<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifdef WNT
#include <windows.h>
#endif

#include <cstdlib>
#include <iostream>
#include <string>
#include <sal/types.h>
#include "cppunittester/protectorfactory.hxx"
#include "osl/module.h"
#include "osl/module.hxx"
#include "osl/thread.h"
#include "rtl/process.h"
#include "rtl/string.h"
#include "rtl/string.hxx"
#include "rtl/textcvt.h"
#include "rtl/ustring.hxx"
#include "sal/main.h"

#include "cppunit/CompilerOutputter.h"
#include "cppunit/Exception.h"
#include "cppunit/TestFailure.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/plugin/PlugInManager.h"
#include "cppunit/plugin/DynamicLibraryManagerException.h"
#include "cppunit/portability/Stream.h"

#include "boost/noncopyable.hpp"
#include <boost/scoped_array.hpp>
#include "boost/static_assert.hpp"

namespace {

void usageFailure() {
    std::cerr
        << ("Usage: cppunittester (--protector <shared-library-path>"
            " <function-symbol>)* <shared-library-path>")
        << std::endl;
    std::exit(EXIT_FAILURE);
}

rtl::OUString getArgument(sal_Int32 index) {
    rtl::OUString arg;
    rtl_getAppCommandArg(index, &arg.pData);
    return arg;
}

std::string convertLazy(rtl::OUString const & s16) {
    rtl::OString s8(rtl::OUStringToOString(s16, osl_getThreadTextEncoding()));
    BOOST_STATIC_ASSERT(sizeof (sal_Int32) <= sizeof (std::string::size_type));
        // ensure following cast is legitimate
    return std::string(
        s8.getStr(), static_cast< std::string::size_type >(s8.getLength()));
}

#if defined TIMETESTS
//Output how long each test took
class TimingListener
    : public CppUnit::TestListener
    , private boost::noncopyable
{
public:
    void startTest( CppUnit::Test *) SAL_OVERRIDE
    {
        m_nStartTime = osl_getGlobalTimer();
    }

    void endTest( CppUnit::Test *test ) SAL_OVERRIDE
    {
        sal_uInt32 nEndTime = osl_getGlobalTimer();
        std::cout << test->getName() << ": " << nEndTime-m_nStartTime
            << "ms" << std::endl;
    }

private:
    sal_uInt32 m_nStartTime;
};
#endif

#ifdef UNX
#include <stdlib.h>
// Setup an env variable so that temp file (or other) can
// have a usefull value to identify the source
class EyecatcherListener
    : public CppUnit::TestListener
    , private boost::noncopyable
{
public:
    void startTest( CppUnit::Test* test) SAL_OVERRIDE
    {
        boost::scoped_array<char> tn(new char [ test->getName().length() + 2 ]);
        strcpy(tn.get(), test->getName().c_str());
        int len = strlen(tn.get());
        for(int i = 0; i < len; i++)
        {
            if(!isalnum(tn[i]))
            {
                tn[i] = '_';
            }
        }
        tn[len] = '_';
        tn[len + 1] = 0;
        setenv("LO_TESTNAME", tn.get(), true);
    }

    void endTest( CppUnit::Test* /* test */ ) SAL_OVERRIDE
    {
    }
};
#endif

class LogFailuresAsTheyHappen : public CppUnit::TestListener
{
public:
    virtual void addFailure( const CppUnit::TestFailure &failure ) SAL_OVERRIDE
    {
        printFailureLocation( failure.sourceLine() );
        printFailedTestName( failure );
        printFailureMessage( failure );
    }

private:
    void printFailureLocation( const CppUnit::SourceLine &sourceLine )
    {
        if ( !sourceLine.isValid() )
            std::cerr << "unknown:0:";
        else
            std::cerr << sourceLine.fileName() << ":" << sourceLine.lineNumber() << ":";
    }

    void printFailedTestName( const CppUnit::TestFailure &failure )
    {
        std::cerr << failure.failedTestName() << std::endl;
    }

    void printFailureMessage( const CppUnit::TestFailure &failure )
    {
        std::cerr << failure.thrownException()->message().shortDescription() << std::endl;
        std::cerr << failure.thrownException()->message().details() << std::endl;
    }
};

//Allow the whole uniting testing framework to be run inside a "Protector"
//which knows about uno exceptions, so it can print the content of the
//exception before falling over and dying
class CPPUNIT_API ProtectedFixtureFunctor
    : public CppUnit::Functor
    , private boost::noncopyable
{
private:
    const std::string &testlib;
    const std::string &args;
    std::vector<CppUnit::Protector *> &protectors;
    CppUnit::TestResult &result;
public:
    ProtectedFixtureFunctor(const std::string& testlib_, const std::string &args_, std::vector<CppUnit::Protector*> &protectors_, CppUnit::TestResult &result_)
        : testlib(testlib_)
        , args(args_)
        , protectors(protectors_)
        , result(result_)
    {
    }
    bool run() const
    {
#ifdef DISABLE_DYNLOADING

        // NOTE: Running cppunit unit tests on iOS was something I did
        // only very early (several years ago) when starting porting
        // this stuff to iOS. The complicated mechanisms to do build
        // such unit test single executables have surely largely
        // bit-rotted or been semi-intentionally broken since. This
        // stuff here left for information only. --tml 2014.

        // For iOS cppunit plugins aren't really "plugins" (shared
        // libraries), but just static archives. In the real main
        // program of a cppunit app, which calls the lo_main() that
        // the SAL_IMPLEMENT_MAIN() below expands to, we specifically
        // call the initialize methods of the CppUnitTestPlugIns that
        // we statically link to the app executable.
#else
        CppUnit::PlugInManager manager;
        try {
            manager.load(testlib, args);
        } catch (const CppUnit::DynamicLibraryManagerException &e) {
            std::cerr << "DynamicLibraryManagerException: \"" << e.what() << "\"\n";
#ifdef WIN32
            const char *pPath = getenv ("PATH");
            if (pPath && strlen (pPath) > 256)
            {
                std::cerr << "Windows has significant build problems with long PATH variables ";
                std::cerr << "please check your PATH variable and re-autogen.\n";
            }
#endif
            std::cerr << "Path is '" << getenv("PATH") << "'\n";
            return false;
        }
#endif

        CppUnit::TestResultCollector collector;
        result.addListener(&collector);

        LogFailuresAsTheyHappen logger;
        result.addListener(&logger);

#ifdef TIMETESTS
        TimingListener timer;
        result.addListener(&timer);
#endif

#ifdef UNX
        EyecatcherListener eye;
        result.addListener(&eye);
#endif
        for (size_t i = 0; i < protectors.size(); ++i)
            result.pushProtector(protectors[i]);

        {
            CppUnit::TestRunner runner;
            runner.addTest(
                CppUnit::TestFactoryRegistry::getRegistry().makeTest());
            runner.run(result);
        }

        for (size_t i = 0; i < protectors.size(); ++i)
            result.popProtector();

        CppUnit::CompilerOutputter outputter(&collector, CppUnit::stdCErr());
        outputter.setNoWrap();
        outputter.write();
        return collector.wasSuccessful();
    }
    virtual bool operator()() const SAL_OVERRIDE
    {
        return run();
    }
};

}

SAL_IMPLEMENT_MAIN() {
#ifdef WNT
    //Disable Dr-Watson in order to crash simply without popup dialogs under
    //windows
    DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
    SetErrorMode(SEM_NOGPFAULTERRORBOX|dwMode);
#ifdef _DEBUG // These functions are present only in the debgging runtime
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#endif
#endif

    std::vector<CppUnit::Protector *> protectors;
    CppUnit::TestResult result;
    std::string args;
    std::string testlib;
    sal_uInt32 index = 0;
    while (index < rtl_getAppCommandArgCount())
    {
        rtl::OUString arg = getArgument(index);
        if ( arg != "--protector" )
        {
            if (testlib.empty())
            {
                testlib = rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr();
                args += testlib;
            }
            else
            {
                args += ' ';
                args += rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr();
            }
            ++index;
            continue;
        }
        if (rtl_getAppCommandArgCount() - index < 3) {
            usageFailure();
        }
        rtl::OUString lib(getArgument(index + 1));
        rtl::OUString sym(getArgument(index + 2));
#ifndef DISABLE_DYNLOADING
        osl::Module mod(lib, SAL_LOADMODULE_GLOBAL);
        oslGenericFunction fn = mod.getFunctionSymbol(sym);
        mod.release();
#else
        oslGenericFunction fn = 0;
        if (sym == "unoexceptionprotector")
            fn = (oslGenericFunction) unoexceptionprotector;
        else if (sym == "unobootstrapprotector")
            fn = (oslGenericFunction) unobootstrapprotector;
        else if (sym == "vclbootstrapprotector")
            fn = (oslGenericFunction) vclbootstrapprotector;
        else
        {
            std::cerr
                << "Only unoexceptionprotector or unobootstrapprotector protectors allowed"
                << std::endl;
            std::exit(EXIT_FAILURE);
        }
#endif
        CppUnit::Protector *protector = fn == 0
            ? 0
            : (*reinterpret_cast< cppunittester::ProtectorFactory * >(fn))();
        if (protector == 0) {
            std::cerr
                << "Failure instantiating protector \"" << convertLazy(lib)
                << "\", \"" << convertLazy(sym) << '"' << std::endl;
            std::exit(EXIT_FAILURE);
        }
        protectors.push_back(protector);
        index+=3;
    }

    ProtectedFixtureFunctor tests(testlib, args, protectors, result);
    bool ok = tests.run();

    return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Keep TestFixture alive until outputter is done with it<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifdef WNT
#include <windows.h>
#endif

#include <cstdlib>
#include <iostream>
#include <string>
#include <sal/types.h>
#include "cppunittester/protectorfactory.hxx"
#include "osl/module.h"
#include "osl/module.hxx"
#include "osl/thread.h"
#include "rtl/process.h"
#include "rtl/string.h"
#include "rtl/string.hxx"
#include "rtl/textcvt.h"
#include "rtl/ustring.hxx"
#include "sal/main.h"

#include "cppunit/CompilerOutputter.h"
#include "cppunit/Exception.h"
#include "cppunit/TestFailure.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestRunner.h"
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/plugin/PlugInManager.h"
#include "cppunit/plugin/DynamicLibraryManagerException.h"
#include "cppunit/portability/Stream.h"

#include "boost/noncopyable.hpp"
#include <boost/scoped_array.hpp>
#include "boost/static_assert.hpp"

namespace {

void usageFailure() {
    std::cerr
        << ("Usage: cppunittester (--protector <shared-library-path>"
            " <function-symbol>)* <shared-library-path>")
        << std::endl;
    std::exit(EXIT_FAILURE);
}

rtl::OUString getArgument(sal_Int32 index) {
    rtl::OUString arg;
    rtl_getAppCommandArg(index, &arg.pData);
    return arg;
}

std::string convertLazy(rtl::OUString const & s16) {
    rtl::OString s8(rtl::OUStringToOString(s16, osl_getThreadTextEncoding()));
    BOOST_STATIC_ASSERT(sizeof (sal_Int32) <= sizeof (std::string::size_type));
        // ensure following cast is legitimate
    return std::string(
        s8.getStr(), static_cast< std::string::size_type >(s8.getLength()));
}

#if defined TIMETESTS
//Output how long each test took
class TimingListener
    : public CppUnit::TestListener
    , private boost::noncopyable
{
public:
    void startTest( CppUnit::Test *) SAL_OVERRIDE
    {
        m_nStartTime = osl_getGlobalTimer();
    }

    void endTest( CppUnit::Test *test ) SAL_OVERRIDE
    {
        sal_uInt32 nEndTime = osl_getGlobalTimer();
        std::cout << test->getName() << ": " << nEndTime-m_nStartTime
            << "ms" << std::endl;
    }

private:
    sal_uInt32 m_nStartTime;
};
#endif

#ifdef UNX
#include <stdlib.h>
// Setup an env variable so that temp file (or other) can
// have a usefull value to identify the source
class EyecatcherListener
    : public CppUnit::TestListener
    , private boost::noncopyable
{
public:
    void startTest( CppUnit::Test* test) SAL_OVERRIDE
    {
        boost::scoped_array<char> tn(new char [ test->getName().length() + 2 ]);
        strcpy(tn.get(), test->getName().c_str());
        int len = strlen(tn.get());
        for(int i = 0; i < len; i++)
        {
            if(!isalnum(tn[i]))
            {
                tn[i] = '_';
            }
        }
        tn[len] = '_';
        tn[len + 1] = 0;
        setenv("LO_TESTNAME", tn.get(), true);
    }

    void endTest( CppUnit::Test* /* test */ ) SAL_OVERRIDE
    {
    }
};
#endif

class LogFailuresAsTheyHappen : public CppUnit::TestListener
{
public:
    virtual void addFailure( const CppUnit::TestFailure &failure ) SAL_OVERRIDE
    {
        printFailureLocation( failure.sourceLine() );
        printFailedTestName( failure );
        printFailureMessage( failure );
    }

private:
    void printFailureLocation( const CppUnit::SourceLine &sourceLine )
    {
        if ( !sourceLine.isValid() )
            std::cerr << "unknown:0:";
        else
            std::cerr << sourceLine.fileName() << ":" << sourceLine.lineNumber() << ":";
    }

    void printFailedTestName( const CppUnit::TestFailure &failure )
    {
        std::cerr << failure.failedTestName() << std::endl;
    }

    void printFailureMessage( const CppUnit::TestFailure &failure )
    {
        std::cerr << failure.thrownException()->message().shortDescription() << std::endl;
        std::cerr << failure.thrownException()->message().details() << std::endl;
    }
};

//Allow the whole uniting testing framework to be run inside a "Protector"
//which knows about uno exceptions, so it can print the content of the
//exception before falling over and dying
class CPPUNIT_API ProtectedFixtureFunctor
    : public CppUnit::Functor
    , private boost::noncopyable
{
private:
    const std::string &testlib;
    const std::string &args;
    std::vector<CppUnit::Protector *> &protectors;
    CppUnit::TestResult &result;
public:
    ProtectedFixtureFunctor(const std::string& testlib_, const std::string &args_, std::vector<CppUnit::Protector*> &protectors_, CppUnit::TestResult &result_)
        : testlib(testlib_)
        , args(args_)
        , protectors(protectors_)
        , result(result_)
    {
    }
    bool run() const
    {
#ifdef DISABLE_DYNLOADING

        // NOTE: Running cppunit unit tests on iOS was something I did
        // only very early (several years ago) when starting porting
        // this stuff to iOS. The complicated mechanisms to do build
        // such unit test single executables have surely largely
        // bit-rotted or been semi-intentionally broken since. This
        // stuff here left for information only. --tml 2014.

        // For iOS cppunit plugins aren't really "plugins" (shared
        // libraries), but just static archives. In the real main
        // program of a cppunit app, which calls the lo_main() that
        // the SAL_IMPLEMENT_MAIN() below expands to, we specifically
        // call the initialize methods of the CppUnitTestPlugIns that
        // we statically link to the app executable.
#else
        CppUnit::PlugInManager manager;
        try {
            manager.load(testlib, args);
        } catch (const CppUnit::DynamicLibraryManagerException &e) {
            std::cerr << "DynamicLibraryManagerException: \"" << e.what() << "\"\n";
#ifdef WIN32
            const char *pPath = getenv ("PATH");
            if (pPath && strlen (pPath) > 256)
            {
                std::cerr << "Windows has significant build problems with long PATH variables ";
                std::cerr << "please check your PATH variable and re-autogen.\n";
            }
#endif
            std::cerr << "Path is '" << getenv("PATH") << "'\n";
            return false;
        }
#endif

        for (size_t i = 0; i < protectors.size(); ++i)
            result.pushProtector(protectors[i]);

        bool success;
        {
            CppUnit::TestResultCollector collector;
            result.addListener(&collector);

            LogFailuresAsTheyHappen logger;
            result.addListener(&logger);

#ifdef TIMETESTS
            TimingListener timer;
            result.addListener(&timer);
#endif

#ifdef UNX
            EyecatcherListener eye;
            result.addListener(&eye);
#endif

            CppUnit::TestRunner runner;
            runner.addTest(
                CppUnit::TestFactoryRegistry::getRegistry().makeTest());
            runner.run(result);

            CppUnit::CompilerOutputter outputter(&collector, CppUnit::stdCErr());
            outputter.setNoWrap();
            outputter.write();
            success = collector.wasSuccessful();
        }

        for (size_t i = 0; i < protectors.size(); ++i)
            result.popProtector();

        return success;
    }
    virtual bool operator()() const SAL_OVERRIDE
    {
        return run();
    }
};

}

SAL_IMPLEMENT_MAIN() {
#ifdef WNT
    //Disable Dr-Watson in order to crash simply without popup dialogs under
    //windows
    DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
    SetErrorMode(SEM_NOGPFAULTERRORBOX|dwMode);
#ifdef _DEBUG // These functions are present only in the debgging runtime
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#endif
#endif

    std::vector<CppUnit::Protector *> protectors;
    CppUnit::TestResult result;
    std::string args;
    std::string testlib;
    sal_uInt32 index = 0;
    while (index < rtl_getAppCommandArgCount())
    {
        rtl::OUString arg = getArgument(index);
        if ( arg != "--protector" )
        {
            if (testlib.empty())
            {
                testlib = rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr();
                args += testlib;
            }
            else
            {
                args += ' ';
                args += rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr();
            }
            ++index;
            continue;
        }
        if (rtl_getAppCommandArgCount() - index < 3) {
            usageFailure();
        }
        rtl::OUString lib(getArgument(index + 1));
        rtl::OUString sym(getArgument(index + 2));
#ifndef DISABLE_DYNLOADING
        osl::Module mod(lib, SAL_LOADMODULE_GLOBAL);
        oslGenericFunction fn = mod.getFunctionSymbol(sym);
        mod.release();
#else
        oslGenericFunction fn = 0;
        if (sym == "unoexceptionprotector")
            fn = (oslGenericFunction) unoexceptionprotector;
        else if (sym == "unobootstrapprotector")
            fn = (oslGenericFunction) unobootstrapprotector;
        else if (sym == "vclbootstrapprotector")
            fn = (oslGenericFunction) vclbootstrapprotector;
        else
        {
            std::cerr
                << "Only unoexceptionprotector or unobootstrapprotector protectors allowed"
                << std::endl;
            std::exit(EXIT_FAILURE);
        }
#endif
        CppUnit::Protector *protector = fn == 0
            ? 0
            : (*reinterpret_cast< cppunittester::ProtectorFactory * >(fn))();
        if (protector == 0) {
            std::cerr
                << "Failure instantiating protector \"" << convertLazy(lib)
                << "\", \"" << convertLazy(sym) << '"' << std::endl;
            std::exit(EXIT_FAILURE);
        }
        protectors.push_back(protector);
        index+=3;
    }

    ProtectedFixtureFunctor tests(testlib, args, protectors, result);
    bool ok = tests.run();

    return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// DrawPolygon.cpp : ܼ  α׷   մϴ.
//

#include "stdafx.h"
#include "NamsGraphics.h"

void Reshape(int w, int h)
{
	glLoadIdentity();
	glViewport(0, 0, w, h);
	gluOrtho2D(0.0, 100.0, 0.0, 100.0);
}

void Display()
{
	glClear(GL_COLOR_BUFFER_BIT);
	glShadeModel(GL_FLAT);

	GLdouble centerX, centerY;
	const GLdouble radius = 25.0;

	// Draw Triangle //
	centerX = 25.0, centerY = 75.0;
	DrawRegularPolygon_2D(centerX, centerY, radius, 3);

	// Draw Pentagon //
	centerX = 75.0, centerY = 75.0;
	DrawRegularPolygon_2D(centerX, centerY, radius, 6);

	// Draw Hexagon //
	centerX = 25.0, centerY = 25.0;
	DrawRegularPolygon_2D(centerX, centerY, radius, 8);

	// Draw Dodecagon //
	centerX = 75.0, centerY = 25.0;
	DrawRegularPolygon_2D(centerX, centerY, radius, 12);

	glutSwapBuffers();
}

int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutCreateWindow("2013210111");
	//glutCreateWindow("Modeling and Renerding Equilateral Polygon");
	glutReshapeFunc(Reshape);
	glutDisplayFunc(Display);
	glutMainLoop();
	return 0;
}

<commit_msg>penta is 5, hexa is 6<commit_after>// DrawPolygon.cpp : ܼ  α׷   մϴ.
//

#include "stdafx.h"
#include "NamsGraphics.h"

void Reshape(int w, int h)
{
	glLoadIdentity();
	glViewport(0, 0, w, h);
	gluOrtho2D(0.0, 100.0, 0.0, 100.0);
}

void Display()
{
	glClear(GL_COLOR_BUFFER_BIT);
	glShadeModel(GL_FLAT);

	GLdouble centerX, centerY;
	const GLdouble radius = 25.0;

	// Draw Triangle //
	centerX = 25.0, centerY = 75.0;
	DrawRegularPolygon_2D(centerX, centerY, radius, 3);

	// Draw Pentagon //
	centerX = 75.0, centerY = 75.0;
	DrawRegularPolygon_2D(centerX, centerY, radius, 5);

	// Draw Hexagon //
	centerX = 25.0, centerY = 25.0;
	DrawRegularPolygon_2D(centerX, centerY, radius, 6);

	// Draw Dodecagon //
	centerX = 75.0, centerY = 25.0;
	DrawRegularPolygon_2D(centerX, centerY, radius, 12);

	glutSwapBuffers();
}

int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutCreateWindow("2013210111");
	//glutCreateWindow("Modeling and Renerding Equilateral Polygon");
	glutReshapeFunc(Reshape);
	glutDisplayFunc(Display);
	glutMainLoop();
	return 0;
}

<|endoftext|>


<commit_before>#ifndef __PY2CPP_HPP__
#define __PY2CPP_HPP__

#include <cassert>
#include <climits>
#include <sstream>
#include <stdexcept>
#include <typeinfo>

#include <map>
#include <set>
#include <string>
#include <tuple>
#include <vector>

#include <Python.h>

namespace dubzzz {
namespace Py2Cpp {

template <class T>
struct CppBuilder
{
  T operator() (PyObject* pyo)
  {
    assert(pyo);

    std::ostringstream oss;
    oss << "No conversion implemented to convert PyObject* into " << typeid(T).name();

    throw std::invalid_argument(oss.str());
    return T {};
  }
};

template <>
struct CppBuilder<PyObject*>
{
  PyObject* operator() (PyObject* pyo)
  {
    assert(pyo);
    return pyo;
  }
};

template <>
struct CppBuilder<bool>
{
  bool operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyBool_Check(pyo))
    {
      return pyo == Py_True;
    }
    throw std::invalid_argument("Not a PyBool instance");
  }
};

template <>
struct CppBuilder<int>
{
  int operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      long v { PyLong_AsLong(pyo) };
      if (v < INT_MIN || v > INT_MAX)
      {
        throw std::overflow_error("Out of <int> boundaries");
      }
      return static_cast<int>(v);
    }
    else if (PyInt_Check(pyo))
    {
      long v { PyInt_AS_LONG(pyo) };
      if (v < INT_MIN || v > INT_MAX)
      {
        throw std::overflow_error("Out of <int> boundaries");
      }
      return static_cast<int>(v);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<unsigned int>
{
  unsigned int operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      unsigned long v { PyLong_AsUnsignedLongMask(pyo) };
      if (v > UINT_MAX)
      {
        throw std::overflow_error("Out of <unsigned int> boundaries");
      }
      return static_cast<unsigned int>(v);
    }
    else if (PyInt_Check(pyo))
    {
      unsigned long v { PyInt_AsUnsignedLongMask(pyo) };
      if (v > UINT_MAX)
      {
        throw std::overflow_error("Out of <unsigned int> boundaries");
      }
      return static_cast<int>(v);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<long>
{
  long operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      return PyLong_AsLong(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AS_LONG(pyo);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<unsigned long>
{
  unsigned long operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      return PyLong_AsUnsignedLong(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AsUnsignedLongMask(pyo);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<long long>
{
  long long operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      return PyLong_AsLongLong(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AS_LONG(pyo);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<unsigned long long>
{
  unsigned long long operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      return PyLong_AsUnsignedLongLong(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AsUnsignedLongLongMask(pyo);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<double>
{
  double operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyFloat_Check(pyo))
    {
      return PyFloat_AS_DOUBLE(pyo);
    }
    else if (PyLong_Check(pyo))
    {
      return PyLong_AsDouble(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AS_LONG(pyo);
    }
    throw std::invalid_argument("Neither a PyDouble nor a PyLong instance");
  }
};

template <>
struct CppBuilder<std::string>
{
  std::string operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyUnicode_Check(pyo))
    {
#if PY_MAJOR_VERSION >=3 and PY_MINOR_VERSION >=3
      long unsigned int size {};
      const char* str { PyUnicode_AsUTF8AndSize(pyo, &size) };
#else
      long unsigned int size { PyUnicode_GET_DATA_SIZE(pyo) }; // depreciated since 3.3
      const char* str { PyUnicode_AS_DATA(pyo) }; // depreciated since 3.3
#endif
      return std::string(str, size);
    }
    throw std::invalid_argument("Not a PyUnicode instance");
  }
};

template <class TUPLE, std::size_t pos>
void _feedCppTuple(TUPLE& tuple, PyObject* root)
{}

template <class TUPLE, std::size_t pos, class T, class... Args>
void _feedCppTuple(TUPLE& tuple, PyObject* root)
{

  std::get<pos>(tuple) = CppBuilder<T>()(PyTuple_GetItem(root, pos));
  _feedCppTuple<TUPLE, pos +1, Args...>(tuple, root);
}

template <class... Args>
struct CppBuilder<std::tuple<Args...>>
{
  std::tuple<Args...> operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyTuple_Check(pyo))
    {
      if (PyTuple_Size(pyo) == sizeof...(Args))
      {
        std::tuple<Args...> tuple { std::make_tuple(Args()...) };
        _feedCppTuple<std::tuple<Args...>, 0, Args...>(tuple, pyo);
        return tuple;
      }
      else
      {
        std::ostringstream oss;
        oss << "PyTuple length differs from asked one: "
            << "PyTuple(" << PyTuple_Size(pyo) << ") "
            << "and std::tuple<...>(" << sizeof...(Args) << ")";
        throw std::length_error(oss.str());
      }
    }
    throw std::invalid_argument("Not a PyTuple instance");
  }
};

template <class T>
struct CppBuilder<std::vector<T>>
{
  std::vector<T> operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyList_Check(pyo))
    {
      long size { PyList_Size(pyo) };
      std::vector<T> v(size);
      for (long i { 0 } ; i != size ; ++i)
      {
        v[i] = CppBuilder<T>()(PyList_GetItem(pyo, i));
      }
      return v;
    }
    throw std::invalid_argument("Not a PyList instance");
  }
};

template <class T>
struct CppBuilder<std::set<T>>
{
  std::set<T> operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PySet_Check(pyo))
    {
      long size { PySet_Size(pyo) };
      std::vector<PyObject*> backup(size);
      std::set<T> s;
      for (long i { 0 } ; i != size ; ++i)
      {
        PyObject* popped { PySet_Pop(pyo) };
        backup[i] = popped;
        s.insert(CppBuilder<T>()(popped));
      }
      for (PyObject* popped : backup)
      {
        PySet_Add(pyo, popped);
        Py_DECREF(popped);
      }
      return s;
    }
    throw std::invalid_argument("Not a PySet instance");
  }
};

template <class K, class T>
struct CppBuilder<std::map<K,T>>
{
  std::map<K,T> operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyDict_Check(pyo))
    {
      std::map<K,T> dict;
      PyObject *key, *value;
      Py_ssize_t pos = 0;
      while (PyDict_Next(pyo, &pos, &key, &value))
      {
        dict[CppBuilder<K>()(key)] = CppBuilder<T>()(value);
      }
      return dict;
    }
    throw std::invalid_argument("Not a PyDict instance");
  }
};

}
}

#endif

<commit_msg>Support for: PyObject* to std::deque, std::list, std::forward_list... (from list())<commit_after>#ifndef __PY2CPP_HPP__
#define __PY2CPP_HPP__

#include <cassert>
#include <climits>
#include <sstream>
#include <stdexcept>
#include <typeinfo>

#include <map>
#include <set>
#include <string>
#include <tuple>

#include <Python.h>

namespace dubzzz {
namespace Py2Cpp {

template <class T>
struct CppBuilder;

template <>
struct CppBuilder<PyObject*>
{
  PyObject* operator() (PyObject* pyo)
  {
    assert(pyo);
    return pyo;
  }
};

template <>
struct CppBuilder<bool>
{
  bool operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyBool_Check(pyo))
    {
      return pyo == Py_True;
    }
    throw std::invalid_argument("Not a PyBool instance");
  }
};

template <>
struct CppBuilder<int>
{
  int operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      long v { PyLong_AsLong(pyo) };
      if (v < INT_MIN || v > INT_MAX)
      {
        throw std::overflow_error("Out of <int> boundaries");
      }
      return static_cast<int>(v);
    }
    else if (PyInt_Check(pyo))
    {
      long v { PyInt_AS_LONG(pyo) };
      if (v < INT_MIN || v > INT_MAX)
      {
        throw std::overflow_error("Out of <int> boundaries");
      }
      return static_cast<int>(v);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<unsigned int>
{
  unsigned int operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      unsigned long v { PyLong_AsUnsignedLongMask(pyo) };
      if (v > UINT_MAX)
      {
        throw std::overflow_error("Out of <unsigned int> boundaries");
      }
      return static_cast<unsigned int>(v);
    }
    else if (PyInt_Check(pyo))
    {
      unsigned long v { PyInt_AsUnsignedLongMask(pyo) };
      if (v > UINT_MAX)
      {
        throw std::overflow_error("Out of <unsigned int> boundaries");
      }
      return static_cast<int>(v);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<long>
{
  long operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      return PyLong_AsLong(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AS_LONG(pyo);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<unsigned long>
{
  unsigned long operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      return PyLong_AsUnsignedLong(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AsUnsignedLongMask(pyo);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<long long>
{
  long long operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      return PyLong_AsLongLong(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AS_LONG(pyo);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<unsigned long long>
{
  unsigned long long operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyLong_Check(pyo))
    {
      return PyLong_AsUnsignedLongLong(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AsUnsignedLongLongMask(pyo);
    }
    throw std::invalid_argument("Not a PyLong instance");
  }
};

template <>
struct CppBuilder<double>
{
  double operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyFloat_Check(pyo))
    {
      return PyFloat_AS_DOUBLE(pyo);
    }
    else if (PyLong_Check(pyo))
    {
      return PyLong_AsDouble(pyo);
    }
    else if (PyInt_Check(pyo))
    {
      return PyInt_AS_LONG(pyo);
    }
    throw std::invalid_argument("Neither a PyDouble nor a PyLong instance");
  }
};

template <>
struct CppBuilder<std::string>
{
  std::string operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyUnicode_Check(pyo))
    {
#if PY_MAJOR_VERSION >=3 and PY_MINOR_VERSION >=3
      long unsigned int size {};
      const char* str { PyUnicode_AsUTF8AndSize(pyo, &size) };
#else
      long unsigned int size { PyUnicode_GET_DATA_SIZE(pyo) }; // depreciated since 3.3
      const char* str { PyUnicode_AS_DATA(pyo) }; // depreciated since 3.3
#endif
      return std::string(str, size);
    }
    throw std::invalid_argument("Not a PyUnicode instance");
  }
};

template <class TUPLE, std::size_t pos>
void _feedCppTuple(TUPLE& tuple, PyObject* root)
{}

template <class TUPLE, std::size_t pos, class T, class... Args>
void _feedCppTuple(TUPLE& tuple, PyObject* root)
{

  std::get<pos>(tuple) = CppBuilder<T>()(PyTuple_GetItem(root, pos));
  _feedCppTuple<TUPLE, pos +1, Args...>(tuple, root);
}

template <class... Args>
struct CppBuilder<std::tuple<Args...>>
{
  std::tuple<Args...> operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyTuple_Check(pyo))
    {
      if (PyTuple_Size(pyo) == sizeof...(Args))
      {
        std::tuple<Args...> tuple { std::make_tuple(Args()...) };
        _feedCppTuple<std::tuple<Args...>, 0, Args...>(tuple, pyo);
        return tuple;
      }
      else
      {
        std::ostringstream oss;
        oss << "PyTuple length differs from asked one: "
            << "PyTuple(" << PyTuple_Size(pyo) << ") "
            << "and std::tuple<...>(" << sizeof...(Args) << ")";
        throw std::length_error(oss.str());
      }
    }
    throw std::invalid_argument("Not a PyTuple instance");
  }
};

/**
 * VECTOR has to have the following characteristics:
 *
 * (constructor):
 *    VECTOR(size_type count)
 *    build a vector of size count
 *
 * ::begin()
 * ::end()
 * ::iterator compatible with ++it
 */
template <class VECTOR>
struct CppBuilder
{
  VECTOR operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyList_Check(pyo))
    {
      unsigned int i { 0 };
      VECTOR v(PyList_Size(pyo));
      for (typename VECTOR::iterator it { v.begin() } ; it != v.end() ; ++it, ++i)
      {
        *it = CppBuilder<typename VECTOR::value_type>()(PyList_GetItem(pyo, i));
      }
      return v;
    }
    throw std::invalid_argument("Not a PyList instance");
  }
};

template <class T>
struct CppBuilder<std::set<T>>
{
  std::set<T> operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PySet_Check(pyo))
    {
      long size { PySet_Size(pyo) };
      std::vector<PyObject*> backup(size);
      std::set<T> s;
      for (long i { 0 } ; i != size ; ++i)
      {
        PyObject* popped { PySet_Pop(pyo) };
        backup[i] = popped;
        s.insert(CppBuilder<T>()(popped));
      }
      for (PyObject* popped : backup)
      {
        PySet_Add(pyo, popped);
        Py_DECREF(popped);
      }
      return s;
    }
    throw std::invalid_argument("Not a PySet instance");
  }
};

template <class K, class T>
struct CppBuilder<std::map<K,T>>
{
  std::map<K,T> operator() (PyObject* pyo)
  {
    assert(pyo);
    if (PyDict_Check(pyo))
    {
      std::map<K,T> dict;
      PyObject *key, *value;
      Py_ssize_t pos = 0;
      while (PyDict_Next(pyo, &pos, &key, &value))
      {
        dict[CppBuilder<K>()(key)] = CppBuilder<T>()(value);
      }
      return dict;
    }
    throw std::invalid_argument("Not a PyDict instance");
  }
};

}
}

#endif

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include "qmatrix.h"

#include <assert.h>
#include <cmath>
#include <iostream>

namespace fasttext {

QMatrix::QMatrix() : qnorm_(false),
  m_(0), n_(0), codesize_(0) {}

QMatrix::QMatrix(const Matrix& mat, int32_t dsub, bool qnorm)
      : qnorm_(qnorm), m_(mat.m_), n_(mat.n_),
        codesize_(m_ * std::ceil(n_ / dsub)) {
  codes_ = new uint8_t[codesize_];
  pq_ = std::unique_ptr<ProductQuantizer>( new ProductQuantizer(n_, dsub));
  if (qnorm_) {
    norm_codes_ = new uint8_t[m_];
    npq_ = std::unique_ptr<ProductQuantizer>( new ProductQuantizer(1, 1));
  }
  quantize(mat);
}

QMatrix::~QMatrix() {
  if (codesize_) { delete[] codes_; }
  if (qnorm_) { delete[] norm_codes_; }
}

void QMatrix::quantizeNorm(const Vector& norms) {
  assert(qnorm_);
  assert(norms.m_ == m_);
  auto dataptr = norms.data_;
  npq_->train(m_, dataptr);
  npq_->compute_codes(dataptr, norm_codes_, m_);
}

void QMatrix::quantize(const Matrix& matrix) {
  assert(n_ == matrix.n_);
  assert(m_ == matrix.m_);
  Matrix temp(matrix);
  if (qnorm_) {
    Vector norms(temp.m_);
    temp.l2NormRow(norms);
    temp.divideRow(norms);
    quantizeNorm(norms);
  }
  auto dataptr = temp.data_;
  pq_->train(m_, dataptr);
  pq_->compute_codes(dataptr, codes_, m_);
}

void QMatrix::addToVector(Vector& x, int32_t t) const {
  real norm = 1;
  if (qnorm_) {
    norm = npq_->get_centroids(0, norm_codes_[t])[0];
  }
  pq_->addcode(x, codes_, t, norm);
}

real QMatrix::dotRow(const Vector& vec, int64_t i) const {
  assert(i >= 0);
  assert(i < m_);
  assert(vec.size() == n_);
  real norm = 1;
  if (qnorm_) {
    norm = npq_->get_centroids(0, norm_codes_[i])[0];
  }
  return pq_->mulcode(vec, codes_, i, norm);
}

int64_t QMatrix::getM() const {
  return m_;
}

int64_t QMatrix::getN() const {
  return n_;
}

void QMatrix::save(std::ostream& out) {
    out.write((char*) &qnorm_, sizeof(qnorm_));
    out.write((char*) &m_, sizeof(m_));
    out.write((char*) &n_, sizeof(n_));
    out.write((char*) &codesize_, sizeof(codesize_));
    out.write((char*) codes_, codesize_ * sizeof(uint8_t));
    pq_->save(out);
    if (qnorm_) {
      out.write((char*) norm_codes_, m_ * sizeof(uint8_t));
      npq_->save(out);
    }
}

void QMatrix::load(std::istream& in) {
    in.read((char*) &qnorm_, sizeof(qnorm_));
    in.read((char*) &m_, sizeof(m_));
    in.read((char*) &n_, sizeof(n_));
    in.read((char*) &codesize_, sizeof(codesize_));
    codes_ = new uint8_t[codesize_];
    in.read((char*) codes_, codesize_ * sizeof(uint8_t));
    pq_ = std::unique_ptr<ProductQuantizer>( new ProductQuantizer());
    pq_->load(in);
    if (qnorm_) {
      norm_codes_ = new uint8_t[m_];
      in.read((char*) norm_codes_, m_ * sizeof(uint8_t));
      npq_ = std::unique_ptr<ProductQuantizer>( new ProductQuantizer());
      npq_->load(in);
    }
}

}
<commit_msg>Fixes memory allocation and cleanup bugs in QMatrix<commit_after>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include "qmatrix.h"

#include <assert.h>
#include <iostream>

namespace fasttext {

QMatrix::QMatrix() : qnorm_(false),
  m_(0), n_(0), codesize_(0) {}

QMatrix::QMatrix(const Matrix& mat, int32_t dsub, bool qnorm)
      : qnorm_(qnorm), m_(mat.m_), n_(mat.n_),
        codesize_(m_ * ((n_ + dsub - 1) / dsub)) {
  if (codesize_ > 0) {
    codes_ = new uint8_t[codesize_];
  }
  pq_ = std::unique_ptr<ProductQuantizer>( new ProductQuantizer(n_, dsub));
  if (qnorm_) {
    norm_codes_ = new uint8_t[m_];
    npq_ = std::unique_ptr<ProductQuantizer>( new ProductQuantizer(1, 1));
  }
  quantize(mat);
}

QMatrix::~QMatrix() {
  if (codesize_ > 0) {
    delete[] codes_;
  }
  if (qnorm_) { delete[] norm_codes_; }
}

void QMatrix::quantizeNorm(const Vector& norms) {
  assert(qnorm_);
  assert(norms.m_ == m_);
  auto dataptr = norms.data_;
  npq_->train(m_, dataptr);
  npq_->compute_codes(dataptr, norm_codes_, m_);
}

void QMatrix::quantize(const Matrix& matrix) {
  assert(n_ == matrix.n_);
  assert(m_ == matrix.m_);
  Matrix temp(matrix);
  if (qnorm_) {
    Vector norms(temp.m_);
    temp.l2NormRow(norms);
    temp.divideRow(norms);
    quantizeNorm(norms);
  }
  auto dataptr = temp.data_;
  pq_->train(m_, dataptr);
  pq_->compute_codes(dataptr, codes_, m_);
}

void QMatrix::addToVector(Vector& x, int32_t t) const {
  real norm = 1;
  if (qnorm_) {
    norm = npq_->get_centroids(0, norm_codes_[t])[0];
  }
  pq_->addcode(x, codes_, t, norm);
}

real QMatrix::dotRow(const Vector& vec, int64_t i) const {
  assert(i >= 0);
  assert(i < m_);
  assert(vec.size() == n_);
  real norm = 1;
  if (qnorm_) {
    norm = npq_->get_centroids(0, norm_codes_[i])[0];
  }
  return pq_->mulcode(vec, codes_, i, norm);
}

int64_t QMatrix::getM() const {
  return m_;
}

int64_t QMatrix::getN() const {
  return n_;
}

void QMatrix::save(std::ostream& out) {
    out.write((char*) &qnorm_, sizeof(qnorm_));
    out.write((char*) &m_, sizeof(m_));
    out.write((char*) &n_, sizeof(n_));
    out.write((char*) &codesize_, sizeof(codesize_));
    out.write((char*) codes_, codesize_ * sizeof(uint8_t));
    pq_->save(out);
    if (qnorm_) {
      out.write((char*) norm_codes_, m_ * sizeof(uint8_t));
      npq_->save(out);
    }
}

void QMatrix::load(std::istream& in) {
    in.read((char*) &qnorm_, sizeof(qnorm_));
    in.read((char*) &m_, sizeof(m_));
    in.read((char*) &n_, sizeof(n_));
    in.read((char*) &codesize_, sizeof(codesize_));
    codes_ = new uint8_t[codesize_];
    in.read((char*) codes_, codesize_ * sizeof(uint8_t));
    pq_ = std::unique_ptr<ProductQuantizer>( new ProductQuantizer());
    pq_->load(in);
    if (qnorm_) {
      norm_codes_ = new uint8_t[m_];
      in.read((char*) norm_codes_, m_ * sizeof(uint8_t));
      npq_ = std::unique_ptr<ProductQuantizer>( new ProductQuantizer());
      npq_->load(in);
    }
}

}
<|endoftext|>


<commit_before>#include <fstream>
#include <string>
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include <musicbrainz3/mbxmlparser.h>
#include <musicbrainz3/metadata.h>
#include <musicbrainz3/model.h>

using namespace std;
using namespace MusicBrainz;

#include "read_file.h"

class ParseUserTest : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(ParseUserTest);
	CPPUNIT_TEST(testUser);
	CPPUNIT_TEST(testUserTypes);
	CPPUNIT_TEST_SUITE_END();

protected:

	void testUser()
	{
		Metadata *md = MbXmlParser().parse(get_file_contents("../test-data/valid/user/User_1.xml"));
		UserList &ul = md->getUserList();
		CPPUNIT_ASSERT_EQUAL(1, int(ul.size()));
		CPPUNIT_ASSERT_EQUAL(string("matt"), ul[0]->getName());
		CPPUNIT_ASSERT_EQUAL(false, ul[0]->getShowNag());
		CPPUNIT_ASSERT_EQUAL(string(NS_EXT_1 + "AutoEditor"), ul[0]->getTypes()[0]);
		CPPUNIT_ASSERT_EQUAL(string(NS_EXT_1 + "RelationshipEditor"), ul[0]->getTypes()[1]);
	}

	void testUserTypes()
	{
		Metadata *md = MbXmlParser().parse(get_file_contents("../test-data/valid/user/User_1.xml"));
		const vector<string> &types = md->getUserList()[0]->getTypes();
		bool isAutoEditor = false;
		bool isRelationshipEditor = false;
		for (vector<string>::const_iterator i = types.begin(); i != types.end(); i++) {
			if (*i == NS_EXT_1 + "AutoEditor")
				isAutoEditor = true;
			else if (*i == NS_EXT_1 + "RelationshipEditor")
				isRelationshipEditor = true;
			else
				CPPUNIT_FAIL(*i);
		}
		CPPUNIT_ASSERT(isAutoEditor);
		CPPUNIT_ASSERT(isRelationshipEditor);
	}

};

CPPUNIT_TEST_SUITE_REGISTRATION(ParseUserTest);

<commit_msg>Ooops.<commit_after>#include <fstream>
#include <string>
#include <iostream>
#include <cppunit/extensions/HelperMacros.h>
#include <musicbrainz3/mbxmlparser.h>
#include <musicbrainz3/metadata.h>
#include <musicbrainz3/model.h>

using namespace std;
using namespace MusicBrainz;

#include "read_file.h"

class ParseUserTest : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(ParseUserTest);
	CPPUNIT_TEST(testUser);
	CPPUNIT_TEST(testUserTypes);
	CPPUNIT_TEST_SUITE_END();

protected:

	void testUser()
	{
		Metadata *md = MbXmlParser().parse(get_file_contents("../test-data/valid/user/User_1.xml"));
		UserList &ul = md->getUserList();
		CPPUNIT_ASSERT_EQUAL(1, int(ul.size()));
		CPPUNIT_ASSERT_EQUAL(string("matt"), ul[0]->getName());
		CPPUNIT_ASSERT_EQUAL(false, ul[0]->getShowNag());
	}

	void testUserTypes()
	{
		Metadata *md = MbXmlParser().parse(get_file_contents("../test-data/valid/user/User_1.xml"));
		const vector<string> &types = md->getUserList()[0]->getTypes();
		bool isAutoEditor = false;
		bool isRelationshipEditor = false;
		for (vector<string>::const_iterator i = types.begin(); i != types.end(); i++) {
			if (*i == NS_EXT_1 + "AutoEditor")
				isAutoEditor = true;
			else if (*i == NS_EXT_1 + "RelationshipEditor")
				isRelationshipEditor = true;
			else
				CPPUNIT_FAIL(*i);
		}
		CPPUNIT_ASSERT(isAutoEditor);
		CPPUNIT_ASSERT(isRelationshipEditor);
	}

};

CPPUNIT_TEST_SUITE_REGISTRATION(ParseUserTest);

<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE TestRagoneChart
#define BOOST_TEST_MAIN
#include <cap/resistor_capacitor.h>
#include <boost/format.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <fstream>

// TODO: electrochemical device should have method to report its current state
// so that we can call something like
// rc->report(time, os);
void report(double const t, std::shared_ptr<cap::SeriesRC const> rc, std::ostream & os = std::cout)
{
    os<<boost::format("  %10.4f  %10.7f  %10.7f  %10.7f  \n")
        % t
        % rc->I
        % rc->U
        % rc->U_C
        ;
}

namespace cap {

void scan(std::shared_ptr<cap::SeriesRC> rc, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout)
{
    double const ratio           = database->get<double>("ratio"              );
    double const initial_voltage = database->get<double>("initial_voltage"    );
    double const final_voltage   = database->get<double>("final_voltage"      );

    double const start_power     = database->get<double>("power_limit" );
    double const finish_energy   = database->get<double>("energy_limit");
    int    const steps           = database->get<int   >("steps"       );

    double power = start_power;
    for ( ; ; power *= ratio)
    {
        rc->I = -power/initial_voltage;
        rc->reset(initial_voltage);
        // TODO: time step control
        double const guess =
        double time_step = (0.5 * rc->C * rc->U * rc->U) / (power + rc->R * rc->I * rc->I) / steps;
        double voltage = initial_voltage;
        double time = 0.0;
        double energy = 0.0;

        int step = 1;
        for ( ; voltage >= final_voltage; time+=time_step, ++step)
        {
            rc->evolve_one_time_step_constant_power(time_step, -power);
            voltage = rc->U;
            energy -= rc->U * rc->I * time_step; // TODO: trapeze
//            report(time, rc, os);
        }

        os<<boost::format("  %10.7f  %10.7f  %10.7f  %10d \n")
            % power
            % energy
            % time
            % step
            ;
        if (energy <= finish_energy)
            break;
    }
}

} // end namespace cap

BOOST_AUTO_TEST_CASE( test_ragone_chart )
{
    // parse input file
    std::shared_ptr<boost::property_tree::ptree> database =
        std::make_shared<boost::property_tree::ptree>();
    read_xml("input_ragone_chart", *database);

    // build an energy storage system
    double const C          = database->get<double>("capacitance"        );
    double const R_series   = database->get<double>("series_resistance"  );

    std::shared_ptr<cap::SeriesRC> rc =
        std::make_shared<cap::SeriesRC>(R_series, C);

    // scan the system
    std::fstream fout;
    fout.open("ragone_chart_data", std::fstream::out);

    cap::scan(rc, database, fout);
}
<commit_msg>fixing typo<commit_after>#define BOOST_TEST_MODULE TestRagoneChart
#define BOOST_TEST_MAIN
#include <cap/resistor_capacitor.h>
#include <boost/format.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <fstream>

// TODO: electrochemical device should have method to report its current state
// so that we can call something like
// rc->report(time, os);
void report(double const t, std::shared_ptr<cap::SeriesRC const> rc, std::ostream & os = std::cout)
{
    os<<boost::format("  %10.4f  %10.7f  %10.7f  %10.7f  \n")
        % t
        % rc->I
        % rc->U
        % rc->U_C
        ;
}

namespace cap {

void scan(std::shared_ptr<cap::SeriesRC> rc, std::shared_ptr<boost::property_tree::ptree const> database, std::ostream & os = std::cout)
{
    double const ratio           = database->get<double>("ratio"              );
    double const initial_voltage = database->get<double>("initial_voltage"    );
    double const final_voltage   = database->get<double>("final_voltage"      );

    double const start_power     = database->get<double>("power_limit" );
    double const finish_energy   = database->get<double>("energy_limit");
    int    const steps           = database->get<int   >("steps"       );

    double power = start_power;
    for ( ; ; power *= ratio)
    {
        rc->I = -power/initial_voltage;
        rc->reset(initial_voltage);
        // TODO: time step control
        double time_step = (0.5 * rc->C * rc->U * rc->U) / (power + rc->R * rc->I * rc->I) / steps;
        double voltage = initial_voltage;
        double time = 0.0;
        double energy = 0.0;

        int step = 1;
        for ( ; voltage >= final_voltage; time+=time_step, ++step)
        {
            rc->evolve_one_time_step_constant_power(time_step, -power);
            voltage = rc->U;
            energy -= rc->U * rc->I * time_step; // TODO: trapeze
//            report(time, rc, os);
        }

        os<<boost::format("  %10.7f  %10.7f  %10.7f  %10d \n")
            % power
            % energy
            % time
            % step
            ;
        if (energy <= finish_energy)
            break;
    }
}

} // end namespace cap

BOOST_AUTO_TEST_CASE( test_ragone_chart )
{
    // parse input file
    std::shared_ptr<boost::property_tree::ptree> database =
        std::make_shared<boost::property_tree::ptree>();
    read_xml("input_ragone_chart", *database);

    // build an energy storage system
    double const C          = database->get<double>("capacitance"        );
    double const R_series   = database->get<double>("series_resistance"  );

    std::shared_ptr<cap::SeriesRC> rc =
        std::make_shared<cap::SeriesRC>(R_series, C);

    // scan the system
    std::fstream fout;
    fout.open("ragone_chart_data", std::fstream::out);

    cap::scan(rc, database, fout);
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

//#define DEBUG // Debug supression

#include <os>
#include <list>
#include <net/inet4>
#include <vector>

using namespace std;
using namespace net;

std::shared_ptr<net::Inet4<VirtioNet> > inet;

void Service::start()
{
  // Assign an IP-address, using Hårek-mapping :-)
  auto& eth0 = hw::Dev::eth<0,VirtioNet>();
  auto& mac = eth0.mac();

  inet = std::make_shared<net::Inet4<VirtioNet>>(eth0);

  inet->network_config({{ mac.part[2],mac.part[3],mac.part[4],mac.part[5] }},
                       {{ 255,255,0,0 }}, // Netmask
                       {{ 10,0,0,1 }}, // Gateway
                       {{ 8,8,8,8}});  // DNS

  printf("Service IP address: %s \n", inet->ip_addr().str().c_str());

  // UDP
  UDP::port_t port = 4242;
  auto& sock = inet->udp().bind(port);

  sock.onRead([] (UDP::Socket& conn, UDP::addr_t addr, UDP::port_t port,
                  const char* data, int len) -> int {
                INFO("Test 2","Starting UDP-test (got UDP data from %s: %i: %s",
                     addr.str().c_str(), port, data);
                // send the same thing right back!
                const int packets { 600 };

                INFO("TEST 2", "Trying to transmit %i UDP packets at maximum throttle", packets);
                for (int i = 0; i < packets; i++)
                  conn.sendto(addr, port, data, len);
                return 0;
              });

  eth0.on_transmit_queue_available([](size_t s){
      CHECK(1,"There are now %i available buffers", s);
    });

  hw::PIT::instance().onTimeout(200ms,[=](){
      const int packets { 600 };
      INFO("TEST 1", "Trying to transmit %i ethernet packets at maximum throttle", packets);
      for (int i=0; i < packets; i++){
        auto pckt = inet->createPacket(inet->MTU());
        Ethernet::header* hdr = reinterpret_cast<Ethernet::header*>(pckt->buffer());
        hdr->dest.major = Ethernet::addr::BROADCAST_FRAME.major;
        hdr->dest.minor = Ethernet::addr::BROADCAST_FRAME.minor;
        hdr->type = Ethernet::ETH_ARP;
        printf("\t Transmit Queue available: %i \n",
               inet->transmit_queue_available());
        printf("\t Bufstore available: %i \n",
               inet->buffers_available());
        inet->link().transmit(pckt);
      }

      CHECK(1,"Transmission didn't panic");

    });

}
<commit_msg>Updated transmission test to wait for ARP-resolution. Fix #456<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

//#define DEBUG // Debug supression

#include <os>
#include <list>
#include <net/inet4>
#include <vector>

using namespace std;
using namespace net;

std::shared_ptr<net::Inet4<VirtioNet> > inet;

void Service::start()
{
  // Assign an IP-address, using Hårek-mapping :-)
  auto& eth0 = hw::Dev::eth<0,VirtioNet>();
  auto& mac = eth0.mac();

  inet = std::make_shared<net::Inet4<VirtioNet>>(eth0);
  auto& timer = hw::PIT::instance();

  inet->network_config({{ mac.part[2],mac.part[3],mac.part[4],mac.part[5] }},
                       {{ 255,255,0,0 }}, // Netmask
                       {{ 10,0,0,1 }}, // Gateway
                       {{ 8,8,8,8}});  // DNS

  printf("Service IP address: %s \n", inet->ip_addr().str().c_str());

  // UDP
  UDP::port_t port = 4242;
  auto& sock = inet->udp().bind(port);

  sock.onRead([&] (UDP::Socket& conn, UDP::addr_t addr, UDP::port_t port,
                  const char* data, int len) -> int {
                string received = std::string(data,len-1);
                INFO("Test 2","Starting UDP-test (got UDP data from %s: %i: '%s')",
                     addr.str().c_str(), port, received.c_str());

                const int packets { 600 };

                string first_reply {string("Received '") + received +
                    "'. Expect " + to_string(packets) + " packets in 1s\n" };

                // Send the first packet, and then wait for ARP
                conn.sendto(addr, port, first_reply.c_str(), first_reply.size());

                timer.onTimeout(1s, [&conn, addr, port, data, len]() {
                    INFO("Test 2", "Trying to transmit %i UDP packets at maximum throttle", packets);
                    auto bufcount = inet->buffers_available();

                    for (int i = 0; i < packets; i++)
                      conn.sendto(addr, port, data, len);

                    CHECK(1,"UDP-transmission didn't panic");
                    auto bufcount2 = inet->buffers_available();

                    CHECKSERT(bufcount2 < bufcount,
                              "%i buffers available after transmission (Had %i). ",
                              bufcount2, bufcount);

                    INFO("Transmision tests","SUCCESS");
                  });

                return 0;

              });

  eth0.on_transmit_queue_available([](size_t s){
      CHECKSERT(s,"There is now room for %i packets in transmit queue", s);
    });

  timer.onTimeout(200ms,[=](){
      const int packets { 600 };
      INFO("Test 1", "Trying to transmit %i ethernet packets at maximum throttle", packets);
      for (int i=0; i < packets; i++){
        auto pckt = inet->createPacket(inet->MTU());
        Ethernet::header* hdr = reinterpret_cast<Ethernet::header*>(pckt->buffer());
        hdr->dest.major = Ethernet::addr::BROADCAST_FRAME.major;
        hdr->dest.minor = Ethernet::addr::BROADCAST_FRAME.minor;
        hdr->type = Ethernet::ETH_ARP;
        inet->link().transmit(pckt);
      }

      CHECK(1,"Transmission didn't panic");
      INFO("Test 1", "Done. Send some UDP-data to %s:%i to continue test",
           inet->ip_addr().str().c_str(), port);

    });

}
<|endoftext|>


<commit_before>/**
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent project.
*
* iotagent is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with iotagent. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with iot_support at tid dot es
*/
#include <ngsi/QueryContext.h>
#include "ngsi_const.h"
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <stdexcept>

iota::QueryContext::QueryContext(const std::istringstream& str_query) {
  rapidjson::Document document;
  char buffer[str_query.str().length()];
  //memcpy(buffer, str_attribute.c_str(), str_attribute.length());
  strcpy(buffer, str_query.str().c_str());
  if (document.ParseInsitu<0>(buffer).HasParseError()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << document.GetParseError();
    what << "[";
    what << document.GetErrorOffset();
    what << "]";
    throw std::runtime_error(what.str());
  }

  if (!document.HasMember(iota::ngsi::NGSI_ENTITIES.c_str()) ||
      !document[iota::ngsi::NGSI_ENTITIES.c_str()].IsArray()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << "invalid or missing field [";
    what << iota::ngsi::NGSI_ENTITIES;
    what << "]";
    throw std::runtime_error(what.str());
  }
  const rapidjson::Value& entities = document[iota::ngsi::NGSI_ENTITIES.c_str()];
  for (rapidjson::SizeType i = 0; i < entities.Size(); i++) {
    iota::Entity entitiy(entities[i]);
    add_entity(entitiy);
  }

  if (!document.HasMember(iota::ngsi::NGSI_ATTRIBUTES.c_str()) ||
      !document[iota::ngsi::NGSI_ATTRIBUTES.c_str()].IsArray()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << "invalid or missing field [";
    what << iota::ngsi::NGSI_ATTRIBUTES;
    what << "]";
    throw std::runtime_error(what.str());
  }
  const rapidjson::Value& attributes = document["attributes"];

  for (rapidjson::SizeType i = 0; i < attributes.Size(); i++) {
    add_attribute(attributes[i].GetString());
  }

};

iota::QueryContext::QueryContext(const rapidjson::Value& query) {

  if (!query.IsObject() ||
      !query.HasMember(iota::ngsi::NGSI_ENTITIES.c_str()) ||
      !query[iota::ngsi::NGSI_ENTITIES.c_str()].IsArray()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << "invalid or missing field [";
    what << iota::ngsi::NGSI_ENTITIES;
    what << "]";
    throw std::runtime_error(what.str());
  }
  if (!query.HasMember(iota::ngsi::NGSI_ATTRIBUTES.c_str()) ||
      !query[iota::ngsi::NGSI_ATTRIBUTES.c_str()].IsArray()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << "invalid or missing field [";
    what << iota::ngsi::NGSI_ATTRIBUTES;
    what << "]";
    throw std::runtime_error(what.str());
  }

  const rapidjson::Value& entities = query[iota::ngsi::NGSI_ENTITIES.c_str()];
  for (rapidjson::SizeType i = 0; i < entities.Size(); i++) {
    iota::Entity entity(entities[i]);
    add_entity(entity);
  }

  const rapidjson::Value& attributes =
    query[iota::ngsi::NGSI_ATTRIBUTES.c_str()];

  for (rapidjson::SizeType i = 0; i < attributes.Size(); i++) {
    add_attribute(attributes[i].GetString());
  }

};

std::string iota::QueryContext::get_string() {
  rapidjson::StringBuffer buffer;
  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
  Serialize(writer);
  return buffer.GetString();
};

void iota::QueryContext::add_entity(const iota::Entity& entity) {
  _entities.push_back(entity);
};

void iota::QueryContext::add_attribute(const std::string& attribute) {
  _attributes.push_back(attribute);
};

<commit_msg>remove queryContext condition, body with no attributes is alloed<commit_after>/**
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent project.
*
* iotagent is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with iotagent. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with iot_support at tid dot es
*/
#include <ngsi/QueryContext.h>
#include "ngsi_const.h"
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <stdexcept>

iota::QueryContext::QueryContext(const std::istringstream& str_query) {
  rapidjson::Document document;
  char buffer[str_query.str().length()];
  //memcpy(buffer, str_attribute.c_str(), str_attribute.length());
  strcpy(buffer, str_query.str().c_str());
  if (document.ParseInsitu<0>(buffer).HasParseError()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << document.GetParseError();
    what << "[";
    what << document.GetErrorOffset();
    what << "]";
    throw std::runtime_error(what.str());
  }

  if (!document.HasMember(iota::ngsi::NGSI_ENTITIES.c_str()) ||
      !document[iota::ngsi::NGSI_ENTITIES.c_str()].IsArray()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << "invalid or missing field [";
    what << iota::ngsi::NGSI_ENTITIES;
    what << "]";
    throw std::runtime_error(what.str());
  }
  const rapidjson::Value& entities = document[iota::ngsi::NGSI_ENTITIES.c_str()];
  for (rapidjson::SizeType i = 0; i < entities.Size(); i++) {
    iota::Entity entitiy(entities[i]);
    add_entity(entitiy);
  }

  if (document.HasMember(iota::ngsi::NGSI_ATTRIBUTES.c_str()) &&
      !document[iota::ngsi::NGSI_ATTRIBUTES.c_str()].IsArray()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << "invalid or missing field [";
    what << iota::ngsi::NGSI_ATTRIBUTES;
    what << "]";
    throw std::runtime_error(what.str());

  }
  const rapidjson::Value& attributes = document["attributes"];

  for (rapidjson::SizeType i = 0; i < attributes.Size(); i++) {
    add_attribute(attributes[i].GetString());
  }

};

iota::QueryContext::QueryContext(const rapidjson::Value& query) {

  if (!query.IsObject() ||
      !query.HasMember(iota::ngsi::NGSI_ENTITIES.c_str()) ||
      !query[iota::ngsi::NGSI_ENTITIES.c_str()].IsArray()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << "invalid or missing field [";
    what << iota::ngsi::NGSI_ENTITIES;
    what << "]";
    throw std::runtime_error(what.str());
  }
  if (!query.HasMember(iota::ngsi::NGSI_ATTRIBUTES.c_str()) ||
      !query[iota::ngsi::NGSI_ATTRIBUTES.c_str()].IsArray()) {
    std::ostringstream what;
    what << "QueryContext: ";
    what << "invalid or missing field [";
    what << iota::ngsi::NGSI_ATTRIBUTES;
    what << "]";
    throw std::runtime_error(what.str());
  }

  const rapidjson::Value& entities = query[iota::ngsi::NGSI_ENTITIES.c_str()];
  for (rapidjson::SizeType i = 0; i < entities.Size(); i++) {
    iota::Entity entity(entities[i]);
    add_entity(entity);
  }

  const rapidjson::Value& attributes =
    query[iota::ngsi::NGSI_ATTRIBUTES.c_str()];

  for (rapidjson::SizeType i = 0; i < attributes.Size(); i++) {
    add_attribute(attributes[i].GetString());
  }

};

std::string iota::QueryContext::get_string() {
  rapidjson::StringBuffer buffer;
  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
  Serialize(writer);
  return buffer.GetString();
};

void iota::QueryContext::add_entity(const iota::Entity& entity) {
  _entities.push_back(entity);
};

void iota::QueryContext::add_attribute(const std::string& attribute) {
  _attributes.push_back(attribute);
};

<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <consensus/validation.h>
#include <net.h>
#include <net_processing.h>
#include <node/context.h>
#include <validation.h>
#include <validationinterface.h>
#include <node/transaction.h>

#include <future>

static TransactionError HandleATMPError(const TxValidationState& state, std::string& err_string_out)
{
    err_string_out = state.ToString();
    if (state.IsInvalid()) {
        if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
            return TransactionError::MISSING_INPUTS;
        }
        return TransactionError::MEMPOOL_REJECTED;
    } else {
        return TransactionError::MEMPOOL_ERROR;
    }
}

TransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback)
{
    // BroadcastTransaction can be called by either sendrawtransaction RPC or wallet RPCs.
    // node.peerman is assigned both before chain clients and before RPC server is accepting calls,
    // and reset after chain clients and RPC sever are stopped. node.peerman should never be null here.
    assert(node.peerman);
    assert(node.mempool);
    std::promise<void> promise;
    uint256 hashTx = tx->GetHash();
    bool callback_set = false;

    { // cs_main scope
    assert(node.chainman);
    LOCK(cs_main);
    // If the transaction is already confirmed in the chain, don't do anything
    // and return early.
    CCoinsViewCache &view = node.chainman->ActiveChainstate().CoinsTip();
    for (size_t o = 0; o < tx->vout.size(); o++) {
        const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
        // IsSpent doesn't mean the coin is spent, it means the output doesn't exist.
        // So if the output does exist, then this transaction exists in the chain.
        if (!existingCoin.IsSpent()) return TransactionError::ALREADY_IN_CHAIN;
    }
    if (!node.mempool->exists(hashTx)) {
        // Transaction is not already in the mempool.
        if (max_tx_fee > 0) {
            // First, call ATMP with test_accept and check the fee. If ATMP
            // fails here, return error immediately.
            const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false /* bypass_limits */,
                                                                  true /* test_accept */);
            if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
                return HandleATMPError(result.m_state, err_string);
            } else if (result.m_base_fees.value() > max_tx_fee) {
                return TransactionError::MAX_FEE_EXCEEDED;
            }
        }
        // Try to submit the transaction to the mempool.
        const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false /* bypass_limits */,
                                                              false /* test_accept */);
        if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
            return HandleATMPError(result.m_state, err_string);
        }

        // Transaction was accepted to the mempool.

        if (wait_callback) {
            // For transactions broadcast from outside the wallet, make sure
            // that the wallet has been notified of the transaction before
            // continuing.
            //
            // This prevents a race where a user might call sendrawtransaction
            // with a transaction to/from their wallet, immediately call some
            // wallet RPC, and get a stale result because callbacks have not
            // yet been processed.
            CallFunctionInValidationInterfaceQueue([&promise] {
                promise.set_value();
            });
            callback_set = true;
        }
    }

    } // cs_main

    if (callback_set) {
        // Wait until Validation Interface clients have been notified of the
        // transaction entering the mempool.
        promise.get_future().wait();
    }

    if (relay) {
        // the mempool tracks locally submitted transactions to make a
        // best-effort of initial broadcast
        node.mempool->AddUnbroadcastTx(hashTx);
        node.peerman->RelayTransaction(hashTx, tx->GetWitnessHash());
    }

    return TransactionError::OK;
}
<commit_msg>[mempool] Only add a transaction to the unbroadcast set when it's added to the mempool<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <consensus/validation.h>
#include <net.h>
#include <net_processing.h>
#include <node/context.h>
#include <validation.h>
#include <validationinterface.h>
#include <node/transaction.h>

#include <future>

static TransactionError HandleATMPError(const TxValidationState& state, std::string& err_string_out)
{
    err_string_out = state.ToString();
    if (state.IsInvalid()) {
        if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) {
            return TransactionError::MISSING_INPUTS;
        }
        return TransactionError::MEMPOOL_REJECTED;
    } else {
        return TransactionError::MEMPOOL_ERROR;
    }
}

TransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback)
{
    // BroadcastTransaction can be called by either sendrawtransaction RPC or wallet RPCs.
    // node.peerman is assigned both before chain clients and before RPC server is accepting calls,
    // and reset after chain clients and RPC sever are stopped. node.peerman should never be null here.
    assert(node.peerman);
    assert(node.mempool);
    std::promise<void> promise;
    uint256 hashTx = tx->GetHash();
    bool callback_set = false;

    { // cs_main scope
    assert(node.chainman);
    LOCK(cs_main);
    // If the transaction is already confirmed in the chain, don't do anything
    // and return early.
    CCoinsViewCache &view = node.chainman->ActiveChainstate().CoinsTip();
    for (size_t o = 0; o < tx->vout.size(); o++) {
        const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
        // IsSpent doesn't mean the coin is spent, it means the output doesn't exist.
        // So if the output does exist, then this transaction exists in the chain.
        if (!existingCoin.IsSpent()) return TransactionError::ALREADY_IN_CHAIN;
    }
    if (!node.mempool->exists(hashTx)) {
        // Transaction is not already in the mempool.
        if (max_tx_fee > 0) {
            // First, call ATMP with test_accept and check the fee. If ATMP
            // fails here, return error immediately.
            const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false /* bypass_limits */,
                                                                  true /* test_accept */);
            if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
                return HandleATMPError(result.m_state, err_string);
            } else if (result.m_base_fees.value() > max_tx_fee) {
                return TransactionError::MAX_FEE_EXCEEDED;
            }
        }
        // Try to submit the transaction to the mempool.
        const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false /* bypass_limits */,
                                                              false /* test_accept */);
        if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
            return HandleATMPError(result.m_state, err_string);
        }

        // Transaction was accepted to the mempool.

        if (relay) {
            // the mempool tracks locally submitted transactions to make a
            // best-effort of initial broadcast
            node.mempool->AddUnbroadcastTx(hashTx);
        }

        if (wait_callback) {
            // For transactions broadcast from outside the wallet, make sure
            // that the wallet has been notified of the transaction before
            // continuing.
            //
            // This prevents a race where a user might call sendrawtransaction
            // with a transaction to/from their wallet, immediately call some
            // wallet RPC, and get a stale result because callbacks have not
            // yet been processed.
            CallFunctionInValidationInterfaceQueue([&promise] {
                promise.set_value();
            });
            callback_set = true;
        }
    }

    } // cs_main

    if (callback_set) {
        // Wait until Validation Interface clients have been notified of the
        // transaction entering the mempool.
        promise.get_future().wait();
    }

    if (relay) {
        node.peerman->RelayTransaction(hashTx, tx->GetWitnessHash());
    }

    return TransactionError::OK;
}
<|endoftext|>