Example #1
0
void UPnpCDSMusic::AddItem( const UPnpCDSRequest    *pRequest, 
                            const QString           &sObjectId,
                            UPnpCDSExtensionResults *pResults,
                            bool                     bAddRef,
                            MSqlQuery               &query )
{
    QString        sName;

    int            nId          = query.value( 0).toInt();
    QString        sArtist      = query.value( 1).toString();
    QString        sAlbum       = query.value( 2).toString();
    QString        sTitle       = query.value( 3).toString();
    QString        sGenre       = query.value( 4).toString();
//    int            nYear        = query.value( 5).toInt();
    int            nTrackNum    = query.value( 6).toInt();
    QString        sDescription = query.value( 7).toString();
    QString        sFileName    = query.value( 8).toString();
    uint           nLength      = query.value( 9).toInt();

/*
    if ((nNodeIdx == 0) || (nNodeIdx == 1))
    {
        sName = QString( "%1-%2:%3" )
                   .arg( sArtist)
                   .arg( sAlbum )
                   .arg( sTitle );
    }
    else
*/
        sName = sTitle;

//cout << nId << " " << sName << endl;


    // ----------------------------------------------------------------------
    // Cache Host ip Address & Port
    // ----------------------------------------------------------------------

//    if (!m_mapBackendIp.contains( sHostName ))
//        m_mapBackendIp[ sHostName ] = gCoreContext->GetSettingOnHost( "BackendServerIp", sHostName);
//
//    if (!m_mapBackendPort.contains( sHostName ))
//        m_mapBackendPort[ sHostName ] = gCoreContext->GetSettingOnHost("BackendStatusPort", sHostName);

    QString sServerIp = gCoreContext->GetSetting( "BackendServerIp"   );
    QString sPort     = gCoreContext->GetSetting( "BackendStatusPort" );

    // ----------------------------------------------------------------------
    // Build Support Strings
    // ----------------------------------------------------------------------

    QString sURIBase   = QString( "http://%1:%2/Myth/" )
                            .arg( sServerIp )
                            .arg( sPort     );

    QString sURIParams = QString( "?Id=%1" )
                            .arg( nId );


    QString sId        = QString( "Music/1/item%1")
                            .arg( sURIParams );

    CDSObject *pItem   = CDSObject::CreateMusicTrack( sId,
                                                      sName,
                                                      sObjectId );
    pItem->m_bRestricted  = true;
    pItem->m_bSearchable  = true;
    pItem->m_sWriteStatus = "NOT_WRITABLE";

    if ( bAddRef )
    {
        QString sRefId = QString( "%1/0/item%2")
                            .arg( m_sExtensionId )
                            .arg( sURIParams     );

        pItem->SetPropValue( "refID", sRefId );
    }

    pItem->SetPropValue( "genre"                , sGenre      );
    pItem->SetPropValue( "description"          , sTitle      );
    pItem->SetPropValue( "longDescription"      , sDescription);

    pItem->SetPropValue( "artist"               ,  sArtist    );
    pItem->SetPropValue( "album"                ,  sAlbum     );
    pItem->SetPropValue( "originalTrackNumber"  ,  QString::number( nTrackNum  ));

/*

    pObject->AddProperty( new Property( "publisher"       , "dc"   ));
    pObject->AddProperty( new Property( "language"        , "dc"   ));
    pObject->AddProperty( new Property( "relation"        , "dc"   ));
    pObject->AddProperty( new Property( "rights"          , "dc"   ));


    pObject->AddProperty( new Property( "playlist"            , "upnp" ));
    pObject->AddProperty( new Property( "storageMedium"       , "upnp" ));
    pObject->AddProperty( new Property( "contributor"         , "dc"   ));
    pObject->AddProperty( new Property( "date"                , "dc"   ));

*/


    pResults->Add( pItem );

    // ----------------------------------------------------------------------
    // Add Music Resource Element based on File extension (HTTP)
    // ----------------------------------------------------------------------

    QFileInfo fInfo( sFileName );

    QString sMimeType = HTTPRequest::GetMimeType( fInfo.suffix() );
    QString sProtocol = QString( "http-get:*:%1:DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01500000000000000000000000000000" ).arg( sMimeType  );
    QString sURI      = QString( "%1GetMusic%2").arg( sURIBase   )
                                                .arg( sURIParams );

    Resource *pRes = pItem->AddResource( sProtocol, sURI );

    nLength /= 1000;

    QString sDur;

    sDur.sprintf("%02d:%02d:%02d",
                  (nLength / 3600) % 24,
                  (nLength / 60) % 60,
                  nLength % 60);

    pRes->AddAttribute( "duration"  , sDur      );
}
Example #2
0
template<UnsignedInt dimensions> void LineSegmentRenderer<dimensions>::draw(Resource<ShapeRendererOptions>& options, const MatrixTypeFor<dimensions, Float>& projectionMatrix) {
    AbstractShapeRenderer<dimensions>::wireframeShader->setTransformationProjectionMatrix(projectionMatrix*
        Implementation::lineSegmentRendererTransformation<dimensions>(line.a(), line.b()))
        .setColor(options->color());
    AbstractShapeRenderer<dimensions>::wireframeMesh->draw(*AbstractShapeRenderer<dimensions>::wireframeShader);
}
Example #3
0
void UPnpCDSMusic::AddItem( const UPnpCDSRequest    *pRequest, 
                            const QString           &sObjectId,
                            UPnpCDSExtensionResults *pResults,
                            bool                     bAddRef,
                            MSqlQuery               &query )
{
    QString        sName;

    int            nId          = query.value( 0).toInt();
    QString        sArtist      = query.value( 1).toString();
    QString        sAlbum       = query.value( 2).toString();
    QString        sTitle       = query.value( 3).toString();
    QString        sGenre       = query.value( 4).toString();
    int            nYear        = query.value( 5).toInt();
    int            nTrackNum    = query.value( 6).toInt();
    QString        sDescription = query.value( 7).toString();
    QString        sFileName    = query.value( 8).toString();
    uint           nLength      = query.value( 9).toInt();
    uint64_t       nFileSize    = (quint64)query.value(10).toULongLong();

#if 0
    if ((nNodeIdx == 0) || (nNodeIdx == 1))
    {
        sName = QString( "%1-%2:%3" )
                   .arg( sArtist)
                   .arg( sAlbum )
                   .arg( sTitle );
    }
    else
#endif
        sName = sTitle;


    // ----------------------------------------------------------------------
    // Cache Host ip Address & Port
    // ----------------------------------------------------------------------

#if 0
    if (!m_mapBackendIp.contains( sHostName ))
        m_mapBackendIp[ sHostName ] = gCoreContext->GetSettingOnHost( "BackendServerIp", sHostName);

    if (!m_mapBackendPort.contains( sHostName ))
        m_mapBackendPort[ sHostName ] = gCoreContext->GetSettingOnHost("BackendStatusPort", sHostName);
#endif

    QString sServerIp = gCoreContext->GetSetting( "BackendServerIp"   );
    QString sPort     = gCoreContext->GetSetting( "BackendStatusPort" );

    // ----------------------------------------------------------------------
    // Build Support Strings
    // ----------------------------------------------------------------------

    QString sURIBase   = QString( "http://%1:%2/Content/" )
                            .arg( sServerIp )
                            .arg( sPort     );

    QString sURIParams = QString( "?Id=%1" )
                            .arg( nId );


    QString sId        = QString( "Music/1/item%1")
                            .arg( sURIParams );

    CDSObject *pItem   = CDSObject::CreateMusicTrack( sId,
                                                      sName,
                                                      sObjectId );
    pItem->m_bRestricted  = true;
    pItem->m_bSearchable  = true;
    pItem->m_sWriteStatus = "NOT_WRITABLE";

    if ( bAddRef )
    {
        QString sRefId = QString( "%1/0/item%2")
                            .arg( m_sExtensionId )
                            .arg( sURIParams     );

        pItem->SetPropValue( "refID", sRefId );
    }

    pItem->SetPropValue( "genre"                , sGenre      );
    pItem->SetPropValue( "description"          , sTitle      );
    pItem->SetPropValue( "longDescription"      , sDescription);

    pItem->SetPropValue( "artist"               ,  sArtist    );
    pItem->SetPropValue( "album"                ,  sAlbum     );
    pItem->SetPropValue( "originalTrackNumber"  ,  QString::number(nTrackNum));
    if (nYear > 0 && nYear < 9999)
        pItem->SetPropValue( "date",  QDate(nYear,1,1).toString(Qt::ISODate));

#if 0
    pObject->AddProperty( new Property( "publisher"       , "dc"   ));
    pObject->AddProperty( new Property( "language"        , "dc"   ));
    pObject->AddProperty( new Property( "relation"        , "dc"   ));
    pObject->AddProperty( new Property( "rights"          , "dc"   ));


    pObject->AddProperty( new Property( "playlist"            , "upnp" ));
    pObject->AddProperty( new Property( "storageMedium"       , "upnp" ));
    pObject->AddProperty( new Property( "contributor"         , "dc"   ));
    pObject->AddProperty( new Property( "date"                , "dc"   ));
#endif

    QString sArtURI = QString( "%1GetAlbumArt?Id=%2").arg( sURIBase   )
                                                     .arg( nId );

    QList<Property*> propList = pItem->GetProperties("albumArtURI");
    if (propList.size() >= 4)
    {
        // Prefer JPEG over PNG here, although PNG is allowed JPEG probably
        // has wider device support and crucially the filesizes are smaller
        // which speeds up loading times over the network

        // We MUST include the thumbnail size, but since some clients may use the
        // first image they see and the thumbnail is tiny, instead return the
        // medium first. The large could be very large, which is no good if the
        // client is pulling images for an entire list at once!

        // Medium
        Property *pProp = propList.at(0);
        if (pProp)
        {
            // Must be no more than 1024x768
            pProp->m_sValue = sArtURI;
            pProp->m_sValue.append("&amp;Width=1024&amp;Height=768");
            pProp->AddAttribute("dlna:profileID", "JPG_MED");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Thumbnail
        pProp = propList.at(1);
        if (pProp)
        {
            // At least one albumArtURI must be a ThumbNail (TN) no larger
            // than 160x160, and it must also be a jpeg
            pProp->m_sValue = sArtURI;
            pProp->m_sValue.append("&amp;Width=160&amp;Height=160");
            pProp->AddAttribute("dlna:profileID", "JPG_TN");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Small
        pProp = propList.at(2);
        if (pProp)
        {
            // Must be no more than 640x480
            pProp->m_sValue = sArtURI;
            pProp->m_sValue.append("&amp;Width=640&amp;Height=480");
            pProp->AddAttribute("dlna:profileID", "JPG_SM");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Large
        pProp = propList.at(3);
        if (pProp)
        {
            // Must be no more than 4096x4096 - for our purposes, just return
            // a fullsize image
            pProp->m_sValue = sArtURI;
            pProp->AddAttribute("dlna:profileID", "JPG_LRG");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }
    }

    pResults->Add( pItem );

    // ----------------------------------------------------------------------
    // Add Music Resource Element based on File extension (HTTP)
    // ----------------------------------------------------------------------

    QFileInfo fInfo( sFileName );

    QString sMimeType = HTTPRequest::GetMimeType( fInfo.suffix() );
    QString sProtocol = QString( "http-get:*:%1:DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01500000000000000000000000000000" ).arg( sMimeType  );
    QString sURI      = QString( "%1GetMusic%2").arg( sURIBase   )
                                                .arg( sURIParams );

    Resource *pRes = pItem->AddResource( sProtocol, sURI );

    nLength /= 1000;

    QString sDur;

    sDur.sprintf("%02d:%02d:%02d",
                  (nLength / 3600) % 24,
                  (nLength / 60) % 60,
                  nLength % 60);

    pRes->AddAttribute( "duration"  , sDur      );
    if (nFileSize > 0)
        pRes->AddAttribute( "size"      , QString::number( nFileSize) );
}
TEST(RawResourceTest, RedirectDuringRevalidation)
{
    Resource* resource = RawResource::create(ResourceRequest("https://example.com/1"), Resource::Raw);
    ResourceResponse response;
    response.setURL(KURL(ParsedURLString, "https://example.com/1"));
    response.setHTTPStatusCode(200);
    resource->responseReceived(response, nullptr);
    const char data[5] = "abcd";
    resource->appendData(data, 4);
    resource->finish();
    memoryCache()->add(resource);

    EXPECT_FALSE(resource->isCacheValidator());
    EXPECT_EQ("https://example.com/1", resource->resourceRequest().url().getString());
    EXPECT_EQ("https://example.com/1", resource->lastResourceRequest().url().getString());

    // Simulate a revalidation.
    resource->setRevalidatingRequest(ResourceRequest("https://example.com/1"));
    EXPECT_TRUE(resource->isCacheValidator());
    EXPECT_EQ("https://example.com/1", resource->resourceRequest().url().getString());
    EXPECT_EQ("https://example.com/1", resource->lastResourceRequest().url().getString());

    Persistent<DummyClient> client = new DummyClient;
    resource->addClient(client);

    // The revalidating request is redirected.
    ResourceResponse redirectResponse;
    redirectResponse.setURL(KURL(ParsedURLString, "https://example.com/1"));
    redirectResponse.setHTTPHeaderField("location", "https://example.com/2");
    redirectResponse.setHTTPStatusCode(308);
    ResourceRequest redirectedRevalidatingRequest("https://example.com/2");
    resource->willFollowRedirect(redirectedRevalidatingRequest, redirectResponse);
    EXPECT_FALSE(resource->isCacheValidator());
    EXPECT_EQ("https://example.com/1", resource->resourceRequest().url().getString());
    EXPECT_EQ("https://example.com/2", resource->lastResourceRequest().url().getString());

    // The final response is received.
    ResourceResponse revalidatingResponse;
    revalidatingResponse.setURL(KURL(ParsedURLString, "https://example.com/2"));
    revalidatingResponse.setHTTPStatusCode(200);
    resource->responseReceived(revalidatingResponse, nullptr);
    const char data2[4] = "xyz";
    resource->appendData(data2, 3);
    resource->finish();
    EXPECT_FALSE(resource->isCacheValidator());
    EXPECT_EQ("https://example.com/1", resource->resourceRequest().url().getString());
    EXPECT_EQ("https://example.com/2", resource->lastResourceRequest().url().getString());
    EXPECT_FALSE(resource->isCacheValidator());
    EXPECT_EQ(200, resource->response().httpStatusCode());
    EXPECT_EQ(3u, resource->resourceBuffer()->size());
    EXPECT_EQ(memoryCache()->resourceForURL(KURL(ParsedURLString, "https://example.com/1")), resource);

    EXPECT_TRUE(client->called());
    EXPECT_EQ(1, client->numberOfRedirectsReceived());
    EXPECT_EQ("xyz", String(client->data().data(), client->data().size()));

    // Test the case where a client is added after revalidation is completed.
    Persistent<DummyClient> client2 = new DummyClient;
    resource->addClient(client2);

    // Because RawResourceClient is added asynchronously,
    // |runPendingTasks()| is called to make |client2| to be notified.
    testing::runPendingTasks();

    EXPECT_TRUE(client2->called());
    EXPECT_EQ(1, client2->numberOfRedirectsReceived());
    EXPECT_EQ("xyz", String(client2->data().data(), client2->data().size()));

    memoryCache()->remove(resource);

    resource->removeClient(client);
    resource->removeClient(client2);
    EXPECT_FALSE(resource->hasClientsOrObservers());
}
int GUIFileSelector::Render(void)
{
	// First step, fill background
	gr_color(mBackgroundColor.red, mBackgroundColor.green, mBackgroundColor.blue, 255);
	gr_fill(mRenderX, mRenderY + mHeaderH, mRenderW, mRenderH - mHeaderH);

	// Next, render the background resource (if it exists)
	if (mBackground && mBackground->GetResource())
	{
		mBackgroundX = mRenderX + ((mRenderW - mBackgroundW) / 2);
		mBackgroundY = mRenderY + ((mRenderH - mBackgroundH) / 2);
		gr_blit(mBackground->GetResource(), 0, 0, mBackgroundW, mBackgroundH, mBackgroundX, mBackgroundY);
	}

	// This tells us how many lines we can actually render
	int lines = (mRenderH - mHeaderH) / (actualLineHeight);
	int line;

	int folderSize = mShowFolders ? mFolderList.size() : 0;
	int fileSize = mShowFiles ? mFileList.size() : 0;

	if (folderSize + fileSize < lines) {
		lines = folderSize + fileSize;
		scrollingY = 0;
	} else {
		lines++;
		if (lines < folderSize + fileSize)
			lines++;
	}

	void* fontResource = NULL;
	if (mFont)  fontResource = mFont->GetResource();

	int yPos = mRenderY + mHeaderH + scrollingY;
	int fontOffsetY = (int)((actualLineHeight - mFontHeight) / 2);
	int currentIconHeight = 0, currentIconWidth = 0;
	int currentIconOffsetY = 0, currentIconOffsetX = 0;
	int folderIconOffsetY = (int)((actualLineHeight - mFolderIconHeight) / 2), fileIconOffsetY = (int)((actualLineHeight - mFileIconHeight) / 2);
	int folderIconOffsetX = (mIconWidth - mFolderIconWidth) / 2, fileIconOffsetX = (mIconWidth - mFileIconWidth) / 2;

	for (line = 0; line < lines; line++)
	{
		Resource* icon;
		std::string label;

		// Set the color for the font
		gr_color(mFontColor.red, mFontColor.green, mFontColor.blue, 255);

		if (line + mStart < folderSize)
		{
			icon = mFolderIcon;
			label = mFolderList.at(line + mStart).fileName;
			currentIconHeight = mFolderIconHeight;
			currentIconWidth = mFolderIconWidth;
			currentIconOffsetY = folderIconOffsetY;
			currentIconOffsetX = folderIconOffsetX;
		}
		else if (line + mStart < folderSize + fileSize)
		{
			icon = mFileIcon;
			label = mFileList.at((line + mStart) - folderSize).fileName;
			currentIconHeight = mFileIconHeight;
			currentIconWidth = mFileIconWidth;
			currentIconOffsetY = fileIconOffsetY;
			currentIconOffsetX = fileIconOffsetX;
		} else {
			continue;
		}

		if (icon && icon->GetResource())
		{
			int rect_y = 0, image_y = (yPos + currentIconOffsetY);
			if (image_y + currentIconHeight > mRenderY + mRenderH)
				rect_y = mRenderY + mRenderH - image_y;
			else
				rect_y = currentIconHeight;
			gr_blit(icon->GetResource(), 0, 0, currentIconWidth, rect_y, mRenderX + currentIconOffsetX, image_y);
		}
		gr_textExWH(mRenderX + mIconWidth + 5, yPos + fontOffsetY, label.c_str(), fontResource, mRenderX + mRenderW, mRenderY + mRenderH);

		// Add the separator
		if (yPos + actualLineHeight < mRenderH + mRenderY) {
			gr_color(mSeparatorColor.red, mSeparatorColor.green, mSeparatorColor.blue, 255);
			gr_fill(mRenderX, yPos + actualLineHeight - mSeparatorH, mRenderW, mSeparatorH);
		}

		// Move the yPos
		yPos += actualLineHeight;
	}

	// Render the Header (last so that it overwrites the top most row for per pixel scrolling)
	// First step, fill background
	gr_color(mHeaderBackgroundColor.red, mHeaderBackgroundColor.green, mHeaderBackgroundColor.blue, 255);
	gr_fill(mRenderX, mRenderY, mRenderW, mHeaderH);

	// Now, we need the header (icon + text)
	yPos = mRenderY;
	{
		Resource* headerIcon;
		int mIconOffsetX = 0;

		// render the icon if it exists
		headerIcon = mHeaderIcon;
		if (headerIcon && headerIcon->GetResource())
		{
			gr_blit(headerIcon->GetResource(), 0, 0, mHeaderIconWidth, mHeaderIconHeight, mRenderX + ((mHeaderIconWidth - mIconWidth) / 2), (yPos + (int)((mHeaderH - mHeaderIconHeight) / 2)));
			mIconOffsetX = mIconWidth;
		}

		// render the text
		gr_color(mHeaderFontColor.red, mHeaderFontColor.green, mHeaderFontColor.blue, 255);
		gr_textExWH(mRenderX + mIconOffsetX + 5, yPos + (int)((mHeaderH - mFontHeight) / 2), mLastValue.c_str(), fontResource, mRenderX + mRenderW, mRenderY + mRenderH);

		// Add the separator
		gr_color(mHeaderSeparatorColor.red, mHeaderSeparatorColor.green, mHeaderSeparatorColor.blue, 255);
		gr_fill(mRenderX, yPos + mHeaderH - mHeaderSeparatorH, mRenderW, mHeaderSeparatorH);
	}

	mUpdate = 0;
	return 0;
}
Example #6
0
TEST_F(ResourceOffersTest, ResourcesGetReofferedAfterTaskInfoError)
{
  Try<Owned<cluster::Master>> master = StartMaster();
  ASSERT_SOME(master);

  Owned<MasterDetector> detector = master.get()->createDetector();
  Try<Owned<cluster::Slave>> slave = StartSlave(detector.get());
  ASSERT_SOME(slave);

  MockScheduler sched1;
  MesosSchedulerDriver driver1(
      &sched1, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);

  EXPECT_CALL(sched1, registered(&driver1, _, _));

  Future<vector<Offer>> offers;
  EXPECT_CALL(sched1, resourceOffers(&driver1, _))
    .WillOnce(FutureArg<1>(&offers))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  driver1.start();

  AWAIT_READY(offers);
  ASSERT_FALSE(offers->empty());

  TaskInfo task;
  task.set_name("");
  task.mutable_task_id()->set_value("1");
  task.mutable_slave_id()->MergeFrom(offers.get()[0].slave_id());
  task.mutable_executor()->MergeFrom(DEFAULT_EXECUTOR_INFO);

  Resource* cpus = task.add_resources();
  cpus->set_name("cpus");
  cpus->set_type(Value::SCALAR);
  cpus->mutable_scalar()->set_value(-1);

  Resource* mem = task.add_resources();
  mem->set_name("mem");
  mem->set_type(Value::SCALAR);
  mem->mutable_scalar()->set_value(static_cast<double>(Gigabytes(1).bytes()));

  vector<TaskInfo> tasks;
  tasks.push_back(task);

  Future<TaskStatus> status;
  EXPECT_CALL(sched1, statusUpdate(&driver1, _))
    .WillOnce(FutureArg<1>(&status));

  driver1.launchTasks(offers.get()[0].id(), tasks);

  AWAIT_READY(status);
  EXPECT_EQ(task.task_id(), status->task_id());
  EXPECT_EQ(TASK_ERROR, status->state());
  EXPECT_EQ(TaskStatus::REASON_TASK_INVALID, status->reason());
  EXPECT_TRUE(status->has_message());
  EXPECT_TRUE(strings::contains(status->message(), "Invalid scalar resource"))
    << status->message();

  MockScheduler sched2;
  MesosSchedulerDriver driver2(
      &sched2, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);

  EXPECT_CALL(sched2, registered(&driver2, _, _));

  EXPECT_CALL(sched2, resourceOffers(&driver2, _))
    .WillOnce(FutureArg<1>(&offers))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  driver2.start();

  AWAIT_READY(offers);

  driver1.stop();
  driver1.join();

  driver2.stop();
  driver2.join();
}
TEST(RawResourceTest, RevalidationSucceededForResourceWithoutBody)
{
    Resource* resource = RawResource::create(ResourceRequest("data:text/html,"), Resource::Raw);
    ResourceResponse response;
    response.setHTTPStatusCode(200);
    resource->responseReceived(response, nullptr);
    resource->finish();
    memoryCache()->add(resource);

    // Simulate a successful revalidation.
    resource->setRevalidatingRequest(ResourceRequest("data:text/html,"));

    Persistent<DummyClient> client = new DummyClient;
    resource->addClient(client);

    ResourceResponse revalidatingResponse;
    revalidatingResponse.setHTTPStatusCode(304);
    resource->responseReceived(revalidatingResponse, nullptr);
    EXPECT_FALSE(resource->isCacheValidator());
    EXPECT_EQ(200, resource->response().httpStatusCode());
    EXPECT_EQ(nullptr, resource->resourceBuffer());
    EXPECT_EQ(memoryCache()->resourceForURL(KURL(ParsedURLString, "data:text/html,")), resource);
    memoryCache()->remove(resource);

    resource->removeClient(client);
    EXPECT_FALSE(resource->hasClientsOrObservers());
    EXPECT_FALSE(client->called());
    EXPECT_EQ(0u, client->data().size());
}
//======================================================================================================================
//
// Selects the resource for extraction
//
void	ObjectController::_handleHarvesterSelectResource(uint64 targetId,Message* message,ObjectControllerCmdProperties* cmdProperties)
{
    PlayerObject*	player	= dynamic_cast<PlayerObject*>(mObject);

    if(!player)
    {
        return;
    }

    //do we have a valid structure ???
    uint64 id = targetId;
    Object* object = gWorldManager->getObjectById(id);
    PlayerStructure* structure = dynamic_cast<PlayerStructure*>(object);

    if(!structure)
    {
        //gMessageLib->sendSystemMessage(player,L"","player_structure","command_no_building");
        return;
    }

    //is the structure in Range???
    float fTransferDistance = gWorldConfig->getConfiguration<float>("Player_Structure_Operate_Distance",(float)10.0);
    if(glm::distance(player->mPosition, structure->mPosition) > fTransferDistance)
    {
        DLOG(INFO) << " ObjectController::_handleHarvesterGetResourceData Structure not in Range";
        return;
    }

    HarvesterObject* harvester = dynamic_cast<HarvesterObject*>(structure);

    //get the relevant Resource
    BString dataStr;
    message->getStringUnicode16(dataStr);

    uint64 resourceId;
    swscanf(dataStr.getUnicode16(),L"%"WidePRIu64,&resourceId);

    Resource* tmpResource = gResourceManager->getResourceById(resourceId);

    if((!tmpResource)||(!tmpResource->getCurrent()))
    {
        DLOG(INFO) << " ObjectController::_handleHarvesterGetResourceData No valid resource!";
        return;
    }

    harvester->setCurrentResource(resourceId);

    // update the current resource in the db
    mDatabase->executeSqlAsync(0,0,"UPDATE harvesters SET ResourceID=%"PRIu64" WHERE id=%"PRIu64" ",resourceId,harvester->getId());

    CurrentResource* cR = reinterpret_cast<CurrentResource*>(tmpResource);
    //resource = reinterpret_cast<CurrentResource*>(gResourceManager->getResourceByNameCRC(resourceName.getCrc()));

    float posX, posZ;
    float ratio = 0.0;

    posX	= harvester->mPosition.x;
    posZ	= harvester->mPosition.z;


    if(cR)
    {
        ratio	= cR->getDistribution((int)posX + 8192,(int)posZ + 8192);
        if(ratio > 1.0)
        {
            ratio = 1.0;
        }
    }

    float ber = harvester->getSpecExtraction();

    harvester->setCurrentExtractionRate(ber*ratio);

    // now enter the new resource in the hoppers resource list if its isnt already in there
    // TODO keep the list up to date by removing unnecessary resources
    // to this end read the list anew and delete every resource with zero amount
    // have a stored function do this

    if(!harvester->checkResourceList(resourceId))
    {
        //do *not* add to list - otherwise we get a racecondition with the asynch update from db !!!
        //harvester->getResourceList()->push_back(std::make_pair(resourceId,float(0.0)));
        //add to db
        mDatabase->executeSqlAsync(0,0,"INSERT INTO harvester_resources VALUES(%"PRIu64",%"PRIu64",0,0)",harvester->getId(),resourceId);
     
    }

    // update the current extractionrate in the db for the stored procedure handling the harvesting
    mDatabase->executeSqlAsync(0,0,"UPDATE harvesters SET rate=%f WHERE id=%"PRIu64" ",(ber*ratio),harvester->getId());
    

    //now send the updates
    gMessageLib->sendCurrentResourceUpdate(harvester,player);
    gMessageLib->sendCurrentExtractionRate(harvester,player);

}
Example #9
0
static Variant HHVM_FUNCTION(mysql_result, const Resource& result, int row,
                                    const Variant& field /* = 0 */) {
  auto res = php_mysql_extract_result(result);
  if (res == nullptr) return false;

  MYSQL_RES *mysql_result = nullptr;
  MYSQL_ROW sql_row = nullptr;
  unsigned long *sql_row_lengths = nullptr;

  if (res->isLocalized()) {
    if (!res->seekRow(row)) return false;
    if (!res->fetchRow()) return false;
  } else {
    mysql_result = res->get();
    if (row < 0 || row >= (int)mysql_num_rows(mysql_result)) {
      raise_warning("Unable to jump to row %d on MySQL result index %d",
                      row, result->o_getId());
      return false;
    }
    mysql_data_seek(mysql_result, row);

    sql_row = mysql_fetch_row(mysql_result);
    if (!sql_row) {
      return false;
    }
    sql_row_lengths = mysql_fetch_lengths(mysql_result);
    if (!sql_row_lengths) {
      return false;
    }
  }

  int field_offset = 0;
  if (!field.isNull()) {
    if (field.isString()) {
      String sfield = field.toString();
      const char *tmp = strchr(sfield.data(), '.');
      String table_name, field_name;
      if (tmp) {
        int pos = tmp - sfield.data();
        table_name = sfield.substr(0, pos);
        field_name = sfield.substr(pos + 1);
      } else {
        field_name = sfield;
      }

      int i = 0;
      bool found = false;
      res->seekField(0);
      while (i < res->getFieldCount()) {
        MySQLFieldInfo *info = res->getFieldInfo(i);
        if ((table_name.empty() || table_name.same(info->table)) &&
            field_name.same(info->name)) {
          field_offset = i;
          found = true;
          break;
        }
        i++;
      }
      if (!found) { /* no match found */
        raise_warning("%s%s%s not found in MySQL result index %d",
                        table_name.data(), (table_name.empty() ? "" : "."),
                        field_name.data(), result->o_getId());
        return false;
      }
    } else {
      field_offset = field.toInt32();
      if (field_offset < 0 ||
          field_offset >= (int)res->getFieldCount()) {
        raise_warning("Bad column offset specified");
        return false;
      }
    }
  }

  if (res->isLocalized()) {
    Variant f = res->getField(field_offset);
    if (!f.isNull()) {
      return f.toString();
    }
  } else {
    if (sql_row[field_offset]) {
      return String(sql_row[field_offset], sql_row_lengths[field_offset],
                    CopyString);
    }
  }
  return init_null();
}
plan_list* update_job(plan_job* job, int num_first_free_slot, first_free_slot **first_free_slots, plan_list* limits, plan_cluster* cluster)
  {
  plan_list* gaps_list;
  plan_gap* new_gap;
  time_t gap_start = -1;
  time_t gap_end = -1;
  node_info* considered_node;
  int cpu_index;
  int gap_usage;
  int job_cpu;
  int tmp_job_cpu;
  int attempt_count;
  int node_latest_cpu_index;
  int total_latest_cpu_index;
  int *tmp_cpu_arr;
  int plan_num_nodes;
  int wipe_fixed_nodes;
  int node_prohibited;
  int *node_ppn_free;
  Resource *res;
  
  int *first_free_slot_availability;
  first_free_slot_availability = (int*) malloc(num_first_free_slot * sizeof(int));

  if (job == NULL || first_free_slots == NULL)
    return NULL;

  /*
   * FIX NODES init
   */

    //je-li nejakej node NULL pak NULLuju vsechny
    wipe_fixed_nodes = 0;
    for (int k = 0; k < job -> req_num_nodes; k++)
      if (job -> fixed_nname_arr[k] == NULL)
        wipe_fixed_nodes = 1;

    if (wipe_fixed_nodes)
      for (int k = 0; k < job -> req_num_nodes; k++)
        if (job -> fixed_nname_arr[k] != NULL)
        {
        free(job -> fixed_nname_arr[k]);
        job -> fixed_nname_arr[k] = NULL;
        }

    if ((node_ppn_free = (int*)malloc(job -> req_num_nodes * sizeof(int))) == NULL)
      {
      perror("Memory Allocation Error");
      return NULL;
      }

    for (int k = 0; k < job -> req_num_nodes; k++)
      {
      node_ppn_free[k] = 1;
      }

  /*
   * first_free_slot_availability init
   *
   * -1 node down
   * -2 not enough CPUs on node
   * -3 not enough mem
   * -4 not enough available mem
   * -5 exception for available mem
   * -6 cpu already used for this job
   * -7 prohibited node
   */

  for (int i = 0; i < num_first_free_slot; i++)
    {
    if (first_free_slots[i] -> time == -1)
      {
      first_free_slot_availability[i] = -1;
      continue;
      }

    if (first_free_slots[i] -> ninfo -> get_avail_before() != 0 && first_free_slots[i] -> ninfo -> get_avail_before() < job->completion_time)
      {
      first_free_slot_availability[i] = -8;
      continue;
      }

    if (first_free_slots[i] -> ninfo->walltime_limit_min != 0 && first_free_slots[i] -> ninfo->walltime_limit_min > job->estimated_processing)
      {
      first_free_slot_availability[i] = -9;
      continue;
      }

    if (first_free_slots[i] -> ninfo->walltime_limit_max != 0 && first_free_slots[i] -> ninfo->walltime_limit_max < job->estimated_processing)
      {
      first_free_slot_availability[i] = -9;
      continue;
      }
        
    if (job->req_gpu > 0)
      {
      if ((res = first_free_slots[i] -> ninfo->get_resource("gpu")) == NULL)
        {
        first_free_slot_availability[i] = -9;
        continue;               
        }
            
      if (res->get_capacity() < job->req_gpu)
        {
        first_free_slot_availability[i] = -9;
        continue;                
        }                
      }

    // prohibited node is something like node down
    node_prohibited = 1;
    if (!job->jinfo->is_exclusive())
      if (!wipe_fixed_nodes)
        {
        for (int k = 0; k < job -> req_num_nodes; k++)
          if (strcmp(job -> fixed_nname_arr[k], first_free_slots[i] -> ninfo -> get_name()) == 0)
            node_prohibited = 0;

	  if (node_prohibited)
            {
            first_free_slot_availability[i] = -7;
            continue;
            }
	}

    if (job -> req_ppn > first_free_slots[i] -> ninfo -> get_cores_total())
      {
      first_free_slot_availability[i] = -2;
      continue;
      }

    if (job -> req_mem > first_free_slots[i] -> mem ||
        job -> req_scratch_local > first_free_slots[i] -> scratch_local)
      {
      first_free_slot_availability[i] = -3;
      continue;
      }

    if (job -> req_mem > first_free_slots[i] -> available_mem ||
	job -> req_scratch_local > first_free_slots[i] -> available_scratch_local)
      {
      first_free_slot_availability[i] = -4;
      continue;
      }

    first_free_slot_availability[i] = 0;
    }


  /*
   *
   * GapList creation
   *
   */
  gaps_list = list_create(Gaps);
  if ((tmp_cpu_arr = (int*)malloc(sizeof(int) * job -> req_ppn)) == NULL)
    {
    perror("Memory Allocation Error");
    return NULL;
    }

  /*
   * job initialization
   * and other init
   */

  considered_node = NULL;
  plan_num_nodes = 0;
  attempt_count = 1;
  gap_usage = 0;
  cpu_index = -1;
  total_latest_cpu_index = -1;
  node_latest_cpu_index = -1;

  job -> start_time = -1;
  job -> completion_time = -1;

  for (int i = 0; i < job -> usage; i++)
    job -> cpu_indexes[i] = -1;

  for (int i = 0; i < job -> req_num_nodes; i++)
    job -> latest_ncpu_index[i] = -1;

  /*
   * main while start
   * i=0!!!!!!!!
   */
  tmp_job_cpu = 0;
  job_cpu = 0;

  if (job->jinfo->is_exclusive())
    {
    considered_node = NULL;

    for (int excl_nodes_counter=0; excl_nodes_counter<job->req_num_nodes; excl_nodes_counter++)
      job -> start_time = find_earliest_node(excl_nodes_counter,job, num_first_free_slot, first_free_slots, first_free_slot_availability);

    if (job -> start_time == 7226578800)
      return NULL;

    for (int i = 0; i < num_first_free_slot; i++)
      for (int j = 0; j<job->req_num_nodes; j++)
        if (job -> ninfo_arr[j] == first_free_slots[i]->ninfo)
          if (job -> start_time < first_free_slots[i]->time)
            first_free_slots[i]->time = job -> start_time;

    job -> completion_time = job -> start_time + job -> estimated_processing;

    int index_counter=0;
    int ppn_counter;
    for (int excl_nodes_counter=0; excl_nodes_counter<job->req_num_nodes; excl_nodes_counter++)
      {
      ppn_counter = 0;
      for (int i = 0; i < num_first_free_slot; i++)
        if (job->ninfo_arr[excl_nodes_counter]==first_free_slots[i]->ninfo && ppn_counter < job->req_ppn && index_counter< job->usage)
          {
          job->cpu_indexes[index_counter]=i;
          index_counter++;
          ppn_counter++;
	  }
      }
    }

  if (!job->jinfo->is_exclusive())
    while (job_cpu < job -> usage)
      {
      //pokud najdu nejdrivejsi procesor nastavim mu first_free_slot_availability na true
      cpu_index = ith_smallest(considered_node,
                               attempt_count,
                               first_free_slots,
                               num_first_free_slot,
                               first_free_slot_availability,
                               node_latest_cpu_index,
                               total_latest_cpu_index);

      //ith_smallest failed
      if (cpu_index==-1)
      {
      /*
      sched_log(PBSEVENT_DEBUG2, PBS_EVENTCLASS_REQUEST, "ith smallest cpu not found!!!", "%d, latest_cpu_index: %d, attempt_count: %d",job -> job_id, node_latest_cpu_index, attempt_count);
      sched_log(PBSEVENT_DEBUG2, PBS_EVENTCLASS_REQUEST, job -> jinfo -> name, "req_nodes: %ld req_ppn: %d req_mem: %ld",job -> req_num_nodes, job -> req_ppn, job -> req_mem);
      for (int m = 0; m < job -> req_num_nodes; m++)
        if (job -> fixed_nname_arr[m] == NULL)
          sched_log(PBSEVENT_DEBUG2, PBS_EVENTCLASS_REQUEST, job -> jinfo -> name, "fixednode: null");
        else
          sched_log(PBSEVENT_DEBUG2, PBS_EVENTCLASS_REQUEST, job -> jinfo -> name, "fixednode: %s", job -> fixed_nname_arr[m]);
      log_print_ffms(first_free_slots,num_first_free_slot);
      log_print_ffnot(first_free_slot_availability, num_first_free_slot);
      */
            
      if (job -> fixed_nname_arr[0] != NULL)
        {
        free(job -> fixed_nname_arr[0]);
        job -> fixed_nname_arr[0] = NULL;
        }
      free(tmp_cpu_arr);

      return NULL;
      }

      if (considered_node != NULL && considered_node != first_free_slots[cpu_index] -> ninfo)
        {
        job_cpu = plan_num_nodes * job -> req_ppn;
        first_free_slot_availability[cpu_index] = ++attempt_count;
        }

      considered_node = first_free_slots[cpu_index] -> ninfo;
      /*
      if (job->jinfo->is_exclusive)
        {
        job->original_req_ppn = job->req_ppn;
        job->req_ppn=considered_node->get_cores_total();
        }
      */

      /*
       * k tomuto by nemelo dochazet moc casto: kvuli vyjimkam zpusobene pameti je mozne ze indexy nebudou serazeny od nejdrivejsiho dostupneho
       * zajistim vlozeni na spravne misto jinak se mohou chybne vytvorit diry a nastavit spatny starttime
       *
       */
      tmp_job_cpu = job_cpu;
      while (tmp_job_cpu > 0 && first_free_slots[job -> cpu_indexes[tmp_job_cpu - 1]] -> time > first_free_slots[cpu_index] -> time)
        {
        job -> cpu_indexes[tmp_job_cpu] = job -> cpu_indexes[tmp_job_cpu - 1];
        tmp_job_cpu--;
        }
      job -> cpu_indexes[tmp_job_cpu] = cpu_index;

      if (node_latest_cpu_index != -1 && first_free_slots[node_latest_cpu_index] -> time <= first_free_slots[cpu_index] -> time)
        node_latest_cpu_index = cpu_index;

      if (node_latest_cpu_index == -1)
        node_latest_cpu_index = cpu_index;

      if (total_latest_cpu_index != -1 && first_free_slots[total_latest_cpu_index] -> time <= first_free_slots[cpu_index] -> time)
        total_latest_cpu_index = cpu_index;

      if (total_latest_cpu_index == -1)
        total_latest_cpu_index = cpu_index;

      tmp_cpu_arr[job_cpu - plan_num_nodes * job -> req_ppn] = cpu_index;

      //ppn nalezeno oznacit aby se uz nepouzilo a jdem na dalsi ppn
      if (job_cpu + 1 == (plan_num_nodes + 1) * job -> req_ppn)
        {
        //do start_time dame index s poslednim starttimem
        job -> start_time = first_free_slots[job -> cpu_indexes[job_cpu]] -> time;
        job -> completion_time = job -> start_time + job -> estimated_processing;
        job -> ninfo_arr[plan_num_nodes] = considered_node;
        job -> latest_ncpu_index[plan_num_nodes] = node_latest_cpu_index;

	for (int i = 0; i < job -> req_ppn; i++)
          first_free_slot_availability[tmp_cpu_arr[i]] = -6;
        
        if (wipe_fixed_nodes)
	  {
          job -> fixed_nname_arr[plan_num_nodes] = strdup(considered_node -> get_name());
          }
        else 
          {
	  //uzel bude pouzit, pokud je to naposled co muze byt pouzit, tak zbytek zakazat
          int not_anymore;
          not_anymore = 0;
          for (int k = 0; k < job -> req_num_nodes; k++)
            if (node_ppn_free[k] == 1 && strcmp(job -> fixed_nname_arr[k], considered_node -> get_name()) == 0)
              {
              if (not_anymore == 1 && !job->jinfo->is_exclusive())
                {//kdzy tu jsem podruhe tak sem job budu moc dat jeste jednou, nezakazovat jeste tenhle uzel
                not_anymore = 0;
                break;
                }
              not_anymore = 1;
              node_ppn_free[k] = 0;
              }

          if (not_anymore == 1)
            for (int i = 0; i < num_first_free_slot; i++)
              if (first_free_slots[i] -> ninfo == considered_node && first_free_slot_availability[i] != -6)
                first_free_slot_availability[i] = -7;
	  }

        considered_node = NULL;

        if (job->jinfo->is_exclusive() && job->original_req_ppn != 0)
          {
          job->req_ppn = job->original_req_ppn;
          job->original_req_ppn=0;
          }

        node_latest_cpu_index = -1;
        plan_num_nodes++;
        }
      job_cpu++;
      }

  if (job->jinfo->is_exclusive() && job->original_req_ppn != 0)
    {
    job->req_ppn = job->original_req_ppn;
    job->original_req_ppn=0;
    }

/*
 * main while ended
 *
 */

  adjust_job_starttime_according_to_limits(limits, job, cluster);

  /*
  for (i=0; i < num_first_free_slot; i++)
    if (first_free_slots[i] -> time != -1)
      first_free_slot_availability[i] = 0;
  */

  /*
   * new gaps creation
   */

  gap_usage = 0;
  cpu_index = -1;
  gap_start = -1;
  gap_end = -1;
  job -> run_me = 1;
  job_cpu = 0;
  if (job->jinfo->is_exclusive())
    {
    int excl_index_num = 0;
    if (job->cpu_indexes != NULL)
      free(job->cpu_indexes);

    if ((job->cpu_indexes = (int*)malloc(num_first_free_slot * sizeof(int))) == NULL)
      {
      perror("Memory Allocation Error");
      return NULL;
      }

    for (int i = 0; i < num_first_free_slot; i++)
      {
      for (int j = 0; j < job->req_num_nodes; j++)
        if (first_free_slots[i]->ninfo == job->ninfo_arr[j])
          {
          int tmp_index=excl_index_num;
          while (tmp_index > 0 && first_free_slots[job->cpu_indexes[tmp_index-1]]->time > first_free_slots[i]->time)
            {
            job->cpu_indexes[tmp_index]=job->cpu_indexes[tmp_index-1];
            tmp_index--;
            }

          job->cpu_indexes[tmp_index]=i;
          excl_index_num++;
	  }
      }

    job->usage = excl_index_num;

    for (int i = 0; i < excl_index_num; i++)
      {
      cpu_index = job->cpu_indexes[i];

      //nastavime zda muze byt job spusten...
      if (first_free_slots[cpu_index] -> free_to_run == 0)
        job -> run_me = 0;

      first_free_slots[cpu_index] -> free_to_run = 0;

      if (gap_start == -1)
	gap_start = first_free_slots[cpu_index] -> time;

      if (gap_start != first_free_slots[cpu_index] -> time)
        {
        gap_end = first_free_slots[cpu_index] -> time;
        new_gap = (plan_gap*) list_add_end(gaps_list, gap_fillin((plan_gap*) NULL, gap_start, gap_end, gap_end - gap_start, gap_usage, job, (plan_gap*)NULL, (plan_gap*)NULL));
        new_gap -> nodes_memory = gap_memory_create(new_gap, job, first_free_slots);
        gap_start = first_free_slots[cpu_index] -> time;
        }

      gap_usage++;
      job_cpu++;
      }
    }

  if (!job->jinfo->is_exclusive())
    while (job_cpu < job -> usage)
      {
      cpu_index = job -> cpu_indexes[job_cpu];

      //nastavime zda muze byt job spusten...
      if (first_free_slots[cpu_index] -> free_to_run == 0)
        job -> run_me = 0;

      first_free_slots[cpu_index] -> free_to_run = 0;

      if (gap_start == -1)
        gap_start = first_free_slots[cpu_index] -> time;

      if (gap_start != first_free_slots[cpu_index] -> time)
        {
        gap_end = first_free_slots[cpu_index] -> time;
        new_gap = (plan_gap*) list_add_end(gaps_list, gap_fillin((plan_gap*) NULL, gap_start, gap_end, gap_end - gap_start, gap_usage, job, (plan_gap*)NULL, (plan_gap*)NULL));
        new_gap -> nodes_memory = gap_memory_create(new_gap, job, first_free_slots);
        gap_start = first_free_slots[cpu_index] -> time;
        }

      gap_usage++;
      job_cpu++;
      }

  if (job->jinfo->is_exclusive())
    first_free_slots_update_exclusive(job, num_first_free_slot, first_free_slots);

  if (!job->jinfo->is_exclusive())
    first_free_slots_update(job, first_free_slots);

  free(tmp_cpu_arr);
  free(node_ppn_free);
  free(first_free_slot_availability);
  return gaps_list;
  }
Example #11
0
void UndoRedo::_process_operation_list(List<Operation>::Element *E) {

	for (; E; E = E->next()) {

		Operation &op = E->get();

		Object *obj = ObjectDB::get_instance(op.object);
		if (!obj) {
			//corruption
			clear_history();
			ERR_FAIL_COND(!obj);
		}

		switch (op.type) {

			case Operation::TYPE_METHOD: {

				Vector<const Variant *> argptrs;
				argptrs.resize(VARIANT_ARG_MAX);
				int argc = 0;

				for (int i = 0; i < VARIANT_ARG_MAX; i++) {
					if (op.args[i].get_type() == Variant::NIL) {
						break;
					}
					argptrs.write[i] = &op.args[i];
					argc++;
				}
				argptrs.resize(argc);

				Variant::CallError ce;
				obj->call(op.name, (const Variant **)argptrs.ptr(), argc, ce);
				if (ce.error != Variant::CallError::CALL_OK) {
					ERR_PRINTS("Error calling method from signal '" + String(op.name) + "': " + Variant::get_call_error_text(obj, op.name, (const Variant **)argptrs.ptr(), argc, ce));
				}
#ifdef TOOLS_ENABLED
				Resource *res = Object::cast_to<Resource>(obj);
				if (res)
					res->set_edited(true);

#endif

				if (method_callback) {
					method_callback(method_callbck_ud, obj, op.name, VARIANT_ARGS_FROM_ARRAY(op.args));
				}
			} break;
			case Operation::TYPE_PROPERTY: {

				obj->set(op.name, op.args[0]);
#ifdef TOOLS_ENABLED
				Resource *res = Object::cast_to<Resource>(obj);
				if (res)
					res->set_edited(true);
#endif
				if (property_callback) {
					property_callback(prop_callback_ud, obj, op.name, op.args[0]);
				}
			} break;
			case Operation::TYPE_REFERENCE: {
				//do nothing
			} break;
		}
	}
}
// Removes resources allocated to a job from the res pool....
bool resPtrEQ(const Resource &lhs, const boost::shared_ptr<Resource> &rhs) {
  return lhs.getId() == rhs->getId();
}
Example #13
0
template<UnsignedInt dimensions> void BoxRenderer<dimensions>::draw(Resource<ShapeRendererOptions>& options, const MatrixTypeFor<dimensions, Float>& projectionMatrix) {
    AbstractBoxRenderer<dimensions>::wireframeShader->setTransformationProjectionMatrix(projectionMatrix*box.transformation())
        .setColor(options->color());
    AbstractBoxRenderer<dimensions>::wireframeMesh->draw(*AbstractBoxRenderer<dimensions>::wireframeShader);
}
Example #14
0
bool TouchExtensionGlobal::postTouchEvent(QTouchEvent *event, QWaylandView *view)
{
    const QList<QTouchEvent::TouchPoint> points = event->touchPoints();
    const int pointCount = points.count();
    if (!pointCount)
        return false;

    wl_client *surfaceClient = view->surface()->client()->client();
    uint32_t time = m_compositor->currentTimeMsecs();
    const int rescount = m_resources.count();

    for (int res = 0; res < rescount; ++res) {
        Resource *target = m_resources.at(res);
        if (target->client() != surfaceClient)
            continue;

        // We will use no touch_frame type of event, to reduce the number of
        // events flowing through the wire. Instead, the number of points sent is
        // included in the touch point events.
        int sentPointCount = 0;
        for (int i = 0; i < pointCount; ++i) {
            if (points.at(i).state() != Qt::TouchPointStationary)
                ++sentPointCount;
        }

        for (int i = 0; i < pointCount; ++i) {
            const QTouchEvent::TouchPoint &tp(points.at(i));
            // Stationary points are never sent. They are cached on client side.
            if (tp.state() == Qt::TouchPointStationary)
                continue;

            uint32_t id = tp.id();
            uint32_t state = (tp.state() & 0xFFFF) | (sentPointCount << 16);
            uint32_t flags = (tp.flags() & 0xFFFF) | (int(event->device()->capabilities()) << 16);

            int x = toFixed(tp.pos().x());
            int y = toFixed(tp.pos().y());
            int nx = toFixed(tp.normalizedPos().x());
            int ny = toFixed(tp.normalizedPos().y());
            int w = toFixed(tp.rect().width());
            int h = toFixed(tp.rect().height());
            int vx = toFixed(tp.velocity().x());
            int vy = toFixed(tp.velocity().y());
            uint32_t pressure = uint32_t(tp.pressure() * 255);

            QByteArray rawData;
            QVector<QPointF> rawPosList = tp.rawScreenPositions();
            int rawPosCount = rawPosList.count();
            if (rawPosCount) {
                rawPosCount = qMin(maxRawPos, rawPosCount);
                QVector<float>::iterator iter = m_posData.begin();
                for (int rpi = 0; rpi < rawPosCount; ++rpi) {
                    const QPointF &rawPos(rawPosList.at(rpi));
                    // This will stay in screen coordinates for performance
                    // reasons, clients using this data will presumably know
                    // what they are doing.
                    *iter++ = static_cast<float>(rawPos.x());
                    *iter++ = static_cast<float>(rawPos.y());
                }
                rawData = QByteArray::fromRawData(reinterpret_cast<const char*>(m_posData.constData()), sizeof(float) * rawPosCount * 2);
            }

            send_touch(target->handle,
                       time, id, state,
                       x, y, nx, ny, w, h,
                       pressure, vx, vy,
                       flags, rawData);
        }

        return true;
    }

    return false;
}
Example #15
0
 ResourceIdEqualPred(const Resource &res) : id(res.get_id()) {}
Example #16
0
bool ODFItem::setFileId(const QHash<QString, quint64> &names, const QString& value, quint64 &fileid) const {
    if ( value == sUNDEF) {
        fileid = i64UNDEF;
        return true; // legal; some properties might not have a value(name)
    }
    if ( Ilwis3Connector::ilwisType(value) & itCOORDSYSTEM) {
        if ( value == "latlonwgs84.csy" ) {
            Resource resource = mastercatalog()->name2Resource("code=epsg:4326", itCOORDSYSTEM);
            if ( !resource.isValid()) {
               return ERROR1(ERR_FIND_SYSTEM_OBJECT_1, "Wgs 84");
            }
            fileid = resource.id();
            return true;
        }
        if ( value == "unknown.csy" ) {
            Resource resource = mastercatalog()->name2Resource("code=csy:unknown", itCOORDSYSTEM);
            if ( !resource.isValid()) {
                return ERROR1(ERR_FIND_SYSTEM_OBJECT_1, "'Unknown' coordinate system");
            }
            fileid = resource.id();
            return true;
        }
    }
    if ( Ilwis3Connector::ilwisType(value) & itGEOREF) {
        if ( value == "none.grf" ) {
            Resource resource = mastercatalog()->name2Resource("code=georef:undetermined", itGEOREF);
            if ( !resource.isValid()) {
                return ERROR1(ERR_FIND_SYSTEM_OBJECT_1, "'undetermined' georeference");
            }
            fileid = resource.id();
            return true;
        }
    }
    QString completeName =  (value.contains(QRegExp("\\\\|/"))) ? value : _odf.fileInfo().canonicalPath() + "/" + value;
    QHash<QString, quint64>::const_iterator iter = names.find(completeName.toLower());
    if (iter != names.end()){
        fileid = iter.value();
    } else {
        // at this time we can't rely on the working catalog to be set(if we are initializing it), so no normal resolve
        // the mastercatalog will contain system items at this moment so we can check these first
        QString baseName = value.left(value.indexOf("."));
        IlwisTypes tp = Ilwis3Connector::ilwisType(value);
        Resource resource = mastercatalog()->name2Resource(baseName, tp);
        if ( resource.isValid()) {
            fileid = resource.id();
        } else {
            QUrl url = QUrl::fromLocalFile(completeName);
            fileid = mastercatalog()->url2id(url, tp);
            if ( fileid == i64UNDEF) {
                kernel()->issues()->log(TR(ERR_MISSING_1).arg(completeName));
                fileid = i64UNDEF;
                return false;
            }
        }
    }
    return true;

}
Example #17
0
 bool operator()(const Resource &res) const {
     return res.get_id() == id;
 } 
Example #18
0
void Inter_v6::o6_loadCursor(OpFuncParams &params) {
	int16 id = _vm->_game->_script->readInt16();

	if ((id == -1) || (id == -2)) {
		char file[10];

		if (id == -1) {
			for (int i = 0; i < 9; i++)
				file[i] = _vm->_game->_script->readChar();
		} else
			strncpy(file, GET_VAR_STR(_vm->_game->_script->readInt16()), 10);

		file[9] = '\0';

		uint16 start = _vm->_game->_script->readUint16();
		int8 index = _vm->_game->_script->readInt8();

		VideoPlayer::Properties props;

		props.sprite = -1;

		int vmdSlot = _vm->_vidPlayer->openVideo(false, file, props);
		if (vmdSlot == -1) {
			warning("Can't open video \"%s\" as cursor", file);
			return;
		}

		int16 framesCount = _vm->_vidPlayer->getFrameCount(vmdSlot);

		for (int i = 0; i < framesCount; i++) {
			props.startFrame   = i;
			props.lastFrame    = i;
			props.waitEndFrame = false;

			_vm->_vidPlayer->play(vmdSlot, props);
			_vm->_vidPlayer->copyFrame(vmdSlot, *_vm->_draw->_cursorSprites,
					0, 0, _vm->_draw->_cursorWidth, _vm->_draw->_cursorWidth,
					(start + i) * _vm->_draw->_cursorWidth, 0);
		}

		_vm->_vidPlayer->closeVideo(vmdSlot);

		_vm->_draw->_cursorAnimLow[index] = start;
		_vm->_draw->_cursorAnimHigh[index] = framesCount + start - 1;
		_vm->_draw->_cursorAnimDelays[index] = 10;

		return;
	}

	int8 index = _vm->_game->_script->readInt8();

	if ((index * _vm->_draw->_cursorWidth) >= _vm->_draw->_cursorSprites->getWidth())
		return;

	Resource *resource = _vm->_game->_resources->getResource((uint16) id);
	if (!resource)
		return;

	_vm->_draw->_cursorSprites->fillRect(index * _vm->_draw->_cursorWidth, 0,
			index * _vm->_draw->_cursorWidth + _vm->_draw->_cursorWidth - 1,
			_vm->_draw->_cursorHeight - 1, 0);

	_vm->_video->drawPackedSprite(resource->getData(),
			resource->getWidth(), resource->getHeight(),
			index * _vm->_draw->_cursorWidth, 0, 0, *_vm->_draw->_cursorSprites);
	_vm->_draw->_cursorAnimLow[index] = 0;

	delete resource;
}
	TestApplicationClient(){
		string user("postgres");
		string rmHost("localhost");
		string rmPort("8032");
		string tokenService = "";
		Yarn::Config config;
		Yarn::Internal::SessionConfig sessionConfig(config);
		MockApplicationClientProtocol *protocol = new MockApplicationClientProtocol(user,rmHost,rmPort,tokenService, sessionConfig);

		ApplicationId appId;
		appId.setId(100);
		appId.setClusterTimestamp(1454307175682);
		GetNewApplicationResponse getNewApplicationResponse;
		getNewApplicationResponse.setApplicationId(appId);
		EXPECT_CALL((*protocol),getNewApplication(_)).Times(AnyNumber()).WillOnce(Return(getNewApplicationResponse));
		EXPECT_CALL((*protocol),submitApplication(_)).Times(AnyNumber()).WillOnce(Return());

		ApplicationReport appReport;
		appReport.setApplicationId(appId);
		appReport.setUser(user);
		string queue("default");
		string appName("hawq");
		string hostname("master");
		appReport.setQueue(queue);
		appReport.setName(appName);
		appReport.setHost(hostname);
		appReport.setRpcPort(8090);
		appReport.setProgress(0.5);
		GetApplicationReportResponse appReportResponse;
		appReportResponse.setApplicationReport(appReport);
		EXPECT_CALL((*protocol),getApplicationReport(_)).Times(AnyNumber()).WillOnce(Return(appReportResponse));

		ContainerId containerId;
		containerId.setId(501);
		containerId.setApplicationId(appId);
		Resource resource;
		resource.setMemory(1024);
		resource.setVirtualCores(1);
		Priority priority;
		priority.setPriority(1);
		ContainerReport report;
		report.setId(containerId);
		report.setResource(resource);
		report.setPriority(priority);
		list<ContainerReport> reportList;
		reportList.push_back(report);
		GetContainersResponse getContainersResponse;
		getContainersResponse.setContainersReportList(reportList);
		EXPECT_CALL((*protocol),getContainers(_)).Times(AnyNumber()).WillOnce(Return(getContainersResponse));

		NodeId nodeId;
		string nodeHost("node1");
		nodeId.setHost(nodeHost);
		nodeId.setPort(9983);
		NodeReport nodeReport;
		nodeReport.setNodeId(nodeId);
		string rackName("default-rack");
		nodeReport.setRackName(rackName);
		nodeReport.setNumContainers(8);
		Resource nodeResource;
		nodeResource.setMemory(2048*8);
		nodeResource.setVirtualCores(8);
		nodeReport.setResourceCapablity(nodeResource);
		nodeReport.setNodeState(NodeState::NS_RUNNING);
		list<NodeReport> nodeReportList;
		nodeReportList.push_back(nodeReport);
		GetClusterNodesResponse getClusterNodesResponse;
		getClusterNodesResponse.setNodeReports(nodeReportList);
		EXPECT_CALL((*protocol),getClusterNodes(_)).Times(AnyNumber()).WillOnce(Return(getClusterNodesResponse));

		QueueInfo queueInfo;
		queueInfo.setQueueName(queue);
		queueInfo.setCapacity(0.67);
		queueInfo.setMaximumCapacity(0.95);
		queueInfo.setCurrentCapacity(0.5);
		queueInfo.setQueueState(QueueState::Q_RUNNING);
		QueueInfo childQueue;
		string childQueueName("hawq-queue");
		childQueue.setQueueName(childQueueName);
		childQueue.setCapacity(0.33);
		childQueue.setMaximumCapacity(0.5);
		childQueue.setCurrentCapacity(0.25);
		list<QueueInfo> childQueueList;
		childQueueList.push_back(childQueue);
		queueInfo.setChildQueues(childQueueList);
		list<ApplicationReport> appReportList;
		appReportList.push_back(appReport);
		queueInfo.setApplicationReports(appReportList);
		GetQueueInfoResponse getQueueInfoResponse;
		getQueueInfoResponse.setQueueInfo(queueInfo);
		EXPECT_CALL((*protocol),getQueueInfo(_)).Times(AnyNumber()).WillOnce(Return(getQueueInfoResponse));

		KillApplicationResponseProto killApplicationResponseProto;
		EXPECT_CALL((*protocol),forceKillApplication(_)).Times(AnyNumber()).WillOnce(Return(KillApplicationResponse(killApplicationResponseProto)));

		YarnClusterMetrics metrics;
		metrics.setNumNodeManagers(10);
		GetClusterMetricsResponse clusterMetricsResponse;
		clusterMetricsResponse.setClusterMetrics(metrics);
		EXPECT_CALL((*protocol),getClusterMetrics(_)).Times(AnyNumber()).WillOnce(Return(clusterMetricsResponse));

		GetApplicationsResponse applicationsResponse;
		applicationsResponse.setApplicationList(appReportList);
		EXPECT_CALL((*protocol),getApplications(_)).Times(AnyNumber()).WillOnce(Return(applicationsResponse));

		QueueUserACLInfo aclInfo;
		aclInfo.setQueueName(queue);
		list<QueueACL> queueACLList;
		QueueACL acl1 = QueueACL::QACL_ADMINISTER_QUEUE;
		QueueACL acl2 = QueueACL::QACL_SUBMIT_APPLICATIONS;
		queueACLList.push_back(acl1);
		queueACLList.push_back(acl2);
		aclInfo.setUserAcls(queueACLList);
		list<QueueUserACLInfo> aclInfoList;
		aclInfoList.push_back(aclInfo);
		GetQueueUserAclsInfoResponse queueUserAclsInfoResponse;
		queueUserAclsInfoResponse.setUserAclsInfoList(aclInfoList);
		EXPECT_CALL((*protocol),getQueueAclsInfo(_)).Times(AnyNumber()).WillOnce(Return(queueUserAclsInfoResponse));

		client = new ApplicationClient(protocol);
	}
Example #20
0
bool SipDialogMonitor::addExtension(UtlString& groupName, Url& contactUrl)
{
   bool result = false;
   mLock.acquire();
   
   // Check whether the group has already existed. If not, create one.
   SipResourceList* list = dynamic_cast <SipResourceList *> (mMonitoredLists.findValue(&groupName));
   if (list == NULL)
   {
      UtlString* listName = new UtlString(groupName);
      list = new SipResourceList((UtlBoolean)TRUE, listName->data(), DIALOG_EVENT_TYPE);
      
      mMonitoredLists.insertKeyAndValue(listName, list);
      OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::addExtension insert listName %s and object %p to the resource list",
                    groupName.data(), list);   
   }

   // Check whether the contact has already being added to the group
   UtlString resourceId;
   contactUrl.getIdentity(resourceId);
   Resource* resource = list->getResource(resourceId);
   if (resource == NULL)
   {
      resource = new Resource(resourceId);
      
      UtlString userName;
      contactUrl.getDisplayName(userName);
      resource->setName(userName);
      
      UtlString id;
      NetMd5Codec::encode(resourceId, id);
      resource->setInstance(id, STATE_PENDIND);
      list->insertResource(resource);
      
      // Send out the SUBSCRIBE
      OsSysLog::add(FAC_LOG, PRI_DEBUG,
                    "SipDialogMonitor::addExtension Sending out the SUBSCRIBE to contact %s",
                    resourceId.data());

      UtlString toUrl;
      contactUrl.toString(toUrl);
      
      UtlString fromUri = "dialogMonitor@" + mDomainName;
      UtlString dialogHandle;
            
      UtlBoolean status = mpSipSubscribeClient->addSubscription(resourceId.data(),
                                                                DIALOG_EVENT_TYPE,
                                                                fromUri.data(),
                                                                toUrl.data(),
                                                                mContact.data(),
                                                                mRefreshTimeout,
                                                                (void *) this,
                                                                SipDialogMonitor::subscriptionStateCallback,
                                                                SipDialogMonitor::notifyEventCallback,
                                                                dialogHandle);
               
      if (!status)
      {
         result = false;
         OsSysLog::add(FAC_LOG, PRI_ERR,
                       "SipDialogMonitor::addExtension Subscription failed to contact %s.",
                       resourceId.data());
      }
      else
      {
         mDialogHandleList.insertKeyAndValue(new UtlString(resourceId), new UtlString(dialogHandle));
         OsSysLog::add(FAC_SIP, PRI_DEBUG,
                       "SipDialogMonitor::addExtension Added dialogHandle: %s",
                       dialogHandle.data());
         result = true;
      }
   }
   else
   {
      OsSysLog::add(FAC_LOG, PRI_WARNING,
                    "SipDialogMonitor::addExtension contact %s already exists.",
                    resourceId.data());
   }

   list->buildBody();
   
   mLock.release();
   return result;
}
TEST(RawResourceTest, RevalidationSucceededUpdateHeaders)
{
    Resource* resource = RawResource::create(ResourceRequest("data:text/html,"), Resource::Raw);
    ResourceResponse response;
    response.setHTTPStatusCode(200);
    response.addHTTPHeaderField("keep-alive", "keep-alive value");
    response.addHTTPHeaderField("expires", "expires value");
    response.addHTTPHeaderField("last-modified", "last-modified value");
    response.addHTTPHeaderField("proxy-authenticate", "proxy-authenticate value");
    response.addHTTPHeaderField("proxy-connection", "proxy-connection value");
    response.addHTTPHeaderField("x-custom", "custom value");
    resource->responseReceived(response, nullptr);
    resource->finish();
    memoryCache()->add(resource);

    // Simulate a successful revalidation.
    resource->setRevalidatingRequest(ResourceRequest("data:text/html,"));

    // Validate that these headers pre-update.
    EXPECT_EQ("keep-alive value", resource->response().httpHeaderField("keep-alive"));
    EXPECT_EQ("expires value", resource->response().httpHeaderField("expires"));
    EXPECT_EQ("last-modified value", resource->response().httpHeaderField("last-modified"));
    EXPECT_EQ("proxy-authenticate value", resource->response().httpHeaderField("proxy-authenticate"));
    EXPECT_EQ("proxy-authenticate value", resource->response().httpHeaderField("proxy-authenticate"));
    EXPECT_EQ("proxy-connection value", resource->response().httpHeaderField("proxy-connection"));
    EXPECT_EQ("custom value", resource->response().httpHeaderField("x-custom"));

    Persistent<DummyClient> client = new DummyClient;
    resource->addClient(client.get());

    // Perform a revalidation step.
    ResourceResponse revalidatingResponse;
    revalidatingResponse.setHTTPStatusCode(304);
    // Headers that aren't copied with an 304 code.
    revalidatingResponse.addHTTPHeaderField("keep-alive", "garbage");
    revalidatingResponse.addHTTPHeaderField("expires", "garbage");
    revalidatingResponse.addHTTPHeaderField("last-modified", "garbage");
    revalidatingResponse.addHTTPHeaderField("proxy-authenticate", "garbage");
    revalidatingResponse.addHTTPHeaderField("proxy-connection", "garbage");
    // Header that is updated with 304 code.
    revalidatingResponse.addHTTPHeaderField("x-custom", "updated");
    resource->responseReceived(revalidatingResponse, nullptr);

    // Validate the original response.
    EXPECT_EQ(200, resource->response().httpStatusCode());

    // Validate that these headers are not updated.
    EXPECT_EQ("keep-alive value", resource->response().httpHeaderField("keep-alive"));
    EXPECT_EQ("expires value", resource->response().httpHeaderField("expires"));
    EXPECT_EQ("last-modified value", resource->response().httpHeaderField("last-modified"));
    EXPECT_EQ("proxy-authenticate value", resource->response().httpHeaderField("proxy-authenticate"));
    EXPECT_EQ("proxy-authenticate value", resource->response().httpHeaderField("proxy-authenticate"));
    EXPECT_EQ("proxy-connection value", resource->response().httpHeaderField("proxy-connection"));
    EXPECT_EQ("updated", resource->response().httpHeaderField("x-custom"));

    memoryCache()->remove(resource);

    resource->removeClient(client);
    EXPECT_FALSE(resource->hasClientsOrObservers());
    EXPECT_FALSE(client->called());
    EXPECT_EQ(0u, client->data().size());
}
Example #22
0
void SipDialogMonitor::publishContent(UtlString& contact, SipDialogEvent* dialogEvent)
{
   bool contentChanged;
   
   // Loop through all the resource lists
   UtlHashMapIterator iterator(mMonitoredLists);
   UtlString* listUri;
   SipResourceList* list;
   Resource* resource;
   UtlString id, state;
   while (listUri = dynamic_cast <UtlString *> (iterator()))
   {
      contentChanged = false;
      
      list = dynamic_cast <SipResourceList *> (mMonitoredLists.findValue(listUri));
      OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipDialogMonitor::publishContent listUri %s list %p",
                    listUri->data(), list); 

      // Search for the contact in this list
      resource = list->getResource(contact);
      if (resource)
      {
         resource->getInstance(id, state);
         
         if (dialogEvent->isEmpty())
         {
            resource->setInstance(id, STATE_TERMINATED);
         }
         else
         {
            Dialog* dialog = dialogEvent->getFirstDialog();
            
            UtlString state, event, code;
            dialog->getState(state, event, code);
            
            if (state.compareTo(STATE_TERMINATED) == 0)
            {
               resource->setInstance(id, STATE_TERMINATED);
            }
            else
            {     
               resource->setInstance(id, STATE_ACTIVE);
            }
         }
         
         list->buildBody();
         contentChanged = true;
      }
      
      if (contentChanged)
      {
         int numOldContents;
         HttpBody* oldContent[1];           
   
         // Publish the content to the subscribe server
         if (!mSipPublishContentMgr.publish(listUri->data(), DIALOG_EVENT_TYPE, DIALOG_EVENT_TYPE, 1, (HttpBody**)&list, 1, numOldContents, oldContent))
         {
            UtlString dialogContent;
            int length;
            
            list->getBytes(&dialogContent, &length);
            OsSysLog::add(FAC_SIP, PRI_ERR, "SipDialogMonitor::publishContent DialogEvent %s\n was not successfully published to the subscribe server",
                          dialogContent.data());
         }
      }
   }
}
Example #23
0
// Weapon Update
void Weapon::Update(float aStep)
{
	// get controller
	const Controller *controller = Database::controller.Get(mControlId);
	if (!controller)
		return;

	// advance fire timer
	mTimer += aStep;

	// get template data
	const WeaponTemplate &weapon = Database::weapontemplate.Get(mId);

	// get trigger value
	float fire = controller->mFire[mChannel];
	bool trigger;
	switch (weapon.mTrigger)
	{
	default:
	case WeaponTemplate::TRIGGER_HOLD: trigger = fire != 0; break;
	case WeaponTemplate::TRIGGER_PRESS: trigger = fire != 0 && mPrevFire == 0; break;
	case WeaponTemplate::TRIGGER_RELEASE: trigger = fire == 0 && mPrevFire != 0; break;
	}
	mPrevFire = fire;

	// if triggered...
	if (trigger)
	{
		// if not busy
		if (mBurst <= 0 && mTimer > -0.001f && (!weapon.mTrack || mTrack < weapon.mTrack))
		{
			// if firing on this phase...
			if (mPhase == 0)
			{
				Resource *resource = NULL;

				// if using ammo
				if (weapon.mCost)
				{
					// ammo resource (if any)
					resource = Database::resource.Get(mAmmo).Get(weapon.mType);
				}

				// if enough ammo...
				if (!resource || weapon.mCost <= resource->GetValue())
				{
					// deduct ammo
					if (resource)
						resource->Add(mId, -weapon.mCost);

					// start a new burst
					mTimer -= weapon.mBurstStart;
					mBurst = weapon.mBurstLength;
				}
				else
				{
					// start "empty" sound cue
					PlaySoundCue(mId, 0x18a7beee /* "empty" */);
				}

				// wrap around
				mPhase = weapon.mCycle - 1;
			}
			else
			{
				// advance phase
				--mPhase;

				// wait for next phase
				mTimer -= weapon.mDelay / weapon.mCycle;
			}
		}
	}

	// if ready to fire...
	while (mBurst > 0 && mTimer > -0.001f && (!weapon.mTrack || mTrack < weapon.mTrack))
	{
		// deduct a burst
		--mBurst;

		// get the entity
		Entity *entity = Database::entity.Get(mId);

		// start the "fire" sound cue
		PlaySoundCue(mId, 0x8eab16d9 /* "fire" */);

		// interpolated transform
		Transform2 basetransform(entity->GetInterpolatedTransform(mTimer / aStep));

		for (int salvo = 0; salvo < weapon.mSalvoShots; ++salvo)
		{
			// get local position
			Transform2 position(weapon.mOffset);

			// apply transform offset
			Transform2 transform(position * basetransform);

			if (weapon.mRecoil)
			{
				// apply recoil force
				for (unsigned int id = mId; id != 0; id = Database::backlink.Get(id))
				{
					if (Collidable *collidable = Database::collidable.Get(id))
					{
						collidable->GetBody()->ApplyImpulse(transform.Rotate(Vector2(0, -weapon.mRecoil)), transform.p);
						break;
					}
				}
			}

			if (weapon.mFlash)
			{
				// instantiate a flash
				unsigned int flashId = Database::Instantiate(weapon.mFlash, Database::owner.Get(mId), mId,
					transform.Angle(), transform.p, entity->GetVelocity(), entity->GetOmega());

				// set fractional turn
				if (Renderable *renderable = Database::renderable.Get(flashId))
					renderable->SetFraction(mTimer / aStep);

				// link it (HACK)
				LinkTemplate linktemplate;
				linktemplate.mOffset = weapon.mOffset;
				linktemplate.mSub = flashId;
				linktemplate.mSecondary = flashId;
				Link *link = new Link(linktemplate, mId);
				Database::Typed<Link *> &links = Database::link.Open(mId);
				links.Put(flashId, link);
				Database::link.Close(mId);
				link->Activate();
			}

			if (weapon.mOrdnance)
			{
				// TO DO: consolidate this with similar spawn patterns (Graze, Spawner)

				// apply position scatter
				position.a += Random::Value(0.0f, weapon.mScatter.a);
				position.p.x += Random::Value(0.0f, weapon.mScatter.p.x);
				position.p.y += Random::Value(0.0f, weapon.mScatter.p.y);

				// get world position
				position *= basetransform;

				// get local velocity
				Transform2 velocity(entity->GetOmega(), position.Unrotate(entity->GetVelocity()));

				// apply velocity inherit
				velocity.a *= weapon.mInherit.a;
				velocity.p.x *= weapon.mInherit.p.x;
				velocity.p.y *= weapon.mInherit.p.y;

				// apply velocity add
				velocity.a += weapon.mVelocity.a;
				velocity.p.x += weapon.mVelocity.p.x;
				velocity.p.y += weapon.mVelocity.p.y;

				// apply velocity variance
				velocity.a += Random::Value(0.0f, weapon.mVariance.a);
				velocity.p.x += Random::Value(0.0f, weapon.mVariance.p.x);
				velocity.p.y += Random::Value(0.0f, weapon.mVariance.p.y);

				// apply velocity aim
				velocity.p.x += controller->mAim.x * weapon.mAim.x;
				velocity.p.y += controller->mAim.y * weapon.mAim.y;

				// get world velocity
				velocity.p = position.Rotate(velocity.p);

				// instantiate a bullet
				unsigned int ordId = Database::Instantiate(weapon.mOrdnance, Database::owner.Get(mId), mId, position.a, position.p, velocity.p, velocity.a);
#ifdef DEBUG_WEAPON_CREATE_ORDNANCE
				DebugPrint("ordnance=\"%s\" owner=\"%s\"\n",
					Database::name.Get(ordId).c_str(),
					Database::name.Get(Database::owner.Get(ordId)).c_str());
#endif

				// set fractional turn
				if (Renderable *renderable = Database::renderable.Get(ordId))
					renderable->SetFraction(mTimer / aStep);

				// if tracking....
				if (weapon.mTrack)
				{
					// add a tracker
					Database::weapontracker.Put(ordId, WeaponTracker(mId));
				}
			}
		}

		// update weapon delay
		if (mBurst > 0)
			mTimer -= weapon.mBurstDelay;
		else
			mTimer -= (weapon.mDelay - weapon.mBurstStart - weapon.mBurstDelay * (weapon.mBurstLength - 1)) / weapon.mCycle;
	}

	if (mTimer > 0.0f)
	{
		// clamp fire delay
		mTimer = 0.0f;
	}
}
Example #24
0
InputSource::InputSource(const Resource &resource) :
  Named(resource.getName()),
  streamPtr(new ArrayStream<const char>(resource.getData(),
                                        resource.getLength())),
  stream(*streamPtr) {}
Example #25
0
bool UPnpCDSVideo::LoadVideos(const UPnpCDSRequest* pRequest,
                              UPnpCDSExtensionResults* pResults,
                              IDTokenMap tokens)
{
    QString sId = pRequest->m_sParentId;
     if (GetCurrentToken(pRequest->m_sParentId).first != "video")
         sId.append("/Video");
    sId.append("=%1");

    uint16_t nCount = pRequest->m_nRequestedCount;
    uint16_t nOffset = pRequest->m_nStartingIndex;

    // We must use a dedicated connection to get an acccurate value from
    // FOUND_ROWS()
    MSqlQuery query(MSqlQuery::InitCon(MSqlQuery::kDedicatedConnection));

    QString sql = "SELECT SQL_CALC_FOUND_ROWS "
                  "v.intid, title, subtitle, filename, director, plot, "
                  "rating, year, userrating, length, "
                  "season, episode, coverfile, insertdate, host, "
                  "g.genre, studio, collectionref, contenttype "
                  "FROM videometadata v "
                  "LEFT JOIN videogenre g ON g.intid=v.category "
                  "%1 " //
                  "ORDER BY title, season, episode "
                  "LIMIT :OFFSET,:COUNT ";

    QStringList clauses;
    QString whereString = BuildWhereClause(clauses, tokens);

    query.prepare(sql.arg(whereString));

    BindValues(query, tokens);

    query.bindValue(":OFFSET", nOffset);
    query.bindValue(":COUNT", nCount);

    if (!query.exec())
        return false;

    while (query.next())
    {

        int            nVidID       = query.value( 0).toInt();
        QString        sTitle       = query.value( 1).toString();
        QString        sSubtitle    = query.value( 2).toString();
        QString        sFilePath    = query.value( 3).toString();
        QString        sDirector    = query.value( 4).toString();
        QString        sPlot        = query.value( 5).toString();
        // QString        sRating      = query.value( 6).toString();
        int            nYear        = query.value( 7).toInt();
        // int             nUserRating  = query.value( 8).toInt();

        uint32_t       nLength      = query.value( 9).toUInt();
        // Convert from minutes to milliseconds
        nLength = (nLength * 60 *1000);

        int            nSeason      = query.value(10).toInt();
        int            nEpisode     = query.value(11).toInt();
        QString        sCoverArt    = query.value(12).toString();
        QDateTime      dtInsertDate =
            MythDate::as_utc(query.value(13).toDateTime());
        QString        sHostName    = query.value(14).toString();
        QString        sGenre       = query.value(15).toString();
    //    QString        sStudio      = query.value(16).toString();
    //    QString        sCollectionRef    = query.value(17).toString();
        QString        sContentType = query.value(18).toString();

        // ----------------------------------------------------------------------
        // Cache Host ip Address & Port
        // ----------------------------------------------------------------------

        // If the host-name is empty then we assume it is our local host
        // otherwise, we look up the host's IP address and port.  When the
        // client then trys to play the video it will be directed to the
        // host which actually has the content.
        if (!m_mapBackendIp.contains( sHostName ))
        {
            if (sHostName.isEmpty())
            {
                m_mapBackendIp[sHostName] =
                    gCoreContext->GetBackendServerIP4();
            }
            else
            {
                m_mapBackendIp[sHostName] =
                    gCoreContext->GetBackendServerIP4(sHostName);
            }
        }

        if (!m_mapBackendPort.contains( sHostName ))
        {
            if (sHostName.isEmpty())
            {
                m_mapBackendPort[sHostName] =
                    gCoreContext->GetBackendStatusPort();
            }
            else
            {
                m_mapBackendPort[sHostName] =
                    gCoreContext->GetBackendStatusPort(sHostName);
            }
        }


        // ----------------------------------------------------------------------
        // Build Support Strings
        // ----------------------------------------------------------------------

        QString sName      = sTitle;
        if( !sSubtitle.isEmpty() )
        {
            sName += " - " + sSubtitle;
        }

        QUrl URIBase;
        URIBase.setScheme("http");
        URIBase.setHost(m_mapBackendIp[sHostName]);
        URIBase.setPort(m_mapBackendPort[sHostName]);

        CDSObject *pItem;
        if (sContentType == "MOVIE")
        {
            pItem = CDSObject::CreateMovie( sId.arg(nVidID),
                                            sTitle,
                                            pRequest->m_sParentId );
        }
        else
        {
            pItem = CDSObject::CreateVideoItem( sId.arg(nVidID),
                                                sName,
                                                pRequest->m_sParentId );
        }

        if (!sSubtitle.isEmpty())
            pItem->SetPropValue( "description", sSubtitle );
        else
            pItem->SetPropValue( "description", sPlot.left(128).append(" ..."));
        pItem->SetPropValue( "longDescription", sPlot );
        pItem->SetPropValue( "director"       , sDirector );

        if (nEpisode > 0 || nSeason > 0) // There has got to be a better way
        {
            pItem->SetPropValue( "seriesTitle"  , sTitle );
            pItem->SetPropValue( "programTitle"  , sSubtitle );
            pItem->SetPropValue( "episodeNumber"  , QString::number(nEpisode));
            //pItem->SetPropValue( "episodeCount"  , nEpisodeCount);
        }

        pItem->SetPropValue( "genre"       , sGenre );
        if (nYear > 1830 && nYear < 9999)
            pItem->SetPropValue( "date",  QDate(nYear,1,1).toString(Qt::ISODate));
        else
            pItem->SetPropValue( "date", UPnPDateTime::DateTimeFormat(dtInsertDate) );

        // HACK: Windows Media Centre Compat (Not a UPnP or DLNA requirement, should only be done for WMC)
//         pItem->SetPropValue( "genre"          , "[Unknown Genre]"     );
//         pItem->SetPropValue( "actor"          , "[Unknown Author]"    );
//         pItem->SetPropValue( "creator"        , "[Unknown Creator]"   );
//         pItem->SetPropValue( "album"          , "[Unknown Album]"     );
        ////

        //pItem->SetPropValue( "producer"       , );
        //pItem->SetPropValue( "rating"         , );
        //pItem->SetPropValue( "actor"          , );
        //pItem->SetPropValue( "publisher"      , );
        //pItem->SetPropValue( "language"       , );
        //pItem->SetPropValue( "relation"       , );
        //pItem->SetPropValue( "region"         , );

        // Only add the reference ID for items which are not in the
        // 'All Videos' container
        QString sRefIDBase = QString("%1/Video").arg(m_sExtensionId);
        if ( pRequest->m_sParentId != sRefIDBase )
        {
            QString sRefId = QString( "%1=%2")
                                .arg( sRefIDBase )
                                .arg( nVidID );

            pItem->SetPropValue( "refID", sRefId );
        }

        // FIXME - If the slave or storage hosting this video is offline we
        //         won't find it. We probably shouldn't list it, but better
        //         still would be storing the filesize in the database so we
        //         don't waste time re-checking it constantly
        QString sFullFileName = sFilePath;
        if (!QFile::exists( sFullFileName ))
        {
            StorageGroup sgroup("Videos");
            sFullFileName = sgroup.FindFile( sFullFileName );
        }
        QFileInfo fInfo( sFullFileName );

        // ----------------------------------------------------------------------
        // Add Video Resource Element based on File extension (HTTP)
        // ----------------------------------------------------------------------

        QString sMimeType = HTTPRequest::GetMimeType( QFileInfo(sFilePath).suffix() );

        // HACK: If we are dealing with a Sony Blu-ray player then we fake the
        // MIME type to force the video to appear
//         if ( pRequest->m_eClient == CDS_ClientSonyDB )
//         {
//             sMimeType = "video/avi";
//         }

        QUrl    resURI    = URIBase;
        resURI.setPath("Content/GetVideo");
        resURI.addQueryItem("Id", QString::number(nVidID));

        QString sProtocol = DLNA::ProtocolInfoString(UPNPProtocol::kHTTP,
                                                     sMimeType);

        Resource *pRes = pItem->AddResource( sProtocol, resURI.toEncoded() );
        pRes->AddAttribute( "size"    , QString("%1").arg(fInfo.size()) );
        pRes->AddAttribute( "duration", UPnPDateTime::resDurationFormat(nLength) );

        // ----------------------------------------------------------------------
        // Add Artwork
        // ----------------------------------------------------------------------
        if (!sCoverArt.isEmpty() && (sCoverArt != "No Cover"))
        {
            PopulateArtworkURIS(pItem, nVidID, URIBase);
        }

        pResults->Add( pItem );
        pItem->DecrRef();
    }

    // Just in case FOUND_ROWS() should fail, ensure m_nTotalMatches contains
    // at least the size of this result set
    if (query.size() >= 0)
        pResults->m_nTotalMatches = query.size();

    // Fetch the total number of matches ignoring any LIMITs
    query.prepare("SELECT FOUND_ROWS()");
    if (query.exec() && query.next())
            pResults->m_nTotalMatches = query.value(0).toUInt();

    return true;
}
Example #26
0
void UPnpCDSTv::AddItem( const UPnpCDSRequest    *pRequest, 
                         const QString           &sObjectId,
                         UPnpCDSExtensionResults *pResults,
                         bool                     bAddRef,
                         MSqlQuery               &query )
{
    int            nChanid      = query.value( 0).toInt();
    QDateTime      dtStartTime  = MythDate::as_utc(query.value(1).toDateTime());
    QDateTime      dtEndTime    = MythDate::as_utc(query.value(2).toDateTime());
    QString        sTitle       = query.value( 3).toString();
    QString        sSubtitle    = query.value( 4).toString();
    QString        sDescription = query.value( 5).toString();
    QString        sCategory    = query.value( 6).toString();
    QString        sHostName    = query.value( 7).toString();
    QString        sRecGroup    = query.value( 8).toString();
    uint64_t       nFileSize    = query.value( 9).toULongLong();
    QString        sBaseName    = query.value(10).toString();

    QDateTime      dtProgStart  =
        MythDate::as_utc(query.value(11).toDateTime());
    QDateTime      dtProgEnd    =
        MythDate::as_utc(query.value(12).toDateTime());
    QString        sStorageGrp  = query.value(13).toString();

    QString        sInetRef     = query.value(14).toString();

    // ----------------------------------------------------------------------
    // Cache Host ip Address & Port
    // ----------------------------------------------------------------------

    if (!m_mapBackendIp.contains( sHostName ))
        m_mapBackendIp[ sHostName ] = gCoreContext->GetBackendServerIP4(sHostName);

    if (!m_mapBackendPort.contains( sHostName ))
        m_mapBackendPort[ sHostName ] = gCoreContext->GetBackendStatusPort(sHostName);

    // ----------------------------------------------------------------------
    // Build Support Strings
    // ----------------------------------------------------------------------

    QString sName      = sTitle + ": " + (sSubtitle.isEmpty() ? sDescription.left(128) : sSubtitle);

    QString sURIBase   = QString( "http://%1:%2/Content/" )
                            .arg( m_mapBackendIp  [ sHostName ] )
                            .arg( m_mapBackendPort[ sHostName ] );

    QString sURIParams = QString( "?ChanId=%1&amp;StartTime=%2" )
                            .arg( nChanid )
                            .arg( dtStartTime.toString(Qt::ISODate));

    QString sId        = QString( "RecTv/0/item%1")
                            .arg( sURIParams );

    CDSObject *pItem   = CDSObject::CreateVideoItem( sId,
                                                     sName,
                                                     sObjectId );
    pItem->m_bRestricted  = false;
    pItem->m_bSearchable  = true;
    pItem->m_sWriteStatus = "WRITABLE";

    if ( bAddRef )
    {
        QString sRefId = QString( "%1/0/item%2")
                            .arg( m_sExtensionId )
                            .arg( sURIParams     );

        pItem->SetPropValue( "refID", sRefId );
    }

    pItem->SetPropValue( "genre"          , sCategory    );
    pItem->SetPropValue( "longDescription", sDescription );
    pItem->SetPropValue( "description"    , sSubtitle    );

    //pItem->SetPropValue( "producer"       , );
    //pItem->SetPropValue( "rating"         , );
    //pItem->SetPropValue( "actor"          , );
    //pItem->SetPropValue( "director"       , );
    //pItem->SetPropValue( "publisher"      , );
    //pItem->SetPropValue( "language"       , );
    //pItem->SetPropValue( "relation"       , );
    //pItem->SetPropValue( "region"         , );

    // ----------------------------------------------------------------------
    // Needed for Microsoft Media Player Compatibility
    // (Won't display correct Title without them)
    // ----------------------------------------------------------------------

    pItem->SetPropValue( "creator"       , "[Unknown Author]" );
    pItem->SetPropValue( "artist"        , "[Unknown Author]" );
    pItem->SetPropValue( "album"         , "[Unknown Series]" );
    pItem->SetPropValue( "actor"         , "[Unknown Author]" );
    pItem->SetPropValue( "date"          , dtStartTime.toString(Qt::ISODate));

    pResults->Add( pItem );

    // ----------------------------------------------------------------------
    // Add Video Resource Element based on File contents/extension (HTTP)
    // ----------------------------------------------------------------------

    StorageGroup sg(sStorageGrp, sHostName);
    QString sFilePath = sg.FindFile(sBaseName);
    QString sMimeType;

    if ( QFile::exists(sFilePath) )
        sMimeType = HTTPRequest::TestMimeType( sFilePath );
    else
        sMimeType = HTTPRequest::TestMimeType( sBaseName );


    // If we are dealing with Window Media Player 12 (i.e. Windows 7)
    // then fake the Mime type to place the recorded TV in the
    // recorded TV section.
    if (pRequest->m_eClient == CDS_ClientWMP &&
        pRequest->m_nClientVersion >= 12.0)
    {
        sMimeType = "video/x-ms-dvr";
    }

    // If we are dealing with a Sony Blu-ray player then we fake the
    // MIME type to force the video to appear
    if ( pRequest->m_eClient == CDS_ClientSonyDB )
    {
        sMimeType = "video/avi";
    }


    // DLNA string below is temp fix for ps3 seeking.
    QString sProtocol = QString( "http-get:*:%1:DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01500000000000000000000000000000" ).arg( sMimeType  );
    QString sURI      = QString( "%1GetRecording%2").arg( sURIBase   )
                                                    .arg( sURIParams );

    // Sony BDPS370 requires a DLNA Profile Name
    // FIXME: detection to determine the correct DLNA Profile Name
    if (sMimeType == "video/mpeg")
    {
        sProtocol += ";DLNA.ORG_PN=MPEG_TS_SD_NA_ISO";
    }

    Resource *pRes = pItem->AddResource( sProtocol, sURI );

    uint uiStart = dtProgStart.toTime_t();
    uint uiEnd   = dtProgEnd.toTime_t();
    uint uiDur   = uiEnd - uiStart;
    
    MSqlQuery query2(MSqlQuery::InitCon());
    query2.prepare( "SELECT data FROM recordedmarkup WHERE chanid=:CHANID AND "
                    "starttime=:STARTTIME AND type = 33" );
    query2.bindValue(":CHANID", (int)nChanid);
    query2.bindValue(":STARTTIME", dtStartTime);
    if (query2.exec() && query2.next())
        uiDur = query2.value(0).toUInt() / 1000;

    QString sDur;

    sDur.sprintf("%02d:%02d:%02d",
                  (uiDur / 3600) % 24,
                  (uiDur / 60) % 60,
                   uiDur % 60);

    LOG(VB_UPNP, LOG_DEBUG, "Duration: " + sDur );

    pRes->AddAttribute( "duration"  , sDur      );
    pRes->AddAttribute( "size"      , QString::number( nFileSize) );

/*
    // ----------------------------------------------------------------------
    // Add Video Resource Element based on File extension (mythtv)
    // ----------------------------------------------------------------------

    sProtocol = QString( "myth:*:%1:*"     ).arg( sMimeType  );
    sURI      = QString( "myth://%1/%2" )
                   .arg( m_mapBackendIp  [ sHostName ] )
                   .arg( sBaseName );

    pRes = pItem->AddResource( sProtocol, sURI );

    pRes->AddAttribute( "duration"  , sDur      );
    pRes->AddAttribute( "size"      , QString::number( nFileSize) );
*/

    // ----------------------------------------------------------------------
    // Add Preview URI as <res>
    // MUST be _TN and 160px
    // ----------------------------------------------------------------------

    sURI = QString( "%1GetPreviewImage%2%3").arg( sURIBase   )
                                            .arg( sURIParams )
                                            .arg( "&amp;Width=160" );

    // TODO: Must be JPG for minimal compliance
    sProtocol = QString( "http-get:*:image/png:DLNA.ORG_PN=PNG_TN");
    pItem->AddResource( sProtocol, sURI );

    // ----------------------------------------------------------------------
    // Add Artwork URI as albumArt
    // ----------------------------------------------------------------------

    sURI = QString( "%1GetRecordingArtwork?Type=coverart&amp;Inetref=%3")
                                              .arg( sURIBase   )
                                              .arg( sInetRef   );

    QList<Property*> propList = pItem->GetProperties("albumArtURI");
    if (propList.size() >= 4)
    {
        // Prefer JPEG over PNG here, although PNG is allowed JPEG probably
        // has wider device support and crucially the filesizes are smaller
        // which speeds up loading times over the network

        // We MUST include the thumbnail size, but since some clients may use the
        // first image they see and the thumbnail is tiny, instead return the
        // medium first. The large could be very large, which is no good if the
        // client is pulling images for an entire list at once!

        // Medium
        Property *pProp = propList.at(0);
        if (pProp)
        {
            // Must be no more than 1024x768
            pProp->m_sValue = sURI;
            pProp->m_sValue.append("&amp;Width=1024&amp;Height=768");
            pProp->AddAttribute("dlna:profileID", "JPG_MED");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Thumbnail
        pProp = propList.at(1);
        if (pProp)
        {
            // At least one albumArtURI must be a ThumbNail (TN) no larger
            // than 160x160, and it must also be a jpeg
            pProp->m_sValue = sURI;
            pProp->m_sValue.append("&amp;Width=160&amp;Height=160");
            pProp->AddAttribute("dlna:profileID", "JPG_TN");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Medium
        pProp = propList.at(2);
        if (pProp)
        {
            // Must be no more than 1024x768
            pProp->m_sValue = sURI;
            pProp->m_sValue.append("&amp;Width=1024&amp;Height=768");
            pProp->AddAttribute("dlna:profileID", "JPG_MED");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }

        // Large
        pProp = propList.at(3);
        if (pProp)
        {
            // Must be no more than 4096x4096 - for our purposes, just return
            // a fullsize image
            pProp->m_sValue = sURI;
            pProp->AddAttribute("dlna:profileID", "JPG_LRG");
            pProp->AddAttribute("xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0");
        }
    }


}
  virtual void resourceOffers(SchedulerDriver* driver,
                              const vector<Offer>& offers)
  {
    cout << "." << flush;
    for (size_t i = 0; i < offers.size(); i++) {
      const Offer& offer = offers[i];

      // Lookup resources we care about.
      // TODO(benh): It would be nice to ultimately have some helper
      // functions for looking up resources.
      double cpus = 0;
      double mem = 0;

      for (int i = 0; i < offer.resources_size(); i++) {
        const Resource& resource = offer.resources(i);
        if (resource.name() == "cpus" &&
            resource.type() == Value::SCALAR) {
          cpus = resource.scalar().value();
        } else if (resource.name() == "mem" &&
                   resource.type() == Value::SCALAR) {
          mem = resource.scalar().value();
        }
      }

      // Launch tasks.
      vector<TaskInfo> tasks;
      while (tasksLaunched < totalTasks &&
             cpus >= CPUS_PER_TASK &&
             mem >= MEM_PER_TASK) {
        int taskId = tasksLaunched++;

        cout << "Starting task " << taskId << " on "
             << offer.hostname() << endl;

        TaskInfo task;
        task.set_name("Task " + lexical_cast<string>(taskId));
        task.mutable_task_id()->set_value(lexical_cast<string>(taskId));
        task.mutable_slave_id()->MergeFrom(offer.slave_id());
        task.mutable_command()->set_value("echo hello");

        Resource* resource;

        resource = task.add_resources();
        resource->set_name("cpus");
        resource->set_type(Value::SCALAR);
        resource->mutable_scalar()->set_value(CPUS_PER_TASK);

        resource = task.add_resources();
        resource->set_name("mem");
        resource->set_type(Value::SCALAR);
        resource->mutable_scalar()->set_value(MEM_PER_TASK);

        tasks.push_back(task);

        cpus -= CPUS_PER_TASK;
        mem -= MEM_PER_TASK;
      }

      driver->launchTasks(offer.id(), tasks);
    }
  }
Example #28
0
 bool operator()(const Resource &a, const Resource &b) const {
     return a.get_id() < b.get_id();
 }
void ResourceModelTester::externalOverbook()
{
    DateTime targetstart = m_project->constraintStartTime();
    DateTime targetend = m_project->constraintEndTime();
    Task *t = m_task;
    Resource *r = m_resource;

    r->addExternalAppointment( "Ext-1", "External project 1", targetstart, targetstart.addDays( 1 ), 100 );
    r->addExternalAppointment( "Ext-1", "External project 1", targetend.addDays( -1 ), targetend, 100 );

    ScheduleManager *sm = m_project->createScheduleManager( "Test Plan" );
    m_project->addScheduleManager( sm );
    sm->setAllowOverbooking( true );
    sm->createSchedules();
    m_project->calculate( *sm );
    long id = sm->scheduleId();
    m_model.setScheduleManager( sm );
    //printSchedulingLog( *sm );
    //printDebug( id );

    // resource group
    QModelIndex idx;
    int rows = m_model.rowCount( idx );
    QCOMPARE( rows, 1 );
    idx = m_model.index( 0, 0, idx );
    QVERIFY( idx.isValid() );
    
    // resource
    rows = m_model.rowCount( idx );
    QCOMPARE( rows, 1 );
    idx = m_model.index( 0, 0, idx );
    QCOMPARE( m_resource->name(), m_model.data( idx ).toString() );

    idx = m_model.index( m_resource );
    QVERIFY( idx.isValid() );

    // appointments
    rows = m_model.rowCount( idx );
    QCOMPARE( rows, m_resource->numAppointments( id ) + m_resource->numExternalAppointments() );
    QCOMPARE( rows, 2 ); // one internal, one external

    // internal appointment
    QModelIndex aidx = m_model.index( 0, 0, idx ); // first appointment (internal)
    QVERIFY( aidx.isValid() );
    rows = m_model.rowCount( aidx ); // num intervals
    QCOMPARE( rows, 1 );

    QModelIndex iidx = m_model.index( 0, 0, aidx ); // first interval
    QVERIFY( iidx.isValid() );
    rows = m_model.rowCount( iidx ); // intervals don't have children
    QCOMPARE( rows, 0 );

    // external appointment
    aidx = m_model.index( 1, 0, idx ); // second appointment (external)
    QVERIFY( aidx.isValid() );
    rows = m_model.rowCount( aidx ); // num intervals
    QCOMPARE( rows, 2 );

    iidx = m_model.index( 0, 0, aidx ); // first interval
    QVERIFY( iidx.isValid() );
    rows = m_model.rowCount( iidx ); // intervals don't have children
    QCOMPARE( rows, 0 );

    iidx = m_model.index( 1, 0, aidx ); // second interval
    QVERIFY( iidx.isValid() );
    rows = m_model.rowCount( iidx ); // intervals don't have children
    QCOMPARE( rows, 0 );


    QCOMPARE( t->startTime(), m_calendar->firstAvailableAfter( targetstart, t->endTime() ) );
    QCOMPARE( t->endTime(), t->startTime() + Duration( 0, 8, 0 ) );

}
Example #30
0
  bool setOption(long option, CVarRef value) {
    if (m_cp == NULL) {
      return false;
    }
    m_error_no = CURLE_OK;

    switch (option) {
    case CURLOPT_INFILESIZE:
    case CURLOPT_VERBOSE:
    case CURLOPT_HEADER:
    case CURLOPT_NOPROGRESS:
    case CURLOPT_NOBODY:
    case CURLOPT_FAILONERROR:
    case CURLOPT_UPLOAD:
    case CURLOPT_POST:
    case CURLOPT_FTPLISTONLY:
    case CURLOPT_FTPAPPEND:
    case CURLOPT_NETRC:
    case CURLOPT_PUT:
    case CURLOPT_TIMEOUT:
#if LIBCURL_VERSION_NUM >= 0x071002
    case CURLOPT_TIMEOUT_MS:
#endif
    case CURLOPT_FTP_USE_EPSV:
    case CURLOPT_LOW_SPEED_LIMIT:
    case CURLOPT_SSLVERSION:
    case CURLOPT_LOW_SPEED_TIME:
    case CURLOPT_RESUME_FROM:
    case CURLOPT_TIMEVALUE:
    case CURLOPT_TIMECONDITION:
    case CURLOPT_TRANSFERTEXT:
    case CURLOPT_HTTPPROXYTUNNEL:
    case CURLOPT_FILETIME:
    case CURLOPT_MAXREDIRS:
    case CURLOPT_MAXCONNECTS:
    case CURLOPT_CLOSEPOLICY:
    case CURLOPT_FRESH_CONNECT:
    case CURLOPT_FORBID_REUSE:
    case CURLOPT_CONNECTTIMEOUT:
#if LIBCURL_VERSION_NUM >= 0x071002
    case CURLOPT_CONNECTTIMEOUT_MS:
#endif
    case CURLOPT_SSL_VERIFYHOST:
    case CURLOPT_SSL_VERIFYPEER:
      //case CURLOPT_DNS_USE_GLOBAL_CACHE: not thread-safe when set to true
    case CURLOPT_NOSIGNAL:
    case CURLOPT_PROXYTYPE:
    case CURLOPT_BUFFERSIZE:
    case CURLOPT_HTTPGET:
    case CURLOPT_HTTP_VERSION:
    case CURLOPT_CRLF:
    case CURLOPT_DNS_CACHE_TIMEOUT:
    case CURLOPT_PROXYPORT:
    case CURLOPT_FTP_USE_EPRT:
    case CURLOPT_HTTPAUTH:
    case CURLOPT_PROXYAUTH:
    case CURLOPT_FTP_CREATE_MISSING_DIRS:
    case CURLOPT_FTPSSLAUTH:
    case CURLOPT_FTP_SSL:
    case CURLOPT_UNRESTRICTED_AUTH:
    case CURLOPT_PORT:
    case CURLOPT_AUTOREFERER:
    case CURLOPT_COOKIESESSION:
    case CURLOPT_TCP_NODELAY:
    case CURLOPT_IPRESOLVE:
    case CURLOPT_FOLLOWLOCATION:
      m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, value.toInt64());
      break;
    case CURLOPT_RETURNTRANSFER:
      m_write.method = value.toBoolean() ? PHP_CURL_RETURN : PHP_CURL_STDOUT;
      break;
    case CURLOPT_BINARYTRANSFER:
      m_write.type = value.toBoolean() ? PHP_CURL_BINARY : PHP_CURL_ASCII;
      break;
    case CURLOPT_PRIVATE:
    case CURLOPT_URL:
    case CURLOPT_PROXY:
    case CURLOPT_USERPWD:
    case CURLOPT_PROXYUSERPWD:
    case CURLOPT_RANGE:
    case CURLOPT_CUSTOMREQUEST:
    case CURLOPT_USERAGENT:
    case CURLOPT_FTPPORT:
    case CURLOPT_COOKIE:
    case CURLOPT_REFERER:
    case CURLOPT_INTERFACE:
    case CURLOPT_KRB4LEVEL:
    case CURLOPT_EGDSOCKET:
    case CURLOPT_CAINFO:
    case CURLOPT_CAPATH:
    case CURLOPT_SSL_CIPHER_LIST:
    case CURLOPT_SSLKEY:
    case CURLOPT_SSLKEYTYPE:
    case CURLOPT_SSLKEYPASSWD:
    case CURLOPT_SSLENGINE:
    case CURLOPT_SSLENGINE_DEFAULT:
    case CURLOPT_SSLCERTTYPE:
    case CURLOPT_ENCODING:
    case CURLOPT_COOKIEJAR:
    case CURLOPT_SSLCERT:
    case CURLOPT_RANDOM_FILE:
    case CURLOPT_COOKIEFILE:
      {
        String svalue = value.toString();
#if LIBCURL_VERSION_NUM >= 0x071100
        /* Strings passed to libcurl as 'char *' arguments, are copied
           by the library... NOTE: before 7.17.0 strings were not copied. */
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, svalue.c_str());
#else
        char *copystr = strndup(svalue.data(), svalue.size());
        m_to_free->str.push_back(copystr);
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, copystr);
#endif
        if (option == CURLOPT_URL) m_url = value;
      }
      break;
    case CURLOPT_FILE:
    case CURLOPT_INFILE:
    case CURLOPT_WRITEHEADER:
    case CURLOPT_STDERR:
      {
        if (!value.isResource()) {
          return false;
        }

        Resource obj = value.toResource();
        if (obj.isNull() || obj.getTyped<File>(true) == NULL) {
          return false;
        }

        switch (option) {
          case CURLOPT_FILE:
            m_write.fp = obj;
            m_write.method = PHP_CURL_FILE;
            break;
          case CURLOPT_WRITEHEADER:
            m_write_header.fp = obj;
            m_write_header.method = PHP_CURL_FILE;
            break;
          case CURLOPT_INFILE:
            m_read.fp = obj;
            m_emptyPost = false;
            break;
          default: {
            if (obj.getTyped<PlainFile>(true) == NULL) {
              return false;
            }
            FILE *fp = obj.getTyped<PlainFile>()->getStream();
            if (!fp) {
              return false;
            }
            m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, fp);
            break;
          }
        }
      }
      break;
    case CURLOPT_WRITEFUNCTION:
      m_write.callback = value;
      m_write.method = PHP_CURL_USER;
      break;
    case CURLOPT_READFUNCTION:
      m_read.callback = value;
      m_read.method = PHP_CURL_USER;
      m_emptyPost = false;
      break;
    case CURLOPT_HEADERFUNCTION:
      m_write_header.callback = value;
      m_write_header.method = PHP_CURL_USER;
      break;
    case CURLOPT_POSTFIELDS:
      m_emptyPost = false;
      if (value.is(KindOfArray) || value.is(KindOfObject)) {
        Array arr = value.toArray();
        curl_httppost *first = NULL;
        curl_httppost *last  = NULL;
        for (ArrayIter iter(arr); iter; ++iter) {
          String key = iter.first().toString();
          String val = iter.second().toString();
          const char *postval = val.data();

          /* The arguments after _NAMELENGTH and _CONTENTSLENGTH
           * must be explicitly cast to long in curl_formadd
           * use since curl needs a long not an int. */
          if (*postval == '@') {
            ++postval;
            m_error_no = (CURLcode)curl_formadd
              (&first, &last,
               CURLFORM_COPYNAME, key.data(),
               CURLFORM_NAMELENGTH, (long)key.size(),
               CURLFORM_FILE, postval,
               CURLFORM_END);
          } else {
            m_error_no = (CURLcode)curl_formadd
              (&first, &last,
               CURLFORM_COPYNAME, key.data(),
               CURLFORM_NAMELENGTH, (long)key.size(),
               CURLFORM_COPYCONTENTS, postval,
               CURLFORM_CONTENTSLENGTH,(long)val.size(),
               CURLFORM_END);
          }
        }

        if (m_error_no != CURLE_OK) {
          return false;
        }

        m_to_free->post.push_back(first);
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_HTTPPOST, first);

      } else {
        String svalue = value.toString();
#if LIBCURL_VERSION_NUM >= 0x071100
        /* with curl 7.17.0 and later, we can use COPYPOSTFIELDS,
           but we have to provide size before */
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDSIZE,
                                      svalue.size());
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_COPYPOSTFIELDS,
                                      svalue.c_str());
#else
        char *post = strndup(svalue.data(), svalue.size());
        m_to_free->str.push_back(post);

        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDS, post);
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDSIZE,
                                      svalue.size());
#endif
      }
      break;
    case CURLOPT_HTTPHEADER:
    case CURLOPT_QUOTE:
    case CURLOPT_HTTP200ALIASES:
    case CURLOPT_POSTQUOTE:
      if (value.is(KindOfArray) || value.is(KindOfObject)) {
        Array arr = value.toArray();
        curl_slist *slist = NULL;
        for (ArrayIter iter(arr); iter; ++iter) {
          String key = iter.first().toString();
          String val = iter.second().toString();

          slist = curl_slist_append(slist, val.c_str());
          if (!slist) {
            raise_warning("Could not build curl_slist");
            return false;
          }
        }

        m_to_free->slist.push_back(slist);
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, slist);

      } else {
        raise_warning("You must pass either an object or an array with "
                      "the CURLOPT_HTTPHEADER, CURLOPT_QUOTE, "
                      "CURLOPT_HTTP200ALIASES and CURLOPT_POSTQUOTE "
                      "arguments");
        return false;
      }
      break;

    case CURLINFO_HEADER_OUT:
      if (value.toInt64() == 1) {
        curl_easy_setopt(m_cp, CURLOPT_DEBUGFUNCTION, curl_debug);
        curl_easy_setopt(m_cp, CURLOPT_DEBUGDATA, (void *)this);
        curl_easy_setopt(m_cp, CURLOPT_VERBOSE, 1);
      } else {
        curl_easy_setopt(m_cp, CURLOPT_DEBUGFUNCTION, NULL);
        curl_easy_setopt(m_cp, CURLOPT_DEBUGDATA, NULL);
        curl_easy_setopt(m_cp, CURLOPT_VERBOSE, 0);
      }
      break;

    case CURLOPT_FB_TLS_VER_MAX:
      {
        int64_t val = value.toInt64();
        if (value.isInteger() &&
            (val == CURLOPT_FB_TLS_VER_MAX_1_0 ||
             val == CURLOPT_FB_TLS_VER_MAX_1_1 ||
             val == CURLOPT_FB_TLS_VER_MAX_NONE)) {
            m_opts.set(int64_t(option), value);
        } else {
          raise_warning("You must pass CURLOPT_FB_TLS_VER_MAX_1_0, "
                        "CURLOPT_FB_TLS_VER_MAX_1_1 or "
                        "CURLOPT_FB_TLS_VER_MAX_NONE with "
                        "CURLOPT_FB_TLS_VER_MAX");
        }
      }
      break;
    case CURLOPT_FB_TLS_CIPHER_SPEC:
      if (value.isString() && !value.toString().empty()) {
        m_opts.set(int64_t(option), value);
      } else {
        raise_warning("CURLOPT_FB_TLS_CIPHER_SPEC requires a non-empty string");
      }
      break;

    default:
      m_error_no = CURLE_FAILED_INIT;
      throw_invalid_argument("option: %ld", option);
      break;
    }

    m_opts.set(int64_t(option), value);

    return m_error_no == CURLE_OK;
  }