<commit_before>#ifdef WIN32
	#include <intrin.h>
#endif
#include "math.hpp"
#include "../vector.hpp"
#include "../matrix.hpp"
#include "../matstack.hpp"
#include "../pose.hpp"
#include "../bits.hpp"
#include "../noseq.hpp"
#include "test.hpp"
#include "../random.hpp"

namespace spn {
	namespace test {
		void MatTest() {
			Mat44 m4 = Mat44::RotationZ(DEGtoRAD(0));
			auto idx = Mat44(Mat44::TagIdentity);
			auto mm4 = m4 * idx;
			m4 *= idx;

			AMat43 mrY = AMat43::RotationY(DEGtoRAD(45));
			auto mrY4 = mrY.convertA44();

			AMat33 mrX = AMat33::RotationX(DEGtoRAD(90));
			AVec3 vrot(0,0,100);
			auto vr = vrot * mrX;
			float len = vrot.length();

			using MyStack = MatStack<Mat33, MatStackTag::PushRight>;
			MyStack stk;
			stk.push(Mat33(mrX));
		}
		void PoseTest() {
			Pose2D p2(AVec2(100,200), 128, AVec2(1,1)),
			p3(AVec2(1,2), 64, AVec2(3,3));
			auto p4 = p2.lerp(p3, 0.5f);
			p4 = p4;

			auto pc = AVec3::FromPacked(MakeChunk(64,128,192,255));
			auto pc2 = pc.toPacked();

			noseq_list<float> ls;
			auto id0 = ls.add(256);
			auto id1 = ls.add(512);
			auto id2 = ls.add(1024);
			std::cout << std::hex
					<< id0 << std::endl
					<< id1 << std::endl
					<< id2 << std::endl;
			ls.rem(id1);
			auto re = ls.alloc();
			re.second = 1.234f;
			for(auto& p : ls) {
				std::cout << p << std::endl;
			}
		}
		void BitFieldTest() {
			struct MyDef : BitDef<uint32_t, BitF<0,14>, BitF<14,6>, BitF<20,12>> {
				enum { VAL0, VAL1, VAL2 }; };
			using Value = BitField<MyDef>;
			Value value(0);
			value.at<Value::VAL2>() = ~0;
			auto mask = value.mask<Value::VAL1>();
			auto raw = value.value();
			std::cout << std::hex << "raw" << raw
									<< "mask" << mask << std::endl;
		}
		void GapTest() {
			auto rd = mgr_random.get(0);
			auto gen = std::bind(&MTRandom::getUniform<float>, std::ref(rd));
			using F16 = std::array<float,16>;
			F16 tmp;
			std::generate(tmp.begin(), tmp.end(), std::ref(gen));

			#define SETAUX(z,n,data)	aux##n = *data++;
			#define CHECKAUX(z,n,data) Assert(Trap, aux##n==*data++)
			{
				struct Test {
					GAP_MATRIX(mat, 4,3,
							(((float, aux0)))
							(((float, aux1)))
							(((float, aux2)))
							(((float, aux3)))
					)

					Test(const F16& tmp) {
						auto* src = SetValue(mat, &tmp[0]);
						BOOST_PP_REPEAT(4, SETAUX, src)
						src = CheckValue(mat, &tmp[0]);
						BOOST_PP_REPEAT(4, CHECKAUX, src)
					}
				} test(tmp);
			}
			{
				struct Test {
					GAP_MATRIX(mat, 4,2,
							(((float, aux0), (float, aux4)))
							(((float, aux1), (float, aux5)))
							(((float, aux2), (float, aux6)))
							(((float, aux3), (float, aux7)))
					)
					Test(const F16& tmp) {
						auto* src = SetValue(mat, &tmp[0]);
						BOOST_PP_REPEAT(8, SETAUX, src)
						src = CheckValue(mat, &tmp[0]);
						BOOST_PP_REPEAT(8, CHECKAUX, src)
					}
				} test(tmp);
			}
			{
				struct Test {
					GAP_VECTOR(vec, 3, (float aux0))
					Test(const F16& tmp) {
						auto* src = SetValue(vec, &tmp[0]);
						BOOST_PP_REPEAT(1, SETAUX, src)
						src = CheckValue(vec, &tmp[0]);
						BOOST_PP_REPEAT(1, CHECKAUX, src)
					}
				} test(tmp);
			}
			{
				struct Test {
					GAP_VECTOR(vec, 2, (float aux0)(float aux1))
					Test(const F16& tmp) {
						auto* src = SetValue(vec, &tmp[0]);
						BOOST_PP_REPEAT(2, SETAUX, src)
						src = CheckValue(vec, &tmp[0]);
						BOOST_PP_REPEAT(2, CHECKAUX, src)
					}
				} test(tmp);
			}
			#undef SETAUX
			#undef CHECKAUX
		}
	}
}
<commit_msg>少しはマシなMatrixテストコードを追加<commit_after>#ifdef WIN32
	#include <intrin.h>
#endif
#include "math.hpp"
#include "../vector.hpp"
#include "../matrix.hpp"
#include "../matstack.hpp"
#include "../pose.hpp"
#include "../bits.hpp"
#include "../noseq.hpp"
#include "test.hpp"
#include "../random.hpp"

namespace spn {
	namespace test {
		#define MATRIXCHECK(z, dummy, dim)	MatrixCheck<BOOST_PP_TUPLE_ELEM(0,dim), BOOST_PP_TUPLE_ELEM(1,dim)>();
		namespace {
			constexpr float Threshold = 5e-4f,
							ValueMin = -1e4f,
							ValueMax = 1e4f,
							N_Iteration = 100;
			auto OpMul = [](auto& v0, auto& v1){ return v0 * v1; };
			auto OpDiv = [](auto& v0, auto& v1){ return v0 / v1; };
			auto OpAdd = [](auto& v0, auto& v1){ return v0 + v1; };
			auto OpSub = [](auto& v0, auto& v1){ return v0 - v1; };
			auto OpCopy = [](auto& v0, auto& v1){ return v1; };
			template <int M, int N>
			using Array2D = std::array<std::array<float, N>, M>;
			template <class RD, class AR, int M, int N, bool A>
			void SetRandom(RD& rd, AR& ar, MatT<M,N,A>& m) {
				for(int i=0 ; i<M ; i++) {
					for(int j=0 ; j<N ; j++) {
						m.ma[i][j] = ar[i][j] = rd();
					}
				}
			}
			template <class AR, int M, int N, bool A>
			bool Compare(const AR& ar, const MatT<M,N,A>& m) {
				for(int i=0 ; i<M ; i++) {
					for(int j=0 ; j<N ; j++) {
						auto diff = ar[i][j] - m.ma[i][j];
						if(std::fabs(diff) >= Threshold)
							return false;
					}
				}
				return true;
			}
			template <class AR>
			struct GetArraySize {
				template <class T, size_t N>
				constexpr static int _size(const std::array<T,N>*) {
					return N;
				}
				constexpr static int size() {
					constexpr AR* ar = nullptr;
					return _size(ar);
				}
			};
			template <class AR, class OP>
			void Operate(AR& ar, OP&& op) {
				using Type = std::decay_t<decltype(ar[0])>;
				for(int i=0 ; i<GetArraySize<AR>::size() ; i++) {
					for(int j=0 ; j<GetArraySize<Type>::size() ; j++)
						op(ar[i][j]);
				}
			}
			template <class AR, class OP>
			void Operate1(AR& ar0, const AR& ar1, OP&& op) {
				using Type = std::decay_t<decltype(ar0[0])>;
				for(int i=0 ; i<GetArraySize<AR>::size(); i++) {
					for(int j=0 ; j<GetArraySize<Type>::size() ; j++)
						ar0[i][j] = op(ar0[i][j], ar1[i][j]);
				}
			}
			template <class AR, class OP>
			void MulArray(AR& ar0, const AR& ar1, OP&& op) {
				using Type = std::decay_t<decltype(ar0[0])>;
				constexpr int width{ GetArraySize<AR>::size() },
							height{ GetArraySize<Type>::size() };
				static_assert(width == height, "rectangular matrix only");
				AR tmp;
				for(int i=0 ; i<width ; i++) {
					for(int j=0 ; j<width; j++) {
						tmp[i][j] = 0;
						for(int k=0 ; k<width ; k++)
							tmp[i][j] += ar0[i][k] * ar1[k][j];
					}
				}
				for(int i=0 ; i<width ; i++) {
					for(int j=0 ; j<width ; j++)
						ar0[i][j] = tmp[i][j];
				}
			}
			template <class AR>
			void TransposeArray(AR& ar0, const AR& ar1) {
				using Type = std::decay_t<decltype(ar0[0])>;
				constexpr int width{ GetArraySize<AR>::size() };
				static_assert(width == GetArraySize<Type>::size(), "width must be equal to height");
				for(int i=0 ; i<width ; i++) {
					for(int j=0 ; j<width ; j++)
						ar0[i][j] = ar1[j][i];
				}
			}
			template <class RD, int M, int N, bool A>
			void _MatrixCheckRect(RD& rd,
									std::integral_constant<int,M>,
									std::integral_constant<int,N>,
									std::integral_constant<bool,A>)
			{}
			template <class RD, int N, bool A>
			void _MatrixCheckRect(RD& rd,
									std::integral_constant<int,N>,
									std::integral_constant<int,N>,
									std::integral_constant<bool,A>)
			{
				using Mat = MatT<N,N,A>;
				auto fnTestMat = [&rd](auto&& opA, auto&& opM) {
					for(int i=0 ; i<N_Iteration ; i++) {
						Mat m0, m1;
						Array2D<N,N> ar0, ar1;
						SetRandom(rd, ar0, m0);
						SetRandom(rd, ar1, m1);
						opA(ar0, ar1, std::forward<std::decay_t<decltype(opM)>>(opM));
						auto m2 = opM(m0,m1);
						m0 = opM(m0, m1);
						Assert(Trap, Compare(ar0, m0))
					}
				};
				// + mat
				fnTestMat([](auto& a0, auto& a1, auto&&){ Operate1(a0,a1,OpAdd); }, OpAdd);
				// - mat
				fnTestMat([](auto& a0, auto& a1, auto&&){ Operate1(a0,a1,OpSub); }, OpSub);
				// * mat
				auto* ptr = &MulArray<std::array<std::array<float, N>, N>, decltype(OpMul)>;
				fnTestMat(ptr, OpMul);
				// = mat
				fnTestMat([](auto& a0, auto& a1, auto&&){ Operate1(a0,a1,OpCopy); }, OpCopy);
				// determinant
				// inversion

				// transpose
				Array2D<N,N>	ar0,ar1;
				Mat				m0,m1;
				SetRandom(rd, ar1, m1);
				TransposeArray(ar0, ar1);
				m0 = m1.transposition();
				Assert(Trap, Compare(ar0, m0))
			}
			template <int M, int N, bool A>
			void _MatrixCheck() {
				// 配列を使って計算した結果とMatrixクラスの結果を、誤差含めて比較
				auto rd = mgr_random.get(0);
				auto rdF = [&rd](){ return rd.template getUniformRange<float>(ValueMin, ValueMax); };

				using Mat = MatT<M,N,A>;
				auto fnTestScalar = [&rdF](auto& rd, auto&& op) {
					for(int i=0 ; i<N_Iteration ; i++) {
						Mat m0;
						Array2D<M,N> ar0;
						SetRandom(rdF, ar0, m0);

						float value = rd();
						Operate(ar0, [value, &op](auto& v){ v = op(v, value); });
						m0 = op(m0, value);
						Assert(Trap, Compare(ar0, m0))
					}
				};
				// += scalar
				fnTestScalar(rdF, OpAdd);
				// -= scalar
				fnTestScalar(rdF, OpSub);
				// *= scalar
				fnTestScalar(rdF, OpMul);
				// /= scalar
				fnTestScalar(rdF, OpDiv);
				// --- Rect Only ---
				_MatrixCheckRect(rdF,
								std::integral_constant<int,M>(),
								std::integral_constant<int,N>(),
								std::integral_constant<bool,A>());
			}
			template <int M, int N>
			void MatrixCheck() {
				_MatrixCheck<M,N,false>();
				_MatrixCheck<M,N,true>();
			}
		}
		void MatTest() {
			BOOST_PP_SEQ_FOR_EACH(MATRIXCHECK, BOOST_PP_IDENTITY, SEQ_MATDEF)
		}
		void PoseTest() {
			Pose2D p2(AVec2(100,200), 128, AVec2(1,1)),
			p3(AVec2(1,2), 64, AVec2(3,3));
			auto p4 = p2.lerp(p3, 0.5f);
			p4 = p4;

			auto pc = AVec3::FromPacked(MakeChunk(64,128,192,255));
			auto pc2 = pc.toPacked();

			noseq_list<float> ls;
			auto id0 = ls.add(256);
			auto id1 = ls.add(512);
			auto id2 = ls.add(1024);
			std::cout << std::hex
					<< id0 << std::endl
					<< id1 << std::endl
					<< id2 << std::endl;
			ls.rem(id1);
			auto re = ls.alloc();
			re.second = 1.234f;
			for(auto& p : ls) {
				std::cout << p << std::endl;
			}
		}
		void BitFieldTest() {
			struct MyDef : BitDef<uint32_t, BitF<0,14>, BitF<14,6>, BitF<20,12>> {
				enum { VAL0, VAL1, VAL2 }; };
			using Value = BitField<MyDef>;
			Value value(0);
			value.at<Value::VAL2>() = ~0;
			auto mask = value.mask<Value::VAL1>();
			auto raw = value.value();
			std::cout << std::hex << "raw" << raw
									<< "mask" << mask << std::endl;
		}
		void GapTest() {
			auto rd = mgr_random.get(0);
			auto gen = std::bind(&MTRandom::getUniform<float>, std::ref(rd));
			using F16 = std::array<float,16>;
			F16 tmp;
			std::generate(tmp.begin(), tmp.end(), std::ref(gen));

			#define SETAUX(z,n,data)	aux##n = *data++;
			#define CHECKAUX(z,n,data) Assert(Trap, aux##n==*data++)
			{
				struct Test {
					GAP_MATRIX(mat, 4,3,
							(((float, aux0)))
							(((float, aux1)))
							(((float, aux2)))
							(((float, aux3)))
					)

					Test(const F16& tmp) {
						auto* src = SetValue(mat, &tmp[0]);
						BOOST_PP_REPEAT(4, SETAUX, src)
						src = CheckValue(mat, &tmp[0]);
						BOOST_PP_REPEAT(4, CHECKAUX, src)
					}
				} test(tmp);
			}
			{
				struct Test {
					GAP_MATRIX(mat, 4,2,
							(((float, aux0), (float, aux4)))
							(((float, aux1), (float, aux5)))
							(((float, aux2), (float, aux6)))
							(((float, aux3), (float, aux7)))
					)
					Test(const F16& tmp) {
						auto* src = SetValue(mat, &tmp[0]);
						BOOST_PP_REPEAT(8, SETAUX, src)
						src = CheckValue(mat, &tmp[0]);
						BOOST_PP_REPEAT(8, CHECKAUX, src)
					}
				} test(tmp);
			}
			{
				struct Test {
					GAP_VECTOR(vec, 3, (float aux0))
					Test(const F16& tmp) {
						auto* src = SetValue(vec, &tmp[0]);
						BOOST_PP_REPEAT(1, SETAUX, src)
						src = CheckValue(vec, &tmp[0]);
						BOOST_PP_REPEAT(1, CHECKAUX, src)
					}
				} test(tmp);
			}
			{
				struct Test {
					GAP_VECTOR(vec, 2, (float aux0)(float aux1))
					Test(const F16& tmp) {
						auto* src = SetValue(vec, &tmp[0]);
						BOOST_PP_REPEAT(2, SETAUX, src)
						src = CheckValue(vec, &tmp[0]);
						BOOST_PP_REPEAT(2, CHECKAUX, src)
					}
				} test(tmp);
			}
			#undef SETAUX
			#undef CHECKAUX
		}
	}
}
<|endoftext|>


<commit_before>#include "LedController.hpp"

#include <algorithm>
#include <bitset>

LedController::LedController(std::ostream& stream) : out{stream}
{
}

void LedController::runProgram(const Instructions& instructions)
{
    for (const auto& instruction : instructions)
    {
        runInstruction(instruction);
    }
}

void LedController::runInstruction(const Instruction& instruction)
{
    switch (instruction.type)
    {
    case InstructionType::OutA: out << ledState; break;
    case InstructionType::LdA:
        ledState = getLedStateFromInteger(instruction.value);
        break;
    }
}

std::string LedController::getLedStateFromInteger(unsigned value)
{
    const std::bitset<8> bitValue{value};
    std::stringstream stream;
    stream << bitValue;
    auto text = stream.str();
    std::transform(text.cbegin(), text.cend(), text.begin(),
                   [](const auto character) {
                       if (character == '1')
                       {
                           constexpr auto ledOnChar = '*';
                           return ledOnChar;
                       }
                       else
                       {
                           constexpr auto ledOffChar = '.';
                           return ledOffChar;
                       }
                   });
    return text + '\n';
}
<commit_msg>Refactor changing number to led states<commit_after>#include "LedController.hpp"

#include <algorithm>
#include <bitset>

LedController::LedController(std::ostream& stream) : out{stream}
{
}

void LedController::runProgram(const Instructions& instructions)
{
    for (const auto& instruction : instructions)
    {
        runInstruction(instruction);
    }
}

void LedController::runInstruction(const Instruction& instruction)
{
    switch (instruction.type)
    {
    case InstructionType::OutA: out << ledState; break;
    case InstructionType::LdA:
        ledState = getLedStateFromInteger(instruction.value);
        break;
    }
}

std::string LedController::getLedStateFromInteger(unsigned value)
{
    const std::bitset<8> bitValue{value};
    constexpr auto ledOnChar = '*';
    constexpr auto ledOffChar = '.';
    constexpr auto lineEnding = '\n';
    return bitValue.to_string(ledOffChar, ledOnChar) + lineEnding;
}
<|endoftext|>


<commit_before>//===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the generation and use of USRs from CXEntities.
//
//===----------------------------------------------------------------------===//

#include "CIndexer.h"
#include "CXCursor.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Lex/PreprocessingRecord.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace clang::cxstring;

//===----------------------------------------------------------------------===//
// USR generation.
//===----------------------------------------------------------------------===//

namespace {
class USRGenerator : public DeclVisitor<USRGenerator> {
  llvm::raw_ostream &Out;
  bool IgnoreResults;
public:
  USRGenerator(llvm::raw_ostream &out) : Out(out), IgnoreResults(false) {}

  bool ignoreResults() const { return IgnoreResults; }

  // Visitation methods from generating USRs from AST elements.
  void VisitBlockDecl(BlockDecl *D);
  void VisitDeclContext(DeclContext *D);
  void VisitFieldDecl(FieldDecl *D);
  void VisitFunctionDecl(FunctionDecl *D);
  void VisitNamedDecl(NamedDecl *D);
  void VisitNamespaceDecl(NamespaceDecl *D);
  void VisitObjCContainerDecl(ObjCContainerDecl *CD);
  void VisitObjCMethodDecl(ObjCMethodDecl *MD);
  void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
  void VisitTagDecl(TagDecl *D);
  void VisitTypedefDecl(TypedefDecl *D);

  /// String generation methods used both by the visitation methods
  /// and from other clients that want to directly generate USRs.  These
  /// methods do not construct complete USRs (which incorporate the parents
  /// of an AST element), but only the fragments concerning the AST element
  /// itself.

  /// Generate a USR fragment for a named declaration.  This does
  /// not include the USR component for the parent.
  void GenNamedDecl(llvm::StringRef name);

  /// Generate a USR for an Objective-C class.
  void GenObjCClass(llvm::StringRef cls);
  /// Generate a USR for an Objective-C class category.
  void GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat);
  /// Generate a USR fragment for an Objective-C instance variable.  The
  /// complete USR can be created by concatenating the USR for the
  /// encompassing class with this USR fragment.
  void GenObjCIvar(llvm::StringRef ivar);
  /// Generate a USR fragment for an Objective-C method.
  void GenObjCMethod(llvm::StringRef sel, bool isInstanceMethod);
  /// Generate a USR fragment for an Objective-C property.
  void GenObjCProperty(llvm::StringRef prop);
  /// Generate a USR for an Objective-C protocol.
  void GenObjCProtocol(llvm::StringRef prot);
};

class StringUSRGenerator {
private:
  llvm::SmallString<1024> StrBuf;
  llvm::raw_svector_ostream Out;
  USRGenerator UG;
public:
  StringUSRGenerator()
    : Out(StrBuf), UG(Out) {
    // Add the USR space prefix.
    Out << "c:";
  }

  llvm::StringRef str() {
    return Out.str();
  }

  USRGenerator* operator->() { return &UG; }

  template <typename T>
  llvm::raw_svector_ostream &operator<<(const T &x) {
    Out << x;
    return Out;
  }
};

} // end anonymous namespace

//===----------------------------------------------------------------------===//
// Generating USRs from ASTS.
//===----------------------------------------------------------------------===//

void USRGenerator::VisitBlockDecl(BlockDecl *D) {
  VisitDeclContext(D->getDeclContext());
  // FIXME: Better support for anonymous blocks.
  Out << "@B^anon";
}

void USRGenerator::VisitDeclContext(DeclContext *DC) {
  if (NamedDecl *D = dyn_cast<NamedDecl>(DC))
    Visit(D);
}

void USRGenerator::VisitFieldDecl(FieldDecl *D) {
  const std::string &s = D->getNameAsString();
  if (s.empty()) {
    // Bit fields can be anonymous.
    IgnoreResults = true;
    return;
  }
  VisitDeclContext(D->getDeclContext());
  Out << "@^FI^" << s;
}

void USRGenerator::VisitFunctionDecl(FunctionDecl *D) {
  VisitDeclContext(D->getDeclContext());
  Out << "@F^" << D->getNameAsString();
}

void USRGenerator::VisitNamedDecl(NamedDecl *D) {
  VisitDeclContext(D->getDeclContext());
  const std::string &s = D->getNameAsString();
  //  assert(!s.empty());
  GenNamedDecl(s);
}

void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) {
  VisitDeclContext(D->getDeclContext());
  Out << "@N^" << D->getNameAsString();
}

void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) {
  Visit(cast<Decl>(D->getDeclContext()));
  GenObjCMethod(DeclarationName(D->getSelector()).getAsString(),
                D->isInstanceMethod());
}

void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) {
  switch (D->getKind()) {
    default:
      assert(false && "Invalid ObjC container.");
    case Decl::ObjCInterface:
    case Decl::ObjCImplementation:
      GenObjCClass(D->getName());
      break;
    case Decl::ObjCCategory: {
      ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
      ObjCInterfaceDecl *ID = CD->getClassInterface();
      if (!ID) {
        // Handle invalid code where the @interface might not
        // have been specified.
        // FIXME: We should be able to generate this USR even if the
        // @interface isn't available.
        IgnoreResults = true;
        return;
      }
      GenObjCCategory(ID->getName(), CD->getName());
      break;
    }
    case Decl::ObjCCategoryImpl: {
      ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
      ObjCInterfaceDecl *ID = CD->getClassInterface();
      if (!ID) {
        // Handle invalid code where the @interface might not
        // have been specified.
        // FIXME: We should be able to generate this USR even if the
        // @interface isn't available.
        IgnoreResults = true;
        return;
      }
      GenObjCCategory(ID->getName(), CD->getName());
      break;
    }
    case Decl::ObjCProtocol:
      GenObjCProtocol(cast<ObjCProtocolDecl>(D)->getName());
      break;
  }
}

void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
  Visit(cast<Decl>(D->getDeclContext()));
  GenObjCProperty(D->getName());
}

void USRGenerator::VisitTagDecl(TagDecl *D) {
  VisitDeclContext(D->getDeclContext());
  switch (D->getTagKind()) {
    case TagDecl::TK_struct: Out << "@S^"; break;
    case TagDecl::TK_class:  Out << "@C^"; break;
    case TagDecl::TK_union:  Out << "@U^"; break;
    case TagDecl::TK_enum:   Out << "@E^"; break;
  }

  // FIXME: Better support for anonymous structures and enums.
  const std::string &s = D->getNameAsString();
  if (s.empty()) {
    if (TypedefDecl *TD = D->getTypedefForAnonDecl())
      Out << "^anontd^" << TD->getNameAsString();
    else
      Out << "^anon";
  }
  else
    Out << s;
}

void USRGenerator::VisitTypedefDecl(TypedefDecl *D) {
  DeclContext *DC = D->getDeclContext();
  if (NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
    Visit(DCN);
  Out << "typedef@" << D->getName();
}

//===----------------------------------------------------------------------===//
// General purpose USR generation methods.
//===----------------------------------------------------------------------===//

void USRGenerator::GenNamedDecl(llvm::StringRef name) {
  Out << "@^" << name;
}

void USRGenerator::GenObjCClass(llvm::StringRef cls) {
  Out << "objc(cs)" << cls;
}

void USRGenerator::GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat) {
  Out << "objc(cy)" << cls << '^' << cat;
}

void USRGenerator::GenObjCIvar(llvm::StringRef ivar) {
  GenNamedDecl(ivar);
}

void USRGenerator::GenObjCMethod(llvm::StringRef meth, bool isInstanceMethod) {
  Out << (isInstanceMethod ? "(im)" : "(cm)") << meth;
}

void USRGenerator::GenObjCProperty(llvm::StringRef prop) {
  Out << "(py)" << prop;
}

void USRGenerator::GenObjCProtocol(llvm::StringRef prot) {
  Out << "objc(pl)" << prot;
}

//===----------------------------------------------------------------------===//
// API hooks.
//===----------------------------------------------------------------------===//

static inline llvm::StringRef extractUSRSuffix(llvm::StringRef s) {
  return s.startswith("c:") ? s.substr(2) : "";
}

static CXString getDeclCursorUSR(const CXCursor &C) {
  Decl *D = cxcursor::getCursorDecl(C);
  if (!D)
    return createCXString(NULL);

  StringUSRGenerator SUG;
  SUG->Visit(D);

  if (SUG->ignoreResults())
    return createCXString("");

    // Return a copy of the string that must be disposed by the caller.
  return createCXString(SUG.str(), true);
}

extern "C" {

CXString clang_getCursorUSR(CXCursor C) {
  const CXCursorKind &K = clang_getCursorKind(C);

  if (clang_isDeclaration(K))
      return getDeclCursorUSR(C);

  if (K == CXCursor_MacroDefinition) {
    StringUSRGenerator SUG;
    SUG << "macro@"
        << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart();
    return createCXString(SUG.str(), true);
  }

  return createCXString("");
}

CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) {
  StringUSRGenerator SUG;
  SUG << extractUSRSuffix(clang_getCString(classUSR));
  SUG->GenObjCIvar(name);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCMethod(const char *name,
                                       unsigned isInstanceMethod,
                                       CXString classUSR) {
  StringUSRGenerator SUG;
  SUG << extractUSRSuffix(clang_getCString(classUSR));
  SUG->GenObjCMethod(name, isInstanceMethod);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCClass(const char *name) {
  StringUSRGenerator SUG;
  SUG->GenObjCClass(name);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCProtocol(const char *name) {
  StringUSRGenerator SUG;
  SUG->GenObjCProtocol(name);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCCategory(const char *class_name,
                                         const char *category_name) {
  StringUSRGenerator SUG;
  SUG->GenObjCCategory(class_name, category_name);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCProperty(const char *property,
                                         CXString classUSR) {
  StringUSRGenerator SUG;
  SUG << extractUSRSuffix(clang_getCString(classUSR));
  SUG->GenObjCProperty(property);
  return createCXString(SUG.str(), true);
}

} // end extern "C"
<commit_msg>Do not generate USRs for declarations with 'no linkage' except for enums, structs, typedefs. Those still need work to disambiguate them across translation units.<commit_after>//===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the generation and use of USRs from CXEntities.
//
//===----------------------------------------------------------------------===//

#include "CIndexer.h"
#include "CXCursor.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Lex/PreprocessingRecord.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace clang::cxstring;

//===----------------------------------------------------------------------===//
// USR generation.
//===----------------------------------------------------------------------===//

namespace {
class USRGenerator : public DeclVisitor<USRGenerator> {
  llvm::raw_ostream &Out;
  bool IgnoreResults;
  ASTUnit *AU;
public:
  USRGenerator(ASTUnit *au, llvm::raw_ostream &out)
    : Out(out), IgnoreResults(false), AU(au) {}

  bool ignoreResults() const { return IgnoreResults; }

  // Visitation methods from generating USRs from AST elements.
  void VisitBlockDecl(BlockDecl *D);
  void VisitDeclContext(DeclContext *D);
  void VisitFieldDecl(FieldDecl *D);
  void VisitFunctionDecl(FunctionDecl *D);
  void VisitNamedDecl(NamedDecl *D);
  void VisitNamespaceDecl(NamespaceDecl *D);
  void VisitObjCContainerDecl(ObjCContainerDecl *CD);
  void VisitObjCMethodDecl(ObjCMethodDecl *MD);
  void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
  void VisitTagDecl(TagDecl *D);
  void VisitTypedefDecl(TypedefDecl *D);

  /// String generation methods used both by the visitation methods
  /// and from other clients that want to directly generate USRs.  These
  /// methods do not construct complete USRs (which incorporate the parents
  /// of an AST element), but only the fragments concerning the AST element
  /// itself.

  /// Generate a USR fragment for a named declaration.  This does
  /// not include the USR component for the parent.
  void GenNamedDecl(llvm::StringRef name);

  /// Generate a USR for an Objective-C class.
  void GenObjCClass(llvm::StringRef cls);
  /// Generate a USR for an Objective-C class category.
  void GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat);
  /// Generate a USR fragment for an Objective-C instance variable.  The
  /// complete USR can be created by concatenating the USR for the
  /// encompassing class with this USR fragment.
  void GenObjCIvar(llvm::StringRef ivar);
  /// Generate a USR fragment for an Objective-C method.
  void GenObjCMethod(llvm::StringRef sel, bool isInstanceMethod);
  /// Generate a USR fragment for an Objective-C property.
  void GenObjCProperty(llvm::StringRef prop);
  /// Generate a USR for an Objective-C protocol.
  void GenObjCProtocol(llvm::StringRef prot);
};

class StringUSRGenerator {
private:
  llvm::SmallString<1024> StrBuf;
  llvm::raw_svector_ostream Out;
  USRGenerator UG;
public:
  StringUSRGenerator(const CXCursor *C = 0)
    : Out(StrBuf), UG(C ? cxcursor::getCursorASTUnit(*C) : 0, Out) {
    // Add the USR space prefix.
    Out << "c:";
  }

  llvm::StringRef str() {
    return Out.str();
  }

  USRGenerator* operator->() { return &UG; }

  template <typename T>
  llvm::raw_svector_ostream &operator<<(const T &x) {
    Out << x;
    return Out;
  }
};

} // end anonymous namespace

//===----------------------------------------------------------------------===//
// Generating USRs from ASTS.
//===----------------------------------------------------------------------===//

void USRGenerator::VisitBlockDecl(BlockDecl *D) {
  VisitDeclContext(D->getDeclContext());
  // FIXME: Better support for anonymous blocks.
  Out << "@B^anon";
}

void USRGenerator::VisitDeclContext(DeclContext *DC) {
  if (NamedDecl *D = dyn_cast<NamedDecl>(DC))
    Visit(D);
}

void USRGenerator::VisitFieldDecl(FieldDecl *D) {
  const std::string &s = D->getNameAsString();
  if (s.empty()) {
    // Bit fields can be anonymous.
    IgnoreResults = true;
    return;
  }
  VisitDeclContext(D->getDeclContext());
  Out << "@^FI^" << s;
}

void USRGenerator::VisitFunctionDecl(FunctionDecl *D) {
  VisitDeclContext(D->getDeclContext());
  Out << "@F^" << D->getNameAsString();
}

void USRGenerator::VisitNamedDecl(NamedDecl *D) {
  VisitDeclContext(D->getDeclContext());
  const std::string &s = D->getNameAsString();
  //  assert(!s.empty());
  GenNamedDecl(s);
}

void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) {
  VisitDeclContext(D->getDeclContext());
  Out << "@N^" << D->getNameAsString();
}

void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) {
  Visit(cast<Decl>(D->getDeclContext()));
  GenObjCMethod(DeclarationName(D->getSelector()).getAsString(),
                D->isInstanceMethod());
}

void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) {
  switch (D->getKind()) {
    default:
      assert(false && "Invalid ObjC container.");
    case Decl::ObjCInterface:
    case Decl::ObjCImplementation:
      GenObjCClass(D->getName());
      break;
    case Decl::ObjCCategory: {
      ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
      ObjCInterfaceDecl *ID = CD->getClassInterface();
      if (!ID) {
        // Handle invalid code where the @interface might not
        // have been specified.
        // FIXME: We should be able to generate this USR even if the
        // @interface isn't available.
        IgnoreResults = true;
        return;
      }
      GenObjCCategory(ID->getName(), CD->getName());
      break;
    }
    case Decl::ObjCCategoryImpl: {
      ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
      ObjCInterfaceDecl *ID = CD->getClassInterface();
      if (!ID) {
        // Handle invalid code where the @interface might not
        // have been specified.
        // FIXME: We should be able to generate this USR even if the
        // @interface isn't available.
        IgnoreResults = true;
        return;
      }
      GenObjCCategory(ID->getName(), CD->getName());
      break;
    }
    case Decl::ObjCProtocol:
      GenObjCProtocol(cast<ObjCProtocolDecl>(D)->getName());
      break;
  }
}

void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
  Visit(cast<Decl>(D->getDeclContext()));
  GenObjCProperty(D->getName());
}

void USRGenerator::VisitTagDecl(TagDecl *D) {
  VisitDeclContext(D->getDeclContext());
  switch (D->getTagKind()) {
    case TagDecl::TK_struct: Out << "@S^"; break;
    case TagDecl::TK_class:  Out << "@C^"; break;
    case TagDecl::TK_union:  Out << "@U^"; break;
    case TagDecl::TK_enum:   Out << "@E^"; break;
  }

  // FIXME: Better support for anonymous structures and enums.
  const std::string &s = D->getNameAsString();
  if (s.empty()) {
    if (TypedefDecl *TD = D->getTypedefForAnonDecl())
      Out << "^anontd^" << TD->getNameAsString();
    else
      Out << "^anon";
  }
  else
    Out << s;
}

void USRGenerator::VisitTypedefDecl(TypedefDecl *D) {
  DeclContext *DC = D->getDeclContext();
  if (NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
    Visit(DCN);
  Out << "typedef@" << D->getName();
}

//===----------------------------------------------------------------------===//
// General purpose USR generation methods.
//===----------------------------------------------------------------------===//

void USRGenerator::GenNamedDecl(llvm::StringRef name) {
  Out << "@^" << name;
}

void USRGenerator::GenObjCClass(llvm::StringRef cls) {
  Out << "objc(cs)" << cls;
}

void USRGenerator::GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat) {
  Out << "objc(cy)" << cls << '^' << cat;
}

void USRGenerator::GenObjCIvar(llvm::StringRef ivar) {
  GenNamedDecl(ivar);
}

void USRGenerator::GenObjCMethod(llvm::StringRef meth, bool isInstanceMethod) {
  Out << (isInstanceMethod ? "(im)" : "(cm)") << meth;
}

void USRGenerator::GenObjCProperty(llvm::StringRef prop) {
  Out << "(py)" << prop;
}

void USRGenerator::GenObjCProtocol(llvm::StringRef prot) {
  Out << "objc(pl)" << prot;
}

//===----------------------------------------------------------------------===//
// API hooks.
//===----------------------------------------------------------------------===//

static inline llvm::StringRef extractUSRSuffix(llvm::StringRef s) {
  return s.startswith("c:") ? s.substr(2) : "";
}

static CXString getDeclCursorUSR(const CXCursor &C) {
  Decl *D = cxcursor::getCursorDecl(C);
  if (!D)
    return createCXString(NULL);

  // Check if the cursor has 'NoLinkage'.
  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
    switch (ND->getLinkage()) {
      case ExternalLinkage:
        // Generate USRs for all entities with external linkage.
        break;
      case NoLinkage:
        // We allow enums, typedefs, and structs that have no linkage to
        // have USRs that are anchored to the file they were defined in
        // (e.g., the header).  This is a little gross, but in principal
        // enums/anonymous structs/etc. defined in a common header file
        // are referred to across multiple translation units.
        if (isa<TagDecl>(ND))
          break;
        // Fall-through.
      case InternalLinkage:
      case UniqueExternalLinkage:
        return createCXString("");
    }

  StringUSRGenerator SUG(&C);
  SUG->Visit(D);

  if (SUG->ignoreResults())
    return createCXString("");

    // Return a copy of the string that must be disposed by the caller.
  return createCXString(SUG.str(), true);
}

extern "C" {

CXString clang_getCursorUSR(CXCursor C) {
  const CXCursorKind &K = clang_getCursorKind(C);

  if (clang_isDeclaration(K))
      return getDeclCursorUSR(C);

  if (K == CXCursor_MacroDefinition) {
    StringUSRGenerator SUG(&C);
    SUG << "macro@"
        << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart();
    return createCXString(SUG.str(), true);
  }

  return createCXString("");
}

CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) {
  StringUSRGenerator SUG;
  SUG << extractUSRSuffix(clang_getCString(classUSR));
  SUG->GenObjCIvar(name);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCMethod(const char *name,
                                       unsigned isInstanceMethod,
                                       CXString classUSR) {
  StringUSRGenerator SUG;
  SUG << extractUSRSuffix(clang_getCString(classUSR));
  SUG->GenObjCMethod(name, isInstanceMethod);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCClass(const char *name) {
  StringUSRGenerator SUG;
  SUG->GenObjCClass(name);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCProtocol(const char *name) {
  StringUSRGenerator SUG;
  SUG->GenObjCProtocol(name);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCCategory(const char *class_name,
                                         const char *category_name) {
  StringUSRGenerator SUG;
  SUG->GenObjCCategory(class_name, category_name);
  return createCXString(SUG.str(), true);
}

CXString clang_constructUSR_ObjCProperty(const char *property,
                                         CXString classUSR) {
  StringUSRGenerator SUG;
  SUG << extractUSRSuffix(clang_getCString(classUSR));
  SUG->GenObjCProperty(property);
  return createCXString(SUG.str(), true);
}

} // end extern "C"
<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_UTILS_POSIX_WRAPPER_MUTEX_HPP
#define IOX_UTILS_POSIX_WRAPPER_MUTEX_HPP

#include "iceoryx_utils/cxx/optional.hpp"
#include "iceoryx_utils/platform/pthread.hpp"

#if defined(__QNX__) || defined(__APPLE__)
#define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE
#define PTHREAD_MUTEX_FAST_NP PTHREAD_MUTEX_NORMAL
#endif

namespace iox
{
namespace posix
{
/// @brief Wrapper for a interprocess pthread based mutex which does not use
///         exceptions!
/// @code
///     #include "iceoryx_utils/internal/posix_wrapper/mutex.hpp"
///
///     int main() {
///         cxx::optional<posix::mutex> myMutex = posix::mutex::CreateMutex(false);
///
///         // always verify if the mutex could be created since we aren't
///         // throwing exceptions
///         if ( myMutex.has_value() ) {
///             myMutex->lock();
///             // ... do stuff
///             myMutex->unlock();
///         }
///
///         {
///             // we need to use the dereferencing operator since myMutex is
///             // a mutex wrapped in an optional
///             std::lock_guard<posix::mutex> lock(*myMutex);
///             // ...
///         }
///
///     }
class mutex
{
  public:
    /// @brief the construction of the mutex can fail which will lead to a call
    ///         to programm termination which is alright for the moment since we are
    ///         intending to get rid of the mutex sooner or later
    mutex(const bool f_isRecursive);

    ~mutex();

    /// @brief all copy and move assignment methods need to be deleted otherwise
    ///         undefined behavior or race conditions will occure if you copy
    ///         or move mutexe when its possible that they are locked or will
    ///         be locked
    mutex(const mutex&) = delete;
    mutex(mutex&&) = delete;
    mutex& operator=(const mutex&) = delete;
    mutex& operator=(mutex&&) = delete;

    /// @brief Locks the mutex object and returns true if the underlying c
    ///         function did not returned any error. If the mutex is already
    ///         locked the method is blocking till the mutex can be locked.
    bool lock();
    /// @brief Unlocks the mutex object and returns true if the underlying c
    ///         function did not returned any error.
    ///        IMPORTANT! Unlocking and unlocked mutex is undefined behavior
    ///         and the underlying c function will report success in this case!
    bool unlock();

    /// @brief  Tries to lock the mutex object. If it is not possible to lock
    ///         the mutex object try_lock will return an error. If the c
    ///         function fails it will return false, otherwise true.
    bool try_lock();

    /// @brief  Returns the native handle which then can be used in
    ///         pthread_mutex_** calls. Required when a pthread_mutex_**
    ///         call is not abstracted with this wrapper.
    pthread_mutex_t get_native_handle() const noexcept;

    pthread_mutex_t m_handle;
};
} // namespace posix
} // namespace iox

#endif // IOX_UTILS_POSIX_WRAPPER_MUTEX_HPP
<commit_msg>iox-#261 Rephrase doxygen about mutex<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_UTILS_POSIX_WRAPPER_MUTEX_HPP
#define IOX_UTILS_POSIX_WRAPPER_MUTEX_HPP

#include "iceoryx_utils/cxx/optional.hpp"
#include "iceoryx_utils/platform/pthread.hpp"

#if defined(__QNX__) || defined(__APPLE__)
#define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE
#define PTHREAD_MUTEX_FAST_NP PTHREAD_MUTEX_NORMAL
#endif

namespace iox
{
namespace posix
{
/// @brief Wrapper for a interprocess pthread based mutex which does not use
///         exceptions!
/// @code
///     #include "iceoryx_utils/internal/posix_wrapper/mutex.hpp"
///
///     int main() {
///         cxx::optional<posix::mutex> myMutex = posix::mutex::CreateMutex(false);
///
///         // always verify if the mutex could be created since we aren't
///         // throwing exceptions
///         if ( myMutex.has_value() ) {
///             myMutex->lock();
///             // ... do stuff
///             myMutex->unlock();
///         }
///
///         {
///             // we need to use the dereferencing operator since myMutex is
///             // a mutex wrapped in an optional
///             std::lock_guard<posix::mutex> lock(*myMutex);
///             // ...
///         }
///
///     }
class mutex
{
  public:
    /// @brief the construction of the mutex can fail. In this case the program will terminate. This is alright for the
    /// moment since we are intending to get rid of the mutex sooner or later
    mutex(const bool f_isRecursive);

    ~mutex();

    /// @brief all copy and move assignment methods need to be deleted otherwise
    ///         undefined behavior or race conditions will occure if you copy
    ///         or move mutexe when its possible that they are locked or will
    ///         be locked
    mutex(const mutex&) = delete;
    mutex(mutex&&) = delete;
    mutex& operator=(const mutex&) = delete;
    mutex& operator=(mutex&&) = delete;

    /// @brief Locks the mutex object and returns true if the underlying c
    ///         function did not returned any error. If the mutex is already
    ///         locked the method is blocking till the mutex can be locked.
    bool lock();
    /// @brief Unlocks the mutex object and returns true if the underlying c
    ///         function did not returned any error.
    ///        IMPORTANT! Unlocking and unlocked mutex is undefined behavior
    ///         and the underlying c function will report success in this case!
    bool unlock();

    /// @brief  Tries to lock the mutex object. If it is not possible to lock
    ///         the mutex object try_lock will return an error. If the c
    ///         function fails it will return false, otherwise true.
    bool try_lock();

    /// @brief  Returns the native handle which then can be used in
    ///         pthread_mutex_** calls. Required when a pthread_mutex_**
    ///         call is not abstracted with this wrapper.
    pthread_mutex_t get_native_handle() const noexcept;

    pthread_mutex_t m_handle;
};
} // namespace posix
} // namespace iox

#endif // IOX_UTILS_POSIX_WRAPPER_MUTEX_HPP
<|endoftext|>


<commit_before>#define BOOST_TEST_MAIN teste1
#if !defined( WIN32 )
    #define BOOST_TEST_DYN_LINK
#endif
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( la ) {
    BOOST_CHECK_EQUAL(1, 1);
}
BOOST_AUTO_TEST_CASE( la2 ) {
    BOOST_CHECK_EQUAL(1, 1);
}<commit_msg>Linux Compile Ajust<commit_after>#define BOOST_TEST_MAIN teste1
#if !defined( WIN32 )
    #define BOOST_TEST_DYN_LINK
#endif
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_CASE( la ) {
    BOOST_CHECK_EQUAL(1, 1);
}
BOOST_AUTO_TEST_CASE( la2 ) {
    BOOST_CHECK_EQUAL(1, 1);
}<|endoftext|>


<commit_before>//
//  Mach7: Pattern Matching Library for C++
//
//  Copyright 2011-2013, Texas A&M University.
//  Copyright 2014 Yuriy Solodkyy.
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//      * Redistributions of source code must retain the above copyright
//        notice, this list of conditions and the following disclaimer.
//
//      * Redistributions in binary form must reproduce the above copyright
//        notice, this list of conditions and the following disclaimer in the
//        documentation and/or other materials provided with the distribution.
//
//      * Neither the names of Mach7 project nor the names of its contributors
//        may be used to endorse or promote products derived from this software
//        without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY
//  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

///
/// \file
///
/// This file is a part of Mach7 library test suite.
///
/// \author Yuriy Solodkyy <yuriy.solodkyy@gmail.com>
///
/// \see https://parasol.tamu.edu/mach7/
/// \see https://github.com/solodon4/Mach7
/// \see https://github.com/solodon4/SELL
///

#include "testshape.hpp"
#include "testutils.hpp"
#include "match.hpp"

//------------------------------------------------------------------------------

#if !defined(NUMBER_OF_BASES)
  #define NUMBER_OF_BASES  5
#endif
#if NUMBER_OF_BASES > NUMBER_OF_DERIVED
  #error Visitor Forwarding only makes sense when number of base classes is smaller than the number of all derived classes.
#endif

//------------------------------------------------------------------------------

template <size_t N>
struct shape_kind;

#define FOR_EACH_MAX NUMBER_OF_BASES-1
#define FOR_EACH_N(N) template <> struct shape_kind<N> : OtherBase, Shape { typedef Shape base_type; shape_kind(size_t kind = N) : Shape(kind) { this->m_all_kinds = (const size_t*)mch::get_kinds<Shape>(mch::original2remapped<Shape>(mch::tag_type(kind))); } void accept(ShapeVisitor&) const; };
#include "loop_over_numbers.hpp"
#undef  FOR_EACH_N
#undef  FOR_EACH_MAX

//------------------------------------------------------------------------------

template <size_t N>
struct shape_kind : shape_kind<N % NUMBER_OF_BASES>
{
    typedef shape_kind<N % NUMBER_OF_BASES> base_type;
    shape_kind() : base_type(N) { this->m_all_kinds = (const size_t*)mch::get_kinds<Shape>(mch::original2remapped<Shape>(mch::tag_type(N))); }
    void accept(ShapeVisitor&) const;
};

//------------------------------------------------------------------------------

struct ShapeVisitor
{
    virtual void visit(const Shape&) {}
    #define FOR_EACH_MAX NUMBER_OF_DERIVED-1
    #define FOR_EACH_N(N) virtual void visit(const shape_kind<N>& s) { visit(static_cast<const shape_kind<N>::base_type&>(s)); }
    #include "loop_over_numbers.hpp"
    #undef  FOR_EACH_N
    #undef  FOR_EACH_MAX
};

//------------------------------------------------------------------------------

#define FOR_EACH_MAX NUMBER_OF_BASES-1
#define FOR_EACH_N(N) void shape_kind<N>::accept(ShapeVisitor& v) const { v.visit(*this); }
#include "loop_over_numbers.hpp"
#undef  FOR_EACH_N
#undef  FOR_EACH_MAX

//------------------------------------------------------------------------------

template <size_t N> void shape_kind<N>::accept(ShapeVisitor& v) const { v.visit(*this); }

SKV(Shape,0); // Declare the smallest kind value for Shape hierarchy

namespace mch ///< Mach7 library namespace
{
template <>         struct bindings<Shape>         { KS(Shape::m_kind); KV(Shape,NUMBER_OF_DERIVED+1); };

// NOTE: We need to explicitly instantiate all bindings as otherwise our kinds
//       associations don't get instantiated and recorded. This happens because
//       now that bindings with specific N > base cases is never instantiated
// FIX:  Wonder though why it didn't instantiate them for base cases at least since
//       we instantiate them explicitly in Case statements
#define FOR_EACH_MAX NUMBER_OF_BASES-1
#define FOR_EACH_N(N) template <> struct bindings<shape_kind<N>> { KV(Shape,N);  BCS(shape_kind<N>,Shape); CM(0,shape_kind<N>::m_member0); CM(1,shape_kind<N>::m_member1); };
#include "loop_over_numbers.hpp"
#undef  FOR_EACH_N
#undef  FOR_EACH_MAX

// NOTE: We need to explicitly instantiate all bindings as otherwise our kinds
//       associations don't get instantiated and recorded. This happens because
//       now that bindings with specific N > base cases is never instantiated
#define FOR_EACH_MAX NUMBER_OF_DERIVED-NUMBER_OF_BASES-1
#define FOR_EACH_N(N) template <> struct bindings<shape_kind<NUMBER_OF_BASES+N>> { KV(Shape,NUMBER_OF_BASES+N);  BCS(shape_kind<NUMBER_OF_BASES+N>,shape_kind<NUMBER_OF_BASES+N>::base_type,Shape); CM(0,shape_kind<NUMBER_OF_BASES+N>::m_member0); CM(1,shape_kind<NUMBER_OF_BASES+N>::m_member1); };
#include "loop_over_numbers.hpp"
#undef  FOR_EACH_N
#undef  FOR_EACH_MAX

} // of namespace mch

//------------------------------------------------------------------------------

#if 1
XTL_TIMED_FUNC_BEGIN
size_t do_match(const Shape& s, size_t)
{
    MatchF(s)
    {
        #define FOR_EACH_MAX  NUMBER_OF_BASES-1
        #define FOR_EACH_N(N) CaseF(shape_kind<N>) return N;
        #include "loop_over_numbers.hpp"
        #undef  FOR_EACH_N
        #undef  FOR_EACH_MAX
    }
    EndMatchF
    return invalid;
}
XTL_TIMED_FUNC_END
#else
#error No preprocessed version provided
#endif

//------------------------------------------------------------------------------

XTL_TIMED_FUNC_BEGIN
size_t do_visit(const Shape& s, size_t)
{
    struct Visitor : ShapeVisitor
    {
        #define FOR_EACH_MAX  NUMBER_OF_BASES-1
        #define FOR_EACH_N(N) virtual void visit(const shape_kind<N>&) { result = N; }
        #include "loop_over_numbers.hpp"
        #undef  FOR_EACH_N
        #undef  FOR_EACH_MAX
        size_t result;
    };

    Visitor v;
    v.result = invalid;
    s.accept(v);
    return v.result;
}
XTL_TIMED_FUNC_END

//------------------------------------------------------------------------------

Shape* make_shape(size_t i)
{
    switch (i % NUMBER_OF_DERIVED)
    {
        #define FOR_EACH_MAX  NUMBER_OF_DERIVED-1
        #define FOR_EACH_N(N) case N: return new shape_kind<N>;
        #include "loop_over_numbers.hpp"
        #undef  FOR_EACH_N
        #undef  FOR_EACH_MAX
    }
    return 0;
}

//------------------------------------------------------------------------------

#include "testvismat1.hpp"    // Utilities for timing tests

//------------------------------------------------------------------------------

int main()
{
    using namespace mch; // Mach7's library namespace

    verdict pp = test_repetitive();
    verdict ps = test_sequential();
    verdict pr = test_randomized();
    std::cout << "OVERALL: "
              << "Repetitive: " << pp << "; "
              << "Sequential: " << ps << "; "
              << "Random: "     << pr
              << std::endl;
}

//------------------------------------------------------------------------------
<commit_msg>CM to Members<commit_after>//
//  Mach7: Pattern Matching Library for C++
//
//  Copyright 2011-2013, Texas A&M University.
//  Copyright 2014 Yuriy Solodkyy.
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//      * Redistributions of source code must retain the above copyright
//        notice, this list of conditions and the following disclaimer.
//
//      * Redistributions in binary form must reproduce the above copyright
//        notice, this list of conditions and the following disclaimer in the
//        documentation and/or other materials provided with the distribution.
//
//      * Neither the names of Mach7 project nor the names of its contributors
//        may be used to endorse or promote products derived from this software
//        without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY
//  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

///
/// \file
///
/// This file is a part of Mach7 library test suite.
///
/// \author Yuriy Solodkyy <yuriy.solodkyy@gmail.com>
///
/// \see https://parasol.tamu.edu/mach7/
/// \see https://github.com/solodon4/Mach7
/// \see https://github.com/solodon4/SELL
///

#include "testshape.hpp"
#include "testutils.hpp"
#include "match.hpp"

//------------------------------------------------------------------------------

#if !defined(NUMBER_OF_BASES)
  #define NUMBER_OF_BASES  5
#endif
#if NUMBER_OF_BASES > NUMBER_OF_DERIVED
  #error Visitor Forwarding only makes sense when number of base classes is smaller than the number of all derived classes.
#endif

//------------------------------------------------------------------------------

template <size_t N>
struct shape_kind;

#define FOR_EACH_MAX NUMBER_OF_BASES-1
#define FOR_EACH_N(N) template <> struct shape_kind<N> : OtherBase, Shape { typedef Shape base_type; shape_kind(size_t kind = N) : Shape(kind) { this->m_all_kinds = (const size_t*)mch::get_kinds<Shape>(mch::original2remapped<Shape>(mch::tag_type(kind))); } void accept(ShapeVisitor&) const; };
#include "loop_over_numbers.hpp"
#undef  FOR_EACH_N
#undef  FOR_EACH_MAX

//------------------------------------------------------------------------------

template <size_t N>
struct shape_kind : shape_kind<N % NUMBER_OF_BASES>
{
    typedef shape_kind<N % NUMBER_OF_BASES> base_type;
    shape_kind() : base_type(N) { this->m_all_kinds = (const size_t*)mch::get_kinds<Shape>(mch::original2remapped<Shape>(mch::tag_type(N))); }
    void accept(ShapeVisitor&) const;
};

//------------------------------------------------------------------------------

struct ShapeVisitor
{
    virtual void visit(const Shape&) {}
    #define FOR_EACH_MAX NUMBER_OF_DERIVED-1
    #define FOR_EACH_N(N) virtual void visit(const shape_kind<N>& s) { visit(static_cast<const shape_kind<N>::base_type&>(s)); }
    #include "loop_over_numbers.hpp"
    #undef  FOR_EACH_N
    #undef  FOR_EACH_MAX
};

//------------------------------------------------------------------------------

#define FOR_EACH_MAX NUMBER_OF_BASES-1
#define FOR_EACH_N(N) void shape_kind<N>::accept(ShapeVisitor& v) const { v.visit(*this); }
#include "loop_over_numbers.hpp"
#undef  FOR_EACH_N
#undef  FOR_EACH_MAX

//------------------------------------------------------------------------------

template <size_t N> void shape_kind<N>::accept(ShapeVisitor& v) const { v.visit(*this); }

SKV(Shape,0); // Declare the smallest kind value for Shape hierarchy

namespace mch ///< Mach7 library namespace
{
template <>         struct bindings<Shape>         { KS(Shape::m_kind); KV(Shape,NUMBER_OF_DERIVED+1); };

// NOTE: We need to explicitly instantiate all bindings as otherwise our kinds
//       associations don't get instantiated and recorded. This happens because
//       now that bindings with specific N > base cases is never instantiated
// FIX:  Wonder though why it didn't instantiate them for base cases at least since
//       we instantiate them explicitly in Case statements
#define FOR_EACH_MAX NUMBER_OF_BASES-1
#define FOR_EACH_N(N) template <> struct bindings<shape_kind<N>> { KV(Shape,N);  BCS(shape_kind<N>,Shape); Members(shape_kind<N>::m_member0,shape_kind<N>::m_member1); };
#include "loop_over_numbers.hpp"
#undef  FOR_EACH_N
#undef  FOR_EACH_MAX

// NOTE: We need to explicitly instantiate all bindings as otherwise our kinds
//       associations don't get instantiated and recorded. This happens because
//       now that bindings with specific N > base cases is never instantiated
#define FOR_EACH_MAX NUMBER_OF_DERIVED-NUMBER_OF_BASES-1
#define FOR_EACH_N(N) template <> struct bindings<shape_kind<NUMBER_OF_BASES+N>> { KV(Shape,NUMBER_OF_BASES+N);  BCS(shape_kind<NUMBER_OF_BASES+N>,shape_kind<NUMBER_OF_BASES+N>::base_type,Shape); Members(shape_kind<NUMBER_OF_BASES+N>::m_member0,shape_kind<NUMBER_OF_BASES+N>::m_member1); };
#include "loop_over_numbers.hpp"
#undef  FOR_EACH_N
#undef  FOR_EACH_MAX

} // of namespace mch

//------------------------------------------------------------------------------

#if 1
XTL_TIMED_FUNC_BEGIN
size_t do_match(const Shape& s, size_t)
{
    MatchF(s)
    {
        #define FOR_EACH_MAX  NUMBER_OF_BASES-1
        #define FOR_EACH_N(N) CaseF(shape_kind<N>) return N;
        #include "loop_over_numbers.hpp"
        #undef  FOR_EACH_N
        #undef  FOR_EACH_MAX
    }
    EndMatchF
    return invalid;
}
XTL_TIMED_FUNC_END
#else
#error No preprocessed version provided
#endif

//------------------------------------------------------------------------------

XTL_TIMED_FUNC_BEGIN
size_t do_visit(const Shape& s, size_t)
{
    struct Visitor : ShapeVisitor
    {
        #define FOR_EACH_MAX  NUMBER_OF_BASES-1
        #define FOR_EACH_N(N) virtual void visit(const shape_kind<N>&) { result = N; }
        #include "loop_over_numbers.hpp"
        #undef  FOR_EACH_N
        #undef  FOR_EACH_MAX
        size_t result;
    };

    Visitor v;
    v.result = invalid;
    s.accept(v);
    return v.result;
}
XTL_TIMED_FUNC_END

//------------------------------------------------------------------------------

Shape* make_shape(size_t i)
{
    switch (i % NUMBER_OF_DERIVED)
    {
        #define FOR_EACH_MAX  NUMBER_OF_DERIVED-1
        #define FOR_EACH_N(N) case N: return new shape_kind<N>;
        #include "loop_over_numbers.hpp"
        #undef  FOR_EACH_N
        #undef  FOR_EACH_MAX
    }
    return 0;
}

//------------------------------------------------------------------------------

#include "testvismat1.hpp"    // Utilities for timing tests

//------------------------------------------------------------------------------

int main()
{
    using namespace mch; // Mach7's library namespace

    verdict pp = test_repetitive();
    verdict ps = test_sequential();
    verdict pr = test_randomized();
    std::cout << "OVERALL: "
              << "Repetitive: " << pp << "; "
              << "Sequential: " << ps << "; "
              << "Random: "     << pr
              << std::endl;
}

//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>// wandurr.cpp - game of wandering around doing stuff written in c++/ncurses
// copyright 2017 inhabited.systems
// This program is covered by the MIT License.
// See the file LICENSE included with this distrubution for terms.

// This game is really just a fun coding exercise for me, and I hope
// I write it in such a way that new c++ coders might be able to
// have fun playing around with a little game programming. :)

// These instructions work on Ubuntu, which is a flavor of Debian, which is a
// type of Linux.  In the following instructions, when it says to type something
// don't type the // characters at the beginning of the line.

// If you don't have an Ubuntu machine, you can either install Ubuntu on your
// computer at home by learning here:

//      https://www.ubuntu.com/download/desktop/install-ubuntu-desktop

// ...or you can create a virtual Ubuntu host at somewhere like digitalocean.com
// for a few dollars a month.  I may add instructions later for how to build on
// Windows and OS X machines, but I don't have that now. :-(

// To compile this program on Ubuntu, first install the tools you will need by
// typing the following command at the shell prompt (you need sudo access):

//      sudo apt-get install build-essential git libncurses5-dev libncursesw5-dev dhex

// If you don't have sudo access, google "get sudo access ubuntu".
// You don't *have* to install dhex, but it is a nice-to-have hex editor.

// Then run these commands at the linux shell prompt:

//      cd ~
//      mkdir code
//      cd code
//      git clone https://github.com/isc1/wandurr.git
//      cd wandurr
//      g++ -std=c++11 -Wall -g -o wandurr wandurr.cpp -lncurses

// Then run the game by typing this:

//      ./wandurr

// If you are learning to program, there is NOTHING that is more helpful to you than
// having a friend who is experienced with the language and tools you are trying to learn
// who can help you when you get stuck or have questions.  Failing that, you can go to
// places like IRC, reddit and other forums to ask questions.  But a friend who can
// help you in person is worth his or her weight in gold!  If you find such a friend, BE
// NICE AND POLITE TO THEM, AND LISTEN CAREFULLY TO WHAT THEY TELL YOU. :-)

#include <stdlib.h>
#include <ncurses.h>
#include <math.h>
#include <signal.h>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

static void finish(int sig);

void vec2dinitrandint(vector<vector<int>>& pvec, int rsize)
{
        for (unsigned int i = 0; i < pvec.size(); i++) {
                    for (unsigned int j = 0; j < pvec[i].size(); j++) {
                                    pvec[i][j] = rand()%rsize;
                                                // cout << "pvec[" << i << "][" << j << "] = " << pvec[i][j] << "\n";
                                            }
                        }
}

void print2dvec(vector<vector<int>> pvec, string title)
{
        // print out the 2d vector of int passed in as pvec
        cout << "\n" << title << "\n";
            for (unsigned int i = 0; i < pvec.size(); i++) {
                        for (unsigned int j = 0; j < pvec[i].size(); j++)
                                        cout << pvec[i][j] << " ";
                                cout << "\n";
                                    }
                cout << "\n";
}

static void finish(int sig)
{
    endwin();
    exit(0);
}

int main(void)
{
    int row = 0, col = 0;

    time_t timenow;
    timenow = time(NULL);
    srand(timenow);
    const int rows = 15, cols = 40;

    (void) signal(SIGINT, finish);
    (void) initscr();
    keypad(stdscr, TRUE);
    (void) nonl();
    (void) cbreak();
    (void) echo();

    vector<vector<int> > vec2d;
    vec2d.resize(rows);
    for (int i = 0; i < rows; ++i)
        vec2d[i].resize(cols);
    vec2dinitrandint(vec2d, 6);
    print2dvec(vec2d, "vec2d");

    if (has_colors())
    {
        //addstr("has_colors()\n");
        refresh();
        //getch();
        start_color();
        init_pair(1, COLOR_WHITE, COLOR_RED);
        init_pair(2, COLOR_WHITE, COLOR_GREEN);
        init_pair(3, COLOR_WHITE, COLOR_YELLOW);
        init_pair(4, COLOR_WHITE, COLOR_BLUE);
        init_pair(5, COLOR_WHITE, COLOR_RED);
        init_pair(6, COLOR_WHITE, COLOR_MAGENTA);
        init_pair(7, COLOR_WHITE, COLOR_CYAN);
    }

    initscr();

    addstr("Wandurr!  This is just a stub program that shows some colors, it is not the real game yet.  Press any key to begin:\n");
    curs_set(0);
    refresh();
    getch();

    nodelay(stdscr, TRUE);
    move(16,0);
    addstr("Press any key to quit.\n");
    while(ERR == getch()) {
        //printw("%d\r", value++);
        //napms(0.00001);

        for(row=0; row < rows; row++) {
            for(col=0; col < cols; col++) {
                move(row,col);
                //attrset(COLOR_PAIR(rand()%7+1));
                attrset(COLOR_PAIR(vec2d[row][col]+1));
                if (vec2d[row][col] > 0) vec2d[row][col]=vec2d[row][col]-1;
                addch(' ');
            }
        }

        napms(1000);
        refresh();
    }

    endwin();
    finish(0);
    return 0;
}
<commit_msg>changed comments<commit_after>// wandurr.cpp - game of wandering around doing stuff written in c++/ncurses
// copyright 2017 inhabited.systems
// This program is covered by the MIT License.
// See the file LICENSE included with this distrubution for terms.

// This game is really just a fun coding exercise for me, and I hope
// I write it in such a way that new c++ coders might be able to
// have fun playing around with a little game programming. :)

// These instructions work on Ubuntu, which is a flavor of Debian, which is a
// type of Linux.  In the following instructions, when it says to type something
// don't type the // characters at the beginning of the line.

// If you don't have an Ubuntu machine, you can either install Ubuntu on your
// computer at home by learning here:

//      https://www.ubuntu.com/download/desktop/install-ubuntu-desktop

// ...or you can create a virtual Ubuntu host at somewhere like digitalocean.com
// for a few dollars a month.  I may add instructions later for how to build on
// Windows and OS X machines, but I don't have that now. :-(

// To compile this program on Ubuntu, first install the tools you will need by
// typing the following command at the shell prompt (you need sudo access):

//      sudo apt-get install build-essential git libncurses5-dev libncursesw5-dev dhex

// If you don't have sudo access, google "get sudo access ubuntu".
// You don't *have* to install dhex, but it is a nice-to-have hex editor.

// Then run these commands at the linux shell prompt:

//      cd ~
//      mkdir code
//      cd code
//      git clone https://github.com/isc1/wandurr.git
//      cd wandurr
//      g++ -std=c++11 -Wall -g -o wandurr wandurr.cpp -lncurses

// Then run the game by typing this:

//      ./wandurr

// If you are learning to program, there is NOTHING that is more helpful to you than
// having a friend who is experienced with the language and tools you are trying to learn
// who can help you when you get stuck or have questions.  Failing that, you can go to
// places like stackechange, IRC, reddit and other forums to ask questions.  But a friend
// who can help you in person is worth his or her weight in gold!  If you find such a
// friend, BE NICE AND POLITE TO THEM, AND LISTEN CAREFULLY TO WHAT THEY TELL YOU. :-)

#include <stdlib.h>
#include <ncurses.h>
#include <math.h>
#include <signal.h>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

static void finish(int sig);

void vec2dinitrandint(vector<vector<int>>& pvec, int rsize)
{
        for (unsigned int i = 0; i < pvec.size(); i++) {
                    for (unsigned int j = 0; j < pvec[i].size(); j++) {
                                    pvec[i][j] = rand()%rsize;
                                                // cout << "pvec[" << i << "][" << j << "] = " << pvec[i][j] << "\n";
                                            }
                        }
}

void print2dvec(vector<vector<int>> pvec, string title)
{
        // print out the 2d vector of int passed in as pvec
        cout << "\n" << title << "\n";
            for (unsigned int i = 0; i < pvec.size(); i++) {
                        for (unsigned int j = 0; j < pvec[i].size(); j++)
                                        cout << pvec[i][j] << " ";
                                cout << "\n";
                                    }
                cout << "\n";
}

static void finish(int sig)
{
    endwin();
    exit(0);
}

int main(void)
{
    int row = 0, col = 0;

    time_t timenow;
    timenow = time(NULL);
    srand(timenow);
    const int rows = 15, cols = 40;

    (void) signal(SIGINT, finish);
    (void) initscr();
    keypad(stdscr, TRUE);
    (void) nonl();
    (void) cbreak();
    (void) echo();

    vector<vector<int> > vec2d;
    vec2d.resize(rows);
    for (int i = 0; i < rows; ++i)
        vec2d[i].resize(cols);
    vec2dinitrandint(vec2d, 6);
    print2dvec(vec2d, "vec2d");

    if (has_colors())
    {
        //addstr("has_colors()\n");
        refresh();
        //getch();
        start_color();
        init_pair(1, COLOR_WHITE, COLOR_RED);
        init_pair(2, COLOR_WHITE, COLOR_GREEN);
        init_pair(3, COLOR_WHITE, COLOR_YELLOW);
        init_pair(4, COLOR_WHITE, COLOR_BLUE);
        init_pair(5, COLOR_WHITE, COLOR_RED);
        init_pair(6, COLOR_WHITE, COLOR_MAGENTA);
        init_pair(7, COLOR_WHITE, COLOR_CYAN);
    }

    initscr();

    addstr("Wandurr!  This is just a stub program that shows some colors, it is not the real game yet.  Press any key to begin:\n");
    curs_set(0);
    refresh();
    getch();

    nodelay(stdscr, TRUE);
    move(16,0);
    addstr("Press any key to quit.\n");
    while(ERR == getch()) {
        //printw("%d\r", value++);
        //napms(0.00001);

        for(row=0; row < rows; row++) {
            for(col=0; col < cols; col++) {
                move(row,col);
                //attrset(COLOR_PAIR(rand()%7+1));
                attrset(COLOR_PAIR(vec2d[row][col]+1));
                if (vec2d[row][col] > 0) vec2d[row][col]=vec2d[row][col]-1;
                addch(' ');
            }
        }

        napms(1000);
        refresh();
    }

    endwin();
    finish(0);
    return 0;
}
<|endoftext|>


<commit_before>#include <string.h>

#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#include "pitches.h"

// Forward declarations.
void jeopardySetup();
void jeopardyLoop();
void clearScreen();
int fastestPlayer();

// Supported game modes.
enum {
  MODE_JEOPARDY,
  MODE_BRAINRING,  // not implemented
  MODE_HAMSA,  // not implemented
};

// All available buttons.
enum {
  BUTTON_PLAYER_1,
  BUTTON_PLAYER_2,
  BUTTON_PLAYER_3,
  BUTTON_PLAYER_4,

  BUTTON_CONTROL_1,
  BUTTON_CONTROL_2,
  BUTTON_CONTROL_3,

  BUTTON_COUNT = BUTTON_CONTROL_3 + 1,

  BUTTON_START = BUTTON_CONTROL_1,
  BUTTON_RESET = BUTTON_CONTROL_3,

  FIRST_PLAYER_BUTTON = BUTTON_PLAYER_1,
  LAST_PLAYER_BUTTON = BUTTON_PLAYER_4,
};

// Pin numbers for each button, indexed by the enum values above.
const int kButtonPins[] = {
  8, 6, 4, 2, // players
  15, 16, 17, // control
};

// Pin numbers for each player's LED, indexed by the buttons enum.
// E.g. kLedPins[BUTTON_PLAYER_1] is the first player's LED.
const int kLedPins[] = {9, 7, 5, 3};

const int kSpeakerPin = 11;

const int kScreenWidth = 16;

// Button debounce delay in milliseconds.
const unsigned long kDebounceMs = 100;

// GLOBAL STATE

// An I2C-connected 16x2 character LCD screen.
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7);

// Selected game mode.
int mode = MODE_JEOPARDY;

// Button state, true means pressed.
bool buttons[BUTTON_COUNT] = { false };
// Button state before the latest update.
bool buttonsBefore[BUTTON_COUNT] = { false };

// For each button, when it was last time pressed in milliseconds since device
// start.
unsigned long lastPressedMs[BUTTON_COUNT] = {0};

// Button labels are printed on the lower line of the screen.
const char* leftButtonLabel = "Start";
const char* rightButtonLabel = "Reset";

void setup() {
  // Analog input 0 is not connected, use noise from it for pseudo-random
  // generator seeding.
  randomSeed(analogRead(0));

  // Setup input and output pins.
  for (const int buttonPin : kButtonPins) {
    pinMode(buttonPin, INPUT_PULLUP);
  }
  for (const int ledPin : kLedPins) {
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, LOW);
  }
  pinMode(kSpeakerPin, OUTPUT);

  // Initialize the screen.
  lcd.begin(/*cols=*/16, /*rows=*/2);
  lcd.setBacklightPin(3, POSITIVE);
  lcd.setBacklight(HIGH);

  // Serial is for debugging.
  Serial.begin(9600);

  // TODO: Select mode.
  jeopardySetup();
}

void loop() {
  unsigned long now = millis();
  // Read all buttons and save their state in a global array.
  for (int i = 0; i < BUTTON_COUNT; ++i) {
    buttonsBefore[i] = buttons[i];
    // Ignore the button state changes if it was pressed less than kDebounceMs
    // milliseconds ago to account for contact bouncing.
    if (now - lastPressedMs[i] > kDebounceMs) {
      // The buttons pins are active LOW.
      buttons[i] = (digitalRead(kButtonPins[i]) == LOW);
    }
  }
  // TODO: Dispatch based on current mode.
  jeopardyLoop();
}

void jeopardySetup() {
  leftButtonLabel = "Start";
  rightButtonLabel = "Reset";
  clearScreen();
  lcd.print("Mode: Jeopardy");
}

void jeopardyLoop() {
  static bool gotWinner = false;
  static bool started = false;
  static unsigned long time = 0;

  if (buttons[BUTTON_RESET] && !buttonsBefore[BUTTON_RESET]) {
    gotWinner = false;
    started = false;
    jeopardySetup();
    for (int ledPin : kLedPins) {
      digitalWrite(ledPin, LOW);
      tone(kSpeakerPin, NOTE_D4, 100/*ms*/);
    }
    return;
  }

  if (gotWinner) {
    return;
  }

  if (buttons[BUTTON_START] && !buttonsBefore[BUTTON_START]) {
    clearScreen();
    started = true;
    time = millis();
  }

  if (started) {
    lcd.home();
    lcd.print((millis() - time) / 1000);
  }

  const int winner = fastestPlayer();
  if (winner != -1) {
    digitalWrite(kLedPins[winner], HIGH);
    tone(kSpeakerPin, NOTE_G4, 100/*ms*/);
    gotWinner = true;
    leftButtonLabel = "Continue";
    rightButtonLabel = "Reset";
    clearScreen();
    lcd.print("Player ");
    lcd.print(winner + 1);
  }
}

void clearScreen() {
  lcd.clear();
  lcd.setCursor(/*row=*/0, /*col=*/1);
  // Print button functions on the lower line of the screen.
  lcd.print(leftButtonLabel);
  const int spaces = kScreenWidth - strlen(leftButtonLabel) -
      strlen(rightButtonLabel);
  for (int i = 0; i < spaces; ++i) {
    lcd.print(' ');
  }
  lcd.print(rightButtonLabel);
  lcd.home();
}

// Returns index of the player who pressed their button first or -1 for nobody.
int fastestPlayer() {
  // First, count how many players have pressed a button.
  int buttonsPressed = 0;
  for (int i = FIRST_PLAYER_BUTTON; i <= LAST_PLAYER_BUTTON; ++i) {
    if (buttons[i] && !buttonsBefore[i]) {
      ++buttonsPressed;
    }
  }
  if (buttonsPressed == 0) {
    return -1;
  }
  int winnerIndex = random(buttonsPressed);
  int player = FIRST_PLAYER_BUTTON;
  for (int i = 0; i < winnerIndex + 1; ++i) {
    while (!buttons[player] || buttonsBefore[player]) {
      ++player;
    }
  }
  return player;
}
<commit_msg>fix a bug in fastestPlayer()<commit_after>#include <string.h>

#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#include "pitches.h"

// Forward declarations.
void jeopardySetup();
void jeopardyLoop();
void clearScreen();
int fastestPlayer();

// Supported game modes.
enum {
  MODE_JEOPARDY,
  MODE_BRAINRING,  // not implemented
  MODE_HAMSA,  // not implemented
};

// All available buttons.
enum {
  BUTTON_PLAYER_1,
  BUTTON_PLAYER_2,
  BUTTON_PLAYER_3,
  BUTTON_PLAYER_4,

  BUTTON_CONTROL_1,
  BUTTON_CONTROL_2,
  BUTTON_CONTROL_3,

  BUTTON_COUNT = BUTTON_CONTROL_3 + 1,

  BUTTON_START = BUTTON_CONTROL_1,
  BUTTON_RESET = BUTTON_CONTROL_3,

  FIRST_PLAYER_BUTTON = BUTTON_PLAYER_1,
  LAST_PLAYER_BUTTON = BUTTON_PLAYER_4,
};

// Pin numbers for each button, indexed by the enum values above.
const int kButtonPins[] = {
  8, 6, 4, 2, // players
  15, 16, 17, // control
};

// Pin numbers for each player's LED, indexed by the buttons enum.
// E.g. kLedPins[BUTTON_PLAYER_1] is the first player's LED.
const int kLedPins[] = {9, 7, 5, 3};

const int kSpeakerPin = 11;

const int kScreenWidth = 16;

// Button debounce delay in milliseconds.
const unsigned long kDebounceMs = 100;

// GLOBAL STATE

// An I2C-connected 16x2 character LCD screen.
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7);

// Selected game mode.
int mode = MODE_JEOPARDY;

// Button state, true means pressed.
bool buttons[BUTTON_COUNT] = { false };
// Button state before the latest update.
bool buttonsBefore[BUTTON_COUNT] = { false };

// For each button, when it was last time pressed in milliseconds since device
// start.
unsigned long lastPressedMs[BUTTON_COUNT] = {0};

// Button labels are printed on the lower line of the screen.
const char* leftButtonLabel = "Start";
const char* rightButtonLabel = "Reset";

void setup() {
  // Analog input 0 is not connected, use noise from it for pseudo-random
  // generator seeding.
  randomSeed(analogRead(0));

  // Setup input and output pins.
  for (const int buttonPin : kButtonPins) {
    pinMode(buttonPin, INPUT_PULLUP);
  }
  for (const int ledPin : kLedPins) {
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, LOW);
  }
  pinMode(kSpeakerPin, OUTPUT);

  // Initialize the screen.
  lcd.begin(/*cols=*/16, /*rows=*/2);
  lcd.setBacklightPin(3, POSITIVE);
  lcd.setBacklight(HIGH);

  // Serial is for debugging.
  Serial.begin(9600);

  // TODO: Select mode.
  jeopardySetup();
}

void loop() {
  unsigned long now = millis();
  // Read all buttons and save their state in a global array.
  for (int i = 0; i < BUTTON_COUNT; ++i) {
    buttonsBefore[i] = buttons[i];
    // Ignore the button state changes if it was pressed less than kDebounceMs
    // milliseconds ago to account for contact bouncing.
    if (now - lastPressedMs[i] > kDebounceMs) {
      // The buttons pins are active LOW.
      buttons[i] = (digitalRead(kButtonPins[i]) == LOW);
    }
  }
  // TODO: Dispatch based on current mode.
  jeopardyLoop();
}

void jeopardySetup() {
  leftButtonLabel = "Start";
  rightButtonLabel = "Reset";
  clearScreen();
  lcd.print("Mode: Jeopardy");
}

void jeopardyLoop() {
  static bool gotWinner = false;
  static bool started = false;
  static unsigned long time = 0;

  if (buttons[BUTTON_RESET] && !buttonsBefore[BUTTON_RESET]) {
    gotWinner = false;
    started = false;
    jeopardySetup();
    for (int ledPin : kLedPins) {
      digitalWrite(ledPin, LOW);
      tone(kSpeakerPin, NOTE_D4, 100/*ms*/);
    }
    return;
  }

  if (gotWinner) {
    return;
  }

  if (buttons[BUTTON_START] && !buttonsBefore[BUTTON_START]) {
    clearScreen();
    started = true;
    time = millis();
  }

  if (started) {
    lcd.home();
    lcd.print((millis() - time) / 1000);
  }

  const int winner = fastestPlayer();
  if (winner != -1) {
    digitalWrite(kLedPins[winner], HIGH);
    tone(kSpeakerPin, NOTE_G4, 100/*ms*/);
    gotWinner = true;
    leftButtonLabel = "Continue";
    rightButtonLabel = "Reset";
    clearScreen();
    lcd.print("Player ");
    lcd.print(winner + 1);
  }
}

void clearScreen() {
  lcd.clear();
  lcd.setCursor(/*row=*/0, /*col=*/1);
  // Print button functions on the lower line of the screen.
  lcd.print(leftButtonLabel);
  const int spaces = kScreenWidth - strlen(leftButtonLabel) -
      strlen(rightButtonLabel);
  for (int i = 0; i < spaces; ++i) {
    lcd.print(' ');
  }
  lcd.print(rightButtonLabel);
  lcd.home();
}

// Returns index of the player who pressed their button first or -1 for nobody.
int fastestPlayer() {
  // First, count how many players have pressed a button.
  int buttonsPressed = 0;
  for (int i = FIRST_PLAYER_BUTTON; i <= LAST_PLAYER_BUTTON; ++i) {
    if (buttons[i] && !buttonsBefore[i]) {
      ++buttonsPressed;
    }
  }
  if (buttonsPressed == 0) {
    return -1;
  }
  int winnerIndex = random(buttonsPressed);
  int winner = -1;
  for (int i = FIRST_PLAYER_BUTTON; i <= LAST_PLAYER_BUTTON; ++i) {
    if (buttons[i] && !buttonsBefore[i]) {
      if (winnerIndex == 0) {
        winner = i;
        break;
      }
      --winnerIndex;
    }
  }
  return winner;
}
<|endoftext|>


<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#ifdef INTEL_MKL

#include "tensorflow/core/common_runtime/threadpool_device.h"

#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/cpu_info.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/session_options.h"

namespace tensorflow {

#if defined(_OPENMP) && !defined(ENABLE_MKLDNN_THREADPOOL)
TEST(MKLThreadPoolDeviceTest, TestOmpDefaults) {
  SessionOptions options;
  unsetenv("OMP_NUM_THREADS");

  ThreadPoolDevice* tp = new ThreadPoolDevice(
      options, "/device:CPU:0", Bytes(256), DeviceLocality(), cpu_allocator());

  const int ht = port::NumHyperthreadsPerCore();
  EXPECT_EQ(omp_get_max_threads(), (port::NumSchedulableCPUs() + ht - 1) / ht);
}

TEST(MKLThreadPoolDeviceTest, TestOmpPreSets) {
  SessionOptions options;
  setenv("OMP_NUM_THREADS", "314", 1);

  ThreadPoolDevice* tp = new ThreadPoolDevice(
      options, "/device:CPU:0", Bytes(256), DeviceLocality(), cpu_allocator());

  EXPECT_EQ(omp_get_max_threads(), 314);
}
#endif  // defined(_OPENMP) && !defined(ENABLE_MKLDNN_THREADPOOL)

}  // namespace tensorflow

#endif  // INTEL_MKL
<commit_msg>Removing unit test that depended on pre seting of OMP threads<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#ifdef INTEL_MKL

#include "tensorflow/core/common_runtime/threadpool_device.h"

#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/cpu_info.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/session_options.h"

namespace tensorflow {

#if defined(_OPENMP) && !defined(ENABLE_MKLDNN_THREADPOOL)
TEST(MKLThreadPoolDeviceTest, TestOmpDefaults) {
  SessionOptions options;
  unsetenv("OMP_NUM_THREADS");

  ThreadPoolDevice* tp = new ThreadPoolDevice(
      options, "/device:CPU:0", Bytes(256), DeviceLocality(), cpu_allocator());

  const int ht = port::NumHyperthreadsPerCore();
  EXPECT_EQ(omp_get_max_threads(), (port::NumSchedulableCPUs() + ht - 1) / ht);
}

#endif  // defined(_OPENMP) && !defined(ENABLE_MKLDNN_THREADPOOL)

}  // namespace tensorflow

#endif  // INTEL_MKL
<|endoftext|>


<commit_before>// @(#) $Id$

/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file   AliHLTTPCAgent.cxx
    @author Matthias Richter
    @date
    @brief  Agent of the libAliHLTTPC library
*/

#include "AliHLTTPCAgent.h"
#include "AliHLTConfiguration.h"

/** global instance for agent registration */
AliHLTTPCAgent gAliHLTTPCAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCAgent)

AliHLTTPCAgent::AliHLTTPCAgent()
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTTPCAgent::~AliHLTTPCAgent()
{
  // see header file for class documentation
}

int AliHLTTPCAgent::CreateConfigurations(AliHLTConfigurationHandler* handler,
					  AliRunLoader* runloader) const
{
  // see header file for class documentation
  if (handler) {
    // digit publisher configuration
    TString arg("-slice 0 -partition 0");
    HLTDebug(arg.Data());
    handler->CreateConfiguration("digit-publisher"  , "TPCDigitPublisher", NULL , arg.Data());

    // the writer configuration
    handler->CreateConfiguration("sink1", "FileWriter"   , "digit-publisher" , NULL);
  }
  return 0;
}

const char* AliHLTTPCAgent::GetLocalRecConfigurations(AliRunLoader* runloader) const
{
  // see header file for class documentation
  return NULL;
  //return "sink1";
}

const char* AliHLTTPCAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return NULL;
}
<commit_msg>TPC default configuration<commit_after>// @(#) $Id$

/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file   AliHLTTPCAgent.cxx
    @author Matthias Richter
    @date
    @brief  Agent of the libAliHLTTPC library
*/

#include "AliHLTTPCAgent.h"
#include "AliHLTConfiguration.h"

/** global instance for agent registration */
AliHLTTPCAgent gAliHLTTPCAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTTPCAgent)

AliHLTTPCAgent::AliHLTTPCAgent()
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTTPCAgent::~AliHLTTPCAgent()
{
  // see header file for class documentation
}

int AliHLTTPCAgent::CreateConfigurations(AliHLTConfigurationHandler* handler,
					  AliRunLoader* runloader) const
{
  // see header file for class documentation
  if (handler) {
    int iMinSlice=0;
    int iMaxSlice=1;
    int iMinPart=0;
    int iMaxPart=1;
    TString fileWriterInput;
    TString esdWriterInput;
    for (int slice=iMinSlice; slice<=iMaxSlice; slice++) {
      TString trackerInput;
      for (int part=iMinPart; part<=iMaxPart; part++) {
	TString arg, publisher, cf;

	// digit publisher components
	arg.Form("-slice %d -partition %d", slice, part);
	publisher.Form("DP_%02d_%d", slice, part);
	handler->CreateConfiguration(publisher.Data(), "TPCDigitPublisher", NULL , arg.Data());

	// cluster finder components
	cf.Form("CF_%02d_%d", slice, part);
	handler->CreateConfiguration(cf.Data(), "TPCClusterFinderUnpacked", publisher.Data(), "pp-run timebins 446");
	if (trackerInput.Length()>0) trackerInput+=" ";
	trackerInput+=cf;
      }
      TString tracker;
      // tracker finder components
      tracker.Form("TR_%02d", slice);
      handler->CreateConfiguration(tracker.Data(), "TPCSliceTracker", trackerInput.Data(), "pp-run bfield 0.5");

      // input for the global file writer
      if (fileWriterInput.Length()>0) fileWriterInput+=" ";
      fileWriterInput+=trackerInput;

      // input for the esd writer
      if (esdWriterInput.Length()>0) esdWriterInput+=" ";
      esdWriterInput+=tracker;
    }

    // the writer configuration
    handler->CreateConfiguration("sink1", "FileWriter"   , fileWriterInput.Data(), "-specfmt -subdir=test_%d -blcknofmt=_0x%x -idfmt=_0x%08x");
    // the esd writer configuration
    handler->CreateConfiguration("esd-writer", "TPCEsdWriter"   , esdWriterInput.Data(), "-datafile AliESDs.root");
  }
  return 0;
}

const char* AliHLTTPCAgent::GetLocalRecConfigurations(AliRunLoader* runloader) const
{
  // see header file for class documentation
  return NULL;
  //return "sink1";
  //return "esd-writer";
}

const char* AliHLTTPCAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return NULL;
}
<|endoftext|>