<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include <cassert>
#include <fstream>
#include <iostream>
#include <strstream>

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

//These came from the debug test.
#include <cstdio>
#include <ctime>
#include <string>
#include <vector>

#include <util/PlatformUtils.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanFileOutputStream.hpp>
#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>

#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>

#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XMLFileReporter.hpp>
#include <FileUtility.hpp>

//This is here for the threads.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winbase.h>
#define THREADFUNCTIONRETURN DWORD WINAPI

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::cin;
	using std::endl;
	using std::ifstream;
	using std::ios_base;
	using std::ostrstream;
	using std::string;
#endif

// This is here for memory leak testing.
#if defined(_DEBUG)
#include <crtdbg.h>
#endif

const char* const excludeStylesheets[] =
{

	"attribset15.xml",
	"entref08.xml",
	"entref10.xml",
	"extend01.xml",
	0
};

const char* const xslStylesheets[] =
{
	"attribset15.xml",
	"entref08.xml",
	"entref10.xml",
	"extend01.xml",
	0

};

inline bool
checkForExclusion(XalanDOMString currentFile)
{

		for (int i=0; excludeStylesheets[i] != 0; i++)
			{	if (equals(currentFile, XalanDOMString(excludeStylesheets[i])))
				return true;
			}
		return false;
}

void
outputMessage(int iter)
{
		cout << "\n" << "Starting Iteration: " << iter << '\0';
}

void
getParams(int argc,
		  const char*	argv[])
{
	if (argc != 1)
	{
		cerr << "Usage: ThreadTest" << endl;
		exit(1);
	}
}

#if defined(XALAN_NO_NAMESPACES)
	typedef vector<XalanDOMString>		FileNameVectorType;
#else
	typedef std::vector<XalanDOMString>	FileNameVectorType;
#endif

int
main(
	 int			argc,
	 const char*	argv[])
{

#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	// Defined root for performance directory. Based on PD's machine.
	const XalanDOMString	confDir(XALAN_STATIC_UCODE_STRING("d:\\xslt\\xsl-test\\conf\\"));
	const XalanDOMString	outDir(XALAN_STATIC_UCODE_STRING("d:\\xslt\\xsl-test\\cplus-mem\\"));

	FileUtility f;
	FileNameVectorType dirs, files;

	// Get the list of Directories that are below perf
	dirs = f.getDirectoryNames(confDir);

	XMLFileReporter	logFile("cpp.xml");
	logFile.logTestFileInit("Memory Testing - Memory leaks detected during ConformanceTests. ");

	getParams(argc, argv);

	try
	{
		// Call the static initializers...
		//XMLPlatformUtils::Initialize();
		XalanTransformer::initialize();

		{
			//XSLTInit	theInit;
			XalanTransformer transformEngine;
			const XalanDOMString  theXSLSuffix(".xsl");
			const XalanDOMString  theXMLSuffix(".xml");
			const XalanDOMString  pathSep(XALAN_STATIC_UCODE_STRING("\\"));
//			const XalanDOMString  outputSuffix(".out");

			for(FileNameVectorType::size_type	j = 0; j < dirs.size(); j++)
			{
			  files = f.getTestFileNames(confDir, dirs[j]);
			  for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
			  { /*
				if (skip)
				{
					if (checkForExclusion(files[i]))
					{
						continue;
					}
				} */
				// Output file name to result log.
				//logFile.logTestCaseInit(files[i]);
			    cout << files[i] << endl;

				const XalanDOMString  theXMLFile= confDir + dirs[j] + pathSep + files[i];
				const XalanDOMString  outFile = outDir + dirs[j] + pathSep + files[i];
				const XalanDOMString  theXSLFile = f.GenerateFileName(theXMLFile,"xsl");
				const XalanDOMString  theOutputFile = f.GenerateFileName(outFile, "out");

				// Do a total end to end transform with no pre parsing of either xsl or xml files.
				XSLTResultTarget		theResultTarget(theOutputFile);
				const XSLTInputSource	xslInputSource(c_wstr(theXSLFile));
				const XSLTInputSource	xmlInputSource(c_wstr(theXMLFile));
				int theResult = 0;
				/*
				const etoetran = eTOeTransform(xmlInputSource,
												xslInputSource,
												theResultTarget,
												csConstructionContext,
												psExecutionContext,
												csProcessor); */
			    theResult = transformEngine.transform(xmlInputSource, xslInputSource, theResultTarget);
			  }
			}
		}
		XalanTransformer::terminate();
	}
	catch(...)
	{
		cerr << "Exception caught!!!" << endl << endl;
	}

return 0;
}
<commit_msg>Added XMLPlatformUtils::Terminate;  always look for exclusions and commented out writing to ReportLog. ReportLogging will be added later.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include <cassert>
#include <fstream>
#include <iostream>
#include <strstream>

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

//These came from the debug test.
#include <cstdio>
#include <ctime>
#include <string>
#include <vector>

#include <util/PlatformUtils.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanFileOutputStream.hpp>
#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>

#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>
#include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>

#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XMLFileReporter.hpp>
#include <FileUtility.hpp>

//This is here for the threads.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winbase.h>
#define THREADFUNCTIONRETURN DWORD WINAPI

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::cin;
	using std::endl;
	using std::ifstream;
	using std::ios_base;
	using std::ostrstream;
	using std::string;
#endif

// This is here for memory leak testing.
#if defined(_DEBUG)
#include <crtdbg.h>
#endif

const char* const excludeStylesheets[] =
{
//	"impincl16.xml",
	0
};

inline bool
checkForExclusion(XalanDOMString currentFile)
{

		for (int i=0; excludeStylesheets[i] != 0; i++)
			{
				if (equals(currentFile, XalanDOMString(excludeStylesheets[i])))
					return true;
			}
		return false;
}

void
getParams(int argc,
		  const char*	argv[])
{
	// This needs additional work.
	if (argc != 1)
	{
		cerr << "Usage: ThreadTest" << endl;
		exit(1);
	}
}

#if defined(XALAN_NO_NAMESPACES)
	typedef vector<XalanDOMString>		FileNameVectorType;
#else
	typedef std::vector<XalanDOMString>	FileNameVectorType;
#endif

int
main(
	 int			argc,
	 const char*	argv[])
{

#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	// Defined root for performance directory. Based on PD's machine.
	const XalanDOMString	confDir(XALAN_STATIC_UCODE_STRING("d:\\xslt\\xsl-test\\conf\\"));
	const XalanDOMString	outDir(XALAN_STATIC_UCODE_STRING("d:\\xslt\\xsl-test\\cplus-mem\\"));

	FileUtility f;
	FileNameVectorType dirs, files;

	// Get the list of Directories that are below perf
	dirs = f.getDirectoryNames(confDir);

	//XMLFileReporter	logFile("cpp.xml");
	//logFile.logTestFileInit("Memory Testing - Memory leaks detected during ConformanceTests. ");

	getParams(argc, argv);

	try
	{
		// Call the static initializers...
		XMLPlatformUtils::Initialize();
		XalanTransformer::initialize();
		XalanTransformer transformEngine;
		{
			const XalanDOMString  theXSLSuffix(".xsl");
			const XalanDOMString  theXMLSuffix(".xml");
			const XalanDOMString  pathSep(XALAN_STATIC_UCODE_STRING("\\"));

			for(FileNameVectorType::size_type	j = 0; j < dirs.size(); j++)
			{
			  files = f.getTestFileNames(confDir, dirs[j]);
			  for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
			  {
				if (checkForExclusion(files[i]))
					{
						continue;
					}

				// Output file name to result log.
				//logFile.logTestCaseInit(files[i]);
			    cout << files[i] << endl;

				const XalanDOMString  theXMLFile= confDir + dirs[j] + pathSep + files[i];
				const XalanDOMString  outFile = outDir + dirs[j] + pathSep + files[i];
				const XalanDOMString  theXSLFile = f.GenerateFileName(theXMLFile,"xsl");
				const XalanDOMString  theOutputFile = f.GenerateFileName(outFile, "out");

				// Do a total end to end transform with no pre parsing of either xsl or xml files.
				XSLTResultTarget		theResultTarget(theOutputFile);
				const XSLTInputSource	xslInputSource(c_wstr(theXSLFile));
				const XSLTInputSource	xmlInputSource(c_wstr(theXMLFile));
				int theResult = 0;

			    theResult = transformEngine.transform(xmlInputSource, xslInputSource, theResultTarget);
				if(theResult != 0)
				{
					cerr << "XalanError: \n" << transformEngine.getLastError();
					//exit (1);
				}

			  }
			}
		}
		XalanTransformer::terminate();
		XMLPlatformUtils::Terminate();
	}
	catch(...)
	{
		cerr << "Exception caught!!!" << endl << endl;
	}

return 0;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "test.hpp"

#include <vector>

//TODO The tests are a bit poor

TEMPLATE_TEST_CASE_2("pooling/deep/max2/1", "[pooling]", Z, float, double) {
    etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0});
    etl::fast_matrix<Z, 2, 4, 4> a;
    a(0) = aa;
    a(1) = aa;

    etl::fast_matrix<Z, 2, 2, 2> b(etl::max_pool_2d<2, 2>(a));

    REQUIRE_EQUALS(b(0, 0, 0), 6.0);
    REQUIRE_EQUALS(b(0, 0, 1), 8.0);
    REQUIRE_EQUALS(b(0, 1, 0), 14.0);
    REQUIRE_EQUALS(b(0, 1, 1), 16.0);

    REQUIRE_EQUALS(b(1, 0, 0), 6.0);
    REQUIRE_EQUALS(b(1, 0, 1), 8.0);
    REQUIRE_EQUALS(b(1, 1, 0), 14.0);
    REQUIRE_EQUALS(b(1, 1, 1), 16.0);
}

TEMPLATE_TEST_CASE_2("pooling/deep/max2/2", "[pooling]", Z, float, double) {
    etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0});
    etl::fast_matrix<Z, 2, 2, 4, 4> a;
    a(0)(0) = aa;
    a(0)(1) = aa;
    a(1)(0) = aa;
    a(1)(1) = aa;

    etl::fast_matrix<Z, 2, 2, 2, 2> b(etl::max_pool_2d<2, 2>(a));

    REQUIRE_EQUALS(b(0, 0, 0, 0), 6.0);
    REQUIRE_EQUALS(b(0, 0, 0, 1), 8.0);
    REQUIRE_EQUALS(b(0, 0, 1, 0), 14.0);
    REQUIRE_EQUALS(b(0, 0, 1, 1), 16.0);

    REQUIRE_EQUALS(b(0, 1, 0, 0), 6.0);
    REQUIRE_EQUALS(b(0, 1, 0, 1), 8.0);
    REQUIRE_EQUALS(b(0, 1, 1, 0), 14.0);
    REQUIRE_EQUALS(b(0, 1, 1, 1), 16.0);

    REQUIRE_EQUALS(b(1, 0, 0, 0), 6.0);
    REQUIRE_EQUALS(b(1, 0, 0, 1), 8.0);
    REQUIRE_EQUALS(b(1, 0, 1, 0), 14.0);
    REQUIRE_EQUALS(b(1, 0, 1, 1), 16.0);

    REQUIRE_EQUALS(b(1, 1, 0, 0), 6.0);
    REQUIRE_EQUALS(b(1, 1, 0, 1), 8.0);
    REQUIRE_EQUALS(b(1, 1, 1, 0), 14.0);
    REQUIRE_EQUALS(b(1, 1, 1, 1), 16.0);
}
<commit_msg>New tests<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "test.hpp"

#include <vector>

//TODO The tests are a bit poor

TEMPLATE_TEST_CASE_2("pooling/deep/max2/1", "[pooling]", Z, float, double) {
    etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0});
    etl::fast_matrix<Z, 2, 4, 4> a;
    a(0) = aa;
    a(1) = aa;

    etl::fast_matrix<Z, 2, 2, 2> b(etl::max_pool_2d<2, 2>(a));

    REQUIRE_EQUALS(b(0, 0, 0), 6.0);
    REQUIRE_EQUALS(b(0, 0, 1), 8.0);
    REQUIRE_EQUALS(b(0, 1, 0), 14.0);
    REQUIRE_EQUALS(b(0, 1, 1), 16.0);

    REQUIRE_EQUALS(b(1, 0, 0), 6.0);
    REQUIRE_EQUALS(b(1, 0, 1), 8.0);
    REQUIRE_EQUALS(b(1, 1, 0), 14.0);
    REQUIRE_EQUALS(b(1, 1, 1), 16.0);
}

TEMPLATE_TEST_CASE_2("pooling/deep/max2/2", "[pooling]", Z, float, double) {
    etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0});
    etl::fast_matrix<Z, 2, 2, 4, 4> a;
    a(0)(0) = aa;
    a(0)(1) = aa;
    a(1)(0) = aa;
    a(1)(1) = aa;

    etl::fast_matrix<Z, 2, 2, 2, 2> b(etl::max_pool_2d<2, 2>(a));

    REQUIRE_EQUALS(b(0, 0, 0, 0), 6.0);
    REQUIRE_EQUALS(b(0, 0, 0, 1), 8.0);
    REQUIRE_EQUALS(b(0, 0, 1, 0), 14.0);
    REQUIRE_EQUALS(b(0, 0, 1, 1), 16.0);

    REQUIRE_EQUALS(b(0, 1, 0, 0), 6.0);
    REQUIRE_EQUALS(b(0, 1, 0, 1), 8.0);
    REQUIRE_EQUALS(b(0, 1, 1, 0), 14.0);
    REQUIRE_EQUALS(b(0, 1, 1, 1), 16.0);

    REQUIRE_EQUALS(b(1, 0, 0, 0), 6.0);
    REQUIRE_EQUALS(b(1, 0, 0, 1), 8.0);
    REQUIRE_EQUALS(b(1, 0, 1, 0), 14.0);
    REQUIRE_EQUALS(b(1, 0, 1, 1), 16.0);

    REQUIRE_EQUALS(b(1, 1, 0, 0), 6.0);
    REQUIRE_EQUALS(b(1, 1, 0, 1), 8.0);
    REQUIRE_EQUALS(b(1, 1, 1, 0), 14.0);
    REQUIRE_EQUALS(b(1, 1, 1, 1), 16.0);
}

TEMPLATE_TEST_CASE_2("pooling/deep/avg2/1", "[pooling]", Z, float, double) {
    etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0});
    etl::fast_matrix<Z, 2, 4, 4> a;
    a(0) = aa;
    a(1) = aa;

    etl::fast_matrix<Z, 2, 2, 2> b(etl::avg_pool_2d<2, 2>(a));

    REQUIRE_EQUALS(b(0, 0, 0), 3.5);
    REQUIRE_EQUALS(b(0, 0, 1), 5.5);
    REQUIRE_EQUALS(b(0, 1, 0), 11.5);
    REQUIRE_EQUALS(b(0, 1, 1), 13.5);

    REQUIRE_EQUALS(b(1, 0, 0), 3.5);
    REQUIRE_EQUALS(b(1, 0, 1), 5.5);
    REQUIRE_EQUALS(b(1, 1, 0), 11.5);
    REQUIRE_EQUALS(b(1, 1, 1), 13.5);
}

TEMPLATE_TEST_CASE_2("pooling/deep/avg2/2", "[pooling]", Z, float, double) {
    etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0});
    etl::fast_matrix<Z, 2, 2, 4, 4> a;
    a(0)(0) = aa;
    a(0)(1) = aa;
    a(1)(0) = aa;
    a(1)(1) = aa;

    etl::fast_matrix<Z, 2, 2, 2, 2> b(etl::avg_pool_2d<2, 2>(a));

    REQUIRE_EQUALS(b(0, 0, 0, 0), 3.5);
    REQUIRE_EQUALS(b(0, 0, 0, 1), 5.5);
    REQUIRE_EQUALS(b(0, 0, 1, 0), 11.5);
    REQUIRE_EQUALS(b(0, 0, 1, 1), 13.5);

    REQUIRE_EQUALS(b(0, 1, 0, 0), 3.5);
    REQUIRE_EQUALS(b(0, 1, 0, 1), 5.5);
    REQUIRE_EQUALS(b(0, 1, 1, 0), 11.5);
    REQUIRE_EQUALS(b(0, 1, 1, 1), 13.5);

    REQUIRE_EQUALS(b(1, 0, 0, 0), 3.5);
    REQUIRE_EQUALS(b(1, 0, 0, 1), 5.5);
    REQUIRE_EQUALS(b(1, 0, 1, 0), 11.5);
    REQUIRE_EQUALS(b(1, 0, 1, 1), 13.5);

    REQUIRE_EQUALS(b(1, 1, 0, 0), 3.5);
    REQUIRE_EQUALS(b(1, 1, 0, 1), 5.5);
    REQUIRE_EQUALS(b(1, 1, 1, 0), 11.5);
    REQUIRE_EQUALS(b(1, 1, 1, 1), 13.5);
}
<|endoftext|>


<commit_before>#include "t-unit.h"
#include <routing/routingtemplate.h>

FIXTURE(RoutingTests) {
	TEST(MatchesNonTemplatedRoute) {
		ApiMock::RoutingTemplate sut("/first/second");
		assert.is_true(sut.isMatch("/first/second"));
	}
}<commit_msg>Test templated routes<commit_after>#include "t-unit.h"
#include <routing/routingtemplate.h>

FIXTURE(RoutingTests) {
	TEST(MatchesNonTemplatedRoute) {
		ApiMock::RoutingTemplate sut("/first/second");
		assert.is_true(sut.isMatch("/first/second"));
	}

	TEST(MatchesTemplatedRoute) {
		ApiMock::RoutingTemplate sut("/first/{second}/third");
		assert.is_true(sut.isMatch("/first/banana/third"));
	}
}<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE sync_access_test
#include <boost/test/unit_test.hpp>

#include <boost/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>

using namespace boost;
namespace ut = boost::unit_test;

static boost::mutex m;

/// thread execution function
static void thread_function(boost::barrier& b)
{
    b.wait(); /// wait until memory barrier allows the execution
    boost::mutex::scoped_lock lock(m); /// lock mutex
    BOOST_CHECK_EQUAL(1,0); /// produce the fault
}

BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_multiple_assertion_faults, 100 );

/// test function which creates threads
BOOST_AUTO_TEST_CASE( test_multiple_assertion_faults )
{
    boost::thread_group tg;      // thread group to manage all threads
    boost::barrier      b(100);  // memory barrier, which should block all threads
                                 // until all 100 threads were created

    for(size_t i=0; i<100; ++i)
        tg.create_thread(boost::bind(thread_function, ref(b))); /// create a thread and pass it the barrier

    tg.join_all();
}

// EOF
<commit_msg>extra ; removed<commit_after>#define BOOST_TEST_MODULE sync_access_test
#include <boost/test/unit_test.hpp>

#include <boost/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>

using namespace boost;
namespace ut = boost::unit_test;

static boost::mutex m;

/// thread execution function
static void thread_function(boost::barrier& b)
{
    b.wait(); /// wait until memory barrier allows the execution
    boost::mutex::scoped_lock lock(m); /// lock mutex
    BOOST_CHECK_EQUAL(1,0); /// produce the fault
}

BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_multiple_assertion_faults, 100 )

/// test function which creates threads
BOOST_AUTO_TEST_CASE( test_multiple_assertion_faults )
{
    boost::thread_group tg;      // thread group to manage all threads
    boost::barrier      b(100);  // memory barrier, which should block all threads
                                 // until all 100 threads were created

    for(size_t i=0; i<100; ++i)
        tg.create_thread(boost::bind(thread_function, ref(b))); /// create a thread and pass it the barrier

    tg.join_all();
}

// EOF
<|endoftext|>


<commit_before>#include "sani/platform/window.hpp"
#include "sani/assert.hpp"

#if SANI_TARGET_PLATFORM == SANI_PLATFORM_WIN32

namespace sani {
	namespace graphics {

		/*
		 *		Some functions always require that the window is in initialized state.
		 *	    Should this be fixed?
		 */

		class Window::Impl {
		public:
			// Simple flag to keep track about the
			// state of the window.
			bool initialized;
			bool isWindowOpen;
			bool isMinimized;

			// Just store basic and long strings
			// to their own fields.

			LPCWSTR title;
			String cTitle;

			int32 width;
			int32 height;
			int32 x;
			int32 y;

			HINSTANCE hInstance;
			HWND hWnd;

			Impl() : initialized(false),
					 isWindowOpen(false),
					 isMinimized(false),
					 title(L"Win32Window"),
					 cTitle("Win32Window"),
					 x(300),
					 y(300) {
			}

			~Impl() {
			}
		};

		Window::Window(const HINSTANCE hInstance, const uint32 width, const uint32 height) : impl(new Impl()) {
			impl->hInstance = hInstance;
			impl->width = width;
			impl->height = height;
		}

		// Private.

		LRESULT CALLBACK Window::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
			Window* window;

			// Sent prior to the WM_CREATE message when a window is first created.
			if (message == WM_NCCREATE) {
				// Get instance pointer.
				window = static_cast<Window*>(reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams);

				// Just set last error to 0.
				SetLastError(0);

				// Try to set the window long ptr.
				if (!SetWindowLongPtr(hWnd, GWL_USERDATA, reinterpret_cast<LONG_PTR>(window))) {
					if (GetLastError() != 0) return FALSE;
				}
			}
			else {
				window = reinterpret_cast<Window*>(GetWindowLongPtr(hWnd, GWL_USERDATA));
			}

			// TODO: use window if needed.

			switch (message) {
				// Close the application.
				case WM_DESTROY:
					PostQuitMessage(0);
					DestroyWindow(hWnd);

					return 0;
				case WM_CREATE:
				{
					// Initialize for OpenGL, set pixel format.
					// TODO: select between OpenGL and DX.
					PIXELFORMATDESCRIPTOR pfd =
					{
						sizeof(PIXELFORMATDESCRIPTOR),
						1,
						PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,		// Flags.
						PFD_TYPE_RGBA,													// The kind of framebuffer. RGBA for palette.
						32,																// Colordepth of the framebuffer.
						0, 0, 0, 0, 0, 0,
						0,
						0,
						0,
						0, 0, 0, 0,
						24,																// Number of bits for the depth buffer.
						8,																// Number of bits for the stencil buffer.
						0,																// Number of Aux buffers in the framebuffer.
						PFD_MAIN_PLANE,
						0,
						0, 0, 0
					};

					// Handle to device.
					HDC hDC = GetDC(hWnd);

					// Set pixel format.
					int pixelFormatID = ChoosePixelFormat(hDC, &pfd);
					SetPixelFormat(hDC, pixelFormatID, &pfd);

					WIN32_ASSERT();

					return 0;
				}
				case WM_SIZE:
					// Get new size of the window.
					RECT wndRect;

					GetWindowRect(window->impl->hWnd, &wndRect);

					window->impl->width = wndRect.right - wndRect.left;
					window->impl->height = wndRect.bottom - wndRect.top;

					return 0;
				case WM_MOVE:
					GetWindowRect(window->impl->hWnd, &wndRect);

					window->impl->x = wndRect.left;
					window->impl->y = wndRect.top;

					return 0;
			}

			// Handle any messages the switch statement didn't.
			return DefWindowProc(hWnd, message, wParam, lParam);
		}

		// Public.

		HWND Window::getHandle() const {
			assert(impl->initialized);

			return impl->hWnd;
		}

		String Window::getTitle() const {
			return impl->cTitle;
		}
		void Window::setTitle(const String& title) {
			const std::wstring stemp = std::wstring(title.begin(), title.end());

			impl->title = stemp.c_str();
			impl->cTitle = title;

			if (impl->initialized) {
				SetWindowText(impl->hWnd, impl->title);
			}
		}

		void Window::minimize() {
			assert(impl->initialized);

			if (impl->isMinimized) return;

			ShowWindow(impl->hWnd, SW_MINIMIZE);

			impl->isMinimized = true;
		}
		void Window::show() {
			assert(impl->initialized);

			if (impl->isMinimized) {
				ShowWindow(impl->hWnd, SW_RESTORE);

				impl->isMinimized = false;
			}
			else {
				ShowWindow(impl->hWnd, SW_SHOW);
			}
		}

		void Window::setSize(const int32 width, const int32 height) {
			if (impl->initialized) MoveWindow(impl->hWnd, impl->x, impl->y, width, height, TRUE);
			else {
				impl->width = width;
				impl->height = height;
			}
		}
		void Window::setWidth(const int32 width) {
			if (impl->initialized) MoveWindow(impl->hWnd, impl->x, impl->y, width, impl->height, TRUE);
			else {
				impl->width = width;
			}
		}
		void Window::setHeight(const int32 height) {
			if (impl->initialized) MoveWindow(impl->hWnd, impl->x, impl->y, impl->width, height, TRUE);
			else {
				impl->height = height;
			}
		}

		void Window::setPosition(const int32 x, const int32 y) {
			if (impl->initialized) MoveWindow(impl->hWnd, y, x, impl->width, impl->height, TRUE);
			else {
				impl->x = x;
				impl->y = y;
			}
		}
		void Window::setX(const int32 x) {
			if (impl->initialized) MoveWindow(impl->hWnd, x, impl->y, impl->width, impl->height, TRUE);
			else {
				impl->x = x;
			}
		}
		void Window::setY(const int32 y) {
			if (impl->initialized) MoveWindow(impl->hWnd, impl->x, y, impl->width, impl->height, TRUE);
			else {
				impl->y = y;
			}
		}

		int32 Window::getX() const {
			return impl->x;
		}
		int32 Window::getY() const {
			return impl->y;
		}

		uint32 Window::getClientWidth() const {
			assert(impl->initialized);

			RECT clntRect;

			GetClientRect(impl->hWnd, &clntRect);

			return clntRect.right- clntRect.left;
		}
		uint32 Window::getClientHeight() const {
			assert(impl->initialized);

			RECT clntRect;

			GetClientRect(impl->hWnd, &clntRect);

			return clntRect.bottom - clntRect.top;
		}

		inline int32 Window::getWidth() {
			return impl->width;
		}
		inline int32 Window::getHeight() {
			return impl->height;
		}

		void Window::listen() const {
			assert(impl->initialized);

			MSG msg;

			if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
				// translate keystroke messages into the right format
				TranslateMessage(&msg);

				// send the message to the WindowProc function
				DispatchMessage(&msg);

				impl->isWindowOpen = msg.message != WM_QUIT;
			}
		}

		bool Window::isOpen() const {
			assert(impl->initialized);

			return impl->isWindowOpen;
		}

		void Window::close() {
			assert(impl->initialized);

			if (!impl->isWindowOpen) return;

			impl->isWindowOpen = false;
		}

		bool Window::initialize() {
			assert(!impl->initialized);

			// Initialize the window.
			WNDCLASSEX windowClass;

			const size_t wndSize = sizeof(WNDCLASSEX);

			ZeroMemory(&windowClass, wndSize);
			WIN32_ASSERT();

			// Fill the struct.
			windowClass.cbSize = wndSize;
			windowClass.style = CS_HREDRAW | CS_VREDRAW;
			windowClass.lpfnWndProc = WndProc;
			windowClass.hInstance = impl->hInstance;
			windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
			windowClass.lpszClassName = L"WindowClass1";

			RegisterClassEx(&windowClass);
			WIN32_ASSERT();

			// TODO: set style to WS_OVERLAPPEDWINDOW for WinDX and
			//		 CS_OWNDC for OpenGL. Create rendering API detection.

			// TODO: open the window to the center of the display.
			// Create the window.
			impl->hWnd = CreateWindowEx(NULL,
										windowClass.lpszClassName,
										impl->title,
										WS_OVERLAPPEDWINDOW,
										impl->x,
										impl->y,
										impl->width,
										impl->height,
										NULL,
										NULL,
										impl->hInstance,
										this);

			WIN32_REQUIRE(impl->hWnd, L"failed to create window");

			// Set background to black.
			const HBRUSH brush = CreateSolidBrush(RGB(0, 0, 0));
			SetClassLongPtr(impl->hWnd, GCLP_HBRBACKGROUND, (LONG)brush);

			impl->initialized = true;
			impl->isWindowOpen = true;

			// Return results.
			return impl->initialized;
		}

		Window::~Window() {
			delete impl;
		}
	}
}

#endif<commit_msg>did some research about the window moving and resizing<commit_after>#include "sani/platform/window.hpp"
#include "sani/assert.hpp"

#if SANI_TARGET_PLATFORM == SANI_PLATFORM_WIN32

namespace sani {
	namespace graphics {

		/*
		 *		Some functions always require that the window is in initialized state.
		 *	    Should this be fixed?
		 */

		class Window::Impl {
		public:
			// Simple flag to keep track about the
			// state of the window.
			bool initialized;
			bool isWindowOpen;
			bool isMinimized;

			// Just store basic and long strings
			// to their own fields.

			LPCWSTR title;
			String cTitle;

			int32 width;
			int32 height;
			int32 x;
			int32 y;

			HINSTANCE hInstance;
			HWND hWnd;

			Impl() : initialized(false),
					 isWindowOpen(false),
					 isMinimized(false),
					 title(L"Win32Window"),
					 cTitle("Win32Window"),
					 x(300),
					 y(300) {
			}

			~Impl() {
			}
		};

		Window::Window(const HINSTANCE hInstance, const uint32 width, const uint32 height) : impl(new Impl()) {
			impl->hInstance = hInstance;
			impl->width = width;
			impl->height = height;
		}

		// Private.

		LRESULT CALLBACK Window::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
			/*
				TODO: window goes to black and stops
					  rendering when moved, fix it.

					  When moving or resizing the window,
					  windows blocks the calling thread by pumping
					  messages to this function. Create new
					  thread for the OpelGL to use?
			*/

			Window* window;

			// Sent prior to the WM_CREATE message when a window is first created.
			if (message == WM_NCCREATE) {
				// Get instance pointer.
				window = static_cast<Window*>(reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams);

				// Just set last error to 0.
				SetLastError(0);

				// Try to set the window long ptr.
				if (!SetWindowLongPtr(hWnd, GWL_USERDATA, reinterpret_cast<LONG_PTR>(window))) {
					if (GetLastError() != 0) return FALSE;
				}
			}
			else {
				window = reinterpret_cast<Window*>(GetWindowLongPtr(hWnd, GWL_USERDATA));
			}

			// TODO: use window if needed.

			switch (message) {
				// Close the application.
				case WM_DESTROY:
					PostQuitMessage(0);
					DestroyWindow(hWnd);

					return 0;
				case WM_CREATE:
				{
					// Initialize for OpenGL, set pixel format.
					// TODO: select between OpenGL and DX.
					PIXELFORMATDESCRIPTOR pfd =
					{
						sizeof(PIXELFORMATDESCRIPTOR),
						1,
						PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,		// Flags.
						PFD_TYPE_RGBA,													// The kind of framebuffer. RGBA for palette.
						32,																// Colordepth of the framebuffer.
						0, 0, 0, 0, 0, 0,
						0,
						0,
						0,
						0, 0, 0, 0,
						24,																// Number of bits for the depth buffer.
						8,																// Number of bits for the stencil buffer.
						0,																// Number of Aux buffers in the framebuffer.
						PFD_MAIN_PLANE,
						0,
						0, 0, 0
					};

					// Handle to device.
					HDC hDC = GetDC(hWnd);

					// Set pixel format.
					int pixelFormatID = ChoosePixelFormat(hDC, &pfd);
					SetPixelFormat(hDC, pixelFormatID, &pfd);

					WIN32_ASSERT();

					return 0;
				}
				case WM_SIZE:
					// Get new size of the window.
					RECT wndRect;

					GetWindowRect(window->impl->hWnd, &wndRect);

					window->impl->width = wndRect.right - wndRect.left;
					window->impl->height = wndRect.bottom - wndRect.top;

					return 0;
				case WM_MOVE:
					GetWindowRect(window->impl->hWnd, &wndRect);

					window->impl->x = wndRect.left;
					window->impl->y = wndRect.top;

					return 0;
			}

			// Handle any messages the switch statement didn't.
			return DefWindowProc(hWnd, message, wParam, lParam);
		}

		// Public.

		HWND Window::getHandle() const {
			assert(impl->initialized);

			return impl->hWnd;
		}

		String Window::getTitle() const {
			return impl->cTitle;
		}
		void Window::setTitle(const String& title) {
			const std::wstring stemp = std::wstring(title.begin(), title.end());

			impl->title = stemp.c_str();
			impl->cTitle = title;

			if (impl->initialized) {
				SetWindowText(impl->hWnd, impl->title);
			}
		}

		void Window::minimize() {
			assert(impl->initialized);

			if (impl->isMinimized) return;

			ShowWindow(impl->hWnd, SW_MINIMIZE);

			impl->isMinimized = true;
		}
		void Window::show() {
			assert(impl->initialized);

			if (impl->isMinimized) {
				ShowWindow(impl->hWnd, SW_RESTORE);

				impl->isMinimized = false;
			}
			else {
				ShowWindow(impl->hWnd, SW_SHOW);
			}
		}

		void Window::setSize(const int32 width, const int32 height) {
			if (impl->initialized) MoveWindow(impl->hWnd, impl->x, impl->y, width, height, TRUE);
			else {
				impl->width = width;
				impl->height = height;
			}
		}
		void Window::setWidth(const int32 width) {
			if (impl->initialized) MoveWindow(impl->hWnd, impl->x, impl->y, width, impl->height, TRUE);
			else {
				impl->width = width;
			}
		}
		void Window::setHeight(const int32 height) {
			if (impl->initialized) MoveWindow(impl->hWnd, impl->x, impl->y, impl->width, height, TRUE);
			else {
				impl->height = height;
			}
		}

		void Window::setPosition(const int32 x, const int32 y) {
			if (impl->initialized) MoveWindow(impl->hWnd, y, x, impl->width, impl->height, TRUE);
			else {
				impl->x = x;
				impl->y = y;
			}
		}
		void Window::setX(const int32 x) {
			if (impl->initialized) MoveWindow(impl->hWnd, x, impl->y, impl->width, impl->height, TRUE);
			else {
				impl->x = x;
			}
		}
		void Window::setY(const int32 y) {
			if (impl->initialized) MoveWindow(impl->hWnd, impl->x, y, impl->width, impl->height, TRUE);
			else {
				impl->y = y;
			}
		}

		int32 Window::getX() const {
			return impl->x;
		}
		int32 Window::getY() const {
			return impl->y;
		}

		uint32 Window::getClientWidth() const {
			assert(impl->initialized);

			RECT clntRect;

			GetClientRect(impl->hWnd, &clntRect);

			return clntRect.right- clntRect.left;
		}
		uint32 Window::getClientHeight() const {
			assert(impl->initialized);

			RECT clntRect;

			GetClientRect(impl->hWnd, &clntRect);

			return clntRect.bottom - clntRect.top;
		}

		inline int32 Window::getWidth() {
			return impl->width;
		}
		inline int32 Window::getHeight() {
			return impl->height;
		}

		void Window::listen() const {
			assert(impl->initialized);

			MSG msg;

			if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
				// translate keystroke messages into the right format
				TranslateMessage(&msg);

				// send the message to the WindowProc function
				DispatchMessage(&msg);

				impl->isWindowOpen = msg.message != WM_QUIT;
			}
		}

		bool Window::isOpen() const {
			assert(impl->initialized);

			return impl->isWindowOpen;
		}

		void Window::close() {
			assert(impl->initialized);

			if (!impl->isWindowOpen) return;

			impl->isWindowOpen = false;
		}

		bool Window::initialize() {
			assert(!impl->initialized);

			// Initialize the window.
			WNDCLASSEX windowClass;

			const size_t wndSize = sizeof(WNDCLASSEX);

			ZeroMemory(&windowClass, wndSize);
			WIN32_ASSERT();

			// Fill the struct.
			windowClass.cbSize = wndSize;
			windowClass.style = CS_HREDRAW | CS_VREDRAW;
			windowClass.lpfnWndProc = WndProc;
			windowClass.hInstance = impl->hInstance;
			windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
			windowClass.lpszClassName = L"WindowClass1";

			RegisterClassEx(&windowClass);
			WIN32_ASSERT();

			// TODO: set style to WS_OVERLAPPEDWINDOW for WinDX and
			//		 CS_OWNDC for OpenGL. Create rendering API detection.

			// TODO: open the window to the center of the display.
			// Create the window.
			impl->hWnd = CreateWindowEx(NULL,
										windowClass.lpszClassName,
										impl->title,
										WS_OVERLAPPEDWINDOW,
										impl->x,
										impl->y,
										impl->width,
										impl->height,
										NULL,
										NULL,
										impl->hInstance,
										this);

			WIN32_REQUIRE(impl->hWnd, L"failed to create window");

			// Set background to black.
			const HBRUSH brush = CreateSolidBrush(RGB(0, 0, 0));
			SetClassLongPtr(impl->hWnd, GCLP_HBRBACKGROUND, (LONG)brush);

			impl->initialized = true;
			impl->isWindowOpen = true;

			// Return results.
			return impl->initialized;
		}

		Window::~Window() {
			delete impl;
		}
	}
}

#endif<|endoftext|>


<commit_before>// Copyright (c) 2012 Cloudera, Inc. All rights reserved.

#include "common/logging.h"
#include "util/webserver.h"
#include "util/metrics.h"
#include <sstream>
#include <boost/algorithm/string/join.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>

using namespace impala;
using namespace std;
using namespace boost;
using namespace boost::algorithm;

Metrics::Metrics()
  : obj_pool_(new ObjectPool()) { }

Status Metrics::Init(Webserver* webserver) {
  if (webserver != NULL) {
    Webserver::PathHandlerCallback default_callback =
        bind<void>(mem_fn(&Metrics::TextCallback), this, _1);
    webserver->RegisterPathHandler("/metrics", default_callback);

    Webserver::PathHandlerCallback json_callback =
        bind<void>(mem_fn(&Metrics::JsonCallback), this, _1);
    webserver->RegisterPathHandler("/jsonmetrics", json_callback);
  }

  return Status::OK;
}

void Metrics::PrintMetricMap(stringstream* output) {
  lock_guard<mutex> l(lock_);
  BOOST_FOREACH(const MetricMap::value_type& m, metric_map_) {
    m.second->Print(output);
  }
}

void Metrics::PrintMetricMapAsJson(vector<string>* metrics) {
  lock_guard<mutex> l(lock_);
  BOOST_FOREACH(const MetricMap::value_type& m, metric_map_) {
    stringstream ss;
    m.second->PrintJson(&ss);
    metrics->push_back(ss.str());
  }
}

string Metrics::DebugString() {
  stringstream ss;
  TextCallback(&ss);
  return ss.str();
}

void Metrics::TextCallback(stringstream* output) {
  (*output) << "
";
  PrintMetricMap(output);
  (*output) << "
";
}

void Metrics::JsonCallback(stringstream* output) {
  (*output) << "
{";
  vector<string> metrics;
  PrintMetricMapAsJson(&metrics);
  (*output) << join(metrics, ",\n");
  (*output) << "}
";
}
<commit_msg>Remove HTML tags from /jsonmetrics<commit_after>// Copyright (c) 2012 Cloudera, Inc. All rights reserved.

#include "common/logging.h"
#include "util/webserver.h"
#include "util/metrics.h"
#include <sstream>
#include <boost/algorithm/string/join.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>

using namespace impala;
using namespace std;
using namespace boost;
using namespace boost::algorithm;

Metrics::Metrics()
  : obj_pool_(new ObjectPool()) { }

Status Metrics::Init(Webserver* webserver) {
  if (webserver != NULL) {
    Webserver::PathHandlerCallback default_callback =
        bind<void>(mem_fn(&Metrics::TextCallback), this, _1);
    webserver->RegisterPathHandler("/metrics", default_callback);

    Webserver::PathHandlerCallback json_callback =
        bind<void>(mem_fn(&Metrics::JsonCallback), this, _1);
    webserver->RegisterPathHandler("/jsonmetrics", json_callback);
  }

  return Status::OK;
}

void Metrics::PrintMetricMap(stringstream* output) {
  lock_guard<mutex> l(lock_);
  BOOST_FOREACH(const MetricMap::value_type& m, metric_map_) {
    m.second->Print(output);
  }
}

void Metrics::PrintMetricMapAsJson(vector<string>* metrics) {
  lock_guard<mutex> l(lock_);
  BOOST_FOREACH(const MetricMap::value_type& m, metric_map_) {
    stringstream ss;
    m.second->PrintJson(&ss);
    metrics->push_back(ss.str());
  }
}

string Metrics::DebugString() {
  stringstream ss;
  TextCallback(&ss);
  return ss.str();
}

void Metrics::TextCallback(stringstream* output) {
  (*output) << "
";
  PrintMetricMap(output);
  (*output) << "
";
}

void Metrics::JsonCallback(stringstream* output) {
  (*output) << "{";
  vector<string> metrics;
  PrintMetricMapAsJson(&metrics);
  (*output) << join(metrics, ",\n");
  (*output) << "}";
}
<|endoftext|>


<commit_before>#include "Song.h"
#include "Sequence.h"
#include "SequenceRow.h"
#include "Pattern.h"
#include "Sequence.h"
#include "Macro.h"
#include "PatternRow.h"
#include "FileSection.h"
#include "SectionListener.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <strings.h>
#include <algorithm>

Song::Song()
	: patternLength(64), sequenceLength(1), mNumListeners(0)
{
	sequence = new Sequence();
	patterns = new Pattern[maxPatterns];
	macros = new Macro[maxMacros];
	strcpy(name, "new song");
}

Song::~Song()
{
	delete[] patterns;
	delete[] macros;
	delete sequence;
}

Sequence& Song::getSequence()
{
	return *sequence;
}

int Song::getLastPatternUsed() const
{
	int last = -1;

	for (int i = 0 ; i < maxPatterns ; ++i)
	{
		if (!patterns[i].isEmpty())
			last = std::max(last, i);
	}

	return last;
}

int Song::getLastMacroUsed() const
{
	int last = -1;

	for (int i = 0 ; i < maxMacros ; ++i)
	{
		if (strlen(macros[i].getName()) > 0 || !macros[i].isEmpty())
			last = std::max(last, i);
	}

	return last;
}

int Song::getPatternLength() const
{
	return patternLength;
}

int Song::getSequenceLength() const
{
	return sequenceLength;
}

Pattern& Song::getPattern(int pattern)
{
	return patterns[pattern];
}

Macro& Song::getMacro(int macro)
{
	return macros[macro];
}

void Song::setPatternLength(int length)
{
	patternLength = length;
}

void Song::setSequenceLength(int length)
{
	sequenceLength = length;
}

FileSection* Song::pack()
{
	FileSection * song = FileSection::createSection("SONG");

	/*
	 * Basic song info
	 */

	// File format version
	song->writeByte(songVersion);
	song->writeByte(SequenceRow::maxTracks);
	song->writeString(name);
	song->writeByte(patternLength - 1);
	song->writeByte(sequenceLength - 1);

	/*
	 * Sequence data
	 */

	FileSection * sequenceData = FileSection::createSection("SEQU");
	int sequenceCount = sequence->getLastSequenceRowUsed() + 1;
	sequenceData->writeByte(sequenceCount);
	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		for (int i = 0 ; i < sequenceCount ; ++i)
		{
			SequenceRow& sequenceRow = sequence->getRow(i);
			sequenceData->writeByte(sequenceRow.pattern[track]);
		}
	}
	song->writeSection(*sequenceData);
	delete sequenceData;

	/*
	 * Patterns
	 */

	FileSection * patternData = FileSection::createSection("PATT");
	int patternCount = getLastPatternUsed() + 1;
	patternData->writeByte(patternCount);
	for (int i = 0 ; i < patternCount ; ++i)
	{
		Pattern& pattern = getPattern(i);
		patternData->writePattern(pattern);
	}
	song->writeSection(*patternData);
	delete patternData;

	/*
	 * Macros
	 */

	FileSection * macroData = FileSection::createSection("MACR");
	int macroCount = getLastMacroUsed() + 1;
	//printf("Saving %d macros\n", macroCount);
	macroData->writeByte(macroCount);
	for (int i = 0 ; i < macroCount ; ++i)
	{
		Macro& macro = getMacro(i);
		macroData->writeString(macro.getName());
		macroData->writePattern(macro);
	}
	song->writeSection(*macroData);
	delete macroData;

	// Call SectionListeners for save

	for (int i = 0 ; i < mNumListeners ; ++i)
	{
		if (mListeners[i].flags & SectionListener::Load)
		{
			FileSection *listenerSection = FileSection::createSection(mListeners[i].sectionId);
			mListeners[i].listener->onFileSectionSave(*listenerSection);
			song->writeSection(*listenerSection);
			delete listenerSection;
		}
	}

	return song;
}

void Song::clear()
{
	sequence->clear();

	strcpy(name, "");

	for (int i = 0 ; i < maxPatterns ; ++i)
	{
		patterns[i].clear();
	}

	for (int i = 0 ; i < maxMacros ; ++i)
	{
		macros[i].clear();
	}

	sequenceLength = 1;
	patternLength = 64;
}

Song::UnpackError Song::unpack(const FileSection& section)
{
	if (strcmp(section.getName(), "SONG") != 0)
		return NotASong;

	clear();

	int offset = 0;
	int version = section.readByte(offset);

	if (version > songVersion)
	{
		// TODO: display a proper error if the version is newer than we can handle
		return ErrorVersion;
	}

	// Default trackCount for version == 0
	int trackCount = 4;

	if (version == FileSection::invalidRead)
		return ErrorRead;

	if (version >= 1)
	{
		trackCount = section.readByte(offset);

		if (trackCount == FileSection::invalidRead)
			return ErrorRead;
	}

	const char *songName = section.readString(offset);

	if (songName == NULL)
		return ErrorRead;

	strncpy(name, songName, songNameLength + 1);

	int temp = section.readByte(offset);

	if (temp == FileSection::invalidRead)
		return ErrorRead;

	patternLength = temp + 1;

	temp = section.readByte(offset);

	if (temp == FileSection::invalidRead)
		return ErrorRead;

	sequenceLength = temp + 1;

	UnpackError returnValue = Success;

	do
	{
		//printf("offset = %d\n", offset);
		FileSection *subSection = section.readSection(offset);
		int subOffset = 0;

		if (subSection == NULL)
			break;

		const char *sectionName = subSection->getName();

		if (sectionName != NULL)
		{
			//printf("Read section %s (%d bytes)\n", sectionName, subSection->getSize());

			if (strcmp(sectionName, "SEQU") == 0)
			{
				int temp = subSection->readByte(subOffset);

				if (temp == FileSection::invalidRead)
				{
					returnValue = ErrorRead;
				}
				else
				{
					int count = temp;

					//printf("Reading %d sequences\n", count);

					if (count > maxSequenceRows)
					{
						returnValue = ErrorRead;
					}
					else
					{
						for (int track = 0 ; track < trackCount && returnValue == Success ; ++track)
						{
							for (int i = 0 ; i < count ; ++i)
							{
								int temp = subSection->readByte(subOffset);

								if (temp == FileSection::invalidRead)
								{
									returnValue = ErrorRead;
									break;
								}

								// Skip tracks that can't fit in our sequence
								if (track < SequenceRow::maxTracks)
									sequence->getRow(i).pattern[track] = temp;
							}
						}
					}
				}
			}
			else if (strcmp(sectionName, "PATT") == 0)
			{
				int temp = subSection->readByte(subOffset);

				if (temp == FileSection::invalidRead)
				{
					returnValue = ErrorRead;
				}
				else
				{
					int count = temp;

					//printf("Reading %d patterns\n", count);

					for (int i = 0 ; i < count ; ++i)
					{
						if (!subSection->readPattern(patterns[i], subOffset))
						{
							returnValue = ErrorRead;
							break;
						}
					}
				}
			}
			else if (strcmp(sectionName, "MACR") == 0)
			{
				int temp = subSection->readByte(subOffset);

				if (temp == FileSection::invalidRead)
				{
					returnValue = ErrorRead;
				}
				else
				{
					int count = temp;

					//printf("Reading %d macros\n", count);

					for (int i = 0 ; i < count ; ++i)
					{
						const char *macroName = subSection->readString(subOffset);

						if (macroName == NULL)
						{
							returnValue = ErrorRead;
							break;
						}

						strncpy(macros[i].getName(), macroName, Macro::macroNameLength + 1);

						if (!subSection->readPattern(macros[i], subOffset))
						{
							returnValue = ErrorRead;
							break;
						}
					}
				}
			}
			else
			{
				for (int i = 0 ; i < mNumListeners ; ++i)
				{
					if ((mListeners[i].flags & SectionListener::Load) && strcmp(mListeners[i].sectionId, sectionName) == 0)
					{
						if (!mListeners[i].listener->onFileSectionLoad(*subSection))
						{
							returnValue = ErrorRead;
							break;
						}
					}
				}
			}
		}
		else
		{
			returnValue = ErrorRead;
		}

		//offset += subOffset;

		delete subSection;
	}
	while (returnValue == Success);

	return returnValue;
}

char *Song::getSongName()
{
	return name;
}

int Song::getSize() const
{
	return 0;
}

bool Song::addSectionListener(const char *sectionId, SectionListener *sectionListener, int flags)
{
	if (mNumListeners >= maxListeners)
		return false;

	SectionListenerInfo& info = mListeners[mNumListeners];
	info.flags = flags;
	info.sectionId = sectionId;
	info.listener = sectionListener;

	mNumListeners++;

	return true;
}
<commit_msg>Wrong flag for saving<commit_after>#include "Song.h"
#include "Sequence.h"
#include "SequenceRow.h"
#include "Pattern.h"
#include "Sequence.h"
#include "Macro.h"
#include "PatternRow.h"
#include "FileSection.h"
#include "SectionListener.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <strings.h>
#include <algorithm>

Song::Song()
	: patternLength(64), sequenceLength(1), mNumListeners(0)
{
	sequence = new Sequence();
	patterns = new Pattern[maxPatterns];
	macros = new Macro[maxMacros];
	strcpy(name, "new song");
}

Song::~Song()
{
	delete[] patterns;
	delete[] macros;
	delete sequence;
}

Sequence& Song::getSequence()
{
	return *sequence;
}

int Song::getLastPatternUsed() const
{
	int last = -1;

	for (int i = 0 ; i < maxPatterns ; ++i)
	{
		if (!patterns[i].isEmpty())
			last = std::max(last, i);
	}

	return last;
}

int Song::getLastMacroUsed() const
{
	int last = -1;

	for (int i = 0 ; i < maxMacros ; ++i)
	{
		if (strlen(macros[i].getName()) > 0 || !macros[i].isEmpty())
			last = std::max(last, i);
	}

	return last;
}

int Song::getPatternLength() const
{
	return patternLength;
}

int Song::getSequenceLength() const
{
	return sequenceLength;
}

Pattern& Song::getPattern(int pattern)
{
	return patterns[pattern];
}

Macro& Song::getMacro(int macro)
{
	return macros[macro];
}

void Song::setPatternLength(int length)
{
	patternLength = length;
}

void Song::setSequenceLength(int length)
{
	sequenceLength = length;
}

FileSection* Song::pack()
{
	FileSection * song = FileSection::createSection("SONG");

	/*
	 * Basic song info
	 */

	// File format version
	song->writeByte(songVersion);
	song->writeByte(SequenceRow::maxTracks);
	song->writeString(name);
	song->writeByte(patternLength - 1);
	song->writeByte(sequenceLength - 1);

	/*
	 * Sequence data
	 */

	FileSection * sequenceData = FileSection::createSection("SEQU");
	int sequenceCount = sequence->getLastSequenceRowUsed() + 1;
	sequenceData->writeByte(sequenceCount);
	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		for (int i = 0 ; i < sequenceCount ; ++i)
		{
			SequenceRow& sequenceRow = sequence->getRow(i);
			sequenceData->writeByte(sequenceRow.pattern[track]);
		}
	}
	song->writeSection(*sequenceData);
	delete sequenceData;

	/*
	 * Patterns
	 */

	FileSection * patternData = FileSection::createSection("PATT");
	int patternCount = getLastPatternUsed() + 1;
	patternData->writeByte(patternCount);
	for (int i = 0 ; i < patternCount ; ++i)
	{
		Pattern& pattern = getPattern(i);
		patternData->writePattern(pattern);
	}
	song->writeSection(*patternData);
	delete patternData;

	/*
	 * Macros
	 */

	FileSection * macroData = FileSection::createSection("MACR");
	int macroCount = getLastMacroUsed() + 1;
	//printf("Saving %d macros\n", macroCount);
	macroData->writeByte(macroCount);
	for (int i = 0 ; i < macroCount ; ++i)
	{
		Macro& macro = getMacro(i);
		macroData->writeString(macro.getName());
		macroData->writePattern(macro);
	}
	song->writeSection(*macroData);
	delete macroData;

	// Call SectionListeners for save

	for (int i = 0 ; i < mNumListeners ; ++i)
	{
		if (mListeners[i].flags & SectionListener::Save)
		{
			FileSection *listenerSection = FileSection::createSection(mListeners[i].sectionId);
			mListeners[i].listener->onFileSectionSave(*listenerSection);
			song->writeSection(*listenerSection);
			delete listenerSection;
		}
	}

	return song;
}

void Song::clear()
{
	sequence->clear();

	strcpy(name, "");

	for (int i = 0 ; i < maxPatterns ; ++i)
	{
		patterns[i].clear();
	}

	for (int i = 0 ; i < maxMacros ; ++i)
	{
		macros[i].clear();
	}

	sequenceLength = 1;
	patternLength = 64;
}

Song::UnpackError Song::unpack(const FileSection& section)
{
	if (strcmp(section.getName(), "SONG") != 0)
		return NotASong;

	clear();

	int offset = 0;
	int version = section.readByte(offset);

	if (version > songVersion)
	{
		// TODO: display a proper error if the version is newer than we can handle
		return ErrorVersion;
	}

	// Default trackCount for version == 0
	int trackCount = 4;

	if (version == FileSection::invalidRead)
		return ErrorRead;

	if (version >= 1)
	{
		trackCount = section.readByte(offset);

		if (trackCount == FileSection::invalidRead)
			return ErrorRead;
	}

	const char *songName = section.readString(offset);

	if (songName == NULL)
		return ErrorRead;

	strncpy(name, songName, songNameLength + 1);

	int temp = section.readByte(offset);

	if (temp == FileSection::invalidRead)
		return ErrorRead;

	patternLength = temp + 1;

	temp = section.readByte(offset);

	if (temp == FileSection::invalidRead)
		return ErrorRead;

	sequenceLength = temp + 1;

	UnpackError returnValue = Success;

	do
	{
		//printf("offset = %d\n", offset);
		FileSection *subSection = section.readSection(offset);
		int subOffset = 0;

		if (subSection == NULL)
			break;

		const char *sectionName = subSection->getName();

		if (sectionName != NULL)
		{
			//printf("Read section %s (%d bytes)\n", sectionName, subSection->getSize());

			if (strcmp(sectionName, "SEQU") == 0)
			{
				int temp = subSection->readByte(subOffset);

				if (temp == FileSection::invalidRead)
				{
					returnValue = ErrorRead;
				}
				else
				{
					int count = temp;

					//printf("Reading %d sequences\n", count);

					if (count > maxSequenceRows)
					{
						returnValue = ErrorRead;
					}
					else
					{
						for (int track = 0 ; track < trackCount && returnValue == Success ; ++track)
						{
							for (int i = 0 ; i < count ; ++i)
							{
								int temp = subSection->readByte(subOffset);

								if (temp == FileSection::invalidRead)
								{
									returnValue = ErrorRead;
									break;
								}

								// Skip tracks that can't fit in our sequence
								if (track < SequenceRow::maxTracks)
									sequence->getRow(i).pattern[track] = temp;
							}
						}
					}
				}
			}
			else if (strcmp(sectionName, "PATT") == 0)
			{
				int temp = subSection->readByte(subOffset);

				if (temp == FileSection::invalidRead)
				{
					returnValue = ErrorRead;
				}
				else
				{
					int count = temp;

					//printf("Reading %d patterns\n", count);

					for (int i = 0 ; i < count ; ++i)
					{
						if (!subSection->readPattern(patterns[i], subOffset))
						{
							returnValue = ErrorRead;
							break;
						}
					}
				}
			}
			else if (strcmp(sectionName, "MACR") == 0)
			{
				int temp = subSection->readByte(subOffset);

				if (temp == FileSection::invalidRead)
				{
					returnValue = ErrorRead;
				}
				else
				{
					int count = temp;

					//printf("Reading %d macros\n", count);

					for (int i = 0 ; i < count ; ++i)
					{
						const char *macroName = subSection->readString(subOffset);

						if (macroName == NULL)
						{
							returnValue = ErrorRead;
							break;
						}

						strncpy(macros[i].getName(), macroName, Macro::macroNameLength + 1);

						if (!subSection->readPattern(macros[i], subOffset))
						{
							returnValue = ErrorRead;
							break;
						}
					}
				}
			}
			else
			{
				for (int i = 0 ; i < mNumListeners ; ++i)
				{
					if ((mListeners[i].flags & SectionListener::Load) && strcmp(mListeners[i].sectionId, sectionName) == 0)
					{
						if (!mListeners[i].listener->onFileSectionLoad(*subSection))
						{
							returnValue = ErrorRead;
							break;
						}
					}
				}
			}
		}
		else
		{
			returnValue = ErrorRead;
		}

		//offset += subOffset;

		delete subSection;
	}
	while (returnValue == Success);

	return returnValue;
}

char *Song::getSongName()
{
	return name;
}

int Song::getSize() const
{
	return 0;
}

bool Song::addSectionListener(const char *sectionId, SectionListener *sectionListener, int flags)
{
	if (mNumListeners >= maxListeners)
		return false;

	SectionListenerInfo& info = mListeners[mNumListeners];
	info.flags = flags;
	info.sectionId = sectionId;
	info.listener = sectionListener;

	mNumListeners++;

	return true;
}
<|endoftext|>


<commit_before>/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2009 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com
 * Copyright (C) 2011 Wayne Stambaugh <stambaughw@verizon.net>
 * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

/**
 * @file pcbnew/controle.cpp
 */

#include "fctsys.h"
#include "class_drawpanel.h"
#include "wxPcbStruct.h"
#include "pcbcommon.h"
#include "macros.h"

#include "pcbnew_id.h"

#include "class_board.h"
#include "class_module.h"

#include "pcbnew.h"
#include "protos.h"
#include "collectors.h"

//external functions used here:
extern bool Magnetize( BOARD* m_Pcb, PCB_EDIT_FRAME* frame,
                       int aCurrentTool, wxSize grid, wxPoint on_grid, wxPoint* curpos );

/**
 * Function AllAreModulesAndReturnSmallestIfSo
 * tests that all items in the collection are MODULEs and if so, returns the
 * smallest MODULE.
 * @return BOARD_ITEM* - The smallest or NULL.
 */
static BOARD_ITEM* AllAreModulesAndReturnSmallestIfSo( GENERAL_COLLECTOR* aCollector )
{
    int count = aCollector->GetCount();

    for( int i = 0; i<count;  ++i )
    {
        if( (*aCollector)[i]->Type() != PCB_MODULE_T )
            return NULL;
    }

    // all are modules, now find smallest MODULE

    int minDim = 0x7FFFFFFF;
    int minNdx = 0;

    for( int i = 0;  i<count;  ++i )
    {
        MODULE* module = (MODULE*) (*aCollector)[i];

        int     lx = module->m_BoundaryBox.GetWidth();
        int     ly = module->m_BoundaryBox.GetHeight();

        int     lmin = MIN( lx, ly );

        if( lmin <= minDim )
        {
            minDim = lmin;
            minNdx = i;
        }
    }

    return (*aCollector)[minNdx];
}

BOARD_ITEM* PCB_BASE_FRAME::PcbGeneralLocateAndDisplay( int aHotKeyCode )
{
    BOARD_ITEM* item;

    GENERAL_COLLECTORS_GUIDE guide = GetCollectorsGuide();

    // Assign to scanList the proper item types desired based on tool type
    // or hotkey that is in play.

    const KICAD_T* scanList = NULL;

    if( aHotKeyCode )
    {
        // @todo: add switch here and add calls to PcbGeneralLocateAndDisplay( int aHotKeyCode )
        // when searching is needed from a hotkey handler
    }
    else if( GetToolId() == ID_NO_TOOL_SELECTED )
    {
        switch( m_HTOOL_current_state )
        {
        case ID_TOOLBARH_PCB_MODE_MODULE:
            scanList = GENERAL_COLLECTOR::ModuleItems;
            break;

        default:
            scanList = DisplayOpt.DisplayZonesMode == 0 ?
                       GENERAL_COLLECTOR::AllBoardItems :
                       GENERAL_COLLECTOR::AllButZones;
            break;
        }
    }
    else
    {
        switch( GetToolId() )
        {
        case ID_PCB_SHOW_1_RATSNEST_BUTT:
            scanList = GENERAL_COLLECTOR::PadsOrModules;
            break;

        case ID_TRACK_BUTT:
            scanList = GENERAL_COLLECTOR::Tracks;
            break;

        case ID_PCB_MODULE_BUTT:
            scanList = GENERAL_COLLECTOR::ModuleItems;
            break;

        case ID_PCB_ZONES_BUTT:
            scanList = GENERAL_COLLECTOR::Zones;
            break;

        default:
            scanList = DisplayOpt.DisplayZonesMode == 0 ?
                       GENERAL_COLLECTOR::AllBoardItems :
                       GENERAL_COLLECTOR::AllButZones;
        }
    }

    m_Collector->Collect( m_Pcb, scanList, GetScreen()->RefPos( true ), guide );

#if 0
    // debugging: print out the collected items, showing their priority order too.
    for( int i = 0; i<m_Collector->GetCount();  ++i )
        (*m_Collector)[i]->Show( 0, std::cout );
#endif

    /* Remove redundancies: sometime, zones are found twice,
     * because zones can be filled by overlapping segments (this is a fill option)
     */
    unsigned long timestampzone = 0;

    for( int ii = 0;  ii < m_Collector->GetCount(); ii++ )
    {
        item = (*m_Collector)[ii];

        if( item->Type() != PCB_ZONE_T )
            continue;

        /* Found a TYPE ZONE */
        if( item->m_TimeStamp == timestampzone )    // Remove it, redundant, zone already found
        {
            m_Collector->Remove( ii );
            ii--;
        }
        else
        {
            timestampzone = item->m_TimeStamp;
        }
    }

    if( m_Collector->GetCount() <= 1 )
    {
        item = (*m_Collector)[0];
        SetCurItem( item );
    }

    // If the count is 2, and first item is a pad or module text, and the 2nd item is its
    // parent module:
    else if( m_Collector->GetCount() == 2
             && ( (*m_Collector)[0]->Type() == PCB_PAD_T || (*m_Collector)[0]->Type() ==
                 PCB_MODULE_TEXT_T )
             && (*m_Collector)[1]->Type() == PCB_MODULE_T && (*m_Collector)[0]->GetParent()==
             (*m_Collector)[1] )
    {
        item = (*m_Collector)[0];
        SetCurItem( item );
    }
    // if all are modules, find the smallest one among the primary choices
    else if( ( item = AllAreModulesAndReturnSmallestIfSo( m_Collector ) ) != NULL )
    {
        SetCurItem( item );
    }

    else    // we can't figure out which item user wants, do popup menu so user can choose
    {
        wxMenu itemMenu;

        /* Give a title to the selection menu. This is also a cancel menu item */
        wxMenuItem * item_title = new wxMenuItem( &itemMenu, -1, _( "Selection Clarification" ) );

#ifdef __WINDOWS__
        wxFont bold_font( *wxNORMAL_FONT );
        bold_font.SetWeight( wxFONTWEIGHT_BOLD );
        bold_font.SetStyle( wxFONTSTYLE_ITALIC );
        item_title->SetFont( bold_font );
#endif

        itemMenu.Append( item_title );
        itemMenu.AppendSeparator();

        int limit = MIN( MAX_ITEMS_IN_PICKER, m_Collector->GetCount() );

        for( int i = 0;  i<limit;  ++i )
        {
            wxString    text;
            item = (*m_Collector)[i];

            text = item->GetSelectMenuText();

            BITMAP_DEF xpm = item->GetMenuImage();

            AddMenuItem( &itemMenu, ID_POPUP_PCB_ITEM_SELECTION_START + i, text, KiBitmap( xpm ) );
        }

        /* @todo: rather than assignment to true, these should be increment and decrement
         * operators throughout _everywhere_.
         *  That way we can handle nesting.
         *  But I tried that and found there cases where the assignment to true (converted to
         * a m_IgnoreMouseEvents++ )
         *  was not balanced with the -- (now m_IgnoreMouseEvents=false), so I had to revert.
         *  Somebody should track down these and make them balanced.
         *  DrawPanel->m_IgnoreMouseEvents = true;
         */

        // this menu's handler is void PCB_BASE_FRAME::ProcessItemSelection()
        // and it calls SetCurItem() which in turn calls DisplayInfo() on the item.
        DrawPanel->m_AbortRequest = true;   // changed in false if an item is selected
        PopupMenu( &itemMenu );

        DrawPanel->MoveCursorToCrossHair();

        // The function ProcessItemSelection() has set the current item, return it.
        if( DrawPanel->m_AbortRequest )     // Nothing selected
            item = NULL;
        else
            item = GetCurItem();
    }

    return item;
}

void PCB_EDIT_FRAME::GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey )
{
    wxRealPoint gridSize;
    wxPoint     oldpos;
    wxPoint     pos = GetScreen()->GetNearestGridPosition( aPosition );

    oldpos = GetScreen()->GetCrossHairPosition();

    gridSize = GetScreen()->GetGridSize();

    switch( aHotKey )
    {
    case WXK_NUMPAD8:
    case WXK_UP:
        pos.y -= wxRound( gridSize.y );
        DrawPanel->MoveCursor( pos );
        break;

    case WXK_NUMPAD2:
    case WXK_DOWN:
        pos.y += wxRound( gridSize.y );
        DrawPanel->MoveCursor( pos );
        break;

    case WXK_NUMPAD4:
    case WXK_LEFT:
        pos.x -= wxRound( gridSize.x );
        DrawPanel->MoveCursor( pos );
        break;

    case WXK_NUMPAD6:
    case WXK_RIGHT:
        pos.x += wxRound( gridSize.x );
        DrawPanel->MoveCursor( pos );
        break;

    default:
        break;
    }

    // Put cursor in new position, according to the zoom keys (if any).
    GetScreen()->SetCrossHairPosition( pos );

    /* Put cursor on grid or a pad centre if requested. If the tool DELETE is active the
     * cursor is left off grid this is better to reach items to delete off grid,
     */
    bool   keep_on_grid = true;

    if( GetToolId() == ID_PCB_DELETE_ITEM_BUTT )
        keep_on_grid = false;

    /* Cursor is left off grid if no block in progress and no moving object */
    if( GetScreen()->m_BlockLocate.m_State != STATE_NO_BLOCK )
        keep_on_grid = true;

    EDA_ITEM* DrawStruct = GetScreen()->GetCurItem();

    if( DrawStruct && DrawStruct->m_Flags )
        keep_on_grid = true;

    if( keep_on_grid )
    {
        wxPoint on_grid = GetScreen()->GetNearestGridPosition( pos );

        wxSize grid;
        grid.x = (int) GetScreen()->GetGridSize().x;
        grid.y = (int) GetScreen()->GetGridSize().y;

        if( Magnetize( m_Pcb, this, GetToolId(), grid, on_grid, &pos ) )
        {
            GetScreen()->SetCrossHairPosition( pos, false );
        }
        else
        {
            // If there's no intrusion and DRC is active, we pass the cursor
            // "as is", and let ShowNewTrackWhenMovingCursor figure out what to do.
            if( !Drc_On || !g_CurrentTrackSegment
              || (BOARD_ITEM*)g_CurrentTrackSegment != this->GetCurItem()
                || !LocateIntrusion( m_Pcb->m_Track, g_CurrentTrackSegment,
                                     GetScreen()->m_Active_Layer, GetScreen()->RefPos( true ) ) )
            {
                GetScreen()->SetCrossHairPosition( on_grid );
            }
        }
    }

    if( oldpos != GetScreen()->GetCrossHairPosition() )
    {
        pos = GetScreen()->GetCrossHairPosition();
        GetScreen()->SetCrossHairPosition( oldpos, false );
        DrawPanel->CrossHairOff( aDC );
        GetScreen()->SetCrossHairPosition( pos, false );
        DrawPanel->CrossHairOn( aDC );

        if( DrawPanel->IsMouseCaptured() )
        {
#ifdef USE_WX_OVERLAY
            wxDCOverlay oDC( DrawPanel->m_overlay, (wxWindowDC*)aDC );
            oDC.Clear();
            DrawPanel->m_mouseCaptureCallback( DrawPanel, aDC, aPosition, false );
#else
            DrawPanel->m_mouseCaptureCallback( DrawPanel, aDC, aPosition, true );
#endif
        }
#ifdef USE_WX_OVERLAY
        else
            DrawPanel->m_overlay.Reset();
#endif
    }

    if( aHotKey )
    {
        OnHotKey( aDC, aHotKey, aPosition );
    }

    UpdateStatusBar();    /* Display new cursor coordinates */
}
<commit_msg>PCBNEW favored module placed on OPPOSITE side selected layer become. Now it select module from selected side if present. Especially handy in contrast view.<commit_after>/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2009 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com
 * Copyright (C) 2011 Wayne Stambaugh <stambaughw@verizon.net>
 * Copyright (C) 1992-2011 KiCad Developers, see AUTHORS.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

/**
 * @file pcbnew/controle.cpp
 */

#include "fctsys.h"
#include "class_drawpanel.h"
#include "wxPcbStruct.h"
#include "pcbcommon.h"
#include "macros.h"

#include "pcbnew_id.h"

#include "class_board.h"
#include "class_module.h"

#include "pcbnew.h"
#include "protos.h"
#include "collectors.h"

//external functions used here:
extern bool Magnetize( BOARD* m_Pcb, PCB_EDIT_FRAME* frame,
                       int aCurrentTool, wxSize grid, wxPoint on_grid, wxPoint* curpos );

/**
 * Function AllAreModulesAndReturnSmallestIfSo
 * tests that all items in the collection are MODULEs and if so, returns the
 * smallest MODULE.
 * @return BOARD_ITEM* - The smallest or NULL.
 */
static BOARD_ITEM* AllAreModulesAndReturnSmallestIfSo( GENERAL_COLLECTOR* aCollector )
{
    int count = aCollector->GetPrimaryCount();     // try to use preferred layer
    if( 0 == count ) count = aCollector->GetCount();

    for( int i = 0; i<count;  ++i )
    {
        if( (*aCollector)[i]->Type() != PCB_MODULE_T )
            return NULL;
    }

    // all are modules, now find smallest MODULE

    int minDim = 0x7FFFFFFF;
    int minNdx = 0;

    for( int i = 0;  i<count;  ++i )
    {
        MODULE* module = (MODULE*) (*aCollector)[i];

        int     lx = module->m_BoundaryBox.GetWidth();
        int     ly = module->m_BoundaryBox.GetHeight();

        int     lmin = MIN( lx, ly );

        if( lmin < minDim )
        {
            minDim = lmin;
            minNdx = i;
        }
    }

    return (*aCollector)[minNdx];
}

BOARD_ITEM* PCB_BASE_FRAME::PcbGeneralLocateAndDisplay( int aHotKeyCode )
{
    BOARD_ITEM* item;

    GENERAL_COLLECTORS_GUIDE guide = GetCollectorsGuide();

    // Assign to scanList the proper item types desired based on tool type
    // or hotkey that is in play.

    const KICAD_T* scanList = NULL;

    if( aHotKeyCode )
    {
        // @todo: add switch here and add calls to PcbGeneralLocateAndDisplay( int aHotKeyCode )
        // when searching is needed from a hotkey handler
    }
    else if( GetToolId() == ID_NO_TOOL_SELECTED )
    {
        switch( m_HTOOL_current_state )
        {
        case ID_TOOLBARH_PCB_MODE_MODULE:
            scanList = GENERAL_COLLECTOR::ModuleItems;
            break;

        default:
            scanList = DisplayOpt.DisplayZonesMode == 0 ?
                       GENERAL_COLLECTOR::AllBoardItems :
                       GENERAL_COLLECTOR::AllButZones;
            break;
        }
    }
    else
    {
        switch( GetToolId() )
        {
        case ID_PCB_SHOW_1_RATSNEST_BUTT:
            scanList = GENERAL_COLLECTOR::PadsOrModules;
            break;

        case ID_TRACK_BUTT:
            scanList = GENERAL_COLLECTOR::Tracks;
            break;

        case ID_PCB_MODULE_BUTT:
            scanList = GENERAL_COLLECTOR::ModuleItems;
            break;

        case ID_PCB_ZONES_BUTT:
            scanList = GENERAL_COLLECTOR::Zones;
            break;

        default:
            scanList = DisplayOpt.DisplayZonesMode == 0 ?
                       GENERAL_COLLECTOR::AllBoardItems :
                       GENERAL_COLLECTOR::AllButZones;
        }
    }

    m_Collector->Collect( m_Pcb, scanList, GetScreen()->RefPos( true ), guide );

#if 0
    // debugging: print out the collected items, showing their priority order too.
    for( int i = 0; i<m_Collector->GetCount();  ++i )
        (*m_Collector)[i]->Show( 0, std::cout );
#endif

    /* Remove redundancies: sometime, zones are found twice,
     * because zones can be filled by overlapping segments (this is a fill option)
     */
    unsigned long timestampzone = 0;

    for( int ii = 0;  ii < m_Collector->GetCount(); ii++ )
    {
        item = (*m_Collector)[ii];

        if( item->Type() != PCB_ZONE_T )
            continue;

        /* Found a TYPE ZONE */
        if( item->m_TimeStamp == timestampzone )    // Remove it, redundant, zone already found
        {
            m_Collector->Remove( ii );
            ii--;
        }
        else
        {
            timestampzone = item->m_TimeStamp;
        }
    }

    if( m_Collector->GetCount() <= 1 )
    {
        item = (*m_Collector)[0];
        SetCurItem( item );
    }

    // If the count is 2, and first item is a pad or module text, and the 2nd item is its
    // parent module:
    else if( m_Collector->GetCount() == 2
             && ( (*m_Collector)[0]->Type() == PCB_PAD_T || (*m_Collector)[0]->Type() ==
                 PCB_MODULE_TEXT_T )
             && (*m_Collector)[1]->Type() == PCB_MODULE_T && (*m_Collector)[0]->GetParent()==
             (*m_Collector)[1] )
    {
        item = (*m_Collector)[0];
        SetCurItem( item );
    }
    // if all are modules, find the smallest one among the primary choices
    else if( ( item = AllAreModulesAndReturnSmallestIfSo( m_Collector ) ) != NULL )
    {
        SetCurItem( item );
    }

    else    // we can't figure out which item user wants, do popup menu so user can choose
    {
        wxMenu itemMenu;

        /* Give a title to the selection menu. This is also a cancel menu item */
        wxMenuItem * item_title = new wxMenuItem( &itemMenu, -1, _( "Selection Clarification" ) );

#ifdef __WINDOWS__
        wxFont bold_font( *wxNORMAL_FONT );
        bold_font.SetWeight( wxFONTWEIGHT_BOLD );
        bold_font.SetStyle( wxFONTSTYLE_ITALIC );
        item_title->SetFont( bold_font );
#endif

        itemMenu.Append( item_title );
        itemMenu.AppendSeparator();

        int limit = MIN( MAX_ITEMS_IN_PICKER, m_Collector->GetCount() );

        for( int i = 0;  i<limit;  ++i )
        {
            wxString    text;
            item = (*m_Collector)[i];

            text = item->GetSelectMenuText();

            BITMAP_DEF xpm = item->GetMenuImage();

            AddMenuItem( &itemMenu, ID_POPUP_PCB_ITEM_SELECTION_START + i, text, KiBitmap( xpm ) );
        }

        /* @todo: rather than assignment to true, these should be increment and decrement
         * operators throughout _everywhere_.
         *  That way we can handle nesting.
         *  But I tried that and found there cases where the assignment to true (converted to
         * a m_IgnoreMouseEvents++ )
         *  was not balanced with the -- (now m_IgnoreMouseEvents=false), so I had to revert.
         *  Somebody should track down these and make them balanced.
         *  DrawPanel->m_IgnoreMouseEvents = true;
         */

        // this menu's handler is void PCB_BASE_FRAME::ProcessItemSelection()
        // and it calls SetCurItem() which in turn calls DisplayInfo() on the item.
        DrawPanel->m_AbortRequest = true;   // changed in false if an item is selected
        PopupMenu( &itemMenu );

        DrawPanel->MoveCursorToCrossHair();

        // The function ProcessItemSelection() has set the current item, return it.
        if( DrawPanel->m_AbortRequest )     // Nothing selected
            item = NULL;
        else
            item = GetCurItem();
    }

    return item;
}

void PCB_EDIT_FRAME::GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey )
{
    wxRealPoint gridSize;
    wxPoint     oldpos;
    wxPoint     pos = GetScreen()->GetNearestGridPosition( aPosition );

    oldpos = GetScreen()->GetCrossHairPosition();

    gridSize = GetScreen()->GetGridSize();

    switch( aHotKey )
    {
    case WXK_NUMPAD8:
    case WXK_UP:
        pos.y -= wxRound( gridSize.y );
        DrawPanel->MoveCursor( pos );
        break;

    case WXK_NUMPAD2:
    case WXK_DOWN:
        pos.y += wxRound( gridSize.y );
        DrawPanel->MoveCursor( pos );
        break;

    case WXK_NUMPAD4:
    case WXK_LEFT:
        pos.x -= wxRound( gridSize.x );
        DrawPanel->MoveCursor( pos );
        break;

    case WXK_NUMPAD6:
    case WXK_RIGHT:
        pos.x += wxRound( gridSize.x );
        DrawPanel->MoveCursor( pos );
        break;

    default:
        break;
    }

    // Put cursor in new position, according to the zoom keys (if any).
    GetScreen()->SetCrossHairPosition( pos );

    /* Put cursor on grid or a pad centre if requested. If the tool DELETE is active the
     * cursor is left off grid this is better to reach items to delete off grid,
     */
    bool   keep_on_grid = true;

    if( GetToolId() == ID_PCB_DELETE_ITEM_BUTT )
        keep_on_grid = false;

    /* Cursor is left off grid if no block in progress and no moving object */
    if( GetScreen()->m_BlockLocate.m_State != STATE_NO_BLOCK )
        keep_on_grid = true;

    EDA_ITEM* DrawStruct = GetScreen()->GetCurItem();

    if( DrawStruct && DrawStruct->m_Flags )
        keep_on_grid = true;

    if( keep_on_grid )
    {
        wxPoint on_grid = GetScreen()->GetNearestGridPosition( pos );

        wxSize grid;
        grid.x = (int) GetScreen()->GetGridSize().x;
        grid.y = (int) GetScreen()->GetGridSize().y;

        if( Magnetize( m_Pcb, this, GetToolId(), grid, on_grid, &pos ) )
        {
            GetScreen()->SetCrossHairPosition( pos, false );
        }
        else
        {
            // If there's no intrusion and DRC is active, we pass the cursor
            // "as is", and let ShowNewTrackWhenMovingCursor figure out what to do.
            if( !Drc_On || !g_CurrentTrackSegment
              || (BOARD_ITEM*)g_CurrentTrackSegment != this->GetCurItem()
                || !LocateIntrusion( m_Pcb->m_Track, g_CurrentTrackSegment,
                                     GetScreen()->m_Active_Layer, GetScreen()->RefPos( true ) ) )
            {
                GetScreen()->SetCrossHairPosition( on_grid );
            }
        }
    }

    if( oldpos != GetScreen()->GetCrossHairPosition() )
    {
        pos = GetScreen()->GetCrossHairPosition();
        GetScreen()->SetCrossHairPosition( oldpos, false );
        DrawPanel->CrossHairOff( aDC );
        GetScreen()->SetCrossHairPosition( pos, false );
        DrawPanel->CrossHairOn( aDC );

        if( DrawPanel->IsMouseCaptured() )
        {
#ifdef USE_WX_OVERLAY
            wxDCOverlay oDC( DrawPanel->m_overlay, (wxWindowDC*)aDC );
            oDC.Clear();
            DrawPanel->m_mouseCaptureCallback( DrawPanel, aDC, aPosition, false );
#else
            DrawPanel->m_mouseCaptureCallback( DrawPanel, aDC, aPosition, true );
#endif
        }
#ifdef USE_WX_OVERLAY
        else
            DrawPanel->m_overlay.Reset();
#endif
    }

    if( aHotKey )
    {
        OnHotKey( aDC, aHotKey, aPosition );
    }

    UpdateStatusBar();    /* Display new cursor coordinates */
}
<|endoftext|>


<commit_before>		/*************************/
		/* affichage des modules */
		/*************************/

#include "fctsys.h"
#include "gr_basic.h"

#include "common.h"
#include "pcbnew.h"
#include "trigo.h"

#ifdef PCBNEW
#include "drag.h"
#endif

#ifdef CVPCB
#include "cvpcb.h"
#endif

/* Police des caracteres de la routine de trace des textes */
extern char *graphic_fonte_shape[];

#include "protos.h"

#define L_MIN_DESSIN 1 /* seuil de largeur des segments pour trace autre que filaire */

/* fonctions locales : */

/******************************************************************/
void Trace_Pads_Only(WinEDA_DrawPanel * panel, wxDC * DC, MODULE * Module,
						int ox, int oy,
						int MasqueLayer,int draw_mode)
/******************************************************************/

/* Trace les pads d'un module en mode SKETCH.
	Utilisee pour afficher les pastilles d'un module lorsque celui ci n'est
	pas affiche par les options d'affichage des Modules

	Les pads affiches doivent apparaitre sur les couches donnees par
	MasqueLayer
*/
{
int tmp;
D_PAD * pt_pad ;
PCB_SCREEN * screen;
WinEDA_BasePcbFrame * frame;

	screen = (PCB_SCREEN *) panel->GetScreen();
	frame = (WinEDA_BasePcbFrame *) panel->m_Parent;

	tmp = frame->m_DisplayPadFill;
	frame->m_DisplayPadFill = FALSE;

	/* trace des pastilles */
	pt_pad = Module->m_Pads;
	for( ; pt_pad != NULL; pt_pad = (D_PAD*) pt_pad->Pnext )
		{
		if( (pt_pad->m_Masque_Layer & MasqueLayer) == 0 ) continue;
		pt_pad->Draw(panel, DC, wxPoint(ox,oy), draw_mode);
		}

	frame->m_DisplayPadFill = tmp;
}

<commit_msg>beautified<commit_after>/*************************/
/* affichage des modules */
/*************************/

#include "fctsys.h"
#include "gr_basic.h"

#include "common.h"
#include "pcbnew.h"
#include "trigo.h"

#ifdef PCBNEW
#include "drag.h"
#endif

#ifdef CVPCB
#include "cvpcb.h"
#endif

/* Police des caracteres de la routine de trace des textes */
extern char* graphic_fonte_shape[];

#include "protos.h"

#define L_MIN_DESSIN 1 /* seuil de largeur des segments pour trace autre que filaire */

/* fonctions locales : */

/******************************************************************/
void Trace_Pads_Only( WinEDA_DrawPanel* panel, wxDC* DC, MODULE* Module,
                      int ox, int oy,
                      int MasqueLayer, int draw_mode )
/******************************************************************/

/* Trace les pads d'un module en mode SKETCH.
 *  Utilisee pour afficher les pastilles d'un module lorsque celui ci n'est
 *  pas affiche par les options d'affichage des Modules
 *
 *  Les pads affiches doivent apparaitre sur les couches donnees par
 *  MasqueLayer
 */
{
    int                  tmp;
    D_PAD*               pt_pad;
    PCB_SCREEN*          screen;
    WinEDA_BasePcbFrame* frame;

    screen = (PCB_SCREEN*) panel->GetScreen();
    frame  = (WinEDA_BasePcbFrame*) panel->m_Parent;

    tmp = frame->m_DisplayPadFill;
    frame->m_DisplayPadFill = FALSE;

    /* trace des pastilles */
    pt_pad = Module->m_Pads;
    for( ; pt_pad != NULL; pt_pad = (D_PAD*) pt_pad->Pnext )
    {
        if( (pt_pad->m_Masque_Layer & MasqueLayer) == 0 )
            continue;
        pt_pad->Draw( panel, DC, wxPoint( ox, oy ), draw_mode );
    }

    frame->m_DisplayPadFill = tmp;
}
<|endoftext|>