├── .gitignore ├── README.md ├── cs144 └── router │ ├── .sha1.d │ ├── .sr_dumper.d │ ├── .sr_utils.d │ ├── sr │ ├── .sr_if.d │ ├── auth_key │ ├── .sr_rt.d │ ├── .sr_arpcache.d │ ├── .sr_main.d │ ├── .sr_router.d │ ├── .sr_vns_comm.d │ ├── ping.sh │ ├── traceroute.sh │ ├── sr_rt.h │ ├── sr_if.h │ ├── sha1.h │ ├── sr_dumper.c │ ├── sr_utils.h │ ├── Makefile │ ├── sr_dumper.h │ ├── sr_router.h │ ├── sr_router.c │ ├── INSTRUCTIONS │ ├── sr_rt.c │ ├── sr_if.c │ ├── vnscommand.h │ ├── sr_arpcache.h │ ├── sr_protocol.h │ └── sr_utils.c ├── book_code ├── src │ ├── dc │ ├── table.cpp │ ├── Makefile │ ├── error.cpp │ ├── main.cpp │ ├── lexer.cpp │ └── parser.cpp └── include │ └── dc.h ├── cs106 ├── gserv │ ├── gserv │ ├── gwin.o │ ├── main.o │ ├── moc_gwin.o │ ├── graphicsarea.o │ ├── cs106graphics.o │ ├── moc_cs106graphics.o │ ├── README │ ├── gserv.pro │ ├── graphicsarea.h │ ├── main.cpp │ ├── graphicsarea.cpp │ ├── gwin.h │ ├── moc_cs106graphics.cpp │ ├── moc_gwin.cpp │ └── cs106graphics.h ├── lib │ └── cs106lib.a ├── assign3 │ ├── lexicon.dat │ ├── Makefile │ ├── warmupA.cpp │ ├── warmupB.cpp │ └── recursion.cpp ├── assign4 │ ├── lexicon.dat │ ├── Sounds │ │ ├── moo.wav │ │ ├── not.wav │ │ ├── .DS_Store │ │ ├── denied.wav │ │ ├── idiot.wav │ │ ├── whoops.wav │ │ ├── excellent.wav │ │ ├── oh really.wav │ │ ├── tweetle.wav │ │ ├── yah as if.wav │ │ ├── dice rattle.wav │ │ ├── tinkerbell.wav │ │ ├── yeah right.wav │ │ ├── come on faster.wav │ │ ├── thats pathetic.wav │ │ └── not fooling anyone.wav │ ├── Makefile │ └── gboggle.h ├── assign1 │ ├── score.txt │ ├── part1.cpp │ ├── Makefile │ ├── part5.cpp │ ├── part4.cpp │ ├── part2.cpp │ └── part3.cpp ├── assign2 │ ├── Makefile │ ├── test.txt │ ├── partA.cpp │ ├── maze.cpp │ ├── maze.h │ └── partB.cpp └── include │ ├── SocketException.h │ ├── ClientSocket.h │ ├── graphicsclient.h │ ├── testgraphics.h │ ├── cmpfn.h │ ├── private │ ├── graphics.h │ ├── scanner.h │ ├── stack.h │ ├── queue.h │ ├── stack.cpp │ ├── set.h │ ├── vector.h │ ├── map.h │ ├── grid.h │ ├── queue.cpp │ ├── bst.h │ ├── set.cpp │ ├── grid.cpp │ └── vector.cpp │ ├── Socket.h │ ├── init.h │ ├── disallowcopy.h │ ├── simpio.h │ ├── sound.h │ ├── random.h │ ├── foreach.h │ ├── strutils.h │ ├── genlib.h │ ├── queue.h │ ├── stack.h │ ├── graphics.h │ └── bst.h ├── cs143 └── doc │ ├── PA1.pdf │ ├── cool-tour.pdf │ └── resources-cool_manual.pdf └── pyext ├── Makefile ├── setup.py └── spammodule.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.swp 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 一些看书碰到和写着玩的程序。。 2 | -------------------------------------------------------------------------------- /cs144/router/.sha1.d: -------------------------------------------------------------------------------- 1 | sha1.o: sha1.c sha1.h 2 | -------------------------------------------------------------------------------- /cs144/router/.sr_dumper.d: -------------------------------------------------------------------------------- 1 | sr_dumper.o: sr_dumper.c sr_dumper.h 2 | -------------------------------------------------------------------------------- /cs144/router/.sr_utils.d: -------------------------------------------------------------------------------- 1 | sr_utils.o: sr_utils.c sr_protocol.h sr_utils.h 2 | -------------------------------------------------------------------------------- /book_code/src/dc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roles/toy_program/master/book_code/src/dc -------------------------------------------------------------------------------- /book_code/src/table.cpp: -------------------------------------------------------------------------------- 1 | #include "dc.h" 2 | 3 | map Table::table; 4 | -------------------------------------------------------------------------------- /cs144/router/sr: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roles/toy_program/master/cs144/router/sr -------------------------------------------------------------------------------- /cs106/gserv/gserv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roles/toy_program/master/cs106/gserv/gserv -------------------------------------------------------------------------------- /cs106/gserv/gwin.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roles/toy_program/master/cs106/gserv/gwin.o -------------------------------------------------------------------------------- /cs106/gserv/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roles/toy_program/master/cs106/gserv/main.o -------------------------------------------------------------------------------- /cs143/doc/PA1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roles/toy_program/master/cs143/doc/PA1.pdf -------------------------------------------------------------------------------- /cs144/router/.sr_if.d: -------------------------------------------------------------------------------- 1 | sr_if.o: sr_if.c sr_if.h sr_protocol.h sr_router.h sr_arpcache.h 2 | -------------------------------------------------------------------------------- /cs144/router/auth_key: -------------------------------------------------------------------------------- 1 | ophCMr/+(4Plq&pdfSUP@kf*uAUPNCf;/Z}ID[VgBW!7hN3sYf 8 | 9 | class SocketException 10 | { 11 | public: 12 | SocketException ( std::string s ) : m_s ( s ) {}; 13 | ~SocketException (){}; 14 | 15 | std::string description() { return m_s; } 16 | 17 | private: 18 | 19 | std::string m_s; 20 | 21 | }; 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /cs106/assign2/test.txt: -------------------------------------------------------------------------------- 1 | Oh its not fag so much as disgust she replied in a voice of 2 | individual quality I dont think I can stick this any longer I 3 | didnt take a secretarial training in order to type out rows of figures 4 | all day long I am bored dearsbored stiff All my powers are wasting 5 | their sweetness on the desert airor rather the town lack of air The 6 | desert would be all right I shouldnt a scrap mind blushing unseen if 7 | I had plenty of space to blush in Ouf I feel as if I should choke 8 | -------------------------------------------------------------------------------- /cs106/include/ClientSocket.h: -------------------------------------------------------------------------------- 1 | // Definition of the ClientSocket class 2 | 3 | #ifndef ClientSocket_class 4 | #define ClientSocket_class 5 | 6 | #include "Socket.h" 7 | 8 | 9 | class ClientSocket : private Socket 10 | { 11 | public: 12 | 13 | ClientSocket ( std::string host, int port ); 14 | virtual ~ClientSocket(){}; 15 | 16 | const ClientSocket& operator << ( const std::string& ) const; 17 | const ClientSocket& operator >> ( std::string& ) const; 18 | 19 | }; 20 | 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /cs106/gserv/gserv.pro: -------------------------------------------------------------------------------- 1 | #------------------------------------------------- 2 | # 3 | # Project created by QtCreator 2011-07-21T09:14:04 4 | # 5 | #------------------------------------------------- 6 | 7 | QT += core gui network 8 | 9 | TARGET = gserv 10 | TEMPLATE = app 11 | 12 | 13 | SOURCES += main.cpp\ 14 | cs106graphics.cpp \ 15 | graphicsarea.cpp \ 16 | gwin.cpp 17 | 18 | HEADERS += \ 19 | cs106graphics.h \ 20 | graphicsarea.h \ 21 | gwin.h 22 | 23 | FORMS += 24 | -------------------------------------------------------------------------------- /cs106/include/graphicsclient.h: -------------------------------------------------------------------------------- 1 | #ifndef GRAPHICSCLIENT_H 2 | #define GRAPHICSCLIENT_H 3 | 4 | #include 5 | #include 6 | #include "ClientSocket.h" 7 | #include "SocketException.h" 8 | 9 | using namespace std; 10 | 11 | class GraphicsClient 12 | { 13 | public: 14 | GraphicsClient(string host, int port); 15 | string ExchangeMsg(string cmd); 16 | 17 | private: 18 | int InitClient(string host, int port); 19 | 20 | ClientSocket *_sock; 21 | }; 22 | 23 | #endif // GRAPHICSCLIENT_H 24 | -------------------------------------------------------------------------------- /cs106/assign1/part1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "random.h" 4 | 5 | using std::cout; 6 | using std::endl; 7 | 8 | bool IsPerfect(int n){ 9 | int sum = 0; 10 | for(int i = 1; i <= static_cast(sqrt(n)); i++){ 11 | if(n % i == 0){ 12 | sum += i + n / i; 13 | } 14 | } 15 | return (sum == 2*n); 16 | } 17 | 18 | int main(){ 19 | for(int i = 2; i <= 10000; i++){ 20 | if(IsPerfect(i)){ 21 | cout << i << endl; 22 | } 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /cs106/assign3/warmupA.cpp: -------------------------------------------------------------------------------- 1 | #include "simpio.h" 2 | #include 3 | 4 | using namespace std; 5 | 6 | /* 7 | * Function : PrintInBinary 8 | * Usage : PrintInBinary(num); 9 | * ------------------- 10 | * 给定一个整数,打印其二进制形式 11 | * 递归的原理是每一次对2求余可以知道是奇数还是偶数, 12 | * 从而确定最后一位二进制位是多少 13 | */ 14 | void PrintInBinary(int num){ 15 | if(num != 0){ 16 | PrintInBinary(num / 2); 17 | cout << num % 2; 18 | } 19 | } 20 | 21 | int main(){ 22 | int num; 23 | cout << "Enter a number : "; 24 | num = GetInteger(); 25 | cout << "Binary format : "; 26 | PrintInBinary(num); 27 | cout << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /pyext/spammodule.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | static PyObject* spam_system(PyObject *self, PyObject *args); 4 | 5 | static PyMethodDef SpamMethods[] = { 6 | {"system", spam_system, METH_VARARGS, "Execute a shell command"}, 7 | {NULL, NULL, 0, NULL} 8 | }; 9 | 10 | static PyObject* 11 | spam_system(PyObject *self, PyObject *args){ 12 | const char *command; 13 | 14 | int sts; 15 | if(!PyArg_ParseTuple(args, "s", &command)) 16 | return NULL; 17 | sts = system(command); 18 | return Py_BuildValue("i", sts); 19 | } 20 | 21 | PyMODINIT_FUNC 22 | initspam(void){ 23 | (void)Py_InitModule("spam", SpamMethods); 24 | } 25 | -------------------------------------------------------------------------------- /cs106/assign1/Makefile: -------------------------------------------------------------------------------- 1 | CC=g++ 2 | LDFLAGS=-lm 3 | CFLAGS=-g -I../include -I../lib -std=c++0x 4 | CS106LIB=../lib/cs106lib.a 5 | 6 | all: part1 part2 part3 part4 part5 7 | 8 | part1: part1.cpp 9 | ${CC} ${LDFLAGS} ${CFLAGS} part1.cpp ${CS106LIB} -o part1 10 | 11 | part2: part2.cpp 12 | ${CC} ${LDFLAGS} ${CFLAGS} part2.cpp ${CS106LIB} -o part2 13 | 14 | part3: part3.cpp 15 | ${CC} ${LDFLAGS} ${CFLAGS} part3.cpp ${CS106LIB} -o part3 16 | 17 | part4: part4.cpp 18 | ${CC} ${LDFLAGS} ${CFLAGS} part4.cpp ${CS106LIB} -o part4 19 | 20 | part5: part5.cpp 21 | ${CC} ${LDFLAGS} ${CFLAGS} part5.cpp ${CS106LIB} -o part5 22 | 23 | clean: 24 | rm -f part1 part2 part3 part4 part5 25 | -------------------------------------------------------------------------------- /cs106/include/testgraphics.h: -------------------------------------------------------------------------------- 1 | /* File: testlib.h 2 | * Last modified: September 2011 by Colin 3 | *------------------------------------ 4 | * This program aims to test the various functions in the 5 | * Graphics and Extgraph libraries 6 | */ 7 | 8 | #ifndef _testlib_h 9 | #define _testlib_h 10 | 11 | #include "genlib.h" 12 | 13 | void BasicGraphics(); 14 | void MoreGraphics(); 15 | void Fills(); 16 | void MouseStuff(); 17 | void Pictures(); 18 | void Erasing(); 19 | void Info(); 20 | void Saves(); 21 | void DrawFill(double width, double height, double density); 22 | void FillGradient(double y); 23 | void EllipseSegments(double w, double h); 24 | void TextLayout(double x, double y); 25 | void CustomColors(); 26 | void DrawRect(double w, double h); 27 | string GetFontDescription(); 28 | void StateTest(string msg, double x, double y); 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /cs106/include/cmpfn.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: cmpfn.h 3 | * Last modified on Wed Sep 18 14:38:14 2002 by zelenski 4 | * ----------------------------------------------------- 5 | * This interface exports a comparison function template. 6 | */ 7 | 8 | #ifndef _cmpfn_h 9 | #define _cmpfn_h 10 | 11 | /* 12 | * Function template: OperatorCmp 13 | * Usage: int sign = OperatorCmp(val1, val2); 14 | * ------------------------------------------- 15 | * This function template is a generic function to 16 | * compare two values using the built-in == and < operators. 17 | * It is supplied as a convenience for those situations 18 | * where a comparison function is required, and the type 19 | * has a built-in ordering that you would like to use. 20 | */ 21 | template 22 | int OperatorCmp(Type one, Type two) { 23 | if (one == two) return 0; 24 | if (one < two) return -1; 25 | return 1; 26 | } 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /book_code/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "dc.h" 2 | 3 | using namespace std; 4 | using namespace Lexer; 5 | using Parser::expr; 6 | using Table::table; 7 | using namespace Error; 8 | 9 | void Dirver::calculate(){ 10 | while(true){ 11 | ts.get(); 12 | if(ts.current().kind == Kind::end) 13 | break; 14 | if(ts.current().kind == Kind::print) 15 | continue; 16 | cout << expr(false) << endl; 17 | //cout << ts.current(); 18 | } 19 | } 20 | 21 | int main(int argc, char* argv[]){ 22 | 23 | table["pi"] = 3.1415926; 24 | table["e"] = 2.7182818; 25 | 26 | switch(argc){ 27 | case 1: 28 | break; 29 | case 2: 30 | ts.set_input(new istringstream{argv[1]}); 31 | default: 32 | error("too many arguments"); 33 | return 1; 34 | } 35 | 36 | Dirver::calculate(); 37 | return no_of_errors; 38 | } 39 | -------------------------------------------------------------------------------- /cs106/include/private/graphics.h: -------------------------------------------------------------------------------- 1 | /* File : private/graphics.h 2 | * Last modified September 2011 by Colin 3 | * ------------------------------------- 4 | * adds a few extensions to the Stanford graphics.h, 5 | * needed by the open-source client/server implementation 6 | */ 7 | 8 | #ifndef _PRIVGRAPHICS_H 9 | #define _PRIVGRAPHICS_H 10 | 11 | #include 12 | #include 13 | #include 14 | #include "../graphicsclient.h" 15 | 16 | using namespace std; 17 | 18 | void StartServer(); 19 | void SetPort(int port); 20 | 21 | /* Some ugly global variables follow (sorry!) 22 | * These are things that need to be stored BEFORE creating the GraphicsClient object. 23 | * It's hard to see how else to handle them in a client/server context 24 | * without breaking the Stanford API. 25 | */ 26 | GraphicsClient *TcpClient = NULL; 27 | int TcpPort = 30004; // a fairly random number, that nobody else seems to be using 28 | string CoordSystem = "inch"; 29 | 30 | #endif // _PRIVGRAPHICS_H 31 | -------------------------------------------------------------------------------- /cs106/gserv/graphicsarea.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: graphicsarea.h 3 | * Last modified August 2011, by Colin 4 | */ 5 | 6 | #ifndef GRAPHICSAREA_H 7 | #define GRAPHICSAREA_H 8 | 9 | #include 10 | 11 | class GraphicsArea : public QGraphicsRectItem 12 | { 13 | 14 | public: 15 | explicit GraphicsArea(double sceneWidth, 16 | double sceneHeight); 17 | // Mouse support 18 | double getMouseX(); 19 | double getMouseY(); 20 | QString mouseButtonIsDown(); 21 | 22 | private: 23 | // re-implemented QGraphicsItem functions 24 | void mousePressEvent(QGraphicsSceneMouseEvent *event); 25 | void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); 26 | void mouseMoveEvent(QGraphicsSceneMouseEvent *event); 27 | 28 | int _areaWidth; 29 | int _areaHeight; 30 | 31 | struct mouseStatus { 32 | QPointF pos; 33 | Qt::MouseButton btn; 34 | bool pressed; 35 | }; 36 | 37 | mouseStatus _lastMouseEvent; 38 | 39 | }; 40 | 41 | #endif // GRAPHICSAREA_H 42 | -------------------------------------------------------------------------------- /cs106/assign1/part5.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void getHistogram(ifstream& ifs, vector& htgram){ 8 | int score; 9 | while(ifs >> score){ 10 | ++htgram[score/10]; 11 | } 12 | } 13 | 14 | void printHistogram(vector& htgram){ 15 | for(int i = 0; i < 10; i++){ 16 | cout << i * 10 << "-" << (i+1) * 10 - 1 << ": "; 17 | for(int j = 0; j < htgram[i]; j++) 18 | cout << 'X'; 19 | cout << endl; 20 | } 21 | } 22 | 23 | int main(){ 24 | ifstream ifs; 25 | vector htgram(10); 26 | for(;;){ 27 | string scoreFile; 28 | cout << "Enter score file : "; 29 | cin >> scoreFile; 30 | ifs.open(scoreFile, ifstream::in); 31 | if((ifs.rdstate() & ifstream::failbit) == 0) //检测是否成功打开文件 32 | break; 33 | cout << "cannot open file " << scoreFile << endl; 34 | } 35 | 36 | getHistogram(ifs, htgram); 37 | printHistogram(htgram); 38 | 39 | ifs.close(); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /cs106/include/private/scanner.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/scanner.h 3 | * Last modified on Tue Jun 9 00:19:57 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the private section of the scanner.h interface. 6 | * This portion of the class definition is taken out of the scanner.h 7 | * header so that the client need not have to see all of these 8 | * details. 9 | */ 10 | 11 | enum realNumScanStateT { 12 | InitialState, 13 | BeforeDecimalPoint, 14 | AfterDecimalPoint, 15 | StartingExponent, 16 | FoundExponentSign, 17 | ScanningExponent, 18 | FinalState 19 | }; 20 | 21 | string buffer; 22 | int len; // buflen; in the original 23 | int cp; 24 | istream *fp; 25 | spaceOptionT spaceOption; 26 | numberOptionT numberOption; 27 | stringOptionT stringOption; 28 | bracketOptionT bracketOption; 29 | Stack savedTokens; 30 | 31 | void skipSpaces(); 32 | int scanToEndOfIdentifier(); 33 | int scanToEndOfInteger(); 34 | int scanToEndOfReal(); 35 | string scanQuotedString(); 36 | char scanEscapeCharacter(); 37 | string scanTag(); 38 | -------------------------------------------------------------------------------- /cs106/include/Socket.h: -------------------------------------------------------------------------------- 1 | /* Definition of the Socket class 2 | Closely based on tutorial code by Rob Tougher 3 | http://linuxgazette.net/74/tougher.html 4 | 5 | Last modified by Colin Leach, July 2011 6 | */ 7 | 8 | #ifndef Socket_class 9 | #define Socket_class 10 | 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | 21 | const int MAXHOSTNAME = 200; // is this used anywhere? 22 | const int MAXCONNECTIONS = 5; 23 | const int MAXRECV = 500; 24 | 25 | class Socket 26 | { 27 | public: 28 | Socket(); 29 | virtual ~Socket(); 30 | 31 | // Server initialization 32 | bool create(); 33 | bool bind ( const int port ); 34 | bool listen() const; 35 | bool accept ( Socket& ) const; 36 | 37 | // Client initialization 38 | bool connect ( const std::string host, const int port ); 39 | 40 | // Data Transimission 41 | bool send ( const std::string ) const; 42 | int recv ( std::string& ) const; 43 | 44 | 45 | void set_non_blocking ( const bool ); 46 | 47 | bool is_valid() const { return m_sock != -1; } 48 | 49 | private: 50 | 51 | int m_sock; 52 | sockaddr_in m_addr; 53 | }; 54 | 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /cs106/include/private/stack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/stack.h 3 | * Last modified on Fri Jun 5 10:50:28 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the private section of the stack.h interface. 6 | * This portion of the class definition is taken out of the stack.h 7 | * header so that the client need not have to see all of these 8 | * details. 9 | */ 10 | 11 | public: 12 | 13 | /* 14 | * Deep copying support 15 | * -------------------- 16 | * Because all data members have correct behavior on operator= 17 | * and copy constructor, the default as synthesized by 18 | * the compiler make a correct copy of the Stack. When pass/return 19 | * stacks by value, or assign one to another, the entire contents 20 | * of the stack, including all elements, are copied. Each stack 21 | * element is copied from the original stack to the copy using 22 | * assignment (operator=). Making copies is generally avoided 23 | * because of the expense and thus, stacks are typically passed by 24 | * reference, however, when a copy is needed, these operations 25 | * correctly are supported. 26 | * 27 | * const Stack & operator=(const Stack & rhs); 28 | * Stack(const Stack & rhs); 29 | */ 30 | 31 | private: 32 | Vector elems; 33 | -------------------------------------------------------------------------------- /cs144/router/sr_rt.h: -------------------------------------------------------------------------------- 1 | /*----------------------------------------------------------------------------- 2 | * file: sr_rt.h 3 | * date: Mon Oct 07 03:53:53 PDT 2002 4 | * Author: casado@stanford.edu 5 | * 6 | * Description: 7 | * 8 | * Methods and datastructures for handeling the routing table 9 | * 10 | *---------------------------------------------------------------------------*/ 11 | 12 | #ifndef sr_RT_H 13 | #define sr_RT_H 14 | 15 | #ifdef _DARWIN_ 16 | #include 17 | #endif 18 | 19 | #include 20 | 21 | #include "sr_if.h" 22 | 23 | /* ---------------------------------------------------------------------------- 24 | * struct sr_rt 25 | * 26 | * Node in the routing table 27 | * 28 | * -------------------------------------------------------------------------- */ 29 | 30 | struct sr_rt 31 | { 32 | struct in_addr dest; 33 | struct in_addr gw; 34 | struct in_addr mask; 35 | char interface[sr_IFACE_NAMELEN]; 36 | struct sr_rt* next; 37 | }; 38 | 39 | 40 | int sr_load_rt(struct sr_instance*,const char*); 41 | void sr_add_rt_entry(struct sr_instance*, struct in_addr,struct in_addr, 42 | struct in_addr, char*); 43 | void sr_print_routing_table(struct sr_instance* sr); 44 | void sr_print_routing_entry(struct sr_rt* entry); 45 | 46 | 47 | #endif /* -- sr_RT_H -- */ 48 | -------------------------------------------------------------------------------- /cs106/include/private/queue.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/queue.h 3 | * Last modified on Fri Jun 5 10:06:00 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the private section of the queue.h interface. 6 | * This portion of the class definition is taken out of the queue.h 7 | * header so that the client need not have to see all of these 8 | * details. 9 | */ 10 | 11 | public: 12 | 13 | /* 14 | * Deep copying support 15 | * -------------------- 16 | * This copy constructor and operator= are defined to make a 17 | * deep copy, making it possible to pass/return queues by value 18 | * and assign from one queue to another. The entire contents of 19 | * the queue, including all elements, are copied. Each queue 20 | * element is copied from the original queue to the copy using 21 | * assignment (operator=). Making copies is generally avoided 22 | * because of the expense and thus, queues are typically passed 23 | * by reference, however, when a copy is needed, these operations 24 | * are supported. 25 | */ 26 | const Queue & operator=(const Queue & rhs); 27 | Queue(const Queue & rhs); 28 | 29 | private: 30 | struct cellT { 31 | ElemType elem; 32 | cellT *next; 33 | }; 34 | 35 | cellT *head; 36 | cellT *tail; 37 | int count; 38 | void deleteCells(); 39 | void copyOtherData(const Queue & rhs); 40 | -------------------------------------------------------------------------------- /cs106/include/init.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: init.h 3 | * Last modified on Jul 18 2011 by Colin Leach 4 | * ----------------------------------------------------- 5 | * A cut-down version of genlib.h 6 | * init.cpp puts a wrapper around the student program, to catch any 7 | * ErrorException raised and output a novice-friendly error message. 8 | * This isn't much documented in Stanford code, but presumably they 9 | * want to prevent the program barfing a long, confusing error message 10 | * (machine-dependent - maybe even a stack dump). 11 | * This is a least-bad-guess implementation by someone who doesn't 12 | * really know what he's doing, but hopefully it will be adequate. 13 | */ 14 | 15 | #ifndef _init_h 16 | #define _init_h 17 | 18 | #include 19 | #include 20 | using namespace std; 21 | 22 | extern int Main(); 23 | 24 | /* 25 | * Class: ErrorException 26 | * --------------------- 27 | * This exception is raised by calls to the Error function, which 28 | * makes it possible for clients to respond to error conditions 29 | * without having their programs bomb completely. 30 | */ 31 | 32 | class ErrorException : public exception { 33 | public: 34 | ErrorException(string msg); 35 | virtual ~ErrorException() throw (); 36 | virtual const char* what() const throw (); 37 | //virtual string getMessage(); 38 | private: 39 | string msg; 40 | }; 41 | 42 | #endif 43 | -------------------------------------------------------------------------------- /cs106/include/disallowcopy.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: disallowcopy.h 3 | * Last modified on Tue Jan 2 13:40:51 2007 by zelenski 4 | * ----------------------------------------------------- 5 | * This file provides a macro that configures a class to disallowing making 6 | * object copies. 7 | */ 8 | 9 | #ifndef _disallowcopy_h 10 | #define _disallowcopy_h 11 | 12 | /* 13 | * Macro: DISALLOW_COPYING 14 | * Usage: DISALLOW_COPYING(MyClass) 15 | * -------------------------------- 16 | * This macro is inserted into the private interface of a class to configure 17 | * the class to have private declarations of assignment (operator=) and copy 18 | * construction. By declaring these private, if a client attempts to invoke 19 | * them, the compiler will raise an error. This effectively disables object 20 | * copying: a client will not be able to assign one object to another or 21 | * pass/return an object by value. This is appropriate when the class does not 22 | * provide the facilities for making copies (because of efficiency and/or 23 | * complexity) and wants to be sure the client doesn't accidentally attempt 24 | * to make a copy and run into problems because of the non-support. 25 | */ 26 | #define DISALLOW_COPYING(Classname) \ 27 | const Classname & operator=(const Classname &) { \ 28 | Error("Copying is disallowed for class "#Classname); \ 29 | return *this; \ 30 | } \ 31 | Classname(const Classname &) { \ 32 | Error("Copying is disallowed for class "#Classname); \ 33 | } 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /cs144/router/sr_if.h: -------------------------------------------------------------------------------- 1 | /*----------------------------------------------------------------------------- 2 | * file: sr_if.h 3 | * date: Sun Oct 06 14:13:13 PDT 2002 4 | * Contact: casado@stanford.edu 5 | * 6 | * Description: 7 | * 8 | * Data structures and methods for handeling interfaces 9 | * 10 | *---------------------------------------------------------------------------*/ 11 | 12 | #ifndef sr_INTERFACE_H 13 | #define sr_INTERFACE_H 14 | 15 | #ifdef _LINUX_ 16 | #include 17 | #endif /* _LINUX_ */ 18 | 19 | #ifdef _SOLARIS_ 20 | #include 21 | #endif /* SOLARIS */ 22 | 23 | #ifdef _DARWIN_ 24 | #include 25 | #endif 26 | 27 | #include "sr_protocol.h" 28 | 29 | struct sr_instance; 30 | 31 | /* ---------------------------------------------------------------------------- 32 | * struct sr_if 33 | * 34 | * Node in the interface list for each router 35 | * 36 | * -------------------------------------------------------------------------- */ 37 | 38 | struct sr_if 39 | { 40 | char name[sr_IFACE_NAMELEN]; 41 | unsigned char addr[ETHER_ADDR_LEN]; 42 | uint32_t ip; 43 | uint32_t speed; 44 | struct sr_if* next; 45 | }; 46 | 47 | struct sr_if* sr_get_interface(struct sr_instance* sr, const char* name); 48 | void sr_add_interface(struct sr_instance*, const char*); 49 | void sr_set_ether_addr(struct sr_instance*, const unsigned char*); 50 | void sr_set_ether_ip(struct sr_instance*, uint32_t ip_nbo); 51 | void sr_print_if_list(struct sr_instance*); 52 | void sr_print_if(struct sr_if*); 53 | 54 | #endif /* -- sr_INTERFACE_H -- */ 55 | -------------------------------------------------------------------------------- /cs106/assign1/part4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | map letterMap {{'A', '0'}, {'E', '0'}, {'I', '0'}, {'O', '0'}, {'U', '0'}, {'H', '0'}, {'W', '0'}, {'Y', '0'}, 9 | {'B', '1'}, {'F', '1'}, {'P', '1'}, {'V', '1'}, 10 | {'C', '2'}, {'G', '2'}, {'J', '2'}, {'K', '2'}, {'Q', '2'}, {'S', '2'}, {'X', '2'}, {'Z', '2'}, 11 | {'D', '3'}, {'T', '3'}, 12 | {'M', '4'}, {'N', '4'}, 13 | {'L', '5'}, 14 | {'R', '6'}}; 15 | 16 | int main(){ 17 | string surname; 18 | for(;;){ 19 | cout << "Enter surname (RETURN to quit):"; 20 | if(!(cin >> surname)){ 21 | break; 22 | } 23 | string code{}; 24 | char preChar, newChar; 25 | for(int i = 0; i < surname.size(); i++){ 26 | if(i == 0){ 27 | code.push_back(toupper(surname[i])); 28 | preChar = code[0]; 29 | }else{ 30 | newChar = letterMap[toupper(surname[i])]; 31 | if(newChar != preChar && newChar != '0'){ 32 | code.push_back(newChar); 33 | preChar = newChar; 34 | } 35 | } 36 | } 37 | while(code.size() < 4) 38 | code.push_back('0'); 39 | if(code.size() > 4) 40 | code = code.substr(0, 4); 41 | cout << "Soundex code for " << surname << " is " << code << endl; 42 | } 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /cs106/include/private/stack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/stack.cpp 3 | * Last modified on Fri Jun 5 10:51:26 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the implementation of the stack.h interface. 6 | * Because of the way C++ compiles templates, this code must be 7 | * available to the compiler when it reads the header file. 8 | */ 9 | 10 | #ifdef _stack_h 11 | 12 | /* 13 | * Stack class implementation 14 | * --------------------------- 15 | * The Stack is internally managed using a Vector. This layered 16 | * implementation makes the job quite trivial, most methods are 17 | * one-liners. 18 | */ 19 | 20 | template 21 | Stack::Stack() { 22 | /* Empty */ 23 | } 24 | 25 | template 26 | Stack::~Stack() { 27 | /* Empty */ 28 | } 29 | 30 | template 31 | int Stack::size() { 32 | return elems.size(); 33 | } 34 | 35 | template 36 | bool Stack::isEmpty() { 37 | return size() == 0; 38 | } 39 | 40 | template 41 | void Stack::push(ElemType elem) { 42 | elems.add(elem); 43 | } 44 | 45 | template 46 | ElemType Stack::pop() { 47 | if (isEmpty()) Error("Attempt to pop from empty stack"); 48 | ElemType top = elems[elems.size()-1]; 49 | elems.removeAt(elems.size()-1); 50 | return top; 51 | } 52 | 53 | template 54 | ElemType Stack::peek() { 55 | if (isEmpty()) Error("Attempt to peek at empty stack"); 56 | return elems[elems.size()-1]; 57 | } 58 | 59 | template 60 | void Stack::clear() { 61 | elems.clear(); 62 | } 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /cs144/router/sha1.h: -------------------------------------------------------------------------------- 1 | /* 2 | * sha1.h 3 | * 4 | * Copyright (C) 1998, 2009 5 | * Paul E. Jones 6 | * All Rights Reserved 7 | * 8 | ***************************************************************************** 9 | * $Id: sha1.h 12 2009-06-22 19:34:25Z paulej $ 10 | ***************************************************************************** 11 | * 12 | * Description: 13 | * This class implements the Secure Hashing Standard as defined 14 | * in FIPS PUB 180-1 published April 17, 1995. 15 | * 16 | * Many of the variable names in the SHA1Context, especially the 17 | * single character names, were used because those were the names 18 | * used in the publication. 19 | * 20 | * Please read the file sha1.c for more information. 21 | * 22 | */ 23 | 24 | #ifndef _SHA1_H_ 25 | #define _SHA1_H_ 26 | 27 | /* 28 | * This structure will hold context information for the hashing 29 | * operation 30 | */ 31 | typedef struct SHA1Context 32 | { 33 | unsigned Message_Digest[5]; /* Message Digest (output) */ 34 | 35 | unsigned Length_Low; /* Message length in bits */ 36 | unsigned Length_High; /* Message length in bits */ 37 | 38 | unsigned char Message_Block[64]; /* 512-bit message blocks */ 39 | int Message_Block_Index; /* Index into message block array */ 40 | 41 | int Computed; /* Is the digest computed? */ 42 | int Corrupted; /* Is the message digest corruped? */ 43 | } SHA1Context; 44 | 45 | /* 46 | * Function Prototypes 47 | */ 48 | void SHA1Reset(SHA1Context *); 49 | int SHA1Result(SHA1Context *); 50 | void SHA1Input( SHA1Context *, 51 | const unsigned char *, 52 | unsigned); 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /cs106/assign3/warmupB.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | bool _CanMakeSum(vector& nums, int targetSum, const vector::iterator curIter){ 8 | if(curIter == nums.end()) 9 | return false; 10 | if(targetSum == *curIter) 11 | return true; 12 | return _CanMakeSum(nums, targetSum, curIter+1) || _CanMakeSum(nums, targetSum-*curIter, curIter+1); 13 | } 14 | 15 | bool CanMakeSum(vector& nums, int targetSum){ 16 | return _CanMakeSum(nums, targetSum, nums.begin()); 17 | } 18 | 19 | void _ListAllSubset(vector& nums, int targetSum, const vector::iterator curIter, list& numList){ 20 | if(curIter == nums.end()) 21 | return; 22 | if(*curIter == targetSum){ 23 | cout << "{"; 24 | for(auto n : numList){ 25 | cout << n << ","; 26 | } 27 | cout << *curIter << "}" << endl; 28 | return; 29 | } 30 | _ListAllSubset(nums, targetSum, curIter+1, numList); 31 | 32 | numList.push_back(*curIter); 33 | _ListAllSubset(nums, targetSum-*curIter, curIter+1, numList); 34 | numList.pop_back(); 35 | } 36 | 37 | void ListAllSubset(vector& nums, int targetSum){ 38 | list numList; 39 | _ListAllSubset(nums, targetSum, nums.begin(), numList); 40 | } 41 | 42 | int main(){ 43 | vector nums{1, 2, 3, 4, 5}; 44 | int targetSum; 45 | 46 | cout << "List number:"; 47 | for(auto n : nums){ 48 | cout << " " << n; 49 | } 50 | cout << endl; 51 | 52 | cout << "Enter target sum: "; 53 | cin >> targetSum; 54 | 55 | if(CanMakeSum(nums, targetSum)){ 56 | cout << "It can" << endl; 57 | }else{ 58 | cout << "It cannot" << endl; 59 | } 60 | 61 | ListAllSubset(nums, targetSum); 62 | } 63 | -------------------------------------------------------------------------------- /cs106/gserv/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * File: main.cpp 3 | * Last modified August 2011 by Colin 4 | * ----------------------------------- 5 | * main() just parses the command line then starts the event loop. 6 | * All serious processing is done in the gWin and GraphicsHandler 7 | * objects, plus GraphicsArea to handle mouse stuff. 8 | */ 9 | 10 | #include 11 | #include "gwin.h" 12 | 13 | using namespace std; 14 | 15 | int main(int argc, char *argv[]) 16 | { 17 | const int DEFAULTPORT = 30004; 18 | const QString DEFAULTHOST = "localhost"; 19 | 20 | int i = 1; 21 | int port = DEFAULTPORT; 22 | QString host = DEFAULTHOST; 23 | bool showTextArea = false; 24 | bool ok; 25 | QString arg; 26 | 27 | while (i < argc) { 28 | arg = argv[i]; 29 | 30 | if (arg == "-p") { // non-default port setting 31 | ++i; 32 | QString newPort = argv[i]; 33 | port = newPort.toInt(&ok); 34 | if (!ok) { 35 | port = DEFAULTPORT; //invalid setting on command line 36 | qDebug() << "Invalid argument to -p option: must be an integer port number <32k" << endl; 37 | } 38 | // qDebug() << "Starting on port " << port << endl; 39 | } 40 | 41 | if (arg == "-h") { // non-default host setting (should be an IP address) 42 | ++i; 43 | host = argv[i]; 44 | // qDebug() << "Starting on host " << host << endl; 45 | } 46 | 47 | if (arg == "-d" || arg == "--debug") { 48 | showTextArea = true; 49 | // qDebug() << "starting in debug mode" << endl; 50 | } 51 | ++i; 52 | } 53 | 54 | QApplication a(argc, argv); 55 | gWin w(port, host, showTextArea); 56 | w.show(); 57 | 58 | return a.exec(); 59 | } 60 | -------------------------------------------------------------------------------- /cs106/assign1/part2.cpp: -------------------------------------------------------------------------------- 1 | #include "random.h" 2 | #include "simpio.h" 3 | #include 4 | 5 | using namespace std; 6 | 7 | void readInput(int& numVoter, double& diffPer, double& errPer){ 8 | cout << "Enter number of voters: "; 9 | numVoter = GetInteger(); 10 | cout << "Enter percentage spread between candidates: "; 11 | diffPer = GetReal(); 12 | cout << "Enter voting error percentage: "; 13 | errPer = GetReal(); 14 | } 15 | 16 | void getCanNum(const int& numVoter, const double& diffPer, 17 | int& numCanA, int& numCanB){ 18 | //numCanA = (1 + diffPer) / 2 * numVoter; 19 | //numCanB = numVoter - numCanA; 20 | numCanA = (0.5 + diffPer) * numVoter; 21 | numCanB = numVoter - numCanA; 22 | } 23 | 24 | int getRealVote(const int& voteCount, const double& errPer, 25 | int& preciseVote, int& errorVote){ 26 | for(int i = 0; i < voteCount; i++){ 27 | if(!RandomChance(errPer)){ 28 | preciseVote++; 29 | }else{ 30 | errorVote++; 31 | } 32 | } 33 | } 34 | 35 | int main(){ 36 | int numVoter; 37 | double diffPer, errPer; 38 | int numCanA, numCanB; 39 | int numVoteA, numVoteB; 40 | const int numTrail = 500; 41 | int invalidTrail = 0; 42 | 43 | Randomize(); 44 | readInput(numVoter, diffPer, errPer); 45 | getCanNum(numVoter, diffPer, numCanA, numCanB); 46 | for(int i = 0; i < numTrail; i++){ 47 | numVoteA = numVoteB = 0; 48 | getRealVote(numCanA, errPer, numVoteA, numVoteB); 49 | getRealVote(numCanB, errPer, numVoteB, numVoteA); 50 | if(numVoteB >= numVoteA){ 51 | ++invalidTrail; 52 | } 53 | } 54 | 55 | cout << "Chance of an invalid election result after 500 trails = " 56 | << invalidTrail * 100.0 / numTrail << "%" << endl; 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /cs106/include/simpio.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: simpio.h 3 | * Last modified on Wed Jul 22 07:01:03 2009 by eroberts 4 | * modified on Wed Sep 18 13:34:29 2002 by zelenski 5 | * ----------------------------------------------------- 6 | * This interface provides access to a simple package of 7 | * functions that simplify the reading of console input. 8 | */ 9 | 10 | #ifndef _simpio_h 11 | #define _simpio_h 12 | 13 | #include "genlib.h" 14 | 15 | /* 16 | * Function: GetInteger 17 | * Usage: n = GetInteger(); 18 | * ------------------------ 19 | * GetInteger reads a line of text from standard input and scans 20 | * it as an integer. The integer value is returned. If an 21 | * integer cannot be scanned or if more characters follow the 22 | * number, the user is given a chance to retry. 23 | */ 24 | 25 | int GetInteger(); 26 | 27 | /* 28 | * Function: GetLong 29 | * Usage: n = GetLong(); 30 | * --------------------- 31 | * GetLong reads a line of text from standard input and scans 32 | * it into a long integer. The long is returned. If the 33 | * number cannot be scanned or if extra characters follow it, 34 | * the user is given a chance to retry. 35 | */ 36 | 37 | long GetLong(); 38 | 39 | /* 40 | * Function: GetReal 41 | * Usage: x = GetReal(); 42 | * --------------------- 43 | * GetReal reads a line of text from standard input and scans 44 | * it as a double. If the number cannot be scanned or if extra 45 | * characters follow after the number ends, the user is given 46 | * a chance to reenter the value. 47 | */ 48 | 49 | double GetReal(); 50 | 51 | /* 52 | * Function: GetLine 53 | * Usage: s = GetLine(); 54 | * --------------------- 55 | * GetLine reads a line of text from standard input and returns 56 | * the line as a string. The newline character that terminates 57 | * the input is not stored as part of the string that is returned. 58 | */ 59 | 60 | string GetLine(); 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /cs106/include/private/set.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/set.h 3 | * Last modified on Fri Jun 5 15:39:43 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the private section of the set.h interface. 6 | * This portion of the class definition is taken out of the set.h 7 | * header so that the client need not have to see all of these 8 | * details. 9 | */ 10 | 11 | public: 12 | 13 | /* 14 | * Legacy function: intersect 15 | * -------------------------- 16 | * This name was changed to intersectWith for symmetry with unionWith. 17 | */ 18 | void intersect(Set & otherSet); 19 | 20 | /* 21 | * Class: Set::Iterator 22 | * --------------------------------- 23 | * This interface defines a nested class within the Set template that 24 | * provides iterator access to the Set contents. 25 | */ 26 | class Iterator : public FE_Iterator { 27 | public: 28 | Iterator(); 29 | bool hasNext(); 30 | ElemType next(); 31 | 32 | private: 33 | Iterator(Set *setptr); 34 | typename BST::Iterator iterator; 35 | friend class Set; 36 | }; 37 | friend class Iterator; 38 | ElemType foreachHook(FE_State & _fe); 39 | 40 | /* 41 | * Deep copying support 42 | * -------------------- 43 | * Because all Set data members have correct behavior on operator= 44 | * and copy constructor, the default for these as synthesized by 45 | * the compiler make a correct copy of the Set. When pass/return 46 | * sets by value, or assign one to another, the entire contents of 47 | * the set, including all elements, are copied. Each set 48 | * element is copied from the original set to the copy using 49 | * assignment (operator=). Making copies is generally avoided 50 | * because of the expense and thus, sets are typically passed by 51 | * reference, however, when a copy is needed, these operations 52 | * are supported. 53 | */ 54 | 55 | private: 56 | BST bst; 57 | int (*cmpFn)(ElemType, ElemType); 58 | -------------------------------------------------------------------------------- /cs106/include/private/vector.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/vector.h 3 | * Last modified on Fri Jun 5 15:39:26 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the private section of the vector.h interface. 6 | * This portion of the class definition is taken out of the vector.h 7 | * header so that the client need not have to see all of these 8 | * details. 9 | */ 10 | 11 | public: 12 | 13 | /* 14 | * Class: Vector::Iterator 15 | * --------------------------------- 16 | * This interface defines a nested class within the Vector template that 17 | * provides iterator access to the Vector contents. 18 | */ 19 | class Iterator : public FE_Iterator { 20 | public: 21 | Iterator(); 22 | bool hasNext(); 23 | ElemType next(); 24 | 25 | private: 26 | Iterator(Vector *vecRef); 27 | Vector *vp; 28 | int curIndex; 29 | long timestamp; 30 | friend class Vector; 31 | }; 32 | friend class Iterator; 33 | ElemType foreachHook(FE_State & _fe); 34 | 35 | /* 36 | * Deep copying support 37 | * -------------------- 38 | * This copy constructor and operator= are defined to make a 39 | * deep copy, making it possible to pass/return vectors by value 40 | * and assign from one vector to another. The entire contents of 41 | * the vector, including all elements, are copied. Each vector 42 | * element is copied from the original vector to the copy using 43 | * assignment (operator=). Making copies is generally avoided 44 | * because of the expense and thus, vectors are typically passed 45 | * by reference, however, when a copy is needed, these operations 46 | * are supported. 47 | */ 48 | const Vector & operator=(const Vector & rhs); 49 | Vector(const Vector & rhs); 50 | 51 | private: 52 | ElemType *elements; 53 | int numAllocated, numUsed; 54 | long timestamp; 55 | 56 | void checkRange(int index, const char *msg); 57 | void enlargeCapacity(); 58 | void copyInternalData(const Vector & other); 59 | -------------------------------------------------------------------------------- /cs106/include/sound.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: sound.h 3 | * Last modified Sept 2011, by Colin 4 | * modified on Wed Sep 18 14:34:59 2002 by zelenski 5 | * modified on Sat Apr 4 09:38:41 1998 by eroberts 6 | * ----------------------------------------------------- 7 | * This interface defines a function for playing a named 8 | * sound file. 9 | */ 10 | 11 | #ifndef _sound_h 12 | #define _sound_h 13 | 14 | #include "genlib.h" 15 | 16 | /* 17 | * Function: PlayNamedSound 18 | * Usage: PlayNamedSound("beep.wav"); 19 | * ---------------------------------- 20 | * This function looks for a sound file with the given name 21 | * in the "Sounds" subdirectory of the project. 22 | * If a matching sound file is located, it is loaded and played. 23 | * The function generates an error if the file cannot be 24 | * found or the sound facility is unimplemented for the platform. 25 | */ 26 | 27 | void PlayNamedSound(string name); 28 | 29 | /* 30 | * Function: SetSoundOn 31 | * Usage: SetSoundOn(false); 32 | * -------------------------- 33 | * This function enables/disables the playing of sound. 34 | * If you call the function passing false, it will disable sound 35 | * and any subsequent calls to PlayNamedSound will be be ignored. 36 | * If you call the function passing true, it will enable sound 37 | * and any subsequent class to PlayNamedSound will operate normally. 38 | * The default is true. 39 | */ 40 | 41 | void SetSoundOn(bool on); 42 | 43 | /* 44 | * Function: TestSound 45 | * Usage: bool haveSound = TestSound(); 46 | * ---------------------------------------------------------------- 47 | * On X11-based systems, playing sounds relies on the Network Audio 48 | * System (ftp://ftp.x.org/contrib/audio/nas/) 49 | * If missing, attempts to play sounds will fail silently. 50 | * You may wish to check in advance by calling TestSound() 51 | * It returns true if the necessary sound drivers are found, 52 | * otherwise false. 53 | */ 54 | 55 | bool TestSound(); 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /cs144/router/sr_dumper.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | #include "sr_dumper.h" 6 | 7 | static void 8 | sf_write_header(FILE *fp, int linktype, int thiszone, int snaplen) 9 | { 10 | struct pcap_file_header hdr; 11 | 12 | hdr.magic = TCPDUMP_MAGIC; 13 | hdr.version_major = PCAP_VERSION_MAJOR; 14 | hdr.version_minor = PCAP_VERSION_MINOR; 15 | 16 | hdr.thiszone = thiszone; 17 | hdr.snaplen = snaplen; 18 | hdr.sigfigs = 0; 19 | hdr.linktype = linktype; 20 | 21 | if (fwrite((char *)&hdr, sizeof(hdr), 1, fp) != 1) 22 | fprintf(stderr, "sf_write_header: can't write header\n"); 23 | } 24 | 25 | /* 26 | * Initialize so that sf_write_header() will output to the file named 'fname'. 27 | */ 28 | FILE * 29 | sr_dump_open(const char *fname, int thiszone, int snaplen) 30 | { 31 | FILE *fp; 32 | 33 | if (fname[0] == '-' && fname[1] == '\0') 34 | fp = stdout; 35 | else { 36 | fp = fopen(fname, "w"); 37 | if (fp == NULL) { 38 | fprintf(stderr, "sr_dump_open: can't open %s", 39 | fname); 40 | return (NULL); 41 | } 42 | } 43 | 44 | sf_write_header(fp, LINKTYPE_ETHERNET, thiszone, snaplen); 45 | 46 | return fp; 47 | } 48 | 49 | /* 50 | * Output a packet to the initialized dump file. 51 | */ 52 | void 53 | sr_dump(FILE *fp, const struct pcap_pkthdr *h, const unsigned char *sp) 54 | { 55 | struct pcap_sf_pkthdr sf_hdr; 56 | 57 | sf_hdr.ts.tv_sec = h->ts.tv_sec; 58 | sf_hdr.ts.tv_usec = h->ts.tv_usec; 59 | sf_hdr.caplen = h->caplen; 60 | sf_hdr.len = h->len; 61 | /* XXX we should check the return status */ 62 | (void)fwrite(&sf_hdr, sizeof(sf_hdr), 1, fp); 63 | (void)fwrite((char *)sp, h->caplen, 1, fp); 64 | } 65 | 66 | void 67 | sr_dump_close(FILE *fp) 68 | { 69 | fclose(fp); 70 | } 71 | 72 | -------------------------------------------------------------------------------- /cs106/assign1/part3.cpp: -------------------------------------------------------------------------------- 1 | #include "graphics.h" 2 | #include "extgraph.h" 3 | #include 4 | #include 5 | #include 6 | #include "random.h" 7 | 8 | using namespace std; 9 | 10 | struct point{ 11 | double x, y; 12 | }; 13 | 14 | void test(){ 15 | cout << "width : " << GetWindowWidth() << endl; 16 | cout << "height : " << GetWindowHeight() << endl; 17 | cout << "current X : " << GetCurrentX() << endl; 18 | cout << "current Y : " << GetCurrentY() << endl; 19 | WaitForMouseDown(); 20 | cout << "mouse X : " << GetMouseX() << endl; 21 | cout << "mouse Y : " << GetMouseY() << endl; 22 | } 23 | 24 | void getInitPoints(vector& pvec){ 25 | for(int i = 0; i < 3; i++){ 26 | WaitForMouseDown(); 27 | pvec[i].x = GetMouseX(); 28 | pvec[i].y = GetMouseY(); 29 | cout << "mouse X : " << pvec[i].x << endl; 30 | cout << "mouse Y : " << pvec[i].y << endl; 31 | WaitForMouseUp(); 32 | } 33 | } 34 | 35 | void drawTriangle(vector& pvec){ 36 | MovePen(pvec[0].x, pvec[0].y); 37 | for(int i = 0, j = 0; i < 3; i++){ 38 | j = (i + 1) % 3; 39 | DrawLine(pvec[j].x - pvec[i].x, pvec[j].y - pvec[i].y); 40 | } 41 | } 42 | 43 | void chaoGame(vector& pvec){ 44 | double curX, curY; 45 | int i = RandomInteger(0, 3); 46 | 47 | curX = pvec[i].x; 48 | curY = pvec[i].y; 49 | MovePen(curX, curY); 50 | SetPenColor(string{"red"}); 51 | for(;;){ 52 | StartFilledRegion(); 53 | DrawArc(0.02, 0, 360); 54 | EndFilledRegion(); 55 | if(MouseButtonIsDown()){ 56 | break; 57 | } 58 | i = RandomInteger(0, 3); 59 | curX = (curX + pvec[i].x) / 2.0; 60 | curY = (curY + pvec[i].y) / 2.0; 61 | MovePen(curX, curY); 62 | UpdateDisplay(); 63 | } 64 | } 65 | 66 | int main(){ 67 | vector pvec(3); 68 | 69 | InitGraphics(); 70 | Randomize(); 71 | 72 | getInitPoints(pvec); 73 | drawTriangle(pvec); 74 | chaoGame(pvec); 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /cs144/router/sr_utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2009 Roger Liao 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions 7 | * are met: 8 | * 1. Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * 2. Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in the 12 | * documentation and/or other materials provided with the distribution. 13 | * 14 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 15 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 18 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 20 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 21 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 22 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 23 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 24 | * SUCH DAMAGE. 25 | * 26 | */ 27 | 28 | #ifndef SR_UTILS_H 29 | #define SR_UTILS_H 30 | 31 | uint16_t cksum(const void *_data, int len); 32 | 33 | uint16_t ethertype(uint8_t *buf); 34 | uint8_t ip_protocol(uint8_t *buf); 35 | 36 | void print_addr_eth(uint8_t *addr); 37 | void print_addr_ip(struct in_addr address); 38 | void print_addr_ip_int(uint32_t ip); 39 | 40 | void print_hdr_eth(uint8_t *buf); 41 | void print_hdr_ip(uint8_t *buf); 42 | void print_hdr_icmp(uint8_t *buf); 43 | void print_hdr_arp(uint8_t *buf); 44 | 45 | /* prints all headers, starting from eth */ 46 | void print_hdrs(uint8_t *buf, uint32_t length); 47 | 48 | #endif /* -- SR_UTILS_H -- */ 49 | -------------------------------------------------------------------------------- /book_code/include/dc.h: -------------------------------------------------------------------------------- 1 | #ifndef Calculator_H 2 | #define Calculator_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using std::string; 11 | using std::ostream; 12 | using std::istream; 13 | using std::map; 14 | 15 | namespace Lexer{ 16 | /* 17 | * Token的类型 18 | */ 19 | enum class Kind : char { 20 | name, number, end, 21 | plus='+', minus='-', mul='*', div='/', print=';', assign='=', 22 | lp='(', rp=')' 23 | }; 24 | 25 | /* 26 | * Token结构体,string_value保存name token的值,number_value保存number token的值 27 | */ 28 | struct Token { 29 | Kind kind; 30 | string string_value; 31 | double number_value; 32 | }; 33 | 34 | /* 35 | * 对Token的格式化输出 36 | */ 37 | ostream& operator<<(ostream &os, Token &t); 38 | 39 | /* 40 | * 对Token输入读取的处理器 41 | */ 42 | class Token_stream{ 43 | public: 44 | Token_stream(istream &s):ip{&s}, owns{false}{ ct = {Kind::end};} 45 | Token_stream(istream *p):ip{p}, owns{true}{ ct = {Kind::end}; } 46 | 47 | ~Token_stream(){ close(); } 48 | 49 | Token get(); //获取下一个token 50 | Token& current(); //获取当前的token的引用 51 | 52 | void set_input(istream &s) { close(); ip = &s; owns=false;} 53 | void set_input(istream *p) { close(); ip = p; owns=true;} 54 | 55 | private: 56 | void close() { if(owns) delete ip; } 57 | 58 | istream *ip; //input stream的指针 59 | bool owns; //这个Token_stream是否拥有ip 60 | Token ct; //current token 61 | }; 62 | 63 | extern Token_stream ts; 64 | } 65 | 66 | 67 | namespace Error{ 68 | double error(const string &s); 69 | extern int no_of_errors; 70 | } 71 | 72 | namespace Table{ 73 | extern map table; 74 | } 75 | 76 | namespace Parser{ 77 | double prim(bool); 78 | double term(bool); 79 | double expr(bool); 80 | } 81 | 82 | namespace Dirver{ 83 | void calculate(); 84 | } 85 | 86 | #endif 87 | -------------------------------------------------------------------------------- /cs144/router/Makefile: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------ 2 | # File: Makefile 3 | # 4 | # Note: This Makefile requires GNU make. 5 | # 6 | # (c) 2001,2000 Stanford University 7 | # 8 | #------------------------------------------------------------------------------ 9 | 10 | all : sr 11 | 12 | CC = gcc 13 | 14 | OSTYPE = $(shell uname) 15 | 16 | ifeq ($(OSTYPE),CYGWIN_NT-5.1) 17 | ARCH = -D_CYGWIN_ 18 | endif 19 | 20 | ifeq ($(OSTYPE),Linux) 21 | ARCH = -D_LINUX_ 22 | SOCK = -lnsl -lresolv 23 | endif 24 | 25 | ifeq ($(OSTYPE),SunOS) 26 | ARCH = -D_SOLARIS_ 27 | SOCK = -lnsl -lsocket -lresolv 28 | endif 29 | 30 | ifeq ($(OSTYPE),Darwin) 31 | ARCH = -D_DARWIN_ 32 | SOCK = -lresolv 33 | endif 34 | 35 | CFLAGS = -g -Wall -ansi -D_DEBUG_ -D_GNU_SOURCE $(ARCH) 36 | 37 | LIBS= $(SOCK) -lm -lpthread 38 | PFLAGS= -follow-child-processes=yes -cache-dir=/tmp/${USER} 39 | PURIFY= purify ${PFLAGS} 40 | 41 | # Add any header files you've added here 42 | sr_HDRS = sr_arpcache.h sr_utils.h sr_dumper.h sr_if.h sr_protocol.h sr_router.h sr_rt.h \ 43 | vnscommand.h sha1.h 44 | 45 | # Add any source files you've added here 46 | sr_SRCS = sr_router.c sr_main.c sr_if.c sr_rt.c sr_vns_comm.c sr_utils.c sr_dumper.c \ 47 | sr_arpcache.c sha1.c 48 | 49 | sr_OBJS = $(patsubst %.c,%.o,$(sr_SRCS)) 50 | sr_DEPS = $(patsubst %.c,.%.d,$(sr_SRCS)) 51 | 52 | $(sr_OBJS) : %.o : %.c 53 | $(CC) -c $(CFLAGS) $< -o $@ 54 | 55 | $(sr_DEPS) : .%.d : %.c 56 | $(CC) -MM $(CFLAGS) $< > $@ 57 | 58 | -include $(sr_DEPS) 59 | 60 | sr : $(sr_OBJS) 61 | $(CC) $(CFLAGS) -o sr $(sr_OBJS) $(LIBS) 62 | 63 | sr.purify : $(sr_OBJS) 64 | $(PURIFY) $(CC) $(CFLAGS) -o sr.purify $(sr_OBJS) $(LIBS) 65 | 66 | .PHONY : clean clean-deps dist 67 | 68 | clean: 69 | rm -f *.o *~ core sr *.dump *.tar tags 70 | 71 | clean-deps: 72 | rm -f .*.d 73 | 74 | dist-clean: clean clean-deps 75 | rm -f .*.swp sr_stub.tar.gz 76 | 77 | dist: dist-clean 78 | (cd ..; tar -X stub/exclude -cvf sr_stub.tar stub/; gzip sr_stub.tar); \ 79 | mv ../sr_stub.tar.gz . 80 | 81 | tags: 82 | ctags *.c 83 | 84 | submit: 85 | @tar -czf router-submit.tar.gz $(sr_SRCS) $(sr_HDRS) README Makefile 86 | 87 | -------------------------------------------------------------------------------- /cs106/include/random.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: random.h 3 | * Version: 1.1CPP 4 | * Last modified on Wed Apr 1 07:57:04 2009 by eroberts 5 | * modified on Wed Sep 18 13:32:23 2002 by zelenski 6 | * ----------------------------------------------------- 7 | * This interface provides several functions for generating 8 | * pseudo-random numbers. 9 | */ 10 | 11 | #ifndef _random_h 12 | #define _random_h 13 | 14 | /* 15 | * Function: Randomize 16 | * Usage: Randomize(); 17 | * ------------------- 18 | * This function sets the random seed so that the random sequence 19 | * is unpredictable. If this function is not called, the other 20 | * functions will return the same values on each run. During the 21 | * debugging phase, it is best not to call this function, so that 22 | * program behavior is repeatable. 23 | */ 24 | 25 | void Randomize(); 26 | 27 | /* 28 | * Function: RandomInteger 29 | * Usage: n = RandomInteger(low, high); 30 | * ------------------------------------ 31 | * This function returns a random integer in the range low to high, 32 | * inclusive. 33 | */ 34 | 35 | int RandomInteger(int low, int high); 36 | 37 | /* 38 | * Function: RandomReal 39 | * Usage: d = RandomReal(low, high); 40 | * --------------------------------- 41 | * This function returns a random real number in the half-open 42 | * interval [low .. high), meaning that the result is always 43 | * greater than or equal to low but strictly less than high. 44 | */ 45 | 46 | double RandomReal(double low, double high); 47 | 48 | /* 49 | * Function: RandomChance 50 | * Usage: if (RandomChance(p)) . . . 51 | * --------------------------------- 52 | * The RandomChance function returns true with the probability 53 | * indicated by p, which should be a floating-point number between 54 | * 0 (meaning never) and 1 (meaning always). For example, calling 55 | * RandomChance(.30) returns true 30 percent of the time. 56 | */ 57 | 58 | bool RandomChance(double p); 59 | 60 | /* 61 | * Function: SetRandomSeed 62 | * Usage: SetRandomSeed(seed); 63 | * --------------------------- 64 | * This function sets the internal random number seed to the 65 | * specified value. Clients can use this function to set a 66 | * specific starting point for the pseudorandom sequence. 67 | */ 68 | 69 | void SetRandomSeed(int seed); 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /cs144/router/sr_dumper.h: -------------------------------------------------------------------------------- 1 | /** 2 | * This header file defines data structures for logging packets in tcpdump 3 | * format as well as a set of operations for logging. 4 | */ 5 | 6 | 7 | #ifdef _LINUX_ 8 | #include 9 | #endif /* _LINUX_ */ 10 | 11 | #ifdef _DARWIN_ 12 | #include 13 | #endif /* _DARWIN_ */ 14 | 15 | #include 16 | 17 | #define PCAP_VERSION_MAJOR 2 18 | #define PCAP_VERSION_MINOR 4 19 | #define PCAP_ETHA_LEN 6 20 | #define PCAP_PROTO_LEN 2 21 | 22 | #define TCPDUMP_MAGIC 0xa1b2c3d4 23 | 24 | #define LINKTYPE_ETHERNET 1 25 | 26 | #define min(a,b) ( (a) < (b) ? (a) : (b) ) 27 | 28 | /* file header */ 29 | struct pcap_file_header { 30 | uint32_t magic; /* magic number */ 31 | uint16_t version_major; /* version number major */ 32 | uint16_t version_minor; /* version number minor */ 33 | int thiszone; /* gmt to local correction */ 34 | uint32_t sigfigs; /* accuracy of timestamps */ 35 | uint32_t snaplen; /* max length saved portion of each pkt */ 36 | uint32_t linktype; /* data link type (LINKTYPE_*) */ 37 | }; 38 | 39 | /* packet header */ 40 | struct pcap_pkthdr { 41 | struct timeval ts; /* time stamp */ 42 | uint32_t caplen; /* length of portion present */ 43 | uint32_t len; /* length this packet (off wire) */ 44 | }; 45 | 46 | /* 47 | * This is a timeval as stored in disk in a dumpfile. 48 | * It has to use the same types everywhere, independent of the actual 49 | * `struct timeval' 50 | */ 51 | struct pcap_timeval { 52 | int tv_sec; /* seconds */ 53 | int tv_usec; /* microseconds */ 54 | }; 55 | 56 | 57 | /* 58 | * How a `pcap_pkthdr' is actually stored in the dumpfile. 59 | */ 60 | struct pcap_sf_pkthdr { 61 | struct pcap_timeval ts; /* time stamp */ 62 | uint32_t caplen; /* length of portion present */ 63 | uint32_t len; /* length this packet (off wire) */ 64 | }; 65 | 66 | /** 67 | * Open a dump file and initialize the file. 68 | */ 69 | FILE* sr_dump_open(const char *fname, int thiszone, int snaplen); 70 | 71 | /** 72 | * Write data into the log file 73 | */ 74 | void sr_dump(FILE *fp, const struct pcap_pkthdr *h, const unsigned char *sp); 75 | 76 | /** 77 | * Close the file 78 | */ 79 | void sr_dump_close(FILE *fp); 80 | -------------------------------------------------------------------------------- /book_code/src/lexer.cpp: -------------------------------------------------------------------------------- 1 | #include "dc.h" 2 | 3 | using namespace std; 4 | 5 | ostream& operator<<(ostream &os, Lexer::Token& t){ 6 | switch(t.kind){ 7 | case Lexer::Kind::number: 8 | os << "Number Token : " << t.number_value << endl; 9 | break; 10 | case Lexer::Kind::name: 11 | os << "Name Token : " << t.string_value << endl; 12 | break; 13 | case Lexer::Kind::end: 14 | os << "End token" << endl; 15 | break; 16 | default: 17 | os << "Operator token : " << static_cast(t.kind) << endl; 18 | break; 19 | } 20 | return os; 21 | } 22 | 23 | Lexer::Token_stream Lexer::ts{cin}; 24 | 25 | Lexer::Token Lexer::Token_stream::get(){ 26 | char ch = 0; 27 | 28 | //*ip >> ch; //这种读入方式直到空白字符才结束, 29 | //会导致x=7这种读入处理有误 30 | 31 | do{ //这种读入方式可以获取下一个非空白字符 32 | if(!ip->get(ch)) 33 | return ct = {Kind::end}; 34 | }while(ch != '\n' && isspace(ch)); 35 | 36 | switch(ch){ 37 | case 0: //ch为0标志读入的结束 38 | return ct = {Kind::end}; 39 | case ';': case '\n': 40 | return ct = {Kind::print}; 41 | case '*': case '/': case '+': 42 | case '-': case '(': case ')': 43 | case '=': //利用枚举类型的基本为char类型进行转换 44 | return ct = {static_cast(ch)}; 45 | case '0': case '1': case '2': case '3': case '4': case '5': 46 | case '6': case '7': case '8': case '9': 47 | case '.': //处理数字的时候将第一个字符写回到istream中 48 | ip->putback(ch); 49 | *ip >> ct.number_value; 50 | ct.kind = Kind::number; 51 | return ct; 52 | default: //要处理Name, Name=,或者error三种情况 53 | if(isalpha(ch)){ 54 | ct.string_value = ch; 55 | while(ip->get(ch) && isalnum(ch)) 56 | ct.string_value += ch; 57 | ip->putback(ch); 58 | ct.kind = Kind::name; 59 | return ct; 60 | } 61 | 62 | //error("bad token"); 63 | return ct = {Kind::print}; 64 | } 65 | } 66 | 67 | Lexer::Token& Lexer::Token_stream::current(){ 68 | return ct; 69 | } 70 | -------------------------------------------------------------------------------- /cs106/include/foreach.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: foreach.h 3 | * Last modified on Thu Jun 11 12:04:09 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This interface defines the foreach keyword, which is used to 6 | * simplify iteration. All iterable classes import this interface, 7 | * so clients never need to do so explicitly. 8 | */ 9 | 10 | #ifndef _foreach_h 11 | #define _foreach_h 12 | 13 | #include "genlib.h" 14 | 15 | /* These #includes are for files that contain "in" as a token */ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | /* Redefine the ios constants (one of which is "in") */ 22 | 23 | static const ios::openmode IOS_APP = ios::app; 24 | static const ios::openmode IOS_ATE = ios::ate; 25 | static const ios::openmode IOS_BINARY = ios::binary; 26 | static const ios::openmode IOS_IN = ios::in; 27 | static const ios::openmode IOS_OUT = ios::out; 28 | static const ios::openmode IOS_TRUNC = ios::trunc; 29 | 30 | /* 31 | * Class: FE_Iterator 32 | * ------------------ 33 | * This class is a base class for all Iterators that can work with 34 | * the foreach construct. The only purpose of this class is to make 35 | * it possible to freeing the iterators after they are no longer needed. 36 | * 37 | * Note: FE_Iterator is implemented in lexicon.cpp, which is the only 38 | * iterable class that is not a template class. 39 | */ 40 | 41 | class FE_Iterator { 42 | public: 43 | FE_Iterator(); 44 | ~FE_Iterator(); 45 | }; 46 | 47 | /* 48 | * Class: FE_State 49 | * --------------- 50 | * This class is used to maintain the state of the foreach processing. 51 | * The class itself is essentially private, but the implementations in 52 | * the different classes use the fields directly. 53 | * 54 | * Note: FE_State is implemented in lexicon.cpp, which is the only 55 | * iterable class that is not a template class. 56 | */ 57 | 58 | class FE_State { 59 | public: 60 | int state; 61 | FE_Iterator *iter; 62 | 63 | FE_State(); 64 | ~FE_State(); 65 | }; 66 | 67 | /* 68 | * Macro: foreach 69 | * Usage: foreach (type var in collection) { . . . } 70 | * ------------------------------------------------- 71 | * Provides a much simpler hook to the iterator facility. 72 | */ 73 | 74 | #define foreach(arg) \ 75 | for (FE_State _fe; _fe.state < 2; ) \ 76 | for (arg.foreachHook(_fe); _fe.state++ == 1; _fe.state = 0) 77 | 78 | #define in = 79 | 80 | #endif 81 | -------------------------------------------------------------------------------- /cs106/include/strutils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: strutils.h 3 | * Last modified on Wed Sep 18 13:37:55 2002 by zelenski 4 | * ----------------------------------------------------- 5 | * The strutils.h file defines some useful helper functions 6 | * not included by the C++ string library. These were taken 7 | * from Eric Roberts's original strlib from his text 8 | * _The Art and Science of C_. 9 | */ 10 | 11 | #ifndef _strutils_h 12 | #define _strutils_h 13 | 14 | #include "genlib.h" 15 | 16 | /* 17 | * Function: IntegerToString 18 | * Usage: s = IntegerToString(n); 19 | * ------------------------------ 20 | * This function converts an integer into the corresponding 21 | * string of digits. For example, IntegerToString(123) 22 | * returns "123" as a string. 23 | */ 24 | 25 | string IntegerToString(int num); 26 | 27 | /* 28 | * Function: RealToString 29 | * Usage: s = RealToString(d); 30 | * --------------------------- 31 | * This function converts a floating-point number into the 32 | * corresponding string form. For example, calling 33 | * RealToString(23.45) returns "23.45". 34 | */ 35 | 36 | string RealToString(double num); 37 | 38 | /* 39 | * Function: StringToInteger 40 | * Usage: n = StringToInteger(s); 41 | * ------------------------------ 42 | * This function converts a string of digits into an integer. 43 | * If the string is not a legal integer or contains extraneous 44 | * characters, StringToInteger signals an error condition. 45 | */ 46 | 47 | int StringToInteger(string str); 48 | 49 | /* 50 | * Function: StringToReal 51 | * Usage: d = StringToReal(s); 52 | * --------------------------- 53 | * This function converts a string representing a real number 54 | * into its corresponding value. If the string is not a 55 | * legal floating-point number or if it contains extraneous 56 | * characters, StringToReal signals an error condition. 57 | */ 58 | 59 | double StringToReal(string str); 60 | 61 | /* 62 | * Function: ConvertToLowerCase 63 | * Usage: s = ConvertToLowerCase(s); 64 | * --------------------------------- 65 | * This function returns a new string with all 66 | * alphabetic characters converted to lower case. 67 | */ 68 | 69 | string ConvertToLowerCase(string s); 70 | 71 | /* 72 | * Function: ConvertToUpperCase 73 | * Usage: s = ConvertToUpperCase(s); 74 | * --------------------------------- 75 | * This function returns a new string with all 76 | * alphabetic characters converted to upper case. 77 | */ 78 | 79 | string ConvertToUpperCase(string s); 80 | 81 | #endif 82 | -------------------------------------------------------------------------------- /cs106/gserv/graphicsarea.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * File: graphicsarea.cpp 3 | * Last modified August 2011, by Colin 4 | * ------------------------------------------------- 5 | * The GraphicsArea object is a rectangle within GraphicsHandler::_gScene 6 | * whose only function is to respond to mouse events. 7 | */ 8 | 9 | #include "graphicsarea.h" 10 | 11 | GraphicsArea::GraphicsArea(double sceneWidth, 12 | double sceneHeight) : 13 | QGraphicsRectItem(0, 0, sceneWidth, sceneHeight) 14 | { 15 | this->setPen(QPen(Qt::lightGray)); 16 | this->setPos(0, 0); 17 | 18 | _lastMouseEvent.pos = QPointF(0,0); 19 | _lastMouseEvent.btn = Qt::NoButton; 20 | _lastMouseEvent.pressed = false; 21 | // qDebug() << "Graphics area constructed"; 22 | } 23 | 24 | // Mouse support 25 | 26 | double GraphicsArea::getMouseX() 27 | { 28 | return _lastMouseEvent.pos.x(); 29 | } 30 | 31 | double GraphicsArea::getMouseY() 32 | { 33 | return _lastMouseEvent.pos.y(); 34 | } 35 | 36 | QString GraphicsArea::mouseButtonIsDown() 37 | // WARNING - only accurate if the mouse was within the 38 | // GraphicsArea when pressed 39 | { 40 | if (_lastMouseEvent.pressed) return "TRUE"; 41 | else return "FALSE"; 42 | } 43 | 44 | // re-implemented QGraphicsItem functions 45 | 46 | void GraphicsArea::mousePressEvent(QGraphicsSceneMouseEvent *event) 47 | // WARNING - only works if the mouse was within the 48 | // GraphicsArea when pressed 49 | { 50 | _lastMouseEvent.pos = event->pos(); 51 | _lastMouseEvent.btn = event->button(); 52 | _lastMouseEvent.pressed = true; 53 | // qDebug() << "press" << _lastMouseEvent.pos.x() 54 | // << _lastMouseEvent.pos.y(); 55 | } 56 | 57 | void GraphicsArea::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) 58 | // works after any valid mousePressEvent, even if the pointer moves 59 | // outside the GraphicsArea before release 60 | { 61 | _lastMouseEvent.pos = event->pos(); 62 | _lastMouseEvent.btn = event->button(); 63 | _lastMouseEvent.pressed = false; 64 | // qDebug() << "release" << _lastMouseEvent.pos.x() 65 | // << _lastMouseEvent.pos.y(); 66 | } 67 | 68 | void GraphicsArea::mouseMoveEvent(QGraphicsSceneMouseEvent *event) 69 | // WARNING - only works after a valid mousePressEvent and before 70 | // the matching mouseReleaseEvent. It's unclear how to track 71 | // the mouse more generally (?) 72 | { 73 | _lastMouseEvent.pos = event->pos(); 74 | // qDebug() << "move" << _lastMouseEvent.pos.x() 75 | // << _lastMouseEvent.pos.y(); 76 | } 77 | -------------------------------------------------------------------------------- /cs144/router/sr_router.h: -------------------------------------------------------------------------------- 1 | /*----------------------------------------------------------------------------- 2 | * File: sr_router.h 3 | * Date: ? 4 | * Authors: Guido Apenzeller, Martin Casado, Virkam V. 5 | * Contact: casado@stanford.edu 6 | * 7 | *---------------------------------------------------------------------------*/ 8 | 9 | #ifndef SR_ROUTER_H 10 | #define SR_ROUTER_H 11 | 12 | #include 13 | #include 14 | #include 15 | 16 | #include "sr_protocol.h" 17 | #include "sr_arpcache.h" 18 | 19 | /* we dont like this debug , but what to do for varargs ? */ 20 | #ifdef _DEBUG_ 21 | #define Debug(x, args...) printf(x, ## args) 22 | #define DebugMAC(x) \ 23 | do { int ivyl; for(ivyl=0; ivyl<5; ivyl++) printf("%02x:", \ 24 | (unsigned char)(x[ivyl])); printf("%02x",(unsigned char)(x[5])); } while (0) 25 | #else 26 | #define Debug(x, args...) do{}while(0) 27 | #define DebugMAC(x) do{}while(0) 28 | #endif 29 | 30 | #define INIT_TTL 255 31 | #define PACKET_DUMP_SIZE 1024 32 | 33 | /* forward declare */ 34 | struct sr_if; 35 | struct sr_rt; 36 | 37 | /* ---------------------------------------------------------------------------- 38 | * struct sr_instance 39 | * 40 | * Encapsulation of the state for a single virtual router. 41 | * 42 | * -------------------------------------------------------------------------- */ 43 | 44 | struct sr_instance 45 | { 46 | int sockfd; /* socket to server */ 47 | char user[32]; /* user name */ 48 | char host[32]; /* host name */ 49 | char template[30]; /* template name if any */ 50 | unsigned short topo_id; 51 | struct sockaddr_in sr_addr; /* address to server */ 52 | struct sr_if* if_list; /* list of interfaces */ 53 | struct sr_rt* routing_table; /* routing table */ 54 | struct sr_arpcache cache; /* ARP cache */ 55 | pthread_attr_t attr; 56 | FILE* logfile; 57 | }; 58 | 59 | /* -- sr_main.c -- */ 60 | int sr_verify_routing_table(struct sr_instance* sr); 61 | 62 | /* -- sr_vns_comm.c -- */ 63 | int sr_send_packet(struct sr_instance* , uint8_t* , unsigned int , const char*); 64 | int sr_connect_to_server(struct sr_instance* ,unsigned short , char* ); 65 | int sr_read_from_server(struct sr_instance* ); 66 | 67 | /* -- sr_router.c -- */ 68 | void sr_init(struct sr_instance* ); 69 | void sr_handlepacket(struct sr_instance* , uint8_t * , unsigned int , char* ); 70 | 71 | /* -- sr_if.c -- */ 72 | void sr_add_interface(struct sr_instance* , const char* ); 73 | void sr_set_ether_ip(struct sr_instance* , uint32_t ); 74 | void sr_set_ether_addr(struct sr_instance* , const unsigned char* ); 75 | void sr_print_if_list(struct sr_instance* ); 76 | 77 | #endif /* SR_ROUTER_H */ 78 | -------------------------------------------------------------------------------- /cs106/include/private/map.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/map.h 3 | * Last modified on Fri Jun 5 15:39:52 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the private section of the map.h interface. 6 | * This portion of the class definition is taken out of the map.h 7 | * header so that the client need not have to see all of these 8 | * details. 9 | */ 10 | 11 | public: 12 | 13 | /* 14 | * Legacy method: add 15 | * ------------------ 16 | * Old name for put method. This name was changed for compatibility 17 | * with Java and to emphasize the symmetry between get and put. 18 | */ 19 | void add(string key, ValueType value); 20 | 21 | /* 22 | * Legacy method: getValue 23 | * ----------------------- 24 | * Old name for get method. This name was changed for compatibility 25 | * with Java and to emphasize the symmetry between get and put. 26 | */ 27 | ValueType getValue(string key); 28 | 29 | /* 30 | * Class: Map::Iterator 31 | * ------------------------------ 32 | * This interface defines a nested class within the Map template that 33 | * provides iterator access to the keys contained in the Map. 34 | */ 35 | class Iterator : public FE_Iterator { 36 | public: 37 | Iterator(); 38 | bool hasNext(); 39 | string next(); 40 | 41 | private: 42 | Iterator(Map *mp); 43 | Map *mp; 44 | int bucketIndex; 45 | void *cellPtr; 46 | long timestamp; 47 | void advanceToNextKey(); 48 | friend class Map; 49 | }; 50 | friend class Iterator; 51 | string foreachHook(FE_State & _fe); 52 | 53 | /* 54 | * Deep copying support 55 | * -------------------- 56 | * This copy constructor and operator= are defined to make a 57 | * deep copy, making it possible to pass/return maps by value 58 | * and assign from one map to another. The entire contents of 59 | * the map, including all entries, are copied. Each map 60 | * entry is copied from the original map to the copy using 61 | * assignment (operator=). Making copies is generally avoided 62 | * because of the expense and thus, maps are typically passed by 63 | * reference, however, when a copy is needed, these operations 64 | * are supported. 65 | */ 66 | const Map & operator=(const Map & rhs); 67 | Map(const Map & rhs); 68 | 69 | private: 70 | struct cellT { 71 | string key; 72 | ValueType value; 73 | cellT *next; 74 | }; 75 | 76 | Vector buckets; 77 | int numEntries; 78 | long timestamp; 79 | 80 | void initBuckets(int nBuckets); 81 | void deleteBuckets(Vector & bucketsToDelete); 82 | int hash(string s); 83 | cellT *findCell(cellT *head, string key, cellT **prev = NULL); 84 | void expandAndRehash(); 85 | void copyOtherEntries(const Map & rhs); 86 | -------------------------------------------------------------------------------- /cs106/include/private/grid.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/grid.h 3 | * Last modified on Fri Jun 5 15:40:23 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the private section of the grid.h interface. 6 | * This portion of the class definition is taken out of the grid.h 7 | * header so that the client need not have to see all of these 8 | * details. 9 | */ 10 | 11 | public: 12 | 13 | /* 14 | * Legacy method: operator() 15 | * Usage: grid(0, 0) = grid(1, 1); 16 | * ------------------------------- 17 | * This method overloads () to access elements from this grid. 18 | * It has been superseded by the [] operator and is not used in 19 | * new code. 20 | */ 21 | ElemType & operator()(int row, int col); 22 | 23 | /* 24 | * Class: Grid::GridRow 25 | * ----------------------------- 26 | * This section of the code defines a nested class within the Grid template 27 | * that makes it possible to use traditional subscripting on Grid values. 28 | */ 29 | class GridRow { 30 | public: 31 | GridRow(); 32 | ElemType & operator[](int col); 33 | 34 | private: 35 | GridRow(Grid *gridRef, int index); 36 | Grid *gp; 37 | int row; 38 | friend class Grid; 39 | }; 40 | friend class GridRow; 41 | 42 | /* 43 | * Class: Grid::Iterator 44 | * ------------------------------- 45 | * This interface defines a nested class within the Grid template that 46 | * provides iterator access to the Grid contents. 47 | */ 48 | class Iterator : public FE_Iterator { 49 | public: 50 | Iterator(); 51 | bool hasNext(); 52 | ElemType next(); 53 | 54 | private: 55 | Iterator(Grid *gridRef); 56 | Grid *gp; 57 | int curRow; 58 | int curCol; 59 | long timestamp; 60 | friend class Grid; 61 | }; 62 | friend class Iterator; 63 | ElemType foreachHook(FE_State & _fe); 64 | 65 | /* 66 | * Deep copying support 67 | * -------------------- 68 | * This copy constructor and operator= are defined to make a 69 | * deep copy, making it possible to pass/return grids by value 70 | * and assign from one grid to another. The entire contents of 71 | * the grid, including all elements, are copied. Each grid 72 | * element is copied from the original grid to the copy using 73 | * assignment (operator=). Making copies is generally avoided 74 | * because of the expense and thus, grids are typically passed by 75 | * reference, however, when a copy is needed, these operations 76 | * are supported. 77 | */ 78 | const Grid & operator=(const Grid & rhs); 79 | Grid(const Grid & rhs); 80 | 81 | private: 82 | 83 | ElemType *elements; 84 | int nRows, nCols; 85 | long timestamp; 86 | 87 | void checkRange(int row, int col); 88 | void copyContentsFrom(const Grid & other); 89 | -------------------------------------------------------------------------------- /cs144/router/sr_router.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * file: sr_router.c 3 | * date: Mon Feb 18 12:50:42 PST 2002 4 | * Contact: casado@stanford.edu 5 | * 6 | * Description: 7 | * 8 | * This file contains all the functions that interact directly 9 | * with the routing table, as well as the main entry method 10 | * for routing. 11 | * 12 | **********************************************************************/ 13 | 14 | #include 15 | #include 16 | 17 | 18 | #include "sr_if.h" 19 | #include "sr_rt.h" 20 | #include "sr_router.h" 21 | #include "sr_protocol.h" 22 | #include "sr_arpcache.h" 23 | #include "sr_utils.h" 24 | 25 | /*--------------------------------------------------------------------- 26 | * Method: sr_init(void) 27 | * Scope: Global 28 | * 29 | * Initialize the routing subsystem 30 | * 31 | *---------------------------------------------------------------------*/ 32 | 33 | void sr_init(struct sr_instance* sr) 34 | { 35 | /* REQUIRES */ 36 | assert(sr); 37 | 38 | /* Initialize cache and cache cleanup thread */ 39 | sr_arpcache_init(&(sr->cache)); 40 | 41 | pthread_attr_init(&(sr->attr)); 42 | pthread_attr_setdetachstate(&(sr->attr), PTHREAD_CREATE_JOINABLE); 43 | pthread_attr_setscope(&(sr->attr), PTHREAD_SCOPE_SYSTEM); 44 | pthread_attr_setscope(&(sr->attr), PTHREAD_SCOPE_SYSTEM); 45 | pthread_t thread; 46 | 47 | pthread_create(&thread, &(sr->attr), sr_arpcache_timeout, sr); 48 | 49 | /* Add initialization code here! */ 50 | 51 | } /* -- sr_init -- */ 52 | 53 | /*--------------------------------------------------------------------- 54 | * Method: sr_handlepacket(uint8_t* p,char* interface) 55 | * Scope: Global 56 | * 57 | * This method is called each time the router receives a packet on the 58 | * interface. The packet buffer, the packet length and the receiving 59 | * interface are passed in as parameters. The packet is complete with 60 | * ethernet headers. 61 | * 62 | * Note: Both the packet buffer and the character's memory are handled 63 | * by sr_vns_comm.c that means do NOT delete either. Make a copy of the 64 | * packet instead if you intend to keep it around beyond the scope of 65 | * the method call. 66 | * 67 | *---------------------------------------------------------------------*/ 68 | 69 | void sr_handlepacket(struct sr_instance* sr, 70 | uint8_t * packet/* lent */, 71 | unsigned int len, 72 | char* interface/* lent */) 73 | { 74 | /* REQUIRES */ 75 | assert(sr); 76 | assert(packet); 77 | assert(interface); 78 | 79 | printf("*** -> Received packet of length %d \n",len); 80 | 81 | /* fill in code here */ 82 | 83 | }/* end sr_ForwardPacket */ 84 | 85 | -------------------------------------------------------------------------------- /cs106/gserv/gwin.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: gwin.cpp 3 | * Last modified September 2011 by Colin 4 | * ------------------------------------------------------- 5 | * Interface definition for the gWin object 6 | */ 7 | 8 | #ifndef gWin_H 9 | #define gWin_H 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include "cs106graphics.h" 25 | 26 | #define VERSION "CS106 Graphics Server version 0.3.1" 27 | 28 | QT_BEGIN_NAMESPACE 29 | class QLabel; 30 | class QTcpServer; 31 | class QTcpSocket; 32 | class GraphicsHandler; 33 | QT_END_NAMESPACE 34 | 35 | class gWin : public QMainWindow 36 | { 37 | Q_OBJECT 38 | 39 | public: 40 | gWin(int port, QString host, bool showTextArea, QWidget *parent = 0); 41 | ~gWin(); 42 | void setWinTitle(QString title); 43 | QString getWinTitle(); 44 | void setWinSize(int w, int h); 45 | QString getWinSize(bool needsConversion, double resolution); 46 | void updateWin(); 47 | 48 | private slots: 49 | void sessionOpened(); 50 | void newConn(); 51 | void exchangeMsgs(); 52 | void appendText(QString s); 53 | void fixWinSize(); 54 | 55 | // menuBar methods 56 | void savePicture(); 57 | void saveLog(); 58 | void copyPic(); 59 | void helpAbout(); 60 | void aboutQt(); 61 | void showDebug(); 62 | void hideDebug(); 63 | 64 | private: 65 | void setupUi(); 66 | void setupDebug(); 67 | void setupMenus(); 68 | void toggleDebug(bool on); 69 | 70 | QVBoxLayout *verticalLayout; 71 | QGraphicsView *graphicsView; 72 | QGraphicsScene *graphicsScene; 73 | QTextEdit *textEdit; 74 | QTcpServer *tcpServer; 75 | QTcpSocket *clientConnection; 76 | GraphicsHandler *graphicsHandler; 77 | QStatusBar *statBar; 78 | int _port; 79 | QString _host; 80 | bool _showTextArea; 81 | QDockWidget *_debugDock; 82 | QLabel *_connMsg; 83 | // QDialog *aboutDlg; 84 | 85 | // menuBar items 86 | QMenu *fileMenu; 87 | QMenu *editMenu; 88 | QMenu *helpMenu; 89 | QAction *savePicAct; 90 | QAction *saveLogAct; 91 | QAction *exitAct; 92 | QAction *copyPicAct; 93 | QAction *helpAboutAct; 94 | QAction *aboutQtAct; 95 | QActionGroup *debugGroup; 96 | QAction *showDebugAct; 97 | QAction *hideDebugAct; 98 | }; 99 | 100 | #endif // gWin_H 101 | -------------------------------------------------------------------------------- /cs106/gserv/moc_cs106graphics.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | ** Meta object code from reading C++ file 'cs106graphics.h' 3 | ** 4 | ** Created: Thu Apr 10 09:20:39 2014 5 | ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1) 6 | ** 7 | ** WARNING! All changes made in this file will be lost! 8 | *****************************************************************************/ 9 | 10 | #include "cs106graphics.h" 11 | #if !defined(Q_MOC_OUTPUT_REVISION) 12 | #error "The header file 'cs106graphics.h' doesn't include ." 13 | #elif Q_MOC_OUTPUT_REVISION != 63 14 | #error "This file was generated using the moc from 4.8.1. It" 15 | #error "cannot be used with the include files from this version of Qt." 16 | #error "(The moc has changed too much.)" 17 | #endif 18 | 19 | QT_BEGIN_MOC_NAMESPACE 20 | static const uint qt_meta_data_GraphicsHandler[] = { 21 | 22 | // content: 23 | 6, // revision 24 | 0, // classname 25 | 0, 0, // classinfo 26 | 0, 0, // methods 27 | 0, 0, // properties 28 | 0, 0, // enums/sets 29 | 0, 0, // constructors 30 | 0, // flags 31 | 0, // signalCount 32 | 33 | 0 // eod 34 | }; 35 | 36 | static const char qt_meta_stringdata_GraphicsHandler[] = { 37 | "GraphicsHandler\0" 38 | }; 39 | 40 | void GraphicsHandler::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) 41 | { 42 | Q_UNUSED(_o); 43 | Q_UNUSED(_id); 44 | Q_UNUSED(_c); 45 | Q_UNUSED(_a); 46 | } 47 | 48 | const QMetaObjectExtraData GraphicsHandler::staticMetaObjectExtraData = { 49 | 0, qt_static_metacall 50 | }; 51 | 52 | const QMetaObject GraphicsHandler::staticMetaObject = { 53 | { &QObject::staticMetaObject, qt_meta_stringdata_GraphicsHandler, 54 | qt_meta_data_GraphicsHandler, &staticMetaObjectExtraData } 55 | }; 56 | 57 | #ifdef Q_NO_DATA_RELOCATION 58 | const QMetaObject &GraphicsHandler::getStaticMetaObject() { return staticMetaObject; } 59 | #endif //Q_NO_DATA_RELOCATION 60 | 61 | const QMetaObject *GraphicsHandler::metaObject() const 62 | { 63 | return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; 64 | } 65 | 66 | void *GraphicsHandler::qt_metacast(const char *_clname) 67 | { 68 | if (!_clname) return 0; 69 | if (!strcmp(_clname, qt_meta_stringdata_GraphicsHandler)) 70 | return static_cast(const_cast< GraphicsHandler*>(this)); 71 | return QObject::qt_metacast(_clname); 72 | } 73 | 74 | int GraphicsHandler::qt_metacall(QMetaObject::Call _c, int _id, void **_a) 75 | { 76 | _id = QObject::qt_metacall(_c, _id, _a); 77 | if (_id < 0) 78 | return _id; 79 | return _id; 80 | } 81 | QT_END_MOC_NAMESPACE 82 | -------------------------------------------------------------------------------- /cs106/assign2/partA.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "random.h" 9 | 10 | using namespace std; 11 | 12 | class TextAnalyser{ 13 | private: 14 | string curSeed; 15 | map > occur; 16 | int order; 17 | 18 | public: 19 | TextAnalyser(ifstream& ifs, int order); 20 | string randomText(); 21 | string getMaxOccur(); 22 | }; 23 | 24 | ifstream& consoleOpenFile(ifstream& ifs){ 25 | for(;;){ 26 | string scoreFile; 27 | cout << "Enter score file : "; 28 | cin >> scoreFile; 29 | ifs.open(scoreFile, ifstream::in); 30 | if((ifs.rdstate() & ifstream::failbit) == 0) //检测是否成功打开文件 31 | break; 32 | cout << "cannot open file " << scoreFile << endl; 33 | } 34 | return ifs; 35 | } 36 | 37 | TextAnalyser::TextAnalyser(ifstream& ifs, int order) 38 | : order{order} 39 | { 40 | list clist{}; 41 | char c; 42 | string seed; 43 | 44 | while(clist.size() < order){ 45 | ifs.get(c); 46 | clist.push_back(c); 47 | } 48 | while(!ifs.eof()){ 49 | ifs.get(c); 50 | seed = string(clist.begin(), clist.end()); 51 | this->occur[seed].push_back(c); 52 | clist.push_back(c); 53 | clist.pop_front(); 54 | } 55 | } 56 | 57 | string TextAnalyser::getMaxOccur(){ 58 | string maxOccurStr; 59 | int maxOccur = 0; 60 | for(auto o : this->occur){ 61 | if(o.second.size() > maxOccur){ 62 | maxOccurStr = o.first; 63 | maxOccur = o.second.size(); 64 | } 65 | } 66 | return maxOccurStr; 67 | } 68 | 69 | string TextAnalyser::randomText(){ 70 | string seed = this->getMaxOccur(); 71 | string text{seed}; 72 | list clist{}; 73 | 74 | for(char c : seed){ 75 | clist.push_back(c); 76 | } 77 | 78 | while(text.size() < 2000){ 79 | if(this->occur.find(seed) == this->occur.end()){ 80 | return text; 81 | } 82 | vector& charCollect = this->occur[seed]; 83 | int i = RandomInteger(0, charCollect.size()); 84 | text.push_back(charCollect[i]); 85 | 86 | clist.push_back(charCollect[i]); 87 | clist.pop_front(); 88 | seed.assign(clist.begin(), clist.end()); 89 | } 90 | 91 | return text; 92 | } 93 | 94 | int main(){ 95 | int order; 96 | ifstream ifs; 97 | 98 | Randomize(); 99 | consoleOpenFile(ifs); 100 | cout << "Enter order: "; 101 | cin >> order; 102 | 103 | TextAnalyser ta{ifs, order}; 104 | 105 | cout << ta.randomText() << endl; 106 | 107 | ifs.close(); 108 | return 0; 109 | } 110 | -------------------------------------------------------------------------------- /cs106/include/private/queue.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/queue.cpp 3 | * Last modified on Tue Jun 9 07:53:03 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the implementation of the queue.h interface. 6 | * Because of the way C++ compiles templates, this code must be 7 | * available to the compiler when it reads the header file. 8 | */ 9 | 10 | #ifdef _queue_h 11 | 12 | /* 13 | * Queue class implementation 14 | * -------------------------- 15 | * The Queue is internally managed as a singly linked list of cells, with a 16 | * head and tail pointer. The front of the queue is at the head; the end 17 | * is at the tail. 18 | */ 19 | 20 | template 21 | Queue::Queue() { 22 | head = tail = NULL; 23 | count = 0; 24 | } 25 | 26 | template 27 | Queue::~Queue() { 28 | deleteCells(); 29 | } 30 | 31 | template 32 | int Queue::size() { 33 | return count; 34 | } 35 | 36 | template 37 | bool Queue::isEmpty() { 38 | return count == 0; 39 | } 40 | 41 | template 42 | void Queue::enqueue(ElemType elem) { 43 | cellT *newOne = new cellT; 44 | newOne->elem = elem; 45 | newOne->next = NULL; 46 | if (head != NULL) { 47 | tail->next = newOne; 48 | } else { 49 | head = newOne; 50 | } 51 | tail = newOne; 52 | count++; 53 | } 54 | 55 | template 56 | ElemType Queue::dequeue() { 57 | if (isEmpty()) Error("Attempt to dequeue from empty queue"); 58 | ElemType first = head->elem; 59 | cellT *toDelete = head; 60 | head = head->next; 61 | delete toDelete; 62 | count--; 63 | return first; 64 | } 65 | 66 | template 67 | ElemType Queue::peek() { 68 | if (isEmpty()) Error("Attempt to peek at empty queue"); 69 | return head->elem; 70 | } 71 | 72 | template 73 | void Queue::clear() { 74 | deleteCells(); 75 | count = 0; 76 | } 77 | 78 | template 79 | void Queue::deleteCells() { 80 | while (head != NULL) { 81 | cellT *next = head->next; 82 | delete head; 83 | head = next; 84 | } 85 | tail = NULL; 86 | } 87 | 88 | template 89 | const Queue &Queue::operator=(const Queue & rhs) { 90 | if (this != &rhs) { 91 | clear(); 92 | copyOtherData(rhs); 93 | } 94 | return *this; 95 | } 96 | 97 | template 98 | Queue::Queue(const Queue & rhs) { 99 | head = tail = NULL; 100 | count = 0; 101 | copyOtherData(rhs); 102 | } 103 | 104 | template 105 | void Queue::copyOtherData(const Queue & rhs) { 106 | for (cellT *cur = rhs.head; cur != NULL; cur = cur->next) { 107 | enqueue(cur->elem); 108 | } 109 | } 110 | #endif 111 | -------------------------------------------------------------------------------- /cs106/include/genlib.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: genlib.h 3 | * Last modified on Sun Jul 17 2011 by Colin Leach 4 | * modified on Mon Jun 8 20:16:05 2009 by eroberts 5 | * modified on Wed Sep 18 13:41:31 2002 by zelenski 6 | * ----------------------------------------------------- 7 | * This header file is indicated to be included in 8 | * all the programs written for CS106B/X and provides a few 9 | * common definitions. Note this header has a "using namespace std" 10 | * clause. If a file includes this header, it can then use 11 | * features from the std namespace without qualifying by scope. 12 | * 13 | * IMPORTANT!! I had to change the interface after failing to 14 | * implement the Stanford version. Hence the genlib.h bundled 15 | * with CS106B exercises is NOT compatible - don't use it with 16 | * Colin's open-source library code. 17 | * Apologies for the inconvenience, but I'm a C++ novice doing 18 | * the best I can. 19 | */ 20 | 21 | #ifndef _genlib_h 22 | #define _genlib_h 23 | 24 | /* This strange-looking pragma is here to disable a warning from Visual C++ 25 | * about truncating long identifiers for debugging symbols. The warning is 26 | * harmless, but a little disconcerting, so we suppress it. It comes up 27 | * using STL and other long template expansions. 28 | */ 29 | #if defined(_MSC_VER) 30 | #pragma warning(disable: 4786) 31 | #endif 32 | 33 | #include 34 | #include 35 | using namespace std; 36 | 37 | /* 38 | * Class: ErrorException 39 | * --------------------- 40 | * This exception is raised by calls to the Error function, which 41 | * makes it possible for clients to respond to error conditions 42 | * without having their programs bomb completely. 43 | */ 44 | 45 | class ErrorException : public exception { 46 | public: 47 | ErrorException(string msg); 48 | virtual ~ErrorException() throw (); 49 | virtual const char* what() const throw (); 50 | //virtual string getMessage(); 51 | private: 52 | string msg; 53 | }; 54 | 55 | /* 56 | * Function: Error 57 | * Usage: Error(msg); 58 | * ------------------ 59 | * Error is used to signal an error condition in a program. It first 60 | * throws an ErrorException. If that isn't caught, it outputs the 61 | * error message string to the cerr stream and then exits the program 62 | * with a status code indicating failure. 63 | */ 64 | 65 | void Error(string str); 66 | 67 | /* 68 | * Function macro: main 69 | * -------------------- 70 | * The purpose of this macro definition is to rename the student 71 | * main to Main in order to allow a custom main defined in our 72 | * libraries to configure the application before passing control 73 | * back to the student program. 74 | * 75 | * Note that this non-Stanford version only affects the zero-argument 76 | * form of main(), not main(int argc, char* argv[]). 77 | * If you want to use command-line arguments, you also have to catch 78 | * your own ErrorException - see init.h/init.cpp for details. 79 | */ 80 | 81 | #define main() Main() 82 | 83 | #endif 84 | -------------------------------------------------------------------------------- /cs106/include/private/bst.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/bst.h 3 | * Last modified on Fri Jun 5 15:40:43 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the private section of the bst.h interface. 6 | * This portion of the class definition is taken out of the bst.h 7 | * header so that the client need not have to see all of these 8 | * details. 9 | */ 10 | 11 | public: 12 | 13 | /* 14 | * Class: BST::Iterator 15 | * ------------------------------ 16 | * This interface defines a nested class within the BST template that 17 | * provides iterator access to the keys contained in the BST. 18 | */ 19 | 20 | class Iterator { 21 | public: 22 | Iterator(); 23 | bool hasNext(); 24 | ElemType next(); 25 | 26 | private: 27 | struct iteratorMarkerT { 28 | void *np; 29 | bool processed; 30 | }; 31 | 32 | Iterator(BST *bstp); 33 | BST *bstp; 34 | Stack stack; 35 | long timestamp; 36 | void advanceToNextNode(); 37 | void findLeftmostChild(); 38 | friend class BST; 39 | }; 40 | friend class Iterator; 41 | ElemType foreachHook(FE_State & _fe); 42 | 43 | /* 44 | * Deep copying support 45 | * -------------------- 46 | * This copy constructor and operator= are defined to make a 47 | * deep copy, making it possible to pass/return trees by value 48 | * and assign from one tree to another. The entire contents of 49 | * the tree, including all elements, are copied. Each tree 50 | * element is copied from the original tree to the copy using 51 | * assignment (operator=). Making copies is generally avoided 52 | * because of the expense and thus, trees are typically passed 53 | * by reference, however, when a copy is needed, these operations 54 | * are supported. 55 | */ 56 | const BST & operator=(const BST & rhs); 57 | BST(const BST & rhs); 58 | 59 | private: 60 | 61 | /* Type definition for node in the tree */ 62 | struct nodeT { 63 | ElemType data; 64 | nodeT *left, *right; 65 | int bf; /* AVL balance factor */ 66 | }; 67 | 68 | /* Constant definitions */ 69 | static const int BST_RIGHT_HEAVY = +1; 70 | static const int BST_IN_BALANCE = 0; 71 | static const int BST_LEFT_HEAVY = -1; 72 | 73 | /* Instance variables */ 74 | nodeT *root; 75 | int numNodes; 76 | long timestamp; 77 | int (*cmpFn)(ElemType, ElemType); 78 | 79 | /* Private method prototypes */ 80 | nodeT *recFindNode(nodeT *t, ElemType & key); 81 | bool recAddNode(nodeT * & t, ElemType & key, bool & createdNewNode); 82 | bool recRemoveNode(nodeT * & t, ElemType & key, bool & didRemove); 83 | bool removeTargetNode(nodeT * & t); 84 | void updateBF(nodeT * & t, int bfDelta); 85 | void recDeleteTree(nodeT *t); 86 | void recBSTAll(nodeT *t, void (*fn)(ElemType)); 87 | void fixRightImbalance(nodeT * & t); 88 | void fixLeftImbalance(nodeT * & t); 89 | void rotateRight(nodeT * & t); 90 | void rotateLeft(nodeT * & t); 91 | void copyOtherEntries(const BST & other); 92 | 93 | /* Template method prototypes */ 94 | 95 | template 96 | void recBSTAll(nodeT *t, void (*fn)(ElemType, ClientDataType &), 97 | ClientDataType & data); 98 | -------------------------------------------------------------------------------- /book_code/src/parser.cpp: -------------------------------------------------------------------------------- 1 | #include "dc.h" 2 | 3 | using namespace Lexer; 4 | using namespace Table; 5 | using namespace Error; 6 | 7 | /* 8 | * Calculator的语法结构如下: 9 | * program: 10 | * end 11 | * expr_list end 12 | * 13 | * expr_list: 14 | * expression print 15 | * expression print expr_list 16 | * 17 | * expression: //expression + term作为expression是一种自身递归的形式 18 | * expression + term 19 | * expression - term 20 | * term 21 | * 22 | * term: 23 | * term / primary 24 | * term * primary 25 | * primary 26 | * 27 | * primary: //在primary中用到expression是一种循环递归的方式 28 | * number 29 | * name 30 | * name = expression 31 | * -primary 32 | * ( expression ) 33 | * ------------------------------ 34 | * prim, term, expr分别对应primary, term, expression的解析函数 35 | * 这些函数的get参数判断进行解析前是否需要从Token_stream中读取下一个token 36 | * 默认的情况下是不需要的,因为在main函数开始的时候已经进行了ts.get() 37 | * 但是在进行局部解析的时候需要针对情况决定是否读取. 38 | * 处理的方式基本跟上面的语法结构解析相似 39 | * 40 | * 每一次switch都是针对ts.current()是因为在这些函数处理后都会读下一个token 41 | * 42 | */ 43 | double Parser::prim(bool get){ 44 | if(get) 45 | ts.get(); 46 | 47 | switch(ts.current().kind){ 48 | case Kind::number:{ 49 | double v = ts.current().number_value; 50 | ts.get(); 51 | return v; 52 | } 53 | case Kind::name:{ 54 | double &v = table[ts.current().string_value]; 55 | if(ts.get().kind == Kind::assign) 56 | v = expr(true); 57 | return v; 58 | } 59 | case Kind::minus: 60 | return -prim(true); 61 | case Kind::lp:{ 62 | double e = expr(true); 63 | if(ts.current().kind != Kind::rp) 64 | return error("')' expected"); 65 | ts.get(); //吃掉右括号')' 66 | return e; 67 | } 68 | default: 69 | return error("primary expected"); 70 | } 71 | } 72 | 73 | double Parser::term(bool get){ 74 | double left = prim(get); 75 | 76 | for(;;){ //死循环用以处理连乘连除的情况 77 | switch(ts.current().kind){ 78 | case Kind::mul: 79 | left *= prim(true); 80 | break; 81 | case Kind::div: //除0判断 82 | if(auto d = prim(true)){ 83 | left /= d; 84 | break; 85 | } 86 | return error("divide by 0"); 87 | default: 88 | return left; 89 | } 90 | } 91 | } 92 | 93 | double Parser::expr(bool get){ 94 | double left = term(get); 95 | 96 | for(;;){ 97 | switch(ts.current().kind){ 98 | case Kind::plus: 99 | left += term(true); 100 | break; 101 | case Kind::minus: 102 | left -= term(true); 103 | break; 104 | default: 105 | return left; 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /cs106/assign4/gboggle.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: gboggle.h 3 | * --------------- 4 | * The gboggle.h file defines the interface for a set of 5 | * functions that 6 | * 7 | * 1. Draw the boggle board 8 | * 2. Manage the word lists 9 | * 3. Update the scoreboard 10 | */ 11 | 12 | #ifndef _gboggle_h 13 | #define _gboggle_h 14 | 15 | #include "genlib.h" 16 | 17 | /* 18 | * Type: playerT 19 | * ------------- 20 | * This enumeration distinguishes the human and computer players. 21 | */ 22 | enum playerT {Human, Computer}; 23 | 24 | 25 | /* 26 | * Constant: MAX_DIMENSION 27 | * ----------------------- 28 | * This constant determines the largest acceptable values for the board dimensions. 29 | */ 30 | const int MAX_DIMENSION = 5; 31 | 32 | /* 33 | * Function: DrawBoard 34 | * Usage: DrawBoard(4, 4); 35 | * ----------------------- 36 | * This function draws the empty layout of the board having the 37 | * specified dimensions. It should be called once at the beginning 38 | * of each game, after calling InitGraphics() to erase the graphics 39 | * window. It will draw the cubes, board, and scoreboard labels. 40 | * The scores and word lists are set to zero. The boggle cubes are 41 | * drawn with blank faces, ready for letters to be set using the 42 | * LabelCube function. If either dimension is <= 0 or > MAX_DIMENSION, 43 | * an error is raised. 44 | */ 45 | void DrawBoard(int numRows, int numCols); 46 | 47 | /* 48 | * Function: LabelCube 49 | * Usage: LabelCube(row, col, letter); 50 | * ----------------------------------- 51 | * This function draws the specified letter on the face of the cube 52 | * at position (row, col). The cubes are numbered from top to bottom 53 | * left to right starting with zero. Therefore, the upper left corner is 54 | * is (0, 0); the lower right is (numRows-1, numCols-1). Thus, the call 55 | * 56 | * LabelCube(0, 3, 'D'); 57 | * 58 | * would put a D in the top right corner cube. An error is raised if 59 | * row or col is out of range for this boggle board. 60 | */ 61 | void LabelCube(int row, int col, char letter); 62 | 63 | 64 | /* 65 | * Function: HighlightCube 66 | * Usage: HighlightCube(row, col, flag); 67 | * ------------------------------------- 68 | * This function highlights or unhighlights the specified cube 69 | * according to the setting of flag: if flag is true, the cube 70 | * is highlighted; if flag is false, the highlight is removed. 71 | * The highlight flag makes it possible for you to show which 72 | * cubes are using when forming a word on the board. An error is 73 | * raised if row or col is out of range for this boggle board. 74 | */ 75 | void HighlightCube(int row, int col, bool flag); 76 | 77 | 78 | /* 79 | * Function: RecordWordForPlayer 80 | * Usage: RecordWordForPlayer(word, player); 81 | * ----------------------------------------- 82 | * This function records the specified word by adding it to 83 | * the screen display for the specified player and updating 84 | * the scoreboard accordingly. Scoring is calculated as 85 | * follows: a 4-letter word is worth 1 point, a 5-letter 86 | * is worth 2 points, and so on. An error is raised if player 87 | * is not a valid value for playerT (Human or Computer). 88 | */ 89 | void RecordWordForPlayer(string word, playerT player); 90 | 91 | 92 | #endif 93 | -------------------------------------------------------------------------------- /cs106/include/queue.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: queue.h 3 | * Last modified on Fri Jun 5 15:36:11 2009 by eroberts 4 | * modified on Tue Jan 2 13:51:36 2007 by zelenski 5 | * ----------------------------------------------------- 6 | * This interface file contains the Queue class template, 7 | * which provides a linear FIFO collection. 8 | */ 9 | 10 | #ifndef _queue_h 11 | #define _queue_h 12 | 13 | #include "genlib.h" 14 | 15 | /* 16 | * Class: Queue 17 | * ------------ 18 | * This interface defines a class that models a queue, or waiting 19 | * line. It is a linear collection managed in first-in-first-out 20 | * order. Values are added to the end and removed from the front. 21 | * The queue operations are enqueue (add to end) and dequeue (remove 22 | * from front). 23 | * 24 | * For maximum generality, the Queue is supplied as a class template. 25 | * The client specializes the queue to hold values of a specific type, 26 | * e.g. Queue or Queue, as needed 27 | */ 28 | 29 | template 30 | class Queue { 31 | 32 | public: 33 | 34 | /* 35 | * Constructor: Queue 36 | * Usage: Queue queue; 37 | * Queue *qp = new Queue; 38 | * --------------------------------------------- 39 | * The constructor initializes a new empty queue. 40 | */ 41 | Queue(); 42 | 43 | /* 44 | * Destructor: ~Queue 45 | * Usage: delete qp; 46 | * ----------------- 47 | * The destructor deallocates storage associated with this queue. 48 | */ 49 | ~Queue(); 50 | 51 | /* 52 | * Method: size 53 | * Usage: nElems = queue.size(); 54 | * ----------------------------- 55 | * This method returns the number of elements in this queue. 56 | */ 57 | int size(); 58 | 59 | /* 60 | * Method: isEmpty 61 | * Usage: if (queue.isEmpty())... 62 | * ------------------------------- 63 | * This method returns true if this queue contains no 64 | * elements, false otherwise. 65 | */ 66 | bool isEmpty(); 67 | 68 | /* 69 | * Method: enqueue 70 | * Usage: queue.enqueue(element); 71 | * ------------------------------- 72 | * This method adds element to the end of this queue. That 73 | * element becomes the last element in the queue. The queue's size 74 | * increases by one. 75 | */ 76 | void enqueue(ElemType elem); 77 | 78 | /* 79 | * Method: dequeue 80 | * Usage: first = queue.dequeue(); 81 | * ------------------------------- 82 | * This method removes the front element from this queue 83 | * and returns it. The front element is the one that was first 84 | * enqueued. The queue's size decreases by one. This function 85 | * raises an error if called on an empty queue. 86 | */ 87 | ElemType dequeue(); 88 | 89 | /* 90 | * Method: peek 91 | * Usage: first = queue.peek(); 92 | * -------------------------- 93 | * This method returns the value of front element in this 94 | * queue, without removing it. The queue's size is unchanged. 95 | * Raises an error if peek is called on an empty queue. 96 | */ 97 | ElemType peek(); 98 | 99 | /* 100 | * Method: clear 101 | * Usage: queue.clear(); 102 | * --------------------- 103 | * This method removes all elements from this queue. The 104 | * queue is made empty and will have size() = 0. 105 | */ 106 | void clear(); 107 | 108 | private: 109 | 110 | #include "private/queue.h" 111 | 112 | }; 113 | 114 | #include "private/queue.cpp" 115 | 116 | #endif 117 | -------------------------------------------------------------------------------- /cs106/include/stack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: stack.h 3 | * Last modified on Wed Apr 1 08:22:08 2009 by eroberts 4 | * modified on Tue Jan 2 13:40:51 2007 by zelenski 5 | * ----------------------------------------------------- 6 | * This interface file contains the Stack class template, 7 | * which provides a linear LIFO collection. 8 | */ 9 | 10 | #ifndef _stack_h 11 | #define _stack_h 12 | 13 | #include "vector.h" 14 | 15 | /* 16 | * Class: Stack 17 | * ------------ 18 | * This interface defines a class template that models a "stack": 19 | * that is, a linear collection of values stacked one on top of 20 | * the other. Values added and removed only from the top of the stack. 21 | * The fundamental stack operations are push (add to top) and pop 22 | * (remove from top). A stack is said to operate in last-in-first-out 23 | * (LIFO) order. 24 | * 25 | * For maximum generality, the Stack is supplied as a class template. 26 | * The client specializes the stack to hold values of a specific type, 27 | * e.g. Stack or Stack, as needed. 28 | */ 29 | 30 | template 31 | class Stack { 32 | 33 | public: 34 | 35 | /* 36 | * Constructor: Stack 37 | * Usage: Stack stack; 38 | * Stack *sp = new Stack; 39 | * --------------------------------------------- 40 | * The constructor initializes a new empty stack. 41 | */ 42 | Stack(); 43 | 44 | /* 45 | * Destructor: ~Stack 46 | * Usage: delete sp; 47 | * ----------------- 48 | * The destructor deallocates storage associated with this stack. 49 | */ 50 | ~Stack(); 51 | 52 | /* 53 | * Method: size 54 | * Usage: nElems = stack.size(); 55 | * ----------------------------- 56 | * This method returns the number of elements in this stack. 57 | */ 58 | int size(); 59 | 60 | /* 61 | * Method: isEmpty 62 | * Usage: if (stack.isEmpty())... 63 | * ------------------------------- 64 | * This method returns true if this stack contains no 65 | * elements, false otherwise. 66 | */ 67 | bool isEmpty(); 68 | 69 | /* 70 | * Method: push 71 | * Usage: stack.push(element); 72 | * ---------------------------- 73 | * This method pushes the specified element onto this 74 | * stack. That element becomes the top element on the stack. The 75 | * stack's size increases by one. 76 | */ 77 | void push(ElemType elem); 78 | 79 | /* 80 | * Method: pop 81 | * Usage: top = stack.pop(); 82 | * ------------------------- 83 | * This method removes the top element from this stack and 84 | * returns it. The top element is the one that was last pushed. The 85 | * stack's size decreases by one. This function raises an error if 86 | * called on an empty stack. 87 | */ 88 | ElemType pop(); 89 | 90 | /* 91 | * Method: peek 92 | * Usage: top = stack.peek(); 93 | * -------------------------- 94 | * This method returns the value of top element from this 95 | * stack, without removing it. The stack's size is unchanged. 96 | * Raises an error if peek is called on an empty stack. 97 | */ 98 | ElemType peek(); 99 | 100 | /* 101 | * Method: clear 102 | * Usage: stack.clear(); 103 | * --------------------- 104 | * This method removes all elements from this stack. The 105 | * stack is made empty and will have size() = 0. 106 | */ 107 | void clear(); 108 | 109 | private: 110 | 111 | #include "private/stack.h" 112 | 113 | }; 114 | 115 | #include "private/stack.cpp" 116 | 117 | #endif 118 | -------------------------------------------------------------------------------- /cs106/assign2/maze.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * File: maze.cpp 3 | * -------------- 4 | * A maze is mostly a grid of walls. plus a little drawing code. 5 | */ 6 | 7 | #include "maze.h" 8 | #include "extgraph.h" 9 | 10 | Maze::Maze(int numRows, int numCols, bool hasWalls) : cells(numRows, numCols) 11 | { 12 | for (int r = 0; r < numRows; r++) 13 | for (int c = 0; c < numCols; c++) 14 | for (int d = 0; d < NumDirs; d++) 15 | cells(r, c).walls[d] = hasWalls; 16 | configured = false; 17 | } 18 | 19 | int Maze::numRows() 20 | { 21 | return cells.numRows(); 22 | } 23 | 24 | int Maze::numCols() 25 | { 26 | return cells.numCols(); 27 | } 28 | 29 | bool Maze::pointInBounds(pointT p) 30 | { 31 | return (p.row >= 0 && p.row < numRows() && p.col >=0 && p.col < numCols()); 32 | } 33 | 34 | 35 | void Maze::draw() 36 | { 37 | InitGraphics(); // this erases entire graphics window 38 | if (!configured) configureGraphics(); 39 | for (int r = 0; r < cells.numRows(); r++) { 40 | for (int c = 0; c < cells.numCols(); c++) { 41 | pointT p = {r, c}; 42 | drawWallsForCell(p); 43 | } 44 | } 45 | UpdateDisplay(); 46 | } 47 | 48 | bool Maze::isWall(pointT p1, pointT p2) 49 | { 50 | if (!pointInBounds(p1) || !pointInBounds(p2)) 51 | Error("Point is not in bounds for maze"); 52 | return cells(p1.row, p1.col).walls[neighborDir(p1, p2)]; 53 | } 54 | 55 | void Maze::setWall(pointT p1, pointT p2, bool state) 56 | { 57 | if (!pointInBounds(p1) || !pointInBounds(p2)) 58 | Error("Point is not in bounds for maze"); 59 | cells(p1.row, p1.col).walls[neighborDir(p1, p2)] = state; 60 | cells(p2.row, p2.col).walls[neighborDir(p2, p1)] = state; 61 | if (!configured) configureGraphics(); 62 | drawWallsForCell(p1); 63 | UpdateDisplay(); 64 | } 65 | void Maze::drawMark(pointT p, string color) 66 | { 67 | if (!pointInBounds(p)) 68 | Error("Point is not in bounds for maze"); 69 | if (!configured) configureGraphics(); 70 | double margin = cellSize*.3; 71 | double length = cellSize - 2*margin; 72 | SetPenColor(color); 73 | MovePen(originX + p.col*cellSize + margin, originY + p.row*cellSize + margin); 74 | DrawLine(length, length); 75 | MovePen(originX + p.col*cellSize + margin, originY + p.row*cellSize + cellSize - margin); 76 | DrawLine(length, -length); 77 | UpdateDisplay(); 78 | } 79 | 80 | 81 | Maze::dirT Maze::neighborDir(pointT p1, pointT p2) 82 | { 83 | if ((abs(p1.row-p2.row) + abs(p1.col-p2.col)) != 1) 84 | Error("Points are not neighbors"); 85 | if (p1.row != p2.row) 86 | return (p1.row < p2.row ? North : South); 87 | else 88 | return (p1.col < p2.col ? East : West); 89 | } 90 | 91 | void Maze::drawWallsForCell(pointT p) 92 | { 93 | MovePen(originX + p.col*cellSize, originY + p.row*cellSize); 94 | SetPenColor(cells(p.row, p.col).walls[South] ? "Black" : "White"); 95 | DrawLine(cellSize, 0); 96 | SetPenColor(cells(p.row, p.col).walls[East] ? "Black" : "White"); 97 | DrawLine(0, cellSize); 98 | SetPenColor(cells(p.row, p.col).walls[North] ? "Black" : "White"); 99 | DrawLine(-cellSize, 0); 100 | SetPenColor(cells(p.row, p.col).walls[West] ? "Black" : "White"); 101 | DrawLine(0, -cellSize); 102 | } 103 | 104 | void Maze::configureGraphics() 105 | { 106 | cellSize = min(GetWindowWidth()/numCols(), GetWindowHeight()/numRows()); 107 | originX = (GetWindowWidth() - numCols()*cellSize)/2; 108 | originY = (GetWindowHeight() - numRows()*cellSize)/2; 109 | originX = originX >= 0 ? originX : 0; 110 | originY = originY >= 0 ? originY : 0; 111 | configured = true; 112 | } 113 | 114 | 115 | -------------------------------------------------------------------------------- /cs144/router/INSTRUCTIONS: -------------------------------------------------------------------------------- 1 | This document describes the environment for the Mininet sr assignment. You will 2 | login to a virtual topology like this one (the IP addresses will be different, 3 | but the nodes will be arranged identically): 4 | 5 | 6 | Application Server 1 7 | +====================+ 8 | | | 9 | | 107.21.41.195 | 10 | | | 11 | +====================+ 12 | / 13 | / 14 | / 15 | eth3: / 16 | 10.0.1.11 / eth1: 107.23.34.64 17 | +============(eth1)==+ 18 | | | 19 | Internet =============(eth3) Your Router | 20 | | | 21 | +============(eth2)==+ 22 | \ eth2: 107.21.14.129 23 | \ 24 | \ 25 | \ 26 | +====================+ 27 | | | 28 | | 107.21.17.29 | 29 | | | 30 | +====================+ 31 | Application Server 2 32 | 33 | 34 | To connect to a topology, first compile the stub code. 35 | Then, you can invoke sr as follows: 36 | 37 | $ ./sr 38 | 39 | By default, ./sr will connect to the mininet controller on localhost. 40 | If you would like to run "sr" remotely, invoke sr as follows: 41 | 42 | $ ./sr -s 43 | 44 | Your output upon connecting should look like this: 45 | 46 | Using VNS sr stub code revised 2009-10-14 (rev 0.20) 47 | Loading filters 48 | --------------------------------------------- 49 | no filters specified. accepting all connections. 50 | --------------------------------------------- 51 | Client ubuntu connecting to Server localhost:8888 52 | Requesting topology 0 53 | successfully authenticated as ubuntu 54 | Connected to new instantiation of topology 0 55 | Loading routing table 56 | --------------------------------------------- 57 | Destination Gateway Mask Iface 58 | 0.0.0.0 10.0.1.1 0.0.0.0 eth3 59 | 107.21.41.195 107.21.41.195 255.255.255.255 eth1 60 | 107.21.17.29 107.21.17.29 255.255.255.255 eth2 61 | --------------------------------------------- 62 | Router interfaces: 63 | eth3 HWaddr0a:2d:eb:6e:0e:29 64 | inet addr 10.0.1.11 65 | eth2 HWaddr4a:56:b8:89:4c:b6 66 | inet addr 107.21.14.129 67 | eth1 HWaddr5e:c3:6a:dd:e5:c8 68 | inet addr 107.23.34.64 69 | <-- Ready to process packets --> 70 | 71 | 72 | IMPORTANT: The system has more users than IP addresses, so you are not assigned 73 | a particular set of static IP addresses. This means each time you connect you 74 | MAY receive a different set of IP addresses. However, the system remembers the 75 | last IP block assigned to you and will always re-assign it to you unless someone 76 | else is currently using it (in which case you will get a new set of IP 77 | addresses). Your routing table (stored in rtable.vrhost) will be automatically 78 | updated by the stub code. 79 | 80 | Please verify that you can see packets arriving to your topology when you try 81 | and ping one of your router interfaces. To do this, connect to your topology as 82 | described above and try and ping eth0 (e.g., 171.67.238.32 in this example). 83 | 84 | $ ping 171.67.238.32 85 | 86 | You should see output from sr that looks like: 87 | 88 | *** -> Received packet of length 42 89 | *** -> Received packet of length 42 90 | *** -> Received packet of length 42 91 | 92 | If so, everything is working! If not, please post your question on piazza. 93 | 94 | Good Luck! 95 | -------------------------------------------------------------------------------- /cs106/gserv/moc_gwin.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | ** Meta object code from reading C++ file 'gwin.h' 3 | ** 4 | ** Created: Thu Apr 10 09:20:40 2014 5 | ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1) 6 | ** 7 | ** WARNING! All changes made in this file will be lost! 8 | *****************************************************************************/ 9 | 10 | #include "gwin.h" 11 | #if !defined(Q_MOC_OUTPUT_REVISION) 12 | #error "The header file 'gwin.h' doesn't include ." 13 | #elif Q_MOC_OUTPUT_REVISION != 63 14 | #error "This file was generated using the moc from 4.8.1. It" 15 | #error "cannot be used with the include files from this version of Qt." 16 | #error "(The moc has changed too much.)" 17 | #endif 18 | 19 | QT_BEGIN_MOC_NAMESPACE 20 | static const uint qt_meta_data_gWin[] = { 21 | 22 | // content: 23 | 6, // revision 24 | 0, // classname 25 | 0, 0, // classinfo 26 | 12, 14, // methods 27 | 0, 0, // properties 28 | 0, 0, // enums/sets 29 | 0, 0, // constructors 30 | 0, // flags 31 | 0, // signalCount 32 | 33 | // slots: signature, parameters, type, tag, flags 34 | 6, 5, 5, 5, 0x08, 35 | 22, 5, 5, 5, 0x08, 36 | 32, 5, 5, 5, 0x08, 37 | 49, 47, 5, 5, 0x08, 38 | 69, 5, 5, 5, 0x08, 39 | 82, 5, 5, 5, 0x08, 40 | 96, 5, 5, 5, 0x08, 41 | 106, 5, 5, 5, 0x08, 42 | 116, 5, 5, 5, 0x08, 43 | 128, 5, 5, 5, 0x08, 44 | 138, 5, 5, 5, 0x08, 45 | 150, 5, 5, 5, 0x08, 46 | 47 | 0 // eod 48 | }; 49 | 50 | static const char qt_meta_stringdata_gWin[] = { 51 | "gWin\0\0sessionOpened()\0newConn()\0" 52 | "exchangeMsgs()\0s\0appendText(QString)\0" 53 | "fixWinSize()\0savePicture()\0saveLog()\0" 54 | "copyPic()\0helpAbout()\0aboutQt()\0" 55 | "showDebug()\0hideDebug()\0" 56 | }; 57 | 58 | void gWin::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) 59 | { 60 | if (_c == QMetaObject::InvokeMetaMethod) { 61 | Q_ASSERT(staticMetaObject.cast(_o)); 62 | gWin *_t = static_cast(_o); 63 | switch (_id) { 64 | case 0: _t->sessionOpened(); break; 65 | case 1: _t->newConn(); break; 66 | case 2: _t->exchangeMsgs(); break; 67 | case 3: _t->appendText((*reinterpret_cast< QString(*)>(_a[1]))); break; 68 | case 4: _t->fixWinSize(); break; 69 | case 5: _t->savePicture(); break; 70 | case 6: _t->saveLog(); break; 71 | case 7: _t->copyPic(); break; 72 | case 8: _t->helpAbout(); break; 73 | case 9: _t->aboutQt(); break; 74 | case 10: _t->showDebug(); break; 75 | case 11: _t->hideDebug(); break; 76 | default: ; 77 | } 78 | } 79 | } 80 | 81 | const QMetaObjectExtraData gWin::staticMetaObjectExtraData = { 82 | 0, qt_static_metacall 83 | }; 84 | 85 | const QMetaObject gWin::staticMetaObject = { 86 | { &QMainWindow::staticMetaObject, qt_meta_stringdata_gWin, 87 | qt_meta_data_gWin, &staticMetaObjectExtraData } 88 | }; 89 | 90 | #ifdef Q_NO_DATA_RELOCATION 91 | const QMetaObject &gWin::getStaticMetaObject() { return staticMetaObject; } 92 | #endif //Q_NO_DATA_RELOCATION 93 | 94 | const QMetaObject *gWin::metaObject() const 95 | { 96 | return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; 97 | } 98 | 99 | void *gWin::qt_metacast(const char *_clname) 100 | { 101 | if (!_clname) return 0; 102 | if (!strcmp(_clname, qt_meta_stringdata_gWin)) 103 | return static_cast(const_cast< gWin*>(this)); 104 | return QMainWindow::qt_metacast(_clname); 105 | } 106 | 107 | int gWin::qt_metacall(QMetaObject::Call _c, int _id, void **_a) 108 | { 109 | _id = QMainWindow::qt_metacall(_c, _id, _a); 110 | if (_id < 0) 111 | return _id; 112 | if (_c == QMetaObject::InvokeMetaMethod) { 113 | if (_id < 12) 114 | qt_static_metacall(this, _c, _id, _a); 115 | _id -= 12; 116 | } 117 | return _id; 118 | } 119 | QT_END_MOC_NAMESPACE 120 | -------------------------------------------------------------------------------- /cs106/assign2/maze.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: maze.h 3 | * ------------ 4 | * Defines the Maze class. 5 | * Last modified Tue Jan 22 20:19:35 PST 2008 jzelenski 6 | */ 7 | 8 | #ifndef _maze_h 9 | #define _maze_h 10 | 11 | #include "genlib.h" 12 | #include "grid.h" 13 | 14 | /* 15 | * Class: Maze 16 | * ----------- 17 | * This class is used to represent a maze and provide operations to 18 | * query and change the maze configuration. A maze is a rectangular grid 19 | * of cells. Each cell identified by pointT (row-col struct). 20 | * Coordinates in the maze are numbered starting at (0,0) in 21 | * the lower left corner. 22 | * A location has neighbors in the four major compass directions (some 23 | * neighbors may not exist for cells along the outer border). The 24 | * maze tracks which walls are up bewteen a cell and its neighbor. 25 | */ 26 | 27 | 28 | /* 29 | * Type: pointT 30 | * ------------ 31 | * The type pointT is used to encapsulate a pair of integer 32 | * coordinates into a single value with row and col components. 33 | */ 34 | 35 | struct pointT { 36 | int row; 37 | int col; 38 | 39 | pointT() {}; 40 | pointT(const pointT& p) : row{p.row}, col{p.col}{}; 41 | pointT(const pointT&& p) : row{p.row}, col{p.col}{}; 42 | pointT(int row, int col) : row{row}, col{col}{}; 43 | 44 | /* 45 | * 重载<即可判断=,Arow = b.row; 54 | this->col = b.col; 55 | return *this; 56 | } 57 | }; 58 | 59 | 60 | class Maze { 61 | public: 62 | 63 | /* 64 | * Constructor: Maze 65 | * Usage: Maze m(10, 20, true); 66 | * ---------------------------- 67 | * The constructor initializes a new maze of the specified dimensions. 68 | * If the hasWalls argument is true, the maze is initially configured with 69 | * all walls intact. If false, the maze starts with no walls at all. 70 | */ 71 | Maze(int numRows, int numCols, bool hasWalls); 72 | 73 | /* 74 | * Member functions: numRows, numCols 75 | * Usage: nRows = maze.numRows(); 76 | * ------------------------------ 77 | * These member functions return the number of rows or columns in 78 | * this maze. 79 | */ 80 | int numRows(); 81 | int numCols(); 82 | 83 | /* 84 | * Member functions: pointInBounds 85 | * Usage: if (!maze.pointInBounds(pt)) 86 | * ----------------------------------- 87 | * This member function returns true if p is within bounds of this 88 | * maze, false otherwise. 89 | */ 90 | bool pointInBounds(pointT p); 91 | 92 | /* 93 | * Member function: isWall 94 | * Usage: if (maze.isWall(a, b))... 95 | * --------------------------------- 96 | * This member function returns true if there is a wall between 97 | * the two cells at points p1 and p2. If the two points are 98 | * not neighbors or if either is out of bounds, an error is raised. 99 | */ 100 | bool isWall(pointT p1, pointT p2); 101 | 102 | /* 103 | * Member function: setWall 104 | * Usage: maze.setWall(a, b, true); 105 | * -------------------------------- 106 | * This member function sets the wall between cells at points 107 | * p1 and p2 to state. It can be used to either add or remove 108 | * walls. The graphical display is updated to match. If the two 109 | * points are not neighbors or either point is out of bounds, 110 | * an error is raised. 111 | */ 112 | void setWall(pointT p1, pointT p2, bool state); 113 | 114 | 115 | /* 116 | * Member function: draw 117 | * Usage: maze.draw(); 118 | * ------------------- 119 | * This member function draws the maze configuration to the graphics 120 | * window, erasing any previous contents. The lower-left corner is 121 | * the cell identified by 0-0. The maze itself is white and walls are 122 | * drawn with black lines. All previous marks are cleared. 123 | */ 124 | void draw(); 125 | 126 | 127 | /* 128 | * Member function: drawMark 129 | * Usage: maze.drawMark(p, "Red"); 130 | * ------------------------------ 131 | * This member function draws a mark on the cell at point p 132 | * in the specified color. To erase a previous mark, you 133 | * can redraw one in white or use the draw function to reset 134 | * all marks. 135 | */ 136 | void drawMark(pointT p, string color); 137 | 138 | 139 | private: 140 | enum dirT {North, East, South, West, NumDirs}; 141 | struct cellT {bool walls[NumDirs];}; 142 | Grid cells; 143 | double originX, originY, cellSize; 144 | bool configured; 145 | 146 | dirT neighborDir(pointT p1, pointT p2); 147 | void drawWallsForCell(pointT p); 148 | void configureGraphics(); 149 | }; 150 | 151 | #endif 152 | 153 | -------------------------------------------------------------------------------- /cs106/assign2/partB.cpp: -------------------------------------------------------------------------------- 1 | #include "maze.h" 2 | #include "random.h" 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | const int numRows = 10; 10 | const int numCols = 20; 11 | 12 | /* 13 | * 迷宫生成器 14 | * -------------------- 15 | * 使用Aldous-Broder算法 16 | * (1)随机选择矩阵中的一个点作为当前点 17 | * (2)随机选择一个当前点的邻居作为选择点 18 | * (3)如果如果选择点为"excluded",则当前点与选择点之间的墙清除,选择点标记为"included" 19 | * (4)将选择点作为当前点,重复(2)(3)(4)直到所有点都是"included" 20 | */ 21 | class MazeGenerator { 22 | public: 23 | /* 24 | * 构造函数:MazeGenerator 25 | * 用法:MazeGenerator mg(m); 26 | * --------------------- 27 | * 将私有的Maze指针指向m 28 | */ 29 | MazeGenerator(Maze& m); 30 | Maze& generateMaze(); 31 | 32 | private: 33 | pointT getRandomNeighborPoint(pointT p); 34 | Maze* m; 35 | pointT curp; 36 | set pointSet; 37 | }; 38 | 39 | class MazeSolver { 40 | public: 41 | void solveMaze(); 42 | /* 43 | * 构造函数:MazeSolver 44 | * 用法:MazeSolver ms(m); 45 | * --------------------- 46 | * 将私有的Maze指针指向m 47 | * 设定迷宫的起始和结束点 48 | */ 49 | MazeSolver(Maze& m); 50 | 51 | private: 52 | enum dirT {North, West, East, South}; 53 | Maze* m; 54 | pointT startp, endp; 55 | map pointSet; 56 | pointT getPointByDir(pointT, dirT); 57 | }; 58 | 59 | pointT MazeGenerator::getRandomNeighborPoint(pointT p){ 60 | pointT newp{p}; 61 | 62 | for(;;){ 63 | int dir = RandomInteger(0, 4); 64 | switch(dir){ 65 | case 0: //north 66 | newp.row--; 67 | break; 68 | case 1: //south 69 | newp.row++; 70 | break; 71 | case 2: //west 72 | newp.col--; 73 | break; 74 | case 3: //east 75 | newp.col++; 76 | break; 77 | } 78 | if(m->pointInBounds(newp)){ 79 | return newp; 80 | }else{ 81 | newp = p; 82 | } 83 | } 84 | } 85 | 86 | MazeGenerator::MazeGenerator(Maze& m){ 87 | this->m = &m; 88 | } 89 | 90 | Maze& MazeGenerator::generateMaze(){ 91 | Randomize(); 92 | curp.row = RandomInteger(0, m->numRows()); 93 | curp.col = RandomInteger(0, m->numCols()); 94 | pointSet.clear(); 95 | pointSet.insert(curp); 96 | 97 | while(pointSet.size() < m->numRows() * m->numCols()){ 98 | pointT newp{ getRandomNeighborPoint(curp) }; 99 | if(pointSet.find(newp) == pointSet.end()){ //excluded 100 | m->setWall(curp, newp, false); 101 | pointSet.insert(newp); 102 | } 103 | curp = newp; 104 | } 105 | 106 | return *m; 107 | } 108 | 109 | MazeSolver::MazeSolver(Maze& m){ 110 | this->m = &m; 111 | this->startp = {0, 0}; 112 | this->endp = {m.numRows() - 1, m.numCols() - 1}; 113 | } 114 | 115 | pointT MazeSolver::getPointByDir(pointT p, dirT dir){ 116 | pointT newp{p}; 117 | switch(dir){ 118 | case North: 119 | newp.row++; 120 | break; 121 | case South: 122 | newp.row--; 123 | break; 124 | case East: 125 | newp.col++; 126 | break; 127 | case West: 128 | newp.col--; 129 | break; 130 | } 131 | return newp; 132 | } 133 | 134 | /* 135 | * 成员函数:solveMaze 136 | * 用法:ms.solveMaze(); 137 | * -------------------- 138 | * 使用广度优先算法遍历迷宫,pointQueue用来保存遍历的点 139 | * pointSet是一个map,以point为key,方向为value, 140 | * 作用是记录访问点的路径,用于最后逆向生成路径 141 | * 方向是一个枚举类型,相反方向之和为3,可用于计算相反方向 142 | * 143 | */ 144 | void MazeSolver::solveMaze(){ 145 | pointT curp{ startp }; 146 | queue pointQueue; 147 | 148 | pointQueue.push(curp); 149 | bool isStop = false; 150 | while(!isStop && !pointQueue.empty()){ 151 | curp = pointQueue.front(); 152 | pointQueue.pop(); 153 | for(int i = 0; i < 4; i++){ 154 | pointT newp = getPointByDir(curp, static_cast(i)); 155 | if(m->pointInBounds(newp) && 156 | !m->isWall(curp, newp) && 157 | pointSet.find(newp) == pointSet.end()){ 158 | pointSet[newp] = static_cast(i); 159 | pointQueue.push(newp); 160 | } 161 | if(newp.row == endp.row && newp.col == endp.col){ 162 | isStop = true; 163 | break; 164 | } 165 | } 166 | } 167 | 168 | curp = endp; 169 | while(curp.row != startp.row || curp.col != startp.col){ 170 | m->drawMark(curp, "Red"); 171 | dirT reverseDir = static_cast(3 - static_cast(pointSet[curp])); 172 | curp = getPointByDir(curp, reverseDir); 173 | } 174 | m->drawMark(curp, "Red"); 175 | } 176 | 177 | int main(){ 178 | Maze m{numRows, numCols, true}; 179 | MazeGenerator mg{m}; 180 | MazeSolver ms{m}; 181 | 182 | m.draw(); 183 | mg.generateMaze(); 184 | ms.solveMaze(); 185 | 186 | return 0; 187 | } 188 | -------------------------------------------------------------------------------- /cs106/include/graphics.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: graphics.h 3 | * Last modified on Wed Apr 1 07:49:39 2009 by eroberts 4 | * modified on Wed Sep 18 14:37:43 2002 by zelenski 5 | * ----------------------------------------------------- 6 | * This interface provides access to a simple library of 7 | * functions that make it possible to draw lines and arcs 8 | * on the screen. This interface presents a portable 9 | * abstraction that can be used with a variety of window 10 | * systems implemented on different hardware platforms. 11 | */ 12 | 13 | #ifndef _graphics_h 14 | #define _graphics_h 15 | 16 | /* 17 | * Overview 18 | * -------- 19 | * This library provides several functions for drawing lines 20 | * and circular arcs in a region of the screen that is 21 | * defined as the "graphics window." Once drawn, these 22 | * lines and arcs stay in their position, which means that 23 | * the package can only be used for static pictures and not 24 | * for animation. 25 | * 26 | * Individual points within the window are specified by 27 | * giving their x and y coordinates. These coordinates are 28 | * real numbers measured in inches, with the origin in the 29 | * lower left corner, as it is in traditional mathematics. 30 | * 31 | * The calls available in the package are listed below. More 32 | * complete descriptions are included with each function 33 | * description. 34 | * 35 | * InitGraphics(); 36 | * MovePen(x, y); 37 | * DrawLine(dx, dy); 38 | * DrawArc(r, start, sweep); 39 | * width = GetWindowWidth(); 40 | * height = GetWindowHeight(); 41 | * x = GetCurrentX(); 42 | * y = GetCurrentY(); 43 | */ 44 | 45 | /* 46 | * Function: InitGraphics 47 | * Usage: InitGraphics(); 48 | * ---------------------- 49 | * This procedure creates the graphics window on the screen. 50 | * The call to InitGraphics must precede any calls to other 51 | * functions in this package and must also precede any printf 52 | * output. In most cases, the InitGraphics call is the first 53 | * statement in the function main. 54 | */ 55 | 56 | void InitGraphics(); 57 | 58 | /* 59 | * Function: MovePen 60 | * Usage: MovePen(x, y); 61 | * --------------------- 62 | * This procedure moves the current point to the position 63 | * (x, y), without drawing a line. The model is that of 64 | * the pen being lifted off the graphics window surface and 65 | * then moved to its new position. 66 | */ 67 | 68 | void MovePen(double x, double y); 69 | 70 | /* 71 | * Function: DrawLine 72 | * Usage: DrawLine(dx, dy); 73 | * ------------------------ 74 | * This procedure draws a line extending from the current 75 | * point by moving the pen dx inches in the x direction 76 | * and dy inches in the y direction. The final position 77 | * becomes the new current point. 78 | */ 79 | 80 | void DrawLine(double dx, double dy); 81 | 82 | /* 83 | * Function: DrawArc 84 | * Usage: DrawArc(r, start, sweep); 85 | * -------------------------------- 86 | * This procedure draws a circular arc, which always begins 87 | * at the current point. The arc itself has radius r, and 88 | * starts at the angle specified by the parameter start, 89 | * relative to the center of the circle. This angle is 90 | * measured in degrees counterclockwise from the 3 o'clock 91 | * position along the x-axis, as in traditional mathematics. 92 | * For example, if start is 0, the arc begins at the 3 o'clock 93 | * position; if start is 90, the arc begins at the 12 o'clock 94 | * position; and so on. The fraction of the circle drawn is 95 | * specified by the parameter sweep, which is also measured in 96 | * degrees. If sweep is 360, DrawArc draws a complete circle; 97 | * if sweep is 90, it draws a quarter of a circle. If the value 98 | * of sweep is positive, the arc is drawn counterclockwise from 99 | * the current point. If sweep is negative, the arc is drawn 100 | * clockwise from the current point. The current point at the 101 | * end of the DrawArc operation is the final position of the pen 102 | * along the arc. 103 | * 104 | * Examples: 105 | * DrawArc(r, 0, 360) Draws a circle to the left of the 106 | * current point. 107 | * DrawArc(r, 90, 180) Draws the left half of a semicircle 108 | * starting from the 12 o'clock position. 109 | * DrawArc(r, 0, 90) Draws a quarter circle from the 3 110 | * o'clock to the 12 o'clock position. 111 | * DrawArc(r, 0, -90) Draws a quarter circle from the 3 112 | * o'clock to the 6 o'clock position. 113 | * DrawArc(r, -90, -90) Draws a quarter circle from the 6 114 | * o'clock to the 9 o'clock position. 115 | */ 116 | 117 | void DrawArc(double r, double start, double sweep); 118 | 119 | /* 120 | * Functions: GetWindowWidth, GetWindowHeight 121 | * Usage: width = GetWindowWidth(); 122 | * height = GetWindowHeight(); 123 | * ------------------------------------------ 124 | * These functions return the width and height of the graphics 125 | * window, in inches. 126 | */ 127 | 128 | double GetWindowWidth(); 129 | double GetWindowHeight(); 130 | 131 | /* 132 | * Functions: GetCurrentX, GetCurrentY 133 | * Usage: x = GetCurrentX(); 134 | * y = GetCurrentY(); 135 | * ----------------------------------- 136 | * These functions return the current x and y positions. 137 | */ 138 | 139 | double GetCurrentX(); 140 | double GetCurrentY(); 141 | 142 | #endif 143 | -------------------------------------------------------------------------------- /cs144/router/sr_rt.c: -------------------------------------------------------------------------------- 1 | /*----------------------------------------------------------------------------- 2 | * file: sr_rt.c 3 | * date: Mon Oct 07 04:02:12 PDT 2002 4 | * Author: casado@stanford.edu 5 | * 6 | * Description: 7 | * 8 | *---------------------------------------------------------------------------*/ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | 17 | #include 18 | #include 19 | #define __USE_MISC 1 /* force linux to show inet_aton */ 20 | #include 21 | 22 | #include "sr_rt.h" 23 | #include "sr_router.h" 24 | 25 | /*--------------------------------------------------------------------- 26 | * Method: 27 | * 28 | *---------------------------------------------------------------------*/ 29 | 30 | int sr_load_rt(struct sr_instance* sr,const char* filename) 31 | { 32 | FILE* fp; 33 | char line[BUFSIZ]; 34 | char dest[32]; 35 | char gw[32]; 36 | char mask[32]; 37 | char iface[32]; 38 | struct in_addr dest_addr; 39 | struct in_addr gw_addr; 40 | struct in_addr mask_addr; 41 | int clear_routing_table = 0; 42 | 43 | /* -- REQUIRES -- */ 44 | assert(filename); 45 | if( access(filename,R_OK) != 0) 46 | { 47 | perror("access"); 48 | return -1; 49 | } 50 | 51 | fp = fopen(filename,"r"); 52 | 53 | while( fgets(line,BUFSIZ,fp) != 0) 54 | { 55 | sscanf(line,"%s %s %s %s",dest,gw,mask,iface); 56 | if(inet_aton(dest,&dest_addr) == 0) 57 | { 58 | fprintf(stderr, 59 | "Error loading routing table, cannot convert %s to valid IP\n", 60 | dest); 61 | return -1; 62 | } 63 | if(inet_aton(gw,&gw_addr) == 0) 64 | { 65 | fprintf(stderr, 66 | "Error loading routing table, cannot convert %s to valid IP\n", 67 | gw); 68 | return -1; 69 | } 70 | if(inet_aton(mask,&mask_addr) == 0) 71 | { 72 | fprintf(stderr, 73 | "Error loading routing table, cannot convert %s to valid IP\n", 74 | mask); 75 | return -1; 76 | } 77 | if( clear_routing_table == 0 ){ 78 | printf("Loading routing table from server, clear local routing table.\n"); 79 | sr->routing_table = 0; 80 | clear_routing_table = 1; 81 | } 82 | sr_add_rt_entry(sr,dest_addr,gw_addr,mask_addr,iface); 83 | } /* -- while -- */ 84 | 85 | return 0; /* -- success -- */ 86 | } /* -- sr_load_rt -- */ 87 | 88 | /*--------------------------------------------------------------------- 89 | * Method: 90 | * 91 | *---------------------------------------------------------------------*/ 92 | 93 | void sr_add_rt_entry(struct sr_instance* sr, struct in_addr dest, 94 | struct in_addr gw, struct in_addr mask,char* if_name) 95 | { 96 | struct sr_rt* rt_walker = 0; 97 | 98 | /* -- REQUIRES -- */ 99 | assert(if_name); 100 | assert(sr); 101 | 102 | /* -- empty list special case -- */ 103 | if(sr->routing_table == 0) 104 | { 105 | sr->routing_table = (struct sr_rt*)malloc(sizeof(struct sr_rt)); 106 | assert(sr->routing_table); 107 | sr->routing_table->next = 0; 108 | sr->routing_table->dest = dest; 109 | sr->routing_table->gw = gw; 110 | sr->routing_table->mask = mask; 111 | strncpy(sr->routing_table->interface,if_name,sr_IFACE_NAMELEN); 112 | 113 | return; 114 | } 115 | 116 | /* -- find the end of the list -- */ 117 | rt_walker = sr->routing_table; 118 | while(rt_walker->next){ 119 | rt_walker = rt_walker->next; 120 | } 121 | 122 | rt_walker->next = (struct sr_rt*)malloc(sizeof(struct sr_rt)); 123 | assert(rt_walker->next); 124 | rt_walker = rt_walker->next; 125 | 126 | rt_walker->next = 0; 127 | rt_walker->dest = dest; 128 | rt_walker->gw = gw; 129 | rt_walker->mask = mask; 130 | strncpy(rt_walker->interface,if_name,sr_IFACE_NAMELEN); 131 | 132 | } /* -- sr_add_entry -- */ 133 | 134 | /*--------------------------------------------------------------------- 135 | * Method: 136 | * 137 | *---------------------------------------------------------------------*/ 138 | 139 | void sr_print_routing_table(struct sr_instance* sr) 140 | { 141 | struct sr_rt* rt_walker = 0; 142 | 143 | if(sr->routing_table == 0) 144 | { 145 | printf(" *warning* Routing table empty \n"); 146 | return; 147 | } 148 | 149 | printf("Destination\tGateway\t\tMask\tIface\n"); 150 | 151 | rt_walker = sr->routing_table; 152 | 153 | sr_print_routing_entry(rt_walker); 154 | while(rt_walker->next) 155 | { 156 | rt_walker = rt_walker->next; 157 | sr_print_routing_entry(rt_walker); 158 | } 159 | 160 | } /* -- sr_print_routing_table -- */ 161 | 162 | /*--------------------------------------------------------------------- 163 | * Method: 164 | * 165 | *---------------------------------------------------------------------*/ 166 | 167 | void sr_print_routing_entry(struct sr_rt* entry) 168 | { 169 | /* -- REQUIRES --*/ 170 | assert(entry); 171 | assert(entry->interface); 172 | 173 | printf("%s\t\t",inet_ntoa(entry->dest)); 174 | printf("%s\t",inet_ntoa(entry->gw)); 175 | printf("%s\t",inet_ntoa(entry->mask)); 176 | printf("%s\n",entry->interface); 177 | 178 | } /* -- sr_print_routing_entry -- */ 179 | -------------------------------------------------------------------------------- /cs144/router/sr_if.c: -------------------------------------------------------------------------------- 1 | /*----------------------------------------------------------------------------- 2 | * file: sr_inface. 3 | * date: Sun Oct 06 14:13:13 PDT 2002 4 | * Contact: casado@stanford.edu 5 | * 6 | * Description: 7 | * 8 | * Data structures and methods for handling interfaces 9 | * 10 | *---------------------------------------------------------------------------*/ 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #ifdef _DARWIN_ 18 | #include 19 | #endif /* _DARWIN_ */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | #include "sr_if.h" 26 | #include "sr_router.h" 27 | 28 | /*--------------------------------------------------------------------- 29 | * Method: sr_get_interface 30 | * Scope: Global 31 | * 32 | * Given an interface name return the interface record or 0 if it doesn't 33 | * exist. 34 | * 35 | *---------------------------------------------------------------------*/ 36 | 37 | struct sr_if* sr_get_interface(struct sr_instance* sr, const char* name) 38 | { 39 | struct sr_if* if_walker = 0; 40 | 41 | /* -- REQUIRES -- */ 42 | assert(name); 43 | assert(sr); 44 | 45 | if_walker = sr->if_list; 46 | 47 | while(if_walker) 48 | { 49 | if(!strncmp(if_walker->name,name,sr_IFACE_NAMELEN)) 50 | { return if_walker; } 51 | if_walker = if_walker->next; 52 | } 53 | 54 | return 0; 55 | } /* -- sr_get_interface -- */ 56 | 57 | /*--------------------------------------------------------------------- 58 | * Method: sr_add_interface(..) 59 | * Scope: Global 60 | * 61 | * Add and interface to the router's list 62 | * 63 | *---------------------------------------------------------------------*/ 64 | 65 | void sr_add_interface(struct sr_instance* sr, const char* name) 66 | { 67 | struct sr_if* if_walker = 0; 68 | 69 | /* -- REQUIRES -- */ 70 | assert(name); 71 | assert(sr); 72 | 73 | /* -- empty list special case -- */ 74 | if(sr->if_list == 0) 75 | { 76 | sr->if_list = (struct sr_if*)malloc(sizeof(struct sr_if)); 77 | assert(sr->if_list); 78 | sr->if_list->next = 0; 79 | strncpy(sr->if_list->name,name,sr_IFACE_NAMELEN); 80 | return; 81 | } 82 | 83 | /* -- find the end of the list -- */ 84 | if_walker = sr->if_list; 85 | while(if_walker->next) 86 | {if_walker = if_walker->next; } 87 | 88 | if_walker->next = (struct sr_if*)malloc(sizeof(struct sr_if)); 89 | assert(if_walker->next); 90 | if_walker = if_walker->next; 91 | strncpy(if_walker->name,name,sr_IFACE_NAMELEN); 92 | if_walker->next = 0; 93 | } /* -- sr_add_interface -- */ 94 | 95 | /*--------------------------------------------------------------------- 96 | * Method: sr_sat_ether_addr(..) 97 | * Scope: Global 98 | * 99 | * set the ethernet address of the LAST interface in the interface list 100 | * 101 | *---------------------------------------------------------------------*/ 102 | 103 | void sr_set_ether_addr(struct sr_instance* sr, const unsigned char* addr) 104 | { 105 | struct sr_if* if_walker = 0; 106 | 107 | /* -- REQUIRES -- */ 108 | assert(sr->if_list); 109 | 110 | if_walker = sr->if_list; 111 | while(if_walker->next) 112 | {if_walker = if_walker->next; } 113 | 114 | /* -- copy address -- */ 115 | memcpy(if_walker->addr,addr,6); 116 | 117 | } /* -- sr_set_ether_addr -- */ 118 | 119 | /*--------------------------------------------------------------------- 120 | * Method: sr_set_ether_ip(..) 121 | * Scope: Global 122 | * 123 | * set the IP address of the LAST interface in the interface list 124 | * 125 | *---------------------------------------------------------------------*/ 126 | 127 | void sr_set_ether_ip(struct sr_instance* sr, uint32_t ip_nbo) 128 | { 129 | struct sr_if* if_walker = 0; 130 | 131 | /* -- REQUIRES -- */ 132 | assert(sr->if_list); 133 | 134 | if_walker = sr->if_list; 135 | while(if_walker->next) 136 | {if_walker = if_walker->next; } 137 | 138 | /* -- copy address -- */ 139 | if_walker->ip = ip_nbo; 140 | 141 | } /* -- sr_set_ether_ip -- */ 142 | 143 | /*--------------------------------------------------------------------- 144 | * Method: sr_print_if_list(..) 145 | * Scope: Global 146 | * 147 | * print out the list of interfaces to stdout 148 | * 149 | *---------------------------------------------------------------------*/ 150 | 151 | void sr_print_if_list(struct sr_instance* sr) 152 | { 153 | struct sr_if* if_walker = 0; 154 | 155 | if(sr->if_list == 0) 156 | { 157 | printf(" Interface list empty \n"); 158 | return; 159 | } 160 | 161 | if_walker = sr->if_list; 162 | 163 | sr_print_if(if_walker); 164 | while(if_walker->next) 165 | { 166 | if_walker = if_walker->next; 167 | sr_print_if(if_walker); 168 | } 169 | 170 | } /* -- sr_print_if_list -- */ 171 | 172 | /*--------------------------------------------------------------------- 173 | * Method: sr_print_if(..) 174 | * Scope: Global 175 | * 176 | * print out a single interface to stdout 177 | * 178 | *---------------------------------------------------------------------*/ 179 | 180 | void sr_print_if(struct sr_if* iface) 181 | { 182 | struct in_addr ip_addr; 183 | 184 | /* -- REQUIRES --*/ 185 | assert(iface); 186 | assert(iface->name); 187 | 188 | ip_addr.s_addr = iface->ip; 189 | 190 | Debug("%s\tHWaddr",iface->name); 191 | DebugMAC(iface->addr); 192 | Debug("\n"); 193 | Debug("\tinet addr %s\n",inet_ntoa(ip_addr)); 194 | } /* -- sr_print_if -- */ 195 | -------------------------------------------------------------------------------- /cs106/assign3/recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "simpio.h" 3 | #include "graphics.h" 4 | #include "extgraph.h" 5 | #include 6 | #include 7 | #include 8 | #include "lexicon.h" 9 | #include 10 | 11 | using namespace std; 12 | 13 | int CountWays(int numStairs){ 14 | if(0 == numStairs){ 15 | return 1; 16 | }else if(1 == numStairs){ 17 | return 1; 18 | } 19 | return CountWays(numStairs-1) + CountWays(numStairs-2); 20 | } 21 | 22 | void testCountWays(){ 23 | cout << "Enter number of stairs: "; 24 | int numStairs = GetInteger(); 25 | cout << "Number of ways: " << CountWays(numStairs) << endl; 26 | } 27 | 28 | void _DrawRuler(double x, double y, double w, double h){ 29 | const static double hlim = 0.01; 30 | if(h < hlim) 31 | return; 32 | MovePen(x + w/2, y); 33 | DrawLine(0, h); 34 | UpdateDisplay(); 35 | _DrawRuler(x, y, w/2, h/2); 36 | _DrawRuler(x + w/2, y, w/2, h/2); 37 | } 38 | 39 | void DrawRuler(double x, double y, double w, double h){ 40 | InitGraphics(); 41 | MovePen(x, y); 42 | DrawLine(w, 0); 43 | UpdateDisplay(); 44 | 45 | _DrawRuler(x, y, w, h); 46 | } 47 | 48 | void testDrawRuler(){ 49 | DrawRuler(0.5, 0.5, 2, 0.5); 50 | } 51 | 52 | /* 53 | * Function: _CountCriticalVotes 54 | * -------------------- 55 | * 假设除了blocksIndex之外block的和为N,整个投票分为A和N-A,blocksIndex对应的投票为X 56 | * 若假定A少于一半,N/2 >= A 57 | * 要使A最终能反超,要A >= (N-X)/2 58 | * 递归的枚举A,看有多少中情况A在这个范围内 59 | */ 60 | int _CountCriticalVotes(vector& blocks, int blocksIndex, int curIndex, 61 | int votes, int lrange, int rrange){ 62 | if(curIndex == blocks.size()){ 63 | if((votes >= lrange) && (votes <= rrange)) 64 | return 1; 65 | else 66 | return 0; 67 | } 68 | if(curIndex == blocksIndex) 69 | return _CountCriticalVotes(blocks, blocksIndex, curIndex+1, votes, lrange, rrange); 70 | return ((votes < rrange) ? _CountCriticalVotes(blocks, blocksIndex, curIndex+1, votes+blocks[curIndex], lrange, rrange) : 0) + 71 | _CountCriticalVotes(blocks, blocksIndex, curIndex+1, votes, lrange, rrange); 72 | } 73 | 74 | int CountCriticalVotes(vector& blocks, int blocksIndex){ 75 | int sum = 0; 76 | for(auto b : blocks){ 77 | sum += b; 78 | } 79 | sum -= blocks[blocksIndex]; 80 | int lrange = ceil((sum - blocks[blocksIndex]) / 2); 81 | int rrange = floor(sum / 2); 82 | 83 | _CountCriticalVotes(blocks, blocksIndex, 0, 0, lrange, rrange); 84 | } 85 | 86 | void testCountCriticalVotes(){ 87 | vector blocks{9, 9, 7, 3, 1, 1}; 88 | int blocksIndex; 89 | 90 | cout << "Blocks: "; 91 | for(auto b : blocks){ 92 | cout << b << " "; 93 | } 94 | cout << endl; 95 | cout << "Enter block index: "; 96 | cin >> blocksIndex; 97 | 98 | cout << "Number of Critical Votes: " << CountCriticalVotes(blocks, blocksIndex) << endl; 99 | } 100 | 101 | void _PrintPrefixWords(string words, string& prefix){ 102 | for(auto pprefix = prefix.begin(), pwords = words.begin(); pprefix != prefix.end(); pprefix++, pwords++){ 103 | if(pwords == words.end() || (*pwords != *pprefix)) 104 | return; 105 | } 106 | cout << words << endl; 107 | } 108 | 109 | void _ListCompletions(string& digitSequence, Lexicon& lex, 110 | int curDigitIndex, string& curPrefix){ 111 | static map keyMap{{'2', string{"abc"}}, {'3', string{"def"}}, 112 | {'4', string{"ghi"}}, {'5', string{"jkl"}}, 113 | {'6', string{"mno"}}, {'7', string{"pqrs"}}, 114 | {'8', string{"tuv"}}, {'9', string{"wxyz"}} 115 | }; 116 | 117 | if(!lex.containsPrefix(curPrefix)){ 118 | return; 119 | } 120 | if(curDigitIndex == digitSequence.size()){ 121 | lex.mapAll(_PrintPrefixWords, curPrefix); 122 | return; 123 | } 124 | for(char c : keyMap[digitSequence[curDigitIndex]]){ 125 | curPrefix.push_back(c); 126 | _ListCompletions(digitSequence, lex, curDigitIndex+1, curPrefix); 127 | curPrefix.erase(curPrefix.size()-1); 128 | } 129 | } 130 | 131 | void ListCompletions(string digitSequence, Lexicon& lex){ 132 | string prefix{}; 133 | _ListCompletions(digitSequence, lex, 0, prefix); 134 | } 135 | 136 | void testListCompletions(){ 137 | Lexicon lex{"lexicon.dat"}; 138 | string digitSequence; 139 | cout << "Enter digit sequence: "; 140 | cin >> digitSequence; 141 | 142 | ListCompletions(digitSequence, lex); 143 | } 144 | 145 | bool _SolvePuzzle(vector& squares, int curIndex, set& hasVisit){ 146 | if(curIndex < 0 || curIndex >= squares.size() || hasVisit.find(curIndex) != hasVisit.end()){ 147 | return false; 148 | } 149 | if(squares[curIndex] == 0){ 150 | return true; 151 | } 152 | hasVisit.insert(curIndex); 153 | return _SolvePuzzle(squares, curIndex + squares[curIndex], hasVisit) || 154 | _SolvePuzzle(squares, curIndex - squares[curIndex], hasVisit); 155 | } 156 | 157 | bool Solvable(int start, vector& squares){ 158 | set hasVisit{}; 159 | return _SolvePuzzle(squares, start, hasVisit); 160 | } 161 | 162 | void testSolvable(){ 163 | //vector squares{3, 6, 4, 1, 3, 4, 2, 5, 3, 0}; 164 | vector squares{3, 1, 4, 1, 0}; 165 | int num; 166 | 167 | cout << "Enter start index: "; 168 | num = GetInteger(); 169 | if(Solvable(num, squares)){ 170 | cout << "It can" << endl; 171 | }else{ 172 | cout << "It cannot" << endl; 173 | } 174 | } 175 | 176 | 177 | 178 | int main(){ 179 | //testCountWays(); 180 | //testDrawRuler(); 181 | //testCountCriticalVotes(); 182 | testListCompletions(); 183 | //testSolvable(); 184 | 185 | return 0; 186 | } 187 | -------------------------------------------------------------------------------- /cs106/include/private/set.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/set.cpp 3 | * Last modified on Thu Jun 11 09:34:08 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the implementation of the set.h interface. 6 | * Because of the way C++ compiles templates, this code must be 7 | * available to the compiler when it reads the header file. 8 | */ 9 | 10 | #ifdef _set_h 11 | 12 | template 13 | Set::Set(int (*cmp)(ElemType, ElemType)) : bst(cmp) { 14 | cmpFn = cmp; 15 | } 16 | 17 | template 18 | Set::~Set() { 19 | /* Empty */ 20 | } 21 | 22 | template 23 | int Set::size() { 24 | return bst.size(); 25 | } 26 | 27 | template 28 | bool Set::isEmpty() { 29 | return bst.isEmpty(); 30 | } 31 | 32 | template 33 | void Set::add(ElemType element) { 34 | bst.add(element); 35 | } 36 | 37 | template 38 | void Set::remove(ElemType element) { 39 | bst.remove(element); 40 | } 41 | 42 | template 43 | bool Set::contains(ElemType element) { 44 | return find(element) != NULL; 45 | } 46 | 47 | template 48 | ElemType *Set::find(ElemType element) { 49 | return bst.find(element); 50 | } 51 | 52 | template 53 | void Set::clear() { 54 | bst.clear(); 55 | } 56 | 57 | /* 58 | * Implementation notes: Set operations 59 | * ------------------------------------ 60 | * The code for equals, isSubsetOf, unionWith, intersectWith, and subtract 61 | * is similar in structure. Each one uses an iterator to walk over 62 | * one (or both) sets, doing add/remove/comparision. 63 | */ 64 | 65 | template 66 | bool Set::equals(Set & otherSet) { 67 | if (cmpFn != otherSet.cmpFn) { 68 | Error("Equals: sets have different comparison functions"); 69 | } 70 | Iterator thisItr = iterator(), otherItr = otherSet.iterator(); 71 | while (thisItr.hasNext() && otherItr.hasNext()) { 72 | if (cmpFn(thisItr.next(), otherItr.next()) != 0) return false; 73 | } 74 | return !thisItr.hasNext() && !otherItr.hasNext(); 75 | } 76 | 77 | template 78 | bool Set::isSubsetOf(Set & otherSet) { 79 | if (cmpFn != otherSet.cmpFn) { 80 | Error("isSubsetOf: sets have different comparison functions"); 81 | } 82 | Iterator iter = iterator(); 83 | while (iter.hasNext()) { 84 | if (!otherSet.contains(iter.next())) return false; 85 | } 86 | return true; 87 | } 88 | 89 | template 90 | void Set::unionWith(Set & otherSet) { 91 | if (cmpFn != otherSet.cmpFn) { 92 | Error("unionWith: sets have different comparison functions"); 93 | } 94 | Iterator iter = otherSet.iterator(); 95 | while (iter.hasNext()) { 96 | add(iter.next()); 97 | } 98 | } 99 | 100 | /* 101 | * Implementation notes: intersectWith 102 | * ----------------------------------- 103 | * The most obvious way to write this method (iterating over 104 | * one set and deleting members that are not in the second) 105 | * fails because you can't change the contents of a collection 106 | * over which you're iterating. This code puts the elements 107 | * to be deleted in a vector and then deletes those. 108 | */ 109 | 110 | template 111 | void Set::intersectWith(Set & otherSet) { 112 | if (cmpFn != otherSet.cmpFn) { 113 | Error("intersectWith:" 114 | " sets have different comparison functions"); 115 | } 116 | Iterator iter = iterator(); 117 | Vector toDelete; 118 | while (iter.hasNext()) { 119 | ElemType elem = iter.next(); 120 | if (!otherSet.contains(elem)) toDelete.add(elem); 121 | } 122 | for (int i = 0; i < toDelete.size(); i++) { 123 | remove(toDelete[i]); 124 | } 125 | } 126 | 127 | template 128 | void Set::intersect(Set & otherSet) { 129 | if (cmpFn != otherSet.cmpFn) { 130 | Error("intersect: sets have different comparison functions"); 131 | } 132 | intersectWith(otherSet); 133 | } 134 | 135 | template 136 | void Set::subtract(Set & otherSet) { 137 | if (cmpFn != otherSet.cmpFn) { 138 | Error("subtract: sets have different comparison functions"); 139 | } 140 | Iterator iter = otherSet.iterator(); 141 | while (iter.hasNext()) { 142 | remove(iter.next()); 143 | } 144 | } 145 | 146 | template 147 | void Set::mapAll(void (*fn)(ElemType)) { 148 | bst.mapAll(fn); 149 | } 150 | 151 | template 152 | template 153 | void Set::mapAll(void (*fn)(ElemType, ClientDataType &), 154 | ClientDataType & data) { 155 | bst.mapAll(fn, data); 156 | } 157 | 158 | /* 159 | * Set::Iterator class implementation 160 | * ---------------------------------- 161 | * The Iterator for Set relies on the underlying implementation of the 162 | * Iterator for the BST class. 163 | */ 164 | 165 | template 166 | Set::Iterator::Iterator() { 167 | /* Empty */ 168 | } 169 | 170 | template 171 | typename Set::Iterator Set::iterator() { 172 | return Iterator(this); 173 | } 174 | 175 | template 176 | Set::Iterator::Iterator(Set *setptr) { 177 | iterator = setptr->bst.iterator(); 178 | } 179 | 180 | template 181 | bool Set::Iterator::hasNext() { 182 | return iterator.hasNext(); 183 | } 184 | 185 | template 186 | ElemType Set::Iterator::next() { 187 | return iterator.next(); 188 | } 189 | 190 | template 191 | ElemType Set::foreachHook(FE_State & fe) { 192 | if (fe.state == 0) fe.iter = new Iterator(this); 193 | if (((Iterator *) fe.iter)->hasNext()) { 194 | fe.state = 1; 195 | return ((Iterator *) fe.iter)->next(); 196 | } else { 197 | fe.state = 2; 198 | return ElemType(); 199 | } 200 | } 201 | 202 | #endif 203 | -------------------------------------------------------------------------------- /cs144/router/vnscommand.h: -------------------------------------------------------------------------------- 1 | /*----------------------------------------------------------------------------- 2 | File: vnscommand.h 3 | Date: Sat Apr 06 21:58:07 PST 2002 4 | Contact: casado@stanford.edu 5 | 6 | Description: 7 | 8 | A c-style declaration of commands for the virtual router. 9 | 10 | ---------------------------------------------------------------------------*/ 11 | 12 | #ifndef __VNSCOMMAND_H 13 | #define __VNSCOMMAND_H 14 | 15 | #define VNSOPEN 1 16 | #define VNSCLOSE 2 17 | #define VNSPACKET 4 18 | #define VNSBANNER 8 19 | #define VNSHWINFO 16 20 | 21 | #define IDSIZE 32 22 | 23 | /*----------------------------------------------------------------------------- 24 | BASE 25 | ---------------------------------------------------------------------------*/ 26 | 27 | typedef struct 28 | { 29 | uint32_t mLen; 30 | uint32_t mType; 31 | }__attribute__ ((__packed__)) c_base; 32 | 33 | /*----------------------------------------------------------------------------- 34 | OPEN 35 | ---------------------------------------------------------------------------*/ 36 | 37 | typedef struct 38 | { 39 | 40 | uint32_t mLen; 41 | uint32_t mType; /* = VNSOPEN */ 42 | uint16_t topoID; /* Id of the topology we want to run on */ 43 | uint16_t pad; /* unused */ 44 | char mVirtualHostID[IDSIZE]; /* Id of the simulated router (e.g. 45 | 'VNS-A'); */ 46 | char mUID[IDSIZE]; /* User id (e.g. "appenz"), for information only */ 47 | char mPass[IDSIZE]; 48 | 49 | }__attribute__ ((__packed__)) c_open; 50 | 51 | /*----------------------------------------------------------------------------- 52 | CLOSE 53 | ---------------------------------------------------------------------------*/ 54 | 55 | typedef struct 56 | { 57 | 58 | uint32_t mLen; 59 | uint32_t mType; 60 | char mErrorMessage[256]; 61 | 62 | }__attribute__ ((__packed__)) c_close; 63 | 64 | /*----------------------------------------------------------------------------- 65 | HWREQUEST 66 | ---------------------------------------------------------------------------*/ 67 | 68 | typedef struct 69 | { 70 | 71 | uint32_t mLen; 72 | uint32_t mType; 73 | 74 | }__attribute__ ((__packed__)) c_hwrequest; 75 | 76 | /*----------------------------------------------------------------------------- 77 | BANNER 78 | ---------------------------------------------------------------------------*/ 79 | 80 | typedef struct 81 | { 82 | 83 | uint32_t mLen; 84 | uint32_t mType; 85 | char mBannerMessage[256]; 86 | 87 | }__attribute__ ((__packed__)) c_banner; 88 | 89 | /*----------------------------------------------------------------------------- 90 | PACKET (header) 91 | ---------------------------------------------------------------------------*/ 92 | 93 | 94 | typedef struct 95 | { 96 | uint32_t mLen; 97 | uint32_t mType; 98 | char mInterfaceName[16]; 99 | uint8_t ether_dhost[6]; 100 | uint8_t ether_shost[6]; 101 | uint16_t ether_type; 102 | 103 | }__attribute__ ((__packed__)) c_packet_ethernet_header; 104 | 105 | typedef struct 106 | { 107 | uint32_t mLen; 108 | uint32_t mType; 109 | char mInterfaceName[16]; 110 | }__attribute__ ((__packed__)) c_packet_header; 111 | 112 | /*----------------------------------------------------------------------------- 113 | HWInfo 114 | ----------------------------------------------------------------------------*/ 115 | 116 | #define HWINTERFACE 1 117 | #define HWSPEED 2 118 | #define HWSUBNET 4 119 | #define HWINUSE 8 120 | #define HWFIXEDIP 16 121 | #define HWETHER 32 122 | #define HWETHIP 64 123 | #define HWMASK 128 124 | 125 | typedef struct 126 | { 127 | uint32_t mKey; 128 | char value[32]; 129 | }__attribute__ ((__packed__)) c_hw_entry; 130 | 131 | typedef struct 132 | { 133 | #define MAXHWENTRIES 256 134 | uint32_t mLen; 135 | uint32_t mType; 136 | c_hw_entry mHWInfo[MAXHWENTRIES]; 137 | }__attribute__ ((__packed__)) c_hwinfo; 138 | 139 | /* ******* New VNS Messages ******** */ 140 | #define VNS_RTABLE 32 141 | #define VNS_OPEN_TEMPLATE 64 142 | #define VNS_AUTH_REQUEST 128 143 | #define VNS_AUTH_REPLY 256 144 | #define VNS_AUTH_STATUS 512 145 | 146 | /* rtable */ 147 | typedef struct 148 | { 149 | uint32_t mLen; 150 | uint32_t mType; 151 | char mVirtualHostID[IDSIZE]; 152 | char rtable[0]; 153 | }__attribute__ ((__packed__)) c_rtable; 154 | 155 | /* open template */ 156 | typedef struct { 157 | uint32_t ip; 158 | uint8_t num_masked_bits; 159 | }__attribute__ ((__packed__)) c_src_filter; 160 | 161 | typedef struct 162 | { 163 | uint32_t mLen; 164 | uint32_t mType; 165 | char templateName[30]; 166 | char mVirtualHostID[IDSIZE]; 167 | c_src_filter srcFilters[0]; 168 | }__attribute__ ((__packed__)) c_open_template; 169 | 170 | /* authentication request */ 171 | typedef struct 172 | { 173 | uint32_t mLen; 174 | uint32_t mType; 175 | uint8_t salt[0]; 176 | 177 | }__attribute__ ((__packed__)) c_auth_request; 178 | 179 | /* authentication reply */ 180 | typedef struct 181 | { 182 | uint32_t mLen; 183 | uint32_t mType; 184 | uint32_t usernameLen; 185 | char username[0]; 186 | /* remainder of the message is the salted sha1 of the user's password */ 187 | }__attribute__ ((__packed__)) c_auth_reply; 188 | 189 | /* authentication status (whether or not a reply was accepted) */ 190 | typedef struct 191 | { 192 | uint32_t mLen; 193 | uint32_t mType; 194 | uint8_t auth_ok; 195 | char msg[0]; 196 | 197 | }__attribute__ ((__packed__)) c_auth_status; 198 | 199 | 200 | #endif /* __VNSCOMMAND_H */ 201 | -------------------------------------------------------------------------------- /cs144/router/sr_arpcache.h: -------------------------------------------------------------------------------- 1 | /* This file defines an ARP cache, which is made of two structures: an ARP 2 | request queue, and ARP cache entries. The ARP request queue holds data about 3 | an outgoing ARP cache request and the packets that are waiting on a reply 4 | to that ARP cache request. The ARP cache entries hold IP->MAC mappings and 5 | are timed out every SR_ARPCACHE_TO seconds. 6 | 7 | Pseudocode for use of these structures follows. 8 | 9 | -- 10 | 11 | # When sending packet to next_hop_ip 12 | entry = arpcache_lookup(next_hop_ip) 13 | 14 | if entry: 15 | use next_hop_ip->mac mapping in entry to send the packet 16 | free entry 17 | else: 18 | req = arpcache_queuereq(next_hop_ip, packet, len) 19 | handle_arpreq(req) 20 | 21 | -- 22 | 23 | The handle_arpreq() function is a function you should write, and it should 24 | handle sending ARP requests if necessary: 25 | 26 | function handle_arpreq(req): 27 | if difftime(now, req->sent) > 1.0 28 | if req->times_sent >= 5: 29 | send icmp host unreachable to source addr of all pkts waiting 30 | on this request 31 | arpreq_destroy(req) 32 | else: 33 | send arp request 34 | req->sent = now 35 | req->times_sent++ 36 | 37 | -- 38 | 39 | The ARP reply processing code should move entries from the ARP request 40 | queue to the ARP cache: 41 | 42 | # When servicing an arp reply that gives us an IP->MAC mapping 43 | req = arpcache_insert(ip, mac) 44 | 45 | if req: 46 | send all packets on the req->packets linked list 47 | arpreq_destroy(req) 48 | 49 | -- 50 | 51 | To meet the guidelines in the assignment (ARP requests are sent every second 52 | until we send 5 ARP requests, then we send ICMP host unreachable back to 53 | all packets waiting on this ARP request), you must fill out the following 54 | function that is called every second and is defined in sr_arpcache.c: 55 | 56 | void sr_arpcache_sweepreqs(struct sr_instance *sr) { 57 | for each request on sr->cache.requests: 58 | handle_arpreq(request) 59 | } 60 | 61 | Since handle_arpreq as defined in the comments above could destroy your 62 | current request, make sure to save the next pointer before calling 63 | handle_arpreq when traversing through the ARP requests linked list. 64 | */ 65 | 66 | #ifndef SR_ARPCACHE_H 67 | #define SR_ARPCACHE_H 68 | 69 | #include 70 | #include 71 | #include 72 | #include "sr_if.h" 73 | 74 | #define SR_ARPCACHE_SZ 100 75 | #define SR_ARPCACHE_TO 15.0 76 | 77 | struct sr_packet { 78 | uint8_t *buf; /* A raw Ethernet frame, presumably with the dest MAC empty */ 79 | unsigned int len; /* Length of raw Ethernet frame */ 80 | char *iface; /* The outgoing interface */ 81 | struct sr_packet *next; 82 | }; 83 | 84 | struct sr_arpentry { 85 | unsigned char mac[6]; 86 | uint32_t ip; /* IP addr in network byte order */ 87 | time_t added; 88 | int valid; 89 | }; 90 | 91 | struct sr_arpreq { 92 | uint32_t ip; 93 | time_t sent; /* Last time this ARP request was sent. You 94 | should update this. If the ARP request was 95 | never sent, will be 0. */ 96 | uint32_t times_sent; /* Number of times this request was sent. You 97 | should update this. */ 98 | struct sr_packet *packets; /* List of pkts waiting on this req to finish */ 99 | struct sr_arpreq *next; 100 | }; 101 | 102 | struct sr_arpcache { 103 | struct sr_arpentry entries[SR_ARPCACHE_SZ]; 104 | struct sr_arpreq *requests; 105 | pthread_mutex_t lock; 106 | pthread_mutexattr_t attr; 107 | }; 108 | 109 | /* Checks if an IP->MAC mapping is in the cache. IP is in network byte order. 110 | You must free the returned structure if it is not NULL. */ 111 | struct sr_arpentry *sr_arpcache_lookup(struct sr_arpcache *cache, uint32_t ip); 112 | 113 | /* Adds an ARP request to the ARP request queue. If the request is already on 114 | the queue, adds the packet to the linked list of packets for this sr_arpreq 115 | that corresponds to this ARP request. The packet argument should not be 116 | freed by the caller. 117 | 118 | A pointer to the ARP request is returned; it should be freed. The caller 119 | can remove the ARP request from the queue by calling sr_arpreq_destroy. */ 120 | struct sr_arpreq *sr_arpcache_queuereq(struct sr_arpcache *cache, 121 | uint32_t ip, 122 | uint8_t *packet, /* borrowed */ 123 | unsigned int packet_len, 124 | char *iface); 125 | 126 | /* This method performs two functions: 127 | 1) Looks up this IP in the request queue. If it is found, returns a pointer 128 | to the sr_arpreq with this IP. Otherwise, returns NULL. 129 | 2) Inserts this IP to MAC mapping in the cache, and marks it valid. */ 130 | struct sr_arpreq *sr_arpcache_insert(struct sr_arpcache *cache, 131 | unsigned char *mac, 132 | uint32_t ip); 133 | 134 | /* Frees all memory associated with this arp request entry. If this arp request 135 | entry is on the arp request queue, it is removed from the queue. */ 136 | void sr_arpreq_destroy(struct sr_arpcache *cache, struct sr_arpreq *entry); 137 | 138 | /* Prints out the ARP table. */ 139 | void sr_arpcache_dump(struct sr_arpcache *cache); 140 | 141 | /* You shouldn't have to call these methods--they're already called in the 142 | starter code for you. The init call is a constructor, the destroy call is 143 | a destructor, and a cleanup thread times out cache entries every 15 144 | seconds. */ 145 | 146 | int sr_arpcache_init(struct sr_arpcache *cache); 147 | int sr_arpcache_destroy(struct sr_arpcache *cache); 148 | void *sr_arpcache_timeout(void *cache_ptr); 149 | 150 | #endif 151 | -------------------------------------------------------------------------------- /cs144/router/sr_protocol.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1998, 1999, 2000 Mike D. Schiffman 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions 7 | * are met: 8 | * 1. Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * 2. Redistributions in binary form must reproduce the above copyright 11 | * notice, this list of conditions and the following disclaimer in the 12 | * documentation and/or other materials provided with the distribution. 13 | * 14 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 15 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 18 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 20 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 21 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 22 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 23 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 24 | * SUCH DAMAGE. 25 | * 26 | */ 27 | 28 | /** 29 | * sr_protocol.h 30 | * 31 | */ 32 | 33 | #ifndef SR_PROTOCOL_H 34 | #define SR_PROTOCOL_H 35 | 36 | #ifdef _LINUX_ 37 | #include 38 | #endif /* _LINUX_ */ 39 | 40 | #include 41 | #include 42 | 43 | 44 | #ifndef IP_MAXPACKET 45 | #define IP_MAXPACKET 65535 46 | #endif 47 | 48 | 49 | 50 | /* FIXME 51 | * ohh how lame .. how very, very lame... how can I ever go out in public 52 | * again?! /mc 53 | */ 54 | 55 | #ifndef __LITTLE_ENDIAN 56 | #define __LITTLE_ENDIAN 1 57 | #endif 58 | 59 | #ifndef __BIG_ENDIAN 60 | #define __BIG_ENDIAN 2 61 | #endif 62 | 63 | #ifndef __BYTE_ORDER 64 | #ifdef _CYGWIN_ 65 | #define __BYTE_ORDER __LITTLE_ENDIAN 66 | #endif 67 | #ifdef _LINUX_ 68 | #define __BYTE_ORDER __LITTLE_ENDIAN 69 | #endif 70 | #ifdef _SOLARIS_ 71 | #define __BYTE_ORDER __BIG_ENDIAN 72 | #endif 73 | #ifdef _DARWIN_ 74 | #define __BYTE_ORDER __BIG_ENDIAN 75 | #endif 76 | #endif 77 | #define ICMP_DATA_SIZE 28 78 | 79 | 80 | /* Structure of a ICMP header 81 | */ 82 | struct sr_icmp_hdr { 83 | uint8_t icmp_type; 84 | uint8_t icmp_code; 85 | uint16_t icmp_sum; 86 | 87 | } __attribute__ ((packed)) ; 88 | typedef struct sr_icmp_hdr sr_icmp_hdr_t; 89 | 90 | 91 | /* Structure of a type3 ICMP header 92 | */ 93 | struct sr_icmp_t3_hdr { 94 | uint8_t icmp_type; 95 | uint8_t icmp_code; 96 | uint16_t icmp_sum; 97 | uint16_t unused; 98 | uint16_t next_mtu; 99 | uint8_t data[ICMP_DATA_SIZE]; 100 | 101 | } __attribute__ ((packed)) ; 102 | typedef struct sr_icmp_t3_hdr sr_icmp_t3_hdr_t; 103 | 104 | 105 | 106 | 107 | /* 108 | * Structure of an internet header, naked of options. 109 | */ 110 | struct sr_ip_hdr 111 | { 112 | #if __BYTE_ORDER == __LITTLE_ENDIAN 113 | unsigned int ip_hl:4; /* header length */ 114 | unsigned int ip_v:4; /* version */ 115 | #elif __BYTE_ORDER == __BIG_ENDIAN 116 | unsigned int ip_v:4; /* version */ 117 | unsigned int ip_hl:4; /* header length */ 118 | #else 119 | #error "Byte ordering ot specified " 120 | #endif 121 | uint8_t ip_tos; /* type of service */ 122 | uint16_t ip_len; /* total length */ 123 | uint16_t ip_id; /* identification */ 124 | uint16_t ip_off; /* fragment offset field */ 125 | #define IP_RF 0x8000 /* reserved fragment flag */ 126 | #define IP_DF 0x4000 /* dont fragment flag */ 127 | #define IP_MF 0x2000 /* more fragments flag */ 128 | #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ 129 | uint8_t ip_ttl; /* time to live */ 130 | uint8_t ip_p; /* protocol */ 131 | uint16_t ip_sum; /* checksum */ 132 | uint32_t ip_src, ip_dst; /* source and dest address */ 133 | } __attribute__ ((packed)) ; 134 | typedef struct sr_ip_hdr sr_ip_hdr_t; 135 | 136 | /* 137 | * Ethernet packet header prototype. Too many O/S's define this differently. 138 | * Easy enough to solve that and define it here. 139 | */ 140 | struct sr_ethernet_hdr 141 | { 142 | #ifndef ETHER_ADDR_LEN 143 | #define ETHER_ADDR_LEN 6 144 | #endif 145 | uint8_t ether_dhost[ETHER_ADDR_LEN]; /* destination ethernet address */ 146 | uint8_t ether_shost[ETHER_ADDR_LEN]; /* source ethernet address */ 147 | uint16_t ether_type; /* packet type ID */ 148 | } __attribute__ ((packed)) ; 149 | typedef struct sr_ethernet_hdr sr_ethernet_hdr_t; 150 | 151 | 152 | 153 | enum sr_ip_protocol { 154 | ip_protocol_icmp = 0x0001, 155 | }; 156 | 157 | enum sr_ethertype { 158 | ethertype_arp = 0x0806, 159 | ethertype_ip = 0x0800, 160 | }; 161 | 162 | 163 | enum sr_arp_opcode { 164 | arp_op_request = 0x0001, 165 | arp_op_reply = 0x0002, 166 | }; 167 | 168 | enum sr_arp_hrd_fmt { 169 | arp_hrd_ethernet = 0x0001, 170 | }; 171 | 172 | 173 | struct sr_arp_hdr 174 | { 175 | unsigned short ar_hrd; /* format of hardware address */ 176 | unsigned short ar_pro; /* format of protocol address */ 177 | unsigned char ar_hln; /* length of hardware address */ 178 | unsigned char ar_pln; /* length of protocol address */ 179 | unsigned short ar_op; /* ARP opcode (command) */ 180 | unsigned char ar_sha[ETHER_ADDR_LEN]; /* sender hardware address */ 181 | uint32_t ar_sip; /* sender IP address */ 182 | unsigned char ar_tha[ETHER_ADDR_LEN]; /* target hardware address */ 183 | uint32_t ar_tip; /* target IP address */ 184 | } __attribute__ ((packed)) ; 185 | typedef struct sr_arp_hdr sr_arp_hdr_t; 186 | 187 | #define sr_IFACE_NAMELEN 32 188 | 189 | #endif /* -- SR_PROTOCOL_H -- */ 190 | -------------------------------------------------------------------------------- /cs106/include/bst.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: bst.h 3 | * Last modified on Fri Jun 5 15:08:03 2009 by eroberts 4 | * modified on Tue Jan 2 14:23:33 2007 by zelenski 5 | * ----------------------------------------------------- 6 | * This interface file contains the BST class template, an 7 | * implementation of a general binary search tree. 8 | * 9 | */ 10 | 11 | #ifndef _bst_h 12 | #define _bst_h 13 | 14 | #include "genlib.h" 15 | #include "cmpfn.h" 16 | #include "stack.h" 17 | #include "foreach.h" 18 | 19 | /* 20 | * Class: BST 21 | * ---------- 22 | * This interface defines a class template for a binary search tree. 23 | * For maximum generality, the BST is supplied as a class template. 24 | * The element type is set by the client. The client specializes 25 | * the tree for specific type, e.g. BST or BST. 26 | * The one requirement on the element type is that the client must 27 | * supply a comparison fn that compares two elements (or be willing 28 | * to use the default comparison function that relies on < and ==). 29 | */ 30 | 31 | template 32 | class BST { 33 | public: 34 | 35 | /* Forward references */ 36 | class Iterator; 37 | 38 | /* 39 | * Constructor: BST 40 | * Usage: BST bst; 41 | * BST songs(CompareSong) 42 | * BST *bp = new BST; 43 | * ----------------------------------------- 44 | * The constructor initializes a new empty binary search tree. 45 | * The one argument is a comparison function, which is called 46 | * to compare data values. This argument is optional, if not 47 | * given, the OperatorCmp function from cmpfn.h is used, which 48 | * applies the built-in operator < to its operands. If the 49 | * behavior of < on your ElemType is defined and sufficient, 50 | * you do not need to supply your own comparison function. 51 | */ 52 | BST(int (*cmpFn)(ElemType one, ElemType two) = OperatorCmp); 53 | 54 | /* 55 | * Destructor: ~BST 56 | * Usage: delete bp; 57 | * ------------------ 58 | * The destructor deallocates storage for this tree. 59 | */ 60 | ~BST(); 61 | 62 | /* 63 | * Method: size 64 | * Usage: count = bst.size(); 65 | * -------------------------- 66 | * This method returns the number of elements in 67 | * this tree. 68 | */ 69 | int size(); 70 | 71 | /* 72 | * Method: isEmpty 73 | * Usage: if (bst.isEmpty())... 74 | * ---------------------------- 75 | * This method returns true if this tree contains no 76 | * elements, false otherwise. 77 | */ 78 | bool isEmpty(); 79 | 80 | /* 81 | * Method: find 82 | * Usage: if (bst.find(key) != NULL) . . . 83 | * ---------------------------------------- 84 | * This method applies the binary search algorithm to 85 | * find a particular key in this tree. The second argument is 86 | * the key to use for comparison. If a node matching key appears 87 | * in the tree, find returns a pointer to the data in that node; 88 | * otherwise, find returns NULL. 89 | */ 90 | ElemType *find(ElemType key); 91 | 92 | /* 93 | * Method: add 94 | * Usage: bst.add(val); 95 | * -------------------- 96 | * This method adds a new node to this tree. The elem 97 | * argument is compared with the data in existing nodes to find 98 | * the proper position. If a node with the same value already 99 | * exists, the contents are overwritten with the new copy and 100 | * false is returned. If no matching node is found, a new node 101 | * is allocated and added to the tree, true is returned. 102 | */ 103 | bool add(ElemType elem); 104 | 105 | /* 106 | * Method: remove 107 | * Usage: bst.remove(key); 108 | ------------------------- 109 | * This method removes a node in this tree that matches 110 | * the specified key. If a node matching key is found, the node 111 | * is removed from the tree and true is returned. If no match 112 | * is found, no changes are made and false is returned. 113 | */ 114 | bool remove(ElemType key); 115 | 116 | /* 117 | * Method: clear 118 | * Usage: bst.clear(); 119 | * ------------------- 120 | * This method removes all elements from this tree. The 121 | * tree is made empty and will have no nodes after being cleared. 122 | */ 123 | void clear(); 124 | 125 | /* 126 | * Method: mapAll 127 | * Usage: bst.mapAll(Print); 128 | * ------------------------- 129 | * This method iterates through this tree and calls the 130 | * function fn once for each element. The order is determined by an 131 | * InOrder walk of the tree. 132 | */ 133 | void mapAll(void (*fn)(ElemType elem)); 134 | 135 | /* 136 | * Method: mapAll 137 | * Usage: bst.mapAll(PrintToFile, outputStream); 138 | * --------------------------------------------- 139 | * This method iterates through this tree con 140 | * and calls the function fn once for each element, passing 141 | * the element and the client's data. That data can be of 142 | * whatever type is needed for the client's callback. The order 143 | * of calls is determined by an InOrder walk of the tree. 144 | */ 145 | template 146 | void mapAll(void (*fn)(ElemType elem, ClientDataType & data), 147 | ClientDataType & data); 148 | 149 | /* 150 | * Method: iterator 151 | * Usage: iter = bst.iterator(); 152 | * ----------------------------- 153 | * This method creates an iterator that allows the client to 154 | * iterate through the elements in this binary search tree. The 155 | * order of elements produced by the iterator is that of an InOrder 156 | * walk of the tree. 157 | * 158 | * The idiomatic code for accessing elements using an iterator is 159 | * to create the iterator from the collection and then enter a loop 160 | * that calls next() while hasNext() is true, like this: 161 | * 162 | * BST::Iterator iter = bst.iterator(); 163 | * while (iter.hasNext()) { 164 | * string key = iter.next(); 165 | * . . . 166 | * } 167 | * 168 | * This pattern can be abbreviated to the following more readable form: 169 | * 170 | * foreach (string key in bst) { 171 | * . . . 172 | * } 173 | * 174 | * To avoid exposing the details of the class, the definition of the 175 | * Iterator class itself appears in the private/bst.h file. 176 | */ 177 | Iterator iterator(); 178 | 179 | private: 180 | 181 | #include "private/bst.h" 182 | 183 | }; 184 | 185 | #include "private/bst.cpp" 186 | 187 | #endif 188 | -------------------------------------------------------------------------------- /cs144/router/sr_utils.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "sr_protocol.h" 5 | #include "sr_utils.h" 6 | 7 | 8 | uint16_t cksum (const void *_data, int len) { 9 | const uint8_t *data = _data; 10 | uint32_t sum; 11 | 12 | for (sum = 0;len >= 2; data += 2, len -= 2) 13 | sum += data[0] << 8 | data[1]; 14 | if (len > 0) 15 | sum += data[0] << 8; 16 | while (sum > 0xffff) 17 | sum = (sum >> 16) + (sum & 0xffff); 18 | sum = htons (~sum); 19 | return sum ? sum : 0xffff; 20 | } 21 | 22 | 23 | uint16_t ethertype(uint8_t *buf) { 24 | sr_ethernet_hdr_t *ehdr = (sr_ethernet_hdr_t *)buf; 25 | return ntohs(ehdr->ether_type); 26 | } 27 | 28 | uint8_t ip_protocol(uint8_t *buf) { 29 | sr_ip_hdr_t *iphdr = (sr_ip_hdr_t *)(buf); 30 | return iphdr->ip_p; 31 | } 32 | 33 | 34 | /* Prints out formatted Ethernet address, e.g. 00:11:22:33:44:55 */ 35 | void print_addr_eth(uint8_t *addr) { 36 | int pos = 0; 37 | uint8_t cur; 38 | for (; pos < ETHER_ADDR_LEN; pos++) { 39 | cur = addr[pos]; 40 | if (pos > 0) 41 | fprintf(stderr, ":"); 42 | fprintf(stderr, "%02X", cur); 43 | } 44 | fprintf(stderr, "\n"); 45 | } 46 | 47 | /* Prints out IP address as a string from in_addr */ 48 | void print_addr_ip(struct in_addr address) { 49 | char buf[INET_ADDRSTRLEN]; 50 | if (inet_ntop(AF_INET, &address, buf, 100) == NULL) 51 | fprintf(stderr,"inet_ntop error on address conversion\n"); 52 | else 53 | fprintf(stderr, "%s\n", buf); 54 | } 55 | 56 | /* Prints out IP address from integer value */ 57 | void print_addr_ip_int(uint32_t ip) { 58 | uint32_t curOctet = ip >> 24; 59 | fprintf(stderr, "%d.", curOctet); 60 | curOctet = (ip << 8) >> 24; 61 | fprintf(stderr, "%d.", curOctet); 62 | curOctet = (ip << 16) >> 24; 63 | fprintf(stderr, "%d.", curOctet); 64 | curOctet = (ip << 24) >> 24; 65 | fprintf(stderr, "%d\n", curOctet); 66 | } 67 | 68 | 69 | /* Prints out fields in Ethernet header. */ 70 | void print_hdr_eth(uint8_t *buf) { 71 | sr_ethernet_hdr_t *ehdr = (sr_ethernet_hdr_t *)buf; 72 | fprintf(stderr, "ETHERNET header:\n"); 73 | fprintf(stderr, "\tdestination: "); 74 | print_addr_eth(ehdr->ether_dhost); 75 | fprintf(stderr, "\tsource: "); 76 | print_addr_eth(ehdr->ether_shost); 77 | fprintf(stderr, "\ttype: %d\n", ntohs(ehdr->ether_type)); 78 | } 79 | 80 | /* Prints out fields in IP header. */ 81 | void print_hdr_ip(uint8_t *buf) { 82 | sr_ip_hdr_t *iphdr = (sr_ip_hdr_t *)(buf); 83 | fprintf(stderr, "IP header:\n"); 84 | fprintf(stderr, "\tversion: %d\n", iphdr->ip_v); 85 | fprintf(stderr, "\theader length: %d\n", iphdr->ip_hl); 86 | fprintf(stderr, "\ttype of service: %d\n", iphdr->ip_tos); 87 | fprintf(stderr, "\tlength: %d\n", ntohs(iphdr->ip_len)); 88 | fprintf(stderr, "\tid: %d\n", ntohs(iphdr->ip_id)); 89 | 90 | if (ntohs(iphdr->ip_off) & IP_DF) 91 | fprintf(stderr, "\tfragment flag: DF\n"); 92 | else if (ntohs(iphdr->ip_off) & IP_MF) 93 | fprintf(stderr, "\tfragment flag: MF\n"); 94 | else if (ntohs(iphdr->ip_off) & IP_RF) 95 | fprintf(stderr, "\tfragment flag: R\n"); 96 | 97 | fprintf(stderr, "\tfragment offset: %d\n", ntohs(iphdr->ip_off) & IP_OFFMASK); 98 | fprintf(stderr, "\tTTL: %d\n", iphdr->ip_ttl); 99 | fprintf(stderr, "\tprotocol: %d\n", iphdr->ip_p); 100 | 101 | /*Keep checksum in NBO*/ 102 | fprintf(stderr, "\tchecksum: %d\n", iphdr->ip_sum); 103 | 104 | fprintf(stderr, "\tsource: "); 105 | print_addr_ip_int(ntohl(iphdr->ip_src)); 106 | 107 | fprintf(stderr, "\tdestination: "); 108 | print_addr_ip_int(ntohl(iphdr->ip_dst)); 109 | } 110 | 111 | /* Prints out ICMP header fields */ 112 | void print_hdr_icmp(uint8_t *buf) { 113 | sr_icmp_hdr_t *icmp_hdr = (sr_icmp_hdr_t *)(buf); 114 | fprintf(stderr, "ICMP header:\n"); 115 | fprintf(stderr, "\ttype: %d\n", icmp_hdr->icmp_type); 116 | fprintf(stderr, "\tcode: %d\n", icmp_hdr->icmp_code); 117 | /* Keep checksum in NBO */ 118 | fprintf(stderr, "\tchecksum: %d\n", icmp_hdr->icmp_sum); 119 | } 120 | 121 | 122 | /* Prints out fields in ARP header */ 123 | void print_hdr_arp(uint8_t *buf) { 124 | sr_arp_hdr_t *arp_hdr = (sr_arp_hdr_t *)(buf); 125 | fprintf(stderr, "ARP header\n"); 126 | fprintf(stderr, "\thardware type: %d\n", ntohs(arp_hdr->ar_hrd)); 127 | fprintf(stderr, "\tprotocol type: %d\n", ntohs(arp_hdr->ar_pro)); 128 | fprintf(stderr, "\thardware address length: %d\n", arp_hdr->ar_hln); 129 | fprintf(stderr, "\tprotocol address length: %d\n", arp_hdr->ar_pln); 130 | fprintf(stderr, "\topcode: %d\n", ntohs(arp_hdr->ar_op)); 131 | 132 | fprintf(stderr, "\tsender hardware address: "); 133 | print_addr_eth(arp_hdr->ar_sha); 134 | fprintf(stderr, "\tsender ip address: "); 135 | print_addr_ip_int(ntohl(arp_hdr->ar_sip)); 136 | 137 | fprintf(stderr, "\ttarget hardware address: "); 138 | print_addr_eth(arp_hdr->ar_tha); 139 | fprintf(stderr, "\ttarget ip address: "); 140 | print_addr_ip_int(ntohl(arp_hdr->ar_tip)); 141 | } 142 | 143 | /* Prints out all possible headers, starting from Ethernet */ 144 | void print_hdrs(uint8_t *buf, uint32_t length) { 145 | 146 | /* Ethernet */ 147 | int minlength = sizeof(sr_ethernet_hdr_t); 148 | if (length < minlength) { 149 | fprintf(stderr, "Failed to print ETHERNET header, insufficient length\n"); 150 | return; 151 | } 152 | 153 | uint16_t ethtype = ethertype(buf); 154 | print_hdr_eth(buf); 155 | 156 | if (ethtype == ethertype_ip) { /* IP */ 157 | minlength += sizeof(sr_ip_hdr_t); 158 | if (length < minlength) { 159 | fprintf(stderr, "Failed to print IP header, insufficient length\n"); 160 | return; 161 | } 162 | 163 | print_hdr_ip(buf + sizeof(sr_ethernet_hdr_t)); 164 | uint8_t ip_proto = ip_protocol(buf + sizeof(sr_ethernet_hdr_t)); 165 | 166 | if (ip_proto == ip_protocol_icmp) { /* ICMP */ 167 | minlength += sizeof(sr_icmp_hdr_t); 168 | if (length < minlength) 169 | fprintf(stderr, "Failed to print ICMP header, insufficient length\n"); 170 | else 171 | print_hdr_icmp(buf + sizeof(sr_ethernet_hdr_t) + sizeof(sr_ip_hdr_t)); 172 | } 173 | } 174 | else if (ethtype == ethertype_arp) { /* ARP */ 175 | minlength += sizeof(sr_arp_hdr_t); 176 | if (length < minlength) 177 | fprintf(stderr, "Failed to print ARP header, insufficient length\n"); 178 | else 179 | print_hdr_arp(buf + sizeof(sr_ethernet_hdr_t)); 180 | } 181 | else { 182 | fprintf(stderr, "Unrecognized Ethernet Type: %d\n", ethtype); 183 | } 184 | } 185 | 186 | -------------------------------------------------------------------------------- /cs106/gserv/cs106graphics.h: -------------------------------------------------------------------------------- 1 | /* 2 | * File: cs106graphics.h 3 | * Created by Colin Leach, July 2011 4 | * ---------------------------------------- 5 | * Implements the GraphicsHandler class 6 | * Responsible for: 7 | * - parsing client messages 8 | * - maintaining graphics state 9 | * - low-level graphics operations in the QGraphicsScene 10 | * - returning a suitable reponse 11 | * The response is always in QString format, suitable for passing 12 | * to the client program via a TCP port 13 | * 14 | * Does not maintain its own on-screen window (gWin does that) 15 | * Does not separate graphics.h functions from extgraph.h functions 16 | */ 17 | 18 | #ifndef CS106GRAPHICS_H 19 | #define CS106GRAPHICS_H 20 | 21 | #include "gwin.h" 22 | #include "graphicsarea.h" 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | QT_BEGIN_NAMESPACE 30 | class gWin; 31 | class GraphicsArea; 32 | QT_END_NAMESPACE 33 | 34 | class GraphicsHandler : public QObject 35 | { 36 | Q_OBJECT 37 | 38 | public: 39 | GraphicsHandler(QGraphicsScene *graphicsScene, 40 | gWin *pWin); 41 | ~GraphicsHandler(); 42 | QString parseMsg(QString msg); 43 | int width(); 44 | int height(); 45 | 46 | struct graphicsState { 47 | double penX; 48 | double penY; 49 | QString fontName; 50 | int pointSize; 51 | QColor penColor; 52 | QString penColorName; 53 | bool eraseMode; 54 | }; 55 | 56 | enum e_coord { 57 | INCH, // origin lower-left, values in inches" 58 | // (though the size of an "inch" may differ on your screen) 59 | CARTESIAN, // origin lower-left, values in pixels 60 | SCREEN // origin upper-left, values in pixels (the server uses this internally) 61 | }; 62 | 63 | private: 64 | // CS106 graphics methods 65 | QString initGraphics(); 66 | QString movePen(QString toX, QString toY); 67 | QString drawLine(QString dX, QString dY); 68 | QString drawArc(QString r, QString start, QString sweep); 69 | QString drawEllipticalArc(QString rx, QString ry, QString start, QString sweep); 70 | QString startFilledRegion(QString density); 71 | QString endFilledRegion(); 72 | QString updateDisplay(); 73 | QString exitGraphics(); 74 | // get status information 75 | QString getCurrentX(); 76 | QString getCurrentY(); 77 | QString getWindowWidth(); 78 | QString getWindowHeight(); 79 | QString getFullScreenwWidth(); 80 | QString getFullScreenHeight(); 81 | QString getXResolution(); 82 | QString getYResolution(); 83 | // Color suppoprt 84 | QString setPenColor(QString color); 85 | QString setPenColorRGB(QString r, QString g, QString b); 86 | QString getPenColor(); 87 | QString defineColor(QString name, QString r, QString g, QString b); 88 | // Text support 89 | QString drawTextString(QString text); 90 | QString textStringWidth(QString text); 91 | QString setFont(QString font); 92 | QString getFont(); 93 | QString setPointSize(QString pSize); 94 | QString getPointSize(); 95 | QString setStyle(QString style); 96 | QString getStyle(); 97 | QString getFontAscent(); 98 | QString getFontDescent(); 99 | QString getFontHeight(); 100 | // Mouse 101 | QString getMouseX(); 102 | QString getMouseY(); 103 | // Pictures 104 | QString drawNamedPicture(QString name); 105 | QString getPictureWidth(QString name); 106 | QString getPictureHeight(QString name); 107 | // Miscellaneous 108 | QString setCoordinateSystem(QString system); 109 | QString getCoordinateSystem(); 110 | QString setEraseMode(QString eMode); 111 | QString getEraseMode(); 112 | QString setWindowTitle(QString title); 113 | QString getWindowTitle(); 114 | QString setWindowSize(QString width, QString height); 115 | QString getWindowSize(); 116 | QString SaveGraphicsState(); 117 | QString RestoreGraphicsState(); 118 | QString PlayNamedSound(QString wavName); 119 | QString SetSoundOn(QString on); 120 | QString TestSound(); 121 | QString pause(QString secs); 122 | 123 | // helper functions 124 | void initColors(); 125 | void clearScreen(); 126 | void setBounds(); 127 | QString intToString(int n); 128 | QString doubleToString(double n); 129 | int stringToPositiveInt(QString s); 130 | double stringToPositiveDouble(QString s); 131 | double degToRad(double Angle); 132 | double ellipseRadius(double rX, double rY, double theta); 133 | Qt::BrushStyle translateDensity(double density); 134 | double xToScreen(double x); 135 | double yToScreen(double y); 136 | double deltaYToScreen(double y); 137 | double xFromScreen(double x); 138 | double yFromScreen(double y); 139 | 140 | // state variables 141 | graphicsState *_currState; 142 | QFont *_currFont; 143 | QPen *_currPen; 144 | QBrush *_currBrush; 145 | QMap _colorMap; 146 | GraphicsArea *_boundBox; 147 | QStack _savedStates; 148 | 149 | // pointer to the scene passed from gWin 150 | QGraphicsScene *_gScene; 151 | 152 | // pointer to window that implements title & size functions 153 | gWin *parentWin; 154 | 155 | // bounding rectangle is from (0,0) to (sceneWidth, sceneHeight) 156 | double _sceneWidth; 157 | double _sceneHeight; 158 | 159 | /* 160 | * The default coordinate system is defined in graphics.h 161 | * Two more are defined in extgraph.h function SetCoordinateSystem(), 162 | * which in Stanford's version does not allow you to return to the default. 163 | * As an extension, this version allows you to change freely, multiple times. 164 | * However, you will re-initialize the graphics each time and lose your 165 | * current settings. 166 | * 167 | * Valid values are in the e_coord enum 168 | */ 169 | e_coord _coord; 170 | 171 | // _fillingRegion is true after startFilledRegion() and before 172 | // endFilledRegion() 173 | bool _fillingRegion; 174 | // _fillStarted means the FilledRegion is part-constructed 175 | // and MovePen() is currently illegal 176 | bool _fillStarted; 177 | // _fillPath defines the outline for the filled region 178 | QPainterPath *_fillPath; 179 | 180 | // store basic information about pictures to avoid re-reading the files 181 | QMap _picMap; 182 | 183 | // sound? 184 | bool _soundOn; 185 | }; 186 | 187 | #define MAXTOKENS 6 188 | #define DEFWIDTH 400 189 | #define DEFHEIGHT 200 190 | #define DEFRESOLUTION 100 // pixels per inch 191 | 192 | #endif // CS106GRAPHICS_H 193 | -------------------------------------------------------------------------------- /cs106/include/private/grid.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/grid.cpp 3 | * Last modified on Fri Jun 5 16:21:12 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the implementation of the grid.h interface. 6 | * Because of the way C++ compiles templates, this code must be 7 | * available to the compiler when it reads the header file. 8 | */ 9 | 10 | #ifdef _grid_h 11 | 12 | /* 13 | * Grid class implementation 14 | * --------------------------- 15 | * The Grid is internally managed as a dynamic array of elements. The array 16 | * itself is one-dimensional, the logical separation into rows and columns 17 | * is done manually. The layout is in row-major order, which is to say that 18 | * the first entire row is laid out contiguously, followed by the entire 19 | * next row and so on. All access is bounds-checked for safety. 20 | */ 21 | 22 | template 23 | Grid::Grid() { 24 | nRows = 0; 25 | nCols = 0; 26 | timestamp = 0L; 27 | elements = NULL; 28 | } 29 | 30 | template 31 | Grid::Grid(int numRows, int numCols) { 32 | elements = NULL; 33 | timestamp = 0L; 34 | resize(numRows, numCols); 35 | } 36 | 37 | template 38 | Grid::~Grid() { 39 | delete[] elements; 40 | } 41 | 42 | template 43 | int Grid::numRows() { 44 | return nRows; 45 | } 46 | 47 | template 48 | int Grid::numCols() { 49 | return nCols; 50 | } 51 | 52 | template 53 | void Grid::resize(int numRows, int numCols) { 54 | if (numRows < 0 || numCols < 0) { 55 | Error("Attempt to resize grid to invalid size (" 56 | + IntegerToString(numRows) + ", " 57 | + IntegerToString(numCols) + ")"); 58 | } 59 | if (elements) delete[] elements; 60 | nRows = numRows; 61 | nCols = numCols; 62 | elements = new ElemType[nRows * nCols]; 63 | timestamp++; 64 | } 65 | 66 | template 67 | ElemType Grid::getAt(int row, int col) { 68 | return (*this)(row, col); 69 | } 70 | 71 | template 72 | void Grid::setAt(int row, int col, ElemType value) { 73 | (*this)(row, col) = value; 74 | } 75 | 76 | template 77 | bool Grid::inBounds(int row, int col) { 78 | return row >= 0 && col >= 0 && row < nRows && col < nCols; 79 | } 80 | 81 | template 82 | ElemType &Grid::operator()(int row, int col) { 83 | checkRange(row,col); 84 | return elements[(row * nCols) + col]; 85 | } 86 | 87 | template 88 | typename Grid::GridRow Grid::operator[](int row) { 89 | return GridRow(this, row); 90 | } 91 | 92 | template 93 | const Grid & Grid::operator=(const Grid & rhs) { 94 | if (this != &rhs) { 95 | delete[] elements; 96 | copyContentsFrom(rhs); 97 | timestamp = 0L; 98 | } 99 | return *this; 100 | } 101 | 102 | template 103 | Grid::Grid(const Grid & rhs) { 104 | copyContentsFrom(rhs); 105 | timestamp = 0L; 106 | } 107 | 108 | template 109 | void Grid::checkRange(int row, int col) { 110 | if (row < 0 || row >= numRows() || col < 0 || col >= numCols()) { 111 | Error("Attempt to access location (" 112 | + IntegerToString(row) + ", " + IntegerToString(col) 113 | + ") in a grid of size (" + IntegerToString(numRows()) 114 | + ", " + IntegerToString(numCols()) + ")"); 115 | } 116 | } 117 | 118 | template 119 | void Grid::copyContentsFrom(const Grid & other) { 120 | nRows = other.nRows; 121 | nCols = other.nCols; 122 | elements = new ElemType[nRows * nCols]; 123 | for (int i = 0; i < nRows * nCols; i++) { 124 | elements[i] = other.elements[i]; 125 | } 126 | } 127 | 128 | template 129 | void Grid::mapAll(void (*fn)(ElemType)) { 130 | long t0 = timestamp; 131 | for (int i = 0; i < nRows * nCols; i++) { 132 | if (timestamp != t0) { 133 | Error("Grid structure has been modified"); 134 | } 135 | fn(elements[i]); 136 | } 137 | } 138 | 139 | template 140 | template 141 | void Grid::mapAll(void (*fn)(ElemType, ClientDataType&), 142 | ClientDataType & data) { 143 | long t0 = timestamp; 144 | for (int i = 0; i < nRows * nCols; i++) { 145 | if (timestamp != t0) { 146 | Error("Grid structure has been modified"); 147 | } 148 | fn(elements[i], data); 149 | } 150 | } 151 | 152 | /* 153 | * Grid::Iterator class implementation 154 | * ---------------------------------- 155 | * The Iterator for Grid maintains a pointer to the original Grid and 156 | * an index into that vector that identifies the next element to return. 157 | */ 158 | 159 | template 160 | Grid::Iterator::Iterator() { 161 | gp = NULL; 162 | } 163 | 164 | template 165 | typename Grid::Iterator Grid::iterator() { 166 | return Iterator(this); 167 | } 168 | 169 | template 170 | Grid::Iterator::Iterator(Grid *gridRef) { 171 | gp = gridRef; 172 | curRow = 0; 173 | curCol = 0; 174 | timestamp = gp->timestamp; 175 | } 176 | 177 | template 178 | bool Grid::Iterator::hasNext() { 179 | if (gp == NULL) Error("hasNext called on uninitialized iterator"); 180 | if (timestamp != gp->timestamp) { 181 | Error("Grid structure has been modified"); 182 | } 183 | return curRow < gp->numRows() && curCol < gp->numCols(); 184 | } 185 | 186 | template 187 | ElemType Grid::Iterator::next() { 188 | if (gp == NULL) Error("next called on uninitialized iterator"); 189 | if (!hasNext()) { 190 | Error("Attempt to get next from iterator" 191 | " where hasNext() is false"); 192 | } 193 | int row = curRow; 194 | int col = curCol++; 195 | if (curCol == gp->numCols()) { 196 | curCol = 0; 197 | curRow++; 198 | } 199 | return (*gp)(row, col); 200 | } 201 | 202 | template 203 | ElemType Grid::foreachHook(FE_State & fe) { 204 | if (fe.state == 0) fe.iter = new Iterator(this); 205 | if (((Iterator *) fe.iter)->hasNext()) { 206 | fe.state = 1; 207 | return ((Iterator *) fe.iter)->next(); 208 | } else { 209 | fe.state = 2; 210 | return ElemType(); 211 | } 212 | } 213 | 214 | /* GridRow implementation */ 215 | 216 | template 217 | Grid::GridRow::GridRow() { 218 | /* Empty */ 219 | } 220 | 221 | template 222 | Grid::GridRow::GridRow(Grid *gridRef, int index) { 223 | gp = gridRef; 224 | row = index; 225 | } 226 | 227 | template 228 | ElemType & Grid::GridRow::operator[](int col) { 229 | return (*gp)(row,col); 230 | } 231 | 232 | #endif 233 | -------------------------------------------------------------------------------- /cs106/include/private/vector.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * File: private/vector.cpp 3 | * Last modified on Fri Jun 5 16:19:42 2009 by eroberts 4 | * ----------------------------------------------------- 5 | * This file contains the implementation of the vector.h interface. 6 | * Because of the way C++ compiles templates, this code must be 7 | * available to the compiler when it reads the header file. 8 | */ 9 | 10 | #ifdef _vector_h 11 | 12 | /* 13 | * Vector class implementation 14 | * --------------------------- 15 | * The Vector is internally managed as a dynamic array of elements. 16 | * It tracks capacity (numAllocated) separately from size (numUsed). 17 | * All access is bounds-checked for safety. 18 | */ 19 | 20 | template 21 | Vector::Vector(int capacity) { 22 | elements = new ElemType[capacity]; 23 | numAllocated = capacity; 24 | numUsed = 0; 25 | timestamp = 0L; 26 | } 27 | 28 | template 29 | Vector::~Vector() { 30 | if (elements != NULL) delete[] elements; 31 | } 32 | 33 | template 34 | inline int Vector::size() { 35 | return numUsed; 36 | } 37 | 38 | template 39 | bool Vector::isEmpty() { 40 | return size() == 0; 41 | } 42 | 43 | template 44 | ElemType Vector::getAt(int index) { 45 | checkRange(index, "getAt"); 46 | return elements[index]; 47 | } 48 | 49 | template 50 | void Vector::setAt(int index, ElemType elem) { 51 | checkRange(index, "setAt"); 52 | elements[index] = elem; 53 | } 54 | 55 | /* Private method: checkRange 56 | * -------------------------- 57 | * Verifies that index is in range for this vector, if not, raises an 58 | * error. The verb string is used in the error message to describe the 59 | * operation that caused the range error, .e.g "setAt" or "removeAt". 60 | */ 61 | 62 | template 63 | inline void Vector::checkRange(int index, const char *verb) { 64 | if (index < 0 || index >= size()) { 65 | Error("Attempt to " + string(verb) + " index " 66 | + IntegerToString(index) + " in a vector of size " 67 | + IntegerToString(size()) + "."); 68 | } 69 | } 70 | 71 | template 72 | inline ElemType &Vector::operator[](int index) { 73 | checkRange(index, "access"); 74 | return elements[index]; 75 | } 76 | 77 | template 78 | void Vector::add(ElemType elem) { 79 | insertAt(numUsed, elem); 80 | } 81 | 82 | template 83 | void Vector::insertAt(int index, ElemType elem) { 84 | if (numAllocated == numUsed) enlargeCapacity(); 85 | if (index != numUsed) checkRange(index, "insertAt"); 86 | for (int i = numUsed; i > index; i--) { 87 | elements[i] = elements[i-1]; 88 | } 89 | elements[index] = elem; 90 | numUsed++; 91 | timestamp++; 92 | } 93 | 94 | template 95 | void Vector::removeAt(int index) { 96 | checkRange(index, "removeAt"); 97 | for (int i = index; i < numUsed-1; i++) { 98 | elements[i] = elements[i+1]; 99 | } 100 | numUsed--; 101 | timestamp++; 102 | } 103 | 104 | template 105 | void Vector::clear() { 106 | delete[] elements; 107 | elements = NULL; 108 | numUsed = numAllocated = 0; 109 | timestamp++; 110 | } 111 | 112 | template 113 | const Vector &Vector::operator=(const Vector & rhs) { 114 | if (this != &rhs) { 115 | clear(); 116 | copyInternalData(rhs); 117 | timestamp = 0L; 118 | } 119 | return *this; 120 | } 121 | 122 | template 123 | Vector::Vector(const Vector & rhs) { 124 | copyInternalData(rhs); 125 | timestamp = 0L; 126 | } 127 | 128 | template 129 | void Vector::mapAll(void (*fn)(ElemType)) { 130 | long t0 = timestamp; 131 | for (int i = 0; i < numUsed; i++) { 132 | if (timestamp != t0) { 133 | Error("Vector structure has been modified"); 134 | } 135 | fn(elements[i]); 136 | } 137 | } 138 | 139 | template 140 | template 141 | void Vector::mapAll(void (*fn)(ElemType, ClientDataType&), 142 | ClientDataType & data) { 143 | long t0 = timestamp; 144 | for (int i = 0; i < numUsed; i++) { 145 | if (timestamp != t0) { 146 | Error("Vector structure has been modified"); 147 | } 148 | fn(elements[i], data); 149 | } 150 | } 151 | 152 | /* 153 | * Vector::Iterator class implementation 154 | * ---------------------------------- 155 | * The Iterator for Vector maintains a pointer to the original Vector and 156 | * an index into that vector that identifies the next element to return. 157 | */ 158 | 159 | template 160 | Vector::Iterator::Iterator() { 161 | vp = NULL; 162 | } 163 | 164 | template 165 | typename Vector::Iterator Vector::iterator() { 166 | return Iterator(this); 167 | } 168 | 169 | template 170 | Vector::Iterator::Iterator(Vector *vecRef) { 171 | vp = vecRef; 172 | curIndex = 0; 173 | timestamp = vp->timestamp; 174 | } 175 | 176 | template 177 | bool Vector::Iterator::hasNext() { 178 | if (vp == NULL) Error("hasNext called on uninitialized iterator"); 179 | if (timestamp != vp->timestamp) { 180 | Error("Vector structure has been modified"); 181 | } 182 | return curIndex < vp->size(); 183 | } 184 | 185 | template 186 | ElemType Vector::Iterator::next() { 187 | if (vp == NULL) Error("next called on uninitialized iterator"); 188 | if (!hasNext()) { 189 | Error("Attempt to get next from iterator" 190 | " where hasNext() is false"); 191 | } 192 | return (*vp)[curIndex++]; 193 | } 194 | 195 | template 196 | ElemType Vector::foreachHook(FE_State & fe) { 197 | if (fe.state == 0) fe.iter = new Iterator(this); 198 | if (((Iterator *) fe.iter)->hasNext()) { 199 | fe.state = 1; 200 | return ((Iterator *) fe.iter)->next(); 201 | } else { 202 | fe.state = 2; 203 | return ElemType(); 204 | } 205 | } 206 | 207 | /* Private method: enlargeCapacity 208 | * ------------------------------- 209 | * Doubles the current capacity of the vector's internal storage, 210 | * copying all existing values. 211 | */ 212 | 213 | template 214 | void Vector::enlargeCapacity() { 215 | numAllocated = (numAllocated == 0 ? 10 : numAllocated*2); 216 | ElemType *newArray = new ElemType[numAllocated]; 217 | for (int i = 0; i < numUsed; i++) { 218 | newArray[i] = elements[i]; 219 | } 220 | delete[] elements; 221 | elements = newArray; 222 | } 223 | 224 | /* Private method: copyInternalData 225 | * -------------------------------- 226 | * Common code factored out of the copy constructor and operator= to 227 | * copy the contents from the other vector. 228 | */ 229 | 230 | template 231 | void Vector::copyInternalData(const Vector & other) { 232 | elements = new ElemType[other.numUsed]; 233 | for (int i = 0; i < other.numUsed; i++) { 234 | elements[i] = other.elements[i]; 235 | } 236 | numUsed = other.numUsed; 237 | numAllocated = other.numUsed; 238 | } 239 | 240 | #endif 241 | --------------------------------------------------------------------------------