コード例 #1
0
/*! @note very important: color cubes of the children must already exist, otherwise there will be a segmentation fault  */
void ColorCubeGenerator::processColorCube(FrameContext& context, Node * node, deque<Node*>& children) {

	const Geometry::Box box = node->getWorldBB();
	ColorCube cc;

	// 1. case: current node's color cube should be processed by drawing Geometry < see processColorCubes(...) >
	if (children.empty()) {
		context.getRenderingContext().pushAndSetLighting(Rendering::LightingParameters(true));
		context.getRenderingContext().applyChanges();

		// render the six sides
		context.getRenderingContext().pushAndSetFBO(fbo.get());
		for (uint8_t _side = 0; _side < 6; ++_side) { // determine the color for each of the 6 faces
			const Geometry::side_t side = static_cast<Geometry::side_t> (_side);
			if (!prepareCamera(context, box, side))
				continue;

			context.getRenderingContext().clearScreen(Util::Color4f(0.0f, 0.0f, 0.0f, 0.0f));
			context.displayNode(node, USE_WORLD_MATRIX);
		}
		context.getRenderingContext().popFBO();
		colorTexture->downloadGLTexture(context.getRenderingContext());

		//////////// debug
// 		static uint32_t counter=0;
// 		stringstream ss;
// 		ss << "screens/colorcube_" << counter++ << ".png";
// 		Util::FileName filename(ss.str());
// 		Rendering::Serialization::saveTexture(context.getRenderingContext(), colorTexture.get(), filename);
		//////////// end debug



		// determine the color for each of the 6 faces
		for (uint8_t _side = 0; _side < 6; ++_side) {
			const Geometry::side_t side = static_cast<Geometry::side_t> (_side);
			if (prepareCamera(context, box, side)){
				const Color4ub c = calculateColor(colorTexture.get(), camera->getViewport()); //calculate color from texture
				cc.colors[static_cast<uint8_t> (side)] = c;
			} else {
				cc.colors[static_cast<uint8_t> (side)] = Color4ub(0, 0, 0, 0);
			}
		}

		context.getRenderingContext().popLighting();
	}
	else{
		context.getRenderingContext().pushAndSetFBO(fbo.get()); // enable the fbo

		// 2. case:  the node is not a closed GroupNode  (inner node)
		for (uint8_t _side = 0; _side < 6; ++_side) { // for each of the six faces
			Geometry::side_t side = static_cast<Geometry::side_t> (_side);
			if (!prepareCamera(context, box, side))
				continue;

			context.getRenderingContext().clearScreen(Util::Color4f(0.0f, 0.0f, 0.0f, 0.0f));
			context.getRenderingContext().pushAndSetMatrix_modelToCamera( context.getRenderingContext().getMatrix_worldToCamera() );


			// draw faces using blending
			context.getRenderingContext().pushAndSetBlending(Rendering::BlendingParameters(Rendering::BlendingParameters::ONE, Rendering::BlendingParameters::ONE_MINUS_SRC_ALPHA));
			context.getRenderingContext().pushAndSetCullFace(Rendering::CullFaceParameters(Rendering::CullFaceParameters::CULL_BACK));
			context.getRenderingContext().pushAndSetDepthBuffer(Rendering::DepthBufferParameters(true, false, Rendering::Comparison::LESS));
			context.getRenderingContext().pushAndSetLighting(Rendering::LightingParameters(false));
			context.getRenderingContext().applyChanges();

			distanceQueue_t nodes(side); // distance queue used for sorting the children with color cubes

			// sort (back-to-front order) the children according to distance of current side to the camera
			for(const auto & child : children) {
				nodes.push(child);
			}

			// draw the faces in back-to-front order
			while (!nodes.empty()) {
				Node* child = nodes.top();
				nodes.pop();
				const ColorCube & childsColorCube = ColorCube::getColorCube(child);
				//cerr << "before drawing colored box " << endl;
				childsColorCube.drawColoredBox(context, child->getWorldBB());
				//cerr << "after drawing colored box" << endl;
			}

			context.getRenderingContext().popLighting();
			context.getRenderingContext().popDepthBuffer();
			context.getRenderingContext().popCullFace();
			context.getRenderingContext().popBlending();
			context.getRenderingContext().popMatrix_modelToCamera();
		}
		context.getRenderingContext().popFBO();
		colorTexture->downloadGLTexture(context.getRenderingContext());
		// determine the color for each of the 6 faces
		for (uint8_t _side = 0; _side < 6; ++_side) {
			Geometry::side_t side = static_cast<Geometry::side_t> (_side);
			if (!prepareCamera(context, box, side))
				continue;
			//calculate color from texture
			cc.colors[static_cast<uint8_t> (side)] = calculateColor(colorTexture.get(), camera->getViewport());
		}
	}

	ColorCube::attachColorCube(node, cc);
}
コード例 #2
0
ファイル: waypoints.cpp プロジェクト: picopter/picopter
/*
 *	flightLoop
 *		1) Initialise copter systems
 *		2) Wait for user allowance to fly.
 *		3) Read in list of waypoints
 *		4) Fly to first waypoint, wait, fly to next, etc..
 *		5) If the end is reached, stop.
 *		
 *		The user may stop the flight at any time. It will continue if the user resumes. At any
 *		point, the user may stop the current flight path and change the waypoint configuration. Upon
 *		resuming flight, the copter will read in the new list of waypoints and start at the
 *		beginning.
 */
void waypointsFlightLoop(FlightBoard &fb, GPS &gps, IMU &imu, Buzzer &buzzer, Logger &logs, deque<coord> &waypoints_list) {	
	cout << "\033[1;32m[WAYPTS]\033[0m Waypoints thread initiated, travelling to the following waypoints:" << endl;
	
	char str_buf[BUFSIZ];
	bool useimu = false;	// Manual setting for debug
	double yaw = 0;	
	GPS_Data gps_data;
	
	for(size_t i = 0; i != waypoints_list.size(); i++) {
		cout << '         ' << i+1 << ": (" << waypoints_list[i].lat << ", " << waypoints_list[i].lon << ")" << endl;
	}
	
	state = 6;
	while ( !gpio::isAutoMode() ) usleep(1000000);
	
	/*if (!useimu) {
		buzzer.playBuzzer(0.25, 100, 100);
		state = 5;
		yaw = inferBearing(&fb, &gps, &logs);
	}*/
	
	coord		currentCoord = {-1, -1};
	double		distanceToNextWaypoint;
	double		bearingToNextWaypoint;
	FB_Data		course = {0, 0, 0, 0};
	int			pastState = -1;

	try {	// Check for any errors, and stop the copter.
		while(!exitProgram) {
			gps.getGPS_Data(&gps_data);
			currentCoord.lat = gps_data.latitude;
			currentCoord.lon = gps_data.longitude;
			
			if (wp_it == waypoints_list.size()) {
				wp_it = 0;
				userState = 0;
			}

			distanceToNextWaypoint = calculate_distance(currentCoord, waypoints_list[wp_it]);
			bearingToNextWaypoint = calculate_bearing(currentCoord, waypoints_list[wp_it]);
			//if (useimu) yaw = getYaw(&imu);
			yaw = gps_data.heading;			

			/* State 4: Manual mode. */
			if (!gpio::isAutoMode()) {
				state = 4;
				wp_it = 0;
				exitProgram = true;
			/* State 0: All stop */
			} else if (waypoints_list.empty() || userState == 0 ) {
				state = 11;
				wp_it = 0;
				exitProgram = true;
			/* State 3: Error. */
			} else if (state == 3 || !checkInPerth(&currentCoord)) {
				state = 3;
				exitProgram = true;
			/* State 2: At waypoint. */
			} else if (distanceToNextWaypoint < WAYPOINT_RADIUS) {
				state = 2;
			/* State 1: Travelling to waypoint. */
			} else {
				state = 1;
			}
			
			/* Only give output if the state changes. Less spamey.. */
			if (pastState != state) {
				switch (state) {
					case 0:
						cout << "\033[1;32m[WAYPTS]\033[0m All stop." << endl;
						break;
					case 1:
						cout << "\033[1;32m[WAYPTS]\033[0m Travelling to waypoint " << wp_it << ", at (" << waypoints_list[wp_it].lat << "," << waypoints_list[wp_it].lon << ")" << endl;
						break;
					case 2:
						cout << "\033[1;32m[WAYPTS]\033[0m At waypoint" << wp_it << "." << endl;
						break;
					case 3:
						cout << "\033[31m[WAYPTS]\033[0m Error reading GPS." << endl;
					case 4:
						cout << "\033[31m[WAYPTS]\033[0m Manual mode engaged." << endl;
					break;
				}
				cout << "\033[1;33m[WAYPTS]\033[0m In state "		<< state << "."	<< endl;
				cout << "\033[1;33m[WAYPTS]\033[0m Facing " << setprecision(6) << yaw << ", at coordinates (" << currentCoord.lat << ", " <<	currentCoord.lon << ")" << endl;

				cout << "\033[1;33m[WAYPTS]\033[0m The next waypoint is at (" << setprecision(6) << waypoints_list[wp_it].lat << ", " << waypoints_list[wp_it].lon << ")"	<< endl;
				
				cout << "\033[1;33m[WAYPTS]\033[0m It is " << setprecision(7) << distanceToNextWaypoint	<< "m away, at a bearing of " << bearingToNextWaypoint << "." << endl;
			
				printFB_Data(&stop);
				
				pastState = state;
			}

			switch(state) {
				case 0:													//Case 0:	Not in auto mode, standby
					fb.setFB_Data(&stop);									//Stop moving
					
					logs.writeLogLine("\033[1;32m[WAYPTS]\033[0m Manual mode");
					sprintf(str_buf, "[WAYPTS] Currently at %f %f.", currentCoord.lat, currentCoord.lon);
					logs.writeLogLine(str_buf);
					
					break;
				
				case 1:
					bearingToNextWaypoint = calculate_bearing(currentCoord, waypoints_list[wp_it]);	//Set a Course
					setCourse(&course, distanceToNextWaypoint, bearingToNextWaypoint, yaw);
					fb.setFB_Data(&course);																//Give command to flight boars
					
					sprintf(str_buf, "[WAYPTS] Aileron is %d, Elevator is %d", course.aileron, course.elevator);
					logs.writeLogLine(str_buf);
					sprintf(str_buf, "[WAYPTS] Moving to next waypoint. It has latitude %f and longitude %f.", waypoints_list[wp_it].lat, waypoints_list[wp_it].lon);
					logs.writeLogLine(str_buf);
					sprintf(str_buf, "[WAYPTS] Currently at %f %f, moving %f m at a bearing of %f degrees.", currentCoord.lat, currentCoord.lon, distanceToNextWaypoint, bearingToNextWaypoint);
					logs.writeLogLine(str_buf);

					break;
				
				case 2:
					fb.setFB_Data(&stop);
					buzzer.playBuzzer(0.4, 100, 100);
					
					logs.writeLogLine("\033[1;32m[WAYPTS]\033[0m Reached waypoint, stopping");
					
					//waypoints_list.push_back(waypoints_list.front());
					wp_it++;
					//waypoints_list.pop_front();

					boost::this_thread::sleep(boost::posix_time::milliseconds(WAIT_AT_WAYPOINTS));
					
					cout << "\033[1;32m[WAYPTS]\033[0m Moving to next waypoint." << endl;
					break;
				
				case 3:
				default:
					fb.setFB_Data(&stop);
					
					logs.writeLogLine("\033[31m[WAYPTS]\033[0m Error reading GPS, stopping");
				break;
			}
			boost::this_thread::sleep(boost::posix_time::milliseconds(100));

		}
	} catch (...) {
		cout << "\033[31m[WAYPTS]\033[0m Error encountered. Stopping copter." << endl;
		fb.setFB_Data(&stop);
		printFB_Data(&stop);
		state = 3;
	}
	cout << "\033[1;32m[WAYPTS]\033[0m Waypoints flight loop terminating." << endl;
	
	buzzer.playBuzzer(0.2, 100, 100);
	usleep(400000);
	buzzer.playBuzzer(0.2, 100, 100);
	usleep(400000);
	buzzer.playBuzzer(0.2, 100, 100);
	usleep(400000);
}
コード例 #3
0
ファイル: KMIN.cpp プロジェクト: thucdx/algorithm-solution
void pop(int x) {
	while (!dq.empty() && dq.front() <= x)
		dq.pop_front();
}
コード例 #4
0
ファイル: 11107.cpp プロジェクト: fredwhite/Backup
int main(){
    int n;
    int i,j;
    int u,v;
    int flag;
    int count;

    int f,s;
    char c;
    int r;
    int lc;

    node nn,cn;
    int ma,lim;

    count=0;
    while(true){
	scanf("%d",&n);
	if(n==0){
	    break;
	}

	if(count!=0){
	    printf("\n");
	}
	count=1;

	sl.clear();

	for(i=0;i<n;i++){
	    scanf("%s",str[i]);
	    u=strlen(str[i]);
	    l[i]=u;
	    for(j=0;j<u;j++){
		nn.idx=i;
		nn.os=j;
		nn.f=0;
		nn.s=0;
		sl.push_back(nn);
	    }
	}
	sort(sl.begin(),sl.end(),cmpa);		

	u=sl.size();

	c=0;
	v=0;
	for(i=0;i<u;i++){
	    if(str[sl[i].idx][sl[i].os]!=c){
		v++;
		c=str[sl[i].idx][sl[i].os];
	    }
	    ra[sl[i].idx][sl[i].os]=v; 
	}

	r=1;
	while(true){
	    flag=0; 
	    for(i=0;i<u;i++){
		sl[i].f=ra[sl[i].idx][sl[i].os];
		if((sl[i].os+r)<l[sl[i].idx]){
		    sl[i].s=ra[sl[i].idx][sl[i].os+r];
		    flag=1;
		}else{
		    sl[i].s=0;
		}
	    }
	    if(flag==0){
		break;
	    }

	    sort(sl.begin(),sl.end(),cmpb);

	    v=0;
	    f=-1;
	    s=-1;
	    for(i=0;i<u;i++){
		if(sl[i].f!=f || sl[i].s!=s){
		    v++;
		    f=sl[i].f;
		    s=sl[i].s;
		}
		ra[sl[i].idx][sl[i].os]=v; 
	    }

	    r*=2;
	}
	for(i=0;i<u;i++){
	    ra[sl[i].idx][sl[i].os]=i;
	}

	for(i=0;i<n;i++){
	    lc=0;
	    for(j=0;j<l[i];j++){
		if(ra[i][j]==0){
		    lcp[i][j]=2147483647;
		}else{
		    v=ra[i][j]-1;
		    if(lc>0){
			lc--;
		    }
		    while((j+lc)<l[i] && (sl[v].os+lc)<l[sl[v].idx]){
			if(str[i][j+lc]!=str[sl[v].idx][sl[v].os+lc]){
			    break;
			}
			lc++;
		    }
		    lcp[i][j]=lc;
		}
	    }
	}

	for(i=0;i<n;i++){
	    lmap[i]=0;
	}
	for(i=0;i<u;i++){
	    hemap[i]=0;
	}
	he.clear();
	de.clear();
	v=0;
	flag=0;

	out.clear();
	ma=0;

	for(i=0;i<u;i++){
	    if(lmap[sl[i].idx]==0){
		v++;
	    }
	    lmap[sl[i].idx]++;
	    if(i>0){
		he.push_back(i);
		push_heap(he.begin(),he.end(),cmpc);
	    }
	    de.push_back(i);

	    while(!de.empty()){
		if(lmap[sl[de.front()].idx]>1){
		    hemap[de.front()]=1;
		    lmap[sl[de.front()].idx]--;
		    de.pop_front();
		}else if(lmap[sl[de.front()].idx]==1 && (v-1)*2>n && v>2){
		    v--;
		    hemap[de.front()]=1;
		    lmap[sl[de.front()].idx]--;
		    de.pop_front();
		}else{
		    break;
		}
	    }
	    hemap[de.front()]=1;

	    while(!he.empty()){
		if(hemap[he.front()]==1){
		    pop_heap(he.begin(),he.end(),cmpc);
		    he.pop_back();
		}else{
		    break;
		}
	    }

	    if(v*2>n && v>=2){
		cn=sl[he.front()];
		lim=lcp[cn.idx][cn.os];
		if(lim>ma){
		    out.clear();
		    out.push_back(cn);
		    flag=1;
		    ma=lim;
		}else if(lim==ma){
		    if(flag==0){
		        out.push_back(cn);
		        flag=1;
		    }
		}else{
		    flag=0;
		}
	    }else{
		flag=0;
	    }
	}

	/*for(i=0;i<u;i++){
	    printf("  %d %s  %d\n",sl[i].idx,&str[sl[i].idx][sl[i].os],lcp[sl[i].idx][sl[i].os]);
	}*/

	if(ma==0){
	    printf("?\n");
	}else{
	    u=out.size();
	    for(i=0;i<u;i++){
		c=str[out[i].idx][out[i].os+ma];
		str[out[i].idx][out[i].os+ma]=0;
		printf("%s\n",&str[out[i].idx][out[i].os]);
		str[out[i].idx][out[i].os+ma]=c;
	    }
	}
    }

    return 0;
}
コード例 #5
0
ファイル: implement.cpp プロジェクト: emmettwu/emmettLeetCode
 bool empty() {
     return q.empty();
 }
コード例 #6
0
ファイル: AI.cpp プロジェクト: gsteelman/mst
void AI::gen_moves( const backgammon_state& s, deque<backgammon_state>& r )
{    
  //The die value we're currently using
  int dieVal = 0;
  
  //How many points to loop through to generate moves
  int LSVal = 0;
  int LEVal = 26;
  
  //Generation of half-state flags. True = need to use this die.
  bool use_0 = true;
  bool use_1 = true;
  
  //For jumping forward spaces in times of bearing off and needing to
  int advance = 0;
  
  //The current state we're using to generate moves from
  backgammon_state curr_state = s;
  
  //Keep going until we generate all the states necessary
  while ( true )
  {
    cout << "\n---------------------------------------------------" << endl;
    
    if ( curr_state.m_dice.size() == 2 )
    {
      cout << "-Singles mode-" << endl;

      //If we need to generate half states using 0 or 1
      if ( (use_0 == true) || (use_1 == true) )
      {
        //generate half-states using die 0
        if ( use_0 == true )
        {
          cout << "  Generation using only 0" << endl;
          dieVal = curr_state.m_dice[0];
          use_0 = false;
          curr_state.m_dice_used[0] = true;
          //curr_state.m_dice_used[1] = false;
        }
        
        //generate half-states using die 1
        else
        {
          //Means we tried to generated using the smaller die first and couldn't
          //Which means we may have a situation in which we need to use 
          //only the largest die
          //if ( r.empty() && (largest_only == false) )
          //{
            //largest_only = true;
          //}
          
          cout << "  Generation using only 1" << endl;
          dieVal = curr_state.m_dice[1];
          use_1 = false;
          curr_state.m_dice_used[0] = false;
          curr_state.m_dice_used[1] = true;
        }
        
      } //End if choosing which die to use first
      
      //use_0 == false and use_1 == false, so we've used both of them
      //but were unable to generate any moves, sucks for us
      else if ( r.empty() )
      {
        cout << "  tried to gen full states, but failed" << endl;
        
        if ( !curr_state.m_move.empty() )
        {
          cout << "falling back to previous state because it still has moves" << endl;
          r.push_back( curr_state );
        }
        
        return;
      }
      
      //Or if we've generated half-states already, and we need to now
      //generate full-states from the half-states
      //else if ( !r.empty() && continue_generation( r.front() ) )
      else if ( continue_generation( r.front() ) )
      {
        //Turn the first half-state into a full-state
        
        //if (used_both)
        //  r.pop_front();
          
        curr_state = r.front();
        r.pop_front();
        
        //check to see if we can only use 1 die from this state, and make it
        //be the larger of the two die
        // if we were able to generate a state, we need to make sure thatit's using
        //   either both die or just the higher one
        
        //If this state requires generation using die 0 to become full
        if ( curr_state.m_dice_used[0] == false )
        {
          cout << "  Generation using 0, already did 1" << endl;
          dieVal = curr_state.m_dice[0];
          curr_state.m_dice_used[0] = true;
        }
        
        //else if it requires generation using die 1 to become full
        else
        {
          cout << "  Genration using 1, already did 0" << endl;
          dieVal = curr_state.m_dice[1];
          curr_state.m_dice_used[1] = true;
        }
        
      } // End generation on first element of r
      
      //If we hit this it means that we don't need to use only 1
      //and we don't need to use only 0, and we don't need to continue 
      //generation, which means we have reached a set of full-states
      //And our possible subsequent states are stored in the (r)esult set
      else if ( !continue_generation( r.front() ) )
      {
        cout << "finished generating moves" << endl;
        return;
      }
      
      else
      {
        cout << "something terrible has happened" << endl;
        return;
      }
      
    } // End generation decisions for singles
    
    //This means we are in doubles mode, meaning quarter-state generations
    //are necessary instead of half-state generations.
    //This code seems to catch errors in our number of die available, too.
    else 
    {
      cout << "-Doubles Mode-" << endl;
      //cin.get();
      if ( r.empty() && curr_state.m_dice_used[0] == true )
      {
        cout << "tried to gen a state before, and it didn't work. suck" << endl;
        if ( !curr_state.m_move.empty() )
        {
          cout << "falling back to previous state because it still has moves" << endl;
          r.push_back( curr_state );
        }
        
        return;
      }
      
      //Initially curr_state = the passed state. So we want to skip generation
      //using the (r)esulting set on the first pass, and only use the first part
      //of the (r)esulting set on the 2nd-4th passes.
      else if ( !r.empty() && continue_generation( r.front() ) )
      {
        cout << "  Generating using a result set state" << endl;
        
        //if (used_both)
        //  r.pop_front();
          
        curr_state = r.front();
        r.pop_front();
      }
      
      //If we hit this it means we're either on the first pass
      //or we have generated at least one state, and all the states we need to
      else if ( !r.empty() && !continue_generation( r.front() ) )
      { 
        return;
      } 
      
      //Mark the next die used for curr_state
      //cout << " curr_State.m_dice.size() = " << curr_state.m_dice.size() << endl;
      for ( int dm = 0; dm < curr_state.m_dice.size(); dm++ )
      {
        if ( curr_state.m_dice_used[dm] == false )
        {
          //cout << "  Generation using " << dm << endl;
          
          curr_state.m_dice_used[dm] = true;
          
          break;
        }
      }
      
      dieVal = curr_state.m_dice[0];
      
    } // End generation decisions for doubles
    
    //Now, if in the current state we have a piece on the bar we need to move
    //we'll limit the j loop to only generate states for the bar point
    //instead of generating for all points
    //If player X and we need to move off the bar
    //cout << "  working on bar moves" << endl;
    if ( (curr_state.m_player == 0) && (curr_state.m_board[25] < 0) )
    { 
      cout << "  Detected bar move for X!" << endl;
      LSVal = 0;
      LEVal = 1;
      //cin.get();
    }
    
    //If player O and we need to move off the bar
    else if ( (curr_state.m_player == 1) && (curr_state.m_board[0] > 0) )
    {
      cout << "  Detected bar move for O!" << endl;
      LSVal = 0;
      LEVal = 1;
      //cin.get();
    }
    
    //Otherwise we don't need to move off of the bar, so we generate a full
    //range of moves for all checkers on all points. 
    else
    {
      LEVal = 26;
      
      bear_check( curr_state );

      //Limits our check of the board to the home quadrants if we're trying to
      //bear off, so we don't waste time checking the rest of the board
      LSVal = ( curr_state.m_bear_off == true) ? ( 19 ) : ( 0 );
    }    
    /************************* end generation decisions **********************/
    
    /***************************** generate moves ****************************/
    curr_state.print();
    cout << "\n  dieVal = " << dieVal << "; LVal = " << LSVal << ", " << LEVal << endl;
    cout << "  ";
    
    //We run through each triangle on the board and see if we can make a move
    //off of that spot
    //bool norm_move = true;
    bool j_edit = false;
    for ( int j = LSVal; j < LEVal; j++ )
    {
      j_edit = false;
      if ( curr_state.m_player == 1 )
        cout << j << " ";
      else
        cout << 25-j << " ";

      //add condition for going off the end of the board lol
      //case:
      // 0 0 0 2 6 3->exit, using a 5
      if ( curr_state.m_bear_off == true )
      {
        //Do a check backward to see if we can even bear off with this pie
      
        //Calculate the furthest back point that's less than the value
        //of the die from the exit on the board. This is the point we can
        //bear off using this die from, and no other point
        //advance = advance_to( curr_state, dieVal );
        
        //case where furthest point is closer to goal than die roll is
        //Pushes j forward a space or two so that we can bear off from
        //the furthest point
        //j += ( 25-j != dieVal ) ? ( (dieVal - furthest) ) : ( 0 );
        
        //if ( (curr_state.m_player == 0) && (curr_state.m_board[25-j] < 0) && (25-j > dieVal) )
        if ( (curr_state.m_player == 0) 
          && (25-j-dieVal < 1)
          && (curr_state.m_board[25-j] == 0)
          && ( !check_back( curr_state, 25-j, dieVal ) )
          )
        {
          advance = advance_to( curr_state, dieVal );
          //cout << "xf(" << dieVal - advance << ") ";
          j+=(dieVal - advance);
          j_edit = true;
          
          cout << ":" << 25-j << " ";
        }
        
        //else if ( (curr_state.m_player == 1) && (curr_state.m_board[j]) && ( j+dieVal != 25) )
        else if ( (curr_state.m_player == 1) 
          && (j+dieVal > 24)
          && (curr_state.m_board[j] == 0)
          && ( !check_back( curr_state, j, dieVal ) )
          )
        {
          advance = advance_to( curr_state, dieVal );
          cout << "of(" << advance - (25-dieVal) << ") ";
          j+=(advance - (25-dieVal));
          j_edit = true;
        }
      }
      
      //call checkback, but only if the current die roll is further away 
      //than our current position
        
      //If we're player X and we own the spot
      if ( (curr_state.m_player == 0) && (curr_state.m_board[25-j] < 0) )
      {
        cout << "+ ";
        //If the spot we would move to is on the board and open
        //OR if we would be trying to bear off and we move off the board
        //Basically, legal move check
        if ( ((25-j-dieVal > 0) && (curr_state.m_board[25-j-dieVal] <= 1))
          || ((curr_state.m_bear_off == true) && (25-j-dieVal < 1)) )
        {
          
          
          //If we're trying to bear off, check special cases
          if ( (curr_state.m_bear_off == true) && (25-j-dieVal < 1) )
          {
            //Means we're not allowed to bear off from this point
            if ( check_back( curr_state, 25-j, dieVal ) == true )
            {
              cout << "cb ";
              continue;
            }
          }
          
          cout << "+ ";
          _MOVES++;

          //Make a copy of the current state
          r.push_back( curr_state );
          
          //Remove a checker from the current spot
          r.back().m_board[25-j]++;

          //If our move keeps us on the board
          if ( 25-j-dieVal > 0 )
          {
            //If we hit the opponent, move their checker to the bar
            if ( curr_state.m_board[25-j-dieVal] == 1 )
            {
              r.back().m_board[25-j-dieVal]--;
              r.back().m_board[0]++;
            }
            
            //Place our checker on the new spot
            r.back().m_board[25-j-dieVal]--;
          }
          
          //Moved off the board
          else
          {
            r.back().m_score++;
          }
          
          //Record the move. If 25-j-dieVal < 0, it means we bear off with this move
          r.back().m_move.push_back(25-j);
          r.back().m_move.push_back(25-j-dieVal);

          //If we pushed j forward, move it back
          if ( j_edit == true )
          {
            j-=( dieVal - advance );
            j_edit = false;
          }
        }
      } 
      
      //If we're player O and O owns the spot
      else if ( (curr_state.m_player == 1) && (curr_state.m_board[j] > 0) )
      {
        //If we're trying to bear off, check special cases
        if ( (curr_state.m_bear_off == true) && (j+dieVal > 24) )
        {
          //Means we're not allowed to bear off from this point
          if ( check_back( curr_state, j, dieVal ) == true )
          {
            cout << "cb ";
            continue;
          }
        }
      
        cout << "~ ";
        //If the spot we would move to is on the board and open
        //OR if we would be trying to bear off and we move off the board
        if ( ((j+dieVal < 25) && (curr_state.m_board[j+dieVal] >= -1))
          || ((curr_state.m_bear_off == true) && (j+dieVal > 24)) )
        {
          cout << "~ ";
          _MOVES++;
          
          //Make a copy of the current state
          r.push_back( curr_state );
          
          //Remove a checker from the current spot
          r.back().m_board[j]--;

          //If our move keeps us on the board
          if ( j+dieVal < 25 )
          {
            //If we hit the opponent, move their checker to the bar
            if ( curr_state.m_board[j+dieVal] == -1 )
            {
              r.back().m_board[j+dieVal]++;
              r.back().m_board[25]--;
            }
            
            //Place our checker on the new spot
            r.back().m_board[j+dieVal]++;
          }
          
          else
          {
            r.back().m_score++;
          }

          //Record the move. If j+dieVal > 24, it means we bear off with this move
          r.back().m_move.push_back(j);
          r.back().m_move.push_back(j+dieVal);

          //If we pushed j forward, move it back
          if ( j_edit == true )
          {
            j-=( advance - (25-dieVal) );
            j_edit = false;
          }          
        }
      }
      
      //And at this point, if we didn't execute X or O generation, it means 
      //no one owned the spot or no one could move from a spot if it was owned
    } 
    
    cout << "\n  r.size() = " << r.size() << endl;
  } 
  
  return;
}                                        
コード例 #7
0
ファイル: ls.cpp プロジェクト: aorti017/rshell
void print_ls(bool flags[], deque<string> paths, string mainPath){
    if(paths.empty()){
        return;
    }
    wcout.imbue(locale(""));
    int cnt = 0;
    struct stat buf;
    string tmp = mainPath;
    string ftmp;
    DIR *dirp = opendir(tmp.c_str());
    if(dirp == NULL){
        perror("opendir");
        exit(0);
    }
    dirent *direntp;
    vector<string> fileObj;
    unordered_map<string, string> filehash;
    if(flags[2]){
        cout << tmp  << ":" << endl;
    }
    errno = 0;
    direntp = readdir(dirp);
    if(errno !=  0){
            perror("readdir");
            exit(0);
        }
    while(direntp){
        if(direntp == NULL){
            perror("readdir");
            exit(0);
        }
        ftmp = direntp->d_name;
        string tmpPath = mainPath;
        tmpPath.append("/");
        tmpPath.append(ftmp);
        if(lstat(tmpPath.c_str(), &buf) == -1){
            perror("lstat");
            exit(0);
        }
        if(flags[0]){
            fileObj.push_back(direntp->d_name);
            filehash[direntp->d_name] = tmpPath;
            cnt++;
        }
        else if(!flags[0] && ftmp.at(0) != '.'){
            fileObj.push_back(direntp->d_name);
            filehash[direntp->d_name] = tmpPath;
            cnt++;
        }
        if(S_ISDIR(buf.st_mode) && ftmp != "." && ftmp != ".."
            && flags[2]){
            if(flags[0]){
                paths.push_back(tmpPath);
            }
            else if(!flags[0] && ftmp.at(0) != '.'){
                paths.push_back(tmpPath);
            }
        }
        errno = 0;
        direntp = readdir(dirp);
        if(errno != 0){
            perror("readdir");
            exit(0);
        }
    }
    total_block_size += getBlk(filehash, fileObj);
    if(flags[1]){
        cout << "total " << total_block_size / 2 << endl;
    }
    total_block_size = 0;
    sort(fileObj.begin(), fileObj.end(), locale("en_US.UTF-8"));
    //int l = get_total_len(fileObj);
    //cout << endl << l << endl;
    unsigned int count = 0;
    unsigned int c_count = 0;
        for(unsigned int i = 0; i < fileObj.size(); i++){
            if(flags[1]){
                //total_block_size += getBlk(filehash, fileObj);
                cout << getInfo(filehash[fileObj.at(i)]);
                if(isDir(filehash[fileObj.at(i)])){
                    if(isHide(fileObj.at(i))){
                        cout << "\033[34;100m";
                        cout << fileObj.at(i);
                        cout << "\033[0m";
                        cout << endl;
                    }
                    else{
                        cout << "\033[34m" << fileObj.at(i)
                            << "\033[0m" << endl;
                    }
                }
                else if(isEx(filehash[fileObj.at(i)])){
                    if(isHide(fileObj.at(i))){
                        cout << "\033[32;100m";
                        cout << fileObj.at(i);
                        cout << "\033[0m";
                        cout << endl;
                    }
                    else{
                        cout << "\033[32m" << fileObj.at(i)
                            << "\033[0m" << endl;
                    }
                }
                else{
                    if(isHide(fileObj.at(i))){
                        cout << "\033[100m";
                        cout << fileObj.at(i);
                        cout << "\033[0m";
                        cout << endl;
                    }
                    else{
                        cout << fileObj.at(i) << endl;
                    }
                }
                c_count++;
            }
            if(!flags[1]){
                //total_block_size += getBlk(filehash, fileObj);
                if(isDir(filehash[fileObj.at(i)])){
                    unsigned int tmp = fileObj.at(i).size();
                    tmp += 2;
                    count += tmp;
                    if(count >= 80){
                        count = tmp;
                        cout << endl;
                    }
                    if(isHide(fileObj.at(i))){
                        cout << "\033[34;100m";
                        cout << fileObj.at(i);
                        cout << "\033[0m";
                    }
                    else{
                        cout << "\033[34m" << fileObj.at(i)
                            <<"\033[0m";
                    }
                    cout << setw(2) << right;
                    cout << "";
                }
                else if(isEx(filehash[fileObj.at(i)])){
                    unsigned int tmp = fileObj.at(i).size();
                    tmp += 2;
                    count += tmp;
                    if(count >= 80){
                        count = tmp;
                        cout << endl;
                    }
                    if(isHide(fileObj.at(i))){
                        cout << "\033[32;100m";
                        cout << fileObj.at(i);
                        cout << "\033[0m";
                    }
                    else{
                        cout << "\033[32m" << fileObj.at(i)
                            << "\033[0m";
                    }
                    cout << setw(2) << right;
                    cout << "";
                }
                else{
                    unsigned int tmp = fileObj.at(i).size();
                    tmp += 2;
                    count += tmp;
                    if(count >= 80){
                        count = tmp;
                        cout << endl;
                    }
                    if(isHide(fileObj.at(i))){
                        cout << "\033[100m";
                        cout << fileObj.at(i);
                        cout << "\033[0m";
                    }
                    else{
                        cout << fileObj.at(i);
                    }
                    cout << "\033[0m";
                    cout << setw(2) << right;
                    cout << "";
                }
                c_count++;
            }
        }
        paths.pop_front();
        if((paths.empty() || flags[2]) && !flags[1] && count > 0){
            cout << /* "a" <<*/ endl;
        }
        if(!paths.empty()){
            cout << /* "b" <<*/ endl;
        }
        count = 0;
    sort(paths.begin(), paths.end(), locale("en_US.UTF-8"));
    fileObj.clear();
    closedir(dirp);
    if(paths.empty()){
        return;
    }
    //total_block_size = 0;
    deque<string> recurPaths;
    recurPaths.push_back(paths.front());
    print_ls(flags, recurPaths, paths.front());
    paths.pop_front();
    if(paths.empty()){
        return;
    }
    else{
        cout << endl;
    }
    print_ls(flags, paths, paths.front());
}
コード例 #8
0
ファイル: main.cpp プロジェクト: vitawebsitedesign/321
void readSingleAssociation(ifstream &fin, deque<dtdclass *>&d_class){
   
    bool associationFinish=false;
    bool firstclass = true;
    string base_name, to_name;/*save the name and two class name of the association*/
    int baseLevel, toLevel;/*to save the level of both class of the association*/
    deque<attribute * > baseQualification, toQualification; /*save the list of qualification*/
    attribute basequali, toquali;/*save the name of the qualification*/
    associate basAsso, toAsso;
    bool haveBasequali = false;/*check if there have qualification in first class*/
    bool haveToquali = false;/*check if there have qualification in second class*/
    bool haveLink=false;/*check the association have link or not*/
    char filedetail[256];/*record the each line of file from the compiler*/
    char linker_name[64];
    string Slinker_name;
    char * tempChar;
    string temp;
    deque<dtdclass*>::iterator first;/*recond the first position of the deque*/
    deque<dtdclass*>::iterator last;/*recond the last position of the deque*/
    do{
        fin.getline(filedetail,255);
        if(strcmp(filedetail, "")==0){continue;}/*if the line is empty, continue*/
        tempChar = strtok(filedetail,"<>");//cut front of "<"
        temp = tempChar;
        if(temp=="/association"){//check if is end of one association
            associationFinish=true;//is control while loop
        }
        else {
            tempChar = strtok(NULL, ">");//get detail between < >
            temp = tempChar;
            if(temp=="/association"){//check if is end of one association
                associationFinish=true;//is control while loop
            }
            else if(temp == "nameOfAssociation"){
                tempChar = strtok(NULL,"<>");//get the name of the association
                strcpy(basAsso.ass_name, tempChar);
                strcpy(toAsso.ass_name , tempChar);
            }
            else if(temp =="class_name"){/*find the class name of the association of the class*/
                tempChar = strtok(NULL, "<>");/*get the class name*/
                if(firstclass ==true){
                    /*call function to read detail of the association of the first class*/
                    readAssoClass(fin, basAsso, toAsso, baseLevel,haveToquali,toQualification);
                    
                    firstclass = !firstclass;
                    strcpy(toAsso.tclass_name, tempChar);/*record the relation class*/
                    base_name = tempChar;
                    Slinker_name = base_name;/*record the name of first class*/
                    }
                else{
                    /*call function to read detail of the association of the second class*/
                    readAssoClass(fin, toAsso, basAsso, toLevel,haveBasequali, baseQualification );
                    
                    strcpy(basAsso.tclass_name , tempChar);/*record the relation class name */
                    to_name = tempChar;
                    Slinker_name = Slinker_name + to_name;/*record the name of the second class*/
                }
            }
            else if(temp =="Link"){
                fin.getline(filedetail,255);
                if(strcmp(filedetail, "")==0){continue;}/*if the line is empty, continue*/
                tempChar = strtok(filedetail,"<>");//cut front of "<"
                tempChar = strtok(NULL,"<>");/*get the detail in "<>" */
                temp = tempChar;
                if(temp=="/association"|| temp =="/Link"){//check if is end of one association
                    associationFinish=true;//is control while loop
                }
                else if(temp == "link_attribute"){
                    fin.getline(filedetail, 255);
                    if(strcmp(filedetail, "")==0){continue;}/*if the line is empty, continue*/
                    tempChar = strtok(filedetail,"<>");//cut front of "<"
                    tempChar = strtok(NULL, ">");//get detail between < >
                    tempChar = strtok(NULL, "<>");
                    temp = tempChar;
                    if(strcmp(toAsso.tclass_name, basAsso.tclass_name)!=0){//the two class name is not the same
                        haveLink = true;/*record the two class have link class*/
                        if(temp !="<"){
                            dtdclass * linkClass = new dtdclass();/*creast a linker class*/
                            linkClass->setname(Slinker_name);
                            linkClass->setlevel(1);
                            int tempMulti;
                            tempMulti = basAsso.to_multi;/*change the multi link of the association*/
                            basAsso.to_multi =1;
                            linkClass->setassociation(basAsso);/*set the association of the link class*/
                            /*get back the original multi link number of the association*/
                            basAsso.to_multi = tempMulti;
                            tempMulti = toAsso.to_multi;
                            toAsso.to_multi = 1;
                            linkClass->setassociation(toAsso);
                            toAsso.to_multi = tempMulti;

                            readLinkAttribute(tempChar, linkClass, fin);/*call the read attribute name*/
                            strcpy(linker_name, Slinker_name.c_str());
                            strcpy(basAsso.tclass_name, linker_name);/*change the relation class name*/
                            basAsso.base_multi =1;
                            strcpy(toAsso.tclass_name, linker_name);
                            toAsso.base_multi =1;
                            d_class.push_back(linkClass);//add link class into deque
                        }
                    }
                    else{
                        attribute base;
                        strcpy(base.att_name, tempChar);
                        base.isId = false;
                        base.ismulti = false;
                        base.max=1;
                        base.min=1;
                        first = d_class.begin();//get the begin of the deque
                        last = d_class.end();//get the end of the deque
                        for (deque<dtdclass *>::iterator i=first; i !=last;i++){
                            if(base_name ==(*i)->getname()){
                                (*i)->setattribute(base);
                            }
                        }
                    }
                    
                    
                }
                else if(temp == "association_class"){
                    bool haveAssociation;/*record the true or false have association class*/
                    //call read association qualification function
                    haveAssociation = readAssoQua(fin, d_class, linker_name, basAsso, toAsso);
                    if(haveAssociation == true){
                        haveLink = true;/*record the two class have link class*/
                        strcpy(basAsso.tclass_name, linker_name);/*change the relation class name*/
                        basAsso.base_multi =1;
                        strcpy(toAsso.tclass_name, linker_name);
                        toAsso.base_multi =1;
                    }
                }
                
            }
        }
    }while(associationFinish != true); //end of read the association
    //search correct class in the deque and put the association in it
    
    if(!d_class.empty()){//check the deque is not empty
        first = d_class.begin();//get the begin of the deque
        last = d_class.end();//get the end of the deque
        if(baseLevel==1 && toLevel ==3){baseLevel =2;}//if the relate is 1...*
        if(haveLink == true){//set the class level being 3, as a reference in DTD
            baseLevel =3;
            toLevel =3;
        }
        for (deque<dtdclass *>::iterator i=first; i !=last;i++){
            if(base_name ==(*i)->getname()){//add association into class
                (*i)->setassociation(basAsso);//add association
                (*i)->setlevel(baseLevel);
                if(haveBasequali == true){
                    if(!baseQualification.empty()){/*get the qualification attribute from the deque and add it into the class*/
                        deque<attribute *>::iterator firstAttribute = baseQualification.begin();
                        deque<attribute *>::iterator lastAttribute =   baseQualification.end();
                        for(deque<attribute * >::iterator attributeI = firstAttribute; attributeI != lastAttribute; attributeI++){
                            strcpy(basequali.att_name, (*attributeI)->att_name);
                            basequali.isId = (*attributeI)->isId;
                            basequali.ismulti= (*attributeI)->ismulti;
                            (*i)->setattribute(basequali);
                        }
                    }
                    
                }//add attribute if there any
            }
            else if(to_name==(*i)->getname()){
                (*i)->setassociation(toAsso);
                (*i)->setlevel(toLevel);
                if(haveToquali ==true){ 
                    if(!toQualification.empty()){/*get the qualification attribute from the deque and add it into the class*/
                        deque<attribute *>::iterator firstToAttribute = toQualification.begin();
                        deque<attribute *>::iterator lastToAttribute =   toQualification.end();
                        for(deque<attribute * >::iterator attributeI = firstToAttribute; attributeI != lastToAttribute; attributeI++){
                            strcpy(toquali.att_name, (*attributeI)->att_name);
                            toquali.isId = (*attributeI)->isId;
                            toquali.ismulti= (*attributeI)->ismulti;
                            (*i)->setattribute(toquali);
                        }
                    }
                        
                }
            }
        }//finish add association
    } 
}
コード例 #9
0
ファイル: main.cpp プロジェクト: vitawebsitedesign/321
bool readAssoQua(ifstream & fin, deque<dtdclass *>&d_class, char * name, associate & basAsso, associate& toAsso){
    char filedetail[256];/*record the each line of file from the compiler*/
    char * tempChar;
    string temp, qualiClass;
    bool finishQualiAssoClass = false;
    bool haveQualification = false;
    bool haveAssociation = false;/*check the association have detail or not*/
    attribute tempattribute;
    deque<attribute *> tempQualification;
    
    deque<dtdclass*>::iterator first;/*recond the first position of the deque*/
    deque<dtdclass*>::iterator last;/*recond the last position of the deque*/
    do{
        fin.getline(filedetail,255);
        if(strcmp(filedetail, "")==0){continue;}/*if the line is empty, continue*/
        tempChar = strtok(filedetail,"<>");//cut front of "<"
        tempChar = strtok(NULL, "<>");/*get the detail between <> */
        temp = tempChar;
        if(temp=="/association_class" || temp =="/Link"){//check if is end of one association class
            finishQualiAssoClass=true;//is control while loop
        }
        else if(temp == "nameOfAssociationClass"){
            haveAssociation=true;
            tempChar = strtok(NULL, "<>");
            strcpy(name, tempChar);
            qualiClass = tempChar;
            if(!d_class.empty()){//check the deque is not empty
                    first = d_class.begin();//get the begin of the deque
                    last = d_class.end();//get the end of the deque
                    for (deque<dtdclass *>::iterator i=first; i !=last;i++){
                        if(qualiClass ==(*i)->getname()){//add association into class
                            (*i)->setlevel(1);
                            int tempMulti;
                            tempMulti = basAsso.to_multi;
                            basAsso.to_multi = 1;/*change the multi link of the association*/
                            (*i)->setassociation(basAsso);//add association
                            basAsso.to_multi = tempMulti;;/*get back the original multi link number of the association*/
                            tempMulti = toAsso.to_multi;
                            toAsso.to_multi =1;/*change the multi link of the association*/
                            (*i)->setassociation(toAsso);//add association
                            toAsso.to_multi = tempMulti;/*get back the original multi link number of the association*/
                            if(haveQualification == true){
                                if(!tempQualification.empty()){/*get the qualification attribute from the deque and add it into the class*/
                                    deque<attribute *>::iterator firstAttribute = tempQualification.begin();
                                    deque<attribute *>::iterator lastAttribute =  tempQualification.end();
                                    for(deque<attribute * >::iterator attributeI = firstAttribute; attributeI != lastAttribute; attributeI++){
                                        strcpy(tempattribute.att_name, (*attributeI)->att_name);
                                        tempattribute.isId = (*attributeI)->isId;
                                        tempattribute.ismulti= (*attributeI)->ismulti;
                                        (*i)->setattribute(tempattribute);//add the attribute into the class
                                    }
                                }
                            }/*finish add all qualification into the class*/
                        }
                    }
                }
        }
        else if(temp == "qualification"){
            haveAssociation = true;
            tempChar = strtok(NULL, "/<");
            temp = tempChar;
            if(temp !="<"){
                attribute * tempAttri = new attribute;
                strcpy(tempAttri->att_name,tempChar);
                tempAttri->isId = true;
                tempAttri->ismulti = false;
                haveQualification =true;
                tempQualification.push_back(tempAttri);
            }
        }
        
    }while(finishQualiAssoClass !=true);
    return haveAssociation;
}
コード例 #10
0
ファイル: server.cpp プロジェクト: IthacaDream/Networking
unsigned long handleClientThread(void*)
{
    int pth_id=MThread::GetCurrentThreadID();

    MSocket *pclient=NULL;
    while(true){

	MutexClient.Lock();
	if(!clientDeque.empty()){
	    pclient=clientDeque.front();
	    clientDeque.pop_front();
	    MutexClient.Unlock();

	    cout<<"In thread: "<<pth_id<<endl;
	    struct timeval testtime;
	    testtime.tv_sec=400;
	    testtime.tv_usec=0;
	    if(pclient->Setsockopt(SOL_SOCKET,SO_RCVTIMEO,
				   (char*)&testtime,sizeof(testtime))==-1)
	    {
		pclient->Shutdown(2);
		pclient->Close();
		delete pclient;
	    }
	    //pclient->SetNonblock(false);//block, return 0
	    int rt;
	    int len=0;
	    cout<<"now begin Recv..."<<endl;

	    Data *mydata=new Data;
	    rt=pclient->SafeRecv(mydata,sizeof(Data));
	    if(rt==-1){//if rt!=-1,then rt==sizeof(Data)
		cout<<"recv error"<<endl;
		pclient->Shutdown(2);
		pclient->Close();
		delete pclient;
		pclient=NULL;
		break;
	    }

	    cout<<"Received data: "<<endl;

	    //´¦ÀíÊý¾Ý
	    
	    cout<<"key: "<<mydata->key<<endl
		<<"value: "<<mydata->value<<endl;

	    char result[]="success";
	    len=strlen(result);
	    rt=pclient->SafeSend(&len,sizeof(int));
	    if(rt==-1){
		cout<<"send error"<<endl;
		pclient->Shutdown(2);
		pclient->Close();
		delete pclient;
		pclient=NULL;
		break;
	    }
	    
	    rt=pclient->SafeSend(result,len);
	    if(rt==-1){
		cout<<"send error"<<endl;
		pclient->Shutdown(2);
		pclient->Close();
		delete pclient;
		pclient=NULL;
		break;
	    }
	    cout<<"send back sucess"<<endl;
	    cout<<"doing sth ..."<<endl;
	    MThread::Sleep(1000);
	    
	}else
	{
	    MutexClient.Unlock();
	    cout<<"deque empty,now sleep(100)..."<<endl;
	    MThread::Sleep(100);
	}
    }
    return 1;

}
コード例 #11
0
ファイル: main.cpp プロジェクト: xuziye0327/acm
void init() {
    while(!order.empty()) order.pop_front();
    while(!moon.empty()) moon.pop_front();
}
コード例 #12
0
ファイル: 372C.cpp プロジェクト: yancouto/maratona-sua-mae
inline void enqueue(ll x) {
	q.push(x);
	while(!dq.empty() && x < dq.back()) dq.pop_back();
	dq.push_back(x);
}
コード例 #13
0
bool iCub::optimization::minVolumeEllipsoid(const deque<Vector> &points,
                                            const double tol,
                                            Matrix &A, Vector &c)
{
    // This code is a C++ version of the MATLAB script written by:
    // Nima Moshtagh ([email protected]), University of Pennsylvania
    //
    // It makes use of the Khachiyan algorithm and aims at minimizing
    // iteratively the following problem:
    //
    // min log(det(A))
    // s.t. (points[i]-c)'*A*(points[i]-c)<=1

    if (points.empty())
        return false;

    // initialization
    int d=points.front().length();
    int N=(int)points.size();
    Vector u(N,1.0/N);
    Matrix U(N,N); U.diagonal(u);
    Matrix Q(d+1,N);
    for (int row=0; row<Q.rows(); row++)
        for (int col=0; col<Q.cols(); col++)
            Q(row,col)=points[col][row];
    for (int col=0; col<Q.cols(); col++)
        Q(Q.rows()-1,col)=1.0;
    Matrix Qt=Q.transposed();

    // run the Khachiyan algorithm
    Matrix M;
    while (true)
    {
        M=Qt*pinv(Q*U*Qt)*Q;
        int j=0; double max=M(j,j);
        for (int row=1; row<M.rows(); row++)
        {
            if (M(row,row)>max)
            {
                max=M(row,row);
                j=row;
            }
        }
        double step_size=(max-d-1.0)/((d+1.0)*(max-1.0));
        Vector new_u=(1.0-step_size)*u;
        new_u[j]+=step_size;
        if (norm(new_u-u)<tol)
            break;
        u=new_u;
        U.diagonal(u);
    }

    // compute the ellipsoid parameters
    Matrix P=Q.removeRows(Q.rows()-1,1);
    c=P*u;
    Matrix C(c.length(),c.length());
    for (int col=0; col<C.cols(); col++)
        C.setCol(col,c[col]*c);
    A=(1.0/d)*pinv(P*U*P.transposed()-C);

    return true;
}
コード例 #14
0
ファイル: 328.cpp プロジェクト: roosephu/project-euler
void push(deque<pair<int, int>> &Q, pair<int, int> v) {
    while (!Q.empty() && Q.back() > v) {
        Q.pop_back();
    }
    Q.push_back(v);
}
コード例 #15
0
//===========================================================================
// Description: Function pops the top  element of an stl queue. An FSM with
// 8 states is implimented through the form of a looped switch. First
// character is analyzed, and states  are transitioned accordingly. In the
// case of a compound opperator, the second character is looked at. If it
// matches /the pattern of those opperators, a second character is popped
// and the opperator is returned as two characters. This loop repeats until
// the stack is empty.
//====== lexer() ============================================================
string lexer(deque<char> & queue)
{
    STATES state = STARTING;
    string tempIdentifier, tempInteger, tempReal;
    char token, tokenNext;
    while(!queue.empty())
    {
        token = queue.front();
        queue.pop_front();
        if(!queue.empty())
            tokenNext = queue.front();
        do {
            switch(state)
            {
            /*
            STARTING STATE
            */
            case STARTING:
                //First character of identifier must be alphabetic
                if(isalpha(token) || token=='_')
                {
                    tempIdentifier+=token;
                    state = IDENTIFIER;
                }
                else if(isdigit(token))
                {
                    tempInteger+=token;
                    state = INTEGER;
                }
                else if(token =='.') state = ERROR;
                else if(token == ' ') state = STARTING;
                else if(token == '$' && queue.empty()) return "$";
                else if(token == '(') {
                    state = STARTING;
                    return "(";
                }
                else if(token == ')') {
                    state = STARTING;
                    return ")";
                }
                else if(token == ',') {
                    state = STARTING;
                    return ",";
                }
                else if(token == '{') {
                    state = STARTING;
                    return "{";
                }
                else if(token == '}') {
                    state = STARTING;
                    return "}";
                }
                else if(token == ';') {
                    state = STARTING;
                    return ";";
                }
                else if(token == '+') {
                    state = STARTING;
                    return "+";
                }
                else if(token == '*') {
                    state = STARTING;
                    return "*";
                }
                else if(token == '-') {
                    state = STARTING;
                    return "-";
                }
                else if(token == '=') {
                    state = STARTING;
                    return "=";
                }
                else if(token == '$')
                {
                    if(tokenNext == '$')
                    {
                        queue.pop_front();
                        return "$$";
                    }
                    else
                        return "$";
                    state = STARTING;
                }
                else if(token == '<')
                {
                    state = STARTING;
                    if(tokenNext == '=')
                    {
                        queue.pop_front();
                        return "<=";
                    }
                    else
                        return "<";
                }
                else if(token == '>')
                {
                    state = STARTING;
                    if(tokenNext == '=')
                    {
                        queue.pop_front();
                        return ">=";
                    }
                    else
                        return ">";
                }
                else if(token == '/')
                {
                    state = STARTING;
                    if(tokenNext == '=')
                    {
                        queue.pop_front();
                        return "/=";
                    }
                    else
                        return "/";
                }

                else if(token == ':')
                {
                    state = STARTING;
                    if(tokenNext == '=')
                    {
                        queue.pop_front();
                        return ":=";
                    }
                    else
                        return ":";
                }
                break;
            /*
            IDENTIFIER STATE
            */
            case IDENTIFIER:
                if(isalpha(token) || token == '_')
                {
                    tempIdentifier+=token;
                    //Switches to ERROR state, if last character in identifier is _
                    if(token == '_' && isalnum(tokenNext)==0)
                        state = ERROR;
                    else
                        state = IDENTIFIER;
                }
                else if(isdigit(token))
                {
                    tempIdentifier+=token;
                    state = IDENTIFIER;
                }
                if(queue.empty()) state = END_IDENTIFIER;
                else if(token == ' ') state = END_IDENTIFIER;
                else if(token == '(') state = END_IDENTIFIER;
                else if(token == ')') state = END_IDENTIFIER;
                else if(token == '{') state = END_IDENTIFIER;
                else if(token == '}') state = END_IDENTIFIER;
                else if(token == ';') state = END_IDENTIFIER;
                else if(token == ',') state = END_IDENTIFIER;
                else if(token == '$') state = END_IDENTIFIER;
                else if(token == '<') state = END_IDENTIFIER;
                else if(token == '>') state = END_IDENTIFIER;
                else if(token == '/') state = END_IDENTIFIER;
                else if(token == '+') state = END_IDENTIFIER;
                else if(token == '*') state = END_IDENTIFIER;
                else if(token == '-') state = END_IDENTIFIER;
                else if(token == ':') state = END_IDENTIFIER;
                break;
            /*
            END IDENTIFIER STATE
            */
            case END_IDENTIFIER:
                if(tempIdentifier!="")
                {
                    string identifier = tempIdentifier;
                    state = STARTING;
                    tempIdentifier.clear();
                    queue.push_front(token);
                    return removeSpaces(identifier);
                }
            /*
            INTEGER STATE
            */
            case INTEGER:
                //Transitions to error state if letter is entered from integer state
                if(isalpha(token))
                {
                    tempInteger+=token;
                    //Waits until string finishes before transitioning to error state
                    if(isalnum(tokenNext)==0)
                        state = ERROR;
                    else
                        state = INTEGER;
                }
                else if(isdigit(token))
                {
                    tempInteger+=token;
                    state = INTEGER;
                }
                else if(token =='.')
                {
                    tempReal+=tempInteger+=".";
                    state = REAL;
                    //Clear integer value before transition to real number
                    tempInteger.clear();
                }
                if(token == ' ') state = END_INTEGER;
                else if(token == '(') state = END_INTEGER;
                else if(token == ')') state = END_INTEGER;
                else if(token == '{') state = END_INTEGER;
                else if(token == '}') state = END_INTEGER;
                else if(token == ';') state = END_INTEGER;
                else if(token == ',') state = END_INTEGER;
                else if(token == '$') state = END_INTEGER;
                else if(token == '<') state = END_INTEGER;
                else if(token == '>') state = END_INTEGER;
                else if(token == '/') state = END_INTEGER;
                else if(token == '+') state = END_INTEGER;
                else if(token == '*') state = END_INTEGER;
                else if(token == '-') state = END_INTEGER;
                else if(token == ':') state = END_INTEGER;
                break;
            /*
            END INTEGER STATE
            */
            case END_INTEGER:
                if(tempInteger!="")
                {
                    string integer = tempInteger;
                    state = STARTING;
                    tempInteger.clear();
                    queue.push_front(token);
                    return removeSpaces(integer);
                }
                break;
            /*
            REAL NUMBERS STATE
            */
            case REAL:
                if(isalpha(token))
                {
                    tempIdentifier+=token;
                    state = END_REAL;
                }
                else if(isdigit(token))
                {
                    tempReal+=token;
                    state = REAL;
                }
                else if(token =='.')
                {
                    tempReal+=token;
                    state = ERROR;
                }
                if(tokenNext == ' ') state = END_REAL;
                else if(tokenNext == '(') state = END_REAL;
                else if(tokenNext == ')') state = END_REAL;
                else if(tokenNext == '{') state = END_REAL;
                else if(tokenNext == '}') state = END_REAL;
                else if(tokenNext == ';') state = END_REAL;
                else if(tokenNext == '$') state = END_REAL;
                else if(tokenNext == ',') state = END_REAL;
                else if(tokenNext == '<') state = END_REAL;
                else if(tokenNext == '>') state = END_REAL;
                else if(tokenNext == '/') state = END_REAL;
                else if(tokenNext == '+') state = END_REAL;
                else if(tokenNext == '*') state = END_REAL;
                else if(tokenNext == '-') state = END_REAL;
                else if(tokenNext == ':') state = END_REAL;
                break;
            /*
            END REAL NUMBERS STATE
            */
            case END_REAL:
                state = STARTING;
                return removeSpaces(tempReal);
                break;
            /*
            ERROR STATE
            */
            case ERROR:
                state = STARTING;
                if(tempIdentifier!="")
                    tempIdentifier.clear();
                if(tempInteger!="")
                    tempInteger.clear();
                if(tempReal!="")
                    tempReal.clear();
                break;
            }
        } while(state == END_IDENTIFIER || state == END_INTEGER || state==END_REAL);
    }
}
コード例 #16
0
ファイル: main.cpp プロジェクト: SRITANU/USACO
int main()
{
    freopen("maze1.in", "r", stdin);
    freopen("maze1.out", "w", stdout);
    scanf("%d %d", &W, &H);
    MMset(dist, -1);
    for (int i = 0; i < 2 * H + 1; i++) {
        getchar();
        for (int j = 0; j < 2 * W + 1; j++) {
            scanf("%c", &maze[i][j]);
        }
    }
    for (int i = 0; i < 2 * W + 1; i++) {
        if (maze[0][i] == ' ') {
            Q.push_back(make_pair(1, i));
            dist[1][i] = 1;
            in[1][i] = 1;
        }
        if (maze[2 * H][i] == ' ') {
            Q.push_back(make_pair(2 * H - 1, i));
            dist[2 * H - 1][i] = 1;
            in[2 * H - 1][i] = 1;
        }
    }
    for (int i = 0; i < 2 * H + 1; i++) {
        if (maze[i][0] == ' ') {
            Q.push_back(make_pair(i, 1));
            dist[i][1] = 1;
            in[i][1] = 1;
        }
        if (maze[i][2 * W] == ' ') {
            Q.push_back(make_pair(i, 2 * W - 1));
            dist[i][2 * W - 1] = 1;
            in[i][2 * W - 1] = 1;
        }
    }
    while (!Q.empty()) {
        int tx = Q.front().first;
        int ty = Q.front().second;
        Q.pop_front();
        in[tx][ty] = 0;
        for (int i = 0; i < 4; i++) {
            int nx = tx + dirx[i] * 2;
            int ny = ty + diry[i] * 2;
            int fx = tx + dirx[i];
            int fy = ty + diry[i];
            if (nx < 0
                || nx >= 2 * H + 1
                || ny < 0
                || ny >= 2 * W + 1
                || maze[fx][fy] != ' ') {
                    continue;
            }
            if (dist[nx][ny] == -1 || dist[nx][ny] > dist[tx][ty] + 1) {
                dist[nx][ny] = dist[tx][ty] + 1;
                if (!in[nx][ny]) {
                    in[nx][ny] = 1;
                    Q.push_back(make_pair(nx, ny));
                }
            }
        }
    }
    int ret = 0;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            ret = max(ret, dist[2 * i + 1][2 * j + 1]);
        }
    }
    printf("%d\n", ret);
    return 0;
}
コード例 #17
0
ファイル: 5845.cpp プロジェクト: Ronnoc/Training
	void init(){_[0]=_[1]=NULL;while(!Q.empty())Q.pop_back();}
コード例 #18
0
 void updateQueue(deque<int> &Q, const vector<int>& nums, int j, Compare cmp) {
     while (!Q.empty() && cmp(nums[Q.back()], nums[j])) Q.pop_back();
     Q.push_back(j);
 }
コード例 #19
0
ファイル: scheduling_Uni.cpp プロジェクト: csl/OS-
void schedule()
{
 
  int num_finished = 0;
  //First Come First Serve
  //Populate the queue based on arrival times
  int min = 1000,proc_num = 0,max = 0;
 
  //cout<<"Proc "<<proc_num<<endl;
  Q.push_back(P[0]);
  int cpu_run,IO_run,cpu_r;
  timer = 0; //Set the Clock
  process current = Q.front();
  current.state = "running";
  bool flag = true;
  max = P[P.size()-1].A;
  while(!Q.empty() || timer <= max || flag)
    {
   

      int counter = 0;
      for(int i = 0; i < P.size(); i++)  // All processes Terminated?
	{
	  if(P[i].state =="terminated")
	  counter++;
	}
     
      if(counter == P.size())
	{
	  flag = false;
	  break;
	}
      
    
      bool no_IO, race = false; 
      
      
      if(current.state == "ready")
	current.state = "running";
     
    
	  cpu_run = 1 + (U[current_random] % current.B);
	  cout<<"CPU Burst: "<<U[current_random]<<endl;
	  current_random++;

       if(cpu_run > current.C)
	 cpu_run = current.C;
      // cout<<"cpu: "<<cpu_run<<endl;
      CPU_time += cpu_run;
  
      for(int i = 1; i  <= cpu_run; i++)
	{
	  timer++;
	if(verbose)
	{
	  cout<<"Current: "<<timer<<" ";
	  for(int k = 0; k  < P.size(); k++)
	    {
	      if(P[k].id == current.id)
		cout<<P[k].id<<" "<<current.state<<" ";
	      else
		cout<<P[k].id<<" "<<P[k].state<<" ";
	      
	    }
	  cout<<endl;}
	  //current.state = "running";
	  if(current.state == "running")
	    current.C = current.C - 1;

	  for(int j = 0; j < P.size(); j++)
	    {
	      //  cout<<"Timer: "<<timer<<" "<<current.state<<" "<<P[j].state<<endl;
	      if(P[j].id != current.id)
		{
		  if(P[j].state == "blocked")  //Decrease block_time for each Blocked Process.
		    {
		      P[j].block_time -= 1;
		      P[j].in_IO_time += 1;
		      if(P[j].block_time == 0)
			{
			  P[j].state = "ready";
			  Q.push_back(P[j]); //Process Ready to run now.
			 
			}
		    }
		  else if(P[j].state == "ready") //If the Process is in ready state and not executing, it is waiting.
		    {
		      for(int k = 0; k < Q.size(); k++)	
			if(Q[k].id == P[j].id)
			  {
			    Q[k].wait_time += 1;
			    //  Q[k].state = "ready"; 
			  }
		    }
		  else if(P[j].state == "unstarted" && P[j].A < timer)
		    {
		      P[j].state = "ready";
		      P[j].wait_time += 1;
		      Q.push_back(P[j]);
		    }
		  if(P[j].A == timer && P[j].state == "unstarted")
		    {
		      P[j].state ="ready";
		      Q.push_back(P[j]);
		    }
		}//P[j].id != current.id
	    }//j ends
	}//i ends
      
      if(current.C == 0)
	{
	  current.finish_time = timer; 
	  current.state = "terminated";
	  for(int k = 0; k < P.size(); k++)
	    {
	      if(P[k].id == current.id)
	      P[k] = current;
	    }
	
	  Q.pop_front();
	  if(Q.size() > 0)
	    current = Q.front();
	}
      else
	{
	      current.state = "blocked";
	      // cout<<"rand"<<U[current_random]<<endl;
	      IO_run = 1 + (U[current_random] % current.IO); //IO run for the current process.
	      cout<<"IO Burst: "<<U[current_random]<<endl;
	      current_random++;
	      for(int i = 0; i < IO_run; i++)
		{
		  timer++;
		}
	      //cout<<"IOR "<<IO_run<<endl;
		current.block_time = 0;
	      IO_time += IO_run;
	      current.state ="ready";
	     // Q.pop_front(); 

	  for(int k = 0; k < P.size(); k++)
	    if(P[k].id == current.id)
	      P[k] = current; //State saved in the Process.
	   // Process is blocked hence popped off the queue. 
	}
    }
   for(int i = 0; i < CP.size(); i++)
    {
      
      cout<<"Process "<<P[i].id<<" : "<<P[i].state<<endl;
      cout<<"(A,B,C,IO) : ( "<<CPZ[i].A<<", "<<CPZ[i].B<<", "<<CPZ[i].C<<", "<<CPZ[i].IO<<" )"<<endl;
      cout<<"Finishing Time: "<< P[i].finish_time<<endl;
      cout<<"Turnaround Time: "<<P[i].finish_time - P[i].A<<endl;
      cout<<"I/O Time: "<<P[i].in_IO_time<<endl;
      cout<<"Waiting Time: "<<P[i].wait_time<<endl;
    }
  cout<<"Summary Data:"<<endl;
  cout<<"Finishing Time: "<<timer<<endl;
  cout<<"CPU Utilization: "<<(float)CPU_time/(timer)<<endl;
    cout<<"I/O Utilization: "<<(float)IO_time/timer<<endl;
  
    cout<<"Throughput: "<<"" <<" processes per hundred cycles "<<(float)((float)P.size()/(float)timer) * (float)100<<endl; 
  float turn = 0.0; int sum = 0;  
for(int i = 0; i < P.size(); i++)
    {
      sum += (P[i].finish_time - P[i].A);
    }
 turn = (float)sum/P.size();
 cout<<"Average Turnaround time: "<<turn<<endl;
 sum = 0; 
for(int i = 0; i < P.size(); i++)
  sum+= P[i].wait_time;
 turn = (float)sum/P.size();
 cout<<"Average Waiting Time: "<<turn<<endl;
}
コード例 #20
0
void OPTTSP_helper(deque<int> &q, deque<int> &s, int &curMin, deque<int> &curPath, int **matrix, vector<int> &Minimum, vector<int> &SecondMinimum, int Promissing)
{
		

	unsigned k, size = q.size();

	if(Promissing/2 >= curMin)
	{
//		cout << "Current Min is: " << curMin << endl;
		return;
	}
	if(q.empty())
	{
		for(int i = 0;i < s.size();i++)
		{
//			cout << s[i];
		}
//		cout << endl;
//		cout << "a" << endl;
//		curCost = curCost + abs(data[s[s.size()-1]].x - data[0].x) + 
//		abs(data[s[s.size()-1]].y - data[0].y);
		Promissing = Promissing - Minimum[s[s.size()-1]] - SecondMinimum[0] +  2 * matrix[s[s.size()-1]][0];		
		
		if(Promissing/2 < curMin)
		{
//			cout << "a" << endl;
			curMin = Promissing/2;
			for(int i=0;i < s.size();i++)
			{
				curPath[i] = s[i];
			}
		}
		return;
	}
	for(k = 0; k != size; k++)
	{
		
//		cout << "a" << endl;
		int c = s.size();	
		if(c >= 3)
		{
			int path1 = matrix[s[c-3]][s[c-2]] + matrix[s[c-1]][q[0]];
			int path2 = matrix[s[c-3]][s[c-1]] + matrix[q[0]][s[c-2]];
			if(path1 > path2)
			{
				q.push_back(q.front());
				q.pop_front();
				continue;
			}
		}
		s.push_back(q[0]);
		q.pop_front();
		
		
//		cout << curVertex << endl;
		
		if(s.size() == 1)
		{
//			curCost = curCost + abs(data[s[s.size()-1]].x-data[0].x)
//				+ abs(data[s[s.size()-1]].y-data[0].y);
			Promissing = Promissing - Minimum[0] - SecondMinimum[s[s.size()-1]] + 2 * matrix[s[s.size()-1]][0];
		}
		else
		{
//			curCost = curCost + abs(data[s[s.size()-1]].x-data[s[s.size()-2]].x)
//				+ abs(data[s[s.size()-1]].y-data[s[s.size()-2]].y);
			Promissing = Promissing - Minimum[s[s.size()-2]] - SecondMinimum[s[s.size()-1]] + 2 * matrix[s[s.size()-1]][s[s.size()-2]];
		}

//		cout << curCost << endl;
			
//		curVertex = s[s.size()-1];
//		cout << "current path size: " << s.size() << "  The last vertex:  " << curVertex << endl;
	
		
		OPTTSP_helper(q, s, curMin, curPath, matrix, Minimum, SecondMinimum, Promissing);
		
		if(s.size() == 1)
		{
			Promissing = Promissing + Minimum[0] + SecondMinimum[s[0]] - 2 * matrix[s[0]][0];
		}
		else
		{
//			curCost = curCost - (abs(data[s[s.size()-1]].x-data[s[s.size()-2]].x)
//				+ abs(data[s[s.size()-1]].y-data[s[s.size()-2]].y));
			Promissing = Promissing + Minimum[s[s.size()-2]] + SecondMinimum[s[s.size()-1]] - 2 * matrix[s[s.size()-1]][s[s.size()-2]];
		}
		q.push_back(s[s.size()-1]);
		s.pop_back();
	}
}
コード例 #21
0
ファイル: appserver.cpp プロジェクト: gary109/udt4-appserver
int 
main(int argc, char* argv[]) {
	const int test_case = 2;
	signal(SIGINT, &signal_handler);
#ifndef WIN32
	void* (*AppServer[test_case])(void*);
#else
	DWORD (WINAPI *AppServer[test_case])(LPVOID);
#endif
	AppServer[0] = AppServer_TCP;
	AppServer[1] = AppServer_UDT;
	cout << "Start AppServer Mode # Callee" << endl;
	UDT::startup();
#ifndef WIN32
	pthread_t srv_udt, srv_tcp;
	pthread_create(&srv_tcp, NULL, AppServer[0], NULL);
	pthread_create(&srv_udt, NULL, AppServer[1], NULL);

	//pthread_join(srv_udt, NULL);
	//pthread_join(srv_tcp, NULL);
#else
	HANDLE srv_udt, srv_tcp;
	srv_tcp = CreateThread(NULL, 0, AppServer[0], NULL, 0, NULL);
	srv_udt = CreateThread(NULL, 0, AppServer[1], NULL, 0, NULL);

	//WaitForSingleObject(srv_udt, INFINITE);
	//WaitForSingleObject(srv_tcp, INFINITE);
#endif
	////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////
	cout << "Run Task loop ...\n";
	main_running = 1;
	while (main_running) 
	{
		if (!taskQueue.empty())
		{
			switch (taskQueue.front()->header.cmd)
			{
			case CMD_C_DISCONNECT:
			{
				connectMap_iter = connectMapKeyC.find(taskQueue.front()->header.cliFD);
				if (connectMap_iter != connectMapKeyC.end())
				{
					UDT::epoll_remove_ssock(tcp_eid, connectMap_iter->second);
#ifndef WIN32
					close(connectMap_iter->second);
#else
					closesocket(connectMap_iter->second);
#endif
				}
				taskQueue.pop_front();
			}
			break;
			case CMD_CONNECT:
			{
				pTcp_sock = new SYSSOCKET;
				if (createTCPSocket(*pTcp_sock, 0) < 0) {
					cout << "\tcan't create tcp socket!" << endl;
				}

				map_insert(&connectMapKeyC, taskQueue.front()->header.cliFD, *pTcp_sock);
				map_insert(&connectMapKeyS, *pTcp_sock, taskQueue.front()->header.cliFD);

				if (tcp_connect(*pTcp_sock, REMOTE_PORT) < 0) {
					printf("\tCan't connect local port 80\n");
				}
				UDT::epoll_add_ssock(tcp_eid, *pTcp_sock);
				taskQueue.pop_front();
			}
			break;
			case CMD_S_DISCONNECT:
			{
				char* buftmp = (char*)(taskQueue.front());
				int res = 0;
				int ssize = 0;
				//UDT::perfmon(client, &trace);
				while (ssize < udtsize)
				{
					//int scv_size;
					//int var_size = sizeof(int);
					//UDT::getsockopt(client, 0, UDT_SNDDATA, &scv_size, &var_size);
					if (UDT::ERROR == (res = UDT::send(client, buftmp + ssize, udtsize - ssize, 0)))
					{
						cout << "send:" << UDT::getlasterror().getErrorMessage() << endl;
						break;
					}

					ssize += res;
				}
				//printf("ok.[%d]\n", res);

				//UDT::perfmon(client, &trace);
				//cout << "\tspeed = " << trace.mbpsSendRate << "Mbits/sec" << endl;

				taskQueue.pop_front();
			}
			break;
			case CMD_DATA_S2T:
			{
				connectMap_iter = connectMapKeyC.find(taskQueue.front()->header.cliFD);
				if (connectMap_iter != connectMapKeyC.end())
				{
					int rs = send(connectMap_iter->second,
						taskQueue.front()->payload.buf,
						taskQueue.front()->payload.len,
						0);
					if (0 > rs)			cout << "\t CMD_DATA_S2T error1.\n";
					else if (rs == 0)	printf("\t CMD_DATA_S2T disconnect.\n");
				}
				taskQueue.pop_front();
			}
			break;
			default:
				break;
			}
		}
	}
	////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////
	UDT::cleanup();
	cout << "AppServer # Callee " << " end." << endl;
	return 0;
}
コード例 #22
0
 const T &max(void) const {
   if (D.empty() == false) {
     return D.front();
   }
   throw length_error("empty queue");
 }
コード例 #23
0
int internal_degree_and_membership (double mixing_parameter, int overlapping_nodes, int max_mem_num, int num_nodes, deque<deque<int> >  & member_matrix, 
bool excess, bool defect,  deque<int> & degree_seq, deque<int> &num_seq, deque<int> &internal_degree_seq, bool fixed_range, int nmin, int nmax, double tau2) {
	
	
	
	
	
	if(num_nodes< overlapping_nodes) {
		
		cerr<<"\n***********************\nERROR: there are more overlapping nodes than nodes in the whole network! Please, decrease the former ones or increase the latter ones"<<endl;
		return -1;
	}
	
	
	// 
	member_matrix.clear();
	internal_degree_seq.clear();
	
	deque<double> cumulative;
	
	// it assigns the internal degree to each node -------------------------------------------------------------------------
	int max_degree_actual=0;		// maximum internal degree

	for (int i=0; i<degree_seq.size(); i++) {
		
		double interno=(1-mixing_parameter)*degree_seq[i];
		int int_interno=int(interno);
		
		
		if (ran4()<(interno-int_interno))
			int_interno++;
		
		if (excess) {
			
			while (   (  double(int_interno)/degree_seq[i] < (1-mixing_parameter) )  &&   (int_interno<degree_seq[i])   )
				int_interno++;
				
		
		}
		
		
		if (defect) {
			
			while (   (  double(int_interno)/degree_seq[i] > (1-mixing_parameter) )  &&   (int_interno>0)   )
				int_interno--;
				
		
		}

		
		
		
		internal_degree_seq.push_back(int_interno);
		
		
		if (int_interno>max_degree_actual)
			max_degree_actual=int_interno;
		
			
	}
	
	
	// it assigns the community size sequence -----------------------------------------------------------------------------
	
	powerlaw(nmax, nmin, tau2, cumulative);
	
	
	if (num_seq.empty()) {
		
		int _num_=0;
		if (!fixed_range && (max_degree_actual+1)>nmin) {
		
			_num_=max_degree_actual+1;			// this helps the assignment of the memberships (it assures that at least one module is big enough to host each node)
			num_seq.push_back(max_degree_actual+1);
		
		}
		
		
		while (true) {
			
			
			int nn=lower_bound(cumulative.begin(), cumulative.end(), ran4())-cumulative.begin()+nmin;
			
			if (nn+_num_<=num_nodes + overlapping_nodes * (max_mem_num-1) ) {
				
				num_seq.push_back(nn);				
				_num_+=nn;
			
			}
			else
				break;
			
			
		}
		
		num_seq[min_element(num_seq.begin(), num_seq.end()) - num_seq.begin()]+=num_nodes + overlapping_nodes * (max_mem_num-1) - _num_;
		
	}
	
	
	//cout<<"num_seq"<<endl;
	//prints(num_seq);
	
	int ncom=num_seq.size();
	
	//cout<<"\n----------------------------------------------------------"<<endl;

	/*
	cout<<"community sizes"<<endl;
	for (int i=0; i<num_seq.size(); i++)
		cout<<num_seq[i]<<" ";
	cout<<endl<<endl;
	//*/
	

	/*
	deque <int> first;
	for (int i=0; i<ncom; i++)
		member_matrix.push_back(first);
	
	
	
	// it puts the overlapping_nodes inside
	cout<<ncom<<endl;
	for (int i=degree_seq.size() - overlapping_nodes; i<degree_seq.size(); i++) {
		
		cout<<i<<endl;
		set<int> members;
		int hh=0;
			
		while(members.size()<max_mem_num) {
				
			int random_module=irand(ncom-1);
				
			if(member_matrix[random_module].size()!=num_seq[random_module])
				members.insert(random_module);
				
			hh++;
				
			if(hh>3*num_nodes) {
				cerr<<"it seems that the overlapping nodes need more communities that those I provided. Please increase the number of communities or decrease the number of overlapping nodes"<<endl;
				return -1;				
			}
	
		}
			
				
		for (set<int>::iterator its=members.begin(); its!=members.end(); its++)
			member_matrix[*its].push_back(i);
				
	}
	
	
	
	// it decides the memberships for the not overlapping nodes		
	
	int moment_module=0;
	for (int i=0; i<num_nodes - overlapping_nodes; i++) {
	
		while(member_matrix[moment_module].size()==num_seq[moment_module])
			 moment_module++;

		member_matrix[moment_module].push_back(i);
		
	}
		
		
	
	*/
	
	// I have to assign the degree to the nodes
	
	
	deque<int> member_numbers;
	for(int i=0; i<overlapping_nodes; i++)
		member_numbers.push_back(max_mem_num);
	for(int i=overlapping_nodes; i<degree_seq.size(); i++)
		member_numbers.push_back(1);
	
	//prints(member_numbers);
	//prints(num_seq);
	
	if(build_bipartite_network(member_matrix, member_numbers, num_seq)==-1) {
		
		cerr<<"it seems that the overlapping nodes need more communities that those I provided. Please increase the number of communities or decrease the number of overlapping nodes"<<endl;
		return -1;			
	
	}
		
	//printm(member_matrix);
	
	//cout<<"degree_seq"<<endl;
	//prints(degree_seq);
	
	//cout<<"internal_degree_seq"<<endl;
	//prints(internal_degree_seq);

	deque<int> available;
	for (int i=0; i<num_nodes; i++)
		available.push_back(0);
	
	for (int i=0; i<member_matrix.size(); i++) {
		for (int j=0; j<member_matrix[i].size(); j++)
			available[member_matrix[i][j]]+=member_matrix[i].size()-1;
	}
	
	//cout<<"available"<<endl;
	//prints(available);
	
	
	deque<int> available_nodes;
	for (int i=0; i<num_nodes; i++)
		available_nodes.push_back(i);
	
	
	deque<int> map_nodes;				// in the position i there is the new name of the node i
	for (int i=0; i<num_nodes; i++)
		map_nodes.push_back(0);

	
	for (int i=degree_seq.size()-1; i>=0; i--) {
		
		int & degree_here=internal_degree_seq[i];
		int try_this = irand(available_nodes.size()-1);
		
		int kr=0;
		while (internal_degree_seq[i] > available[available_nodes[try_this]]) {
		
			kr++;
			try_this = irand(available_nodes.size()-1);
			if(kr==3*num_nodes) {
			
				if(change_community_size(num_seq)==-1) {
					
					cerr<<"\n***********************\nERROR: this program needs more than one community to work fine"<<endl;
					return -1;
				
				}
				
				cout<<"it took too long to decide the memberships; I will try to change the community sizes"<<endl;

				cout<<"new community sizes"<<endl;
				for (int i=0; i<num_seq.size(); i++)
					cout<<num_seq[i]<<" ";
				cout<<endl<<endl;
				
				return (internal_degree_and_membership(mixing_parameter, overlapping_nodes, max_mem_num, num_nodes, member_matrix, excess, defect, degree_seq, num_seq, internal_degree_seq, fixed_range, nmin, nmax, tau2));
			
			
			}
			
			
		}
		
		
		
		map_nodes[available_nodes[try_this]]=i;
		
		available_nodes[try_this]=available_nodes[available_nodes.size()-1];
		available_nodes.pop_back();
		
	
	
	}
	
	
	for (int i=0; i<member_matrix.size(); i++) {
		for (int j=0; j<member_matrix[i].size(); j++)
			member_matrix[i][j]=map_nodes[member_matrix[i][j]];	
	}
	
	
	
	for (int i=0; i<member_matrix.size(); i++)
		sort(member_matrix[i].begin(), member_matrix[i].end());

		
	return 0;

}
コード例 #24
0
ファイル: optimization.cpp プロジェクト: objeck/objeck-lang
void ItermediateOptimizer::ApplyReduction(IntermediateInstruction* test, IntermediateInstruction* instr, 
                                          IntermediateInstruction* top_instr, deque<IntermediateInstruction*> &working_stack, 
                                          IntermediateBlock* outputs)
{
  int shift = 0;
  switch(test->GetOperand()) {
  case 2:
    shift = 1;
    break;

  case 4:
    shift = 2;
    break;

  case 8:
    shift = 3;
    break;

  case 16:
    shift = 4;
    break;

  case 32:
    shift = 5;
    break;

  case 64:
    shift = 6;
    break;

  case 128:
    shift = 7;
    break;

  case 256:
    shift = 8;
    break;

  default:
    AddBackReduction(instr, top_instr, working_stack, outputs);
    break;
  }

  deque<IntermediateInstruction*> rewrite_instrs;
  if(shift) {
    rewrite_instrs.push_back(IntermediateFactory::Instance()->MakeInstruction(cur_line_num, LOAD_INT_LIT, shift));
    // exclude literal
    if(working_stack.front()->GetType() != LOAD_INT_LIT) {
      rewrite_instrs.push_back(working_stack.front());
    }
    if(top_instr->GetType() != LOAD_INT_LIT) {
      rewrite_instrs.push_back(top_instr);
    }
    working_stack.pop_front();
    // shift left or right
    if(instr->GetType() == MUL_INT) {
      rewrite_instrs.push_back(IntermediateFactory::Instance()->MakeInstruction(cur_line_num, SHL_INT, shift));
    } 
    else {
      rewrite_instrs.push_back(IntermediateFactory::Instance()->MakeInstruction(cur_line_num, SHR_INT, shift));
    }
  }
  
  // add original instructions
  while(!working_stack.empty()) {
    outputs->AddInstruction(working_stack.back());
    working_stack.pop_back();
  }
  
  // add rewritten instructions
  for(size_t i = 0; i < rewrite_instrs.size(); ++i) {
    outputs->AddInstruction(rewrite_instrs[i]);
  }
}
コード例 #25
0
ファイル: waypoints_loop4.cpp プロジェクト: picopter/picopter
/*
 *	flightLoop
 *		1) Initialise copter systems
 *		2) Wait for user allowance to fly.
 *		3) Read in list of waypoints
 *		4) Fly to first waypoint, wait, fly to next, etc..
 *		5) If the end is reached, stop.
 *		
 *		The user may stop the flight at any time. It will continue if the user resumes. At any
 *		point, the user may stop the current flight path and change the waypoint configuration. Upon
 *		resuming flight, the copter will read in the new list of waypoints and start at the
 *		beginning.
 */
void waypoints_loop4(hardware &hardware_list, Logger &log, deque<coord> &waypoints_list, string config_filename) {	
	cout << "\033[1;32m[WAYPTS]\033[0m Waypoints thread initiated, travelling to the following waypoints:" << endl;
	char str_buf[BUFSIZ];
	log.clearLog();
	
	time_t start, now, last_displayed;
	time(&start);
    time(&now);
    time(&last_displayed);
	
	//Grab references to hardware
	FlightBoard *fb	= hardware_list.fb;
	GPS *gps		= hardware_list.gps;
	IMU *imu		= hardware_list.imu;
	
	bool useimu = hardware_list.IMU_Working;
	double yaw = 0;
	
	//Configure configurable variables (if file is given)
	if(!config_filename.empty()) {
		loadParameters(config_filename);
	}
	
	//Construct PID controller
	PID controller_perp   = PID(-Kp_PERP, -Ki_PERP, -Kd_PERP, MAIN_LOOP_DELAY, 3, 0.95);
	PID controller_inline = PID(-Kp_INLINE, -Ki_INLINE, -Kd_INLINE, MAIN_LOOP_DELAY, 3, 0.95);
	
	//Construct buzzer
	Buzzer buzzer;
	buzzer.playBuzzer(BUZZER_DURATION, BUZZER_FREQUENCY, BUZZER_VOLUME);
	usleep((int)(BUZZER_DURATION*1.1)*1000*1000);
	
	//Print list of waypoints
	for(size_t i = 0; i != waypoints_list.size(); i++) {
		cout << "         " << i+1 << ": (" << setprecision(6) << waypoints_list[i].lat << ", " << setprecision(6) << waypoints_list[i].lon << ")" << endl;
	}
	
	//Wait here for auto mode and conduct bearing test if necessary
	state = 6;
    cout << "\033[1;33m[WAYPTS]\033[0m Waiting for auto mode." << endl;
	while ( !gpio::isAutoMode() && !exitProgram) usleep(500*1000);
    cout << "\033[1;31m[WAYPTS]\033[0m Auto mode engaged." << endl;
	
	if (!useimu && !exitProgram) {
		buzzer.playBuzzer(0.25, 10, 100);
        cout << "\033[1;31m[WAYPTS]\033[0m Conducting bearing test..." << endl;
		state = 5;
		yaw = inferBearing(fb, gps);
        cout << "\033[1;31m[WAYPTS]\033[0m Bearing test complete." << endl;
	}
	state = 1;
	
	//Initialise loop variables
	coord		currentCoord = {-1, -1};
	double		distanceToNextWaypoint;
	double		bearingToNextWaypoint;
	FB_Data		course = {0, 0, 0, 0};
	int			pastState = -1;
	velocity 	flightVector = {-1, -1};
	
	//Plot initial path
	currentCoord = getCoord(gps);
	line path;
	if (!waypoints_list.empty()) {
		path = get_path(currentCoord, waypoints_list[wp_it]);
	}

    
    cout << "\033[1;32m[WAYPTS]\033[0m Starting main loop." << endl;
    
	try {	// Check for any errors, and stop the copter.
		while(!exitProgram) {
			currentCoord = getCoord(gps);
			
			
			//Write data for Michael
			time(&now);
			if (!waypoints_list.empty()) {
				sprintf(str_buf, "%.f,%3.6f,%3.6f,%3.6f,%3.6f", difftime(now, start), currentCoord.lat, currentCoord.lon, waypoints_list[wp_it].lat, waypoints_list[wp_it].lon);
			} else {
				sprintf(str_buf, "%.f,%3.6f,%3.6f,,", difftime(now, start), currentCoord.lat, currentCoord.lon);
			}
			log.writeLogLine(str_buf, false);
			
			
			if(!waypoints_list.empty()) {
				distanceToNextWaypoint = calculate_distance(currentCoord, waypoints_list[wp_it]);
				bearingToNextWaypoint = calculate_bearing(currentCoord, waypoints_list[wp_it]);
			}
			
			if (useimu) yaw = getYaw(imu);
			

			
			
			
			
			/* State 4: Manual mode. */
			if (!gpio::isAutoMode()) {
				state = 4;
				wp_it = 0;
				exitProgram = true;
			/* State 0: All stop */
			} else if (waypoints_list.empty() || wp_it == waypoints_list.size() || userState == 0 ) {
				state = 11;
				userState = 0;
				wp_it = 0;
				exitProgram = true;
			/* State 3: Error. */
			} else if (state == 3 || !checkInPerth(&currentCoord)) {
				state = 3;
				exitProgram = true;
			/* State 2: At waypoint. */
			} else if (distanceToNextWaypoint < WAYPOINT_RADIUS) {
				state = 2;
			/* State 1: Travelling to waypoint. */
			} else {
				state = 1;
			}
			
			/* Only give output if the state changes. Less spamey.. */
			if (pastState != state || (state == 1 && difftime(now, last_displayed) >0.9)) {
				switch (state) {
					case 0:
						cout << "\033[1;32m[WAYPTS]\033[0m All stop." << endl;
						break;
					case 1:
						cout << "\033[1;32m[WAYPTS]\033[0m Travelling to waypoint " << wp_it << ", at (" << waypoints_list[wp_it].lat << "," << waypoints_list[wp_it].lon << ")" << endl;
						break;
					case 2:
						cout << "\033[1;32m[WAYPTS]\033[0m At waypoint" << wp_it << "." << endl;
						break;
					case 3:
						cout << "\033[31m[WAYPTS]\033[0m Error reading GPS." << endl;
					case 4:
						cout << "\033[31m[WAYPTS]\033[0m Manual mode engaged." << endl;
					break;
				}
				cout << "\033[1;33m[WAYPTS]\033[0m In state "		<< state << "."	<< endl;
				cout << "\033[1;33m[WAYPTS]\033[0m Facing " << setprecision(6) << yaw << ", at coordinates (" << currentCoord.lat << ", " <<	currentCoord.lon << ")" << endl;

				cout << "\033[1;33m[WAYPTS]\033[0m The next waypoint is at (" << setprecision(6) << waypoints_list[wp_it].lat << ", " << waypoints_list[wp_it].lon << ")"	<< endl;
				
				cout << "\033[1;33m[WAYPTS]\033[0m It is " << setprecision(7) << distanceToNextWaypoint	<< "m away, at a bearing of " << bearingToNextWaypoint << "." << endl;
				
				pastState = state;
				last_displayed = now;

			}

			switch(state) {
				case 0:													//Case 0:	Not in auto mode, standby
					fb->setFB_Data(&stop);									//Stop moving
					
					/*
					log.writeLogLine("\033[1;32m[WAYPTS]\033[0m Manual mode");
					sprintf(str_buf, "[WAYPTS] Currently at %f %f.", currentCoord.lat, currentCoord.lon);
					log.writeLogLine(str_buf);
					*/
					
					break;
				
				case 1:
				
					flightVector = get_velocity(&controller_perp, &controller_inline, currentCoord, path, SPEED_LIMIT_);
					setCourse(&course, flightVector, yaw);
					fb->setFB_Data(&course);																//Give command to flight boars
					
					/*
					sprintf(str_buf, "[WAYPTS] Aileron is %d, Elevator is %d", course.aileron, course.elevator);
					log.writeLogLine(str_buf);
					sprintf(str_buf, "[WAYPTS] Moving to next waypoint. It has latitude %f and longitude %f.", waypoints_list[wp_it].lat, waypoints_list[wp_it].lon);
					log.writeLogLine(str_buf);
					sprintf(str_buf, "[WAYPTS] Currently at %f %f, moving %f m at a bearing of %f degrees.", currentCoord.lat, currentCoord.lon, distanceToNextWaypoint, bearingToNextWaypoint);
					log.writeLogLine(str_buf);
					*/

					break;
				
				case 2:
					fb->setFB_Data(&stop);
					buzzer.playBuzzer(BUZZER_DURATION, BUZZER_FREQUENCY, BUZZER_VOLUME);
					
					/*
					log.writeLogLine("\033[1;32m[WAYPTS]\033[0m Reached waypoint, stopping");
					*/
					
					
					wp_it++;
					if(repeatLoop && wp_it == waypoints_list.size()) {
						wp_it = 0;
					}
					
					if (wp_it != waypoints_list.size()) {
						path = get_path(currentCoord, waypoints_list[wp_it]);
					}
					
					usleep(WAIT_AT_WAYPOINTS*1000);
					
					controller_perp.clear();
					controller_inline.clear();
					cout << "\033[1;32m[WAYPTS]\033[0m Moving to next waypoint." << endl;
					break;
				
				case 3:
				default:
					fb->setFB_Data(&stop);
					/*
					log.writeLogLine("\033[31m[WAYPTS]\033[0m Error reading GPS, stopping");
					*/
				break;
			}
			usleep(MAIN_LOOP_DELAY*1000);

		}
	} catch (...) {
		cout << "\033[31m[WAYPTS]\033[0m Error encountered. Stopping copter." << endl;
		fb->setFB_Data(&stop);
		state = 3;
	}
	cout << "\033[1;32m[WAYPTS]\033[0m Waypoints flight loop terminating." << endl;
	
	buzzer.playBuzzer(1.0, 20, 60);
	usleep(2100*1000);
}
コード例 #26
0
ファイル: crmenu.cpp プロジェクト: richardicooper/Crystals
CcParse CrMenu::ParseInput( deque<string> &  tokenList )
{
    CcParse retVal(true, mXCanResize, mYCanResize);
    bool hasTokenForMe = true;

    // Initialization for the first time
    if( ! mSelfInitialised )
    {
        LOGSTAT("*** Menu *** Initing...");
        mName = string(tokenList.front());
        tokenList.pop_front();
        mText = string(tokenList.front());
        tokenList.pop_front();

        mSelfInitialised = true;
        LOGSTAT( "*** Created Menu      " + mName );
    }
    // End of Init, now comes the general parser

    while ( hasTokenForMe && ! tokenList.empty() )
    {
        switch ( CcController::GetDescriptor( tokenList.front(), kAttributeClass ) )
        {
            case kTMenu:
            {
                CrMenu* mMenuPtr = new CrMenu( this );
                if ( mMenuPtr != nil )
                {
                    tokenList.pop_front();
                    // ParseInput generates all objects in the menu
                    // Of course the token list must be full
                    retVal = mMenuPtr->ParseInput( tokenList );
                    if ( ! retVal.OK() )
                    {
                        delete mMenuPtr;
                        mMenuPtr = nil;
                    }
                }
                CcMenuItem * menuItem = new CcMenuItem(this);
                menuItem->type = CR_SUBMENU;
                menuItem->text = menuItem->originaltext = mMenuPtr->mText;
                menuItem->name = mMenuPtr->mName;
                menuItem->command = "";
                menuItem->ptr = mMenuPtr;
                bool moreTokens = true;
                while ( moreTokens && !tokenList.empty() )
                {
                    switch ( CcController::GetDescriptor( tokenList.front(), kAttributeClass ) )
                    {
                        case kTMenuDisableCondition:
                        {
                            tokenList.pop_front();
                            menuItem->disable = Condition( tokenList.front() );
                            tokenList.pop_front();
                            break;
                        }
                        case kTMenuEnableCondition:
                        {
                            tokenList.pop_front();
                            menuItem->enable = Condition( tokenList.front() );
                            tokenList.pop_front();
                            break;
                        }
                        default:
                        {
                            moreTokens = false;
                            break;
                        }
                    }
                }

                menuItem->id = ((CxMenu*)ptr_to_cxObject)->AddMenu((CxMenu*)menuItem->ptr->GetWidget(),(char*)menuItem->text.c_str());
                mMenuList.push_back(menuItem);
                AddMenuItem(menuItem);
                break;
            }
            case kTItem:
            {
                tokenList.pop_front();
                CcMenuItem* menuItem = new CcMenuItem(this);
                menuItem->type = CR_MENUITEM;
                menuItem->name = string(tokenList.front());
                tokenList.pop_front();
                menuItem->text    = menuItem->originaltext    = string(tokenList.front());
                tokenList.pop_front();
                menuItem->command = menuItem->originalcommand = string(tokenList.front());
                tokenList.pop_front();
                menuItem->ptr = nil;
                bool moreTokens = true;
                while ( moreTokens && !tokenList.empty() )
                {
                    switch ( CcController::GetDescriptor( tokenList.front(), kAttributeClass ) )
                    {
                        case kTMenuDisableCondition:
                        {
                            tokenList.pop_front();
                            menuItem->disable = Condition( tokenList.front() );
                            tokenList.pop_front();
                            break;
                        }
                        case kTMenuEnableCondition:
                        {
                            tokenList.pop_front();
                            menuItem->enable = Condition( tokenList.front() );
                            tokenList.pop_front();
                            break;
                        }
                        default:
                        {
                            moreTokens = false;
                            break;
                        }
                    }
                }
                menuItem->id = ((CxMenu*)ptr_to_cxObject)->AddItem((char*)menuItem->text.c_str());
                mMenuList.push_back(menuItem);
                AddMenuItem(menuItem);

                ostringstream strstrm;
                strstrm << "Menu item id: " << menuItem->id;
                LOGSTAT( strstrm.str() );

                break;
            }
            case kTMenuSplit:
            {
                tokenList.pop_front();
                CcMenuItem* menuItem = new CcMenuItem(this);
                menuItem->type = CR_SPLIT;
                menuItem->name = "";
                menuItem->text = "";
                menuItem->command = "";
                menuItem->ptr = nil;
                menuItem->disable = 0;
                mMenuList.push_back(menuItem);
                menuItem->id = ((CxMenu*)ptr_to_cxObject)->AddItem();
                AddMenuItem(menuItem);
                break;
            }
            case kTEndMenu:
            {
                tokenList.pop_front();
                hasTokenForMe = false;
                break; // We leave the token in the list and exit the loop
            }
            default:
            {
                hasTokenForMe = false;
                break; // We leave the token in the list and exit the loop
            }
        }
    }


    return retVal;
}
コード例 #27
0
ファイル: KMIN.cpp プロジェクト: thucdx/algorithm-solution
void push(int x) {
	while (!dq.empty() && a[dq.back()] >= a[x])
		dq.pop_back();
	dq.push_back(x);
}
コード例 #28
0
ファイル: OscListener.cpp プロジェクト: SethGibson/DroneTest
bool OscListener::hasWaitingMessages() const
{
	std::lock_guard<mutex> lock( mMutex );
	return ! mMessages.empty();
}
コード例 #29
0
ファイル: scheduling_RR.cpp プロジェクト: csl/OS-
void schedule()
{
  int cpu_run = 0, IO_run = 0, timer = 0;
  process current = Q.front();

  if(current.state == "unstarted" && current.A <= timer )
    {
      current.state = "ready";
    }
  while(!Q.empty() && timer < 1800)
    {
      int counter = 0;
      
      //Edge cases
      for(int i = 0; i < Q.size(); i++) //All processes unstarted or blocked.
	if(Q[i].state == "unstarted" || Q[i].state == "blocked")
	  counter++;
      if(counter == Q.size())
	{
	  bool flag = true;
	  while(flag)
	    {
	      timer++;
	      for(int i = 0; i < Q.size(); i++)
		{
		  if(Q[i].state == "unstarted")
		    {
		      if(Q[i].A == timer)
			{
			  Q[i].state="ready";
			  current = Q[i];
			  Q.erase(Q.begin() + i);
			  Q.push_front(current);
			  flag = false;
			}
		    }
		  else if(Q[i].state == "blocked")
		    {
		      Q[i].block_time--;
		      Q[i].in_IO_time++;
		      if(Q[i].block_time == 0)
			{
			  Q[i].state ="ready";
			  current = Q[i];
			  Q.erase(Q.begin() + i);
			  Q.push_front(current);
			  flag = false;
			}
		    }
		}
	    }
	}
      //End Edge Cases
      if(current.state == "unstarted" && current.A > timer) // If process is unstarted place it at the back of the queue.
	{
	  process temp = current;
	  Q.pop_front();
	  Q.push_back(temp);
	  current = Q.front(); // Initialize the current process. 
	}

      if(current.state == "ready")
	{
	  current.state = "running";
	}
      
      cpu_run = 1 + (U[current_random] % current.B);
      current_random++;
      cout<<current.id<<" "<<current.state<<" "<<timer<<endl;
      //Update CPU_time
      
	
      for(int i = 0; i < RR_Q; i++)
	{
	  timer++;
	  //I/O Utilization of other Processes. 
	  for(int j = 0; j < Q.size(); j++)
	    {
	      if(current.id != Q[j].id)
		{
		  if(Q[j].state == "blocked")
		    {
		      Q[j].in_IO_time++;
		      Q[j].block_time--;
		      if(Q[j].block_time == 0)
			Q[j].state = "ready";
		    }
		  else if(Q[j].state == "ready")
		    {
		      Q[j].wait_time++;
		    }
		  else if(Q[j].state == "unstarted" && Q[j].A <= timer)
		    {
		      // cout<<Q[j].id<<" "<<timer<<endl;
		      Q[j].state = "ready";
		    }
		} //current != Q[j].
	    }//end for j.
	  
	  if(current.state == "running")
	    {
	      current.C = current.C - 1; //Decrement the CPU requirement.
	      cpu_run--;
	      CPU_time++;
	      
	      if(cpu_run == 0)
		{
		  current.state = "blocked"; //Run ends before the quantum.
		  break;
		}
	    }
	  else if(current.state == "blocked")
	    {
	      current.in_IO_time++;
	      current.block_time--;
	      if(current.block_time == 0)
		current.state = "ready";
	      //Process is Blocked. 
	      break;
	    }
	}//end for i
      
      if(current.C == 0) //Process has finished executing.
	{
	  current.state = "terminated";
	  current.finish_time = timer; 
	  for(int k = 0; k < P.size(); k++) //When Process finished copy the state.
	    if(current.id == P[k].id)
	      P[k] = current;
	  Q.pop_front(); //Process not pushed back. Done!.
	  if(Q.size() > 0)
	  current = Q.front();
	}
      else //Process does its I/O. 
 	{
	  if(current.state == "running") //Process used up its quantum
	    current.state = "blocked"; //Else the process has already been blocked
	  IO_run = 1 + (U[current_random] % current.IO);
	  current_random++;
	  current.block_time = IO_run;
	  IO_time += IO_run;
	  
	  //Now put the process at the end of the queue. 
	  process temp = current;
	  Q.pop_front();
	  Q.push_back(temp);
	  current = Q.front(); // Initialize the current process. 
	  //
	  
	}
    }
    for(int i = 0; i < CP.size(); i++)
    {
      
      cout<<"Process "<<CP[i].id<<" : "<<P[i].state<<endl;
      cout<<"(A,B,C,IO) : ( "<<CP[i].A<<", "<<CP[i].B<<", "<<CP[i].C<<", "<<CP[i].IO<<" )"<<endl;
      cout<<"Finishing Time: "<< P[i].finish_time<<endl;
      cout<<"Turnaround Time: "<<P[i].finish_time - P[i].A<<endl;
      cout<<"I/O Time: "<<P[i].in_IO_time<<endl;
      cout<<"Waiting Time: "<<P[i].wait_time<<endl;
    }
  cout<<"Summary Data:"<<endl;
  cout<<"Finishing Time: "<<timer<<endl;
  cout<<"CPU Utilization: "<<(float)CPU_time/(timer)<<endl;
  cout<<"I/O Utilization: "<<(float)IO_time/timer<<endl;
  //Fill in these later
  cout<<"Throughput: "<<"" <<" processes per hundred cycles"<<endl; 
  cout<<"Average Turnaround time: "<<endl;
  cout<<"Average Waiting Time: "<<endl;
}
コード例 #30
0
ファイル: 5410738_WA.cpp プロジェクト: seaify/poj-codes
int main()
{
	//freopen("in.txt","r",stdin);
//	freopen("out1.txt","w+",stdout);
//	int T=0;
	while(EOF!=scanf("%d %d",&N,&F))
	{
		q.clear();
		sum[0]=0;opt=0;
		for(i=1;i<=N;++i)
		{
			scanf("%d",&a[i]);
			a[i]=a[i]*1000;
			if(a[i]>opt)
				opt=a[i];
			sum[i]=sum[i-1]+a[i];
		}
		if(F==N)
		{
			printf("%d\n",sum[N]/N);
			continue;
		}
		if(F==1) //////故N>=2
		{
			printf("%d\n",opt);
			continue;
		}
		cnt.x=0,cnt.y=0;
		q.push_front(cnt);
		opt=sum[F]/F;
		cnt.x=1,cnt.y=sum[1];
		q.push_front(cnt);
		if(sum[F+1]/(F+1)>opt)
			opt=sum[F+1]/(F+1);
	    if((sum[F+1]-sum[1])/F>opt)
			opt=(sum[F+1]-sum[1])/F; /////为判断出单调性,必须先压入2个点。。。
		for(i=F+2;i<=N;++i)
		{
		    cnt.x=i-F,cnt.y=sum[i-F];  ///可能压入的点
			while(test());
			q.push_front(cnt);
			cnt.x=i,cnt.y=sum[i];//寻找最优值。。。。
		    last=0;
			if(q.size()==1)
			{
				last=(cnt.y-q.back().y)/(cnt.x-q.back().x);
				continue;
			}
			t=q.back();    ////此时必存在2个元素
			q.pop_back();
			s=q.back();
			while((cnt.y-t.y)/(cnt.x-t.x)<(cnt.y-s.y)/(cnt.x-s.x))  ////保证至少2个元素...,last不断的扩大。。直到碰到一个比它小或等于的
			{
			   t=q.back();
			   q.pop_back();
			   if(q.empty())
				   break;
			   s=q.back();
			}
			q.push_back(t);
			last=(cnt.y-t.y)/(cnt.x-t.x);
			if(last>opt)
				opt=last;
		}
		printf("%d\n",opt);
	}
	return 0;
}