Example #1
0
inline void load(
    Archive & ar,
    STD::vector<bool, Allocator> &t,
    const unsigned int /* file_version */
){
    // retrieve number of elements
    unsigned int count;
    ar >> BOOST_SERIALIZATION_NVP(count);
    t.clear();
    while(count-- > 0){
        bool i;
        ar >> boost::serialization::make_nvp("item", i);
        t.push_back(i);
    }
}
Example #2
0
 virtual bool DoItem(Item &Itm,int &Fd) override {
     Fd = -1;
     files.push_back(Itm.Name);
     return true;
 }
Example #3
0
int main()
{
  labels.push_back("LLT");
  labels.push_back("LDLT");
  labels.push_back("PartialPivLU");
  labels.push_back("FullPivLU");
  labels.push_back("HouseholderQR");
  labels.push_back("ColPivHouseholderQR");
  labels.push_back("CompleteOrthogonalDecomposition");
  labels.push_back("FullPivHouseholderQR");
  labels.push_back("JacobiSVD");
  labels.push_back("BDCSVD");

  for(int i=0; i<labels.size(); ++i)
    results[labels[i]].fill(-1);

  const int small = 8;
  sizes.push_back(Array2i(small,small));
  sizes.push_back(Array2i(100,100));
  sizes.push_back(Array2i(1000,1000));
  sizes.push_back(Array2i(4000,4000));
  sizes.push_back(Array2i(10000,small));
  sizes.push_back(Array2i(10000,100));
  sizes.push_back(Array2i(10000,1000));
  sizes.push_back(Array2i(10000,4000));

  using namespace std;

  for(int k=0; k<sizes.size(); ++k)
  {
    cout << sizes[k](0) << "x" << sizes[k](1) << "...\n";
    bench<float,Dynamic>(k,sizes[k](0),sizes[k](1));
  }

  cout.width(32);
  cout << "solver/size";
  cout << "  ";
  for(int k=0; k<sizes.size(); ++k)
  {
    std::stringstream ss;
    ss << sizes[k](0) << "x" << sizes[k](1);
    cout.width(10); cout << ss.str(); cout << " ";
  }
  cout << endl;


  for(int i=0; i<labels.size(); ++i)
  {
    cout.width(32); cout << labels[i]; cout << "  ";
    ArrayXf r = (results[labels[i]]*100000.f).floor()/100.f;
    for(int k=0; k<sizes.size(); ++k)
    {
      cout.width(10);
      if(r(k)>=1e6)  cout << "-";
      else           cout << r(k);
      cout << " ";
    }
    cout << endl;
  }

  // HTML output
  cout << "<table class=\"manual\">" << endl;
  cout << "<tr><th>solver/size</th>" << endl;
  for(int k=0; k<sizes.size(); ++k)
    cout << "  <th>" << sizes[k](0) << "x" << sizes[k](1) << "</th>";
  cout << "</tr>" << endl;
  for(int i=0; i<labels.size(); ++i)
  {
    cout << "<tr";
    if(i%2==1) cout << " class=\"alt\"";
    cout << "><td>" << labels[i] << "</td>";
    ArrayXf r = (results[labels[i]]*100000.f).floor()/100.f;
    for(int k=0; k<sizes.size(); ++k)
    {
      if(r(k)>=1e6) cout << "<td>-</td>";
      else
      {
        cout << "<td>" << r(k);
        if(i>0)
          cout << " (x" << numext::round(10.f*results[labels[i]](k)/results["LLT"](k))/10.f << ")";
        if(i<4 && sizes[k](0)!=sizes[k](1))
          cout << " <sup><a href=\"#note_ls\">*</a></sup>";
        cout << "</td>";
      }
    }
    cout << "</tr>" << endl;
  }
  cout << "</table>" << endl;

//   cout << "LLT                             (ms)  " << (results["LLT"]*1000.).format(fmt) << "\n";
//   cout << "LDLT                             (%)  " << (results["LDLT"]/results["LLT"]).format(fmt) << "\n";
//   cout << "PartialPivLU                     (%)  " << (results["PartialPivLU"]/results["LLT"]).format(fmt) << "\n";
//   cout << "FullPivLU                        (%)  " << (results["FullPivLU"]/results["LLT"]).format(fmt) << "\n";
//   cout << "HouseholderQR                    (%)  " << (results["HouseholderQR"]/results["LLT"]).format(fmt) << "\n";
//   cout << "ColPivHouseholderQR              (%)  " << (results["ColPivHouseholderQR"]/results["LLT"]).format(fmt) << "\n";
//   cout << "CompleteOrthogonalDecomposition  (%)  " << (results["CompleteOrthogonalDecomposition"]/results["LLT"]).format(fmt) << "\n";
//   cout << "FullPivHouseholderQR             (%)  " << (results["FullPivHouseholderQR"]/results["LLT"]).format(fmt) << "\n";
//   cout << "JacobiSVD                        (%)  " << (results["JacobiSVD"]/results["LLT"]).format(fmt) << "\n";
//   cout << "BDCSVD                           (%)  " << (results["BDCSVD"]/results["LLT"]).format(fmt) << "\n";
}
Example #4
0
void ReTriangulation::findIllegalEdge(std::vector<Vec3f>* point, std::vector<int>& pointOnEdge, std::vector<int>& pointOnFace, std::vector<Vec2i>& illegalEdge)
{
	Vec3f v1=(*point)[pointOnEdge[1]]-(*point)[pointOnEdge[0]]; v1.normalize();
	std::vector<float> dis;
	std::vector<int> pointOrder;
	for(int i=0;i<pointOnFace.size();i++)
	{
		float a=v1*((*point)[pointOnFace[i]]-(*point)[pointOnEdge[0]]);
		dis.push_back(a);
	}

	if(pointOnFace.size()==1)
	{
		illegalEdge.push_back(Vec2i(pointOnEdge[0], pointOnEdge[1]));
		return;
	}
	if(pointOnFace.size()==2)
	{
		pointOrder.resize(4);
		pointOrder[0]=pointOnEdge[0];
		if(dis[0]>dis[1])
		{
			pointOrder[1]=pointOnFace[1];
			pointOrder[2]=pointOnFace[0];
		}
		else
		{
			pointOrder[1]=pointOnFace[0];
			pointOrder[2]=pointOnFace[1];
		}
		pointOrder[3]=pointOnEdge[1];

		illegalEdge.push_back(Vec2i(pointOrder[0],pointOrder[3]));
		illegalEdge.push_back(Vec2i(pointOrder[0],pointOrder[2]));
		illegalEdge.push_back(Vec2i(pointOrder[1],pointOrder[3]));
		return;
	}
	if(pointOnFace.size()==3)
	{
		pointOrder.resize(5);
		pointOrder[0]=pointOnEdge[0];
		if(dis[0]<dis[1])
		{
			if(dis[0]<dis[2])
			{
				if(dis[1]<dis[2])
				{
					pointOrder[1]=pointOnFace[0];
					pointOrder[2]=pointOnFace[1];
					pointOrder[3]=pointOnFace[2];
				}
				else
				{
					pointOrder[1]=pointOnFace[0];
					pointOrder[2]=pointOnFace[2];
					pointOrder[3]=pointOnFace[1];
				}	
			}
			else
			{
				pointOrder[1]=pointOnFace[2];
				pointOrder[2]=pointOnFace[0];
				pointOrder[3]=pointOnFace[1];
			}
		}
		else
		{
			if(dis[0]<dis[2])
			{
				pointOrder[1]=pointOnFace[1];
				pointOrder[2]=pointOnFace[0];
				pointOrder[3]=pointOnFace[2];
			}
			else
			{
				if(dis[1]<dis[2])
				{
					pointOrder[1]=pointOnFace[1];
					pointOrder[2]=pointOnFace[2];
					pointOrder[3]=pointOnFace[0];
				}
				else
				{
					pointOrder[1]=pointOnFace[2];
					pointOrder[2]=pointOnFace[1];
					pointOrder[3]=pointOnFace[0];
				}	
			}
		}
		pointOrder[4]=pointOnEdge[1];

		illegalEdge.push_back(Vec2i(pointOrder[0],pointOrder[4]));
		illegalEdge.push_back(Vec2i(pointOrder[0],pointOrder[3]));
		illegalEdge.push_back(Vec2i(pointOrder[1],pointOrder[4]));
		illegalEdge.push_back(Vec2i(pointOrder[0],pointOrder[2]));
		illegalEdge.push_back(Vec2i(pointOrder[1],pointOrder[3]));
		illegalEdge.push_back(Vec2i(pointOrder[2],pointOrder[4]));
	}
}
Example #5
0
void AlnusPhyolgeticBranch::addChild(AlnusPhyolgeticBranch *child)
{
    mChildren.push_back(child);
}
Example #6
0
    void Registration::ICPFindCorrespondance(const Point3DSet* pRef, const Point3DSet* pOrigin, const MagicMath::HomoMatrix4* pTransInit,
            std::vector<int>& sampleIndex,  std::vector<int>& correspondIndex)
    {
        //DebugLog << "Registration::ICPFindCorrespondance" << std::endl;
        //float timeStart = MagicCore::ToolKit::GetTime();
        /*int dim = 3;
        int refNum = pRef->GetPointNumber();
        float* dataSet = new float[refNum * dim];
        for (int i = 0; i < refNum; i++)
        {
            MagicMath::Vector3 pos = pRef->GetPoint(i)->GetPosition();
            dataSet[dim * i + 0] = pos[0];
            dataSet[dim * i + 1] = pos[1];
            dataSet[dim * i + 2] = pos[2];
        }*/
        
        /*FLANNParameters searchPara;
        searchPara = DEFAULT_FLANN_PARAMETERS;
        searchPara.algorithm = FLANN_INDEX_KDTREE;
        searchPara.trees = 8;
        searchPara.log_level = FLANN_LOG_INFO;
	    searchPara.checks = 64;
        float speedup;
        flann_index_t indexId = flann_build_index(dataSet, refNum, dim, &speedup, &searchPara);
        DebugLog << "        Flann: " << MagicCore::ToolKit::GetTime() - timeStart << std::endl;*/
        int nn = 1;
        int dim = 3;
        int searchNum = sampleIndex.size();
        float* searchSet = new float[searchNum * dim];
        for (int i = 0; i < searchNum; i++)
        {
            MagicMath::Vector3 pos = pTransInit->TransformPoint( pOrigin->GetPoint(sampleIndex.at(i))->GetPosition() );
            searchSet[dim * i + 0] = pos[0];
            searchSet[dim * i + 1] = pos[1];
            searchSet[dim * i + 2] = pos[2];
        }
        int* pIndex = new int[searchNum * nn];
        float* pDist = new float[searchNum * nn];
        flann_find_nearest_neighbors_index(mFlannIndex, searchSet, searchNum, pIndex, pDist, nn, &mSearchPara);
        //flann_free_index(indexId, &searchPara);
        //delete []dataSet;
        delete []searchSet;
        

        //delete wrong correspondance
        float distThre = 500.f;
        float norThre = 0.1f; //cos(85);
        std::vector<int> sampleIndexBak = sampleIndex;
        sampleIndex.clear();
        correspondIndex.clear();
        for (int i = 0; i < searchNum; i++)
        {
            if (pDist[i] > distThre)
            {
        //        DebugLog << "Large dist: " << pDist[i] << std::endl;
                continue;
            }
            float norDist = pRef->GetPoint(pIndex[i])->GetNormal() * (pTransInit->RotateVector( pOrigin->GetPoint(sampleIndexBak.at(i))->GetNormal() ));
            if (norDist < norThre || norDist > 1.0)
            {
         //       DebugLog << "Large Nor: " << norDist << std::endl;
                continue;
            }
            sampleIndex.push_back(sampleIndexBak.at(i));
            correspondIndex.push_back(pIndex[i]);
        }
        //DebugLog << "Sample Number: " << sampleIndex.size() << std::endl;
        delete []pIndex;
        delete []pDist;
    }
/**
 * Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
 *
 * - Arguments are delimited with whitespace
 * - Extra whitespace at the beginning and end and between arguments will be ignored
 * - Text can be "double" or 'single' quoted
 * - The backslash \c \ is used as escape character
 *   - Outside quotes, any character can be escaped
 *   - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
 *   - Within single quotes, no escaping is possible and no special interpretation takes place
 *
 * @param[out]   args        Parsed arguments will be appended to this list
 * @param[in]    strCommand  Command line to split
 */
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
    enum CmdParseState
    {
        STATE_EATING_SPACES,
        STATE_ARGUMENT,
        STATE_SINGLEQUOTED,
        STATE_DOUBLEQUOTED,
        STATE_ESCAPE_OUTER,
        STATE_ESCAPE_DOUBLEQUOTED
    } state = STATE_EATING_SPACES;
    std::string curarg;
    foreach(char ch, strCommand)
    {
        switch(state)
        {
        case STATE_ARGUMENT: // In or after argument
        case STATE_EATING_SPACES: // Handle runs of whitespace
            switch(ch)
            {
            case '"': state = STATE_DOUBLEQUOTED; break;
            case '\'': state = STATE_SINGLEQUOTED; break;
            case '\\': state = STATE_ESCAPE_OUTER; break;
            case ' ': case '\n': case '\t':
                if(state == STATE_ARGUMENT) // Space ends argument
                {
                    args.push_back(curarg);
                    curarg.clear();
                }
                state = STATE_EATING_SPACES;
                break;
            default: curarg += ch; state = STATE_ARGUMENT;
            }
            break;
        case STATE_SINGLEQUOTED: // Single-quoted string
            switch(ch)
            {
            case '\'': state = STATE_ARGUMENT; break;
            default: curarg += ch;
            }
            break;
        case STATE_DOUBLEQUOTED: // Double-quoted string
            switch(ch)
            {
            case '"': state = STATE_ARGUMENT; break;
            case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
            default: curarg += ch;
            }
            break;
        case STATE_ESCAPE_OUTER: // '\' outside quotes
            curarg += ch; state = STATE_ARGUMENT;
            break;
        case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
            if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
            curarg += ch; state = STATE_DOUBLEQUOTED;
            break;
        }
    }
    switch(state) // final state
    {
    case STATE_EATING_SPACES:
        return true;
    case STATE_ARGUMENT:
        args.push_back(curarg);
        return true;
    default: // ERROR to end in one of the other states
        return false;
    }
}
/**
 * Function TestForExistingItem
 * test if aItem exists somewhere in lists of items
 * This is a function used by PutDataInPreviousState to be sure an item was not deleted
 * since an undo or redo.
 * This could be possible:
 *   - if a call to SaveCopyInUndoList was forgotten in Pcbnew
 *   - in zones outlines, when a change in one zone merges this zone with an other
 * This function avoids a Pcbnew crash
 * Before using this function to test existence of items,
 * it must be called with aItem = NULL to prepare the list
 * @param aPcb = board to test
 * @param aItem = item to find
 *              = NULL to build the list of existing items
 */
static bool TestForExistingItem( BOARD* aPcb, BOARD_ITEM* aItem )
{
    static std::vector<BOARD_ITEM*> itemsList;

    if( aItem == NULL ) // Build list
    {
        // Count items to store in itemsList:
        int icnt = 0;
        BOARD_ITEM* item;

        // Count tracks:
        for( item = aPcb->m_Track; item != NULL; item = item->Next() )
            icnt++;

        // Count modules:
        for( item = aPcb->m_Modules; item != NULL; item = item->Next() )
            icnt++;

        // Count drawings
        for( item = aPcb->m_Drawings; item != NULL; item = item->Next() )
            icnt++;

        // Count zones outlines
        icnt +=  aPcb->GetAreaCount();

        // Count zones segm (now obsolete):
        for( item = aPcb->m_Zone; item != NULL; item = item->Next() )
             icnt++;

        // Build candidate list:
        itemsList.clear();
        itemsList.reserve(icnt);

        // Store items in list:
        // Append tracks:
        for( item = aPcb->m_Track; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Append modules:
        for( item = aPcb->m_Modules; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Append drawings
        for( item = aPcb->m_Drawings; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Append zones outlines
        for( int ii = 0; ii < aPcb->GetAreaCount(); ii++ )
            itemsList.push_back( aPcb->GetArea( ii ) );

        // Append zones segm:
        for( item = aPcb->m_Zone; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Sort list
        std::sort( itemsList.begin(), itemsList.end() );
        return false;
    }

    // search in list:
    return std::binary_search( itemsList.begin(), itemsList.end(), aItem );
}
Example #9
0
void extractNegPatches(std::vector<CNegDataset> &negSet,
                       std::vector<CNegPatch> &negPatch,
                       CConfig conf){
    cv::Rect tempRect;

    std::vector<CNegPatch> tNegPatch(0);//, posPatch(0);
    nCk nck;
    int negPatchNum;

    negPatch.clear();

    tempRect.width  = conf.p_width;
    tempRect.height = conf.p_height;

    // extract negative patch
    std::cout << negSet.size() << std::endl;
    std::cout << negSet.at(0).img.at(0)->cols << std::endl;
    std::cout << negSet.at(0).img.at(0)->rows << std::endl;
    for(int i = 0; i < negSet.size(); ++i){
        for(int j = 0; j < negSet.at(i).img.at(0)->cols - conf.p_width; j += conf.stride){
            for(int k = 0; k < negSet.at(i).img.at(0)->rows - conf.p_height; k += conf.stride){

                tempRect.x = j;
                tempRect.y = k;
                int pix = 0;

                // detect negative patch
//                if(conf.learningMode != 2 && negSet.at(i).img.at(1)->at<ushort>(k + (conf.p_height / 2) + 1, j + (conf.p_width / 2) + 1 ) != 0){
//                    cv::Mat roi;
//                    roi = (*negSet.at(i).img.at(1))(cv::Rect(j, k, conf.p_width, conf.p_height));
//                    pix = calcSumOfDepth(roi,conf);
//                }

                //tPatch.setPatch(temp, negImage.at(i));
                //if(conf.learningMode == 2 || pix > 0){
                    CNegPatch negTemp(&negSet.at(i),tempRect);
                    tNegPatch.push_back(negTemp);
                //}
            }//x
        }//y
    } // every image

    // choose negative patch randamly
    negPatchNum = conf.patchRatio * conf.pnRatio;
    //std::cout << "pos patch num : " << posPatch.size() << " neg patch num : " << negPatchNum << std::endl;

    if(negPatchNum < tNegPatch.size()){
        std::set<int> chosenPatch = nck.generate(tNegPatch.size(), negPatchNum);//totalPatchNum * conf.patchRatio);
        std::set<int>::iterator ite = chosenPatch.begin();

        while(ite != chosenPatch.end()){
            negPatch.push_back(tNegPatch.at(*ite));
            ite++;
        }
    }else{
        std::cout << "only " << tNegPatch.size() << " pathes extracted from negative images" << std::endl;
        std::cout << "can't extract enogh negative patch please set pnratio more low!" << std::endl;
        exit(-1);
    }

//    patches.push_back(posPatch);
//    patches.push_back(negPatch);
}
Example #10
0
void loadTrainPosFile(CConfig conf, std::vector<CPosDataset> &posSet)
{
    std::string traindatafilepath = conf.trainpath + PATH_SEP +  conf.traindatafile;
    int n_folders;
    int n_files;
    std::vector<std::string> trainimagefolder;
    std::vector<CPosDataset> tempDataSet;
    std::string trainDataListPath;
    int dataSetNum;
    CClassDatabase database;
    cv::Point tempPoint;
    nCk nck;

    posSet.clear();

    //read train data folder list
    std::ifstream in(traindatafilepath.c_str());
    if(!in.is_open()){
        std::cout << "train data floder list is not found!" << std::endl;
        exit(1);
    }

    // read train pos folder
    in >> n_folders;
    std::cout << "number of training data folders : " << n_folders << std::endl;
    trainimagefolder.resize(n_folders);
    for(int i = 0;i < n_folders; ++i)
        in >> trainimagefolder.at(i);
    std::cout << trainimagefolder.at(0) << std::endl;

    // close train pos data folder list
    in.close();

    std::cout << "train folders lists : " << std::endl;
    //read train file name and grand truth from file
    tempDataSet.clear();
    for(int i = 0;i < n_folders; ++i){
        trainDataListPath
                = conf.trainpath + PATH_SEP + trainimagefolder.at(i) + PATH_SEP + conf.traindatalist;

        std::cout << trainDataListPath << std::endl;
        std::string imageFilePath
                = conf.trainpath + PATH_SEP + trainimagefolder.at(i) + PATH_SEP;

        std::ifstream trainDataList(trainDataListPath.c_str());
        if(!trainDataList.is_open()){
            std::cout << "can't read " << trainDataListPath << std::endl;
            exit(1);
        }

        trainDataList >> n_files;

        for(int j = 0;j < n_files; ++j){
            CPosDataset posTemp;
            std::string nameTemp;


            //            posTemp.angles.clear();
            //            posTemp.centerPoint.clear();

            //read file names
            trainDataList >> nameTemp;
            posTemp.setRgbImagePath(imageFilePath + nameTemp);
	    

            trainDataList >> nameTemp;
            posTemp.setDepthImagePath(imageFilePath + nameTemp);

            trainDataList >> nameTemp;// dummy

            //read class name
            std::string tempClassName;
            trainDataList >> tempClassName;
            //temp.className.push_back(tempClassName);
            posTemp.setClassName(tempClassName);

            // read image size
            cv::Mat tempImage = cv::imread(posTemp.getRgbImagePath(),3);
            cv::Size tempSize = cv::Size(tempImage.cols, tempImage.rows);

            // set center point
            tempPoint = cv::Point(tempImage.cols / 2, tempImage.rows / 2);
            posTemp.setCenterPoint(tempPoint);

            // registre class param to class database
            database.add(posTemp.getParam()->getClassName(), tempSize, 0);

            //read angle grand truth
            double tempAngle;
            trainDataList >> tempAngle;
            posTemp.setAngle(tempAngle);

            tempDataSet.push_back(posTemp);
        }

        trainDataList.close();
    }

    dataSetNum = tempDataSet.size();
    int dataOffset = 0;
    database.show();
    for(int j = 0;j < database.vNode.size(); j++){
        std::set<int> chosenData = nck.generate(database.vNode.at(j).instances, conf.imagePerTree);

        std::set<int>::iterator ite = chosenData.begin();

        while(ite != chosenData.end()){
            posSet.push_back(tempDataSet.at(*ite + dataOffset));
            //std::cout << tempDataSet.at(*ite + dataOffset).getRgbImagePath() << std::endl;
            ite++;
        }
        dataOffset += database.vNode.at(j).instances;
    }


    //    std::cout << "show chosen dataset" << std::endl;
    //    for(int i = 0; i < dataSet.size(); ++i){
    //        dataSet.at(i).showDataset();
    //    }
}
Example #11
0
// extract patch from images
// !!!!!!coution!!!!!!!
// this function is use for negatime mode!!!!!
void extractPosPatches(std::vector<CPosDataset> &posSet,
                       std::vector<CPosPatch> &posPatch,
                       CConfig conf,
                       const int treeNum,
                       const CClassDatabase &classDatabase){
    cv::Rect tempRect;

    std::vector<CPosPatch> tPosPatch(0);//, posPatch(0);
    std::vector<std::vector<CPosPatch> > patchPerClass(classDatabase.vNode.size());
    int pixNum;
    nCk nck;
    int classNum = 0;
    cv::Mat roi;

    posPatch.clear();

    tempRect.width  = conf.p_width;
    tempRect.height = conf.p_height;

    std::cout << "image num is " << posSet.size();

    std::cout << "extracting patch from image" << std::endl;
    for(int l = 0;l < posSet.size(); ++l){
        std::cout << posSet.at(l).getRgbImagePath() << std::endl;
//                    cv::namedWindow("test");
//                    cv::imshow("test", *posSet.at(l).img.at(0));
//                    cv::waitKey(0);
//                    cv::destroyWindow("test");
        for(int j = 0; j < posSet.at(l).img.at(0)->cols - conf.p_width; j += conf.stride){
            for(int k = 0; k < posSet.at(l).img.at(0)->rows - conf.p_height; k += conf.stride){
                tempRect.x = j;
                tempRect.y = k;
                pixNum = 0;
                int centerDepthFlag = 1;

                // detect negative patch
//                if(conf.learningMode != 2 && posSet.at(l).img.at(1)->at<ushort>(k + (conf.p_height / 2) + 1, j + (conf.p_width / 2) + 1 ) != 0){

//                    roi = (*posSet.at(l).img.at(1))(cv::Rect(j, k, conf.p_width, conf.p_height));
//                    pixNum = calcSumOfDepth(roi,conf);
//                }
//                    for(int m = j; m < j + conf.p_width; ++m){
//                        for(int n = k; n < k + conf.p_height; ++n){
//                            if(posSet.at(l).img.at(1)->at<ushort>(k + (conf.p_height / 2) + 1, j + (conf.p_width / 2) + 1 ) != 0)
//                                pixNum += (int)(posSet.at(l).img.at(1)->at<ushort>(n, m));
//                        }
//                    }

                // set patch class
                classNum = classDatabase.search(posSet.at(l).getParam()->getClassName());//dataSet.at(l).className.at(0));
                if(classNum == -1){
                    std::cout << "class not found!" << std::endl;
                    exit(-1);
                }

                //tPatch.setPatch(temp, image.at(l), dataSet.at(l), classNum);


                CPosPatch posTemp(&posSet.at(l),tempRect);
                //if (conf.learningMode == 2){// || pixNum > 0){
                    tPosPatch.push_back(posTemp);
                    patchPerClass.at(classNum).push_back(posTemp);

                //} // if
            }//x
        }//y
    }//allimages

    for(int w = 0; w < patchPerClass.size(); ++w){
        std::cout << patchPerClass.at(w).size() << " ";
    }
    std::cout << std::endl;

    std::vector<int> patchNum(patchPerClass.size(),conf.patchRatio);

    for(int i = 0; i < patchPerClass.size(); ++i){
        if(i == treeNum % patchPerClass.size())
            patchNum.at(i) = conf.patchRatio;
        else
            patchNum.at(i) = conf.patchRatio * conf.acPatchRatio;
    }

    for(int w = 0; w < patchPerClass.size(); ++w){
        std::cout << patchPerClass.at(w).size() << " ";
    }

    // choose patch from each image
    for(int i = 0; i < patchPerClass.size(); ++i){
        if(patchPerClass.at(i).size() > conf.patchRatio){

            std::set<int> chosenPatch = nck.generate(patchPerClass.at(i).size(),patchNum.at(i));// conf.patchRatio);//totalPatchNum * conf.patchRatio);
            std::set<int>::iterator ite = chosenPatch.begin();

            while(ite != chosenPatch.end()){
                //std::cout << "this is for debug ite is " << tPosPatch.at(*ite).center << std::endl;
                //std::cout <<posPatch.at(i)
                //std::cout << patchPerClass.at(i).at(*ite).getRgbImageFilePath() << std::endl;
                posPatch.push_back(patchPerClass.at(i).at(*ite));
                ite++;
            }
        }else{
//                std::cout << classNum << std::endl;
////            cv::namedWindow("test");
////            cv::imshow("test", *posSet.at(0).img.at(0));
////            cv::waitKey(0);
////            cv::destroyWindow("test");
//            //std::cout << *posSet.at(1).img.at(1) << std::endl;
//                std::cout << patchPerClass.size() << std::endl;

            std::cout << "can't extruct enough patch" << std::endl;
            //exit(-1);
        }
    }
    return;
}
Example #12
0
 static void exec(std::vector<unsigned> &v, std::vector<GLenum> &e)
 {
     v.push_back(createShadowSampler());
     e.push_back(GL_TEXTURE_2D_ARRAY);
     CreateSamplers<tp...>::exec(v, e);
 }
Example #13
0
 static void exec(std::vector<unsigned> &v, std::vector<GLenum> &e)
 {
     v.push_back(createBilinearSampler());
     e.push_back(GL_TEXTURE_3D);
     CreateSamplers<tp...>::exec(v, e);
 }
Example #14
0
 ShaderHelperSingleton()
 {
     CleanTable.push_back(this->kill);
 }
Example #15
0
 void AssignUniforms_impl(const char* name, U... rest)
 {
     uniforms.push_back(glGetUniformLocation(Program, name));
     AssignUniforms_impl(rest...);
 }
void IfcConstructionProductResourceType::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
	IfcConstructionResourceType::getAttributes( vec_attributes );
	vec_attributes.push_back( std::make_pair( "PredefinedType", m_PredefinedType ) );
}
Example #17
0
 void add_rekt(RectInfo child) {
     children.push_back(child);
 }
Example #18
0
int readConfigFiles(void)
{
    FILE *fd = nullptr;
    const char *fname;
    
    //first read sensor params file
    //try if file exists and try to open for reading
    fname = "nodeparams.cfg";
    if( access( fname, F_OK ) != -1 )
    {
        fd = fopen(fname, "r");
        if (fd != NULL)
        {
            numNodes = 0;
            uchar listik[MAX_NODES];

            char *line = NULL;
            size_t L = 0;
            ssize_t read;
            
            while ((read = getline(&line, &L, fd)) != -1) {
                //count colons, if there is MAX_SENSORS+1 of them, then it is node line,
                //else it is error
                int colons = 0;
                for (int xxx=0; xxx < read; xxx++) { if (line[xxx] == ':') colons++; }
                if (colons == MAX_SENSORS+1)
                {
                    char **pole;
                    int poleLen;
                    poleLen = explode(line, ":", &pole);
                    int node = atoi(pole[0]);
                    int numS = atoi(pole[1]);
                    
                    nodeValues[node] = (NODE_VALUES_T*)malloc(sizeof(NODE_VALUES_T) );
                    memset((void*)nodeValues[node], 0, sizeof(NODE_VALUES_T) );
                    nodeValues[node]->node = node;
                    nodeValues[node]->num_sensors = numS;
                    nodeValues[node]->low_power_alive = LOW_POWER_ALIVE_TIMEOUT; //for all sensors (even not the low powered)
                    
                    for (int xxx=0; xxx < numS; xxx++)
                    {
                        uchar sType = atoi(pole[xxx+2]);
                        nodeValues[node]->sensor_types[xxx] = sType;
                        //determine, if it is low power node
                        if (sType >= LOW_POWER_NODE_SIGN) nodeValues[node]->is_low_power = 1; 
                    }
                    
                    freeArrayOfPointers((void***)&pole, poleLen);
                    
                    nodeValues[node]->sensors = (volatile SENSOR_VAL_T**) malloc( sizeof(SENSOR_VAL_T*) * numS);  //alloc array of pointers to sensors values
                    for (int x = 0; x < numS; x++ ) //alloc sensor val structures
                    {
                        nodeValues[node]->sensors[x] = (SENSOR_VAL_T*) malloc( sizeof(SENSOR_VAL_T) );
                        memset((void*)nodeValues[node]->sensors[x], 255, sizeof(SENSOR_VAL_T) );
                    }
                    
                    nodeValues[node]->sensor_names = (volatile uchar**) malloc( sizeof(uchar*) * MAX_SENSORS); //alloc array of
                    memset((void*)nodeValues[node]->sensor_names, 0, sizeof(char*) * MAX_SENSORS);
                    for (int xxx=0; xxx < numS; xxx++)
                    {
                        size_t LL = 0;
                        ssize_t r = 0;
                        volatile uchar* volatile lin = NULL;
                        
                        r = getline((char**)&lin, &LL, fd);
                        //strip \r\n from end of line
                        lin[r-1] = 0;
                        lin[r-2] = 0;
                        
                        nodeValues[node]->sensor_names[xxx] = lin;
                        //do not free *lin because we want to *lin remain allocated in sensor names
                    }

                    listik[numNodes] = (uchar)node;
                    numNodes++;

                }
                
                free(line);
                line = NULL;
                L = 0;
            }
            fclose(fd);
            
            //copy only valid values from temporary list to normal list (clearing the original list before)
            if (numNodes > 0) //only if there are nodes
            {
                nodeList = (uchar *) malloc(numNodes);
                memcpy((void*)nodeList, listik, numNodes);
            }
        }
        else
        {
            printf("Cannot open %s for reading\n", fname);
        }
    }
    else
    {
        printf("File %s does not exist\n", fname);
    }
    
    //second read sensor intervals file
    //try if file exists and try to open for reading
    fname = "intervals.cfg";
    if( access( fname, F_OK ) != -1 )
    {
        fd = fopen(fname, "r");
        if (fd != NULL)
        {
            char *line = NULL;
            size_t L = 0;
            ssize_t read;
            
            while ((read = getline(&line, &L, fd)) != -1) {
                //count commas ",", if there is MAX_SENSORS of them, then it is node line,
                //else it is error
                int commas = 0;
                for (int xxx=0; xxx < read; xxx++) { if (line[xxx] == ',') commas++; }
                if (commas == MAX_SENSORS)
                {
                    char **pole;
                    int poleLen;
                    poleLen = explode(line, ":", &pole);
                    int node = atoi(pole[0]);

                    //node array is not initialised
                    sensorIntervals[node] = (SENSOR_INTERVAL_REC *) malloc(sizeof(SENSOR_INTERVAL_REC) * MAX_SENSORS);
                    memset((void*)sensorIntervals[node], 0, sizeof(SENSOR_INTERVAL_REC) * MAX_SENSORS);
                    
                    char **pole1;
                    int poleLen1;
                    
                    for (int x = 0; x < MAX_SENSORS; x++)
                    {
                        poleLen1 = explode(pole[x+1], ",", &pole1);
                        int interval = atoi(pole1[0]);
                        
                        //two possibilities - interval is 0 - reading disabled (dont push to vector)
                        //or bigger than 0 - interval enabled (push to vector)
                        if (interval > 0)
                        {
                            sensorIntervals[node][x].interval = interval;
                            sensorIntervals[node][x].countDown = 1;
                            //this 1 in countdown will invoke real read of value, because it was read never before
                            //and we dont wanna wait whole interval before the value will be available

                            //prepare new record to be pushed
                            SENSOR_INTERVAL_VECT_REC rec;
                            rec.nodeNum = node;
                            rec.sensorNum = x;
                            
                            //add record also to interval vector
                            intervalVect.push_back(rec);
                        }
                        else
                        {
                            sensorIntervals[node][x].interval = 0;
                            sensorIntervals[node][x].countDown = 0;
                        }
                        
                        freeArrayOfPointers((void***)&pole1, poleLen1);
                    }
                    
                    freeArrayOfPointers((void***)&pole, poleLen);
                }
            }
        }
        else
        {
            printf("Cannot open %s for reading\n", fname);
        }
    }
    else
    {
        printf("File %s does not exist\n", fname);
    }

    return 1;
}
Example #19
0
	void addObserver(Observer& obs)
	{
		observer_.push_back(&obs);
	}
Example #20
0
 regex_token_iterator_implementation(const regex_type* p, BidirectionalIterator last, int sub, match_flag_type f)
    : end(last), re(*p), flags(f){ subs.push_back(sub); }
Example #21
0
  void testInitialzation(const Teuchos::RCP<Teuchos::ParameterList>& ipb,
			 std::vector<panzer::BC>& bcs)
  {
    // Physics block
    Teuchos::ParameterList& physics_block = ipb->sublist("test physics");
    {
      Teuchos::ParameterList& p = physics_block.sublist("a");
      p.set("Type","Energy");
      p.set("Prefix","");
      p.set("Model ID","solid");
      p.set("Basis Type","HGrad");
      p.set("Basis Order",2);
      p.set("Integration Order",1);
    }
    {
      Teuchos::ParameterList& p = physics_block.sublist("b");
      p.set("Type","Energy");
      p.set("Prefix","ION_");
      p.set("Model ID","ion solid");
      p.set("Basis Type","HGrad");
      p.set("Basis Order",1);
      p.set("Integration Order",1);
    }

    {
      std::size_t bc_id = 0;
      panzer::BCType neumann = BCT_Dirichlet;
      std::string sideset_id = "left";
      std::string element_block_id = "eblock-0_0";
      std::string dof_name = "UX";
      std::string strategy = "Constant";
      double value = 5.0;
      Teuchos::ParameterList p;
      p.set("Value",value);
      panzer::BC bc(bc_id, neumann, sideset_id, element_block_id, dof_name, 
		    strategy, p);
      bcs.push_back(bc);
    }    
    {
      std::size_t bc_id = 0;
      panzer::BCType neumann = BCT_Dirichlet;
      std::string sideset_id = "right";
      std::string element_block_id = "eblock-1_0";
      std::string dof_name = "UX";
      std::string strategy = "Constant";
      double value = 5.0;
      Teuchos::ParameterList p;
      p.set("Value",value);
      panzer::BC bc(bc_id, neumann, sideset_id, element_block_id, dof_name, 
		    strategy, p);
      bcs.push_back(bc);
    }   
    {
      std::size_t bc_id = 0;
      panzer::BCType neumann = BCT_Dirichlet;
      std::string sideset_id = "top";
      std::string element_block_id = "eblock-1_0";
      std::string dof_name = "UX";
      std::string strategy = "Constant";
      double value = 5.0;
      Teuchos::ParameterList p;
      p.set("Value",value);
      panzer::BC bc(bc_id, neumann, sideset_id, element_block_id, dof_name, 
		    strategy, p);
      bcs.push_back(bc);
    }
  }
void StoreNonOverlappingIndices(std::vector<T_MatchPos> &lis, 
    std::vector<T_MatchPos> &noOvpLis) {
	unsigned int i;

	//
	// Greedily add lis matches according to weight.  A match may be added
	// as long as it does not overlap with any other matches.
	//
 
	// do nothing on empty lists
	if (lis.empty()) return;

	//
	// First build a list of matches sorted by weight.
	SortMatchPosListByWeight(lis);

	//
	// The first match is guaranteed to not overlap.
	noOvpLis.push_back(lis[0]);

	//
	// Nothing is overlapping, and everything is sorted when there is 
	// just one value.
	if (lis.size() == 1) return;

	//
	// Next, add matches as long as they do not overlap.
	for (i = 1; i < lis.size(); i++ ){
		VectorIndex j;
		int lts = lis[i].t;
		int lte = lis[i].t + lis[i].GetLength();
		int lqs = lis[i].q;
		int lqe = lis[i].q + lis[i].GetLength();

		int ovpFound = 0;
		for (j =0; j < noOvpLis.size(); j++ ){
			int tIntvStart = noOvpLis[j].t;
			int tIntvEnd   = noOvpLis[j].t + noOvpLis[j].GetLength();
			int qIntvStart = noOvpLis[j].q;
			int qIntvEnd   = noOvpLis[j].q + noOvpLis[j].GetLength();
			if ((lts >= tIntvStart and lts < tIntvEnd) or 
					(lte >  tIntvStart and lte <= tIntvEnd) or
					(lqs >= qIntvStart and lqs < qIntvEnd) or
					(lqe >  qIntvStart and lqe <= qIntvEnd)) {
				ovpFound = 1;
				break;
			}
		}
		if (!ovpFound) {
			noOvpLis.push_back(lis[i]);
		}
	}
	
	//
	// Now, the matches are found in order of size, but they need to
	// be stored in order of text.
	//
	SortMatchPosList(noOvpLis);

	//
	// The match pos list was sorted in order of weight. 
	// Just in case it causes problems down the line, re-sort it 
	// according to query pos.
	//
	lis = noOvpLis;
	SortMatchPosList(lis);
}
Example #23
0
void pydynd::deduce_pyseq_shape_using_dtype(PyObject *obj, const ndt::type &tp,
                                            std::vector<intptr_t> &shape,
                                            bool initial_pass,
                                            size_t current_axis)
{
  bool is_sequence = (PySequence_Check(obj) != 0 && !PyUnicode_Check(obj) &&
                      !PyDict_Check(obj));
#if PY_VERSION_HEX < 0x03000000
  is_sequence = is_sequence && !PyString_Check(obj);
#endif
  Py_ssize_t size = 0;
  if (is_sequence) {
    size = PySequence_Size(obj);
    if (size == -1 && PyErr_Occurred()) {
      PyErr_Clear();
      is_sequence = false;
    }
  }

  if (is_sequence) {
    if (shape.size() == current_axis) {
      if (initial_pass) {
        shape.push_back(size);
      }
      else if (tp.get_id() == struct_id || tp.get_id() == tuple_id) {
        // Signal that this is a dimension which is sometimes scalar, to allow
        // for
        // raggedness in the struct type's fields
        shape.push_back(pydynd_shape_deduction_ragged);
      }
      else {
        throw runtime_error(
            "dynd array doesn't support dimensions"
            " which are sometimes scalars and sometimes arrays");
      }
    }
    else {
      if (shape[current_axis] != size && shape[current_axis] >= 0) {
        // A variable-sized dimension
        shape[current_axis] = pydynd_shape_deduction_var;
      }
    }

    for (Py_ssize_t i = 0; i < size; ++i) {
      pyobject_ownref item(PySequence_GetItem(obj, i));
      deduce_pyseq_shape_using_dtype(item.get(), tp, shape,
                                     i == 0 && initial_pass, current_axis + 1);
    }
  }
  else {
    if (PyDict_Check(obj) && tp.get_id() == struct_id) {
      if (shape.size() == current_axis) {
        shape.push_back(pydynd_shape_deduction_dict);
      }
      else if (shape[current_axis] != pydynd_shape_deduction_ragged) {
        shape[current_axis] = pydynd_shape_deduction_dict;
      }
    }
    else if (shape.size() != current_axis) {
      if (tp.get_id() == struct_id || tp.get_id() == tuple_id) {
        shape[current_axis] = pydynd_shape_deduction_ragged;
      }
      else {
        throw runtime_error(
            "dynd array doesn't support dimensions"
            " which are sometimes scalars and sometimes arrays");
      }
    }
  }
}
Example #24
0
void WiimoteScanner::FindWiimotes(std::vector<Wiimote*> & found_wiimotes, Wiimote* & found_board)
{
	// supposedly 1.28 seconds
	int const wait_len = 1;

	int const max_infos = 255;
	inquiry_info scan_infos[max_infos] = {};
	auto* scan_infos_ptr = scan_infos;
	found_board = nullptr;

	// Scan for Bluetooth devices
	int const found_devices = hci_inquiry(device_id, wait_len, max_infos, nullptr, &scan_infos_ptr, IREQ_CACHE_FLUSH);
	if (found_devices < 0)
	{
		ERROR_LOG(WIIMOTE, "Error searching for Bluetooth devices.");
		return;
	}

	DEBUG_LOG(WIIMOTE, "Found %i Bluetooth device(s).", found_devices);

	// Display discovered devices
	for (int i = 0; i < found_devices; ++i)
	{
		ERROR_LOG(WIIMOTE, "found a device...");

		// BT names are a maximum of 248 bytes apparently
		char name[255] = {};
		if (hci_read_remote_name(device_sock, &scan_infos[i].bdaddr, sizeof(name), name, 1000) < 0)
		{
			ERROR_LOG(WIIMOTE, "name request failed");
			continue;
		}

		ERROR_LOG(WIIMOTE, "device name %s", name);
		if (IsValidBluetoothName(name))
		{
			bool new_wiimote = true;

			// TODO: do this

			// Determine if this Wiimote has already been found.
			//for (int j = 0; j < MAX_WIIMOTES && new_wiimote; ++j)
			//{
			//	if (wm[j] && bacmp(&scan_infos[i].bdaddr,&wm[j]->bdaddr) == 0)
			//		new_wiimote = false;
			//}

			if (new_wiimote)
			{
				// Found a new device
				char bdaddr_str[18] = {};
				ba2str(&scan_infos[i].bdaddr, bdaddr_str);

				Wiimote* wm = new WiimoteLinux(scan_infos[i].bdaddr);
				if (IsBalanceBoardName(name))
				{
					found_board = wm;
					NOTICE_LOG(WIIMOTE, "Found balance board (%s).", bdaddr_str);
				}
				else
				{
					found_wiimotes.push_back(wm);
					NOTICE_LOG(WIIMOTE, "Found Wiimote (%s).", bdaddr_str);
				}
			}
		}
	}

}
Example #25
0
void ReTriangulation::delaunayTriangulation(std::vector<Vec3f>* point, Vec3i face, Vec2i edge, std::vector<int>& idx, int pointOnEdge, std::vector<int>& pointOnFace, std::vector<Vec3i>& triangles)
{
	// 1. 순서대로 point 정렬
	std::vector<int> pointIdx;
	std::vector<float> dis;
	pointIdx.push_back(pointOnEdge);
	dis.push_back(0.0);
	for(int i=0;i<pointOnFace.size();i++)
	{
		float _dis=((*point)[pointOnEdge]-(*point)[pointOnFace[i]]).norm();
		dis.push_back(_dis);
		pointIdx.push_back(pointOnFace[i]);
		for(int j=0;j<dis.size();j++)
		{
			if(dis[j]>_dis)
			{
				for(int k=dis.size()-1;k>j;k--)
				{
					dis[k]=dis[k-1];
					pointIdx[k]=pointIdx[k-1];
				}
				dis[j]=_dis;
				pointIdx[j]=pointOnFace[i];
				break;
			}
		}
	}

	// 2. Intersection 된 edge에 포함되지 않는 point
	int _pointIdx;
	for(int i=0;i<3;i++)
	{
		if(!((face[i]==edge[0])||(face[i]==edge[1])))
			_pointIdx=face[i];
	}

	// 2. Triangulation
	for(int i=0;i<pointIdx.size()-1;i++)
	{
		triangles.push_back(Vec3i(edge[0], pointIdx[i], pointIdx[i+1]));
		triangles.push_back(Vec3i(edge[1], pointIdx[i], pointIdx[i+1]));
	}
	triangles.push_back(Vec3i(edge[0], pointIdx[pointIdx.size()-1], _pointIdx));
	triangles.push_back(Vec3i(edge[1], pointIdx[pointIdx.size()-1], _pointIdx));

	for(int i=0;i<idx.size();i++)
	{
		for(int j=0;j<triangles.size();j++)
		{
			for(int k=0;k<3;k++)
			{
				if(triangles[j][k]==idx[i])
				{
					triangles[j]=triangles[triangles.size()-1];
					triangles.pop_back();
					j--;
					break;
				}
			}
		}
	}
}
Example #26
0
void exn_path(std::vector<const php::ExnNode*>& ret, const php::ExnNode* n) {
  if (!n) return;
  exn_path(ret, n->parent);
  ret.push_back(n);
}
Example #27
0
void ReTriangulation::delaunayTriangulation(std::vector<Vec3f>* point, Vec3i face, std::vector<int>& idx, std::vector<int>& pointOnEdge, std::vector<int>& pointOnFace, std::vector<Vec3i>& triangles, int preNbPoint)
{
	GeometricFunc func;
	std::vector<std::vector<int>> trianglesAroundEdge;
	std::vector<std::vector<int>> edgesInTriangle;
	std::vector<Vec2i> edges;
	Vec3f normal=func.computeNormal(point, face);

	triangles.push_back(face);

	for(int i=0;i<pointOnEdge.size();i++)
	{
		for(int j=0;j<triangles.size();j++)
		{
			int edgeIdx=-1;
			for(int k=0;k<3;k++)
			{
				Vec3f l1=(*point)[triangles[j][k]];
				Vec3f l2=(*point)[triangles[j][(k+1)%3]];
				Vec3f p=(*point)[pointOnEdge[i]];
				if(func.isPointInLine(l1, l2, p))
				{
					edgeIdx=(k+2)%3;
					break;
				}
			}
			if(edgeIdx>-1)
			{
				//add triangles and edges
				triangles.push_back(Vec3i(triangles[j][(edgeIdx+1)%3], pointOnEdge[i], triangles[j][edgeIdx]));
				triangles.push_back(Vec3i(pointOnEdge[i], triangles[j][(edgeIdx+2)%3], triangles[j][edgeIdx]));

				//remove triangle
				triangles[j]=triangles[triangles.size()-1];
				triangles.pop_back();
				break;
			}
		}
	}

	for(int i=0;i<pointOnFace.size();i++)
	{
		int count=0;
		for(int j=0;j<triangles.size();j++)
		{
			int edgeIdx=-1;
			for(int k=0;k<3;k++)
			{
				Vec3f l1=(*point)[triangles[j][k]];
				Vec3f l2=(*point)[triangles[j][(k+1)%3]];
				Vec3f p=(*point)[pointOnFace[i]];
				if(func.isPointInLine(l1, l2, p))
				{
					edgeIdx=(k+2)%3;
					break;
				}
			}
			if(edgeIdx>-1)
			{
				//add triangles and edges
				triangles.push_back(Vec3i(triangles[j][(edgeIdx+1)%3], pointOnFace[i], triangles[j][edgeIdx]));
				triangles.push_back(Vec3i(pointOnFace[i], triangles[j][(edgeIdx+2)%3], triangles[j][edgeIdx]));

				//remove triangle
				triangles[j]=triangles[triangles.size()-1];
				triangles.pop_back();
				count++;
				if(count>1)
					break;
			}
			else if(func.isPointInTri(point, triangles[j], pointOnFace[i]))
			{
				//add triangles
				triangles.push_back(Vec3i(pointOnFace[i], triangles[j][0], triangles[j][1]));
				triangles.push_back(Vec3i(pointOnFace[i], triangles[j][1], triangles[j][2]));
				triangles.push_back(Vec3i(pointOnFace[i], triangles[j][2], triangles[j][0]));

				//remove triangle
				triangles[j]=triangles[triangles.size()-1];
				triangles.pop_back();

				int triIdx=triangles.size()-2;
				legalizeEdge(point, pointOnFace[i], Vec2i(triangles[triIdx][1], triangles[triIdx][2]), triIdx, triangles);
				triIdx=triangles.size()-1;
				legalizeEdge(point, pointOnFace[i], Vec2i(triangles[triIdx][1], triangles[triIdx][2]), triIdx, triangles);
				triIdx=j;
				legalizeEdge(point, pointOnFace[i], Vec2i(triangles[triIdx][1], triangles[triIdx][2]), triIdx, triangles);
				break;
			}
		}
	}

	for(int i=0;i<idx.size();i++)
	{
		for(int j=0;j<triangles.size();j++)
		{
			for(int k=0;k<3;k++)
			{
				if(triangles[j][k]==idx[i])
				{
					triangles[j]=triangles[triangles.size()-1];
					triangles.pop_back();
					j--;
					break;
				}
			}
		}
	}
}
Example #28
0
ResourceLoader::ErrorCode ResourceLoader::getResources(std::vector<Resource>& _ret, const boost::filesystem::path& _resourceDir)
{
	if (!fs::exists(_resourceDir) || !fs::is_directory(_resourceDir))
	{
		return ErrorCode::DIRECTORY_NOT_FOUND;
	}

	fs::path resourceFile = _resourceDir / "resources.txt";
	if (!fs::exists(resourceFile) || !fs::is_regular_file(resourceFile))
	{
		return ErrorCode::RESOURCE_FILE_NOT_FOUND;
	}

	ErrorCode res = ErrorCode::SUCCESS;

	int rowNr = 0;
	fs::fstream f(resourceFile);
	while (!f.eof())
	{
		rowNr++;

		std::string line;
		std::getline(f, line);

		if (line.empty() || line[0] == '#')
		{
			continue;
		}

		std::istringstream ss(line);
		std::string type;
		std::getline(ss, type, ':');

		if (ss.eof())
		{
			res = ErrorCode::INVALID_FORMAT;
			continue;
		}

		if (type.empty())
		{
			res = ErrorCode::INVALID_FORMAT;
			continue;
		}

		std::string resourceName;
		std::string resourcePath;
		ss >> resourceName >> resourcePath;

		if (resourceName.empty() || resourcePath.empty())
		{
			res = ErrorCode::INVALID_FORMAT;
			continue;
		}

		Resource res = { type, resourceName, _resourceDir / resourcePath };

		_ret.push_back(res);
	}

	return res;
}
Example #29
0
int hpx_main()
{
    
    {
        using namespace std;
        ifstream fin;
        string path = __FILE__;
        string wordlist_path;
        string remove = "spell_check.cpp";
        for (int i = 0; i < path.length() - remove.length(); i++)
        {
            wordlist_path.push_back(path[i]);
            if (path[i] == '\\')
            {
                wordlist_path.push_back(path[i]);
            }
        }
        //list of American English words in alphabetical order. Provided by Kevin at http://wordlist.sourceforge.net/
        wordlist_path = wordlist_path + "5desk.txt";
        fin.open(wordlist_path);
        int wordcount = 0;
        cout << "Reading dictionary file to memory...\n";
        hpx::util::high_resolution_timer t;
        if(fin.is_open())
        {
            string temp;
            while (fin.good())
            {
                getline(fin, temp);
                for (int i = 0; i < temp.length(); i++)
                temp[i] = tolower(temp[i]);
                words.push_back(temp);
                wordcount++;
            }
            cout << wordcount << " words loaded in " << t.elapsed() << "s.\n";
        }
        else
        {
            cout << "Error: Unable to open file.\n";
            return hpx::finalize();
        }
        fin.close();
        char* word = new char[1024];
        cout << "Enter the words you would like to spellcheck, separated by a \"Space\", and then press \"Enter\".\n";
        cin.getline(word,1024, '\n');
        vector<bool> contraction;
        vector<string> strs;
        {
            vector<string> temp;
            boost::split(temp, word, boost::is_any_of("\n\t -"));
            for (int i = 0; i < temp.size(); i++)
            {
                bool isContraction = false;
                string holder;
                for (int j = 0; j < temp[i].size(); j++)
                {
                    //a size check to avoid errors
                    if (temp[i].size() - j - 1 == 2)
                    {
                    //if this is a contraction, ignore the rest of it...
                        if (temp[i][j+1] == '\'' && temp[i][j] == 'n' && temp[i][j+2] == 't')
                        {
                            //but label this as a contraction
                            isContraction = true;
                            break;
                        }
                    }
                    //remove any garbage characters
                    if (toupper(temp[i][j]) >= 'A' && toupper(temp[i][j]) <= 'Z')
                        holder.push_back(tolower(temp[i][j]));
                }
                if (holder.size() > 0)
                {
                    contraction.push_back(isContraction);
                    strs.push_back(holder);
                }
            }
        }
        t.restart();
        {
            using hpx::lcos::future;
            using hpx::async;
            using hpx::wait_all;
            vector<search_action> sAct;//[sizeX * sizeY];
            vector<future<string>> wordRun;
            wordRun.reserve(strs.size());
            for (int i = 0; i < strs.size(); ++i)
            {
                string& single = strs[i]; 
                int start = 0;
                hpx::naming::id_type const locality_id = hpx::find_here();
                search_action temp;
                wordRun.push_back(async(temp, locality_id, start, wordcount, single));
                sAct.push_back(temp);
                //cout << search(0, wordcount, single) << endl;
            }
            wait_all(wordRun);
            cout << "Search completed in " << t.elapsed() << "s.\n";
            for (int i = 0; i < strs.size(); i++)
            {
                cout << "Word number " << i + 1 << ":\n";
                if (contraction[i])
                    cout << "Note: This word seems to be a contraction.\nThe last two letters have been ignored.\n";
                cout << wordRun[i].get();
            }
        }
    }
    return hpx::finalize(); // Handles HPX shutdown
}
Example #30
0
static void AppendKeys(std::vector<KeyDef> &keys, const std::vector<KeyDef> &newKeys) {
	for (auto iter = newKeys.begin(); iter != newKeys.end(); ++iter) {
		keys.push_back(*iter);
	}
}