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

#include <memory>

#include "SurgSim/Physics/MassSpringRepresentationContact.h"
#include "SurgSim/Physics/ContactConstraintData.h"
#include "SurgSim/Physics/ConstraintImplementation.h"

#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Physics/MassSpringRepresentationLocalization.h"

namespace SurgSim
{

namespace Physics
{

MassSpringRepresentationContact::MassSpringRepresentationContact()
{

}

MassSpringRepresentationContact::~MassSpringRepresentationContact()
{

}

void MassSpringRepresentationContact::doBuild(double dt,
			const ConstraintData& data,
			const std::shared_ptr<Localization>& localization,
			MlcpPhysicsProblem* mlcp,
			unsigned int indexOfRepresentation,
			unsigned int indexOfConstraint,
			ConstraintSideSign sign)
{
	MlcpPhysicsProblem::Matrix& H    = mlcp->H;
	MlcpPhysicsProblem::Matrix& CHt  = mlcp->CHt;
	MlcpPhysicsProblem::Matrix& HCHt = mlcp->A;
	MlcpPhysicsProblem::Vector& b    = mlcp->b;

	unsigned int nodeId = std::static_pointer_cast<MassSpringRepresentationLocalization>(localization)->getLocalNode();
	std::shared_ptr<Representation> representation = localization->getRepresentation();
	auto massSpring = std::static_pointer_cast<MassSpringRepresentation>(representation);

	if (!massSpring->isActive())
	{
		return;
	}

	const double scale = (sign == CONSTRAINT_POSITIVE_SIDE) ? 1.0 : -1.0;
	const SurgSim::Math::Matrix& C = massSpring->getComplianceMatrix();
	const ContactConstraintData& contactData = static_cast<const ContactConstraintData&>(data);
	const SurgSim::Math::Vector3d& n = contactData.getNormal();
	const double d = contactData.getDistance();

	// FRICTIONLESS CONTACT in a LCP
	//   (n, d) defines the plane of contact
	//   P(t) the point of contact (usually after free motion)
	//
	// The constraint equation for a plane is
	//   n.P(t+dt) + d >= 0
	// Using the Backward Euler numerical integration scheme
	//   n.[ P(t) + dt.V(t+dt) ] + d >= 0
	//   [n.dt].V(t+dt) + [n.P(t) + d] >= 0
	// The solver requires an equation of the form
	//   H.V(t+dt) + b >= 0
	// Therefore
	//   H = n.dt
	//   b = n.P(t) + d             -> P(t) evaluated after free motion

	// Fill up b with the constraint equation...
	SurgSim::Math::Vector3d globalPosition = localization->calculatePosition();
	double violation = n.dot(globalPosition) + d;
	b[indexOfConstraint] += violation * scale;

	// Fill matrices with just the non null values
	// (H+H') = H+H'
	// => H += H';
	//
	// C(H+H')t = CHt + CH't
	// => CHt += CH't;
	//
	// (H+H')C(H+H')t = HCHt + HCH't + H'C(H+H')t
	// => HCHt += H(CH't) + H'[C(H+H')t];

	// H'
	SurgSim::Math::Vector3d localH = dt * scale * n;

	// CH't
	SurgSim::Math::Vector localCHt = C.middleCols(indexOfRepresentation + 3*nodeId, 3) * localH;

	// HCHt += H(CH't)
	HCHt.col(indexOfConstraint) += H * localCHt;

	// H += H'
	H.block<1,3>(indexOfConstraint, indexOfRepresentation + 3*nodeId) += localH.transpose();

	// CHt += CH't
	CHt.col(indexOfConstraint) += localCHt;

	// HCHt += H'[C(H+H')t]
	HCHt.row(indexOfConstraint) += localH.transpose() * CHt.middleRows(indexOfRepresentation + 3*nodeId, 3);

}

SurgSim::Math::MlcpConstraintType MassSpringRepresentationContact::getMlcpConstraintType() const
{
	return SurgSim::Math::MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT;
}

SurgSim::Physics::RepresentationType MassSpringRepresentationContact::getRepresentationType() const
{
	return 	REPRESENTATION_TYPE_MASSSPRING;
}

unsigned int MassSpringRepresentationContact::doGetNumDof() const
{
	return 1;
}

}; // namespace Physics

}; // namespace SurgSim<commit_msg>Fix spaces<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <memory>

#include "SurgSim/Physics/MassSpringRepresentationContact.h"
#include "SurgSim/Physics/ContactConstraintData.h"
#include "SurgSim/Physics/ConstraintImplementation.h"

#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Physics/MassSpringRepresentationLocalization.h"

namespace SurgSim
{

namespace Physics
{

MassSpringRepresentationContact::MassSpringRepresentationContact()
{

}

MassSpringRepresentationContact::~MassSpringRepresentationContact()
{

}

void MassSpringRepresentationContact::doBuild(double dt,
			const ConstraintData& data,
			const std::shared_ptr<Localization>& localization,
			MlcpPhysicsProblem* mlcp,
			unsigned int indexOfRepresentation,
			unsigned int indexOfConstraint,
			ConstraintSideSign sign)
{
	MlcpPhysicsProblem::Matrix& H    = mlcp->H;
	MlcpPhysicsProblem::Matrix& CHt  = mlcp->CHt;
	MlcpPhysicsProblem::Matrix& HCHt = mlcp->A;
	MlcpPhysicsProblem::Vector& b    = mlcp->b;

	unsigned int nodeId = std::static_pointer_cast<MassSpringRepresentationLocalization>(localization)->getLocalNode();
	std::shared_ptr<Representation> representation = localization->getRepresentation();
	auto massSpring = std::static_pointer_cast<MassSpringRepresentation>(representation);

	if ( !massSpring->isActive())
	{
		return;
	}

	const double scale = (sign == CONSTRAINT_POSITIVE_SIDE) ? 1.0 : -1.0;
	const SurgSim::Math::Matrix& C = massSpring->getComplianceMatrix();
	const ContactConstraintData& contactData = static_cast<const ContactConstraintData&>(data);
	const SurgSim::Math::Vector3d& n = contactData.getNormal();
	const double d = contactData.getDistance();

	// FRICTIONLESS CONTACT in a LCP
	//   (n, d) defines the plane of contact
	//   P(t) the point of contact (usually after free motion)
	//
	// The constraint equation for a plane is
	//   n.P(t+dt) + d >= 0
	// Using the Backward Euler numerical integration scheme
	//   n.[ P(t) + dt.V(t+dt) ] + d >= 0
	//   [n.dt].V(t+dt) + [n.P(t) + d] >= 0
	// The solver requires an equation of the form
	//   H.V(t+dt) + b >= 0
	// Therefore
	//   H = n.dt
	//   b = n.P(t) + d             -> P(t) evaluated after free motion

	// Fill up b with the constraint equation...
	SurgSim::Math::Vector3d globalPosition = localization->calculatePosition();
	double violation = n.dot(globalPosition) + d;
	b[indexOfConstraint] += violation * scale;

	// Fill matrices with just the non null values
	// (H+H') = H+H'
	// => H += H';
	//
	// C(H+H')t = CHt + CH't
	// => CHt += CH't;
	//
	// (H+H')C(H+H')t = HCHt + HCH't + H'C(H+H')t
	// => HCHt += H(CH't) + H'[C(H+H')t];

	// H'
	SurgSim::Math::Vector3d localH = dt * scale * n;

	// CH't
	SurgSim::Math::Vector localCHt = C.middleCols(indexOfRepresentation + 3*nodeId, 3) * localH;

	// HCHt += H(CH't)
	HCHt.col(indexOfConstraint) += H * localCHt;

	// H += H'
	H.block<1,3>(indexOfConstraint, indexOfRepresentation + 3*nodeId) += localH.transpose();

	// CHt += CH't
	CHt.col(indexOfConstraint) += localCHt;

	// HCHt += H'[C(H+H')t]
	HCHt.row(indexOfConstraint) += localH.transpose() * CHt.middleRows(indexOfRepresentation + 3*nodeId, 3);

}

SurgSim::Math::MlcpConstraintType MassSpringRepresentationContact::getMlcpConstraintType() const
{
	return SurgSim::Math::MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT;
}

SurgSim::Physics::RepresentationType MassSpringRepresentationContact::getRepresentationType() const
{
	return REPRESENTATION_TYPE_MASSSPRING;
}

unsigned int MassSpringRepresentationContact::doGetNumDof() const
{
	return 1;
}

}; // namespace Physics

}; // namespace SurgSim<|endoftext|>


<commit_before>/**
 * Unit Tests for TicTacToeBoard
**/

#include <gtest/gtest.h>
#include "TicTacToeBoard.h"

class TicTacToeBoardTest : public ::testing::Test
{
	protected:
		TicTacToeBoardTest(){} //constructor runs before each test
		virtual ~TicTacToeBoardTest(){} //destructor cleans up after tests
		virtual void SetUp(){} //sets up before each test (after constructor)
		virtual void TearDown(){} //clean up after each test, (before destructor)
};

/* EXAMPLE TEST FORMAT
TEST(TicTacToeBoardTest, sanityCheck)
{
	ASSERT_TRUE(true);
}
*/
TEST(TicTacToeBoardTest, toggleTurn1)
{
	TicTacToeBoard T;
	ASSERT_EQ('O', T.toggleTurn());
}

TEST(TicTacToeBoardTest, toggleTurn2)
{
	TicTacToeBoard T;
	T.toggleTurn();
	ASSERT_EQ('X', T.toggleTurn());
}

TEST(TicTacToeBoardTest, placePiece1)
{
	TicTacToeBoard T;
	ASSERT_EQ('X', T.placePiece(1,1));
}

TEST(TicTacToeBoardTest, placePiece2)
{
	TicTacToeBoard T;
	T.placePiece(2,1);
	ASSERT_EQ('O', T.placePiece(1,1));
}

TEST(TicTacToeBoardTest, placePiece3)
{
	TicTacToeBoard T;
	T.placePiece(2,1);
	ASSERT_EQ('X', T.placePiece(2,1));
}

TEST(TicTacToeBoardTest, placePiece4)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.placePiece(4,6));
}

TEST(TicTacToeBoardTest, placePiece5)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.placePiece(-2,-2));
}

TEST(TicTacToeBoardTest, placePiece6)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.placePiece(2,22));
}

TEST(TicTacToeBoardTest, placePiece7)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.placePiece(2,-2));
}

TEST(TicTacToeBoardTest, getPiece1)
{
	TicTacToeBoard T;
	ASSERT_EQ(' ', T.getPiece(1,1));
}

TEST(TicTacToeBoardTest, getPiece2)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.getPiece(4,4));
}

TEST(TicTacToeBoardTest, getPiece3)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.getPiece(-1,-1));
}

TEST(TicTacToeBoardTest, getPiece4)
{
	TicTacToeBoard T;
	T.placePiece(1,1);
	ASSERT_EQ('X', T.getPiece(1,1));
}

TEST(TicTacToeBoardTest, getPiece5)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.getPiece(1,-1));
}

TEST(TicTacToeBoardTest, getPiece6)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.getPiece(1,11));
}

TEST(TicTacToeBoardTest, getWinner1)
{
	TicTacToeBoard T;
	T.placePiece(1,1);
	ASSERT_EQ('?', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner2)
{
	TicTacToeBoard T;
	T.placePiece(1,1);
	T.placePiece(0,0);
	T.placePiece(0,1);
	T.placePiece(0,2);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ('X', T.getWinner());
}
  /*
  BUG: Describe the situation and what the EXPECTED outcome should be
  but also what the ACTUAL outcome is with your bug
  */
TEST(TicTacToeBoardTest, getWinner3)
{
	TicTacToeBoard T;
	T.placePiece(0,1);
	T.placePiece(0,0);
	T.placePiece(1,0);
	T.placePiece(0,2);
	T.placePiece(1,2);
	T.placePiece(1,1);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ('O', T.getWinner());
}
  /*
  BUG: Describe the situation and what the EXPECTED outcome should be
  but also what the ACTUAL outcome is with your bug
  */
TEST(TicTacToeBoardTest, getWinner4)
{
	TicTacToeBoard T;
	T.placePiece(0,1);
	T.placePiece(0,0);
	T.placePiece(0,2);
	T.placePiece(1,1);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ(' ', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner5)
{
	TicTacToeBoard T;
	T.placePiece(0,0);
	T.placePiece(0,2);
	T.placePiece(0,1);
	T.placePiece(1,1);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,2);
	T.placePiece(2,0);
	ASSERT_EQ('X', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner6)
{
	TicTacToeBoard T;
	T.placePiece(0,0);
	T.placePiece(0,1);
	T.placePiece(0,2);
	T.placePiece(1,1);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ(' ', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner7)
{
	TicTacToeBoard T;
	T.placePiece(1,1);
	T.placePiece(0,2);
	T.placePiece(0,1);
	T.placePiece(0,0);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,0);
	T.placePiece(2,1);
	T.placePiece(2,2);
	ASSERT_EQ(' ', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner8)
{
	TicTacToeBoard T;
	T.placePiece(0,0);
	T.placePiece(0,2);
	T.placePiece(0,1);
	T.placePiece(1,1);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ('O', T.getWinner());
}<commit_msg>BUG FIXED<commit_after>/**
 * Unit Tests for TicTacToeBoard
**/
//
#include <gtest/gtest.h>
#include "TicTacToeBoard.h"

class TicTacToeBoardTest : public ::testing::Test
{
	protected:
		TicTacToeBoardTest(){} //constructor runs before each test
		virtual ~TicTacToeBoardTest(){} //destructor cleans up after tests
		virtual void SetUp(){} //sets up before each test (after constructor)
		virtual void TearDown(){} //clean up after each test, (before destructor)
};

/* EXAMPLE TEST FORMAT
TEST(TicTacToeBoardTest, sanityCheck)
{
	ASSERT_TRUE(true);
}
*/
TEST(TicTacToeBoardTest, toggleTurn1)
{
	TicTacToeBoard T;
	ASSERT_EQ('O', T.toggleTurn());
}

TEST(TicTacToeBoardTest, toggleTurn2)
{
	TicTacToeBoard T;
	T.toggleTurn();
	ASSERT_EQ('X', T.toggleTurn());
}

TEST(TicTacToeBoardTest, placePiece1)
{
	TicTacToeBoard T;
	ASSERT_EQ('X', T.placePiece(1,1));
}

TEST(TicTacToeBoardTest, placePiece2)
{
	TicTacToeBoard T;
	T.placePiece(2,1);
	ASSERT_EQ('O', T.placePiece(1,1));
}

TEST(TicTacToeBoardTest, placePiece3)
{
	TicTacToeBoard T;
	T.placePiece(2,1);
	ASSERT_EQ('X', T.placePiece(2,1));
}

TEST(TicTacToeBoardTest, placePiece4)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.placePiece(4,6));
}

TEST(TicTacToeBoardTest, placePiece5)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.placePiece(-2,-2));
}

TEST(TicTacToeBoardTest, placePiece6)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.placePiece(2,22));
}

TEST(TicTacToeBoardTest, placePiece7)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.placePiece(2,-2));
}

TEST(TicTacToeBoardTest, getPiece1)
{
	TicTacToeBoard T;
	ASSERT_EQ(' ', T.getPiece(1,1));
}

TEST(TicTacToeBoardTest, getPiece2)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.getPiece(4,4));
}

TEST(TicTacToeBoardTest, getPiece3)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.getPiece(-1,-1));
}

TEST(TicTacToeBoardTest, getPiece4)
{
	TicTacToeBoard T;
	T.placePiece(1,1);
	ASSERT_EQ('X', T.getPiece(1,1));
}

TEST(TicTacToeBoardTest, getPiece5)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.getPiece(1,-1));
}

TEST(TicTacToeBoardTest, getPiece6)
{
	TicTacToeBoard T;
	ASSERT_EQ('?', T.getPiece(1,11));
}

TEST(TicTacToeBoardTest, getWinner1)
{
	TicTacToeBoard T;
	T.placePiece(1,1);
	ASSERT_EQ('?', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner2)
{
	TicTacToeBoard T;
	T.placePiece(1,1);
	T.placePiece(0,0);
	T.placePiece(0,1);
	T.placePiece(0,2);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ('X', T.getWinner());
}
  /*
  BUG: Describe the situation and what the EXPECTED outcome should be
  but also what the ACTUAL outcome is with your bug
  */
TEST(TicTacToeBoardTest, getWinner3)
{
	TicTacToeBoard T;
	T.placePiece(0,1);
	T.placePiece(0,0);
	T.placePiece(1,0);
	T.placePiece(0,2);
	T.placePiece(1,2);
	T.placePiece(1,1);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ('O', T.getWinner());
}
  /*
  BUG: Describe the situation and what the EXPECTED outcome should be
  but also what the ACTUAL outcome is with your bug
  */
TEST(TicTacToeBoardTest, getWinner4)
{
	TicTacToeBoard T;
	T.placePiece(0,1);
	T.placePiece(0,0);
	T.placePiece(0,2);
	T.placePiece(1,1);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ(' ', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner5)
{
	TicTacToeBoard T;
	T.placePiece(0,0);
	T.placePiece(0,2);
	T.placePiece(0,1);
	T.placePiece(1,1);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,2);
	T.placePiece(2,0);
	ASSERT_EQ('X', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner6)
{
	TicTacToeBoard T;
	T.placePiece(0,0);
	T.placePiece(0,1);
	T.placePiece(0,2);
	T.placePiece(1,1);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ(' ', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner7)
{
	TicTacToeBoard T;
	T.placePiece(1,1);
	T.placePiece(0,2);
	T.placePiece(0,1);
	T.placePiece(0,0);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,0);
	T.placePiece(2,1);
	T.placePiece(2,2);
	ASSERT_EQ(' ', T.getWinner());
}

TEST(TicTacToeBoardTest, getWinner8)
{
	TicTacToeBoard T;
	T.placePiece(0,0);
	T.placePiece(0,2);
	T.placePiece(0,1);
	T.placePiece(1,1);
	T.placePiece(1,0);
	T.placePiece(1,2);
	T.placePiece(2,1);
	T.placePiece(2,0);
	T.placePiece(2,2);
	ASSERT_EQ('O', T.getWinner());
}
<|endoftext|>


<commit_before>/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#include <Box2D/Collision/b2BroadPhase.h>
#include <cstring>
using namespace std;

b2BroadPhase::b2BroadPhase()
{
	m_proxyCount = 0;

	m_pairCapacity = 16;
	m_pairCount = 0;
	m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));

	m_moveCapacity = 16;
	m_moveCount = 0;
	m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
}

b2BroadPhase::~b2BroadPhase()
{
	b2Free(m_moveBuffer);
	b2Free(m_pairBuffer);
}

int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData)
{
	int32 proxyId = m_tree.CreateProxy(aabb, userData);
	++m_proxyCount;
	BufferMove(proxyId);
	return proxyId;
}

void b2BroadPhase::DestroyProxy(int32 proxyId)
{
	UnBufferMove(proxyId);
	--m_proxyCount;
	m_tree.DestroyProxy(proxyId);
}

void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement)
{
	bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement);
	if (buffer)
	{
		BufferMove(proxyId);
	}
}

void b2BroadPhase::TouchProxy(int32 proxyId)
{
	BufferMove(proxyId);
}

void b2BroadPhase::BufferMove(int32 proxyId)
{
	if (m_moveCount == m_moveCapacity)
	{
		int32* oldBuffer = m_moveBuffer;
		m_moveCapacity *= 2;
		m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
		memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32));
		b2Free(oldBuffer);
	}

	m_moveBuffer[m_moveCount] = proxyId;
	++m_moveCount;
}

void b2BroadPhase::UnBufferMove(int32 proxyId)
{
	for (int32 i = 0; i < m_moveCount; ++i)
	{
		if (m_moveBuffer[i] == proxyId)
		{
			m_moveBuffer[i] = e_nullProxy;
			return;
		}
	}
}

// This is called from b2DynamicTree::Query when we are gathering pairs.
bool b2BroadPhase::QueryCallback(int32 proxyId)
{
	// A proxy cannot form a pair with itself.
	if (proxyId == m_queryProxyId)
	{
		return true;
	}

	// Grow the pair buffer as needed.
	if (m_pairCount == m_pairCapacity)
	{
		b2Pair* oldBuffer = m_pairBuffer;
		m_pairCapacity *= 2;
		m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
		memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair));
		b2Free(oldBuffer);
	}

	m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId);
	m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId);
	++m_pairCount;

	return true;
}
<commit_msg>Box2D bug fix.<commit_after>/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/

#include <Box2D/Collision/b2BroadPhase.h>
#include <cstring>
using namespace std;

b2BroadPhase::b2BroadPhase()
{
	m_proxyCount = 0;

	m_pairCapacity = 16;
	m_pairCount = 0;
	m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));

	m_moveCapacity = 16;
	m_moveCount = 0;
	m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
}

b2BroadPhase::~b2BroadPhase()
{
	b2Free(m_moveBuffer);
	b2Free(m_pairBuffer);
}

int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData)
{
	int32 proxyId = m_tree.CreateProxy(aabb, userData);
	++m_proxyCount;
	BufferMove(proxyId);
	return proxyId;
}

void b2BroadPhase::DestroyProxy(int32 proxyId)
{
	UnBufferMove(proxyId);
	--m_proxyCount;
	m_tree.DestroyProxy(proxyId);
}

void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement)
{
	bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement);
	if (buffer)
	{
		BufferMove(proxyId);
	}
}

void b2BroadPhase::TouchProxy(int32 proxyId)
{
	BufferMove(proxyId);
}

void b2BroadPhase::BufferMove(int32 proxyId)
{
	if (m_moveCount == m_moveCapacity)
	{
		int32* oldBuffer = m_moveBuffer;
		m_moveCapacity *= 2;
		m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
		memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32));
		b2Free(oldBuffer);
	}

	m_moveBuffer[m_moveCount] = proxyId;
	++m_moveCount;
}

void b2BroadPhase::UnBufferMove(int32 proxyId)
{
	for (int32 i = 0; i < m_moveCount; ++i)
	{
		if (m_moveBuffer[i] == proxyId)
		{
			m_moveBuffer[i] = e_nullProxy;
		}
	}
}

// This is called from b2DynamicTree::Query when we are gathering pairs.
bool b2BroadPhase::QueryCallback(int32 proxyId)
{
	// A proxy cannot form a pair with itself.
	if (proxyId == m_queryProxyId)
	{
		return true;
	}

	// Grow the pair buffer as needed.
	if (m_pairCount == m_pairCapacity)
	{
		b2Pair* oldBuffer = m_pairBuffer;
		m_pairCapacity *= 2;
		m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
		memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair));
		b2Free(oldBuffer);
	}

	m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId);
	m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId);
	++m_pairCount;

	return true;
}
<|endoftext|>


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

#include "open_spiel/game_transforms/turn_based_simultaneous_game.h"

#include <random>
#include <string>

#include "open_spiel/abseil-cpp/absl/random/uniform_int_distribution.h"
#include "open_spiel/spiel.h"

namespace open_spiel {
namespace {

void SimulateGames(std::mt19937* rng, const Game& game, State* sim_state,
                   State* turn_based_state) {
  while (!sim_state->IsTerminal()) {
    const State* wrapped_sim_state =
        dynamic_cast<TurnBasedSimultaneousState*>(turn_based_state)
            ->SimultaneousGameState();

    // Now check that the states are identical via the ToString().
    SPIEL_CHECK_EQ(sim_state->ToString(), wrapped_sim_state->ToString());

    if (sim_state->IsChanceNode()) {
      SPIEL_CHECK_TRUE(turn_based_state->IsChanceNode());

      // Chance node; sample one according to underlying distribution
      std::vector<std::pair<Action, double>> outcomes =
          sim_state->ChanceOutcomes();
      Action action =
          open_spiel::SampleAction(
              outcomes, std::uniform_real_distribution<double>(0.0, 1.0)(*rng))
              .first;

      std::cout << "sampled outcome: %s\n"
                << sim_state->ActionToString(kChancePlayerId, action)
                << std::endl;

      sim_state->ApplyAction(action);
      turn_based_state->ApplyAction(action);
    } else if (sim_state->CurrentPlayer() == kSimultaneousPlayerId) {
      SPIEL_CHECK_EQ(wrapped_sim_state->CurrentPlayer(), kSimultaneousPlayerId);

      // Players choose simultaneously.
      std::vector<Action> joint_action;

      // Sample an action for each player
      for (auto p = Player{0}; p < game.NumPlayers(); p++) {
        if (game.GetType().provides_information_state_string) {
          // Check the information states to each player are consistent.
          SPIEL_CHECK_EQ(sim_state->InformationStateString(p),
                         wrapped_sim_state->InformationStateString(p));
        }

        std::vector<Action> actions;
        actions = sim_state->LegalActions(p);
        absl::uniform_int_distribution<> dis(0, actions.size() - 1);
        Action action = actions[dis(*rng)];
        joint_action.push_back(action);
        std::cout << "player " << p << " chose "
                  << sim_state->ActionToString(p, action) << std::endl;
        SPIEL_CHECK_EQ(p, turn_based_state->CurrentPlayer());
        turn_based_state->ApplyAction(action);
      }

      sim_state->ApplyActions(joint_action);
    } else {
      std::cerr << "Reach a decision node in a simultaneous game.";
      SPIEL_CHECK_TRUE(false);
    }

    std::cout << "State: " << std::endl << sim_state->ToString() << std::endl;
  }

  SPIEL_CHECK_TRUE(turn_based_state->IsTerminal());

  auto sim_returns = sim_state->Returns();
  auto turn_returns = turn_based_state->Returns();

  for (auto player = Player{0}; player < game.NumPlayers(); player++) {
    double utility = sim_returns[player];
    SPIEL_CHECK_GE(utility, game.MinUtility());
    SPIEL_CHECK_LE(utility, game.MaxUtility());
    std::cout << "Utility to player " << player << " is " << utility
              << std::endl;

    double other_utility = turn_returns[player];
    SPIEL_CHECK_EQ(utility, other_utility);
  }
}

void BasicTurnBasedSimultaneousTests() {
  std::mt19937 rng;

  for (const GameType& type : RegisteredGameTypes()) {
    if (!type.ContainsRequiredParameters()) {
      std::string name = type.short_name;
      if (type.dynamics == GameType::Dynamics::kSimultaneous) {
        std::cout << "TurnBasedSimultaneous: Testing " << name << std::endl;
        for (int i = 0; i < 100; ++i) {
          std::shared_ptr<const Game> sim_game = LoadGame(name);
          std::shared_ptr<const Game> turn_based_game =
              ConvertToTurnBased(*LoadGame(name));
          auto sim_state = sim_game->NewInitialState();
          auto turn_based_state = turn_based_game->NewInitialState();
          SimulateGames(&rng, *sim_game, sim_state.get(),
                        turn_based_state.get());
        }
      }
    }
  }
}

}  // namespace
}  // namespace open_spiel

int main(int argc, char** argv) {
  open_spiel::BasicTurnBasedSimultaneousTests();
}
<commit_msg>Fix test for single-player nodes<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "open_spiel/game_transforms/turn_based_simultaneous_game.h"

#include <random>
#include <string>

#include "open_spiel/abseil-cpp/absl/random/uniform_int_distribution.h"
#include "open_spiel/spiel.h"

namespace open_spiel {
namespace {

void SimulateGames(std::mt19937* rng, const Game& game, State* sim_state,
                   State* turn_based_state) {
  while (!sim_state->IsTerminal()) {
    const State* wrapped_sim_state =
        dynamic_cast<TurnBasedSimultaneousState*>(turn_based_state)
            ->SimultaneousGameState();

    // Now check that the states are identical via the ToString().
    SPIEL_CHECK_EQ(sim_state->ToString(), wrapped_sim_state->ToString());

    if (sim_state->IsChanceNode()) {
      SPIEL_CHECK_TRUE(turn_based_state->IsChanceNode());

      // Chance node; sample one according to underlying distribution
      std::vector<std::pair<Action, double>> outcomes =
          sim_state->ChanceOutcomes();
      Action action =
          open_spiel::SampleAction(
              outcomes, std::uniform_real_distribution<double>(0.0, 1.0)(*rng))
              .first;

      std::cout << "sampled outcome: %s\n"
                << sim_state->ActionToString(kChancePlayerId, action)
                << std::endl;

      sim_state->ApplyAction(action);
      turn_based_state->ApplyAction(action);
    } else if (sim_state->CurrentPlayer() == kSimultaneousPlayerId) {
      SPIEL_CHECK_EQ(wrapped_sim_state->CurrentPlayer(), kSimultaneousPlayerId);

      // Players choose simultaneously.
      std::vector<Action> joint_action;

      // Sample an action for each player
      for (auto p = Player{0}; p < game.NumPlayers(); p++) {
        if (game.GetType().provides_information_state_string) {
          // Check the information states to each player are consistent.
          SPIEL_CHECK_EQ(sim_state->InformationStateString(p),
                         wrapped_sim_state->InformationStateString(p));
        }

        std::vector<Action> actions;
        actions = sim_state->LegalActions(p);
        absl::uniform_int_distribution<> dis(0, actions.size() - 1);
        Action action = actions[dis(*rng)];
        joint_action.push_back(action);
        std::cout << "player " << p << " chose "
                  << sim_state->ActionToString(p, action) << std::endl;
        SPIEL_CHECK_EQ(p, turn_based_state->CurrentPlayer());
        turn_based_state->ApplyAction(action);
      }

      sim_state->ApplyActions(joint_action);
    } else {
      SPIEL_CHECK_EQ(sim_state->CurrentPlayer(), wrapped_sim_state->CurrentPlayer());
      SPIEL_CHECK_EQ(sim_state->CurrentPlayer(), turn_based_state->CurrentPlayer());

      Player p = sim_state->CurrentPlayer();

      if (game.GetType().provides_information_state_string) {
        // Check the information states to each player are consistent.
        SPIEL_CHECK_EQ(sim_state->InformationStateString(p),
                       wrapped_sim_state->InformationStateString(p));
      }

      std::vector<Action> actions;
      actions = sim_state->LegalActions(p);
      absl::uniform_int_distribution<> dis(0, actions.size() - 1);
      Action action = actions[dis(*rng)];

      std::cout << "player " << p << " chose "
                << sim_state->ActionToString(p, action) << std::endl;

      turn_based_state->ApplyAction(action);
      sim_state->ApplyAction(action);
    }

    std::cout << "State: " << std::endl << sim_state->ToString() << std::endl;
  }

  SPIEL_CHECK_TRUE(turn_based_state->IsTerminal());

  auto sim_returns = sim_state->Returns();
  auto turn_returns = turn_based_state->Returns();

  for (auto player = Player{0}; player < game.NumPlayers(); player++) {
    double utility = sim_returns[player];
    SPIEL_CHECK_GE(utility, game.MinUtility());
    SPIEL_CHECK_LE(utility, game.MaxUtility());
    std::cout << "Utility to player " << player << " is " << utility
              << std::endl;

    double other_utility = turn_returns[player];
    SPIEL_CHECK_EQ(utility, other_utility);
  }
}

void BasicTurnBasedSimultaneousTests() {
  std::mt19937 rng;

  for (const GameType& type : RegisteredGameTypes()) {
    if (!type.ContainsRequiredParameters()) {
      std::string name = type.short_name;
      if (type.dynamics == GameType::Dynamics::kSimultaneous) {
        std::cout << "TurnBasedSimultaneous: Testing " << name << std::endl;
        for (int i = 0; i < 100; ++i) {
          std::shared_ptr<const Game> sim_game = LoadGame(name);
          std::shared_ptr<const Game> turn_based_game =
              ConvertToTurnBased(*LoadGame(name));
          auto sim_state = sim_game->NewInitialState();
          auto turn_based_state = turn_based_game->NewInitialState();
          SimulateGames(&rng, *sim_game, sim_state.get(),
                        turn_based_state.get());
        }
      }
    }
  }
}

}  // namespace
}  // namespace open_spiel

int main(int argc, char** argv) {
  open_spiel::BasicTurnBasedSimultaneousTests();
}
<|endoftext|>


<commit_before><commit_msg>Fix top-level trace event name in MessageLoop::RunTask<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkLoggerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#if defined(_MSC_VER)
   //Warning about: identifier was truncated to '255' characters in the debug information (MVC6.0 Debug)
#pragma warning( disable : 4786 )
#endif

#include <iostream>
#include <fstream>
#include "itkStdStreamLogOutput.h"
#include "itkLogger.h"

class LogTester
{
public:
  itk::Logger* GetLogger() { return m_Logger; }
  void SetLogger(itk::Logger* logger) { m_Logger = logger; }
  void log() {
    itkLogMacro( DEBUG, "DEBUG message by itkLogMacro\n" );
    itkLogMacro( INFO, "INFO message by itkLogMacro\n" );
    itkLogMacro( WARNING, "WARNING message by itkLogMacro\n" );
    itkLogMacro( CRITICAL, "CRITICAL message by itkLogMacro\n" );
    itkLogMacro( FATAL, "FATAL message by itkLogMacro\n" );
    itkLogMacro( MUSTFLUSH, "MUSTFLUSH message by itkLogMacro\n" );
  }
  static void logStatic(LogTester* tester)
  {
    itkLogMacroStatic(tester, DEBUG, "DEBUG message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, INFO, "INFO message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, WARNING, "WARNING message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, CRITICAL, "CRITICAL message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, FATAL, "FATAL message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, MUSTFLUSH, "MUSTFLUSH message by itkLogMacroStatic\n" );
  }
private:
  itk::Logger* m_Logger;
};

int itkLoggerTest( int argc, char *argv [] )
{
  try
    {
    if (argc < 2)
      {
      std::cout << "Usage: " << argv[0] << " logFilename" << std::endl;
      return EXIT_FAILURE;
      }

    // Create an ITK StdStreamLogOutputs
    itk::StdStreamLogOutput::Pointer coutput = itk::StdStreamLogOutput::New();
    itk::StdStreamLogOutput::Pointer foutput = itk::StdStreamLogOutput::New();
    coutput->SetStream(std::cout);
    std::ofstream fout(argv[1]);
    foutput->SetStream(fout);

    // Create an ITK Logger
    itk::Logger::Pointer logger = itk::Logger::New();

    std::cout << "Testing itk::Logger" << std::endl;

    // Setting the logger
    logger->SetName("org.itk.rootLogger");
    logger->SetPriorityLevel(itk::LoggerBase::INFO);
    logger->SetLevelForFlushing(itk::LoggerBase::CRITICAL);

    std::cout << "  Adding console and file stream LogOutputs" << std::endl;
    logger->AddLogOutput(coutput);
    logger->AddLogOutput(foutput);

    // Printing the logger's member variables
    std::cout << "  Name: " << logger->GetName() << std::endl;
    std::cout << "  Priority Level: " << logger->GetPriorityLevel() << std::endl;
    std::cout << "  Level For Flushing: " << logger->GetLevelForFlushing() << std::endl;

    // Logging by the itkLogMacro from a class with itk::Logger
    std::cout << "  Logging by the itkLogMacro from a class with itk::Logger" << std::endl;
    LogTester tester;
    tester.SetLogger(logger);
    tester.log();
    // Logging by the itkLogMacroStatic from a class with itk::Logger
    std::cout << "  Logging by the itkLogMacroStatic from a class with itk::Logger" << std::endl;
    LogTester::logStatic(&tester);

    // Writing by the logger
    std::cout << "  Writing by itk::Logger" << std::endl;
    logger->Write(itk::LoggerBase::DEBUG, "This is the DEBUG message.\n");
    logger->Write(itk::LoggerBase::INFO, "This is the INFO message.\n");
    logger->Write(itk::LoggerBase::WARNING, "This is the WARNING message.\n");
    logger->Write(itk::LoggerBase::CRITICAL, "This is the CRITICAL message.\n");
    logger->Write(itk::LoggerBase::FATAL, "This is the FATAL message.\n");
    logger->Write(itk::LoggerBase::MUSTFLUSH, "This is the MUSTFLUSH message.\n");
    logger->Flush();
    }
  catch(...)
    {
    std::cerr << "Exception catched !!" << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "[PASSED]" << std::endl;
  return EXIT_SUCCESS;
}

<commit_msg>ENH: Adding test for the functionality of printing out the time stamp in a      human readable format.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkLoggerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#if defined(_MSC_VER)
   //Warning about: identifier was truncated to '255' characters in the debug information (MVC6.0 Debug)
#pragma warning( disable : 4786 )
#endif

#include <iostream>
#include <fstream>
#include "itkStdStreamLogOutput.h"
#include "itkLogger.h"

class LogTester
{
public:
  itk::Logger* GetLogger() { return m_Logger; }
  void SetLogger(itk::Logger* logger) { m_Logger = logger; }
  void log() {
    itkLogMacro( DEBUG, "DEBUG message by itkLogMacro\n" );
    itkLogMacro( INFO, "INFO message by itkLogMacro\n" );
    itkLogMacro( WARNING, "WARNING message by itkLogMacro\n" );
    itkLogMacro( CRITICAL, "CRITICAL message by itkLogMacro\n" );
    itkLogMacro( FATAL, "FATAL message by itkLogMacro\n" );
    itkLogMacro( MUSTFLUSH, "MUSTFLUSH message by itkLogMacro\n" );
  }
  static void logStatic(LogTester* tester)
  {
    itkLogMacroStatic(tester, DEBUG, "DEBUG message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, INFO, "INFO message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, WARNING, "WARNING message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, CRITICAL, "CRITICAL message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, FATAL, "FATAL message by itkLogMacroStatic\n" );
    itkLogMacroStatic(tester, MUSTFLUSH, "MUSTFLUSH message by itkLogMacroStatic\n" );
  }
private:
  itk::Logger* m_Logger;
};

int itkLoggerTest( int argc, char *argv [] )
{
  try
    {
    if (argc < 2)
      {
      std::cout << "Usage: " << argv[0] << " logFilename" << std::endl;
      return EXIT_FAILURE;
      }

    // Create an ITK StdStreamLogOutputs
    itk::StdStreamLogOutput::Pointer coutput = itk::StdStreamLogOutput::New();
    itk::StdStreamLogOutput::Pointer foutput = itk::StdStreamLogOutput::New();
    coutput->SetStream(std::cout);
    std::ofstream fout(argv[1]);
    foutput->SetStream(fout);

    // Create an ITK Logger
    itk::Logger::Pointer logger = itk::Logger::New();

    std::cout << "Testing itk::Logger" << std::endl;

    // Setting the logger
    logger->SetName("org.itk.rootLogger");
    logger->SetPriorityLevel(itk::LoggerBase::INFO);
    logger->SetLevelForFlushing(itk::LoggerBase::CRITICAL);

    std::cout << "  Adding console and file stream LogOutputs" << std::endl;
    logger->AddLogOutput(coutput);
    logger->AddLogOutput(foutput);

    // Printing the logger's member variables
    std::cout << "  Name: " << logger->GetName() << std::endl;
    std::cout << "  Priority Level: " << logger->GetPriorityLevel() << std::endl;
    std::cout << "  Level For Flushing: " << logger->GetLevelForFlushing() << std::endl;

    // Logging by the itkLogMacro from a class with itk::Logger
    std::cout << "  Logging by the itkLogMacro from a class with itk::Logger" << std::endl;
    LogTester tester;
    tester.SetLogger(logger);
    tester.log();
    // Logging by the itkLogMacroStatic from a class with itk::Logger
    std::cout << "  Logging by the itkLogMacroStatic from a class with itk::Logger" << std::endl;
    LogTester::logStatic(&tester);

    // Writing by the logger
    std::cout << "  Writing by itk::Logger" << std::endl;
    logger->Write(itk::LoggerBase::DEBUG, "This is the DEBUG message.\n");
    logger->Write(itk::LoggerBase::INFO, "This is the INFO message.\n");
    logger->Write(itk::LoggerBase::WARNING, "This is the WARNING message.\n");
    logger->Write(itk::LoggerBase::CRITICAL, "This is the CRITICAL message.\n");
    logger->Write(itk::LoggerBase::FATAL, "This is the FATAL message.\n");
    logger->Write(itk::LoggerBase::MUSTFLUSH, "This is the MUSTFLUSH message.\n");
    logger->Flush();

    logger->SetTimeStampFormat( itk::LoggerBase::HUMANREADABLE );

    // Writing by the logger
    std::cout << "  Writing by itk::Logger in Human Readable format" << std::endl;
    logger->Write(itk::LoggerBase::DEBUG, "This is the DEBUG message.\n");
    logger->Write(itk::LoggerBase::INFO, "This is the INFO message.\n");
    logger->Write(itk::LoggerBase::WARNING, "This is the WARNING message.\n");
    logger->Write(itk::LoggerBase::CRITICAL, "This is the CRITICAL message.\n");
    logger->Write(itk::LoggerBase::FATAL, "This is the FATAL message.\n");
    logger->Write(itk::LoggerBase::MUSTFLUSH, "This is the MUSTFLUSH message.\n");
    logger->Flush();
    }
  catch(...)
    {
    std::cerr << "Exception catched !!" << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "[PASSED]" << std::endl;
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVTKImageIOTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <fstream>
#include <iostream>
#include "itkRandomImageSource.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkVTKImageIO.h"

int itkVTKImageIOTest(int argc, char* argv[] )
{
  typedef itk::Image<float,2> FloatImageType;

  if( argc < 3 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  output1 output2 " << std::endl;
    return 1;
    }

  // Create a source object (in this case a random image generator).
  // The source object is templated on the output type.
  //
  unsigned long size[2];
  size[0]=128; size[1]=64;

  itk::RandomImageSource<FloatImageType>::Pointer random;
  random = itk::RandomImageSource<FloatImageType>::New();
  random->SetMin(0.0);
  random->SetMax(1.0);
  random->SetSize(size);

  // Create a mapper (in this case a writer). A mapper
  // is templated on the input type.
  //
  itk::VTKImageIO::Pointer vtkIO;
  vtkIO = itk::VTKImageIO::New();

  // Write out the image
  itk::ImageFileWriter<FloatImageType>::Pointer writer;
  writer = itk::ImageFileWriter<FloatImageType>::New();
  writer->SetInput(random->GetOutput());
  writer->SetFileName(argv[1]);
  writer->SetImageIO(vtkIO);
  writer->Write();

  if ( !vtkIO->CanReadFile(argv[1]) )
    {
    return 1;
    }

  // Create a source object (in this case a reader)
  itk::ImageFileReader<FloatImageType>::Pointer reader;
  reader = itk::ImageFileReader<FloatImageType>::New();
  reader->SetImageIO(vtkIO);
  reader->SetFileName(argv[1]);
  reader->Update();

  writer->SetInput(reader->GetOutput());
  writer->SetFileName(argv[2]);
  writer->Write();

  return EXIT_SUCCESS;
}

<commit_msg>ENH: better coverage.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVTKImageIOTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <fstream>
#include <iostream>
#include "itkRandomImageSource.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkVTKImageIO.h"
#include "itkNumericTraits.h"

template<class TScalar, unsigned int TDimension>
int ReadWrite(TScalar low, TScalar hi, char *file1, char *file2, bool ascii)
{
  typedef itk::Image<TScalar,TDimension> ImageType;

  // Create a source object (in this case a random image generator).
  // The source object is templated on the output type.
  //
  unsigned long size[TDimension];
  for (unsigned int i = 0; i < TDimension; i++)
    {
    size[i]= 2 << (i + 1);
    }
  itk::RandomImageSource<ImageType>::Pointer random;
  random = itk::RandomImageSource<ImageType>::New();
  random->SetMin(low);
  random->SetMax(hi);
  random->SetSize(size);

  float spacing[3] = {5.0f, 10.0f, 15.0f};
  float origin[3] = {-5.0f, -10.0f, -15.0f};
  random->SetSpacing(spacing);
  random->SetOrigin(origin);

  // Create a mapper (in this case a writer). A mapper
  // is templated on the input type.
  //
  itk::VTKImageIO::Pointer vtkIO;
  vtkIO = itk::VTKImageIO::New();
  if (ascii)
    {
    vtkIO->SetFileTypeToASCII();
    }
  else
    {
    vtkIO->SetFileTypeToBinary();
    }

  // Write out the image
  itk::ImageFileWriter<ImageType>::Pointer writer;
  writer = itk::ImageFileWriter<ImageType>::New();
  writer->SetInput(random->GetOutput());
  writer->SetFileName(file1);
  writer->SetImageIO(vtkIO);
  writer->Write();

  if ( !vtkIO->CanReadFile(file1) )
    {
    return 1;
    }

  // Create a source object (in this case a reader)
  itk::ImageFileReader<ImageType>::Pointer reader;
  reader = itk::ImageFileReader<ImageType>::New();
  reader->SetImageIO(vtkIO);
  reader->SetFileName(file1);
  reader->Update();

  writer->SetInput(reader->GetOutput());
  writer->SetFileName(file2);
  writer->Write();

  return 0;
}

int itkVTKImageIOTest(int argc, char* argv[] )
{

  if( argc < 3 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  output1 output2 " << std::endl;
    return 1;
    }

  int status = 0;

  status += ReadWrite<float,2>(itk::NumericTraits<float>::NonpositiveMin(),
                             itk::NumericTraits<float>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<float,2>(itk::NumericTraits<float>::NonpositiveMin(),
                             itk::NumericTraits<float>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<float,3>(itk::NumericTraits<float>::NonpositiveMin(),
                             itk::NumericTraits<float>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<float,3>(itk::NumericTraits<float>::NonpositiveMin(),
                             itk::NumericTraits<float>::max(),
                             argv[1], argv[2], true);

  status += ReadWrite<double,2>(itk::NumericTraits<double>::NonpositiveMin(),
                             itk::NumericTraits<double>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<double,2>(itk::NumericTraits<double>::NonpositiveMin(),
                             itk::NumericTraits<double>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<double,3>(itk::NumericTraits<double>::NonpositiveMin(),
                             itk::NumericTraits<double>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<double,3>(itk::NumericTraits<double>::NonpositiveMin(),
                             itk::NumericTraits<double>::max(),
                             argv[1], argv[2], true);

  status += ReadWrite<unsigned char,2>(itk::NumericTraits<unsigned char>::NonpositiveMin(),
                             itk::NumericTraits<unsigned char>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<unsigned char,2>(itk::NumericTraits<unsigned char>::NonpositiveMin(),
                             itk::NumericTraits<unsigned char>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<unsigned char,3>(itk::NumericTraits<unsigned char>::NonpositiveMin(),
                             itk::NumericTraits<unsigned char>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<unsigned char,3>(itk::NumericTraits<unsigned char>::NonpositiveMin(),
                             itk::NumericTraits<unsigned char>::max(),
                             argv[1], argv[2], true);

  status += ReadWrite<char,2>(itk::NumericTraits<char>::NonpositiveMin(),
                             itk::NumericTraits<char>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<char,2>(itk::NumericTraits<char>::NonpositiveMin(),
                             itk::NumericTraits<char>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<char,3>(itk::NumericTraits<char>::NonpositiveMin(),
                             itk::NumericTraits<char>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<char,3>(itk::NumericTraits<char>::NonpositiveMin(),
                             itk::NumericTraits<char>::max(),
                             argv[1], argv[2], true);

  status += ReadWrite<unsigned short,2>(itk::NumericTraits<unsigned short>::NonpositiveMin(),
                             itk::NumericTraits<unsigned short>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<unsigned short,2>(itk::NumericTraits<unsigned short>::NonpositiveMin(),
                             itk::NumericTraits<unsigned short>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<unsigned short,3>(itk::NumericTraits<unsigned short>::NonpositiveMin(),
                             itk::NumericTraits<unsigned short>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<unsigned short,3>(itk::NumericTraits<unsigned short>::NonpositiveMin(),
                             itk::NumericTraits<unsigned short>::max(),
                             argv[1], argv[2], true);

  status += ReadWrite<short,2>(itk::NumericTraits<short>::NonpositiveMin(),
                             itk::NumericTraits<short>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<short,2>(itk::NumericTraits<short>::NonpositiveMin(),
                             itk::NumericTraits<short>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<short,3>(itk::NumericTraits<short>::NonpositiveMin(),
                             itk::NumericTraits<short>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<short,3>(itk::NumericTraits<short>::NonpositiveMin(),
                             itk::NumericTraits<short>::max(),
                             argv[1], argv[2], true);

  status += ReadWrite<int,2>(itk::NumericTraits<int>::NonpositiveMin(),
                             itk::NumericTraits<int>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<int,2>(itk::NumericTraits<int>::NonpositiveMin(),
                             itk::NumericTraits<int>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<int,3>(itk::NumericTraits<int>::NonpositiveMin(),
                             itk::NumericTraits<int>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<int,3>(itk::NumericTraits<int>::NonpositiveMin(),
                             itk::NumericTraits<int>::max(),
                             argv[1], argv[2], true);

  status += ReadWrite<unsigned long,2>(itk::NumericTraits<unsigned long>::NonpositiveMin(),
                             itk::NumericTraits<unsigned long>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<unsigned long,2>(itk::NumericTraits<unsigned long>::NonpositiveMin(),
                             itk::NumericTraits<unsigned long>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<unsigned long,3>(itk::NumericTraits<unsigned long>::NonpositiveMin(),
                             itk::NumericTraits<unsigned long>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<unsigned long,3>(itk::NumericTraits<unsigned long>::NonpositiveMin(),
                             itk::NumericTraits<unsigned long>::max(),
                             argv[1], argv[2], true);

  status += ReadWrite<long,2>(itk::NumericTraits<long>::NonpositiveMin(),
                             itk::NumericTraits<long>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<long,2>(itk::NumericTraits<long>::NonpositiveMin(),
                             itk::NumericTraits<long>::max(),
                             argv[1], argv[2], true);
  status += ReadWrite<long,3>(itk::NumericTraits<long>::NonpositiveMin(),
                             itk::NumericTraits<long>::max(),
                             argv[1], argv[2], false);
  status += ReadWrite<long,3>(itk::NumericTraits<long>::NonpositiveMin(),
                             itk::NumericTraits<long>::max(),
                             argv[1], argv[2], true);

  return status;
}
<|endoftext|>


<commit_before>#ifndef RDB_PROTOCOL_TERM_WALKER_HPP_
#define RDB_PROTOCOL_TERM_WALKER_HPP_

namespace ql {

#include "rdb_protocol/error.hpp"
#include "rdb_protocol/ql2.pb.h"
#include "rdb_protocol/ql2_extensions.pb.h"

// We use this class to walk a term and do something to every node.
class term_walker_t {
public:
    // This constructor fills in the backtraces of a term (`walk`) and checks
    // that it's well-formed with regard to write placement.
    explicit term_walker_t(Term *root) : depth(0), writes_legal(true), bt(0) {
        walk(root, 0, head_frame);
    }

    // This constructor propagates a backtrace down a tree until it hits a node
    // that already has a backtrace (this is used for e.g. rewrite terms so that
    // they return reasonable backtraces in the macroexpanded nodes).
    term_walker_t(Term *root, const Backtrace *_bt)
        : depth(0), writes_legal(true), bt(_bt) {
        propwalk(root, 0, head_frame);
    }
    ~term_walker_t() {
        r_sanity_check(depth == 0);
        r_sanity_check(writes_legal == true);
    }

    void walk(Term *t, Term *parent, backtrace_t::frame_t frame) {
        r_sanity_check(!bt);

        val_pusher_t<int> depth_pusher(&depth, depth+1);
        add_bt(t, parent, frame);

        if (t->type() == Term::ASC || t->type() == Term::DESC) {
            rcheck_src(&t->GetExtension(ql2::extension::backtrace),
                       parent && parent->type() == Term::ORDERBY,
                       strprintf("%s may only be used as an argument to ORDERBY.",
                                 (t->type() == Term::ASC ? "ASC" : "DESC")));
        }

        bool writes_still_legal = writes_are_still_legal(parent, frame);
        rcheck_src(&t->GetExtension(ql2::extension::backtrace),
                   writes_still_legal || !term_is_write_or_meta(t),
                   strprintf("Cannot nest writes or meta ops in stream operations.  "
                             "Use FOREACH instead."));
        val_pusher_t<bool> writes_legal_pusher(&writes_legal, writes_still_legal);

        term_recurse(t, &term_walker_t::walk);
    }

    void propwalk(Term *t, UNUSED Term *parent, UNUSED backtrace_t::frame_t frame) {
        r_sanity_check(bt);

        if (!t->HasExtension(ql2::extension::backtrace)) {
            *t->MutableExtension(ql2::extension::backtrace) = *bt;
            term_recurse(t, &term_walker_t::propwalk);
        }
    }
private:
    // Recurses to child terms.
    void term_recurse(Term *t, void (term_walker_t::*callback)(Term *, Term *,
                                                                backtrace_t::frame_t)) {
        for (int i = 0; i < t->args_size(); ++i) {
            (this->*callback)(t->mutable_args(i), t, backtrace_t::frame_t(i));
        }
        for (int i = 0; i < t->optargs_size(); ++i) {
            Term_AssocPair *ap = t->mutable_optargs(i);
            (this->*callback)(ap->mutable_val(), t, backtrace_t::frame_t(ap->key()));
        }
    }

    // Adds a backtrace to a term.
    void add_bt(Term *t, Term *parent, backtrace_t::frame_t frame) {
        r_sanity_check(t->ExtensionSize(ql2::extension::backtrace) == 0);
        if (parent) {
            *t->MutableExtension(ql2::extension::backtrace)
                = parent->GetExtension(ql2::extension::backtrace);
        } else {
            r_sanity_check(frame.is_head());
        }
        *t->MutableExtension(ql2::extension::backtrace)->add_frames() = frame.toproto();
    }

    // Returns true if `t` is a write or a meta op.
    static bool term_is_write_or_meta(Term *t) {
        return t->type() == Term::UPDATE
            || t->type() == Term::DELETE
            || t->type() == Term::INSERT
            || t->type() == Term::REPLACE

            || t->type() == Term::DB_CREATE
            || t->type() == Term::DB_DROP
            || t->type() == Term::DB_LIST
            || t->type() == Term::TABLE_CREATE
            || t->type() == Term::TABLE_DROP
            || t->type() == Term::TABLE_LIST;
    }

    // Returns true if writes are still legal at this node.  Basically:
    // * Once writes become illegal, they are never legal again.
    // * Writes are legal at the root.
    // * If the parent term forbids writes in its function arguments AND we
    //   aren't inside the 0th argument, writes are forbidden.
    // * Writes are legal in all other cases.
    bool writes_are_still_legal(Term *parent, backtrace_t::frame_t frame) {
        if (!writes_legal) return false; // writes never become legal again
        if (!parent) return true; // writes legal at root of tree
        if (term_forbids_writes(parent) && frame.is_stream_funcall_frame()) {
            return false;
        }
        return true;
    }
    static bool term_forbids_writes(Term *term) {
        return term->type() == Term::REDUCE
            || term->type() == Term::MAP
            || term->type() == Term::FILTER
            || term->type() == Term::CONCATMAP
            || term->type() == Term::GROUPED_MAP_REDUCE
            || term->type() == Term::GROUPBY
            || term->type() == Term::INNER_JOIN
            || term->type() == Term::OUTER_JOIN
            || term->type() == Term::EQ_JOIN

            || term->type() == Term::UPDATE
            || term->type() == Term::DELETE
            || term->type() == Term::REPLACE
            || term->type() == Term::INSERT;
    }

    // We use this class to change a value while recursing, then restore it to
    // its previous value.
    template<class T>
    class val_pusher_t {
    public:
        val_pusher_t(T *_val_ptr, T new_val) : val_ptr(_val_ptr) {
            old_val = *val_ptr;
            *val_ptr = new_val;
        }
        ~val_pusher_t() {
            *val_ptr = old_val;
        }
    private:
        T old_val;
        T *val_ptr;
    };

    int depth;
    bool writes_legal;
    const Backtrace *bt;
};

} // namespace ql

#endif // RDB_PROTOCOL_TERM_WALKER_HPP_
<commit_msg>updated term_walker and changed to a switch statement to catch future omissions (c.f. Issue 749)<commit_after>#ifndef RDB_PROTOCOL_TERM_WALKER_HPP_
#define RDB_PROTOCOL_TERM_WALKER_HPP_

namespace ql {

#include "rdb_protocol/error.hpp"
#include "rdb_protocol/ql2.pb.h"
#include "rdb_protocol/ql2_extensions.pb.h"

// We use this class to walk a term and do something to every node.
class term_walker_t {
public:
    // This constructor fills in the backtraces of a term (`walk`) and checks
    // that it's well-formed with regard to write placement.
    explicit term_walker_t(Term *root) : depth(0), writes_legal(true), bt(0) {
        walk(root, 0, head_frame);
    }

    // This constructor propagates a backtrace down a tree until it hits a node
    // that already has a backtrace (this is used for e.g. rewrite terms so that
    // they return reasonable backtraces in the macroexpanded nodes).
    term_walker_t(Term *root, const Backtrace *_bt)
        : depth(0), writes_legal(true), bt(_bt) {
        propwalk(root, 0, head_frame);
    }
    ~term_walker_t() {
        r_sanity_check(depth == 0);
        r_sanity_check(writes_legal == true);
    }

    void walk(Term *t, Term *parent, backtrace_t::frame_t frame) {
        r_sanity_check(!bt);

        val_pusher_t<int> depth_pusher(&depth, depth+1);
        add_bt(t, parent, frame);

        if (t->type() == Term::ASC || t->type() == Term::DESC) {
            rcheck_src(&t->GetExtension(ql2::extension::backtrace),
                       parent && parent->type() == Term::ORDERBY,
                       strprintf("%s may only be used as an argument to ORDERBY.",
                                 (t->type() == Term::ASC ? "ASC" : "DESC")));
        }

        bool writes_still_legal = writes_are_still_legal(parent, frame);
        rcheck_src(&t->GetExtension(ql2::extension::backtrace),
                   writes_still_legal || !term_is_write_or_meta(t),
                   strprintf("Cannot nest writes or meta ops in stream operations.  "
                             "Use FOREACH instead."));
        val_pusher_t<bool> writes_legal_pusher(&writes_legal, writes_still_legal);

        term_recurse(t, &term_walker_t::walk);
    }

    void propwalk(Term *t, UNUSED Term *parent, UNUSED backtrace_t::frame_t frame) {
        r_sanity_check(bt);

        if (!t->HasExtension(ql2::extension::backtrace)) {
            *t->MutableExtension(ql2::extension::backtrace) = *bt;
            term_recurse(t, &term_walker_t::propwalk);
        }
    }
private:
    // Recurses to child terms.
    void term_recurse(Term *t, void (term_walker_t::*callback)(Term *, Term *,
                                                                backtrace_t::frame_t)) {
        for (int i = 0; i < t->args_size(); ++i) {
            (this->*callback)(t->mutable_args(i), t, backtrace_t::frame_t(i));
        }
        for (int i = 0; i < t->optargs_size(); ++i) {
            Term_AssocPair *ap = t->mutable_optargs(i);
            (this->*callback)(ap->mutable_val(), t, backtrace_t::frame_t(ap->key()));
        }
    }

    // Adds a backtrace to a term.
    void add_bt(Term *t, Term *parent, backtrace_t::frame_t frame) {
        r_sanity_check(t->ExtensionSize(ql2::extension::backtrace) == 0);
        if (parent) {
            *t->MutableExtension(ql2::extension::backtrace)
                = parent->GetExtension(ql2::extension::backtrace);
        } else {
            r_sanity_check(frame.is_head());
        }
        *t->MutableExtension(ql2::extension::backtrace)->add_frames() = frame.toproto();
    }

    // Returns true if `t` is a write or a meta op.
    static bool term_is_write_or_meta(Term *t) {
        switch (t->type()) {
        case Term::UPDATE: case Term::DELETE: case Term::INSERT: case Term::REPLACE:
        case Term::DB_CREATE: case Term::DB_DROP: case Term::DB_LIST:
        case Term::TABLE_CREATE: case Term::TABLE_DROP: case Term::TABLE_LIST:
        case Term::INDEX_CREATE: case Term::INDEX_DROP: case Term::INDEX_LIST:
            return true;

        case Term::DATUM: case Term::MAKE_ARRAY: case Term::MAKE_OBJ: case Term::VAR:
        case Term::JAVASCRIPT: case Term::ERROR: case Term::IMPLICIT_VAR: case Term::DB:
        case Term::TABLE: case Term::GET: case Term::GET_ALL: case Term::EQ:
        case Term::NE: case Term::LT: case Term::LE: case Term::GT: case Term::GE:
        case Term::NOT: case Term::ADD: case Term::SUB: case Term::MUL: case Term::DIV:
        case Term::MOD: case Term::APPEND: case Term::SLICE: case Term::GETATTR:
        case Term::CONTAINS: case Term::PLUCK: case Term::WITHOUT: case Term::MERGE:
        case Term::BETWEEN: case Term::REDUCE: case Term::MAP: case Term::FILTER:
        case Term::CONCATMAP: case Term::ORDERBY: case Term::DISTINCT: case Term::COUNT:
        case Term::UNION: case Term::NTH: case Term::GROUPED_MAP_REDUCE:
        case Term::LIMIT: case Term::SKIP: case Term::GROUPBY: case Term::INNER_JOIN:
        case Term::OUTER_JOIN: case Term::EQ_JOIN: case Term::ZIP: case Term::COERCE_TO:
        case Term::TYPEOF: case Term::FUNCALL: case Term::BRANCH: case Term::ANY:
        case Term::ALL: case Term::FOREACH: case Term::FUNC: case Term::ASC:
        case Term::DESC:
            return false;
        default: unreachable();
        }
    }

    // Returns true if writes are still legal at this node.  Basically:
    // * Once writes become illegal, they are never legal again.
    // * Writes are legal at the root.
    // * If the parent term forbids writes in its function arguments AND we
    //   aren't inside the 0th argument, writes are forbidden.
    // * Writes are legal in all other cases.
    bool writes_are_still_legal(Term *parent, backtrace_t::frame_t frame) {
        if (!writes_legal) return false; // writes never become legal again
        if (!parent) return true; // writes legal at root of tree
        if (term_forbids_writes(parent) && frame.is_stream_funcall_frame()) {
            return false;
        }
        return true;
    }
    static bool term_forbids_writes(Term *term) {
        switch (term->type()) {
        case Term::REDUCE: case Term::MAP: case Term::FILTER: case Term::CONCATMAP:
        case Term::GROUPED_MAP_REDUCE: case Term::GROUPBY: case Term::INNER_JOIN:
        case Term::OUTER_JOIN: case Term::EQ_JOIN: case Term::UPDATE:
        case Term::DELETE: case Term::REPLACE: case Term::INSERT:
            return true;

        case Term::DATUM: case Term::MAKE_ARRAY: case Term::MAKE_OBJ: case Term::VAR:
        case Term::JAVASCRIPT: case Term::ERROR: case Term::IMPLICIT_VAR: case Term::DB:
        case Term::TABLE: case Term::GET: case Term::GET_ALL: case Term::EQ:
        case Term::NE: case Term::LT: case Term::LE: case Term::GT: case Term::GE:
        case Term::NOT: case Term::ADD: case Term::SUB: case Term::MUL: case Term::DIV:
        case Term::MOD: case Term::APPEND: case Term::SLICE: case Term::GETATTR:
        case Term::CONTAINS: case Term::PLUCK: case Term::WITHOUT: case Term::MERGE:
        case Term::BETWEEN: case Term::ORDERBY: case Term::DISTINCT: case Term::COUNT:
        case Term::UNION: case Term::NTH: case Term::LIMIT: case Term::SKIP:
        case Term::ZIP: case Term::COERCE_TO: case Term::TYPEOF: case Term::DB_CREATE:
        case Term::DB_DROP: case Term::DB_LIST: case Term::TABLE_CREATE:
        case Term::TABLE_DROP: case Term::TABLE_LIST: case Term::INDEX_CREATE:
        case Term::INDEX_DROP: case Term::INDEX_LIST: case Term::FUNCALL:
        case Term::BRANCH: case Term::ANY: case Term::ALL: case Term::FOREACH:
        case Term::FUNC: case Term::ASC: case Term::DESC:
            return false;
        default: unreachable();
        }
    }

    // We use this class to change a value while recursing, then restore it to
    // its previous value.
    template<class T>
    class val_pusher_t {
    public:
        val_pusher_t(T *_val_ptr, T new_val) : val_ptr(_val_ptr) {
            old_val = *val_ptr;
            *val_ptr = new_val;
        }
        ~val_pusher_t() {
            *val_ptr = old_val;
        }
    private:
        T old_val;
        T *val_ptr;
    };

    int depth;
    bool writes_legal;
    const Backtrace *bt;
};

} // namespace ql

#endif // RDB_PROTOCOL_TERM_WALKER_HPP_
<|endoftext|>


<commit_before>/******************************************************************************/
/*                                                                            */
/*                        b b c p _ P r o g M o n . C                         */
/*                                                                            */
/* (c) 2002 by the Board of Trustees of the Leland Stanford, Jr., University  */
/*      All Rights Reserved. See bbcp_Version.C for complete License Terms    *//*                            All Rights Reserved                             */
/*   Produced by Andrew Hanushevsky for Stanford University under contract    */
/*              DE-AC03-76-SFO0515 with the Department of Energy              */
/******************************************************************************/

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include "bbcp_Config.h"
#include "bbcp_Debug.h"
#include "bbcp_File.h"
#include "bbcp_Headers.h"
#include "bbcp_ProgMon.h"
#include "bbcp_Timer.h"
#include "bbcp_ZCX.h"

/******************************************************************************/
/*                      G l o b a l   V a r i a b l e s                       */
/******************************************************************************/

extern bbcp_Config   bbcp_Config;

/******************************************************************************/
/*           E x t e r n a l   I n t e r f a c e   R o u t i n e s            */
/******************************************************************************/

extern "C"
{
void *bbcp_MonProg(void *pp)
{
     bbcp_ProgMon *pmp = (bbcp_ProgMon *)pp;
     pmp->Monitor();
     return (void *)0;
}
}

/******************************************************************************/
/*                               M o n i t o r                                */
/******************************************************************************/

void bbcp_ProgMon::Monitor()
{
   unsigned int  elptime, lasttime, intvtime;
   long long     cxbytes = 0, curbytes, lastbytes = 0;
   float         cratio;
   double        xfrtime, xfrtnow;
   bbcp_Timer    etime;
   char          buff[200], pbuff[24], tbuff[24], cxinfo[40], *cxip;
   const char    *xtXB, *xaXB;
   int           bewordy = bbcp_Config.Options & bbcp_VERBOSE;

// Determine whether we need to report compression ratio (assume no percentages)
//
   if (CXp) cxip = cxinfo;
      else cxip = (char *)"";
   strcpy(pbuff, "not");

// Run a loop until we are killed, reporting what we see
//
   etime.Start(); etime.Report(lasttime);
   while(!alldone && CondMon.Wait(wtime))
      {etime.Stop(); etime.Report(elptime);

       curbytes = FSp->Stats();
       if (Tbytes) sprintf(pbuff,"%d%%",static_cast<int>(curbytes*100/Tbytes));
       xfrtime =  static_cast<double>(curbytes)
               / (static_cast<double>(elptime) / 1000.0);

       if (CXp)
          {if (!(cxbytes = CXp->Bytes())) cratio = 0.0;
              else cratio = static_cast<float>(curbytes*10/cxbytes) / 10.0;
           sprintf(cxinfo, " compressed %.1f", cratio);
          }

       if (bewordy)
          {intvtime = elptime - lasttime;
           xfrtnow =  static_cast<double>(curbytes-lastbytes)
                   / (static_cast<double>(intvtime) / 1000.0);
           xaXB = bbcp_Config::Scale(xfrtnow);
          }
       lastbytes = curbytes;
       lasttime  = elptime;
       xtXB = bbcp_Config::Scale(xfrtime);

       if (bbcp_Config.Logfn) *tbuff = 0;
          else etime.Format(tbuff);
       if (bewordy)
          sprintf(buff, "bbcp: %s %s done; %.1f %sB/s, "
                        "avg %.1f %sB/s%s\n",
                        tbuff,  pbuff, xfrtnow, xtXB, xfrtime, xaXB, cxip);
          else
          sprintf(buff, "bbcp: %s %s done; %.1f %sB/s%s\n",
                         tbuff,  pbuff, xfrtime, xtXB, cxip);
       cerr <<buff <<flush;
      }

// Post the semaphore to indicate we are done. This is a far safer way to
// synchronize exits than using pthread_join().
//
   monDone.Post();
}

/******************************************************************************/
/*                                 S t a r t                                  */
/******************************************************************************/

void bbcp_ProgMon::Start(bbcp_File *fs_obj, bbcp_ZCX *cx_obj, int pint,
                         long long xfrbytes)
{  int retc;

// If we are already monitoring, issue a stop
//
   if (mytid) Stop();

// Preset all values
//
   alldone = 0;
   FSp     = fs_obj;
   CXp     = cx_obj;
   wtime   = pint;
   Tbytes  = xfrbytes;

// Run a thread to start the monitor
//
   if (retc = bbcp_Thread_Run(bbcp_MonProg, (void *)this, &mytid))
      {DEBUG("Error " <<retc <<" starting progress monitor thread.");}
      else {DEBUG("Thread " <<mytid <<" monitoring progress.");}
   return;
}

/******************************************************************************/
/*                                  S t o p                                   */
/******************************************************************************/

void bbcp_ProgMon::Stop()
{

// Simply issue a cancel to the thread running the progress monitor
//
   alldone = 1;
   if (mytid)
      {DEBUG("Progress monitor " <<mytid <<" stopped.");
       CondMon.Signal();
       monDone.Wait();
       mytid = 0;
      }
}
<commit_msg>Print correct units when showing avg and incremental transfer rates in progress messages.<commit_after>/******************************************************************************/
/*                                                                            */
/*                        b b c p _ P r o g M o n . C                         */
/*                                                                            */
/* (c) 2002 by the Board of Trustees of the Leland Stanford, Jr., University  */
/*      All Rights Reserved. See bbcp_Version.C for complete License Terms    *//*                            All Rights Reserved                             */
/*   Produced by Andrew Hanushevsky for Stanford University under contract    */
/*              DE-AC03-76-SFO0515 with the Department of Energy              */
/******************************************************************************/

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include "bbcp_Config.h"
#include "bbcp_Debug.h"
#include "bbcp_File.h"
#include "bbcp_Headers.h"
#include "bbcp_ProgMon.h"
#include "bbcp_Timer.h"
#include "bbcp_ZCX.h"

/******************************************************************************/
/*                      G l o b a l   V a r i a b l e s                       */
/******************************************************************************/

extern bbcp_Config   bbcp_Config;

/******************************************************************************/
/*           E x t e r n a l   I n t e r f a c e   R o u t i n e s            */
/******************************************************************************/

extern "C"
{
void *bbcp_MonProg(void *pp)
{
     bbcp_ProgMon *pmp = (bbcp_ProgMon *)pp;
     pmp->Monitor();
     return (void *)0;
}
}

/******************************************************************************/
/*                               M o n i t o r                                */
/******************************************************************************/

void bbcp_ProgMon::Monitor()
{
   unsigned int  elptime, lasttime, intvtime;
   long long     cxbytes = 0, curbytes, lastbytes = 0;
   float         cratio;
   double        xfrtime, xfrtnow;
   bbcp_Timer    etime;
   char          buff[200], pbuff[24], tbuff[24], cxinfo[40], *cxip;
   const char    *xtXB, *xaXB;
   int           bewordy = bbcp_Config.Options & bbcp_VERBOSE;

// Determine whether we need to report compression ratio (assume no percentages)
//
   if (CXp) cxip = cxinfo;
      else cxip = (char *)"";
   strcpy(pbuff, "not");

// Run a loop until we are killed, reporting what we see
//
   etime.Start(); etime.Report(lasttime);
   while(!alldone && CondMon.Wait(wtime))
      {etime.Stop(); etime.Report(elptime);

       curbytes = FSp->Stats();
       if (Tbytes) sprintf(pbuff,"%d%%",static_cast<int>(curbytes*100/Tbytes));
       xfrtime =  static_cast<double>(curbytes)
               / (static_cast<double>(elptime) / 1000.0);

       if (CXp)
          {if (!(cxbytes = CXp->Bytes())) cratio = 0.0;
              else cratio = static_cast<float>(curbytes*10/cxbytes) / 10.0;
           sprintf(cxinfo, " compressed %.1f", cratio);
          }

       if (bewordy)
          {intvtime = elptime - lasttime;
           xfrtnow =  static_cast<double>(curbytes-lastbytes)
                   / (static_cast<double>(intvtime) / 1000.0);
           xaXB = bbcp_Config::Scale(xfrtnow);
          }
       lastbytes = curbytes;
       lasttime  = elptime;
       xtXB = bbcp_Config::Scale(xfrtime);

       if (bbcp_Config.Logfn) *tbuff = 0;
          else etime.Format(tbuff);
       if (bewordy)
          sprintf(buff, "bbcp: %s %s done; %.1f %sB/s, "
                        "avg %.1f %sB/s%s\n",
                        tbuff,  pbuff, xfrtnow, xaXB, xfrtime, xtXB, cxip);
          else
          sprintf(buff, "bbcp: %s %s done; %.1f %sB/s%s\n",
                         tbuff,  pbuff, xfrtime, xtXB, cxip);
       cerr <<buff <<flush;
      }

// Post the semaphore to indicate we are done. This is a far safer way to
// synchronize exits than using pthread_join().
//
   monDone.Post();
}

/******************************************************************************/
/*                                 S t a r t                                  */
/******************************************************************************/

void bbcp_ProgMon::Start(bbcp_File *fs_obj, bbcp_ZCX *cx_obj, int pint,
                         long long xfrbytes)
{  int retc;

// If we are already monitoring, issue a stop
//
   if (mytid) Stop();

// Preset all values
//
   alldone = 0;
   FSp     = fs_obj;
   CXp     = cx_obj;
   wtime   = pint;
   Tbytes  = xfrbytes;

// Run a thread to start the monitor
//
   if (retc = bbcp_Thread_Run(bbcp_MonProg, (void *)this, &mytid))
      {DEBUG("Error " <<retc <<" starting progress monitor thread.");}
      else {DEBUG("Thread " <<mytid <<" monitoring progress.");}
   return;
}

/******************************************************************************/
/*                                  S t o p                                   */
/******************************************************************************/

void bbcp_ProgMon::Stop()
{

// Simply issue a cancel to the thread running the progress monitor
//
   alldone = 1;
   if (mytid)
      {DEBUG("Progress monitor " <<mytid <<" stopped.");
       CondMon.Signal();
       monDone.Wait();
       mytid = 0;
      }
}
<|endoftext|>