Example #1
0
// Action_Outtraj::Init()
Action::RetType Action_Outtraj::Init(ArgList& actionArgs, ActionInit& init, int debugIn)
{
  // Set up output traj
  std::string trajfilename = actionArgs.GetStringNext();
  if (trajfilename.empty()) {
    mprinterr("Error: No filename given.\nError: Usage: ");
    Help();
    return Action::ERR;
  }
  associatedParm_ = init.DSL().GetTopology(actionArgs);
  if (associatedParm_ == 0) {
    mprinterr("Error: Could not get associated topology for %s\n",trajfilename.c_str());
    return Action::ERR;
  }
  std::string rangeArg = actionArgs.GetStringKey("onlymembers");
  if (rangeArg.empty())
    isActive_ = true;
  else {
    Range members;
    if (members.SetRange( rangeArg )) return Action::ERR;
    isActive_ = members.InRange( init.DSL().EnsembleNum() );
  }
  // If maxmin, get the name of the dataset as well as the max and min values.
  double lastmin = 0.0;
  double lastmax = 0.0;
  while ( actionArgs.Contains("maxmin") ) {
    std::string datasetName = actionArgs.GetStringKey("maxmin");
    if (!datasetName.empty()) {
      DataSet* dset = init.DSL().GetDataSet(datasetName);
      if (dset==0) {
        mprintf("Error: maxmin: Could not get dataset %s\n",datasetName.c_str());
        return Action::ERR;
      } else {
        // Currently only allow int, float, or double datasets
        if (dset->Type() != DataSet::INTEGER &&
            dset->Type() != DataSet::FLOAT &&
            dset->Type() != DataSet::DOUBLE) 
        {
          mprinterr("Error: maxmin: Only int, float, or double dataset (%s) supported.\n",
                  datasetName.c_str());
          return Action::ERR;
        }
        Dsets_.push_back( (DataSet_1D*)dset );
        Max_.push_back( actionArgs.getKeyDouble("max",lastmax) );
        Min_.push_back( actionArgs.getKeyDouble("min",lastmin) );
        lastmax = Max_.back();
        lastmin = Min_.back();
      }
    } else {
      mprinterr("Error: maxmin Usage: maxmin <setname> max <max> min <min>\n");
      return Action::ERR;
    }
  }
# ifdef MPI
  trajComm_ = init.TrajComm();
  if (trajComm_.Size() > 1 && !Dsets_.empty()) {
    mprinterr("Error: outtraj 'maxmin' currently does not work when using > 1 thread\n"
              "Error:   to write trajectory (currently %i threads)\n", trajComm_.Size());
    return Action::ERR;
  }
  outtraj_.SetTrajComm( trajComm_ );
# endif
  // Initialize output trajectory with remaining arguments
  if (isActive_) {
    outtraj_.SetDebug(debugIn);
    if ( outtraj_.InitEnsembleTrajWrite(trajfilename, actionArgs.RemainingArgs(),
                                        TrajectoryFile::UNKNOWN_TRAJ, init.DSL().EnsembleNum()) )
      return Action::ERR;
  }
  isSetup_ = false;

  mprintf("    OUTTRAJ: Writing frames associated with topology '%s'\n", associatedParm_->c_str());
  if (!rangeArg.empty())
    mprintf("\tonlymembers: Only writing members %s\n", rangeArg.c_str());
  for (unsigned int ds = 0; ds < Dsets_.size(); ++ds)
    mprintf("\tmaxmin: Printing trajectory frames based on %g <= %s <= %g\n",
            Min_[ds], Dsets_[ds]->legend(), Max_[ds]);

  return Action::OK;
} 
Example #2
0
boost::iterator_range<descendant_iterator<typename Range::iterator> >
make_descendant(Range const& r) {
    return boost::make_iterator_range
            (descendant_iterator<typename Range::iterator>(r.begin(), r.end()),
             descendant_iterator<typename Range::iterator>());
}
String CodeEditorComponent::getTextInRange (const Range<int>& range) const
{
    return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
                                    CodeDocument::Position (&document, range.getEnd()));
}
bool InsertListCommand::doApplyForSingleParagraph(bool forceCreateList, const HTMLQualifiedName& listTag, Range& currentSelection)
{
    // FIXME: This will produce unexpected results for a selection that starts just before a
    // table and ends inside the first cell, selectionForParagraphIteration should probably
    // be renamed and deployed inside setEndingSelection().
    Node* selectionNode = endingSelection().start().anchorNode();
    Node* listChildNode = enclosingListChild(selectionNode);
    bool switchListType = false;
    if (listChildNode) {
        if (!listChildNode->parentNode()->hasEditableStyle())
            return false;
        // Remove the list child.
        RefPtrWillBeRawPtr<HTMLElement> listElement = enclosingList(listChildNode);
        if (!listElement) {
            listElement = fixOrphanedListChild(listChildNode);
            listElement = mergeWithNeighboringLists(listElement);
        }
        if (!listElement->hasTagName(listTag)) {
            // |listChildNode| will be removed from the list and a list of type
            // |m_type| will be created.
            switchListType = true;
        }

        // If the list is of the desired type, and we are not removing the list,
        // then exit early.
        if (!switchListType && forceCreateList)
            return true;

        // If the entire list is selected, then convert the whole list.
        if (switchListType && isNodeVisiblyContainedWithin(*listElement, currentSelection)) {
            bool rangeStartIsInList = visiblePositionBeforeNode(*listElement).deepEquivalent() == createVisiblePosition(currentSelection.startPosition()).deepEquivalent();
            bool rangeEndIsInList = visiblePositionAfterNode(*listElement).deepEquivalent() == createVisiblePosition(currentSelection.endPosition()).deepEquivalent();

            RefPtrWillBeRawPtr<HTMLElement> newList = createHTMLElement(document(), listTag);
            insertNodeBefore(newList, listElement);

            Node* firstChildInList = enclosingListChild(createVisiblePosition(firstPositionInNode(listElement.get())).deepEquivalent().anchorNode(), listElement.get());
            Element* outerBlock = firstChildInList && isBlockFlowElement(*firstChildInList) ? toElement(firstChildInList) : listElement.get();

            moveParagraphWithClones(createVisiblePosition(firstPositionInNode(listElement.get())), createVisiblePosition(lastPositionInNode(listElement.get())), newList.get(), outerBlock);

            // Manually remove listNode because moveParagraphWithClones sometimes leaves it behind in the document.
            // See the bug 33668 and editing/execCommand/insert-list-orphaned-item-with-nested-lists.html.
            // FIXME: This might be a bug in moveParagraphWithClones or deleteSelection.
            if (listElement && listElement->inDocument())
                removeNode(listElement);

            newList = mergeWithNeighboringLists(newList);

            // Restore the start and the end of current selection if they started inside listNode
            // because moveParagraphWithClones could have removed them.
            if (rangeStartIsInList && newList)
                currentSelection.setStart(newList, 0, IGNORE_EXCEPTION);
            if (rangeEndIsInList && newList)
                currentSelection.setEnd(newList, lastOffsetInNode(newList.get()), IGNORE_EXCEPTION);

            setEndingSelection(createVisiblePosition(firstPositionInNode(newList.get())));

            return true;
        }

        unlistifyParagraph(endingSelection().visibleStart(), listElement.get(), listChildNode);
    }

    if (!listChildNode || switchListType || forceCreateList)
        m_listElement = listifyParagraph(endingSelection().visibleStart(), listTag);

    return true;
}
Example #5
0
	virtual int evaluate(char* buf, int maxbuf, Range range) const {
		float vmax = range.isReversed()? range.rmax: range.rmin;
		return sprintf(buf, "%f", vmax);
	}
void cloth::SwFactory::extractSelfCollisionIndices(const Cloth& cloth, Range<uint32_t> destIndices) const
{
	const SwCloth& swCloth = static_cast<const SwClothImpl&>(cloth).mCloth;
	PX_ASSERT(destIndices.size() == swCloth.mSelfCollisionIndices.size());
	PxMemCopy(destIndices.begin(), swCloth.mSelfCollisionIndices.begin(), destIndices.size() * sizeof(uint32_t));
}
void cloth::SwFactory::extractFabricData(const Fabric& fabric, Range<uint32_t> phases, Range<uint32_t> sets,
                                         Range<float> restvalues, Range<uint32_t> indices, Range<uint32_t> anchors,
                                         Range<float> tetherLengths, Range<uint32_t> triangles) const
{
	const SwFabric& swFabric = static_cast<const SwFabric&>(fabric);

	PX_ASSERT(phases.empty() || phases.size() == swFabric.getNumPhases());
	PX_ASSERT(restvalues.empty() || restvalues.size() == swFabric.getNumRestvalues());
	PX_ASSERT(sets.empty() || sets.size() == swFabric.getNumSets());
	PX_ASSERT(indices.empty() || indices.size() == swFabric.getNumIndices());
	PX_ASSERT(anchors.empty() || anchors.size() == swFabric.getNumTethers());
	PX_ASSERT(tetherLengths.empty() || tetherLengths.size() == swFabric.getNumTethers());

	for(uint32_t i = 0; !phases.empty(); ++i, phases.popFront())
		phases.front() = swFabric.mPhases[i];

	const uint32_t* sEnd = swFabric.mSets.end(), *sIt;
	const float* rBegin = swFabric.mRestvalues.begin(), *rIt = rBegin;
	const uint16_t* iIt = swFabric.mIndices.begin();

	uint32_t* sDst = sets.begin();
	float* rDst = restvalues.begin();
	uint32_t* iDst = indices.begin();

	uint32_t numConstraints = 0;
	for(sIt = swFabric.mSets.begin(); ++sIt != sEnd;)
	{
		const float* rEnd = rBegin + *sIt;
		for(; rIt != rEnd; ++rIt)
		{
			uint16_t i0 = *iIt++;
			uint16_t i1 = *iIt++;

			if(PxMax(i0, i1) >= swFabric.mNumParticles)
				continue;

			if(!restvalues.empty())
				*rDst++ = *rIt;

			if(!indices.empty())
			{
				*iDst++ = i0;
				*iDst++ = i1;
			}

			++numConstraints;
		}

		if(!sets.empty())
			*sDst++ = numConstraints;
	}

	for(uint32_t i = 0; !anchors.empty(); ++i, anchors.popFront())
		anchors.front() = swFabric.mTethers[i].mAnchor;

	for(uint32_t i = 0; !tetherLengths.empty(); ++i, tetherLengths.popFront())
		tetherLengths.front() = swFabric.mTethers[i].mLength * swFabric.mTetherLengthScale;

	for(uint32_t i = 0; !triangles.empty(); ++i, triangles.popFront())
		triangles.front() = swFabric.mTriangles[i];
}
 size_t hash() const {
   return range.GetEndPos();
 }
 virtual bool operator==(const FFState& other) const {
   const DistortionState_traditional& o =
     static_cast<const DistortionState_traditional&>(other);
   return range.GetEndPos() == o.range.GetEndPos();
 }
Example #10
0
int LineChart::DrawScale(wxMemoryDC &dc){
	int leftOrientationEdge = 0;
	int rightOrientationEdge = _currentWidth - 1;

	int scaleOrientation = LineChart::ORIENTATION_LEFT;

	wxFont labelFont = GetFont();



	int tickLabelWidth = 0;
	for (SeriesMap::iterator it = m_seriesMap.begin(); it != m_seriesMap.end(); ++it){

		int maxLabelWidth = 0;
		Series *series = it->second;
		Range * range = m_rangeArray[series->GetRangeId()];


		double minValue = range->GetMin();
		double maxValue = range->GetMax();
		double rangeSize = maxValue - minValue;
		double stepInterval = (maxValue - minValue) / 10;
		if (stepInterval == 0) stepInterval = 1;

		dc.SetPen(*wxThePenList->FindOrCreatePen(series->GetColor(), 1, wxSOLID));

		dc.SetTextForeground(series->GetColor());

		bool labelOn = false;
		int tickLabelHeight,tickDescent,tickExternalLeading;
		dc.DrawLine(leftOrientationEdge, 0, leftOrientationEdge, _currentHeight);

		for (double tick = minValue; tick <=maxValue; tick += stepInterval){

			int y = _currentHeight - (double)_currentHeight * ((tick - minValue) / rangeSize);
			int nextY = _currentHeight - (double)_currentHeight * ((tick + stepInterval - minValue) / rangeSize);

			if (labelOn){
				wxString numberFormat = "%." + wxString::Format("%df", range->GetPrecision());
				wxString tickLabel = wxString::Format(numberFormat, tick);
				dc.GetTextExtent(tickLabel, &tickLabelHeight, &tickLabelWidth, &tickDescent, &tickExternalLeading, &labelFont);
				if (tickLabelHeight > maxLabelWidth) maxLabelWidth = tickLabelHeight;

				if (tickLabelWidth < y - nextY ){
					switch (scaleOrientation){
						case LineChart::ORIENTATION_LEFT:
						{
							dc.DrawRotatedText(tickLabel, leftOrientationEdge, y, 0);
							break;
						}
						case LineChart::ORIENTATION_RIGHT:
						{
							dc.DrawRotatedText(tickLabel, rightOrientationEdge, y, 0);
							break;
						}
					}
				}
			}
			labelOn = !labelOn;
			dc.DrawLine(leftOrientationEdge, y, leftOrientationEdge + tickLabelWidth, y);
		}

		maxLabelWidth+=(tickLabelWidth / 2);
		switch (scaleOrientation){
			case LineChart::ORIENTATION_LEFT:
			{
				leftOrientationEdge += (maxLabelWidth);
				break;
			}
			case LineChart::ORIENTATION_RIGHT:
			{
				rightOrientationEdge -= (maxLabelWidth);
				break;
			}
		}
	}
	return leftOrientationEdge;
}
void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
{
    selectRegion (CodeDocument::Position (document, newRange.getStart()),
                  CodeDocument::Position (document, newRange.getEnd()));
}
Example #12
0
void LineChart::OnPaint(wxPaintEvent &event){

	wxPaintDC old_dc(this);

	float zoomFactor = (float)_zoomPercentage / 100;

	int w,h ;
	GetClientSize(&w,&h);

	if (w != _currentWidth || h != _currentHeight){
		delete (_memBitmap);
		_currentWidth = w;
		_currentHeight = h;
		_memBitmap = new wxBitmap(_currentWidth, _currentHeight);
	}
	/////////////////
	// Create a memory DC
	wxMemoryDC dc;
	dc.SelectObject(*_memBitmap);

	wxColor backColor = GetBackgroundColour();
	dc.SetBackground(*wxTheBrushList->FindOrCreateBrush(backColor,wxSOLID));
	dc.SetBrush(*wxTheBrushList->FindOrCreateBrush(backColor,wxSOLID));
	dc.Clear();
	DrawGrid(dc);

	if (m_showScale){
		m_leftEdge = DrawScale(dc);
	}
	else{
		m_leftEdge = 0;
	}

	size_t largestBufferSize = GetMaxSeriesBufferSize();
	double lastValue = 0;
	for (SeriesMap::iterator it = m_seriesMap.begin(); it != m_seriesMap.end(); ++it){

		float currentX = (float)m_leftEdge;
		int lastX = (int)currentX;
		int lastY;

		Series *series = it->second;
		dc.SetPen(*wxThePenList->FindOrCreatePen(series->GetColor(), 1, wxSOLID));
		size_t bufSize = series->GetBufferSize();
		Range *range = m_rangeArray[series->GetRangeId()];
		if (bufSize > 0){

			double minValue = range->GetMin();
			double maxValue = range->GetMax();

			double loggedValue = series->GetValueAt(0);

			double percentageOfMax = (loggedValue - minValue) / (maxValue - minValue);
			lastY = h - (int)(((double)h) * percentageOfMax);

			size_t i = (size_t)(((double)largestBufferSize) * m_viewOffsetFactor);

			while (i < bufSize && currentX < _currentWidth ){
				if (i == m_markerIndex){
					wxPen pen = dc.GetPen();
					dc.SetPen(*wxThePenList->FindOrCreatePen(*wxLIGHT_GREY, 1, wxSOLID));
					dc.DrawLine(currentX, 0, currentX, _currentHeight);
					DrawCurrentValues(dc, i, currentX, CURRENT_VALUES_TOP_OFFSET);
					dc.SetPen(pen);
				}

				loggedValue = series->GetValueAt(i);

				if (DatalogValue::NULL_VALUE == loggedValue){
					loggedValue = lastValue;
				}
				else{
					lastValue = loggedValue;
				}

				double percentageOfMax = (loggedValue - minValue) / (maxValue - minValue);

				int y = h - (int)(((double)h) * percentageOfMax);

				dc.DrawLine(lastX, lastY, (int)currentX, y);
				lastX = (int)currentX;
				lastY = y;
				currentX += zoomFactor;
				i++;
			}
		}
	}
	if (m_showData) DrawMouseoverMarker(dc);
	//blit into the real DC
	old_dc.Blit(0,0,_currentWidth,_currentHeight,&dc,0,0);

}
Example #13
0
bool compare()
{
  Range range;
  EntityHandle hex[2];
  EntityHandle dod[2];
  Tag elemtag;
  Range::iterator iter;
  
  // get tag
  if (MB_SUCCESS != iface->tag_get_handle( bitname, 2, MB_TYPE_BIT, elemtag ))
    moab_error( "tag_get_handle" );
  
  // get two hexes
  char two = '\002';
  const void* tarray[] = { &two };
  if (MB_SUCCESS != iface->
      get_entities_by_type_and_tag( 0, MBHEX, &elemtag, tarray, 1, range ))
    moab_error( "get_entities_by_type_and_tag" );
  if (range.size() != 2)
  {
    fprintf( stderr, "Expected 2 Hexes.  Got %lu\n", (unsigned long)range.size() );
    exit( 1 );
  }
  iter = range.begin();
  hex[0] = *iter;
  hex[1] = *++iter;
  
  // get two polyhedra
  range.clear();
  char one = '\001';
  const void* oarray[] = { &one };
  if (MB_SUCCESS != iface->
      get_entities_by_type_and_tag( 0, MBPOLYHEDRON, &elemtag, oarray, 1, range ))
    moab_error( "get_entities_by_type_and_tag" );
  if (range.size() != 2)
  {
    fprintf( stderr, "Expected 2 Polyhedra.  Got %lu\n", (unsigned long)range.size() );
    exit( 1 );
  }
  iter = range.begin();
  dod[0] = *iter;
  dod[1] = *++iter;
  
  // compare hexes
  std::vector<EntityHandle> conn[2];
  if (MB_SUCCESS != iface->get_connectivity( hex  , 1, conn[0] ) ||
      MB_SUCCESS != iface->get_connectivity( hex+1, 1, conn[1] ))
    moab_error( "get_connectivity" );
  if (!compare_conn( conn[0], conn[1] ))
    return false;
  
  // compare polyhedra
  
  std::vector<EntityHandle> face[2];
  conn[0].clear(); conn[1].clear();
  if (MB_SUCCESS != iface->get_connectivity( dod  , 1, conn[0], false ) ||
      MB_SUCCESS != iface->get_connectivity( dod+1, 1, conn[1], false ))
    moab_error( "get_connectivity" );
  if (conn[0].size() != 12 || conn[1].size() != 12)
  {
    fprintf(stderr, "Expected two dodecahedrons.  Got polyhedrons with "
                    "%lu and %lu faces respectively.\n", 
                    (unsigned long)conn[0].size(), (unsigned long)conn[1].size() );
    return false;
  }
  
  for (int i = 0; i < 12; ++i )
  {
    face[0].clear(); face[1].clear();
    if (MB_SUCCESS != iface->get_connectivity( &conn[0][i], 1, face[0], false) ||
        MB_SUCCESS != iface->get_connectivity( &conn[1][i], 1, face[1], false))
      moab_error( "get_connectivity" );
    if (!compare_conn( face[0], face[1] ))
      return false;
  }
  
  // compare sets
  
  if (!compare_sets( VERTEX_SET_ID, tagname ) ||
      !compare_sets( FACE_SET_ID ) ||
      !compare_sets( REGION_SET_ID ) ||
      !compare_sets( EMPTY_SET_ID ) ||
      !compare_sets( SET_SET_ID, GLOBAL_ID_TAG_NAME ))
    return false;
    
  // check tags
  if (!compare_tags( dod ))
    return false;
  
  return true;
}
Example #14
0
/* Compare the two sets with the specified global id.
   If tag_name is not null, compare all entities in the
   sets using the value of the tag to match entities.
   Tag must be an integer type.
 */
bool compare_sets( int id, const char* tag_name = 0 )
{
  bool ok;
  ErrorCode rval;
  
  // get sets
 
  Tag id_tag;
  if (MB_SUCCESS != iface->tag_get_handle( GLOBAL_ID_TAG_NAME, 1, MB_TYPE_INTEGER,id_tag ))
  {
    fprintf(stderr, "Could not find global id tag in file.\n");
    return false;
  }
  
  Range range;
  const void* tag_data[] = { &id };
  rval = iface->get_entities_by_type_and_tag( 0, MBENTITYSET, &id_tag, tag_data, 1, range );
  if (MB_ENTITY_NOT_FOUND == rval || range.size() != 2)
  {
    fprintf(stderr, "Could not find set with id %d pair in file\n", id );
    return false;
  }
  else if (MB_SUCCESS != rval)
    moab_error( "get_entities_by_type_and_tag" );
  
  EntityHandle set1 = *range.begin();
  EntityHandle set2 = *++range.begin();
  
    // Compare set descriptions

  unsigned opt1, opt2;
  if (MB_SUCCESS != iface->get_meshset_options( set1, opt1 ) ||
      MB_SUCCESS != iface->get_meshset_options( set2, opt2 ))
    moab_error( "get_meshset_options" );
  
  if (opt1 != opt2)
  {
    fprintf(stderr, "Sets with id %d do not have matching options.\n"
                    "Set 1: track_owner=%s set=%s ordered=%s\n"
                    "Set 2: track_owner=%s set=%s ordered=%s\n",
                    id,
                    opt1 & MESHSET_TRACK_OWNER ? "yes" : "no",
                    opt1 & MESHSET_SET         ? "yes" : "no",
                    opt1 & MESHSET_ORDERED     ? "yes" : "no",
                    opt2 & MESHSET_TRACK_OWNER ? "yes" : "no",
                    opt2 & MESHSET_SET         ? "yes" : "no",
                    opt2 & MESHSET_ORDERED     ? "yes" : "no" );
    return false;
  }

    // Compare set contents
    // First check if same number of entities.
    // Then select from three possible methods to compare set contents
    //  o If caller gave us a tag to use, compare entities by tag value
    //  o If set is ordered, compare entity types in order
    //  o Otherwise compare counts of entity types in sets

  std::vector<EntityHandle> list1, list2;
  if (MB_SUCCESS != iface->get_entities_by_handle( set1, list1 ) ||
      MB_SUCCESS != iface->get_entities_by_handle( set2, list2 ))
    moab_error( "get_entities_by_handle" );
      
  if (list1.size() != list2.size())
  {
    fprintf(stderr, "Sets with id %d do not have the same number of entities.\n"
                    "Set 1 : %u  Set 2 : %u\n", 
                    id, (unsigned)list1.size(), (unsigned)list2.size() );
    return false;
  }
  
  if (tag_name) // compare contents using tag value
  {
    Tag tag;
    if (MB_SUCCESS != iface->tag_get_handle( tag_name, 0, MB_TYPE_OPAQUE, tag, MB_TAG_ANY ))
    {
      fprintf(stderr, "Could not find tag \"%s\" in file.\n", tag_name);
      return false;
    }
    
      // Make sure tag is integer type
    DataType type;
    if (MB_SUCCESS != iface->tag_get_data_type( tag, type ))
      moab_error( "tag_get_data_type" );
    if (MB_TYPE_INTEGER != type && MB_TYPE_OPAQUE != type)
      moab_error( "compare_sets" );
    
    std::vector<int> data1( list1.size() ), data2( list2.size() );
    if (MB_SUCCESS != iface->tag_get_data( tag, &list1[0], list1.size(), &data1[0] )
     || MB_SUCCESS != iface->tag_get_data( tag, &list2[0], list2.size(), &data2[0] ))
      moab_error("tag_get_data");
  
    if (!(opt1 & MESHSET_ORDERED))
    {
      std::sort( data1.begin(), data1.end() );
      std::sort( data2.begin(), data2.end() );
    }
    
    for (unsigned i = 0; i < data1.size(); ++i)
      if (data1[i] != data2[i])
      {
        fprintf( stderr, "Entities in sets with id %d do not have matching tag values.\n", id );
        return false;
      }
  }
  else if (opt1 & MESHSET_ORDERED) // compare types of each entity in set
  {
    ok = true;
    for (unsigned i = 0; i < list1.size(); ++i)
      if (iface->type_from_handle(list1[i]) != iface->type_from_handle(list2[i]))
      {
        fprintf(stderr, "Entities at position %u in ordered sets with id %d\n"
                        "have different types.\n", i, id );
        ok = false;
      }
    if (!ok)
      return false;
  }
  else // compare count of entity types in each set
  {
    unsigned counts1[MBMAXTYPE], counts2[MBMAXTYPE];
    memset( counts1, 0, MBMAXTYPE * sizeof(unsigned) );
    memset( counts2, 0, MBMAXTYPE * sizeof(unsigned) );
    for (unsigned i = 0; i < list1.size(); ++i)
    {
      counts1[iface->type_from_handle(list1[i])]++;
      counts2[iface->type_from_handle(list2[i])]++;
    }

    ok = true;
    for (int j = 0; j < MBMAXTYPE; ++j)
      if (counts1[j] != counts2[j])
      {
        fprintf(stderr, "Sets with id %d have differing numbers of %s: %u and %u\n",
                id, CN::EntityTypeName((EntityType)j), counts1[j], counts2[j] );
        ok = false;
      }
    if (!ok)
      return false;
  }

    // Compare set parent/child links using global id

  ok = true;
  const char* words[] = { "children", "parents" };
  std::vector<EntityHandle> adj1, adj2;
  for (unsigned two = 0; two < 2; ++two)
  {
    adj1.clear(); adj2.clear();
    if (two) 
    {
      if (MB_SUCCESS != iface->get_parent_meshsets(set1, adj1) ||
          MB_SUCCESS != iface->get_parent_meshsets(set2, adj2))
        moab_error( "get_parent_meshsets" );
    }
    else
    {
      if (MB_SUCCESS != iface->get_child_meshsets(set1, adj1) ||
          MB_SUCCESS != iface->get_child_meshsets(set2, adj2))
        moab_error( "get_child_meshsets" );
    }
    
    if (adj1.size() != adj2.size())
    {
      fprintf(stderr, "Sets with id %d have different number of %s: %u and %u\n",
        id, words[two], (unsigned)adj1.size(), (unsigned)adj2.size() );
      ok = false;
      continue;
    }
    
    std::vector<int> ids1(adj1.size()), ids2(adj2.size());
    unsigned i;
    for (i = 0; i < adj1.size(); ++i)
    {
      rval = iface->tag_get_data( id_tag, &adj1[i], 1, &ids1[i] );
      if (MB_TAG_NOT_FOUND == rval)
        ids1[i] = 0;
      else if (MB_SUCCESS != rval)
        moab_error("tag_get_data");
        
      rval = iface->tag_get_data( id_tag, &adj2[i], 1, &ids2[i] );
      if (MB_TAG_NOT_FOUND == rval)
        ids2[i] = 0;
      else if (MB_SUCCESS != rval)
        moab_error("tag_get_data");
    }
    
    std::sort( ids1.begin(), ids1.end() );
    std::sort( ids2.begin(), ids2.end() );
    for (i = 0; i < ids1.size(); ++i)
    {
      if (ids1[i] != ids2[i])
      {
        fprintf(stderr, "Sets with id %d have non-matching %s\n", id, words[two] );
        ok = false;
        break;
      }
    }
  }
  return ok;
}
Example #15
0
range_adapter<Mode, Range>::range_adapter(const Range& rng)
    : first_(rng.begin()), cur_(rng.begin()), last_(rng.end()) { }
Example #16
0
//! Writes out a file
ErrorCode WriteGmsh::write_file(const char *file_name,
                                const bool overwrite,
                                const FileOptions& options,
                                const EntityHandle *output_list,
                                const int num_sets,
                                const std::vector<std::string>& /* qa_list */,
                                const Tag* /* tag_list */,
                                int /* num_tags */,
                                int /* export_dimension */)
{
  ErrorCode rval;
  Tag global_id = 0, block_tag = 0, geom_tag = 0, prtn_tag = 0;

  if (!overwrite) {
    rval = mWriteIface->check_doesnt_exist(file_name);
    if (MB_SUCCESS != rval)
      return rval;
  }

  // Get tags
  mbImpl->tag_get_handle(GLOBAL_ID_TAG_NAME, 1, MB_TYPE_INTEGER, global_id);
  mbImpl->tag_get_handle(MATERIAL_SET_TAG_NAME, 1, MB_TYPE_INTEGER, block_tag);
  if (global_id) 
    mbImpl->tag_get_handle(GEOM_DIMENSION_TAG_NAME, 1, MB_TYPE_INTEGER, geom_tag);
  mbImpl->tag_get_handle(PARALLEL_PARTITION_TAG_NAME, 1, MB_TYPE_INTEGER, prtn_tag);

  // Define arrays to hold entity sets of interest
  Range sets[3];
  Tag set_tags[] = {block_tag, geom_tag, prtn_tag};
  Tag set_ids[] = {block_tag, 0 /*global_id*/, prtn_tag};

  // Get entities to write
  Range elements, nodes;
  if (!output_list) {
    rval = mbImpl->get_entities_by_dimension(0, 0, nodes, false);
    if (MB_SUCCESS != rval)
      return rval;
    for (int d = 1; d < 3; ++d) {
      Range tmp_range;
      rval = mbImpl->get_entities_by_dimension(0, d, tmp_range, false);
      if (MB_SUCCESS != rval)
        return rval;
      elements.merge(tmp_range);
    }

    for (int s = 0; s < 3; ++s) {
      if (set_tags[s]) {
        rval = mbImpl->get_entities_by_type_and_tag(0, MBENTITYSET, set_tags + s, 0, 1, sets[s]);
        if (MB_SUCCESS != rval)
          return rval;
      }
    }
  }
  else {
    for (int i = 0; i < num_sets; ++i) {
      EntityHandle set = output_list[i];
      for (int d = 1; d < 3; ++d) {
        Range tmp_range, tmp_nodes;
        rval = mbImpl->get_entities_by_dimension(set, d, tmp_range, true);
        if (rval != MB_SUCCESS)
          return rval;
        elements.merge(tmp_range);
        rval = mbImpl->get_adjacencies(tmp_range, set, false, tmp_nodes);
        if (rval != MB_SUCCESS)
          return rval;
        nodes.merge(tmp_nodes);
      }

      for (int s = 0; s < 3; ++s) {
        if (set_tags[s]) {
          Range tmp_range;
          rval = mbImpl->get_entities_by_type_and_tag(set, MBENTITYSET, set_tags + s, 0, 1, tmp_range);
          if (MB_SUCCESS != rval)
            return rval;
          sets[s].merge(tmp_range);
          int junk;
          rval = mbImpl->tag_get_data(set_tags[s], &set, 1, &junk);
          if (MB_SUCCESS == rval)
            sets[s].insert(set);
        }
      }
    }
  }

  if (elements.empty()) {
    MB_SET_ERR(MB_ENTITY_NOT_FOUND, "Nothing to write");
  }

  // Get global IDs for all elements.
  // First try to get from tag.  If tag is not defined or not set
  // for all elements, use handle value instead.
  std::vector<int> global_id_array(elements.size());
  std::vector<int>::iterator id_iter;
  if (!global_id || MB_SUCCESS !=
      mbImpl->tag_get_data(global_id, elements, &global_id_array[0])) {
    id_iter = global_id_array.begin();
    for (Range::iterator i = elements.begin(); i != elements.end(); ++i, ++id_iter)
      *id_iter = mbImpl->id_from_handle(*i);
  }

  // Figure out the maximum ID value so we know where to start allocating
  // new IDs when we encounter ID conflicts.
  int max_id = 0;
  for (id_iter = global_id_array.begin(); id_iter != global_id_array.end(); ++id_iter)
    if (*id_iter > max_id)
      max_id = *id_iter;

  // Initialize ElemInfo struct for each element
  std::map<EntityHandle, ElemInfo> elem_sets; // Per-element info
  std::set<int> elem_global_ids; // Temporary for finding duplicate IDs
  id_iter = global_id_array.begin();
  // Iterate backwards to give highest-dimension entities first dibs for
  // a conflicting ID.
  for (Range::reverse_iterator i = elements.rbegin(); i != elements.rend(); ++i) {
    int id = *id_iter;
    ++id_iter;
    if (!elem_global_ids.insert(id).second)
      id = max_id++;

    ElemInfo& ei = elem_sets[*i];
    ei.count = 0;
    ei.id = id;

    EntityType type = mbImpl->type_from_handle(*i);
    int num_vtx;
    const EntityHandle* conn;
    rval = mbImpl->get_connectivity(*i, conn, num_vtx);
    if (MB_SUCCESS != rval)
      return rval;

    ei.type = GmshUtil::get_gmsh_type(type, num_vtx);
    if (ei.type < 0) {
      MB_SET_ERR(MB_FILE_WRITE_ERROR, "Gmem file format does not support element of type " << CN::EntityTypeName(type) << " with " << num_vtx << " vertices");
    }
  }
  // Don't need these any more, free memory.
  elem_global_ids.clear();
  global_id_array.clear();

  // For each material set, geometry set, or partition; store
  // the ID of the set on each element.
  for (int s = 0; s < 3; ++s) {
    if (!set_tags[s])
      continue;

    for (Range::iterator i = sets[s].begin(); i != sets[s].end(); ++i) {
      int id;
      if (set_ids[s]) {
        rval = mbImpl->tag_get_data(set_ids[s], &*i, 1, &id);
        if (MB_SUCCESS != rval)
          return rval;
      }
      else
        id = mbImpl->id_from_handle(*i);

      Range elems;
      rval = mbImpl->get_entities_by_handle(*i, elems);
      if (MB_SUCCESS != rval)
        return rval;

      elems = intersect(elems, elements);
      for (Range::iterator j = elems.begin(); j != elems.end(); ++j)
        elem_sets[*j].set(s, id);
    }
  }

  // Create file
  std::ofstream out(file_name);
  if (!out)
    return MB_FILE_DOES_NOT_EXIST;

  // Write header
  out << "$MeshFormat" << std::endl;
  out << "2.0 0 " << sizeof(double) << std::endl;
  out << "$EndMeshFormat" << std::endl;

  // Set precision for node coordinates
  int precision;
  if (MB_SUCCESS != options.get_int_option("PRECISION", precision))
    precision = DEFAULT_PRECISION;
  const int old_precision = out.precision();
  out.precision(precision);

  // Write nodes
  out << "$Nodes" << std::endl;
  out << nodes.size() << std::endl;
  std::vector<double> coords(3*nodes.size());
  rval = mbImpl->get_coords(nodes, &coords[0]);
  if (MB_SUCCESS != rval)
    return rval;
  std::vector<double>::iterator c = coords.begin();
  for (Range::iterator i = nodes.begin(); i != nodes.end(); ++i) {
    out << mbImpl->id_from_handle(*i);
    out << " " << *c; ++c;
    out << " " << *c; ++c;
    out << " " << *c; ++c;
    out << std::endl;
  }
  out << "$EndNodes" << std::endl;
  coords.clear();

  // Restore stream state
  out.precision(old_precision);

  // Write elements
  out << "$Elements" << std::endl;
  out << elem_sets.size() << std::endl;
  for (std::map<EntityHandle, ElemInfo>::iterator i = elem_sets.begin();
       i != elem_sets.end(); ++i) {
    int num_vtx;
    const EntityHandle* conn;
    rval = mbImpl->get_connectivity(i->first, conn, num_vtx);
    if (MB_SUCCESS != rval)
      return rval;
    out << i->second.id << ' ' << i->second.type << ' ' << i->second.count;
    for (int j = 0; j < i->second.count; ++j)
      out << ' ' << i->second.sets[j];

    const int* order = GmshUtil::gmshElemTypes[i->second.type].node_order;

    // Need to re-order vertices
    if (order) {
      for (int j = 0; j < num_vtx; ++j)
        out << ' ' << mbImpl->id_from_handle(conn[order[j]]);
    }
    else {
      for (int j = 0; j < num_vtx; ++j)
        out << ' ' << mbImpl->id_from_handle(conn[j]);
    }
    out << std::endl;
  }
  out << "$EndElements" << std::endl;

  // Done
  return MB_SUCCESS;
}
void cloth::SwFactory::extractCollisionData(const Cloth& cloth, Range<PxVec4> spheres, Range<uint32_t> capsules,
                                            Range<PxVec4> planes, Range<uint32_t> convexes, Range<PxVec3> triangles) const
{
	PX_ASSERT(&cloth.getFactory() == this);

	const SwCloth& swCloth = static_cast<const SwClothImpl&>(cloth).mCloth;

	PX_ASSERT(spheres.empty() || spheres.size() == swCloth.mStartCollisionSpheres.size());
	PX_ASSERT(capsules.empty() || capsules.size() == swCloth.mCapsuleIndices.size() * 2);
	PX_ASSERT(planes.empty() || planes.size() == swCloth.mStartCollisionPlanes.size());
	PX_ASSERT(convexes.empty() || convexes.size() == swCloth.mConvexMasks.size());
	PX_ASSERT(triangles.empty() || triangles.size() == swCloth.mStartCollisionTriangles.size());

	if(!swCloth.mStartCollisionSpheres.empty() && !spheres.empty())
		memcpy(spheres.begin(), &swCloth.mStartCollisionSpheres.front(),
		       swCloth.mStartCollisionSpheres.size() * sizeof(PxVec4));

	if(!swCloth.mCapsuleIndices.empty() && !capsules.empty())
		memcpy(capsules.begin(), &swCloth.mCapsuleIndices.front(), swCloth.mCapsuleIndices.size() * sizeof(IndexPair));

	if(!swCloth.mStartCollisionPlanes.empty() && !planes.empty())
		memcpy(planes.begin(), &swCloth.mStartCollisionPlanes.front(),
		       swCloth.mStartCollisionPlanes.size() * sizeof(PxVec4));

	if(!swCloth.mConvexMasks.empty() && !convexes.empty())
		memcpy(convexes.begin(), &swCloth.mConvexMasks.front(), swCloth.mConvexMasks.size() * sizeof(uint32_t));

	if(!swCloth.mStartCollisionTriangles.empty() && !triangles.empty())
		memcpy(triangles.begin(), &swCloth.mStartCollisionTriangles.front(),
		       swCloth.mStartCollisionTriangles.size() * sizeof(PxVec3));
}
Example #18
0
void KateViInsertMode::replayCompletion()
{
  const KateViInputModeManager::Completion completion = m_viInputModeManager->nextLoggedCompletion();
  // Find beginning of the word.
  Cursor cursorPos = m_view->cursorPosition();
  Cursor wordStart = Cursor::invalid();
  if (!doc()->character(cursorPos).isLetterOrNumber() && doc()->character(cursorPos) != '_')
  {
    cursorPos.setColumn(cursorPos.column() - 1);
  }
  while (cursorPos.column() >= 0 && (doc()->character(cursorPos).isLetterOrNumber() || doc()->character(cursorPos) == '_'))
  {
    wordStart = cursorPos;
    cursorPos.setColumn(cursorPos.column() - 1);
  }
  // Find end of current word.
  cursorPos = m_view->cursorPosition();
  Cursor wordEnd = Cursor(cursorPos.line(), cursorPos.column() - 1);
  while (cursorPos.column() < doc()->lineLength(cursorPos.line()) && (doc()->character(cursorPos).isLetterOrNumber() || doc()->character(cursorPos) == '_'))
  {
    wordEnd = cursorPos;
    cursorPos.setColumn(cursorPos.column() + 1);
  }
  QString completionText = completion.completedText();
  const Range currentWord = Range(wordStart, Cursor(wordEnd.line(), wordEnd.column() + 1));
  // Should we merge opening brackets? Yes, if completion is a function with arguments and after the cursor
  // there is (optional whitespace) followed by an open bracket.
  int offsetFinalCursorPosBy = 0;
  if (completion.completionType() == KateViInputModeManager::Completion::FunctionWithArgs)
  {
    const int nextMergableBracketAfterCursorPos = findNextMergeableBracketPos(currentWord.end());
    if (nextMergableBracketAfterCursorPos != -1)
    {
      if (completionText.endsWith("()"))
      {
        // Strip "()".
        completionText = completionText.left(completionText.length() - 2);
      }
      else if (completionText.endsWith("();"))
      {
        // Strip "();".
        completionText = completionText.left(completionText.length() - 3);
      }
      // Ensure cursor ends up after the merged open bracket.
      offsetFinalCursorPosBy = nextMergableBracketAfterCursorPos + 1;
    }
    else
    {
      if (!completionText.endsWith("()") && !completionText.endsWith("();"))
      {
        // Original completion merged with an opening bracket; we'll have to add our own brackets.
        completionText.append("()");
      }
      // Position cursor correctly i.e. we'll have added "functionname()" or "functionname();"; need to step back by
      // one or two to be after the opening bracket.
      offsetFinalCursorPosBy = completionText.endsWith(';') ? -2 : -1;
    }
  }
  Cursor deleteEnd =  completion.removeTail() ? currentWord.end() :
                                                Cursor(m_view->cursorPosition().line(), m_view->cursorPosition().column() + 0);

  if (currentWord.isValid())
  {
    doc()->removeText(Range(currentWord.start(), deleteEnd));
    doc()->insertText(currentWord.start(), completionText);
  }
  else
  {
    doc()->insertText(m_view->cursorPosition(), completionText);
  }

  if (offsetFinalCursorPosBy != 0)
  {
    m_view->setCursorPosition(Cursor(m_view->cursorPosition().line(), m_view->cursorPosition().column() + offsetFinalCursorPosBy));
  }

  if (!m_viInputModeManager->isReplayingLastChange())
  {
    Q_ASSERT(m_viInputModeManager->isReplayingMacro());
    // Post the completion back: it needs to be added to the "last change" list ...
    m_viInputModeManager->logCompletionEvent(completion);
    // ... but don't log the ctrl-space that led to this call to replayCompletion(), as
    // a synthetic ctrl-space was just added to the last change keypresses by logCompletionEvent(), and we don't
    // want to duplicate them!
    m_viInputModeManager->doNotLogCurrentKeypress();
  }
}
void cloth::SwFactory::extractRestPositions(const Cloth& cloth, Range<PxVec4> destRestPositions) const
{
	const SwCloth& swCloth = static_cast<const SwClothImpl&>(cloth).mCloth;
	PX_ASSERT(destRestPositions.size() == swCloth.mRestPositions.size());
	PxMemCopy(destRestPositions.begin(), swCloth.mRestPositions.begin(), destRestPositions.size() * sizeof(PxVec4));
}
Example #20
0
 bool Range::operator==(const Range& other) const
 {
     return start()==other.start() && end()==other.end();
 }
Example #21
0
bool Sheet::mergeCells(const Range & range)
{
    return cells.mergeCells(range.from(), range.to());
}
Example #22
0
 bool Range::EqualsIgnoringDirection(const Range& other) const
 {
     return GetMin()==other.GetMin() && GetMax()==other.GetMax();
 }
Example #23
0
	virtual int evaluate(char* buf, int maxbuf, Range range) const {
		dbg(1, "VMaxExpression::evaluate(%s)", buf);
		float vmin = range.isReversed()? range.rmin: range.rmax;
		return sprintf(buf, "%f", vmin);
	}
Example #24
0
 bool Range::Intersects(const Range& range) const
 {
     return IsValid() && range.IsValid() &&
         !(range.GetMax()<GetMin() || range.GetMin()>=GetMax());
 }
Example #25
0
void TextFinder::scopeStringMatches(int identifier,
                                    const WebString& searchText,
                                    const WebFindOptions& options,
                                    bool reset) {
  // TODO(dglazkov): The reset/continue cases need to be untangled into two
  // separate functions. This collation of logic is unnecessary and adds to
  // overall complexity of the code.
  if (reset) {
    // This is a brand new search, so we need to reset everything.
    // Scoping is just about to begin.
    m_scopingInProgress = true;

    // Need to keep the current identifier locally in order to finish the
    // request in case the frame is detached during the process.
    m_findRequestIdentifier = identifier;

    // Clear highlighting for this frame.
    unmarkAllTextMatches();

    // Clear the tickmarks and results cache.
    clearFindMatchesCache();

    // Clear the counters from last operation.
    m_lastMatchCount = 0;
    m_nextInvalidateAfter = 0;
    m_resumeScopingFromRange = nullptr;

    // The view might be null on detached frames.
    LocalFrame* frame = ownerFrame().frame();
    if (frame && frame->page())
      m_frameScoping = true;

    // Now, defer scoping until later to allow find operation to finish quickly.
    scopeStringMatchesSoon(
        identifier, searchText, options,
        false);  // false means just reset, so don't do it again.
    return;
  }

  if (!shouldScopeMatches(searchText, options)) {
    finishCurrentScopingEffort(identifier);
    return;
  }

  PositionInFlatTree searchStart =
      PositionInFlatTree::firstPositionInNode(ownerFrame().frame()->document());
  PositionInFlatTree searchEnd =
      PositionInFlatTree::lastPositionInNode(ownerFrame().frame()->document());
  DCHECK_EQ(searchStart.document(), searchEnd.document());

  if (m_resumeScopingFromRange) {
    // This is a continuation of a scoping operation that timed out and didn't
    // complete last time around, so we should start from where we left off.
    DCHECK(m_resumeScopingFromRange->collapsed());
    searchStart = fromPositionInDOMTree<EditingInFlatTreeStrategy>(
        m_resumeScopingFromRange->endPosition());
    if (searchStart.document() != searchEnd.document())
      return;
  }

  // TODO(dglazkov): The use of updateStyleAndLayoutIgnorePendingStylesheets
  // needs to be audited.  see http://crbug.com/590369 for more details.
  searchStart.document()->updateStyleAndLayoutIgnorePendingStylesheets();

  // This timeout controls how long we scope before releasing control. This
  // value does not prevent us from running for longer than this, but it is
  // periodically checked to see if we have exceeded our allocated time.
  const double maxScopingDuration = 0.1;  // seconds

  int matchCount = 0;
  bool timedOut = false;
  double startTime = currentTime();
  do {
    // Find next occurrence of the search string.
    // FIXME: (http://crbug.com/6818) This WebKit operation may run for longer
    // than the timeout value, and is not interruptible as it is currently
    // written. We may need to rewrite it with interruptibility in mind, or
    // find an alternative.
    const EphemeralRangeInFlatTree result =
        findPlainText(EphemeralRangeInFlatTree(searchStart, searchEnd),
                      searchText, options.matchCase ? 0 : CaseInsensitive);
    if (result.isCollapsed()) {
      // Not found.
      break;
    }
    Range* resultRange = Range::create(
        result.document(), toPositionInDOMTree(result.startPosition()),
        toPositionInDOMTree(result.endPosition()));
    if (resultRange->collapsed()) {
      // resultRange will be collapsed if the matched text spans over multiple
      // TreeScopes.  FIXME: Show such matches to users.
      searchStart = result.endPosition();
      continue;
    }

    ++matchCount;

    // Catch a special case where Find found something but doesn't know what
    // the bounding box for it is. In this case we set the first match we find
    // as the active rect.
    IntRect resultBounds = resultRange->boundingBox();
    IntRect activeSelectionRect;
    if (m_locatingActiveRect) {
      activeSelectionRect =
          m_activeMatch.get() ? m_activeMatch->boundingBox() : resultBounds;
    }

    // If the Find function found a match it will have stored where the
    // match was found in m_activeSelectionRect on the current frame. If we
    // find this rect during scoping it means we have found the active
    // tickmark.
    bool foundActiveMatch = false;
    if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) {
      // We have found the active tickmark frame.
      m_currentActiveMatchFrame = true;
      foundActiveMatch = true;
      // We also know which tickmark is active now.
      m_activeMatchIndex = matchCount - 1;
      // To stop looking for the active tickmark, we set this flag.
      m_locatingActiveRect = false;

      // Notify browser of new location for the selected rectangle.
      reportFindInPageSelection(
          ownerFrame().frameView()->contentsToRootFrame(resultBounds),
          m_activeMatchIndex + 1, identifier);
    }

    ownerFrame().frame()->document()->markers().addTextMatchMarker(
        EphemeralRange(resultRange), foundActiveMatch);

    m_findMatchesCache.append(
        FindMatch(resultRange, m_lastMatchCount + matchCount));

    // Set the new start for the search range to be the end of the previous
    // result range. There is no need to use a VisiblePosition here,
    // since findPlainText will use a TextIterator to go over the visible
    // text nodes.
    searchStart = result.endPosition();

    m_resumeScopingFromRange = Range::create(
        result.document(), toPositionInDOMTree(result.endPosition()),
        toPositionInDOMTree(result.endPosition()));
    timedOut = (currentTime() - startTime) >= maxScopingDuration;
  } while (!timedOut);

  // Remember what we search for last time, so we can skip searching if more
  // letters are added to the search string (and last outcome was 0).
  m_lastSearchString = searchText;

  if (matchCount > 0) {
    ownerFrame().frame()->editor().setMarkedTextMatchesAreHighlighted(true);

    m_lastMatchCount += matchCount;

    // Let the frame know how many matches we found during this pass.
    ownerFrame().increaseMatchCount(matchCount, identifier);
  }

  if (timedOut) {
    // If we found anything during this pass, we should redraw. However, we
    // don't want to spam too much if the page is extremely long, so if we
    // reach a certain point we start throttling the redraw requests.
    if (matchCount > 0)
      invalidateIfNecessary();

    // Scoping effort ran out of time, lets ask for another time-slice.
    scopeStringMatchesSoon(identifier, searchText, options,
                           false);  // don't reset.
    return;                         // Done for now, resume work later.
  }

  finishCurrentScopingEffort(identifier);
}
Example #26
0
 bool Range::Contains(const Range& range) const
 {
     return IsValid() && range.IsValid() &&
         GetMin()<=range.GetMin() && range.GetMax()<=GetMax();
 }
void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
{
    moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
    moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
}
Example #28
0
static void computeShapeByReshapeMask(const MatShape &srcShape,
                                      const MatShape &maskShape,
                                      Range srcRange /*= Range::all()*/,
                                      MatShape& dstShape)
{
    int srcShapeSize = (int)srcShape.size();
    int maskShapeSize = (int)maskShape.size();

    if (srcRange == Range::all())
        srcRange = Range(0, srcShapeSize);
    else
    {
        int sz = srcRange.size();
        srcRange.start = clamp(srcRange.start, srcShapeSize);
        srcRange.end = srcRange.end == INT_MAX ? srcShapeSize : srcRange.start + sz;
    }

    bool explicitMask = !maskShape.empty();  // All mask values are positive.
    for (int i = 0, n = maskShape.size(); i < n && explicitMask; ++i)
    {
        explicitMask = maskShape[i] > 0;
    }
    // Working range of source shape is a range where area(src) == area(mask).
    if (explicitMask)
    {
        int maskTotal = total(maskShape);
        // Go from the end of mask until we collect required total.
        bool matched = false;
        for (int i = srcRange.end - 1; i >= srcRange.start; --i)
        {
            if (matched)
            {
                if (i == 0 || total(srcShape, i, srcRange.end) != maskTotal)
                {
                    srcRange.start = i + 1;
                    break;
                }
            }
            else
            {
                matched = total(srcShape, i, srcRange.end) == maskTotal;
            }
        }
        CV_Assert(total(srcShape, srcRange.start, srcRange.end) == maskTotal);
    }

    CV_Assert(0 <= srcRange.start && srcRange.start <= srcRange.end && srcRange.end <= srcShapeSize);
    int dstShapeSize = srcShapeSize - srcRange.size() + maskShapeSize;
    dstShape.resize(dstShapeSize);

    std::copy(srcShape.begin(), srcShape.begin() + srcRange.start, dstShape.begin());
    std::copy(srcShape.begin() + srcRange.end, srcShape.begin() + srcShapeSize, dstShape.begin() + srcRange.start + maskShapeSize);

    int inferDim = -1;
    for (int i = 0; i < maskShapeSize; i++)
    {
        if (maskShape[i] > 0)
        {
            dstShape[srcRange.start + i] = maskShape[i];
        }
        else if (maskShape[i] == 0)
        {
            if (srcRange.start + i >= srcShapeSize)
                CV_Error(Error::StsBadArg, format("Copy dim[%d] (which has zero size) is out of the source shape bounds", srcRange.start + i));
            dstShape[srcRange.start + i] = srcShape[srcRange.start + i];
        }
        else if (maskShape[i] == -1)
        {
            if (inferDim != -1)
                CV_Error(Error::StsAssert, "Duplicate of inferred dim (which is denoted by -1)");
            inferDim = srcRange.start + i;
            dstShape[inferDim] = 1;
        }
        else
            CV_Error(Error::StsBadArg, "maskShape[i] >= -1");
    }

    size_t srcTotal = total(srcShape);
    size_t dstTotal = total(dstShape);

    if (inferDim != -1)
    {
        if (srcTotal % dstTotal != 0)
            CV_Error(Error::StsBackTrace, "Can't infer a dim denoted by -1");

        dstShape[inferDim] = (int)(srcTotal / dstTotal);
    }
    else
    {
        CV_Assert(srcTotal == dstTotal);
    }
}
Example #29
0
// Gets the vertex eitities from a simple cube file load and checks that 
// they are in the correct locations.
void read_cube_vertex_pos_test()
{
  
  ErrorCode rval;
  //Open the test file
  Core moab;
  Interface* mb = &moab;
  read_file( mb, input_cube );

  //Retrieve all vertex handles from the mesh
  Range verts;
  rval = mb->get_entities_by_type( 0, MBVERTEX, verts );
  CHECK_ERR( rval );

  int number_of_verts = verts.size();
  CHECK_EQUAL( 8, number_of_verts );
  //Get the vertex coordinates
  double x[8];
  double y[8];
  double z[8];
  rval = mb-> get_coords( verts, &x[0], &y[0], &z[0] );
  CHECK_ERR(rval);

  //Check against known locations of the vertices

  std::vector<double> x_ref;
  std::vector<double> y_ref;
  std::vector<double> z_ref;

  // Vertex 1
  x_ref.push_back( 5 );
  y_ref.push_back( -5 );
  z_ref.push_back( 5 );

  // Vertex 2
  x_ref.push_back( 5 );
  y_ref.push_back( 5 );
  z_ref.push_back( 5 );

  // Vertex 3
  x_ref.push_back( -5 );
  y_ref.push_back( 5 );
  z_ref.push_back( 5 );

  // Vertex 4
  x_ref.push_back( -5 );
  y_ref.push_back( -5 );
  z_ref.push_back( 5 );

  // Vertex 5
  x_ref.push_back( 5 );
  y_ref.push_back( 5 );
  z_ref.push_back( -5 );

  // Vertex 6
  x_ref.push_back( 5 );
  y_ref.push_back( -5 );
  z_ref.push_back( -5 );

  // Vertex 7
  x_ref.push_back( -5 );
  y_ref.push_back( -5 );
  z_ref.push_back( -5 );
 
  // Vertex 8
  x_ref.push_back( -5 );
  y_ref.push_back( 5 );
  z_ref.push_back( -5 );
 
  std::cout << verts.size() << std::endl;
  std::cout << x_ref.size() << std::endl;
  
  for(unsigned int i=0; i<verts.size(); i++)
    {
      for(unsigned int j=0; j<x_ref.size(); j++)
	{
	  if( x[i]==x_ref[j] && y[i]==y_ref[j] && z[i]==z_ref[j] )
            {
              x_ref.erase( x_ref.begin()+j );
              y_ref.erase( y_ref.begin()+j );
              z_ref.erase( z_ref.begin()+j );
            }
	}
    }
  
  //After looping through each vertex loaded from the mesh
  //there should be no entities left in the reference vector
  int leftovers = x_ref.size();
  CHECK_EQUAL( 0, leftovers );

}
Example #30
0
static void PrintKVRange(Range r)
{
    while(!r.IsEmpty())
        sPrintF(L"%s ",sPopHead(r).Value);
    sPrintF(L"\n");
}