The document describes modifications made to a queue simulation program to measure the average time packets spend in the system. It is modified to track the arrival and departure time of each packet. When a packet arrives, its arrival time is recorded. When the packet departs, its processing time is calculated as the difference between departure and arrival time. These processing times are summed over all packets to calculate the average time spent in the system. The key code changes involve adding variables to track each packet's arrival and departure times, calculate processing time, and sum times across all packets.
The document discusses various descriptive statistics that can be calculated in R using the iris dataset. It covers loading and viewing the structure of the iris data, as well as functions to find the mean, median, mode, range, standard deviation, quartiles and interquartile range of variables in the dataset. Examples are provided using sepal length to demonstrate calculating each statistic.
The purpose of types:
To define what the program should do.
e.g. read an array of integers and return a double
To guarantee that the program is meaningful.
that it does not add a string to an integer
that variables are declared before they are used
To document the programmer's intentions.
better than comments, which are not checked by the compiler
To optimize the use of hardware.
reserve the minimal amount of memory, but not more
use the most appropriate machine instructions.
This document discusses programming techniques for Turing machines (TMs), including storing data in states, using multiple tracks, and implementing subroutines. It also covers extensions to basic TMs, such as multitape and nondeterministic TMs. Restricted TMs like those with semi-infinite tapes, stack machines, and counter machines are also examined. Finally, the document informally argues that TMs and modern computers are equally powerful models of computation.
Here is a Python class with the specifications provided in the question:
class PICTURE:
def __init__(self, pno, category, location):
self.pno = pno
self.category = category
self.location = location
def FixLocation(self, new_location):
self.location = new_location
This defines a PICTURE class with three instance attributes - pno, category and location as specified in the question. It also defines a FixLocation method to assign a new location as required.
This document provides an introduction to automata theory and finite automata. It defines an automaton as an abstract computing device that follows a predetermined sequence of operations automatically. A finite automaton has a finite number of states and can be deterministic or non-deterministic. The document outlines the formal definitions and representations of finite automata. It also discusses related concepts like alphabets, strings, languages, and the conversions between non-deterministic and deterministic finite automata. Methods for minimizing deterministic finite automata using Myhill-Nerode theorem and equivalence theorem are also introduced.
YouTube Link: https://youtu.be/T6uCFDRVoRE
** Python Certification Training: https://www.edureka.co/python **
This Edureka Python JSON PPT will introduce you to JSON in Python and how you can do Parsing with various other operations.
The session will focus on pointers like:
Introduction to JSON in Python
Why do we use JSON?
Parsing JSON
Coding Demonstration
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
The document discusses various descriptive statistics that can be calculated in R using the iris dataset. It covers loading and viewing the structure of the iris data, as well as functions to find the mean, median, mode, range, standard deviation, quartiles and interquartile range of variables in the dataset. Examples are provided using sepal length to demonstrate calculating each statistic.
The purpose of types:
To define what the program should do.
e.g. read an array of integers and return a double
To guarantee that the program is meaningful.
that it does not add a string to an integer
that variables are declared before they are used
To document the programmer's intentions.
better than comments, which are not checked by the compiler
To optimize the use of hardware.
reserve the minimal amount of memory, but not more
use the most appropriate machine instructions.
This document discusses programming techniques for Turing machines (TMs), including storing data in states, using multiple tracks, and implementing subroutines. It also covers extensions to basic TMs, such as multitape and nondeterministic TMs. Restricted TMs like those with semi-infinite tapes, stack machines, and counter machines are also examined. Finally, the document informally argues that TMs and modern computers are equally powerful models of computation.
Here is a Python class with the specifications provided in the question:
class PICTURE:
def __init__(self, pno, category, location):
self.pno = pno
self.category = category
self.location = location
def FixLocation(self, new_location):
self.location = new_location
This defines a PICTURE class with three instance attributes - pno, category and location as specified in the question. It also defines a FixLocation method to assign a new location as required.
This document provides an introduction to automata theory and finite automata. It defines an automaton as an abstract computing device that follows a predetermined sequence of operations automatically. A finite automaton has a finite number of states and can be deterministic or non-deterministic. The document outlines the formal definitions and representations of finite automata. It also discusses related concepts like alphabets, strings, languages, and the conversions between non-deterministic and deterministic finite automata. Methods for minimizing deterministic finite automata using Myhill-Nerode theorem and equivalence theorem are also introduced.
YouTube Link: https://youtu.be/T6uCFDRVoRE
** Python Certification Training: https://www.edureka.co/python **
This Edureka Python JSON PPT will introduce you to JSON in Python and how you can do Parsing with various other operations.
The session will focus on pointers like:
Introduction to JSON in Python
Why do we use JSON?
Parsing JSON
Coding Demonstration
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Python Session - 3
Escape Sequence
Data Types
Conversion between data types
Operators
Python Numbers
Python List
Python Tuple
Python Strings
Python Set
Python Dictionary
Huffman's algorithm is a lossless data compression algorithm that assigns variable-length binary codes to characters based on their frequencies, with more common characters getting shorter codes. It builds a Huffman tree by starting with individual leaf nodes for each unique character and their frequencies, then combining the two lowest frequency nodes into an internal node until only one node remains as the root. Codes are then assigned by traversing paths from the root to leaves.
This document discusses theory of computation and finite automata. It begins by defining theory of computation as dealing with the logic of computation using abstract machines called automata. It then defines basic terminology like symbols, alphabets, strings, and languages. Next, it introduces finite automata as the simplest machines that recognize patterns using a finite set of states. Deterministic finite automata and nondeterministic finite automata are described as the two types of finite automata, differing in their transition functions. Transition diagrams and tables are also presented as ways to represent finite automata.
This document discusses various Java concepts like object-oriented programming, compilation, the main method signature, command line arguments, byte code checking, type casting, and input/output in Java using classes like DataInputStream and Scanner. It provides code examples for accepting user input using these classes and parsing the input into different data types like integer and float. It also compares DataInputStream and Scanner, noting that Scanner avoids the need to manually convert input types.
This lecture slide contains:
- Difference between FA, PDA and TM
- Formal definition of TM
- TM transition function and configuration
- Designing TM for different languages
- Simulating TM for different strings
The document summarizes three string matching algorithms: Knuth-Morris-Pratt algorithm, Boyer-Moore string search algorithm, and Bitap algorithm. It provides details on each algorithm, including an overview, inventors, pseudocode, examples, and explanations of how they work. The Knuth-Morris-Pratt algorithm uses information about the pattern string to skip previously examined characters when a mismatch occurs. The Boyer-Moore algorithm uses preprocessing of the pattern to calculate shift amounts to skip alignments. The Bitap algorithm uses a bit array and bitwise operations to efficiently compare characters.
The document discusses intermediate code generation in compilers. It aims to generate a machine-independent intermediate form (IR) that is suitable for optimization and portability. The IR facilitates retargeting compilers to new machines and enables machine-independent code optimization. Common IR representations include abstract syntax trees, directed acyclic graphs, control flow graphs, postfix notation, and three-address code. Three-address code is a simple representation where instructions have at most three operands. It allows efficient code manipulation and optimization.
This document discusses algorithms and their analysis. It defines an algorithm as a well-defined computational procedure that takes input and produces output. Properties of a good algorithm include being correct, unambiguous, terminating, and simple. Algorithm analysis methods like operation count, step count (RAM model), and asymptotic notations are introduced. Insertion sort is used as an example to illustrate exact and asymptotic analysis. Common asymptotic notations like Big-O, Omega, and Theta are defined to describe an algorithm's time complexity.
This document discusses different techniques for reading files in Python. It begins by explaining what files are and the different types, with a focus on text files. It then demonstrates opening a file and reading the entire contents in one string. Next, it shows how to read each line of a file as a separate string using readlines(). Finally, it provides an example of printing the lines of a file in reverse order to illustrate reading files in different ways. The key techniques covered are reading the entire file, reading a specified number of characters, reading each line as a separate string, and iterating through the lines in reverse order.
The document discusses heap data structures and their use in priority queues and heapsort. It defines a heap as a complete binary tree stored in an array. Each node stores a value, with the heap property being that a node's value is greater than or equal to its children's values (for a max heap). Algorithms like Max-Heapify, Build-Max-Heap, Heap-Extract-Max, and Heap-Increase-Key are presented to maintain the heap property during operations. Priority queues use heaps to efficiently retrieve the maximum element, while heapsort sorts an array by building a max heap and repeatedly extracting elements.
Germany - AuRegisThe challenge of establishing a unified electronic system i...Corporate Registers Forum
A presentation on AuRegis, and the challenge of establishing a unified electronic system in a federal state. Presentation is about the current efforts to develop a unified electronic business register system in Germany.
The document contains program code snippets for various networking lab programs including:
1. A CRC program to calculate and check CRC of transmitted data frames.
2. A distance vector routing program to calculate shortest paths between nodes in a network.
3. A FIFO client and server program for inter-process communication using named pipes.
4. Other programs for frame sorting, Hamming code, leaky bucket algorithm, RSA encryption, and a TCP client.
The Theory of Computation deals with how efficiently problems can be solved using algorithms on computational models. It is divided into three branches: automata theory, computability theory, and complexity theory. Complexity theory analyzes problem difficulty and classifies problems as easy or hard to solve efficiently. Computability theory determines if problems are solvable or unsolvable. Automata theory studies the properties of computation models like finite automata and Turing machines. The overall purpose is to develop mathematical models of computation that reflect real-world computers and determine computational limitations.
This document provides an overview of securing network devices by configuring router hardening, secure administrative access, and network monitoring techniques. It discusses topics like configuring a secure network perimeter, securing router administration access, enhancing security for virtual logins, and configuring an SSH daemon for secure remote management. The document also covers securing the Cisco IOS image and configuration files using the resilient configuration feature.
This document discusses and defines four common algorithms for string matching:
1. The naive algorithm compares characters one by one with a time complexity of O(MN).
2. The Knuth-Morris-Pratt (KMP) algorithm uses pattern preprocessing to skip previously checked characters, achieving linear time complexity of O(N+M).
3. The Boyer-Moore (BM) algorithm matches strings from right to left and uses pattern preprocessing tables to skip more characters than KMP, with sublinear worst-case time complexity of O(N/M).
4. The Rabin-Karp (RK) algorithm uses hashing techniques to find matches in text substrings, with time complexity of
The document discusses Turing machines. It begins by introducing Alan Turing as the father of the Turing machine model. A Turing machine is a general model of a CPU that can manipulate data through a finite set of states and symbols. It consists of a tape divided into cells that can be read from and written to by a tape head. The tape head moves left and right across the cells. The document then provides examples of constructing Turing machines to accept specific languages, such as the language "aba" and checking for palindromes of even length strings. Transition tables are used to represent the state transitions of the Turing machines.
This presentation educates you about Python MySQL - Database Connection, Python MySQL - Database Connection, Establishing connection with MySQL using python with sample program.
For more topics stay tuned with Learnbay.
The document discusses the ASP.NET page lifecycle. It begins with an introduction explaining that a requested web page goes through a series of steps on the server before being returned to the browser. It then outlines the main stages of the lifecycle including initialization, load, processing of events, rendering, and unload. Finally, it provides more details on specific events within each stage such as Page_Init and Load and the order in which they are executed.
This document reviews MVP2 of the RideSmart app, which improved upon issues in MVP1 like text responses to non-users and lack of silent mode indication. It shows updated UI, persistent notifications, and whitelisting in MVP2 led to higher satisfaction and importance scores compared to MVP1, especially for silencing and automated responses. Next steps include adding requested features like location extraction and drive end notifications, more customization, testing with more users, and releasing to the App Store.
La profesora Laura Velásquez enseñará a los estudiantes de transición en la Institución Educativa Del Barrio Simón Bolívar sobre el número uno. Los niños identificarán el número uno y su trazo, y desarrollarán competencias socio-afectivas, cognitivas y motricidad fina mediante una actividad en la que decorarán una tarjeta con el número uno usando materiales como plastilina y temperas.
Python Session - 3
Escape Sequence
Data Types
Conversion between data types
Operators
Python Numbers
Python List
Python Tuple
Python Strings
Python Set
Python Dictionary
Huffman's algorithm is a lossless data compression algorithm that assigns variable-length binary codes to characters based on their frequencies, with more common characters getting shorter codes. It builds a Huffman tree by starting with individual leaf nodes for each unique character and their frequencies, then combining the two lowest frequency nodes into an internal node until only one node remains as the root. Codes are then assigned by traversing paths from the root to leaves.
This document discusses theory of computation and finite automata. It begins by defining theory of computation as dealing with the logic of computation using abstract machines called automata. It then defines basic terminology like symbols, alphabets, strings, and languages. Next, it introduces finite automata as the simplest machines that recognize patterns using a finite set of states. Deterministic finite automata and nondeterministic finite automata are described as the two types of finite automata, differing in their transition functions. Transition diagrams and tables are also presented as ways to represent finite automata.
This document discusses various Java concepts like object-oriented programming, compilation, the main method signature, command line arguments, byte code checking, type casting, and input/output in Java using classes like DataInputStream and Scanner. It provides code examples for accepting user input using these classes and parsing the input into different data types like integer and float. It also compares DataInputStream and Scanner, noting that Scanner avoids the need to manually convert input types.
This lecture slide contains:
- Difference between FA, PDA and TM
- Formal definition of TM
- TM transition function and configuration
- Designing TM for different languages
- Simulating TM for different strings
The document summarizes three string matching algorithms: Knuth-Morris-Pratt algorithm, Boyer-Moore string search algorithm, and Bitap algorithm. It provides details on each algorithm, including an overview, inventors, pseudocode, examples, and explanations of how they work. The Knuth-Morris-Pratt algorithm uses information about the pattern string to skip previously examined characters when a mismatch occurs. The Boyer-Moore algorithm uses preprocessing of the pattern to calculate shift amounts to skip alignments. The Bitap algorithm uses a bit array and bitwise operations to efficiently compare characters.
The document discusses intermediate code generation in compilers. It aims to generate a machine-independent intermediate form (IR) that is suitable for optimization and portability. The IR facilitates retargeting compilers to new machines and enables machine-independent code optimization. Common IR representations include abstract syntax trees, directed acyclic graphs, control flow graphs, postfix notation, and three-address code. Three-address code is a simple representation where instructions have at most three operands. It allows efficient code manipulation and optimization.
This document discusses algorithms and their analysis. It defines an algorithm as a well-defined computational procedure that takes input and produces output. Properties of a good algorithm include being correct, unambiguous, terminating, and simple. Algorithm analysis methods like operation count, step count (RAM model), and asymptotic notations are introduced. Insertion sort is used as an example to illustrate exact and asymptotic analysis. Common asymptotic notations like Big-O, Omega, and Theta are defined to describe an algorithm's time complexity.
This document discusses different techniques for reading files in Python. It begins by explaining what files are and the different types, with a focus on text files. It then demonstrates opening a file and reading the entire contents in one string. Next, it shows how to read each line of a file as a separate string using readlines(). Finally, it provides an example of printing the lines of a file in reverse order to illustrate reading files in different ways. The key techniques covered are reading the entire file, reading a specified number of characters, reading each line as a separate string, and iterating through the lines in reverse order.
The document discusses heap data structures and their use in priority queues and heapsort. It defines a heap as a complete binary tree stored in an array. Each node stores a value, with the heap property being that a node's value is greater than or equal to its children's values (for a max heap). Algorithms like Max-Heapify, Build-Max-Heap, Heap-Extract-Max, and Heap-Increase-Key are presented to maintain the heap property during operations. Priority queues use heaps to efficiently retrieve the maximum element, while heapsort sorts an array by building a max heap and repeatedly extracting elements.
Germany - AuRegisThe challenge of establishing a unified electronic system i...Corporate Registers Forum
A presentation on AuRegis, and the challenge of establishing a unified electronic system in a federal state. Presentation is about the current efforts to develop a unified electronic business register system in Germany.
The document contains program code snippets for various networking lab programs including:
1. A CRC program to calculate and check CRC of transmitted data frames.
2. A distance vector routing program to calculate shortest paths between nodes in a network.
3. A FIFO client and server program for inter-process communication using named pipes.
4. Other programs for frame sorting, Hamming code, leaky bucket algorithm, RSA encryption, and a TCP client.
The Theory of Computation deals with how efficiently problems can be solved using algorithms on computational models. It is divided into three branches: automata theory, computability theory, and complexity theory. Complexity theory analyzes problem difficulty and classifies problems as easy or hard to solve efficiently. Computability theory determines if problems are solvable or unsolvable. Automata theory studies the properties of computation models like finite automata and Turing machines. The overall purpose is to develop mathematical models of computation that reflect real-world computers and determine computational limitations.
This document provides an overview of securing network devices by configuring router hardening, secure administrative access, and network monitoring techniques. It discusses topics like configuring a secure network perimeter, securing router administration access, enhancing security for virtual logins, and configuring an SSH daemon for secure remote management. The document also covers securing the Cisco IOS image and configuration files using the resilient configuration feature.
This document discusses and defines four common algorithms for string matching:
1. The naive algorithm compares characters one by one with a time complexity of O(MN).
2. The Knuth-Morris-Pratt (KMP) algorithm uses pattern preprocessing to skip previously checked characters, achieving linear time complexity of O(N+M).
3. The Boyer-Moore (BM) algorithm matches strings from right to left and uses pattern preprocessing tables to skip more characters than KMP, with sublinear worst-case time complexity of O(N/M).
4. The Rabin-Karp (RK) algorithm uses hashing techniques to find matches in text substrings, with time complexity of
The document discusses Turing machines. It begins by introducing Alan Turing as the father of the Turing machine model. A Turing machine is a general model of a CPU that can manipulate data through a finite set of states and symbols. It consists of a tape divided into cells that can be read from and written to by a tape head. The tape head moves left and right across the cells. The document then provides examples of constructing Turing machines to accept specific languages, such as the language "aba" and checking for palindromes of even length strings. Transition tables are used to represent the state transitions of the Turing machines.
This presentation educates you about Python MySQL - Database Connection, Python MySQL - Database Connection, Establishing connection with MySQL using python with sample program.
For more topics stay tuned with Learnbay.
The document discusses the ASP.NET page lifecycle. It begins with an introduction explaining that a requested web page goes through a series of steps on the server before being returned to the browser. It then outlines the main stages of the lifecycle including initialization, load, processing of events, rendering, and unload. Finally, it provides more details on specific events within each stage such as Page_Init and Load and the order in which they are executed.
This document reviews MVP2 of the RideSmart app, which improved upon issues in MVP1 like text responses to non-users and lack of silent mode indication. It shows updated UI, persistent notifications, and whitelisting in MVP2 led to higher satisfaction and importance scores compared to MVP1, especially for silencing and automated responses. Next steps include adding requested features like location extraction and drive end notifications, more customization, testing with more users, and releasing to the App Store.
La profesora Laura Velásquez enseñará a los estudiantes de transición en la Institución Educativa Del Barrio Simón Bolívar sobre el número uno. Los niños identificarán el número uno y su trazo, y desarrollarán competencias socio-afectivas, cognitivas y motricidad fina mediante una actividad en la que decorarán una tarjeta con el número uno usando materiales como plastilina y temperas.
This document summarizes the results of user testing of a water conservation product. It provides the product demo team members' names, notes that existing solutions are dissatisfying, and that the team has assembled a new product. User test results show high importance and satisfaction ratings for features like saving water and money. Unexpected issues included some users not understanding the water unit of measurement and readability concerns. Personal tips were seen as very helpful but sensor setup was too complex. The document concludes by thanking the audience.
This document describes a lip reading training app called Lip Reading Trainer created by Team Apperture. The app allows users to upload videos, add captions, watch videos, and guess captions to practice lip reading and learn sign language. The primary customers are people with hearing disabilities between 15-40 who are currently learning lip reading and want to review and practice visual cues. It also targets video content creators between 20-50 who produce videos with dialogue and rely on captions to make their content accessible.
El documento contiene información sobre pinturas rupestres prehistóricas, símbolos, escritura egipcia, la aparición de la escritura y características del idioma chino. Cubre temas que van desde 40.000 a.C. hasta 1920 d.C.
Este documento proporciona información sobre el uso seguro y la operación de una placa de cocción. Incluye secciones sobre información de seguridad, instrucciones de seguridad, descripción del dispositivo, uso diario, consejos, limpieza, resolución de problemas, montaje, especificaciones técnicas y eficiencia energética. El documento enfatiza la importancia de seguir las instrucciones de seguridad para evitar lesiones o daños, y proporciona detalles sobre el uso adecuado y el mantenimiento de la placa de
Under the terms of the GNU LGPL license, the document states that a user is permitted to modify the Webkit library for personal use and Adobe provides the object code linking to Webkit as required. The user can also reverse engineer only the portions of Adobe software linking to and using Webkit, but only to debug changes made to Webkit. Any other reverse engineering of Adobe software is prohibited as it contains valuable trade secrets and patented methods.
El documento habla sobre la licenciatura en educación infantil de Laura Melissa Vizcaino Vizcaino. Describe las diferentes páginas del trabajo de Laura que incluyen un resumen de Caperucita Roja y las funciones clave de un educador infantil como detectar problemas, elaborar programas educativos, liderar proyectos, promover estrategias pedagógicas, ofrecer ayuda familiar y organizar eventos recreativos.
Sisältöä elämään!® hoiva- ja hyvinvointipalvelut on liittynyt Helsingin kaupungin palvelusetelituottajaksi omaishoidon tuntilomituksessa joulukuusta 2015 alkaen. Omaishoidon palveluseteli on vaihtoehto omaishoitajien lakisääteisten vapaapäivien järjestämiseen ja tapahtuu asiakkaan omassa kodissa.
Este documento presenta varios proyectos de diseño industrial realizados por estudiantes de la PUCV. Incluye el diseño de un muelle flotante para la embarcación Amereida, una embarcación neumática múltiple de travesía y un catálogo con más proyectos para la acreditación de la carrera de Diseño Industrial. Cada proyecto describe brevemente sus objetivos, requerimientos y soluciones propuestas.
Customer service dental practice presentation fileMark Stallwood
Dental practice now needs to consider customer service as an integral part of its offering. Presentation to University of Adelaide Dental School Post Graduate Continuing Education Conference
The document provides instructions for a C++ programming assignment involving functions, pointers, arrays, and calculating pi. It includes 6 problems to solve:
1. Write functions to demonstrate default arguments, constant arguments, and random number generation.
2. Analyze sample code and identify errors in provided code snippets.
3. Write functions to calculate sums of various data types.
4. Use a Monte Carlo simulation to approximate pi by simulating dart throws on a circle and square.
5. Write functions to print, reverse, and transpose arrays.
6. Write functions to operate on strings and pointers.
Proposed pricing model for cloud computingAdeel Javaid
Cloud computing is an emerging technology of business computing and it is becoming a development trend. The process of entering into the cloud is generally in the form of queue, so that each user needs to wait until the current user is being served. In the system, each Cloud Computing User (CCU) requests Cloud Computing Service Provider (CCSP) to use the resources, if CCU(cloud computing user) finds that the server is busy then the user has to wait till the current user completes the job which leads to more queue length and increased waiting time. So to solve this problem, it is the work of CCSP’s to provide service to users with less waiting time otherwise there is a chance that the user might be leaving from queue. CCSP’s can use multiple servers for reducing queue length and waiting time. In this paper, we have shown how the multiple servers can reduce the mean queue length and waiting time. Our approach is to treat a multiserver system as an M/M/m queuing model, such that a profit maximization model could be worked out.
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docxMARRY7
/* Lab Assignment 4 CSE330 Spring 2014 */
/* Skeleton Code for ex0 of lab4 */
/* No code will be provided for ex1 of lab4 */
#include <stdio.h> /* for NULL */
#include <ctype.h> /* for atoi() */
#include <errno.h> /* for perror() */
#include <signal.h> /* for sigvec() etc. */
#include <sys/types.h> /* for <arpa/inet.h> */
#include <sys/socket.h> /* for PF_INET, etc. */
#include <netinet/in.h> /* for struct sockaddr_in */
#include <arpa/inet.h> /* for inet_addr() */
#include <sys/time.h>
#include "lab4.h"
/* this is in netinet/in.h; included here for reference only.
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
*/
/***************************************************************************/
#define LINESIZE 80
#define TYPE0TIMEOUT 3
#define TYPE1TIMEOUT 30
/* You should give a long timeout, like 30sec, otherwise */
/* duplicated responses from the server may cause some problem */
#define MAXRETRY 3
/***************************************************************************/
static char *RCSId="$Id: client2.c,v 4 2014/04/20 03:15:07 cse3300 Exp $";
/***************************************************************************/
/* some functions you may find useful if you implement them */
extern int stringToAddress(char *s, struct sockaddr_in *a);
extern int msgok(LABMSG *);
extern u_short msgchecksum(u_short *);
extern void alarmCatcher(void);
extern int tries; /* for retransmission routines */
int numtries;
/***** this will die ****/
FILE *logFile;
void die(char *s)
{
perror(s);
exit(2);
}
void startTimer(int secs)
{
alarm(secs);
}
void stopTimer(void)
{
alarm(0);
}
/* should change it by yourself if needed!!! */
void printResponse(LABMSG *mp, int ck)
{
int type;
mp->courseEtc = ntohs(mp->courseEtc);
type = ( (mp->courseEtc & MESSAGETYPE) !=0)?1:0;
printf("course=%d, Type=%d\n", mp->courseEtc&0x3fff,type);
if (ntohl(mp->cookie) != ck)
printf("Cookies don't match: sent %x received %x\n",mp->cookie,ck);
if (mp->courseEtc & REQRESP)
printf("response ");
else {
printf("request??\n");
return;
}
mp->result = ntohs(mp->result);
/*printf(" result = %x: ",mp->result);*/
if (mp->result&TRANSOUTCOME) { /* Check outcome */
printf("error: ");
switch (mp->result & 0x7fff) {
case ERROR_CHECKSUM:
printf("checksum failure\n");
break;
case ERROR_SYNTAX:
printf("syntax error\n");
break;
case ERROR_UNKSSN:
printf("unknown SSN %d\n", ntohl(mp->reqSSN) );
break;
case ERROR_SERVER:
printf("Unspecified Server Error\n");
default:
printf("Unknown Error.\n");
} /* case switch */
} else { /* successful transaction */
if(type)printf("Test succeeded.");
if (!type) /* Type 0 -- print SSN and Response */
printf(": %d -> %d\n", ntohl(mp->reqSSN), mp->result&0x7fff);
else
printf("\n"); /* XXX print number of responses */
}
}
/*-----------------------------------*/
/* added by ZXC:
this fun ...
Video games are written as a main loop: process player input, update the state of the game, render a new frame to the screen, repeat. They do this 60 times a second, with millisecond timing. Most monitoring tools are also written as loops: send a probe, wait for the response, update a data store, sleep. Often this is done pretty slowly, maybe once a second! In video games if you can’t update fast enough, you skip the rendering step and the frame rate drops. With monitoring tools if your loop takes to long you also stop logging data as often, and instead of choppy gameplay you get gaps in your graphs, often when you need that data the most!
Let’s use ping as an example and see how we can rewrite its main loop to function more like a video game, keeping a high frame rate.
Modify this code to use multiple threads with the same data1.Modif.pdfmallik3000
Modify this code to use multiple threads with the same data
1.Modify the main function to implement a loop that reads 10 integers from the console (user
input) and stores these numbers in a one-dimensional (1D) array (this code will go right after the
comment that says “Add code to perform any needed initialization or to process user input”).
You should use a global array for this.
2.Implement a separatepthread function function for each one of the following operations:
a.Count and print out how many of the entered numbers are negative. This function must be
named countNegatives
b.Calculate and print the average value of all the numbers entered. This function must be named
average
c.Print the numbers in reverse order from the order in which they were entered. This function
must be named reverse
3.Modify the main function to create one pthread for each one of the functions that you
implemented in (3) above (this code will go between the comment that says “TODO: Modify
according to assignment requirements” and the “if (rc)” check).
Compile your program and run it several times. If the output of your program is garbled, you
may need to add a small delay in between creating the next thread.
#include
#include
using namespace std;
void *routineName(void *arg)
{
// TODO: Add code that implements
// the thread\'s functionality
cout << \"Thread is running...\" << endl;
return 0;
}
int main()
{
pthread_t id;
int rc;
int ints;
for(int x; x<10; x++)
{
cout << \"Enter Integer: \" <>
}
rc = pthread_create(&id, NULL, routineName, NULL);
if (rc){
cout << \"ERROR; return code from pthread_create() is \" << rc << endl;
return -1;
}
pthread_exit(0);
}
Solution
#include
#include
#include
using namespace std;
int ints[10];
//Method to count negatives in the input array
void *countNegatives(void*){
int count = 0;
for(int i=0;i<10;i++){
if(ints[i]<0){
count++;
}
}
cout<<\"Number of negatives: \"<=0;i--){
cout<> ints[x];
}
//Creating pthread to countNegatives
rc = pthread_create(&t1, NULL, countNegatives, NULL);
if(rc){
cout << \"Error:unable to create thread,\" << rc << endl;
}
//Adding delay
sleep(1);
//Creating pthread to compute average
rc = pthread_create(&t2, NULL, average, NULL);
if(rc){
cout << \"Error:unable to create thread,\" << rc << endl;
}
//Adding delay
sleep(1);
//Creating pthread to print in reverse
rc = pthread_create(&t3, NULL, reverse, NULL);
if(rc){
cout << \"Error:unable to create thread,\" << rc << endl;
}
//Adding delay
sleep(1);
void* status;
//waiting for t1 to join
rc = pthread_join(t1,&status);
if(rc){
cout << \"Error:unable to join,\" << rc << endl;
}
//waiting for t2 to join
rc = pthread_join(t2,&status);
if(rc){
cout << \"Error:unable to join,\" << rc << endl;
}
//waiting for t3 to join
rc = pthread_join(t3,&status);
if(rc){
cout << \"Error:unable to join,\" << rc << endl;
}
pthread_exit(0);
}.
This document provides information on setting up wireless simulations in NS-2 including:
1) Details on configuring wireless node parameters, channels, propagation models, interfaces, and routing protocols.
2) Examples of generating node mobility using the setdest script and generating traffic using cbrgen.
3) The format of DSR trace files and how to calculate routing overhead and packet delivery ratio from these files using AWK.
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
Reactive programming models asynchronous data streams as signals that produce events over time. ReactiveCocoa is a framework that implements reactive programming in Objective-C. It uses signals to represent asynchronous data streams and operators to transform and combine signals. ReactiveCocoa code separates the logic to produce and consume data, making it more modular, reusable, testable and by reducing state and mutability. While the syntax is different, learning to think reactively can improve code quality and stability.
1) RPC (Remote Procedure Call) allows a client to call procedures or functions on a remote server. The client specifies the server address and port to communicate.
2) An RPC system requires three files - an X file defining remote functions, a server C++ file implementing these functions, and a client C++ file to call the functions.
3) The tutorial provides example code of these three files to demonstrate a simple message passing between an RPC client and server. The client can call the "printmessage" function defined on the server to display a message.
This is an PPT of C++. This includes the topic of Parameter such as"Reference Parameter, Passing object by reference, constant parameter & Default parameter. "
The document contains summaries of code snippets and explanations of technical concepts. It discusses:
1) How a code snippet with post-increment operator i++ would output a garbage value.
2) Why a code snippet multiplying two ints and storing in a long int variable would not give the desired output.
3) Why a code snippet attempting to concatenate a character to a string would not work.
4) How to determine the maximum number of elements an array can hold based on its data type and memory model.
5) How to read data from specific memory locations using the peekb() function.
The document contains summaries of code snippets and explanations of technical concepts. It discusses:
1) How a code snippet with post-increment operator i++ would output a garbage value.
2) Why a code snippet multiplying two ints and storing in a long int variable would not give the desired output.
3) Why a code snippet attempting to concatenate a character to a string would not work.
4) How to determine the maximum number of elements an array can hold based on its data type and memory model.
5) How to read data from specific memory locations using the peekb() function in C.
The document provides an overview of the C programming language. It states that C was developed in 1972 by Dennis Ritchie at Bell Labs and was used to develop the UNIX operating system. The document then covers various features of C like it being a mid-level programming language, having structured programming, pointers, loops, functions, arrays, and more. It provides examples to explain concepts like input/output functions, data types, operators, control structures, and pointers.
The document provides code snippets showing how to perform various tasks like variable interchange, finding absolute value of a negative number, breaking down a 3-digit number into single digits, and calculating average marks in C++ and Java. It also explains some key differences between C++ and Java like using endl vs println to print on new lines and concatenating strings with variables.
The document discusses functions in C++ and provides examples of defining and calling functions. It explains that a function allows structuring programs in a modular way and accessing structured programming capabilities. A function is defined with a return type, name, parameters, and body. Parameters allow passing arguments when calling the function. The function examples demonstrate defining an addition function, calling it from main to add two numbers and return the result. It also covers function scope, with local variables only accessible within the function and global variables accessible anywhere.
The document describes the architecture of Cassandra, including its startup process, layers (API, Dynamo, database), services (StorageProxy, MessagingService, Gossip), and failure handling. It also details how nodes communicate via the Gossip protocol to exchange state information and maintain a consistent cluster view.
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxcarliotwaycave
Instruction:
1. Please read the two articles. (Kincheloe part 1 & 2)
2. Please choose some of the topics covered in each chapter, provide a brief summary (2-3 sentences) of those topics.
3. Then add your reflections, insights, or relevant experiences, etc. to help illustrate or expand upon the course.
4. This journal should be at least 400 words.
p5-start.cppp5-start.cpp/**
* @author Jane Student
* @cwid 123 45 678
* @class CSci 430, Spring 2018
* @ide Visual Studio Express 2010
* @date November 15, 2018
* @assg prog-04
*
* @description This program implements a simulation of process
* scheduling policies. In this program, we implement round-robin
* scheduling, where the time slice quantum can be specified as
* as a command line parameter. And we also implement shortest
* remaining time (SRT) scheduling policy
*/
#include<stdlib.h>
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<list>
usingnamespace std;
// global constants
// I won't test your round robin implementation with more than 20 processes
constint MAX_PROCESSES =20;
constint NO_PROCESS =0;
// Simple structure, holds all of the information about processes, their names
// arrival and service times, that we are to simulate.
typedefstruct
{
string processName;
int arrivalTime;
int serviceTime;
// holds running count of time slices for current time quantum, when
// serviceTime == quantum, time slice is up
int sliceTime;
// holds total number of time steps currently run, when == to
// serviceTime process is done
int totalTime;
// holds time when process finishes, used to calculate final stats,
// like T_r, T_r/T_s
int finishTime;
// a boolean flag, we will set this to true when the process is complete
bool finished;
}Process;
// Process table, holds table of information about processes we are simulating
typedefstruct
{
int numProcesses;
Process* process[MAX_PROCESSES];
}ProcessTable;
/** Create process table
* Allocate memory for a new process table. Load the process
* information from the simulation file into a table with the process
* information needed to perform the simulation. At the same time we
* initialize other information in process table for use in the
* simulation. Return the newly created ProcessTable
*
* @param processFilanem The name (char*) of the file to open and read
* the process information from.
* @param processTable This is actually a return parameter. This
* should be a pointer to an already allocated array of
* Process structure items. We will fill in this structure
* and return the process information.
*
* @returns ProcessTable* The newly allocated and initialized ProcessTable
* structure.
*/
ProcessTable* createProcessTable(char* processFilename)
{
ifstream simprocessfile(processFilename);
ProcessTable* processTable;
int pid;
string processName;
int arrivalTime;
int serviceTime;
// If we can't open file, abort and let ...
The document discusses data types, data structures, algorithms, recursion, and asymptotic analysis. It provides definitions and examples of key concepts like abstract data types, data abstraction, algorithms, iterative vs recursive algorithms, complexity analysis using Big-O, Big-Omega and Big-Theta notations. Examples of recursively implementing algorithms to find sum of natural numbers, factorial, GCD, Fibonacci series are presented.
NS2 - the network simulator which is proved useful in studying the dynamic nature of communication networks. Simulation of wired as well as wireless network functions and protocols( e.g. routing algorithms, TCP, UDP ) can be done using NS2
Kapacitor - Real Time Data Processing EnginePrashant Vats
Kapacitor is a native data processing engine.Kapacitor is a native data processing engine.It can process both stream and batch data from InfluxDB.It lets you plug in your own custom logic or user-defined functions to process alerts with dynamic thresholds. Key Kapacitor Capabilities
-Alerting
-ETL (Extraction, Transformation and Loading)
-Action Oriented
-Streaming Analytics
-Anomaly Detection
Kapacitor uses a DSL (Domain Specific Language) called TICKscript to define tasks.
Similar to Router Queue Simulation in C++ in MMNN and MM1 conditions (20)
Router Queue Simulation in C++ in MMNN and MM1 conditions
1. Task 1.1
Generate 1000 independent uniformly distributed random numbers (in range 0 to 1). Calculate the
sample mean and sample standard deviation of these numbers.
#include<math.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include<iostream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <time.h>
using namespace std;
int main()
{
float Rand_Value[1000];
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 1000; i++)
{
Rand_Value[i] = (float) rand()/RAND_MAX ;
//cout << (float) rand()/RAND_MAX << endl;
}
for (int j = 0; j < 1000; j++)
{
cout<<Rand_Value[j]<<endl; //= (float) rand()/RAND_MAX ;
//cout << (float) rand()/RAND_MAX << endl;
}
cin.get();
return 0;
}
2. Task 1.2
Generate 1000 independent exponentially distributed random numbers with mean 35.0. Calculate the
sample mean and sample standard deviation of these numbers.
-Since I preferred compiling C++ in windows using Visual studio I was not able to use “drand48” to
produce exponentially distributed random numbers so I implemented another method using “rand”
#include<math.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include<iostream>
#include<math.h>
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <time.h>
using namespace std;
int main()
{
const int N = 1000;
float Rand_Value_exp[N];
float Rand_Value[N];
float mean = 35.0;
float exp,var=0, dev = 0;
float sum = 0;
srand( (unsigned)time( NULL ) );
for (int i = 0; i < N; i++)
{
3. Rand_Value_exp[i] = ( (int)(- log((float) rand() / RAND_MAX) *
mean + 0.5) );
//Rand_Value[i] = (float) rand()/ RAND_MAX;
sum = sum+Rand_Value_exp[i];
}
for (int j = 0; j < N; j++)
{
cout<<Rand_Value_exp[j]<<endl; //= (float) rand()/RAND_MAX ;
}
cout<<"Sample mean is equal:n";
exp = sum/N;
cout<<sum/N;
for(int k=0; k < N;k++)
{
var = pow((Rand_Value_exp[k] - exp),2) + var;
}
dev = sqrt(var)/N;
cout<<"n";
cout<<"Standard deviation="<<dev;
cin.get();
return 0;
}
4. Task 2
What conclusions did you draw from Lab 1 concerning:
1. Accuracy vs number of events for a fixed occupancy (or utilisation)?
2. Accuracy vs occupancy for a fixed number of events?
In a Single server Queuing modeling in fixed utilization ( where the ratio of arrival rate and departure
rate is fixed ) it can be seen that the higher accurate number can be produced when there are less
events .it means for example in modeling 1 case where the exact solution is known the accuracy is at its
highest.
In case of modeling for fixed number of events I have tested the program with 100 events with different
arrival rate and holding time ratio and It seems the accuracy is higher for higher utilization.
5. Task 3
Task 1 in Lab 2 asks for a comparison of the mean queue lengths of M/M/1 and M/D/1 queues. What
do you conclude? Give some evidence.
The difference between M/M/1 and M/D/1 is Deterministic service time which is constant, rather than
being exponentially distributed. So we modified the code by eliminating the “negexp” function and
compared the results .we observed that the mean queue length for the system with more random case
(M/M/1, which has both random arrivals and random service) is greater than the less random case
(M/D/1) which can be explained by looking at the formula for:
Average length of Queue in M/M/1 system
Average length of Queue in M/M/D system
Task 3.2
Summarize the code changes required between the M/M/1 ssq.c simulation and the M/M/N/N
simulation of Task 2 in Lab 2.
In this task the user inputs the numbers of servers to programs ( “NumberOfServer” ) and programs
simply multiples the numbers of packets being serviced by this n server.it also decrements the
DEPARTURE packets based on n. for example in the case of 3 servers 3 packets will be serviced and once
they depart the system 3 packets will be decremented from the list .
/* program ssq.c */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <iostream>
( )ρ
ρ
−
=
1
2
Q
( )ρ
ρ
−
=
12
2
Q
6. using namespace std;
#define NEW(type) (type *) malloc(sizeof(type))
#define ARRIVAL 1
#define DEPARTURE 2
/* Event by event simulation of a single server queue with infinite
waiting
room */
int
gmt, /* absolute time */
q, /* number of customers in the system */
narr, /* number of arrivals */
q_sum, /* sum of queue lengths at arrival instants */
iat, /* mean interarrival time */
service_time, /* mean holding time */
total_events; /* number of events to be simulated */
int NumberOfServer; /* Number of Server */
unsigned int
seed; /* seed for the random number generator */
typedef struct schedule_info{
int time; /* Time that event occurs */
int event_type; /* Type of event */
struct schedule_info *next; /* Pointer to next item in linked
list */
} EVENTLIST;
struct schedule_info
*head,
*tail;
int act(void);
int negexp(int);
void arrival(void);
void departure(void);
void schedule(int, int);
void sim_init(void);
/*************************************************************************
*/
int main(){
sim_init();
while (narr < total_events){
switch (act()){
case ARRIVAL:
arrival();
break;
7. case DEPARTURE:
departure();
break;
default:
printf("error in act proceduren");
exit(1);
break;
} /* end switch */
} /* end while */
printf("The mean queue length seen by arriving customers is: %8.4fn",
((float) q_sum) / narr);
int n; cin>>n;
return(0);
} /* end main */
/*************************************************************************
*/
int negexp(int mean) /* returns a negexp rv with mean `mean' */
{
return ( (int)(- log((float) rand() / RAND_MAX) * mean + 0.5) );
}
/*************************************************************************
*/
void arrival() /* a customer arrives */
{
//defines number of servers
narr += NumberOfServer; /* keep tally of number of
arrivals */
q_sum += q;
schedule(negexp(iat), ARRIVAL); /* schedule the next arrival */
//accumulates numbers of customers in the system based on number of
servers
q += NumberOfServer;
//marks the last node in the server as DEPARTURE
if (q == NumberOfServer)
schedule(negexp(service_time), DEPARTURE);
}
/*************************************************************************
*/
void departure() /* a customer departs */
{
//Decrements number of customers in the system after customer departs
q -= NumberOfServer;
8. if (q > 0)
schedule(negexp(service_time), DEPARTURE);
}
/*************************************************************************
*/
/*************************************************************************
*/
void schedule(int time_interval, int event) /* Schedules an event of type
*/
/* 'event' at time
'time_interval'
in the future */
{
int
event_time;
struct schedule_info
*x,
*t;
event_time = gmt + time_interval;
t = NEW(EVENTLIST);
for(x=head ; x->next->time<event_time && x->next!=tail ; x=x->next);
t->time = event_time;
t->event_type = event;
t->next = x->next;
x->next = t;
}
/*************************************************************************
*/
int act() /* find the next event and go to it */
{
int
type;
struct schedule_info
*x;
gmt = head->next->time; /* step time forward to the next event */
type = head->next->event_type; /* Record type of this next event */
x = head->next; /* Delete event from linked list */
head->next = head->next->next;
free(x);
return type; /* return value is type of the next event */
}
/*************************************************************************
/
/*************************************************************************
*/
void sim_init()
/* initialise the simulation */
9. {
printf("nenter the mean interarrival time and the mean holding
timen");
scanf("%d%d", &iat, &service_time);
printf("enter the total number of customers to be simulatedn");
scanf("%d", &total_events);
printf("enter the seedn");
scanf("%d", &seed);
srand(seed);
printf("enter Number Of Servern");
scanf("%d", &NumberOfServer);
//srand(seed);
head = NEW(EVENTLIST);
tail = NEW(EVENTLIST);
head->next = tail;
tail->next = tail;
//service_time = service_time /10;
q = 0;
narr = 0;
q_sum = 0;
schedule(negexp(iat), ARRIVAL); /* schedule the first arrival */
}
/*************************************************************************
*/
Task 4.1
Take the router queue simulation (r_ssq.c), and modify it so that the simulation measures the
average time spent in the system by packets, i.e. the average time between a packet arriving, and
completion of its service. Assume that the service discipline in first-in-first-out (FIFO).
Use these parameter values:
Mean packet length = 1000 octets (i.e. 8,000 bits) Router capacity = 1 Mbps (i.e. 1,000,000 bps)
Briefly summarize the code changes required to implement the above.
/* program ssq.c */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <limits.h>
#include <iostream>
10. using namespace std;
#define NEW(type) (type *) malloc(sizeof(type))
#define ARRIVAL 1
#define DEPARTURE 2
/* Event by event simulation of a single server queue with infinite
waiting
room */
double
gmt, /* absolute time */
iat; /* mean interarrival time */
int
q, /* number of customers in the system */
narr, /* number of arrivals */
q_sum, /* sum of queue lengths at arrival instants */
r_capacity, /* router processing capacity */
mean_pkt_length, /* mean packet length */
total_events; /* number of events to be simulated */
double sumOfProcessTime = 0;
int arrivalTime = 0;
int departTime = 0;
int Count=0;
long
seed; /* seed for the random number generator */
typedef struct schedule_info{
double time; /* Time that event occurs */
int event_type; /* Type of event */
struct schedule_info *next; /* Pointer to next item in linked
list */
} EVENTLIST;
struct schedule_info
*head,
*tail;
int act(void);
double negexp(double);
double negexp_srv(int);
void arrival(void);
void departure(void);
void schedule(double, int);
void sim_init(void);
/*************************************************************************
*/
int main(){
11. sim_init();
while (narr < total_events){
switch (act()){
case ARRIVAL:
arrival();
break;
case DEPARTURE:
departure();
break;
default:
printf("error in act proceduren");
exit(1);
break;
} /* end switch */
} /* end while */
printf(" average time spent in the system by packets is: %8.4fn",
((float) q_sum) / narr);
printf("The answer for task 4.1 is:n");
//Calculating the average time
cout<< (double)(sumOfProcessTime/Count);
int age;
cin >> age;
return(0);
} /* end main */
/*************************************************************************
*/
double negexp(double mean) /* returns a negexp rv with mean `mean' */
{
return ( (int)(- log((float) rand() / RAND_MAX) * mean + 0.5) );
}
/*************************************************************************
*/
double negexp_srv(int mean) /* returns a negexp rv with mean `mean' */
{
int pkt_length;
pkt_length = (int)( (int)(- log((float) rand() / RAND_MAX) * mean + 0.5)
);
double service_time = (pkt_length*8.0)/(r_capacity*pow(10.0,6.0));
//Count number of received packet by router
Count++;
//Calculating the sum of process time for each packet
sumOfProcessTime = (service_time)+sumOfProcessTime;
return (service_time);
12. }
/*************************************************************************
*/
void arrival() /* a customer arrives */
{
narr += 1; /* keep tally of number of arrivals */
q_sum += q;
schedule(negexp(iat), ARRIVAL); /* schedule the next arrival */
q += 1;
if (q == 1)
{
schedule(negexp_srv(mean_pkt_length), DEPARTURE);
}
//Some of process time, which is the subtrack of arrival time and
departTime calculated in each depart time
//sumOfProcessTime = (arrivalTime - departTime)+sumOfProcessTime;
}
/*************************************************************************
*/
void departure() /* a customer departs */
{
q -= 1;
if (q > 0)
schedule(negexp_srv(mean_pkt_length), DEPARTURE);
}
/*************************************************************************
*/
/*************************************************************************
*/
void schedule(double time_interval, int event) /* Schedules an event of
type */
/* 'event' at time
'time_interval'
in the future */
{
double
event_time;
struct schedule_info
13. *x,
*t;
event_time = gmt + time_interval;
t = NEW(EVENTLIST);
for(x=head ; x->next->time<event_time && x->next!=tail ; x=x->next);
t->time = event_time;
t->event_type = event;
//if(event == 1)
//{
/// arrivalTime = event_time;
//}
//if(event == 2)
//{
//departTime = event_time;
//}
t->next = x->next;
x->next = t;
}
/*************************************************************************
*/
int act() /* find the next event and go to it */
{
int
type;
struct schedule_info
*x;
gmt = head->next->time; /* step time forward to the next event */
type = head->next->event_type; /* Record type of this next event */
x = head->next; /* Delete event from linked list */
head->next = head->next->next;
free(x);
return type; /* return value is type of the next event */
}
/*************************************************************************
/
/*************************************************************************
*/
void sim_init()
/* initialise the simulation */
{
int iar;
printf("nenter the mean packet arrival rate (pkts/sec) and the mean
packet length (octets)n");
scanf("%d%d", &iar, &mean_pkt_length);
printf("nenter the router transmission capacity (Mbps)n");
scanf("%d", &r_capacity);
printf("enter the total number of packets to be simulatedn");
14. scanf("%d", &total_events);
// providing automated seed from system time */
seed = time(NULL);
srand(seed);
head = NEW(EVENTLIST);
tail = NEW(EVENTLIST);
head->next = tail;
tail->next = tail;
gmt = 0.0;
q = 0;
narr = 0;
q_sum = 0;
iat = 1.0 / iar;
schedule(negexp(iat), ARRIVAL); /* schedule the first arrival */
}
/*************************************************************************
*/
Task 4.2
Present the results from your simulation of Task 4.1 in graphical form, for occupancies in the range 0.0
to 0.9, including 95% confidence intervals for the estimated mean system times. Show also the
theoretical values on your graph.
15. Above graph is based on mean system time produced for occupancy between 0.0 to .9 for 100 packets
by 1 Mbps Router and mean packet length of 1000 octet and confidence interval of %95(standard
deviation = .013971)
Mean service time for theoretical values are shown in following graph
occupancy 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
Mean system time 0.000172 0.000664 0.000744 0.01996 0.02164 0.024264 0.027384 0.032608 0.03496
confidence %95 0.008659 0.008659 0.008659 0.008659 0.008659 0.008659 0.008659 0.008659 0.008659
-0.005
0
0.005
0.01
0.015
0.02
0.025
0.03
0.035
0.04
0 0.2 0.4 0.6 0.8 1
Occupancy
Mean system time
Mean system time
0
0.005
0.01
0.015
0.02
0.025
0 0.01 0.02 0.03 0.04 0.05
Theoritical values
Mean system time
Mean system time