<commit_before>
#include <ionWindow.h>
#include <ionGraphics.h>
#include <ionGraphicsGL.h>
#include <ionScene.h>
#include <ionApplication.h>

using namespace ion;
using namespace ion::Scene;
using namespace ion::Graphics;

int main()
{
	////////////////////
	// ionEngine Init //
	////////////////////

	Log::AddDefaultOutputs();

	SingletonPointer<CGraphicsAPI> GraphicsAPI;
	SingletonPointer<CWindowManager> WindowManager;
	SingletonPointer<CTimeManager> TimeManager;
	SingletonPointer<CSceneManager> SceneManager;
	SingletonPointer<CAssetManager> AssetManager;

	GraphicsAPI->Init(new Graphics::COpenGLImplementation());
	WindowManager->Init(GraphicsAPI);
	TimeManager->Init(WindowManager);
	SceneManager->Init(GraphicsAPI);
	AssetManager->Init(GraphicsAPI);

	CWindow * Window = WindowManager->CreateWindow(vec2i(1600, 900), "DemoApplication", EWindowType::Windowed);

	AssetManager->SetAssetPath("Assets/");
	AssetManager->SetShaderPath("Shaders/");
	AssetManager->SetTexturePath("Images/");

	SharedPointer<IGraphicsContext> Context = GraphicsAPI->GetWindowContext(Window);
	SharedPointer<IRenderTarget> RenderTarget = Context->GetBackBuffer();
	RenderTarget->SetClearColor(color3f(0.3f));

	/////////////////
	// Load Assets //
	/////////////////

	CSimpleMesh * SphereMesh = CGeometryCreator::CreateSphere();
	CSimpleMesh * SkySphereMesh = CGeometryCreator::CreateSkySphere();
	CSimpleMesh * PlaneMesh = CGeometryCreator::CreatePlane(vec2f(100.f));

	SharedPointer<IShaderProgram> DiffuseShader = AssetManager->LoadShader("Diffuse");
	SharedPointer<IShaderProgram> SimpleShader = AssetManager->LoadShader("Simple");
	SharedPointer<IShaderProgram> SpecularShader = AssetManager->LoadShader("Specular");
	SharedPointer<IShaderProgram> SkySphereShader = AssetManager->LoadShader("SkySphere");

	SharedPointer<ITexture2D> SkyMap = AssetManager->LoadTexture("SkyMap.jpg");
	SkyMap->SetMagFilter(ITexture::EFilter::Nearest);

	////////////////////
	// ionScene Setup //
	////////////////////

	CRenderPass * RenderPass = new CRenderPass(Context);
	RenderPass->SetRenderTarget(RenderTarget);
	SceneManager->AddRenderPass(RenderPass);

	CPerspectiveCamera * Camera = new CPerspectiveCamera(Window->GetAspectRatio());
	Camera->SetPosition(vec3f(0, 3, -5));
	Camera->SetFocalLength(0.4f);
	RenderPass->SetActiveCamera(Camera);

	CCameraController * Controller = new CCameraController(Camera);
	Controller->SetTheta(15.f * Constants32::Pi / 48.f);
	Controller->SetPhi(-Constants32::Pi / 16.f);
	Window->AddListener(Controller);
	TimeManager->MakeUpdateTick(0.02)->AddListener(Controller);

	/////////////////
	// Add Objects //
	/////////////////

	CSimpleMeshSceneObject * LightSphere1 = new CSimpleMeshSceneObject();
	LightSphere1->SetMesh(SphereMesh);
	LightSphere1->SetShader(SimpleShader);
	LightSphere1->SetPosition(vec3f(0, 1, 0));
	RenderPass->AddSceneObject(LightSphere1);

	CSimpleMeshSceneObject * LightSphere2 = new CSimpleMeshSceneObject();
	LightSphere2->SetMesh(SphereMesh);
	LightSphere2->SetShader(SimpleShader);
	LightSphere2->SetPosition(vec3f(4, 2, 0));
	RenderPass->AddSceneObject(LightSphere2);

	CSimpleMeshSceneObject * LightSphere3 = new CSimpleMeshSceneObject();
	LightSphere3->SetMesh(SphereMesh);
	LightSphere3->SetShader(SimpleShader);
	LightSphere3->SetPosition(vec3f(12, 3, 0));
	RenderPass->AddSceneObject(LightSphere3);

	CSimpleMeshSceneObject * SpecularSphere = new CSimpleMeshSceneObject();
	SpecularSphere->SetMesh(SphereMesh);
	SpecularSphere->SetShader(SpecularShader);
	SpecularSphere->SetPosition(vec3f(3, 3, 6));
	RenderPass->AddSceneObject(SpecularSphere);

	CSimpleMeshSceneObject * PlaneObject = new CSimpleMeshSceneObject();
	PlaneObject->SetMesh(PlaneMesh);
	PlaneObject->SetShader(DiffuseShader);
	RenderPass->AddSceneObject(PlaneObject);

	CSimpleMeshSceneObject * SkySphereObject = new CSimpleMeshSceneObject();
	SkySphereObject->SetMesh(SkySphereMesh);
	SkySphereObject->SetShader(SkySphereShader);
	SkySphereObject->SetTexture("uTexture", SkyMap);
	RenderPass->AddSceneObject(SkySphereObject);

	CPointLight * Light1 = new CPointLight();
	Light1->SetPosition(vec3f(0, 1, 0));
	Light1->SetColor(Colors::Red);
	RenderPass->AddLight(Light1);

	CPointLight * Light2 = new CPointLight();
	Light2->SetPosition(vec3f(4, 2, 0));
	Light2->SetColor(Colors::Green);
	RenderPass->AddLight(Light2);

	CPointLight * Light3 = new CPointLight();
	Light3->SetPosition(vec3f(12, 3, 0));
	Light3->SetColor(Colors::Blue);
	RenderPass->AddLight(Light3);

	///////////////
	// Main Loop //
	///////////////

	TimeManager->Init();
	while (WindowManager->Run())
	{
		TimeManager->Update();

		float const MinimumBrightness = 0.2f;
		float const MaximumBrightness = 1.f - MinimumBrightness;
		float const Brightness = (Sin<float>((float) TimeManager->GetRunTime()) / 2.f + 0.5f) * MaximumBrightness + MinimumBrightness;
		float const Radius = Brightness * 10.f;
		Light1->SetRadius(Radius);
		Light2->SetRadius(Radius);
		Light3->SetRadius(Radius);

		float const Bright = 1;
		float const Dim = 0.5f;
		LightSphere1->GetMaterial().Diffuse = color3f(Bright, Dim, Dim) * Brightness;
		LightSphere2->GetMaterial().Diffuse = color3f(Dim, Bright, Dim) * Brightness;
		LightSphere3->GetMaterial().Diffuse = color3f(Dim, Dim, Bright) * Brightness;
		LightSphere1->SetScale(Brightness);
		LightSphere2->SetScale(Brightness);
		LightSphere3->SetScale(Brightness);

		SkySphereObject->SetPosition(Camera->GetPosition());

		RenderTarget->ClearColorAndDepth();
		SceneManager->DrawAll();
		Window->SwapBuffers();
	}

	return 0;
}
<commit_msg>One error missed in previous commit<commit_after>
#include <ionWindow.h>
#include <ionGraphics.h>
#include <ionGraphicsGL.h>
#include <ionScene.h>
#include <ionApplication.h>

using namespace ion;
using namespace ion::Scene;
using namespace ion::Graphics;

int main()
{
	////////////////////
	// ionEngine Init //
	////////////////////

	Log::AddDefaultOutputs();

	SingletonPointer<CGraphicsAPI> GraphicsAPI;
	SingletonPointer<CWindowManager> WindowManager;
	SingletonPointer<CTimeManager> TimeManager;
	SingletonPointer<CSceneManager> SceneManager;
	SingletonPointer<CAssetManager> AssetManager;

	GraphicsAPI->Init(new Graphics::COpenGLImplementation());
	WindowManager->Init(GraphicsAPI);
	TimeManager->Init(WindowManager);
	SceneManager->Init(GraphicsAPI);
	AssetManager->Init(GraphicsAPI);

	CWindow * Window = WindowManager->CreateWindow(vec2i(1600, 900), "DemoApplication", EWindowType::Windowed);

	AssetManager->SetAssetPath("Assets/");
	AssetManager->SetShaderPath("Shaders/");
	AssetManager->SetTexturePath("Images/");

	SharedPointer<IGraphicsContext> Context = GraphicsAPI->GetWindowContext(Window);
	SharedPointer<IRenderTarget> RenderTarget = Context->GetBackBuffer();
	RenderTarget->SetClearColor(color3f(0.3f));

	/////////////////
	// Load Assets //
	/////////////////

	CSimpleMesh * SphereMesh = CGeometryCreator::CreateSphere();
	CSimpleMesh * SkySphereMesh = CGeometryCreator::CreateSkySphere();
	CSimpleMesh * PlaneMesh = CGeometryCreator::CreatePlane(vec2f(100.f));

	SharedPointer<IShaderProgram> DiffuseShader = AssetManager->LoadShader("Diffuse");
	SharedPointer<IShaderProgram> SimpleShader = AssetManager->LoadShader("Simple");
	SharedPointer<IShaderProgram> SpecularShader = AssetManager->LoadShader("Specular");
	SharedPointer<IShaderProgram> SkySphereShader = AssetManager->LoadShader("SkySphere");

	SharedPointer<ITexture2D> SkyMap = AssetManager->LoadTexture("SkyMap.jpg");
	SkyMap->SetMagFilter(ITexture::EFilter::Nearest);

	////////////////////
	// ionScene Setup //
	////////////////////

	CRenderPass * RenderPass = new CRenderPass(Context);
	RenderPass->SetRenderTarget(RenderTarget);
	SceneManager->AddRenderPass(RenderPass);

	CPerspectiveCamera * Camera = new CPerspectiveCamera(Window->GetAspectRatio());
	Camera->SetPosition(vec3f(0, 3, -5));
	Camera->SetFocalLength(0.4f);
	RenderPass->SetActiveCamera(Camera);

	CCameraController * Controller = new CCameraController(Camera);
	Controller->SetTheta(15.f * Constants32::Pi / 48.f);
	Controller->SetPhi(-Constants32::Pi / 16.f);
	Window->AddListener(Controller);
	TimeManager->MakeUpdateTick(0.02)->AddListener(Controller);

	/////////////////
	// Add Objects //
	/////////////////

	CSimpleMeshSceneObject * LightSphere1 = new CSimpleMeshSceneObject();
	LightSphere1->SetMesh(SphereMesh);
	LightSphere1->SetShader(SimpleShader);
	LightSphere1->SetPosition(vec3f(0, 1, 0));
	RenderPass->AddSceneObject(LightSphere1);

	CSimpleMeshSceneObject * LightSphere2 = new CSimpleMeshSceneObject();
	LightSphere2->SetMesh(SphereMesh);
	LightSphere2->SetShader(SimpleShader);
	LightSphere2->SetPosition(vec3f(4, 2, 0));
	RenderPass->AddSceneObject(LightSphere2);

	CSimpleMeshSceneObject * LightSphere3 = new CSimpleMeshSceneObject();
	LightSphere3->SetMesh(SphereMesh);
	LightSphere3->SetShader(SimpleShader);
	LightSphere3->SetPosition(vec3f(12, 3, 0));
	RenderPass->AddSceneObject(LightSphere3);

	CSimpleMeshSceneObject * SpecularSphere = new CSimpleMeshSceneObject();
	SpecularSphere->SetMesh(SphereMesh);
	SpecularSphere->SetShader(SpecularShader);
	SpecularSphere->SetPosition(vec3f(3, 3, 6));
	RenderPass->AddSceneObject(SpecularSphere);

	CSimpleMeshSceneObject * PlaneObject = new CSimpleMeshSceneObject();
	PlaneObject->SetMesh(PlaneMesh);
	PlaneObject->SetShader(DiffuseShader);
	RenderPass->AddSceneObject(PlaneObject);

	CSimpleMeshSceneObject * SkySphereObject = new CSimpleMeshSceneObject();
	SkySphereObject->SetMesh(SkySphereMesh);
	SkySphereObject->SetShader(SkySphereShader);
	SkySphereObject->SetTexture("uTexture", SkyMap);
	RenderPass->AddSceneObject(SkySphereObject);

	CPointLight * Light1 = new CPointLight();
	Light1->SetPosition(vec3f(0, 1, 0));
	Light1->SetColor(Colors::Red);
	RenderPass->AddLight(Light1);

	CPointLight * Light2 = new CPointLight();
	Light2->SetPosition(vec3f(4, 2, 0));
	Light2->SetColor(Colors::Green);
	RenderPass->AddLight(Light2);

	CPointLight * Light3 = new CPointLight();
	Light3->SetPosition(vec3f(12, 3, 0));
	Light3->SetColor(Colors::Blue);
	RenderPass->AddLight(Light3);

	///////////////
	// Main Loop //
	///////////////

	TimeManager->Init(WindowManager);
	while (WindowManager->Run())
	{
		TimeManager->Update();

		float const MinimumBrightness = 0.2f;
		float const MaximumBrightness = 1.f - MinimumBrightness;
		float const Brightness = (Sin<float>((float) TimeManager->GetRunTime()) / 2.f + 0.5f) * MaximumBrightness + MinimumBrightness;
		float const Radius = Brightness * 10.f;
		Light1->SetRadius(Radius);
		Light2->SetRadius(Radius);
		Light3->SetRadius(Radius);

		float const Bright = 1;
		float const Dim = 0.5f;
		LightSphere1->GetMaterial().Diffuse = color3f(Bright, Dim, Dim) * Brightness;
		LightSphere2->GetMaterial().Diffuse = color3f(Dim, Bright, Dim) * Brightness;
		LightSphere3->GetMaterial().Diffuse = color3f(Dim, Dim, Bright) * Brightness;
		LightSphere1->SetScale(Brightness);
		LightSphere2->SetScale(Brightness);
		LightSphere3->SetScale(Brightness);

		SkySphereObject->SetPosition(Camera->GetPosition());

		RenderTarget->ClearColorAndDepth();
		SceneManager->DrawAll();
		Window->SwapBuffers();
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "yaml-cpp/value.h"
#include <map>

int main()
{
	YAML::Value value(YAML::ValueType::Sequence);
	for(int i=0;i<5;i++)
		value.append(i);

	for(YAML::const_iterator it=value.begin();it!=value.end();++it) {
		std::cout << it->as<int>() << "\n";
	}

	return 0;
}
<commit_msg>Map iterator works\!<commit_after>#include "yaml-cpp/value.h"
#include <map>

int main()
{
	YAML::Value value;
	value["seq"] = YAML::Value(YAML::ValueType::Sequence);
	for(int i=0;i<5;i++)
		value["seq"].append(i);
	value["map"]["one"] = "I";
	value["map"]["two"] = "II";
	value["map"]["three"] = "III";
	value["map"]["four"] = "IV";

	for(YAML::const_iterator it=value["seq"].begin();it!=value["seq"].end();++it) {
		std::cout << it->as<int>() << "\n";
	}

	for(YAML::const_iterator it=value["map"].begin();it!=value["map"].end();++it) {
		std::cout << it->first.as<std::string>() << " -> " << it->second.as<std::string>() << "\n";
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <optional.h>
#include "yatf/include/yatf.h"

namespace {

template <typename T>
void test_no_value() {
    optional<T> opt;
    REQUIRE_FALSE(opt);
    REQUIRE_FALSE(opt.has_value());
    REQUIRE_FALSE(opt == T{});
    REQUIRE(opt != T{});
    REQUIRE(opt == optional<T>());
    REQUIRE(optional<T>() == opt);
    REQUIRE_FALSE(opt != optional<T>());
    REQUIRE_FALSE(optional<T>() != opt);
    REQUIRE_FALSE(opt == optional<T>(T{}));
    REQUIRE_FALSE(optional<T>(T{}) == opt);
}

} // namespace anon

TEST(optional, can_have_no_value) {
    test_no_value<int>();
    test_no_value<char>();
    test_no_value<float>();
    test_no_value<double>();
    optional<int> opt;
    for (signed char i = -127; i < 127; i++) {
        REQUIRE_FALSE(opt == (signed char)3);
        REQUIRE(opt != (signed char)3);
        REQUIRE_FALSE(opt > i);
        REQUIRE_FALSE(opt >= i);
        REQUIRE_FALSE(opt < i);
        REQUIRE_FALSE(opt <= i);
    }
}

TEST(optional, can_set_value) {
    optional<int> opt;
    opt = 4;
    REQUIRE(opt);
    REQUIRE(opt.has_value());
    REQUIRE(opt.value() == 4);
    REQUIRE(opt == 4);
    REQUIRE_FALSE(opt == 5);
    REQUIRE(opt != -4);
    REQUIRE_FALSE(opt != 4);
    REQUIRE(opt < 5);
    REQUIRE_FALSE(opt < 2);
    REQUIRE(opt <= 4);
    REQUIRE_FALSE(opt <= 2);
    REQUIRE(opt > 2);
    REQUIRE_FALSE(opt > 5);
    REQUIRE(opt >= 4);
    REQUIRE_FALSE(opt >= 9);
    REQUIRE(opt == optional<int>(4));
    REQUIRE(optional<int>(4) == opt);
    REQUIRE(opt != optional<int>(10));
    REQUIRE(optional<int>(10) != opt);
    REQUIRE_FALSE(opt == optional<int>());
    REQUIRE_FALSE(optional<int>() == opt);
    REQUIRE(opt != optional<int>());
    REQUIRE(optional<int>() != opt);
}

<commit_msg>Add optional test<commit_after>#include <optional.h>
#include "yatf/include/yatf.h"

namespace {

template <typename T>
void test_no_value() {
    optional<T> opt;
    REQUIRE_FALSE(opt);
    REQUIRE_FALSE(opt.has_value());
    REQUIRE_FALSE(opt == T{});
    REQUIRE(opt != T{});
    REQUIRE(opt == optional<T>());
    REQUIRE(optional<T>() == opt);
    REQUIRE_FALSE(opt != optional<T>());
    REQUIRE_FALSE(optional<T>() != opt);
    REQUIRE_FALSE(opt == optional<T>(T{}));
    REQUIRE_FALSE(optional<T>(T{}) == opt);
}

} // namespace anon

TEST(optional, can_have_no_value) {
    test_no_value<int>();
    test_no_value<char>();
    test_no_value<float>();
    test_no_value<double>();
    optional<int> opt;
    for (signed char i = -127; i < 127; i++) {
        REQUIRE_FALSE(opt == (signed char)3);
        REQUIRE(opt != (signed char)3);
        REQUIRE_FALSE(opt > i);
        REQUIRE_FALSE(opt >= i);
        REQUIRE_FALSE(opt < i);
        REQUIRE_FALSE(opt <= i);
    }
}

TEST(optional, can_set_value) {
    optional<int> opt;
    opt = 4;
    REQUIRE(opt);
    REQUIRE(opt.has_value());
    REQUIRE(opt.value() == 4);
    REQUIRE(opt == 4);
    REQUIRE_FALSE(opt == 5);
    REQUIRE(opt != -4);
    REQUIRE_FALSE(opt != 4);
    REQUIRE(opt < 5);
    REQUIRE_FALSE(opt < 2);
    REQUIRE(opt <= 4);
    REQUIRE_FALSE(opt <= 2);
    REQUIRE(opt > 2);
    REQUIRE_FALSE(opt > 5);
    REQUIRE(opt >= 4);
    REQUIRE_FALSE(opt >= 9);
    REQUIRE(opt == optional<int>(4));
    REQUIRE(optional<int>(4) == opt);
    REQUIRE(opt != optional<int>(10));
    REQUIRE(optional<int>(10) != opt);
    REQUIRE_FALSE(opt == optional<int>());
    REQUIRE_FALSE(optional<int>() == opt);
    REQUIRE(opt != optional<int>());
    REQUIRE(optional<int>() != opt);
}

namespace {

template <typename Type>
void test_with_type() {
    {
        optional<Type> opt;
        REQUIRE(opt == optional<Type>());
        REQUIRE(opt != Type());
        REQUIRE(opt != optional<Type>(Type()));
        REQUIRE(optional<Type>() != Type());
        REQUIRE(optional<Type>() == opt);
        REQUIRE(optional<Type>(Type()) != opt);
        opt = Type();
        REQUIRE(opt != optional<Type>());
        REQUIRE(opt == Type());
        REQUIRE(optional<Type>() != opt);
        REQUIRE(opt == optional<Type>(Type()));
        REQUIRE(optional<Type>(Type()) == opt);
    }
}

} // namespace

TEST(optional, works_with_simple_types) {
    test_with_type<bool>();
    test_with_type<char>();
    test_with_type<signed char>();
    test_with_type<unsigned char>();
    test_with_type<short>();
    test_with_type<unsigned short>();
    test_with_type<int>();
    test_with_type<unsigned int>();
    test_with_type<long>();
    test_with_type<long long>();
}
<|endoftext|>


<commit_before>/**
 * @file lltoolbar.cpp
 * @author James Cook, Richard Nelson
 * @brief Large friendly buttons at bottom of screen.
 *
 * $LicenseInfo:firstyear=2002&license=viewergpl$
 *
 * Copyright (c) 2002-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "lltoolbar.h"

#include "imageids.h"
#include "llfloaterreg.h"
#include "llfontgl.h"
#include "llflyoutbutton.h"
#include "llrect.h"
#include "llparcel.h"

#include "llagent.h"
#include "llagentwearables.h"
#include "llbutton.h"
#include "llfocusmgr.h"
#include "llviewercontrol.h"
#include "llmenucommands.h"
#include "llimview.h"
#include "lluiconstants.h"
#include "llvoavatarself.h"
#include "lltooldraganddrop.h"
#include "llfloaterinventory.h"
#include "llfloaterchatterbox.h"
#include "llfloaterfriends.h"
#include "llfloatersnapshot.h"
#include "llinventorypanel.h"
#include "lltoolmgr.h"
#include "llui.h"
#include "llviewermenu.h"
//#include "llfirstuse.h"
#include "llpanelblockedlist.h"
#include "llscrolllistctrl.h"
#include "llscrolllistitem.h"
#include "llscrolllistcell.h"
#include "llviewerparcelmgr.h"
#include "lluictrlfactory.h"
#include "llviewerwindow.h"
#include "lltoolgrab.h"
#include "llcombobox.h"
#include "llimpanel.h"
#include "lllayoutstack.h"

#if LL_DARWIN

	#include "llresizehandle.h"

#endif // LL_DARWIN

//
// Globals
//

LLToolBar *gToolBar = NULL;

//
// Statics
//
F32	LLToolBar::sInventoryAutoOpenTime = 1.f;

//
// Functions
//

LLToolBar::LLToolBar()
:	LLPanel()
#if LL_DARWIN
	, mResizeHandle(NULL)
#endif // LL_DARWIN
{
	setIsChrome(TRUE);
	setFocusRoot(TRUE);

	mCommitCallbackRegistrar.add("HandleCommunicate", &LLToolBar::onClickCommunicate);
}

BOOL LLToolBar::postBuild()
{
	for (child_list_const_iter_t child_iter = getChildList()->begin();
		 child_iter != getChildList()->end(); ++child_iter)
	{
		LLView *view = *child_iter;
		LLButton* buttonp = dynamic_cast<LLButton*>(view);
		if(buttonp)
		{
			buttonp->setSoundFlags(LLView::SILENT);
		}
	}

#if LL_DARWIN
	if(mResizeHandle == NULL)
	{
		LLRect rect(0, 0, RESIZE_HANDLE_WIDTH, RESIZE_HANDLE_HEIGHT);
		LLResizeHandle::Params p;
		p.name("");
		p.rect(rect);
		p.min_width(RESIZE_HANDLE_WIDTH);
		p.min_height(RESIZE_HANDLE_HEIGHT);
		p.enabled(false);
		mResizeHandle = LLUICtrlFactory::create<LLResizeHandle>(p);
		addChildInBack(mResizeHandle);
		LLLayoutStack* toolbar_stack = getChild<LLLayoutStack>("toolbar_stack");
		toolbar_stack->reshape(toolbar_stack->getRect().getWidth() - RESIZE_HANDLE_WIDTH, toolbar_stack->getRect().getHeight());
	}
#endif // LL_DARWIN

	layoutButtons();

	return TRUE;
}

LLToolBar::~LLToolBar()
{
	// LLView destructor cleans up children
}

BOOL LLToolBar::handleDragAndDrop(S32 x, S32 y, MASK mask, BOOL drop,
									 EDragAndDropType cargo_type,
									 void* cargo_data,
									 EAcceptance* accept,
									 std::string& tooltip_msg)
{
	LLButton* inventory_btn = getChild<LLButton>("inventory_btn");
	if (!inventory_btn) return FALSE;

	LLRect button_screen_rect;
	inventory_btn->localRectToScreen(inventory_btn->getRect(),&button_screen_rect);

	const LLInventoryPanel *active_panel = LLInventoryPanel::getActiveInventoryPanel();
	if(active_panel)
	{
		mInventoryAutoOpen = FALSE;
	}
	else if (button_screen_rect.pointInRect(x, y))
	{
		if (mInventoryAutoOpen)
		{
			if (!active_panel &&
				mInventoryAutoOpenTimer.getElapsedTimeF32() > sInventoryAutoOpenTime)
			{
				LLFloaterInventory::showAgentInventory();
			}
		}
		else
		{
			mInventoryAutoOpen = TRUE;
			mInventoryAutoOpenTimer.reset();
		}
	}

	return LLPanel::handleDragAndDrop(x, y, mask, drop, cargo_type, cargo_data, accept, tooltip_msg);
}

// static
void LLToolBar::toggle(void*)
{
	BOOL show = gSavedSettings.getBOOL("ShowToolBar");
	gSavedSettings.setBOOL("ShowToolBar", !show);
	gToolBar->setVisible(!show);
}

// static
BOOL LLToolBar::visible(void*)
{
	return gToolBar->getVisible();
}

void LLToolBar::layoutButtons()
{
#if LL_DARWIN
	const S32 FUDGE_WIDTH_OF_SCREEN = 4;
	S32 width = gViewerWindow->getWindowWidthScaled() + FUDGE_WIDTH_OF_SCREEN;
	S32 pad = 2;

	// this function may be called before postBuild(), in which case mResizeHandle won't have been set up yet.
	if(mResizeHandle != NULL)
	{
		if(!gViewerWindow->getWindow()->getFullscreen())
		{
			// Only when running in windowed mode on the Mac, leave room for a resize widget on the right edge of the bar.
			width -= RESIZE_HANDLE_WIDTH;

			LLRect r;
			r.mLeft = width - pad;
			r.mBottom = 0;
			r.mRight = r.mLeft + RESIZE_HANDLE_WIDTH;
			r.mTop = r.mBottom + RESIZE_HANDLE_HEIGHT;
			mResizeHandle->setRect(r);
			mResizeHandle->setVisible(TRUE);
		}
		else
		{
			mResizeHandle->setVisible(FALSE);
		}
	}
#endif // LL_DARWIN
}

// virtual
void LLToolBar::reshape(S32 width, S32 height, BOOL called_from_parent)
{
	LLPanel::reshape(width, height, called_from_parent);

	layoutButtons();
}

// Per-frame updates of visibility
void LLToolBar::refresh()
{
	BOOL show = gSavedSettings.getBOOL("ShowToolBar");
	BOOL mouselook = gAgent.cameraMouselook();
	setVisible(show && !mouselook);

	if (isInVisibleChain())
	{
		updateCommunicateList();
	}
}

void LLToolBar::updateCommunicateList()
{
	LLFlyoutButton* communicate_button = getChild<LLFlyoutButton>("communicate_btn");
	LLSD selected = communicate_button->getValue();

	communicate_button->removeall();

	LLFloater* frontmost_floater = LLFloaterChatterBox::getInstance()->getActiveFloater();
	LLScrollListItem* itemp = NULL;

	LLSD contact_sd;
	contact_sd["value"] = "contacts";
	contact_sd["columns"][0]["value"] = LLFloaterMyFriends::getInstance()->getShortTitle();
	if (LLFloaterMyFriends::getInstance() == frontmost_floater)
	{
		contact_sd["columns"][0]["font"]["name"] = "SANSSERIF_SMALL";
		contact_sd["columns"][0]["font"]["style"] = "BOLD";
		// make sure current tab is selected in list
		if (selected.isUndefined())
		{
			selected = "contacts";
		}
	}
	itemp = communicate_button->addElement(contact_sd, ADD_TOP);

	communicate_button->addSeparator(ADD_TOP);
	communicate_button->add(getString("Redock Windows"), LLSD("redock"), ADD_TOP);
	communicate_button->addSeparator(ADD_TOP);
	communicate_button->add(getString("Blocked List"), LLSD("mute list"), ADD_TOP);

	std::set<LLHandle<LLFloater> >::const_iterator floater_handle_it;

	if (gIMMgr->getIMFloaterHandles().size() > 0)
	{
		communicate_button->addSeparator(ADD_TOP);
	}

	for(floater_handle_it = gIMMgr->getIMFloaterHandles().begin(); floater_handle_it != gIMMgr->getIMFloaterHandles().end(); ++floater_handle_it)
	{
		LLFloaterIMPanel* im_floaterp = (LLFloaterIMPanel*)floater_handle_it->get();
		if (im_floaterp)
		{
			std::string floater_title = im_floaterp->getNumUnreadMessages() > 0 ? "*" : "";
			floater_title.append(im_floaterp->getShortTitle());
			LLSD im_sd;
			im_sd["value"] = im_floaterp->getSessionID();
			im_sd["columns"][0]["value"] = floater_title;
			if (im_floaterp  == frontmost_floater)
			{
				im_sd["columns"][0]["font"]["name"] = "SANSSERIF_SMALL";
				im_sd["columns"][0]["font"]["style"] = "BOLD";
				if (selected.isUndefined())
				{
					selected = im_floaterp->getSessionID();
				}
			}
			itemp = communicate_button->addElement(im_sd, ADD_TOP);
		}
	}

	communicate_button->setValue(selected);
}

// static
void LLToolBar::onClickCommunicate(LLUICtrl* ctrl, const LLSD& user_data)
{
	LLFlyoutButton* communicate_button = dynamic_cast<LLFlyoutButton*>(ctrl);
	llassert_always(communicate_button);

	LLSD selected_option = communicate_button->getValue();

	if (selected_option.asString() == "contacts")
	{
		LLFloaterReg::showInstance("contacts", "friends");
	}
	else if (selected_option.asString() == "local chat")
	{
		LLFloaterReg::showInstance("communicate", "local");
	}
	else if (selected_option.asString() == "redock")
	{
		LLFloaterChatterBox* chatterbox_instance = LLFloaterChatterBox::getInstance();
		if(chatterbox_instance)
		{
			chatterbox_instance->addFloater(LLFloaterMyFriends::getInstance(), FALSE);

			LLUUID session_to_show;

			std::set<LLHandle<LLFloater> >::const_iterator floater_handle_it;
			for(floater_handle_it = gIMMgr->getIMFloaterHandles().begin(); floater_handle_it != gIMMgr->getIMFloaterHandles().end(); ++floater_handle_it)
			{
				LLFloater* im_floaterp = floater_handle_it->get();
				if (im_floaterp)
				{
					if (im_floaterp->isFrontmost())
					{
						session_to_show = ((LLFloaterIMPanel*)im_floaterp)->getSessionID();
					}
					chatterbox_instance->addFloater(im_floaterp, FALSE);
				}
			}
			LLFloaterReg::showInstance("communicate", session_to_show);
		}
	}
	else if (selected_option.asString() == "mute list")
	{
		LLPanelBlockedList::showPanelAndSelect(LLUUID::null);
	}
	else if (selected_option.isUndefined()) // user just clicked the communicate button, treat as toggle
	{
		LLFloaterReg::toggleInstance("communicate");
		}
	else // otherwise selection_option is undifined or a specific IM session id
	{
		LLFloaterReg::showInstance("communicate", selected_option);
	}
}

<commit_msg>CID-385<commit_after>/**
 * @file lltoolbar.cpp
 * @author James Cook, Richard Nelson
 * @brief Large friendly buttons at bottom of screen.
 *
 * $LicenseInfo:firstyear=2002&license=viewergpl$
 *
 * Copyright (c) 2002-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "lltoolbar.h"

#include "imageids.h"
#include "llfloaterreg.h"
#include "llfontgl.h"
#include "llflyoutbutton.h"
#include "llrect.h"
#include "llparcel.h"

#include "llagent.h"
#include "llagentwearables.h"
#include "llbutton.h"
#include "llfocusmgr.h"
#include "llviewercontrol.h"
#include "llmenucommands.h"
#include "llimview.h"
#include "lluiconstants.h"
#include "llvoavatarself.h"
#include "lltooldraganddrop.h"
#include "llfloaterinventory.h"
#include "llfloaterchatterbox.h"
#include "llfloaterfriends.h"
#include "llfloatersnapshot.h"
#include "llinventorypanel.h"
#include "lltoolmgr.h"
#include "llui.h"
#include "llviewermenu.h"
//#include "llfirstuse.h"
#include "llpanelblockedlist.h"
#include "llscrolllistctrl.h"
#include "llscrolllistitem.h"
#include "llscrolllistcell.h"
#include "llviewerparcelmgr.h"
#include "lluictrlfactory.h"
#include "llviewerwindow.h"
#include "lltoolgrab.h"
#include "llcombobox.h"
#include "llimpanel.h"
#include "lllayoutstack.h"

#if LL_DARWIN

	#include "llresizehandle.h"

#endif // LL_DARWIN

//
// Globals
//

LLToolBar *gToolBar = NULL;

//
// Statics
//
F32	LLToolBar::sInventoryAutoOpenTime = 1.f;

//
// Functions
//

LLToolBar::LLToolBar()
	: LLPanel(),

	mInventoryAutoOpen(FALSE),
	mNumUnreadIMs(0)
#if LL_DARWIN
	, mResizeHandle(NULL),
#endif // LL_DARWIN
{
	setIsChrome(TRUE);
	setFocusRoot(TRUE);

	mCommitCallbackRegistrar.add("HandleCommunicate", &LLToolBar::onClickCommunicate);
}

BOOL LLToolBar::postBuild()
{
	for (child_list_const_iter_t child_iter = getChildList()->begin();
		 child_iter != getChildList()->end(); ++child_iter)
	{
		LLView *view = *child_iter;
		LLButton* buttonp = dynamic_cast<LLButton*>(view);
		if(buttonp)
		{
			buttonp->setSoundFlags(LLView::SILENT);
		}
	}

#if LL_DARWIN
	if(mResizeHandle == NULL)
	{
		LLRect rect(0, 0, RESIZE_HANDLE_WIDTH, RESIZE_HANDLE_HEIGHT);
		LLResizeHandle::Params p;
		p.name("");
		p.rect(rect);
		p.min_width(RESIZE_HANDLE_WIDTH);
		p.min_height(RESIZE_HANDLE_HEIGHT);
		p.enabled(false);
		mResizeHandle = LLUICtrlFactory::create<LLResizeHandle>(p);
		addChildInBack(mResizeHandle);
		LLLayoutStack* toolbar_stack = getChild<LLLayoutStack>("toolbar_stack");
		toolbar_stack->reshape(toolbar_stack->getRect().getWidth() - RESIZE_HANDLE_WIDTH, toolbar_stack->getRect().getHeight());
	}
#endif // LL_DARWIN

	layoutButtons();

	return TRUE;
}

LLToolBar::~LLToolBar()
{
	// LLView destructor cleans up children
}

BOOL LLToolBar::handleDragAndDrop(S32 x, S32 y, MASK mask, BOOL drop,
									 EDragAndDropType cargo_type,
									 void* cargo_data,
									 EAcceptance* accept,
									 std::string& tooltip_msg)
{
	LLButton* inventory_btn = getChild<LLButton>("inventory_btn");
	if (!inventory_btn) return FALSE;

	LLRect button_screen_rect;
	inventory_btn->localRectToScreen(inventory_btn->getRect(),&button_screen_rect);

	const LLInventoryPanel *active_panel = LLInventoryPanel::getActiveInventoryPanel();
	if(active_panel)
	{
		mInventoryAutoOpen = FALSE;
	}
	else if (button_screen_rect.pointInRect(x, y))
	{
		if (mInventoryAutoOpen)
		{
			if (!active_panel &&
				mInventoryAutoOpenTimer.getElapsedTimeF32() > sInventoryAutoOpenTime)
			{
				LLFloaterInventory::showAgentInventory();
			}
		}
		else
		{
			mInventoryAutoOpen = TRUE;
			mInventoryAutoOpenTimer.reset();
		}
	}

	return LLPanel::handleDragAndDrop(x, y, mask, drop, cargo_type, cargo_data, accept, tooltip_msg);
}

// static
void LLToolBar::toggle(void*)
{
	BOOL show = gSavedSettings.getBOOL("ShowToolBar");
	gSavedSettings.setBOOL("ShowToolBar", !show);
	gToolBar->setVisible(!show);
}

// static
BOOL LLToolBar::visible(void*)
{
	return gToolBar->getVisible();
}

void LLToolBar::layoutButtons()
{
#if LL_DARWIN
	const S32 FUDGE_WIDTH_OF_SCREEN = 4;
	S32 width = gViewerWindow->getWindowWidthScaled() + FUDGE_WIDTH_OF_SCREEN;
	S32 pad = 2;

	// this function may be called before postBuild(), in which case mResizeHandle won't have been set up yet.
	if(mResizeHandle != NULL)
	{
		if(!gViewerWindow->getWindow()->getFullscreen())
		{
			// Only when running in windowed mode on the Mac, leave room for a resize widget on the right edge of the bar.
			width -= RESIZE_HANDLE_WIDTH;

			LLRect r;
			r.mLeft = width - pad;
			r.mBottom = 0;
			r.mRight = r.mLeft + RESIZE_HANDLE_WIDTH;
			r.mTop = r.mBottom + RESIZE_HANDLE_HEIGHT;
			mResizeHandle->setRect(r);
			mResizeHandle->setVisible(TRUE);
		}
		else
		{
			mResizeHandle->setVisible(FALSE);
		}
	}
#endif // LL_DARWIN
}

// virtual
void LLToolBar::reshape(S32 width, S32 height, BOOL called_from_parent)
{
	LLPanel::reshape(width, height, called_from_parent);

	layoutButtons();
}

// Per-frame updates of visibility
void LLToolBar::refresh()
{
	BOOL show = gSavedSettings.getBOOL("ShowToolBar");
	BOOL mouselook = gAgent.cameraMouselook();
	setVisible(show && !mouselook);

	if (isInVisibleChain())
	{
		updateCommunicateList();
	}
}

void LLToolBar::updateCommunicateList()
{
	LLFlyoutButton* communicate_button = getChild<LLFlyoutButton>("communicate_btn");
	LLSD selected = communicate_button->getValue();

	communicate_button->removeall();

	LLFloater* frontmost_floater = LLFloaterChatterBox::getInstance()->getActiveFloater();
	LLScrollListItem* itemp = NULL;

	LLSD contact_sd;
	contact_sd["value"] = "contacts";
	contact_sd["columns"][0]["value"] = LLFloaterMyFriends::getInstance()->getShortTitle();
	if (LLFloaterMyFriends::getInstance() == frontmost_floater)
	{
		contact_sd["columns"][0]["font"]["name"] = "SANSSERIF_SMALL";
		contact_sd["columns"][0]["font"]["style"] = "BOLD";
		// make sure current tab is selected in list
		if (selected.isUndefined())
		{
			selected = "contacts";
		}
	}
	itemp = communicate_button->addElement(contact_sd, ADD_TOP);

	communicate_button->addSeparator(ADD_TOP);
	communicate_button->add(getString("Redock Windows"), LLSD("redock"), ADD_TOP);
	communicate_button->addSeparator(ADD_TOP);
	communicate_button->add(getString("Blocked List"), LLSD("mute list"), ADD_TOP);

	std::set<LLHandle<LLFloater> >::const_iterator floater_handle_it;

	if (gIMMgr->getIMFloaterHandles().size() > 0)
	{
		communicate_button->addSeparator(ADD_TOP);
	}

	for(floater_handle_it = gIMMgr->getIMFloaterHandles().begin(); floater_handle_it != gIMMgr->getIMFloaterHandles().end(); ++floater_handle_it)
	{
		LLFloaterIMPanel* im_floaterp = (LLFloaterIMPanel*)floater_handle_it->get();
		if (im_floaterp)
		{
			std::string floater_title = im_floaterp->getNumUnreadMessages() > 0 ? "*" : "";
			floater_title.append(im_floaterp->getShortTitle());
			LLSD im_sd;
			im_sd["value"] = im_floaterp->getSessionID();
			im_sd["columns"][0]["value"] = floater_title;
			if (im_floaterp  == frontmost_floater)
			{
				im_sd["columns"][0]["font"]["name"] = "SANSSERIF_SMALL";
				im_sd["columns"][0]["font"]["style"] = "BOLD";
				if (selected.isUndefined())
				{
					selected = im_floaterp->getSessionID();
				}
			}
			itemp = communicate_button->addElement(im_sd, ADD_TOP);
		}
	}

	communicate_button->setValue(selected);
}

// static
void LLToolBar::onClickCommunicate(LLUICtrl* ctrl, const LLSD& user_data)
{
	LLFlyoutButton* communicate_button = dynamic_cast<LLFlyoutButton*>(ctrl);
	llassert_always(communicate_button);

	LLSD selected_option = communicate_button->getValue();

	if (selected_option.asString() == "contacts")
	{
		LLFloaterReg::showInstance("contacts", "friends");
	}
	else if (selected_option.asString() == "local chat")
	{
		LLFloaterReg::showInstance("communicate", "local");
	}
	else if (selected_option.asString() == "redock")
	{
		LLFloaterChatterBox* chatterbox_instance = LLFloaterChatterBox::getInstance();
		if(chatterbox_instance)
		{
			chatterbox_instance->addFloater(LLFloaterMyFriends::getInstance(), FALSE);

			LLUUID session_to_show;

			std::set<LLHandle<LLFloater> >::const_iterator floater_handle_it;
			for(floater_handle_it = gIMMgr->getIMFloaterHandles().begin(); floater_handle_it != gIMMgr->getIMFloaterHandles().end(); ++floater_handle_it)
			{
				LLFloater* im_floaterp = floater_handle_it->get();
				if (im_floaterp)
				{
					if (im_floaterp->isFrontmost())
					{
						session_to_show = ((LLFloaterIMPanel*)im_floaterp)->getSessionID();
					}
					chatterbox_instance->addFloater(im_floaterp, FALSE);
				}
			}
			LLFloaterReg::showInstance("communicate", session_to_show);
		}
	}
	else if (selected_option.asString() == "mute list")
	{
		LLPanelBlockedList::showPanelAndSelect(LLUUID::null);
	}
	else if (selected_option.isUndefined()) // user just clicked the communicate button, treat as toggle
	{
		LLFloaterReg::toggleInstance("communicate");
		}
	else // otherwise selection_option is undifined or a specific IM session id
	{
		LLFloaterReg::showInstance("communicate", selected_option);
	}
}

<|endoftext|>


<commit_before>#include <clpeak.h>

#define MSTRINGIFY(...) #__VA_ARGS__

static const char *stringifiedKernels =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_dp_kernels.cl"
#include "compute_integer_kernels.cl"
;

static const char *stringifiedKernelsNoInt =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_dp_kernels.cl"
;

clPeak::clPeak():forcePlatform(false),forceDevice(false), specifiedPlatform(-1), specifiedDevice(-1), useEventTimer(false),
       isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true), isTransferBW(true), isKernelLatency(true)
{
}

clPeak::~clPeak()
{
    if(log) delete log;
}

int clPeak::runAll()
{
    try
    {
        vector<cl::Platform> platforms;
        cl::Platform::get(&platforms);

        log->xmlOpenTag("clpeak");
        log->xmlAppendAttribs("os", OS_NAME);
        for(int p=0; p < (int)platforms.size(); p++)
        {
            if(forcePlatform && (p != specifiedPlatform))
                continue;

            log->print(NEWLINE "Platform: " + platforms[p].getInfo<CL_PLATFORM_NAME>() + NEWLINE);
            log->xmlOpenTag("platform");
            log->xmlAppendAttribs("name", platforms[p].getInfo<CL_PLATFORM_NAME>());

            cl_context_properties cps[3] = {
                    CL_CONTEXT_PLATFORM,
                    (cl_context_properties)(platforms[p])(),
                    0
                };
            cl::Context ctx(CL_DEVICE_TYPE_ALL, cps);
            vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();

            string plaformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
            bool isIntel = (plaformName.find("Intel") != std::string::npos)? true: false;
            bool isPocl = (plaformName.find("Portable Computing Language") != std::string::npos)? true: false;

            cl::Program prog;

            // FIXME Disabling integer compute tests on intel platform
            // Kernel build is taking much much longer time
            if(isIntel) {
                cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
                isComputeInt = false;
                prog = cl::Program(ctx, source);
            } else {
                cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
                prog = cl::Program(ctx, source);
            }

            // FIXME Disable compute-dp & comute-integer tests for pocl
            // DP test segfaults & integer test takes infinite time in llc step
            if(isPocl)
            {
                isComputeDP = false;
                isComputeInt = false;
            }

            try {
                prog.build(devices, BUILD_OPTIONS);
            }
            catch (cl::Error error)
            {
                log->print(TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) + NEWLINE NEWLINE);
            }

            for(int d=0; d < (int)devices.size(); d++)
            {
                if(forceDevice && (d != specifiedDevice))
                    continue;

                device_info_t devInfo = getDeviceInfo(devices[d]);

                log->print(TAB "Device: " + devInfo.deviceName + NEWLINE);
                log->print(TAB TAB "Driver version  : ");
                log->print(devInfo.driverVersion);  log->print(" (" OS_NAME ")" NEWLINE);
                log->print(TAB TAB "Compute units   : ");
                log->print(devInfo.numCUs);         log->print(NEWLINE);
                log->print(TAB TAB "Clock frequency : ");
                log->print(devInfo.maxClockFreq);   log->print(" MHz" NEWLINE);
                log->xmlOpenTag("device");
                log->xmlAppendAttribs("name", devInfo.deviceName);
                log->xmlAppendAttribs("driver_version", devInfo.driverVersion);

                cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);

                runGlobalBandwidthTest(queue, prog, devInfo);
                runComputeSP(queue, prog, devInfo);
                runComputeDP(queue, prog, devInfo);
                runComputeInteger(queue, prog, devInfo);
                runTransferBandwidthTest(queue, prog, devInfo);
                runKernelLatency(queue, prog, devInfo);

                log->print(NEWLINE);
                log->xmlCloseTag();       // device
            }
            log->xmlCloseTag();           // platform
        }
        log->xmlCloseTag();               // clpeak
    }
    catch(cl::Error error)
    {
        log->print(error.err() + NEWLINE);
        return -1;
    }

    return 0;
}

float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, int iters)
{
    float timed = 0;

    // Dummy calls
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
    queue.finish();

    if(useEventTimer)
    {
        for(int i=0; i<iters; i++)
        {
            cl::Event timeEvent;

            queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
            queue.finish();
            timed += timeInUS(timeEvent);
        }
    } else      // std timer
    {
        Timer timer;

        timer.start();
        for(int i=0; i<iters; i++)
        {
            queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
        }
        queue.finish();
        timed = timer.stopAndTime();
    }

    return (timed / iters);
}

<commit_msg>disables integer tests on apple<commit_after>#include <clpeak.h>

#define MSTRINGIFY(...) #__VA_ARGS__

static const char *stringifiedKernels =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_dp_kernels.cl"
#include "compute_integer_kernels.cl"
;

static const char *stringifiedKernelsNoInt =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_dp_kernels.cl"
;

clPeak::clPeak():forcePlatform(false),forceDevice(false), specifiedPlatform(-1), specifiedDevice(-1), useEventTimer(false),
       isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true), isTransferBW(true), isKernelLatency(true)
{
}

clPeak::~clPeak()
{
    if(log) delete log;
}

int clPeak::runAll()
{
    try
    {
        vector<cl::Platform> platforms;
        cl::Platform::get(&platforms);

        log->xmlOpenTag("clpeak");
        log->xmlAppendAttribs("os", OS_NAME);
        for(int p=0; p < (int)platforms.size(); p++)
        {
            if(forcePlatform && (p != specifiedPlatform))
                continue;

            log->print(NEWLINE "Platform: " + platforms[p].getInfo<CL_PLATFORM_NAME>() + NEWLINE);
            log->xmlOpenTag("platform");
            log->xmlAppendAttribs("name", platforms[p].getInfo<CL_PLATFORM_NAME>());

            cl_context_properties cps[3] = {
                    CL_CONTEXT_PLATFORM,
                    (cl_context_properties)(platforms[p])(),
                    0
                };
            cl::Context ctx(CL_DEVICE_TYPE_ALL, cps);
            vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();

            string plaformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
            bool isIntel = (plaformName.find("Intel") != std::string::npos)? true: false;
            bool isPocl = (plaformName.find("Portable Computing Language") != std::string::npos)? true: false;
            bool isApple = (plaformName.find("Apple") != std::string::npos)? true: false;

            cl::Program prog;

            // FIXME Disabling integer compute tests on intel platform
            // Kernel build is taking much much longer time
            // FIXME Disabling integer compute tests on apple platform
            // Causes Segmentation fault: 11
            if(isIntel || isApple) {
                cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
                isComputeInt = false;
                prog = cl::Program(ctx, source);
            } else {
                cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
                prog = cl::Program(ctx, source);
            }

            // FIXME Disable compute-dp & comute-integer tests for pocl
            // DP test segfaults & integer test takes infinite time in llc step
            if(isPocl)
            {
                isComputeDP = false;
                isComputeInt = false;
            }

            try {
                prog.build(devices, BUILD_OPTIONS);
            }
            catch (cl::Error error)
            {
                log->print(TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) + NEWLINE NEWLINE);
            }

            for(int d=0; d < (int)devices.size(); d++)
            {
                if(forceDevice && (d != specifiedDevice))
                    continue;

                device_info_t devInfo = getDeviceInfo(devices[d]);

                log->print(TAB "Device: " + devInfo.deviceName + NEWLINE);
                log->print(TAB TAB "Driver version  : ");
                log->print(devInfo.driverVersion);  log->print(" (" OS_NAME ")" NEWLINE);
                log->print(TAB TAB "Compute units   : ");
                log->print(devInfo.numCUs);         log->print(NEWLINE);
                log->print(TAB TAB "Clock frequency : ");
                log->print(devInfo.maxClockFreq);   log->print(" MHz" NEWLINE);
                log->xmlOpenTag("device");
                log->xmlAppendAttribs("name", devInfo.deviceName);
                log->xmlAppendAttribs("driver_version", devInfo.driverVersion);

                cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);

                runGlobalBandwidthTest(queue, prog, devInfo);
                runComputeSP(queue, prog, devInfo);
                runComputeDP(queue, prog, devInfo);
                runComputeInteger(queue, prog, devInfo);
                runTransferBandwidthTest(queue, prog, devInfo);
                runKernelLatency(queue, prog, devInfo);

                log->print(NEWLINE);
                log->xmlCloseTag();       // device
            }
            log->xmlCloseTag();           // platform
        }
        log->xmlCloseTag();               // clpeak
    }
    catch(cl::Error error)
    {
        log->print(error.err() + NEWLINE);
        return -1;
    }

    return 0;
}

float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, int iters)
{
    float timed = 0;

    // Dummy calls
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
    queue.finish();

    if(useEventTimer)
    {
        for(int i=0; i<iters; i++)
        {
            cl::Event timeEvent;

            queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
            queue.finish();
            timed += timeInUS(timeEvent);
        }
    } else      // std timer
    {
        Timer timer;

        timer.start();
        for(int i=0; i<iters; i++)
        {
            queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
        }
        queue.finish();
        timed = timer.stopAndTime();
    }

    return (timed / iters);
}

<|endoftext|>


<commit_before>// Copyright 2016 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "util/misc/metrics.h"

#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "build/build_config.h"

namespace crashpad {

// static
void Metrics::CrashReportSize(FileHandle file) {
  const FileOffset size = LoggingFileSizeByHandle(file);
  UMA_HISTOGRAM_CUSTOM_COUNTS(
      "Crashpad.CrashReportSize", size, 0, 5 * 1024 * 1024, 50);
}

// static
void Metrics::ExceptionCaptureResult(CaptureResult result) {
  UMA_HISTOGRAM_ENUMERATION("Crashpad.ExceptionCaptureResult",
                            static_cast<int32_t>(result),
                            static_cast<int32_t>(CaptureResult::kMaxValue));
}

// static
void Metrics::ExceptionCode(uint32_t exception_code) {
#if defined(OS_WIN)
  const char kExceptionCodeString[] = "Crashpad.ExceptionCode.Win";
#elif defined(OS_MACOSX)
  const char kExceptionCodeString[] = "Crashpad.ExceptionCode.Mac";
#endif
  UMA_HISTOGRAM_SPARSE_SLOWLY(kExceptionCodeString,
                              static_cast<int32_t>(exception_code));
}

// static
void Metrics::ExceptionEncountered() {
  UMA_HISTOGRAM_COUNTS("Crashpad.ExceptionEncountered", 1);
}

}  // namespace crashpad
<commit_msg>static const on const char[] for UMA string<commit_after>// Copyright 2016 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "util/misc/metrics.h"

#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "build/build_config.h"

namespace crashpad {

// static
void Metrics::CrashReportSize(FileHandle file) {
  const FileOffset size = LoggingFileSizeByHandle(file);
  UMA_HISTOGRAM_CUSTOM_COUNTS(
      "Crashpad.CrashReportSize", size, 0, 5 * 1024 * 1024, 50);
}

// static
void Metrics::ExceptionCaptureResult(CaptureResult result) {
  UMA_HISTOGRAM_ENUMERATION("Crashpad.ExceptionCaptureResult",
                            static_cast<int32_t>(result),
                            static_cast<int32_t>(CaptureResult::kMaxValue));
}

// static
void Metrics::ExceptionCode(uint32_t exception_code) {
#if defined(OS_WIN)
  static const char kExceptionCodeString[] = "Crashpad.ExceptionCode.Win";
#elif defined(OS_MACOSX)
  static const char kExceptionCodeString[] = "Crashpad.ExceptionCode.Mac";
#endif
  UMA_HISTOGRAM_SPARSE_SLOWLY(kExceptionCodeString,
                              static_cast<int32_t>(exception_code));
}

// static
void Metrics::ExceptionEncountered() {
  UMA_HISTOGRAM_COUNTS("Crashpad.ExceptionEncountered", 1);
}

}  // namespace crashpad
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: idlcproduce.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 03:49:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _IDLC_ASTMODULE_HXX_
#include <idlc/astmodule.hxx>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif

#ifdef SAL_UNX
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#endif

using namespace ::rtl;
using namespace ::osl;

StringList* pCreatedDirectories = NULL;

static sal_Bool checkOutputPath(const OString& completeName)
{
    OString sysPathName = convertToAbsoluteSystemPath(completeName);
    OStringBuffer buffer(sysPathName.getLength());

    if ( sysPathName.indexOf( SEPARATOR ) == -1 )
        return sal_True;

    sal_Int32 nIndex = 0;
    OString token(sysPathName.getToken(0, SEPARATOR, nIndex));
    const sal_Char* p = token.getStr();
    if (strcmp(p, "..") == 0
        || *(p+1) == ':'
        || strcmp(p, ".") == 0)
    {
        buffer.append(token);
        buffer.append(SEPARATOR);
    }
    else
        nIndex = 0;

    do
    {
        buffer.append(sysPathName.getToken(0, SEPARATOR, nIndex));

        if ( buffer.getLength() > 0 && nIndex != -1 )
        {
#ifdef SAL_UNX
            if (mkdir((char*)buffer.getStr(), 0777) == -1)
#else
            if (mkdir((char*)buffer.getStr()) == -1)
#endif
            {
                if (errno == ENOENT)
                {
                    fprintf(stderr, "%s: cannot create directory '%s'\n",
                            idlc()->getOptions()->getProgramName().getStr(), buffer.getStr());
                    return sal_False;
                }
            } else
            {
                if ( !pCreatedDirectories )
                    pCreatedDirectories = new StringList();
                pCreatedDirectories->push_front(buffer.getStr());
            }
        }
        buffer.append(SEPARATOR);
    } while( nIndex != -1 );
    return sal_True;
}

static sal_Bool cleanPath()
{
    if ( pCreatedDirectories )
    {
        StringList::iterator iter = pCreatedDirectories->begin();
        StringList::iterator end = pCreatedDirectories->end();
        while ( iter != end )
        {
//#ifdef SAL_UNX
//          if (rmdir((char*)(*iter).getStr(), 0777) == -1)
//#else
            if (rmdir((char*)(*iter).getStr()) == -1)
//#endif
            {
                fprintf(stderr, "%s: cannot remove directory '%s'\n",
                        idlc()->getOptions()->getProgramName().getStr(), (*iter).getStr());
                return sal_False;
            }
            ++iter;
        }
        delete pCreatedDirectories;
    }
    return sal_True;
}

void removeIfExists(const OString& pathname)
{
    unlink(pathname.getStr());
}

sal_Int32 SAL_CALL produceFile(const OString& regFileName)
{
    Options* pOptions = idlc()->getOptions();

    OString regTmpName = regFileName.replaceAt(regFileName.getLength() -3, 3, "_idlc_");

    if ( !checkOutputPath(regFileName) )
    {
        fprintf(stderr, "%s: could not create path of registry file '%s'.\n",
                pOptions->getProgramName().getStr(), regFileName.getStr());
        return 1;
    }

    RegistryLoader regLoader;

    if ( !regLoader.isLoaded() )
    {
        fprintf(stderr, "%s: could not load registry dll.\n",
                pOptions->getProgramName().getStr());
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    Registry regFile(regLoader);

    removeIfExists(regTmpName);
    OString urlRegTmpName = convertToFileUrl(regTmpName);
    if ( regFile.create(OStringToOUString(urlRegTmpName, RTL_TEXTENCODING_UTF8)) )
    {
        fprintf(stderr, "%s: could not create registry file '%s'\n",
                pOptions->getProgramName().getStr(), regTmpName.getStr());
        removeIfExists(regTmpName);
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    RegistryKey rootKey;
    if ( regFile.openRootKey(rootKey) )
    {
        fprintf(stderr, "%s: could not open root of registry file '%s'\n",
                pOptions->getProgramName().getStr(), regFileName.getStr());
        removeIfExists(regTmpName);
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    // produce registry file
    if ( !idlc()->getRoot()->dump(rootKey) )
    {
        rootKey.closeKey();
        regFile.close();
        regFile.destroy(OStringToOUString(regFileName, RTL_TEXTENCODING_UTF8));
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    if ( rootKey.closeKey() )
    {
        fprintf(stderr, "%s: could not close root of registry file '%s'\n",
                pOptions->getProgramName().getStr(), regFileName.getStr());
        removeIfExists(regTmpName);
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }
    if ( regFile.close() )
    {
        fprintf(stderr, "%s: could not close registry file '%s'\n",
                pOptions->getProgramName().getStr(), regFileName.getStr());
        removeIfExists(regTmpName);
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    removeIfExists(regFileName);

    if ( File::move(OStringToOUString(regTmpName, osl_getThreadTextEncoding()),
                    OStringToOUString(regFileName, osl_getThreadTextEncoding())) != FileBase::E_None ) {
        fprintf(stderr, "%s: cannot rename temporary registry '%s' to '%s'\n",
                idlc()->getOptions()->getProgramName().getStr(),
                regTmpName.getStr(), regFileName.getStr());
        removeIfExists(regTmpName);
        cleanPath();
        return 1;
    }
    removeIfExists(regTmpName);

    return 0;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.12.8); FILE MERGED 2006/09/01 17:31:15 kaib 1.12.8.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: idlcproduce.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:14:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _IDLC_ASTMODULE_HXX_
#include <idlc/astmodule.hxx>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif

#ifdef SAL_UNX
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#endif

using namespace ::rtl;
using namespace ::osl;

StringList* pCreatedDirectories = NULL;

static sal_Bool checkOutputPath(const OString& completeName)
{
    OString sysPathName = convertToAbsoluteSystemPath(completeName);
    OStringBuffer buffer(sysPathName.getLength());

    if ( sysPathName.indexOf( SEPARATOR ) == -1 )
        return sal_True;

    sal_Int32 nIndex = 0;
    OString token(sysPathName.getToken(0, SEPARATOR, nIndex));
    const sal_Char* p = token.getStr();
    if (strcmp(p, "..") == 0
        || *(p+1) == ':'
        || strcmp(p, ".") == 0)
    {
        buffer.append(token);
        buffer.append(SEPARATOR);
    }
    else
        nIndex = 0;

    do
    {
        buffer.append(sysPathName.getToken(0, SEPARATOR, nIndex));

        if ( buffer.getLength() > 0 && nIndex != -1 )
        {
#ifdef SAL_UNX
            if (mkdir((char*)buffer.getStr(), 0777) == -1)
#else
            if (mkdir((char*)buffer.getStr()) == -1)
#endif
            {
                if (errno == ENOENT)
                {
                    fprintf(stderr, "%s: cannot create directory '%s'\n",
                            idlc()->getOptions()->getProgramName().getStr(), buffer.getStr());
                    return sal_False;
                }
            } else
            {
                if ( !pCreatedDirectories )
                    pCreatedDirectories = new StringList();
                pCreatedDirectories->push_front(buffer.getStr());
            }
        }
        buffer.append(SEPARATOR);
    } while( nIndex != -1 );
    return sal_True;
}

static sal_Bool cleanPath()
{
    if ( pCreatedDirectories )
    {
        StringList::iterator iter = pCreatedDirectories->begin();
        StringList::iterator end = pCreatedDirectories->end();
        while ( iter != end )
        {
//#ifdef SAL_UNX
//          if (rmdir((char*)(*iter).getStr(), 0777) == -1)
//#else
            if (rmdir((char*)(*iter).getStr()) == -1)
//#endif
            {
                fprintf(stderr, "%s: cannot remove directory '%s'\n",
                        idlc()->getOptions()->getProgramName().getStr(), (*iter).getStr());
                return sal_False;
            }
            ++iter;
        }
        delete pCreatedDirectories;
    }
    return sal_True;
}

void removeIfExists(const OString& pathname)
{
    unlink(pathname.getStr());
}

sal_Int32 SAL_CALL produceFile(const OString& regFileName)
{
    Options* pOptions = idlc()->getOptions();

    OString regTmpName = regFileName.replaceAt(regFileName.getLength() -3, 3, "_idlc_");

    if ( !checkOutputPath(regFileName) )
    {
        fprintf(stderr, "%s: could not create path of registry file '%s'.\n",
                pOptions->getProgramName().getStr(), regFileName.getStr());
        return 1;
    }

    RegistryLoader regLoader;

    if ( !regLoader.isLoaded() )
    {
        fprintf(stderr, "%s: could not load registry dll.\n",
                pOptions->getProgramName().getStr());
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    Registry regFile(regLoader);

    removeIfExists(regTmpName);
    OString urlRegTmpName = convertToFileUrl(regTmpName);
    if ( regFile.create(OStringToOUString(urlRegTmpName, RTL_TEXTENCODING_UTF8)) )
    {
        fprintf(stderr, "%s: could not create registry file '%s'\n",
                pOptions->getProgramName().getStr(), regTmpName.getStr());
        removeIfExists(regTmpName);
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    RegistryKey rootKey;
    if ( regFile.openRootKey(rootKey) )
    {
        fprintf(stderr, "%s: could not open root of registry file '%s'\n",
                pOptions->getProgramName().getStr(), regFileName.getStr());
        removeIfExists(regTmpName);
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    // produce registry file
    if ( !idlc()->getRoot()->dump(rootKey) )
    {
        rootKey.closeKey();
        regFile.close();
        regFile.destroy(OStringToOUString(regFileName, RTL_TEXTENCODING_UTF8));
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    if ( rootKey.closeKey() )
    {
        fprintf(stderr, "%s: could not close root of registry file '%s'\n",
                pOptions->getProgramName().getStr(), regFileName.getStr());
        removeIfExists(regTmpName);
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }
    if ( regFile.close() )
    {
        fprintf(stderr, "%s: could not close registry file '%s'\n",
                pOptions->getProgramName().getStr(), regFileName.getStr());
        removeIfExists(regTmpName);
        removeIfExists(regFileName);
        cleanPath();
        return 1;
    }

    removeIfExists(regFileName);

    if ( File::move(OStringToOUString(regTmpName, osl_getThreadTextEncoding()),
                    OStringToOUString(regFileName, osl_getThreadTextEncoding())) != FileBase::E_None ) {
        fprintf(stderr, "%s: cannot rename temporary registry '%s' to '%s'\n",
                idlc()->getOptions()->getProgramName().getStr(),
                regTmpName.getStr(), regFileName.getStr());
        removeIfExists(regTmpName);
        cleanPath();
        return 1;
    }
    removeIfExists(regTmpName);

    return 0;
}
<|endoftext|>


<commit_before>//An int array name arr is sorted from lowest to highest and outputed.
#include <iostream>

using namespace std;
int main() {
  int arr[5] = {8, 5, 1, 6, 9};
  size_t S = sizeof(arr)/sizeof(arr[0]);
  for (int i = 0; i < S - 1; i++) {
    for (int j = 0; j < S - 1; j++) {
      if (arr[j] > arr[j + 1])
        swap(arr[j], arr[j + 1]);
    }
  }

  //OUTPUT
  for (int i = 0; i < S; i++) {
    cout << arr[i] << endl;
  }
}<commit_msg>removed folder<commit_after><|endoftext|>


<commit_before>// Copyright 2012 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <exception>
using std::exception;
#include <iomanip>
using std::fixed;
using std::setprecision;
#include <limits>
using std::numeric_limits;
#include <cmath>
#include <ctime>

#include <ArgumentList.hpp>
using isa::utils::ArgumentList;
#include <Observation.hpp>
using AstroData::Observation;
#include <InitializeOpenCL.hpp>
using isa::OpenCL::initializeOpenCL;
#include <CLData.hpp>
using isa::OpenCL::CLData;
#include <utils.hpp>
using isa::utils::same;
#include <SNR.hpp>
using PulsarSearch::SNR;
#include <SNRCPU.hpp>
using PulsarSearch::pulsarSNR;

typedef float dataType;
const string typeName("float");

int main(int argc, char *argv[]) {
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	unsigned int nrDMsPerBlock = 0;
	unsigned int nrPeriodsPerBlock = 0;
	long long unsigned int wrongValues = 0;
	Observation< dataType > observation("SNRTest", typeName);
	CLData< dataType > foldedData("FoldedData", true);
	CLData< dataType > SNRData("SNRData", true);
	CLData< dataType > SNRDataCPU("SNRDataCPU", true);

	try {
		ArgumentList args(argc, argv);

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

		observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms"));
		observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods"));
		observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));

		nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-p1");
		nrPeriodsPerBlock = args.getSwitchArgument< unsigned int >("-p2");
	} catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// OpenCL Initialization
	cl::Context * clContext = new cl::Context();
	vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
	vector< cl::Device > * clDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();

	initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);

	// Allocate memory
	foldedData.allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
	foldedData.setCLContext(clContext);
	foldedData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	SNRData.allocateHostData(observation.getNrPeriods() * observation.getNrPaddedDMs());
	SNRData.setCLContext(clContext);
	SNRData.setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	SNRDataCPU.allocateHostData(observation.getNrPeriods() * observation.getNrPaddedDMs());

	try {
		foldedData.allocateDeviceData();
		SNRData.allocateDeviceData();
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}

	srand(time(NULL));
	for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
		for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
			for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
				foldedData.setHostDataItem((bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + dm, rand() % 100);
			}
		}
	}

	// Generate kernel
	SNR< dataType > clSNR("clSNR", typeName);
	clSNR.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
	clSNR.setObservation(&observation);
	clSNR.setNrDMsPerBlock(nrDMsPerBlock);
	clSNR.setNrPeriodsPerBlock(nrPeriodsPerBlock);
	clSNR.setPulsarPipeline();
	clSNR.generateCode();

	// SNR test
	foldedData.copyHostToDevice();
	clSNR(&foldedData, &SNRData);
	SNRData.copyDeviceToHost();
	pulsarSNR(observation, foldedData.getHostData(), SNRDataCPU.getHostData());
	for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
		for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
			if ( !same(SNRDataCPU[(period * observation.getNrPaddedDMs()) + dm], SNRData[(period * observation.getNrPaddedDMs()) + dm]) ) {
				wrongValues++;
			}
		}
	}

	cout << "Wrong values: " << wrongValues << " (" << setprecision(2) << (wrongValues * 100.0f) / (observation.getNrDMs() * observation.getNrPeriods()) << "%)" << endl;
	cout << endl;

	return 0;
}

<commit_msg>OpenCL test.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <ctime>

#include <ArgumentList.hpp>
#include <Exceptions.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <utils.hpp>
#include <SNR.hpp>

typedef float dataType;
std::string typeName("float");

int main(int argc, char *argv[]) {
  bool print = false;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
  unsigned int nrDMsPerBlock = 0;
  unsigned int nrPeriodsPerBlock = 0;
  unsigned int nrDMsPerThread = 0;
  unsigned int nrPeriodsPerThread = 0;
	long long unsigned int wrongSamples = 0;
	AstroData::Observation< dataType > observation("SNRTest", typeName);

	try {
    isa::utils::ArgumentList args(argc, argv);
    print = args.getSwitch("-print");
		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
    observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db");
    nrPeriodsPerBlock = args.getSwitchArgument< unsigned int >("-pb");
    nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt");
    nrPeriodsPerThread = args.getSwitchArgument< unsigned int >("-pt");
		observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms"));
    observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods"));
    observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));
	} catch  ( isa::Exceptions::SwitchNotFound &err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }catch ( std::exception &err ) {
    std::cerr << "Usage: " << argv[0] << " [-print] -opencl_platform ... -opencl_device ... -padding ... -db ... -pb ... -dt ... -pt ... -dms ... -periods ... -bins ..." << std::endl;
		return 1;
	}

	// Initialize OpenCL
	cl::Context * clContext = new cl::Context();
	std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
	std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
	std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();

  isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);

	// Allocate memory
  std::vector< dataType > foldedData = std::vector< dataType >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
  cl::Buffer foldedData_d;
  std::vector< dataType > snrs = std::vector< dataType >(observation.getNrPeriods() * observation.getNrPaddedDMs());
  std::vector< dataType > snrs_c = std::vector< dataType >(observation.getNrPeriods() * observation.getNrPaddedDMs());
  cl::Buffer snrs_d;
  try {
    foldedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, foldedData.size() * sizeof(dataType), NULL, NULL);
    snrs_d = cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, snrs.size() * sizeof(dataType), NULL, NULL);
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

	srand(time(NULL));
  for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
    for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
      for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
        foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM] = static_cast< dataType >(rand() % 10);
      }
    }
	}
  std::fill(snrs.begin(), snrs.end(), static_cast< dataType >(0));
  std::fill(snrs_c.begin(), snrs_c.end(), static_cast< dataType >(0));

  // Copy data structures to device
  try {
    clQueues->at(clDeviceID)[0].enqueueWriteBuffer(foldedData_d, CL_FALSE, 0, foldedData.size() * sizeof(dataType), reinterpret_cast< void * >(foldedData.data()));
    clQueues->at(clDeviceID)[0].enqueueWriteBuffer(snrs_d, CL_FALSE, 0, snrs.size() * sizeof(dataType), reinterpret_cast< void * >(snrs.data()));
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

  // Generate kernel
  cl::Kernel * kernel;
  std::string * code = PulsarSearch::getSNROpenCL(nrDMsPerBlock, nrPeriodsPerBlock, nrDMsPerThread, nrPeriodsPerThread, typeName, observation);
  if ( print ) {
    std::cout << *code << std::endl;
  }

  try {
    kernel = isa::OpenCL::compile("snr", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID));
  } catch ( isa::Exceptions::OpenCLError &err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }

  // Run OpenCL kernel and CPU control
  try {
    cl::NDRange global(observation.getNrPaddedDMs() / DMsPerThread, observation.getNrPeriods() / periodsPerThread);
    cl::NDRange local(nrDMsPerBlock, nrPeriodsPerBlock);

    kernel->setArg(0, foldedData_d);
    kernel->setArg(1, snrs_d);

    clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, NULL, &event);
    PulsarSearch::snrFoldedTS(observation, foldedData, snrs_c);
  } catch ( cl::Error &err ) {
    std::cerr << "OpenCL error: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl;
    return 1;
  }

  for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
    for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
      if ( ! isa::utils::same(snrs_c[(period * observation.getNrPaddedDMs()) + dm], snrs[(period * observation.getNrPaddedDMs()) + dm]) ) {
        wrongSamples++;
      }
    }
  }

  if ( wrongSamples > 0 ) {
    std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << std::endl;
  } else {
    std::cout << "TEST PASSED." << std::endl;
  }

	return 0;
}

<|endoftext|>


<commit_before>#include <evenk/task.h>

#include <experimental/memory_resource>

#include <signal.h>
#include <setjmp.h>

int
test()
{
    printf("%s\n", __PRETTY_FUNCTION__);
    return 42;
}

int
testN(int n)
{
    printf("%s\n", __PRETTY_FUNCTION__);
    return n;
}

struct Test
{
    void operator()() const
    {
	printf("%s\n", __PRETTY_FUNCTION__);
    }
};

struct Test24
{
    Test24() = default;

    Test24(Test24 &&other) = default;
    Test24 &operator=(Test24 &&other) = default;

    Test24(const Test24 &other) = delete;
    Test24 &operator=(const Test24 &other) = delete;

    void operator()() const
    {
	printf("%s\n", __PRETTY_FUNCTION__);
    }

    char dummy[24] = {0};
};

struct Test48
{
    Test48() = default;

    Test48(Test48 &&other) = default;
    Test48 &operator=(Test48 &&other) = default;

    void operator()() const
    {
	printf("%s\n", __PRETTY_FUNCTION__);
    }

    char dummy[48] = {0};
};

struct TestD
{
    bool gone = false;

    TestD() {}

    TestD(TestD &&other) {
	gone = other.gone;
	other.gone = true;
    }

    ~TestD()
    {
	if (!gone)
	    printf("%s\n", __PRETTY_FUNCTION__);
    }

    void operator()() const
    {
	printf("%s\n", __PRETTY_FUNCTION__);
    }
};

jmp_buf jmp_target;
void signal_handler(int sig)
{
	longjmp(jmp_target, sig);
}

int
main()
{
	printf("trivial_task tests\n"
	       "==================\n\n");

	{
		auto task = evenk::trivial_task<int>(test);
		auto result = task();
		printf("function result: %d\n", result);
	}
	printf("\n");

	{
		auto func = std::bind(testN, 42);
		auto task = evenk::trivial_task<int>(std::ref(func));
		auto result = task();
		printf("binding result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::trivial_task<int>([] {
			printf("%s\n", __PRETTY_FUNCTION__);
			return 42;
		});
		auto result = task();
		printf("lambda result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::trivial_task<void>(Test());
		task();
	}
	printf("\n");

	{
		auto task = evenk::trivial_task<void, 24>(Test24());
		task();
	}
	printf("\n");

	{
		auto task = evenk::trivial_task<void, 48>(Test48());
		task();
	}
	printf("\n");

	{
		Test48 test;
		auto task = evenk::trivial_task<void>(std::ref(test));
		task();
	}
	printf("\n");

	printf("task tests\n"
	       "==========\n\n");

	{
		auto task = evenk::task<int>(test);
		auto result = task();
		printf("function result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::task<int>(std::bind(testN, 42));
		auto result = task();
		printf("binding result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::task<int, 8, std::experimental::pmr::polymorphic_allocator<char>>(std::bind(testN, 42));
		auto result = task();
		printf("pmr binding result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::task<void>(Test48());
		task();
	}
	printf("\n");

	{
		TestD test;
		auto task = evenk::task<void>(std::move(test));
		task();
	}
	printf("\n");

	printf("default ctor tests\n"
	       "==================\n\n");

	{
		auto task = evenk::trivial_task<void>();
		printf("default trivial_task is callable: %d\n", bool(task));

		auto saved_handler = signal(SIGSEGV, signal_handler);
		auto jmp_result = setjmp(jmp_target);
		if (jmp_result) {
			printf("signal %d caught on its call\n", jmp_result);
		} else {
			task();
		}
		signal(SIGSEGV, saved_handler);
	}
	printf("\n");

	{
		auto task = evenk::task<void>();
		printf("default task is callable: %d\n", bool(task));

		try {
			task();
		} catch (std::bad_function_call&) {
			printf("exception caught on its call\n");
		}
	}
	printf("\n");

	return 0;
}

<commit_msg>Clarify a couple of messages<commit_after>#include <evenk/task.h>

#include <experimental/memory_resource>

#include <signal.h>
#include <setjmp.h>

int
test()
{
    printf("%s\n", __PRETTY_FUNCTION__);
    return 42;
}

int
testN(int n)
{
    printf("%s\n", __PRETTY_FUNCTION__);
    return n;
}

struct Test
{
    void operator()() const
    {
	printf("%s\n", __PRETTY_FUNCTION__);
    }
};

struct Test24
{
    Test24() = default;

    Test24(Test24 &&other) = default;
    Test24 &operator=(Test24 &&other) = default;

    Test24(const Test24 &other) = delete;
    Test24 &operator=(const Test24 &other) = delete;

    void operator()() const
    {
	printf("%s\n", __PRETTY_FUNCTION__);
    }

    char dummy[24] = {0};
};

struct Test48
{
    Test48() = default;

    Test48(Test48 &&other) = default;
    Test48 &operator=(Test48 &&other) = default;

    void operator()() const
    {
	printf("%s\n", __PRETTY_FUNCTION__);
    }

    char dummy[48] = {0};
};

struct TestD
{
    bool gone = false;

    TestD() {}

    TestD(TestD &&other) {
	gone = other.gone;
	other.gone = true;
    }

    ~TestD()
    {
	if (!gone)
	    printf("%s\n", __PRETTY_FUNCTION__);
    }

    void operator()() const
    {
	printf("%s\n", __PRETTY_FUNCTION__);
    }
};

jmp_buf jmp_target;
void signal_handler(int sig)
{
	longjmp(jmp_target, sig);
}

int
main()
{
	printf("trivial_task tests\n"
	       "==================\n\n");

	{
		auto task = evenk::trivial_task<int>(test);
		auto result = task();
		printf("function result: %d\n", result);
	}
	printf("\n");

	{
		auto func = std::bind(testN, 42);
		auto task = evenk::trivial_task<int>(std::ref(func));
		auto result = task();
		printf("binding result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::trivial_task<int>([] {
			printf("%s\n", __PRETTY_FUNCTION__);
			return 42;
		});
		auto result = task();
		printf("lambda result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::trivial_task<void>(Test());
		task();
	}
	printf("\n");

	{
		auto task = evenk::trivial_task<void, 24>(Test24());
		task();
	}
	printf("\n");

	{
		auto task = evenk::trivial_task<void, 48>(Test48());
		task();
	}
	printf("\n");

	{
		Test48 test;
		auto task = evenk::trivial_task<void>(std::ref(test));
		task();
	}
	printf("\n");

	printf("task tests\n"
	       "==========\n\n");

	{
		auto task = evenk::task<int>(test);
		auto result = task();
		printf("function result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::task<int>(std::bind(testN, 42));
		auto result = task();
		printf("binding result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::task<int, 8, std::experimental::pmr::polymorphic_allocator<char>>(std::bind(testN, 42));
		auto result = task();
		printf("pmr binding result: %d\n", result);
	}
	printf("\n");

	{
		auto task = evenk::task<void>(Test48());
		task();
	}
	printf("\n");

	{
		TestD test;
		auto task = evenk::task<void>(std::move(test));
		task();
	}
	printf("\n");

	printf("default ctor tests\n"
	       "==================\n\n");

	{
		auto task = evenk::trivial_task<void>();
		printf("default trivial_task is callable: %d\n", bool(task));

		auto saved_handler = signal(SIGSEGV, signal_handler);
		auto jmp_result = setjmp(jmp_target);
		if (jmp_result) {
			printf("signal %d caught on its call (as expected)\n", jmp_result);
		} else {
			task();
		}
		signal(SIGSEGV, saved_handler);
	}
	printf("\n");

	{
		auto task = evenk::task<void>();
		printf("default task is callable: %d\n", bool(task));

		try {
			task();
		} catch (std::bad_function_call&) {
			printf("exception caught on its call (as expected)\n");
		}
	}
	printf("\n");

	return 0;
}

<|endoftext|>