CSIS 330 Quiz 7 Liberty University

IMPORTANT: AFTER PURCHASE, LOG IN TO YOUR ACCOUNT AND SCROLL DOWN BELOW THIS PAGE TO DOWNLOAD FILES WITH ANSWERS.

  1. Traffic cannot be forwarded between subnets without the use of a router.
  2. You are given an IPv4 network address of 192.168.10.0/24 by your ISP.  You need to subnet this network.  You know that the subnet mask will be 255.255.255.252. Therefore, what is the new slash prefix of the network address?
  3. You need to subnet a network that has 5 subnets, each with at least 16 hosts.  Which subnet mask would you use?
  4. The IP address 198.10.132.67 /26 is a network address.
  5. A new department has been established with 511 hosts that require addresses.  Currently, the company uses the 10.20.0.0/16 address space.  How many bits must the network administrator borrow to provide addresses for this subnet without wasting addresses?
  6. In subnetting, borrowing bits from the host portion of the address results in more host addresses that can be assigned but fewer subnets that can be defined.
  7. You are given an IPv4 network address of 192.168.10.0/24 by your ISP.  You need to subnet this network. You know that you need at least 6 subnets.   How many hosts per subnet will be possible in the new design?
  8. To determine whether traffic on a network is local or remote, a router uses a ______________________.
  9. Within a network, there are two addresses that cannot be assigned to devices.  These addresses are  the __________________.
  10. You are given an IPv4 network address of 192.168.10.0/24 by your ISP.  You need to subnet this network. You know that you need at least 6 subnets.  What will be the address of your first usable host in your first subnet (i.e. subnet[0])?
  11. Which of the following subnet masks is used to represent a prefix mask of / 26
  12. Using an IPv4 network address of 192.168.2.0/26, what is the last usable host address in the second subnet (i.e. subnet[1])?
  13. You are given an IPv4 network address of 192.168.10.0/24 by your ISP.  You need to subnet this network.  You know that the subnet mask will be 255.255.255.252. What is the last usable host address of the first subnet (i.e. subnet[0])?
  14. What is the first step in planning network subnets?
  15. In creating subnets for IPv6, conversion to binary is not required.
  16. You are given an IPv4 network address of 192.168.10.0/24 by your ISP.  You need to subnet this network. You know that you need at least 6 subnets.  How many bits will you need to borrow to achieve this?
  17. How many hosts per network can you have with a subnet mask of 255.255.192.0?
  18. You have an interface on a router with the IP address of 192.168.192.10 /29.  What is the broadcast address the hosts will use on this LAN?
  19. How many valid host addresses are created when 4 host bits are borrowed from the 10.20.20.0/24 network?
  20. You are given an IPv4 network address of 192.168.10.0/24 by your ISP.  You need to subnet this network.  You know that the subnet mask will be 255.255.255.252. What is the broadcast address of the first subnet (i.e. subnet[0])?
  21. What is the maximum number of IP addresses that can be assigned to hosts on a local subnet that uses the 255.255.255.224 subnet mask?
  22. How many usable hosts per sub-network will you have using a /17 address?
  23. Which one of the following is a private IP address?
  24. You are given an IPv4 network address of 192.168.10.0/24 by your ISP.  You need to subnet this network. You know that you need at least 6 subnets.  What will be the subnet mask in the new design?
  25. A ____________________ is necessary for devices on different networks to communicate.

BUY MORE MATERIALS FOR THIS COURSE:

CSIS 330 Quiz 1 Liberty University

CSIS 330 Quiz 2 Liberty University

CSIS 330 Quiz 3 Liberty University

CSIS 330 Quiz 4 Liberty University

CSIS 330 Quiz 5 Liberty University

CSIS 330 Quiz 6 Liberty University

CSIS 330 Quiz 7 Liberty University

CSIS 330 Final Exam

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

C++ Dictionaries And Hashing

Source/Assg13/assg-13.cpp

Source/Assg13/assg-13.cpp

/**
*
*
*  @description  Assignment 13 Dictionaries and Hash table
*   implementations.
*/
#include   < cassert >
#include   < iostream >
#include   "KeyValuePair.hpp"
#include   "Employee.hpp"
#include   "HashDictionary.hpp"

using   namespace  std ;

/** main
* The main entry point for this program.  Execution of this program
* will begin with this main function.
*
*  @param  argc The command line argument count which is the number of
*     command line arguments provided by user when they started
*     the program.
*  @param  argv The command line arguments, an array of character
*     arrays.
*
*  @returns  An int value indicating program exit status.  Usually 0
*     is returned to indicate normal exit and a non-zero value
*     is returned to indicate an error condition.
*/
int  main ( int  argc ,   char **  argv )
{
// -----------------------------------------------------------------------
cout  <<   "----- testing Employee record and KeyValuePair class  -----------"   <<  endl ;
KeyValuePair < int ,  string >  pair ( 42 ,   "blue" );
cout  <<   "test key: "   <<  pair . key ()   <<  endl ;
assert ( pair . key ()   ==   42 );
cout  <<   "test value: "   <<  pair . value ()   <<  endl ;
assert ( pair . value ()   ==   "blue" );

int  id  =   3 ;
Employee  e ( id ,   "Derek Harter" ,   "1234 Main Street, Commerce TX" ,   12345.67 );
cout  <<  e  <<  endl ;
assert ( e . getId ()   ==   3 );
assert ( e . getName ()   ==   "Derek Harter" );
cout  <<  endl ;

// -----------------------------------------------------------------------
cout  <<   "-------------- testing quadratic probing  -----------------------"   <<  endl ;
const   int  TABLE_SIZE  =   7 ;
HashDictionary < int ,   Employee >  dict ( TABLE_SIZE ,  EMPTY_EMPLOYEE_ID );

cout  <<   "Newly created hash dictionary should be empty, size: "   <<  dict . size ()   <<  endl ;
assert ( dict . size ()   ==   0 );

int  probeIndex  =   0 ;
//cout << "probe index: " << probeIndex
//     << " returned probe value: " << dict.probe(id, probeIndex)
//     << endl;
//assert(dict.probe(id, probeIndex) == 2);

probeIndex  =   1 ;
//cout << "probe index: " << probeIndex
//     << " returned probe value: " << dict.probe(id, probeIndex)
//     << endl;
//assert(dict.probe(id, probeIndex) == 5);

probeIndex  =   5 ;
//cout << "probe index: " << probeIndex
//     << " returned probe value: " << dict.probe(id, probeIndex)
//     << endl;
//assert(dict.probe(id, probeIndex) == 37);
cout  <<  endl ;

// -----------------------------------------------------------------------
cout  <<   "-------------- testing mid-square hashing  ----------------------"   <<  endl ;
// the following asserts will only work for 32 bit ints, leave asserts
// commented out if you have 64 bit asserts
cout  <<   "Assuming 32 bit (4 byte) ints for these tests: "   <<   sizeof ( int )   <<  endl ;
assert ( sizeof ( int )   ==   4 );

//id = 3918;
//cout << "hash key: " << id
//     << " returned hash value: " << dict.hash(id)
//     << endl;
//assert(dict.hash(id) == 1);

//id = 48517;
//cout << "hash key: " << id
//     << " returned hash value: " << dict.hash(id)
//     << endl;
//assert(dict.hash(id) == 6);

//id = 913478;
//cout << "hash key: " << id
//     << " returned hash value: " << dict.hash(id)
//     << endl;
//assert(dict.hash(id) == 5);

//id = 8372915;
//cout << "hash key: " << id
//     << " returned hash value: " << dict.hash(id)
//     << endl;
//assert(dict.hash(id) == 4);

// test that the distribution of the hash values
// over the possible slots/buckets looks relatively
// evenly distributed
int  counts [ TABLE_SIZE ]   =   { 0 };
//for (id = 0; id < 1000000; id++)
//{
//  int hash = dict.hash(id);
//  counts[hash]++;
//}

// display results
int  sum  =   0 ;
for   ( int  slot  =   0 ;  slot  <  TABLE_SIZE ;  slot ++ )
{
cout  <<   "counts for slot["   <<  slot  <<   "] = "
<<  counts [ slot ]   <<  endl ;
sum  =  sum  +  counts [ slot ];
}
// spot check results
//assert(sum == 1000000);
//assert(counts[0] == 143055);
//assert(counts[6] == 142520);
cout  <<  endl ;

// -----------------------------------------------------------------------
cout  <<   "-------------- testing dictionary insertion  --------------------"   <<  endl ;
id  =   438901234 ;
//dict.insert(id, Employee(id, "Derek Harter", "123 Main St. Commerce TX", 58.23));
id  =   192834192 ;
//dict.insert(id, Employee(id, "Alice White", "384 Bois'darc. Campbell TX", 45.45));
id  =   998439281 ;
//dict.insert(id, Employee(id, "Bob Green", "92 Washington Apt. 5 Greenville TX", 16.00));
id  =   362817371 ;
//dict.insert(id, Employee(id, "Carol Black", "8913 FM 24 Cooper TX", 28.50));
cout  <<   "After inserting "   <<  dict . size ()   <<   " employees:"   <<  endl ;
cout  <<  dict  <<  endl ;

// spot check that hash table entries were correctly performed
//assert(dict.size() == 4);
//assert(dict[3].key() == 192834192);
//assert(dict[3].value().getName() == "Alice White");
//assert(dict[1].key() == 438901234);
//assert(dict[1].value().getName() == "Derek Harter");
cout  <<  endl ;

// -----------------------------------------------------------------------
cout  <<   "-------------- testing dictionary search  -----------------------"   <<  endl ;
id  =   438901234 ;
//e = dict.find(id);
//cout << "Search for id: " << id << endl;
//cout << "   Found employee: " << e << endl;
//assert(e.getId() == id);
//assert(e.getName() == "Derek Harter");

id  =   362817371 ;
//e = dict.find(id);
//cout << "Search for id: " << id << endl;
//cout << "   Found employee: " << e << endl;
//assert(e.getId() == id);
//assert(e.getName() == "Carol Black");

id  =   239481432 ;
//e = dict.find(id);
//cout << "Unsuccessful Search for id: " << id << endl;
//cout << "   Found employee: " << e << endl;
//assert(e.getId() == EMPTY_EMPLOYEE_ID);
//assert(e.getName() == "");
cout  <<  endl ;

// return 0 to indicate successful completion
return   0 ;
}

Source/Assg13/assg13.pdf

 

Assg 13: Dictionaries and Hashing

COSC 2336 Spring 2019

April 18, 2019

Dates:

Due: Sunday May 05, by Midnight

Objectives

• More practice with using class templates

• Learn about implementing and using key/value pair Dictionary ab- straction

• Implement and learn about some basic hashing techniques, like mid- square hasing and quadratic probing for closed hashing schemes.

Description

In this assignment you will be implementing some basic mechanisms of a hash table to implement a Dictionary that uses hashing to store and search for items in its collection. You have been given many files for this assign- ment. I have provided an Employee class in “Employee.[hpp|cpp]” and a KeyValuePair class in “KeyValuePair.[hpp|cpp]”. You will not need to make any changes to these files or classes, they should work as given for this as- signment.

You will be adding and implementing some member functions to the HashDictionary class. The initial “HashDictionary.[hpp|cpp]” file contains a constructor and destructor for a HashDictionary as well as some other accessors and operators already implemented that are used for testing.

You will be implementing a closed hash table mechanism using quadratic probing of the slots. You will also implement a version of the mid-square

1

 

 

hashing function described in our textbook (Shaffer section 9.4.3 on closed hashing mechinsms).

For this assignment you need to perform the following tasks.

1. Your first task is to implement methods to define the probe sequence for closed hasing. Add a member function named probe() to the HashDictionary class. Be aware that the HashDictionary class is a templatized on <Key, Value> templates, thus when you implement the class methods you need to templatize the class methods correctly. You can look at the example implementations of size() and the con- structors to remind yourself how to do this correctly.

In any case, probe() is a member function that takes two parameters, a Key and an integer index value. We are not using secondary hashing (as described in our textbook) so the Key value will actually not be used in your function. However, keep it as a parameter as the gen- eral abstraction/API for the probe function should include it for cases where secondary hashing is used. probe() should be a const class member function, as calling it does not change the dictionary. Finally probe() will return an ineger as its result.

Your probe() funciton should implement a quadratic probing scheme as described in our Shaffer textbook section 9.4.3 on pg. 338. Use c1 = 1, c2 =2, c3 = 2 as the parameters for your quadratic probe (the tests of probe() assume your probe sequence is using these pa- rameter values for the quadratic function).

2. You second tasks is to implement a hash function for integer like keys using the described mid-square hasing function (Shaffer 9.4.1 Example 9.6 pg. 327). We will create a slight variation of this algorithm for our hashing dictionary. First of all the hash() member functions should take a Key as its only input parameter, and it will then return a regular int as its result. Since this is a hash function, the integer value should be in the range 0 – tableSize-1, so don’t forget to mod by the tableSize before returning your hash result.

hash() should work like this. First of all, you should square the key value that is passed in. Then, assuming we are working with a 32 bit int, we want to only keep the middle 16 bits of the square of the key to use for our hash. There are many ways to work with and get the bits you need, but most likely you will want to use C bitwise operators to do this. For example, a simple method to get the middle 16 bits is

2

 

 

to first mask out the upper 8 bits using the bitwise & operator (e.g. key & 0x00FFFFFF) will mask out the high order 8 bits to 0). Then once you have removed the upper most significant 8 bits, you can left shift the key by 8 bits, thus dropping out the lower least significant 8 bits (e.g. key >> 8). Performing a mask of the upper 8 bits and shifting out the lower 8 bits will result in you only retaining the middle 16 bits.

If your system is using 64 bit integers rather than 32 bit integers, perform the mid-square method but retain the middle 32 bits of the result. You can use the sizeof(int) method to determine how many bytes are in an int on your system. I will give a bonus point if you write your hash() function to correctly work for both 32 and 64 bit values by testing sizeof(int) and doing the appopriate work to get the middle bits. Again after you square the key and get the middle bits, make sure you modulo the result to get an actual has index in the correct range.

3. The third task is to add the insert()method to your HashDictionary so that you can insert new key/value pairs into the dictionary. insert() should take a constant Key reference and a constant Value reference as its input parameters (note that both of these parameters should be declared as const, and they should both be reference pa- rameters, so use the & to indicate they are passed by reference). Your insert() function does not return a result, so it will be a void func- tion.

The algorithm for insert is described in Shaffer 9.4.3 on pg. 334. You need to call and use the probe() and hash() funciton you created in the first 2 steps to correctly define/implement your closed hashing probe sequence. The basica algorithm is that you use hash() to de- termine the initial home slot, and probe() gives an offset you should add. Basically you have to search the hashTable using the probe se- quence until you find an empty slot. Once you find an empty slot, you should create a new instance of a KeyValuePair<Key, Value> object, that contains the key and value that were provided as input param- eters to your insert() function. This KeyValuePair instance should then be inserted into the table at the location where you find the first empty slot on the probe sequence. Also don’t forget to update the valueCount paramemter of the HashDictionary class that keeps track of the number of items currently in the dictionary.

3

 

 

4. Finally you will also implement the find() method to search for a particular key in your dictionary. The find() member function taks a single Key parameter as input (it should be a const Key& reference parameter). The find() functin will return a Value as a result, which will be the Value of the record associated with the given Key if it was found in the dictionary, or an empty Value() object if it was not found.

The find() method uses the same probe sequence as insert() imple- mented by your probe() and hash() methods. So you should again search along the probe sequence, until you either find the key you were given to search for, or else find an empty slot. Then at the end, if you found the key in the hashTable you should return the value that corresponds to the key that was searched for. If the search failed and you found an empty slot on your probe sequence, you should instead return an empty Value() object, which is used as an indicator for a failed search.

In this assignment you will be given a lot of starting code. As usual, there is an “assg-13.cpp” file which contains commented out tests of the code/functions you are to write. You have been given and “Em- ployee.[hpp|cpp]” file containing a simple definition of a (non-templated) class/record that holds a few pieces of information about a theoretical Employee. We use this class to create a hash dictionary for testing with the employee id as the key, and the Employee record as the associated value in our Dictionary. You have also been given a template class in the file “KeyValuePair.[hpp|cpp]”. This contains a templatized container to holding a key/value pair of items. You will not need to add any code or make any changes in the Employee or KeyValuePair class files.

You have also been given a “HashDictionary.[hpp|cpp]” file containing beginning defintions of a HashDictionary class. The member functions you need to add for this assignment should be added to these files.

Here is an example of the output you should get if your code is passing all of the tests and is able to run the simulation. You may not get the exact same statistics for the runSimulation() output, as the simulation is generating random numbers, but you should see similar values.

—– testing Employee record and KeyValuePair class ———– test key: 42 test value: blue ( id: 3, Derek Harter, 1234 Main Street, Commerce TX, 12345.67 )

4

 

 

————– testing quadratic probing ———————– Newly created hash dictionary should be empty, size: 0 probe index: 0 returned probe value: 2 probe index: 1 returned probe value: 5 probe index: 5 returned probe value: 37

————– testing mid-square hashing ———————- Assuming 32 bit (4 byte) ints for these tests: 4 hash key: 3918 returned hash value: 1 hash key: 48517 returned hash value: 6 hash key: 913478 returned hash value: 5 hash key: 8372915 returned hash value: 4 counts for slot[0] = 143055 counts for slot[1] = 143040 counts for slot[2] = 143362 counts for slot[3] = 142399 counts for slot[4] = 142966 counts for slot[5] = 142658 counts for slot[6] = 142520

————– testing dictionary insertion ——————– After inserting 4 employees: Slot: 0

Key : 362817371 Value: ( id: 362817371, Carol Black, 8913 FM 24 Cooper TX, 28.50 )

Slot: 1 Key : 438901234 Value: ( id: 438901234, Derek Harter, 123 Main St. Commerce TX, 58.23 )

Slot: 2 Key : 0 Value: ( id: 0, , , 0.00 )

Slot: 3 Key : 192834192 Value: ( id: 192834192, Alice White, 384 Bois’darc. Campbell TX, 45.45 )

Slot: 4

5

 

 

Key : 998439281 Value: ( id: 998439281, Bob Green, 92 Washington Apt. 5 Greenville TX, 16.00 )

Slot: 5 Key : 0 Value: ( id: 0, , , 0.00 )

Slot: 6 Key : 0 Value: ( id: 0, , , 0.00 )

————– testing dictionary search ———————– Search for id: 438901234

Found employee: ( id: 438901234, Derek Harter, 123 Main St. Commerce TX, 58.23 )

Search for id: 362817371 Found employee: ( id: 362817371, Carol Black, 8913 FM 24 Cooper TX, 28.50 )

Unsuccessful Search for id: 239481432 Found employee: ( id: 0, , , 0.00 )

Assignment Submission

A MyLeoOnline submission folder has been created for this assignment. You should attach and upload your completed “HashDictionary.[hpp|cpp]” source files to the submission folder to complete this assignment. You do not need to submit your “assg-13.cpp” file with the tests, nor the Employee or KeyVal- uePair files, since you should not have made changes to any of these (except to uncomment out the tests in assg-13.cpp). Please only submit the asked for source code files, I do not need your build projects, executables, project files, etc.

6

 

 

Requirements and Grading Rubrics

Program Execution, Output and Functional Requirements

1. Your program must compile, run and produce some sort of output to be graded. 0 if not satisfied.

2. (20 pts.) probe() member function implemented. Function is using quadratic probing as asked for, with correct values for c1, c2 and c3 parameters. Probe sequence appears correct and passes tests.

3. (20 pts.) hash() member function implemented correctly. Function implements the mid-square method as described. Function correctly uses only the 16 middle bits if system uses 32 bit integers.

4. (30 pts.) insert() member function implemented and working. Func- tion appears to be correctly generating probe sequence using the probe() and hash() functions. Items are correctly inserted into ex- pected location in the hash table.

5. (30 pts.) find()member function implemented and working. Function appears to be also correctly using the probe sequence in the same was as insert(). Function passes the expected tests.

Program Style

Your programs must conform to the style and formatting guidelines given for this class. The following is a list of the guidelines that are required for the assignment to be submitted this week.

1. Most importantly, make sure you figure out how to set your indentation settings correctly. All programs must use 2 spaces for all indentation levels, and all indentation levels must be correctly indented. Also all tabs must be removed from files, and only 2 spaces used for indentation.

2. A function header must be present for member functions you define. You must give a short description of the function, and document all of the input parameters to the function, as well as the return value and data type of the function if it returns a value for the member functions, just like for regular functions. However, setter and getter methods do not require function headers.

7

 

 

3. You should have a document header for your class. The class header document should give a description of the class. Also you should doc- ument all private member variables that the class manages in the class document header.

4. Do not include any statements (such as system(“pause”) or inputting a key from the user to continue) that are meant to keep the terminal from going away. Do not include any code that is specific to a single operating system, such as the system(“pause”) which is Microsoft Windows specific.

8

 

Source/Assg13/Employee.cpp

Source/Assg13/Employee.cpp

/**

*  @description  Simple example of an Employee record/class
*   we can use to demonstrate HashDictionary key/value pair
*   management.
*/
#include   < string >
#include   < iostream >
#include   < iomanip >
#include   < sstream >
#include   "Employee.hpp"
using   namespace  std ;

/** constructor
* Default constructor for our Employee record/class.  Construct an
* empty employee record
*/
Employee :: Employee ()
{
this -> id  =  EMPTY_EMPLOYEE_ID ;
this -> name  =   "" ;
this -> address  =   "" ;
this -> salary  =   0.0 ;
}

/** constructor
* Basic constructor for our Employee record/class.
*/
Employee :: Employee ( int  id ,  string name ,  string address ,   float  salary )
{
this -> id  =  id ;
this -> name  =  name ;
this -> address  =  address ;
this -> salary  =  salary ;
}

/** id accessor
* Accessor method to get the employee id.
*
*  @returns  int Returns the integer employee id value.
*/
int   Employee :: getId ()   const
{
return  id ;
}

/** name accessor
* Accessor method to get the employee name.
*
*  @returns  string Returns the string containing the full
*   employee name for this record.
*/
string  Employee :: getName ()   const
{
return  name ;
}

/** overload operator<<
* Friend function to ouput representation of Employee to an
* output stream.
*
*  @param  out A reference to an output stream to which we should
*   send the representation of an employee record for display.
*  @param  employee The reference to the employee record to be displayed.
*
*  @returns  ostream& Returns a reference to the original output
*   stream, but now the employee information should have been
*   inserted into the stream for display.
*/
ostream &   operator << ( ostream &  out ,   Employee &  employee )
{
//out << "Employee id: " << employee.id << endl
//    << "    name   : " << employee.name << endl
//    << "    address: " << employee.address << endl
//    << "    salary : " << fixed << setprecision(2) << employee.salary << endl;
out  <<   "( id: "   <<  employee . id  <<   ", "
<<  employee . name  <<   ", "
<<  employee . address  <<   ", "
<<  fixed  <<  setprecision ( 2 )   <<  employee . salary  <<   " )"   <<  endl ;

return  out ;
}

Source/Assg13/Employee.hpp

/** * @description Simple example of an Employee record/class * we can use to demonstrate HashDictionary key/value pair * management. */ #include <string> #include <iostream> using namespace std; #ifndef EMPLOYEE_HPP #define EMPLOYEE_HPP // This should really be a class constant, however this // global constant represents a flag that is used to // indicate empty slots and/or failed search. const int EMPTY_EMPLOYEE_ID = 0; /** Employee * A simple Employee class/record to demonstrate/test * our hashing dictionary assignment. * NOTE: we are using 0 as a flag to represent an unused * slot or an invalid/empty employee. This is used/assumed * by our dictionary class to determine if a slot is empty * and/or to give a failure result for a failed search. */ class Employee { private: int id; string name; string address; float salary; public: Employee(); Employee(int id, string name, string address, float salary); int getId() const; string getName() const; friend ostream& operator<<(ostream& out, Employee& employee); }; #endif // EMPLOYEE_HPP

Source/Assg13/HashDictionary.cpp

Source/Assg13/HashDictionary.cpp

/**

*  @description  Template class for definining a dictionary
*   that uses a hash table of KeyValuePair items.
*   Based on Shaffer hashdict implementation pg. 340
*/

/** constructor
* Standard constructor for the HashDictionary
*
*  @param  tableSize The size of the hash table that should be
*   generated for internal use by this dictionary for hasing.
*  @param  emptyKey A special flag/value that can be used to detect
*   invalid/unused keys.  We need this so we can indicate which
*   slots/buckets in our hash table are currently empty, and also
*   this value is used as a return result when an unsuccessful
*   search is performed on the dictionary.
*/
template   < class   Key ,   class   Value >
HashDictionary < Key ,   Value >:: HashDictionary ( int  tableSize ,   Key  emptyKey )
{
this -> tableSize  =  tableSize ;
this -> EMPTYKEY  =  emptyKey ;
valueCount  =   0 ;

// allocate an array/table of the indicated initial size
hashTable  =   new   KeyValuePair < Key ,   Value > [ tableSize ];

// initialize the hash table so all slots are initially empty
for   ( int  index  =   0 ;  index  <  tableSize ;  index ++ )
{
hashTable [ index ]. setKey ( EMPTYKEY );
}
}

/** destructor
* Standard destructor for the HashDictionary.  Be good memory managers and
* free up the dynamically allocated array of memory pointed to by hashTable.
*/
template   < class   Key ,   class   Value >
HashDictionary < Key ,   Value >::~ HashDictionary ()
{
delete []  hashTable ;
}

/** size
* Accessor method to get the current size of this dictionary,
* e.g. the count of the number of key/value pairs currently being
* managed in our hash table.
*
*  @returns  in Returns the current number of items being managed by
*   this dictionary and currently in our hashTable.
*/
template   < class   Key ,   class   Value >
int   HashDictionary < Key ,   Value >:: size ()   const
{
return  valueCount ;
}

// Place your implementations of the class methods probe(), hash(),
// insert() and find() here

/** overload indexing operator[]
* Overload indexing operator[] to provide direct access
* to hash table.  This is not normally part of the Dictionary
* API/abstraction, but included here for testing.
*
*  @param  index An integer index.  The index should be in the range 0 - tablesize-1.
*
*  @returns  KeyValuePair<> Returns a KeyValuePair object if the index into the
*   internal hash table is a valid index.  This method throws an exception if
*   the index is not a valid slot of the hash table.
*/
template   < class   Key ,   class   Value >
KeyValuePair < Key ,   Value >&   HashDictionary < Key ,   Value >:: operator []( int  index )
{
if   ( index  <   0   ||  index  >=  tableSize )
{
cout  <<   "Error: <HashDictionary::operator[] invalid index: "
<<  index  <<   " table size is currently: "
<<  tableSize  <<  endl ;
assert ( false );
}

return  hashTable [ index ];
}

/** HashDictionary output stream operator
* Friend function for HashDictionary.  We normally wouldn't have
* something like this for a Dictionary or HashTable, but for testing
* and learning purposes, we want to be able to display the contents of
* each slot in the hash table of a HashDictionary container.
*
*  @param  out An output stream reference into which we should insert
*   a representation of the given HashDictionary.
*  @param  aDict A HashDictionary object that we want to display/represent
*   on an output stream.
*
*  @returns  ostream& Returns a reference to the original given output stream,
*   but now the values representing the dictionary we were given should
*   have been sent into the output stream.
*/
template   < typename  K ,   typename  V >
ostream &   operator << ( ostream &  out ,   const   HashDictionary < K ,  V >&  aDict )
{
for   ( int  slot  =   0 ;  slot  <  aDict . tableSize ;  slot ++ )
{
out  <<   "Slot: "   <<  slot  <<  endl ;
out  <<   "     Key  : "   <<  aDict . hashTable [ slot ]. key ()   <<  endl ;
out  <<   "     Value: "   <<  aDict . hashTable [ slot ]. value ()   <<  endl ;
}
out  <<  endl ;
return  out ;
}

Source/Assg13/HashDictionary.hpp

/** * @description Template class for definining a dictionary * that uses a hash table of KeyValuePair items. * Based on Shaffer hashdict implementation pg. 340 */ #include <cassert> #include <iostream> #include “KeyValuePair.hpp” using namespace std; #ifndef HASHDICTIONARY_HPP #define HASHDICTIONARY_HPP /** HashDictionary * An implementation of a dictionary that uses a hash table to insert, search * and delete a set of KeyValuePair items. In the assignment, we will be * implementing a closed hashing table with quadratic probing. The hash function * will implement a version of the mid-square hasing function described in * our Shaffer textbook. * * @value hashTable An array of KeyValuePair items, the hash table this class/container * is managing. * @value tableSize The actual size of the hashTable array * @value valueCount The number of KeyValuePair items that are currently being * managed and are contained in the hashTable * @value EMPTYKEY A special user-supplied key that can be used to indicate empty * slots. Since how we determine what is a valid/invalid key will depend on the * key type, the user must supply this special flag/value when setting up the * hash dictionary. */ template <class Key, class Value> class HashDictionary { protected: KeyValuePair<Key, Value>* hashTable; // the hash table int tableSize; // the size of the hash table, e.g. symbol M from textbook int valueCount; // the count of the number of value items currently in table Key EMPTYKEY; // a special user-supplied key that can be used to indicate empty slots public: // constructors and destructors HashDictionary(int tableSize, Key emptyKey); ~HashDictionary(); // accessor methods int size() const; // searching and insertion // all 4 of the methods you were required to create for this // assignment should have appropriate class method signatures // defined here. // overload operators (mostly for testing) KeyValuePair<Key, Value>& operator[](int index); template <typename K, typename V> friend ostream& operator<<(ostream& out, const HashDictionary<K, V>& aDict); }; #include “HashDictionary.cpp” #endif // HASHDICTIONARY_HPP

Source/Assg13/KeyValuePair.cpp

Source/Assg13/KeyValuePair.cpp

/**

*  @description  Template class for definining Key/Value pairs,
*   suitable for dictionary and hash table implementations.
*   Based on Shaffer KVPair ADT definition, pg. 139 Fig 4.31.
*/

/** constructor
* Default constructor for a KeyValuePair.
*/
template   < class   Key ,   class   Value >
KeyValuePair < Key ,   Value >:: KeyValuePair ()
{

}

/** constructor
* Standard constructor for a KeyValuePair.
*
*  @param  key The key portion that is to be stored in this pair.
*  @param  value The value portion that is to be stored in this pair.
*/
template   < class   Key ,   class   Value >
KeyValuePair < Key ,   Value >:: KeyValuePair ( Key  key ,   Value   value )
{
this -> myKey  =  key ;
this -> myValue  =   value ;
}

/** key accessor
* Accessor method to get and return the key for this key/value pair
*
*  @returns  Key Returns an object of template type Key, which is the
*   key portion of the pair in this container.
*/
template   < class   Key ,   class   Value >
Key   KeyValuePair < Key ,   Value >:: key ()
{
return  myKey ;
}

/** key setter
* Accessor method to set the key for this key/value pair
*
*  @param  key The new value to update the key to for this pair.
*/
template   < class   Key ,   class   Value >
void   KeyValuePair < Key ,   Value >:: setKey ( Key  key )
{
this -> myKey  =  key ;
}

/** value accessor
* Accessor method to get and return the value for this key/value pair.
*
*  @returns  Value& Returns a reference to the value object in this
*   key value pair container.
*/
template   < class   Key ,   class   Value >
Value &   KeyValuePair < Key ,   Value >:: value ()
{
return  myValue ;
}

Source/Assg13/KeyValuePair.hpp

/** * @description Template class for definining Key/Value pairs, * suitable for dictionary and hash table implementations. * Based on Shaffer KVPair ADT definition, pg. 139 Fig 4.31. */ #ifndef KEYVALUEPAIR_HPP #define KEYVALUEPAIR_HPP /** KeyValue Pair * Definition of basic key/value pair container. This container of course * associates a value (usually a record like a class or struct), with * a key (can be anything). * * We do not use the comparator Strategy pattern as discussed in * Shaffer pg. 144 here. We assume that the Key type has suitably * overloaded operators for <, >, ==, <=, >= operations as needed * in order to compare and order keys if needed by dictionaries and * hash tables using a KeyValuePair. * * @value key The key for a key/value pair item/association. * @value value The value for a key/value pair, usually something like * a record (a class or struct of data we are hashing or keeping in * a dictionary). */ template <class Key, class Value> class KeyValuePair { private: Key myKey; Value myValue; public: // constructors KeyValuePair(); KeyValuePair(Key key, Value value); // accessors, getters and setters Key key(); void setKey(Key key); Value& value(); }; #include “KeyValuePair.cpp” #endif // KEYVALUEPAIR_HPP

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

Concepts Of Programming Language: Building A Scanner

Example Pseudocode

Problem: Given a sorted array a with n elements (i.e., a[0] <= a[1] <= … a[n-1]) and a number m, find if m is in the array.

 

1. Main pseudo code

 

data

given data

n: the number of integers given

a[0], …, a[n-1]: the given integers

m: given integer (to check if it is in a)

unknown data: N.A.

intermediate data:

found: indicating if is found from a

plan

// get array an from user input (numbers in a must be ordered).

n = getseries(a)

// find if is in array from index 0 to n-1

found = search(a, 0 , n-1, m)

if found print is found in a.

Otherwise print is not found in a.

 

(Pseudo code for all functions used in the main pseudocode)

 

2. Pseudo code for search function

 

Function name: search

input:

a: an array of numbers

bottom, top: bottom and top index

m: the number to search from a[bottom] to a[top]

output:

b: 1 if is in a a[bottom] to a[top]0 otherwise

Data

mid: middle index of the array

plan:

if (bottom > top) b = 0 and stop.

find the mid point mid of the array between bottom and top

if (a[mid] == mb = 1

else if (m > a[mid])

P2.1 // find if m is in a from mid+1 to top:

b = search(a, mid+1, top, m)

else P2.2 // find if m is in from bottom to mid-1

b = search(a, bottom, mid-1,m)

 

3. Pseudo code for getSeries function

 

omitted here

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

Concepts Of Programming Language: Building A Scanner

Example Pseudocode

Problem: Given a sorted array a with n elements (i.e., a[0] <= a[1] <= … a[n-1]) and a number m, find if m is in the array.

 

1. Main pseudo code

 

data

given data

n: the number of integers given

a[0], …, a[n-1]: the given integers

m: given integer (to check if it is in a)

unknown data: N.A.

intermediate data:

found: indicating if is found from a

plan

// get array an from user input (numbers in a must be ordered).

n = getseries(a)

// find if is in array from index 0 to n-1

found = search(a, 0 , n-1, m)

if found print is found in a.

Otherwise print is not found in a.

 

(Pseudo code for all functions used in the main pseudocode)

 

2. Pseudo code for search function

 

Function name: search

input:

a: an array of numbers

bottom, top: bottom and top index

m: the number to search from a[bottom] to a[top]

output:

b: 1 if is in a a[bottom] to a[top]0 otherwise

Data

mid: middle index of the array

plan:

if (bottom > top) b = 0 and stop.

find the mid point mid of the array between bottom and top

if (a[mid] == mb = 1

else if (m > a[mid])

P2.1 // find if m is in a from mid+1 to top:

b = search(a, mid+1, top, m)

else P2.2 // find if m is in from bottom to mid-1

b = search(a, bottom, mid-1,m)

 

3. Pseudo code for getSeries function

 

omitted here

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

CMIS PROJECT

1

Project 3

In this assignment you will be performing some additional queries against your Online Vehicle Sales (OVS), Inc. online transaction processing (OLTP) database and also creating some simple anonymous PL/SQL blocks.

You will also begin the creation of a data warehouse database for Online Vehicle Sales (OVS), Inc. The full data warehouse is comprised of 4 dimension tables and a fact table based on the Star Schema diagram posted in LEO’s Week #6 area. Your OLTP database tables and star schema tables will reside in the same Oracle schema.

This assignment is based on the fully populated tables from Homework #2 so it assumes you’ve completed all work for that assignment.

You can perform this assignment based on a database on Nova or any other Oracle system you wish, but you must use the Oracle RDBMS.

You should use one or more SQL script files to complete this assignment. Your script files should contain all your SQL and PL/SQL code. Do NOT submit your SQL script files. Doing so may result in confusion and will result in lost points.

Everything for this assignment must be in a single file. If you are using SQL*Plus you must put all your SQL, PL/SQL, and results together in a single SPOOL file. If you are using SQL Developer or other GUI, put all your screen snapshots in a single file for both your SQL statements and PL/SQL as they executed and the results. Failure to include all your SQL, PL/SQL, and all your results along with them will result in lost points.

Do NOT submit additional files as this only complicates the grading, and will result in lost points.

Here are the specific assignment steps. In order to earn full credit you must keep your steps in order, number your steps, and put everything in a single file.

1) Execute SELECT COUNT(*) FROM <table_name>; statements for all 6 of your OVS, Inc. OLTP tables. You should have at least the following counts: CUSTOMERS table – 100 rows, VEHICLES table – 50 rows, SALESPERSONS table – 10 rows, FINANCING_PLANS – 5 rows, SALES table – 200 rows, and SALES_FINANCINGS table – 200 rows.

2) Via a single SELECT query display the zip code, make, and count with the largest total car purchases for a zip code and make combination (there may be a tie with two or more). Show the SQL statement you used and the results returned by Oracle from executing your SQL statement right after the statement.

3) Develop a PL/SQL anonymous block that displays the total sales for a zip code for a specific zip code. You may use any of your zip codes you wish. Show the PL/SQL statements in your block, the actual execution of your block, and the results returned.

2

4) Develop a PL/SQL anonymous block that displays the zip code with the largest total car purchases. Since there can be a tie with two or more zip codes, ensure that the lowest numeric zip code is displayed. The zip code displayed should correlate to the results of Step #2. Show the PL/SQL statements in your block, the actual execution of your block, and the results returned.

5) This step begins the creation of your data warehouse. Ensure that your FINANCING_PLANS table has already been created and populated via a “SELECT * FROM financing_plans;” SQL query. This table is used by both your OLTP database and serves as a dimension table in the star schema of your data warehouse database. Your Plan_ID primary key is the Plan_Code column. Don’t worry about changing this to Plan_Code or changing any other column names you already have. Show the SQL you used and executed and the results.

6) Create the DEALERSHIPS star schema dimension table via SQL. Add at least 2 rows of data via INSERT statement(s). After populating your DEALERSHIPS table execute a “SELECT * FROM dealerships;” SQL statement to display the entire contents. Show all your SQL code for this step and the Oracle results from executing it.

7) Create the VEHICLES star schema dimension table via SQL. Change your existing OLTP VEHICLES table to OLTP_VEHICLES via the SQL RENAME command and change your SALES table’s foreign key to reference this new table name. For the Vehicle_Code primary key column use an Oracle sequence to populate the values. For the Description column use all concatenated combinations of Make and Model of vehicles you have. Use a PL/SQL block to populate the Description column by SELECTing the combinations from your OLTP_VEHICLES table and then INSERTing the combinations into your new VEHICLES table, which would best be performed via a cursor in a loop. After populating your VEHICLES table execute a “SELECT * FROM vehicles ORDER BY vehicle_code” SQL statement to display the entire contents. Show all your SQL and PL/SQL code for this step and the Oracle results from executing it.

Your submission MUST be in a single text, Word, or PDF file with all steps numbered and in order.

Project 3 grading rubric

Attribute

Meets

Does Not Meet

CREATE TABLE SQL statements

20 points

Uses an SQL script file.

Creates the DEALERSHIPS star schema dimension table.

Creates the VEHICLES star schema dimension table.

Changes your existing OLTP VEHICLES table to OLTP_VEHICLES via the SQL RENAME command and change your SALES table’s foreign key to reference this new table name.

0 points

Does not use an SQL script file.

Does not create the DEALERSHIPS star schema dimension table.

Does not create the VEHICLES star schema dimension table.

Does not change your existing OLTP VEHICLES table to OLTP_VEHICLES via the SQL RENAME command or change your SALES table’s foreign key

3

Uses an Oracle sequence to populate the Vehicle_Code values.

Uses all concatenated combinations of Make and Model of vehicles for the Description column.

Uses an Oracle RDBMS.

All SQL statements are syntactically correct and execute without error.

to reference this new table name.

Does not use an Oracle sequence to populate the Vehicle_Code values.

Does not use all concatenated combinations of Make and Model of vehicles for the Description column.

Does not use an Oracle RDBMS.

All SQL statements are not syntactically correct or execute without error.

INSERT SQL statements

25 points

Adds at least 2 rows of data via INSERT statement(s) to the DEALERSHIPS Star schema table.

All SQL statements are syntactically correct and execute without error.

0 points

Does not add at least 2 rows of data via INSERT statement(s) to the DEALERSHIPS Star schema table.

All SQL statements are not syntactically correct or execute without error.

SELECT SQL statements

5 points

Executes SELECT COUNT(*) FROM <table_name>; for all OLT tables resulting in expected counts.

Via a single SELECT query display the zip code, make, and count with the largest total car purchases for a zip code and make combination.

Ensures that your FINANCING_PLANS table has already been created and populated via a “SELECT * FROM

0 points

Does not execute SELECT COUNT(*) FROM <table_name>; for all OLT tables resulting in expected counts.

Does not, via a single SELECT query, display the zip code, make, and count with the largest total car purchases for a zip code and make combination.

Does not ensure that your FINANCING_PLANS table has already been created and

4

financing_plans.

After populating your DEALERSHIPS table execute a “SELECT * FROM dealerships;”

After populating your VEHICLES table execute a “SELECT * FROM vehicles ORDER BY vehicle_code”.

All SQL statements are syntactically correct and execute without error.

populated via a “SELECT * FROM financing_plans.

Does not, After populating your DEALERSHIPS table execute a “SELECT * FROM dealerships;”

Does not, after populating your VEHICLES table execute a “SELECT * FROM vehicles ORDER BY vehicle_code”.

All SQL statements are syntactically correct and execute without error.

All SQL statements are not syntactically correct or execute without error.

PL/SQL anonymous blocks

40 points

Develops a PL/SQL anonymous block that displays the total sales for a zip code for a specific zip code.

Develops a PL/SQL anonymous block that displays the zip code with the largest total car purchases.

Ensures that the lowest numeric zip code is displayed.

The zip code displayed should correlate to the results of Step #2 above.

Uses a PL/SQL block to populate the Description column by SELECTing the combinations from your OLTP_VEHICLES table and then INSERTing the combinations into your new VEHICLES table, which would best be performed via a cursor in a loop.

0 points

Does not develop a PL/SQL anonymous block that displays the total sales for a zip code for a specific zip code.

Does not develop a PL/SQL anonymous block that displays the zip code with the largest total car purchases.

Does not ensure that the lowest numeric zip code is displayed.

The zip code displayed does not correlate to the results of Step #2 above.

Does not use a PL/SQL block to populate the Description column by SELECTing the combinations from your OLTP_VEHICLES table and then INSERTing the combinations into your new VEHICLES table, which would

5

best be performed via a cursor in a loop.

SQL script file and SPOOL file

10 points

Submits either an SQL*Plus SPOOL file or screen snapshots of the output if using SQL Developer or another GUI.

Demonstrates DROP TABLE, CREATE TABLE, and ALTER TABLE SQL statements as they executed and the Oracle responses.

Demonstrates INSERT SQL statements as they executed and the Oracle responses.

Displays the contents of all tables from SELECT * FROM tablename; statements.

Displays all single SELECT statements queries.

Displays all PL/SQL code and execution.

Does NOT submit a SQL script file.

Includes a SET ECHO ON SQL*Plus statement in your SQL script file to ensure that all the SQL that is executed is displayed in your SPOOL file.

0 points

Does not submit either an SQL*Plus SPOOL file or screen snapshots of the output if using SQL Developer or another GUI.

Does not demonstrate DROP TABLE, CREATE TABLE, and ALTER TABLE SQL statements as they executed and the Oracle responses.

Does not demonstrate INSERT SQL statements as they executed and the Oracle responses.

Does not display the contents of all tables from SELECT * FROM tablename; statements.

Does not display all single SELECT statements queries.

Does not display all PL/SQL code and execution.

Submits a SQL script file.

Does not Include a SET ECHO ON SQL*Plus statement in your SQL script file to ensure that all the SQL that is executed is displayed in your SPOOL file.

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

Wk 1: Discussion 2 [Due Tomorrow]

Review the “Chapter Two Case: Michael Porter on TED – The Case for Letting Business Solve Social Problems” at the end of Ch. 2 of Business Driven Technology.

Answer the following questions:

  • Do you agree or disagree that business can solve social problems? Justify your answer.
  • How can the concepts discussed by Michael Porter help with the decision making process for managers at the three different managerial levels?

Respond to at least three of your peers. In your response, address any thoughts you have on if business can solve social problems and if it can help managers make decisions.

Students need to contribute three substantive posts in this discussion by the due date indicated. The substantive posts can be any combination of responses and replies.

Peer 1

If the statement was stated slightly different I would completely agree with it. I do believe that business can help with social problems, but they will not be the resolve for them. For example, many commercial grocery stores donate all the food that is past its “Selling” date to food banks and non-profits that feed the poor. Just because it has past its sell by date does not mean the food is bad, it just means you cannot legally sell the product. There are more and more non-profits to help the less fortunate in almost every community. The fact that businesses will not be the resolve for social problems is simply because they are a business they are here to make money, one of the reasons for even the handout of the food example is because they get to write that loss off on taxes.

Most businesses are broken into a few different management levels, Operations, VPs and executive staff. The operations management provide day to day decisions that affect the operations of say their bank branch which they manage. They make decisions such as who is working which teller line. VPs and support staff make decisions on who is doing what problems or incidents. The Executive staff focus on more of the business long term decisions which have an affect of the entire company.

Reference: Baltzan P (2017, Business Driven Technology (7th ed) New York, NY, McGraw-Hill

Peer 2

Do you agree or disagree that business can solve social problems? Justify your answer.

Yes, I do believe that businesses can help solve social problems. There have been an increasing number of restaurants, farmers markets, grocery stores and even some college campuses that donate fresh food that is past its’ selling prime, but still perfectly safe to eat, to food pantries who distribute it to low income families in both rural and urban food deserts. This not only helps feed many needy families but is also good for the planet. Wasted food is a huge producer of greenhouse gasses which contribute to climate change.

Publix supermarkets are active supporters of youth organizations in their communities and also donate to Habitat for Humanity. Stoneyfield farms are big contributors to environmental causes and nonprofits.          .

Bill and Melinda Gates created their foundation to help improve the health conditions for children in developing countries. They have also donated hundreds of millions of dollars to the library system to provide internet access and computers to libraries nationwide. Their foundation is also dedicated to improving our failing education system by donating millions of dollars to help schools hire and retain high-quality teachers, and educational materials. Warren Buffett is also a huge contributor to the foundation. While this is a non-profit, it does have a big social impact.

These are just a few examples of how businesses are working to help solve social problems. I also believe that when a business is involved in giving back to their communities and helping to solve social injustices or supporting environmental issues, this helps build customer goodwill which in turn can lead to increased profits. I know I would rather spend a little more with a company that does good things and gives back than one that only cares about their shareholders profits. Mr. Porter stated that we need to achieve scalability when it comes to businesses helping solve social problems. If businesses are to buy in to this, they need to see how much more profitable they could be by working on social problems and less profitable by not doing it.

·        How can the concepts discussed by Michael Porter help with the decision- making process for managers at the three different managerial levels?

Operational – These lower level managers make structured decisions that affect the day to day operations of their departments regarding internal functions, such as which machine an employee will run today or shifting people around to cover for someone who is out sick.

Managerial – These middle level managers make semi-structured decisions that affect a short-ish term time frame. Their performance indicators focus on efficiency and effectiveness.

Strategic – These high level, senior executives make unstructured decisions that affect a long term time frame. Their focus is on the effectiveness and success of the entire company.

Reference:

Baltzan, P. (2017). Business driven technology (7th ed.).

New York, NY: McGraw-Hill/Irwin.

Peer 3

After listen to the TED talk of Michael Porter, I believe business can solve Social problems, if they are willing. One of the main issues that Micheal bring up is the scale of the social issues, While the government and NGOs can make some progress the scale of the social problems are so large that they can not make large scale impacts on the problems, the resources are limited and not enough money being tax revenue and donations. Business have more resources and business create wealth from what Micheal talked about. (Porter, 2013). Since business make the wealth and money, the businesses need to be involve to have which will allow business resources to deal with the scales of the social problems. One social issue that is talked about is pollution, the conventional thing by business it is not worrying about pollution so that you make more money well the fact is business can be have less pollution and still be profitable, yes it is a balance however, if after the initial investment to be less polluting they will still be profitable and pollute less which will in-turn help with the social problem of pollution where the government and NGO can not assist.

Reference: Porter, M 2013. Retrieved from https://www.ted.com/talks/michael_porter_why_business_can_be_good_at_solving_social_problems#t-587925

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

NETWORKING QUIZ

Mike Meyers’

CompTIA Network+® Guide to Managing and

Troubleshooting Networks

Third Edition

(Exam N10-005)

 

 

This page intentionally left blank

 

 

Mike Meyers’

CompTIA Network+® Guide to Managing and

Troubleshooting Networks

Third Edition

(Exam N10-005)

Mike Meyers

New York Chicago San Francisco Lisbon London Madrid Mexico City Milan

New Delhi San Juan Seoul Singapore Sydney Toronto

BaseTech

 

 

Copyright © 2012 by the McGraw-Hill Companies. All rights reserved. Printed in the United States of America. Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication.

ISBN: 978-0-07-179981-2

MHID: 0-07-179981-8

The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-178911-0, MHID: 0-07-178911-1.

All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefi t of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps.

McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. To contact a representative please e-mail us at bulksales@mcgraw-hill.com.

McGraw-Hill is an independent entity from CompTIA®. This publication and digital content may be used in assisting students to prepare for the CompTIA Network+ exam. Neither CompTIA nor McGraw-Hill warrants that use of this publication and digital content will ensure passing any exam. CompTIA and CompTIA Network+ are trademarks or registered trademarks of CompTIA in the United States and/or other countries. All other trademarks are trademarks of their respective owners.

Fluke images printed with permission of Fluke Corporation, ©Fluke Corp. Intel image printed with permission of Intel Corporation, ©Intel Corp. TRENDnet images printed with permission of Trendnet Media, ©TRENDnet. Equalizer E650GX image printed by permission of Coyote Point Systems, ©Coyote Point Systems, Inc. www.coyotepoint.com. NetGear image printed with permission of NetGear, ©NETGEAR, Inc. Hewlett-Packard images printed with permission of HP, ©Hewlett-Packard CLEAR image printed with permission of CLEAR, ©CLEAR

TERMS OF USE

This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGrawHill”) and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms.

THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances shall McGraw-Hill and/ or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.

E-book conversion by codeMantra

Version 2.0

 

 

About the Author■■ Michael Meyers is the industry’s leading authority on CompTIA Network+ certifica- tion. He is the president and founder of Total Seminars, LLC, a major provider of PC and network repair seminars for thousands of organizations throughout the world, and a member of CompTIA.

Mike has written numerous popular textbooks, including the best-selling Mike Meyers’ CompTIA A+® Guide to Managing & Troubleshooting PCs, Mike Meyers’ CompTIA A+® Guide to Essentials, and Mike Meyers’ CompTIA A+® Guide to Operating Systems.

About the Contributor Scott Jernigan wields a mighty red pen as Editor in Chief for Total Seminars. With a Master of Arts degree in Medieval History, Scott feels as much at home in the musty archives of London as he does in the warm CRT glow of Total Seminars’ Houston head- quarters. After fleeing a purely academic life, he dove headfirst into IT, working as an instructor, editor, and writer.

Scott has written, edited, and contributed to dozens of books on computer liter- acy, hardware, operating systems, networking, and certification, including Computer Literacy—Your Ticket to IC3 Certification, and co-authoring with Mike Meyers the All-in- One CompTIA Strata® IT Fundamentals Exam Guide.

Scott has taught computer classes all over the United States, including stints at the United Nations in New York and the FBI Academy in Quantico. Practicing what he preaches, Scott is a CompTIA A+ and CompTIA Network+ certified technician, a Microsoft Certified Professional, a Microsoft Office User Specialist, and Certiport Inter- net and Computing Core Certified.

About the Technical Editor Jonathan S. Weissman earned his master’s degree in Computer and Information Science from Brooklyn College (CUNY), and holds nineteen industry certifications, including Cisco CCNA, CompTIA Security+, CompTIA i-Net+, CompTIA Network+, CompTIA A+, CompTIA Linux+, Novell CNE, Novell CNA, Microsoft Office Master, Microsoft MCAS Word, Microsoft MCAS PowerPoint, Microsoft MCAS Excel, Microsoft MCAS Access, Microsoft MCAS Outlook, and Microsoft MCAS Vista.

Jonathan is a tenured Assistant Professor of Computing Sciences at Finger Lakes Community College, in Canandaigua, NY, and also teaches graduate and under- graduate computer science courses at nearby Rochester Institute of Technology. In addi- tion, Jonathan does computer, network, and security consulting for area businesses and individuals.

Between FLCC and RIT, Jonathan has taught nearly two dozen different computer science courses, including networking, security, administration, forensics, program- ming, operating systems, hardware, and software.

Students evaluating his teaching emphasize that he simplifies their understanding of difficult topics, while at the same time makes the class interesting and entertaining.

Jonathan completely designed and configured FLCC’s newest Networking & Secu- rity Lab. Serving as IT Program Coordinator, he rewrote FLCC’s Information Technol- ogy course requirements for the degree, keeping it current with the changes in industry over the years.

This textbook is just one of the many that Jonathan has edited for thoroughness and accuracy.

BaseTech

 

 

This page intentionally left blank

 

 

vii

Acknowledgments■■ I’d like to acknowledge the many people who contributed their talents to make this book possible:

To Tim Green, my acquisitions editor at McGraw-Hill: Didn’t think I’d get the book out this quickly, did you? Thanks for your superb support and encouragement, as always.

To my in-house Editor-in-Chief, Scott Jernigan: Didn’t think we’d get the book out that fast, did you? How many 85s do you have now? Pelape still smokes them all in DPS.

To Jonathan Weissman, technical editor: Holy crap, you kicked my butt. Thanks for making my book dramatically better than it has ever been.

To LeeAnn Pickrell, copy editor: u made me write good, thx. To Michael Smyer, Total Seminars’ resident tech guru and photogra-

pher: Glad to see you staying focused. And your photos rocked as always! To Ford Pierson, graphics maven and editor: Superb conceptual art?

Check! Great editing? Check! Beating the boss in Unreal Tournament over and over again? Check, unfortunately.

To Aaron Verber, editor extraordinaire: Your quiet toils in the dark cor- ner of the office have once again paid outstanding dividends!

To Dudley Lehmer, my partner at Total Seminars: As always, thanks for keeping the ship afloat while I got to play on this book!

To Stephanie Evans, acquisitions coordinator at McGraw-Hill: You are my favorite South African ambassador since the Springboks. Thanks for keeping track of everything and (gently) smacking Scott when he forgot things.

To Molly Sharp and Jody McKenzie, project editors: It was a joy to work with you, Molly, and again with you, Jody. I couldn’t have asked for a better team! (Didn’t think I could resist making the pun, did you?)

To Andrea Fox, proofreader: You did a super job, thank you To Tom and Molly Sharp, compositors: The layout was excellent,

thanks!

To Staci Lynne ■■ Davis, vegan chef and

punk rocker: Thanks for showing me your world

and, in the process, expanding mine.

BaseTech

 

 

Key Terms, identified in red, point out important vocabulary and definitions that you need to know.

Tech Tip sidebars provide inside information from experienced IT professionals.

Cross Check questions develop reasoning skills: ask, compare, contrast, and explain.

Engaging and Motivational— Using a conversational style and proven instructional approach, the author explains technical concepts in a clear, interesting way using real-world examples.

Makes Learning Fun!— Rich, colorful text and enhanced illustrations bring technical subjects to life.

10BaseT also introduced the networking world to the RJ-45 connector (Figure 4.9). Each pin on the RJ-45 connects to a single wire inside the cable; this enables de- vices to put voltage on the indi- vidual wires within the cable. The pins on the RJ-45 are numbered from 1 to 8, as shown in Figure 4.10.

The 10BaseT standard designates some of these numbered wires for specific purposes. As mentioned earlier, although the cable has four pairs, 10BaseT uses only two of the pairs. 10BaseT devices use pins 1 and 2 to send data, and pins 3 and 6 to receive data. Even though one pair of wires sends data and another receives data, a 10BaseT device cannot send and receive simul- taneously. The rules of CSMA/CD still apply: only one device can use the segment contained in the hub without causing a collision. Later versions of Ethernet will change this rule.

An RJ-45 connector is usually called a crimp, and the act (some folks call it an art) of installing a crimp onto the end of a piece of UTP cable is called crimping. The tool used to secure a crimp onto the end of a cable is a crimper. Each wire inside a UTP cable must connect to the proper pin inside the crimp. Manufacturers color-code each wire within a piece of four-pair UTP to assist in properly matching the ends. Each pair of wires consists of a solid- colored wire and a striped wire: blue/blue-white, orange/orange-white, brown/brown-white, and green/green-white (Figure 4.11).

The Telecommunications Industry Association/Electronics Industries Alliance (TIA/EIA) defines the industry standard for correct crimping of four-pair UTP for 10BaseT networks. Two standards currently exist: TIA/ EIA 568A and TIA/EIA 568B. Figure 4.12 shows the TIA/EIA 568A and TIA/ EIA 568B color-code standards. Note that the wire pairs used by 10BaseT (1 and 2; 3 and 6) come from the same color pairs (green/green-white and orange/orange-white). Following an established color-code scheme, such as TIA/EIA 568A, ensures that the wires match up correctly at each end of the cable.

66 Mike Meyers’ CompTIA Network+ Guide to Managing and Troubleshooting Networks

Cross Check Check Your CATs!

You’ve already seen CAT levels in Chapter 3, “Cabling and Topology,” so check your memory and review the different speeds of the various CAT levels. Could 10BaseT use CAT 2? Could it use CAT 6? What types of devices can use CAT 1?

• Figure 4.9 Two views of an RJ-45 connector

• Figure 4.10 The pins on an RJ-45 connector are numbered 1 through 8.

• Figure 4.11 Color-coded pairs

The real name for RJ-45 is “8 Position 8 Contact (8P8C) modular plug.” The name RJ-45 is so dominant, however, that nobody but the nerdiest of nerds calls it by its real name. Stick to RJ-45.

AbouT ThIs book

Proven Learning Method Keeps You on Track Mike Meyers’ CompTIA Network+® Guide to Managing and Troubleshooting Networks is structured to give you comprehensive knowledge of computer skills and technologies. The textbook’s active learning methodology guides you beyond mere recall and—through thought-provoking activities, labs, and sidebars—helps you develop critical-thinking, diagnostic, and communication skills.

Information technology (IT) offers many career paths, leading to occupations in such fields as PC repair, network administration, telecommunications, Web development, graphic design, and desktop support. To become competent in any IT field, however, you need

certain basic computer skills. Mike Meyers’ CompTIA Network+® Guide to Managing and Troubleshooting Networks builds a foundation for success in the IT field by introducing you to fundamental technology concepts and giving you essential computer skills.

Important Technology skills ■

10BaseT also introduced the networking world to the RJ-45 connector (Figure 4.9). Each pin on the RJ-45 connects to a single wire inside the cable; this enables de- vices to put voltage on the indi- vidual wires within the cable. The pins on the RJ-45 are numbered from 1 to 8, as shown in Figure 4.10.

The 10BaseT standard designates some of these numbered wires for specific purposes. As mentioned earlier, although the cable has four pairs, 10BaseT uses only two of the pairs. 10BaseT devices use pins 1 and 2 to send data, and pins 3 and 6 to receive data. Even though one pair of wires sends data and another receives data, a 10BaseT device cannot send and receive simul- taneously. The rules of CSMA/CD still apply: only one device can use the segment contained in the hub without causing a collision. Later versions of Ethernet will change this rule.

An RJ-45 connector is usually called a crimp, and the act (some folks call it an art) of installing a crimp onto the end of a piece of UTP cable is called crimping. The tool used to secure a crimp onto the end of a cable is a crimper. Each wire inside a UTP cable must connect to the proper pin inside the crimp. Manufacturers color-code each wire within a piece of four-pair UTP to assist in properly matching the ends. Each pair of wires consists of a solid- colored wire and a striped wire: blue/blue-white, orange/orange-white, brown/brown-white, and green/green-white (Figure 4.11).

The Telecommunications Industry Association/Electronics Industries Alliance (TIA/EIA) defines the industry standard for correct crimping of four-pair UTP for 10BaseT networks. Two standards currently exist: TIA/ EIA 568A and TIA/EIA 568B. Figure 4.12 shows the TIA/EIA 568A and TIA/ EIA 568B color-code standards. Note that the wire pairs used by 10BaseT (1 and 2; 3 and 6) come from the same color pairs (green/green-white and orange/orange-white). Following an established color-code scheme, such as TIA/EIA 568A, ensures that the wires match up correctly at each end of the cable.

66 Mike Meyers’ CompTIA Network+ Guide to Managing and Troubleshooting Networks

Cross Check Check Your CATs!

You’ve already seen CAT levels in Chapter 3, “Cabling and Topology,” so check your memory and review the different speeds of the various CAT levels. Could 10BaseT use CAT 2? Could it use CAT 6? What types of devices can use CAT 1?

• Figure 4.9 Two views of an RJ-45 connector

• Figure 4.10 The pins on an RJ-45 connector are numbered 1 through 8.

• Figure 4.11 Color-coded pairs

The real name for RJ-45 is “8 Position 8 Contact (8P8C) modular plug.” The name RJ-45 is so dominant, however, that nobody but the nerdiest of nerds calls it by its real name. Stick to RJ-45.

10BaseT also introduced the networking world to the RJ-45 connector (Figure 4.9). Each pin on the RJ-45 connects to a single wire inside the cable; this enables de- vices to put voltage on the indi- vidual wires within the cable. The pins on the RJ-45 are numbered from 1 to 8, as shown in Figure 4.10.

The 10BaseT standard designates some of these numbered wires for specific purposes. As mentioned earlier, although the cable has four pairs, 10BaseT uses only two of the pairs. 10BaseT devices use pins 1 and 2 to send data, and pins 3 and 6 to receive data. Even though one pair of wires sends data and another receives data, a 10BaseT device cannot send and receive simul- taneously. The rules of CSMA/CD still apply: only one device can use the segment contained in the hub without causing a collision. Later versions of Ethernet will change this rule.

An RJ-45 connector is usually called a crimp, and the act (some folks call it an art) of installing a crimp onto the end of a piece of UTP cable is called crimping. The tool used to secure a crimp onto the end of a cable is a crimper. Each wire inside a UTP cable must connect to the proper pin inside the crimp. Manufacturers color-code each wire within a piece of four-pair UTP to assist in properly matching the ends. Each pair of wires consists of a solid- colored wire and a striped wire: blue/blue-white, orange/orange-white, brown/brown-white, and green/green-white (Figure 4.11).

The Telecommunications Industry Association/Electronics Industries Alliance (TIA/EIA) defines the industry standard for correct crimping of four-pair UTP for 10BaseT networks. Two standards currently exist: TIA/ EIA 568A and TIA/EIA 568B. Figure 4.12 shows the TIA/EIA 568A and TIA/ EIA 568B color-code standards. Note that the wire pairs used by 10BaseT (1 and 2; 3 and 6) come from the same color pairs (green/green-white and orange/orange-white). Following an established color-code scheme, such as TIA/EIA 568A, ensures that the wires match up correctly at each end of the cable.

66 Mike Meyers’ CompTIA Network+ Guide to Managing and Troubleshooting Networks

Cross Check Check Your CATs!

You’ve already seen CAT levels in Chapter 3, “Cabling and Topology,” so check your memory and review the different speeds of the various CAT levels. Could 10BaseT use CAT 2? Could it use CAT 6? What types of devices can use CAT 1?

• Figure 4.9 Two views of an RJ-45 connector

• Figure 4.10 The pins on an RJ-45 connector are numbered 1 through 8.

• Figure 4.11 Color-coded pairs

The real name for RJ-45 is “8 Position 8 Contact (8P8C) modular plug.” The name RJ-45 is so dominant, however, that nobody but the nerdiest of nerds calls it by its real name. Stick to RJ-45.

/ Mike Meyers’ CompTIA Network+ Guide to Managing and Troubleshooting Networks, Third Edition / Meyers / 911-1 / fm blind folio ix

 

 

consider that type of NIC. The spe- cific process by which a NIC uses electricity to send and receive data is exceedingly complicated, but luck- ily for you, not necessary to under- stand. Instead, just think of a charge on the wire as a one, and no charge as a zero. A chunk of data moving in pulses across a wire might look something like Figure 2.13.

If you put an oscilloscope on the wire to measure voltage, you’d see something like Figure 2.14. An oscilloscope is a powerful micro- scope that enables you to see elec- trical pulses.

Now, remembering that the pulses represent bi- nary data, visualize instead a string of ones and zeroes moving across the wire (Figure 2.15).

Once you understand how data moves along the wire, the next question becomes this: how does the net- work get the right data to the right system? All networks transmit data by breaking whatever is moving across the physical layer (files, print jobs, Web pages, and so forth) into discrete chunks called frames. A frame is basically a container for a chunk of data moving across a network. The NIC creates and sends, as well as receives and reads, these frames.

I like to visualize an imaginary table inside every NIC that acts as a frame creation and reading station. I see frames as those pneumatic canis- ters you see when you go to a drive-in teller at a bank. A little guy inside the network card—named Nick, naturally!—builds these pneumatic canisters (the frames) on the table, and then shoots them out on the wire to the hub (Figure 2.16).

Chapter 2: Building a Network with the OSI Model 15

Try This! What’s Your MAC Address?

You can readily determine your MAC address on a Windows computer from the command line. This works in all modern versions of Windows.

1. In Windows 2000/XP, click Start | Run. Enter the command CMD and press the ENTER key to get to a command prompt.

2. In Windows Vista, click Start, enter CMD in the Start Search text box, and press the ENTER key to get to a command prompt.

3. At the command prompt, type the command IPCONFIG /ALL and press the ENTER key.

• Figure 2.13 Data moving along a wire

• Figure 2.14 Oscilloscope of data

• Figure 2.15 Data as ones and zeroes

• Figure 2.16 Inside the NIC

A number of different frame types are used in different net- works. All NICs on the same net- work must use the same frame type or they will not be able to communicate with other NICs.

Each chapter includes Learning Objectives ■ that set measurable goals for chapter-by-chapter progress

Illustrations ■ that give you a clear picture of the technologies

Tutorials ■ that teach you to perform essential tasks and procedures hands-on

Try This!, Cross Check ■ , and Tech Tip sidebars that encourage you to practice and apply concepts in real-world settings

Notes, Tips ■ , and Warnings that guide you through difficult areas

Chapter Summaries ■ and Key Terms Lists that provide you with an easy way to review important concepts and vocabulary

Challenging End-of-Chapter Tests ■ that include vocabulary-building exercises, multiple-choice questions, essay questions, and on-the-job lab projects

This pedagogically rich book is designed to make learning easy and enjoyable and to help you develop the skills and critical-thinking abilities that will enable you to adapt to different job situations and troubleshoot problems.

Mike Meyers’ proven ability to explain concepts in a clear, direct, even humorous way makes this book interesting, motivational, and fun.

Effective Learning Tools ■

Proven Learning Method Keeps You on Track Mike Meyers’ CompTIA Network+® Guide to Managing and Troubleshooting Networks is structured to give you comprehensive knowledge of computer skills and technologies. The textbook’s active learning methodology guides you beyond mere recall and—through thought-provoking activities, labs, and sidebars—helps you develop critical-thinking, diagnostic, and communication skills.

Try This! exercises apply core skills in a new setting.

Chapter Review sections provide concept summaries, key terms lists, and lots of questions and projects.

Key Terms Lists presents the important terms identified in the chapter.

Offers Practical Experience— Tutorials and lab assignments develop essential hands-on skills and put concepts in real-world contexts.

Robust Learning Tools— Summaries, key terms lists, quizzes, essay questions, and lab projects help you practice skills and measure progress.

Notes,Tips, and Warnings create a road map for success.

consider that type of NIC. The spe- cific process by which a NIC uses electricity to send and receive data is exceedingly complicated, but luck- ily for you, not necessary to under- stand. Instead, just think of a charge on the wire as a one, and no charge as a zero. A chunk of data moving in pulses across a wire might look something like Figure 2.13.

If you put an oscilloscope on the wire to measure voltage, you’d see something like Figure 2.14. An oscilloscope is a powerful micro- scope that enables you to see elec- trical pulses.

Now, remembering that the pulses represent bi- nary data, visualize instead a string of ones and zeroes moving across the wire (Figure 2.15).

Once you understand how data moves along the wire, the next question becomes this: how does the net- work get the right data to the right system? All networks transmit data by breaking whatever is moving across the physical layer (files, print jobs, Web pages, and so forth) into discrete chunks called frames. A frame is basically a container for a chunk of data moving across a network. The NIC creates and sends, as well as receives and reads, these frames.

I like to visualize an imaginary table inside every NIC that acts as a frame creation and reading station. I see frames as those pneumatic canis- ters you see when you go to a drive-in teller at a bank. A little guy inside the network card—named Nick, naturally!—builds these pneumatic canisters (the frames) on the table, and then shoots them out on the wire to the hub (Figure 2.16).

Chapter 2: Building a Network with the OSI Model 15

Try This! What’s Your MAC Address?

You can readily determine your MAC address on a Windows computer from the command line. This works in all modern versions of Windows.

1. In Windows 2000/XP, click Start | Run. Enter the command CMD and press the ENTER key to get to a command prompt.

2. In Windows Vista, click Start, enter CMD in the Start Search text box, and press the ENTER key to get to a command prompt.

3. At the command prompt, type the command IPCONFIG /ALL and press the ENTER key.

• Figure 2.13 Data moving along a wire

• Figure 2.14 Oscilloscope of data

• Figure 2.15 Data as ones and zeroes

• Figure 2.16 Inside the NIC

A number of different frame types are used in different net- works. All NICs on the same net- work must use the same frame type or they will not be able to communicate with other NICs.

consider that type of NIC. The spe- cific process by which a NIC uses electricity to send and receive data is exceedingly complicated, but luck- ily for you, not necessary to under- stand. Instead, just think of a charge on the wire as a one, and no charge as a zero. A chunk of data moving in pulses across a wire might look something like Figure 2.13.

If you put an oscilloscope on the wire to measure voltage, you’d see something like Figure 2.14. An oscilloscope is a powerful micro- scope that enables you to see elec- trical pulses.

Now, remembering that the pulses represent bi- nary data, visualize instead a string of ones and zeroes moving across the wire (Figure 2.15).

Once you understand how data moves along the wire, the next question becomes this: how does the net- work get the right data to the right system? All networks transmit data by breaking whatever is moving across the physical layer (files, print jobs, Web pages, and so forth) into discrete chunks called frames. A frame is basically a container for a chunk of data moving across a network. The NIC creates and sends, as well as receives and reads, these frames.

I like to visualize an imaginary table inside every NIC that acts as a frame creation and reading station. I see frames as those pneumatic canis- ters you see when you go to a drive-in teller at a bank. A little guy inside the network card—named Nick, naturally!—builds these pneumatic canisters (the frames) on the table, and then shoots them out on the wire to the hub (Figure 2.16).

Chapter 2: Building a Network with the OSI Model 15

Try This! What’s Your MAC Address?

You can readily determine your MAC address on a Windows computer from the command line. This works in all modern versions of Windows.

1. In Windows 2000/XP, click Start | Run. Enter the command CMD and press the ENTER key to get to a command prompt.

2. In Windows Vista, click Start, enter CMD in the Start Search text box, and press the ENTER key to get to a command prompt.

3. At the command prompt, type the command IPCONFIG /ALL and press the ENTER key.

• Figure 2.13 Data moving along a wire

• Figure 2.14 Oscilloscope of data

• Figure 2.15 Data as ones and zeroes

• Figure 2.16 Inside the NIC

A number of different frame types are used in different net- works. All NICs on the same net- work must use the same frame type or they will not be able to communicate with other NICs.

BaseTech

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

Creating Scatter Diagrams And Correlation Matrix Using Stata

1

BADM 735 – Comparative Economics – Assignment Five (C)

Creating Scatter Diagrams and Correlation Matrix Using Stata

A scatter diagram plots two variables taken from the same point in time for different countries

to show relationship between the two variables.

For better understanding of scatter plots watch the video contained in the link below

 

According to the text, economic outcomes measured by economic growth is affected by a number

of factors. Also, hundreds of empirical studies on economic growth across countries have

highlighted the correlation between economic growth and a variety of variables.

a) Using your data from Assignment 3 B: Construct a scatterplot, in stata, that shows the

relationship between:

 

 Economic growth and Gross capital formation (% of GDP) (A measure of Investment)

 Economic growth and General government final consumption expenditure (% of GDP)

 Economic growth and Trade (% of GDP)

 Economic growth and Inflation, consumer prices (annual %)

 Economic growth and Foreign direct investment, net inflows (% of GDP)

 Economic growth and Population, total

 Economic growth and Total natural resources rents (% of GDP)

**Economic growth is our dependent variable; all the other variables are independent**

The graphs below should serve as a guide.

According to the graph, there appears to be a

positive correlation between Economic

Growth and Investment. The Correlation

coefficient is about 0.154 which confirms a

weak positive correlation between the two

variables.

 

 

 

 

 

 

 

 

 

 

2

STATA COMMANDS FOR SCATTER PLOTS

STEP 1: USING THE COMMAND WINDOW INSTALL “asdoc” AS SHOWN BELOW

 

“asdoc” is an add-on to stata that allows you to produce nicely formatted tables tables in stata

 

STEP 2: USING THE YOUR DO-FILE YOU CAN CREATE SCATTER PLOTS AS

SHOWN BELOW

 

 Why twoway -Because a scatter diagram plots two variables or shows the relationship

between two variables.

 Ifit- Fit a line in the scatter plot

 Note that your dependent variable comes before the independent variable ( as you can see

economic growth comes before trade)

Please note also that you have to run the same command for all the other relationships; for

example to show the relationship between economic growth and inflation you run:

twoway (scatter Economic_Growth Inflation) (lfit Economic_Growth Inflation)

 

STEP 3: EDITING, FORMATTING AND SAVING YOUR GRAPH

 It is important you edit your graph to conform to the scatter plot shown above. The video

contained in the link below should help you edit and format your graph.

 

 

STEP 4: COPY YOUR GRAPHS INTO WORD

 

 

 

3

b) Create a correlation matrix table that shows pairwise correlation coefficients between the

following variables (without significance test): GDP growth (annual %), Gross capital

formation (% of GDP), General government final consumption expenditure (% of GDP),

Trade (% of GDP), Inflation, consumer prices (annual %), Foreign direct investment, net

inflows (% of GDP), Population, total, and Total natural resources rents (% of GDP)

For better understanding of correlations watch the video contained in the link below

 

STATA COMMANDS FOR CORRELATION MATRIX

USING THE YOUR DO-FILE YOU CAN GENERATE THE CORRELATION MATRIX

AS SHOWN BELOW

 

 

A sample shot of a correlation matrix

 Column (1) is Economic Growth

 Column (2) is Investment

 Column (3) is Government Expenditure

The 0.154 shows the strength of the relationship between Economic growth and Investment

 

 

 

 

 

 

 

 

 

4

c) Compare the correlation matrix with the scatter graphs. See the example below

According to the graph, there appears to be a

positive correlation between Economic

Growth and Investment. The Correlation

coefficient is about 0.154 which confirms a

weak positive correlation between the two

variables.

 

 

 

 

 

 

 

 

 

 

 

***Please do not hesitate to call or email if you need assistance***

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

P5_CS6262

Project 5 : Machine Learning for Security

Spring, 2021

Contents:

1 Goals 2

2 Section 1: Project quiz (5 points) 3-4

3 Section 2: Project setup 5

4 Section 3: Project tasks (95 points) 6-11

5 Section 4: Final deliverables and rubric 12-14

6 Section 5: FAQs 15-18

7 Section 6: Academic integrity 19

1

 

 

Goals of the Project

● The goal of this project is to introduce students to machine learning techniques and methodologies that help to differentiate between malicious and legitimate network traffic.

● In summary, students are introduced to: ○ how to build a machine-learning model based on normal network traffic. ○ how to conduct a blending attack producing artificial network traffic that

resembles the normal one, and bypasses the learned model.

Suggestion We recommend you to use the Linux VM provided. However, in the past, students faced no difficulty in setting up the project and working on either Windows or Macintosh OS.

Readings and Resources This project relies on the following readings:

● “Anomalous Payload-based Worm Detection and Signature Generation”, Ke Wang and Salvatore J.Stolfo, RAID2004

● “Polymorphic Blending Attacks”, Prahlad Fogla, Monirul Sharif, Roberto Perdisci, Oleg Kolesnikov, Wenke Lee, Usenix Security 2006

● “Sensitivity and specificity”

2

 

 

Section 1: Project Quiz (5 points)

We have created a small quiz to help you understand the topics covered in this project. Please read the papers (under Readings and Resources) before attempting the quiz and the subsequent tasks.

1. In 1-gram PAYL, the byte frequency is calculated by counting the number of occurrences of a

particular byte and dividing it by the length of the payload.

a. True

b. False

2. The threshold for Mahalanobis distance is used to determine if the current payload is normal

or malicious. Specifically, if the Mahalanobis distance of the current payload is LESS than the

threshold, the current payload is malicious and an alert is raised by PAYL.

a. True

b. False

3. Since polymorphic blending attacks try to evade network anomaly based intrusion detection

system (IDS) by making the attacks look like normal traffic, they can be viewed as a subclass of

mimicry attacks.

a. True

b. False

4. In polymorphic blending attacks, the attacker uses an artificial profile which can be defined as:

a. The attack payload’s profile which can bypass the IDS

b. The profile of the payload generated by the polymorphic decryptor

c. The profile estimated by observing normal traffic

d. None of the above

5. Polymorphic blending attacks use the following basic steps: (1) Blend the attack body within

an instance of normal traffic payload and create an artificial payload using polymorphic

encryption, (2) Let the IDS analyse this artificial payload and monitor the response received

from IDS (3) Based on the response received repeat step 1 with another instance of normal

traffic payload. Repeat until you find an artificial payload that can evade the IDS.

a. True

b. False

3

 

 

1.1: Deliverables

For each question, please enter your option in answers.txt as shown in the sample file below. You

will deliver answers.txt for this part.

You can find answers.txt under the project directory.

4

 

 

Section 2: Project Setup

You can either use the provided VM to complete the project OR you can set up your own environment locally.

2.1: VM Setup 1. Download the VM using one of the links provided in the project description on canvas. 2. All the required packages/dependencies are already installed in the VM. The project files are under: Desktop -> project 5

2.2: Local Setup 1. Download the project zip file from the link provided in the project description on canvas .

2. Please refer SETUP.txt in the PAYL directory to install the dependencies, using the same versions specified in the SETUP.txt.

TIP: Even if you are using the provided VM, please check SETUP.txt to understand how the project is set up and to get an overview on the various code components in the project. This might help in debugging any issues you might face later.

5

 

 

Section 3: Project Tasks (95 points)

3.1: Task A – (30 points)

3.1.1: Preliminary Reading Please refer to the reference readings to learn about how PAYL model works, in particular,

a) how to extract byte frequency from the data b) how to train the model c) the definitions of parameters, threshold and smoothing factor

3.1.2: Code and data provided The PAYL directory provides he PAYL code and data for model training.

3.1.3: PAYL Code Workflow Here is the workflow of the provided PAYL code:

● Operates in 2 modes: a) training mode: It reads pcap files provided in the ‘data’ directory, and tests

parameters and reports the True Positive rates. b) testing mode: It first builds a model using parameters and data specified in the

directory. Then it will test a specific packet and decide whether the test packet fits the model.

● Training mode ○ Read the normal traffic data and divide it into two parts, 75% of the data for

training and the rest 25% for testing (NOTE: You will NOT change these portions in the code).

○ Sort the payload strings by length and generate a model for each length. ○ Each model per length is based on [mean frequency of each ascii, standard deviation

of frequencies for each ascii].

To run PAYL in training mode

$ python3 wrapper.py

Testing mode

● Read the normal traffic data from the directory, and train a model using specific parameters. Then test the specific packet (fed from the command line) using the trained model.

● Compute the mahalanobis distance between each test payload and the model (of the same length)

● Label the payload: If the mahalanobis distance is below the specified threshold, label the payload as normal traffic. Otherwise, label the packet as attack traffic.

6

 

 

To run PAYL in testing mode

$ python3 wrapper.py [FILE.pcap]

where FILE.pcap is the data you will test.

3.1.4: Tasks – Conduct experiments to select parameters

● You are provided with artificial payloads (normal network traffic) to train a PAYL model. ● After reading the reference papers, it should make sense that you cannot train the PAYL

model on the entire traffic of different protocols. So first you need to select a protocol: a) HTTP or b) DNS by changing the hard-coded option in wrapper.py.

● The next step is to select a proper pair of parameters for the model. For the selection process, you will provide a range for both parameters (by modifying the threshold and smoothing factor in wrapper.py). Then run wrapper.py on training mode and make sure the normal traffic (artificial payloads stored in the default data folder) is fed while training.

● The code will output the statistics for the parameters in the range. As shown in the figure below, for each pair of parameters, you will observe a True Positive Rate. You need to report a pair of parameters (mSF and mTmd) output by the code that achieves True Positive rate of 96% or more. More than 99% true positive rate is possible and you may find multiple pairs of parameters that can achieve that.

The figure shows a sample output from the wrapper.py. You will find mSF and mTMD values which make mTP>96% for both HTTP and DNS protocols respectively. The parameters can be different for the two protocols.

3.1.5: Deliverables

Please report for each protocol that you used, the parameters that you found (output by

wrapper.py) in a file named parameters.txt. Please report a decimal with 2-digit accuracy for

each parameter.

7

 

 

NOTE: You are given a sample parameters.txt with dummy values in the PAYL directory. Please

update the relevant values with your own answer. Check section 4 for more details.

NOTE: The value for “Distance” in parameters.txt will be obtained in the next task (section 3.2).

TIP: You can set lower and upper bound values of both parameters in wrapper.py as the values you found in training mode to avoid multiple iterations during testing mode.

3.2: Task B – (5 points)

Download your unique attack payload [YOUR_GTUSERNAME.pcap] from Files in Canvas. (Path: Files -> Projects -> Project Five -> student pcaps) Replace YOUR_GTUSERNAME with your GT username.

For this part, your task is to examine the parameters you chose in Task A. Once the parameters are fixed, make sure the attack data does not fit the model, while the artificial ones (normal network traffic) fit. If such properties do not hold, you may want to redo Task A to modify the parameters to fulfill the requirements for both Task A and Task B. This procedure is essential for demonstrating the polymorphic blending attack in Task C.

Use PAYL in testing mode ● You will first test your unique attack payload for both HTTP and DNS protocols ( NOTE:

DO NOT forget to change Smoothing Factor and Threshold for Mahalanobis Distance when you change the protocol).

● Verify that your attack payload gets rejected for both protocols. By rejected, we mean that you will get the “It doesn’t fit the model” message on your test screen as presented in the following figure.

● Then verify the artificial payloads (normal traffic). We provide two artificial payloads; one for HTTP (http_artificial_profile.pcap) and one for DNS (dns_artificial_profile.pcap). Both

8

 

 

are in the PAYL folder. Test each artificial payload against your model. That is, use testing mode as explained above by giving each artificial payload as parameter. (NOTE: DO NOT forget to change parameters according to each protocol while testing relevant payload, e.g., DNS parameters to test dns_artificial_profile.pcap.) These should be accepted by the model. That is, you should get an output message that says “It fits the model” as presented in the following figure.

3.2.1: Deliverables Please report your calculated distance (mDISTANCE in above figures) in parameters.txt for each protocol with the values of the attack payload (YOUR_GTUSERNAME.pcap) after completing Task B.

NOTE: You are given a sample parameters.txt with dummy values under PAYL directory. Please

update the relevant values with your own answer. Check section 4 for more details.

3.3: Task C – (60 points)

Preliminary reading. Please refer to the “Polymorphic Blending Attacks” paper. In particular, section 4.2 that describes how to evade 1-gram and the model implementation. More specifically we are focusing on the case where m <= n and the substitution is ONE-TO-MANY.

We assume that the attacker has a specific payload (attack payload) that she would like to blend in with the normal traffic. Also, we assume that the attacker has access to one packet (artificial profile payload) that is normal and is accepted as normal by the PAYL model.

The attacker’s goal is to transform the byte frequency of the attack traffic so that it matches the byte frequency of the normal traffic, and thus bypass the PAYL model.

9

 

 

NOTE: Complete this task ONLY for the HTTP protocol.

Code provided: Please look at the Polymorphic_blend directory. All files (including attack payload) for this task should be in this directory. Hence, copy your unique attack payload also in this directory. Rename ATTACKBODY_PATH in task1.py with your unique attack payload name (YOUR_GTUSERNAME.pcap).

How to run the code

$ python3 task1.py

NOTE: You need to complete Task C before running task1.py.

Main function task1.py contains all the functions that are called to transform the byte frequency of the attack traffic.

Output ● The code should generate a new payload (filename: output) that can successfully bypass

the PAYL model that you have found above (using your selected parameters in Task A and B).

● The new payload (output) is shellcode.bin + encrypted attack body + XOR table + padding. Please refer to the paper for full descriptions and definitions of shellcode, attack body, XOR table and padding.

● The shellcode is provided.

Substitution table We provide the skeleton for the code needed to generate a substitution table, based on the byte frequency of attack payload and artificial profile payload. For the purpose of implementation, the substitution table can be e.g. a python dictionary table. We ask that you complete the code for the substitution function. The substitution is one-to-many. Skeleton code prints the substitution table to the console. You will deliver your substitution table in substitution_table.txt file as in the following format.

NOTE: This is just an example to show the format of the table. Please ignore the frequency values. NOTE: The substitution table should have the frequencies as observed in the normal payload. Please do NOT normalize these values in substitution_table.txt. You can normalize the values later during substitution in substitution.py.

10

 

 

Padding Similarly, we have provided a skeleton for the padding function and we are asking you to complete

the rest.

Main tasks

Please complete the code for the substitution.py and padding.py and then run task1.py to

generate the new payload (output).

3.3.1: Deliverables

● You will deliver substitution.py, padding.py, your new payload (output) and substitution_table.txt for this task.

● You’re expected to write comments for your code. Otherwise, you will lose 5 points.

Test your output Test your new payload (output) against the PAYL model and verify that it is accepted. FP should be 100% indicating that the payload got accepted as legit, even though it is malicious. You should run as follows and observe the following output, and get the output message that says, “It fits the model”.

TIP: Check the relevant FAQs in section 5.

IMPORTANT: Please check section 5.6 to understand how you can verify your code.

11

 

 

Section 4: Final deliverables and Rubric

Tasks Deliverable Files

Project Quiz answers.txt

A & B parameters.txt

C substitution.py

padding.py

substitution_table.txt

output

Total: 6 files

Total points: 100

4.1: Project Quiz – 5 points

4.2: Task A – 30 points Please report (for each protocol) the parameters that you found in a file named parameters.txt. Please report a decimal with 2 digit accuracy for each parameter.

4.3: Task B – 5 points Please report your calculated distance (mDISTANCE in above figures) in parameters.txt for each protocol with the values of the attack payload after completing Task B.

parameters.txt format:

|Protocol:HTTP| |Threshold:1111.00| |SmoothingFactor:0.01| |TruePositiveRate:50.00| |Distance:2000.00| |Protocol:DNS| |Threshold:2222.00| |SmoothingFactor:0.00| |TruePositiveRate:50.00| |Distance:2000.00|

NOTE: You are given a sample parameters.txt with dummy values under PAYL directory. Please

update each value with your own answer. Those values should only come from the PAYL script’s

output to the console. (not from the values modified inside the script).

12

 

 

Description of fields in parameters.txt

|Protocol:HTTP| |Threshold:1111.00| // Part A |SmoothingFactor 0.01| // Part A |TruePositiveRate:50.00| // Part A |Distance:20020.00| // Part B, mDISTANCE this is the mDISTANCE value that you get from your unique pcap file (python wrapper.py <yourunique.pcap>) |Protocol:DNS| |Threshold:2222.00| // Part A |SmoothingFactor:0.00| // Part A |TruePositiveRate:50.00| // Part A |Distance:22000.00| // Part B, mDISTANCE this is the mDISTANCE value that you get from your unique pcap file (python wrapper.py <yourunique.pcap>)

NOTE: “0.3” should be entered as “0.30”. “2” should be entered as “2.00”.

4.4: Task C – 60 points Code: 40 points. Please submit your code files substitution.py (20 points) and padding.py (10 points), and your substitution_table.txt (10 points).

Output: 20 points. Please submit your output of Task C generated as a new file after running task1.py.

4.5: !! Important Notes (Please check before submission) !!

● Every file name with wrong name and/or extension will be penalized with 5 points.

● Do NOT ZIP your deliverable files. You will lose 5 points for zipped files.

● Follow the format for substitution_table.txt above (section 3.3), for wrong format you will lose 5 points.

● Follow the format for parameters.txt above, for the wrong format you will lose 5 points.

● Do not forget to update your parameters.txt If you submit sample parameters.txt with dummy values, you will get 0/35 for Task A and B. We won’t accept resubmission after the due date.

● You should complete Task A, B and C with the same set of parameters. If your output doesn’t pass the model with parameters in your parameters.txt you will get 0/20 for output.

13

 

 

● For Task B, in parameters.txt you will report calculated distance after you provide your own attack payload. (i.e.YOUR_GTUSERNAME.pcap)

● For Task C, You are allowed to import and use “random” or “numpy”. Do NOT import any other libraries.

● If you don’t implement the correct algorithm for Task C, even if your output passes the model you won’t get full credit. We will not accept the implementation of ONE-ONE mapping. (Check section 5.2)

● Don’t forget to put comments for your code. Otherwise, you will lose 5 points.

14

 

 

Section 5: FAQs

5.1: Task C clarifications

● As we saw in part A+B, your unique attack payload does not fit the model. In Task C we want to make our pcap fit.

● We care about our attack payload being turned into what a normal payload would look like. ● We’re simply performing substitution and padding to match the character frequency and

packet size. ● We want to modify the various python functions to perform this substitution and padding

for us. ● After the functions have been crafted, copy the file it generates (output) over to your PAYL

directory and test it (python3 wrapper.py output). You want it to fit the model.

5.2: How to implement Substitution Table & Substitute? First Refer to the “Polymorphic Blending Attacks” paper. In particular, section 4.2 that describes how to evade 1-gram and the model implementation. More specifically we are focusing on the case where m <= n and the substitution is ONE-TO-MANY.

NOTE: We will not accept the implementation of ONE-ONE mapping.

Refer to the example provided in the write-up (section 5.5).

After reading the paper and example, it should be obvious how to implement a substitution table. If you still have any specific questions you can post your questions on piazza.

Substitution Given an attack byte, find the mapping in your Substitution Table. You will have multiple choices because of how we constructed the table. Pick one based on the ratio of the bytes frequency to the sum of all frequencies. You have to normalize the frequencies to sum up to 1.

NOTE: You are allowed to import and use “random or numpy” for this task. Do NOT import any other libraries.

5.3: How to implement Padding? Find the byte with the largest byte frequency difference, say ‘a’, and append ‘a’ to the raw_payload (padding.py). Padding function is called repeatedly when

len(raw_payload) < len(artificial_payload) (as in task1.py).

So each time you only need to pad one byte when the padding function is called.

15

 

 

5.4: XOR and result Clarification in Task C

Both are lists of characters, where ‘result’ keeps the replacement chars and ‘xor’ keeps the XOR of replacement and corresponding attack value.

From the sample in the write-up. Assume ‘t’ is replaced by ‘Z’ then your result will include ‘Z’ and xor table will include XOR(‘t’,’Z’)=’.’

NOTE: Be careful while XORing the chars NOTE: You substitution_table.txt should have the format we mentioned in the writeup. NOTE: You need to verify your Task C and see your original packet content. (check section 5.6)

5.5: Simple example for substitution Please refer to the ‘Polymorphic Blending Attack’: Substitution part

Example # normal traffic (x) and attack traffic (y):

x = abbcccdddd, y = rrsss

# distinct characters in normal traffic (n) and attack body (m): n = 4, m = 2

# frequency of characters in normal traffic f(x) and attack body g(y): f(x) = [(‘d’, 0.4), (‘c’, 0.3), (‘b’, 0.2), (‘a’, 0.1)] , g(y) = [(‘s’, 0.6), (‘r’, 0.4)]

For the first m characters in (x), create a one-to-one mapping in both sets: Let : t^f(y_j) = f(x_i) Then:

S(s) = [(‘d’, 0.4)] S(r) = [(‘c’, 0.3)] t^f(s) = 0.4 t^f(r) = 0.3

For the (m+1)th char, first find the attack character with max ratio of g(y_j)/t^f(y_j): g(s)/(t^f(s)) = 0.6/0.4 = 1.5 g(r)/(t^f(r)) = 0.4/0.3 = 1.33

So, the next attack character is ‘s’. Then, your substitution table at this step is: S(s)= [(‘d’, 0.4), (‘b’,0.2)] S(r)= [(‘c’, 0.3)]

16

 

 

and update: t^f(s)=0.4+0.2=0.6

Repeat to find the next attack character and so on. g(s) / (t^f(s)) = 0.6/0.6 = 1 g(r) / (t^f(r)) = 0.4/0.3 = 1.33

Now, the next attack character is ‘r’. Then, your substitution table at this step is S(s)= [(‘d’, 0.4), (‘b’,0.2)] S(r)= [(‘c’, 0.3), (‘a’,0.1)]

and update: t^f(r) = 0.3 + 0.1 = 0.4

After you finish the substitution, you are done with t^f(y_j)’s and you will make a substitution with the frequency weight of each character in the table.

s is substituted with: d with a probability of 0.4/(0.4+0.2) b with a probability of 0.2/(0.4+0.2)

r is substituted with: c with a probability of 0.3/(0.3+0.1) a with a probability of 0.1/(0.3+0.1)

It is up to you how you implement a weighted random assignment, but it is a trivial step.

5.6 How to verify Task C? If you only have 64-bit compiler, you need to run following:

$ sudo apt-get install lib32gcc-4.9-dev

$ sudo apt-get install gcc-multilib

NOTE: You can also verify Task C using lib32gcc-9-dev.

If you’re on Ubuntu Xenial, the one listed in the instructions should work: lib32gcc-4.9-dev If you’re on Debian Buster or Ubuntu Bionic, try: lib32gcc-8-dev If you’re on Ubuntu Cosmic or Disco, try: lib32gcc-9-dev

The 32 bit compiler is already installed in the VM.

Next, you need to generate your payload. So, somewhere near the end of task1.py add the following to create your payload.bin:

17

 

 

payload_file:

payload_file.write(bytearray(“”.join(adjusted_attack_body + xor_table), “utf8”))

Now, run task1.py to generate payload.bin and once it’s generated, run the makefile with make and then run a.out:

$ make

$ ./a.out

If all is well, you should see your original packet contents. If not and you get a bunch of funny letters it didn’t work.

NOTE: It was only tested on Linux, you might need to make a few modifications according to your system configuration.

18

 

 

Section 6: Academic Integrity

● All submitted code must be written by you. ● Borrowing or adapting code from other students and websites like Stack Overflow, code

repositories, and other sources is strictly forbidden. ● You may not discuss specific solutions. Keep your discussions at a high level. ● Sharing code is strictly forbidden. ● Note that we will report you to the Office of Student Integrity if there is a violation. ● As a reminder, please review the Georgia Tech Honor Code and the course policies

outlined in the syllabus.

Good luck and have fun!!

19

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!

Phython

Case Study/.DS_Store

Case Study/breezypythongui.py

“”” File: breezypythongui.py Version: 1.1 Copyright 2012, 2013 by Ken Lambert Resources for easy Python GUIs. LICENSE: This is open-source software released under the terms of the GPL (http://www.gnu.org/licenses/gpl.html). Its capabilities mirror those of BreezyGUI and BreezySwing, open-source frameworks for writing GUIs in Java, written by Ken Lambert and Martin Osborne. PLATFORMS: The package is a wrapper around Tkinter (Python 3.X) and should run on any platform where Tkinter is available. INSTALLATION: Put this file where Python can see it. RELEASE NOTES: Version 1.1 now includes the class EasyPanel, for organizing subpanes in windows and dialogs (updated 12-19-2012). Version 1.1 now also runs on either Python 3.x.x or Python 2.x.x (updated 2-4-2013). “”” import sys versionNumber = sys.version_info.major if versionNumber == 3: import tkinter import tkinter.simpledialog Tkinter = tkinter tkSimpleDialog = tkinter.simpledialog else: import Tkinter import tkSimpleDialog N = Tkinter.N S = Tkinter.S E = Tkinter.E W = Tkinter.W CENTER = Tkinter.CENTER END = Tkinter.END NORMAL = Tkinter.NORMAL DISABLED = Tkinter.DISABLED NONE = Tkinter.NONE WORD = Tkinter.WORD VERTICAL = Tkinter.VERTICAL HORIZONTAL = Tkinter.HORIZONTAL RAISED = Tkinter.RAISED SINGLE = Tkinter.SINGLE ACTIVE = Tkinter.ACTIVE class EasyFrame(Tkinter.Frame): “””Represents an application window.””” def __init__(self, title = “”, width = None, height = None, background = “white”, resizable = True): “””Will shrink wrap the window around the widgets if width and height are not provided.””” Tkinter.Frame.__init__(self, borderwidth = 4, relief = “sunken”) if width and height: self.setSize(width, height) self.master.title(title) self.grid() # Expand the frame within the window self.master.rowconfigure(0, weight = 1) self.master.columnconfigure(0, weight = 1) self.grid(sticky = N+S+E+W) # Set the background color and resizability self.setBackground(background) self.setResizable(resizable) def setBackground(self, color): “””Resets the window’s background color to color.””” self[“background”] = color def setResizable(self, state): “””Resets the window’s resizable property to True or False.””” self.master.resizable(state, state) def setSize(self, width, height): “””Resets the window’s width and height in pixels.””” self.master.geometry(str(width)+ “x” + str(height)) def setTitle(self, title): “””Resets the window’s title to title.””” self.master.title(title) # Methods to add widgets to the window. The row and column in # the grid are required arguments. def addLabel(self, text, row, column, columnspan = 1, rowspan = 1, sticky = N+W, font = None, background = “white”, foreground = “black”): “””Creates and inserts a label at the row and column, and returns the label.””” label = Tkinter.Label(self, text = text, font = font, background = background, foreground = foreground) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) label.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return label def addButton(self, text, row, column, columnspan = 1, rowspan = 1, command = lambda: None, state = NORMAL): “””Creates and inserts a button at the row and column, and returns the button.””” button = Tkinter.Button(self, text = text, command = command, state = state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) button.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5) return button def addFloatField(self, value, row, column, columnspan = 1, rowspan = 1, width = 20, precision = None, sticky = N+E, state = NORMAL): “””Creates and inserts a float field at the row and column, and returns the float field.””” field = FloatField(self, value, width, precision, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addIntegerField(self, value, row, column, columnspan = 1, rowspan = 1, width = 10, sticky = N+E, state = NORMAL): “””Creates and inserts an integer field at the row and column, and returns the integer field.””” field = IntegerField(self, value, width, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextField(self, text, row, column, columnspan = 1, rowspan = 1, width = 20, sticky = N+E, state = NORMAL): “””Creates and inserts a text field at the row and column, and returns the text field.””” field = TextField(self, text, width, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextArea(self, text, row, column, rowspan = 1, columnspan = 1, width = 80, height = 5, wrap = NONE): “””Creates and inserts a multiline text area at the row and column, and returns the text area. Vertical and horizontal scrollbars are provided.””” frame = Tkinter.Frame(self) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) self.columnconfigure(column, weight = 1) self.rowconfigure(row, weight = 1) xScroll = Tkinter.Scrollbar(frame, orient = HORIZONTAL) xScroll.grid(row = 1, column = 0, sticky = E+W) yScroll = Tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) area = TextArea(frame, text, width, height, xScroll.set, yScroll.set, wrap) area.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) xScroll[“command”] = area.xview yScroll[“command”] = area.yview return area def addListbox(self, row, column, rowspan = 1, columnspan = 1, width = 10, height = 5, listItemSelected = lambda index: index): “””Creates and inserts a scrolling list box at the row and column, with a width and height in lines and columns of text, and a default item selection method, and returns the list box.””” frame = Tkinter.Frame(self) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) self.columnconfigure(column, weight = 1) self.rowconfigure(row, weight = 1) yScroll = Tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) listBox = EasyListbox(frame, width, height, yScroll.set, listItemSelected) listBox.grid(row = 0, column = 0, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) yScroll[“command”] = listBox.yview return listBox def addCanvas(self, canvas = None, row = 0, column = 0, rowspan = 1, columnspan = 1, width = 200, height = 100, background = “white”): “””Creates and inserts a canvas at the row and column, and returns the canvas.””” if not canvas: canvas = EasyCanvas(self, width = width, height = height, background = background) canvas.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = W+E+N+S) self.columnconfigure(column, weight = 10) self.rowconfigure(row, weight = 10) return canvas def addScale(self, row, column, rowspan = 1, columnspan = 1, command = lambda value: value, from_ = 0, to = 0, label = “”, length = 100, orient = HORIZONTAL, resolution = 1, tickinterval = 0): “””Creates and inserts a scale at the row and column, and returns the scale.””” scale = Tkinter.Scale(self, command = command, from_ = from_, to = to, label = label, length = length, orient = orient, resolution = resolution, tickinterval = tickinterval, relief = “sunken”, borderwidth = 4) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) scale.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) return scale def addMenuBar(self, row, column, rowspan = 1, columnspan = 1, orient = “horizontal”): “””Creates and inserts a menu bar at the row and column, and returns the menu bar.””” if not orient in (“horizontal”, “vertical”): raise ValueError(“orient must be horizontal or vertical”) menuBar = EasyMenuBar(self, orient) menuBar.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+W) return menuBar def addCheckbutton(self, text, row, column, rowspan = 1, columnspan = 1, sticky = N+S+E+W, command = lambda : 0): “””Creates and inserts check button at the row and column, and returns the check button.””” cb = EasyCheckbutton(self, text, command) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) cb.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return cb def addRadiobuttonGroup(self, row, column, rowspan = 1, columnspan = 1, orient = VERTICAL): “””Creates and returns a radio button group.””” return EasyRadiobuttonGroup(self, row, column, rowspan, columnspan, orient) # Added 12-18-2012 def addPanel(self, row, column, rowspan = 1, columnspan = 1, background = “white”): “””Creates and returns a panel.””” return EasyPanel(self, row, column, rowspan, columnspan, background) # Method to pop up a message box from this window. def messageBox(self, title = “”, message = “”, width = 25, height = 5): “””Creates and pops up a message box, with the given title, message, and width and height in rows and columns of text.””” dlg = MessageBox(self, title, message, width, height) return dlg.modified() # Method to pop up a prompter box from this window. def prompterBox(self, title = “”, promptString = “”, inputText = “”, fieldWidth = 20): “””Creates and pops up a prompter box, with the given title, prompt, input text, and field width in columns of text. Returns the text entered at the prompt.””” dlg = PrompterBox(self, title, promptString, inputText, fieldWidth) return dlg.getText() # Classes for easy widgets class AbstractField(Tkinter.Entry): “””Represents common features of float fields, integer fields, and text fields.””” def __init__(self, parent, value, width, state): self.var = Tkinter.StringVar() self.setValue(value) Tkinter.Entry.__init__(self, parent, textvariable = self.var, width = width, state = state) def setValue(self, value): self.var.set(value) def getValue(self): return self.var.get() class FloatField(AbstractField): “””Represents a single line box for I/O of floats.””” def __init__(self, parent, value, width, precision, state): self.setPrecision(precision) AbstractField.__init__(self, parent, value, width, state) def getNumber(self): “””Returns the float contained in the field. Raises: ValueError if number format is bad.””” return float(self.getValue()) def setNumber(self, number): “””Replaces the float contained in the field.””” self.setValue(self._precision % number) def setPrecision(self, precision): “””Resets the precision for the display of a float.””” if precision and precision >= 0: self._precision = “%0.” + str(precision) + “f” else: self._precision = “%f” class IntegerField(AbstractField): “””Represents a single line box for I/O of integers.””” def __init__(self, parent, value, width, state): AbstractField.__init__(self, parent, value, width, state) def getNumber(self): “””Returns the integer contained in the field. Raises: ValueError if number format is bad.””” return int(self.getValue()) def setNumber(self, number): “””Replaces the integer contained in the field.””” self.setValue(str(number)) class TextField(AbstractField): “””Represents a single line box for I/O of strings.””” def __init__(self, parent, value, width, state): AbstractField.__init__(self, parent, value, width, state) def getText(self): “””Returns the string contained in the field.””” return self.getValue() def setText(self, text): “””Replaces the string contained in the field.””” self.setValue(text) class TextArea(Tkinter.Text): “””Represents a box for I/O of multiline text.””” def __init__(self, parent, text, width, height, xscrollcommand, yscrollcommand, wrap): Tkinter.Text.__init__(self, parent, width = width, height = height, wrap = wrap, xscrollcommand = xscrollcommand, yscrollcommand = yscrollcommand) self.setText(text) def getText(self): “””Returns the string contained in the text area.””” return self.get(“1.0”, END) def setText(self, text): “””Replaces the string contained in the text area.””” self.delete(“1.0”, END) self.insert(“1.0”, text) def appendText(self, text): “””Inserts the text after the string contained in the text area.””” self.insert(END, text) class EasyListbox(Tkinter.Listbox): “””Represents a list box.””” def __init__(self, parent, width, height, yscrollcommand, listItemSelected): self._listItemSelected = listItemSelected Tkinter.Listbox.__init__(self, parent, width = width, height = height, yscrollcommand = yscrollcommand, selectmode = SINGLE) self.bind(“<<ListboxSelect>>”, self.triggerListItemSelected) def triggerListItemSelected(self, event): “””Strategy method to respond to an item selection in the list box. Runs the client’s listItemSelected method with the selected index if there is one.””” if self.size() == 0: return widget = event.widget index = widget.curselection()[0] self._listItemSelected(index) def getSelectedIndex(self): “””Returns the index of the selected item or -1 if no item is selected.””” tup = self.curselection() if len(tup) == 0: return -1 else: return int(tup[0]) def getSelectedItem(self): “””Returns the selected item or the empty string if no item is selected.””” index = self.getSelectedIndex() if index == -1: return “” else: return self.get(index) def setSelectedIndex(self, index): “””Selects the item at the index if it’s in the range.””” if index < 0 or index >= self.size(): return self.selection_set(index, index) def clear(self): “””Deletes all items from the list box.””” while self.size() > 0: self.delete(0) def getIndex(self, item): “””Returns the index of item if it’s in the list box, or -1 otherwise.””” tup = self.get(0, self.size() – 1) if item in tup: return tup.index(item) else: return -1 class EasyRadiobuttonGroup(Tkinter.Frame): “””Represents a group of radio buttons, only one of which is selected at any given time.””” def __init__(self, parent, row, column, rowspan, columnspan, orient): Tkinter.Frame.__init__(self, parent) self.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+S+E+W) self._commonVar = Tkinter.StringVar(“”) self._buttons = dict() self._orient = orient self._buttonRow = self._buttonColumn = 0 def addRadiobutton(self, text, command = lambda : 0): “””Creates a button with the given text and command, adds it to the group, and returns the button.””” if text in self._buttons: raise ValueError(“Button with this label already in the group”) button = Tkinter.Radiobutton(self, text = text, value = text, command = command, variable = self._commonVar) self._buttons[text] = button button.grid(row = self._buttonRow, column = self._buttonColumn, sticky = N+W) if self._orient == VERTICAL: self.rowconfigure(self._buttonRow, weight = 1) self._buttonRow += 1 else: self.columnconfigure(self._buttonColumn, weight = 1) self._buttonColumn += 1 return button def getSelectedButton(self): if not self._commonVar.get() in self._buttons: raise ValueError(“No button has been selected yet.”) return self._buttons[self._commonVar.get()] def setSelectedButton(self, button): self._commonVar.set(button[“value”]) class EasyCheckbutton(Tkinter.Checkbutton): “””Represents a check button.””” def __init__(self, parent, text, command): self._variable = Tkinter.IntVar() Tkinter.Checkbutton.__init__(self, parent, text = text, variable = self._variable, command = command) def isChecked(self): “””Returns True if the button is checked or False otherwise.””” return self._variable.get() != 0 class EasyMenuBar(Tkinter.Frame): “””Represents a menu bar.””” def __init__(self, parent, orient): self._orient = orient self._row = self._column = 0 Tkinter.Frame.__init__(self, parent, relief = RAISED, borderwidth = 1) def addMenu(self, text, state = NORMAL): “””Creates and inserts a menu into the menubar, and returns the menu.””” menu = EasyMenubutton(self, text, state = state) menu.grid(row = self._row, column = self._column) if self._orient == “horizontal”: self._column += 1 else: self._row += 1 return menu class EasyMenubutton(Tkinter.Menubutton): “””Represents a menu button.””” def __init__(self, menuBar, text, state): Tkinter.Menubutton.__init__(self, menuBar, text = text, state = state) self.menu = Tkinter.Menu(self) self[“menu”] = self.menu self._currentIndex = -1 def addMenuItem(self, text, command, state = NORMAL): “””Inserts a menu option in the given menu.””” self.menu.add_command(label = text, command = command, state = state) self._currentIndex += 1 return EasyMenuItem(self, self._currentIndex) class EasyMenuItem(object): “””Represents an option in a drop-down menu.””” def __init__(self, menu, index): self._menu = menu self._index = index def setState(self, state): “””Sets the state of the item to state.””” self._menu.menu.entryconfigure(self._index, state = state) class EasyCanvas(Tkinter.Canvas): “””Represents a rectangular area for interactive drawing of shapes. Supports simple commands for drawing lines, rectangles, and ovals, as well as methods for responding to mouse events in the canvas.””” def __init__(self, parent, width = None, height = None, background = “white”): Tkinter.Canvas.__init__(self, parent, width = width, height = height, background = background) self.bind(“<Double-Button-1>”, self.mouseDoubleClicked) self.bind(“<ButtonPress-1>”, self.mousePressed) self.bind(“<ButtonRelease-1>”, self.mouseReleased) self.bind(“<B1-Motion>”, self.mouseDragged) # Mouse event handling methods. One or more of these methods can # be overridden in the subclass to implement the required actions. # The event argument can be used to extract the current mouse # cursor coordinates (event.x and event.y). def mouseDoubleClicked(self, event): “””Triggered when the mouse is double-clicked in the area of this canvas.””” return def mousePressed(self, event): “””Triggered when the mouse is pressed in the area of this canvas.””” return def mouseReleased(self, event): “””Triggered when the mouse is released in the area of this canvas.””” return def mouseDragged(self, event): “””Triggered when the mouse is dragged in the area of this canvas.””” return def getWidth(self): “””Returns the width of the canvas.””” return self[“width”] def getHeight(self): “””Returns the height of the canvas.””” return self[“height”] def drawLine(self, x0, y0, x1, y1, fill = “black”, width = 1): item = self.create_line(x0, y0, x1, y1) self.itemconfig(item, fill = fill, width = width) return item def drawRectangle(self, x0, y0, x1, y1, outline = “black”, fill = None): “””Draws a rectangle with the given corner points, outline color, and fill color.””” item = self.create_rectangle(x0, y0, x1, y1) self.itemconfig(item, outline = outline, fill = fill) return item def drawOval(self, x0, y0, x1, y1, outline = “black”, fill = None): “””Draws an ovel within the given corner points, with the given outline color and fill color.””” item = self.create_oval(x0, y0, x1, y1) self.itemconfig(item, outline = outline, fill = fill) return item def drawText(self, text, x, y, fill = “black”): “””Draws the given text (a string) at the given coordinates with the given fill color. The string is centered vertically and horizontally at the given coordinates.””” item = self.create_text(x, y) self.itemconfig(item, text = text, fill = fill) return item def drawImage(self, image, x, y, anchor = CENTER): “””Draws the given image (a PhotoImage) at the given coordinates. The image is centered at the given coordinates by default.””” item = self.create_image(x, y, image = image, anchor = anchor) self.itemconfig(item, image = image, anchor = anchor) return item def deleteItem(self, item): “””Removes and erases the shape with the given item number from the canvas.””” self.delete(item) # Support classes for dialogs. class MessageBox(tkSimpleDialog.Dialog): “””Represents a message dialog with a scrollable text area.””” @classmethod def message(cls, title = “”, message = “”, width = 25, height = 5): MessageBox(Tkinter.Frame(), title, message, width, height) def __init__(self, parent, title, message, width, height): “””Set up the window and widgets.””” self._message = message self._width = width self._height = height self._modified = False tkSimpleDialog.Dialog.__init__(self, parent, title) def body(self, master): self.resizable(0, 0) yScroll = Tkinter.Scrollbar(master, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) output = Tkinter.Text(master, width = self._width, height = self._height, padx = 5, pady = 5, wrap = WORD, yscrollcommand = yScroll.set) output.grid(row = 0, column = 0, sticky = N+W+S+E) output.insert(“1.0”, self._message) output[“state”] = DISABLED yScroll[“command”] = output.yview return output def buttonbox(self): ”’add standard button box. override if you do not want the standard buttons”’ box = Tkinter.Frame(self) w = Tkinter.Button(box, text=”OK”, width = 10, command = self.ok, default = ACTIVE) w.pack() self.bind(“<Return>”, self.ok) box.pack() def apply(self): “””Quits the dialog.””” self._modified = True def modified(self): return self._modified class PrompterBox(tkSimpleDialog.Dialog): “””Represents an input dialog with a text field.””” @classmethod def prompt(cls, title = “”, promptString = “”, inputText = “”, fieldWidth = 20): “””Creates and pops up an input dialog.””” dlg = PrompterBox(Tkinter.Frame(), title, promptString, inputText, fieldWidth) return dlg.getText() def __init__(self, parent, title, promptString, inputText, fieldWidth): “””Set up the window and widgets.””” self._prompt = promptString self._text = inputText self._width = fieldWidth self._modified = False tkSimpleDialog.Dialog.__init__(self, parent, title) def body(self, master): self.resizable(0, 0) label = Tkinter.Label(master, text = self._prompt) label.grid(row = 0, column = 0, padx = 5, sticky = N+W+S+E) self._field = TextField(master, self._text, self._width, NORMAL) self._field.grid(row = 1, column = 0, padx = 5, sticky = N+W+S+E) return self._field def buttonbox(self): ”’add standard button box. override if you do not want the standard buttons”’ box = Tkinter.Frame(self) w = Tkinter.Button(box, text=”OK”, width = 10, command = self.ok, default = ACTIVE) w.pack() self.bind(“<Return>”, self.ok) box.pack() def apply(self): “””Quits the dialog.””” self._modified = True def modified(self): return self._modified def getText(self): “””Returns the text currently in the text field.””” return self._field.getText() class EasyDialog(tkSimpleDialog.Dialog): “””Represents a general-purpose dialog. Subclasses should include body and apply methods.””” def __init__(self, parent, title = “”): “””Set up the window and widgets.””” self._modified = False tkSimpleDialog.Dialog.__init__(self, parent, title) def modified(self): “””Returns the modified status of the dialog.””” return self._modified def setModified(self): self._modified = True def addLabel(self, master, text, row, column, columnspan = 1, rowspan = 1, sticky = N+W, font = None): “””Creates and inserts a label at the row and column, and returns the label.””” label = Tkinter.Label(master, text = text, font = font) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) label.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return label def addButton(self, master, text, row, column, columnspan = 1, rowspan = 1, command = lambda: None, state = NORMAL): “””Creates and inserts a button at the row and column, and returns the button.””” button = Tkinter.Button(master, text = text, command = command, state = state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) button.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5) return button def addFloatField(self, master, value, row, column, columnspan = 1, rowspan = 1, width = 20, precision = None, sticky = N+E, state = NORMAL): “””Creates and inserts a float field at the row and column, and returns the float field.””” field = FloatField(master, value, width, precision, state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addIntegerField(self, master, value, row, column, columnspan = 1, rowspan = 1, width = 10, sticky = N+E, state = NORMAL): “””Creates and inserts an integer field at the row and column, and returns the integer field.””” field = IntegerField(master, value, width, state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextField(self, master, text, row, column, columnspan = 1, rowspan = 1, width = 20, sticky = N+E, state = NORMAL): “””Creates and inserts a text field at the row and column, and returns the text field.””” field = TextField(master, text, width, state) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addCheckbutton(self, master, text, row, column, rowspan = 1, columnspan = 1, sticky = N+S+E+W, command = lambda : 0): “””Creates and inserts check button at the row and column, and returns the check button.””” cb = EasyCheckbutton(master, text, command) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) cb.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return cb def addRadiobuttonGroup(self, master, row, column, rowspan = 1, columnspan = 1, orient = VERTICAL): “””Creates and returns a radio button group.””” return EasyRadiobuttonGroup(master, row, column, rowspan, columnspan, orient) def addScale(self, master, row, column, rowspan = 1, columnspan = 1, command = lambda value: value, from_ = 0, to = 0, label = “”, length = 100, orient = HORIZONTAL, resolution = 1, tickinterval = 0): “””Creates and inserts a scale at the row and column, and returns the scale.””” scale = Tkinter.Scale(master, command = command, from_ = from_, to = to, label = label, length = length, orient = orient, resolution = resolution, tickinterval = tickinterval, relief = “sunken”, borderwidth = 4) master.rowconfigure(row, weight = 1) master.columnconfigure(column, weight = 1) scale.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) return scale def addTextArea(self, master, text, row, column, rowspan = 1, columnspan = 1, width = 80, height = 5, wrap = NONE): “””Creates and inserts a multiline text area at the row and column, and returns the text area. Vertical and horizontal scrollbars are provided.””” frame = Tkinter.Frame(master) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) master.columnconfigure(column, weight = 1) master.rowconfigure(row, weight = 1) xScroll = Tkinter.Scrollbar(frame, orient = HORIZONTAL) xScroll.grid(row = 1, column = 0, sticky = E+W) yScroll = Tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) area = TextArea(frame, text, width, height, xScroll.set, yScroll.set, wrap) area.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) xScroll[“command”] = area.xview yScroll[“command”] = area.yview return area def addListbox(self, master, row, column, rowspan = 1, columnspan = 1, width = 10, height = 5, listItemSelected = lambda index: index): “””Creates and inserts a scrolling list box at the row and column, with a width and height in lines and columns of text, and a default item selection method, and returns the list box.””” frame = Tkinter.Frame(master) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) master.columnconfigure(column, weight = 1) master.rowconfigure(row, weight = 1) yScroll = Tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) listBox = EasyListbox(frame, width, height, yScroll.set, listItemSelected) listBox.grid(row = 0, column = 0, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) yScroll[“command”] = listBox.yview return listBox def addCanvas(self, master, canvas = None, row = 0, column = 0, rowspan = 1, columnspan = 1, width = 200, height = 100, background = “white”): “””Creates and inserts a canvas at the row and column, and returns the canvas.””” if not canvas: canvas = EasyCanvas(master, width = width, height = height, background = background) canvas.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = W+E+N+S) master.columnconfigure(column, weight = 10) master.rowconfigure(row, weight = 10) return canvas def addMenuBar(self, master, row, column, rowspan = 1, columnspan = 1, orient = “horizontal”): “””Creates and inserts a menu bar at the row and column, and returns the menu bar.””” if not orient in (“horizontal”, “vertical”): raise ValueError(“orient must be horizontal or vertical”) menuBar = EasyMenuBar(master, orient) menuBar.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+W) return menuBar def messageBox(self, title = “”, message = “”, width = 25, height = 5): “””Creates and pops up a message box, with the given title, message, and width and height in rows and columns of text.””” dlg = MessageBox(self, title, message, width, height) return dlg.modified() # Added 12-18-2012 def addPanel(self, master, row, column, rowspan = 1, columnspan = 1, background = “white”): “””Creates and returns a panel.””” return EasyPanel(master, row, column, rowspan, columnspan, background) # Added 12-18-2012 class EasyPanel(Tkinter.Frame): “””Organizes a group of widgets in a panel (nested frame).””” def __init__(self, parent, row, column, rowspan, columnspan, background): Tkinter.Frame.__init__(self, parent) parent.rowconfigure(row, weight = 1) parent.columnconfigure(column, weight = 1) self.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+S+E+W) self.setBackground(background) def setBackground(self, color): “””Resets the panel’s background color to color.””” self[“background”] = color def addButton(self, text, row, column, columnspan = 1, rowspan = 1, command = lambda: None, state = NORMAL): “””Creates and inserts a button at the row and column, and returns the button.””” button = Tkinter.Button(self, text = text, command = command, state = state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) button.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5) return button def addLabel(self, text, row, column, columnspan = 1, rowspan = 1, sticky = N+W, font = None, background = “white”, foreground = “black”): “””Creates and inserts a label at the row and column, and returns the label.””” label = Tkinter.Label(self, text = text, font = font, background = background, foreground = foreground) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) label.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return label def addFloatField(self, value, row, column, columnspan = 1, rowspan = 1, width = 20, precision = None, sticky = N+E, state = NORMAL): “””Creates and inserts a float field at the row and column, and returns the float field.””” field = FloatField(self, value, width, precision, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addIntegerField(self, value, row, column, columnspan = 1, rowspan = 1, width = 10, sticky = N+E, state = NORMAL): “””Creates and inserts an integer field at the row and column, and returns the integer field.””” field = IntegerField(self, value, width, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextField(self, text, row, column, columnspan = 1, rowspan = 1, width = 20, sticky = N+E, state = NORMAL): “””Creates and inserts a text field at the row and column, and returns the text field.””” field = TextField(self, text, width, state) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) field.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return field def addTextArea(self, text, row, column, rowspan = 1, columnspan = 1, width = 80, height = 5, wrap = NONE): “””Creates and inserts a multiline text area at the row and column, and returns the text area. Vertical and horizontal scrollbars are provided.””” frame = Tkinter.Frame(self) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) self.columnconfigure(column, weight = 1) self.rowconfigure(row, weight = 1) xScroll = Tkinter.Scrollbar(frame, orient = HORIZONTAL) xScroll.grid(row = 1, column = 0, sticky = E+W) yScroll = Tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) area = TextArea(frame, text, width, height, xScroll.set, yScroll.set, wrap) area.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) xScroll[“command”] = area.xview yScroll[“command”] = area.yview return area def addListbox(self, row, column, rowspan = 1, columnspan = 1, width = 10, height = 5, listItemSelected = lambda index: index): “””Creates and inserts a scrolling list box at the row and column, with a width and height in lines and columns of text, and a default item selection method, and returns the list box.””” frame = Tkinter.Frame(self) frame.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) self.columnconfigure(column, weight = 1) self.rowconfigure(row, weight = 1) yScroll = Tkinter.Scrollbar(frame, orient = VERTICAL) yScroll.grid(row = 0, column = 1, sticky = N+S) listBox = EasyListbox(frame, width, height, yScroll.set, listItemSelected) listBox.grid(row = 0, column = 0, sticky = N+S+E+W) frame.columnconfigure(0, weight = 1) frame.rowconfigure(0, weight = 1) yScroll[“command”] = listBox.yview return listBox def addCanvas(self, canvas = None, row = 0, column = 0, rowspan = 1, columnspan = 1, width = 200, height = 100, background = “white”): “””Creates and inserts a canvas at the row and column, and returns the canvas.””” if not canvas: canvas = EasyCanvas(self, width = width, height = height, background = background) canvas.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = W+E+N+S) self.columnconfigure(column, weight = 10) self.rowconfigure(row, weight = 10) return canvas def addScale(self, row, column, rowspan = 1, columnspan = 1, command = lambda value: value, from_ = 0, to = 0, label = “”, length = 100, orient = HORIZONTAL, resolution = 1, tickinterval = 0): “””Creates and inserts a scale at the row and column, and returns the scale.””” scale = Tkinter.Scale(self, command = command, from_ = from_, to = to, label = label, length = length, orient = orient, resolution = resolution, tickinterval = tickinterval, relief = “sunken”, borderwidth = 4) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) scale.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, sticky = N+S+E+W) return scale def addMenuBar(self, row, column, rowspan = 1, columnspan = 1, orient = “horizontal”): “””Creates and inserts a menu bar at the row and column, and returns the menu bar.””” if not orient in (“horizontal”, “vertical”): raise ValueError(“orient must be horizontal or vertical”) menuBar = EasyMenuBar(self, orient) menuBar.grid(row = row, column = column, rowspan = rowspan, columnspan = columnspan, sticky = N+W) return menuBar def addCheckbutton(self, text, row, column, rowspan = 1, columnspan = 1, sticky = N+S+E+W, command = lambda : 0): “””Creates and inserts check button at the row and column, and returns the check button.””” cb = EasyCheckbutton(self, text, command) self.rowconfigure(row, weight = 1) self.columnconfigure(column, weight = 1) cb.grid(row = row, column = column, columnspan = columnspan, rowspan = rowspan, padx = 5, pady = 5, sticky = sticky) return cb def addRadiobuttonGroup(self, row, column, rowspan = 1, columnspan = 1, orient = VERTICAL): “””Creates and returns a radio button group.””” return EasyRadiobuttonGroup(self, row, column, rowspan, columnspan, orient) def addPanel(self, row, column, rowspan = 1, columnspan = 1, background = “white”): “””Creates and returns a panel.””” return EasyPanel(self, row, column, rowspan, columnspan, background)

Case Study/doctor.py

import random class Doctor(): QUALIFIERS = [‘Why do you say that ‘, ‘You seem to think that ‘, ‘Did I just hear you say that ‘, ‘Why do you believe that ‘ ] REPLACEMENTS = {‘I’: ‘you’, ‘me’: ‘you’, ‘my’: ‘your’, ‘we’: ‘you’, ‘us’: ‘you’, ‘am’: ‘are’, ‘you’: ‘I’, ‘You’: ‘I’} HEDGES = [‘Go on.’, ‘I would like to hear more about that.’, ‘And what do you think about this?’, ‘Please continue.’] def __init__(self): self.history = [] def greeting(self): return ‘Good morning, how can I help you today?’ def farewell(self): return ‘Have a nice day!’ def reply(self, sentence): choice = random.randint (1, 10) if choice == 1: if len(self.history) > 3: answer = ‘Earlier you said that ‘ + \ self.change_person(random.choice(self.history)) else: answer = random.choice(Doctor.HEDGES) elif choice in (2,3,4,5): answer = random.choice(Doctor.QUALIFIERS) + \ self.change_person(sentence) else: answer = random.choice(Doctor.HEDGES) self.history.append(sentence) return answer def change_person(self, sentence): oldlist = sentence.split() newlist = [] for word in oldlist: if word in Doctor.REPLACEMENTS: newlist.append(Doctor.REPLACEMENTS[word]) else: newlist.append(word) return ” “.join(newlist)

Case Study/doctorclient.py

“”” File: doctorclient.py GUI-based view for client for non-directive psychotherapy. “”” from socket import * from codecs import decode from breezypythongui import EasyFrame HOST = “localhost” PORT = 5000 BUFSIZE = 1024 ADDRESS = (HOST, PORT) CODE = “ascii” class DoctorClient(EasyFrame): “””Represents the client’s window.””” COLOR = “#CCEEFF” # Light blue def __init__(self): “””Initialize the window and widgets.””” EasyFrame.__init__(self, title = “Doctor”, background = DoctorClient.COLOR) # Add the labels, fields, and button self.drLabel = self.addLabel(text = “Want to connect?”, row = 0, column = 0, columnspan = 2, background = DoctorClient.COLOR) self.ptField = self.addTextField(text = “”, row = 1, column = 0, columnspan = 2, width = 50) self.sendBtn = self.addButton(row = 2, column = 0, text = “Send reply”, command = self.sendReply, state = “disabled”) self.connectBtn = self.addButton(row = 2, column = 1, text = “Connect”, command = self.connect) # Support the return key in the input field self.ptField.bind(“<Return>”, lambda event: self.sendReply()) def sendReply(self): “””Sends patient input to doctor, and receives and outputs doctor’s reply.””” ptInput = self.ptField.getText() if ptInput != “”: self.server.send(bytes(ptInput, CODE)) drReply = decode(self.server.recv(BUFSIZE), CODE) if not drReply: self.messageBox(message = “Doctor diconnected”) self.disconnect() else: self.drLabel[“text”] = drReply self.ptField.setText(“”) def connect(self): “””Starts a new session with the doctor.””” self.server = socket(AF_INET, SOCK_STREAM) self.server.connect(ADDRESS) self.drLabel[“text”] = decode(self.server.recv(BUFSIZE), CODE) self.connectBtn[“text”] = “Disconnect” self.connectBtn[“command”] = self.disconnect self.sendBtn[“state”] = “normal” def disconnect(self): “””Ends the session with the doctor.””” self.server.close() self.ptField.setText(“”) self.drLabel[“text”] = “Want to connect?” self.connectBtn[“text”] = “Connect” self.connectBtn[“command”] = self.connect self.sendBtn[“state”] = “disabled” def main(): “””Instantiate and pop up the window.””” DoctorClient().mainloop() if __name__ == “__main__”: main()

Case Study/doctorclienthandler.py

“”” File: doctorclienthandler.py Client handler for providing non-directive psychotherapy. “”” from codecs import decode from threading import Thread from doctor import Doctor BUFSIZE = 1024 CODE = “ascii” class DoctorClientHandler(Thread): “””Handles a session between a doctor and a patient.””” def __init__(self, client): Thread.__init__(self) self.client = client self.dr = Doctor() def run(self): self.client.send(bytes(self.dr.greeting(), CODE)) while True: message = decode(self.client.recv(BUFSIZE), CODE) if not message: print(“Client disconnected”) self.client.close() break else: self.client.send(bytes(self.dr.reply(message), CODE))

Case Study/doctorserver.py

“”” File: doctorserver.py Server for providing non-directive psychotherapy. Uses client handlers to handle clients’ requests. “”” from socket import * from doctorclienthandler import DoctorClientHandler HOST = “localhost” PORT = 5000 ADDRESS = (HOST, PORT) server = socket(AF_INET, SOCK_STREAM) server.bind(ADDRESS) server.listen(5) # The server now just waits for connections from clients # and hands sockets off to client handlers while True: print(“Waiting for connection . . .”) client, address = server.accept() print(“… connected from: “, address) handler = DoctorClientHandler(client) handler.start()

Case Study/doctorgui.py

“”” File: doctorservergui.py Project 5 GUI-based view for non-directive psychotherapy. “”” from doctor import Doctor from breezypythongui import EasyFrame class DoctorGUI(EasyFrame): “””Represents the app’s window.””” COLOR = “#CCEEFF” def __init__(self): “””Initialize the frame and widgets.””” EasyFrame.__init__(self, title = “Doctor”, background = DoctorGUI.COLOR) # Instantiate the model self.doctor = Doctor() # Add the labels, fields, and button self.addLabel(text = “Doctor”, row = 0, column = 0, background = DoctorGUI.COLOR) self.drField = self.addTextField(self.doctor.greeting(), row = 0, column = 1, width = 50, state = “readonly”) self.addLabel(text = “Patient”, row = 1, column = 0, background = DoctorGUI.COLOR) self.ptField = self.addTextField(text = “”, row = 1, column = 1, width = 50) self.button = self.addButton(row = 2, column = 0, columnspan = 2, text = “Send reply”, command = self.sendReply) # Support the return key in the input field self.ptField.bind(“<Return>”, lambda event: self.sendReply()) def sendReply(self): “””Sends patient input to doctor, receives and outputs reply.””” ptInput = self.ptField.getText() if ptInput.upper() == “QUIT”: self.drField.setText(self.doctor.farewell()) self.button[“command”] = self.newSession self.button[“text”] = “New session” else: drReply = self.doctor.reply(ptInput) self.drField.setText(drReply) def newSession(self): “””Starts a new session with the doctor.””” self.doctor = Doctor() self.ptField.setText(“”) self.drField.setText(self.doctor.greeting()) self.button[“command”] = self.sendReply self.button[“text”] = “Send reply” def main(): “””Instantiate and pop up the window.””” DoctorGUI().mainloop() if __name__ == “__main__”: main()

 
Do you need a similar assignment done for you from scratch? Order now!
Use Discount Code "Newclient" for a 15% Discount!