コード例 #1
0
void BackgroundUtil::SortBackgroundChangesArray( vector<BackgroundChange> &vBackgroundChanges )
{
	sort( vBackgroundChanges.begin(), vBackgroundChanges.end(), CompareBackgroundChanges );
}
コード例 #2
0
ファイル: scene.cpp プロジェクト: ksaishashank/ProjectSoft
void DecoSceneNode::RenderAllSceneObjects(DecoRenderInterface* RI, DecoCamera* camera, SceneObjectType objType, DecoDrawType drawType)

{

	vector<DecoRenderData*> tempSortList;

	vector<DecoRenderData*> translucentDrawList;

	vector<DOUBLE> distanceList;

	ConvexVolume viewFrustum = camera->getViewFrustum();

	INT toRender = 0, beRendered = 0;

	DecoRenderData* floor = NULL, *ceiling = NULL;

	DecoLight* Lights[MAX_LIGHT];

	INT numEffectiveLights = 0;
	

	for (vector<DecoSceneObject*>::iterator objIter = sceneObjs.begin(); objIter != sceneObjs.end(); objIter++)

	{

		DecoSceneObject* obj = *objIter;

		if (obj->IsRenderable() && (objType == AllT || obj->GetType() == objType))

		{

			DecoRenderData* objDecoRenderData = obj->GetRenderData();

			assert(objDecoRenderData);

			//if (viewFrustum.BoxCheck(objDecoRenderData->GetBoundingBox()) != CF_Outside)

			{
				if (objDecoRenderData->NeedSort())

				{
					DOUBLE distSqr = (camera->getEye() - objDecoRenderData->GetBoundingBox().GetCenter()).lengthSqr();

					distanceList.push_back(distSqr);

					sort(distanceList.begin(), distanceList.end());

					vector<DOUBLE>::iterator it = find(distanceList.begin(), distanceList.end(), distSqr);

					translucentDrawList.insert(translucentDrawList.begin() + (it - distanceList.begin()), objDecoRenderData);

				}

				else

				{

					GetRelevantLights(objDecoRenderData, numEffectiveLights, Lights);

					objDecoRenderData->Render(RI, Lights, numEffectiveLights, drawType);

					DecoStat::GetSingleton()->CumulateObjectRendered(1);

				}



#ifdef DEBUG_BOUNDINGBOX

				RI->SetColor(0xff0000ff);

				objDecoRenderData->RenderBoundingBox(RI);

#endif
			}

			DecoStat::GetSingleton()->CumulateObjectTotal(1);

		}

	}


	for (vector<DecoRenderData*>::iterator translucentRenderDataIter = translucentDrawList.begin(); translucentRenderDataIter != translucentDrawList.end(); translucentRenderDataIter++)

	{

		GetRelevantLights((*translucentRenderDataIter), numEffectiveLights, Lights);

		(*translucentRenderDataIter)->RenderOpaqueSection(RI, Lights, numEffectiveLights, drawType);

		DecoStat::GetSingleton()->CumulateObjectRendered(1);

	}

	for (vector<DecoRenderData*>::iterator translucentRenderDataIter = translucentDrawList.begin(); translucentRenderDataIter != translucentDrawList.end(); translucentRenderDataIter++)

	{

		GetRelevantLights((*translucentRenderDataIter), numEffectiveLights, Lights);

		(*translucentRenderDataIter)->RenderTransparentSection(RI, Lights, numEffectiveLights, drawType);

	}

}
コード例 #3
0
void DhQAbstractTableModel::Dvhsort(int x1) {
  return sort(x1);
}
コード例 #4
0
void SDFFelementManager::generate(){
  channelManager* cmanager=parser->get_cmanager();

  sort(); // sort the elements according to time

  // calculate the duration of the sequence
  if (end_time<0) {
    use_end_time=extract_end_time();
  } else {
    use_end_time=end_time;
  }

  // initialize the sequence Generator and add all used channels
  std::map<std::string, std::vector<SDFFsequenceElement*> >::const_iterator i;
  for (i=elements.begin(); i!=elements.end(); ++i) {
    generator->add_used(i->first);
    //std::cout<<i->first<<" added\n";
  }
  generator->init(cmanager, sample_timestep, use_end_time);
  //std::cout<<generator->report()<<std::endl;
  //std::cout<<"going through items ..."<<std::endl;
  // go through all elements and call their generate() function
  for (i=elements.begin(); i!=elements.end(); ++i) {
    double vstart=0; // contains the value of the channel at t=0
    double t0=0; // end time of last instruction
    double v0=vstart; // last value of last instruction ... initial value befor first instruction
    cm_channel ch=cmanager->get(i->first); // description of the current channel
    //std::cout<<std::endl<<i->first<<":  \n";
    if (i->second.size()>0) {
      if (i->second[0]->extract_real_t_start()==0) v0=i->second[0]->get_startvalue(); // if the first element starts at t=0
                                                                                    // we have to get the start value from there
      for (size_t j=0; j<i->second.size(); j++) {
        //std::cout<<j;
        double t1=i->second[j]->extract_real_t_start(); // start time of current instruction

        // if there is a gap between the last and the current instruction, we have to fill it:
        if (t1>t0) {
          if (ch.type==cmAnalogOutput) { // analog channel
            //std::cout<<" gap_set_analog t0="<<t0<<"  t1="<<t1<<"  v0="<<v0<<"\n";
            generator->set_analog(i->first, t0, t1, cmanager->scale_value(i->first, v0));
          } else { // digital channel
            //std::cout<<" gap_set_digital t0="<<t0<<"  t1="<<t1<<"  v0="<<v0<<"\n";
            generator->set_digital(i->first, t0, t1, cmanager->invert_value(i->first, v0>0.2));
          }
        }
        // generate the current instruction
        i->second[j]->generate();

        // store end time and end value of current instruction
        t0=i->second[j]->extract_real_t_end();
        v0=i->second[j]->get_endvalue();
      }

      // now we have to check whether there is a gap between the instruction and use_end_time
      if (t0<use_end_time) {
        if (ch.type==cmAnalogOutput) { // analog channel
          //std::cout<<" endgap_set_analog t0="<<t0<<"  t1="<<use_end_time<<"  v0="<<v0<<"\n";
          generator->set_analog(i->first, t0, use_end_time, cmanager->scale_value(i->first, v0));
        } else { // digital channel
          //std::cout<<" endgap_set_digital_end t0="<<t0<<"  t1="<<use_end_time<<"  v0="<<v0<<"\n";
          generator->set_digital(i->first, t0, use_end_time, cmanager->invert_value(i->first, v0>0.2));
        }
      }
    } else {
      // here we set the channel to the standard initial value 0, stored in vstart!
      if (ch.type==cmAnalogOutput) { // analog channel
        generator->set_analog(i->first, 0, use_end_time, cmanager->scale_value(i->first, vstart));
      } else { // digital channel
        generator->set_digital(i->first, 0, use_end_time, cmanager->invert_value(i->first, vstart>0.2));
      }
    }
  }

};
コード例 #5
0
ファイル: anagram.cpp プロジェクト: DerellLicht/winagrams
//********************************************************************
void find_anagrams(HWND hwnd)
{
   char msgstr[81] ;
   //  read data out of hwnd:IDC_PHRASE
   char input_bfr[MAX_PKT_CHARS+1] ;
   uint input_bfr_len = GetWindowTextA (GetDlgItem(hwnd,IDC_PHRASE) , input_bfr, MAX_PKT_CHARS);
   if (input_bfr_len > MAX_PKT_CHARS) 
       input_bfr_len = MAX_PKT_CHARS ;
   input_bfr[MAX_PKT_CHARS] = 0 ;
   if (vflag)  //lint !e506 !e774
      syslog("find_anagrams: [%u] [%s]\n", input_bfr_len, input_bfr) ;

   //  scan for separator char
   excl_idx = 0 ; //  reset exclusions list
   char *hd ;
   char *tl = strchr(input_bfr, '!');
   if (tl != NULL) {
      *tl++ = 0 ; //  NULL-term word list, point to exclusions list
      while (LOOP_FOREVER) {
         tl = strip_leading_spaces(tl);
         if (*tl != 0) {
            hd = tl ;
            tl = strchr(hd, ' ');
            if (tl != NULL) {
               *tl++ = 0 ;
               //  hd points to one exclusion arg
            }
            add_to_excl_list(hd);
            if (tl == NULL) {
               break;
            }
         }
      }
   }

   status_message("Begin new anagram search") ;

   // clear_message_area(&this_term);
   clear_message_area();
   if (excl_idx == 0) {
      status_message("excl: <none>", 1);
   }
   else
   {
      uint slen = sprintf(msgstr, "excl: ");
      for (uint idx=0; idx<excl_idx; idx++) {
         slen += (uint) sprintf(msgstr+slen, "%s ", excl_list[idx]);
      }
      status_message(msgstr, 1);
   }
   delete_wordlist() ;

   ZeroMemory((char *) &freq[0], sizeof(freq)) ;
   nletters = 0 ;
   for (char *p = input_bfr; *p != 0; p++) {
      if (*p != ' ') {
         freq[(uint) (u8) *p]++ ;
         nletters++;
      }
   }
   if (maxgen == 0)
       maxgen = nletters;
   
   wordlist = buildwordlist ();
   if (wordlist == NULL) {
      syslog("Empty dictionary or no suitable words.\n");
      return ;
   }

   wordlist = sort (wordlist);
   initfind (wordlist);

   solutions_found = 0 ;
   findanags (0, forgelinks (wordlist), nletters);
   if (solutions_found == 0) {
      status_message("no anagrams found for input string !") ;
   } else {
      // reverse_list_entries() ;
      // InsertListViewItems(solutions_found);  //  This triggers drawing of listview
      myTerminal->reverse_list_entries() ;
      update_listview();

      wsprintf(msgstr, "%u anagrams found", solutions_found) ;
      status_message(msgstr) ;
   }
}
コード例 #6
0
void DhQAbstractProxyModel::Dvhsort(int x1) {
  return sort(x1);
}
コード例 #7
0
ファイル: mergeBed.cpp プロジェクト: cjfields/bedtools
void BedMerge::ReportMergedScores(const vector<string> &scores) {
    if (scores.size() > 0) {
        printf("\t");

        // convert the scores to floats
        vector<float> data;
        for (size_t i = 0 ; i < scores.size() ; i++) {
            data.push_back(atof(scores[i].c_str()));
        }    

        if (_scoreOp == "sum") {
            printf("%.3f", accumulate(data.begin(), data.end(), 0.0));
        }
        else if (_scoreOp == "min") {
            printf("%.3f", *min_element( data.begin(), data.end() ));
        }
        else if (_scoreOp == "max") {
            printf("%.3f", *max_element( data.begin(), data.end() ));
        }
        else if (_scoreOp == "mean") {
            double total = accumulate(data.begin(), data.end(), 0.0);
            double mean = total / data.size();
            printf("%.3f", mean);
        }
        else if (_scoreOp == "median") {
            double median = 0.0;
            sort(data.begin(), data.end());
            int totalLines = data.size();
            if ((totalLines % 2) > 0) {
                long mid;
                mid = totalLines / 2;
                median = data[mid];
            }
            else {
                long midLow, midHigh;
                midLow = (totalLines / 2) - 1;
                midHigh = (totalLines / 2);
                median = (data[midLow] + data[midHigh]) / 2.0;
            }
            printf("%.3f", median);
        }
        else if ((_scoreOp == "mode") || (_scoreOp == "antimode")) {
             // compute the frequency of each unique value
             map<string, int> freqs;
             vector<string>::const_iterator dIt  = scores.begin();
             vector<string>::const_iterator dEnd = scores.end();
             for (; dIt != dEnd; ++dIt) {
                 freqs[*dIt]++;
             }

             // grab the mode and the anti mode
             string mode, antiMode;
             int    count = 0;
             int minCount = INT_MAX;
             for(map<string,int>::const_iterator iter = freqs.begin(); iter != freqs.end(); ++iter) {
                 if (iter->second > count) {
                     mode = iter->first;
                     count = iter->second;
                 }
                 if (iter->second < minCount) {
                     antiMode = iter->first;
                     minCount = iter->second;
                 }
             }
             // report
             if (_scoreOp == "mode") {
                 printf("%s", mode.c_str());
             }
             else if (_scoreOp == "antimode") {
                 printf("%s", antiMode.c_str());
             }
         }
         else if (_scoreOp == "collapse") {    
            vector<string>::const_iterator scoreItr = scores.begin();
            vector<string>::const_iterator scoreEnd = scores.end();
            for (; scoreItr != scoreEnd; ++scoreItr) {
                if (scoreItr < (scoreEnd - 1))
                    cout << *scoreItr << ";";
                else
                    cout << *scoreItr;
            }
        }
    }
    else {        
        cerr << endl 
             << "*****" << endl 
             << "*****ERROR: No scores found to report for the -scores option. Exiting." << endl 
             << "*****" << endl;
        exit(1);
    }
}
コード例 #8
0
ファイル: lab1pr11.cpp プロジェクト: ssharar/CSCE-121
int main()
{
	//Variables initialized
	double input = 0;
	string unit;
	Vector<double> inputs;
	
	double conversion = 0;
	
	double large = 0;
	double small = 0;
	
	//Inputs
	//Asks user to input a number
	//Uses this number to set the initial largest and smallest number (as the first value is both the largest and smallest so far
	cout << "Please enter a number and unit (cm, m, in, or ft). Press '|' to terminate." << endl;
	cin >> input >> unit;

	if (unit == "m")
	{
		conversion = input;
		large = conversion;
		small = conversion;
		inputs.push_back(conversion);
	}
	else if (unit == "cm")
	{
		conversion = input / 100;
		large = conversion;
		small = conversion;
		inputs.push_back(conversion);
	}
	else if (unit == "in")
	{
		conversion = input / (100*2.54);
		large = conversion;
		small = conversion;
		inputs.push_back(conversion);
	}
	else if (unit == "ft")
	{
		conversion = input / (100*2.54) / 12;
		large = conversion;
		small = conversion;
		inputs.push_back(conversion);
	}
	else
	{
		cout << "Incorrect unit please enter valid unit." << endl;
		exit(0);
	}

	//Asks user for an input
	cout << "Please enter a list of numbers with units (cm, m, in, or ft). Press '|' to terminate." << endl;

	//Comparison
	//Takes in inputs from the user
	//Terminates when "|" or a value other than a double is entred
	while (cin >> input >> unit)
	{
		if (unit == "m")
		{
			conversion = input;

			//If the input is larger than the largest value prints out the input as new largest value and sets large value to this number
			if (conversion > large)
			{
				large = conversion;
				inputs.push_back(conversion);
			}
			//If input is less than largest value goes in through another comparison
			else if (conversion < large)
			{
				//If input is greater than the smallest and smaller than the largest it is a middle value
				//Outputs middle value while notifying user
				if (conversion > small)
				{
					inputs.push_back(conversion);
				}
				//If input is smaller than smallest prints out the input as new smallest value and sets small value to this number
				else if (conversion < small)
				{
					small = conversion;
					inputs.push_back(conversion);
				}
				//If input is equal to smallest then prints out the input as smallest value and sets small value to this number
				else
				{
					small = conversion;
					inputs.push_back(conversion);
				}
				//If input is equal to largest then prints out the input as largest value and sets large value to this number
			}
			else
			{
				large = conversion;
				inputs.push_back(conversion);
			}
		}
		
		else if (unit == "cm")
		{
			
			conversion = input / 100;
			
			//If the input is larger than the largest value prints out the input as new largest value and sets large value to this number
			if (conversion > large)
			{
				large = conversion;
				inputs.push_back(conversion);
			}
			//If input is less than largest value goes in through another comparison
			else if (conversion < large)
			{
				//If input is greater than the smallest and smaller than the largest it is a middle value
				//Outputs middle value while notifying user
				if (conversion > small)
				{
					inputs.push_back(conversion);
				}
				//If input is smaller than smallest prints out the input as new smallest value and sets small value to this number
				else if (conversion < small)
				{
					small = conversion;
					inputs.push_back(conversion);
				}
				//If input is equal to smallest then prints out the input as smallest value and sets small value to this number
				else
				{
					small = conversion;
					inputs.push_back(conversion);
				}
				//If input is equal to largest then prints out the input as largest value and sets large value to this number
			}
			else
			{
				large = conversion;
				inputs.push_back(conversion);
			}
		}
		else if (unit == "in")
		{
			
			conversion = (input / 100) * 2.54;
			
			//If the input is larger than the largest value prints out the input as new largest value and sets large value to this number
			if (conversion > large)
			{
				large = conversion;
				inputs.push_back(conversion);
			}
			//If input is less than largest value goes in through another comparison
			else if (conversion < large)
			{
				//If input is greater than the smallest and smaller than the largest it is a middle value
				//Outputs middle value while notifying user
				if (conversion > small)
				{
					inputs.push_back(conversion);
				}
				//If input is smaller than smallest prints out the input as new smallest value and sets small value to this number
				else if (conversion < small)
				{
					small = conversion;
					inputs.push_back(conversion);
				}
				//If input is equal to smallest then prints out the input as smallest value and sets small value to this number
				else
				{
					small = conversion;
					inputs.push_back(conversion);
				}
			}
			//If input is equal to largest then prints out the input as largest value and sets large value to this number
			else
			{
				large = conversion;
				inputs.push_back(conversion);
			}
		}
		else if (unit == "ft")
		{
			
			conversion = ((input / 100) * 2.54) / 12;
			
				//If the input is larger than the largest value prints out the input as new largest value and sets large value to this number
			if (conversion > large)
			{
				large = conversion;
				inputs.push_back(conversion);
			}
			//If input is less than largest value goes in through another comparison
			else if (conversion < large)
			{
				//If input is greater than the smallest and smaller than the largest it is a middle value
				//Outputs middle value while notifying user
				if (conversion > small)
				{
					inputs.push_back(conversion);
				}
				//If input is smaller than smallest prints out the input as new smallest value and sets small value to this number
				else if (conversion < small)
				{
					small = conversion;
					inputs.push_back(conversion);
				}
				//If input is equal to smallest then prints out the input as smallest value and sets small value to this number
				else
				{
					small = conversion;
					inputs.push_back(conversion);
				}
			}
			//If input is equal to largest then prints out the input as largest value and sets large value to this number
			else
			{
				large = conversion;
				inputs.push_back(conversion);
			}
		}
		else 
		{
			cout << "Incorrect unit please enter valid unit." << endl;
			break;
		}
	}

	double sum;
	for (int count = 0; count < inputs.size(); count++)	
	{
		sum += inputs[count];
	}
	
	sort (inputs.begin(), inputs.end());
	
	for (int element = 0; element < inputs.size(); element++)	
	{
		cout << "The value of position " << element << " is " << inputs[element] << " meters. ";
	}	
	
	cout << "\n" << "The largest value was " << large << " in meters." << endl;
	cout << "The smallest value was " << small << " in meters." << endl;
	cout << "The number of values entered was " << inputs.size() << "." << endl;
	cout << "The sum of all the values was " << sum << " in meters." << endl;
	
	return 0;

}
コード例 #9
0
ファイル: race.cpp プロジェクト: Jonesey13/CatandMouse
Vector2u Race::getNearestValidSquare(unsigned PlayerNumber){
    Vector2u Dim=track.getDim();
    vector<double> norm(Dim.x*Dim.y,0);
    Vector2d Position=Player[PlayerNumber].PositionBeforeDeath;

    for (unsigned k=0; k<Dim.x*Dim.y;++k)
    {
        unsigned k1= k % Dim.x;
        unsigned k2= k / Dim.x;
        norm[k]=sqrt(pow(k1+0.5-Position.x,2)+pow(k2+0.5-Position.y,2));
    }
    vector<int> index(norm.size(), 0);
    for (unsigned i = 0 ; i != index.size() ; i++) {
        index[i] = i;
    }

    sort(index.begin(), index.end(),[&](const int& a, const int& b) {return (norm[a] < norm[b]);});

    unsigned j=0;
    bool SquareValid=false;
    bool CarCollision=false;
    vector<PROPERTIES> InvalidTiles={FALL,WALL};
    while (SquareValid==false || CarCollision==true)
    {
        CarCollision=false;
        SquareValid=true;
        unsigned k1=index[j]%Dim.x;
        unsigned k2=index[j]/Dim.x;
        Tile* CurrentTile=track.getTile(k1,k2);
        Detect Detection=CurrentTile->Detection;
        for (unsigned i=0; i<InvalidTiles.size(); i++)
        {
            if (Detection.x.count(InvalidTiles[i])==1)
            {
                SquareValid=0;
            }
        }
        if(CurrentTile->isSquare==0)
        {
            SquareValid=0;
        }

        Player[PlayerNumber].Position=Vector2d(k1+0.5, k2+0.5);
        for (unsigned i=0; i< Player.size();++i)
        {
            Car *Car1,*Car2;
            if(i==PlayerNumber)
            {
                continue;
            }
            Car1=&Player[PlayerNumber];
            Car2=&Player[i];

            vector<Vector2d> Bounding1=Car1->Bounding;
            for (unsigned k=0; k<Bounding1.size();k++)
            {
                Bounding1[k]=RotateVector(Bounding1[k],Player[PlayerNumber].Rotation);
                Bounding1[k]+=Player[PlayerNumber].Position;
            }
            Vector2d Center1=accumulate(Bounding1.begin(),Bounding1.end(),Vector2d(0,0))/static_cast<double>(Bounding1.size());

            vector<Vector2d> Bounding2=Car2->Bounding;
            for (unsigned k=0; k<Bounding2.size();k++)
            {
                Bounding2[k]=RotateVector(Bounding2[k],Player[i].Rotation);
                Bounding2[k]+=Player[i].Position;
            }
            Vector2d Center2=accumulate(Bounding2.begin(),Bounding2.end(),Vector2d(0,0))/static_cast<double>(Bounding2.size());

            if( InPolygon(Bounding1,Bounding2) || InPolygon(Center1,Bounding2) || InPolygon(Center2,Bounding1) )
            {
                CarCollision=1;
            }
        }
        j++;
        if (j==Dim.x*Dim.y)
        {
            cerr<<"Failed to Find Valid Square!!"<<endl;
        }
    }
    return Vector2u(index[j-1]%Dim.x,index[j-1]/Dim.x);
}
コード例 #10
0
/***********************************************************
synopsis: do all of the initialisation for a new game:
          build the screen
	  get a random word and generate anagrams
	  (must get less than 66 anagrams to display on screen)
	  initialise all the game control flags

inputs: head - first node in the answers list (in/out)
        dblHead - first node in the dictionary list
	screen - the SDL_Surface to display the image
	letters - first node in the letter sprites (in/out)

outputs: n/a
***********************************************************/
static void
newGame(struct node** head, struct dlb_node* dlbHead, 
        SDL_Surface* screen, struct sprite** letters)
{
    char guess[9];
    char remain[9];
    int happy = 0;   /* we don't want any more than ones with 66 answers */
                     /* - that's all we can show... */
    int i;

	/* show background */
	strcpy(txt, language);
	ShowBMP(strcat(txt,"images/background.bmp"),screen, 0,0);

	destroyLetters(letters);
    assert(*letters == NULL);

	while (!happy) {
        char buffer[9];
        getRandomWord(buffer, sizeof(buffer));
		strcpy(guess,"");
		strcpy(rootWord, buffer);
		bigWordLen = strlen(rootWord)-1;
		strcpy(remain, rootWord);

		rootWord[bigWordLen] = '\0';

		/* destroy answers list */
		destroyAnswers(head);

		/* generate anagrams from random word */
		ag(head, dlbHead, guess, remain);

		answersSought = Length(*head);
		happy = ((answersSought <= 77) && (answersSought >= 6));

#ifdef DEBUG
		if (!happy) {
			Debug("Too Many Answers!  word: %s, answers: %i",
                   rootWord, answersSought);
		}
#endif
	}

#ifdef DEBUG
    Debug("Selected word: %s, answers: %i", rootWord, answersSought);
#endif

    /* now we have a good set of words - sort them alphabetically */
    sort(head);

	for (i = bigWordLen; i < 7; i++){
		remain[i] = SPACE_CHAR;
	}
	remain[7] = '\0';
	remain[bigWordLen]='\0';

	shuffleWord(remain);
	strcpy(shuffle, remain);

	strcpy(answer, SPACE_FILLED_STRING);

	/* build up the letter sprites */
    assert(*letters == NULL && screen != NULL);
	buildLetters(letters, screen);
	addClock(letters, screen);
	addScore(letters, screen);

	/* display all answer boxes */
	displayAnswerBoxes(*head, screen);

	gotBigWord = 0;
	score = 0;
	updateTheScore = 1;
	gamePaused = 0;
	winGame = 0;
	answersGot = 0;

	gameStart = time(0);
	gameTime = 0;
	stopTheClock = 0;
}
コード例 #11
0
ファイル: main.cpp プロジェクト: AwenHuang/OOP
int main(){
		Convexhull h;
		vector<Point> point;
		vector<Point> result;
		vector<Point> internal;

		while(1){
				int i,option,n;
				cout << "Please choose method: (1)brute force (2)Jarvis's march (3)exit" <<endl;
				cin >> option;
				
				ifstream finput("Input.txt");
			
				internal.clear();
				point.clear();
				result.clear();
				
				finput >> n; // Ū¤F´X­Ó¦r¤¸
				for(i=0; i<n; i++){
						double x,y;
						finput >> x >> y;
						Point a = Point(x,y);
						point.push_back(a);
				}
				struct timeval tv, tv2;
				unsigned long long int start_utime, end_utime;
				if(option == 1){
						gettimeofday(&tv, NULL);
						h.FindConvexHull_bf(point, result);
						gettimeofday(&tv2, NULL);
						start_utime = tv.tv_sec*1000000 + tv.tv_usec;
						end_utime = tv2.tv_sec*1000000 + tv2.tv_usec;
				}
				else if(option == 2){
						gettimeofday(&tv, NULL);
						h.FindConvexHull_jm(point, result);
						gettimeofday(&tv2, NULL);
						start_utime = tv.tv_sec*1000000 + tv.tv_usec;
						end_utime = tv2.tv_sec*1000000 + tv2.tv_usec;
				}
				else
						break;
				cout << "cost time: " << end_utime - start_utime << " us" <<endl;
				internal = h.FindInternalPoint(point,result);
				
				ofstream foutput("Output.txt");
				foutput << internal.size() << endl;
				
				vector<Point> upper;
				vector<Point> lower;
				upper.clear();
				lower.clear();
				for(i=0; i<internal.size(); i++){
						if(internal[i].y >= 0)
								upper.push_back(internal[i]);
						else
								lower.push_back(internal[i]);
				}
				sort(upper.begin(), upper.end(), up_compare);
				sort(lower.begin(), lower.end(), low_compare);
		
				for(i=0; i<upper.size(); i++)
						foutput << upper[i].x << " " << upper[i].y << endl;
				for(i=0; i<lower.size(); i++)
						foutput << lower[i].x << " " << lower[i].y << endl;
				foutput << endl;

				foutput << result.size() << endl;

				Point start_p = FindStartPoint(result);
				upper.clear();
				lower.clear();
				for(i=0; i<result.size(); i++){
						if(result[i] == start_p)
								continue;
						if(result[i].y > start_p.y)
								upper.push_back(result[i]);
						else
								lower.push_back(result[i]);
				}
				sort(upper.begin(), upper.end(), up_compare);
				sort(lower.begin(), lower.end(), low_compare);
				foutput << start_p.x << " " << start_p.y << endl;
				for(i=0; i<upper.size(); i++)
						foutput << upper[i].x << " " << upper[i].y << endl;
				for(i=0; i<lower.size(); i++)
						foutput << lower[i].x << " " << lower[i].y << endl;
		}

		return 0;
}
コード例 #12
0
ファイル: datamodel.cpp プロジェクト: KDE/plasma-framework
void SortFilterModel::setSortOrder(const Qt::SortOrder order)
{
    sort(0, order);
}
コード例 #13
0
void main()
{
	link_list mylist;

	init_list(&mylist);

	int select = 1;
	elem_type item;
	node *p = NULL;
	while(select)
	{
		printf("*************************************************\n");
		printf("*  [1] push_back	 [2] push_front 	*\n");
		printf("*  [3] show_list	 [4] pop_back    	*\n");
		printf("*  [5] pop_front	 [6] insert_val 	*\n");
		printf("*  [7] find 	 	 [8] get_length 	*\n");
		printf("*  [9] delete_val	 [10] sort   	 	*\n");
		printf("*  [11] resever		 [12] clear 	 	*\n");
		printf("*  [13*] destroy	 [0] quit_system 	*\n");
		printf("*  [14] prior_node 	 [15] next_node 	*\n");
		printf("*************************************************\n");

		printf("请选择操作选项:> ");
		scanf("%d", &select);

		if(select == 0)
			break;

		switch(select)
		{
			case 1:
				printf("请输入要插入的数据(-1结束):>");
				while(scanf("%d", &item), item != -1)
				{
					push_back(&mylist, item);
				}
				break;
			case 2:
				printf("请输入要插入的数据(头插法, -1结束);>");
				while(scanf("%d", &item), item != -1)
				{
					push_front(&mylist, item);
				}
				break;
			case 3:
				show_list(&mylist);
				break;
			case 4:
				pop_back(&mylist);
				break;
			case 5:
				pop_front(&mylist);
				break;
			case 6:
				printf("请输入要插入的数据:>");
				scanf("%d", &item);
				insert_val(&mylist, item);
				break;
			case 7:
				printf("请输入要查找的数据:>");
				scanf("%d", &item);
				p = find(&mylist, item);
				if (p == NULL)
				{
					printf("要查找的数据在单链表中不存在.");
				}
				else
				 	printf("在单链表查找到数据: %d\n", p->data);
				break;
			case 8:
				printf("单链表的长度为: %d\n", get_length(&mylist));
				break;
			case 9:
				printf("请输入要删除的值:> ");
				scanf("%d", &item);
				delete_val(&mylist, item);
				break;
			case 10:
				sort(&mylist);
				break;
			case 11:
				resver(&mylist);
				break;
			case 12:
				clear(&mylist);
				break;
			case 14:
				printf("请输入要查找的数据:>");
				scanf("%d", &item);
				p = prior_node(&mylist, item);
				if (p == NULL || p == (&mylist)->head)
				{
					printf("要查找的数据在单链表中不存在前驱.\n");
				}
				else
				{
			 	 	printf("要查找的数据在单链表中的前驱为:%d.\n", p->data);	
				}
				break;
 	 	 	case 15:
				printf("请输入要查找的数据:>");
				scanf("%d", &item);
				p = next_node(&mylist, item);
				if (p == NULL)
				{
					printf("要查找的数据在单链表中不存在后继.\n");
				}
				else
				{
			 	 	printf("要查找的数据在单链表中的后继为:%d.\n", p->data);	
				}
				break;

			default:
				printf("输入的选择有误,请重新输入.\n");
				break;
		}
	}
	destroy(&mylist);
}
コード例 #14
0
void ME_Regression_DataSet::report_feature_statistics(int f_idx, const char *name) const
{
    vector<double> vals0,vals1;
    double avg_nz0=0, avg_nz1=0;
    double wnz0=0, wnz1=0, wz0=0, wz1=0;
    int i;

    for (i=0; i<samples.size(); i++)
    {
        double val = 0;
        int j;
        for (j=0; j<samples[i].f_vals.size(); j++)
        {
            if (samples[i].f_vals[j].f_idx == f_idx)
            {
                val = samples[i].f_vals[j].val;
                break;
            }
        }

        double weight = samples[i].weight;
        int label = samples[i].label;

        if (val != 0)
        {
            if (label == 0)
            {
                wnz0+= weight;
                avg_nz0 += weight * val;
                vals0.push_back(val);
            }
            else
            {
                wnz1+= weight;
                avg_nz1 += weight * val;
                vals1.push_back(val);
            }
        }
        else
        {
            if (label == 0)
            {
                wz0+=weight;
            }
            else
                wz1+=weight;
        }
    }

    if (avg_nz0 != 0)
        avg_nz0/=wnz0;
    if (avg_nz1 != 0)
        avg_nz1/=wnz1;

    printf("Statistics for feature %d ",f_idx);
    if (name)
        printf(" %s",name);
    printf("\n");
    printf("Class 0:\n");
    printf("weight samples with non-zero vals: %.3f (%.2f)  samples with zero val: %.3f (%.2f)\n",
           wnz0,wnz0/(wnz0+wz0),wz0,wz0/(wnz0+wz0));

    printf("Avg weighted: %g    non-weighted vals:\n",avg_nz0);
    sort(vals0.begin(),vals0.end());

    // prints avgs of tenths of the values
    int ts=vals0.size()/10;
    int p=0;
    for (i=0; i<9; i++)
    {
        int next=p+ts;
        int j;
        double av=0;
        for (j=p; j<next; j++)
            av+=vals0[j];

        printf("%.4f  ",av/ts);
        p+=ts;
    }

    double av=0;
    for (i=p; i<vals0.size(); i++)
        av+=vals0[i];

    printf("%.4f\n",av/(vals0.size()-p));


    printf("Class 1:\n");
    printf("weight samples with non-zero vals: %.3f (%.2f)  samples with zero val: %.3f (%.2f)\n",
           wnz1,wnz1/(wnz1+wz1),wz1,wz1/(wnz1+wz1));

    printf("Avg weighted: %g    non-weighted vals:\n",avg_nz1);
    sort(vals1.begin(),vals1.end());

    // prints avgs of tenths of the values
    ts=vals1.size()/10;
    p=0;
    for (i=0; i<9; i++)
    {
        int next=p+ts;
        int j;
        double av=0;
        for (j=p; j<next; j++)
            av+=vals1[j];

        printf("%.4f  ",av/ts);
        p+=ts;
    }

    av=0;
    for (i=p; i<vals1.size(); i++)
        av+=vals1[i];

    printf("%.4f\n\n\n",av/(vals1.size()-p));

}
コード例 #15
0
void CZapitBouquet::sortBouquetByNumber(void)
{
	sort(tvChannels.begin(), tvChannels.end(), CmpChannelByChNum());
	sort(radioChannels.begin(), radioChannels.end(), CmpChannelByChNum());
}
コード例 #16
0
FilteredPlacesModel::FilteredPlacesModel(QObject *parent) : QSortFilterProxyModel(parent)
, m_placesModel(new KFilePlacesModel(this))
{
    setSourceModel(m_placesModel);
    sort(0);
}
コード例 #17
0
 void wiggleSort(vector<int>& nums) {
     int mid = (nums.size() - 1) / 2;
     sort(nums.begin(), nums.end());  // O(nlogn) time
     reversedTriPartitionWithVI(nums, nums[mid]);  // O(n) time, O(1) space
 }
コード例 #18
0
LibraryTreeWidget::LibraryTreeWidget(QWidget *parent)
	: QTreeWidget(parent)
{
	setSelectionMode(QAbstractItemView::ExtendedSelection);
	setDragEnabled(true);
	viewport()->setAcceptDrops(true);
	setDropIndicatorShown(true);
	setDragDropMode(QAbstractItemView::InternalMove);

	invisibleRootItem()->setFlags(invisibleRootItem()->flags() & ~Qt::ItemIsDropEnabled);

	setHeaderHidden(true);

	setEditTriggers(QAbstractItemView::EditKeyPressed | QAbstractItemView::SelectedClicked);

	addNewFileAction_ = new QAction(tr("Add New File..."), this);
	connect(addNewFileAction_, SIGNAL(triggered()), this, SLOT(addNewFile()));

	importToLibraryAction_ = new QAction(tr("Add Existing Files..."), this);
	connect(importToLibraryAction_, SIGNAL(triggered()), this, SLOT(importToLibrary()));

//	newFontAction_ = new QAction(tr("New Font..."), this);
//	connect(newFontAction_, SIGNAL(triggered()), this, SLOT(newFont()));

	newFolderAction_ = new QAction(tr("New Folder"), this);
	connect(newFolderAction_, SIGNAL(triggered()), this, SLOT(newFolder()));

	removeAction_ = new QAction(tr("Remove"), this);
	connect(removeAction_, SIGNAL(triggered()), this, SLOT(remove()));

	renameAction_ = new QAction(tr("Rename"), this);
	//renameAction_->setShortcut(Qt::Key_F2);
	connect(renameAction_, SIGNAL(triggered()), this, SLOT(rename()));

	sortAction_ = new QAction(tr("Sort"), this);
	connect(sortAction_, SIGNAL(triggered()), this, SLOT(sort()));

	codeDependenciesAction_ = new QAction(tr("Code Dependencies..."), this);
	connect(codeDependenciesAction_, SIGNAL(triggered()), this, SLOT(codeDependencies()));

	insertIntoDocumentAction_ = new QAction(tr("Insert Into Document"), this);
	connect(insertIntoDocumentAction_, SIGNAL(triggered()), this, SLOT(insertIntoDocument()));

	projectPropertiesAction_ = new QAction(tr("Properties..."), this);
	connect(projectPropertiesAction_, SIGNAL(triggered()), this, SLOT(projectProperties()));

	automaticDownsizingAction_ = new QAction(tr("Automatic Downsizing"), this);
	automaticDownsizingAction_->setCheckable(true);
	connect(automaticDownsizingAction_, SIGNAL(triggered(bool)), this, SLOT(automaticDownsizing(bool)));

    excludeFromExecutionAction_ = new QAction(tr("Exclude from Execution"), this);
    excludeFromExecutionAction_->setCheckable(true);
    connect(excludeFromExecutionAction_, SIGNAL(triggered(bool)), this, SLOT(excludeFromExecution(bool)));

    setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this, SIGNAL(customContextMenuRequested  (const QPoint&)),
			this, SLOT  (onCustomContextMenuRequested(const QPoint&)));

	connect(this, SIGNAL(itemDoubleClicked  (QTreeWidgetItem*, int)),
			this, SLOT  (onItemDoubleClicked(QTreeWidgetItem*, int)));

	connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)),
			this, SLOT  (onCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)));

	isModifed_ = false;
	xmlString_ = toXml().toString();

	QTimer* timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(checkModification()));
	timer->start(500);
}
コード例 #19
0
//main function
int main() {
	//print out some application instructions
	printf("Enter some numbers that are bigger than 0 and smaller than %u\n", UINT_MAX);
	printf("If you enter the number 0 the applications will print out all given numbers as a sorted list\n\n---- Input --------------\n\n");
	
	
	//declare a c-generic datatype
	List container;
	
	//initialize the list
	memset(&container, 0, sizeof(List));
	construct(List, &container, sizeof(unsigned int), FREEOBJ);
	
	
	
	while(1) {
		//read out an element
		unsigned int* t=malloc(sizeof(unsigned int));
		scanf("%u", t);
		
		//add it to the list
		push_back(List, &container, t, DYNAMIC);
		
		//break if zero is the input
		if(*t==0)
			break;
	}
	
	
	printf("\n\n---- Unsorted --------------\n\n");
	
	//set print functions
	set_print(List, &container, print);
	
	//print all element in our list
	print_all(List, &container);
	
	
	//lets have fun with iterators (instead using print_all)
	printf("\n\n---- Iterators --------------\n\n");
	
	ListIter* i = create(ListIter, &container);
	//check if it is empty - this will never happen
	if(!empty(List, &container)) {
		//place the iterator at the first element
		head(ListIter, i);
		
		do {
			printf("%u\n", *((unsigned int*)retrieve(ListIter, i)));
			
		}while(!next(ListIter, i));
	}
	
	//give the memory free
	destroy(ListIter, i);
	
	
	printf("\n\n---- Sorted ASC --------------\n\n");
	
	//set the sort functions
	set_compare(List, &container, intcmp);
	
	//use the in-place sort
	sort(List, &container);
	
	
	print_all(List, &container);
	
	
	//give the memory free
	destruct(List, &container);
	
	printf("\n\n");
	return 0;
}
コード例 #20
0
ファイル: neutrinoyparser.cpp プロジェクト: Firmeware/max-tdt
//-------------------------------------------------------------------------
// func: Bouquet Edit
//-------------------------------------------------------------------------
std::string  CNeutrinoYParser::func_set_bouquet_edit_form(CyhookHandler *hh, std::string para)
{
	if (!(hh->ParamList["selected"].empty()))
	{
		int selected = atoi(hh->ParamList["selected"].c_str()) - 1;
		int mode = NeutrinoAPI->Zapit->getMode();
		ZapitChannelList* channels = mode == CZapitClient::MODE_TV ? &(g_bouquetManager->Bouquets[selected]->tvChannels) : &(g_bouquetManager->Bouquets[selected]->radioChannels);
		for(int j = 0; j < (int) channels->size(); j++) {
			hh->ParamList["bouquet_channels"] +=
				string_printf("<option value=\""
					PRINTF_CHANNEL_ID_TYPE_NO_LEADING_ZEROS
					"\">%s</option>\n",
					(*channels)[j]->channel_id,
					(*channels)[j]->getName().c_str());
		}
		ZapitChannelList Channels;
		Channels.clear();
		if (mode == CZapitClient::MODE_RADIO) {
			for (tallchans_iterator it = allchans.begin(); it != allchans.end(); it++)
				if (it->second.getServiceType() == ST_DIGITAL_RADIO_SOUND_SERVICE)
					Channels.push_back(&(it->second));
		} else {
			for (tallchans_iterator it = allchans.begin(); it != allchans.end(); it++)
				if (it->second.getServiceType() != ST_DIGITAL_RADIO_SOUND_SERVICE)
					Channels.push_back(&(it->second));
		}
		sort(Channels.begin(), Channels.end(), CmpChannelByChName());

		for (int i = 0; i < (int) Channels.size(); i++) {
			if (!g_bouquetManager->existsChannelInBouquet(selected, Channels[i]->channel_id)){
				hh->ParamList["all_channels"] +=
					string_printf("<option value=\""
						PRINTF_CHANNEL_ID_TYPE_NO_LEADING_ZEROS
						"\">%s</option>\n",
						Channels[i]->channel_id,
						Channels[i]->getName().c_str());
			}
		}
#if 0
		CZapitClient::BouquetChannelList BChannelList;
		CZapitClient::BouquetChannelList::iterator channels;

		int selected = atoi(hh->ParamList["selected"].c_str()) - 1;

		// List channels in bouquet
		NeutrinoAPI->Zapit->getBouquetChannels(selected, BChannelList, CZapitClient::MODE_CURRENT, true); // UTF-8
		for(channels = BChannelList.begin(); channels != BChannelList.end(); channels++)
		{
			hh->ParamList["bouquet_channels"] +=
				string_printf("<option value=\""
					PRINTF_CHANNEL_ID_TYPE_NO_LEADING_ZEROS
					"\">%s</option>\n",
					channels->channel_id,
					channels->name);
		}
		// List all channels
		NeutrinoAPI->Zapit->getChannels(BChannelList, CZapitClient::MODE_CURRENT, CZapitClient::SORT_ALPHA, true); // UTF-8
		for(channels = BChannelList.begin(); channels != BChannelList.end(); channels++)
		{
			if (!NeutrinoAPI->Zapit->existsChannelInBouquet(selected, channels->channel_id)){
				hh->ParamList["all_channels"] +=
					string_printf("<option value=\""
						PRINTF_CHANNEL_ID_TYPE_NO_LEADING_ZEROS
						"\">%s</option>\n",
						channels->channel_id,
						channels->name);
			}
		}
#endif
		return "";
	}
	else
		return "No Bouquet selected";
}
コード例 #21
0
ファイル: main.c プロジェクト: grishasergei/hpc_stars
int main(int argc, char **argv)
{
   int N, i, j;
   clock_t start, end;
    /*
   if(argc < 2)
   {
      printf("usage: ./a.out N\n");
      return 0;
   }
     */
    N = 1000;//atoi(argv[1]);
    
    printf("MAX INT: %d\n", INT_MAX);
    
   star_t *stars;
   stars = (star_t *) malloc(N*sizeof(star_t));
   
   printf("creating random stars: \t");
   start = clock();
   
   create_random_array(stars, N);
   
   end = clock();
   printtime(start, end);
 //  print_stars(stars, N);
         
   printf("sorting stars:    \t");
   start = clock();

   sort(stars, N);
   
   end = clock();
   printtime(start, end);
//      print_stars(stars, N);
   
   printf("allocating matrix: \t");
   start = clock();
   //float_t **matrix;
    matrix* m;
    m = matrix_create(N, N);
    
   end = clock();
   printtime(start, end);
   
   printf("filling matrix: \t");
   start = clock();
   fill_matrix(stars, m, N);
   
   //print_matrix(matrix,N);
   end = clock();
   printtime(start, end);
   
   printf("generating histogram: \t");
   start = clock();
   int *histogram = (int *)calloc(NUM_HIST_BOXES,sizeof(int));
   hist_param_t histparams = generate_histogram(m, histogram, N, NUM_HIST_BOXES);
   end = clock();
   printtime(start, end);

   display_histogram(histogram, histparams);
    
    free(histogram);
    free(m->data);
    free(m);
    /*
    for (i=0; i<N; i++) {
        printf("%s: %f\n",stars[i].designation,stars[i].distanceFromOrigin);
    }
    */
    /*
    for (i=0; i<N; i++) {
        for (j=0; j<N; j++) {
            printf("%.2f ",matrix_get(*m, i, j));
        }
        printf("\n");
    }
     */
}
コード例 #22
0
ファイル: neutrinoyparser.cpp プロジェクト: Firmeware/max-tdt
//-------------------------------------------------------------------------
// Template 1:classname, 2:zAlarmTime, 3: zStopTime, 4:zRep, 5:zRepCouunt
//		6:zType, 7:sAddData, 8:timer->eventID, 9:timer->eventID
//-------------------------------------------------------------------------
std::string  CNeutrinoYParser::func_get_timer_list(CyhookHandler *hh, std::string para)
{
	std::string yresult;
	CTimerd::TimerList timerlist;				// List of bouquets

	timerlist.clear();
	NeutrinoAPI->Timerd->getTimerList(timerlist);
	sort(timerlist.begin(), timerlist.end());

	CZapitClient::BouquetChannelList channellist_tv;     
	CZapitClient::BouquetChannelList channellist_radio;     
	channellist_tv.clear();
	channellist_radio.clear();

	int i = 1;
	char classname= 'a';
	CTimerd::TimerList::iterator timer = timerlist.begin();
	for(; timer != timerlist.end();timer++)
	{
		classname = (i++&1)?'a':'b';

		// build alarm/stoptime
		char zAlarmTime[25] = {0};
		struct tm *alarmTime = localtime(&(timer->alarmTime));
		strftime(zAlarmTime,20,"%d.%m. %H:%M",alarmTime);

		char zAnnounceTime[25] = {0};
		struct tm *announceTime = localtime(&(timer->announceTime));
		strftime(zAnnounceTime,20,"%d.%m. %H:%M",announceTime);

		char zStopTime[25] = {0};
		if(timer->stopTime > 0)
		{
			struct tm *stopTime = localtime(&(timer->stopTime));
			strftime(zStopTime,20,"%d.%m. %H:%M",stopTime);     
		}
		// repeat
		std::string zRep = NeutrinoAPI->timerEventRepeat2Str(timer->eventRepeat);
		std::string zRepCount;
		if (timer->eventRepeat == CTimerd::TIMERREPEAT_ONCE)
			zRepCount = "-";
		else
			zRepCount = (timer->repeatCount == 0) ? "&#x221E;" : string_printf("%dx",timer->repeatCount);
		// timer type
		std::string zType = NeutrinoAPI->timerEventType2Str(timer->eventType);
		// Add Data
		std::string sAddData="";
		switch(timer->eventType)
		{
			case CTimerd::TIMER_NEXTPROGRAM :
			case CTimerd::TIMER_ZAPTO :
			case CTimerd::TIMER_RECORD :
			{
				sAddData = ZapitTools::UTF8_to_Latin1(NeutrinoAPI->Zapit->getChannelName(timer->channel_id).c_str());
				if (sAddData.empty())
					sAddData = NeutrinoAPI->Zapit->isChannelTVChannel(timer->channel_id) ? "Unbekannter TV-Kanal" : "Unbekannter Radiokanal";

				if( timer->apids != TIMERD_APIDS_CONF)
				{
					std::string separator = "";
					sAddData += '(';
					if( timer->apids & TIMERD_APIDS_STD )
					{
						sAddData += "STD";
						separator = "/";
					}
					if( timer->apids & TIMERD_APIDS_ALT )
					{
						sAddData += separator;
						sAddData += "ALT";
						separator = "/";
					}
					if( timer->apids & TIMERD_APIDS_AC3 )
					{
						sAddData += separator;
						sAddData += "AC3";
						separator = "/";
					}
					sAddData += ')';
				}
				if(timer->epgID!=0)
				{
					CSectionsdClient sdc;
					CEPGData epgdata;
					if (sdc.getEPGid(timer->epgID, timer->epg_starttime, &epgdata))
						sAddData+="<br/>" + epgdata.title;
					else
						sAddData+=std::string("<br/>")+timer->epgTitle;
				}
				else
					sAddData+=std::string("<br/>")+timer->epgTitle;
			}
			break;
			case CTimerd::TIMER_STANDBY :
			{
				sAddData = "Standby: ";
				if(timer->standby_on)
					sAddData+= "An";
				else
					sAddData+="Aus";
			}
			break;
			case CTimerd::TIMER_REMIND :
				sAddData = std::string(timer->message).substr(0,20);
				break;
			case CTimerd::TIMER_EXEC_PLUGIN :
				sAddData = std::string(timer->pluginName);
				break;

			default:{}
		}
		yresult += string_printf(para.c_str(), classname, zAlarmTime, zStopTime, zRep.c_str(), zRepCount.c_str(),
					zType.c_str(), sAddData.c_str(),timer->eventID,timer->eventID);
	}
	classname = (i++&1)?'a':'b';

	return yresult;
}
コード例 #23
0
int SDFFelementManager::check(){
  channelManager* cmanager=parser->get_cmanager();

  // sort the sequence
  sort();

  // now check whether we use one of the required fields (if there are)
  if (cmanager->contains_required()) {
    for (size_t j=0; j<cmanager->get_channel_count(); j++) {
      if (cmanager->get(j).required) {
        if (elements.find(cmanager->get(j).name)==elements.end())
          parser->add_error_t(SEQUENCER_CSVERROR_NOREQUIRED_NUM, format(get_errormessage(SEQUENCER_SDFFERROR_NOREQUIRED_NUM), (*cmanager)[j].name.c_str()), format(get_errorsmessage(SEQUENCER_SDFFERROR_NOREQUIRED_NUM), (*cmanager)[j].name.c_str()), parser->get_current_filename(), 0);
      }
    }
  }

  // now go through all channels
  std::map<std::string, std::vector<SDFFsequenceElement*> >::const_iterator i;
  for (i=elements.begin(); i!=elements.end(); ++i) {
    // for each channel we have to check all elements:
    //    1. do they collide with the time 0 (negative times are not allowed)?
    //    2. do two elements collide, i.e. do they intersect?
    //    3. call check of each element This will also check whether the channel exists

    if (i->second.size()==1) {
      // now call the check method
      i->second[0]->check();
      //std::cout<<"checked "<<i->first<<"["<<0<<"]\n";
      // here we only have to check for collision with t=0
      if (i->second[0]->extract_real_t_start()<0) {
        parser->add_error(SEQUENCER_SDFFERROR_NONEGTIME_NUM, i->second[0]->get_filename(), i->second[0]->extract_real_t_start(), i->second[0]->get_line());
      }
      // if end_time>0 we also have to check for collisions with t=end_time
      if (end_time>0) {
        if (i->second[0]->extract_real_t_end()>end_time) {
          parser->add_error(SEQUENCER_SDFFERROR_AFTEREND_NUM, i->second[0]->get_filename(), i->second[0]->extract_real_t_end(), i->second[0]->get_line());
        }
      }

    }
    if (i->second.size()>1) {
      for (size_t j=0; j<i->second.size(); j++) {
        // now call the check method
        i->second[j]->check();
        //std::cout<<"checked "<<i->first<<"["<<j<<"]: t_start="<<i->second[j]->extract_real_t_start()<<",   t_end="<<i->second[j]->extract_real_t_end()<<"\n";
        // here we only have to check for collision with t=0
        if (i->second[j]->extract_real_t_start()<0) {
          parser->add_error(SEQUENCER_SDFFERROR_NONEGTIME_NUM, i->second[j]->get_filename(), i->second[j]->extract_real_t_start(), i->second[j]->get_line());
        }
        // if end_time>0 we also have to check for collisions with t=end_time
        if (end_time>0) {
          if (i->second[j]->extract_real_t_end()>end_time) {
            parser->add_error(SEQUENCER_SDFFERROR_AFTEREND_NUM, i->second[j]->get_filename(), i->second[j]->extract_real_t_end(), i->second[j]->get_line());
          }
        }

        // if this is j>0 we can compare j to j-1 to determine collisions
        if (j>0) {
          if (i->second[j]->extract_real_t_start() < i->second[j-1]->extract_real_t_end()) {
            parser->add_error(SEQUENCER_SDFFERROR_COLLISION_NUM, format(get_errormessage(SEQUENCER_SDFFERROR_COLLISION_NUM), i->first.c_str(), i->second[j-1]->extract_real_t_end(), i->second[j-1]->get_line(), i->second[j]->extract_real_t_end(), i->second[j]->get_line()), format(get_errorsmessage(SEQUENCER_SDFFERROR_COLLISION_NUM), i->second[j-1]->get_line(), i->second[j]->get_line()), i->second[j]->get_filename(), i->second[j]->extract_real_t_start(), i->second[j]->get_line());
          }
          /*if (i->second[j]->extract_real_t_start() == i->second[j-1]->extract_real_t_start()) {
            parser->add_error(SEQUENCER_SDFFERROR_COLLISION_NUM, format(get_errormessage(SEQUENCER_SDFFERROR_COLLISION_NUM), i->first.c_str(), i->second[j-1]->extract_real_t_start(), i->second[j-1]->get_line(), i->second[j]->extract_real_t_start(), i->second[j]->get_line()), format(get_errorsmessage(SEQUENCER_SDFFERROR_COLLISION_NUM), i->second[j-1]->get_line(), i->second[j]->get_line()), i->second[j]->get_filename(), i->second[j]->extract_real_t_start(), i->second[j]->get_line());
          }*/
        }
      }
    }
  }
  if (parser->get_errornum()>0) return -1;
  if (parser->get_warningnum()>0) return +1;
  return 0;
};
コード例 #24
0
std::vector<std::string> SerialInterface::enumerate_ports()
{
        std::vector<std::string> SerialDeviceList = std::vector<std::string>();
        
        #ifdef __unix__
        
        DIR *dp;
        struct dirent *dirp;
        std::string f, d;
        std::vector<std::string>::iterator it;
        char buf[PATH_MAX];
        
        struct serial_struct serinfo;
        int fd;
        
        if ((dp = opendir("/dev/")) == NULL)
        {
                std::cerr << "Error (" << errno << ") opening /dev/" << std::endl;
        }
        else
        {
                while ((dirp = readdir(dp)) != NULL)
                {
                        f = dirp->d_name;
                        d = "/dev/" + f;
                        if (f.find("ttyS") == 0)
                        {
                                if ((fd = ::open(d.c_str(), O_RDWR|O_NONBLOCK)) < 0)
                                {
                                        std::cerr << "Cannot open port " << d << std::endl;
                                        continue;
                                }
                                
                                serinfo.reserved_char[0] = 0;
                                
                                if (::ioctl(fd, TIOCGSERIAL, &serinfo) < 0)
                                {
                                        std::cerr << "Cannot get serial info for " << d << std::endl;
                                        ::close(fd);
                                        continue;
                                }
                                
                                if (serinfo.port != 0)
                                        SerialDeviceList.push_back(d);
                                
                                ::close(fd);
                                
                                continue;
                        }
                        if (f.find("ttyUSB") == 0)
                        {
                                SerialDeviceList.push_back(d);
                        }
                }
                
                closedir(dp);
        }
        
        if ((dp = opendir("/dev/serial/by-id/")) != NULL)
        {
                while ((dirp = readdir(dp)) != NULL)
                {
                        f = dirp->d_name;
                        if (f == "." || f == "..")
                                continue;
                        f = "/dev/serial/by-id/" + f;
                        if (realpath(f.c_str(), buf));
                        {
                                f = buf;
                                SerialDeviceList.push_back(f);
                        }
                }
                
                closedir(dp);
        }
        
        #elif defined _WIN32
        
        TCHAR szDevices[65535];
        unsigned long dwChars = QueryDosDevice(NULL, szDevices, 65535);
        TCHAR *ptr = szDevices;
        TCHAR *temp_ptr;
        std::string c;
        
        while (dwChars)
        {
                int port;
                
                if (sscanf(ptr, "COM%d", &port) == 1)
                {
                        c = ptr;
                        SerialDeviceList.push_back(c);
                }
                
                temp_ptr = strchr(ptr, 0);
                dwChars -= (DWORD)((temp_ptr - ptr) / sizeof(TCHAR) + 1);
                ptr = temp_ptr + 1;
        }
        
        #endif
        
        // sort it
        sort(SerialDeviceList.begin(), SerialDeviceList.end(), doj::alphanum_less<std::string>());
        
        // remove duplicates
        SerialDeviceList.erase(std::unique(SerialDeviceList.begin(), SerialDeviceList.end()), SerialDeviceList.end());
        
        return SerialDeviceList;
}
コード例 #25
0
inline void sort(T1& a, T2 comp) {
  sort(ALL(a), comp);
}
コード例 #26
0
void CBouquetManager::sortBouquets(void)
{
	sort(Bouquets.begin(), Bouquets.end(), CmpBouquetByChName());
}
コード例 #27
0
ファイル: Algorithm.cpp プロジェクト: SortC/SortC
void Algorithm::doSort(){
	if(!isSorted){
		sort();
		isSorted= true;
	}
}
コード例 #28
0
void CZapitBouquet::sortBouquet(void)
{
	sort(tvChannels.begin(), tvChannels.end(), CmpChannelByChName());
	sort(radioChannels.begin(), radioChannels.end(), CmpChannelByChName());
}
コード例 #29
0
void DhQAbstractTableModel::Dvhsort(int x1, long x2) {
  return sort(x1, (Qt::SortOrder)x2);
}
コード例 #30
0
void MeshWithConnectivity::LoopSubdivision() {
	// generate new (odd) vertices

	// visited edge -> vertex position information
	// Note that this is different from the one in computeConnectivity()
	typedef std::map<std::pair<int, int>, int> edgemap_t;
	edgemap_t new_vertices;

	// The new data must be doublebuffered or otherwise some of the calculations below would
	// not read the original positions but the newly changed ones, which is slightly wrong.
	std::vector<Vec3f> new_positions(positions.size());
	std::vector<Vec3f> new_normals(normals.size());
	std::vector<Vec3f> new_colors(colors.size());

	for (size_t i = 0; i < indices.size(); ++i)
		for (int j = 0; j < 3; ++j) {
			int v0 = indices[i][j];
			int v1 = indices[i][(j+1)%3];

			// Map the edge endpoint indices to new vertex index.
			// We use min and max because the edge direction does not matter when we finally
			// rebuild the new faces (R3); this is how we always get unique indices for the map.
			auto edge = std::make_pair(min(v0, v1), max(v0, v1));

			// With naive iteration, we would find each edge twice, because each is part of two triangles
			// (if the mesh does not have any holes/empty borders). Thus, we keep track of the already
			// visited edges in the new_vertices map. That requires the small R3 task below in the 'if' block.
			if (new_vertices.find(edge) == new_vertices.end()) {
				// YOUR CODE HERE (R4): compute the position for odd (= new) vertex.
				Vec3f pos, col, norm;
				int leftvertex, rightvertex;
				// You will need to use the neighbor information to find the correct vertices.
				// Be careful with indexing!
				// No need to worry about boundaries, though (except for the extra credit!).

				// Then, use the correct weights for each four corner vertex.
				// This default implementation just puts the new vertex at the edge midpoint.
				if (j == 0)
					leftvertex = indices[i][2];
				else if (j == 1)
					leftvertex = indices[i][0];
				else
					leftvertex = indices[i][1];
				Vec3i neigh = neighborTris[i];
				bool found = false;
				for (int k = 0; k < 3; k++)
				{
					int kms = neigh[k];

					if (kms == -1)
						continue;

					int x = indices[kms][0], y= indices[kms][1], z = indices[kms][2];
					if ((indices[kms][0] == v0 || indices[kms][1] == v0 || indices[kms][2] == v0) && (indices[kms][0] == v1 || indices[kms][1] == v1 || indices[kms][2] == v1))
					{
						if ((x == v0 && y == v1) || (x == v1 && y == v0))
							rightvertex = z;
						else if ((y == v0 && z == v1) || (z == v0 && y == v1))
							rightvertex = x;
						else
							rightvertex = y;
						found = true;
						break;
					}
				}
				if (found){
					pos = ((3.0f * (positions[v0] + positions[v1])) + (positions[leftvertex] + positions[rightvertex])) / 8.0f;
					col = ((3.0f * (colors[v0] + colors[v1])) + (colors[leftvertex] + colors[rightvertex])) / 8.0f;
					norm = ((3.0f * (normals[v0] + normals[v1])) + (normals[leftvertex] + normals[rightvertex])) / 8.0f;
				}

				else {
					pos = 0.5f * (positions[v0] + positions[v1]);
					col = 0.5f * (colors[v0] + colors[v1]);
					norm = 0.5f * (normals[v0] + normals[v1]);
				}
				new_positions.push_back(pos);
				new_colors.push_back(col);
				new_normals.push_back(norm);

				// YOUR CODE HERE (R3):
				// Map the edge to the correct vertex index.
				new_vertices[edge] = new_positions.size() - 1;
				// This is just one line! Use new_vertices and the index of the just added position.
			}
		}
		// compute positions for even (old) vertices
		std::vector<bool> vertexComputed(new_positions.size(), false);

		for (int i = 0; i < (int)indices.size(); ++i) {
			for (int j = 0; j < 3; ++j) {
				int v0 = indices[i][j];

				// don't redo if this one is already done
				if (vertexComputed[v0])
					continue;

				vertexComputed[v0] = true;

				Vec3f pos, col, norm;
				std::vector<int> neighbors;
				// YOUR CODE HERE (R5): reposition the old vertices

				// This default implementation just passes the data through unchanged.
				// You need to replace these three lines with the loop over the 1-ring
				// around vertex v0, and compute the new position as a weighted average
				// of the other vertices as described in the handout.
				for (int k = 0; k < indices.size(); k++){
					for (int l = 0; l < 3; l++){
						if (indices[k][l] == v0){
							neighbors.push_back(indices[k][(l + 1) % 3]);
							neighbors.push_back(indices[k][(l + 2) % 3]);
						}
					}
				}
				sort(neighbors.begin(), neighbors.end());
				neighbors.erase(std::unique(neighbors.begin(),neighbors.end()), neighbors.end());

				int n = neighbors.size();
				float b;
				if (n>3)
					b = 3.0f / (8.0f * n);
				else if (n == 3)
					b = 3.0f / 16.0f;
				else
					b = 0.0f;
				Vec3f rightsum1, rightsum2, rightsum3;
				for (int k = 0; k < neighbors.size(); k++){
					rightsum1 += positions[neighbors[k]];
					rightsum2 += colors[neighbors[k]];
					rightsum3 += normals[neighbors[k]];
				}
				rightsum1 *= (float)b;
				rightsum2 *= (float)b;
				rightsum3 *= (float)b;
				float ks = 1.0f - (float)n*(float)b;
				rightsum1 += ks * positions[v0];
				rightsum2 += ks * colors[v0];
				rightsum3 += ks * normals[v0];
				pos = rightsum1;
				col = rightsum2;
				norm = rightsum3;

				new_positions[v0] = pos;
				new_colors[v0] = col;
				new_normals[v0] = norm;
			}
		}
		// and then, finally, regenerate topology
		// every triangle turns into four new ones
		std::vector<Vec3i> new_indices;
		new_indices.reserve(indices.size()*4);
		for (size_t i = 0; i < indices.size(); ++i) {
			Vec3i even = indices[i]; // start vertices of e_0, e_1, e_2

			// YOUR CODE HERE (R3):
			// fill in X and Y (it's the same for both)
			auto edge_a = std::make_pair(min(even.x, even.y), max(even.x, even.y));
			auto edge_b = std::make_pair(min(even.z, even.y), max(even.z, even.y));
			auto edge_c = std::make_pair(min(even.x, even.z), max(even.x, even.z));

			// The edges edge_a, edge_b and edge_c now define the vertex indices via new_vertices.
			// (The mapping is done in the loop above.)
			// The indices define the smaller triangle inside the indices defined by "even", in order.
			// Read the vertex indices out of new_vertices to build the small triangle "odd"
			int a, b, c;
			a = new_vertices[edge_a];
			b = new_vertices[edge_b];
			c = new_vertices[edge_c];
			// Vec3i odd = ...
			new_indices.push_back(Vec3i(a,b,c));
			new_indices.push_back(Vec3i(a, b, even[1]));
			new_indices.push_back(Vec3i(a,c, even[0]));
			new_indices.push_back(Vec3i(b, c, even[2]));
			// Then, construct the four smaller triangles from the surrounding big triangle  "even"
			// and the inner one, "odd". Push them to "new_indices".

			// NOTE: REMOVE the following line after you're done with the new triangles.
			// This just keeps the mesh intact and serves as an example on how to add new triangles.
			//new_indices.push_back( Vec3i( even[0], even[1], even[2] ) );
		}

		// ADD THESE LINES when R3 is finished. Replace the originals with the repositioned data.
		indices = std::move(new_indices);
		positions = std::move(new_positions);
		normals = std::move(new_normals);
		colors = std::move(new_colors);
		neighborTris.size();
}