Пример #1
0
 bool empty() const { return in.empty() and out.empty(); }
Пример #2
0
void TestRunner::uninit3()
{
    const QString app("uninit3");
    m_expectCrash = true;
    const QString binary = runTestBinary(app + QDir::separator() + app);
    const QString srcDir = srcDirForApp(app);

    QVERIFY(m_logMessages.isEmpty());

    QCOMPARE(m_errors.count(), 2);
    //BEGIN first error
    {
    const Error error = m_errors.first();
    QCOMPARE(error.kind(), int(UninitValue));
    QCOMPARE(error.stacks().count(), 2);
    //BEGIN first stack
    {
    const Stack stack = error.stacks().first();
    QCOMPARE(stack.line(), qint64(-1));
    QCOMPARE(stack.frames().count(), 1);

    const Frame frame = stack.frames().first();
    QCOMPARE(frame.functionName(), QString("main"));
    QCOMPARE(frame.line(), 4);

    QCOMPARE(frame.object(), binary);
    QCOMPARE(frame.file(), QLatin1String("main.cpp"));
    QCOMPARE(QDir::cleanPath(frame.directory()), srcDir);
    }
    //BEGIN second stack
    {
    const Stack stack = error.stacks().last();
    QCOMPARE(stack.line(), qint64(-1));
    QCOMPARE(stack.frames().count(), 1);

    const Frame frame = stack.frames().first();
    QCOMPARE(frame.functionName(), QString("main"));
    QCOMPARE(frame.line(), 2);

    QCOMPARE(frame.object(), binary);
    QCOMPARE(frame.file(), QLatin1String("main.cpp"));
    QCOMPARE(QDir::cleanPath(frame.directory()), srcDir);
    }
    }
    //BEGIN second error
    {
    const Error error = m_errors.last();
    QCOMPARE(error.kind(), int(InvalidRead));
    QCOMPARE(error.stacks().count(), 1);

    const Stack stack = error.stacks().first();
    QCOMPARE(stack.line(), qint64(-1));
    QCOMPARE(stack.frames().count(), 1);

    const Frame frame = stack.frames().first();
    QCOMPARE(frame.functionName(), QString("main"));
    QCOMPARE(frame.line(), 4);

    QCOMPARE(frame.object(), binary);
    QCOMPARE(frame.file(), QLatin1String("main.cpp"));
    QCOMPARE(QDir::cleanPath(frame.directory()), srcDir);
    }
}
Пример #3
0
void testStack() {
    Stack<int> mycontainer;

    cout << "\n\n Begin test function for the Stack<T> class\n";

    // Testing the push function
    cout << "Testing size of new empty container: " << mycontainer.length() << endl;

    mycontainer.push(1);
    cout << "Testing push(1), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    cout << "Size is " << mycontainer.length() << endl;

    mycontainer.push(2);
    cout << "Testing push(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    cout << "Size is " << mycontainer.length() << endl;

    mycontainer.push(2);
    cout << "Testing push(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    cout << "Size is " << mycontainer.length() << endl;

    mycontainer.push(2);
    cout << "Testing push(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    cout << "Size is " << mycontainer.length() << endl;

    mycontainer.push(2);
    cout << "Testing push(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    cout << "Size is " << mycontainer.length() << endl;

    mycontainer.push(2);
    cout << "Testing push(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    cout << "Size is " << mycontainer.length() << endl << endl;

    int size = mycontainer.length();
    cout << "Testing pop(), top(), length() and isEmpty() functions \n"
            << "in a for loop with iterations greater than container size.";
    for (int i = 0; i < size + 1; i++) {
        cout << "\nIteration: " << i + 1 << "\n";
        if (!mycontainer.isEmpty()) {
            cout << " mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n");
            cout << "Stack size before pop is " << mycontainer.length() << endl;
            cout << "Top of container is " << mycontainer.top() << endl;
            mycontainer.pop();
        } else {
            cout << "The Stack is empty.\n";
        }

        cout << "Stack size is now: " << mycontainer.length() << endl;
    }
    cout << "\nFinished for loop\n";

    cout << "\nTesting the reference for top() function.\n";
    cout << "Start with int test = 7. mycontainer.push(test)\n";
    int test = 7;
    mycontainer.push(test);
    cout << "Testing with test = 8. test=mycontainer.top(). mycontainer.top() = 13 \n";
    test = 8;
    test = mycontainer.top();
    mycontainer.top() = 13;
    cout << "Test is now " << test << " front of container is " << mycontainer.top() << "\n";
    test = 11;
    mycontainer.push(test);
    cout << "Test is now " << test << " top of container is " << mycontainer.top() << "\n";

    mycontainer.top() = test;
    cout << "Test is now " << test << " top of container is " << mycontainer.top() << "\n";


    cout << "\nmycontainer size is " << mycontainer.length() << endl;
    cout << "\nTesting the clear() function: \n";
    mycontainer.clear();
    cout << "mycontainer size now is " << mycontainer.length()
            << " mycontainer is empty: "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");

    cout << "\nTesting assignment operator: container2 = mycontainer\n";
    cout << "Filling mycontainer with ints starting at 42\n";
    size = 5;
    // Fill mycontainer with ints to test copy constructor
    for (int i = 0; i < size; i++) {
        mycontainer.push(i + 41);
    }

    cout << "mycontainer size now is " << mycontainer.length()
            << " mycontainer is empty: "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");

    Stack<int> container2;
    container2 = mycontainer;
    cout << "mycontainer size is: " << mycontainer.length() << endl;
    cout << "container2 size now is " << container2.length()
            << " container is empty: "
            << (container2.isEmpty() ? " true\n" : "false\n");

    cout << "Testing the contents of container2 and mycontainer using pop() functions:\n";
    size = container2.length();
    for (int i = 0; i < size; i++) {
        cout << "Attempting front and pop functions. Iteration: " << i + 1 << "\n";

        // Don't perform the operation if either container is empty. 
        // Output should be the same for both containers
        if (!container2.isEmpty() || !mycontainer.isEmpty()) {
            cout << "\tcontainer2 - top(): " << container2.top() << endl;
            container2.pop();
            cout << "\tmycontainer - top(): " << mycontainer.top() << endl;
            mycontainer.pop();
        } else {
            cout << "Containers are empty.\n";
        }
    }

    cout << "\nTesting the copy constructor. Filling mycontainer ints\n";
    size = 5;
    // Fill mycontainer with ints to test copy constructor
    for (int i = 0; i < size; i++) {
        mycontainer.push(i + 41);
    }

    cout << "mycontainer size now is " << mycontainer.length()
            << " mycontainer is empty: "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");

    Stack<int> container3(mycontainer);

    cout << "container3 size is: " << container3.length();
    cout << "\nTesting the contents of container3 and mycontainer using back() and pop() functions:\n";
    size = container3.length();
    for (int i = 0; i < size; i++) {
        cout << "Attempting front and pop functions. Iteration: " << i + 1 << "\n";

        // Don't perform the operation if either container is empty. 
        // Output should be the same for both containers
        if (!container3.isEmpty() || !mycontainer.isEmpty()) {
            cout << "\tcontainer3 - top(): " << container3.top() << "\n";
            container3.pop();
            cout << "\tmycontainer - front(): " << mycontainer.top() << "\n";
            mycontainer.pop();
        } else {
            cout << "Containers are empty.\n";
        }
    }
    cout << "\nEnd of test function for the Stack<T> class\n\n";
}
Пример #4
0
TEST(Stack, isnt_full_stack_IsFull_0)
{
	Stack<int> *S = new Stack<int>;
	S->Push(1);
	EXPECT_EQ(0, S->IsFull());
}
//---------------------------------------------------------
// Compute x-coordinates (LP-based approach) (for cluster graphs)
//---------------------------------------------------------
void OptimalHierarchyClusterLayout::computeXCoordinates(
	const ExtendedNestingGraph& H,
	ClusterGraphCopyAttributes &AGC)
{
	const ClusterGraphCopy &CG = H.getClusterGraph();

	const int k = H.numberOfLayers();

	//
	// preprocessing: determine nodes that are considered as virtual
	//
	m_isVirtual.init(H);

	int i;
	for(i = 0; i < k; ++i)
	{
		int last = -1;

		// Process nodes on layer i from left to right
		Stack<const LHTreeNode*> S;
		S.push(H.layerHierarchyTree(i));
		while(!S.empty())
		{
			const LHTreeNode *vNode = S.pop();

			if(vNode->isCompound()) {
				for(int j = vNode->numberOfChildren()-1; j >= 0; --j)
					S.push(vNode->child(j));

			} else {
				node v = vNode->getNode();

				if(H.isLongEdgeDummy(v) == true) {
					m_isVirtual[v] = true;

					edge e = v->firstAdj()->theEdge();
					if(e->target() == v)
						e = v->lastAdj()->theEdge();
					node u = e->target();

					if(H.verticalSegment(e) == false)
						continue;

					if(H.isLongEdgeDummy(u) == true) {
						int down = H.pos(u);
						if(last != -1 && last > down) {
							m_isVirtual[v] = false;
						} else {
							last = down;
						}
					}
				} else {
					m_isVirtual[v] = false;
				}
			}
		}
	}

	//
	// determine variables of LP
	//
	int nSegments     = 0; // number of vertical segments
	int nRealVertices = 0; // number of real vertices
	int nEdges        = 0; // number of edges not in vertical segments
	int nBalanced     = 0; // number of real vertices with deg > 1 for which balancing constraints may be applied

	m_vIndex.init(H,-1); // for real node: index of x[v] for dummy: index of corresponding segment
	NodeArray<int> bIndex(H,-1); // (relative) index of b[v]
	EdgeArray<int> eIndex(H,-1); // for edge not in vertical segment: its index
	Array<int> count(H.numberOfEdges());	// counts the number of dummy vertices
											// in corresponding segment that are not at
											// position 0

	int nSpacingConstraints = 0;
	for(i = 0; i < k; ++i)
	{
		Stack<const LHTreeNode*> S;
		S.push(H.layerHierarchyTree(i));
		while(!S.empty())
		{
			const LHTreeNode *vNode = S.pop();

			if(vNode->isCompound()) {
				cluster c = vNode->originalCluster();

				if(H.isVirtual(c) == false)
					nSpacingConstraints += (c == CG.rootCluster()) ? 1 : 2;

				for(int j = vNode->numberOfChildren()-1; j >= 0; --j)
					S.push(vNode->child(j));

			} else {
				node v = vNode->getNode();

				// ignore dummy nodes and nodes representing cluster
				// (top or bottom) border
				if(H.type(v) == ExtendedNestingGraph::ntClusterBottom || H.type(v) == ExtendedNestingGraph::ntClusterTop)
					continue;

				++nSpacingConstraints;

				// ignore dummy nodes
				if(m_isVirtual[v] == true)
					continue;

				// we've found a real vertex
				m_vIndex[v] = nRealVertices++;
				if(v->degree() > 1)
					bIndex[v] = nBalanced++;

				// consider all outgoing edges
				edge e;
				forall_adj_edges(e,v) {
					node w = e->target();
					if(w == v)
						continue;

					// we've found an edge not belonging to a vetical segment
					eIndex[e] = nEdges++;

					if(m_isVirtual[w] == false)
						continue;

					do {
						// we've found a vertical segment
						count[nSegments] = 0;
						do {
							m_vIndex[w] = nSegments;
							count[nSegments] += 2;

							// next edge / dummy in segment
							e = e->adjTarget()->cyclicSucc()->theEdge();
							w = e->target();
						} while(m_isVirtual[w] && H.verticalSegment(e));

						++nSegments;

						// edge following vertical segment
						eIndex[e] = nEdges++;

					} while(m_isVirtual[w]);
				}
			}
		}
	}
Пример #6
0
/**********************************************************************
 * MAIN: Simple driver program to exercise our Stack data type
 ***********************************************************************/
int main()
{
   //
   // Integer Stack
   //

   cout << "#### Integers ####\n";
   Stack <int> stack; 
   int value;

   // add three to the stack
   for (int i = 0; i < 3; i++)
   {
      cout << "push: ";
      cin >> value;
      stack.push(value);
   }
   
   // remove one just for kicks
   stack.pop(value);
   cout << "\tpop: " << value << endl;

   // add three more
   for (int i = 0; i < 3; i++)
   {
      cout << "push: ";
      cin >> value;
      stack.push(value);
   }

   // remove them all 
   while (stack.pop(value))
      cout << "\tpop: " << value << endl;
   assert(stack.isEmpty());

   //
   // String Stack
   //

   cout << "#### Strings ####\n";
   Stack <string> stringStack;
   string stringValue;

   // add three to the stack
   for (int i = 0; i < 3; i++)
   {
      cout << "push: ";
      cin >> stringValue;
      stringStack.push(stringValue);
   }

   // remove one just for kicks
   stringStack.pop(stringValue);
   cout << "\tpop: " << stringValue << endl;

   // add three more
   for (int i = 0; i < 3; i++)
   {
      cout << "push: ";
      cin >> stringValue;
      stringStack.push(stringValue);
   }

   // remove them all
   while (stringStack.pop(stringValue))
      cout << "\tpop: " << stringValue << endl;
   assert(stringStack.isEmpty());
   
   return 0;
}
Пример #7
0
TEST(Stack, empty_stack_IsEmpty_1)
{
	Stack<int> *S = new Stack<int>;
	EXPECT_EQ(1, S->IsEmpty());
}
Пример #8
0
int main()
{	
	Stack<double, 30> d;
    Stack<char , 20> s;
	s.push('+');
	s.push('-');
	s.push('*');
	s.push('/');
	cout << typeid(s).name() << endl;
	cout << typeid(d).name() << endl;
	while(!s.empty())
		cout << s.pop() << endl;
	d.push(100);
	d.push(60);
	d.push(234.34);d.push(324.234);
	while(!d.empty())
		cout << d.pop() << endl;
	
}
Пример #9
0
void testSeq(int *A, int size){
    for (int i=0; i<size; i++) S.push(A[i]);
    qDebug() << "After " << size << " push operations, size:" << S.getSize();
}
Пример #10
0
bool EXECUTE(int ret_inst)
{
  cout << "\n\t At any time during the exection of the program, the following keywords can be used\n";
  cout << "\t'rc' : To change   the current register contents\n";
  cout << "\t'rd' : To display  the current register contents\n";
  cout << "\t'md' : To display  the current memory and register contents\n";
  cout << "\t'mc' : To change   the current execution mode\n";
  cout << "\t'rc' : To change   the current break point state \n";
  cout << "\t'fp' : To print all the current flag contents\n";
  string tmp = "" , mode = "";
  char input[100];input[0]=0;
  cout << "\n  Set the Execution Mode by pressing one of the following :\n";
  cout << "\t'm' : execute Microinstruction by Microinstruction\n";
  cout << "\t'i' : execute Instruction by Instruction\n";
  cout << "\t'p' : execute entire program (default mode)\n";
  strcpy(input,"p");
  while (true)
    {
      cout << "\tExecution Mode : ";
      getchar();
      scanf("%[^\n]",input);
      mode = input ;
      if (mode != "p" && mode !="m" && mode!="i")
	{
	  cout << "Invalid Entry . Press (m/i/p) .\n";
	  continue ;
	}
      break;
    }
  cout << "\tPress 'bp' to set additional break-points besides (brk) in the program  : ";
  getchar();
  scanf("%[^\n]",input);
  tmp = input ;
  bool be = false ;
  if (tmp == "bp")
    {
      if (SetBreakPoints() == false )
	return false ;
    }
  cout << "\tPress be/bd to enable/disable all break-points (default disable)\n";
  string Microinstruction="";
  int count_inst = -1; // Counter to count the number of instructions executed
  cout << "\n\tProgram Execution Begins .......\n\n";
  while ( TRUE )
    {
      /*
	This is the main loop. All modules are executed in this order. NOTICE
      */
      ret_inst = MS.Sequencer(ret_inst , DC , FL);
      if (ret_inst == 0)
	count_inst++;
      Microinstruction = MPM.Fetch(ret_inst);
      PC.Operation(Microinstruction , DB);		//Program Counter Module
      MR.Operation(Microinstruction,DB);		//Memory Address Module
      Mem.Operation(Microinstruction,DB,MR);		//Memory Address Module
      DC.Operation(Microinstruction,DB);		//Decoder Module
      MS.Operation(Microinstruction,DC);		//MicroSequencer Module
      IOR.Operation(Microinstruction,DB,RG,FL);	//Instr. Oper. Register Module
      RG.Operation(Microinstruction,DB,PC,SP,AC,OP,ALU1);		//Register File Module
      OP.Operation(Microinstruction,DB);		//Operand Module
      AC.S_Operation(Microinstruction,DB);		// Special Accumulator Operation (only to EAR)
      ALU1.Operation(Microinstruction,DB,OP,FL);	//ALU Module
      AC.Operation(Microinstruction,DB,ALU1);		//Accumulator Module
      SP.Operation(Microinstruction,DB);		//Stack Module
      MR.Operation(Microinstruction,DB);		//Memory Address Module
      Mem.Operation(Microinstruction,DB,MR);		//Memory Address Module
      RG.Operation(Microinstruction,DB,PC,SP,AC,OP,ALU1);		//Register File Module
      OP.Operation(Microinstruction,DB);		//Operand Module
      PC.S_Operation(Microinstruction, DB);		// Special PC Operation
      //		FL.Operation(Microinstruction);			//Flag Register Module (only to LPC)
      if (Microinstruction == "000000000000000000001000000000000000000000")
	break;
      clocks++;
      if (Print(mode,count_inst,ret_inst,Microinstruction , be) ==  false)
	return false;
    }
  return true;
}
Пример #11
0
int main(int argc , char *argv[])
{

  //	Setting the Flag lookup table /*   May have to take this from user ..... check later */
  flag_lookup["u"]	="000";
  flag_lookup["z"]	="001";
  flag_lookup["nz"]	="010";
  flag_lookup["p"]	="011";
  flag_lookup["m"]	="100";
  flag_lookup["c"]	="101";
  flag_lookup["nc"]	="110";
  flag_lookup["op"]	="111";
  //	Flag lookup table completed

  //	Feeding the first three locations of MicroProgram Memory 	 /*HAS TO BE USER FED */
  //	            00000000001111111111222222222233333333334
  //	            01234567890123456789012345678901234567890
  MPM.Addr_MS[0] = "00000000000000000000000000000010010000000";
  MPM.Addr_MS[1] = "00000000000000000000000001000001000110000";
  MPM.Addr_MS[2] = "00000000000000000000000100000000000000000";

  //	Scanning of User's instruction set is done by a different module

  bool ret = Scan_init(MPM,ALU1,RG,Mem);
  if (ret == false  )
    {
      cout << "\nProblem in scanning the design file. Please correct the file and try again\n";
      return -1 ;// Problem in scanning
    }

  //	Scanning of User's input program file is done by a different module
  char ch = 'n';

  if (errno)
    {
      perror ("Pre-execution error ");
      return -1;
    }

  while ( TRUE )
    {
      MS.clear();
      labels.clear();
      label_lookup.clear();
      breaks.clear();
      ret = Scan_input(Mem,ALU1,RG);
      if (ret == false)
	{
	  cout << "\nProblem with the user program file. Please correct the file and try again.\n"; 
	  return -1 ;
	}

      //	 NEW ADDED  -   Date 16th Nov 2009
      //	 Scaning a memory input file from the user
      if ( false == Mem.FillMemory())
	{
	  return -1;
	}

      //	Initializing Modules
      PC.Init("00000000");   /* Change */
      SP.Init();
      //	Modules initialized

      if (errno)
	{
	  perror ("Input file error  ");
	  return -1;
	}

      //	Initializing Databus
      strcpy(DB.DATA,"");
      DB.FLAG = FREE;

      //	Initial Memory Map
      cout << "\tDo you want to print the initial contents of Memory and Registers ? [y/n] : ";
      cin >> ch;
      if (ch == 'y')
	Disp.InitialMap(Mem,RG,PC,AC,OP,SP);

      //	Execution of Program
      bool val = EXECUTE(0);

      if (errno)
	{
	  perror("Error in execution ");
	  break;
	}

      //	Final Memory Map
      cout << "\tDo you want to print the final contents of Memory and Registers [y/n]?  : ";
      cin >> ch;
      if (ch == 'y')
	Disp.FinalMap(Mem,RG,PC,AC,OP,SP);
		
      cout << "\n\tTotal number of clock cycles taken to run the program  :\t"<<clocks<<"\n\n";
		
      cout << "\n\tDo you want to run another program [y/n] ? :";
      cin >> ch;
      if (ch !='y')
	break;
      labels.clear();
      clocks = 0;
      label_lookup.clear();
      breaks.clear();
    }
  return 0;
}
Пример #12
0
 void pop() throw(underflow) 
 { 
     if (empty()) throw underflow();
     in_to_out(); 
     out.pop(); 
 }
Пример #13
0
 void push(const T& x) { in.push(x); }
Пример #14
0
 size_type size() const { return in.size()+out.size(); }
Пример #15
0
int main()
{
    // Testing List
    List<std::string> list;
    std::cout << "Is the list empty? = " << list.empty() << std::endl;
    std::string line;
    std::ifstream myfile ("datain.dat");
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,line);
            list.push_back(line);
        }
        myfile.close();
    }
    list.sort();
    std::ofstream outfile("output.txt");
    outfile << "List in ascending output (strings): " << std::endl << std::endl;
    if (outfile.is_open())
    {
        for (List<std::string>::iterator it = list.begin(); it != list.end(); ++it)
            outfile << *it << std::endl;
    }

    list.sort("desc");
    std::ofstream desc_outfile("output2.txt");
    desc_outfile << "List in descending output (strings): " << std::endl << std::endl;
    if (desc_outfile.is_open())
    {
        for (List<std::string>::iterator it = list.begin(); it != list.end(); ++it)
            desc_outfile << *it << std::endl;
    }

    
    std::cout << "pop back is " << list.pop_back() << std::endl;
    list.remove(list.begin() + 2);
    List<std::string>::iterator iters = list.begin();
    std::cout << " get next is " << iters.get_next() << std::endl;
    list.push_back(*iters);

    std::cout << "size is " << list.size() << std::endl;
    List<std::string> list2 = list;
    for (List<std::string>::iterator iter = list2.begin();
         iter != list2.end(); ++iter)
    {
        std::cout << (*iter) << std::endl;
    }
    std::cout << "search result " << list.search("5") << std::endl;
    std::cout << "get_head() " << list.get_head() << std::endl;
    List<std::string>::iterator it = list.begin() + 1;
    std::cout << "has_next() " << it.has_next() << std::endl;

    // Stack testing
    Stack<std::string> stack;
    std::cout << "stack.empty() (should be 1) " << stack.empty() << std::endl;
    std::ifstream my_stack_file ("datain.dat");
    if (my_stack_file.is_open())
    {
        while ( my_stack_file.good() )
        {
            getline (my_stack_file,line);
            stack.push(line);
        }
        my_stack_file.close();
    }
    stack.pop();
    std::cout << "stack top is " << stack.show_top() << std::endl;
    std::cout << "stack.empty() " << stack.empty() << std::endl;
    std::cout << "stack.is_full() " << stack.is_full() << std::endl;

    std::ofstream stack_out("stack_output.txt");
    stack_out << "Popping stack output ( minus 1): " << std::endl << std::endl;
    while (!stack.empty())
        stack_out << stack.pop() << std::endl;

    // Testing Queue
    Queue<std::string> queue;
    std::cout << "queue.empty() (should be 1) " << queue.empty() << std::endl;
    std::ifstream my_queue_file ("datain.dat");
    if (my_queue_file.is_open())
    {
        while ( my_queue_file.good() )
        {
            getline (my_queue_file,line);
            queue.enqueue(line);
        }
        my_queue_file.close();
    }
    std::cout << "searching queue for '5': " << queue.search("5") << std::endl;
    std::cout << "queue.empty() (should be 0) " << queue.empty() << std::endl;
    std::ofstream queue_out("queue_output.txt");
    queue.sort();
    queue_out << "Dequeue queue output sorted ascending: " << std::endl << std::endl;
    while (!queue.empty())
        queue_out << queue.dequeue() << std::endl;
    if (my_queue_file.is_open())
    {
        while ( my_queue_file.good() )
        {
            getline (my_queue_file,line);
            queue.enqueue(line);
        }
        my_queue_file.close();
    }
    std::ofstream queue_out_desc("queue_output_Desc.txt");
    queue.sort("desc");;
    queue_out_desc << "Dequeue queue output sorted descending: " << std::endl << std::endl;
    while (!queue.empty())
        queue_out_desc << queue.dequeue() << std::endl;

    std::cout << "queue.is_full(): " << stack.is_full() << std::endl;

    std::cin.ignore();
}
Пример #16
0
void Level::remove(Vector target) {
    Stack<GameObject*>* stack = this->tiles[target.y][target.x];
    if (stack) {
        stack->pop();
    }
}
Пример #17
0
int main(/*int argc, char *argv[]*/)
{
    Stack<string> s;
#ifdef DEBUG
    assert(s.size() == 0);
#endif
    try{
        s.pop();
    } catch(string e){
        cout << e << endl;
    }

    s.push("Hello11");
    s.push("Hello22");
    s.push("Hello33");
#ifdef DEBUG
    assert(s.size() == 3);
#endif
    string str = s.getElement();
    s.pop();
#ifdef DEBUG
    assert(s.size() == 2);
#endif
    cout << "String: " << str << endl;
    s.clear();
#ifdef DEBUG
    assert(s.size() == 0);
#endif
    return 0;
}
Пример #18
0
void Level::charToObject(int i, int j, char c, bool empty) {
    if (c == ' ') {
        return;
    }

    Stack<GameObject*>* stack;
    if (this->tiles[i][j] == NULL) {
        stack = new Stack<GameObject*>();
        this->tiles[i][j] = stack;
    }
    else {
        stack = this->tiles[i][j];
    }

    GameObject* gobj = NULL;

    if (!empty) {
        switch(c) {
        case Global::VWallSymbol:
        case Global::HWallSymbol:
        case Global::FloorSymbol:
        case Global::PassageSymbol:
        case Global::DoorSymbol:
            break;

        // Potions!
        case Global::RHPotionSymbol:
            gobj = this->game->addObject(RHPotionKind);
            break;
        case Global::BAPotionSymbol:
            gobj = this->game->addObject(BAPotionKind);
            break;
        case Global::BDPotionSymbol:
            gobj = this->game->addObject(BDPotionKind);
            break;
        case Global::PHPotionSymbol:
            gobj = this->game->addObject(PHPotionKind);
            break;
        case Global::WAPotionSymbol:
            gobj = this->game->addObject(WAPotionKind);
            break;
        case Global::WDPotionSymbol:
            gobj = this->game->addObject(WDPotionKind);
            break;

        // Gold!
        case Global::GoldSmallSymbol:
            gobj = this->game->addObject(GoldSmallKind);
            break;
        case Global::GoldNormalSymbol:
            gobj = this->game->addObject(GoldNormalKind);
            break;
        case Global::GoldMerchantSymbol:
            gobj = this->game->addObject(GoldMerchantKind);
            break;
        case Global::GoldDragonSymbol:
            gobj = this->game->addObject(GoldDragonKind);
            break;

        case Global::HumanSymbol:
            gobj = this->game->addObject(HumanKind);
            break;
        case Global::DwarfSymbol:
            gobj = this->game->addObject(DwarfKind);
            break;
        case Global::ElfSymbol:
            gobj = this->game->addObject(ElfKind);
            break;
        case Global::OrcSymbol:
            gobj = this->game->addObject(OrcKind);
            break;
        case Global::MerchantSymbol:
            gobj = this->game->addObject(MerchantKind);
            break;
        case Global::HalflingSymbol:
            gobj = this->game->addObject(HalflingKind);
            break;
        case Global::DragonSymbol:
            gobj = this->game->addObject(DragonKind);
            break;

        case Global::StairsSymbol:
            gobj = this->game->addObject(StairsKind);
            this->stairs = gobj;
            break;

        case Global::PlayerSymbol:
            this->spawn.x = j;
            this->spawn.y = i;
            break;

        default:
            gobj = this->game->addObject(DoorKind);
            break;
        }
    }
    else {
        switch(c) {
        case Global::VWallSymbol:
            gobj = this->game->addObject(VWallKind);
            break;
        case Global::HWallSymbol:
            gobj = this->game->addObject(HWallKind);
            break;

        case Global::Chamber1Symbol:
        case Global::Chamber2Symbol:
        case Global::Chamber3Symbol:
        case Global::Chamber4Symbol:
        case Global::Chamber5Symbol:
        {
            gobj = this->game->addObject(FloorKind);
            int num;
            stringstream convert;
            convert << c;
            convert >> num;
            Vector v;
            v.x = j;
            v.y = i;
            this->chambers[num].push_back(v);
            break;
        }
        case Global::PassageSymbol:
            gobj = this->game->addObject(PassageKind);
            break;
        case Global::DoorSymbol:
            gobj = this->game->addObject(DoorKind);
            break;
        default:
            gobj = NULL;
            break;
        }
    }

    if (gobj) {
        gobj->setPosition(j, i);
        stack->push(gobj);
    }
}
Пример #19
0
void add_queue(Stack<Queue<temp_automaton>>& s) {
	Queue<temp_automaton> q;
	temp_automaton a;
	q.push(a);
	s.push(q);
}
void
ThreadStackHelper::GetNativeStack(Stack& aStack)
{
#ifdef MOZ_THREADSTACKHELPER_NATIVE
  ThreadContext context;
  context.mStack = MakeUnique<uint8_t[]>(ThreadContext::kMaxStackSize);

  ScopedSetPtr<ThreadContext> contextPtr(mContextToFill, &context);

  // Get pseudostack first and fill the thread context.
  GetStack(aStack);
  NS_ENSURE_TRUE_VOID(context.mValid);

  CodeModulesProvider modulesProvider;
  google_breakpad::BasicCodeModules modules(&modulesProvider);
  google_breakpad::BasicSourceLineResolver resolver;
  google_breakpad::StackFrameSymbolizer symbolizer(nullptr, &resolver);

#if defined(MOZ_THREADSTACKHELPER_X86)
  google_breakpad::StackwalkerX86 stackWalker(
    nullptr, &context.mContext, &context, &modules, &symbolizer);
#elif defined(MOZ_THREADSTACKHELPER_X64)
  google_breakpad::StackwalkerAMD64 stackWalker(
    nullptr, &context.mContext, &context, &modules, &symbolizer);
#elif defined(MOZ_THREADSTACKHELPER_ARM)
  google_breakpad::StackwalkerARM stackWalker(
    nullptr, &context.mContext, -1, &context, &modules, &symbolizer);
#else
  #error "Unsupported architecture"
#endif

  google_breakpad::CallStack callStack;
  std::vector<const google_breakpad::CodeModule*> modules_without_symbols;

  google_breakpad::Stackwalker::set_max_frames(ThreadContext::kMaxStackFrames);
  google_breakpad::Stackwalker::
    set_max_frames_scanned(ThreadContext::kMaxStackFrames);

  NS_ENSURE_TRUE_VOID(stackWalker.Walk(&callStack, &modules_without_symbols));

  const std::vector<google_breakpad::StackFrame*>& frames(*callStack.frames());
  for (intptr_t i = frames.size() - 1; i >= 0; i--) {
    const google_breakpad::StackFrame& frame = *frames[i];
    if (!frame.module) {
      continue;
    }
    const string& module = frame.module->code_file();
#if defined(XP_LINUX) || defined(XP_MACOSX)
    const char PATH_SEP = '/';
#elif defined(XP_WIN)
    const char PATH_SEP = '\\';
#endif
    const char* const module_basename = strrchr(module.c_str(), PATH_SEP);
    const char* const module_name = module_basename ?
                                    module_basename + 1 : module.c_str();

    char buffer[0x100];
    size_t len = 0;
    if (!frame.function_name.empty()) {
      len = PR_snprintf(buffer, sizeof(buffer), "%s:%s",
                        module_name, frame.function_name.c_str());
    } else {
      len = PR_snprintf(buffer, sizeof(buffer), "%s:0x%p",
                        module_name, (intptr_t)
                        (frame.instruction - frame.module->base_address()));
    }
    if (len) {
      aStack.AppendViaBuffer(buffer, len);
    }
  }
#endif // MOZ_THREADSTACKHELPER_NATIVE
}
Пример #21
0
TEST(Stack, isnt_empty_stack_IsEmpty_0)
{
	Stack<int> *S = new Stack<int>;
	S->Push(1);
	EXPECT_EQ(0, S->IsEmpty());
}
Пример #22
0
			/** \memberof Machine */
			inline Counter depth() const {
				return callbacks.size();
			}
Пример #23
0
TEST(Stack, can_push)
{
	Stack<int> *S = new Stack<int>;
	ASSERT_NO_THROW(S->Push(3));
}
void izraz(char a[1000])
{
    int br=0;
    char c[1200];
    Stack<char> b;
    Stack<char> d;
    /// pravi izraz samo ot znacite
for(int i=0;i<1000;i++)
{
    if(a[i]<='0'||a[i]>='9')
    {
        b.push(a[i]);
    }

}

   while(!b.isempty())
   {
       if(b.top()=='(')
       {
           d.push(b.pop());
       }
       if(b.top()=='-'|| b.top()=='+')
       {
           d.push(b.pop());
          if(b.top()=='*'|| b.top()=='/')
          {
              d.push(')');
              d.push(b.pop());
          }
          else d.push(b.pop());
       }
   }
   ///dobavq 4islata kum znacite
   int i;
   while(a[i]<='0'||a[i]>='9')
   {
       c[i]=a[i];
       d.pop();
   }
    int j=i;
for( i=0;i<1000;i++)
{
    if(a[i]>='0'||a[i]<='9')
    {
        c[j]=a[i];
        c[j+1]=d.pop();
        if((a[i+2]<='0'||a[i+2]>='9')&&(i+3<=1000))
        {
            c[j+2]=d.pop();
            i=i+3;
            if(d.top()=')')
            {c[j+3]=d.pop();
            j=j+4;

            }
            else j=j+3;
        }


    }

}
for(int i=0;i<1200;i++)
{
    cout<<c[i];
}
}
Пример #25
0
void TestRunner::testLeak4()
{
    const QString app("leak4");
    const QString binary = runTestBinary(app + QDir::separator() + app,
                                         QStringList() << "--show-reachable=yes");
    const QString srcDir = srcDirForApp("leak4");

    QVERIFY(m_logMessages.isEmpty());

    QCOMPARE(m_errors.count(), 2);
    //BEGIN first error
    {
    const Error error = m_errors.first();
    QCOMPARE(error.kind(), int(Leak_IndirectlyLost));
    QCOMPARE(error.leakedBlocks(), qint64(1));
    QCOMPARE(error.leakedBytes(), quint64(8));
    QCOMPARE(error.stacks().count(), 1);
    const Stack stack = error.stacks().first();
    QCOMPARE(stack.line(), qint64(-1));
    QCOMPARE(stack.frames().count(), 3);
    {
        const Frame frame = stack.frames().at(0);
        QCOMPARE(frame.functionName(), QString("operator new(unsigned long)"));
    }
    {
        const Frame frame = stack.frames().at(2);
        QCOMPARE(frame.functionName(), QString("main"));
        QCOMPARE(frame.line(), 14);

        QCOMPARE(frame.object(), binary);
        QCOMPARE(frame.file(), QLatin1String("main.cpp"));
        QCOMPARE(QDir::cleanPath(frame.directory()), srcDir);
    }
    {
        const Frame frame = stack.frames().at(1);
        QCOMPARE(frame.functionName(), QString("Foo::Foo()"));
        QCOMPARE(frame.line(), 6);

        QCOMPARE(frame.object(), binary);
        QCOMPARE(frame.file(), QLatin1String("main.cpp"));
        QCOMPARE(QDir::cleanPath(frame.directory()), srcDir);
    }
    {
        const Frame frame = stack.frames().at(2);
        QCOMPARE(frame.functionName(), QString("main"));
        QCOMPARE(frame.line(), 14);

        QCOMPARE(frame.object(), binary);
        QCOMPARE(frame.file(), QLatin1String("main.cpp"));
        QCOMPARE(QDir::cleanPath(frame.directory()), srcDir);
    }
    }
    //BEGIN second error
    {
    const Error error = m_errors.last();
    QCOMPARE(error.kind(), int(Leak_DefinitelyLost));
    QCOMPARE(error.leakedBlocks(), qint64(1));
    QCOMPARE(error.leakedBytes(), quint64(16));
    QCOMPARE(error.stacks().count(), 1);
    const Stack stack = error.stacks().first();
    QCOMPARE(stack.line(), qint64(-1));
    QCOMPARE(stack.frames().count(), 2);
    {
        const Frame frame = stack.frames().at(0);
        QCOMPARE(frame.functionName(), QString("operator new(unsigned long)"));
    }
    {
        const Frame frame = stack.frames().at(1);
        QCOMPARE(frame.functionName(), QString("main"));
        QCOMPARE(frame.line(), 14);

        QCOMPARE(frame.object(), binary);
        QCOMPARE(frame.file(), QLatin1String("main.cpp"));
        QCOMPARE(QDir::cleanPath(frame.directory()), srcDir);
    }
    }
}
Пример #26
0
int main()
{
	cout << "It runs!" << endl;
	
	//create a stack & show it works
	Stack<int> s;
        s.pop();
        s.print();
        cout<<"Empty?  "<<s.empty()<<endl;
        cout<<s.size()<<endl;
        for(int i=0; i<10; i++) {
            s.push(2*i+1);
            s.print();
            cout<<s.size()<<endl<<endl;
        }
        cout<<"Empty?  "<<s.empty()<<endl;
        cout<<"The top is "<<(s.top())<<endl;
        for(int i=0; i<12; i++) {
            s.pop();
            s.print();
        }
        cout<<"The top is "<<(s.top())<<endl;
	//create a queue & show it works
	Queue<int> q;
        q.print();
        cout<<"Empty?  "<<q.empty()<<endl;
        cout<<q.size()<<endl;
        for(int i=0; i<10; i++) {
            q.push(2*i+1);
            q.print();
            cout<<q.size()<<endl<<endl;
        }
        cout<<"Empty?  "<<q.empty()<<endl;
        cout<<"The front is "<<(q.front())<<endl;
        cout<<"The rear is "<<(q.back())<<endl;
        for(int i=0; i<12; i++) {
            q.pop();
            q.print();
        }
        cout<<"The front is "<<(q.front())<<endl;
        cout<<"The rear is "<<(q.back())<<endl;

        Deque<int> d;
        d.print();
        for(int i=0; i<10; i++) {
            d.push_back(i);
            d.print();
        }
        for(int i=0; i<10; i++) {
            if(i%2==0) {cout<<"back"<<endl;
                d.pop_back();}
            else{cout<<"front"<<endl;
                d.pop_front();}
            d.print();
        }
}
Пример #27
0
void agglomerate_stack_queue(Stack& stack, double threshold, 
                                bool use_mito, bool use_edge_weight)
{
    if (threshold == 0.0) {
        return;
    }

    RagPtr rag = stack.get_rag();
    FeatureMgrPtr feature_mgr = stack.get_feature_manager();

    vector<QE> all_edges;	    	
    int count=0; 	
    for (Rag_t::edges_iterator iter = rag->edges_begin(); iter != rag->edges_end(); ++iter) {
        if ( (!(*iter)->is_preserve()) && (!(*iter)->is_false_edge()) ) {


            RagNode_t* rag_node1 = (*iter)->get_node1();
            RagNode_t* rag_node2 = (*iter)->get_node2();

            Node_t node1 = rag_node1->get_node_id(); 
            Node_t node2 = rag_node2->get_node_id(); 

            double val;
            if(use_edge_weight)
                val = (*iter)->get_weight();
            else	
                val = feature_mgr->get_prob(*iter);    

            (*iter)->set_weight(val);
            (*iter)->set_property("qloc", count);

            QE tmpelem(val, make_pair(node1,node2));	
            all_edges.push_back(tmpelem); 

            count++;
        }
    }

    double error=0;  	

    MergePriorityQueue<QE> *Q = new MergePriorityQueue<QE>(rag.get());
    Q->set_storage(&all_edges);	

    PriorityQCombine node_combine_alg(feature_mgr.get(), rag.get(), Q); 

    while (!Q->is_empty()){
        QE tmpqe = Q->heap_extract_min();	

        //RagEdge_t* rag_edge = tmpqe.get_val();
        Node_t node1 = tmpqe.get_val().first;
        Node_t node2 = tmpqe.get_val().second;
        RagEdge_t* rag_edge = rag->find_rag_edge(node1,node2);;

        if (!rag_edge || !tmpqe.valid()) {
            continue;
        }
        double prob = tmpqe.get_key();
        if (prob>threshold)
            break;	

        RagNode_t* rag_node1 = rag_edge->get_node1();
        RagNode_t* rag_node2 = rag_edge->get_node2();
        node1 = rag_node1->get_node_id(); 
        node2 = rag_node2->get_node_id(); 

        if (use_mito) {
            if (is_mito(rag_node1) || is_mito(rag_node2)) {
                continue;
            }
        }

        // retain node1 
        stack.merge_labels(node2, node1, &node_combine_alg);
    }		



}
Пример #28
0
void
Triangle_Processor::Process( Stack<AtomicRegion>&  Offspring)
  {
  TimesCalled ++;
  if (TimesCalled == 1)
    {
    TheRule->Apply(LocalIntegrand(),Geometry(),Integral(),AbsoluteError());
    Offspring.MakeEmpty();
    return;
    };
  if(TimesCalled == 2)
    {
    real NewVolume
          = Geometry().Volume()/2;
    Stack<Triangle> Parts;
    Vector<unsigned int> DiffOrder(Diffs.Size());
    const real difffac = real(1)/real(0.45);    
    const real difftreshold = 1e-3;

    TheRule->ComputeDiffs(LocalIntegrand(),Geometry(),Diffs); 

    // Sort the differences in descending order.
    for (unsigned int ik=0 ; ik<=2 ; ik++)  { DiffOrder[ik] = ik; }
    for (unsigned int i=0 ; i<=1 ; i++)  
      {
     for (unsigned int k=i+1 ; k<=2 ; k++)
         if (Diffs[DiffOrder[k]]>Diffs[DiffOrder[i]])
            {
            unsigned int h = DiffOrder[i];
            DiffOrder[i] = DiffOrder[k];
            DiffOrder[k] = h;
            }
      }

    if (Diffs[DiffOrder[0]] < difftreshold)
      {
      TheDivisor4->Apply(Geometry(),Parts,DiffOrder);
      NewVolume /=2;
      }
    else 
      {
      if (Diffs[DiffOrder[0]]>difffac*Diffs[DiffOrder[2]])
        {
        TheDivisor2->Apply (Geometry(),Parts,DiffOrder);
        }
      else 
        { 
        TheDivisor4->Apply(Geometry(),Parts,DiffOrder);
        NewVolume /=2;
        }	
      };

    unsigned int N = Parts.Size();
    for (unsigned int ii =0;ii<N;ii++)
      {
      Triangle* g = Parts.Pop();
      g->Volume(NewVolume);
      Processor<Triangle>* p = Descendant();
      Atomic<Triangle>* a = new Atomic<Triangle>(g,p);
      a->LocalIntegrand(&LocalIntegrand());
      Offspring.Push(a);
      };
    return;
    };
   Error(TimesCalled > 2,
     "Triangle_Processor : more than two calls of Process()");
   }
string ExpressionNotationConverter::ConvertInfixToPostfix(string expression)
{
	Stack operatorStack;
	Stack operandStack;
	string outputString = "";

	auto tmp = expression;

	while (tmp.length() > 0)
	{
		auto strLength = tmp.length();
		auto numberToSkip = 0;
		auto skip = 1;

		do
		{
			auto tmp1 = tmp.substr(numberToSkip, 1);

			if (!isdigit(tmp1[0]))
				break;

			numberToSkip++;
		} while (numberToSkip - 1 < strLength);

		if (numberToSkip > 0)
		{
			skip = numberToSkip;
		}

		auto subString = tmp.substr(0, strLength - (strLength - skip));
		auto currentCharacterPrecedence = DeterminePrecidence(subString);

		if (subString == "(")
		{
			operatorStack.Push(subString);
		}
		else if (subString == ")")
		{
			while (!operatorStack.IsEmpty() && operatorStack.Peek() != "(")
			{
				auto currentOperator = operatorStack.Pop();
				auto lhs = stoi(operandStack.Pop());
				auto rhs = stoi(operandStack.Pop());
				auto result = to_string(ApplyOperation(currentOperator, lhs, rhs));

				operandStack.Push(result);

				if (currentOperator != "(" && currentOperator != ")")
				{
					outputString += currentOperator + " ";
				}
			}

			auto paren = operatorStack.Pop();
		}
		else if (currentCharacterPrecedence == OPERAND)
		{
			operandStack.Push(subString);

			outputString += subString + " ";
		}
		else
		{
			while (!operatorStack.IsEmpty() && currentCharacterPrecedence <= DeterminePrecidence(operatorStack.Peek()))
			{
				auto currentOperator = operatorStack.Pop();

				outputString += currentOperator + " ";

				if (currentOperator != "(" && currentOperator != ")")
				{
					auto lhs = stoi(operandStack.Pop());
					auto rhs = stoi(operandStack.Pop());
					auto result = to_string(ApplyOperation(currentOperator, lhs, rhs));

					operandStack.Push(result);
				}
			}

			operatorStack.Push(subString);
		}

		tmp = string(tmp.substr(skip));
	}

	while (!operatorStack.IsEmpty())
	{
		auto currentOperator = operatorStack.Pop();

		if (currentOperator == "(" || currentOperator == ")")
		{
			outputString = "Invalid Expression!";

			break;
		}

		auto lhs = stoi(operandStack.Pop());
		auto rhs = stoi(operandStack.Pop());
		auto result = to_string(ApplyOperation(currentOperator, lhs, rhs));

		operandStack.Push(result);

		outputString += currentOperator + " ";
	}

	if (outputString == "Invalid Expression!")
	{
		return outputString;
	}

	auto result = operandStack.Pop();

	return outputString += " : " + result;
}
Пример #30
0
/*****************************************************
 * CONVERT INFIX TO POSTFIX
 * Convert infix equation "5 + 2" into postifx "5 2 +"
 *****************************************************/
string convertInfixToPostfix(const string & infix)
{
   string postfix;

   /**********************************
   Implement code for infix to postfix
   **********************************/
   char token,
         topToken;
   Stack<char> myStack;
   const string BLANK = " ";
   for (int i = 0; i < infix.length(); i++)
   {
      token = infix[i];
      switch(token)
      {
         case ' ' : break;    //do nothing skip blanks
         case '(' : myStack.push(token);
                    break;
         case ')' : for (;;)
            {
               assert (!myStack.empty());
               topToken = myStack.top();
               myStack.pop();
               if (topToken == '(') break;
               postfix.append(BLANK + topToken);
            }
            break;
         case '+' : case '-' :
         case '^' : case '*' : case '/' : case '%':
                    for (;;)
                    {
                        if (myStack.empty() ||
                           myStack.top() == '(' ||
                           ((token == '^' || token == '*' || token == '/' || token == '%') &&
                           (myStack.top() == '*' || myStack.top() == '+' || myStack.top() == '-')))
                        {
                           myStack.push(token);
                           break;
                        }
                        else
                        {
                           topToken = myStack.top();
                           myStack.pop();
                           postfix.append(BLANK + topToken);
                        }
                    }
                    break;
         default : //operand
                  // postfix.append(BLANK + token);
                  if ( isdigit(infix[i-1]) )
                  {
                     postfix.append(1, token);
                  }
                  else
                  {
                     postfix.append(BLANK + token);
                  }

                  for(;;)
                  {
                     if ( !isalnum(infix[i+1]) ) break; //end of identifier
                     i++;
                     token = infix[i];
                     postfix.append(1, token);
                  }
      }
   }
   // pop remaining operators on the stack
   for (;;)
   {
      if (myStack.empty()) break;
      topToken = myStack.top();
      myStack.pop();
      if (topToken != '(')
      {
         postfix.append(BLANK + topToken);
      }
      else
      {
         std::cout << " *** Error in infix expression ***\n";
         break;
      }
   }

   return postfix;
}