Example #1
0
void
LocationIndexRobinBcCoefs::setBcCoefs(
   const std::shared_ptr<pdat::ArrayData<double> >& acoef_data,
   const std::shared_ptr<pdat::ArrayData<double> >& bcoef_data,
   const std::shared_ptr<pdat::ArrayData<double> >& gcoef_data,
   const std::shared_ptr<hier::Variable>& variable,
   const hier::Patch& patch,
   const hier::BoundaryBox& bdry_box,
   double fill_time) const
{
   TBOX_ASSERT_DIM_OBJDIM_EQUALITY2(d_dim, patch, bdry_box);

   NULL_USE(variable);
   NULL_USE(patch);
   NULL_USE(fill_time);

   int location = bdry_box.getLocationIndex();
   TBOX_ASSERT(location >= 0 && location < 2 * d_dim.getValue());
   if (acoef_data) {
      TBOX_ASSERT_DIM_OBJDIM_EQUALITY1(d_dim, *acoef_data);

      acoef_data->fill(d_a_map[location]);
   }
   if (bcoef_data) {
      TBOX_ASSERT_DIM_OBJDIM_EQUALITY1(d_dim, *bcoef_data);

      bcoef_data->fill(d_b_map[location]);
   }
   if (gcoef_data) {
      TBOX_ASSERT_DIM_OBJDIM_EQUALITY1(d_dim, *gcoef_data);

      gcoef_data->fill(d_g_map[location]);
   }
}
Example #2
0
QPoolRectObject::QPoolRectObject
(
	QPoolEngine* engine,
	std::shared_ptr<engine::Object> poolObject
)
:
QPoolObject(engine,poolObject)
{
	// Compute geometric properties
    std::shared_ptr<engine::RectangleShape> rectShape
    (
        std::static_pointer_cast<engine::RectangleShape>(poolObject->shape())
    );
	
	double centerX = poolObject->shape()->center()[0];
	double centerY = poolObject->shape()->center()[1];
    double w = rectShape->width();
	double h = rectShape->height();

	this->setRect
	(
		centerX-0.5*w,
		centerY-0.5*h,
		rectShape->width(),
		rectShape->height()
    );
}
	void FogDemo::CreateVertexBuffer(ID3D11Device* device, const std::shared_ptr<Mesh>& mesh, ID3D11Buffer** vertexBuffer) const
	{
		const std::vector<XMFLOAT3>& sourceVertices = mesh->Vertices();

		std::shared_ptr<std::vector<XMFLOAT3>> textureCoordinates = mesh->TextureCoordinates().at(0);
		assert(textureCoordinates->size() == sourceVertices.size());

		const std::vector<XMFLOAT3>& normals = mesh->Normals();
		assert(normals.size() == sourceVertices.size());

		std::vector<VertexPositionTextureNormal> vertices;
		vertices.reserve(sourceVertices.size());
		for (UINT i = 0; i < sourceVertices.size(); i++)
		{
			XMFLOAT3 position = sourceVertices.at(i);
			XMFLOAT3 uv = textureCoordinates->at(i);
			XMFLOAT3 normal = normals.at(i);
			vertices.push_back(VertexPositionTextureNormal(XMFLOAT4(position.x, position.y, position.z, 1.0f), XMFLOAT2(uv.x, uv.y), normal));
		}

		D3D11_BUFFER_DESC vertexBufferDesc;
		ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc));
		vertexBufferDesc.ByteWidth = (UINT)(sizeof(VertexPositionTextureNormal) * vertices.size());
		vertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE;
		vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;

		D3D11_SUBRESOURCE_DATA vertexSubResourceData;
		ZeroMemory(&vertexSubResourceData, sizeof(vertexSubResourceData));
		vertexSubResourceData.pSysMem = &vertices[0];
		ThrowIfFailed(device->CreateBuffer(&vertexBufferDesc, &vertexSubResourceData, vertexBuffer), "ID3D11Device::CreateBuffer() failed.");
	}
void ReceivedInputState::OnTouchEvent(std::shared_ptr<AppTouch_Event> event)
{
    if (mCurrentElapsedMs <= mControllerRef.waitForLongPressMs())
    {
        if (event->args().type == PointerInputEventType::Up)
        {
            mFSM.ChangeTo(MovingPiecesState::MovementSubStateIds::Waiting);
            return;
        }
        
        if (event->args().type == PointerInputEventType::Motion)
        {
            auto filteredMotion = FilterMotion(event->args().motion, mControllerRef.minValueXMotion());
            
            if ( filteredMotion.dx != 0)
            {
                // Save this initial motion
                auto movingState = std::static_pointer_cast<MovingBlockPieceInputState>(mFSM.FindState(MovingPiecesState::MovementSubStateIds::Moving_Block));

                if (movingState)
                {
                    movingState->initialMotion = filteredMotion;
                }
                
                mFSM.ChangeTo(MovingPiecesState::MovementSubStateIds::Moving_Block);
            }
        }
    }
}
Example #5
0
// Canonicalize a graph, renumbering it so that all structurally equivalent
// graphs have same numbers.
std::shared_ptr<Graph> Canonicalize(const std::shared_ptr<Graph>& graph) {
  auto r = std::make_shared<Graph>(graph->scope_root());
  std::unordered_map<Value*, Value*> rn_env;
  auto rn_fn = [&](Value* v) { return rn_env.at(v); };
  for (auto* input : graph->inputs()) {
    auto* r_input = r->addInput();
    r_input->copyMetadata(input);
    r_input->setStage(input->stage());
    rn_env[input] = r_input;
  }
  for (auto* node : graph->nodes()) {
    auto* r_node = r->createClone(node, rn_fn);
    r_node->setStage(node->stage());
    r->appendNode(r_node);
    auto outputs = node->outputs();
    auto r_outputs = r_node->outputs();
    for (size_t i = 0; i < outputs.size(); i++) {
      r_outputs.at(i)->setStage(outputs.at(i)->stage());
      rn_env[outputs.at(i)] = r_outputs.at(i);
    }
  }
  for (auto* output : graph->outputs()) {
    r->registerOutput(rn_fn(output));
  }
  r->setStage(graph->stage());

  return r;

}
Example #6
0
void StoreApiStoreOrderOrderIdResource::GET_method_handler(const std::shared_ptr<restbed::Session> session) {

	const auto request = session->get_request();

			// Getting the path params
			const int64_t orderId = request->get_path_parameter("orderId", 0L);
			
		
			
			// Change the value of this variable to the appropriate response before sending the response
			int status_code = 200;
			
			/**
			 * Process the received information here
			 */
			
			if (status_code == 200) {
				std::shared_ptr<Order> response = NULL;
				session->close(200, "successful operation", { {"Connection", "close"} });
				return;
			}
			if (status_code == 400) {
				session->close(400, "Invalid ID supplied", { {"Connection", "close"} });
				return;
			}
			if (status_code == 404) {
				session->close(404, "Order not found", { {"Connection", "close"} });
				return;
			}

}
ActorDescriptorPtr StoreDelegateRddActor::generateActorDescriptor() {
  static std::shared_ptr<ActorDescriptorWrapper> descriptor;
  if (descriptor)
    return descriptor;

  descriptor = generateBaseActorDescriptor(STORE_DELEGATE_RDD_ACTOR);

  // in operation
  ActorOperationDescriporWrapper inCreateDelegateRdd;
  inCreateDelegateRdd.setName(CREATE_STORE_DELEGATE_RDD);
  inCreateDelegateRdd.setDescription("Create store delegate RDD.");
  inCreateDelegateRdd.setPayloadType("idgs.rdd.pb.CreateDelegateRddRequest");
  descriptor->setInOperation(inCreateDelegateRdd.getName(), inCreateDelegateRdd);

  // out operation
  // out operation for CREATE_STORE_DELEGATE_RDD
  ActorOperationDescriporWrapper inCreateDelegatePartition;
  inCreateDelegatePartition.setName(CREATE_DELEGATE_PARTITION);
  inCreateDelegatePartition.setDescription("Out for create store delegate RDD, to create delegate partition.");
  inCreateDelegatePartition.setPayloadType("idgs.rdd.pb.CreateDelegatePartitionRequest");
  descriptor->setOutOperation(inCreateDelegatePartition.getName(), inCreateDelegatePartition);

  // out descriptor for message RDD_TRANSFORM, RDD_READY
  ActorOperationDescriporWrapper outRddPartitionProcess;
  outRddPartitionProcess.setName(RDD_PARTITION_PROCESS);
  outRddPartitionProcess.setDescription("out message for RDD_TRANSFORM, RDD_READY");
  outRddPartitionProcess.setPayloadType("idgs.rdd.pb.CreateDelegateRddRequest");
  descriptor->setOutOperation(outRddPartitionProcess.getName(), outRddPartitionProcess);

  StoreDelegateRddActor::descriptor = descriptor;
  return descriptor;
}
Example #8
0
    /** We got some data for a ledger we are no longer acquiring
        Since we paid the price to receive it, we might as well stash it in case we need it.
        Nodes are received in wire format and must be stashed/hashed in prefix format
    */
    void gotStaleData (std::shared_ptr<protocol::TMLedgerData> packet_ptr)
    {
        const uint256 uZero;
        Serializer s;
        try
        {
            for (int i = 0; i < packet_ptr->nodes ().size (); ++i)
            {
                auto const& node = packet_ptr->nodes (i);

                if (!node.has_nodeid () || !node.has_nodedata ())
                    return;

                SHAMapTreeNode newNode(
                    Blob (node.nodedata().begin(), node.nodedata().end()),
                    0, snfWIRE, uZero, false);

                s.erase();
                newNode.addRaw(s, snfPREFIX);

                auto blob = std::make_shared<Blob> (s.begin(), s.end());

                getApp().getOPs().addFetchPack (newNode.getNodeHash(), blob);
            }
        }
        catch (...)
        {
        }
    }
	// Implement echo
	virtual bool handler(std::shared_ptr<IComms> comms)
	{
std::cerr << "<TEST> handler - START" << std::endl;

		while (comms->isOpen())
		{
			TimeUtils::msSleep(200) ;
			if (!comms->isOpen())
				break ;

			std::string rx ;
			std::cerr << "<TEST> handler - Receive..." << std::endl;
			if (!comms->receive(rx))
				break ;

			// echo back
			if (!rx.empty())
			{
				std::cerr << "<TEST> handler - Echo" << std::endl;
				comms->send(rx) ;
			}
		}

std::cerr << "<TEST> handler - END" << std::endl;
		return false ;
	}
Example #10
0
Platform::Platform(
    const std::shared_ptr<input::Manager> &input_manager,
    const graphics::Rect &static_display_frame,
    bool single_window)
    : input_manager_(input_manager),
      event_thread_running_(false),
      single_window_(single_window) {
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_EVENTS) < 0) {
    const auto message = utils::string_format("Failed to initialize SDL: %s", SDL_GetError());
    BOOST_THROW_EXCEPTION(std::runtime_error(message));
  }

  auto display_frame = graphics::Rect::Invalid;
  if (static_display_frame == graphics::Rect::Invalid) {
    for (auto n = 0; n < SDL_GetNumVideoDisplays(); n++) {
      SDL_Rect r;
      if (SDL_GetDisplayBounds(n, &r) != 0) continue;

      graphics::Rect frame{r.x, r.y, r.x + r.w, r.y + r.h};

      if (display_frame == graphics::Rect::Invalid)
        display_frame = frame;
      else
        display_frame.merge(frame);
    }

    if (display_frame == graphics::Rect::Invalid)
      BOOST_THROW_EXCEPTION(
          std::runtime_error("No valid display configuration found"));
  } else {
    display_frame = static_display_frame;
    window_size_immutable_ = true;
  }

  graphics::emugl::DisplayInfo::get()->set_resolution(display_frame.width(), display_frame.height());

  pointer_ = input_manager->create_device();
  pointer_->set_name("anbox-pointer");
  pointer_->set_driver_version(1);
  pointer_->set_input_id({BUS_VIRTUAL, 2, 2, 2});
  pointer_->set_physical_location("none");
  pointer_->set_key_bit(BTN_MOUSE);
  // NOTE: We don't use REL_X/REL_Y in reality but have to specify them here
  // to allow InputFlinger to detect we're a cursor device.
  pointer_->set_rel_bit(REL_X);
  pointer_->set_rel_bit(REL_Y);
  pointer_->set_rel_bit(REL_HWHEEL);
  pointer_->set_rel_bit(REL_WHEEL);
  pointer_->set_prop_bit(INPUT_PROP_POINTER);

  keyboard_ = input_manager->create_device();
  keyboard_->set_name("anbox-keyboard");
  keyboard_->set_driver_version(1);
  keyboard_->set_input_id({BUS_VIRTUAL, 3, 3, 3});
  keyboard_->set_physical_location("none");
  keyboard_->set_key_bit(BTN_MISC);
  keyboard_->set_key_bit(KEY_OK);

  event_thread_ = std::thread(&Platform::process_events, this);
}
Example #11
0
void RandomForest::Node<T>::GetSampleList(std::shared_ptr<std::vector<int> > o_posSampleList, std::shared_ptr<std::vector<int> > o_negSampleList) const
{
    if (featureIndex==-1)
    {
        for(int i=0; i<sampleIndexList->size(); i++)
        {
            int tempIndex=sampleIndexList->at(i);
            T label=tree->GetTrainData()->at(tempIndex)->back();
            if (label > 0)
            {
                o_posSampleList->push_back(tempIndex);
            }
            else{
                o_negSampleList->push_back(tempIndex);
            }
        }
        return;
    }
    if (left)
    {
        left->GetSampleList(o_posSampleList,o_negSampleList);
    }

    if (right)
    {
        right->GetSampleList(o_posSampleList,o_negSampleList);
    }
}
Example #12
0
void PV61Sync::requestSubchain(std::shared_ptr<EthereumPeer> _peer)
{
	auto syncPeer = m_chainSyncPeers.find(_peer);
	if (syncPeer != m_chainSyncPeers.end())
	{
		// Already downoading, request next batch
		SubChain const& s = m_downloadingChainMap.at(syncPeer->second);
		_peer->requestHashes(s.lastHash);
	}
	else if (needsSyncing(_peer))
	{
		if (!m_readyChainMap.empty())
		{
			clog(NetAllDetail) << "Helping with hashchin download";
			SubChain& s = m_readyChainMap.begin()->second;
			_peer->requestHashes(s.lastHash);
			m_downloadingChainMap[m_readyChainMap.begin()->first] = move(s);
			m_chainSyncPeers[_peer] = m_readyChainMap.begin()->first;
			m_readyChainMap.erase(m_readyChainMap.begin());
		}
		else if (!m_downloadingChainMap.empty() && m_hashScanComplete)
			// Lead syncer is done, just grab whatever we can
			_peer->requestHashes(m_downloadingChainMap.begin()->second.lastHash);
	}
}
Example #13
0
void PV61Sync::syncHashes(std::shared_ptr<EthereumPeer> _peer)
{
	if (_peer->m_protocolVersion != host().protocolVersion())
	{
		m_readyChainMap.clear();
		m_completeChainMap.clear();
		m_downloadingChainMap.clear();
		m_syncingBlockNumber = 0;
		m_chainSyncPeers.clear();
		m_knownHashes.clear();
		m_hashScanComplete = false;
		PV60Sync::syncHashes(_peer);
		return;
	}
	if (m_state == SyncState::Idle)
	{
		if (isSyncing(_peer))
			clog(NetWarn) << "Bad state: not asking for Hashes, yet syncing!";

		if (m_syncingBlockNumber == 0)
			m_syncingBlockNumber = host().chain().number() + c_hashSubchainSize;
		m_syncingTotalDifficulty = _peer->m_totalDifficulty;
		setState(_peer, SyncState::Hashes, true);
		_peer->requestHashes(m_syncingBlockNumber, 1);
	}
	else if (m_state == SyncState::Hashes)
	{
		if (!isSyncing(_peer))
			clog(NetWarn) << "Bad state: asking for Hashes yet not syncing!";

		m_syncingBlockNumber += c_hashSubchainSize;
		setState(_peer, SyncState::Hashes, true);
		_peer->requestHashes(m_syncingBlockNumber, 1);
	}
}
void SpiderWebApp::setupGlsl()
{
	// These are the names of our out going vertices. GlslProg needs to
	// know which attributes should be captured by Transform FeedBack.
	std::vector<std::string> feedbackVaryings({
		"tf_position_mass",
		"tf_velocity"
	});
	
	gl::GlslProg::Format updateFormat;
	updateFormat.vertex( loadAsset( "update.vert" ) )
				// Because we have separate buffers with which
				// to capture attributes, we're using GL_SEPERATE_ATTRIBS
				.feedbackFormat( GL_SEPARATE_ATTRIBS )
				// We also send the names of the attributes to capture
				.feedbackVaryings( feedbackVaryings );
	
	mUpdateGlsl = gl::GlslProg::create( updateFormat );
	// Set this, otherwise it will be set to vec3( 0, 0, 0 ),
	// which is in the center of the cloth
	mUpdateGlsl->uniform( "rayPosition", vec3( 0 ) );
	mUpdateGlsl->uniform( "gravity", vec3(0, 0.08f, 0) );
//	mUpdateGlsl->uniform( "rest_length", 20.0 );
	mUpdateGlsl->uniform( "c", mOptions->getDamping() );
	mUpdateGlsl->uniform( "k", mOptions->getSpringConstant() );
	mUpdateGlsl->uniform( "tension", mOptions->getTension() );
	mUpdateGlsl->uniform( "t", mOptions->getTimestep() );
	
	gl::GlslProg::Format renderFormat;
	renderFormat.vertex( loadAsset( "render.vert" ) )
				.fragment( loadAsset( "render.frag" ) );
	
	mRenderGlsl = gl::GlslProg::create( renderFormat );
}
Example #15
0
bool CIADodge::accept(const std::shared_ptr<Logic::IMessage> &message)
{
    return message->getType() == "DAMAGED" ||
           message->getType() == "FALLING" ||
           message->getType() == "CHANGE_TARGET" ||
           message->getType() == "CAN_IA";
}
Example #16
0
std::shared_ptr<VolumeGL> VolumeRAM2GLConverter::createFrom(
    std::shared_ptr<const VolumeRAM> volumeRAM) const {
    auto volume =
        std::make_shared<VolumeGL>(volumeRAM->getDimensions(), volumeRAM->getDataFormat(), false);
    volume->getTexture()->initialize(volumeRAM->getData());
    return volume;
}
int compareSections(std::shared_ptr<OsmAnd::RoutePlannerContext::RoutingSubsectionContext> o1,
                    std::shared_ptr<OsmAnd::RoutePlannerContext::RoutingSubsectionContext> o2) {
    int v1 = (o1->getAccessCounter() + 1) * intpow(10, o1->getLoadsCounter() -1);
    int v2 = (o2->getAccessCounter() + 1) * intpow(10, o1->getLoadsCounter() -1);
    //return v1 < v2 ? -1 : (v1 == v2 ? 0 : 1);
    return v1 < v2;
}
Example #18
0
bool ComplexConfigValue::merge(std::shared_ptr<ConfigValue> other)
{
    if(other->getType() != COMPLEX)
        return false;

    if(name != other->getName())
    {
        throw std::runtime_error("Internal Error, merge between mismatching value");
    }

    const ComplexConfigValue *cother = dynamic_cast<const ComplexConfigValue *>(other.get());
    
    for(const auto &it : cother->values)
    {
        std::map<std::string, std::shared_ptr<ConfigValue> >::iterator entry = values.find(it.first);
        if(entry != values.end())
        {
            if(!entry->second->merge(it.second))
                return false;
        }
        else
        {
            values.insert(it);
        }
    }    
    return true;
}
Example #19
0
		/**
		 * @brief Construct data of the Entity from an XML object
		 *
		 * <p> Constructs the EntityGroup's own member variables only from the input XML object. </p>
		 *
		 * <p> Do not consider about constructing children Entity objects' data in EntityGroup::construct().
		 * Those children Entity objects' data will constructed by their own construct() method. Even insertion
		 * of XML objects representing children are done by abstract method of EntityGroup::toXML(). </p>
		 *
		 * <p> Constructs only data of EntityGroup's own. </p>
		 *
		 * \par [Inherited]
		 *		@copydoc Entity::construct()
		 */
		virtual void construct(std::shared_ptr<library::XML> xml)
		{
			clear();
			if (xml->has(CHILD_TAG()) == false)
				return;

			std::shared_ptr<library::XMLList> &xmlList = xml->get(CHILD_TAG());

			if (std::is_same<_Container, std::vector<_Container::value_type, _Container::allocator_type>>::value == true)
			{
				//FOR RESERVE
				assign(xmlList->size(), nullptr);
				erase(begin(), end());
			}

			for (size_t i = 0; i < xmlList->size(); i++)
			{
				std::shared_ptr<library::XML> &xmlElement = xmlList->at(i);

				entity_type *entity = createChild(xmlElement);
				if (entity != nullptr)
				{
					entity->construct(xmlList->at(i));
					emplace_back(entity);
				}
			}
		};
Example #20
0
bool ArrayConfigValue::merge(std::shared_ptr< ConfigValue > other)
{
    if(other->getType() != ARRAY)
        return false;

    if(name != other->getName())
    {
        throw std::runtime_error("Internal Error, merge between mismatching value");
    }
    
    const ArrayConfigValue *aother = dynamic_cast<const ArrayConfigValue *>(other.get());
    
    //we only support direct overwrite by index
    for(size_t i = 0; i < aother->values.size(); i++)
    {
        if(i < values.size())
        {
            values[i] = aother->values[i];
        }
        else
        {
            values.push_back(aother->values[i]);
        }
    }
    
    return true;
}
Example #21
0
void VolumeGL2CLGLConverter::update(std::shared_ptr<const VolumeGL> volumeSrc,
                                    std::shared_ptr<VolumeCLGL> volumeDst) const {
    // Do nothing since they are sharing data
    if (volumeSrc->getDimensions() != volumeDst->getDimensions()) {
        volumeDst->setDimensions(volumeSrc->getDimensions());
    }
}
		void PeerComm::HandleHandshake(std::shared_ptr<std::array<char, 68>> buffer, const boost::system::error_code& error)
		{
			std::unique_lock<std::mutex> _(m_Mutex);

			if ((*buffer)[0] != 19)
			{
				m_State = PeerCommState::Error;
				return;
			}
			std::string protocolId(buffer->data() + 1, 19);
			if (protocolId != "BitTorrent protocol")
			{
				m_State = PeerCommState::Error;
				return;
			}

			std::string infoHash(buffer->data() + 28, 20);
			if (infoHash != m_InfoHash)
			{
				std::cout << "bad info_hash" << std::endl;
				m_State = PeerCommState::Error;
				return;
			}

			std::string peerId(buffer->data() + 48, 20);
			m_PeerID = peerId;

			m_State = PeerCommState::Choked;
			QueueReceiveMessage();
		}
Example #23
0
    static void query_extent(std::shared_ptr<sqlite_resultset> rs,
                             mapnik::box2d<double>& extent)
    {

        bool first = true;
        while (rs->is_valid() && rs->step_next())
        {
            int size;
            const char* data = static_cast<const char*>(rs->column_blob(0, size));
            if (data)
            {
                mapnik::geometry_container paths;
                if (mapnik::geometry_utils::from_wkb(paths, data, size, mapnik::wkbAuto))
                {
                    for (unsigned i=0; i<paths.size(); ++i)
                    {
                        mapnik::box2d<double> const& bbox = paths[i].envelope();
                        if (bbox.valid())
                        {
                            if (first)
                            {
                                first = false;
                                extent = bbox;
                            }
                            else
                            {
                                extent.expand_to_include(bbox);
                            }
                        }
                    }
                }
            }
        }
    }
		void PeerComm::HandleMessagePayload(std::shared_ptr<std::vector<char>> payload_, const boost::system::error_code& error)
		{
			if (!error)
			{
				QueueReceiveMessage();

				auto id = (*payload_)[0];
					
				std::vector<char> payload;
				payload.reserve(payload_->size() - 1);
				payload.insert(payload.end(), payload_->begin() + 1, payload_->end());

				std::unique_lock<std::mutex> _(m_Mutex);

				switch ((Peer::MessageType)id)
				{
				case Peer::MessageType::Choke:
					m_State = PeerCommState::Choked;
					m_Incoming.push_back(std::make_unique<Peer::Choke>());
					break;
				case Peer::MessageType::Unchoke:
					m_State = PeerCommState::Working;
					m_Incoming.push_back(std::make_unique<Peer::Unchoke>());
					break;
				case Peer::MessageType::Interested:
					m_Incoming.push_back(std::make_unique<Peer::Interested>());
					break;
				case Peer::MessageType::NotInterested:
					m_Incoming.push_back(std::make_unique<Peer::NotInterested>());
					break;
				case Peer::MessageType::Have:
					m_Incoming.push_back(std::make_unique<Peer::Have>(payload));
					break;
				case Peer::MessageType::Bitfield:
					m_Incoming.push_back(std::make_unique<Peer::Bitfield>(payload));
					break;
				case Peer::MessageType::Request:
					m_Incoming.push_back(std::make_unique<Peer::Request>(payload));
					break;
				case Peer::MessageType::Piece:
					m_Incoming.push_back(std::make_unique<Peer::Piece>(payload));
					break;
				case Peer::MessageType::Cancel:
					m_Incoming.push_back(std::make_unique<Peer::Cancel>(payload));
					break;
				case Peer::MessageType::Port:
					m_Incoming.push_back(std::make_unique<Peer::Port>(payload));
					break;
				default:
					std::cout << "invalid message id" << std::endl;
					m_State = PeerCommState::Error;
					return;
				}
			}
			else
			{
				std::unique_lock<std::mutex> _(m_Mutex);
				m_State = PeerCommState::Error;
			}
		}
tts::dictionary::entry::entry(const std::shared_ptr<buffer> &aPhonemes, std::shared_ptr<phoneme_reader> &aPhonemeSet)
	: type(tts::dictionary::phonemes)
{
	aPhonemeSet->reset(aPhonemes);
	while (aPhonemeSet->read())
		phonemes.push_back(*aPhonemeSet);
}
Example #26
0
	void Game::destroyAsteroid(std::shared_ptr<Asteroid>& asteroid, bool addPoints)
	{
		int size = asteroid->asteroidSize();
		float asteroidSize = Asteroid::AsteroidSizes().at(size);
		Math::vec2 pos = asteroid->physicsComponent()->getPosition() + (asteroidSize / 2.f);

		// Add to score if needed
		if (addPoints)
			m_ship.addScore((Asteroid::AsteroidSizes().size() - size) * 100);

		// Flag asteroid as destroyed
		asteroid->destroy();

		// If the asteroid is not the smallest one yet, spawn two new ones
		if (size != 0)
		{
			size--;
			asteroidSize = Asteroid::AsteroidSizes().at(size);
			pos -= asteroidSize / 2.f;
			Math::vec2 dir = Math::normalize(asteroid->physicsComponent()->getVelocity());

			dir = Math::rotate(dir, 0.5f * Math::pi<float>());
			m_asteroids.push_back(std::make_shared<Asteroid>(size, pos + (dir * asteroidSize / 2.f), dir));
			m_asteroids.push_back(std::make_shared<Asteroid>(size, pos + (-dir * asteroidSize / 2.f), -dir));
		}
	}
MatrixViewDialog::MatrixViewDialog(std::shared_ptr<Matrix<int>>& matrix, int pos, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MatrixViewDialog),
    data(matrix),
    _pos(pos)
{
    ui->setupUi(this);
    setWindowTitle(QString::fromStdString(matrix->toStr()) + " info");

    ui->tableWidget->setRowCount(matrix->rows());
    ui->tableWidget->setColumnCount(matrix->columns());
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    for (size_t i = 0; i < matrix->rows(); ++i) {
        for (size_t j = 0; j < matrix->columns(); ++j) {
            auto tmpItem = new QTableWidgetItem;

            auto tmpStr = QString::fromStdString(std::to_string((*matrix)(i,j)));
            tmpItem->setText(tmpStr);
            tmpItem->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(i, j, tmpItem);
        }
    }

    connect(ui->saveBtn, SIGNAL(clicked()), SLOT(saveBtnClicked()));
    connect(ui->removeBtn, SIGNAL(clicked()), SLOT(removeBtnClicked()));
}
Example #28
0
static void default_generators(
    w_query* query,
    const std::shared_ptr<w_root_t>& root,
    struct w_query_ctx* ctx) {
  bool generated = false;

  // Time based query
  if (ctx->since.is_timestamp || !ctx->since.clock.is_fresh_instance) {
    time_generator(query, root, ctx);
    generated = true;
  }

  // Suffix
  if (!query->suffixes.empty()) {
    root->view()->suffixGenerator(query, ctx);
    generated = true;
  }

  if (!query->paths.empty()) {
    root->view()->pathGenerator(query, ctx);
    generated = true;
  }

  if (query->glob_tree) {
    root->view()->globGenerator(query, ctx);
    generated = true;
  }

  // And finally, if there were no other generators, we walk all known
  // files
  if (!generated) {
    root->view()->allFilesGenerator(query, ctx);
  }
}
Example #29
0
int main(int argc, char**argv)
{
    using namespace std::placeholders;
    bkLogger.reset(new BackendLogger("./game.log"));
    bkLogger->start();
    gLogger.setAppendCallback(std::bind(dumpfunc,_1, _2));
    LOG_DEBUG("int={some int},str={your name}", 25,"hello");
    LOG_DEBUG("hello logging");

    int a{32};
    float f{33.3};
    std::string s{"logging"};
    stFoo foo;
    LOG_TRACE("int={},float={}, {foo data}", a, f, foo);

    bool flag = (argc>1)?true:false;
    bench(flag);

    /*
    char buffer[64*1024];
    g_file = fopen("/dev/null", "w");
    setbuffer(g_file, buffer, sizeof buffer);
    bench();
    fclose(g_file);

    g_file = NULL;
    */

    sleep(8);
    bkLogger->stop();
}
Example #30
0
void CommunicationInterface::onRequestInformation(std::shared_ptr<Entity> const &entity,
                                                  std::vector<std::shared_ptr<InformationSpecification>> const &requests)
{
  _log->info("Information request received from '%v'", entity->toString());
  std::vector<std::shared_ptr<InformationElement<GContainer>>> infos;

  for (auto &request : requests)
  {
    this->bridge->informationStore->getInformation(request,infos);
  }

  int count = infos.size();
  if (count == 0)
  {
    _log->warn("No information found for request from '%v'", entity->toString());
    return;
  }


  _log->info("Sending '%v' information to '%v'", count, entity->toString());
  for (auto &info : infos)
  {
    auto m = std::make_shared<InformationMessage>();
    m->setEntity(entity);
    m->getInformations().push_back(info);
    this->sendMessage(m);
  }
}