Пример #1
0
World::World()
{
	int nrows = 15,ncols = 15;
	
	// Define blocks size.height
	for(int i = 0; i < nrows; ++i) {
		_rowHeights.push_back(80 + 100*double(std::rand())/RAND_MAX);
	}
	
	// Define blocks size.width
	for(int i = 0; i < ncols; ++i) {
		_colWidths.push_back(80 + 100*double(std::rand())/RAND_MAX);
	}
	
	Geo::RectSplitter splitter(Vector(20,20));
	
	_blockMatrix.reserve(nrows);
	
	double y = 0;
	
	for(int i = 0; i < nrows; ++i) {
		_blockMatrix.push_back(WorldRow());
		
		WorldRow &row = _blockMatrix.back();
		
		row.reserve(ncols);
		
		double x = 0;
		
		for(int j = 0; j < ncols; ++j) {
			Geo::Rectangle blockRect = Geo::Rectangle(Point(x,y),Vector(_colWidths[j],_rowHeights[i])).inset(6);
			
			row.push_back(Block(blockRect, splitter, _texturePool));
			
			x += _colWidths[j];
		}
		
		y += _rowHeights[i];
	}
	
	setBoundingSphere(BoundingSphere::createWithAABox(Point(),Point() + size()));
}
    /**
     * Parse the header and fill the headerInfo struct and returns a boolean
     * indicating if the table is spectrum or detector ID based
     * @param headerInfo :: [Out] Fills the given struct with details about the header
     * @returns True if the header is spectrum based, false otherwise
     */
    bool UpdateInstrumentFromFile::parseAsciiHeader(UpdateInstrumentFromFile::AsciiFileHeader & headerInfo)
    {
      const std::string header = getProperty("AsciiHeader");
      if(header.empty())
      {
        throw std::invalid_argument("Ascii file provided but the AsciiHeader property is empty, cannot interpret columns");
      }

      Poco::StringTokenizer splitter(header, ",",Poco::StringTokenizer::TOK_TRIM);
      headerInfo.colCount = splitter.count();
      auto it = splitter.begin(); // First column must be spectrum number or detector ID
      const std::string & col0 = *it;
      bool isSpectrum(false);
      if(boost::iequals("spectrum",col0)) isSpectrum = true;
      if(!isSpectrum && !boost::iequals("id",col0))
      {
        throw std::invalid_argument("Invalid AsciiHeader, first column name must be either 'spectrum' or 'id'");
      }

      ++it;
      size_t counter(1);
      for(; it != splitter.end(); ++it)
      {
        const std::string & colName = *it;
        if(boost::iequals("R",colName)) headerInfo.rColIdx = counter;
        else if(boost::iequals("theta",colName)) headerInfo.thetaColIdx = counter;
        else if(boost::iequals("phi",colName)) headerInfo.phiColIdx = counter;
        else if(boost::iequals("-",colName)) // Skip dashed
        {
          ++counter;
          continue;
        }
        else
        {
          headerInfo.detParCols.insert(counter);
          headerInfo.colToName.insert(std::make_pair(counter, colName));
        }
        ++counter;
      }

      return isSpectrum;
    }
Пример #3
0
	monthly_care_plan(QWidget* parent):QWidget(parent){
		if (parent->objectName().isEmpty()){
			parent->setObjectName(QString::fromUtf8("monthly_care_plan"));
		}
		parent->resize(800, 480);
		
		QSplitter splitter(Qt::Horizontal);
		
		verticalLayoutWidget = new QWidget(parent);
		verticalLayoutWidget->setObjectName(QString::fromUtf8("verticalLayoutWidget"));
		verticalLayoutWidget->setGeometry(QRect(0, 0, 160, 480));
		verticalLayoutWidget->setMinimumSize(160,480);
		verticalLayout = new QVBoxLayout(verticalLayoutWidget);
		verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
		verticalLayout->setContentsMargins(0, 0, 0, 0);
		care_plan_label = new QLabel(verticalLayoutWidget);
		care_plan_label->setObjectName(QString::fromUtf8("care_plan_label"));
		QFont font;
		font.setPointSize(14);
		care_plan_label->setFont(font);
		care_plan_label->setAlignment(Qt::AlignCenter);

		verticalLayout->addWidget(care_plan_label);

		human_list = new QListWidget(verticalLayoutWidget);
		human_list->setObjectName(QString::fromUtf8("human_list"));
		human_list->setMinimumSize(161,440);
		human_list->setMouseTracking(false);
		human_list->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

		verticalLayout->addWidget(human_list);

		human_widget = new one_human(this);
		human_widget->setGeometry(161, 0, 800-160, 480);

		this->retranslateUi(parent);

		QMetaObject::connectSlotsByName(parent);
		this->setMinimumSize(300,480);
	}
Пример #4
0
  BVH2::Base* BVH2Builder<Heuristic>::BuildTask::recurse(size_t depth, atomic_set<PrimRefBlock>& prims, const PrimInfo& pinfo, const Split& split)
  {
    /*! compute leaf and split cost */
    const float leafSAH  = parent->trity.intCost*pinfo.sah();
    const float splitSAH = BVH2::travCost*halfArea(pinfo.geomBounds)+parent->trity.intCost*split.sah();
    assert(atomic_set<PrimRefBlock>::block_iterator_unsafe(prims).size() == pinfo.size());
    assert(leafSAH >= 0 && splitSAH >= 0);

    /*! create a leaf node when threshold reached or SAH tells us to stop */
    if (pinfo.size() <= 1 || depth > BVH2::maxDepth || (pinfo.size() <= parent->bvh->maxLeafTris && leafSAH <= splitSAH)) {
      return parent->createLeaf(*thread,prims,pinfo);
    }

    /*! perform best found split and find new splits */
    SplitterNormal splitter(*thread,&parent->alloc,parent->triangles,parent->vertices,prims,pinfo,split);

    /*! create an inner node */
    BVH2::Node* node = (BVH2::Node*) parent->bvh->alloc.malloc(*thread,sizeof(BVH2::Node),1 << BVH2::alignment); node->clear();
    node->set(1,splitter.rinfo.geomBounds,recurse(depth+1,splitter.rprims,splitter.rinfo,splitter.rsplit));
    node->set(0,splitter.linfo.geomBounds,recurse(depth+1,splitter.lprims,splitter.linfo,splitter.lsplit));
    return BVH2::Base::encodeNode(node);
  }
Пример #5
0
void BookTracker::addBookFromString(string line) {
    string word = "";

    const int PARAMTYPES = 2;
    string bookAndListParams[PARAMTYPES];
    stringstream splitter(line);

    for (int i = 0; i < PARAMTYPES; i++) {
        if (getline(splitter, word, '*')) {
            bookAndListParams[i] = word;
        }
    }

    stringstream bookSplitter(bookAndListParams[0]);
    const int BOOKPARAMS = 3;
    string bookParams[BOOKPARAMS];
    for (int i = 0; i < BOOKPARAMS; i++) {
        if (getline(bookSplitter, word, '~')) {
            bookParams[i] = word;
        }
    }

    int have, want;
    string name = "";
    //store params for creation
    name = bookParams[0];
    have = stoi(bookParams[1]);
    want = stoi(bookParams[2]);
    //add book
    add(name, have, want);
    //add waitlist
    stringstream waitSplitter(bookAndListParams[1]);
    while (getline(waitSplitter, word, '~')) {
        if (word != "null" && word != "") {
            addToWaitlist(name, word);
        }
    }
}
Пример #6
0
    bool load_one_file(fs::path const& path, conn_data const& conn, size_t bulksize)
    {
        try
        {
            oracle_loader loader(conn, bulksize);

            PRINT_INFO(fmt(_("%1% :loading ...")) % path);

            cdr_file_splitter splitter(path);

            size_t count = 0;

            do 
            {
                cdr_buffer const buffer = splitter.get_next();
                if (buffer.empty())
                    break;

                if (loader.load(buffer))
                    count++;

            } while (true);

            PRINT_INFO(fmt(_("%1% :flush ...")) % path);
            loader.flush();

            PRINT_INFO(fmt(_("%1% :loaded %2% records")) % path % count);

            rename_dat_file(path);
        }
        catch (std::exception const& err)
        {
            PRINT_ERROR(fmt(_("load_one_file ERROR: %1%")) % err.what());
            return false;
        }

        return true;
    }
void
CreateBlueprintVisitorHelper::handleNumberTermAsText(query::NumberTerm &n)
{
    vespalib::string termStr = termAsString(n);
    queryeval::SplitFloat splitter(termStr);
    if (splitter.parts() > 1) {
        query::SimplePhrase phraseNode(n.getView(), n.getId(), n.getWeight());
        phraseNode.setStateFrom(n);
        for (size_t i = 0; i < splitter.parts(); ++i) {
            query::Node::UP nn;
            nn.reset(new query::SimpleStringTerm(splitter.getPart(i), "", 0, query::Weight(0)));
            phraseNode.append(std::move(nn));
        }
        visitPhrase(phraseNode);
    } else {
        if (splitter.parts() == 1) {
            termStr = splitter.getPart(0);
        }
        query::SimpleStringTerm stringNode(termStr, n.getView(), n.getId(), n.getWeight());
        stringNode.setStateFrom(n);
        visit(stringNode);
    }
}
    void BvHierarchyAlgorithm::initMesh(Proxy* parent, Mesh* mesh) {
        if (!parent) {
            throw NullPointerException("parent");
        }
        if (!mesh) {
            throw NullPointerException("mesh");
        }

        BvHierarchyProxyData* data = static_cast<BvHierarchyProxyData*>(parent->getDetectorDeformProxyData(getProxyDataIndex()));
        if (!data) {
            throw NullPointerException("data");
        }
        BvHierarchyBvhNode* node = new BvHierarchyBvhNode(mWorld, mesh);
        node->initializeNode();
        BvHierarchySplitter splitter(mWorld, mesh, node);
        splitter.startSplitting();

        // AB: parent->getBvHierarchyNode() already adjusts to the Shape.
        //     -> the toplevel node therefore already works using "top-down"
        //        updates.
        //        consequently, we dont need to do any update in our own,
        //        custom, toplevel node.
        if (!node->getChildren().empty()) {
            node->setIgnoreShape(true);
        }

        if (data->mDeformableNode) {
            throw Exception("data->mDeformableNode is not NULL");
        }
        data->mDeformableNode = node;

        const int maxDepth = 3;
        setTopDown(node, 1, maxDepth);

        node->reinitializeChildren();
    }
Пример #9
0
//adds a book from formatted string with delimitor
//returns book with those off waitlist
string BookTracker::addBookFromDeliveryString(string lineIn) {
    string line = lineIn;
    string word = "";
    const int NUMOFPARAMS = 3;

    //get params in a array
    string bookParams[NUMOFPARAMS];
    stringstream splitter(line);
    for (int i = 0; i < NUMOFPARAMS; i++) {
        if (getline(splitter, word, '~')) {
            bookParams[i] = word;
        }
    }

    int have, want;
    string name = "";
    //store params for creation
    name = bookParams[0];
    have = stoi(bookParams[1]);
    want = stoi(bookParams[2]);

    try {
        string result = "";
        BookNode *node = findBook(name);
        node->addToHaveValue(have);
        node->setWantValue(want);
        result = emptyWaitList(name);
        return result;
    } catch (logic_error e) { //add book if not found
        add(name, have, want);
        return "The book " + name + " has been added to the Inventory.";
    }

    return "";

}
Пример #10
0
	//////////////////////////////////////////////////////////////////////////////
	/// @details    Constructor from configuration file name.
	///
	/// @param      cfg_filename  Configuration file name.
	///
	/// @post       Configuration has been loaded.
	///
	/// @exception  std::runtime_error  Configuration file could not be opened.
	///
	AppConfigReader::AppConfigReader(std::string const& cfg_filename)
		: m_cfg()
	{
		std::cout << "loading configuration from file \"" << cfg_filename << "\"" << std::endl;
		
		//  open file
		std::ifstream cfg_file(cfg_filename.c_str());
		if (! cfg_file.good())
		{
			throw std::runtime_error("failed to open config file");
		}
		
		//  process lines
		std::string line;
		unsigned int line_num = 0;
		while (std::getline(cfg_file, line))
		{
			++line_num;
			
			RemoveComment(line);
			
			std::istringstream splitter(line);
			
			//  read key (if any)
			std::string key;
			splitter >> key;
			if (0 == key.size())
			{
				continue;
			}

			//  read value (if any)
			std::string value;
			splitter >> value;

			if (0 == value.size())
			{
				std::cout << cfg_filename << ":" << line_num << ": warning: ignoring line with key but no value" << std::endl;
				std::cout << cfg_filename << ":" << line_num << ": " << line << std::endl;
				continue;				
			}
	
			//  identify which key we've just read
			if (key == "Nx")
			{
				m_cfg.m_Nx = StringToInt(value);
			}
			else if (key == "Ny")
			{
				m_cfg.m_Ny = StringToInt(value);
			}
			else if (key == "T")
			{
				m_cfg.m_T = StringToInt(value); 
			}
			else if (key == "TT")
			{
				m_cfg.m_TT = StringToInt(value);
			}
			else if (key == "r")
			{
				m_cfg.m_r = StringToDouble(value);
			}
			else if (key == "a")
			{
				m_cfg.m_a = StringToDouble(value);
			}
			else if (key == "b")
			{
				m_cfg.m_b = StringToDouble(value);
			}
			else if (key == "m")
			{
				m_cfg.m_m = StringToDouble(value);
			}
			else if (key == "k")
			{
				m_cfg.m_k = StringToDouble(value);
			}
			else if (key == "l")
			{
				m_cfg.m_l = StringToDouble(value);
			}
			else if (key == "dt")
			{
				m_cfg.m_dt = StringToDouble(value);
			}
			else
			{
				std::cout << cfg_filename << ":" << line_num << ": warning: unrecognised key name" << std::endl;
				std::cout << cfg_filename << ":" << line_num << ": " << line << std::endl;				
			}
		}
		
		m_cfg.Print();
	}
Пример #11
0
int main()
{

	SetConsoleTitle(TEXT("First project")); //çàãîëîâîê îêíà êîíñîëè
	system("color 79"); //ôîí è òåêñò
	setlocale(LC_ALL, "Russian");
	SetConsoleCP(1251); //êîäèðîâêà âõîäíîãî ïîòîêà.
	SetConsoleOutputCP(1251); //è âûõîäíîãî
							  // Ðàáîòàåò òîëüêî äëÿ Lucida Console.
	do {
		system("cls"); //î÷èùàåì îêíî êîíñîëè
		printf("Çàäàíèå 26.\nÍàïèñàòü ïðîãðàììó, êîòîðàÿ ñ÷èòûâàåò ìàññèâ NxM âåùåñòâåííûõ ÷èñåë,\n"
			"â êàæäîé ñòðîêå èùåòñÿ ìèíèìàëüíîå çíà÷åíèå, çàòåì ñðåäè âñåõ ìèíèìàëüíûõ èùåòñÿ\n"
			"ìàêñèìàëüíûé ýëåìåíò è âûâîäèòñÿ åãî èíäåêñ è çíà÷åíèå.\nÇàòåì ââîäèòñÿ ñ êëàâèàòóðû ñòðîêà\n"
			"äëèííîé íå áîëåå 256 ñèìâîëîâ, â íåé èùåòñÿ ñëîâî äëèíîé áîëåå 4, â êîòîðîì áóêâà à\n"
			"âñòðå÷àåòñÿ ðåæå è âûâîäèòñÿ ýòî ñëîâî.\n");
		int n, m; //ðàçìåðû òàáëèöû
		printf("Ââåäèòå êîë-âî ñòðîê \n");
		scanf_s("%d", &n); //÷èòàåì
		getchar();
		printf("Ââåäèòå êîë-âî ñòîëáöîâ \n");
		scanf_s("%d", &m); //ðàçìåðû
		getchar();
		double** ar = new double*[n]; //âûäåëÿåì ïàìÿòü
		for (int i = 0; i < n; i++)
		{
			ar[i] = new double[m]; //äëÿ ñòðîê
		}
		printf("Ââåäèòå ýë-òû ìàññèâà \n");
		for (int i = 0; i < n; i++) //÷èòàåì ýëåìåíòû ìàññèâà.
			for (int j = 0; j < m; j++) {
				printf("ar[%d][%d] = ", i, j);
				scanf_s("%lf", &ar[i][j]); //÷èòàåì ýëåìåíòû
				getchar(); //è \n äî êó÷è.
			}
		min_elem max = task(ar, n, m); //èùåì ìàêñèìàëüíûé èç ìèíèìàëüíûõ
		printf("Èíåêñû i = %d j = %d\nÇíà÷åíèå: %lf\n", max.ind1, max.ind2, max.value); //âûâîäèì åãî èíäåêñû è çíà÷åíèå
		for (int i = 0; i < n; i++) //î÷èùàåì ïàìÿòü
		{
			delete[] ar[i];
		}
		delete[] ar;
		char* string = (char*)malloc(256 * sizeof(char)); //âûäåëÿåì ïàìÿòü ïîä ñòðîêó
		printf("Ââåäèòå ñòðîêó:\n");
		fgets(string, 255, stdin); //÷èòàåì å¸
		wlist list = splitter(string); //âûäåëÿåì ñëîâà
		if (find_task_word(list) == -1) //åñëè íåò ñëîâ áîëåå 4 áóêâ òî ôóíêöèÿ âåðíåò -1
		{
			printf("Íåò ñëîâ èç áîëåå ÷åì 4 áóêâ.\n");
		}
		else //èíà÷å âûâîäèì ñëîâî áîëåå 4 áóêâ ñîäåðæàùåå ìåíüøåå ÷èñëî áóêâ à.
		{
			printf("Ñëîâî èç áîëåå ÷åì 4 áóêâ ñ íàèìåíüøèì êîëè÷åñòâîì áóêâ 'à':\n%s\n", list.words[find_task_word(list)]);
		}
		//free(list.words);
		wlist_clear(list); //÷èñòèì ïàìÿòü èç ïîä ëèñòà ñëîâ.
		free(string); //è ñòðîêè.
		_CrtDumpMemoryLeaks(); //ïðîâåðÿåì ïàìÿòü íà óòå÷êè.
	} while (answer());
	return 0;
}
Пример #12
0
long double octfloattofloat(const char *float_string) {
  /* Convert an octal string from the given pointer in an float value ;
   ********************************************************************/
 
  if (float_string == NULL) {
    /** Invalid argument **/
    fprintf(stderr,"%s %s\n",__func__,strerror(EINVAL)) ;
    exit(EXIT_FAILURE) ;
  }
 
  if ( ! is_string_oct(float_string,true) ) {
    /** Invalid argument **/
    fprintf(stderr,"%s %s\n",__func__,strerror(EINVAL)) ;
    exit(EXIT_FAILURE) ;
  }
 
  if ( strchr(float_string,'.') == NULL) {
    /** Case argument string is not a float, return integer value (long double) cast */
    return __octfloattofloattintpart(float_string) ;
  }
  char *oct_float_str_saved=strdup(float_string) ;
  _Bool is_negativ=false ;
  if ( float_string[0] == '-' ) {
    /** Case argument string is an negativ value we remember it for returning */
    is_negativ=true ;
    int i,c ;
     for (i=1,c=0 ; i < (int) strlen(float_string) ; i++,c++) {
       oct_float_str_saved[c]=float_string[i] ;
     }
     oct_float_str_saved[c]='\0' ;
  }
  else {
    oct_float_str_saved=strdup(float_string) ;
  }
 
  /** variables for splitting in integer and float part */
 
  char *oct_int_part=malloc(64) ;
  char *oct_float_part=malloc(64) ;
  memset(oct_int_part,'\0',64) ;
  memset(oct_float_part,'\0',64) ;
 
  /** Perform splitting for getting float part we are interest */
  splitter(oct_float_str_saved,oct_int_part,oct_float_part) ;
 
  long double res_int = __octfloattofloattintpart(oct_int_part) ; /** value to return for the integer part */
 
  unsigned int c  ;           /** float part index */
  int cc ;                    /** float exponent value */
  long double res_float=0.0 ; /** variable for computing float part */
 
  for(c=0 ,cc=-1 ; c < (unsigned int) strlen(oct_float_part) ; c++,cc--) {
    res_float += (long double) get_digit(oct_float_part[c]) * powl(8,cc) ;
  }
 
  free(oct_int_part) ;
  free(oct_float_part) ;
  free(oct_float_str_saved) ;
 
  if ( is_negativ ) {
     return - (long double) (res_int + res_float) ;
   }
   else {
     return (long double) res_int + res_float ;
   }
}
Пример #13
0
    void cut_uint_le()
    {
        CPPUNIT_MSG("little-endian byte order");

        typedef cds::algo::split_bitstring< size_t > split_bitstring;

        size_t src = sizeof(src) == 8 ? 0xFEDCBA9876543210 : 0x76543210;
        split_bitstring splitter(src);
        size_t res;

        // Trivial case
        CPPUNIT_ASSERT( !splitter.eos() );
        CPPUNIT_ASSERT( splitter );
        res = splitter.cut(sizeof(src) * 8);
        CPPUNIT_ASSERT_EX( res == src, "src=" << src << ", result=" << res );
        CPPUNIT_ASSERT( splitter.eos() );
        CPPUNIT_ASSERT( !splitter );
        CPPUNIT_ASSERT(splitter.safe_cut(sizeof(src) * 8) == 0 );
        CPPUNIT_ASSERT( splitter.eos() );
        CPPUNIT_ASSERT( !splitter );
        splitter.reset();
        CPPUNIT_ASSERT( !splitter.eos() );
        CPPUNIT_ASSERT( splitter );
        res = splitter.cut(sizeof(src) * 8);
        CPPUNIT_ASSERT_EX( res == src, "src=" << src << ", result=" << res );
        CPPUNIT_ASSERT( splitter.eos() );
        CPPUNIT_ASSERT( !splitter );
        CPPUNIT_ASSERT(splitter.safe_cut(sizeof(src) * 8) == 0 );
        CPPUNIT_ASSERT( splitter.eos() );
        CPPUNIT_ASSERT( !splitter );

        // Cut each hex digit
        splitter.reset();
        for ( size_t i = 0; i < sizeof(size_t) * 2; ++i ) {
            CPPUNIT_ASSERT( !splitter.eos() );
            CPPUNIT_ASSERT( splitter );
            CPPUNIT_ASSERT( splitter.cut( 4 ) == i );
        }
        CPPUNIT_ASSERT( splitter.eos() );
        CPPUNIT_ASSERT( !splitter );

        // by one bit
        {
            splitter.reset();
            res = 0;
            for ( size_t i = 0; i < sizeof(size_t) * 8; ++i ) {
                CPPUNIT_ASSERT( !splitter.eos() );
                CPPUNIT_ASSERT( splitter );
                res = res + (splitter.cut( 1 ) << i);
            }
            CPPUNIT_ASSERT( splitter.eos() );
            CPPUNIT_ASSERT( !splitter );
            CPPUNIT_ASSERT( res == src );
        }

        // random cut
        {
            for ( size_t k = 0; k < 100; ++k ) {
                splitter.reset();
                res = 0;
                size_t shift = 0;
                while ( splitter ) {
                    CPPUNIT_ASSERT( !splitter.eos() );
                    CPPUNIT_ASSERT( splitter );
                    int bits = rand() % 16;
                    res = res + ( splitter.safe_cut( bits ) << shift );
                    shift += bits;
                }
                CPPUNIT_ASSERT( splitter.eos() );
                CPPUNIT_ASSERT( !splitter );
                CPPUNIT_ASSERT( res == src );
            }
        }
    }
Пример #14
0
Sidebar_Widget::Sidebar_Widget(QWidget *parent, KParts::ReadOnlyPart *par, const char *name,bool universalMode, const QString &currentProfile)
	:QWidget(parent,name),m_universalMode(universalMode),m_partParent(par),m_currentProfile(currentProfile)
{
	m_somethingVisible = false;
	m_initial = true;
	m_noUpdate = false;
	m_layout = 0;
	m_currentButton = 0;
	m_activeModule = 0;
	m_userMovedSplitter = false;
        //kdDebug() << "**** Sidebar_Widget:SidebarWidget()"<<endl;
	if (universalMode)
	{
		m_relPath = "konqsidebartng/kicker_entries/";
	}
	else
	{
		m_relPath = "konqsidebartng/" + currentProfile + "/entries/";
	}
	m_path = KGlobal::dirs()->saveLocation("data", m_relPath, true);
	m_buttons.setAutoDelete(true);
	m_hasStoredUrl = false;
	m_latestViewed = -1;
	setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));

	QSplitter *splitterWidget = splitter();
	if (splitterWidget) {
		splitterWidget->setResizeMode(parent, QSplitter::FollowSizeHint);
		splitterWidget->setOpaqueResize( false );
		connect(splitterWidget,SIGNAL(setRubberbandCalled()),SLOT(userMovedSplitter()));
	}
		
	m_area = new KDockArea(this);
	m_area->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
	m_mainDockWidget = m_area->createDockWidget("free", 0);
	m_mainDockWidget->setWidget(new QWidget(m_mainDockWidget));
	m_area->setMainDockWidget(m_mainDockWidget);
	m_area->setMinimumWidth(0);
	m_mainDockWidget->setDockSite(KDockWidget::DockTop);
	m_mainDockWidget->setEnableDocking(KDockWidget::DockNone);

	m_buttonBar = new KMultiTabBar(KMultiTabBar::Vertical,this);
	m_buttonBar->showActiveTabTexts(true);

	m_menu = new QPopupMenu(this, "Sidebar_Widget::Menu");
	QPopupMenu *addMenu = new QPopupMenu(this, "Sidebar_Widget::addPopup");
	m_menu->insertItem(i18n("Add New"), addMenu, 0);
	m_menu->insertItem(i18n("Multiple Views"), 1);
	m_menu->insertItem(i18n("Show Tabs Left"), 2);
	m_menu->insertItem(i18n("Show Configuration Button"), 3);
	if (!m_universalMode) {
		m_menu->insertItem(SmallIconSet("remove"),
                                   i18n("Close Navigation Panel"),
				par, SLOT(deleteLater()));
	}
        connect(m_menu, SIGNAL(aboutToShow()),
		this, SLOT(aboutToShowConfigMenu()));
	connect(m_menu, SIGNAL(activated(int)),
		this, SLOT(activatedMenu(int)));

	m_buttonPopup = 0;
	addBackEnd *ab = new addBackEnd(this, addMenu, universalMode,
                                        currentProfile,
                                        "Sidebar_Widget-addBackEnd");

	connect(ab, SIGNAL(updateNeeded()),
		this, SLOT(updateButtons()));
	connect(ab, SIGNAL(initialCopyNeeded()),
		this, SLOT(finishRollBack()));

	initialCopy();

        if (universalMode)
        {
                m_config = new KConfig("konqsidebartng_kicker.rc");
        }
        else
        {
                m_config = new KConfig("konqsidebartng.rc");
                m_config->setGroup(currentProfile);
        }
        readConfig();

        // Disable stuff (useful for Kiosk mode)!
        m_menu->setItemVisible(1, !m_immutableSingleWidgetMode);
        m_menu->setItemVisible(2, !m_immutableShowTabsLeft);
        m_menu->setItemVisible(3, !m_immutableShowExtraButtons);

	connect(&m_configTimer, SIGNAL(timeout()),
		this, SLOT(saveConfig()));
	m_somethingVisible = !m_openViews.isEmpty();
	doLayout();
	QTimer::singleShot(0,this,SLOT(createButtons()));
	connect(m_area, SIGNAL(dockWidgetHasUndocked(KDockWidget*)),
		this, SLOT(dockWidgetHasUndocked(KDockWidget*)));
}
Пример #15
0
TEST(TestStringSplitter, AllSepTest1)
{
    const char* str = ",";
    StringSplitter splitter(str, ',');
    EXPECT_EQ(splitter, false);
}
Пример #16
0
void Inventory::fromFile(std::string filename){
    std::ifstream infile(filename);
    if (infile){
        if(filename == "game.txt"){
            while (infile){
                if(infile){
                    std::string strInput;
                    std::getline(infile, strInput);
                    if(strInput.length()>0){
                        std::stringstream splitter(strInput);
                        //std::string title,price,copies,condition,genre,rating,maker;
                        std::string title,price,copies,condition,genre,rating,maker,preorder;
                        getline(splitter,title,',');
                        getline(splitter,price,',');
                        getline(splitter,copies,',');
                        getline(splitter,condition,',');
                        getline(splitter,preorder,',');
                        getline(splitter,genre,',');
                        getline(splitter,rating,',');
                        getline(splitter,maker,',');
                        Game* g = new Game(stoi(copies), stof(price), title, genre,rating, to_bool(condition),maker, to_bool(preorder));
                        gameStock.add(g);
//                        std::cout << "\nRead:\t" << g->toString() << "\n";
                    }
                }
            }
        }
        if(filename == "console.txt"){
            while (infile){
                if(infile){
                    std::string strInput;
                    std::getline(infile, strInput);
                    if(strInput.length()>0){
                        std::stringstream splitter(strInput);
                        std::string title,price,copies,condition,edition,maker,warranty;
                        getline(splitter,title,',');
                        getline(splitter,price,',');
                        getline(splitter,copies,',');
                        getline(splitter,condition,',');
                        getline(splitter,edition,',');
                        getline(splitter,maker,',');
                        getline(splitter,warranty,',');
                        Console* c = new Console(stoi(copies), stof(price), title, edition,maker, stoi(warranty), to_bool(condition));
                        consoleStock.add(c);
//                        std::cout << "\nRead:\t" << c->toString() << "\n";
                    }
                }
            }
        }
        if(filename == "accessory.txt"){
            while (infile){
                if(infile){
                    std::string strInput;
                    std::getline(infile, strInput);
                    if(strInput.length()>0){
                        std::stringstream splitter(strInput);
                        std::string title,price,copies,condition,consoleTo,warranty;
                        getline(splitter,title,',');
                        getline(splitter,price,',');
                        getline(splitter,copies,',');
                        getline(splitter,condition,',');
                        getline(splitter,consoleTo,',');
                        getline(splitter,warranty,',');
                        Accessory* a = new Accessory(stoi(copies), stof(price), title, consoleTo, to_bool(condition), stoi(warranty));
                        acessStock.add(a);
//                        std::cout << "\nRead:\t" << a->toString() << "\n";
                        
                    }
                }
            }
        }
        infile.close();
    }
    else {
        std::cout << "Can't read from file. Inventory not loaded.\n";
    }
}
Пример #17
0
int QResourceRoot::findNode(const QString &_path, const QLocale &locale) const
{
    QString path = _path;
    {
        QString root = mappingRoot();
        if(!root.isEmpty()) {
            if(root == path) {
                path = QLatin1Char('/');
            } else {
                if(!root.endsWith(QLatin1Char('/')))
                    root += QLatin1Char('/');
                if(path.size() >= root.size() && path.startsWith(root))
                    path = path.mid(root.length()-1);
                if(path.isEmpty())
                    path = QLatin1Char('/');
            }
        }
    }
#ifdef DEBUG_RESOURCE_MATCH
    qDebug() << "!!!!" << "START" << path << locale.country() << locale.language();
#endif

    if(path == QLatin1String("/"))
        return 0;

    //the root node is always first
    int child_count = (tree[6] << 24) + (tree[7] << 16) +
                      (tree[8] << 8) + (tree[9] << 0);
    int child       = (tree[10] << 24) + (tree[11] << 16) +
                      (tree[12] << 8) + (tree[13] << 0);

    //now iterate up the tree
    int node = -1;

    QStringSplitter splitter(path);
    while (child_count && splitter.hasNext()) {
        QStringRef segment = splitter.next();

#ifdef DEBUG_RESOURCE_MATCH
        qDebug() << "  CHILDREN" << segment;
        for(int j = 0; j < child_count; ++j) {
            qDebug() << "   " << child+j << " :: " << name(child+j);
        }
#endif
        const int h = qHash(segment);

        //do the binary search for the hash
        int l = 0, r = child_count-1;
        int sub_node = (l+r+1)/2;
        while(r != l) {
            const int sub_node_hash = hash(child+sub_node);
            if(h == sub_node_hash)
                break;
            else if(h < sub_node_hash)
                r = sub_node - 1;
            else
                l = sub_node;
            sub_node = (l + r + 1) / 2;
        }
        sub_node += child;

        //now do the "harder" compares
        bool found = false;
        if(hash(sub_node) == h) {
            while(sub_node > child && hash(sub_node-1) == h) //backup for collisions
                --sub_node;
            for(; sub_node < child+child_count && hash(sub_node) == h; ++sub_node) { //here we go...
                if(name(sub_node) == segment) {
                    found = true;
                    int offset = findOffset(sub_node);
#ifdef DEBUG_RESOURCE_MATCH
                    qDebug() << "  TRY" << sub_node << name(sub_node) << offset;
#endif
                    offset += 4;  //jump past name

                    const short flags = (tree[offset+0] << 8) +
                                        (tree[offset+1] << 0);
                    offset += 2;

                    if(!splitter.hasNext()) {
                        if(!(flags & Directory)) {
                            const short country = (tree[offset+0] << 8) +
                                                  (tree[offset+1] << 0);
                            offset += 2;

                            const short language = (tree[offset+0] << 8) +
                                                   (tree[offset+1] << 0);
                            offset += 2;
#ifdef DEBUG_RESOURCE_MATCH
                            qDebug() << "    " << "LOCALE" << country << language;
#endif
                            if(country == locale.country() && language == locale.language()) {
#ifdef DEBUG_RESOURCE_MATCH
                                qDebug() << "!!!!" << "FINISHED" << __LINE__ << sub_node;
#endif
                                return sub_node;
                            } else if((country == QLocale::AnyCountry && language == locale.language()) ||
                                      (country == QLocale::AnyCountry && language == QLocale::C && node == -1)) {
                                node = sub_node;
                            }
                            continue;
                        } else {
#ifdef DEBUG_RESOURCE_MATCH
                            qDebug() << "!!!!" << "FINISHED" << __LINE__ << sub_node;
#endif

                            return sub_node;
                        }
                    }

                    if(!(flags & Directory))
                        return -1;

                    child_count = (tree[offset+0] << 24) + (tree[offset+1] << 16) +
                                  (tree[offset+2] << 8) + (tree[offset+3] << 0);
                    offset += 4;
                    child = (tree[offset+0] << 24) + (tree[offset+1] << 16) +
                            (tree[offset+2] << 8) + (tree[offset+3] << 0);
                    break;
                }
            }
        }
        if(!found)
            break;
    }
#ifdef DEBUG_RESOURCE_MATCH
    qDebug() << "!!!!" << "FINISHED" << __LINE__ << node;
#endif
    return node;
}
Пример #18
0
int main(int argn, char **argv) {
    MPI_Init(&argn, &argv);

    int rank, size;
    MPI_Comm communicator = MPI_COMM_WORLD;
    MPI_Comm_rank(communicator, &rank);
    MPI_Comm_size(communicator, &size);

    PPartitionConfig partition_config;
    DspacConfig dspac_config;
    std::string graph_filename;

    int ret_code = parse_dspac_parameters(argn, argv, partition_config, dspac_config, graph_filename);

    if (ret_code) {
        MPI_Finalize();
        return 0;
    }
    if (rank == ROOT) {
        std::cout << "graph: " << graph_filename << "\n"
                  << "infinity edge weight: " << dspac_config.infinity << "\n"
                  << "seed: " << partition_config.seed << "\n"
                  << "k: " << partition_config.k << "\n"
                  << "ncores: " << size << std::endl;
    }

    timer t;
    MPI_Barrier(MPI_COMM_WORLD);
    {
        t.restart();
        if (rank == ROOT) std::cout << "running collective dummy operations ";
        dummy_operations dop;
        dop.run_collective_dummy_operations();
    }
    MPI_Barrier(MPI_COMM_WORLD);

    if (rank == ROOT) {
        std::cout << "took " << t.elapsed() << std::endl;
    }

    // load input graph
    t.restart();
    parallel_graph_access input_graph(communicator);
    edge_balanced_graph_io::read_binary_graph_edge_balanced(input_graph, graph_filename, partition_config, rank, size);
    if (rank == ROOT) {
        std::cout << "input IO took " << t.elapsed() << "\n"
                  << "n(input): " << input_graph.number_of_global_nodes() << "\n"
                  << "m(input): " << input_graph.number_of_global_edges() << std::endl;
    }
    MPI_Barrier(communicator);

    // construct split graph
    t.restart();
    parallel_graph_access split_graph(communicator);
    dspac splitter(input_graph, communicator, dspac_config.infinity);
    splitter.construct(split_graph);
    if (rank == ROOT) {
        std::cout << "split graph construction took " << t.elapsed() << "\n"
                  << "n(split): " << split_graph.number_of_global_nodes() << "\n"
                  << "m(split): " << split_graph.number_of_global_edges() << std::endl;
    }

    // partition split graph
    t.restart();
    executeParhip(split_graph, partition_config);
    if (rank == ROOT) {
        std::cout << "parhip took " << t.elapsed() << std::endl;
    }

    // evaluate edge partition
    t.restart();
    splitter.fix_cut_dominant_edges(split_graph);
    std::vector<PartitionID> edge_partition = splitter.project_partition(split_graph);
    EdgeWeight vertex_cut = splitter.calculate_vertex_cut(partition_config.k, edge_partition);
    if (rank == ROOT) {
        std::cout << "evaluation took " << t.elapsed() << "\n"
                  << "vertex cut: " << vertex_cut << std::endl;
    }

    if( partition_config.save_partition ) {
            parallel_vector_io pvio;
            std::string filename("tmpedgepartition.txtp");
            pvio.writePartitionSimpleParallel(split_graph, filename);
    }

    if( partition_config.save_partition_binary ) {
            parallel_vector_io pvio;
            std::string filename("tmpedgepartition.binp");
            pvio.writePartitionBinaryParallelPosix(partition_config, split_graph, filename);
    }

    MPI_Barrier(MPI_COMM_WORLD);
    MPI_Finalize();
}
Пример #19
0
MutFileDataType FileNameDialog(wxWindow * parent,
                        int Command,
                        wxString Filename)
{
	DEBUGLOG2(gui,_T("Command: %d"),Command);

	static const wxString logic_sources(_("Mutabor tuning file (*.mut)|*.mut|Old Mutabor tuning file (*.mus)|*.mus|All files (*.*)|*.*"));

	static const wxString route_sources(_("Mutabor routing file (*.murx)|*.murx|Old Mutabor routing file (*.mur)|*.mur|All files (*.*)|*.*"));

	wxString title, filetypes,
	dir(wxEmptyString), name(wxEmptyString) , ext(wxEmptyString);

	int flags;

	MutFileDataType retval;
	switch (Command) {

	case CM_FILEOPEN:
		title = _("Which Mutabor file shall be loaded?");
		filetypes = logic_sources;
		flags = wxFD_CHANGE_DIR | wxFD_FILE_MUST_EXIST | wxFD_OPEN;
		break;

	case mutaborGUI::CM_EXECUTE:
		title = _("Which Mutabor file shall be executed?");
		filetypes = logic_sources;
		flags = wxFD_CHANGE_DIR | wxFD_FILE_MUST_EXIST | wxFD_OPEN;
		break;

	case CM_FILESAVEAS:
		title = _("Enter the new Mutabor file name, please!");
		filetypes = logic_sources;
		flags = wxFD_CHANGE_DIR | wxFD_OVERWRITE_PROMPT | wxFD_SAVE;
		break;

	case mutaborGUI::CM_ROUTELOAD:
		title = _("Which Mutabor route file shall be loaded?");
		filetypes = route_sources;
		flags = wxFD_CHANGE_DIR | wxFD_FILE_MUST_EXIST | wxFD_OPEN;
		break;

	case mutaborGUI::CM_ROUTESAVE:
	case mutaborGUI::CM_ROUTESAVEAS:
		title = _("Enter the new Mutabor route file name, please!");
		filetypes = route_sources;
		flags = wxFD_CHANGE_DIR | wxFD_OVERWRITE_PROMPT | wxFD_SAVE;
		break;

	default:
		wxLogError(_("Unexpected Command Id in FileNameDialog: %d"),Command);
		retval.type = MutFileDataType::Unknown;
		return retval;
	}

	if (!Filename.IsEmpty()) {
		wxFileName splitter(Filename);
		ext = splitter.GetExt();
		name = splitter.GetFullName();
		dir = splitter.GetPath();
	}

	wxFileDialog  * FileSelector = new wxFileDialog(parent, title, dir, name, filetypes, flags);

	int cmd = FileSelector->ShowModal();

	if (cmd != wxID_OK) {
		retval.type  = MutFileDataType::Canceled;
		return retval;
	}
	retval.name = FileSelector->GetPath();
	switch (Command) {
	case CM_FILEOPEN:
	case mutaborGUI::CM_EXECUTE:
	case CM_FILESAVEAS:
			retval.type=MutFileDataType::LogicSource;
		break;
	case mutaborGUI::CM_ROUTELOAD:
	case mutaborGUI::CM_ROUTESAVE:
	case mutaborGUI::CM_ROUTESAVEAS:
		switch (FileSelector->GetFilterIndex()) {
		case 0: 
			retval.type = MutFileDataType::XMLRoute1;
			break;
		case 1: 
			retval.type = MutFileDataType::UTF8TextRoute;
			break;
		default:
			wxString ext = retval.name.GetExt().Upper();
			if (ext == _T("MUR")) {
				retval.type = MutFileDataType::UTF8TextRoute;
			} else if (ext == _T("MURX")) {
				retval.type = MutFileDataType::XMLRoute1;
			} else retval.type = MutFileDataType::Unknown;
		}
		break;

	default:
		wxLogError(_("Unexpected Command Id in FileNameDialog: %d"),Command);
		retval.type = MutFileDataType::Unknown;
		return retval;
	}

	FileSelector->Destroy();

	return retval;
}
Пример #20
0
TIGLViewerWindow::TIGLViewerWindow()
    : myLastFolder(tr(""))
    , cpacsConfiguration(NULL)
{
    setupUi(this);

    tiglViewerSettings = &TIGLViewerSettings::Instance();
    settingsDialog = new TIGLViewerSettingsDialog(*tiglViewerSettings, this);

    myScene  = new TIGLViewerContext();
    myOCC->setContext(myScene->getContext());

    // we create a timer to workaround QFileSystemWatcher bug,
    // which emits multiple signals in a few milliseconds. This caused
    // TIGLViewer to also open a document many times.
    // Now, when we get a signal, we start the timer and only after the
    // timer times out, we reopen the cpacs config
    openTimer = new QTimer(this);
    openTimer->setSingleShot(true);
    // the timeout of 200ms is a bit arbitrary but should be conservative enough
    // to catch all events
    openTimer->setInterval(200);

    //redirect everything to TIGL console, let error messages be printed in red
    stdoutStream = new QDebugStream(std::cout);
    errorStream  = new QDebugStream(std::cerr);
    errorStream->setMarkup("<b><font color=\"red\">","</font></b>");

    // insert two loggers, one for the log history and one for the console
    CSharedPtr<tigl::CTiglLogSplitter> splitter(new tigl::CTiglLogSplitter);
    logHistory = CSharedPtr<TIGLViewerLogHistory>(new TIGLViewerLogHistory);
    logHistory->SetVerbosity(TILOG_DEBUG4);
    splitter->AddLogger(logHistory);

    logDirect = CSharedPtr<TIGLViewerLogRedirection>(new TIGLViewerLogRedirection);
    logDirect->SetVerbosity(TILOG_WARNING);
    tigl::PTiglLogger logHTMLDecorator(new TIGLViewerLoggerHTMLDecorator(logDirect));
    splitter->AddLogger(logHTMLDecorator);

    // register logger at tigl
    tigl::CTiglLogging::Instance().SetLogger(splitter);

    QPalette p = console->palette();
    p.setColor(QPalette::Base, Qt::black);
    console->setPalette(p);

    //cpacsConfiguration = new TIGLViewerDocument(this);
    scriptEngine = new TIGLScriptEngine(this);
    
    setAcceptDrops(true);

    connectSignals();
    createMenus();
    updateMenus();

    loadSettings();

    statusBar()->showMessage(tr("A context menu is available by right-clicking"));

    setWindowTitle(tr(PARAMS.windowTitle.toLatin1().data()));
    setMinimumSize(160, 160);
}
Пример #21
0
BSPTree_Ptr BSPTree::load_postorder_text(std::istream& is)
{
	std::string line;
	std::getline(is, line);
	int nodeCount;
	try							{ nodeCount = lexical_cast<int,std::string>(line); }
	catch(bad_lexical_cast&)	{ throw Exception("The BSP node count is not a number"); }

	std::vector<BSPNode_Ptr> nodes(nodeCount);

	int n = 0;
	while(n < nodeCount && std::getline(is, line))
	{
		typedef boost::char_separator<char> sep;
		typedef boost::tokenizer<sep> tokenizer;

		tokenizer tok(line, sep(" "));
		std::vector<std::string> tokens(tok.begin(), tok.end());
		size_t tokenCount = tokens.size();
		if(tokenCount < 2) throw Exception("Bad BSP node: " + lexical_cast<std::string,int>(n));

		if(tokens[1] == "E")
		{
			if(tokenCount < 6 || tokens[4] != "[" || tokens[tokenCount-1] != "]")
				throw Exception("Bad empty leaf node: " + lexical_cast<std::string,int>(n));

			int polyCount;
			try							{ polyCount = lexical_cast<int,std::string>(tokens[3]); }
			catch(bad_lexical_cast&)	{ throw Exception("The leaf polygon count is not a number: " + lexical_cast<std::string,int>(n)); }

			std::vector<int> polyIndices;

			for(size_t i=5; i<tokenCount-1; ++i)
			{
				int polyIndex;
				try							{ polyIndex = lexical_cast<int,std::string>(tokens[i]); }
				catch(bad_lexical_cast&)	{ throw Exception("A polygon index is not a number in leaf: " + lexical_cast<std::string,int>(n)); }

				polyIndices.push_back(polyIndex);
			}

			nodes[n] = BSPLeaf::make_empty_leaf(n, polyIndices);
		}
		else if(tokens[1] == "S")
		{
			nodes[n] = BSPLeaf::make_solid_leaf(n);
		}
		else if(tokens[1] == "B")
		{
			if(tokenCount != 11 || tokens[5] != "(" || tokens[10] != ")")
				throw Exception("Bad branch node: " + lexical_cast<std::string,int>(n));

			int leftIndex, rightIndex;
			double a, b, c, d;
			try
			{
				leftIndex = lexical_cast<int,std::string>(tokens[2]);
				rightIndex = lexical_cast<int,std::string>(tokens[3]);
				a = lexical_cast<double,std::string>(tokens[6]);
				b = lexical_cast<double,std::string>(tokens[7]);
				c = lexical_cast<double,std::string>(tokens[8]);
				d = lexical_cast<double,std::string>(tokens[9]);
			}
			catch(bad_lexical_cast&)	{ throw Exception("One of the values was not a number in branch node: " + lexical_cast<std::string,int>(n)); }

			BSPNode_Ptr left = nodes[leftIndex];
			BSPNode_Ptr right = nodes[rightIndex];
			if(left && right)
			{
				Plane_Ptr splitter(new Plane(Vector3d(a,b,c), d));
				nodes[n] = BSPNode_Ptr(new BSPBranch(n, splitter, left, right));
			}
			else throw Exception("The BSP nodes are not stored in postorder: the child nodes for this branch have not yet been loaded");
		}

		++n;
	}

	return BSPTree_Ptr(new BSPTree(nodes));
}
Пример #22
0
void OCC_Connect::Intersect(BRep_Builder &BB, TopoDS_Shape &target,
    TopoDS_Shape &shape, TopoDS_Shape &tool)
{
    /***************************************************************************
        We start by splitting edges at all the edge-edge intersections.
        This may generate new vertices and edges.
    ***************************************************************************/
    MergeVertices(shape,tool);
    LocOpe_SplitShape splitter1(shape);
    LocOpe_SplitShape splitter2(tool);
    TopOpeBRep_ShapeIntersector intersector;
    for(intersector.InitIntersection(shape,tool);
        intersector.MoreIntersection();
        intersector.NextIntersection()
    ) {
        if(verbose&Cutting) {
            cout << "++++++++++++++++++++++++++++++++++++++++"
                "++++++++++++++++++++++++++++++++++++++++\n";
            intersector.DumpCurrent(1); cout << " --> ";
            intersector.DumpCurrent(2); cout << '\n';
        }

        TopOpeBRep_EdgesIntersector &ee=intersector.ChangeEdgesIntersector();
        if( intersector.CurrentGeomShape(1).ShapeType()==TopAbs_EDGE &&
            intersector.CurrentGeomShape(2).ShapeType()==TopAbs_EDGE
        ) {
            for(ee.InitPoint(); ee.MorePoint(); ee.NextPoint()) {
                TopOpeBRep_Point2d const &p=ee.Point();
                if(verbose&Cutting)
                    cout << "point loop " << p.Parameter(1) << '\n';
                TopoDS_Vertex vertex;
                if(p.IsVertex(1))
                    vertex=p.Vertex(1);
                else if(p.IsVertex(2))
                    vertex=p.Vertex(2);
                else
                    vertex=BRepBuilderAPI_MakeVertex(p.Value());
                if(!p.IsVertex(1)) {
                    TopoDS_Edge edge=TopoDS::Edge(ee.Edge(1));
                    if(!splitter1.CanSplit(edge)) {
                        if(verbose&Cutting)
                            cout << "Cannot split 1\n";;
                    } else {
                        if(verbose&Cutting)
                            cout << "splitting model 1\n";
                        try { splitter1.Add(vertex,p.Parameter(1),edge); }
                        catch(Standard_ConstructionError c) {
                            if(verbose&Cutting)
                                cout << "Ooops \n";
                        }
                    }
                }
                if(!p.IsVertex(2)) {
                    TopoDS_Edge edge=TopoDS::Edge(ee.Edge(2));
                    if(!splitter2.CanSplit(edge)) {
                        if(verbose&Cutting)
                            cout << "Cannot split 2\n";;
                    } else {
                        if(verbose&Cutting)
                            cout << "splitting model 2\n";
                        try { splitter2.Add(vertex,p.Parameter(2),edge); }
                        catch(Standard_ConstructionError c) {
                            if(verbose&Cutting)
                                cout << "Ooops \n";
                        }
                    }
                }
            }
        }
    }

    /***************************************************************************
        Not all intersections seem to be caught, this is an attempt to catch
        some missing intersections. FIXME, this is almost certainly incomplete.
    ***************************************************************************/
    TopTools_IndexedMapOfShape edges, faces, vertices;
    vertices.Clear();
    TopExp::MapShapes(shape,TopAbs_VERTEX,vertices);
    TopExp::MapShapes(tool,TopAbs_VERTEX,vertices);

    edges.Clear();
    TopExp::MapShapes(shape,TopAbs_EDGE,edges);
    for(int e=1; e<=edges.Extent(); e++) {
        TopoDS_Edge edge=TopoDS::Edge(edges(e));
        TopoDS_Vertex o1, o2;
        TopExp::Vertices(edge,o1,o2);
        int skip1=vertices.FindIndex(o1);
        int skip2=vertices.FindIndex(o2);
        for(int v=1; v<=vertices.Extent(); v++) {
            if(v==skip1 || v==skip2)
                continue;
            TopoDS_Vertex vertex=TopoDS::Vertex(vertices(v));
            BRepExtrema_ExtPC distance(vertex,edge);
            if(!distance.IsDone())
                continue;
            double tolerance=std::max(BRep_Tool::Tolerance(edge),
                                      BRep_Tool::Tolerance(vertex));
            for(int i=1;i<=distance.NbExt();i++) {
#if (OCC_VERSION_MAJOR == 6) && (OCC_VERSION_MINOR < 5)
              double value = distance.Value(i);
#else
              double value = distance.SquareDistance(i);
#endif
              if(value<tolerance) {
                    try {
                        // No idea why this can fail
                        splitter1.Add(vertex,distance.Parameter(i),edge);
                    }
                    catch(Standard_ConstructionError c) {
                        if(verbose&Cutting) {
                            cout << "Adding vertex to edge failed\n";
                            TopoDS_Vertex v1, v2;
                            TopExp::Vertices(edge,v1,v2);
                            if(BRepTools::Compare(v1,vertex))
                                cout << "Merge v1\n";
                            if(BRepTools::Compare(v2,vertex))
                                cout << "Merge v2\n";
                            double d1=BRep_Tool::Pnt(v1).Distance(
                                BRep_Tool::Pnt(vertex));
                            double d2=BRep_Tool::Pnt(v2).Distance(
                                BRep_Tool::Pnt(vertex));
                            cout << "Adding " << i << " to edge " << e
                                << " distance=" << value
                                << " parameter=" << distance.Parameter(i)
                                << " point=" << distance.Point(i)
                                << " dv1=" << d1
                                << " dv2=" << d2
                                << endl;
                            BRepTools::Dump(vertex,cout);
                            BRepTools::Dump(edge,cout);
                        }
                    }
                }
            }
        }
    }

    edges.Clear();
    TopExp::MapShapes(tool,TopAbs_EDGE,edges);
    for(int e=1; e<=edges.Extent(); e++) {
        TopoDS_Edge edge=TopoDS::Edge(edges(e));
        TopoDS_Vertex o1, o2;
        TopExp::Vertices(edge,o1,o2);
        int skip1=vertices.FindIndex(o1);
        int skip2=vertices.FindIndex(o2);
        for(int v=1; v<=vertices.Extent(); v++) {
            if(v==skip1 || v==skip2)
                continue;
            TopoDS_Vertex vertex=TopoDS::Vertex(vertices(v));
            BRepExtrema_ExtPC distance(vertex,edge);
            if(!distance.IsDone())
                continue;
            double tolerance=std::max(BRep_Tool::Tolerance(edge),
                                      BRep_Tool::Tolerance(vertex));
            for(int i=1;i<=distance.NbExt();i++) {
#if (OCC_VERSION_MAJOR == 6) && (OCC_VERSION_MINOR < 5)
              double value = distance.Value(i);
#else
              double value = distance.SquareDistance(i);
#endif
              if(value<tolerance) {
                    try {
                        splitter2.Add(vertex,distance.Parameter(i),edge);
                    }
                    catch(Standard_ConstructionError c) {
                        if(verbose&Cutting) {
                            cout << "Adding vertex to edge failed\n";
                            TopoDS_Vertex v1, v2;
                            TopExp::Vertices(edge,v1,v2);
                            if(BRepTools::Compare(v1,vertex))
                                cout << "Merge v1\n";
                            if(BRepTools::Compare(v2,vertex))
                                cout << "Merge v2\n";
                            double d1=BRep_Tool::Pnt(v1).Distance(
                                BRep_Tool::Pnt(vertex));
                            double d2=BRep_Tool::Pnt(v2).Distance(
                                BRep_Tool::Pnt(vertex));
                            cout << "Adding " << i << " to edge " << e
                                << " distance=" << value
                                << " parameter=" << distance.Parameter(i)
                                << " point=" << distance.Point(i)
                                << " dv1=" << d1
                                << " dv2=" << d2
                                << endl;
                            BRepTools::Dump(vertex,cout);
                            BRepTools::Dump(edge,cout);
                        }
                    }
                }
            }
        }
    }

    /***************************************************************************
        We need the shapes with all the edge-edge intersections to split
        all the faces. All vertices and edges which can be merged, will
        be merged.
    ***************************************************************************/
    TopoDS_Compound intermediate1;
    BB.MakeCompound(intermediate1);
    for(TopTools_ListIteratorOfListOfShape p(splitter1.DescendantShapes(shape));
        p.More();
        p.Next()
    ) {
        BB.Add(intermediate1,p.Value());
    }
    TopoDS_Compound intermediate2;
    BB.MakeCompound(intermediate2);
    for(TopTools_ListIteratorOfListOfShape p(splitter2.DescendantShapes(tool));
        p.More();
        p.Next()
    ) {
        BB.Add(intermediate2,p.Value());
    }
    if(verbose&Cutting) {
        cout << "Before merging vertices and edges\n";
        TopoDS_Compound t;
        BB.MakeCompound(t);
        BB.Add(t,intermediate1);
        BB.Add(t,intermediate2);
        PrintItemCount(t);
    }
    MergeVertices(intermediate1,intermediate2);
    MergeEdges(intermediate1,intermediate2);
    if(verbose&Cutting) {
        cout << "After merging vertices and edges\n";
        TopoDS_Compound t;
        BB.MakeCompound(t);
        BB.Add(t,intermediate1);
        BB.Add(t,intermediate2);
        PrintItemCount(t);
    }

    // Create the result
    TopoDS_Compound result;
    BB.MakeCompound(result);
    BB.Add(result,intermediate1);
    BB.Add(result,intermediate2);

    // Add any missing PCurves
    for(TopExp_Explorer face(result,TopAbs_FACE); face.More(); face.Next()) {
        for(TopExp_Explorer edge(face.Current(),TopAbs_EDGE);
            edge.More();
            edge.Next()
        ) {
            Standard_Real s, e;
            TopoDS_Edge c_edge=TopoDS::Edge(edge.Current());
            TopoDS_Face c_face=TopoDS::Face(face.Current());
            Handle_Geom2d_Curve c=BRep_Tool::CurveOnSurface(c_edge,c_face,s,e);
            if(c.IsNull()) {
                if(verbose&Cutting)
                    cout << "Adding missing PCurve\n";
                ShapeFix_Edge().FixAddPCurve(c_edge,c_face,false,1e-7);
            }
        }
    }

    /***************************************************************************
        We determine which edges/wires are going to cut a face. To do this
        we create a map of FaceCutters which is indexed by the face number
        in the faces map. The FaceCutters generate the correct cutting wires.
    ***************************************************************************/
    int retry;
do {
    if(verbose&Cutting)
        std::cout << "STARTED CUTTING\n";
    retry=0;
    edges.Clear(); TopExp::MapShapes(result,TopAbs_EDGE,edges);
    faces.Clear(); TopExp::MapShapes(result,TopAbs_FACE,faces);
    cutmap_t cutters=SelectCuttingEdges(edges,faces);

    /***************************************************************************
        Apply all face splits stored in the map.
    ***************************************************************************/
    int cut_count=0;
    LocOpe_SplitShape splitter(result);
    for(cutmap_t::iterator f=cutters.begin(); f!=cutters.end(); f++) {
        TopoDS_Face const &face=TopoDS::Face(faces(f->first));
        FaceCutters &cutter=f->second;
        cut_count+=cutter.size();
        if(verbose&Cutting) {
            cout << "Cutting face " << f->first << " *************************\n";
            BRepTools::Dump(face,cout);
        }
        cutter.Build(face,result,verbose);
        for(FaceCutters::iterator p=cutter.begin(); p!=cutter.end(); p++) {
            TopTools_IndexedMapOfShape edges;
            TopExp::MapShapes(*p,TopAbs_EDGE,edges);
            if(edges.Extent()<3 && BRep_Tool::IsClosed(*p)) {
                // FIXME This doesn't work.
                cout << "IGNORED Closed wire with less than three edges\n";
                continue;
            }
            //BRepTools::Dump(*p,cout);
            try {
                splitter.Add(*p,face);
            }
            catch(Standard_ConstructionError c) {
                cout << "splitting the face failed\n";
                retry=1;
            }
        }
    }
    if(verbose&Cutting)
        cout << cut_count << " cuts in " << cutters.size() << " faces\n";

    // Create the final shape with the cutted faces.
    TopoDS_Compound cutted;
    BB.MakeCompound(cutted);
    int count=0;
    for(TopTools_ListIteratorOfListOfShape p(splitter.DescendantShapes(result));
        p.More();
        p.Next()
    ) {
        if(++count==1) {
            if(verbose&Cutting) {
                cout << "--------- " << count << " ---------------------------\n";
                BRepTools::Dump(p.Value(),cout);
            }
            BB.Add(cutted,p.Value());
        }
    }
    MergeFaces(cutted);
    result=cutted;
} while(0 && retry);
    target=result;
}
Пример #23
0
OnionTree_Ptr OnionTree::load_postorder_text(std::istream& is)
{
	std::string line;

	LineIO::portable_getline(is, line);
	int mapCount;
	try							{ mapCount = lexical_cast<int>(line); }
	catch(bad_lexical_cast&)	{ throw Exception("The map count is not a number"); }

	LineIO::portable_getline(is, line);
	int nodeCount;
	try							{ nodeCount = lexical_cast<int>(line); }
	catch(bad_lexical_cast&)	{ throw Exception("The onion node count is not a number"); }

	std::vector<OnionNode_Ptr> nodes(nodeCount);

	int n = 0;
	while(n < nodeCount && LineIO::portable_getline(is, line))
	{
		typedef boost::char_separator<char> sep;
		typedef boost::tokenizer<sep> tokenizer;

		tokenizer tok(line, sep(" "));
		std::vector<std::string> tokens(tok.begin(), tok.end());
		size_t tokenCount = tokens.size();
		if(tokenCount < 2) throw Exception("Bad onion node: " + lexical_cast<std::string>(n));

		if(tokens[1] == "B")
		{
			if(tokenCount != 11 || tokens[5] != "(" || tokens[10] != ")")
				throw Exception("Bad branch node: " + lexical_cast<std::string>(n));

			int leftIndex, rightIndex;
			double a, b, c, d;
			try
			{
				leftIndex = lexical_cast<int>(tokens[2]);
				rightIndex = lexical_cast<int>(tokens[3]);
				a = lexical_cast<double>(tokens[6]);
				b = lexical_cast<double>(tokens[7]);
				c = lexical_cast<double>(tokens[8]);
				d = lexical_cast<double>(tokens[9]);
			}
			catch(bad_lexical_cast&)	{ throw Exception("One of the values was not a number in branch node: " + lexical_cast<std::string>(n)); }

			OnionNode_Ptr left = nodes[leftIndex];
			OnionNode_Ptr right = nodes[rightIndex];
			if(left && right)
			{
				Plane_Ptr splitter(new Plane(Vector3d(a,b,c), d));
				nodes[n] = OnionNode_Ptr(new OnionBranch(n, splitter, left, right));
			}
			else throw Exception("The onion nodes are not stored in postorder: the child nodes for this branch have not yet been loaded");
		}
		else
		{
			// We're dealing with an onion leaf.
			if(tokenCount < 8 || tokens[1] != "(" || tokens[3] != ")" || tokens[6] != "[" || tokens[tokenCount-1] != "]")
				throw Exception("Bad leaf node: " + lexical_cast<std::string>(n));

			if(tokens[2].length() != mapCount)
				throw Exception("Bad leaf solidity descriptor: " + lexical_cast<std::string>(n));

			// Construct the solidity descriptor.
			boost::dynamic_bitset<> solidityDescriptor(mapCount);
			for(size_t i=0, len=tokens[2].length(); i<len; ++i)
			{
				if(tokens[2][i] == '0') solidityDescriptor.set(i, false);
				else if(tokens[2][i] == '1') solidityDescriptor.set(i, true);
				else throw Exception("Bad leaf solidity descriptor: " + lexical_cast<std::string>(n));
			}

			// Read in any polygon indices.
			int polyCount;
			try							{ polyCount = lexical_cast<int>(tokens[5]); }
			catch(bad_lexical_cast&)	{ throw Exception("The leaf polygon count is not a number: " + lexical_cast<std::string>(n)); }

			std::vector<int> polyIndices;

			for(size_t i=7; i<tokenCount-1; ++i)
			{
				int polyIndex;
				try							{ polyIndex = lexical_cast<int>(tokens[i]); }
				catch(bad_lexical_cast&)	{ throw Exception("A polygon index is not a number in leaf: " + lexical_cast<std::string>(n)); }

				polyIndices.push_back(polyIndex);
			}

			nodes[n].reset(new OnionLeaf(n, solidityDescriptor, polyIndices));
		}

		++n;
	}

	return OnionTree_Ptr(new OnionTree(nodes, mapCount));
}
Пример #24
0
		void splitHeaders(const SharedBuffer& sb, std::vector<std::string>& headers) {
			std::string src(sb.buffer(), sb.size());
			StringSplitter splitter(src, "\r\n", false);
			const std::vector<std::string>& lines = splitter.get();
			headers.insert(headers.begin(), lines.begin(), lines.end());
		}
Пример #25
0
bool KateCommands::SedReplace::exec (Kate::View *view, const QString &cmd, QString &msg)
{
   kdDebug(13025)<<"SedReplace::execCmd( "<<cmd<<" )"<<endl;

  QRegExp delim("^[$%]?s\\s*([^\\w\\s])");
  if ( delim.search( cmd ) < 0 ) return false;

  bool fullFile=cmd[0]=='%';
  bool noCase=cmd[cmd.length()-1]=='i' || cmd[cmd.length()-2]=='i';
  bool repeat=cmd[cmd.length()-1]=='g' || cmd[cmd.length()-2]=='g';
  bool onlySelect=cmd[0]=='$';

  QString d = delim.cap(1);
   kdDebug(13025)<<"SedReplace: delimiter is '"<<d<<"'"<<endl;

  QRegExp splitter( QString("^[$%]?s\\s*")  + d + "((?:[^\\\\\\" + d + "]|\\\\.)*)\\" + d +"((?:[^\\\\\\" + d + "]|\\\\.)*)\\" + d + "[ig]{0,2}$" );
  if (splitter.search(cmd)<0) return false;

  QString find=splitter.cap(1);
   kdDebug(13025)<< "SedReplace: find=" << find.latin1() <<endl;

  QString replace=splitter.cap(2);
  exchangeAbbrevs(replace);
   kdDebug(13025)<< "SedReplace: replace=" << replace.latin1() <<endl;

   if ( find.contains("\\n") )
   {
     msg = i18n("Sorry, but Kate is not able to replace newlines, yet");
     return false;
   }

  KateDocument *doc = ((KateView*)view)->doc();
  if ( ! doc ) return false;

  doc->editStart();

  int res = 0;

  if (fullFile)
  {
    uint numLines=doc->numLines();
    for (int line=0; (uint)line < numLines; line++)
    {
      res += sedMagic( doc, line, find, replace, d, !noCase, repeat );
      if ( ! repeat && res ) break;
    }
  }
  else if (onlySelect)
  {
    int startline = doc->selStartLine();
    uint startcol = doc->selStartCol();
    int endcol = -1;
    do {
      if ( startline == doc->selEndLine() )
        endcol = doc->selEndCol();

      res += sedMagic( doc, startline, find, replace, d, !noCase, repeat, startcol, endcol );

      /*if ( startcol )*/ startcol = 0;

      startline++;
    } while ( (int)startline <= doc->selEndLine() );
  }
  else // just this line
  {
    int line=view->cursorLine();
    res += sedMagic(doc, line, find, replace, d, !noCase, repeat);
  }

  msg = i18n("1 replacement done", "%n replacements done",res );

  doc->editEnd();

  return true;
}
Пример #26
0
TEST(TestStringSplitter, EmptyTest)
{
    const char* str = "";
    StringSplitter splitter(str, ',');
    EXPECT_EQ(splitter, false);
}
Пример #27
0
void get_defaults(char *filename, struct udata *ud)
{
	config_t cfg, *cf;
	const char *value;
#if LIBCONFIG_VER_MAJOR == 1
# if LIBCONFIG_VER_MINOR >= 4
	int ival;
# endif
# else
	long ival;
#endif

	if (access(filename, R_OK) == -1) {
		olog(LOG_ERR, "Cannot read defaults from %s: %s", filename, strerror(errno));
		return;
	}

	config_init(cf = &cfg);

	if (!config_read_file(cf, filename)) {
		olog(LOG_ERR, "Syntax error in %s:%d - %s",
			filename,
			config_error_line(cf),
			config_error_text(cf));
		config_destroy(cf);
		exit(2);
	}

	if (config_lookup_string(cf, "OTR_STORAGEDIR", &value) != CONFIG_FALSE)
		strcpy(STORAGEDIR, value);

	if (ud == NULL) {
		/* being invoked by ocat; return */
		return;
	}
#if WITH_MQTT
	if (config_lookup_string(cf, "OTR_HOST", &value) != CONFIG_FALSE) {
		if (ud->hostname) free(ud->hostname);
		ud->hostname = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_PORT", &ival) != CONFIG_FALSE) {
		ud->port = ival;
	}
	if (config_lookup_string(cf, "OTR_USER", &value) != CONFIG_FALSE) {
		if (ud->username) free(ud->username);
		ud->username = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_string(cf, "OTR_PASS", &value) != CONFIG_FALSE) {
		if (ud->password) free(ud->password);
		ud->password = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_QOS", &ival) != CONFIG_FALSE) {
		ud->qos = ival;
	}
	if (config_lookup_string(cf, "OTR_CLIENTID", &value) != CONFIG_FALSE) {
		if (ud->clientid) free(ud->clientid);
		ud->clientid = (value) ? strdup(value) : NULL;
	}

	if (config_lookup_string(cf, "OTR_CAFILE", &value) != CONFIG_FALSE) {
		if (ud->cafile) free(ud->cafile);
		ud->cafile = (value) ? strdup(value) : NULL;
	}

	/* Topics is a blank-separated string of words; split and add to JSON array */
	if (config_lookup_string(cf, "OTR_TOPICS", &value) != CONFIG_FALSE) {
		char *parts[40];
		int np, n;
		if (ud->topics) json_delete(ud->topics);

		if ((np = splitter((char *)value, " ", parts)) < 1) {
			olog(LOG_ERR, "Illegal value in OTR_TOPICS");
			exit(2);
		}
		ud->topics = json_mkarray();

		for (n = 0; n < np; n++) {
			json_append_element(ud->topics, json_mkstring(parts[n]));
		}
		splitterfree(parts);
	}
#endif /* WITH_MQTT */

	if (config_lookup_string(cf, "OTR_GEOKEY", &value) != CONFIG_FALSE) {
		if (ud->geokey) free(ud->geokey);
		ud->geokey = (value) ? strdup(value) : NULL;
	}

	if (config_lookup_int(cf, "OTR_PRECISION", &ival) != CONFIG_FALSE) {
		geohash_setprec(ival);
	}

#if WITH_HTTP
	if (config_lookup_string(cf, "OTR_HTTPHOST", &value) != CONFIG_FALSE) {
		if (ud->http_host) free(ud->http_host);
		ud->http_host = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_HTTPPORT", &ival) != CONFIG_FALSE) {
		ud->http_port = ival;
	}
	if (config_lookup_string(cf, "OTR_HTTPLOGDIR", &value) != CONFIG_FALSE) {
		if (ud->http_logdir) free(ud->http_logdir);
		ud->http_logdir = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_string(cf, "OTR_BROWSERAPIKEY", &value) != CONFIG_FALSE) {
		if (ud->browser_apikey) free(ud->browser_apikey);
		ud->browser_apikey = (value) ? strdup(value) : NULL;
	}
#endif /* WITH_HTTP */

#if WITH_LUA
	if (config_lookup_string(cf, "OTR_LUASCRIPT", &value) != CONFIG_FALSE) {
		if (ud->luascript) free(ud->luascript);
		ud->luascript = (value) ? strdup(value) : NULL;
	}
#endif

	config_destroy(cf);
}
Пример #28
0
TEST(TestStringSplitter, NULLTest)
{
    const char* str = NULL;
    StringSplitter splitter(str, ',');
    EXPECT_EQ(splitter, false);
}