Esempio n. 1
0
size_t BufferArray::append(const void * src, size_t len)
{
	const size_t ret(len);
	const char * c_src(static_cast<const char *>(src));
					  
	// First, try to copy into the last block
	if (len && ! mBlocks.empty())
	{
		Block & last(*mBlocks.back());
		if (last.mUsed < last.mAlloced)
		{
			// Some will fit...
			const size_t copy_len((std::min)(len, (last.mAlloced - last.mUsed)));

			memcpy(&last.mData[last.mUsed], c_src, copy_len);
			last.mUsed += copy_len;
			llassert_always(last.mUsed <= last.mAlloced);
			mLen += copy_len;
			c_src += copy_len;
			len -= copy_len;
		}
	}

	// Then get new blocks as needed
	while (len)
	{
		const size_t copy_len((std::min)(len, BLOCK_ALLOC_SIZE));
		
		if (mBlocks.size() >= mBlocks.capacity())
		{
			mBlocks.reserve(mBlocks.size() + 5);
		}
		Block * block = Block::alloc(BLOCK_ALLOC_SIZE);
		memcpy(block->mData, c_src, copy_len);
		block->mUsed = copy_len;
		llassert_always(block->mUsed <= block->mAlloced);
		mBlocks.push_back(block);
		mLen += copy_len;
		c_src += copy_len;
		len -= copy_len;
	}
	return ret;
}
Esempio n. 2
0
void XTS_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset)
   {
   BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");
   const size_t sz = buffer.size() - offset;
   uint8_t* buf = buffer.data() + offset;

   BOTAN_ASSERT(sz >= minimum_final_size(), "Have sufficient final input in XTS decrypt");

   const size_t BS = cipher().block_size();

   if(sz % BS == 0)
      {
      update(buffer, offset);
      }
   else
      {
      // steal ciphertext
      const size_t full_blocks = ((sz / BS) - 1) * BS;
      const size_t final_bytes = sz - full_blocks;
      BOTAN_ASSERT(final_bytes > BS && final_bytes < 2*BS, "Left over size in expected range");

      secure_vector<uint8_t> last(buf + full_blocks, buf + full_blocks + final_bytes);
      buffer.resize(full_blocks + offset);
      update(buffer, offset);

      xor_buf(last, tweak() + BS, BS);
      cipher().decrypt(last);
      xor_buf(last, tweak() + BS, BS);

      for(size_t i = 0; i != final_bytes - BS; ++i)
         {
         last[i] ^= last[i + BS];
         last[i + BS] ^= last[i];
         last[i] ^= last[i + BS];
         }

      xor_buf(last, tweak(), BS);
      cipher().decrypt(last);
      xor_buf(last, tweak(), BS);

      buffer += last;
      }
   }
Esempio n. 3
0
void CTS_Decryption::finish(secure_vector<uint8_t>& buffer, size_t offset)
   {
   BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");
   const size_t sz = buffer.size() - offset;
   uint8_t* buf = buffer.data() + offset;

   const size_t BS = cipher().block_size();

   if(sz < BS + 1)
      throw Encoding_Error(name() + ": insufficient data to decrypt");

   if(sz % BS == 0)
      {
      // swap last two blocks

      for(size_t i = 0; i != BS; ++i)
         std::swap(buffer[buffer.size()-BS+i], buffer[buffer.size()-2*BS+i]);

      update(buffer, offset);
      }
   else
      {
      const size_t full_blocks = ((sz / BS) - 1) * BS;
      const size_t final_bytes = sz - full_blocks;
      BOTAN_ASSERT(final_bytes > BS && final_bytes < 2*BS, "Left over size in expected range");

      secure_vector<uint8_t> last(buf + full_blocks, buf + full_blocks + final_bytes);
      buffer.resize(full_blocks + offset);
      update(buffer, offset);

      cipher().decrypt(last.data());

      xor_buf(last.data(), &last[BS], final_bytes - BS);

      for(size_t i = 0; i != final_bytes - BS; ++i)
         std::swap(last[i], last[i + BS]);

      cipher().decrypt(last.data());
      xor_buf(last.data(), state_ptr(), BS);

      buffer += last;
      }
   }
std::string IntToUTF8String(int convertMe){
    
    // We only care about plane 1 right now,
    // but know that we have other options (0x10FFFF)
    // Technically UTF-8 is "limited" to 4 bytes, so it's not
    // Like it matters much anyways these days
        
    if(convertMe == 0)
        return " ";
    if( (convertMe <= 0x7F) && (convertMe > 0x00) ){
        
        std::string out(".");
        
        std::bitset<8> x(convertMe);
        
        unsigned long l = x.to_ulong();
        unsigned char c = static_cast<unsigned char>(l);
        out[0] = c;
        
        return out;
        
    } else if ( (convertMe >= 0x80) && (convertMe <= 0x07FF) ) {
        
        std::string out("..");
        
        int firstShift = (convertMe >> 0x06) ^ 0xC0;
        int secondShift = ((convertMe ^ 0xFFC0) | 0x80) & ~0x40;
        
        std::bitset<8> first(firstShift);
        std::bitset<8> last(secondShift);
        
        
        unsigned long l = first.to_ulong();
        unsigned char c = static_cast<unsigned char>(l);
        out[0] = c;
        
        unsigned long ltwo = last.to_ulong();
        unsigned char ctwo = static_cast<unsigned char>(ltwo);
        out[1] = ctwo;
        
        return out;
        
    } else if( (convertMe >= 0x0800) && (convertMe <= 0xFFFF) ){
void DiscreteTrajectory<Frame>::Append(
    Instant const& time,
    DegreesOfFreedom<Frame> const& degrees_of_freedom) {
  CHECK(this->is_root() || time > this->Fork().time())
       << "Append at " << time << " which is before fork time "
       << this->Fork().time();

  if (!timeline_.empty() && timeline_.cbegin()->first == time) {
    LOG(WARNING) << "Append at existing time " << time
                 << ", time range = [" << this->Begin().time() << ", "
                 << last().time() << "]";
    return;
  }
  auto it = timeline_.emplace_hint(timeline_.end(),
                                   time,
                                   degrees_of_freedom);
  // Decrementing |end()| is much faster than incrementing |it|.  Don't ask.
  CHECK(--timeline_.end() == it) << "Append out of order";
}
/*
 * The algorithm to break a multiple open or closed subpaths is:
 * Subpath is closed
 * - open behind the last point in the subpath
 * - go on like as described in Not closed
 * Not closed
 * - break from the back of the subpath
 */
KoPathBreakAtPointCommand::KoPathBreakAtPointCommand(const QList<KoPathPointData> & pointDataList, KUndo2Command *parent)
        : KUndo2Command(parent)
        , m_deletePoints(true)
{
    QList<KoPathPointData> sortedPointDataList(pointDataList);
    qSort(sortedPointDataList);
    setText(i18nc("(qtundo-format)", "Break subpath at points"));

    QList<KoPathPointData>::const_iterator it(sortedPointDataList.constBegin());
    for (; it != sortedPointDataList.constEnd(); ++it) {
        KoPathShape * pathShape = it->pathShape;
        KoPathPoint * point = pathShape->pointByIndex(it->pointIndex);
        if(! point)
            continue;

        // check if subpath is closed and the point is start or end point of the subpath
        if(! pathShape->isClosedSubpath(it->pointIndex.first)) {
            if(it->pointIndex.second == 0
                || it->pointIndex.second == pathShape->subpathPointCount(it->pointIndex.first)) {
                continue;
            }
        }

        m_pointDataList.append(*it);
        m_points.push_back(new KoPathPoint(*point));
        m_closedIndex.push_back(KoPathPointIndex(-1, 0));
    }

    KoPathPointData last(0, KoPathPointIndex(-1, -1));
    for (int i = m_pointDataList.size() - 1; i >= 0; --i) {
        const KoPathPointData &current = m_pointDataList.at(i);

        if (last.pathShape != current.pathShape || last.pointIndex.first != current.pointIndex.first) {
            last = current;
            if (current.pathShape->isClosedSubpath(current.pointIndex.first)) {
                // the break will happen before the inserted point so we have to increment by 1
                m_closedIndex[i] = current.pointIndex;
                ++m_closedIndex[i].second;
            }
        }
    }
}
void KoPathBreakAtPointCommand::redo()
{
    KUndo2Command::redo();
    KoPathPointData last(0, KoPathPointIndex(-1, -1));

    // offset, needed when path was opened
    int offset = 0;
    for (int i = m_pointDataList.size() - 1; i >= 0; --i) {
        const KoPathPointData & pd = m_pointDataList.at(i);
        KoPathShape * pathShape = pd.pathShape;

        KoPathPointIndex pointIndex = pd.pointIndex;
        if (last.pathShape != pathShape || last.pointIndex.first != pointIndex.first) {
            offset = 0;
        }

        pointIndex.second = pointIndex.second + offset + 1;
        pathShape->insertPoint(m_points[i], pointIndex);

        if (m_closedIndex.at(i).first != -1) {
            m_closedIndex[i] = pathShape->openSubpath(m_closedIndex.at(i));
            offset = m_closedIndex.at(i).second;
        } else {
            KoPathPointIndex breakIndex = pd.pointIndex;
            breakIndex.second += offset;
            pathShape->breakAfter(breakIndex);
            m_closedIndex[i].second = offset;
        }

        if (last.pathShape != pathShape) {
            if (last.pathShape) {
                last.pathShape->update();
            }
            last = pd;
        }
    }
    if (last.pathShape) {
        last.pathShape->update();
    }

    m_deletePoints = false;
}
Esempio n. 8
0
std::ostream& operator << (std::ostream& s, const adobe::extents_t::slice_t& x)
{
    adobe::guide_set_t::const_iterator first(x.guide_set_m.begin());
    adobe::guide_set_t::const_iterator last(x.guide_set_m.end());

    s   << adobe::begin_bag("[0]")
            << adobe::begin_sequence
                << adobe::format(adobe::static_name_t("length"))
                << adobe::format(x.length_m)
            << adobe::end_sequence
            << adobe::begin_sequence
                << adobe::format(adobe::static_name_t("outset"))
                << adobe::begin_sequence
                    << adobe::format(x.outset_m.first)
                    << adobe::format(x.outset_m.second)
                << adobe::end_sequence
            << adobe::end_sequence
            << adobe::begin_sequence
                << adobe::format(adobe::static_name_t("frame"))
                << adobe::begin_sequence
                    << adobe::format(x.frame_m.first)
                    << adobe::format(x.frame_m.second)
                << adobe::end_sequence
            << adobe::end_sequence
            << adobe::begin_sequence
                << adobe::format(adobe::static_name_t("inset"))
                << adobe::begin_sequence
                    << adobe::format(x.inset_m.first)
                    << adobe::format(x.inset_m.second)
                << adobe::end_sequence
            << adobe::end_sequence
            << adobe::begin_sequence
                << adobe::format(adobe::static_name_t("poi_set"))
                << adobe::begin_sequence;
                    for (; first != last; ++first)
                        s << adobe::format(*first);
            s   << adobe::end_sequence
            << adobe::end_sequence
        << adobe::end_bag;

    return s;
}
Esempio n. 9
0
        float interpKey(const Nif::FloatKeyList::VecType &keys, float time, float def=0.f) const
        {
            if (keys.size() == 0)
                return def;

            if(time <= keys.front().mTime)
                return keys.front().mValue;

            Nif::FloatKeyList::VecType::const_iterator iter(keys.begin()+1);
            for(;iter != keys.end();iter++)
            {
                if(iter->mTime < time)
                    continue;

                Nif::FloatKeyList::VecType::const_iterator last(iter-1);
                float a = (time-last->mTime) / (iter->mTime-last->mTime);
                return last->mValue + ((iter->mValue - last->mValue)*a);
            }
            return keys.back().mValue;
        }
Esempio n. 10
0
real TimesExpression::execute(Environment &env) const {
	SaveOldValue<real> it  (env.iteration_value());
	SaveOldValue<real> last(env.last_value     ());

	try {
		for (real n = exec<0>(env), i = 0; i < n; i += 1.0) {
			it = i;
			last = exec<1>(env);
		}

		return exec<2>(env);
	}
	catch (BreakException &e) {
		if (e.end()) {
			return e.getValue();
		} else {
			throw;
		}
	}
}
Esempio n. 11
0
void tab_group_t::measure(extents_t& result)
{
    assert(control_m);

    // REVISIT (fbrereto) : A lot of static metrics values added here

    boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
    for (tab_set_t::iterator first(items_m.begin()), last(items_m.end());
         first != last;
         ++first) {
        GG::X text_width = style->DefaultFont()->TextExtent(first->name_m).x;
        result.width() += Value(text_width) + 18;
    }

    result.height() = Value(control_m->MinUsableSize().y);

    result.vertical().frame_m.first = result.height() + 7;

    result.height() = 5;
}
Esempio n. 12
0
void rai::landing::distribute_one ()
{
	auto now (rai::seconds_since_epoch ());
	rai::block_hash last (1);
	while (!last.is_zero () && store.last + distribution_interval.count () < now)
	{
		auto amount (distribution_amount ((store.last - store.start) >> interval_exponent));
		last = wallet->send_sync (store.source, store.destination, amount);
		if (!last.is_zero ())
		{
			BOOST_LOG (node.log) << boost::str (boost::format ("Successfully distributed %1% in block %2%") % amount % last.to_string ());
			store.last += distribution_interval.count ();
			write_store ();
		}
		else
		{
			BOOST_LOG (node.log) << "Error while sending distribution";
		}
	}
}
Esempio n. 13
0
void TileNode::queryTile(const SpatialDimension* hashing, const Query& query, Response& response, ulong level) const {
	const ulong d = level % hashing->key().size();

	if (query.evalTile(d)) {
		if (query.getTile(d) == _pivot.value() || (last() && util::intersects(_pivot.value(), query.getTile(d)))) {
			aggregateTile(hashing, query, response, level);

		} else if (_pivot.value().z < query.zoom) {
			if (_container[0] != nullptr) _container[0]->queryTile(hashing, query, response, level + 1);
			if (_container[1] != nullptr) _container[1]->queryTile(hashing, query, response, level + 1);
			if (_container[2] != nullptr) _container[2]->queryTile(hashing, query, response, level + 1);
			if (_container[3] != nullptr) _container[3]->queryTile(hashing, query, response, level + 1);
		} 		
	} else {
		if (_container[0] != nullptr) _container[0]->queryTile(hashing, query, response, level + 1);
		if (_container[1] != nullptr) _container[1]->queryTile(hashing, query, response, level + 1);
		if (_container[2] != nullptr) _container[2]->queryTile(hashing, query, response, level + 1);
		if (_container[3] != nullptr) _container[3]->queryTile(hashing, query, response, level + 1);
	}
}
Esempio n. 14
0
   bool tBlob::ConnectedWithImageBorder( uint32_xy size_ )const {
      if( this->streak_count() == 0 ) {
         return false;
      }

      auto iStreakStart = _streaks.begin();
      auto iStreakEnd = _streaks.end();
      auto bottom  = size_.x() - 1 ;
      auto right   = size_.y() - 1;
      uint32_t top = 0;
      uint32_t left = 0;

      while( iStreakStart != iStreakEnd ) {
         auto x = iStreakStart->x();
         auto y = iStreakStart->y();
         auto last_ = iStreakStart->last();

         if(
            // top
            y == top
            ||

            // bottom
            y == bottom
            ||

            // left
            x == left
            ||

            // right
            last_ == right
         ) {
            return true;
         }

         ++iStreakStart;
      }

      return false;
   }
Esempio n. 15
0
void
ReliableSession::expire_naks()
{
  if (this->nak_requests_.empty()) return; // nothing to expire

  ACE_Time_Value deadline(ACE_OS::gettimeofday());
  deadline -= this->link_->config()->nak_timeout_;

  NakRequestMap::iterator first(this->nak_requests_.begin());
  NakRequestMap::iterator last(this->nak_requests_.upper_bound(deadline));

  if (first == last) return; // nothing to expire

  // Skip unrecoverable datagrams to
  // re-establish a baseline to detect future reception gaps.
  SequenceNumber lastSeq = (last == this->nak_requests_.end())
                         ? this->nak_requests_.rbegin()->second
                         : last->second;

  std::vector<SequenceRange> dropped;
  if (this->nak_sequence_.insert(SequenceRange(this->nak_sequence_.low(),
                                               lastSeq), dropped)) {

    for (size_t i = 0; i < dropped.size(); ++i) {
      this->reassembly_.data_unavailable(dropped[i]);
    }

    ACE_ERROR((LM_WARNING,
                ACE_TEXT("(%P|%t) WARNING: ")
                ACE_TEXT("ReliableSession::expire_naks: ")
                ACE_TEXT("timed out waiting on remote peer %#08x%08x to send missing samples: %q - %q!\n"),
                (unsigned int)(this->remote_peer_ >> 32),
                (unsigned int) this->remote_peer_,
                this->nak_sequence_.low().getValue(),
                lastSeq.getValue()));
  }

  // Clear expired repair requests:
  this->nak_requests_.erase(first, last);
  deliver_held_data();
}
Esempio n. 16
0
uint32 CBackgroundSound::getDuration()
{
	if (_DurationValid)
		return _Duration;

	vector<sint32>	durations;
	CAudioMixerUser *mixer = CAudioMixerUser::instance();
	std::vector<TSoundInfo>::const_iterator first(_Sounds.begin()), last(_Sounds.end());
	for (; first != last; ++first)
	{
		CSound *sound = mixer->getSoundId(first->SoundName);
		if (sound != NULL)
			durations.push_back(sound->getDuration());
	}
	if (durations.empty())
		return 0;
	_Duration = *(std::max_element(durations.begin(), durations.end()));
	_DurationValid = true;

	return _Duration;
}
Esempio n. 17
0
  void WMALuminance::onLast() {
    std::list<double> queue;
    for (InputImageInfo in : inputs) {
      queue.push_back(in.luminance);
      if (queue.size() > count)
        queue.pop_front();
      double sum = 0;
      double sumWeight = 0;
      size_t i = 1;
      for (double d : queue) {
        double w = (double) i / (double) queue.size();
        sum += w * d;
        sumWeight += w;
        i++;
      }

      in.luminanceChange = (sum / sumWeight) - in.luminance;
      emit input(in);
    }
    emit last();
  }
 vector<vector<int>> generate(int numRows)
 {
     vector<vector<int>> ans;
     if(numRows<=0)
     {
         return ans;
     }
     vector<int> last(1,1);
     ans.push_back(last);
     for(int i=2;i<=numRows;i++)
     {
         vector<int> curr(i,1);
         for(int j=1;j<last.size();j++)
         {
             curr[j]=last[j-1]+last[j];
         }
         ans.push_back(curr);
         last=curr;
     }
     return ans;
 }
Esempio n. 19
0
        static Uint64 calculate(
            size_t size,
            size_t vertexCount,
            const dataType* data
        ) {
            if (vertexCount < 2) {
                return 0;
            }

            typedef gmtl::Vec<dataType, 2> Vec;
            const dataType* v = data;

            Uint64 total = 0;
            Vec last(v[0], v[1]); v += size;
            for (size_t i = 1; i < vertexCount; ++i, v += size) {
                total += Uint64(std::max(myabs(v[0] - last[0]),
                                         myabs(v[1] - last[1])));
                last = Vec(v[0], v[1]);
            }
            return total;
        }
Esempio n. 20
0
    double ROCCurve::AUC()
    {
      if (score_clas_pairs_.empty())
      {
        std::cerr << "ROCCurve::AUC() : unsuitable dataset (no positives or no negatives)\n";
        return 0.5;
      }

      score_clas_pairs_.sort(simsortdec());
      // value that is not in score_clas_pairs_
      double prevsim = score_clas_pairs_.begin()->first + 1;
      UInt truePos = 0;
      UInt falsePos = 0;
      std::vector<DPosition<2> > polygon;
      for (std::list<std::pair<double, bool> >::const_iterator cit = score_clas_pairs_.begin(); cit != score_clas_pairs_.end(); ++cit)
      {
        if (fabs(cit->first - prevsim) > 1e-8)
        {
          polygon.push_back(DPosition<2>((double)falsePos / neg_, (double)truePos / pos_));
        }
        if (cit->second)
        {
          ++truePos;
        }
        else
        {
          ++falsePos;
        }
      }
      polygon.push_back(DPosition<2>(1, 1));
      std::sort(polygon.begin(), polygon.end());
      DPosition<2> last(0, 0);
      double area(0);
      for (std::vector<DPosition<2> >::const_iterator it = polygon.begin(); it != polygon.end(); ++it)
      {
        area += (it->getX() - last.getX()) * (it->getY());
        last = *it;
      }
      return area;
    }
/**
 * @brief Create a sprite previewer.
 * @param parent The parent object or nullptr.
 */
SpritePreviewer::SpritePreviewer(QWidget *parent) :
  QWidget(parent),
  model(nullptr),
  zoom(1.0) {

  ui.setupUi(this);

  // Create frame and origin items.
  item = new QGraphicsPixmapItem();
  origin_h = new QGraphicsLineItem();
  origin_v = new QGraphicsLineItem();

  origin_h->setPen(QPen(Qt::blue));
  origin_v->setPen(QPen(Qt::blue));

  // Create the scene.
  ui.frame_view->setScene(new QGraphicsScene());
  ui.frame_view->scene()->addItem(item);
  ui.frame_view->scene()->addItem(origin_h);
  ui.frame_view->scene()->addItem(origin_v);
  ui.frame_view->scene()->setBackgroundBrush(
        ui.frame_view->scene()->palette().base());

  // Zoom.
  ui.zoom_button->setMenu(create_zoom_menu());
  ui.zoom_button->setPopupMode(QToolButton::InstantPopup);
  set_zoom(2.0);
  update_zoom();

  connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));

  connect(ui.start_button, SIGNAL(clicked()), this, SLOT(start()));
  connect(ui.stop_button, SIGNAL(clicked()), this, SLOT(stop()));
  connect(ui.first_button, SIGNAL(clicked()), this, SLOT(first()));
  connect(ui.previous_button, SIGNAL(clicked()), this, SLOT(previous()));
  connect(ui.last_button, SIGNAL(clicked()), this, SLOT(last()));
  connect(ui.next_button, SIGNAL(clicked()), this, SLOT(next()));

  connect(ui.origin_check_box, SIGNAL(clicked()), this, SLOT(update_origin()));
}
Esempio n. 22
0
void
AGActivityGen::generateOutputFile(std::list<AGTrip>& trips) {
    AGActivityTripWriter atw(outputFile);
    if (trips.size() != 0) {
        std::list<AGTrip>::iterator it;
        //variables for TESTS:
        int firstTrip = trips.front().getTime() + trips.front().getDay() * 86400;
        int lastTrip = trips.front().getTime() + trips.front().getDay() * 86400;
        std::map<int, int> histogram;
        for (int i = 0; i < 100; ++i) {
            histogram[i] = 0;
        }
        //END var TESTS
        for (it = trips.begin(); it != trips.end(); ++it) {
            atw.addTrip(*it);
            //TEST
            if (it->getTime() + 86400 * it->getDay() > lastTrip) {
                lastTrip = it->getTime() + 86400 * it->getDay();
            }
            if (it->getTime() + 86400 * it->getDay() < firstTrip) {
                firstTrip = it->getTime() + 86400 * it->getDay();
            }
            //++histogram[((it->getDay()-1)*86400 + it->getTime())/3600];
            ++histogram[(it->getTime()) / 3600];
            //END TEST
        }
        //PRINT TEST
        AGTime first(firstTrip);
        AGTime last(lastTrip);
        std::cout << "first real trip: " << first.getDay() << ", " << first.getHour() << ":" << first.getMinute() << ":" << first.getSecond() << std::endl;
        std::cout << "last real trip: " << last.getDay() << ", " << last.getHour() << ":" << last.getMinute() << ":" << last.getSecond() << std::endl;
        for (int i = 0; i < 100; ++i) {
            if (histogram[i] > 0) {
                std::cout << "histogram[ hour " << i << " ] = " << histogram[i] << std::endl;
            }
        }
    } else {
        std::cout << "No real trips were generated" << std::endl;
    }
}
Esempio n. 23
0
void Cdmatest::FetchNodeResultsL( TInt /*aResultsRef*/, CBufBase& aObject,
							  const TDesC8& /*aType*/ )
	{
	TPtrC8 ptr( aObject.Ptr( 0 ) );	
	iLog->Log( _L8("FetchNodeResultsL for '%S': '%S'" ), iURI, &ptr );
	
	if ( ptr.Length() > 0 )
		{
		TPtrC8 last( LastURISeg( ptr ) );
		HBufC8 *oldUri = HBufC8::NewL( iURI->Length() );
		(*oldUri) = *iURI; 
		do 
			{
			iLog->Log ( _L8( " Node: '%S' "), &last );
			HBufC8 *nUri = HBufC8::NewLC( oldUri->Length() + 1 + last.Length() );
			nUri->Des().Copy( *oldUri ) ;
			nUri->Des().Append( '/' );
			nUri->Des().Append( last );
			
			SetURIL( nUri );
			//iResultsFunction = FetchNodeResultsL;
			
		    //TPtrC8 parentURI(RemoveLastSeg(*nUri));
		    //HBufC8 *luid = GetLuidAllocLC( parentURI );
		    CleanupStack::Pop( nUri );
			
			HBufC8 *luid = GetLuidAllocLC( *iURI );
			
			Adapter()->ChildURIListL( *nUri, KNullDesC8, *iEmptyMappingInfoArray, 4, 5 );//Dipak
			
			CleanupStack::PopAndDestroy( luid ); 			
			
			ptr.Set( RemoveLastURISeg( ptr ) );
			last.Set( LastURISeg( ptr ) );
			
			}
		while (last != KNullDesC8);	
		}
	
	}
void test_stability(bool expect_stable) {
  const unsigned kPopulationSize = 100;
  int ia[kPopulationSize];
  for (unsigned i = 0; i < kPopulationSize; ++i)
    ia[i] = i;
  PopulationIterator first(ia);
  PopulationIterator last(ia + kPopulationSize);

  const unsigned kSampleSize = 20;
  int oa[kPopulationSize];
  SampleIterator out(oa);

  std::minstd_rand g;

  const int kIterations = 1000;
  bool unstable = false;
  for (int i = 0; i < kIterations; ++i) {
    std::experimental::sample(first, last, out, kSampleSize, g);
    unstable |= !std::is_sorted(oa, oa + kSampleSize);
  }
  assert(expect_stable == !unstable);
}
Esempio n. 25
0
QString DebconfFrontend::substitute(const QString &key, const QString &rest) const
{
    Substitutions sub = m_subst[key];
    QString result, var, escape;
    QRegExp rx(QStringLiteral( "^(.*)(\\\\)?\\$\\{([^\\{\\}]+)\\}(.*)$" ));
    QString last(rest);
    int pos = 0;
    while ( (pos = rx.indexIn(rest, pos)) != -1) {
        qCDebug(DEBCONF) << "var found! at" << pos;
        result += rx.cap(1);
        escape = rx.cap(2);
        var = rx.cap(3);
        last = rx.cap(4);
        if (!escape.isEmpty()) {
            result += QString(QLatin1Literal( "${" ) % var % QLatin1Char( '}' ));
        } else {
            result += sub.value(var);
        }
        pos += rx.matchedLength();
    }
    return result + last;
}
Esempio n. 26
0
int main()
{
    int n, q;
    while (scanf("%d%d", &n, &q) == 2) {
        std::vector<int> a(n), first(n, -1), last(n);
        int total = 0;
        for (int i = 0; i < n; ++ i) {
            scanf("%d", &a[i]);
            a[i] --, last[a[i]] = i;
            if (first[a[i]] == -1) {
                total ++, first[a[i]] = i;
            }
        }
        std::vector<Query> queries;
        for (int i = 0, l, r; i < q; ++ i) {
            scanf("%d%d", &l, &r);
            queries.push_back(Query {l - 1, r - 1, i});
        }
        std::sort(queries.begin(), queries.end());
        std::vector<int> count(n), result(q);
        for (int i = 0, k = 0; i < n; ++ i) {
            while (k < q && queries[k].r == i) {
                int& ref = result[queries[k].id] = total;
                for (int j = queries[k].l; j < n; j += ~j & j + 1) {
                    ref -= count[j];
                }
                k ++;
            }
            if (last[a[i]] == i) {
                for (int j = first[a[i]] - 1; ~j; j -= ~j & j + 1) {
                    count[j] ++;
                }
            }
        }
        for (int i = 0; i < q; ++ i) {
            printf("%d\n", result[i]);
        }
    }
}
void Reptation_method::get_avg(deque <Reptile_point> & reptile, 
			       Properties_point & pt) {
  int size=reptile.size();
  int nwf=reptile[0].prop.kinetic.GetDim(0);
  if(nwf >1) error("nwf > 0 not supported yet");

  pt.setSize(nwf);
  
  Reptile_point & last(reptile[size-1]);

  //How to do averaging at either end.  Not doing this right
  //now because of correlated sampling..if we really want energies,
  //usually DMC is a better choice.
  pt=last.prop;
  //Reptile_point & first(reptile[0]);  
  //pt.kinetic(0)=.5*(first.prop.kinetic(0)+last.prop.kinetic(0));
  //pt.nonlocal(0)=.5*(first.prop.nonlocal(0)+last.prop.nonlocal(0));
  //pt.potential(0)=.5*(first.prop.potential(0) + last.prop.potential(0));
  pt.count=1;
  pt.weight=1;
  
}
 int countPalindromicSubsequences(string S) {
     int n = S.size();
     prev = vector<vector<int>>(n, vector<int>(4, -1));
     next = vector<vector<int>>(n, vector<int>(4, -1));
     dp = vector<vector<int>>(n, vector<int>(n));
     vector<int> last(4, -1);
     for (int i = 0; i < n; ++i) {
         last[S[i] - 'a'] = i;
         for (int j = 0; j < 4; ++j) {
             prev[i][j] = last[j];
         }
     }
     fill(last.begin(), last.end(), -1);
     for (int i = n - 1; i >= 0; --i) {
         last[S[i] - 'a'] = i;
         for (int j = 0; j < 4; ++j) {
             next[i][j] = last[j];
         }
     }
     
     return dfs(S, 0, n - 1);
 }
Esempio n. 29
0
bool SVSet::isConsistent() const
{
#ifdef ENABLE_CONSISTENCY_CHECKS
   DLPSV* ps;
   DLPSV* next;
   for (ps = list.first(); ps; ps = next)
   {
      if (!ps->isConsistent())
         return MSGinconsistent("SVSet");
      if (ps->mem() > &last())
         return MSGinconsistent("SVSet");
      next = list.next(ps);
      if (next && ps->mem() + ps->max() + 1 != next->mem()) {
         return MSGinconsistent("SVSet");
      }
   }
   return DataArray < SVector::Element > ::isConsistent() 
      && set.isConsistent() && list.isConsistent();
#else
   return true;
#endif
}
/*!
    \internal
    \brief Records point to list with timestamp.
    \param point Point to be recorded.
    \param time Time to be recorded.
    \return Nothing.

*/
void HbPointRecorder::record(qreal point, const QTime &time)
{
    // Empty list always accepts first point without tests.
    if ( !isEmpty() ) {
        // No point to record a point, if timestamp is less or equal with previous.
        if ( lastTime().msecsTo(time) == 0 ) {
            DEBUG() << "Ignoring point, because no difference in time stamps.";
            return;
        }

        // Don't tolerate points, which are too close to previously recorded point.
        if ( qAbs(lastPoint() - point) < mThreshold ) {
            DEBUG() << "Ignoring point, because it is withing threshold of previous point";
            return;
        }
    }

    // In case the list contains two or more points, direction can be
    // determined. Each new point added needs to be checked for direction
    // change.
    if ( length() > 1 ) {
        // Clear list, on direction change. Leave the last recorded point
        // to the list, as it can be considered as first point for new direction.
        if ( dirChanged( point ) ) {
            HbPointTime temp = last();
            clear();
            append(temp);
        }
    }

    // Finally check, if the position has changed. Don't record point, when no position
    // change.
    if ( isEmpty() || point != lastPoint() ) {
        // Add point and time to list.
        append(HbPointTime(point, time));
    } else {
        DEBUG() << "Ignoring point, because it equals previous.";
    }
}