<commit_before>#include "PropositionalGrounder.h"
#include "../atom/Choice.h"

namespace DLV2{

namespace grounder{

void PropositionalGrounder::ground() {
        for (unsigned i=0; i < statementDependency->getRulesSize(); i++) {
                groundRule(statementDependency->getRule(i));
        }

        for (unsigned i = 0; i < statementDependency->getConstraintSize(); i++) {
                groundRule(statementDependency->getConstraint(i));
        }

        addTrueNegationConstraints();

        outputBuilder->onEnd();
}

 bool PropositionalGrounder::groundRule(Rule* r, unordered_set<index_object>* componentPredicateInHead){
        gRule = new Rule(true,r->getSizeHead(),r->getSizeBody());
        var_assignment fakeAss;

        for (unsigned i = 0; i < r->getSizeBody(); i++) {
                Atom* atom=r->getAtomInBody(i);
                Atom* gAtom = nullptr;
                bool simply=false;
                if(atom->isClassicalLiteral()){
                        if(!groundClassical(atom,gAtom)){
                                delete gAtom;
                                freeGRule();
                                return false;
                        }
                        simply=gAtom->isFact();
                }else if(atom->isBuiltIn()){
                        simply=true;
                        gRule->setAtomToSimplifyInBody(i,true);
                        if(!groundBuiltin(atom,gAtom)){
                                freeGRule();
                                return false;
                        }
                }else if(atom->isAggregateAtom()){
                        ResultEvaluation result = groundAggregate(atom,gAtom);
                        gRule->setAtomInBody(i, gAtom);
                        simply=(result==SATISFY);
                }
                gRule->setAtomInBody(i,gAtom);
                gRule->setAtomToSimplifyInBody(i, simply);
        }

        if(r->isChoiceRule()){
                Atom* choice = r->getAtomInHead(0);
                Atom *gAtom = nullptr;
                groundChoice(choice,gAtom);
                gRule->setAtomInHead(0,gAtom);
        }else{
                 for (unsigned i = 0; i < r->getSizeHead(); i++) {
                         Atom* atom=r->getAtomInHead(i);
                         Atom* atomToInsert = getAtomToInsert(atom,!gRule->areThereUndefinedAtomInBody() && !r->isChoiceRule() && r->getSizeHead() <=1 );
                         gRule->setAtomInHead(i,atomToInsert);
                         gRule->setAtomToSimplifyInHead(i, atomToInsert->isFact());
                 }
         }
        outputBuilder->onRule(gRule);
        freeGRule();
        return true;
}

Atom* PropositionalGrounder::getAtomToInsert(Atom* atom, bool setFact) {
        auto extTable =predicateExtTable->getPredicateExt(atom->getPredicate());
        Atom *groundAtom = extTable->getGroundAtom(atom);
        Atom* atomToInsert=nullptr;
        if(groundAtom!=nullptr){
                if(setFact)groundAtom->setFact(true);
                atomToInsert = groundAtom;
        }else{
                atomToInsert = atom->clone();
                atomToInsert->setFact(setFact);
                atomToInsert->setNegative(false);
                extTable->addAtom(atomToInsert, NOFACT);
        }

        if(atom->isNegative()){
                atomToInsert = atomToInsert->clone();
                atomToInsert->setNegative(true);
        }
        return atomToInsert;
}

ResultEvaluation PropositionalGrounder::groundAggregate(DLV2::grounder::Atom *atom, DLV2::grounder::Atom *&gAtom){
        ResultEvaluation result=UNDEF;
        gAtom = new AggregateAtom(atom->getFirstGuard(),atom->getFirstBinop(),atom->getSecondGuard(),atom->getSecondBinop(),atom->getAggregateFunction(),atom->isNegative());
        for (unsigned j = 0; j < atom->getAggregateElementsSize(); j++) {
                auto ae = atom->getAggregateElement(j);
                AggregateElement* gae = new AggregateElement;
                gae->setTerms(ae->getTerms());
                for (auto& naf : ae->getNafLiterals()) {
                        auto gnaf = getAtomToInsert(naf);
                        gae->addNafLiterals(gnaf);
                }
                gAtom->addAggregateElement(gae);
                result = gAtom->partialEvaluate();
                if(result==SATISFY)break;
        }
        if(result==SATISFY)return SATISFY;
        result = gAtom->finalEvaluate();
        return result;
};

void PropositionalGrounder::groundChoice(Atom* atom, Atom*& gAtom) {
        vector<ChoiceElement*> ces;
        for (unsigned i= 0; i < atom->getChoiceElementsSize(); i++) {
                auto ce = atom->getChoiceElement(i);
                ChoiceElement* gce = new ChoiceElement();
                for (unsigned j = 0; j < ce->getSize(); j++) {
                        auto at = getAtomToInsert(ce->getAtom(j));
                        gce->add(at);
                }
                ces.push_back(gce);
        }
        gAtom = new DLV2::grounder::Choice();
        gAtom->setChoiceElements(ces);
};

}
}
<commit_msg>Fix minor<commit_after>#include "PropositionalGrounder.h"
#include "../atom/Choice.h"

namespace DLV2{

namespace grounder{

void PropositionalGrounder::ground() {
        for (unsigned i=0; i < statementDependency->getRulesSize(); i++) {
                groundRule(statementDependency->getRule(i));
        }

        for (unsigned i = 0; i < statementDependency->getConstraintSize(); i++) {
                groundRule(statementDependency->getConstraint(i));
        }

        for (unsigned i = 0; i < statementDependency->getWeakContraintsSize(); i++) {
                groundRule(statementDependency->getWeakContraint(i));
        }

        addTrueNegationConstraints();

        outputBuilder->onEnd();
}

 bool PropositionalGrounder::groundRule(Rule* r, unordered_set<index_object>* componentPredicateInHead){
         unsigned sizeHead =r->getSizeHead();
         unsigned sizeBody=r->getSizeBody();
         gRule = (r->isWeakConstraint())? new WeakConstraint(true,sizeBody,r->getWeight(),r->getLevel(),r->getLabel())
                 : new Rule(true,sizeHead,sizeBody);
        var_assignment fakeAss;

        for (unsigned i = 0; i < sizeBody; i++) {
                Atom* atom=r->getAtomInBody(i);
                Atom* gAtom = nullptr;
                bool simply=false;
                if(atom->isClassicalLiteral()){
                        if(!groundClassical(atom,gAtom)){
                                delete gAtom;
                                freeGRule();
                                return false;
                        }
                        simply=gAtom->isFact();
                }else if(atom->isBuiltIn()){
                        simply=true;
                        gRule->setAtomToSimplifyInBody(i,true);
                        if(!groundBuiltin(atom,gAtom)){
                                freeGRule();
                                return false;
                        }
                }else if(atom->isAggregateAtom()){
                        ResultEvaluation result = groundAggregate(atom,gAtom);
                        gRule->setAtomInBody(i, gAtom);
                        simply=(result==SATISFY);
                }
                gRule->setAtomInBody(i,gAtom);
                gRule->setAtomToSimplifyInBody(i, simply);
        }

        if(r->isChoiceRule()){
                Atom* choice = r->getAtomInHead(0);
                Atom *gAtom = nullptr;
                groundChoice(choice,gAtom);
                gRule->setAtomInHead(0,gAtom);
        }else{
                 for (unsigned i = 0; i < sizeHead; i++) {
                         Atom* atom=r->getAtomInHead(i);
                         Atom* atomToInsert = getAtomToInsert(atom,!gRule->areThereUndefinedAtomInBody() && !r->isChoiceRule() && r->getSizeHead() <=1 );
                         gRule->setAtomInHead(i,atomToInsert);
                         gRule->setAtomToSimplifyInHead(i, atomToInsert->isFact());
                 }
        }
        outputBuilder->onRule(gRule);
        freeGRule();
        return true;
}

Atom* PropositionalGrounder::getAtomToInsert(Atom* atom, bool setFact) {
        auto extTable =predicateExtTable->getPredicateExt(atom->getPredicate());
        Atom *groundAtom = extTable->getGroundAtom(atom);
        Atom* atomToInsert=nullptr;
        if(groundAtom!=nullptr){
                if(setFact)groundAtom->setFact(true);
                atomToInsert = groundAtom;
        }else{
                atomToInsert = atom->clone();
                atomToInsert->setFact(setFact);
                atomToInsert->setNegative(false);
                extTable->addAtom(atomToInsert, NOFACT);
        }

        if(atom->isNegative()){
                atomToInsert = atomToInsert->clone();
                atomToInsert->setNegative(true);
        }
        return atomToInsert;
}

ResultEvaluation PropositionalGrounder::groundAggregate(DLV2::grounder::Atom *atom, DLV2::grounder::Atom *&gAtom){
        ResultEvaluation result=UNDEF;
        gAtom = new AggregateAtom(atom->getFirstGuard(),atom->getFirstBinop(),atom->getSecondGuard(),atom->getSecondBinop(),atom->getAggregateFunction(),atom->isNegative());
        for (unsigned j = 0; j < atom->getAggregateElementsSize(); j++) {
                auto ae = atom->getAggregateElement(j);
                AggregateElement* gae = new AggregateElement;
                gae->setTerms(ae->getTerms());
                for (auto& naf : ae->getNafLiterals()) {
                        auto gnaf = getAtomToInsert(naf);
                        gae->addNafLiterals(gnaf);
                }
                gAtom->addAggregateElement(gae);
                result = gAtom->partialEvaluate();
                if(result==SATISFY)break;
        }
        if(result==SATISFY)return SATISFY;
        result = gAtom->finalEvaluate();
        return result;
};

void PropositionalGrounder::groundChoice(Atom* atom, Atom*& gAtom) {
        vector<ChoiceElement*> ces;
        for (unsigned i= 0; i < atom->getChoiceElementsSize(); i++) {
                auto ce = atom->getChoiceElement(i);
                ChoiceElement* gce = new ChoiceElement();
                for (unsigned j = 0; j < ce->getSize(); j++) {
                        auto at = getAtomToInsert(ce->getAtom(j));
                        gce->add(at);
                }
                ces.push_back(gce);
        }
        gAtom = new DLV2::grounder::Choice();
        gAtom->setChoiceElements(ces);
};

}
}
<|endoftext|>


<commit_before>/*
 * Author: Laurent Goderre
 */

#include <Arduino.h>
#include "Lane.h"

const String laneStr = "Lane #";
const String laneStrEnd =  ": ";

Lane::Lane(int laneNumber, int lenTargets, Target* targets[]): number(laneNumber), lenTargets(lenTargets), targets(targets) {
}

Lane::~Lane(void){}

void Lane::showTarget() {
	Serial.print(laneStr + (number + 1) + laneStrEnd);
	currentTarget = targets[rand() % lenTargets];
	currentTarget->show();
}

void Lane::hideCurrentTarget(){
	Serial.print(laneStr + (number + 1) + laneStrEnd);
	currentTarget->hide();
}

<commit_msg>Implemented the lane destructor<commit_after>/*
 * Author: Laurent Goderre
 */

#include <Arduino.h>
#include "Lane.h"

const String laneStr = "Lane #";
const String laneStrEnd =  ": ";

Lane::Lane(int laneNumber, int lenTargets, Target* targets[]): number(laneNumber), lenTargets(lenTargets), targets(targets) {
}

Lane::~Lane(void){
	for(int t=0;t<lenTargets;t++) {
		delete targets[t];
	}
}

void Lane::showTarget() {
	Serial.print(laneStr + (number + 1) + laneStrEnd);
	currentTarget = targets[rand() % lenTargets];
	currentTarget->show();
}

void Lane::hideCurrentTarget(){
	Serial.print(laneStr + (number + 1) + laneStrEnd);
	currentTarget->hide();
}

<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"

#include <sstream>
#include <windows.h>

namespace
{
	// must be used to not leak memory in case something would throw
	class auto_localfree
	{
	public:
		auto_localfree(HLOCAL memory)
			: m_memory(memory)
		{
		}
		~auto_localfree()
		{
			if (m_memory)
				LocalFree(m_memory);
		}
	private:
		HLOCAL m_memory;
	};

	std::string utf8_native(std::string const& s)
	{
		std::wstring ws;
		libtorrent::utf8_wchar(s, ws);
		std::size_t size = wcstombs(0, ws.c_str(), 0);
		if (size == std::size_t(-1)) return s;
		std::string ret;
		ret.resize(size);
		size = wcstombs(&ret[0], ws.c_str(), size + 1);
		ret.resize(size);
		return ret;
	}

	void throw_exception(const char* thrower)
	{
		DWORD err = GetLastError();

#ifdef UNICODE
		wchar_t *wbuffer = 0;
		FormatMessage(
			FORMAT_MESSAGE_FROM_SYSTEM
			|FORMAT_MESSAGE_ALLOCATE_BUFFER
			, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
		auto_localfree auto_free(wbuffer);
		std::string tmp_utf8;
		libtorrent::wchar_utf8(wbuffer, tmp_utf8);
		char const* buffer = tmp_utf8.c_str();
#else
		char* buffer = 0;
		FormatMessage(
			FORMAT_MESSAGE_FROM_SYSTEM
			|FORMAT_MESSAGE_ALLOCATE_BUFFER
			, 0, err, 0, (LPSTR)&buffer, 0, 0);
		auto_localfree auto_free(buffer);
#endif

		std::stringstream s;
		s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");

		throw libtorrent::file_error(s.str());
	}
}

namespace libtorrent
{

	struct file::impl : boost::noncopyable
	{
		enum open_flags
		{
			read_flag = 1,
			write_flag = 2
		};

		enum seek_mode
		{
			seek_begin = FILE_BEGIN,
			seek_from_here = FILE_CURRENT,
			seek_end = FILE_END
		};

		impl()
		{
			m_file_handle = INVALID_HANDLE_VALUE;
		}

		void open(const char *file_name, open_flags flags)
		{
			assert(file_name);
			assert(flags & (read_flag | write_flag));

			DWORD access_mask = 0;
			if (flags & read_flag)
				access_mask |= GENERIC_READ;
			if (flags & write_flag)
				access_mask |= GENERIC_WRITE;

			assert(access_mask & (GENERIC_READ | GENERIC_WRITE));

		#ifdef UNICODE
			std::wstring wfile_name(utf8_wchar(file_name));
			HANDLE new_handle = CreateFile(
				(LPCWSTR)wfile_name.c_str()
				, access_mask
				, FILE_SHARE_READ
				, 0
				, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
				, FILE_ATTRIBUTE_NORMAL
				, 0);
		#else
			HANDLE new_handle = CreateFile(
				utf8_native(file_name).c_str()
				, access_mask
				, FILE_SHARE_READ
				, 0
				, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
				, FILE_ATTRIBUTE_NORMAL
				, 0);
		#endif

			if (new_handle == INVALID_HANDLE_VALUE)
			{
				std::stringstream s;
				throw_exception(file_name);
			}
			// will only close old file if the open succeeded
			close();
			m_file_handle = new_handle;
		}

		void close()
		{
			if (m_file_handle != INVALID_HANDLE_VALUE)
			{
				CloseHandle(m_file_handle);
				m_file_handle = INVALID_HANDLE_VALUE;
			}
		}

		~impl()
		{
			close();
		}

		size_type write(const char* buffer, size_type num_bytes)
		{
			assert(buffer);
			assert(num_bytes > 0);
			assert((DWORD)num_bytes == num_bytes);
			DWORD bytes_written = 0;
			if (num_bytes != 0)
			{
				if (FALSE == WriteFile(
					m_file_handle
					, buffer
					, (DWORD)num_bytes
					, &bytes_written
					, 0))
				{
					throw_exception("file::write");
				}
			}
			return bytes_written;
		}

		size_type read(char* buffer, size_type num_bytes)
		{
			assert(buffer);
			assert(num_bytes > 0);
			assert((DWORD)num_bytes == num_bytes);

			DWORD bytes_read = 0;
			if (num_bytes != 0)
			{
				if (FALSE == ReadFile(
					m_file_handle
					, buffer
					, (DWORD)num_bytes
					, &bytes_read
					, 0))
				{
					throw_exception("file::read");
				}
			}
			return bytes_read;
		}

		void seek(size_type pos, seek_mode from_where)
		{
			assert(pos >= 0 || from_where != seek_begin);
			assert(pos <= 0 || from_where != seek_end);
			LARGE_INTEGER offs;
			offs.QuadPart = pos;
			if (FALSE == SetFilePointerEx(
				m_file_handle
				, offs
				, &offs
				, from_where))
			{
				throw_exception("file::seek");
			}
		}

		size_type tell()
		{
			LARGE_INTEGER offs;
			offs.QuadPart = 0;

			// is there any other way to get offset?
			if (FALSE == SetFilePointerEx(
				m_file_handle
				, offs
				, &offs
				, FILE_CURRENT))
			{
				throw_exception("file::tell");
			}

			size_type pos=offs.QuadPart;
			assert(pos>=0);
			return pos;
		}
/*
		size_type size()
		{
			LARGE_INTEGER s;
			if (FALSE == GetFileSizeEx(m_file_handle, &s))
			{
				throw_exception("file::size");
			}

			size_type size = s.QuadPart;
			assert(size >= 0);
			return size;
		}
*/
	private:

		HANDLE m_file_handle;

	};
}

namespace libtorrent
{

	const file::seek_mode file::begin(file::impl::seek_begin);
	const file::seek_mode file::end(file::impl::seek_end);

	const file::open_mode file::in(file::impl::read_flag);
	const file::open_mode file::out(file::impl::write_flag);

	file::file()
		: m_impl(new libtorrent::file::impl())
	{
	}
	file::file(boost::filesystem::path const& p, open_mode m)
		: m_impl(new libtorrent::file::impl())
	{
		open(p,m);
	}

	file::~file()
	{
	}

	void file::open(boost::filesystem::path const& p, open_mode m)
	{
		assert(p.is_complete());
		m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buffer, size_type num_bytes)
	{
		return m_impl->write(buffer, num_bytes);
	}

	size_type file::read(char* buffer, size_type num_bytes)
	{
		return m_impl->read(buffer, num_bytes);
	}

	void file::seek(size_type pos, seek_mode m)
	{
		m_impl->seek(pos,impl::seek_mode(m.m_val));
	}

	size_type file::tell()
	{
		return m_impl->tell();
	}
}
<commit_msg>*** empty log message ***<commit_after>/*

Copyright (c) 2003, Magnus Jonsson & Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/file.hpp"
#include "libtorrent/utf8.hpp"

#include <sstream>
#include <windows.h>

namespace
{
	// must be used to not leak memory in case something would throw
	class auto_localfree
	{
	public:
		auto_localfree(HLOCAL memory)
			: m_memory(memory)
		{
		}
		~auto_localfree()
		{
			if (m_memory)
				LocalFree(m_memory);
		}
	private:
		HLOCAL m_memory;
	};

	std::string utf8_native(std::string const& s)
	{
		std::wstring ws;
		libtorrent::utf8_wchar(s, ws);
		std::size_t size = wcstombs(0, ws.c_str(), 0);
		if (size == std::size_t(-1)) return s;
		std::string ret;
		ret.resize(size);
		size = wcstombs(&ret[0], ws.c_str(), size + 1);
		ret.resize(size-1);
		return ret;
	}

	void throw_exception(const char* thrower)
	{
		DWORD err = GetLastError();

#ifdef UNICODE
		wchar_t *wbuffer = 0;
		FormatMessage(
			FORMAT_MESSAGE_FROM_SYSTEM
			|FORMAT_MESSAGE_ALLOCATE_BUFFER
			, 0, err, 0, (LPWSTR)&wbuffer, 0, 0);
		auto_localfree auto_free(wbuffer);
		std::string tmp_utf8;
		libtorrent::wchar_utf8(wbuffer, tmp_utf8);
		char const* buffer = tmp_utf8.c_str();
#else
		char* buffer = 0;
		FormatMessage(
			FORMAT_MESSAGE_FROM_SYSTEM
			|FORMAT_MESSAGE_ALLOCATE_BUFFER
			, 0, err, 0, (LPSTR)&buffer, 0, 0);
		auto_localfree auto_free(buffer);
#endif

		std::stringstream s;
		s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL");

		throw libtorrent::file_error(s.str());
	}
}

namespace libtorrent
{

	struct file::impl : boost::noncopyable
	{
		enum open_flags
		{
			read_flag = 1,
			write_flag = 2
		};

		enum seek_mode
		{
			seek_begin = FILE_BEGIN,
			seek_from_here = FILE_CURRENT,
			seek_end = FILE_END
		};

		impl()
		{
			m_file_handle = INVALID_HANDLE_VALUE;
		}

		void open(const char *file_name, open_flags flags)
		{
			assert(file_name);
			assert(flags & (read_flag | write_flag));

			DWORD access_mask = 0;
			if (flags & read_flag)
				access_mask |= GENERIC_READ;
			if (flags & write_flag)
				access_mask |= GENERIC_WRITE;

			assert(access_mask & (GENERIC_READ | GENERIC_WRITE));

		#ifdef UNICODE
			std::wstring wfile_name(utf8_wchar(file_name));
			HANDLE new_handle = CreateFile(
				(LPCWSTR)wfile_name.c_str()
				, access_mask
				, FILE_SHARE_READ
				, 0
				, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
				, FILE_ATTRIBUTE_NORMAL
				, 0);
		#else
			HANDLE new_handle = CreateFile(
				utf8_native(file_name).c_str()
				, access_mask
				, FILE_SHARE_READ
				, 0
				, (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING
				, FILE_ATTRIBUTE_NORMAL
				, 0);
		#endif

			if (new_handle == INVALID_HANDLE_VALUE)
			{
				std::stringstream s;
				throw_exception(file_name);
			}
			// will only close old file if the open succeeded
			close();
			m_file_handle = new_handle;
		}

		void close()
		{
			if (m_file_handle != INVALID_HANDLE_VALUE)
			{
				CloseHandle(m_file_handle);
				m_file_handle = INVALID_HANDLE_VALUE;
			}
		}

		~impl()
		{
			close();
		}

		size_type write(const char* buffer, size_type num_bytes)
		{
			assert(buffer);
			assert(num_bytes > 0);
			assert((DWORD)num_bytes == num_bytes);
			DWORD bytes_written = 0;
			if (num_bytes != 0)
			{
				if (FALSE == WriteFile(
					m_file_handle
					, buffer
					, (DWORD)num_bytes
					, &bytes_written
					, 0))
				{
					throw_exception("file::write");
				}
			}
			return bytes_written;
		}

		size_type read(char* buffer, size_type num_bytes)
		{
			assert(buffer);
			assert(num_bytes > 0);
			assert((DWORD)num_bytes == num_bytes);

			DWORD bytes_read = 0;
			if (num_bytes != 0)
			{
				if (FALSE == ReadFile(
					m_file_handle
					, buffer
					, (DWORD)num_bytes
					, &bytes_read
					, 0))
				{
					throw_exception("file::read");
				}
			}
			return bytes_read;
		}

		void seek(size_type pos, seek_mode from_where)
		{
			assert(pos >= 0 || from_where != seek_begin);
			assert(pos <= 0 || from_where != seek_end);
			LARGE_INTEGER offs;
			offs.QuadPart = pos;
			if (FALSE == SetFilePointerEx(
				m_file_handle
				, offs
				, &offs
				, from_where))
			{
				throw_exception("file::seek");
			}
		}

		size_type tell()
		{
			LARGE_INTEGER offs;
			offs.QuadPart = 0;

			// is there any other way to get offset?
			if (FALSE == SetFilePointerEx(
				m_file_handle
				, offs
				, &offs
				, FILE_CURRENT))
			{
				throw_exception("file::tell");
			}

			size_type pos=offs.QuadPart;
			assert(pos>=0);
			return pos;
		}
/*
		size_type size()
		{
			LARGE_INTEGER s;
			if (FALSE == GetFileSizeEx(m_file_handle, &s))
			{
				throw_exception("file::size");
			}

			size_type size = s.QuadPart;
			assert(size >= 0);
			return size;
		}
*/
	private:

		HANDLE m_file_handle;

	};
}

namespace libtorrent
{

	const file::seek_mode file::begin(file::impl::seek_begin);
	const file::seek_mode file::end(file::impl::seek_end);

	const file::open_mode file::in(file::impl::read_flag);
	const file::open_mode file::out(file::impl::write_flag);

	file::file()
		: m_impl(new libtorrent::file::impl())
	{
	}
	file::file(boost::filesystem::path const& p, open_mode m)
		: m_impl(new libtorrent::file::impl())
	{
		open(p,m);
	}

	file::~file()
	{
	}

	void file::open(boost::filesystem::path const& p, open_mode m)
	{
		assert(p.is_complete());
		m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask));
	}

	void file::close()
	{
		m_impl->close();
	}

	size_type file::write(const char* buffer, size_type num_bytes)
	{
		return m_impl->write(buffer, num_bytes);
	}

	size_type file::read(char* buffer, size_type num_bytes)
	{
		return m_impl->read(buffer, num_bytes);
	}

	void file::seek(size_type pos, seek_mode m)
	{
		m_impl->seek(pos,impl::seek_mode(m.m_val));
	}

	size_type file::tell()
	{
		return m_impl->tell();
	}
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: chips/p9/procedures/ipl/hwp/p9_pm.H $                         */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* EKB Project                                                            */
/*                                                                        */
/* COPYRIGHT 2015                                                         */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_pm.H
/// @brief Common header for Power Manangement procedures
///

// *HWP HWP Owner       : Amit Kumar <akumar3@us.ibm.com>
// *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner        : Bilicon Patil <bilpatil@in.ibm.com>
// *HWP Team            : PM
// *HWP Level           : 2
// *HWP Consumed by     : HS

#ifndef _P9_PM_H_
#define _P9_PM_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Macro Defintions
//------------------------------------------------------------------------------

// Create a multi-bit mask of @a n bits starting at bit @a b
#define BITS(b, n) ((0xffffffffffffffffull << (64 - (n))) >> (b))

// Create a single bit mask at bit @a b
#define BIT(b) BITS((b), 1)

//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
namespace p9pm
{

enum PM_FLOW_MODE
{
    PM_RESET        = 0x1,
    PM_INIT         = 0x2,
    PM_SETUP        = 0x3,
    PM_SETUP_PIB    = 0x4,
    PM_SETUP_ALL    = 0x5,
    PM_RESET_SOFT   = 0x6,
    PM_INIT_SOFT    = 0x7,
    PM_INIT_SPECIAL = 0x8,
};

} // end of namespace p9pm

#endif // _P9_PM_H_
<commit_msg>Fix all incorrect copyright prologs<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: chips/p9/procedures/hwp/pm/p9_pm.H $                          */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* EKB Project                                                            */
/*                                                                        */
/* COPYRIGHT 2015                                                         */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_pm.H
/// @brief Common header for Power Manangement procedures
///

// *HWP HWP Owner       : Amit Kumar <akumar3@us.ibm.com>
// *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner        : Bilicon Patil <bilpatil@in.ibm.com>
// *HWP Team            : PM
// *HWP Level           : 2
// *HWP Consumed by     : HS

#ifndef _P9_PM_H_
#define _P9_PM_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Macro Defintions
//------------------------------------------------------------------------------

// Create a multi-bit mask of @a n bits starting at bit @a b
#define BITS(b, n) ((0xffffffffffffffffull << (64 - (n))) >> (b))

// Create a single bit mask at bit @a b
#define BIT(b) BITS((b), 1)

//------------------------------------------------------------------------------
// Constant definitions
//------------------------------------------------------------------------------
namespace p9pm
{

enum PM_FLOW_MODE
{
    PM_RESET        = 0x1,
    PM_INIT         = 0x2,
    PM_SETUP        = 0x3,
    PM_SETUP_PIB    = 0x4,
    PM_SETUP_ALL    = 0x5,
    PM_RESET_SOFT   = 0x6,
    PM_INIT_SOFT    = 0x7,
    PM_INIT_SPECIAL = 0x8,
};

} // end of namespace p9pm

#endif // _P9_PM_H_
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/spd/spd_field.H $               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file spd_field.H
/// @brief SPD data fields
///

// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP

#ifndef _MSS_SPD_FIELD_H_
#define _MSS_SPD_FIELD_H_

#include <cstdint>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/mss_field.H>

namespace mss
{
namespace spd
{

///
/// @class init_fields
/// @brief Initial fields needed to know how to parse the SPD
/// @note These are preliminary fields that need to be independently
/// decoded from any specific DRAM generation SPEC (e.g. SPD factory)
///
class init_fields
{
    private:

        enum
        {
            // Byte 1
            REVISION_START = 0,
            REVISION_LEN = 8,

            // Byte 2
            DEVICE_TYPE_START = 0,
            DEVICE_TYPE_LEN = 8,

            // Byte 3
            HYBRID_START = 0,
            HYBRID_LEN = 1,
            HYBRID_MEDIA_START = 1,
            HYBRID_MEDIA_LEN = 3,
            BASE_MODULE_START = 4,
            BASE_MODULE_LEN = 4,

            // Byte 130
            REF_RAW_CARD_START = 0,
            REF_RAW_CARD_LEN = 8,
        };

    public:

        // 1st field: Byte number
        // 2nd field: Start bit
        // 3rd field: Bit length
        static constexpr mss::field_t REVISION{1, REVISION_START, REVISION_LEN};
        static constexpr mss::field_t DEVICE_TYPE{2, DEVICE_TYPE_START, DEVICE_TYPE_LEN};
        static constexpr mss::field_t BASE_MODULE{3, BASE_MODULE_START, BASE_MODULE_LEN};
        static constexpr mss::field_t HYBRID{3, HYBRID_START, HYBRID_LEN};
        static constexpr mss::field_t HYBRID_MEDIA{3, HYBRID_MEDIA_START, HYBRID_MEDIA_LEN};
        static constexpr mss::field_t REF_RAW_CARD{130, REF_RAW_CARD_START, REF_RAW_CARD_LEN};
};

///
/// @class fields
/// @brief Collection of SPD fields
/// @tparam D DRAM device type (e.g. DDR4)
/// @tparam S SPD parameter (e.g. RDIMM_MODULE, NVDIMM_MODULE)
///
template <device_type D, parameters S>
class fields;

}// spd
}// mss

#endif // _MSS_SPD_FIELD_H_
<commit_msg>Initial mss_field endian modification<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/spd/spd_field.H $               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file spd_field.H
/// @brief SPD data fields
///

// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP

#ifndef _MSS_SPD_FIELD_H_
#define _MSS_SPD_FIELD_H_

#include <cstdint>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/mss_field.H>

namespace mss
{
namespace spd
{

///
/// @class init_fields
/// @brief Initial fields needed to know how to parse the SPD
/// @note These are preliminary fields that need to be independently
/// decoded from any specific DRAM generation SPEC (e.g. SPD factory)
///
class init_fields
{
    private:

        enum
        {
            // Byte 1
            REVISION_START = 0,
            REVISION_LEN = 8,

            // Byte 2
            DEVICE_TYPE_START = 0,
            DEVICE_TYPE_LEN = 8,

            // Byte 3
            HYBRID_START = 0,
            HYBRID_LEN = 1,
            HYBRID_MEDIA_START = 1,
            HYBRID_MEDIA_LEN = 3,
            BASE_MODULE_START = 4,
            BASE_MODULE_LEN = 4,

            // Byte 130
            REF_RAW_CARD_START = 0,
            REF_RAW_CARD_LEN = 8,
        };

    public:

        // 1st field: Byte number
        // 2nd field: Start bit
        // 3rd field: Bit length
        static constexpr mss::field_t<mss::endian::LITTLE> REVISION{1, REVISION_START, REVISION_LEN};
        static constexpr mss::field_t<mss::endian::LITTLE> DEVICE_TYPE{2, DEVICE_TYPE_START, DEVICE_TYPE_LEN};
        static constexpr mss::field_t<mss::endian::LITTLE> BASE_MODULE{3, BASE_MODULE_START, BASE_MODULE_LEN};
        static constexpr mss::field_t<mss::endian::LITTLE> HYBRID{3, HYBRID_START, HYBRID_LEN};
        static constexpr mss::field_t<mss::endian::LITTLE> HYBRID_MEDIA{3, HYBRID_MEDIA_START, HYBRID_MEDIA_LEN};
        static constexpr mss::field_t<mss::endian::LITTLE> REF_RAW_CARD{130, REF_RAW_CARD_START, REF_RAW_CARD_LEN};
};

///
/// @class fields
/// @brief Collection of SPD fields
/// @tparam D DRAM device type (e.g. DDR4)
/// @tparam S SPD parameter (e.g. RDIMM_MODULE, NVDIMM_MODULE)
///
template <device_type D, parameters S>
class fields;

}// spd
}// mss

#endif // _MSS_SPD_FIELD_H_
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <wiringPi.h>
#include <lcd.h>
#include <mcp23017.h>
#include <SFML/Audio.hpp>
#include "Main.h"

using namespace std;

int main()
{
	initialization();

	system("sleep 10");

	/*
   string currentInstrument;
   string currentOctave;

   bool instrumentButton;
   bool octaveButton;

   while (1) // Infinite loop
   {
      while (instrumentButton == 1) // While the instrument button is pressed...
      {
         if (currentInstrument == "piano")
         {
            instrumentChange("guitar", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
         else if (currentInstrument == "guitar")
         {
            instrumentChange("trumpet", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
         else
         {
            instrumentChange("piano", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
      }

      while (octaveButton == 1) // While the octave button is pressed...
      {
         if (currentOctave == "medium")
         {
            octaveChange("high", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
         else if (currentOctave == "high")
         {
            octaveChange("low", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
         else
         {
            octaveChange("medium", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
      }
   //}*/

   return 0; // Exit program
}

static void adafruitLCDSetup(int colour)
{
	int i;

	// temp for compile
	colour = colour;

	//	Backlight LEDs

	pinMode(AF_RED, OUTPUT);
	pinMode(AF_GREEN, OUTPUT);
	pinMode(AF_BLUE, OUTPUT);
	//setBacklightColour(colour);

	//	Input buttons

	for (i = 0; i <= 4; ++i)
	{
		pinMode(AF_BASE + i, INPUT);
		pullUpDnControl(AF_BASE + i, PUD_UP);	// Enable pull-ups, switches close to 0v
	}

	// Control signals

	pinMode(AF_RW, OUTPUT); digitalWrite(AF_RW, LOW);	// Not used with wiringPi - always in write mode

														// The other control pins are initialised with lcdInit ()

	lcdHandle = lcdInit(2, 16, 4, AF_RS, AF_E, AF_DB4, AF_DB5, AF_DB6, AF_DB7, 0, 0, 0, 0);

	if (lcdHandle < 0)
	{
		fprintf(stderr, "lcdInit failed\n");
		exit(EXIT_FAILURE);
	}
}

void initialization(void) {
	wiringPiSetupSys();

	// --- Code snippet from http://wiringpi.com/examples/adafruit-rgb-lcd-plate-and-wiringpi/
	mcp23017Setup(AF_BASE, 0x20);
	adafruitLCDSetup(1);
	//lcdHandle = lcdInit(2, 16, 4, AF_RS, AF_E, AF_DB4, AF_DB5, AF_DB6, AF_DB7, 0, 0, 0, 0);

	if (lcdHandle < 0)
	{
		fprintf(stderr, "lcdInit failed\n");
		exit(EXIT_FAILURE);
	}
	// ---

	// Defaults setup
	currentInstrument = Instrument::Piano;
	currentOctave = Octave::Medium;

	displayChange(currentInstrument, currentOctave);
}

void instrumentChange(Instrument & currentInstrument) // Function to change instrument
{
   switch (currentInstrument)
   {
   case Piano :
      currentInstrument = Instrument::Guitar;
      break;
   case Guitar :
      currentInstrument = Instrument::Trumpet;
      break;
   case Trumpet :
      currentInstrument = Instrument::Piano;
      break;
   }

   displayChange(currentInstrument, currentOctave);
}

void octaveChange(Octave & currentOctave) // Function to change octave
{
   switch (currentOctave)
   {
   case Low:
      currentOctave = Octave::Medium;
      break;
   case Medium:
      currentOctave = Octave::High;
      break;
   case High:
      currentOctave = Octave::Low;
      break;
   }

   displayChange(currentInstrument, currentOctave);
}

void displayChange(Instrument currentInstrument, Octave currentOctave) // Function to change display values
{
    // Change instrument on display
    string instrument = "Inst: ";

    switch (currentInstrument)
    {
    case Piano :
		instrument += "Piano";
        break;
    case Guitar :
		instrument += "Guitar";
        break;
    case Trumpet :
		instrument += "Trumpet";
        break;
    }

    // Change octave on display
    string octave = "Octa: ";

    switch (currentOctave)
    {
    case Low :
		octave += "Low";
        break;
    case Medium :
		octave += "Medium";
        break;
    case High :
		octave += "High";
        break;
    }

	lcdClear(lcdHandle);

	lcdPosition(lcdHandle, 0, 0);
	lcdPuts(lcdHandle, instrument.c_str());

    lcdPosition(lcdHandle, 0, 1);
    lcdPuts(lcdHandle, octave.c_str());
}
<commit_msg>Cleaning up LCD initialization code<commit_after>#include <iostream>
#include <string>
#include <wiringPi.h>
#include <lcd.h>
#include <mcp23017.h>
#include <SFML/Audio.hpp>
#include "Main.h"

using namespace std;

int main()
{
	initialization();

	system("sleep 10");

	/*
   string currentInstrument;
   string currentOctave;

   bool instrumentButton;
   bool octaveButton;

   while (1) // Infinite loop
   {
      while (instrumentButton == 1) // While the instrument button is pressed...
      {
         if (currentInstrument == "piano")
         {
            instrumentChange("guitar", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
         else if (currentInstrument == "guitar")
         {
            instrumentChange("trumpet", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
         else
         {
            instrumentChange("piano", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
      }

      while (octaveButton == 1) // While the octave button is pressed...
      {
         if (currentOctave == "medium")
         {
            octaveChange("high", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
         else if (currentOctave == "high")
         {
            octaveChange("low", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
         else
         {
            octaveChange("medium", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
      }
   //}*/

   return 0; // Exit program
}

void initialization(void) {
	wiringPiSetupGpio();

	// --- Code snippet from http://wiringpi.com/examples/adafruit-rgb-lcd-plate-and-wiringpi/
	mcp23017Setup(AF_BASE, 0x20);

	//	Backlight LEDs
	pinMode(AF_RED, OUTPUT);
	pinMode(AF_GREEN, OUTPUT);
	pinMode(AF_BLUE, OUTPUT);
	pinMode(AF_RW, OUTPUT); digitalWrite(AF_RW, LOW);	// Not used with wiringPi - always in write mode
														// The other control pins are initialised with lcdInit ()

	lcdHandle = lcdInit(2, 16, 4, AF_RS, AF_E, AF_DB4, AF_DB5, AF_DB6, AF_DB7, 0, 0, 0, 0);

	if (lcdHandle < 0)
	{
		fprintf(stderr, "lcdInit failed\n");
		exit(EXIT_FAILURE);
	}
	// ---

	// Defaults setup
	currentInstrument = Instrument::Piano;
	currentOctave = Octave::Medium;

	displayChange(currentInstrument, currentOctave);
}

void instrumentChange(Instrument & currentInstrument) // Function to change instrument
{
   switch (currentInstrument)
   {
   case Piano :
      currentInstrument = Instrument::Guitar;
      break;
   case Guitar :
      currentInstrument = Instrument::Trumpet;
      break;
   case Trumpet :
      currentInstrument = Instrument::Piano;
      break;
   }

   displayChange(currentInstrument, currentOctave);
}

void octaveChange(Octave & currentOctave) // Function to change octave
{
   switch (currentOctave)
   {
   case Low:
      currentOctave = Octave::Medium;
      break;
   case Medium:
      currentOctave = Octave::High;
      break;
   case High:
      currentOctave = Octave::Low;
      break;
   }

   displayChange(currentInstrument, currentOctave);
}

void displayChange(Instrument currentInstrument, Octave currentOctave) // Function to change display values
{
    // Change instrument on display
    string instrument = "Inst: ";

    switch (currentInstrument)
    {
    case Piano :
		instrument += "Piano";
        break;
    case Guitar :
		instrument += "Guitar";
        break;
    case Trumpet :
		instrument += "Trumpet";
        break;
    }

    // Change octave on display
    string octave = "Octa: ";

    switch (currentOctave)
    {
    case Low :
		octave += "Low";
        break;
    case Medium :
		octave += "Medium";
        break;
    case High :
		octave += "High";
        break;
    }

	lcdClear(lcdHandle);

	lcdPosition(lcdHandle, 0, 0);
	lcdPuts(lcdHandle, instrument.c_str());

    lcdPosition(lcdHandle, 0, 1);
    lcdPuts(lcdHandle, octave.c_str());
}
<|endoftext|>


<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2012 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include "rhodes/JNIRhodes.h"
#include "common/RhoConf.h"
#include "Push.h"
#include "sync/RhoconnectClientManager.h"
#include "sync/ILoginListener.h"

#include "logging/RhoLog.h"

#include "gcmpushclient.h"

//----------------------------------------------------------------------------------------------------------------------
extern "C" void Init_GCMPushClient()
{
    // create GCM push client
    RAWTRACEC("Init_GCMPushClient", "creating GCM client >>>>>>>>>>>>>>");

    rho::gcm::GcmPushClient* pClient = new rho::gcm::GcmPushClient();

    RAWTRACEC("Init_GCMPushClient", "adding GCM client >>>>>>>>>>>>>>>>");

    rho::push::CPushManager::getInstance()->addClient(pClient);

}
//----------------------------------------------------------------------------------------------------------------------

namespace rho { namespace gcm {

IMPLEMENT_LOGCLASS(GcmPushClient, "GcmPushClient");

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

const char* const GcmPushClient::s_GCM_FACADE_CLASS = "com.rhomobile.rhodes.gcm.GCMFacade";

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::doRegister()
{
    LOG(TRACE) + "GcmPushRegister()";

    JNIEnv *env = jnienv();

    static jclass cls = rho_find_class(env, s_GCM_FACADE_CLASS);
    if (!cls) {
        LOG(ERROR) + "Cannot find class: " + s_GCM_FACADE_CLASS;
        return;
    }

    static jmethodID mid = env->GetStaticMethodID(cls, "Register", "(Ljava/lang/String;)V");
    if (!mid) {
        LOG(ERROR) + "Cannot get " + s_GCM_FACADE_CLASS + ".Register() method";
        return;
    }

    jhstring jhSenderId = rho_cast<jstring>(m_hashProps["senderId"]);

    env->CallStaticVoidMethod(cls, mid, jhSenderId.get());
}

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::doUnregister()
{
    LOG(TRACE) + "GcmPushUnregister()";

    JNIEnv *env = jnienv();

    static jclass cls = rho_find_class(env, s_GCM_FACADE_CLASS);
    if (!cls) {
        LOG(ERROR) + "Cannot find class: " + s_GCM_FACADE_CLASS;
        return;
    }

    static jmethodID mid = env->GetStaticMethodID(cls, "Unregister", "()V");
    if (!mid) {
        LOG(ERROR) + "Cannot get " + s_GCM_FACADE_CLASS + ".Unregister() method";
        return;
    }

    env->CallStaticVoidMethod(cls, mid);
}
//----------------------------------------------------------------------------------------------------------------------
const String GcmPushClient::s_Type = "gcm";

GcmPushClient::GcmPushClient()
{
    CMethodResult result;
    setProperty("id", s_Type, result);
    setProperty("type", IPush::PUSH_TYPE_NATIVE, result);
    setProperty("senderId", RHOCONF().getString("Push.gcm.senderId"), result);

    LOG(TRACE) + "request GCM registration >>>>>>>>>>>>>>>>";
    doRegister();
}

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

void GcmPushClient::getDeviceId(CMethodResult& result)
{
    String deviceId = m_hashProps["deviceId"];

    if(deviceId.length() != 0)
    {
        LOG(TRACE) + "GCM deviceId: " + deviceId;
        result.set(deviceId);
    }
    else
    {
        LOG(TRACE) + "Still waiting for GCM deviceId";
        m_deviceIdResult = result;
    }
}

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::startNotifications(CMethodResult& result)
{
    LOG(TRACE) + "Start GCM push notifications";
    m_oResult = result;
}

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::stopNotifications(CMethodResult& result)
{
    LOG(TRACE) + "Stop GCM push notifications";
    m_oResult = CMethodResult();
}

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::setDeviceId(const String& deviceId)
{
    CMethodResult result;
    setProperty("deviceId", deviceId, result);

    LOG(TRACE) + "creating client register";
    rho::sync::RhoconnectClientManager::clientRegisterCreate(deviceId.c_str());

    getDeviceId(m_deviceIdResult);
    m_deviceIdResult = CMethodResult();

}

//----------------------------------------------------------------------------------------------------------------------
bool GcmPushClient::callBack(const String& json)
{
    LOG(TRACE) + "GCM push notification: " + json;

    m_oResult.setJSON(json);

    return true;
}

}}

<commit_msg>Android: Fix GCM push registration<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2012 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include "rhodes/JNIRhodes.h"
#include "common/RhoConf.h"
#include "Push.h"
#include "sync/RhoconnectClientManager.h"
#include "sync/ILoginListener.h"

#include "logging/RhoLog.h"

#include "gcmpushclient.h"

//----------------------------------------------------------------------------------------------------------------------
extern "C" void Init_GCMPushClient()
{
    // create GCM push client
    RAWTRACEC("Init_GCMPushClient", "creating GCM client >>>>>>>>>>>>>>");

    rho::gcm::GcmPushClient* pClient = new rho::gcm::GcmPushClient();

    RAWTRACEC("Init_GCMPushClient", "adding GCM client >>>>>>>>>>>>>>>>");

    rho::push::CPushManager::getInstance()->addClient(pClient);

    RAWTRACEC("Init_GCMPushClient", "request GCM registration >>>>>>>>>>>>>>>>");

    pClient->doRegister();

}
//----------------------------------------------------------------------------------------------------------------------

namespace rho { namespace gcm {

IMPLEMENT_LOGCLASS(GcmPushClient, "GcmPushClient");

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

const char* const GcmPushClient::s_GCM_FACADE_CLASS = "com.rhomobile.rhodes.gcm.GCMFacade";

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::doRegister()
{
    LOG(TRACE) + "GcmPushRegister()";

    JNIEnv *env = jnienv();

    static jclass cls = rho_find_class(env, s_GCM_FACADE_CLASS);
    if (!cls) {
        LOG(ERROR) + "Cannot find class: " + s_GCM_FACADE_CLASS;
        return;
    }

    static jmethodID mid = env->GetStaticMethodID(cls, "Register", "(Ljava/lang/String;)V");
    if (!mid) {
        LOG(ERROR) + "Cannot get " + s_GCM_FACADE_CLASS + ".Register() method";
        return;
    }

    jhstring jhSenderId = rho_cast<jstring>(m_hashProps["senderId"]);

    env->CallStaticVoidMethod(cls, mid, jhSenderId.get());
}

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::doUnregister()
{
    LOG(TRACE) + "GcmPushUnregister()";

    JNIEnv *env = jnienv();

    static jclass cls = rho_find_class(env, s_GCM_FACADE_CLASS);
    if (!cls) {
        LOG(ERROR) + "Cannot find class: " + s_GCM_FACADE_CLASS;
        return;
    }

    static jmethodID mid = env->GetStaticMethodID(cls, "Unregister", "()V");
    if (!mid) {
        LOG(ERROR) + "Cannot get " + s_GCM_FACADE_CLASS + ".Unregister() method";
        return;
    }

    env->CallStaticVoidMethod(cls, mid);
}
//----------------------------------------------------------------------------------------------------------------------
const String GcmPushClient::s_Type = "gcm";

GcmPushClient::GcmPushClient()
{
    CMethodResult result;
    setProperty("id", s_Type, result);
    setProperty("type", IPush::PUSH_TYPE_NATIVE, result);
    setProperty("senderId", RHOCONF().getString("Push.gcm.senderId"), result);
}

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

void GcmPushClient::getDeviceId(CMethodResult& result)
{
    String deviceId = m_hashProps["deviceId"];

    if(deviceId.length() != 0)
    {
        LOG(TRACE) + "GCM deviceId: " + deviceId;
        result.set(deviceId);
    }
    else
    {
        LOG(TRACE) + "Still waiting for GCM deviceId";
        m_deviceIdResult = result;
    }
}

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::startNotifications(CMethodResult& result)
{
    LOG(TRACE) + "Start GCM push notifications";
    m_oResult = result;
}

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::stopNotifications(CMethodResult& result)
{
    LOG(TRACE) + "Stop GCM push notifications";
    m_oResult = CMethodResult();
}

//----------------------------------------------------------------------------------------------------------------------
void GcmPushClient::setDeviceId(const String& deviceId)
{
    CMethodResult result;
    setProperty("deviceId", deviceId, result);

    LOG(TRACE) + "creating client register";
    rho::sync::RhoconnectClientManager::clientRegisterCreate(deviceId.c_str());

    getDeviceId(m_deviceIdResult);
    m_deviceIdResult = CMethodResult();

}

//----------------------------------------------------------------------------------------------------------------------
bool GcmPushClient::callBack(const String& json)
{
    LOG(TRACE) + "GCM push notification: " + json;

    m_oResult.setJSON(json);

    return true;
}

}}

<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main()
{
   cout << "Hello world.\n";

   system("pause");
   return 0;
}<commit_msg>Program Outline<commit_after>#include <iostream>
#include <string>
#include <wiringPi.h>
using namespace std;

void instrumentChange(string, &string);
void octaveChange(string, string, &string);
void displayChange(string, string);

// Press a button to turn on the piano and display

int main()
{
   string currentInstrument;
   string currentOctave;

   // Default settings for piano
   instrumentChange("piano", currentInstrument);
   octaveChange("piano", "medium", currentOctave);

   // Default settings for display
   displayChange(currentInstrument, currentOctave);

   bool offButton;
   bool instrumentButton;
   bool octaveButton;

   while (offButton != 1) // While the off button isn't pressed...
   {
      while (instrumentButton == 1) // While the instrument button is pressed...
      {
         if (currentInstrument == "piano")
         {
            instrumentChange("guitar", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
         else if (currentInstrument == "guitar")
         {
            instrumentChange("trumpet", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
         else
         {
            instrumentChange("piano", currentInstrument);
            displayChange(currentInstrument, currentOctave);
         }
      }

      while (octaveButton == 1) // While the octave button is pressed...
      {
         if (currentOctave == "medium")
         {
            octaveChange("high", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
         else if (currentOctave == "high")
         {
            octaveChange("low", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
         else
         {
            octaveChange("medium", currentOctave);
            displayChange(currentInstrument, currentOctave);
         }
      }
   }

   return 0; // Exit program
}

void instrumentChange(string instrument, string &newInstrument) // Function for changing instruments
{
   if (instrument == "piano")
   {
      // Switch all button sound files to medium piano

      newInstrument = "piano";
   }
   else if (instrument == "guitar")
   {
      // Switch all button sound files to medium guitar

      newInstrument = "guitar";
   }
   else
   {
      // Switch all button sound files to medium trumpet

      newInstrument = "trumpet"
   }
}

void octaveChange(string instrument, string octave, string &newOctave) // Function for changing octaves
{
   if (instrument == "piano")
   {
      if (octave == "low")
      {
         // Switch all button sound files to low piano

         newOctave = "low";
      }
      else if (octave == "medium")
      {
         // Switch all button sound files to medium piano

         newOctave = "medium";
      }
      else
      {
         // Switch all button sound files to high piano

         newOctave = "high";
      }
   }
   else if (instrument == "guitar")
   {
      if (octave == "low")
      {
         // Switch all button sound files to low guitar

         newOctave = "low";
      }
      else if (octave == "medium")
      {
         // Switch all button sound files to medium guitar

         newOctave = "medium";
      }
      else
      {
         // Switch all button sound files to high guitar

         newOctave = "high";
      }
   }
   else
   {
      if (octave == "low")
      {
         // Switch all button sound files to low trumpet

         newOctave = "low";
      }
      else if (octave == "medium")
      {
         // Switch all button sound files to medium trumpet

         newOctave = "medium";
      }
      else
      {
         // Switch all button sound files to high trumpet

         newOctave = "high";
      }
   }

   void displayChange(string instrument, string octave)
   {
      // Displays instrument and octave
      cout << "Instrument: " << instrument << endl;
      cout << "Octave: " << octave;
   }
}<|endoftext|>


<commit_before>/*
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * - Neither the name of prim nor the names of its contributors may be used to
 * endorse or promote products derived from this software without specific prior
 * written permission.
 *
 * See the NOTICE file distributed with this work for additional information
 * regarding copyright ownership.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <gtest/gtest.h>
#include <prim/prim.h>

#include <cmath>
#include <ctime>

#include <deque>
#include <list>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "rnd/Random.h"

TEST(Random, seed) {
  const u64 kRands = 1000;

  // initialize a bunch of Random objects
  std::vector<rnd::Random*> rands;
  for (u64 i = 0; i < kRands; i++) {
    rands.push_back(new rnd::Random((i+1) << 32));
  }

  // get the first value of each random
  std::vector<u64> values;
  for (u64 i = 0; i < kRands; i++) {
    values.push_back(rands[i]->nextU64(0, U64_MAX));
  }

  // re-seed each random, verify the random produces the same value
  for (u64 n = 0; n < 5; n++) {
    for (u64 i = 0; i < kRands; i++) {
      rands[i]->seed((i+1) << 32);
      u64 value = rands.at(i)->nextU64(0, U64_MAX);
      ASSERT_EQ(value, values.at(i));
    }
  }

  // cleanup the Random objects
  for (u64 i = 0; i < kRands; i++) {
    delete rands[i];
  }
}

TEST(Random, u64) {
  const u64 kBkts = 1000;
  const u64 kRounds = 10000000;
  std::vector<u64> buckets(kBkts, 0);
  rnd::Random rand(0xDEADBEEF12345678lu);

  for (u64 r = 0; r < kRounds; r++) {
    u64 value = rand.nextF64(0, kBkts);
    buckets.at(value)++;
  }

  f64 sum = 0;
  for (u64 b = 0; b < kBkts; b++) {
    sum += buckets.at(b);
    // printf("[%lu] = %lu\n", b, buckets.at(b));
  }
  f64 mean = sum / kBkts;

  sum = 0;
  for (u64 b = 0; b < kBkts; b++) {
    f64 c = (static_cast<f64>(buckets.at(b)) - mean);
    c *= c;
    sum += c;
  }
  f64 stdDev = std::sqrt(sum / kBkts);
  // printf("stdDev = %f\n", stdDev);
  stdDev /= kRounds;
  // printf("relStdDev = %f\n", stdDev);
  ASSERT_LE(stdDev, 0.00009);
}

TEST(Random, f64) {
  const u64 kBkts = 1000;
  const u64 kRounds = 10000000;
  std::vector<u64> buckets(kBkts, 0);
  rnd::Random rand(0xDEADBEEF12345678lu);

  for (u64 r = 0; r < kRounds; r++) {
    f64 value = rand.nextF64(0, 1000);
    buckets.at(static_cast<u64>(value))++;
  }

  f64 sum = 0;
  for (u64 b = 0; b < kBkts; b++) {
    sum += buckets.at(b);
    // printf("[%lu] = %lu\n", b, buckets.at(b));
  }
  f64 mean = sum / kBkts;

  sum = 0;
  for (u64 b = 0; b < kBkts; b++) {
    f64 c = (static_cast<f64>(buckets.at(b)) - mean);
    c *= c;
    sum += c;
  }
  f64 stdDev = std::sqrt(sum / kBkts);
  // printf("stdDev = %f\n", stdDev);
  stdDev /= kRounds;
  // printf("relStdDev = %f\n", stdDev);
  ASSERT_LE(stdDev, 0.00009);
}

TEST(Random, bool) {
  const u64 kRounds = 100000000;

  // use a non-deterministic RNG to seed our deterministic PRNG
  srand(time(nullptr));
  for (u64 t = 0; t < 10; t++) {
    u64 seed = 0;
    for (u64 b = 0; b < sizeof(u64); b++) {
      u64 byte = rand() % 0xFF;  // NOLINT
      seed = (seed << 8) | byte;
    }

    rnd::Random rand(seed);

    u64 count = 0;
    for (u64 r = 0; r < kRounds; r++) {
      if (rand.nextBool()) {
        count++;
      }
    }

    f64 ratio = static_cast<f64>(count) / kRounds;
    f64 dev = std::abs(0.5 - ratio);
    // printf("ratio %.15f\n", ratio);
    // printf("dev %.15f\n", dev);
    ASSERT_LE(dev, 0.0002);
  }
}

TEST(Random, shuffle) {
  const u64 kSize = 100;
  const u64 kRounds = 1000000;

  // make base vector
  std::vector<u64> a;
  for (u64 idx = 0; idx < kSize; idx++) {
    a.push_back(idx);
  }

  // test seeding reproduces same shuffle
  rnd::Random rand(123);
  std::vector<u64> b = a;
  std::vector<u64> c = a;
  rand.shuffle(b.begin(), b.end());  // iterator version
  rand.seed(123);
  rand.shuffle(&c);  // container version
  ASSERT_EQ(b, c);

  // generate distribution
  std::vector<u64> buckets(kSize, 0);
  for (u32 round = 0; round < kRounds; round++) {
    // make a copy
    std::vector<u64> d = a;

    // shuffle it
    if (round % 2 == 0) {
      rand.shuffle(d.begin(), d.end());
    } else {
      rand.shuffle(&d);
    }

    // find where element 0 landed
    bool found = false;
    for (u64 idx = 0; idx < kSize; idx++) {
      if (d[idx] == 0) {
        buckets.at(idx)++;
        found = true;
        break;
      }
    }
    ASSERT_TRUE(found);
  }

  // verify distribution is uniform
  f64 sum = 0;
  for (u64 b = 0; b < kSize; b++) {
    sum += buckets.at(b);
    // printf("[%lu] = %lu\n", b, buckets.at(b));
  }
  f64 mean = sum / kSize;
  sum = 0;
  for (u64 b = 0; b < kSize; b++) {
    f64 c = (static_cast<f64>(buckets.at(b)) - mean);
    c *= c;
    sum += c;
  }
  f64 stdDev = std::sqrt(sum / kSize);
  // printf("stdDev = %f\n", stdDev);
  stdDev /= kRounds;
  // printf("relStdDev = %f\n", stdDev);
  ASSERT_LE(stdDev, 0.00015);
}

TEST(Random, retrieve) {
  rnd::Random rnd(12345678);

  const std::set<u32> SVALS({1, 2, 3, 4});
  const std::set<std::pair<u32, u32> > PVALS(
      {{1, 1}, {2, 2}, {3, 3}, {4, 4}});

  std::deque<u32> deque({1, 2, 3, 4});
  std::list<u32> list({1, 2, 3, 4});
  std::vector<u32> vector({1, 2, 3, 4});
  std::set<u32> oset({1, 2, 3, 4});
  std::map<u32, u32> omap({{1, 1}, {2, 2}, {3, 3}, {4, 4}});
  std::unordered_set<u32> uset({1, 2, 3, 4});
  std::unordered_map<u32, u32> umap({{1, 1}, {2, 2}, {3, 3}, {4, 4}});

  u32 r;
  std::pair<u32, u32> p;

  r = rnd.retrieve(&deque);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(deque.size(), 4u);

  r = rnd.retrieve(&list);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(list.size(), 4u);

  r = rnd.retrieve(&vector);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(vector.size(), 4u);

  r = rnd.retrieve(&oset);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(oset.size(), 4u);

  p = rnd.retrieve(&omap);
  ASSERT_EQ(PVALS.count(p), 1u);
  ASSERT_EQ(omap.size(), 4u);

  r = rnd.retrieve(&uset);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(uset.size(), 4u);

  p = rnd.retrieve(&umap);
  ASSERT_EQ(PVALS.count(p), 1u);
  ASSERT_EQ(umap.size(), 4u);
}

TEST(Random, remove) {
  rnd::Random rnd(12345678);

  const std::set<u32> SVALS({1, 2, 3, 4});
  const std::set<std::pair<u32, u32> > PVALS(
      {{1, 1}, {2, 2}, {3, 3}, {4, 4}});

  std::deque<u32> deque({1, 2, 3, 4});
  std::list<u32> list({1, 2, 3, 4});
  std::vector<u32> vector({1, 2, 3, 4});
  std::set<u32> oset({1, 2, 3, 4});
  std::map<u32, u32> omap({{1, 1}, {2, 2}, {3, 3}, {4, 4}});
  std::unordered_set<u32> uset({1, 2, 3, 4});
  std::unordered_map<u32, u32> umap({{1, 1}, {2, 2}, {3, 3}, {4, 4}});

  u32 r;
  std::pair<u32, u32> p;

  r = rnd.remove(&deque);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(deque.size(), 3u);

  r = rnd.remove(&list);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(list.size(), 3u);

  r = rnd.remove(&vector);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(vector.size(), 3u);

  r = rnd.remove(&oset);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(oset.size(), 3u);

  p = rnd.remove(&omap);
  ASSERT_EQ(PVALS.count(p), 1u);
  ASSERT_EQ(omap.size(), 3u);

  r = rnd.remove(&uset);
  ASSERT_EQ(SVALS.count(r), 1u);
  ASSERT_EQ(uset.size(), 3u);

  p = rnd.remove(&umap);
  ASSERT_EQ(PVALS.count(p), 1u);
  ASSERT_EQ(umap.size(), 3u);
}
<commit_msg>more unit testing on Random.remove<commit_after>/*
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * - Neither the name of prim nor the names of its contributors may be used to
 * endorse or promote products derived from this software without specific prior
 * written permission.
 *
 * See the NOTICE file distributed with this work for additional information
 * regarding copyright ownership.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <gtest/gtest.h>
#include <prim/prim.h>

#include <cmath>
#include <ctime>

#include <deque>
#include <list>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "rnd/Random.h"

TEST(Random, seed) {
  const u64 kRands = 1000;

  // initialize a bunch of Random objects
  std::vector<rnd::Random*> rands;
  for (u64 i = 0; i < kRands; i++) {
    rands.push_back(new rnd::Random((i+1) << 32));
  }

  // get the first value of each random
  std::vector<u64> values;
  for (u64 i = 0; i < kRands; i++) {
    values.push_back(rands[i]->nextU64(0, U64_MAX));
  }

  // re-seed each random, verify the random produces the same value
  for (u64 n = 0; n < 5; n++) {
    for (u64 i = 0; i < kRands; i++) {
      rands[i]->seed((i+1) << 32);
      u64 value = rands.at(i)->nextU64(0, U64_MAX);
      ASSERT_EQ(value, values.at(i));
    }
  }

  // cleanup the Random objects
  for (u64 i = 0; i < kRands; i++) {
    delete rands[i];
  }
}

TEST(Random, u64) {
  const u64 kBkts = 1000;
  const u64 kRounds = 10000000;
  std::vector<u64> buckets(kBkts, 0);
  rnd::Random rand(0xDEADBEEF12345678lu);

  for (u64 r = 0; r < kRounds; r++) {
    u64 value = rand.nextF64(0, kBkts);
    buckets.at(value)++;
  }

  f64 sum = 0;
  for (u64 b = 0; b < kBkts; b++) {
    sum += buckets.at(b);
    // printf("[%lu] = %lu\n", b, buckets.at(b));
  }
  f64 mean = sum / kBkts;

  sum = 0;
  for (u64 b = 0; b < kBkts; b++) {
    f64 c = (static_cast<f64>(buckets.at(b)) - mean);
    c *= c;
    sum += c;
  }
  f64 stdDev = std::sqrt(sum / kBkts);
  // printf("stdDev = %f\n", stdDev);
  stdDev /= kRounds;
  // printf("relStdDev = %f\n", stdDev);
  ASSERT_LE(stdDev, 0.00009);
}

TEST(Random, f64) {
  const u64 kBkts = 1000;
  const u64 kRounds = 10000000;
  std::vector<u64> buckets(kBkts, 0);
  rnd::Random rand(0xDEADBEEF12345678lu);

  for (u64 r = 0; r < kRounds; r++) {
    f64 value = rand.nextF64(0, 1000);
    buckets.at(static_cast<u64>(value))++;
  }

  f64 sum = 0;
  for (u64 b = 0; b < kBkts; b++) {
    sum += buckets.at(b);
    // printf("[%lu] = %lu\n", b, buckets.at(b));
  }
  f64 mean = sum / kBkts;

  sum = 0;
  for (u64 b = 0; b < kBkts; b++) {
    f64 c = (static_cast<f64>(buckets.at(b)) - mean);
    c *= c;
    sum += c;
  }
  f64 stdDev = std::sqrt(sum / kBkts);
  // printf("stdDev = %f\n", stdDev);
  stdDev /= kRounds;
  // printf("relStdDev = %f\n", stdDev);
  ASSERT_LE(stdDev, 0.00009);
}

TEST(Random, bool) {
  const u64 kRounds = 100000000;

  // use a non-deterministic RNG to seed our deterministic PRNG
  srand(time(nullptr));
  for (u64 t = 0; t < 10; t++) {
    u64 seed = 0;
    for (u64 b = 0; b < sizeof(u64); b++) {
      u64 byte = rand() % 0xFF;  // NOLINT
      seed = (seed << 8) | byte;
    }

    rnd::Random rand(seed);

    u64 count = 0;
    for (u64 r = 0; r < kRounds; r++) {
      if (rand.nextBool()) {
        count++;
      }
    }

    f64 ratio = static_cast<f64>(count) / kRounds;
    f64 dev = std::abs(0.5 - ratio);
    // printf("ratio %.15f\n", ratio);
    // printf("dev %.15f\n", dev);
    ASSERT_LE(dev, 0.0002);
  }
}

TEST(Random, shuffle) {
  const u64 kSize = 100;
  const u64 kRounds = 1000000;

  // make base vector
  std::vector<u64> a;
  for (u64 idx = 0; idx < kSize; idx++) {
    a.push_back(idx);
  }

  // test seeding reproduces same shuffle
  rnd::Random rand(123);
  std::vector<u64> b = a;
  std::vector<u64> c = a;
  rand.shuffle(b.begin(), b.end());  // iterator version
  rand.seed(123);
  rand.shuffle(&c);  // container version
  ASSERT_EQ(b, c);

  // generate distribution
  std::vector<u64> buckets(kSize, 0);
  for (u32 round = 0; round < kRounds; round++) {
    // make a copy
    std::vector<u64> d = a;

    // shuffle it
    if (round % 2 == 0) {
      rand.shuffle(d.begin(), d.end());
    } else {
      rand.shuffle(&d);
    }

    // find where element 0 landed
    bool found = false;
    for (u64 idx = 0; idx < kSize; idx++) {
      if (d[idx] == 0) {
        buckets.at(idx)++;
        found = true;
        break;
      }
    }
    ASSERT_TRUE(found);
  }

  // verify distribution is uniform
  f64 sum = 0;
  for (u64 b = 0; b < kSize; b++) {
    sum += buckets.at(b);
    // printf("[%lu] = %lu\n", b, buckets.at(b));
  }
  f64 mean = sum / kSize;
  sum = 0;
  for (u64 b = 0; b < kSize; b++) {
    f64 c = (static_cast<f64>(buckets.at(b)) - mean);
    c *= c;
    sum += c;
  }
  f64 stdDev = std::sqrt(sum / kSize);
  // printf("stdDev = %f\n", stdDev);
  stdDev /= kRounds;
  // printf("relStdDev = %f\n", stdDev);
  ASSERT_LE(stdDev, 0.00015);
}

TEST(Random, retrieve) {
  rnd::Random rnd(12345678);

  const std::set<u32> kSingleVals({1, 2, 3, 4});
  const std::set<std::pair<u32, u32> > kPairVals(
      {{1, 1}, {2, 2}, {3, 3}, {4, 4}});

  std::deque<u32> deque({1, 2, 3, 4});
  std::list<u32> list({1, 2, 3, 4});
  std::vector<u32> vector({1, 2, 3, 4});
  std::set<u32> oset({1, 2, 3, 4});
  std::map<u32, u32> omap({{1, 1}, {2, 2}, {3, 3}, {4, 4}});
  std::unordered_set<u32> uset({1, 2, 3, 4});
  std::unordered_map<u32, u32> umap({{1, 1}, {2, 2}, {3, 3}, {4, 4}});

  u32 r;
  std::pair<u32, u32> p;

  r = rnd.retrieve(&deque);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(deque.size(), 4u);

  r = rnd.retrieve(&list);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(list.size(), 4u);

  r = rnd.retrieve(&vector);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(vector.size(), 4u);

  r = rnd.retrieve(&oset);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(oset.size(), 4u);

  p = rnd.retrieve(&omap);
  ASSERT_EQ(kPairVals.count(p), 1u);
  ASSERT_EQ(omap.size(), 4u);

  r = rnd.retrieve(&uset);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(uset.size(), 4u);

  p = rnd.retrieve(&umap);
  ASSERT_EQ(kPairVals.count(p), 1u);
  ASSERT_EQ(umap.size(), 4u);
}

TEST(Random, remove) {
  rnd::Random rnd(12345678);

  const std::set<u32> kSingleVals({1, 2, 3, 4});
  const std::set<std::pair<u32, u32> > kPairVals(
      {{1, 1}, {2, 2}, {3, 3}, {4, 4}});

  std::deque<u32> deque({1, 2, 3, 4});
  std::list<u32> list({1, 2, 3, 4});
  std::vector<u32> vector({1, 2, 3, 4});
  std::set<u32> oset({1, 2, 3, 4});
  std::map<u32, u32> omap({{1, 1}, {2, 2}, {3, 3}, {4, 4}});
  std::unordered_set<u32> uset({1, 2, 3, 4});
  std::unordered_map<u32, u32> umap({{1, 1}, {2, 2}, {3, 3}, {4, 4}});

  u32 r;
  std::pair<u32, u32> p;

  r = rnd.remove(&deque);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(deque.size(), 3u);

  r = rnd.remove(&list);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(list.size(), 3u);

  r = rnd.remove(&vector);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(vector.size(), 3u);

  r = rnd.remove(&oset);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(oset.size(), 3u);

  p = rnd.remove(&omap);
  ASSERT_EQ(kPairVals.count(p), 1u);
  ASSERT_EQ(omap.size(), 3u);

  r = rnd.remove(&uset);
  ASSERT_EQ(kSingleVals.count(r), 1u);
  ASSERT_EQ(uset.size(), 3u);

  p = rnd.remove(&umap);
  ASSERT_EQ(kPairVals.count(p), 1u);
  ASSERT_EQ(umap.size(), 3u);
}

TEST(Random, removeDist) {
  rnd::Random rnd(12345678);

  const std::set<u32> kSingleVals({1, 2, 3, 4});
  std::vector<u32> counts(4, 0);

  const u32 kRounds = 1000000;
  for (u32 r = 0; r < kRounds; r++) {
    std::unordered_set<u32> uset({1, 2, 3, 4});
    u32 v = rnd.remove(&uset);
    ASSERT_EQ(kSingleVals.count(v), 1u);
    ASSERT_EQ(uset.size(), 3u);
    counts.at(v - 1)++;
  }

  for (u32 c = 0; c < counts.size(); c++) {
    ASSERT_NEAR(counts.at(c), kRounds / 4.0, 0.001 * kRounds);
  }
}
<|endoftext|>


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

#include "EratMedium.h"
#include "SieveOfEratosthenes.h"
#include "EratBase.h"
#include "WheelFactorization.h"
#include "defs.h"

#include <algorithm>
#include <list>

EratMedium::EratMedium(const SieveOfEratosthenes& soe) :
  EratBase<Modulo210Wheel_t, WheelPrime_2> (soe)
{
  static_assert(defs::ERATMEDIUM_FACTOR <= 15, "defs::ERATMEDIUM_FACTOR <= 15");
  uint32_t sqrtStop = soe.getSquareRoot();
  uint32_t max      = soe.getSieveSize() * defs::ERATMEDIUM_FACTOR;
  uint32_t limit    = std::min<uint32_t>(sqrtStop, max);
  this->setLimit(limit);
}

/**
 * Implementation of the segmented sieve of Eratosthenes with wheel
 * factorization optimized for medium sieving primes with a few
 * multiples per segment.
 * This implementation uses a sieve array with 30 numbers per byte and
 * a modulo 210 wheel that skips multiples of 2, 3, 5 and 7.
 * @see SieveOfEratosthenes::crossOffMultiples()
 */
void EratMedium::sieve(uint8_t* sieve, uint32_t sieveSize)
{
  std::list<Bucket_t>::iterator bucket     = buckets_.begin();
  std::list<Bucket_t>::iterator bucketsEnd = buckets_.end();
  for (; bucket != bucketsEnd; ++bucket)
  {
    WheelPrime_t* wPrime = bucket->begin();
    WheelPrime_t* end    = bucket->end();
    // remove the multiples of sieving primes within the
    // current bucket from the sieve array
    for (; wPrime != end; wPrime++) {
      uint32_t sievingPrime = wPrime->getSievingPrime();
      uint32_t wheelIndex   = wPrime->getWheelIndex();
      uint32_t sieveIndex   = wPrime->getSieveIndex();
      // cross-off the multiples (unset corresponding bits) of the
      // current sieving prime within the sieve array
      while (sieveIndex < sieveSize) {
        uint32_t unsetBit = wheel(wheelIndex)->unsetBit;
        uint32_t factor   = wheel(wheelIndex)->nextMultipleFactor;
        uint32_t correct  = wheel(wheelIndex)->correct;
         int32_t next     = wheel(wheelIndex)->next;
        sieve[sieveIndex] &= unsetBit;
        wheelIndex += next;
        sieveIndex += sievingPrime * factor + correct;
      }
      sieveIndex -= sieveSize;
      // set sieveIndex and wheelIndex for the next segment
      wPrime->set(sievingPrime, sieveIndex, wheelIndex);
    }
  }
}
<commit_msg>removed premature optimization<commit_after>//
// Copyright (c) 2011 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//   * Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above
//     copyright notice, this list of conditions and the following
//     disclaimer in the documentation and/or other materials provided
//     with the distribution.
//   * Neither the name of the author nor the names of its
//     contributors may be used to endorse or promote products derived
//     from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

#include "EratMedium.h"
#include "SieveOfEratosthenes.h"
#include "EratBase.h"
#include "WheelFactorization.h"
#include "defs.h"

#include <algorithm>
#include <list>

EratMedium::EratMedium(const SieveOfEratosthenes& soe) :
  EratBase<Modulo210Wheel_t, WheelPrime_2> (soe)
{
  static_assert(defs::ERATMEDIUM_FACTOR <= 15, "defs::ERATMEDIUM_FACTOR <= 15");
  uint32_t sqrtStop = soe.getSquareRoot();
  uint32_t max      = soe.getSieveSize() * defs::ERATMEDIUM_FACTOR;
  uint32_t limit    = std::min<uint32_t>(sqrtStop, max);
  this->setLimit(limit);
}

/**
 * Implementation of the segmented sieve of Eratosthenes with wheel
 * factorization optimized for medium sieving primes with a few
 * multiples per segment.
 * This implementation uses a sieve array with 30 numbers per byte and
 * a modulo 210 wheel that skips multiples of 2, 3, 5 and 7.
 * @see SieveOfEratosthenes::crossOffMultiples()
 */
void EratMedium::sieve(uint8_t* sieve, uint32_t sieveSize)
{
  for (BucketList_t::iterator bucket = buckets_.begin(); bucket != buckets_.end(); ++bucket) {
    WheelPrime_t* wPrime = bucket->begin();
    WheelPrime_t* end    = bucket->end();
    // remove the multiples of sieving primes within the
    // current bucket from the sieve array
    for (; wPrime != end; wPrime++) {
      uint32_t sieveIndex   = wPrime->getSieveIndex();
      uint32_t wheelIndex   = wPrime->getWheelIndex();
      uint32_t sievingPrime = wPrime->getSievingPrime();
      // cross-off the multiples (unset corresponding bits) of the
      // current sieving prime within the sieve array
      while (sieveIndex < sieveSize) {
        sieve[sieveIndex] &= wheel(wheelIndex)->unsetBit;
        sieveIndex        += wheel(wheelIndex)->nextMultipleFactor * sievingPrime;
        sieveIndex        += wheel(wheelIndex)->correct;
        wheelIndex        += wheel(wheelIndex)->next;
      }
      sieveIndex -= sieveSize;
      // set sieveIndex and wheelIndex for the next segment
      wPrime->set(sievingPrime, sieveIndex, wheelIndex);
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Removed image-to-ground and ground-to-image.  there is an option that already does these.  Fixed explanation of one of the options<commit_after><|endoftext|>


<commit_before>// Thanks to Scott Gray (OpenAI) for the idea to pass the arguments
// as a string constructed with struct.pack in python

#include "triton/driver/buffer.h"
#include "triton/driver/stream.h"
#include "triton/runtime/function.h"
#include "triton/tools/bench.hpp"
#include "torch/script.h"
#include "ATen/cuda/CUDAContext.h"

namespace rt = triton::runtime;
namespace drv = triton::driver;

typedef std::pair<int, int> map_key_t;
extern std::map<map_key_t, std::shared_ptr<rt::function::grid_fn_ty>> id_grid_map;
extern std::map<map_key_t, std::shared_ptr<rt::function>> id_fn_map;
std::shared_ptr<drv::device> host_device;
std::shared_ptr<drv::context> host_context;
std::shared_ptr<drv::stream> host_stream;

int64_t cdiv_sum(torch::Tensor x, int64_t div){
  TORCH_CHECK(!x.is_cuda(), "Argument of cdiv_sum must be a CPU tensor")
  auto _x  = x.accessor<int, 1>();
  int64_t ret = 0;
  for(size_t i = 0; i < x.size(0); i++)
    ret += (_x[i] + div - 1) / div;
  return ret;
}

void init_host_stream() {
  if(!host_stream){
    host_device.reset(new drv::host_device());
    host_context.reset(drv::context::create(&*host_device));
    host_stream.reset(drv::stream::create(host_context->backend()));
  }
}

CUstream torch_get_cuda_stream(int64_t dev_id) {
  return (CUstream)c10::cuda::getCurrentCUDAStream(dev_id).stream();
}

CUdeviceptr torch_get_cuda_device(int64_t dev_id) {
  CUdevice ret;
  triton::driver::dispatch::cuDeviceGet(&ret, dev_id);
  return ret;
}

void synchronize(int64_t dev_id) {
  if(dev_id == -1){
    init_host_stream();
    host_stream->synchronize();
  }
  else{
    triton::driver::cu_stream stream(torch_get_cuda_stream(dev_id), false);
    stream.synchronize();
  }

}

void launch_kernel(int64_t op_id, int64_t dev_id, const std::string& args,
                   const std::vector<std::string>& constant_names, const std::vector<torch::Tensor>& constant_vals){
  rt::function* fn = id_fn_map.at({op_id, dev_id}).get();
  for(size_t n = 0; n < constant_names.size(); n++){
    const torch::Tensor& x = constant_vals[n];
    fn->set_cst(constant_names[n].c_str(), (char*)x.data_ptr(), x.numel()*x.element_size());
  }
  if(dev_id == -1){
    init_host_stream();
    (*fn)((void**)args.c_str(), args.size(), *id_grid_map.at({op_id, dev_id}), &*host_stream, &*host_device);
  }
  else{
    triton::driver::cu_stream stream(torch_get_cuda_stream(dev_id), false);
    triton::driver::cu_device device(torch_get_cuda_device(dev_id), false);
    (*fn)((void**)args.c_str(), args.size(), *id_grid_map.at({op_id, dev_id}), &stream, &device);
  }
}

static auto registry = torch::RegisterOperators()
                       .op("triton::launch_kernel", &launch_kernel)
                       .op("triton::cdiv_sum", &cdiv_sum)
                       .op("triton::synchronize", &synchronize);
<commit_msg>[PYTHON] Context switching logic moved to PyTorch<commit_after>// Thanks to Scott Gray (OpenAI) for the idea to pass the arguments
// as a string constructed with struct.pack in python

#include "triton/driver/buffer.h"
#include "triton/driver/stream.h"
#include "triton/runtime/function.h"
#include "triton/tools/bench.hpp"
#include "torch/script.h"
#include "ATen/cuda/CUDAContext.h"
#include <c10/cuda/CUDAException.h>
#include <cuda_runtime_api.h>

namespace rt = triton::runtime;
namespace drv = triton::driver;

typedef std::pair<int, int> map_key_t;
extern std::map<map_key_t, std::shared_ptr<rt::function::grid_fn_ty>> id_grid_map;
extern std::map<map_key_t, std::shared_ptr<rt::function>> id_fn_map;
std::shared_ptr<drv::device> host_device;
std::shared_ptr<drv::context> host_context;
std::shared_ptr<drv::stream> host_stream;

int64_t cdiv_sum(torch::Tensor x, int64_t div){
  TORCH_CHECK(!x.is_cuda(), "Argument of cdiv_sum must be a CPU tensor")
  auto _x  = x.accessor<int, 1>();
  int64_t ret = 0;
  for(size_t i = 0; i < x.size(0); i++)
    ret += (_x[i] + div - 1) / div;
  return ret;
}

void init_host_stream() {
  if(!host_stream){
    host_device.reset(new drv::host_device());
    host_context.reset(drv::context::create(&*host_device));
    host_stream.reset(drv::stream::create(host_context->backend()));
  }
}

CUstream torch_get_cuda_stream(int64_t dev_id) {
  return (CUstream)c10::cuda::getCurrentCUDAStream(dev_id).stream();
}

CUdeviceptr torch_get_cuda_device(int64_t dev_id) {
  CUdevice ret;
  triton::driver::dispatch::cuDeviceGet(&ret, dev_id);
  return ret;
}

void synchronize(int64_t dev_id) {
  if(dev_id == -1){
    init_host_stream();
    host_stream->synchronize();
  }
  else{
    triton::driver::cu_stream stream(torch_get_cuda_stream(dev_id), false);
    stream.synchronize();
  }

}

void launch_kernel(int64_t op_id, int64_t dev_id, const std::string& args,
                   const std::vector<std::string>& constant_names, const std::vector<torch::Tensor>& constant_vals){
  rt::function* fn = id_fn_map.at({op_id, dev_id}).get();
  for(size_t n = 0; n < constant_names.size(); n++){
    const torch::Tensor& x = constant_vals[n];
    fn->set_cst(constant_names[n].c_str(), (char*)x.data_ptr(), x.numel()*x.element_size());
  }
  if(dev_id == -1){
    init_host_stream();
    (*fn)((void**)args.c_str(), args.size(), *id_grid_map.at({op_id, dev_id}), &*host_stream, &*host_device);
  }
  else{
    C10_CUDA_CHECK(cudaSetDevice(dev_id));
    triton::driver::cu_stream stream(torch_get_cuda_stream(dev_id), false);
    triton::driver::cu_device device(torch_get_cuda_device(dev_id), false);
    (*fn)((void**)args.c_str(), args.size(), *id_grid_map.at({op_id, dev_id}), &stream, &device);
  }
}

static auto registry = torch::RegisterOperators()
                       .op("triton::launch_kernel", &launch_kernel)
                       .op("triton::cdiv_sum", &cdiv_sum)
                       .op("triton::synchronize", &synchronize);
<|endoftext|>


<commit_before>#include "InputHandler.h"
#include <iostream>
#include <SDL2/SDL.h>

static InputHandler* s_pInstance;

InputHandler::InputHandler() {}

InputHandler *InputHandler::Instance() {
	if (s_pInstance == 0) {
		s_pInstance = new InputHandler();
	}

	return s_pInstance;
}

bool InputHandler::update() {
	bool ret = true;
	SDL_Event event;
	while (SDL_PollEvent(&event)) {
		if (event.type == SDL_QUIT) {
			ret = false;
		}
	}

	return ret;
}

void InputHandler::initialiseJoysticks() {
	if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) {
		SDL_InitSubSystem(SDL_INIT_JOYSTICK);
	}

	if (SDL_NumJoysticks() == 0) {
		m_bJoysticksInitialised = false;
	}
	else {
		for (int i = 0; i < SDL_NumJoysticks(); i++) {
			SDL_Joystick* joy = SDL_JoystickOpen(i);
			if (joy) {
				m_joysticks.push_back(joy);
			}
			else {
				std::cout << SDL_GetError();
			}
		}
		SDL_JoystickEventState(SDL_ENABLE);
		m_bJoysticksInitialised = true;
		std::cout << "Initialised "<< m_joysticks.size() << " joystick(s)\n";
	}
}

void InputHandler::clean() {
	if (m_bJoysticksInitialised) {
		for (int i = 0; i < SDL_NumJoysticks(); i++){
			SDL_JoystickClose(m_joysticks[i]);
		}

		std::cout << "Cleaned "<< m_joysticks.size() << " joystick(s)\n";
	}
}

bool InputHandler::joysticksInitialised() {
	return m_bJoysticksInitialised;
}

void InputHandler::free() {
	delete s_pInstance;
	s_pInstance = 0;
}
<commit_msg>If the axis of the joystick is moved, get which joystick was activated<commit_after>#include "InputHandler.h"
#include <iostream>
#include <SDL2/SDL.h>

static InputHandler* s_pInstance;

InputHandler::InputHandler() {}

InputHandler *InputHandler::Instance() {
	if (s_pInstance == 0) {
		s_pInstance = new InputHandler();
	}

	return s_pInstance;
}

bool InputHandler::update() {
	bool ret = true;
	SDL_Event event;
	while (SDL_PollEvent(&event)) {
		if (event.type == SDL_QUIT) {
			ret = false;
		}
		else if (event.type == SDL_JOYAXISMOTION) {
			int whichOne = event.jaxis.which;
			std::cout << "Joystick " << whichOne << " manipulated\n";
		}
	}

	return ret;
}

void InputHandler::initialiseJoysticks() {
	if (SDL_WasInit(SDL_INIT_JOYSTICK) == 0) {
		SDL_InitSubSystem(SDL_INIT_JOYSTICK);
	}

	if (SDL_NumJoysticks() == 0) {
		m_bJoysticksInitialised = false;
	}
	else {
		for (int i = 0; i < SDL_NumJoysticks(); i++) {
			SDL_Joystick* joy = SDL_JoystickOpen(i);
			if (joy) {
				m_joysticks.push_back(joy);
			}
			else {
				std::cout << SDL_GetError();
			}
		}
		SDL_JoystickEventState(SDL_ENABLE);
		m_bJoysticksInitialised = true;
		std::cout << "Initialised "<< m_joysticks.size() << " joystick(s)\n";
	}
}

void InputHandler::clean() {
	if (m_bJoysticksInitialised) {
		for (int i = 0; i < SDL_NumJoysticks(); i++){
			SDL_JoystickClose(m_joysticks[i]);
		}

		std::cout << "Cleaned "<< m_joysticks.size() << " joystick(s)\n";
	}
}

bool InputHandler::joysticksInitialised() {
	return m_bJoysticksInitialised;
}

void InputHandler::free() {
	delete s_pInstance;
	s_pInstance = 0;
}
<|endoftext|>