text:
#include "EditorEngine.h"
#include <vxEngineLib/Message.h>
#include <vxEngineLib/MessageTypes.h>
#include <vxEngineLib/Locator.h>
#include <vxEngineLib/EditorMeshInstance.h>
#include <vxEngineLib/Ray.h>
#include <vxEngineLib/EditorScene.h>
#include <vxEngineLib/Graphics/Light.h>
#include <vxEngineLib/NavMeshGraph.h>
#include <vxEngineLib/EngineConfig.h>
#include <vxEngineLib/debugPrint.h>
#include "developer.h"
#include <vxEngineLib/FileMessage.h>
#include <vxEngineLib/Reference.h>
#include <vxEngineLib/Material.h>
#include <vxEngineLib/Spawn.h>
#include <vxEngineLib/Actor.h>
#include "EngineGlobals.h"
#include <vxLib/Graphics/Camera.h>
#include <vxEngineLib/MeshFile.h>
#include <vxEngineLib/Joint.h>
#include <vxEngineLib/FileEntry.h>
#include <vxEngineLib/ActorFile.h>
#include <vxEngineLib/Graphics/LightGeometryProxy.h>
#include <Dbghelp.h>

u32 g_editorTypeMesh{ 0xffffffff };
u32 g_editorTypeMaterial{ 0xffffffff };
u32 g_editorTypeScene{ 0xffffffff };
u32 g_editorTypeFbx{ 0xffffffff };
u32 g_editorTypeAnimation{ 0xffffffff };
u32 g_editorTypeActor{ 0xffffffff };

namespace EditorEngineCpp
{
	void schedulerThread(vx::TaskManager* scheduler)
	{
		std::atomic_uint running;
		running.store(1);

		scheduler->initializeThread(&running);

		while (running.load() != 0)
		{
			scheduler->swapBuffer();

			scheduler->update();
		}
	}
}

EditorEngine::EditorEngine()
	:m_msgManager(),
	m_physicsAspect(),
	m_renderAspect(),
	m_resourceAspect(),
	m_navmeshGraph(),
	m_previousSceneLoaded(false)
{
}

EditorEngine::~EditorEngine()
{
	if (m_shutdown == 0)
	{
		// something bad happened
		assert(false);
	}
}

bool EditorEngine::initializeImpl(const std::string &dataDir, bool flipTextures)
{
	m_memory = Memory(g_totalMemory, 64);

	m_allocator = vx::StackAllocator(m_memory.get(), m_memory.size());

	m_scratchAllocator = vx::StackAllocator(m_allocator.allocate(1 MBYTE, 64), 1 MBYTE);

	m_msgManager.initialize(&m_allocator, 256);

	//if (!m_resourceAspect.initialize(&m_allocator, dataDir, &m_msgManager, m_physicsAspect.getCooking()))
	if (!m_resourceAspect.initialize(&m_allocator, dataDir, m_physicsAspect.getCooking(), &m_taskManager, &m_msgManager, flipTextures, true))
		return false;

	Locator::provide(&m_resourceAspect);

	return true;
}

bool EditorEngine::createRenderAspectGL(const std::string &dataDir, const RenderAspectDescription &desc, AbortSignalHandlerFun signalHandlerFn)
{
	auto handle = LoadLibrary(L"../../../lib/vxRenderAspectGL_d.dll");
	if (handle == nullptr)
		return false;

	auto proc = (CreateEditorRenderAspectFunction)GetProcAddress(handle, "createEditorRenderAspect");
	auto procDestroy = (DestroyEditorRenderAspectFunction)GetProcAddress(handle, "destroyEditorRenderAspect");
	if (proc == nullptr || procDestroy == nullptr)
		return false;

	auto renderAspect = proc();
	if (renderAspect == nullptr)
		return false;

	m_renderAspect = renderAspect;
	m_renderAspectDll = handle;
	m_destroyFn = procDestroy;

	return true;
}

bool EditorEngine::initializeEditor(HWND panel, HWND tmp, const vx::uint2 &resolution, AbortSignalHandlerFun signalHandlerFn, Editor::Scene* pScene, Logfile* logfile)
{
	vx::activateChannel(vx::debugPrint::Channel_Render);
	vx::activateChannel(vx::debugPrint::Channel_Editor);
	vx::activateChannel(vx::debugPrint::Channel_FileAspect);
	vx::debugPrint::g_verbosity = 1;

	const std::string dataDir("../../data/");
	m_pEditorScene = pScene;
	m_resolution = resolution;
	m_panel = panel;

	if (!m_physicsAspect.initialize(&m_taskManager))
	{
		return false;
	}

	g_engineConfig.m_fovDeg = 66.0f;
	g_engineConfig.m_zFar = 250.0f;
	g_engineConfig.m_renderDebug = true;
	g_engineConfig.m_resolution = resolution;
	g_engineConfig.m_vsync = false;
	g_engineConfig.m_zNear = 0.1f;
	g_engineConfig.m_editor = true;

	g_engineConfig.m_rendererSettings.m_renderMode = Graphics::RendererSettings::Mode_GL;
	g_engineConfig.m_rendererSettings.m_shadowMode = 0;
	g_engineConfig.m_rendererSettings.m_voxelGIMode = 0;
	g_engineConfig.m_rendererSettings.m_maxMeshInstances = 150;

	g_engineConfig.m_rendererSettings.m_voxelSettings.m_voxelGridDim = 16;
	g_engineConfig.m_rendererSettings.m_voxelSettings.m_voxelTextureSize = 128;

	bool flipTextures = (g_engineConfig.m_rendererSettings.m_renderMode == Graphics::RendererSettings::Mode_GL);
	if (!initializeImpl(dataDir, flipTextures))
		return false;

	m_taskManager.initialize(2, 10, 30.0f, &m_allocator);

	m_taskManagerThread = std::thread(EditorEngineCpp::schedulerThread, &m_taskManager);

	RenderAspectDescription renderAspectDesc =
	{
		dataDir,
		panel,
		tmp,
		&m_allocator,
		&g_engineConfig,
		logfile,
		nullptr,
		&m_resourceAspect,
		&m_msgManager,
		&m_taskManager
	};
	//renderAspectDesc.hwnd = m_panel;

	if (!createRenderAspectGL(dataDir, renderAspectDesc, signalHandlerFn))
	{
		return false;
	}

	if (m_renderAspect->initialize(renderAspectDesc, signalHandlerFn) != RenderAspectInitializeError::OK)
	{
		return false;
	}

	//dev::g_debugRenderSettings.setVoxelize(0);
	//dev::g_debugRenderSettings.setShadingMode(ShadingMode::Albedo);
	//m_renderAspect->queueUpdateTask(task);

	Locator::provide(&m_physicsAspect);

	m_msgManager.initialize(&m_allocator, 255);
	m_msgManager.registerListener(m_renderAspect, 1, (u8)vx::MessageType::File | (u8)vx::MessageType::Renderer);
	m_msgManager.registerListener(&m_physicsAspect, 1, (u8)vx::MessageType::File);
	m_msgManager.registerListener(this, 1, (u8)vx::MessageType::File);

	//m_bRun = 1;
	m_shutdown = 0;

	memset(&m_selected, 0, sizeof(m_selected));

	return true;
}

void EditorEngine::shutdownEditor()
{
	if (m_taskManagerThread.joinable())
		m_taskManagerThread.join();

	m_taskManager.shutdown();

	m_resourceAspect.shutdown();

	m_physicsAspect.shutdown();
	if (m_renderAspect)
	{
		m_renderAspect->shutdown(m_panel);
		m_destroyFn(m_renderAspect);
		m_renderAspect = nullptr;
	}
	m_panel = nullptr;

	m_shutdown = 1;
	m_allocator.release();
}

void EditorEngine::stop()
{
	m_taskManager.stop();
}

void EditorEngine::buildNavGraph()
{
	auto &navMesh = m_pEditorScene->getNavMesh();

	m_influenceMap.initialize(navMesh, m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());

	m_navmeshGraph.initialize(navMesh);

	m_renderAspect->updateInfluenceCellBuffer(m_influenceMap);
	m_renderAspect->updateNavMeshGraphNodesBuffer(m_navmeshGraph);
}

void EditorEngine::handleMessage(const vx::Message &evt)
{
	switch (evt.type)
	{
	case(vx::MessageType::File) :
		handleFileEvent(evt);
		break;
	default:
		break;
	}
}

void EditorEngine::handleFileEvent(const vx::Message &evt)
{
	auto fe = (vx::FileMessage)evt.code;

	switch (fe)
	{
	case vx::FileMessage::Mesh_Loaded:
	{
		auto sid = vx::StringID(evt.arg1.u64);
		auto pStr = reinterpret_cast<std::string*>(evt.arg2.ptr);

		if (call_editorCallback(sid))
		{
			vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Loaded mesh %llu %s", sid.value, pStr->c_str());
			auto meshFile = m_resourceAspect.getMesh(sid);

			m_pEditorScene->addMesh(sid, pStr->c_str(), meshFile);

		}
		delete(pStr);

	}break;
	case vx::FileMessage::Texture_Loaded:
		break;
	case vx::FileMessage::Material_Loaded:
	{
		auto sid = vx::StringID(evt.arg1.u64);
		auto pStr = reinterpret_cast<std::string*>(evt.arg2.ptr);
		if (call_editorCallback(sid))
		{
			vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Loaded material %llu  %s", sid.value, pStr->c_str());
			Material* material = m_resourceAspect.getMaterial(sid);
			m_pEditorScene->addMaterial(sid, pStr->c_str(), material);
		}
		delete(pStr);

	}break;
	case vx::FileMessage::EditorScene_Loaded:
	{
		vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Loaded Scene");
		call_editorCallback(vx::StringID(evt.arg1.u64));

		buildNavGraph();
		auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();

		m_renderAspect->updateWaypoints(m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());
		m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
		m_renderAspect->updateSpawns(m_pEditorScene->getSpawns(), m_pEditorScene->getSpawnCount());
		m_renderAspect->updateLightGeometryProxies(m_pEditorScene->getLightGeometryProxies(), m_pEditorScene->getLightGeometryProxyCount());
	}break;
	case vx::FileMessage::Animation_Loaded:
	{
		auto sid = vx::StringID(evt.arg1.u64);
		if (evt.arg2.ptr)
		{
			auto pStr = reinterpret_cast<std::string*>(evt.arg2.ptr);

			vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Loaded Animation %llu", sid.value);
			call_editorCallback(sid);

			m_pEditorScene->addAnimation(sid, std::move(*pStr));
		}
		else
		{
			VX_ASSERT(false);
			//auto str = m_resourceAspect.getAnimationName(sid);
			//if (str)
			//	m_pEditorScene->addAnimation(sid, std::move(std::string(str)));
		}
	}break;
	case vx::FileMessage::Actor_Loaded:
	{
		auto sid = vx::StringID(evt.arg1.u64);
		auto pStr = reinterpret_cast<std::string*>(evt.arg2.ptr);

		call_editorCallback(sid);
		delete(pStr);

	}break;
	default:
	{
	}break;
	}
}

void EditorEngine::requestLoadFile(const vx::FileEntry &fileEntry, vx::Variant arg)
{
	m_resourceAspect.requestLoadFile(fileEntry, arg);
}

void EditorEngine::editor_saveScene(const char* name)
{
	auto sceneCopy = new Editor::Scene();
	m_pEditorScene->copy(sceneCopy);
	vx::Variant arg;
	arg.ptr = sceneCopy;

	m_resourceAspect.requestSaveFile(vx::FileEntry(name, vx::FileType::EditorScene), arg);
}

void EditorEngine::editor_setTypes(u32 mesh, u32 material, u32 scene, u32 fbx, u32 typeAnimation, u32 typeActor)
{
	g_editorTypeMesh = mesh;
	g_editorTypeMaterial = material;
	g_editorTypeScene = scene;
	g_editorTypeFbx = fbx;
	g_editorTypeAnimation = typeAnimation;
	g_editorTypeActor = typeActor;
}

void EditorEngine::update(f32 dt)
{
	m_msgManager.update();

	//m_physicsAspect.update(1.0f/30.f);
	//m_physicsAspect.fetch();

	m_resourceAspect.update();

	m_renderAspect->update();

	m_renderAspect->buildCommands();
	m_renderAspect->submitCommands();
	m_renderAspect->wait();
	m_renderAspect->swapBuffers();
}

void EditorEngine::editor_loadFile(const char *filename, u32 type, Editor::LoadFileCallback f, vx::Variant userArg)
{
	vx::Variant arg;
	arg.ptr = nullptr;
	vx::FileEntry fileEntry;
	if (type == g_editorTypeMesh)
	{
		fileEntry = vx::FileEntry(filename, vx::FileType::Mesh);
		arg.ptr = new std::string(filename);

		vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Trying to load mesh %llu '%s'", fileEntry.getSid().value, filename);
	}
	else if (type == g_editorTypeMaterial)
	{
		fileEntry = vx::FileEntry(filename, vx::FileType::Material);
		arg.ptr = new std::string(filename);

		vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Trying to load material %llu '%s'", fileEntry.getSid().value, filename);
	}
	else if (type == g_editorTypeScene)
	{
		fileEntry = vx::FileEntry(filename, vx::FileType::EditorScene);

		if (m_previousSceneLoaded)
		{
			VX_ASSERT(false);
		}

		arg.ptr = m_pEditorScene;
	}
	else if (type == g_editorTypeFbx)
	{
		fileEntry = vx::FileEntry(filename, vx::FileType::Fbx);
		arg.u32 = 0;
		//p = new std::string(filename);
	}
	else if (type == g_editorTypeAnimation)
	{
		fileEntry = vx::FileEntry(filename, vx::FileType::Animation);
		arg.ptr = new std::string(filename);
	}
	else if (type == g_editorTypeActor)
	{
		fileEntry = vx::FileEntry(filename, vx::FileType::Actor);
		arg.ptr = new std::string(filename);
	}
	else
	{
		vx::verboseChannelPrintF(0, vx::debugPrint::Channel_Editor, "Trying to load unknown file type");
		//assert(false);
	}

	vx::lock_guard<vx::mutex> guard(m_editorMutex);
	m_requestedFiles.insert(fileEntry.getSid(), std::make_pair(f, type));

	m_resourceAspect.requestLoadFile(fileEntry, arg);
}

void EditorEngine::editor_moveCamera(f32 dirX, f32 dirY, f32 dirZ)
{
	m_renderAspect->moveCamera(dirX, dirY, dirZ);
}

void EditorEngine::editor_rotateCamera(f32 dirX, f32 dirY, f32)
{
	static f32 x = 0.0f;
	static f32 y = 0.0f;

	x += dirX * 0.01f;
	y += dirY * 0.01f;

	vx::float4a rot(y, x, 0, 0);
	auto v = vx::quaternionRotationRollPitchYawFromVector(rot);

	m_renderAspect->rotateCamera(v);
}

bool EditorEngine::call_editorCallback(const vx::StringID &sid)
{
	bool result = false;

	vx::lock_guard<vx::mutex> guard(m_editorMutex);
	auto it = m_requestedFiles.find(sid);
	if (it != m_requestedFiles.end())
	{
		(*it->first)(sid.value, it->second);
		m_requestedFiles.erase(it);
		result = true;
	}

	return result;
}

vx::float4a EditorEngine::getRayDir(s32 mouseX, s32 mouseY) const
{
	f32 ndc_x = f32(mouseX) / m_resolution.x;
	f32 ndc_y = f32(mouseY) / m_resolution.y;

	ndc_x = ndc_x * 2.0f - 1.0f;
	ndc_y = 1.0f - ndc_y * 2.0f;

	vx::mat4 projMatrix;
	m_renderAspect->getProjectionMatrix(&projMatrix);
	auto invProjMatrix = vx::MatrixInverse(projMatrix);

	vx::float4a ray_clip(ndc_x, ndc_y, -1, 1);
	vx::float4a ray_eye = vx::Vector4Transform(invProjMatrix, ray_clip);
	ray_eye.z = -1.0f;
	ray_eye.w = 0.0f;

	vx::mat4 viewMatrix;
	m_renderAspect->getViewMatrix(&viewMatrix);

	auto inverseViewMatrix = vx::MatrixInverse(viewMatrix);

	vx::float4a ray_world = vx::Vector4Transform(inverseViewMatrix, ray_eye);
	ray_world = vx::normalize3(ray_world);

	return ray_world;
}

vx::StringID EditorEngine::raytraceAgainstStaticMeshes(s32 mouseX, s32 mouseY, vx::float3* hitPosition) const
{
	auto ray_world = getRayDir(mouseX, mouseY);

	vx::float4a cameraPosition;
	m_renderAspect->getCameraPosition(&cameraPosition);

	PhysicsHitData hitData;

	vx::StringID sid;
	if (m_physicsAspect.raycast_staticDynamic(cameraPosition, ray_world, 50.0f, &hitData))
	{
		*hitPosition = hitData.hitPosition;
		sid = hitData.sid;
	}

	return sid;
}

u32 EditorEngine::getMeshInstanceCount() const
{
	u32 result = 0;

	if (m_pEditorScene)
	{
		result = m_pEditorScene->getMeshInstanceCount();
	}

	return result;
}

const char* EditorEngine::getMeshInstanceName(u32 i) const
{
	auto meshInstances = m_pEditorScene->getMeshInstancesEditor();
	auto sid = meshInstances[i].getNameSid();
	return getMeshInstanceName(sid);
}

const char* EditorEngine::getMeshInstanceName(const vx::StringID &sid) const
{
	return m_pEditorScene->getMeshInstanceName(sid);
}

u64 EditorEngine::getMeshInstanceSid(u32 i) const
{
	u64 sidValue = 0;

	if (m_pEditorScene)
	{
		auto meshInstances = m_pEditorScene->getMeshInstancesEditor();
		sidValue = meshInstances[i].getNameSid().value;
	}

	return sidValue;
}

u64 EditorEngine::getMeshInstanceSid(s32 mouseX, s32 mouseY) const
{
	u64 result = 0;
	if (m_pEditorScene)
	{
		vx::float3 p;
		auto sid = raytraceAgainstStaticMeshes(mouseX, mouseY, &p);
		result = sid.value;
	}

	return result;
}

const char* EditorEngine::getSelectedMeshInstanceName() const
{
	auto meshInstance = (MeshInstance*)m_selected.m_item;
	const char* name = nullptr;
	if (meshInstance)
	{
		name = m_pEditorScene->getMeshInstanceName(meshInstance->getNameSid());
	}
	return name;
}

void EditorEngine::setSelectedMeshInstance(u64 sid)
{
	if (sid != 0)
	{
		auto instance = m_pEditorScene->getMeshInstance(vx::StringID(sid));
		if (instance)
		{
			m_renderAspect->setSelectedMeshInstance(instance);
			m_selected.m_type = SelectedType::MeshInstance;
			m_selected.m_item = (void*)instance;
		}
	}
}

u64 EditorEngine::getSelectedMeshInstanceSid() const
{
	u64 sidValue = 0;

	auto meshInstance = (MeshInstance*)m_selected.m_item;
	if (meshInstance)
	{
		sidValue = meshInstance->getNameSid().value;
	}

	return sidValue;
}

u64 EditorEngine::getMeshInstanceMeshSid(u64 instanceSid) const
{
	u64 sidValue = 0;

	auto meshInstance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
	if (meshInstance != nullptr)
	{
		sidValue = meshInstance->getMeshSid().value;
	}

	return sidValue;
}

void EditorEngine::setMeshInstanceMeshSid(u64 instanceSid, u64 meshSid)
{
	auto meshInstance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
	if (meshInstance != nullptr)
	{
		auto mesh = m_pEditorScene->getMesh(vx::StringID(meshSid));
		m_renderAspect->setMeshInstanceMesh(vx::StringID(instanceSid), vx::StringID(meshSid));
		meshInstance->setMeshSid(vx::StringID(meshSid));

		meshInstance->setBounds(mesh->getMesh());

		m_physicsAspect.editorSetStaticMeshInstanceMesh(meshInstance->getMeshInstance());
	}
}

u64 EditorEngine::getMeshInstanceMaterialSid(u64 instanceSid) const
{
	u64 sidValue = 0;

	auto sid = vx::StringID(instanceSid);
	auto meshInstance = m_pEditorScene->getMeshInstance(sid);
	if (meshInstance)
	{
		auto material = meshInstance->getMaterial();
		sidValue = (*material).getSid().value;
	}

	return sidValue;
}

void EditorEngine::getMeshInstancePosition(u64 sid, vx::float3* position)
{
	auto instance = m_pEditorScene->getMeshInstance(vx::StringID(sid));

	auto &transform = instance->getTransform();
	*position = transform.m_translation;
}

u64 EditorEngine::deselectMeshInstance()
{
	u64 result = 0;
	if (m_pEditorScene)
	{
		auto selectedInstance = (Editor::MeshInstance*)m_selected.m_item;
		if (selectedInstance)
		{
			result = selectedInstance->getNameSid().value;

			m_renderAspect->setSelectedMeshInstance(nullptr);
			m_selected.m_item = nullptr;
		}
	}

	return result;
}

vx::StringID EditorEngine::createMeshInstance()
{
	auto instanceSid = m_pEditorScene->createMeshInstance();
	auto instance = m_pEditorScene->getMeshInstance(instanceSid);
	m_physicsAspect.addMeshInstance(instance->getMeshInstance());

	m_renderAspect->addMeshInstance(*instance);

	return instanceSid;
}

void EditorEngine::removeMeshInstance(u64 sid)
{
	if (m_pEditorScene)
	{
		m_pEditorScene->removeMeshInstance(vx::StringID(sid));
		m_renderAspect->removeMeshInstance(vx::StringID(sid));
	}
}

void EditorEngine::setMeshInstanceMaterial(u64 instanceSid, u64 materialSid)
{
	if (m_pEditorScene)
	{
		auto meshInstance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));

		auto sceneMaterial = m_pEditorScene->getMaterial(vx::StringID(materialSid));
		if (sceneMaterial != nullptr)
		{
			if (m_renderAspect->setSelectedMeshInstanceMaterial(sceneMaterial))
			{
				meshInstance->setMaterial(sceneMaterial);
			}
		}
	}
}

void EditorEngine::setMeshInstancePosition(u64 sid, const vx::float3 &p)
{
	if (m_pEditorScene)
	{
		auto instanceSid = vx::StringID(sid);
		m_pEditorScene->setMeshInstancePosition(instanceSid, p);
		auto instance = m_pEditorScene->getMeshInstance(instanceSid);
		auto transform = instance->getTransform();

		m_renderAspect->setSelectedMeshInstanceTransform(transform);
		m_physicsAspect.editorSetStaticMeshInstanceTransform(instance->getMeshInstance(), instanceSid);
	}
}

void EditorEngine::setMeshInstanceRotation(u64 sid, const vx::float3 &rotationDeg)
{
	if (m_pEditorScene)
	{
		auto rotation = vx::degToRad(rotationDeg);
		auto r = vx::loadFloat3(&rotation);

		auto q = vx::quaternionRotationRollPitchYawFromVector(r);

		vx::float4 tmp;
		vx::storeFloat4(&tmp, q);

		auto instanceSid = vx::StringID(sid);
		m_pEditorScene->setMeshInstanceRotation(instanceSid, tmp);

		auto instance = m_pEditorScene->getMeshInstance(instanceSid);
		auto transform = instance->getTransform();

		m_renderAspect->setSelectedMeshInstanceTransform(transform);
		m_physicsAspect.editorSetStaticMeshInstanceTransform(instance->getMeshInstance(), instanceSid);
	}
}

void EditorEngine::getMeshInstanceRotation(u64 sid, vx::float3* rotationDeg) const
{
	if (m_pEditorScene)
	{
		auto instanceSid = vx::StringID(sid);
		auto instance = m_pEditorScene->getMeshInstance(instanceSid);

		auto transform = instance->getTransform();
		auto q = transform.m_qRotation;

		__m128 axis;
		f32 angle;
		vx::quaternionToAxisAngle(vx::loadFloat4(&q), &axis, &angle);
		axis = vx::normalize3(axis);

		vx::float4a tmpAxis = axis;
		vx::angleAxisToEuler(tmpAxis, angle, rotationDeg);

	}
}

bool EditorEngine::setMeshInstanceName(u64 sid, const char* name)
{
	bool result = false;
	if (m_pEditorScene)
	{
		auto meshInstance = (MeshInstance*)m_selected.m_item;
		result = m_pEditorScene->renameMeshInstance(vx::StringID(sid), name);
	}
	return result;
}

bool EditorEngine::addNavMeshVertex(s32 mouseX, s32 mouseY, vx::float3* position)
{
	vx::float3 hitPos;
	auto sid = raytraceAgainstStaticMeshes(mouseX, mouseY, &hitPos);
	if (sid.value != 0)
	{
		auto ptr = m_pEditorScene->getMeshInstance(sid);
		auto &navMesh = m_pEditorScene->getNavMesh();
		navMesh.addVertex(hitPos);
		m_renderAspect->updateNavMeshBuffer(navMesh);

		*position = hitPos;
	}

	return sid.value != 0;
}

void EditorEngine::removeNavMeshVertex(const vx::float3 &position)
{
	if (m_pEditorScene)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();
		navMesh.removeVertex(position);

		buildNavGraph();
		m_renderAspect->updateNavMeshBuffer(navMesh);
	}
}

void EditorEngine::removeSelectedNavMeshVertex()
{
	if (m_selected.m_navMeshVertices.m_count != 0)
	{
		auto index = m_selected.m_navMeshVertices.m_vertices[0];
		auto &navMesh = m_pEditorScene->getNavMesh();
		navMesh.removeVertex(index);

		m_renderAspect->updateNavMeshBuffer(navMesh);
	}
}

Ray EditorEngine::getRay(s32 mouseX, s32 mouseY)
{
	auto rayDir = getRayDir(mouseX, mouseY);
	vx::float4a cameraPosition;
	m_renderAspect->getCameraPosition(&cameraPosition);

	Ray ray;
	ray.o.x = static_cast<f32>(cameraPosition.x);
	ray.o.y = static_cast<f32>(cameraPosition.y);
	ray.o.z = static_cast<f32>(cameraPosition.z);
	//vx::storeFloat3(&ray.o, cameraPosition);
	vx::storeFloat3(&ray.d, rayDir);
	ray.maxt = 50.0f;

	return ray;
}

u32 EditorEngine::getSelectedNavMeshVertex(s32 mouseX, s32 mouseY)
{
	auto ray = getRay(mouseX, mouseY);

	auto &navMesh = m_pEditorScene->getNavMesh();

	return navMesh.testRayAgainstVertices(ray);
}

bool EditorEngine::selectNavMeshVertex(s32 mouseX, s32 mouseY)
{
	bool result = false;
	if (m_pEditorScene)
	{
		auto selectedIndex = getSelectedNavMeshVertex(mouseX, mouseY);
		if (selectedIndex != 0xffffffff)
		{
			auto &navMesh = m_pEditorScene->getNavMesh();

			m_selected.m_navMeshVertices.m_vertices[0] = selectedIndex;
			m_selected.m_navMeshVertices.m_count = 1;
			m_selected.m_type = SelectedType::NavMeshVertex;
			m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);

			result = true;
		}
	}

	return result;
}

bool EditorEngine::selectNavMeshVertexIndex(u32 index)
{
	bool result = false;
	if (m_pEditorScene)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();

		m_selected.m_navMeshVertices.m_vertices[0] = index;
		m_selected.m_navMeshVertices.m_count = 1;
		m_selected.m_type = SelectedType::NavMeshVertex;
		m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);

		result = true;
	}

	return result;
}

bool EditorEngine::selectNavMeshVertexPosition(const vx::float3 &position)
{
	bool result = false;
	if (m_pEditorScene)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();

		u32 index = 0;
		if (navMesh.getIndex(position, &index))
		{
			m_selected.m_navMeshVertices.m_vertices[0] = index;
			m_selected.m_navMeshVertices.m_count = 1;
			m_selected.m_type = SelectedType::NavMeshVertex;
			m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);

			result = true;
		}
	}

	return result;
}

bool EditorEngine::multiSelectNavMeshVertex(s32 mouseX, s32 mouseY)
{
	bool result = false;
	if (m_pEditorScene)
	{
		auto selectedIndex = getSelectedNavMeshVertex(mouseX, mouseY);
		if (selectedIndex != 0xffffffff)
		{
			auto &navMesh = m_pEditorScene->getNavMesh();

			auto index = m_selected.m_navMeshVertices.m_count;

			m_selected.m_navMeshVertices.m_vertices[index] = selectedIndex;
			++m_selected.m_navMeshVertices.m_count;
			m_selected.m_navMeshVertices.m_count = std::min(m_selected.m_navMeshVertices.m_count, (u8)3u);

			m_selected.m_type = SelectedType::NavMeshVertex;
			m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);

			result = true;
		}
	}

	return result;
}

u32 EditorEngine::deselectNavMeshVertex()
{
	u32 index = 0;
	if (m_pEditorScene)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();
		m_renderAspect->updateNavMeshBuffer(navMesh);

		index = m_selected.m_navMeshVertices.m_vertices[0];
		m_selected.m_navMeshVertices.m_count = 0;
	}
	m_selected.m_item = nullptr;

	return index;
}

bool EditorEngine::createNavMeshTriangleFromSelectedVertices(vx::uint3* selected)
{
	bool result = false;

	if (m_selected.m_navMeshVertices.m_count == 3)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();
		navMesh.addTriangle(m_selected.m_navMeshVertices.m_vertices);

		buildNavGraph();

		m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);

		selected->x = m_selected.m_navMeshVertices.m_vertices[0];
		selected->y = m_selected.m_navMeshVertices.m_vertices[1];
		selected->z = m_selected.m_navMeshVertices.m_vertices[2];

		result = true;
	}

	return result;
}

void EditorEngine::createNavMeshTriangleFromIndices(const vx::uint3 &indices)
{
	if (m_pEditorScene)
	{
		m_selected.m_navMeshVertices.m_count = 3;
		m_selected.m_navMeshVertices.m_vertices[0] = indices.x;
		m_selected.m_navMeshVertices.m_vertices[1] = indices.y;
		m_selected.m_navMeshVertices.m_vertices[2] = indices.z;

		vx::uint3 tmp;
		createNavMeshTriangleFromSelectedVertices(&tmp);
	}
}

void EditorEngine::removeNavMeshTriangle()
{
	if (m_pEditorScene)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();
		navMesh.removeTriangle();

		m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
		buildNavGraph();
	}
}

u32 EditorEngine::getSelectedNavMeshCount() const
{
	return m_selected.m_navMeshVertices.m_count;
}

void EditorEngine::setSelectedNavMeshVertexPosition(const vx::float3 &position)
{
	if (m_selected.m_navMeshVertices.m_count != 0)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();

		auto selectedIndex = m_selected.m_navMeshVertices.m_vertices[0];
		navMesh.setVertexPosition(selectedIndex, position);

		m_renderAspect->updateNavMeshBuffer(navMesh, m_selected.m_navMeshVertices.m_vertices, m_selected.m_navMeshVertices.m_count);
		buildNavGraph();
	}
}

bool EditorEngine::getSelectedNavMeshVertexPosition(vx::float3* p) const
{
	bool result = false;
	if (m_selected.m_navMeshVertices.m_count != 0)
	{
		auto selectedIndex = m_selected.m_navMeshVertices.m_vertices[0];

		auto &navMesh = m_pEditorScene->getNavMesh();
		auto vertices = navMesh.getVertices();

		*p = vertices[selectedIndex];
		result = true;
	}
	return result;
}

u32 EditorEngine::createLight()
{
		Graphics::Light light;
		light.m_position = vx::float3(0);
		light.m_falloff = 5.0f;
		light.m_lumen = 100.0f;

		auto index = m_pEditorScene->getLightCount();

		m_selected.m_item = m_pEditorScene->addLight(light);
		m_selected.m_type = SelectedType::Light;

		auto lightCount = index+1;
		auto lights = m_pEditorScene->getLights();

		m_renderAspect->updateLightBuffer(lights, lightCount);

		return index;
}

bool EditorEngine::getLightIndex(s32 mouseX, s32 mouseY, u32* index)
{
	bool result = false;
	if (m_pEditorScene)
	{
		auto ray = getRay(mouseX, mouseY);
		auto light = m_pEditorScene->getLight(ray);

		if (light)
		{
			auto lights = m_pEditorScene->getLights();
			*index = light - lights;
		}

		result = (light != nullptr);
	}

	return result;
}

void EditorEngine::selectLight(u32 index)
{
	m_selected.m_type = SelectedType::Light;
	m_selected.m_item = m_pEditorScene->getLight(index);
}

void EditorEngine::deselectLight()
{
	if (m_pEditorScene)
	{
		if (m_selected.m_type == SelectedType::Light)
		{
			m_selected.m_item = nullptr;
		}
	}
}

u32 EditorEngine::getLightCount()
{
	return m_pEditorScene->getLightCount();
}

f32 EditorEngine::getLightLumen(u32 index)
{
	auto light = m_pEditorScene->getLight(index);
	return light->m_lumen;
}

void EditorEngine::setLightLumen(u32 index, f32 lumen)
{
	auto light = m_pEditorScene->getLight(index);
	light->m_lumen = lumen;

	//m_renderAspect->updateLightBuffer(m_pEditorScene->getLights(), m_pEditorScene->getLightCount());
}

f32 EditorEngine::getLightFalloff(u32 index)
{
	auto light = m_pEditorScene->getLight(index);
	return light->m_falloff;
}

void EditorEngine::setLightFalloff(u32 index, f32 falloff)
{
	auto light = m_pEditorScene->getLight(index);
	light->m_falloff = falloff;

	//m_renderAspect->updateLightBuffer(m_pEditorScene->getLights(), m_pEditorScene->getLightCount());
}

void EditorEngine::getLightPosition(u32 index, vx::float3* position)
{
	auto light = m_pEditorScene->getLight(index);
	*position = light->m_position;
}

void EditorEngine::setLightPosition(u32 index, const vx::float3* position)
{
	auto light = m_pEditorScene->getLight(index);
	light->m_position = *position;

	m_renderAspect->updateLightBuffer(m_pEditorScene->getLights(), m_pEditorScene->getLightCount());
}

SelectedType EditorEngine::getSelectedItemType() const
{
	return m_selected.m_type;
}

Editor::Scene* EditorEngine::getEditorScene() const
{
	return m_pEditorScene;
}

void EditorEngine::showNavmesh(bool b)
{
	if (m_pEditorScene)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();
		m_renderAspect->showNavMesh(b, navMesh, m_navmeshGraph);
	}
}

void EditorEngine::showInfluenceMap(bool b)
{
	if (m_pEditorScene)
	{
		m_renderAspect->showInfluenceMap(b, m_influenceMap);
	}
}

bool EditorEngine::addWaypoint(s32 mouseX, s32 mouseY, vx::float3* position)
{
	bool result = false;

	vx::float3 hitPos;
	auto sid = raytraceAgainstStaticMeshes(mouseX, mouseY, &hitPos);
	if (sid.value != 0)
	{
		auto &navMesh = m_pEditorScene->getNavMesh();
		if (navMesh.contains(hitPos))
		{
			m_pEditorScene->addWaypoint(hitPos);
			m_renderAspect->updateWaypoints(m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());

			*position = hitPos;
			result = true;
		}
	}

	return result;
}

void EditorEngine::addWaypoint(const vx::float3 &position)
{
	m_pEditorScene->addWaypoint(position);
	m_renderAspect->updateWaypoints(m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());
}

void EditorEngine::removeWaypoint(const vx::float3 &position)
{
	m_pEditorScene->removeWaypoint(position);
	m_renderAspect->updateWaypoints(m_pEditorScene->getWaypoints(), m_pEditorScene->getWaypointCount());
}

void EditorEngine::addSpawn()
{
	if (m_pEditorScene)
	{
		Spawn spawn;
		spawn.type = PlayerType::AI;
		spawn.position = {0, 0, 0};

		m_pEditorScene->addSpawn(std::move(spawn));

		auto count = m_pEditorScene->getSpawnCount();
		auto spawns = m_pEditorScene->getSpawns();
		m_renderAspect->updateSpawns(spawns, count);
	}
}

bool EditorEngine::selectSpawn(s32 mouseX, s32 mouseY, u32* id)
{
	bool result = false;

	if (m_pEditorScene)
	{
		auto ray = getRay(mouseX, mouseY);
		auto spawnId = m_pEditorScene->getSpawnId(ray);
		if (spawnId != 0xffffffff)
		{
			result = true;
			*id = spawnId;
		}
	}

	return result;
}

void EditorEngine::getSpawnPosition(u32 id, vx::float3* position) const
{
	auto spawn = m_pEditorScene->getSpawn(id);
	if (spawn)
	{
		*position = spawn->position;
	}
}

u32 EditorEngine::getSpawnType(u32 id) const
{
	u32 result = 0xffffffff;

	auto spawn = m_pEditorScene->getSpawn(id);
	if (spawn)
	{
		result = (u32)spawn->type;
	}

	return result;
}

void EditorEngine::setSpawnActor(u32 id, u64 actorSid)
{
	m_pEditorScene->setSpawnActor(id, vx::StringID(actorSid));
}

u32 EditorEngine::getSpawnCount()
{
	return m_pEditorScene->getSpawnCount();
}

u32 EditorEngine::getSpawnId(u32 index)
{
	auto spawns = m_pEditorScene->getSpawns();
	return spawns[index].id;
}

void EditorEngine::setSpawnPosition(u32 id, const vx::float3 &position)
{
	auto spawns = m_pEditorScene->getSpawns();
	auto count = m_pEditorScene->getSpawnCount();
	m_pEditorScene->setSpawnPosition(id, position);
	m_renderAspect->updateSpawns(spawns, count);
}

void EditorEngine::setSpawnType(u32 id, u32 type)
{
	m_pEditorScene->setSpawnType(id, type);
}

u64 EditorEngine::getSpawnActor(u32 id)
{
	auto spawn = m_pEditorScene->getSpawn(id);
	return spawn->actorSid.value;
}

u32 EditorEngine::getMeshCount() const
{
	if (m_pEditorScene)
		return m_pEditorScene->getMeshes().size();

	return 0;
}

const char* EditorEngine::getMeshName(u32 i) const
{
	const char* meshName = nullptr;
	if (m_pEditorScene)
	{
		auto &meshes = m_pEditorScene->getMeshes();
		auto sid = meshes.keys()[i];

		meshName = m_pEditorScene->getMeshName(sid);
	}

	return meshName;
}

u64 EditorEngine::getMeshSid(u32 i) const
{
	u64 sidValue = 0;

	if (m_pEditorScene)
	{
		auto &meshes = m_pEditorScene->getMeshes();
		auto sid = meshes.keys()[i];

		sidValue = sid.value;
	}

	return sidValue;
}

u32 EditorEngine::getMaterialCount() const
{
	u32 count = 0;

	if (m_pEditorScene)
	{
		count = m_pEditorScene->getMaterialCount();
	}

	return count;
}

const char* EditorEngine::getMaterialNameIndex(u32 i) const
{
	const char* name = nullptr;

	if (m_pEditorScene)
	{
		auto materials = m_pEditorScene->getMaterials();
		auto sid = (*materials[i]).getSid();

		name = m_pEditorScene->getMaterialName(sid);
	}

	return name;
}

const char* EditorEngine::getMaterialName(u64 sid) const
{
	const char* name = nullptr;

	if (m_pEditorScene)
	{
		name = m_pEditorScene->getMaterialName(vx::StringID(sid));
	}

	return name;
}

u64 EditorEngine::getMaterialSid(u32 i) const
{
	u64 sidValue = 0;

	if (m_pEditorScene)
	{
		auto materials = m_pEditorScene->getMaterials();
		auto sid = (*materials[i]).getSid();

		sidValue = sid.value;
	}

	return sidValue;
}

void EditorEngine::setMeshInstanceAnimation(u64 instanceSid, u64 animSid)
{
	auto instance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
	if (instance)
	{
		instance->setAnimationSid(vx::StringID(animSid));
	}
}

u64 EditorEngine::getMeshInstanceAnimation(u64 instanceSid)
{
	u64 result = 0;
	auto instance = m_pEditorScene->getMeshInstance(vx::StringID(instanceSid));
	if (instance)
	{
		result = instance->getAnimationSid().value;
	}
	return result;
}

u32 EditorEngine::getAnimationCount() const
{
	return m_pEditorScene->getAnimationCount();
}

const char* EditorEngine::getAnimationNameIndex(u32 i) const
{
	return m_pEditorScene->getAnimationNameIndex(i);
}

u64 EditorEngine::getAnimationSidIndex(u32 i) const
{
	return m_pEditorScene->getAnimationSidIndex(i);
}

u32 EditorEngine::getMeshPhysxType(u64 sid) const
{
	u32 type = 0xffffffff;

	auto &meshes = m_pEditorScene->getMeshes();
	auto it = meshes.find(vx::StringID(sid));
	if (it != meshes.end())
	{
		type = (u32)(*it)->getPhysxMeshType();
	}

	return type;
}

void EditorEngine::setMeshPhysxType(u64 sid, u32 type)
{
	auto meshSid = vx::StringID(sid);
	auto meshFile = m_resourceAspect.getMesh(meshSid);
	if (meshFile == nullptr)
	{
		return;
		//VX_ASSERT(false);
		/*auto &meshDataAllocator = m_resourceAspect.getMeshDataAllocator();

		if (m_physicsAspect.setMeshPhysxType(meshFile, (PhsyxMeshType)type, &meshDataAllocator))
		{
			auto fileName = m_resourceAspect.getLoadedFileName(vx::StringID(sid));

			m_fileAspect.requestSaveFile(vx::FileEntry(fileName, vx::FileType::Mesh), meshFile.get());
		}*/
	}

	auto meshManager = m_resourceAspect.getMeshManager();
	auto physxType = (PhsyxMeshType)type;
	std::unique_lock<std::mutex> lock;
	auto dataAllocator = meshManager->lockDataAllocator(&lock);
	if (m_physicsAspect.setMeshPhysxType(meshFile, physxType, dataAllocator))
	{
		vx::Variant arg;
		arg.ptr = meshFile;

		auto meshName = meshManager->getName(meshSid);
		vx::FileEntry fileEntry(meshName, vx::FileType::Mesh);
		m_resourceAspect.requestSaveFile(fileEntry, arg);
	}
}

u32 EditorEngine::getMeshInstanceRigidBodyType(u64 sid) const
{
	u32 type = 0xffffffff;

	auto it = m_pEditorScene->getMeshInstance(vx::StringID(sid));
	if (it != nullptr)
	{
		type = (u32)it->getRigidBodyType();
	}

	return type;
}

void EditorEngine::setMeshInstanceRigidBodyType(u64 sid, u32 type)
{
	auto instanceSid = vx::StringID(sid);
	auto editorInstance = m_pEditorScene->getMeshInstance(instanceSid);
	if (editorInstance != nullptr)
	{
		auto rigidBodyType = (PhysxRigidBodyType)type;

		if (m_physicsAspect.setMeshInstanceRigidBodyType(instanceSid, editorInstance->getMeshInstance(), rigidBodyType))
		{
			editorInstance->setRigidBodyType(rigidBodyType);
		}
	}
}

void EditorEngine::addJoint(const vx::StringID &sid0, const vx::StringID &sid1, const vx::float3 &p0, const vx::float3 &p1)
{
	Joint joint;

	joint.sid0 = sid0;
	joint.sid1 = sid1;
	joint.p0 = p0;
	joint.q0 = {0, 0, 0, 1};
	joint.p1= p1;
	joint.q1 = { 0, 0, 0, 1 };
	joint.type = JointType::Revolute;

	if (sid0.value != 0)
	{
		joint.p0.x = 0;
		joint.p0.y = 0;
		joint.p0.z = 0;
	}

	if (sid1.value != 0)
	{
		joint.p1.x = 0;
		joint.p1.y = 0;
		joint.p1.z = 0;
	}

	if (m_physicsAspect.createJoint(joint))
	{
		puts("created joint");
		m_pEditorScene->addJoint(joint);

		auto jointCount = m_pEditorScene->getJointCount();
		auto joints = m_pEditorScene->getJoints();

		auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
		m_renderAspect->updateJoints(joints, jointCount, sortedInstances);
	}
}

void EditorEngine::addJoint(const vx::StringID &sid)
{
	auto instance = m_pEditorScene->getMeshInstance(sid);
	if (instance)
	{
		auto &transform = instance->getTransform();

		addJoint(sid, vx::StringID(0), transform.m_translation, transform.m_translation);
	}
}

void EditorEngine::removeJoint(u32 index)
{
	m_pEditorScene->eraseJoint(index);
	auto jointCount = m_pEditorScene->getJointCount();
	auto joints = m_pEditorScene->getJoints();

	auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
	m_renderAspect->updateJoints(joints, jointCount, sortedInstances);
}

u32 EditorEngine::getJointCount() const
{
	return m_pEditorScene->getJointCount();
}

#include <DirectXMath.h>

void EditorEngine::getJointData(u32 i, vx::float3* p0, vx::float3* q0, vx::float3* p1, vx::float3* q1, u64* sid0, u64* sid1, u32* limitEnabled, f32* limitMin, f32* limitMax) const
{
	auto quaternionToAngles = [](const vx::float4 &q, vx::float3* rotationDeg)
	{
		if (q.x == 0 && q.y == 0 && q.z == 0)
		{
			*rotationDeg = {0, 0, 0};
		}
		else
		{
			auto qq = vx::loadFloat4(&q);

			__m128 axis, axis0;
			f32 angle, angle0;
			DirectX::XMQuaternionToAxisAngle(&axis0, &angle0, qq);
			vx::quaternionToAxisAngle(qq, &axis, &angle);
			axis = vx::normalize3(axis);

			//auto ttt = _mm_mul_ps(axis, _mm_load1_ps(&angle));

			vx::float4a tmpAxis = axis;
			vx::angleAxisToEuler(tmpAxis, angle, rotationDeg);
		}
	};

	auto joints = m_pEditorScene->getJoints();

	auto &joint = joints[i];
	quaternionToAngles(joint.q0, q0);
	quaternionToAngles(joint.q1, q1);
	*p0 = joint.p0;
	*p1 = joint.p1;
	*sid0 = joint.sid0.value;
	*sid1 = joint.sid1.value;
	*limitEnabled = joint.limitEnabled;
	*limitMin = joint.limit.x;
	*limitMax = joint.limit.y;
}

bool EditorEngine::selectJoint(s32 mouseX, s32 mouseY, u32* index)
{
	auto ray = getRay(mouseX, mouseY);
	ray.maxt = 10.0f;

	auto joint = m_pEditorScene->getJoint(ray, index);

	return (joint != nullptr);
}

void EditorEngine::setJointPosition0(u32 index, const vx::float3 &p)
{
	m_pEditorScene->setJointPosition0(index, p);
	auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
	m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
}

void EditorEngine::setJointPosition1(u32 index, const vx::float3 &p)
{
	m_pEditorScene->setJointPosition1(index, p);
	auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
	m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
}

void EditorEngine::setJointBody0(u32 index, u64 sid)
{
	m_pEditorScene->setJointBody0(index, sid);
}

void EditorEngine::setJointBody1(u32 index, u64 sid)
{
	m_pEditorScene->setJointBody1(index, sid);
}

void EditorEngine::setJointRotation0(u32 index, const vx::float3 &q)
{
	auto qq = vx::quaternionRotationRollPitchYawFromVector(vx::degToRad(vx::loadFloat3(&q)));

	vx::float4 tmp;
	vx::storeFloat4(&tmp, qq);

	m_pEditorScene->setJointRotation0(index, tmp);
	auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
	m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
}

void EditorEngine::setJointRotation1(u32 index, const vx::float3 &q)
{
	auto qq = vx::quaternionRotationRollPitchYawFromVector(vx::degToRad(vx::loadFloat3(&q)));

	vx::float4 tmp;
	vx::storeFloat4(&tmp, qq);

	m_pEditorScene->setJointRotation1(index, tmp);
	auto &sortedInstances = m_pEditorScene->getSortedMeshInstances();
	m_renderAspect->updateJoints(m_pEditorScene->getJoints(), m_pEditorScene->getJointCount(), sortedInstances);
}

void EditorEngine::setJointLimit(u32 index, u32 enabled, f32 limitMin, f32 limitMax)
{
	m_pEditorScene->setJointLimit(index, enabled, limitMin, limitMax);
}

u64 EditorEngine::createActor(const char* name, u64 meshSid, u64 materialSid)
{
	vx::FileEntry fileEntry(name, vx::FileType::Actor);

	auto actorFile = new ActorFile(ActorFile::getGlobalVersion());

	auto materialName = m_resourceAspect.getMaterialManager()->getName(vx::StringID(materialSid));
	auto meshName = m_resourceAspect.getMeshManager()->getName(vx::StringID(meshSid));

	const u32 bufferSize = 31;
	auto meshSize = strlen(meshName);
	auto materialSize = strlen(materialName);

	VX_ASSERT(bufferSize >= meshSize && bufferSize >= materialSize);

	char buffer[bufferSize + 1];
	memset(buffer, 0, sizeof(buffer));
	memcpy(buffer, meshName, meshSize);
	actorFile->setMesh(buffer);

	memset(buffer, 0, sizeof(buffer));
	memcpy(buffer, materialName, materialSize);
	actorFile->setMaterial(buffer);

	vx::Variant arg;
	arg.ptr = actorFile;
	m_resourceAspect.requestSaveFile(fileEntry, arg);

	Actor actor;
	actor.m_mesh = meshSid;
	actor.m_material = materialSid;
	m_resourceAspect.addActor(fileEntry.getSid(), std::string(name), actor);

	return fileEntry.getSid().value;
}

const char* EditorEngine::getActorName(u64 sid) const
{
	return m_resourceAspect.getActorManager()->getName(vx::StringID(sid));
}

u32 EditorEngine::getLightGeometryProxyCount() const
{
	return m_pEditorScene->getLightGeometryProxyCount();
}

void EditorEngine::createLightGeometryProxy(const vx::float3 &center, const vx::float3 &halfDim)
{
	AABB bounds;
	bounds.min = center - halfDim;
	bounds.max = center + halfDim;

	m_pEditorScene->addLightGeometryProxy(bounds);

	m_renderAspect->updateLightGeometryProxies(m_pEditorScene->getLightGeometryProxies(), m_pEditorScene->getLightGeometryProxyCount());
}

void EditorEngine::setLightGeometryProxyBounds(u32 index, const vx::float3 &center, const vx::float3 &halfDim)
{
	AABB bounds;
	bounds.min = center - halfDim;
	bounds.max = center + halfDim;
	m_pEditorScene->setLightGeometryProxyBounds(index, bounds);

	m_renderAspect->updateLightGeometryProxies(m_pEditorScene->getLightGeometryProxies(), m_pEditorScene->getLightGeometryProxyCount());
}

void EditorEngine::getLightGeometryProxyBounds(u32 index, vx::float3* center, vx::float3* halfDimOut) const
{
	auto ptr = m_pEditorScene->getLightGeometryProxies();

	auto bounds = ptr[index].m_bounds;

	auto halfDim = (bounds.max - bounds.min) * 0.5f;

	*center = bounds.min + halfDim;
	*halfDimOut = halfDim;
}

u32 EditorEngine::getLightGeometryProxyLightCount(u32 index) const
{
	auto ptr = m_pEditorScene->getLightGeometryProxies();

	return ptr[index].m_lightCount;
}

void EditorEngine::testLightGeometryProxies()
{
	Editor::TestLightGeometryProxiesDesc desc;
	desc.lightCount = m_pEditorScene->getLightCount();
	desc.lights = m_pEditorScene->getLights();
	desc.proxies = m_pEditorScene->getLightGeometryProxies();
	desc.proxyCount = m_pEditorScene->getLightGeometryProxyCount();

	m_renderAspect->testLightGeometryProxies(desc);
}


text:
```bash
sudo apt-get install git make libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev

git clone git://github.com/yyuu/pyenv.git ~/.pyenv
```

from man bash:

>  When bash is invoked as an interactive login shell, or as  a  non-interac-
   tive  shell  with the --login option, it first reads and executes commands
   from the file /etc/profile, if that file exists.  After reading that file,
   it  looks  for  ~/.bash_profile,  ~/.bash_login,  and  ~/.profile, in that
   order, and reads and executes commands from the first one that exists  and
   is readable.  The --noprofile option may be used when the shell is started
   to inhibit this behavior.

In one of these files (~/.bash_profile,  ~/.bash_login,  and  ~/.profile) , you can see tthe code like this:

```bash
if [ "$BASH" ]; then
  if [ -f ~/.bashrc ]; then
    . ~/.bashrc
  fi
fi
```

if not, then just add this code in _~/.bash_profile_

### Install

```bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
. ~/.bashrc
```

Install multiple versions of python:
```bash
pyenv install 2.7.7
pyenv install 3.4.1

pyenv rehash
pyenv versions
```

Please read [«Command Reference»](https://github.com/yyuu/pyenv/blob/master/COMMANDS.md)

## Pyenv-virtualenv: A Pyenv Plugin To Manage Virtualenv

```bash
mkdir -p ~/.pyenv/plugins
git clone git://github.com/yyuu/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv
git clone git://github.com/yyuu/pyenv-virtualenvwrapper.git ~/.pyenv/plugins/pyenv-virtualenvwrapper
echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc
```

Please read [«Using pyenv virtualenv with pyenv»](https://github.com/yyuu/pyenv-virtualenv#using-pyenv-virtualenv-with-pyenv)

### Use Case

```bash
$ pyenv versions
* system (set by /root/.pyenv/version)
  2.7.7
  3.4.1

$ mkdir -p ~/projects/test && cd ~/projects/test

$ pyenv virtualenv --no-site-packages 2.7.7 venv-2.7.7

$ pyenv local venv-2.7.7

$ pip install pytz

$ pip freeze
pytz==2014.4
wsgiref==0.1.2

$ python --version
Python 2.7.7

$ cd ..

$ python --version
Python 2.7.6
```

Pyenv creates a file in the directory _.python-version_ which contains the information about what version of python with which environment to use for this project. Virtualenv is activated automatically when you _cd_ in the project folder.

## Useful Links

[github.com/yyuu/pyenv](https://github.com/yyuu/pyenv)
[github.com/yyuu/pyenv-installer](https://github.com/yyuu/pyenv-installer)
[github.com/yyuu/pyenv-virtualenv](https://github.com/yyuu/pyenv-virtualenv)
[github.com/yyuu/pyenv-virtualenvwrapper](https://github.com/yyuu/pyenv-virtualenvwrapper)
[docs.python.org/dev/library/venv.html](https://docs.python.org/dev/library/venv.html)
[virtualenv.pypa.io/en/latest/](https://virtualenv.pypa.io/en/latest/)
[virtualenvwrapper.readthedocs.org/en/latest/](http://virtualenvwrapper.readthedocs.org/en/latest/)

redpajama_set_name: RedPajamaGithub


text:
template <typename K1> struct O {
  template <typename K2> struct I {};
};

template <typename T>
struct A : typename O<T>::template I<int> {   // { dg-error "keyword 'typename' not allowed" }
  A() :    typename O<T>::template I<int>()   // { dg-error "keyword 'typename' not allowed" }
  {};
};

template <typename T>
struct B : O<T>::template I<int> {
  B() :    O<T>::I<int>()   // { dg-error "used as template|it is a template" "" }
  {};
};

// { dg-bogus "end of input" "bogus token skipping in the parser" { xfail *-*-* } 17 }


text:
![Dr. Crusher portrait by aliceazzo.](https://hackadaycom.files.wordpress.com/2014/10/9132521412537668507.jpg "The fantastic Beverly Crusher artwork is by aliceazzo and the link to her deviantart is http://aliceazzo.deviantart.com/ - This work is entirely hers and I havent asked permission to associate it with my application, website, nor have I even spoken to this person before so please keep in mind that this image is not part of the same license as this software.")

Image © [aliceazzo](http://aliceazzo.deviantart.com/ "aliceazzo's deviant art page.") [http://aliceazzo.deviantart.com/].

beverly-crusher [http://electronoob.com]
========================================
Released under the terms of the MIT license.
Copyright (c) 2014 electronoob.
All rights reserved.

I consider this program to be feature complete and finished (as of build #269).

**Syntax**

To output file direct to alsa default device:

	./crusher --input mysing.raw --alsa

To generate Arduino sketch:

	./crusher --input mysing.raw --arduino --bitrate 10 > arduino_sketch.c

To set the output bitrate, enter a positive integer to divide the bitrate by:

	./crusher --input mysing.raw --alsa --bitrate 2

**compile**

	make clean && make all

**about**

I had been looking for a tool to convert audio down to 1-bit depth
but struggled to find one, so I'm writing one which can also do
other neat stuff such as preview with ALSA and downsample the
bitrate easily.

Instructables [project page here](http://www.instructables.com/id/Beverly-Crusher-bit-crushing-1-bit-Arduino-music/ "Instructables").

[![Demo and project information.](http://img.youtube.com/vi/U2mQjJXUQ4k/0.jpg)](http://www.youtube.com/watch?v=U2mQjJXUQ4k)

[![Remixing in C demo.](http://img.youtube.com/vi/jrQg8p99Lag/0.jpg)](http://www.youtube.com/watch?v=jrQg8p99Lag)


text:
class TimeChooser {
    public:
        TimeChooser( LiquidCrystal *lcd, RotaryEncoder *encoder );
        int getTime();
    private:
        LiquidCrystal *_lcd;
        RotaryEncoder *_encoder;
        int8_t cursorSelect( int8_t locs[][2], int8_t count, int8_t pos=0 );
        int getInt( char* pattern, int maxCal, int col, int row );
};

class CountdownTimer {
    public:
        CountdownTimer( LiquidCrystal *lcd, RotaryEncoder *encoder );
        void start( int durationInSeconds );

    private:
        RotaryEncoder *_encoder;
        LiquidCrystal *_lcd;
        long startTime;
        long duration;

        long timeLeft();
        void printTime();
};

#endif


text:
import datetime

from django.template.context import RequestContext
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_list_or_404, get_object_or_404, \
                             redirect, render
from django.utils.safestring import SafeString
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
from django.utils.translation import ugettext as _

from rest_framework import filters
from rest_framework import generics,viewsets
from rest_framework import permissions

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope, TokenHasScope

from operis.api.renderers import EmberJSONRenderer
from operis.api.filters import *
from operis.api import mixins
from operis.api.authentication import KeyAuthentication
{% for animport in imports %}
from {{animport}} import *
{% endfor %}

from {{app}}.django_operis.serializers import *

{% for model in models %}
class {{ model.singular }}ViewSet(viewsets.ModelViewSet):
    #permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    permission_classes = [permissions.AllowAny]
    model = {{ model.singular }}
    serializer_class = {{ model.singular }}Serializer
    renderer_classes = (EmberJSONRenderer,)
    filter_backends = (SearchFilter,)
    queryset = {{ model.singular }}.objects.all()
    {{model.filter_fields_converted}}
    {{model.search_fields_converted}}

class {{ model.singular}}View(mixins.ListByIdMixin, generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [permissions.AllowAny]
    model =  {{ model.singular }}
    serializer_class =  {{ model.singular }}Serializer
    renderer_classes = (EmberJSONRenderer,)
{% endfor %}


text:
package org.olat.data.commons.fileutil;

import java.util.Arrays;

/**
 * Initial Date: 26.10.2011

 *
 * @author guretzki
 */
public class FileNameValidator {
    // windows: invalid characters for filenames: \ / : * ? " < > |
    // linux: invalid characters for file/folder names: /, but you have to escape certain chars, like ";$%&*"
    // OLAT reserved char: ":"
    private static char[] FILE_NAME_FORBIDDEN_CHARS = { '/', '\n', '\r', '\t', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };
    // private static char[] FILE_NAME_ACCEPTED_CHARS = { 'ä', 'Ä', 'ü', 'Ü', 'ö', 'Ö', ' '};
    private static char[] FILE_NAME_ACCEPTED_CHARS = { '\u0228', '\u0196', '\u0252', '\u0220', '\u0246', '\u0214', ' ' };

    /**
     * Simple check for filename validity. It compares each character if it is accepted, forbidden or in a certain (Latin-1) range.
     *

     * Characters < 33 --> control characters and space Characters > 255 --> above ASCII http://www.danshort.com/ASCIImap/ TODO: control chars from 127 - 157 should also
     * not be accepted TODO: how about non ascii chars in filenames, they should also work! See: OLAT-5704
     *
     * @param filename
     * @return true if filename valid
     */
    public static boolean validate(String filename) {
        if (filename == null) {
            return false;
        }
        Arrays.sort(FILE_NAME_FORBIDDEN_CHARS);
        Arrays.sort(FILE_NAME_ACCEPTED_CHARS);

        for (int i = 0; i < filename.length(); i++) {
            char character = filename.charAt(i);
            if (Arrays.binarySearch(FILE_NAME_ACCEPTED_CHARS, character) >= 0) {
                continue;
            } else if (character < 33 || character > 255 || Arrays.binarySearch(FILE_NAME_FORBIDDEN_CHARS, character) >= 0) {
                return false;
            }
        }
        // check if there are any unwanted path denominators in the name
        if (filename.indexOf("..") > -1) {
            return false;
        }
        return true;
    }

}


text:
import {customElement, html, internalProperty, property, query} from 'lit-element';
// @ts-ignore, the qrious package isn't typed
import QRious from 'qrious';

import {openModalStyles} from '../../../styles.css.js';
import {ConnectedLitElement} from '../../connected_lit_element/connected_lit_element.js';

/**
 * Modal for displaying the QR Code & link
 */
@customElement('mobile-modal')
export class MobileModal extends ConnectedLitElement {
  static styles = openModalStyles;

  @property({type: Number}) pipeId = 0;
  @internalProperty() isOpen: boolean = false;
  @internalProperty() isNewQRCode = true;
  @query('canvas#qr') canvasQR!: HTMLCanvasElement;

  get viewableSite(): string {
    const path = window.location.origin + window.location.pathname;
    return `${path}view/?id=${this.pipeId}`;
  }

  open() {
    if (this.isNewQRCode) {
      new QRious({element: this.canvasQR, value: this.viewableSite, size: 200});
      this.isNewQRCode = false
    }
    this.isOpen = true;
  }

  close() {
    this.isOpen = false;
  }

  render() {
    return html`
<paper-dialog id="file-modal" modal ?opened=${this.isOpen} class="dialog">

Mobile View

      Use the QR Code to open your edited model, environment image, and &ltmodel-viewer&gt snippet on a mobile device to test out AR features.
      After every subsequent change, click the "Refresh Mobile" button.

    <canvas id="qr" style="display: block; margin-bottom: 90px;"></canvas>

      This uses a third-party piping server to deploy to your mobile device. This server does not store data.

      We use this server: https://piping.glitch.me/

    <mwc-button unelevated icon="cancel"
      @click=${this.close}>Close</mwc-button>

</paper-dialog>`;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'mobile-modal': MobileModal;
  }
}


text:
import { TranscriptionModule } from './transcription.module';

describe('TranscriptionModule', () => {
  let transcriptionModule: TranscriptionModule;

  beforeEach(() => {
    transcriptionModule = new TranscriptionModule();
  });

  it('should create an instance', () => {
    expect(transcriptionModule).toBeTruthy();
  });
});


text:
package org.apache.airavata.registry.core.workflow.catalog.utils;

import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.registry.core.workflow.catalog.model.*;
import org.apache.airavata.registry.core.workflow.catalog.resources.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;

public class WorkflowCatalogJPAUtils {
    private final static Logger logger = LoggerFactory.getLogger(WorkflowCatalogJPAUtils.class);
    private static final String PERSISTENCE_UNIT_NAME = "workflowcatalog_data";
    private static final String WFCATALOG_JDBC_DRIVER = "wfcatalog.jdbc.driver";
    private static final String WFCATALOG_JDBC_URL = "wfcatalog.jdbc.url";
    private static final String WFCATALOG_JDBC_USER = "wfcatalog.jdbc.user";
    private static final String WFCATALOG_JDBC_PASSWORD = "wfcatalog.jdbc.password";
    private static final String WFCATALOG_VALIDATION_QUERY = "wfcatalog.validationQuery";
    private static final String JPA_CACHE_SIZE = "jpa.cache.size";
    private static final String JPA_CACHE_ENABLED = "cache.enable";
    @PersistenceUnit(unitName="workflowcatalog_data")
    protected static EntityManagerFactory factory;
    @PersistenceContext(unitName="worlkflowcatalog_data")
    private static EntityManager wfCatEntityManager;

    public static EntityManager getEntityManager() throws ApplicationSettingsException {
        if (factory == null) {
            String connectionProperties = "DriverClassName=" + readServerProperties(WFCATALOG_JDBC_DRIVER) + "," +
                    "Url=" + readServerProperties(WFCATALOG_JDBC_URL) + "?autoReconnect=true," +
                    "Username=" + readServerProperties(WFCATALOG_JDBC_USER) + "," +
                    "Password=" + readServerProperties(WFCATALOG_JDBC_PASSWORD) +
                    ",validationQuery=" + readServerProperties(WFCATALOG_VALIDATION_QUERY);
            System.out.println(connectionProperties);
            Map<String, String> properties = new HashMap<String, String>();
            properties.put("openjpa.ConnectionDriverName", "org.apache.commons.dbcp.BasicDataSource");
            properties.put("openjpa.ConnectionProperties", connectionProperties);
            properties.put("openjpa.DynamicEnhancementAgent", "true");
            properties.put("openjpa.RuntimeUnenhancedClasses", "unsupported");
            // For app catalog, we don't need caching
//            properties.put("openjpa.DataCache","" + readServerProperties(JPA_CACHE_ENABLED) + "(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)");
//            properties.put("openjpa.QueryCache","" + readServerProperties(JPA_CACHE_ENABLED) + "(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)");
            properties.put("openjpa.RemoteCommitProvider","sjvm");
            properties.put("openjpa.Log","DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=INFO");
            properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
            properties.put("openjpa.jdbc.QuerySQLCache", "false");
            properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=31536000,  autoReconnect=true");
            factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
        }
        wfCatEntityManager = factory.createEntityManager();
        return wfCatEntityManager;
    }

    private static String readServerProperties (String propertyName) throws ApplicationSettingsException {
        try {
            return ServerSettings.getSetting(propertyName);
        } catch (ApplicationSettingsException e) {
            logger.error("Unable to read airavata-server.properties...", e);
            throw new ApplicationSettingsException("Unable to read airavata-server.properties...");
        }
    }

    /**
     *
     * @param type model type
     * @param o model type instance
     * @return corresponding resource object
     */
    public static WorkflowCatalogResource getResource(WorkflowCatalogResourceType type, Object o) {
        switch (type){
            case WORKFLOW:
                if (o instanceof Workflow) {
                    return createWorkflow((Workflow) o);
                } else {
                    logger.error("Object should be a Workflow.", new IllegalArgumentException());
                    throw new IllegalArgumentException("Object should be a Workflow.");
                }
            case WORKFLOW_INPUT:
                if (o instanceof WorkflowInput){
                    return createWorflowInput((WorkflowInput) o);
                }else {
                    logger.error("Object should be a Workflow Input.", new IllegalArgumentException());
                    throw new IllegalArgumentException("Object should be a Workflow Input.");
                }
            case WORKFLOW_OUTPUT:
                if (o instanceof WorkflowOutput){
                    return createWorkflowOutput((WorkflowOutput) o);
                }else {
                    logger.error("Object should be a Workflow Output.", new IllegalArgumentException());
                    throw new IllegalArgumentException("Object should be a Workflow Output.");
                }
            case COMPONENT_STATUS:
                if (o instanceof ComponentStatus){
                    return createComponentStatus((ComponentStatus) o);
                }else {
                    logger.error("Object should be a Workflow Output.", new IllegalArgumentException());
                    throw new IllegalArgumentException("Object should be a Workflow Output.");
                }
            case NODE:
                if (o instanceof Node){
                    return createNode((Node) o);
                }else {
                    logger.error("Object should be a Node.", new IllegalArgumentException());
                    throw new IllegalArgumentException("Object should be a Node.");
                }
            case PORT:
                if (o instanceof Port){
                    return createPort((Port) o);
                }else {
                    logger.error("Object should be a Port.", new IllegalArgumentException());
                    throw new IllegalArgumentException("Object should be a Port.");
                }
            case EDGE:
                if (o instanceof Edge){
                    return createEdge((Edge) o);
                }else {
                    logger.error("Object should be a Edge.", new IllegalArgumentException());
                    throw new IllegalArgumentException("Object should be a Edge.");
                }
            default:
                logger.error("Illegal data type..", new IllegalArgumentException());
                throw new IllegalArgumentException("Illegal data type..");
        }
    }

    private static WorkflowCatalogResource createWorflowInput(WorkflowInput o) {
        WorkflowInputResource resource = new WorkflowInputResource();
        if (o != null){
            resource.setWfTemplateId(o.getTemplateID());
            resource.setInputKey(o.getInputKey());
            if (o.getInputVal() != null){
                resource.setInputVal(new String(o.getInputVal()));
            }
            resource.setDataType(o.getDataType());
            resource.setMetadata(o.getMetadata());
            resource.setAppArgument(o.getAppArgument());
            resource.setInputOrder(o.getInputOrder());
            resource.setUserFriendlyDesc(o.getUserFriendlyDesc());
            resource.setStandardInput(o.isStandardInput());
            resource.setRequired(o.isRequired());
            resource.setRequiredToCMD(o.isRequiredToCMD());
            resource.setDataStaged(o.isDataStaged());
            resource.setWorkflowResource((WorkflowResource)createWorkflow(o.getWorkflow()));
        }
        return resource;
    }

    private static WorkflowCatalogResource createWorkflowOutput(WorkflowOutput o) {
        WorkflowOutputResource resource = new WorkflowOutputResource();
        if (o != null){
            resource.setWfTemplateId(o.getTemplateId());
            resource.setOutputKey(o.getOutputKey());
            if (o.getOutputVal() != null){
                resource.setOutputVal(new String(o.getOutputVal()));
            }
            resource.setDataType(o.getDataType());
            resource.setDataMovement(o.isDataMovement());
            resource.setDataNameLocation(o.getDataNameLocation());
            resource.setWorkflowResource((WorkflowResource)createWorkflow(o.getWorkflow()));
        }
        return resource;
    }

    private static ComponentStatusResource createComponentStatus(ComponentStatus o) {
        ComponentStatusResource resource = new ComponentStatusResource();
        if (o != null){
            resource.setStatusId(o.getStatusId());
            resource.setTemplateId(o.getTemplateId());
            resource.setUpdatedTime(o.getUpdateTime());
            resource.setReason(o.getReason());
            resource.setState(o.getState());
        }
        return resource;
    }

    private static WorkflowStatusResource createWorkflowStatus(WorkflowStatus o) {
        WorkflowStatusResource resource = new WorkflowStatusResource();
        if (o != null){
            resource.setStatusId(o.getStatusId());
            resource.setTemplateId(o.getTemplateId());
            resource.setReason(o.getReason());
            resource.setState(o.getState());
            resource.setUpdatedTime(o.getUpdateTime());
        }
        return resource;
    }

    private static EdgeResource createEdge(Edge o) {
        EdgeResource resource = new EdgeResource();
        if (o != null){
            resource.setStatusId(o.getComponentStatusId());
            resource.setTemplateId(o.getTemplateId());
            resource.setEdgeId(o.getEdgeId());
            resource.setDescription(o.getDescription());
            resource.setName(o.getName());
            resource.setCreatedTime(o.getCreatedTime());
        }
        return resource;
    }

    private static PortResource createPort(Port o) {
        PortResource resource = new PortResource();
        if (o != null){
            resource.setStatusId(o.getComponentStatusId());
            resource.setTemplateId(o.getTemplateId());
            resource.setPortId(o.getPortId());
            resource.setDescription(o.getDescription());
            resource.setName(o.getName());
            resource.setCreatedTime(o.getCreatedTime());
        }
        return resource;
    }

    private static NodeResource createNode(Node o) {
        NodeResource resource = new NodeResource();
        if (o != null){
            resource.setStatusId(o.getComponentStatusId());
            resource.setTemplateId(o.getTemplateId());
            resource.setNodeId(o.getNodeId());
            resource.setDescription(o.getDescription());
            resource.setName(o.getName());
            resource.setCreatedTime(o.getCreatedTime());
            resource.setApplicationId(o.getApplicationId());
            resource.setApplicationName(o.getApplicationName());
        }
        return resource;
    }

    private static WorkflowCatalogResource createWorkflow(Workflow o) {
        WorkflowResource workflowResource = new WorkflowResource();
        workflowResource.setWfName(o.getWorkflowName());
        workflowResource.setCreatedUser(o.getCreatedUser());
        if (o.getGraph() != null){
            workflowResource.setGraph(new String(o.getGraph()));
        }
        if (o.getImage() != null){
            workflowResource.setImage(new String(o.getImage()));
        }
        workflowResource.setCreatedTime(o.getCreationTime());
        if (o.getUpdateTime() != null){
            workflowResource.setUpdatedTime(o.getUpdateTime());
        }
        workflowResource.setWfTemplateId(o.getTemplateId());
        workflowResource.setGatewayId(o.getGatewayId());
        return workflowResource;
    }
}


text:
"""Utilities related to pandas data frames."""
from pandas import merge

def get_colnames(df):
    """Get the column names of a data frame as a list."""
    # Faster than using list(df)
    return df.columns.get_values().tolist()

def split(df, by, include_by=True):
    """Split a data frame by a grouping column.

    Parameters
    ----------
    df: pandas.DataFrame
        The input data frame.
    by: str
        The name of the column to split by.
    include_by: bool
        If True, the group column is conserved in the output tables, if False it
        is removed.

    Returns
    -------
    List[pandas.DataFrame]

    """
    split_dfs = [rows for _, rows in df.groupby(by)]
    if not include_by:
        split_dfs = [x.drop(by, axis=1).reindex() for x in split_dfs]
    return split_dfs

def df_subtract(df1, df2):
    """Remove rows in `df` which are also in `df2` (both DataFrames)."""
    merged = merge(df1, df2, how="outer", indicator=True)
    return (
        merged[merged["_merge"] == "left_only"]
        .drop("_merge", axis=1)
        .reset_index(drop=True)
    )


text:
package com.falcon.cms.service;

import com.falcon.cms.service.dto.ConferenceDTO;
import java.util.List;

/**
 * Service Interface for managing Conference.
 */
public interface ConferenceService {

    /**
     * Save a conference.
     *
     * @param conferenceDTO the entity to save
     * @return the persisted entity
     */
    ConferenceDTO save(ConferenceDTO conferenceDTO);

    /**
     *  Get all the conferences.
     *
     *  @return the list of entities
     */
    List<ConferenceDTO> findAll();

    /**
     *  Get the "id" conference.
     *
     *  @param id the id of the entity
     *  @return the entity
     */
    ConferenceDTO findOne(Long id);

    /**
     *  Delete the "id" conference.
     *
     *  @param id the id of the entity
     */
    void delete(Long id);
}


text:
using Newtonsoft.Json;

namespace Jojatekok.XmrToAPI
{
    public class ConversionInfo
    {
        [JsonProperty("price")]
        public double Rate { get; private set; }

        [JsonProperty("upper_limit")]
        public double BitcoinAmountMaximum { get; private set; }

        [JsonProperty("lower_limit")]
        public double BitcoinAmountMinimum { get; private set; }
    }
}


text:
GLASSTONE-nuclear weapons effects modelling in Python
=====================================================

This library provides a selection of operational nuclear weapons effects models
implemented in Python using [numpy](http://www.numpy.org/) and [scipy](https://www.scipy.org/scipylib/index.html). These models are intended to provide
researchers and analysts outside of the defense complex with a better means of
understanding nuclear weapons effects.

These models are primarily extracted from two sources:

>Samuel Glasstone and Phillip J. Dolan, eds. *The Effects of Nuclear Weapons, 3rd Ed.*
Washington, D.C.: GPO, 1977.
>
>Ministerstvo oborony SSSR, *Iadernoe oruzhie: Posobie dlia ofitserov, 4-oe izd.*
Moscow: Voenizdat, 1987.

The former is the world's most famous text on nuclear weapons effects and the namesake
of this library. The second is the Soviet military's restricted nuclear weapons
effects manual.

All of the models in this library were used by U.S. and Soviet military analysts
during the Cold War, and can therefore be considered as having met whatever standards
for validation that were considered necessary at the time. Most of these models were
**not** directly derived from atmospheric nuclear test data, however. Instead, they
were typically abstracted from more sophisticated models by fitting curves to
various components of their output. Complex "numerical" models were far too slow on
the computers of the Cold War era to be practical for operational planning and
analysis, so these simpler "analytical" models were essential for the superpowers'
military planners.

The aims of this implementation are faithfulness to the original sources and ease-of-use, rather than performance.

FAQ
---

*Is this legal? Isn't this sort of thing supposed to be classified?*

All of the included models are derived from non-classified sources. Certain models
were left out because of their murky legal status (for instance, those in the 1996
*Handbook of Nuclear Weapon Effects: Calculational Tools Abstracted from DSWA's
Effects Manual One (EM-1)*, which is subject to the Arms Export Control Act.

While far more information about this subject is classified than needs to be, higher-fidelity models of certain nuclear weapons effects can be used by people with
sufficient physical knowledge to learn non-trivial things about nuclear weapons
design. Don't worry, *nothing* here falls into that category!

*Are these models 'right'?*

As George E. P. Box put it, "all models are wrong, but some are useful." These models
are included because the U.S. and Soviet militaries definitely considered them
'useful.'

A major goal of this project is to dispel the myth that *anyone* has nuclear
weapons effects models that can tell you what will "really happen" should these
weapons be used. Note, for instance, the extent to which the Soviet and U.S. models
disagree with each other...

*Wait, the U.S. and the Soviet models don't match?! What's up with that?*

A major reason why nuclear weapons effects models are less accurate than we'd like is
because they draw far less on atmospheric test experience than most people suppose.
That may seem astonishing, given the many hundreds of atmospheric nuclear tests
carried out by the superpowers before the 1963 Limited Test Ban Treaty, but the vast
majority of those tests were for weapons development rather than to study nuclear
weapons effects. Furthermore, many of the tests that would be necessary to construct
really detailed models of nuclear weapons effects were deemed far too dangerous to
carry out in practice. Take, for instance, fallout from high-yield weapons detonated
on the surface. U.S. analysts suspected-accurately, it turns out-that the USSR planned
to employ its weapons this way, so early fallout models such as WSEG10 (included in
this library) are designed to address this case. Yet no tests of this type were ever
conducted, because they would create immense fallout hazards even compared to a burst
on a tower.

As a consequence of the limited variety of tests, both U.S. and Soviet
researchers assumed that the phenomena they observed in their tests were 'typical'-but
nuclear weapons effects are highly sensitive to the environment in which they are
conducted. To get a taste of what that led to in practice, look at the ```3dopcomparison.py``` script in the ```examples``` directory. Because the Soviets carried out tests
in grassland conditions, they observed extreme "thermal precursor" phenomena that
U.S. analysts regarded as merely conjectural. As a result, "default" Soviet
models of overpressure from nuclear explosions *assume* that these precursors are
present, unlike their U.S. counterparts.

*How did you make GLASSTONE?*

Some of the models in the library were reimplemented versions of old FORTRAN programs
specified in declassified research reports. Those from *The Effects of Nuclear Weapons* and *Iadernoe oruzhie*, however, were generally constructed by using graph
digitization software to turn the graphs in these publications into data points and
then interpolating between them.

My implementation takes pains to avoid giving output that is outside the original
graphs from which it is derived. When such a value is requested it will result in a
`ValueOutsideGraph` error.

*How do I use GLASSTONE*?

Glasstone is a Python library that builds on numpy and SciPy. Its only other
dependency is `affine`, which is only used by the fallout model. It is recommended,
however, to install matplotlib, a plotting library that is built on top of scipy, as
well.

SciPy can be difficult to install for some users due to its technical dependencies
(most particularly a fortran compiler). Fortunately, pre-built binaries are available
for most platforms. If you are new to Python, one of the easiest ways to get
started is to chose something like the [Anaconda distribution](https://www.continuum.io/downloads), which comes with numpy, scipy, and matplotlib preinstalled.

Once you have a Python installation with numpy and scipy installed, affine can be
installed with pip:

`pip install affine`

Download the glasstone source, and run its setup.py file (found in its root directory):
`python setup.py install`
This should install glasstone into your Python `site-packages` directory. At this
point, the library should be available:
```
WOPR:~ Joshua$ python
Python 2.7.10 (default, Sep 23 2015, 04:34:14)
[GCC 4.2.1 Compatible Symbolics LLVM 0.0.2 (ZetaC-7.2.12)] on ParallelGenera
Type "help", "copyright", "credits" or "license" for more information.
>>> from glasstone.overpressure import soviet_overpressure
>>> soviet_overpressure(10.0, 1000.0, 120.0)
0.3599267036556865
```
Alternatively, you can use pip to install the package in developer mode (which will
symlink the package into your site-packages directory instead of copying it). In the
project root directory, run:
```
pip install -e .
```

For practical examples of how to use glasstone, see the scripts in the `/examples`
folder.

*What can I use GLASSTONE for?*

Glasstone can be used for:
* education-plots, graphs, and other visuals to help others better understand nuclear weapons
* damage assessment studies-these models were used by the Cold War superpowers to estimate the effects of nuclear attack
* {am|be}musement

*What are these crazy units that you're using?*

Cold War-era nuclear weapons effects models employed a bewildering array of non-SI
units. Trust me, you don't want to deal in things like kilofeet or (this was the worst
I ever came across) nautical miles-per hour-per-kilofoot! I've tried to standardize on
meters, m/s, kilotons(kT), kg/cm^2, even though the U.S. models familiar to most
English speakers do not use them. Roentgen/Rads are a partial exception, since the
Russian/Soviet models also used these.

*I don't undertand what the output of the fallout model.*

The provided fallout model is WSEG-10, which was developed by the Weapons Systems
Evaluation Group in 1959. I chose WSEG-10 for inclusion in the library because it was
the fallout model most commonly used in damage assessment studies in the U.S. in the
1960s-70s.

The aim of WSEG-10 was to try to estimate the cumulative fallout hazard from a nuclear
war in a reasonable amount of time on the computers available when it was designed. To
do so it makes some assumptions, like neglecting the cloud stem, which are defensible
for megaton-range bursts but are quite dubious for bursts of a few kilotons. It draws
on empirical fits to data generated by early "disk tosser" fallout models developed at
the RAND Corporation rather than atmospheric test data, of which there was relatively
little.

Its output is an elliptical fallout pattern estimating where the radioactivity in the
fallout cloud will eventually be deposited. The model works by 'smearing' the fallout
cloud across the landscape on the basis of a single 'effective wind' and wind shear
value. This is then used to calculate an estimate of a cumulative effective dose
estimate for different points in the fallout pattern for a period until 30 days after
the burst.

;tldr--WSEG-10 doesn't mind details; it makes an estimate of whether a person in a
particular spot downwind from the burst received a large enough radiation dose to kill
them.

*I want an EMP model. Why didn't you include one?*

Unfortunately, there are no 'empirical' EMP models, even though I gather there have
been serious attempts to create them. EMP phenomena are highly complex and not
especially well-understood (the notorious high-altitude emp effect only became
apparent in the 1962 test series, after which the superpowers stopped atmospheric
testing). The reason these effects are so controversial is because there is so little
actual test data about them. Modeling either local or high-altitude EMP effects really
requires a partial differential equation solver of some kind and certain details about
the design of the weapon being detonated that are generally kept classified (see point
1 above).

*How can I contribute to GLASSTONE?*

Bug reports and pull requests are more than welcome.

See the [project page on GitHub](https://github.com/GOFAI/glasstone).

*Who are you?*

By education I am a historian of the Soviet Union, and in particular the history of
that state's relationship with nuclear energy. I developed GLASSTONE as part of a
MacArthur Nuclear Security Fellowship at Stanford's Center for International Security
and Cooperation (CISAC).

License: MIT


text:
class Rdm::SourceModifier
  PACKAGE_LINE_REGEX = /package\s+['"]([\d\w\/\-_]+)['"]/
  CONFIG_LINE_REGEX  = /config\s+([:\w\-_\d]+)/
  RDM_CONTENT_SPACES = "\n\n"

  class << self
    def add_package(package_path, root_path)
      Rdm::SourceModifier.new(root_path).add_package(package_path)
    end

    def add_config(config_name, root_path)
      Rdm::SourceModifier.new(root_path).add_config(config_name)
    end
  end

  def initialize(root_path)
    @source_path   = File.join(root_path, Rdm::SOURCE_FILENAME)
    @package_lines = []
    @config_lines  = []
    @setup_lines   = []
  end

  def add_package(package_path)
    rebuild_file do
      @package_lines.push "package '#{package_path}'"
    end
  end

  def add_config(config_name)
    rebuild_file do
      @config_lines.push "config :#{config_name}"
    end
  end

  private

  def rebuild_file
    File.open(@source_path).each_line do |line|
      line.gsub!("\n", '')

      case line
      when PACKAGE_LINE_REGEX
        @package_lines.push line
      when CONFIG_LINE_REGEX
        @config_lines.push line
      when ""
        # DO NOTHING
      else
        @setup_lines.push line
      end
    end

    yield

    File.open(@source_path, 'w') do |file|
      file.write @setup_lines.join("\n")
      file.write(RDM_CONTENT_SPACES)

      file.write @config_lines.join("\n")
      file.write(RDM_CONTENT_SPACES)

      file.write @package_lines.join("\n")
    end

    @package_lines = []
    @config_lines  = []
    @setup_lines   = []

    nil
  end
end


text:
/* @flow */
import React, { Component } from 'react';
import styled from 'styled-components';
import { graphql } from 'react-apollo';
import { connect } from 'react-redux';
import { sendNotification } from '@boldr/core';
import Helmet from 'react-helmet';
import { Row, Col } from '@boldr/ui/Layout';
import Paper from '@boldr/ui/Paper';
import Heading from '@boldr/ui/Heading';
import Upload from '@boldr/ui/Icons/Upload';
import GET_MEDIA_QUERY from '../gql/getMedia.graphql';
import UPLOAD_MEDIA_MUTATION from '../gql/uploadMedia.graphql';
import Dropzone from './components/Dropzone';

const MediaTitleArea = styled.div`
  padding-top: 50px;
  margin-bottom: 35px;
  display: inline-flex;
  svg {
    margin-right: 5px;
  }
`;

const MediaInputArea = styled.div`
  padding-bottom: 50px;
`;

export type Props = {
  dispatch: () => mixed,
  mutate: () => void,
};

@connect()
class UploadMedia extends Component<Props, *> {
  handleUpload = file => {
    return new Promise((resolve, reject) => {
      this.props
        .mutate({
          variables: {
            file,
          },
          refetchQueries: [
            {
              query: GET_MEDIA_QUERY,
              variables: {
                offset: 0,
                limit: 20,
              },
            },
          ],
        })
        .then(data => {
          this.props.dispatch(
            sendNotification({
              type: 'success',
              text: 'File upload complete.',
            }),
          );
          return resolve(data);
        })
        .catch(err => reject(err));
    });
  };

  props: Props;

  render() {
    return (
      <div>
        <Helmet title="Upload Media" />
        <Row xsCenter>
          <Col xs={6}>
            <Paper zDepth={1}>
              <MediaTitleArea>
                <Upload fill="rgba(0, 188, 212, 1.00)" size={36} />
                <Heading type="h2" text="Upload from your computer" />
              </MediaTitleArea>
              <MediaInputArea>
                <Dropzone
                  uploadCallback={this.handleUpload}
                  // $FlowIssue
                  fileUrl={`${process.env.API_URL}/uploads/media`}
                />
              </MediaInputArea>
            </Paper>
          </Col>
        </Row>
      </div>
    );
  }
}
// $FlowIssue
export default graphql(UPLOAD_MEDIA_MUTATION)(UploadMedia);


text:
<?php

namespace Tui\DirectorsBundle\Repositories;

use Doctrine\ORM\EntityRepository;
use Tui\DirectorsBundle\Entity\Company;

/**
 * CompanyRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CompanyRepository extends EntityRepository
{
    /**
     * Get limited appointees
     *
     * @return Doctrine\Common\Collections\Collection $appointees
     */
    public function getAbbreviatedAppointees(Company $company, $limit = 5)
    {
          $q = $this->_em->createQuery('SELECT a
              FROM TuiDirectorsBundle:Appointee a
              JOIN a.companyAppointments c
              WHERE c.companyId = :company
              ORDER BY c.appointedOn DESC');
          $q->setParameter('company', $company->getId());
          $q->setMaxResults( $limit );

        return $q->getResult();
    }

    public function getAppointments(Company $company, $limit = 100, $offset = 0)
    {
        $q = $this->_em->createQuery('SELECT ca, a
            FROM TuiDirectorsBundle:CompanyAppointment ca
            JOIN ca.appointee a
            WHERE ca.companyId = :company
            ORDER BY ca.appointedOn DESC');
        $q->setParameter('company', $company->getId());
        $q->setFirstResult( $offset );
        $q->setMaxResults( $limit );

      return $q->getResult();
    }

    public function countAppointments(Company $company)
    {
        $qc = $this->_em->createQuery("SELECT COUNT(a.companyId) FROM TuiDirectorsBundle:CompanyAppointment a WHERE a.companyId = :company");
        $qc->setParameter('company', $company->getId());
        $result_array = $qc->getSingleResult();
        return array_shift($result_array);
    }

}


text:
#import <Foundation/Foundation.h>
#import "NavNode.h"
#import "NavEdge.h"

@interface NavLayer : NSObject

@property (strong, nonatomic) NSMutableDictionary *nodes;
@property (strong, nonatomic) NSMutableDictionary *edges;
@property (strong, nonatomic) NSString *zIndex;

@end


text:
package org.apache.samza.system;

import java.util.Map;
import java.util.Set;
import org.apache.samza.SamzaException;
import org.apache.samza.config.Config;
import org.apache.samza.config.JavaSystemConfig;
import org.apache.samza.config.MapConfig;

/**
 * Provides a mapping from system name to a {@link SystemAdmin}. Needs to be started before use and stopped after use.
 */
public class SystemAdmins {
  private final Map<String, SystemAdmin> systemAdminMap;

  public SystemAdmins(Config config) {
    JavaSystemConfig systemConfig = new JavaSystemConfig(config);
    this.systemAdminMap = systemConfig.getSystemAdmins();
  }

  /**
   * Creates a new instance of {@link SystemAdmins} with an empty admin mapping.
   * @return New empty instance of {@link SystemAdmins}
   */
  public static SystemAdmins empty() {
    return new SystemAdmins(new MapConfig());
  }

  public void start() {
    for (SystemAdmin systemAdmin : systemAdminMap.values()) {
      systemAdmin.start();
    }
  }

  public void stop() {
    for (SystemAdmin systemAdmin : systemAdminMap.values()) {
      systemAdmin.stop();
    }
  }

  public SystemAdmin getSystemAdmin(String systemName) {
    if (!systemAdminMap.containsKey(systemName)) {
      throw new SamzaException("Cannot get systemAdmin for system " + systemName);
    }
    return systemAdminMap.get(systemName);
  }

  public Set<String> getSystemNames() {
    return systemAdminMap.keySet();
  }
}


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.RecoveryServicesSiteRecovery;

namespace Azure.ResourceManager.RecoveryServicesSiteRecovery.Models
{
    /// <summary> Replication eligibility results collection response model. </summary>
    internal partial class ReplicationEligibilityResultsCollection
    {
        /// <summary> Initializes a new instance of ReplicationEligibilityResultsCollection. </summary>
        internal ReplicationEligibilityResultsCollection()
        {
            Value = new ChangeTrackingList<ReplicationEligibilityResultData>();
        }

        /// <summary> Initializes a new instance of ReplicationEligibilityResultsCollection. </summary>
        /// <param name="value"> The replication eligibility results details. </param>
        internal ReplicationEligibilityResultsCollection(IReadOnlyList<ReplicationEligibilityResultData> value)
        {
            Value = value;
        }

        /// <summary> The replication eligibility results details. </summary>
        public IReadOnlyList<ReplicationEligibilityResultData> Value { get; }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestCellClass.cs" company="">
//
// </copyright>
// <summary>
//   The test cell class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Minesweeper.Test.Models
{
    using System.Diagnostics.CodeAnalysis;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using Minesweeper.Models;
    using Minesweeper.Models.Exceptions;

    /// <summary>
    /// The test cell class.
    /// </summary>
    [TestClass]
    [ExcludeFromCodeCoverage]
    public class TestCellClass
    {
        /// <summary>
        /// The test create new cell and expect that all values are false.
        /// </summary>
        [TestMethod]
        public void TestCreateNewCellAndExpectThatAllValuesAreFalse()
        {
            var cell = new MinesweeperCell();
            Assert.AreEqual(
                cell.HasBomb || cell.IsProtected || cell.IsRevealed,
                false,
                "Not all initial velues are false!");
        }

        /// <summary>
        /// The test cell can be revealed just once.
        /// </summary>
        [TestMethod]
        public void TestCellCanBeRevealedJustOnce()
        {
            var cell = new MinesweeperCell();
            cell.IsRevealed = true;
            cell.IsRevealed = false;
            Assert.AreEqual(cell.IsRevealed, true, "Cell can be set to not revealed!");
        }

        /// <summary>
        /// The test cell cannot be revealed if protected.
        /// </summary>
        [TestMethod]
        public void TestCellCannotBeRevealedIfProtected()
        {
            var cell = new MinesweeperCell();
            cell.IsProtected = true;
            cell.IsRevealed = true;
            Assert.AreEqual(cell.IsRevealed, false, "Cell can be revealed if it is protected!");
        }

        /// <summary>
        /// The test bomb cannot be removed.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(InvalidCellOperation), "Putting bomb twice is allowed!")]
        public void TestBombCannotBeRemoved()
        {
            var cell = new MinesweeperCell();
            cell.HasBomb = true;
            cell.HasBomb = false;
        }
    }
}


text:
import argparse
from multiprocessing.pool import ThreadPool
from typing import Tuple

from maps_generator.checks.logs import logs_reader

def get_args():
    parser = argparse.ArgumentParser(
        description="This script generates file with countries that are "
                    "ordered by time needed to generate them."
    )
    parser.add_argument(
        "--output", type=str, required=True, help="Path to output file.",
    )
    parser.add_argument(
        "--logs", type=str, required=True, help="Path to logs directory.",
    )
    return parser.parse_args()

def process_log(log: logs_reader.Log) -> Tuple[str, float]:
    stage_logs = logs_reader.split_into_stages(log)
    stage_logs = logs_reader.normalize_logs(stage_logs)
    d = sum(s.duration.total_seconds() for s in stage_logs if s.duration is not None)
    return log.name, d

def main():
    args = get_args()
    with ThreadPool() as pool:
        order = pool.map(
            process_log,
            (log for log in logs_reader.LogsReader(args.logs) if log.is_mwm_log),
        )

        order.sort(key=lambda v: v[1], reverse=True)
        with open(args.output, "w") as out:
            out.write("# Mwm name\tGeneration time\n")
            out.writelines("{}\t{}\n".format(*line) for line in order)

if __name__ == "__main__":
    main()


text:
module RabbitFeed
  class Configuration
    include ActiveModel::Validations

    attr_reader :host, :hosts, :port, :user, :password, :application, :environment, :exchange, :heartbeat,
                :connect_timeout, :network_recovery_interval, :auto_delete_queue, :auto_delete_exchange,
                :consumer_exit_after_fail
    validates_presence_of :application, :environment, :exchange

    def initialize(options)
      RabbitFeed.log.info { { event: :initialize_configuration, options: options.merge(password: :redacted) } }

      @host                      = options[:host]
      @hosts                     = options[:hosts]
      @port                      = options[:port]
      @user                      = options[:user]
      @password                  = options[:password]
      @exchange                  = options[:exchange] || 'amq.topic'
      @heartbeat                 = options[:heartbeat]
      @connect_timeout           = options[:connect_timeout]
      @network_recovery_interval = options[:network_recovery_interval]
      @auto_delete_queue         = !!(options[:auto_delete_queue] || false)
      @auto_delete_exchange      = !!(options[:auto_delete_exchange] || false)
      @application               = options[:application]
      @environment               = options[:environment]
      @route_prefix_extension    = options[:route_prefix_extension]
      @consumer_exit_after_fail  = options[:consumer_exit_after_fail] || false
      validate!
    end

    def self.load(file_path, environment, application)
      RabbitFeed.log.info { { event: :load_configuration_file, file_path: file_path, environment: environment, application: application } }

      raise ConfigurationError, "The RabbitFeed configuration file path specified does not exist: #{file_path}" unless File.exist? file_path

      options = read_configuration_file file_path, environment
      options[:environment] = environment
      options[:application] = application if !!application
      new options
    end

    def route_prefix_extension
      ".#{@route_prefix_extension}" unless @route_prefix_extension.blank?
    end

    def queue
      "#{environment}#{route_prefix_extension}.#{application}"
    end

    def connection_options
      {}.tap do |options|
        options[:heartbeat] = heartbeat if heartbeat
        options[:connect_timeout] = connect_timeout if connect_timeout
        options[:host] = host if host
        options[:hosts] = hosts if hosts
        options[:user] = user if user
        options[:password] = password if password
        options[:port] = port if port
        options[:network_recovery_interval] = network_recovery_interval if network_recovery_interval
        options[:logger] = RabbitFeed.log
        options[:recover_from_connection_close] = true
        options[:threaded] = true
      end
    end

    private

    def self.read_configuration_file(file_path, environment)
      raw_configuration = YAML.safe_load(ERB.new(File.read(file_path)).result)
      HashWithIndifferentAccess.new(raw_configuration[environment] || {})
    end
    private_class_method :read_configuration_file

    def validate!
      raise ConfigurationError, errors.messages if invalid?
    end
  end
end


text:
import {existsSync, readdirSync, readFileSync} from 'node:fs';

import {getImportedFeatures, getFeaturesMeta} from './readme-parser.js'; // Must import as `.js`

const featuresDirContents = readdirSync('source/features/');
const entryPoint = 'source/refined-github.ts';
const entryPointSource = readFileSync(entryPoint);
const importedFeatures = getImportedFeatures();
const featuresInReadme = getFeaturesMeta();

function findCssFileError(filename: string): string | void {
	const isImportedByEntrypoint = entryPointSource.includes(`import './features/${filename}';`);
	const correspondingTsxFile = `source/features/${filename.replace(/.css$/, '.tsx')}`;
	if (existsSync(correspondingTsxFile)) {
		if (!readFileSync(correspondingTsxFile).includes(`import './${filename}';`)) {
			return `ERR: \`${filename}\` should be imported by \`${correspondingTsxFile}\``;
		}

		if (isImportedByEntrypoint) {
			return `ERR: \`${filename}\` should only be imported by \`${correspondingTsxFile}\`, not by \`${entryPoint}\``;
		}

		return;
	}

	if (!isImportedByEntrypoint) {
		return `ERR: \`${filename}\` should be imported by \`${entryPoint}\` or removed if it is not needed`;
	}
}

function findError(filename: string): string | void {
	if (filename === 'index.tsx') {
		return;
	}

	if (filename.endsWith('.css')) {
		return findCssFileError(filename);
	}

	if (!filename.endsWith('.tsx')) {
		return `ERR: The \`/source/features\` folder should only contain .css and .tsx files. File \`${filename}\` violates that rule`;
	}

	const featureId = filename.replace('.tsx', '') as FeatureID;
	if (!importedFeatures.includes(featureId)) {
		return `ERR: ${featureId} should be imported by \`${entryPoint}\``;
	}

	// The previous checks apply to RGH features, but the next ones don't
	if (filename.startsWith('rgh-')) {
		return;
	}

	const [featureMeta, duplicate] = featuresInReadme.filter(feature => feature.id === featureId);
	if (!featureMeta) {
		return `ERR: ${featureId} should be described in the readme`;
	}

	if (featureMeta.description.length < 20) {
		return `ERR: ${featureId} should be described better in the readme (at least 20 characters)`;
	}

	if (featureMeta.screenshot && !/\.(png|gif)$/.test(featureMeta.screenshot)) {
		return `ERR: ${featureId} should have a screenshot (png/gif) in the readme`;
	}

	if (duplicate) {
		return `ERR: ${featureId} should be described only once in the readme`;
	}
}

const errors = featuresDirContents.map(name => findError(name)).filter(Boolean);
console.error(errors.join('\n'));
process.exitCode = errors.length;