vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> results;
        int size1 = nums.size();
        vector<int> myqueue;
        
        if (k<=0 || size1 == 0)
           return results;
        
        int max = -1000;
        for(int i=0; i<k; i++)
         {
             myqueue.push_back(nums[i]);
             if (max <= nums[i])
                max = nums[i];
         }
         results.push_back(max);
         
         for (int i=k; i< size1; i++)
         {
             int tmp = myqueue[0];
             myqueue.erase(myqueue.begin());
             myqueue.push_back(nums[i]);
             std::cout<<"tmp........."<< tmp <<"\n";
             printQueue(myqueue);
             if (tmp==max)
             {
                 max = getMax(myqueue);
                 results.push_back(max);
             }
			 else if (nums[i]> max)
			 {
			    max = nums[i];
				results.push_back(max);
			 }
             else
                 results.push_back(max);
             
         }
        return results;
    }
Beispiel #2
0
F32 CubeReflector::calcFaceScore( const ReflectParams &params, U32 faceidx )
{
   if ( Parent::calcScore( params ) <= 0.0f )
      return score;
   
   VectorF vLookatPt(0.0f, 0.0f, 0.0f);

   switch( faceidx )
   {
   case 0 : // D3DCUBEMAP_FACE_POSITIVE_X:
      vLookatPt = VectorF( 1.0f, 0.0f, 0.0f );      
      break;
   case 1 : // D3DCUBEMAP_FACE_NEGATIVE_X:
      vLookatPt = VectorF( -1.0f, 0.0f, 0.0f );      
      break;
   case 2 : // D3DCUBEMAP_FACE_POSITIVE_Y:
      vLookatPt = VectorF( 0.0f, 1.0f, 0.0f );      
      break;
   case 3 : // D3DCUBEMAP_FACE_NEGATIVE_Y:
      vLookatPt = VectorF( 0.0f, -1.0f, 0.0f );      
      break;
   case 4 : // D3DCUBEMAP_FACE_POSITIVE_Z:
      vLookatPt = VectorF( 0.0f, 0.0f, 1.0f );      
      break;
   case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
      vLookatPt = VectorF( 0.0f, 0.0f, -1.0f );      
      break;
   }

   VectorF cameraDir;
   params.query->cameraMatrix.getColumn( 1, &cameraDir );

   F32 dot = mDot( cameraDir, -vLookatPt );

   dot = getMax( ( dot + 1.0f ) / 2.0f, 0.1f );

   score *= dot;

   return score;
}
Beispiel #3
0
bool Global::intersectCCRectWithSector(double _rectX, double _rectY, double _rectW, double _rectH, double _pointX, double _pointY, double _angleL, double _angleR)
{
	bool res = false;
	double angle[4];

	angle[0] = atan2(_rectH - _pointY, _rectW - _pointX) * angleChange / pi;
	angle[1] = atan2(_rectY - _pointY, _rectW - _pointX) * angleChange / pi;
	angle[2] = atan2(_rectH - _pointY, _rectX - _pointX) * angleChange / pi;
	angle[3] = atan2(_rectY - _pointY, _rectX - _pointX) * angleChange / pi;

	for (unsigned int i = 0; i < 4; i++)
	{
		changeAngleAtan2To360(&angle[i]);
	}

	double angleMin = getMin(angle, 4);
	double angleMax = getMax(angle, 4);

	//CCLOG("GameControl : angleMin = %f, angleMax = %f, angleL = %f, angleR = %f", angleMin, angleMax, _angleL, _angleR);

	if ((_angleL > angleMin) && (_angleL < angleMax))
	{
		res = true;
	}
	else if ((_angleR > angleMin) && (_angleR < angleMax))
	{
		res = true;
	}
	else if ((_angleL < angleMin) && (_angleR > angleMin))
	{
		res = true;
	}
	else if ((_angleL < angleMax) && (_angleR > angleMax))
	{
		res = true;
	}

	return res;
}
Beispiel #4
0
/*
 * Writes the final IMAGE to a file. Only the root calls this function
 */
void writeImageLocal(File *f, char *line, double **image, int nRow, int nCol) {
  int r,c,work;
  double max;

  max = getMax(image, nRow, nCol);  //gets max value for normalization

  f=fopen("Lenna64x64.pgm","w");

  fprintf(f,"P5\n");
  fprintf(f,"# Simple image test\n");
  fprintf(f,"%d %d\n",nCol,nRow);
  fprintf(f,"%d\n",MAX_GREY);

  for (r=0; r < nRow; r++) {
    for (c=0; c < nCol; c++) {
      work = (int) ( (image[r][c] / max) * MAX_GREY);
      fputc((char)work,f);
    }
  }

  fclose(f);
}
Beispiel #5
0
void SimAnalog::updateData()
{
   //vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimAnalog::updateData()\n"<< vprDEBUG_FLUSH;

   // -- Update analog data --- //
   for (unsigned int i = 0; i < mSimKeysUp.size(); ++i)
   {
      int upPressed   = checkKeyPair(mSimKeysUp[i]);
      int downPressed = checkKeyPair(mSimKeysDown[i]);

      mAnaData[i].setTime();
      mAnaData[i].setValue(mAnaData[i].getValue() + upPressed   * mAnaStep);
      mAnaData[i].setValue(mAnaData[i].getValue() - downPressed * mAnaStep);

      if (mAutoReturn == true && upPressed == 0 && downPressed == 0)
      {
         if (mAnaData[i].getValue() >= mInitialValue + mAnaStep)
         {
            mAnaData[i].setValue(mAnaData[i].getValue() - mAnaStep);
         }
         else if (mAnaData[i].getValue() <= mInitialValue - mAnaStep )
         {
            mAnaData[i].setValue(mAnaData[i].getValue() + mAnaStep);
         }
         else
         {
            mAnaData[i].setValue(mInitialValue);
         }
      }

      // Clamp to the min/max range
      mAnaData[i].setValue(gmtl::Math::clamp(mAnaData[i].getValue(),
                                              getMin(), getMax()));
   }

   // Locks and then swaps the indices.
   addAnalogSample(mAnaData);
   swapAnalogBuffers();
}
void printUnsorted(int arr[], int n) {
  int s = -1, e = -1;
  for(int i = 0; i < n - 1; i++){
    if(arr[i] > arr[i+1]){
      s = i;
      break; 
    }  
  }
  
  for(int i = n - 1; i > 0; i--){
    if(arr[i] < arr[i-1]){
      e = i;
      break; 
    }
  }

  if((s == =1 && e == -1) || e < s) {
    return;
  }
  
  int max = getMax(arr, s, e);
  int min = getMin(arr, s, e);
  
  for(int i = 0; i < s; i++){
    if(arr[i] > min){
      s = i;
      break;
    }
  }

  for(int i = n - 1; i >= 0; i--){
    if(arr[i] < max){
      e = i;
      break;
    }
  }

  printf("%d %d\n", s, e);
}
Beispiel #7
0
BSONObj ChunkType::toBSON() const {
    BSONObjBuilder builder;
    if (_name)
        builder.append(name.name(), getName());
    if (_ns)
        builder.append(ns.name(), getNS());
    if (_min)
        builder.append(min.name(), getMin());
    if (_max)
        builder.append(max.name(), getMax());
    if (_shard)
        builder.append(shard.name(), getShard());
    if (_version) {
        // For now, write both the deprecated *and* the new fields
        _version->addToBSON(builder, version());
        _version->addToBSON(builder, DEPRECATED_lastmod());
    }
    if (_jumbo)
        builder.append(jumbo.name(), getJumbo());

    return builder.obj();
}
Beispiel #8
0
StatusWith<MigrationType> MigrationType::fromBSON(const BSONObj& source) {
    MigrationType migrationType;

    {
        std::string migrationNS;
        Status status = bsonExtractStringField(source, ns.name(), &migrationNS);
        if (!status.isOK())
            return status;
        migrationType._nss = NamespaceString(migrationNS);
    }

    {
        auto chunkRangeStatus = ChunkRange::fromBSON(source);
        if (!chunkRangeStatus.isOK())
            return chunkRangeStatus.getStatus();

        const auto chunkRange = std::move(chunkRangeStatus.getValue());
        migrationType._min = chunkRange.getMin().getOwned();
        migrationType._max = chunkRange.getMax().getOwned();
    }

    {
        std::string migrationToShard;
        Status status = bsonExtractStringField(source, toShard.name(), &migrationToShard);
        if (!status.isOK())
            return status;
        migrationType._toShard = migrationToShard;
    }

    {
        std::string migrationFromShard;
        Status status = bsonExtractStringField(source, fromShard.name(), &migrationFromShard);
        if (!status.isOK())
            return status;
        migrationType._fromShard = migrationFromShard;
    }

    return migrationType;
}
PxCapsulePlayer::PxCapsulePlayer( Player *player, PxWorld *world )
 : PxPlayer( player, world ),
   mCapsuleController( NULL )      
{
   world->releaseWriteLock();

   PlayerData *datablock = dynamic_cast<PlayerData*>( player->getDataBlock() );
  
   // Don't forget to initialize base member!
   mSize = datablock->boxSize;

   const Point3F &pos = player->getPosition();

   NxCapsuleControllerDesc desc;
   desc.skinWidth = mSkinWidth;
   desc.radius = getMax( mSize.x, mSize.y ) * 0.5f;
   desc.radius -= desc.skinWidth;
   desc.height = mSize.z - ( desc.radius * 2.0f );
   desc.height -= desc.skinWidth * 2.0f;

   desc.climbingMode = CLIMB_CONSTRAINED;
   desc.position.set( pos.x, pos.y, pos.z + ( mSize.z * 0.5f ) );
   desc.upDirection = NX_Z;
   desc.callback = this; // TODO: Fix this as well!
	desc.slopeLimit = datablock->runSurfaceCos;
	desc.stepOffset = datablock->maxStepHeight;

   mUserData.setObject( player );
   desc.userData = &mUserData;

   // Don't forget to initialize base member!
   mController = mWorld->createController( desc );

   // Cast to a NxCapsuleController for our convenience
      mCapsuleController = static_cast<NxCapsuleController*>( mController );

   mCapsuleController->setInteraction( NXIF_INTERACTION_INCLUDE );
   mCapsuleController->getActor()->setMass( datablock->mass );
}
Beispiel #10
0
ThreadPool::ThreadPool( const char* name, U32 numThreads )
   : mName( name ),
     mNumThreads( numThreads ),
     mNumThreadsAwake( 0 ),
     mThreads( 0 ),
     mSemaphore( 0 )
{
   // Number of worker threads to create.

   if( !mNumThreads )
   {
      // Use platformCPUInfo directly as in the case of the global pool,
      // Platform::SystemInfo will not yet have been initialized.
      
      U32 numLogical = 0;
      U32 numPhysical = 0;
      U32 numCores = 0;

      CPUInfo::CPUCount( numLogical, numCores, numPhysical );
      
      const U32 baseCount = getMax( numLogical, numCores );
      mNumThreads = (baseCount > 0) ? baseCount : 2;
   }
   
   #ifdef DEBUG_SPEW
   Platform::outputDebugString( "[ThreadPool] spawning %i threads", mNumThreads );
   #endif

   // Create the threads.

   mNumThreadsAwake = mNumThreads;
   mNumThreadsReady = mNumThreads;
   for( U32 i = 0; i < mNumThreads; i ++ )
   {
      WorkerThread* thread = new WorkerThread( this, i );
      thread->start();
   }
}
Beispiel #11
0
/**
 * @brief Called when the node is captured by the mouse
 */
void uiBarNode::onCapturedMouseMove (uiNode_t* node, int x, int y)
{
	UI_NodeAbsoluteToRelativePos(node, &x, &y);

	if (x < 0)
		x = 0;
	else if (x > node->box.size[0])
		x = node->box.size[0];
	if (y < 0)
		y = 0;
	else if (y > node->box.size[1])
		y = node->box.size[1];

	float frac;
	const float min = getMin(node);
	const float max = getMax(node);

	switch (EXTRADATA(node).orientation) {
	case ALIGN_UC:
		frac = (node->box.size[1] - (float) y) / node->box.size[1];
		break;
	case ALIGN_LC:
		frac = (float) y / node->box.size[1];
		break;
	case ALIGN_CR:
		frac = (float) x / node->box.size[0];
		break;
	case ALIGN_CL:
		frac = (node->box.size[0] - (float) x) / node->box.size[0];
		break;
	default:
		frac = 0;
		Com_Printf("UI_BarNodeCapturedMouseMove: Orientation %d not supported\n", EXTRADATA(node).orientation);
		break;
	}

	setValue(node, min + frac * (max - min));
}
Beispiel #12
0
log_double UniformPrior::accountForMeanSubstChange( TreeAln &traln, const AbstractParameter* param, double oldFc, double newFc )const 
{
  auto result = 0.; 

  auto maxV =  exp( - getMin() / newFc) , 
    minV = exp(  - getMax() / newFc) ; 

  for(auto &b : traln.extractBranches(param))
    {
      bool less = b.getLength().getValue() < minV; 
      bool greater = b.getLength().getValue() > maxV; 
	      
      assert(not (less && greater)); 

      if(less || greater)
	{
	  // tout << b.getLength() << " is not okay (" << b.getInterpretedLength(traln,param) << ")" << std::endl; 
	  result += - std::numeric_limits<double>::infinity();
	}
    }
  
  return log_double::fromAbs(result); 
} 
Beispiel #13
0
void ColorArray::set( int in_ncolor, int* in_color, int in_nalpha, double* in_alpha)
{
  ncolor  = getMax(in_ncolor, in_nalpha);
  nalpha  = in_nalpha;
  u8* ptr = arrayptr = (u8*) realloc( arrayptr, sizeof(u8) * 4 * ncolor);

  hint_alphablend = false;

  for (unsigned int i=0;i<ncolor;i++) {
    int base = (i%in_ncolor) * 3;
    ptr[0] = (u8) in_color[base];
    ptr[1] = (u8) in_color[base+1];
    ptr[2] = (u8) in_color[base+2];
    if (in_nalpha > 0) {
      u8 alpha = (u8) ( clamp( (float) in_alpha[i%in_nalpha], 0.0f, 1.0f) * 255.0f );
      if (alpha < 255)
        hint_alphablend = true;
      ptr[3] = alpha;
    } else
      ptr[3] = 0xFF;
    ptr += 4;    
  }
}
 int FindGreatestSumOfSubArray(vector<int> array) {
     
     if(array.empty())
         return 0;
     
     int retMax=INT_MIN;
     int len = array.size();
     vector<int> ans(len,INT_MIN);
     
     ans[0] = array[0];
     retMax = ans[0];
     
     for(int i=1; i<len; i++)
     {
     	ans[i] = getMax( (ans[i-1] + array[i]), array[i]);  
         
         if(ans[i] > retMax)
             retMax = ans[i];
     }
     
     return retMax;
 
 }
Beispiel #15
0
void DecalData::onStaticModified( const char *slotName, const char *newValue )
{
   Parent::onStaticModified( slotName, newValue );

   if ( !isProperlyAdded() )
      return;

   // To allow changing materials live.
   if ( dStricmp( slotName, "material" ) == 0 )
   {
      materialName = newValue;
      _updateMaterial();
   }
   // To allow changing name live.
   else if ( dStricmp( slotName, "name" ) == 0 )
   {
      lookupName = getName();
   }
   else if ( dStricmp( slotName, "renderPriority" ) == 0 )
   {
      renderPriority = getMax( renderPriority, (U8)1 );
   }
}
QList<int> ValueModelBase::getPrimeNumber(QList<int> in)
{
	QList<int> prime;
	std::ifstream inStream("primeList.txt");
	std::string in_string;
	inStream >> in_string;
	
	QString in_qstring = QString(in_string.c_str());
	QStringList prime_1_10000 = in_qstring.split(',');
	int max = getMax(in);
	int endIndex = 0;
	for (size_t i = 0; i < prime_1_10000.size(); i++)
	{
		//qdebug() << prime_1_10000.at(i).toInt();
		if (prime_1_10000.at(i).toInt() >= max)
		{
			//qdebug() << i;
			endIndex = i;
			break;
		}
	}

	for (size_t i = 0; i <= endIndex; i++)
	{
		for (auto& obj: in)
		{
			if (obj == prime_1_10000.at(i).toInt())
			{
				prime.push_back(obj);
			}
			
		}
		
	}

	return prime;
}
Beispiel #17
0
void Pot::update(){     
    currentValue = ofClamp(currentValue, outputMin, outputMax);   
    midiValue = ofMap(currentValue, getMin(), getMax(), outputMin, outputMax);
    midiValue = ofClamp(midiValue, outputMin, outputMax);
        
    //normalValue = ofClamp(currentValue, outputMin, outputMax);      
    //cout << borderAreaWidth << endl;
    /*
    switch(mode){   
        case NORMAL:
            midiValue = normalValue;
            break;
        case SWITCH_OFF_BOTTOM://under threshold, sends zero. after threshold, (outputMin, outputMax)              
            if(currentValue < zeroThreshold){                 
                midiValue = 0;                
            }
            else{
                midiValue = normalValue; //or from zerothreshold??
            }            
            break;
        case MIN_MAX_AREAS: //under and over thresholds, sends min and max respectively.             
            if(currentValue < bottomAreaPos){
                midiValue = outputMin;
            }
            else if(currentValue > topAreaPos){
                midiValue = outputMax;
            }
            else{
                midiValue = normalValue;
            } 
            break;          
    }*/ 
    
    if(sendMIDIonUpdate){
        sendMIDI();
    }
}
Beispiel #18
0
void J1DSliderObj::update(JGraphics g, double dx, double dy, JRegion& rgn, double scale) {
  int dt = depth2+2;
  JRect rect = getIExtent(dx, dy, scale);
  if ((rect.width > dt) && (rect.height > dt)) {
    int oldv = value;
    JRect clip = rect, thumb;
    JRegion frgn(clip.shrinkBy(depth+1, depth+1));
    if (type == HORIZONTAL) {
      int len = rect.width-dt-dt;
      if (oldf != factor) {
	oldf = factor;
	fraction = (factor*rect.width-dt)/len;
	fraction = max(0.0, min(1.0, fraction));
      }
      int pos = (int)JMath::round(fraction*len);
      thumb = JRect(clip.x+pos, clip.y, dt, clip.height);
    } else {
      int len = rect.height-dt-dt;
      if (oldf != factor) {
	oldf = factor;
	fraction = (factor*rect.height-dt)/len;
	fraction = max(0.0, min(1.0, fraction));
      }
      int pos = (int)JMath::round((1.0-fraction)*len);
      thumb = JRect(clip.x, clip.y+pos, clip.width, dt);
    }
    int vmin = getMin();
    value = (int)JMath::round(fraction*(getMax()-vmin)+vmin);
    if (value != oldv) broadcast(0);
    g.setJColor(color);
    g.fill3DJRect(thumb, depth);
    g.setJRegion((frgn & rgn)-JRegion(thumb));
    g.setJColor(bkgnd);
    g.fillJRect(clip);
    g.setJRegion(rgn);
  }
}
Beispiel #19
0
// Remember that this method only superficially looks like a normal
// writeElement() method.
DECLARE_EXPORT void FlowPlan::writeElement(XMLOutput *o, const Keyword& tag, mode m) const
{
  o->BeginObject(tag);
  o->writeElement(Tags::tag_date, getDate());
  o->writeElement(Tags::tag_quantity, getQuantity());
  o->writeElement(Tags::tag_onhand, getOnhand());
  o->writeElement(Tags::tag_minimum, getMin());
  o->writeElement(Tags::tag_maximum, getMax());
  if (!dynamic_cast<OperationPlan*>(o->getCurrentObject()))
    o->writeElement(Tags::tag_operationplan, &*getOperationPlan());

  // Write pegging info.
  if (o->getContentType() == XMLOutput::PLANDETAIL)
  {
    // Write the upstream pegging
    PeggingIterator k(this, false);
    if (k) --k;
    for (; k; --k)
      o->writeElement(Tags::tag_pegging,
        Tags::tag_level, -k.getLevel(),
        Tags::tag_operationplan, k.getOperationPlan()->getIdentifier(),
        Tags::tag_quantity, k.getQuantity()
        );

    // Write the downstream pegging
    PeggingIterator l(this, true);
    if (l) ++l;
    for (; l; ++l)
      o->writeElement(Tags::tag_pegging,
        Tags::tag_level, l.getLevel(),
        Tags::tag_operationplan, l.getOperationPlan()->getIdentifier(),
        Tags::tag_quantity, l.getQuantity()
        );
  }

  o->EndObject(tag);
}
  bool brightRGB::apply(const image& src,
			dvector& dest) const {
    std::vector<channel8> ch;

    switch (getParameters().type) {
      case parameters::Minimum: {
	return getMin(src,dest);
      }
      case parameters::Maximum: {
	return getMax(src,dest);
      }
      case parameters::Average: {
	return getAverage(src,dest);
      }
      case parameters::Median: {
	return getMedian(src,dest);
      }
      default:{
	setStatusString("Kind of filter-type doesn't exist");
	return false;
      }
    }
    return true;
  };
void Godunov::SinglePhase(const double & CFL) {
	double t = 0;
	while (t < getMax()) {
		BoundaryConditions();
		for (unsigned i = 0; i < getCell().size(); ++i) {
			if (i == getCell().size() - 2)
				continue;
			RiemannSolver riemann(getCell()[i % getCell().size()],
					getCell()[(i + 1) % getCell().size()], 1);
			riemann.solve();
			riemann.phase_star_[0].Sample(0, setCell()[i].setPhase()[0].setU_half(),
					setCell()[i].setPhase()[0].setP_half(),
					setCell()[i].setPhase()[0].setD_half(), riemann.phase_star_[0].pstar[0]
                                                          , riemann.phase_star_[0].ustar[0]);
			setCell()[i].setPhase()[0].InterCellFlux();
		}
		computeDT(CFL);
		timeIntegration();
		for (unsigned i = 0; i < getCell().size(); ++i) {
			setCell()[i].setPhase()[0].computeScalFromCons();
		}
		t += getDt();
	}
}
Beispiel #22
0
uint64_t freq_pstate_getCpuClockMin(const int cpu_id )
{
    char buff[256];
    unsigned int pct = 0;
    unsigned int maxFreq = getMax();
    if (num_steps == 0)
    {
        steps();
    }
    uint64_t clock = ((percent[0]) * maxFreq) * 10;
    FILE* f = fopen("/sys/devices/system/cpu/intel_pstate/min_perf_pct","r");
    if (f != NULL)
    {
        char *eptr = fgets(buff, 256, f);
        if (eptr != NULL)
        {
            pct = strtoull(buff, NULL, 10);
            for (int i=0; i < num_steps; i++)
            {
                if (percent[i] == pct)
                {
                    if (i > 0)
                        clock = ((percent[i-1]) * maxFreq) * 10;
                    else
                        clock = ((percent[i]) * maxFreq) * 10;
                    break;
                }
            }
        }
        fclose(f);
    }
    return clock;



}
 int firstMissingPositive(vector<int> &A) {
     if (A.empty())
         return 1;
     
     int max = getMax(A);
     int *positiveNumbers = new int[max + 1];
     memset(positiveNumbers, 0, sizeof(int) * (max + 1));
     
     for (int i = 0; i < A.size(); i++) {
         if (A[i] > 0) {
             positiveNumbers[A[i]] = A[i];
         }
     }
     
     for (int i = 1; i <= max; i++) {
         if (positiveNumbers[i] != i) {
             return i;
         }
     }
     
     delete positiveNumbers;
     
     return max + 1; //All positive numbers in A are continous. The missing integer is the next positive numbers of max
 }
Beispiel #24
0
void ParseUpdate(char *updatefile){
	
	uupdatecount = mupdatecount = uupdatemedian  = mupdatemedian = uprefixCount =  0;
	char k=0;
	int j = 0;
	tempStr3 = (char *)calloc(1,2*sizeof(char));
	charToStr3 = (char *)calloc(1,sizeof(char));
	filePointer3 = (FILE *) calloc(1,10 * sizeof(FILE)); 
	
	filePointer3 = fopen(updatefile, "r+");
	
	if( filePointer3 == NULL) 
		fprintf(stderr,"\nMemory cannot be allocated to filepointer3");
	
	else 
		while( !feof(filePointer3) ) {
		
			e = (char)getc(filePointer3);
			
			if (e == 'W' || e == 'A') { 
				fseek(filePointer3,10,SEEK_CUR);
				continue;
			}
		
			else {
			
				sprintf(charToStr3,"%c",e);
				strcat(tempStr3,charToStr3);
		
				if( e == '.' || e == '\n' || e == '/' || e == ' ') {

					k++;
					if(k == 1) {
						uprefixOctet1 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
				
					if(k == 2) {
						uprefixOctet2 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
				
					if(k == 3) {
						uprefixOctet3 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
				
					if(k == 4) {
						uprefixOctet4 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
			
					if(k == 5) {
						uprefixLength = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
					if(k == 6) {
						unextHopOctet1 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
					if(k == 7) {
						unextHopOctet2 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
					if(k == 8) {
						unextHopOctet3 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
					if(k == 9) {
						unextHopOctet4 = atoi(tempStr3);
						strcpy(tempStr3,initializer);
					}
		
				}
			}
		
		if (e == '\n' ) {
			k = 0;
			
			if(uprefixLength < 2 || uprefixLength > 30) 
				continue;
			
			u = u1 = v = v1 = g = g1 = h = h1 = 0;
				
			getPrefix(uprefixOctet1, uprefixOctet2,uprefixOctet3,uprefixOctet4 ,uprefixLength, uprefixFinal, muprefixFinal);
			uprefixCount++;
			
			if(unextHopOctet1 == 0 && unextHopOctet2 == 0 && unextHopOctet3 == 0 && unextHopOctet4 == 0 ){
				printf("\n\nDeleting nextHop at %d.%d.%d.%d/%d ", uprefixOctet1,uprefixOctet2, uprefixOctet3, uprefixOctet4, uprefixLength);
				//getPrefix(uprefixOctet1, uprefixOctet2,uprefixOctet3,uprefixOctet4 ,uprefixLength, uprefixFinal, muprefixFinal);
				rdtsc(u);
				deleteNode(uprefixFinal,trie->root,uprefixLength);
				rdtsc(u1);
				updateuniarray[uupdatecount++] = (u1 - u);
				rdtsc(v);
				mdeleteNode(muprefixFinal,mtrie->root,muprefixLength);
				rdtsc(v1);
				
				updatemultiarray[mupdatecount++] = (v1 - v);
			}
			else {
				printf("\n\nUpdating nextHop at %d.%d.%d.%d/%d ", uprefixOctet1,uprefixOctet2, uprefixOctet3, uprefixOctet4, uprefixLength, unextHopOctet1,unextHopOctet2,unextHopOctet3,unextHopOctet4);
				
				//getPrefix(uprefixOctet1, uprefixOctet2,uprefixOctet3,uprefixOctet4 ,uprefixLength, uprefixFinal, muprefixFinal);
				
				strcpy(nextHop1, initializer);
				sprintf(nextHop1,"%d.%d.%d.%d",unextHopOctet1,unextHopOctet2,unextHopOctet3,unextHopOctet4);
				
				if(uprefixLength % 2 == 0)
					muprefixLength = uprefixLength / 2;
				else 
					muprefixLength = (uprefixLength/2) + 1;
			
				rdtsc(g);
				for(j = 0 ; j< uprefixLength; j++){
			
					data1 = NULL;
					
					if( j == 0 ) tempNode2 = trie->root;
					
					if(j == uprefixLength -1) {
						data1 = (char *)calloc(1,20*sizeof(char));
						strcpy(data1,nextHop1);
					}
					
					if(uprefixFinal[j] == 0){	
						tempNode2 = updateNode(trie,tempNode2,data1,0);
						if(j == uprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", tempNode2->data );
							if((tempNode2->data = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to newdata");
							strcpy(tempNode2->data,nextHop1);
							printf("\nThe new value at this address is %s", tempNode2->data );
						}
						continue;
					}
					
					else {
						if(uprefixFinal[j] == 1){
							 tempNode2 = updateNode(trie,tempNode2,data1,1);
							 if(j == uprefixLength - 1 ){
							 	printf("\nReplacing nextHop");
							 	printf("\nThe previous value at this address was %s", tempNode2->data );
								if((tempNode2->data = (char *)calloc(1,20*sizeof(char)))==NULL)
									fprintf(stderr,"Memory could not be allocated using calloc to newdata");
							strcpy(tempNode2->data,nextHop1);
							printf("\nThe new value at this address is %s", tempNode2->data );
							}
						 	 continue;
						}						
					}
				}
				
				rdtsc(g1);
				updateuniarray[uupdatecount++] = (g1 - g);
				rdtsc(h);
				for(j = 0 ; j< muprefixLength; j++){
			
					mdata1 = NULL;
					
					if( j == 0 ) mtempNode2 = mtrie->root;
					
					if(j == muprefixLength -1) {
						mdata1 = (char *)calloc(1,20*sizeof(char));
						strcpy(mdata1,nextHop1);
					}
					
					if(strcmp(muprefixFinal[j], "00") == 0){	
						mtempNode2 = mupdateNode(mtrie,mtempNode2,mdata1,"00",0);
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->pdata );
							if((mtempNode2->pdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->pdata");
							strcpy(mtempNode2->pdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->pdata );
						}
						continue;
					}
					
					else if(strcmp(muprefixFinal[j], "01") == 0){	
						mtempNode2 = mupdateNode(mtrie,mtempNode2,mdata1,"01",0);
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->pdata );
							if((mtempNode2->pdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->pdata");
							strcpy(mtempNode2->pdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->pdata );
						}
						continue;
					}
					
					else if(strcmp(muprefixFinal[j], "10") == 0){	
						mtempNode2 = mupdateNode(mtrie,mtempNode2,mdata1,"10",0);
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->pdata );
							if((mtempNode2->pdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->pdata");
							strcpy(mtempNode2->pdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->pdata );
						}
						continue;
					}
					
					else if(strcmp(muprefixFinal[j], "11") == 0){	
						mtempNode2 = mupdateNode(mtrie,mtempNode2,mdata1,"11",0);
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->pdata );
							if((mtempNode2->pdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->pdata");
							strcpy(mtempNode2->pdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->pdata );
						}
						continue;
					}
					else {
						if(strcmp(muprefixFinal[j], "0") == 0){	
							 mupdateNode(mtrie,mtempNode2,mdata1,"00",1);
							 mupdateNode(mtrie,mtempNode2,mdata1,"01",1);
						
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->first->sdata );
							
							if((mtempNode2->first->sdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->first->sdata");
							
							strcpy(mtempNode2->first->sdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->first->sdata );
							
							printf("\nThe previous value at this address was %s", mtempNode2->second->sdata );
							
							if((mtempNode2->second->sdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->first->sdata");
							
							strcpy(mtempNode2->second->sdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->second->sdata );
						
						}
						continue;
					}	
					
						else if(strcmp(muprefixFinal[j], "1") == 0){	
							 mupdateNode(mtrie,mtempNode2,mdata1,"10",1);
							 mupdateNode(mtrie,mtempNode2,mdata1,"11",1);
						
						if(j == muprefixLength - 1){
							printf("\nReplacing nextHop");
							printf("\nThe previous value at this address was %s", mtempNode2->third->sdata );
							
							if((mtempNode2->third->sdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->third->sdata");
							
							strcpy(mtempNode2->third->sdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->third->sdata );
							
							printf("\nThe previous value at this address was %s", mtempNode2->fourth->sdata );
							
							if((mtempNode2->fourth->sdata = (char *)calloc(1,20*sizeof(char)))==NULL)
								fprintf(stderr,"Memory could not be allocated using calloc to mtempNode2->fourth->sdata");
							
							strcpy(mtempNode2->fourth->sdata,nextHop1);
							printf("\nThe new value at this address is %s", mtempNode2->fourth->sdata );
						
						}
						continue;
					}	
					
					}
				}
				rdtsc(h1);
				updatemultiarray[mupdatecount++] = (h1 - h);
				unextHopOctet1 = unextHopOctet2 = unextHopOctet3 = unextHopOctet4 = 0;
			}
				
				
		}		
	}
	
	uupdatemedian = getMedian(updateuniarray,uupdatecount);
	mupdatemedian = getMedian(updatemultiarray,mupdatecount);	
	uupdatemean = getMean(updateuniarray,uupdatecount);
	mupdatemean = getMean(updatemultiarray,mupdatecount);	
	uupdatemin = getMin(updateuniarray,uupdatecount);
	mupdatemin = getMin(updatemultiarray,mupdatecount);	
	uupdatemax = getMax(updateuniarray,uupdatecount);
	mupdatemax = getMax(updatemultiarray,mupdatecount);	
	
}
Beispiel #25
0
void ParseLookup(char *lookupfile){
	
	ulpmcount = mlpmcount = ulpmmedian = mlpmmedian= lookupCount = 0;
	k = 0;
	tempStr2 = (char *)calloc(1,2*sizeof(char));
	charToStr2 = (char *)calloc(1,sizeof(char));
	filePointer2 = (FILE *) calloc(1,10 * sizeof(FILE)); 

	filePointer2 = fopen(lookupfile, "r+");
	//printf("\n\nInside ParseLookup() lookup.txt starts here\n\n");

	if( filePointer2 == NULL) 
		fprintf(stderr,"\nMemory cannot be allocated to filepointer2");
	
	else 
	while( !feof(filePointer2) ) {
		
		d = (char)getc(filePointer2);
		sprintf(charToStr2,"%c",d);
		strcat(tempStr2,charToStr2);
		
		if( d == '.' || d == '\n') {

			k++;
			if(k == 1) {
				lookupOctet1 = atoi(tempStr2);
				strcpy(tempStr2,initializer);
			}
			if(k == 2) {
				lookupOctet2 = atoi(tempStr2);
				strcpy(tempStr2,initializer);
			}
			if(k == 3) {
				lookupOctet3 = atoi(tempStr2);
				strcpy(tempStr2,initializer);
			}
			if(k == 4) {
				lookupOctet4 = atoi(tempStr2);
				strcpy(tempStr2,initializer);
			}
		
		
		}
			if (d == '\n' ) {		
				k = 0;
				printf("\nAddress %d.%d.%d.%d  ", lookupOctet1, lookupOctet2,lookupOctet3,lookupOctet4 );
				getPrefix(lookupOctet1, lookupOctet2,lookupOctet3,lookupOctet4 ,lookupLength, lookupFinal, mlookupFinal);
				getLongestPrefixMatch(lookupFinal, mlookupFinal);
			}
	}
	
	 
	ulpmmedian = getMedian(lpmuniarray,ulpmcount);
	mlpmmedian = getMedian(lpmmultiarray,mlpmcount);
	ulpmmean = getMean(lpmuniarray,ulpmcount);
	mlpmmean = getMean(lpmmultiarray,mlpmcount);
	ulpmmin = getMin(lpmuniarray,ulpmcount);
	mlpmmin = getMin(lpmmultiarray,mlpmcount);
	ulpmmax = getMax(lpmuniarray,ulpmcount);
	mlpmmax = getMax(lpmmultiarray,mlpmcount);
}
Beispiel #26
0
void DecalRoad::_generateEdges()
{      
   PROFILE_SCOPE( DecalRoad_generateEdges );

   //Con::warnf( "%s - generateEdges", isServerObject() ? "server" : "client" );

   if ( mNodes.size() > 0 )
   {
      // Set our object position to the first node.
      const Point3F &nodePt = mNodes.first().point;
      MatrixF mat( true );
      mat.setPosition( nodePt );
      Parent::setTransform( mat );

      // The server object has global bounds, which Parent::setTransform 
      // messes up so we must reset it.
      if ( isServerObject() )
      {
         mObjBox.minExtents.set(-1e10, -1e10, -1e10);
         mObjBox.maxExtents.set( 1e10,  1e10,  1e10);
      }
   }


   if ( mNodes.size() < 2 )
      return;

   // Ensure nodes are above the terrain height at their xy position
   for ( U32 i = 0; i < mNodes.size(); i++ )
   {
      _getTerrainHeight( mNodes[i].point );
   }

   // Now start generating edges...

   U32 nodeCount = mNodes.size();
   Point3F *positions = new Point3F[nodeCount];

   for ( U32 i = 0; i < nodeCount; i++ )
   {
      const RoadNode &node = mNodes[i];
      positions[i].set( node.point.x, node.point.y, node.width );
   }

   CatmullRom<Point3F> spline;
   spline.initialize( nodeCount, positions );
   delete [] positions;

   mEdges.clear();

   Point3F lastBreakVector(0,0,0);      
   RoadEdge slice;
   Point3F lastBreakNode;
   lastBreakNode = spline.evaluate(0.0f);

   for ( U32 i = 1; i < mNodes.size(); i++ )
   {
      F32 t1 = spline.getTime(i);
      F32 t0 = spline.getTime(i-1);

      F32 segLength = spline.arcLength( t0, t1 );

      U32 numSegments = mCeil( segLength / MIN_METERS_PER_SEGMENT );
      numSegments = getMax( numSegments, (U32)1 );
      F32 tstep = ( t1 - t0 ) / numSegments; 

      U32 startIdx = 0;
      U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;

      for ( U32 j = startIdx; j < endIdx; j++ )
      {
         F32 t = t0 + tstep * j;
         Point3F splineNode = spline.evaluate(t);
         F32 width = splineNode.z;
         _getTerrainHeight( splineNode );

         Point3F toNodeVec = splineNode - lastBreakNode;
         toNodeVec.normalizeSafe();

         if ( lastBreakVector.isZero() )
            lastBreakVector = toNodeVec;

         F32 angle = mRadToDeg( mAcos( mDot( toNodeVec, lastBreakVector ) ) );

         if ( j == startIdx || 
            ( j == endIdx - 1 && i == mNodes.size() - 1 ) ||
            angle > mBreakAngle )
         {
            // Push back a spline node
            //slice.p1.set( splineNode.x, splineNode.y, 0.0f );
            //_getTerrainHeight( slice.p1 );
            slice.p1 = splineNode;
            slice.uvec.set(0,0,1);
            slice.width = width;            
            slice.parentNodeIdx = i-1;
            mEdges.push_back( slice );         

            lastBreakVector = splineNode - lastBreakNode;
            lastBreakVector.normalizeSafe();

            lastBreakNode = splineNode;
         }          
      }
   }

   /*
   for ( U32 i = 1; i < nodeCount; i++ )
   {
      F32 t0 = spline.getTime( i-1 );
      F32 t1 = spline.getTime( i );

      F32 segLength = spline.arcLength( t0, t1 );

      U32 numSegments = mCeil( segLength / mBreakAngle );
      numSegments = getMax( numSegments, (U32)1 );
      F32 tstep = ( t1 - t0 ) / numSegments;

      AssertFatal( numSegments > 0, "DecalRoad::_generateEdges, got zero segments!" );   

      U32 startIdx = 0;
      U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;

      for ( U32 j = startIdx; j < endIdx; j++ )
      {
         F32 t = t0 + tstep * j;
         Point3F val = spline.evaluate(t);

         RoadEdge edge;         
         edge.p1.set( val.x, val.y, 0.0f );    
         _getTerrainHeight( val.x, val.y, edge.p1.z );    
         edge.uvec.set(0,0,1);
         edge.width = val.z;
         edge.parentNodeIdx = i-1;
         mEdges.push_back( edge );
      }   
   }
   */

   //
   // Calculate fvec and rvec for all edges
   //
   RoadEdge *edge = NULL;
   RoadEdge *nextEdge = NULL;

   for ( U32 i = 0; i < mEdges.size() - 1; i++ )
   {
      edge = &mEdges[i];
      nextEdge = &mEdges[i+1];

      edge->fvec = nextEdge->p1 - edge->p1;
      edge->fvec.normalize();

      edge->rvec = mCross( edge->fvec, edge->uvec );
      edge->rvec.normalize();
   }

   // Must do the last edge outside the loop
   RoadEdge *lastEdge = &mEdges[mEdges.size()-1];
   RoadEdge *prevEdge = &mEdges[mEdges.size()-2];
   lastEdge->fvec = prevEdge->fvec;
   lastEdge->rvec = prevEdge->rvec;


   //
   // Calculate p0/p2 for all edges
   //      
   for ( U32 i = 0; i < mEdges.size(); i++ )
   {
      RoadEdge *edge = &mEdges[i];
      edge->p0 = edge->p1 - edge->rvec * edge->width * 0.5f;
      edge->p2 = edge->p1 + edge->rvec * edge->width * 0.5f;
      _getTerrainHeight( edge->p0 );
      _getTerrainHeight( edge->p2 );
   }   
}
Beispiel #27
0
Cube Cube::boundingBox()
{

    return Cube(getMin(),getMax(),getCenter());
}
Beispiel #28
0
void updateChunkWriteStatsAndSplitIfNeeded(OperationContext* opCtx,
                                           ChunkManager* manager,
                                           Chunk* chunk,
                                           long dataWritten) {
    // Disable lastError tracking so that any errors, which occur during auto-split do not get
    // bubbled up on the client connection doing a write.
    LastError::Disabled d(&LastError::get(cc()));

    const auto balancerConfig = Grid::get(opCtx)->getBalancerConfiguration();

    const bool minIsInf =
        (0 == manager->getShardKeyPattern().getKeyPattern().globalMin().woCompare(chunk->getMin()));
    const bool maxIsInf =
        (0 == manager->getShardKeyPattern().getKeyPattern().globalMax().woCompare(chunk->getMax()));

    const uint64_t chunkBytesWritten = chunk->addBytesWritten(dataWritten);

    const uint64_t desiredChunkSize =
        calculateDesiredChunkSize(balancerConfig->getMaxChunkSizeBytes(), manager->numChunks());

    if (!chunk->shouldSplit(desiredChunkSize, minIsInf, maxIsInf)) {
        return;
    }

    const NamespaceString nss(manager->getns());

    if (!manager->_autoSplitThrottle._splitTickets.tryAcquire()) {
        LOG(1) << "won't auto split because not enough tickets: " << nss;
        return;
    }

    TicketHolderReleaser releaser(&(manager->_autoSplitThrottle._splitTickets));

    const ChunkRange chunkRange(chunk->getMin(), chunk->getMax());

    try {
        // Ensure we have the most up-to-date balancer configuration
        uassertStatusOK(balancerConfig->refreshAndCheck(opCtx));

        if (!balancerConfig->getShouldAutoSplit()) {
            return;
        }

        LOG(1) << "about to initiate autosplit: " << redact(chunk->toString())
               << " dataWritten: " << chunkBytesWritten
               << " desiredChunkSize: " << desiredChunkSize;

        const uint64_t chunkSizeToUse = [&]() {
            const uint64_t estNumSplitPoints = chunkBytesWritten / desiredChunkSize * 2;

            if (estNumSplitPoints >= kTooManySplitPoints) {
                // The current desired chunk size will split the chunk into lots of small chunk and
                // at the worst case this can result into thousands of chunks. So check and see if a
                // bigger value can be used.
                return std::min(chunkBytesWritten, balancerConfig->getMaxChunkSizeBytes());
            } else {
                return desiredChunkSize;
            }
        }();

        auto splitPoints =
            uassertStatusOK(shardutil::selectChunkSplitPoints(opCtx,
                                                              chunk->getShardId(),
                                                              nss,
                                                              manager->getShardKeyPattern(),
                                                              chunkRange,
                                                              chunkSizeToUse,
                                                              boost::none));

        if (splitPoints.size() <= 1) {
            // No split points means there isn't enough data to split on; 1 split point means we
            // have
            // between half the chunk size to full chunk size so there is no need to split yet
            chunk->clearBytesWritten();
            return;
        }

        if (minIsInf || maxIsInf) {
            // We don't want to reset _dataWritten since we want to check the other side right away
        } else {
            // We're splitting, so should wait a bit
            chunk->clearBytesWritten();
        }

        // We assume that if the chunk being split is the first (or last) one on the collection,
        // this chunk is likely to see more insertions. Instead of splitting mid-chunk, we use the
        // very first (or last) key as a split point.
        //
        // This heuristic is skipped for "special" shard key patterns that are not likely to produce
        // monotonically increasing or decreasing values (e.g. hashed shard keys).
        if (KeyPattern::isOrderedKeyPattern(manager->getShardKeyPattern().toBSON())) {
            if (minIsInf) {
                BSONObj key = findExtremeKeyForShard(
                    opCtx, nss, chunk->getShardId(), manager->getShardKeyPattern(), true);
                if (!key.isEmpty()) {
                    splitPoints.front() = key.getOwned();
                }
            } else if (maxIsInf) {
                BSONObj key = findExtremeKeyForShard(
                    opCtx, nss, chunk->getShardId(), manager->getShardKeyPattern(), false);
                if (!key.isEmpty()) {
                    splitPoints.back() = key.getOwned();
                }
            }
        }

        const auto suggestedMigrateChunk =
            uassertStatusOK(shardutil::splitChunkAtMultiplePoints(opCtx,
                                                                  chunk->getShardId(),
                                                                  nss,
                                                                  manager->getShardKeyPattern(),
                                                                  manager->getVersion(),
                                                                  chunkRange,
                                                                  splitPoints));

        // Balance the resulting chunks if the option is enabled and if the shard suggested a chunk
        // to balance
        const bool shouldBalance = [&]() {
            if (!balancerConfig->shouldBalanceForAutoSplit())
                return false;

            auto collStatus =
                Grid::get(opCtx)->catalogClient()->getCollection(opCtx, manager->getns());
            if (!collStatus.isOK()) {
                log() << "Auto-split for " << nss << " failed to load collection metadata"
                      << causedBy(redact(collStatus.getStatus()));
                return false;
            }

            return collStatus.getValue().value.getAllowBalance();
        }();

        log() << "autosplitted " << nss << " chunk: " << redact(chunk->toString()) << " into "
              << (splitPoints.size() + 1) << " parts (desiredChunkSize " << desiredChunkSize << ")"
              << (suggestedMigrateChunk ? "" : (std::string) " (migrate suggested" +
                          (shouldBalance ? ")" : ", but no migrations allowed)"));

        // Reload the chunk manager after the split
        auto routingInfo = uassertStatusOK(
            Grid::get(opCtx)->catalogCache()->getShardedCollectionRoutingInfoWithRefresh(opCtx,
                                                                                         nss));

        if (!shouldBalance || !suggestedMigrateChunk) {
            return;
        }

        // Top chunk optimization - try to move the top chunk out of this shard to prevent the hot
        // spot from staying on a single shard. This is based on the assumption that succeeding
        // inserts will fall on the top chunk.

        // We need to use the latest chunk manager (after the split) in order to have the most
        // up-to-date view of the chunk we are about to move
        auto suggestedChunk = routingInfo.cm()->findIntersectingChunkWithSimpleCollation(
            suggestedMigrateChunk->getMin());

        ChunkType chunkToMove;
        chunkToMove.setNS(nss.ns());
        chunkToMove.setShard(suggestedChunk->getShardId());
        chunkToMove.setMin(suggestedChunk->getMin());
        chunkToMove.setMax(suggestedChunk->getMax());
        chunkToMove.setVersion(suggestedChunk->getLastmod());

        uassertStatusOK(configsvr_client::rebalanceChunk(opCtx, chunkToMove));

        // Ensure the collection gets reloaded because of the move
        Grid::get(opCtx)->catalogCache()->invalidateShardedCollection(nss);
    } catch (const DBException& ex) {
        chunk->clearBytesWritten();

        if (ErrorCodes::isStaleShardingError(ErrorCodes::Error(ex.getCode()))) {
            log() << "Unable to auto-split chunk " << redact(chunkRange.toString()) << causedBy(ex)
                  << ", going to invalidate routing table entry for " << nss;
            Grid::get(opCtx)->catalogCache()->invalidateShardedCollection(nss);
        }
    }
}
Beispiel #29
0
bool PxBody::init(   PhysicsCollision *shape, 
                     F32 mass,
                     U32 bodyFlags,
                     SceneObject *obj, 
                     PhysicsWorld *world )
{
   AssertFatal( obj, "PxBody::init - Got a null scene object!" );
   AssertFatal( world, "PxBody::init - Got a null world!" );
   AssertFatal( dynamic_cast<PxWorld*>( world ), "PxBody::init - The world is the wrong type!" );
   AssertFatal( shape, "PxBody::init - Got a null collision shape!" );
   AssertFatal( dynamic_cast<PxCollision*>( shape ), "PxBody::init - The collision shape is the wrong type!" );
   AssertFatal( !((PxCollision*)shape)->getShapes().empty(), "PxBody::init - Got empty collision shape!" );
	 
   // Cleanup any previous actor.
   _releaseActor();

   mWorld = (PxWorld*)world;
   mColShape = (PxCollision*)shape;
   mBodyFlags = bodyFlags;

   NxActorDesc actorDesc;
   NxBodyDesc bodyDesc;

   const bool isKinematic = mBodyFlags & BF_KINEMATIC;
   const bool isTrigger = mBodyFlags & BF_TRIGGER;
   const bool isDebris = mBodyFlags & BF_DEBRIS;

   if ( isKinematic )
   {
      // Kinematics are dynamics... so they need
      // a body description.
      actorDesc.body = &bodyDesc;
      bodyDesc.mass = getMax( mass, 1.0f );
	   bodyDesc.flags	|= NX_BF_KINEMATIC;
   }
   else if ( mass > 0.0f )
   {
      // We have mass so its a dynamic.
      actorDesc.body = &bodyDesc;
      bodyDesc.mass = mass;
   }

   if ( isTrigger )
      actorDesc.flags |= NX_AF_DISABLE_RESPONSE;

   // Add all the shapes.
   const Vector<NxShapeDesc*> &shapes = mColShape->getShapes();
   for ( U32 i=0; i < shapes.size(); i++ )
   {
      NxShapeDesc *desc = shapes[i];

      // If this hits then something is broken with 
      // this descrption... check all the fields to be
      // sure their values are correctly filled out.
      AssertFatal( desc->isValid(), "PxBody::init - Got invalid shape description!" );

      if ( isTrigger )
         desc->group = 31;

      if ( isDebris )
         desc->group = 30;

      actorDesc.shapes.push_back( desc );
   }

   // This sucks, but it has to happen if we want
   // to avoid write lock errors from PhysX right now.
   mWorld->releaseWriteLock();

   mActor = mWorld->getScene()->createActor( actorDesc );
   mIsEnabled = true;

   if ( isDebris )
      mActor->setDominanceGroup( 31 );

   mUserData.setObject( obj );
   mUserData.setBody( this );
   mActor->userData = &mUserData;

   return true;
}
Beispiel #30
0
void AutomationPattern::flipY()
{
	flipY(getMin(), getMax());
}