Exemple #1
0
void NexusWriter::write(Xtray *xt)
{
	while (true) { // for an easy rerun
		if (readers_.isNull() || readers_->v().empty()) {
			// check if there is the new readers vector
			pw::lockmutex lm(mutexNew_);
			if (readers_ == readersNew_)
				break; // still nowhere to write to
			
			readers_ = readersNew_;
			continue;
		}

		ReaderVec::Vec::const_iterator end = readers_->v().end();
		ReaderVec::Vec::const_iterator it = readers_->v().begin();
		Xtray::QueId xid;
		if (!(*it)->writeFirst(readers_->gen(), xt, xid)) {
			// pick up the new readers and restart
			pw::lockmutex lm(mutexNew_);
			readers_ = readersNew_;
			continue;
		}
		for (++it; it != end; ++it) {
			(*it)->write(xt, xid);
		}

		break; // loop normally exits!
	}
}
void GSTrailMakingTest::Finished()
{
    if (m_isFinished)
    {
        return;
    }

    m_isFinished = true;

    if (TheGSCogTestMenu::Instance()->IsPrac())
    {
        std::string str;
        if (m_correct == 0)
        {
            // TODO offer another practice go
            str = "Oh dear, you didn't get any correct! Well, I am sure you will do better this time!";

            LurkMsg lm(str, LURK_FG, LURK_BG, AMJU_CENTRE, OnReset);
            TheLurker::Instance()->Queue(lm);
        }
        else
        {
            TheSoundManager::Instance()->PlayWav("sound/applause3.wav");

            str = "OK, you got " + ToString(m_correct) +
                  " correct! Let's try it for real!";

            LurkMsg lm(str, LURK_FG, LURK_BG, AMJU_CENTRE, OnReset);
            TheLurker::Instance()->Queue(lm);
        }

        TheGSCogTestMenu::Instance()->SetIsPrac(false);
    }
    else
    {
        std::string str;
        if (m_correct == 0)
        {
            str = "Oh dear, you didn't get any correct! Well, I am sure you will do better next time!";
        }
        else
        {
            str = "Well done! You got " + ToString(m_correct) + " correct!";
            TheSoundManager::Instance()->PlayWav("sound/applause3.wav");
        }
        LurkMsg lm(str, LURK_FG, LURK_BG, AMJU_CENTRE);
        TheLurker::Instance()->Queue(lm);

        TheCogTestResults::Instance()->StoreResult(new Result(m_testId, "correct", ToString(m_correct)));
        TheCogTestResults::Instance()->StoreResult(new Result(m_testId, "incorrect", ToString(m_incorrect)));
        TheCogTestResults::Instance()->StoreResult(new Result(m_testId, "time", ToString(m_timer)));

        UpdateScore();

        TheGSCogTestMenu::Instance()->AdvanceToNextTest();

        TheGame::Instance()->SetCurrentState(TheGSCogTestMenu::Instance());
    }
}
Exemple #3
0
void Player::OnSpaceshipCollision(Spaceship* spaceship)
{
  // TODO Only process on first collision frame, ignore subsequently
  if (!IsLocalPlayer())
  {
    return;
  }

  FirstTimeMsgThisSession("This is your spaceship!", UNIQUE_MSG_ID, false); 

  if (m_isDead)
  {
    std::string str = "Your health is restored!";
    LurkMsg lm(GameLookup(str), LURK_FG, LURK_BG, AMJU_CENTRE);
    TheLurker::Instance()->Queue(lm);
    ChangeHeartCount(100);
    m_isDead = false;
  }

  int fc = GetLocalPlayerFuelCount();
  if (fc == 0)
  {
    FirstTimeMsgThisSession("Your spaceship needs fuel. Please find fuel cells and bring them back here!", UNIQUE_MSG_ID, false);
    return;
  }

std::cout << "Fuel cells: " << fc << "\n"; 

  // TODO Different bands
// TODO Needs better msg
  std::string str = "Thanks for bringing fuel to your spaceship, <p>!";
  LurkMsg lm(GameLookup(str), LURK_FG, LURK_BG, AMJU_CENTRE);
  TheLurker::Instance()->Queue(lm);

  spaceship->AddFuel(fc);

  // Add fc to server-based count of total fuel cells you have ever brought
  // Count goes up for this player: total num fuel cells ever brought to ship
  ChangePlayerCount(FUELCELL_KEY, fc);

  // Send system message that you brought fuel
  static const int BROADCAST = -2;
  if (fc == 1)
  {
    str = "<BROUGHT A FUEL CELL TO THE SHIP>";
  }
  else
  {
    str = "<BROUGHT " + ToString(fc) + " FUEL CELLS TO THE SHIP>";
  }
  TheMsgManager::Instance()->SendMsg(GetLocalPlayerId(), BROADCAST, str);

  static GSMain* gsm = TheGSMain::Instance();
  gsm->SetFuelCells(0);    

  ResetLocalPlayerFuelCount();
}
/** 3D rigid transformation refinement using LM
 * Refine the Scale, Rotation and translation rigid transformation
 * using a Levenberg-Marquardt opimization.
 *
 * \param[in] x1 The first 3xN matrix of euclidean points
 * \param[in] x2 The second 3xN matrix of euclidean points
 * \param[out] S The initial scale factor
 * \param[out] t The initial 3x1 translation
 * \param[out] R The initial 3x3 rotation
 *
 * \return none
 */
static void Refine_RTS( const Mat &x1,
                        const Mat &x2,
                        double * S,
                        Vec3 * t,
                        Mat3 * R )
{
  {
    lm_SRTRefine_functor functor( 7, 3 * x1.cols(), x1, x2, *S, *R, *t );

    Eigen::NumericalDiff<lm_SRTRefine_functor> numDiff( functor );

    Eigen::LevenbergMarquardt<Eigen::NumericalDiff<lm_SRTRefine_functor> > lm( numDiff );
    lm.parameters.maxfev = 1000;
    Vec xlm = Vec::Zero( 7 ); // The deviation vector {tx,ty,tz,rotX,rotY,rotZ,S}

    lm.minimize( xlm );

    Vec3 transAdd = xlm.block<3, 1>( 0, 0 );
    Vec3 rot = xlm.block<3, 1>( 3, 0 );
    double SAdd = xlm( 6 );

    //Build the rotation matrix
    Mat3 Rcor =
      ( Eigen::AngleAxis<double>( rot( 0 ), Vec3::UnitX() )
        * Eigen::AngleAxis<double>( rot( 1 ), Vec3::UnitY() )
        * Eigen::AngleAxis<double>( rot( 2 ), Vec3::UnitZ() ) ).toRotationMatrix();

    *R = ( *R ) * Rcor;
    *t = ( *t ) + transAdd;
    *S = ( *S ) + SAdd;
  }

  // Refine rotation
  {
    lm_RRefine_functor functor( 3, 3 * x1.cols(), x1, x2, *S, *R, *t );

    Eigen::NumericalDiff<lm_RRefine_functor> numDiff( functor );

    Eigen::LevenbergMarquardt<Eigen::NumericalDiff<lm_RRefine_functor> > lm( numDiff );
    lm.parameters.maxfev = 1000;
    Vec xlm = Vec::Zero( 3 ); // The deviation vector {rotX,rotY,rotZ}

    lm.minimize( xlm );

    Vec3 rot = xlm.block<3, 1>( 0, 0 );

    //Build the rotation matrix
    Mat3 Rcor =
      ( Eigen::AngleAxis<double>( rot( 0 ), Vec3::UnitX() )
        * Eigen::AngleAxis<double>( rot( 1 ), Vec3::UnitY() )
        * Eigen::AngleAxis<double>( rot( 2 ), Vec3::UnitZ() ) ).toRotationMatrix();

    *R = ( *R ) * Rcor;
  }
}
Exemple #5
0
void App::markTrieadDead(TrieadOwner *to)
{
	pw::lockmutex lm(mutex_);

	Triead *t = to->get();

	TrieadUpdMap::const_iterator it = threads_.find(t->getName());
	if (it == threads_.end())
		return; // silently ignore because might be already disposed of
	TrieadUpd *upd = it->second;
	if (upd->t_.get() != t)
		return; // silently ignore because might be already disposed of

	markTrieadConstructedL(upd, t);
	try {
		// XXX if aborting on exception, the catch won't help
		markTrieadReadyL(upd, t);
	} catch (Exception e) {
		// Just ignore, marking the App aborted is good enough.
		// After all, the current thread is about to exit anyway
		// and might even be calling this from its destructor,
		// so there is no need to make its life more difficult.
	}
	markTrieadDeadL(upd, t);
}
Exemple #6
0
Onceref<TrieadOwner> App::makeTriead(const string &tname, const string &fragname)
{
	if (tname.empty())
		throw Exception::fTrace("Empty thread name is not allowed, in application '%s'.", name_.c_str());

	pw::lockmutex lm(mutex_);

	TrieadUpdMap::iterator it = threads_.find(tname);
	TrieadUpd *upd;
	if (it == threads_.end()) {
		upd = new TrieadUpd(mutex_);
		threads_[tname] = upd;
		if (++unreadyCnt_ == 1 && !isAbortedL())
			ready_.reset();
		if (++aliveCnt_ == 1)
			dead_.reset();
	} else {
		upd = it->second;
		if(!upd->t_.isNull())
			throw Exception::fTrace("Duplicate thread name '%s' is not allowed, in application '%s'.", 
				tname.c_str(), name_.c_str());
	}

	Triead *th = new Triead(tname, fragname, drain_);
	TrieadOwner *ow = new TrieadOwner(this, th);
	upd->t_ = th;

	refreshDeadlineL(timeout_);

	return ow; // the only owner API for the thread!
}
Exemple #7
0
void RoomService::onRoomCreate(int const to, Message *msg)
{
  Account *acc = Core::acc_manager->getAccount(to);

  if (acc)
    {
      Room *room;
      std::string name;
      std::string password;

      name = msg->getAttr<std::string>(std::string("name"));
      password = msg->getAttr<std::string>(std::string("password"));
      room = Core::room_manager->createRoom(name, password);
	  room->addPlayer(new Player(0, to, acc, Player::MASTER));
	  acc->setRoom(room);

      Message *rmsg = new Message(Message::ROOM_STATE);
      InternalMessage *imsg = new InternalMessage(new TCPPacket(rmsg, 0), to);
      imsg->addReceiver(to);
      rmsg->setAttr("id", Ultra::Value((unsigned short)room->getID()));
      rmsg->setAttr("state", Ultra::Value((char)Room::OK));

      std::stringstream ss;
      
      ss << room->getID();

      Logging::Message lm("Room create [id = " + ss.str() + ']', "RoomService", Logging::Message::DEBUG);
      this->_log << lm;

      Core::srv_manager->notifyService(ServiceManager::DISPATCH, imsg);
  }
}
Exemple #8
0
void RoomService::onRoomPlayerInfo(int const to, Message *msg)
{
	Account *acc = Core::acc_manager->getAccount(to);
	
	if (acc)
	{
		Room *room = acc->getRoom();
		if (room)
		{
			char state = msg->getAttr<char>("state");
			char specState = msg->getAttr<char>("stateSpec");
			if (state == Player::LEFT && (room->getCurrentPlayer() == 1 || specState == Player::MASTER))
			{
				std::stringstream ss;
				ss << room->getID();
				room->kickAll();
				Core::room_manager->deleteRoom(room->getID());
				Logging::Message lm("Room deleted [id = " + ss.str() + ']', "RoomService", Logging::Message::DEBUG);
				this->_log << lm;
			}
			else
				room->notify(new InternalMessage(new TCPPacket(msg), to));
		}
	}
}
Exemple #9
0
void App::setDeadline(const timespec &dl)
{
	pw::lockmutex lm(mutex_);
	if (!threads_.empty()) // XXX this might be not the best idea with frags
		throw Exception::fTrace("Triceps application '%s' deadline can not be changed after the thread creation.", name_.c_str());
	deadline_ = dl;
}
Exemple #10
0
void
opengv::absolute_pose::modules::gpnp_optimize(
  const Eigen::Matrix<double,12,1> & a,
  const Eigen::Matrix<double,12,12> & V,
  const points_t & c,
  std::vector<double> & factors )
{
  const int n=factors.size();
  VectorXd x(n);

  for(size_t i = 0; i < factors.size(); i++)
    x[i] = factors[i];

  GpnpOptimizationFunctor functor( a, V, c, factors.size() );
  NumericalDiff<GpnpOptimizationFunctor> numDiff(functor);
  LevenbergMarquardt< NumericalDiff<GpnpOptimizationFunctor> > lm(numDiff);

  lm.resetParameters();
  lm.parameters.ftol = 1.E10*NumTraits<double>::epsilon();
  lm.parameters.xtol = 1.E10*NumTraits<double>::epsilon();
  lm.parameters.maxfev = 1000;
  lm.minimize(x);

  for(size_t i = 0; i < factors.size(); i++)
    factors[i] = x[i];
}
Exemple #11
0
int main(int argc, char** argv)
{
    LM lm("/afs/cs.stanford.edu/u/awni/wsj/ctc-utils/lm_bg.arpa");
    std::cout << lm.word_to_int["ACCEPT"] << std::endl;
    std::cout << lm.score_bg("HELLO AGAIN") << std::endl;
    std::cout << lm.score_bg("HELLO ABDO") << std::endl;
}
Exemple #12
0
//
// Main code.
//
int main(int /* argc */, char* /* argv */[])
{
    int rc( 0 );

    try {
        Engine* engine( Engine::createInstance() );

        LayerManager* lm( engine->getLayerManager() );
        sgtpepper = new Object( "sgtpepper" );
        lm->at(0)->add(sgtpepper);

        engine->setKeyboardDownHandler(new KeyDown());
        engine->setKeyboardUpHandler(new KeyUp());
        engine->setMouseMotionHandler(new MouseMoved());
        engine->setMouseButtonHandler(new MouseButtonClicked());
        engine->run();
    }
    catch (Exception& e) {
        std::cerr << " [**] Caught exception: \"" << e.what() << "\"." << std::endl;
        rc = -1;
    }

    Engine::deleteInstance();
    return rc;
}
Exemple #13
0
	bool splitlock::wait_for_worker(const struct timespec &abstime, 
		bool timed)
	{
		int res;

		pw::lockmutex lm(cond_enter_);
		while(true) {
			if (cond_enter_.sleepers_ > 0)
				// worker is already trying to enter
				return true; 

			switch(wi_) {
			case WORKER_WILL_ENTER:
				if (timed) {
					res = cond_worker_.timedwait(abstime);
					if (res == ETIMEDOUT)
						return false;
				} else {
					cond_worker_.wait();
				}
				break;
			case WORKER_WONT_ENTER:
				return false;
			case WORKER_MIGHT_ENTER:
				res = cond_worker_.timedwait(abstime);
				if (res == ETIMEDOUT 
				&& wi_ == WORKER_MIGHT_ENTER)
					return false;
				// else something definite became known,
				// parse this knowledge on the next
				// iteration
				break;
			};
		}
	}
void PCRecorder::print() {
  if (counters == NULL) return;

  tty->cr();
  tty->print_cr("Printing compiled methods with PC buckets having more than %d ticks", ProfilerPCTickThreshold);
  tty->print_cr("===================================================================");
  tty->cr();

  GrowableArray<CodeBlob*>* candidates = new GrowableArray<CodeBlob*>(20);


  int s;
  {
    MutexLockerEx lm(CodeCache_lock, Mutex::_no_safepoint_check_flag);
    s = size();
  }

  for (int index = 0; index < s; index++) {
    int count = counters[index];
    if (count > ProfilerPCTickThreshold) {
      address pc = pc_for(index);
      CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
      if (cb != NULL && candidates->find(cb) < 0) {
        candidates->push(cb);
      }
    }
  }
  for (int i = 0; i < candidates->length(); i++) {
    print_blobs(candidates->at(i));
  }
}
Exemple #15
0
transformation_t optimize_nonlinear(
    const AbsoluteAdapterBase & adapter,
    const Indices & indices )
{
  const int n=6;
  VectorXd x(n);

  x.block<3,1>(0,0) = adapter.gett();
  x.block<3,1>(3,0) = math::rot2cayley(adapter.getR());

  OptimizeNonlinearFunctor1 functor( adapter, indices );
  NumericalDiff<OptimizeNonlinearFunctor1> numDiff(functor);
  LevenbergMarquardt< NumericalDiff<OptimizeNonlinearFunctor1> > lm(numDiff);

  lm.resetParameters();
  lm.parameters.ftol = 1.E1*NumTraits<double>::epsilon();
  lm.parameters.xtol = 1.E1*NumTraits<double>::epsilon();
  lm.parameters.maxfev = 1000;
  lm.minimize(x);

  transformation_t transformation;
  transformation.col(3) = x.block<3,1>(0,0);
  transformation.block<3,3>(0,0) = math::cayley2rot(x.block<3,1>(3,0));
  return transformation;
}
/* WARNING: nothing in this test removes old segments, so running for
   too long will overflow the last emtpy segment and cause an
   assertion failure. This is not a bug, but rather an omission in the
   test driver.
 */
void doit(size_t nmax, size_t segment_size, bool verbose) {
#define P(msg, ...) do { if (verbose) fprintf(stderr, msg "\n", ##__VA_ARGS__); } while (0)

    log_segment_mgr lm(segment_size-SKIP_LOG_SIZE, SKIP_LOG_SIZE);
    uint64_t n = 0;
    uint64_t now = stopwatch_t::now();
    uint32_t seed[] = {uint32_t(now), uint32_t(now>>32)};
Exemple #17
0
void App::setTimeout(int sec, int fragsec)
{
	pw::lockmutex lm(mutex_);
	if (!threads_.empty()) // XXX this might be not the best idea with frags
		throw Exception::fTrace("Triceps application '%s' deadline can not be changed after the thread creation.", name_.c_str());
	computeDeadlineL(sec);
	timeout_ = fragsec < 0? sec : fragsec;
}
Exemple #18
0
// DEBUG to
	// ...
	int semaphore::signal(unsigned n)
	{
		pw::lockmutex lm(leadcond_);
		value_ += n;
		if (leadn_ && value_ >= leadn_)
			leadcond_.signal();
		return value_;
	}
Exemple #19
0
void ModuleList::addLayoutModule(string const & modname,
	string const & filename, string const & description,
	vector<string> const & pkgs, vector<string> const & req,
	vector<string> const & exc, string const & catgy, bool const local)
{
	LyXModule lm(modname, filename, description, pkgs, req, exc, catgy, local);
	modlist_.push_back(lm);
}
Exemple #20
0
	int semaphore::trywait(unsigned n)
	{
		pw::lockmutex lm(leadcond_);
		if(leadn_ || value_ < n)
			return ETIMEDOUT;
		value_ -= n;
		return 0;
	}
Exemple #21
0
bool App::harvestOnce()
{
	while(true) {
		Autoref<TrieadUpd> upd;
		Autoref<TrieadJoin> j;
		{
			pw::lockmutex lm(mutex_);
			if (zombies_.empty()) {
				bool dead = isDead();
				if (!dead)
					needHarvest_.reset();
				return dead;
			}
			upd = zombies_.front();
			j = upd->j_;

			if (j.isNull() || upd->joining_) // j should never be NULL but just in case
				continue; // a duplicate, ignore it

			upd->joining_ = true;
			zombies_.pop_front();
		}

		// this part must happen outside mutex
		Erref err;
		try {
			j->join();
		} catch (Exception e) {
			err = e.getErrors();
		}

		{
			pw::lockmutex lm(mutex_);
			upd->joined_ = true;
			upd->j_ = NULL; // drop the reference
			if (upd->dispose_)
				disposeL(upd->t_->getName());
		}
		
		if (err->hasError())
			// j still keeps a reference, so it's OK to refer by it
			throw Exception::f(err, "Failed to join the thread '%s' of application '%s':",
						j->getName().c_str(), name_.c_str());
	}
}
Exemple #22
0
 bool
 is_connection_permitted(unsigned long ipAddress)
 {
     std::unique_lock<std::mutex> lm(connectionsCountLock);
     return connection_conditions.wait_for(lm, std::chrono::seconds(maximumTimeout), [this, ipAddress]() {
         std::map<unsigned long, unsigned long>::const_iterator it = this->ipConnections.find(ipAddress);
         return it == this->ipConnections.end() || it->second < this->connectionsPerIp;
     });
 }
void PCRecorder::init() {
  MutexLockerEx lm(CodeCache_lock, Mutex::_no_safepoint_check_flag);
  int s = size();
  counters = NEW_C_HEAP_ARRAY(int, s, mtInternal);
  for (int index = 0; index < s; index++) {
    counters[index] = 0;
  }
  base = CodeCache::first_address();
}
Exemple #24
0
// called from reftarget invalidation
bool weakref::invalidate1() 
{
	pw::lockmutex lm(mutex_);
	reftarget *t = target_;
	target_ = 0;
	if (t)
		hold_.acquire();
	return (t != 0);
}
Exemple #25
0
        void 
        retain_connection(http_connection_context *ctx)
        {
            std::unique_lock<std::mutex> lm(connectionsCountLock);

            activeConnections.insert(ctx);

            ipConnections[ctx->ipAddress]++;
        }
Exemple #26
0
void App::markTrieadConstructed(TrieadOwner *to)
{
	pw::lockmutex lm(mutex_);

	Triead *t = to->get();
	TrieadUpd *upd = assertTrieadL(t);

	markTrieadConstructedL(upd, t);
}
Exemple #27
0
        void
        release_connection(http_connection_context *ctx)
        {
            std::unique_lock<std::mutex> lm(connectionsCountLock);

            activeConnections.erase(ctx);

            ipConnections[ctx->ipAddress]--;
        }
Exemple #28
0
double 
find_AML_star(std::string &a, 
	 std::string &b, 
	 std::string &c,
	 std::string &center,
         sequence_model model){
  std::vector<std::string *> vec(4);
  
  vec[0] = &a;
  vec[1] = &b;
  vec[2] = &c;
  //add parsimony solution
  center.reserve(a.size());
  center.clear();
  for ( size_t i = 0 ; i < a.size() ; i++ )
    center.push_back(parsimony_star(a[i],b[i],c[i]));
  vec[3] = &center;

  SequenceTree::NodeMatrix lm(4);
  fillLikelihoodMatrix(vec,lm,model);
  
  //likelihood with x in center
  double a_l = lm.getDistance(0,1) + lm.getDistance(0,2);
  double b_l = lm.getDistance(0,1) + lm.getDistance(1,2);
  double c_l = lm.getDistance(0,2) + lm.getDistance(1,2);
  double parsimony_l = lm.getDistance(0,3) + lm.getDistance(1,3) + lm.getDistance(2,3);  
  //  PRINT(a_l); PRINT(b_l); PRINT(c_l); PRINT(parsimony_l);

  double max_l = parsimony_l;
  std::string *maxstr = &center;
  if ( a_l > max_l ){
    //    PRINT(a_l);
    maxstr = &a;
    max_l = a_l;
  }

  if ( b_l > max_l ){
    //PRINT(b_l);
    maxstr = &b;
    max_l = b_l;
  }

  if ( c_l > max_l ){
    //PRINT(c_l);
    maxstr = &c;
    max_l = c_l;
  }

  
  //if parsimony not min copy the correct one
  if ( maxstr != &center ){
    center.clear();
    center.append(*maxstr);
  }

  return max_l;
}
Exemple #29
0
// make the reference strong, return its current value
void *weakref::grab() 
{
	grabs_.acquire();
	void *owner;
	{
		pw::lockmutex lm(mutex_);
		owner = target_? target_->owner_ : 0;
	}
	return owner;
}
Exemple #30
0
Onceref<App> App::find(const string &name)
{
	pw::lockmutex lm(apps_mutex_);

	Map::iterator it = apps_.find(name);
	if (it == apps_.end())
		throw Exception::fTrace("Triceps application '%s' is not found.", name.c_str());

	return it->second;
}