Ejemplo n.º 1
0
// called on the master server when the league message is received
void nKrawall::ReceiveLeagueMessage(const tString& message)
{
    //  con << message;

    if (message[0] == 'K')
    {
        tString killer(message.c_str()+1);
        tString victim(message.c_str()+1+killer.Len());

        MasterFrag(killer, victim);
    }
    else if (message[0] == 'R')
    {
        tString numP(message.c_str()+1);
        int pos = 1 + numP.Len();

        int numPlayers = atoi(numP);
        tArray<tString> players(numPlayers);
        for (int i = numPlayers-1; i>=0; i--)
        {
            players(i) = tString(message.c_str()+pos);
            pos += players(i).Len();
        }

        MasterRoundEnd(&players[0], numPlayers);
    }
}
Ejemplo n.º 2
0
void runKillTest(bool abortive) {
  Server server;

  int sock = createConnectedSocket(server.port());

  std::thread killer([&server, abortive] {
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    shutdownSocketSet.shutdownAll(abortive);
    server.join();
  });

  char c;
  int r = read(sock, &c, 1);

  // "abortive" is just a hint for ShutdownSocketSet, so accept both
  // behaviors
  if (abortive) {
    if (r == -1) {
      EXPECT_EQ(ECONNRESET, errno);
    } else {
      EXPECT_EQ(r, 0);
    }
  } else {
    EXPECT_EQ(0, r);
  }

  close(sock);

  killer.join();

  // NOT closed by server when it exited
  EXPECT_EQ(1, server.closeClients(false));
}
void NotifyParentOnDeathSystem::Update( double DeltaTime )
{
    for ( auto actor : mScene.GetActorsFromMap( GetType_static() ) )
    {
        Opt<INotifyParentOnDeathComponent> notifyParentOnDeathC = actor->Get<INotifyParentOnDeathComponent>();
        if ( !notifyParentOnDeathC.IsValid() )
        {
            continue;
        }
        Opt<Actor> parent( mScene.GetActor( notifyParentOnDeathC->GetParentGUID() ) );
        Opt<Actor> killer( mScene.GetActor( notifyParentOnDeathC->GetKillerGUID() ) );

        if( !parent.IsValid() )
        {
            continue;
        }

        Opt<IHealthComponent> healthC = actor->Get<IHealthComponent>();
        if( !healthC.IsValid() || healthC->IsAlive() )
        {
            continue;
        }
        if( !killer.IsValid() )
        {
            continue;
        }
        Opt<IListenChildDeathComponent> listenChildDeathC = parent->Get<IListenChildDeathComponent>();
        if ( !listenChildDeathC.IsValid() )
        {
            continue;
        }
        listenChildDeathC->SetKillerOfChildGUID( killer->GetGUID() );
    }
}
Ejemplo n.º 4
0
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    createMyMenu();
    backAction = new QAction( tr("Exit"), this );
    backAction->setSoftKeyRole( QAction::NegativeSoftKey );
    connect(backAction, SIGNAL(triggered()), this, SLOT(killer()));
    addAction( backAction );
    open = false;
}
/**
 * Create the input set: an array of given size with random doubles
 *
 * use character-swapping algorithm from strfry.c in glibc
 * 
 * http://www.koders.com/c/fidBD83E492934F9F671DE79B11E6AC0277F9887CF5.aspx
 *
 */
void prepareInput (int size, int argc, char **argv) {
  int i;
  char c, *p;
  int sorted = 0;
  int numOutOfOrder = 0;
  int distance = 0;
  int distribution = 0;

  while ((c = getopt(argc, argv, "abdku:")) != -1) {
    switch (c) {
    case 'a':
      sorted = 1;
      break;

    case 'b':
      distribution = 1;
      break;

    case 'k':
      sorted = -2;
      break;

    case 'd':
      sorted = -1;
      break;
      
    case 'g':
      groupingSize = atoi(optarg);
      break;

    case 'u':
      p = strstr(optarg, ",");
      *p = '\0';
      numOutOfOrder = atoi(optarg);
      distance = atoi(p+1);
      *p = ',';
      break;

    default:
      break;
    }
  }
  optind = 0;  /* reset getopt for next time around. */

  /* create numElements copies of a random double */
  values = (double **) calloc (size, sizeof (double *));

  if (verbose) {
    printf ("Constructing array of %d doubless\n", size);
  }

  if (distribution == 0) {
    /* Generate uniformly between [0,1) */
    double den = RAND_MAX;
    for (i = 0; i < size; i++) {
      values[i] = calloc (1, sizeof (double));
      *values[i] = random();
      *values[i] /= den;    
    }
  } else {
    /* Generate random numbers with mean 0 and std deviation of 1. */
    /* Uses the Polar Box Muller method. Must normalize all values. */
    /* to be between 0 and 1. To do this, we compute min and max values */
    /* and adjust all values, which leads to a mean of 0.5. */
    double den = RAND_MAX;
    double min = RAND_MAX;
    double max = -RAND_MAX;
    double ratio;

    i = 0;
    while (i < size) {
      double u1, u2, w;
      do {
	u1 = random();
	u1 /= den;

	u2= random();
	u2 /= den;

	u1 = 2*u1 - 1;
	u2 = 2*u2 - 1;

	w = u1*u1 + u2*u2;
      } while (w >= 1 || w == 0);

      w = sqrt((-2*log(w))/w);

      values[i] = calloc (1, sizeof (double));
      *values[i] = u1*w;
      if (*values[i] < min) {
	min = *values[i];
      }
      if (*values[i] > max) {
	max = *values[i];
      }

      i++;

      if (i < size) {
	values[i] = calloc (1, sizeof (double));
	*values[i] = u2*w; 

	if (*values[i] < min) {
	  min = *values[i];
	}
	if (*values[i] > max) {
	  max = *values[i];
	}
	i++;
      }
    }

    /* normalize to fit within [0,1). Since we can't be exactly 1, we */
    /* tighten up the ratio by adding one to the denominator. */
    ratio = 1/(1 + max - min);
    for (i = 0; i < size; i++) {
      *values[i] = (*values[i]-min)*ratio;
    }
  }

  if (sorted) {
    double *combined;
    if (verbose) { printf ("sorting first...\n"); }

    /* convert pointer-based values into contiguous value expected for
     * the internal qsort. */
    combined = (double *) calloc (numElements, ELEMENT_SIZE);

    /* copy into the combined */
    for (i = 0; i < numElements; i++) {
      combined[i] = *values[i];
    }

    if (sorted == 1) {
      qsort (combined, numElements, ELEMENT_SIZE,
	     (int (*)(const void *,const void *)) ascending);
    } else if (sorted == -1) {
      qsort (combined, numElements, ELEMENT_SIZE,
	     (int (*)(const void *,const void *)) descending);
    } else if (sorted == -2) {
      qsort (combined, numElements, ELEMENT_SIZE,
	     (int (*)(const void *,const void *)) ascending);
      killer (combined, numElements);
    }

    /* move everything back into position now. */
    for (i = 0; i < numElements; i++) {
      *values[i] = combined[i];
    }

    free (combined); /* done */

    /* now make numOutOfOrder swaps... */
    while (numOutOfOrder-- > 0) {
      double *tmp;
      int j;
      /* Compute random value */
      i = 1 + (int) (numElements * (rand() / (RAND_MAX + 1.0)));
      i %= numElements;

      /* find distance (either up or down) from i. */
      if (distance == 0) {
	j = 1 + (int) (numElements * (rand() / (RAND_MAX + 1.0)));
	j %= numElements;
      } else {
	j = i + distance;
	if (j > numElements-1) { j = i - distance; if (j < 0) { j = 0;}} 
      }

      /* swap values. */
      if (verbose) { printf ("swap %d with %d\n", i, j); }
      tmp = values[i];
      values[i] = values[j];
      values[j] = tmp;
    }
  }

  if (verbose) {
    printf ("Done constructing array of %d entries\n", size);
  }
}
Ejemplo n.º 6
0
void Executor::timerEvent(QTimerEvent *)
{
   TimerKiller killer(this, timer_id_, interval_);
   //ищем топовое окно заданного класса
   static const QString psClass = "TfrmTable";
   static const int minFoldHue = 15;
   static const int maxFoldHue = 30;
   static const int minCallHue = 60;
   static const int maxCallHue = 70;
   static const int minCheckHue = 42;
   static const int maxCheckHue = 58;

   //смотрим топовое окно
   WId FgWnd = GetForegroundWindow();
   char clName[MAX_WND_TEXT];
   GetClassNameA(FgWnd, clName, MAX_WND_TEXT);
   QString sClass(clName);
   if (!sClass.contains(psClass))
   {
      return;
   }

   //область кнопок
   QRect checkRect;
   QRect foldRect;
   bool hasCheck = false;
   bool hasFold  = false;
   bool hasCall  = false;

   int btnHeight = 110;
   int btnWidth = 0;
   WId BtnWnd = FindWindowEx(FgWnd, NULL, L"TAniLayer", NULL); 
   if (BtnWnd)
   {
      RECT btnRect;
      //GetClientRect(BtnWnd, &btnRect);
      GetWindowRect(BtnWnd, &btnRect);
      btnHeight = btnRect.bottom - btnRect.top;
      btnWidth = btnRect.right - btnRect.left;
      btnWidth = btnWidth >> 1;
      HwndToTop(FgWnd);

      //делаем скрин области кнопок
      QPixmap pixBtn = QPixmap::grabWindow(BtnWnd, btnWidth, 0, btnWidth, btnHeight);
      QImage imgBtn  = pixBtn.toImage();
      //imgBtn.save("btn.bmp");
      
      QPoint ptFold, ptCall, ptCheck;
      //здесь нужна обработка нашего хода
      static const int rectMin = 10;
      //Начинаем поиск с кнопки Чек
      //если она есть то однозначно наш ход
      hasCheck = Proc770::checkHueButton(imgBtn, minCheckHue, maxCheckHue, 
         rectMin, checkRect);
      if (!hasCheck)
      {
         //ищем кнопку Fold и Call
         hasFold = Proc770::checkHueButton(imgBtn, minFoldHue, maxFoldHue, 
            rectMin, foldRect);
         hasCall = Proc770::checkHueButton(imgBtn, minCallHue, maxCallHue, rectMin);

         if (hasFold && hasCall)
         {
            //qDebug() << "FOLD is avail";
         }
         else
         {
            return;
         }
      }
      else
      {
         //qDebug() << "CHECK is avail";
      }
   }

   //здесь наш ход
   QPixmap pixRoom = QPixmap::grabWindow(FgWnd);
   QRect rectRoom = pixRoom.rect();
   rectRoom.setHeight(rectRoom.height() - btnHeight);
   QImage imgRoom = pixRoom.copy(rectRoom).toImage();
   
   // устанавливаем изображение для обработки
   cardProc_->setImage(imgRoom);
   // если стадия префлопа 
   if (cardProc_->isPreflop())
   {
      //qDebug() << "Preflop!";
      // получить карманные карты
      bool ok = false;
      QPair<QRect, QRect> holeCards = cardProc_->getHoleCards(&ok);
      if (!ok)
         return;

      /// Debugging {
      //uint num = 0;
      //num = QDateTime::currentDateTime().toTime_t();
      //imgRoom.save(QString("test/table_%1.bmp").arg(num));
      //imgBtn.save(QString("test/btns_%1.bmp").arg(num));
      //imgRoom.copy(holeCards.first).save(QString("test/first_%1.bmp").arg(num));
      //imgRoom.copy(holeCards.second).save(QString("test/second_%1.bmp").arg(num));
      /// } Debugging

      if (holeCards.first.isEmpty() || holeCards.second.isEmpty() ||
          holeCards.first.isNull() || holeCards.second.isNull())
          return;

      QImage firstImg  = imgRoom.copy(holeCards.first);
      QImage secondImg = imgRoom.copy(holeCards.second);

      QString card1 = cardFromImage(firstImg);
      QString card2 = cardFromImage(secondImg);

      if (card1.length() != 2 || card2.length() != 2)
         return;

      //qDebug() << card1 << card2;
      
      //сохранить карты в кэш
      QString joined = card1 + card2;
      if (joined == cache_ && !lastIsFold_)
      {
         //хорошие карты - человек думает, не мешать
         return;
      } 
      else
      {
         cache_ = joined;
      }
      
      QString range = cardRangeFromHoles(card1, card2);
      //qDebug() << range;
      if (playingCard_.contains(range))
      {
         //panic!
         lastIsFold_ = false;
         if (data_.visualAlert)
         {
            alarm_->highlight(joined, FgWnd);
         }
         if (data_.turnBeep)
         {
            QString appExe = qApp->applicationDirPath();
            QSound::play(appExe + "/sounds/turn.wav");
         }
      }
      else
      {
         if (data_.advisorMode)
         {
            QString advice = tr("Fold/Check this hand: %1")
               .arg(card1 + " " + card2);
            cbFun(advice.toStdString().c_str());
            return;
         }
         
         //foldOrCheck(FgWnd);
         //qDebug() << "Check Rect" << checkRect;
         int w = checkRect.width();
         int h = checkRect.height();
         checkRect.setX(btnWidth + checkRect.x());
         checkRect.setY(imgRoom.height() + checkRect.y());
         checkRect.setWidth(w);
         checkRect.setHeight(h);
         //qDebug() << "New Check Rect" << checkRect;

         //qDebug() << "Fold Rect" << foldRect;
         w = foldRect.width();
         h = foldRect.height();
         foldRect.setX(btnWidth + foldRect.x());
         foldRect.setY(imgRoom.height() + foldRect.y());
         foldRect.setWidth(w);
         foldRect.setHeight(h);
         //qDebug() << "New Fold Rect" << foldRect;
         if (hasCheck)
         {
            if (data_.checkBeep)
            {
               QString appExe = qApp->applicationDirPath();
               QSound::play(appExe + "/sounds/check.wav");
            }
            
            clickTo(FgWnd, checkRect);
            
            if (data_.showFolded)
            {
               QString sAction = tr("This hand has been checked: ");
               cbFun(QString(sAction + card1 + " " + card2).toStdString().c_str());
            }

            //обнулить кэш
            cache_.clear();
            lastIsFold_ = false;
         }
         else if (hasFold)
         {
            lastIsFold_ = true;
            if (data_.foldBeep)
            {
               QString appExe = qApp->applicationDirPath();
               QSound::play(appExe + "/sounds/fold.wav");
            }

            clickTo(FgWnd, foldRect);
            
            if (data_.showFolded)
            {
               QString sAction = tr("This hand has been folded: ");
               cbFun(QString(sAction + card1 + " " + card2).toStdString().c_str());
            }
         }
      }
   }
//код для набивки базы карт
/*
   qDebug() << "Check Rect" << checkRect;
   int w = checkRect.width();
   int h = checkRect.height();
   checkRect.setX(btnWidth + checkRect.x());
   checkRect.setY(imgRoom.height() + checkRect.y());
   checkRect.setWidth(w);
   checkRect.setHeight(h);
   qDebug() << "New Check Rect" << checkRect;

   qDebug() << "Fold Rect" << foldRect;
   w = foldRect.width();
   h = foldRect.height();
   foldRect.setX(btnWidth + foldRect.x());
   foldRect.setY(imgRoom.height() + foldRect.y());
   foldRect.setWidth(w);
   foldRect.setHeight(h);
   qDebug() << "New Fold Rect" << foldRect;

   if (cardProc_->isPreflop())
   {
      if (hasCheck)
      {
         clickTo(FgWnd, checkRect);
      }
      else if (hasFold && hasCall)
      {
         clickTo(FgWnd, foldRect);
      }
   }
   else
   {
      clickTo(FgWnd, foldRect);
      clickTo(FgWnd, checkRect);

      qDebug() << "Flop at least!";
      return;
   }
*/
}
Ejemplo n.º 7
0
		void EpidemicRoutingExtension::run() throw ()
		{
			class BundleFilter : public dtn::storage::BundleSelector
			{
			public:
				BundleFilter(const NeighborDatabase::NeighborEntry &entry, const std::set<dtn::core::Node> &neighbors, const dtn::core::FilterContext &context, const dtn::net::ConnectionManager::protocol_list &plist)
				 : _entry(entry), _neighbors(neighbors), _plist(plist), _context(context)
				{};

				virtual ~BundleFilter() {};

				virtual dtn::data::Size limit() const throw () { return _entry.getFreeTransferSlots(); };

				virtual bool addIfSelected(dtn::storage::BundleResult &result, const dtn::data::MetaBundle &meta) const throw (dtn::storage::BundleSelectorException)
				{
					// check Scope Control Block - do not forward bundles with hop limit == 0
					if (meta.hopcount == 0)
					{
						return false;
					}

					// do not forward local bundles
					if ((meta.destination.getNode() == dtn::core::BundleCore::local)
							&& meta.get(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON)
						)
					{
						return false;
					}

					// check Scope Control Block - do not forward non-group bundles with hop limit <= 1
					if ((meta.hopcount <= 1) && (meta.get(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON)))
					{
						return false;
					}

					// do not forward bundles addressed to this neighbor,
					// because this is handled by neighbor routing extension
					if (_entry.eid == meta.destination.getNode())
					{
						return false;
					}

					// request limits from neighbor database
					try {
						const RoutingLimitations &limits = _entry.getDataset<RoutingLimitations>();

						if (meta.get(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON))
						{
							// check if the peer accepts bundles for other nodes
							if (limits.getLimit(RoutingLimitations::LIMIT_LOCAL_ONLY) > 0) return false;
						}
						else
						{
							// check if destination permits non-singleton bundles
							if (limits.getLimit(RoutingLimitations::LIMIT_SINGLETON_ONLY) > 0) return false;
						}

						// check if the payload is too large for the neighbor
						if ((limits.getLimit(RoutingLimitations::LIMIT_FOREIGN_BLOCKSIZE) > 0) &&
							((size_t)limits.getLimit(RoutingLimitations::LIMIT_FOREIGN_BLOCKSIZE) < meta.getPayloadLength())) return false;
					} catch (const NeighborDatabase::DatasetNotAvailableException&) { }

					// if this is a singleton bundle ...
					if (meta.get(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON))
					{
						const dtn::core::Node n(meta.destination.getNode());

						// do not forward the bundle if the final destination is available
						if (_neighbors.find(n) != _neighbors.end())
						{
							return false;
						}
					}

					// do not forward bundles already known by the destination
					// throws BloomfilterNotAvailableException if no filter is available or it is expired
					try {
						if (_entry.has(meta, true))
						{
							return false;
						}
					} catch (const dtn::routing::NeighborDatabase::BloomfilterNotAvailableException&) {
						throw dtn::storage::BundleSelectorException();
					}

					// update filter context
					dtn::core::FilterContext context = _context;
					context.setMetaBundle(meta);

					// check bundle filter for each possible path
					for (dtn::net::ConnectionManager::protocol_list::const_iterator it = _plist.begin(); it != _plist.end(); ++it)
					{
						const dtn::core::Node::Protocol &p = (*it);

						// update context with current protocol
						context.setProtocol(p);

						// execute filtering
						dtn::core::BundleFilter::ACTION ret = dtn::core::BundleCore::getInstance().evaluate(dtn::core::BundleFilter::ROUTING, context);

						if (ret == dtn::core::BundleFilter::ACCEPT)
						{
							// put the selected bundle with targeted interface into the result-set
							static_cast<RoutingResult&>(result).put(meta, p);
							return true;
						}
					}

					return false;
				};

			private:
				const NeighborDatabase::NeighborEntry &_entry;
				const std::set<dtn::core::Node> &_neighbors;
				const dtn::net::ConnectionManager::protocol_list &_plist;
				const dtn::core::FilterContext &_context;
			};

			// list for bundles
			RoutingResult list;

			// set of known neighbors
			std::set<dtn::core::Node> neighbors;

			while (true)
			{
				try {
					Task *t = _taskqueue.poll();
					std::auto_ptr<Task> killer(t);

					IBRCOMMON_LOGGER_DEBUG_TAG(EpidemicRoutingExtension::TAG, 50) << "processing task " << t->toString() << IBRCOMMON_LOGGER_ENDL;

					try {
						/**
						 * SearchNextBundleTask triggers a search for a bundle to transfer
						 * to another host. This Task is generated by TransferCompleted, TransferAborted
						 * and node events.
						 */
						try {
							SearchNextBundleTask &task = dynamic_cast<SearchNextBundleTask&>(*t);

							// clear the result list
							list.clear();

							// lock the neighbor database while searching for bundles
							try {
								NeighborDatabase &db = (**this).getNeighborDB();
								ibrcommon::MutexLock l(db);
								NeighborDatabase::NeighborEntry &entry = db.get(task.eid, true);

								// check if enough transfer slots available (threshold reached)
								if (!entry.isTransferThresholdReached())
									throw NeighborDatabase::NoMoreTransfersAvailable(task.eid);

								if (dtn::daemon::Configuration::getInstance().getNetwork().doPreferDirect()) {
									// get current neighbor list
									neighbors = dtn::core::BundleCore::getInstance().getConnectionManager().getNeighbors();
								} else {
									// "prefer direct" option disabled - clear the list of neighbors
									neighbors.clear();
								}

								// get a list of protocols supported by both, the local BPA and the remote peer
								const dtn::net::ConnectionManager::protocol_list plist =
										dtn::core::BundleCore::getInstance().getConnectionManager().getSupportedProtocols(entry.eid);

								// create a filter context
								dtn::core::FilterContext context;
								context.setPeer(entry.eid);
								context.setRouting(*this);

								// get the bundle filter of the neighbor
								const BundleFilter filter(entry, neighbors, context, plist);

								// some debug output
								IBRCOMMON_LOGGER_DEBUG_TAG(EpidemicRoutingExtension::TAG, 40) << "search some bundles not known by " << task.eid.getString() << IBRCOMMON_LOGGER_ENDL;

								// query some unknown bundle from the storage
								(**this).getSeeker().get(filter, list);
							} catch (const dtn::storage::BundleSelectorException&) {
								// query a new summary vector from this neighbor
								(**this).doHandshake(task.eid);
							}

							// send the bundles as long as we have resources
							for (RoutingResult::const_iterator iter = list.begin(); iter != list.end(); ++iter)
							{
								try {
									// transfer the bundle to the neighbor
									transferTo(task.eid, (*iter).first, (*iter).second);
								} catch (const NeighborDatabase::AlreadyInTransitException&) { };
							}
						} catch (const NeighborDatabase::NoMoreTransfersAvailable &ex) {
							// remember that this peer has pending transfers
							ibrcommon::MutexLock pending_lock(_pending_mutex);
							_pending_peers.insert(ex.peer);

							IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "task " << t->toString() << " aborted: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
						} catch (const NeighborDatabase::EntryNotFoundException &ex) {
							IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "task " << t->toString() << " aborted: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
						} catch (const NodeNotAvailableException &ex) {
							IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "task " << t->toString() << " aborted: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
						} catch (const dtn::storage::NoBundleFoundException &ex) {
							IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "task " << t->toString() << " aborted: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
						} catch (const std::bad_cast&) { };
					} catch (const ibrcommon::Exception &ex) {
						IBRCOMMON_LOGGER_DEBUG_TAG(EpidemicRoutingExtension::TAG, 20) << "task failed: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
					}
				} catch (const std::exception &ex) {
					IBRCOMMON_LOGGER_DEBUG_TAG(EpidemicRoutingExtension::TAG, 15) << "terminated due to " << ex.what() << IBRCOMMON_LOGGER_ENDL;
					return;
				}

				yield();
			}
		}