<commit_before>// $Id$

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (c) 2006 University of Edinburgh
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 University of Edinburgh 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.
***********************************************************************/

// example file on how to use moses library

#ifdef WIN32
// Include Visual Leak Detector
#include <vld.h>
#endif

#include <fstream>
#include "Main.h"
#include "LatticePath.h"
#include "FactorCollection.h"
#include "Manager.h"
#include "Phrase.h"
#include "Util.h"
#include "LatticePathList.h"
#include "Timer.h"
#include "IOCommandLine.h"
#include "IOFile.h"
#include "Sentence.h"
#include "ConfusionNet.h"

#if HAVE_CONFIG_H
#include "config.h"
#  ifdef HAVE_MYSQLPP
#    define USE_MYSQL 1
#  endif
#else
// those not using autoconf have to build MySQL support for now
#  define USE_MYSQL 1
#endif

#undef USE_MYSQL
#ifdef USE_MYSQL
#include "IOMySQL.h"
#endif

using namespace std;
Timer timer;

int main(int argc, char* argv[])
{
	timer.start("Starting...");

	std::cerr
		<<"============================================================================\n"
		<<"starting "<<argv[0]<<"  (build on "<<__DATE__<<")\n"
		<<"============================================================================\n"
		<<"\n"
    <<"the command line was: \n";
	for(int i=0;i<argc;++i) std::cerr<<argv[i]<<" ";
  std::cerr
		<<"\n"
		<<"============================================================================\n";

	StaticData staticData;

	if (!staticData.LoadParameters(argc, argv))
		return EXIT_FAILURE;

	/*
	 * boost::shared_ptr<UnknownWordHandler> unknownWordHandler(new UnknownWordHandler);
	staticData.SetUnknownWordHandler(unknownWordHandler);
  */
		if (staticData.GetVerboseLevel() > 0)
		{
#if N_BEST
		std::cerr << "N_BEST=enabled\n";
#else
		std::cerr << "N_BEST=disabled\n";
#endif
		}

	// set up read/writing class
	InputOutput *inputOutput = GetInputOutput(staticData);

  std::cerr << "The score component vector looks like this:\n" << staticData.GetScoreIndexManager();

	if (inputOutput == NULL)
		return EXIT_FAILURE;

	// read each sentence & decode
	while(InputType *source = inputOutput->GetInput((staticData.GetInputType() ?
																									 static_cast<InputType*>(new ConfusionNet) :
																									 static_cast<InputType*>(new Sentence(Input)))))
	{
		TRACE_ERR(*source<<"\n");

		TranslationOptionCollection *translationOptionCollection=source->CreateTranslationOptionCollection();
		assert(translationOptionCollection);

		staticData.InitializeBeforeSentenceProcessing(*source);
		Manager manager(*source, *translationOptionCollection, staticData);
		manager.ProcessSentence();
		inputOutput->SetOutput(manager.GetBestHypothesis(), source->GetTranslationId(),
                        staticData.GetReportSourceSpan(),
                        staticData.GetReportAllFactors()
                        );

		// n-best
		size_t nBestSize = staticData.GetNBestSize();
		if (nBestSize > 0)
		{
			TRACE_ERR(nBestSize << " " << staticData.GetNBestFilePath() << endl);
			LatticePathList nBestList;
			manager.CalcNBest(nBestSize, nBestList);
			inputOutput->SetNBest(nBestList, source->GetTranslationId());
			RemoveAllInColl< LatticePathList::iterator > (nBestList);
		}

		// delete source
		//		inputOutput->Release(source);
		staticData.CleanUpAfterSentenceProcessing();
		delete translationOptionCollection;
		delete source;
	}

	delete inputOutput;

	timer.check("End.");
	return EXIT_SUCCESS;
}

InputOutput *GetInputOutput(StaticData &staticData)
{
	InputOutput *inputOutput;
	const std::vector<FactorType> &factorOrder = staticData.GetInputFactorOrder();
	FactorTypeSet inputFactorUsed(factorOrder);

	// io
	if (staticData.GetIOMethod() == IOMethodMySQL)
	{
		TRACE_ERR("IO from MySQL" << endl);
#if USE_MYSQL
		const PARAM_VEC &mySQLParam = staticData.GetParam("mysql");
		inputOutput = new IOMySQL(mySQLParam[0], mySQLParam[1], mySQLParam[2], mySQLParam[3]
														, Scan<long>(mySQLParam[4]), Scan<long>(mySQLParam[5])
														, factorOrder, inputFactorUsed, staticData.GetFactorCollection());
		staticData.LoadPhraseTables();
#else
		TRACE_ERR( "moses was not built with mysql libraries, please configure\n"
							<< "  to use another input method.\n");
		inputOutput = NULL;
#endif
	}
	else if (staticData.GetIOMethod() == IOMethodFile)
	{
		TRACE_ERR("IO from File" << endl);
		string					inputFileHash;
		list< Phrase >	inputPhraseList;
		string filePath = staticData.GetParam("input-file")[0];

		TRACE_ERR("About to create ioFile" << endl);
		IOFile *ioFile = new IOFile(factorOrder, inputFactorUsed
																	, staticData.GetFactorCollection()
																	, staticData.GetNBestSize()
																	, staticData.GetNBestFilePath()
																	, filePath);
		if(staticData.GetInputType())
			{
				TRACE_ERR("Do not read input phrases for confusion net translation\n");
			}
		else
			{
				TRACE_ERR("About to GetInputPhrase\n");
				ioFile->GetInputPhrase(inputPhraseList);
			}
		TRACE_ERR("After GetInputPhrase" << endl);
		inputOutput = ioFile;
		inputFileHash = GetMD5Hash(filePath);
		TRACE_ERR("About to LoadPhraseTables" << endl);
		staticData.LoadPhraseTables(true, inputFileHash, inputPhraseList);
		ioFile->ResetSentenceId();
	}
	else
	{
		TRACE_ERR("IO from STDOUT/STDIN" << endl);
		inputOutput = new IOCommandLine(factorOrder, inputFactorUsed
																	, staticData.GetFactorCollection()
																	, staticData.GetNBestSize()
																	, staticData.GetNBestFilePath());
		staticData.LoadPhraseTables();
	}
	staticData.LoadMapping();
	timer.check("Created input-output object");

	return inputOutput;
}

<commit_msg>add score logging<commit_after>// $Id$

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (c) 2006 University of Edinburgh
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 University of Edinburgh 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.
***********************************************************************/

// example file on how to use moses library

#ifdef WIN32
// Include Visual Leak Detector
#include <vld.h>
#endif

#include <fstream>
#include "Main.h"
#include "LatticePath.h"
#include "FactorCollection.h"
#include "Manager.h"
#include "Phrase.h"
#include "Util.h"
#include "LatticePathList.h"
#include "Timer.h"
#include "IOCommandLine.h"
#include "IOFile.h"
#include "Sentence.h"
#include "ConfusionNet.h"

#if HAVE_CONFIG_H
#include "config.h"
#  ifdef HAVE_MYSQLPP
#    define USE_MYSQL 1
#  endif
#else
// those not using autoconf have to build MySQL support for now
#  define USE_MYSQL 1
#endif

#undef USE_MYSQL
#ifdef USE_MYSQL
#include "IOMySQL.h"
#endif

using namespace std;
Timer timer;

int main(int argc, char* argv[])
{
	timer.start("Starting...");

	std::cerr
		<<"============================================================================\n"
		<<"starting "<<argv[0]<<"  (build on "<<__DATE__<<")\n"
		<<"============================================================================\n"
		<<"\n"
    <<"the command line was: \n";
	for(int i=0;i<argc;++i) std::cerr<<argv[i]<<" ";
  std::cerr
		<<"\n"
		<<"============================================================================\n";

	StaticData staticData;

	if (!staticData.LoadParameters(argc, argv))
		return EXIT_FAILURE;

	/*
	 * boost::shared_ptr<UnknownWordHandler> unknownWordHandler(new UnknownWordHandler);
	staticData.SetUnknownWordHandler(unknownWordHandler);
  */
		if (staticData.GetVerboseLevel() > 0)
		{
#if N_BEST
		std::cerr << "N_BEST=enabled\n";
#else
		std::cerr << "N_BEST=disabled\n";
#endif
		}

	// set up read/writing class
	InputOutput *inputOutput = GetInputOutput(staticData);

  std::cerr << "The score component vector looks like this:\n" << staticData.GetScoreIndexManager();
  std::cerr << "The global weight vector looks like this:\n";
	vector<float> weights = staticData.GetAllWeights();
	std::cerr << weights[0];
	for (size_t j=1; j<weights.size(); j++) { std::cerr << ", " << weights[j]; }
	std::cerr << "\n";

	if (inputOutput == NULL)
		return EXIT_FAILURE;

	// read each sentence & decode
	while(InputType *source = inputOutput->GetInput((staticData.GetInputType() ?
																									 static_cast<InputType*>(new ConfusionNet) :
																									 static_cast<InputType*>(new Sentence(Input)))))
	{
		TRACE_ERR(*source<<"\n");

		TranslationOptionCollection *translationOptionCollection=source->CreateTranslationOptionCollection();
		assert(translationOptionCollection);

		staticData.InitializeBeforeSentenceProcessing(*source);
		Manager manager(*source, *translationOptionCollection, staticData);
		manager.ProcessSentence();
		inputOutput->SetOutput(manager.GetBestHypothesis(), source->GetTranslationId(),
                        staticData.GetReportSourceSpan(),
                        staticData.GetReportAllFactors()
                        );

		// n-best
		size_t nBestSize = staticData.GetNBestSize();
		if (nBestSize > 0)
		{
			TRACE_ERR(nBestSize << " " << staticData.GetNBestFilePath() << endl);
			LatticePathList nBestList;
			manager.CalcNBest(nBestSize, nBestList);
			inputOutput->SetNBest(nBestList, source->GetTranslationId());
			RemoveAllInColl< LatticePathList::iterator > (nBestList);
		}

		// delete source
		//		inputOutput->Release(source);
		staticData.CleanUpAfterSentenceProcessing();
		delete translationOptionCollection;
		delete source;
	}

	delete inputOutput;

	timer.check("End.");
	return EXIT_SUCCESS;
}

InputOutput *GetInputOutput(StaticData &staticData)
{
	InputOutput *inputOutput;
	const std::vector<FactorType> &factorOrder = staticData.GetInputFactorOrder();
	FactorTypeSet inputFactorUsed(factorOrder);

	// io
	if (staticData.GetIOMethod() == IOMethodMySQL)
	{
		TRACE_ERR("IO from MySQL" << endl);
#if USE_MYSQL
		const PARAM_VEC &mySQLParam = staticData.GetParam("mysql");
		inputOutput = new IOMySQL(mySQLParam[0], mySQLParam[1], mySQLParam[2], mySQLParam[3]
														, Scan<long>(mySQLParam[4]), Scan<long>(mySQLParam[5])
														, factorOrder, inputFactorUsed, staticData.GetFactorCollection());
		staticData.LoadPhraseTables();
#else
		TRACE_ERR( "moses was not built with mysql libraries, please configure\n"
							<< "  to use another input method.\n");
		inputOutput = NULL;
#endif
	}
	else if (staticData.GetIOMethod() == IOMethodFile)
	{
		TRACE_ERR("IO from File" << endl);
		string					inputFileHash;
		list< Phrase >	inputPhraseList;
		string filePath = staticData.GetParam("input-file")[0];

		TRACE_ERR("About to create ioFile" << endl);
		IOFile *ioFile = new IOFile(factorOrder, inputFactorUsed
																	, staticData.GetFactorCollection()
																	, staticData.GetNBestSize()
																	, staticData.GetNBestFilePath()
																	, filePath);
		if(staticData.GetInputType())
			{
				TRACE_ERR("Do not read input phrases for confusion net translation\n");
			}
		else
			{
				TRACE_ERR("About to GetInputPhrase\n");
				ioFile->GetInputPhrase(inputPhraseList);
			}
		TRACE_ERR("After GetInputPhrase" << endl);
		inputOutput = ioFile;
		inputFileHash = GetMD5Hash(filePath);
		TRACE_ERR("About to LoadPhraseTables" << endl);
		staticData.LoadPhraseTables(true, inputFileHash, inputPhraseList);
		ioFile->ResetSentenceId();
	}
	else
	{
		TRACE_ERR("IO from STDOUT/STDIN" << endl);
		inputOutput = new IOCommandLine(factorOrder, inputFactorUsed
																	, staticData.GetFactorCollection()
																	, staticData.GetNBestSize()
																	, staticData.GetNBestFilePath());
		staticData.LoadPhraseTables();
	}
	staticData.LoadMapping();
	timer.check("Created input-output object");

	return inputOutput;
}

<|endoftext|>


<commit_before>#include "gm.h"
#include "SkPicture.h"
#include "SkRectShape.h"
#include "SkGroupShape.h"

namespace skiagm {

static SkRect make_rect(int l, int t, int r, int b) {
    SkRect rect;
    rect.set(SkIntToScalar(l), SkIntToScalar(t),
             SkIntToScalar(r), SkIntToScalar(b));
    return rect;
}

static SkShape* make_shape0(bool red) {
    SkRectShape* s = new SkRectShape;
    s->setRect(make_rect(10, 10, 90, 90));
    if (red) {
        s->paint().setColor(SK_ColorRED);
    }
    return s;
}

static SkShape* make_shape1() {
    SkRectShape* s = new SkRectShape;
    s->setOval(make_rect(10, 10, 90, 90));
    s->paint().setColor(SK_ColorBLUE);
    return s;
}

static SkShape* make_shape2() {
    SkRectShape* s = new SkRectShape;
    s->setRRect(make_rect(10, 10, 90, 90),
                SkIntToScalar(20), SkIntToScalar(20));
    s->paint().setColor(SK_ColorGREEN);
    return s;
}

///////////////////////////////////////////////////////////////////////////////

class ShapesGM : public GM {
    SkGroupShape fGroup;
    SkMatrixRef*    fMatrixRefs[4];
public:
	ShapesGM() {
        SkMatrix m;
        fGroup.appendShape(make_shape0(false))->unref();
        m.setRotate(SkIntToScalar(30), SkIntToScalar(50), SkIntToScalar(50));
        m.postTranslate(0, SkIntToScalar(120));
        fGroup.appendShape(make_shape0(true), m)->unref();

        m.setTranslate(SkIntToScalar(120), 0);
        fGroup.appendShape(make_shape1(), m)->unref();
        m.postTranslate(0, SkIntToScalar(120));
        fGroup.appendShape(make_shape2(), m)->unref();

        for (size_t i = 0; i < SK_ARRAY_COUNT(fMatrixRefs); i++) {
            SkSafeRef(fMatrixRefs[i] = fGroup.getShapeMatrixRef(i));
        }
    }

    virtual ~ShapesGM() {
        for (size_t i = 0; i < SK_ARRAY_COUNT(fMatrixRefs); i++) {
            SkSafeUnref(fMatrixRefs[i]);
        }
    }

protected:
    virtual SkString onShortName() {
        return SkString("shapes");
    }

	virtual SkISize onISize() {
        return make_isize(380, 480);
    }

    void drawBG(SkCanvas* canvas) {
        canvas->drawColor(0xFFDDDDDD);
    }

    virtual void onDraw(SkCanvas* canvas) {
        this->drawBG(canvas);

        SkMatrix saveM = *fMatrixRefs[3];
        SkScalar c = SkIntToScalar(50);
        fMatrixRefs[3]->preRotate(SkIntToScalar(30), c, c);

        SkMatrix matrix;

        SkGroupShape* gs = new SkGroupShape;
        SkAutoUnref aur(gs);
        gs->appendShape(&fGroup);
        matrix.setScale(-SK_Scalar1, SK_Scalar1);
        matrix.postTranslate(SkIntToScalar(220), SkIntToScalar(240));
        gs->appendShape(&fGroup, matrix);
        matrix.setTranslate(SkIntToScalar(240), 0);
        matrix.preScale(SK_Scalar1*2, SK_Scalar1*2);
        gs->appendShape(&fGroup, matrix);

#if 0
        canvas->drawShape(gs);
#else
        SkPicture pict;
        SkCanvas* cv = pict.beginRecording(1000, 1000);
        cv->scale(SK_ScalarHalf, SK_ScalarHalf);
        cv->drawShape(gs);
        cv->translate(SkIntToScalar(680), SkIntToScalar(480));
        cv->scale(-SK_Scalar1, SK_Scalar1);
        cv->drawShape(gs);
        pict.endRecording();
        canvas->drawPicture(pict);
#endif

        *fMatrixRefs[3] = saveM;
}

private:
    typedef GM INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new ShapesGM; }
static GMRegistry reg(MyFactory);

}
<commit_msg>fix refcount bug - as picture gets referenced by canvas when canvas is a picture-recording canvas, so it can't live on the stack. Probably a bug: nested pictures should probably ref some internal impl, so that callers can be free to use the stack when they want to.<commit_after>#include "gm.h"
#include "SkPicture.h"
#include "SkRectShape.h"
#include "SkGroupShape.h"

namespace skiagm {

static SkRect make_rect(int l, int t, int r, int b) {
    SkRect rect;
    rect.set(SkIntToScalar(l), SkIntToScalar(t),
             SkIntToScalar(r), SkIntToScalar(b));
    return rect;
}

static SkShape* make_shape0(bool red) {
    SkRectShape* s = new SkRectShape;
    s->setRect(make_rect(10, 10, 90, 90));
    if (red) {
        s->paint().setColor(SK_ColorRED);
    }
    return s;
}

static SkShape* make_shape1() {
    SkRectShape* s = new SkRectShape;
    s->setOval(make_rect(10, 10, 90, 90));
    s->paint().setColor(SK_ColorBLUE);
    return s;
}

static SkShape* make_shape2() {
    SkRectShape* s = new SkRectShape;
    s->setRRect(make_rect(10, 10, 90, 90),
                SkIntToScalar(20), SkIntToScalar(20));
    s->paint().setColor(SK_ColorGREEN);
    return s;
}

///////////////////////////////////////////////////////////////////////////////

class ShapesGM : public GM {
    SkGroupShape fGroup;
    SkMatrixRef*    fMatrixRefs[4];
public:
	ShapesGM() {
        SkMatrix m;
        fGroup.appendShape(make_shape0(false))->unref();
        m.setRotate(SkIntToScalar(30), SkIntToScalar(50), SkIntToScalar(50));
        m.postTranslate(0, SkIntToScalar(120));
        fGroup.appendShape(make_shape0(true), m)->unref();

        m.setTranslate(SkIntToScalar(120), 0);
        fGroup.appendShape(make_shape1(), m)->unref();
        m.postTranslate(0, SkIntToScalar(120));
        fGroup.appendShape(make_shape2(), m)->unref();

        for (size_t i = 0; i < SK_ARRAY_COUNT(fMatrixRefs); i++) {
            SkSafeRef(fMatrixRefs[i] = fGroup.getShapeMatrixRef(i));
        }
    }

    virtual ~ShapesGM() {
        for (size_t i = 0; i < SK_ARRAY_COUNT(fMatrixRefs); i++) {
            SkSafeUnref(fMatrixRefs[i]);
        }
    }

protected:
    virtual SkString onShortName() {
        return SkString("shapes");
    }

	virtual SkISize onISize() {
        return make_isize(380, 480);
    }

    void drawBG(SkCanvas* canvas) {
        canvas->drawColor(0xFFDDDDDD);
    }

    virtual void onDraw(SkCanvas* canvas) {
        this->drawBG(canvas);

        SkMatrix saveM = *fMatrixRefs[3];
        SkScalar c = SkIntToScalar(50);
        fMatrixRefs[3]->preRotate(SkIntToScalar(30), c, c);

        SkMatrix matrix;

        SkGroupShape* gs = new SkGroupShape;
        SkAutoUnref aur(gs);
        gs->appendShape(&fGroup);
        matrix.setScale(-SK_Scalar1, SK_Scalar1);
        matrix.postTranslate(SkIntToScalar(220), SkIntToScalar(240));
        gs->appendShape(&fGroup, matrix);
        matrix.setTranslate(SkIntToScalar(240), 0);
        matrix.preScale(SK_Scalar1*2, SK_Scalar1*2);
        gs->appendShape(&fGroup, matrix);

#if 0
        canvas->drawShape(gs);
#else
        SkPicture* pict = new SkPicture;
        SkCanvas* cv = pict->beginRecording(1000, 1000);
        cv->scale(SK_ScalarHalf, SK_ScalarHalf);
        cv->drawShape(gs);
        cv->translate(SkIntToScalar(680), SkIntToScalar(480));
        cv->scale(-SK_Scalar1, SK_Scalar1);
        cv->drawShape(gs);
        pict->endRecording();
        canvas->drawPicture(*pict);
        pict->unref();
#endif

        *fMatrixRefs[3] = saveM;
}

private:
    typedef GM INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new ShapesGM; }
static GMRegistry reg(MyFactory);

}
<|endoftext|>


<commit_before>//
// Created by aj on 5/17/16.
//

#include <libxml++/libxml++.h>
#include <iostream>
#include "XMLppTools.h"

using namespace Glib;
using namespace xmlpp;
using namespace std;

//TODO: Handle error conditions
void XMLppTools::populateGameFromScoreboardXML(Game * gameToPopulate, XMLMemoryUnit * scoreboardXMLMemory, Glib::ustring teamIDToFind) {
    //Proof of concept XML parser
    try {
        DomParser parser;
        parser.parse_memory(*(scoreboardXMLMemory->memory));

        if(parser) {
            Node *root;
            root  = parser.get_document()->get_root_node();

            NodeSet titles;
            titles = root->find("//game");

            for(NodeSet::iterator i = titles.begin(); i != titles.end(); i++) {
                Element *enode;
                enode = dynamic_cast<Element *>(*i);

                if(enode){
                    ustring id = enode->get_attribute("id")->get_value();

                    if(id.find(teamIDToFind) != ustring::npos) {
                        gameToPopulate->gameID = id;
                        gameToPopulate->exists = true;
                    }
                }
            }
        }
    } catch (std::exception &e) {
        cout << e.what() << endl;
    }
}

void XMLppTools::populateScoreboardXML(Game *gameObj, XMLMemoryUnit *xmlMem) {
    try {
        DomParser parser;
        parser.parse_memory(*(xmlMem->memory));

        if(parser) {
            Node * root;
            root  = parser.get_document()->get_root_node();

            Element * rootElem;
            rootElem = dynamic_cast<Element *>(root);

            gameObj->away->code = rootElem->get_attribute("away_team_code")->get_value();
            gameObj->home->code = rootElem->get_attribute("home_team_code")->get_value();

            //Parse linescore
            Node * linescore;
            linescore = root->get_first_child("linescore");

            Element * linescoreElem;
            linescoreElem = dynamic_cast<Element *>(linescore);

            //Retrieve base score
            gameObj->awayRun = atoi(linescoreElem->get_attribute("away_team_runs")->get_value().c_str());
            gameObj->awayHit = atoi(linescoreElem->get_attribute("away_team_hits")->get_value().c_str());
            gameObj->awayErr = atoi(linescoreElem->get_attribute("away_team_errors")->get_value().c_str());
            gameObj->homeRun = atoi(linescoreElem->get_attribute("home_team_runs")->get_value().c_str());
            gameObj->homeHit = atoi(linescoreElem->get_attribute("home_team_hits")->get_value().c_str());
            gameObj->homeErr = atoi(linescoreElem->get_attribute("home_team_errors")->get_value().c_str());

            //Retrieve inning scores
            NodeSet innings;
            innings = linescore->find("//inning_line_score");

            for(NodeSet::iterator i = innings.begin(); i != innings.end(); i++) {
                Element * inningElem;
                inningElem = dynamic_cast<Element *>(*i);

                unsigned int inningNum = (unsigned)atoi(inningElem->get_attribute("inning")->get_value().c_str());
                int awayInningRuns = atoi(inningElem->get_attribute("away")->get_value().c_str());

                try {
                    int homeInningRuns = atoi(inningElem->get_attribute("home")->get_value().c_str());

                    if (gameObj->homeScore->size() < inningNum) {
                        gameObj->homeScore->resize(inningNum);
                    }

                    gameObj->homeScore->at(inningNum - 1) = homeInningRuns;
                } catch(std::exception &e) {
                    //Home hasn't played this inning so don't bother
                }

                //Fixme: Check reserve to make sure this isn't hammering memory
                if(gameObj->awayScore->size() < inningNum) {
                    gameObj->awayScore->resize(inningNum);
                }

                gameObj->awayScore->at(inningNum-1) = awayInningRuns;
            }
        }
    } catch (std::exception &e) {
        cout << e.what() << endl;
    }
}

<commit_msg>fixes segfaults related to various inning state conditions<commit_after>//
// Created by aj on 5/17/16.
//

#include <libxml++/libxml++.h>
#include <iostream>
#include "XMLppTools.h"

using namespace Glib;
using namespace xmlpp;
using namespace std;

//TODO: Handle error conditions
void XMLppTools::populateGameFromScoreboardXML(Game * gameToPopulate, XMLMemoryUnit * scoreboardXMLMemory, Glib::ustring teamIDToFind) {
    //Proof of concept XML parser
    try {
        DomParser parser;
        parser.parse_memory(*(scoreboardXMLMemory->memory));

        if(parser) {
            Node *root;
            root  = parser.get_document()->get_root_node();

            NodeSet titles;
            titles = root->find("//game");

            for(NodeSet::iterator i = titles.begin(); i != titles.end(); i++) {
                Element *enode;
                enode = dynamic_cast<Element *>(*i);

                if(enode){
                    ustring id = enode->get_attribute("id")->get_value();

                    if(id.find(teamIDToFind) != ustring::npos) {
                        gameToPopulate->gameID = id;
                        gameToPopulate->exists = true;
                    }
                }
            }
        }
    } catch (std::exception &e) {
        cout << e.what() << endl;
    }
}

void XMLppTools::populateScoreboardXML(Game *gameObj, XMLMemoryUnit *xmlMem) {
    try {
        DomParser parser;
        parser.parse_memory(*(xmlMem->memory));

        if(parser) {
            Node * root;
            root  = parser.get_document()->get_root_node();

            Element * rootElem;
            rootElem = dynamic_cast<Element *>(root);

            gameObj->away->code = rootElem->get_attribute("away_team_code")->get_value();
            gameObj->home->code = rootElem->get_attribute("home_team_code")->get_value();

            //Parse linescore
            Node * linescore;
            linescore = root->get_first_child("linescore");

            Element * linescoreElem;
            linescoreElem = dynamic_cast<Element *>(linescore);

            //Retrieve base score
            gameObj->awayRun = atoi(linescoreElem->get_attribute("away_team_runs")->get_value().c_str());
            gameObj->awayHit = atoi(linescoreElem->get_attribute("away_team_hits")->get_value().c_str());
            gameObj->awayErr = atoi(linescoreElem->get_attribute("away_team_errors")->get_value().c_str());
            gameObj->homeRun = atoi(linescoreElem->get_attribute("home_team_runs")->get_value().c_str());
            gameObj->homeHit = atoi(linescoreElem->get_attribute("home_team_hits")->get_value().c_str());
            gameObj->homeErr = atoi(linescoreElem->get_attribute("home_team_errors")->get_value().c_str());

            //Retrieve inning scores
            NodeSet innings;
            innings = linescore->find("//inning_line_score");

            for(NodeSet::iterator i = innings.begin(); i != innings.end(); i++) {
                Element * inningElem;
                inningElem = dynamic_cast<Element *>(*i);

                unsigned int inningNum = (unsigned)atoi(inningElem->get_attribute("inning")->get_value().c_str());

                ustring awayRunStr = inningElem->get_attribute("away")->get_value();

                /* chaining if statements prevents a segfault when the end of an inning is reached
                 * XML excerpt:
                 * [...]
                 * <inning_line_score away="0" home="0" inning="6"/>
                 * <inning_line_score away="" inning="7"/>
                 * [...]
                 */
                if(awayRunStr != "") {
                    int awayInningRuns = atoi(awayRunStr.c_str());

                    //Fixme: Check reserve to make sure this isn't hammering memory
                    if(gameObj->awayScore->size() < inningNum) {
                        gameObj->awayScore->resize(inningNum);
                    }

                    gameObj->awayScore->at(inningNum-1) = awayInningRuns;

                    ustring homeRunStr = inningElem->get_attribute("home")->get_value();

                    /* handles middle of an inning
                     * XML excerpt:
                     * [...]
                     * <inning_line_score away="0" home="0" inning="6"/>
                     * <inning_line_score away="5" home="" inning="7"/>
                     * [...]
                     */
                    if(homeRunStr != "") {
                        int homeInningRuns = atoi(inningElem->get_attribute("home")->get_value().c_str());

                        if(gameObj->homeScore->size() < inningNum) {
                            gameObj->homeScore->resize(inningNum);
                        }

                        gameObj->homeScore->at(inningNum-1) = homeInningRuns;
                    }
                }
            }
        }
    } catch (std::exception &e) {
        cout << e.what() << endl;
    }
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 SeNDA
 *
 * 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.
 *
 */
/**
 * FILE adtnSender.cpp
 * AUTHOR Blackcatn13
 * DATE Apr 5, 2016
 * VERSION 1
 *
 */

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <iostream>
#include <fstream>
#include <cstring>
#include <map>
#include "adtnSocket.h"

static void help(std::string program_name) {
  std::cout << program_name << " is part of the SeNDA aDTNPlus platform\n"
            << "Usage: " << program_name << " -i '127.0.0.1' -p '50000'"
            << " -d 'node2:50' -m 'This is a message for node2.'\n"
            << "Required options:\n"
            << "   [-i | --listeningIP] Ip\t\t\tIP of the listening node.\n"
            << "   [-p | --port] port\t\t\tPort where the node is listening.\n"
            << "   [-d | --destination] destination node\t\t\t"
            << "Which node is the destination.\n"
            << "   [-m | --message] message to send\t\t\tThe message to send.\n"
            << "Supported options:\n"
            << "   [-h | --help]\t\t\t\tShows this help message.\n"
            << std::endl;
}

int main(int argc, char **argv) {
  int opt = -1, option_index = 0;
  std::string ip = "";
  int port = -1;
  std::map<FirstFrameworkExtensionsIds, std::string> codes;
  std::map<FirstFrameworkExtensionsIds, std::string> files;
  std::string destination = "";
  std::string message = "";

  static struct option long_options[] = { { "listeningIP", required_argument, 0,
      'i' }, { "port", required_argument, 0, 'p' }, { "destination",
  required_argument, 0, 'd' }, { "message", required_argument, 0, 'm' }, {
      "create", required_argument, 0, 'c' },
      { "del", required_argument, 0, 'e' },
      { "dest", required_argument, 0, 't' },
      { "life", required_argument, 0, 'l' },
      { "fwd", required_argument, 0, 'f' }, { "createFile", required_argument,
          0, 'C' }, { "delFile", required_argument, 0, 'E' }, { "destFile",
      required_argument, 0, 'T' }, { "lifeFile", required_argument, 0, 'L' }, {
          "fwdFile", required_argument, 0, 'F' },
      { "help", no_argument, 0, 'h' }, { 0, 0, 0, 0 } };

  while ((opt = getopt_long(argc, argv, "i:p:d:m:c:e:t:l:f:C:E:T:L:F:h",
                            long_options, &option_index))) {
    switch (opt) {
      case 'i':
        ip = std::string(optarg);
        break;
      case 'p':
        port = std::atoi(optarg);
        break;
      case 'd':
        destination = std::string(optarg);
        break;
      case 'm':
        message = std::string(optarg);
        break;
      case 'c':
        codes[FirstFrameworkExtensionsIds::CONTAINER_CREATION] = std::string(
            optarg);
        break;
      case 'C':
        files[FirstFrameworkExtensionsIds::CONTAINER_CREATION] = std::string(
            optarg);
        break;
      case 'e':
        codes[FirstFrameworkExtensionsIds::CONTAINER_DELETION] = std::string(
            optarg);
        break;
      case 'E':
        files[FirstFrameworkExtensionsIds::CONTAINER_DELETION] = std::string(
            optarg);
        break;
      case 't':
        codes[FirstFrameworkExtensionsIds::DESTINATION] = std::string(optarg);
        break;
      case 'T':
        files[FirstFrameworkExtensionsIds::DESTINATION] = std::string(optarg);
        break;
      case 'l':
        codes[FirstFrameworkExtensionsIds::LIFETIME] = std::string(optarg);
        break;
      case 'L':
        files[FirstFrameworkExtensionsIds::LIFETIME] = std::string(optarg);
        break;
      case 'f':
        codes[FirstFrameworkExtensionsIds::FORWARD] = std::string(optarg);
        break;
      case 'F':
        files[FirstFrameworkExtensionsIds::FORWARD] = std::string(optarg);
        break;
      case 'h':
        help(std::string(argv[0]));
        exit(0);
      default:
        break;
    }
    if (opt == -1)
      break;
  }
  if (ip == "" || port == -1 || destination == "" || message == "") {
    help(std::string(argv[0]));
    exit(0);
  }

  adtnSocket s = adtnSocket(ip, port);
  // Add the codes if any
  for (auto it = codes.begin(); it != codes.end(); ++it) {
    s.addFrameworkExtension(
        static_cast<uint8_t>(FrameworksIds::FIRST_FRAMEWORK),
        static_cast<uint8_t>(it->first), it->second);
  }
  for (auto it = files.begin(); it != files.end(); ++it) {
    std::ifstream codeFile(it->second);
    if (codeFile) {
      std::string code((std::istreambuf_iterator<char>(codeFile)),
                       std::istreambuf_iterator<char>());
      s.addFrameworkExtension(
          static_cast<uint8_t>(FrameworksIds::FIRST_FRAMEWORK),
          static_cast<uint8_t>(it->first), code);
      codeFile.close();
    } else {
      std::cout << "Cannot open the file " << it->second << std::endl;
    }
  }
  try {
    s.send(destination, message);
  } catch (const std::exception &e) {
    std::cout << e.what() << std::endl;
  }
  return 0;
}

<commit_msg>Updates adtnSender help.<commit_after>/*
 * Copyright (c) 2016 SeNDA
 *
 * 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.
 *
 */
/**
 * FILE adtnSender.cpp
 * AUTHOR Blackcatn13
 * DATE Apr 5, 2016
 * VERSION 1
 *
 */

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <getopt.h>
#include <string>
#include <iostream>
#include <fstream>
#include <cstring>
#include <map>
#include "adtnSocket.h"

static void help(std::string program_name) {
  std::cout
      << program_name
      << " is part of the SeNDA aDTNPlus platform\n"
      << "Usage: "
      << program_name
      << " -i '127.0.0.1' -p '50000'"
      << " -d 'node2:50' -m 'This is a message for node2.'\n"
      << "Required options:\n"
      << "   [-i | --listeningIP] Ip\t\t\tIP of the listening node.\n"
      << "   [-p | --port] port\t\t\t\tPort where the node is listening.\n"
      << "   [-d | --destination] destination node\t"
      << "Which node is the destination.\n"
      << "   [-m | --message] message to send\t\tThe message to send.\n"
      << "Supported options:\n"
      << "   [-c | --create] creation code\t\tAdds the code to the "
      "CONTAINER_CREATION extension.\n"
      << "   [-C | --createFile] creation code in file\tAdds the code from "
      "the file to the CONTAINER_CREATION extension.\n"
      << "   [-e | --del] deletion code\t\t\tAdds the code to the "
      "CONTAINER_DELETION extension.\n"
      << "   [-E | --delFile] deletion code in file\tAdds the code from the "
          "file to the CONTAINER_DELETION extension.\n"
      << "   [-t | --dest] destination code\t\tAdds the code to the "
          "DESTINATION extension.\n"
      << "   [-T | --destFile] destination code file\tAdds the code from the "
          "file to the DESTINATION extension.\n"
      << "   [-l | --life] lifetime code\t\t\tAdds the code to the "
          "LIFETIME extension.\n"
      << "   [-L | --lifeFile] lifetime code file\t\tAdds the code from the file "
          "to the LIFETIME extension.\n"
      << "   [-f | --fwd] forward code\t\t\tAdds the code to the "
          "FORWARD extension.\n"
      << "   [-F | --fwdFile] forward code file\t\tAdds the code from the file "
          "to the FORWARD extension.\n"
      << "   [-h | --help]\t\t\t\tShows this help message.\n" << std::endl;
}

int main(int argc, char **argv) {
  int opt = -1, option_index = 0;
  std::string ip = "";
  int port = -1;
  std::map<FirstFrameworkExtensionsIds, std::string> codes;
  std::map<FirstFrameworkExtensionsIds, std::string> files;
  std::string destination = "";
  std::string message = "";

  static struct option long_options[] = { { "listeningIP", required_argument, 0,
      'i' }, { "port", required_argument, 0, 'p' }, { "destination",
  required_argument, 0, 'd' }, { "message", required_argument, 0, 'm' }, {
      "create", required_argument, 0, 'c' },
      { "del", required_argument, 0, 'e' },
      { "dest", required_argument, 0, 't' },
      { "life", required_argument, 0, 'l' },
      { "fwd", required_argument, 0, 'f' }, { "createFile", required_argument,
          0, 'C' }, { "delFile", required_argument, 0, 'E' }, { "destFile",
      required_argument, 0, 'T' }, { "lifeFile", required_argument, 0, 'L' }, {
          "fwdFile", required_argument, 0, 'F' },
      { "help", no_argument, 0, 'h' }, { 0, 0, 0, 0 } };

  while ((opt = getopt_long(argc, argv, "i:p:d:m:c:e:t:l:f:C:E:T:L:F:h",
                            long_options, &option_index))) {
    switch (opt) {
      case 'i':
        ip = std::string(optarg);
        break;
      case 'p':
        port = std::atoi(optarg);
        break;
      case 'd':
        destination = std::string(optarg);
        break;
      case 'm':
        message = std::string(optarg);
        break;
      case 'c':
        codes[FirstFrameworkExtensionsIds::CONTAINER_CREATION] = std::string(
            optarg);
        break;
      case 'C':
        files[FirstFrameworkExtensionsIds::CONTAINER_CREATION] = std::string(
            optarg);
        break;
      case 'e':
        codes[FirstFrameworkExtensionsIds::CONTAINER_DELETION] = std::string(
            optarg);
        break;
      case 'E':
        files[FirstFrameworkExtensionsIds::CONTAINER_DELETION] = std::string(
            optarg);
        break;
      case 't':
        codes[FirstFrameworkExtensionsIds::DESTINATION] = std::string(optarg);
        break;
      case 'T':
        files[FirstFrameworkExtensionsIds::DESTINATION] = std::string(optarg);
        break;
      case 'l':
        codes[FirstFrameworkExtensionsIds::LIFETIME] = std::string(optarg);
        break;
      case 'L':
        files[FirstFrameworkExtensionsIds::LIFETIME] = std::string(optarg);
        break;
      case 'f':
        codes[FirstFrameworkExtensionsIds::FORWARD] = std::string(optarg);
        break;
      case 'F':
        files[FirstFrameworkExtensionsIds::FORWARD] = std::string(optarg);
        break;
      case 'h':
        help(std::string(argv[0]));
        exit(0);
      default:
        break;
    }
    if (opt == -1)
      break;
  }
  if (ip == "" || port == -1 || destination == "" || message == "") {
    help(std::string(argv[0]));
    exit(0);
  }

  adtnSocket s = adtnSocket(ip, port);
  // Add the codes if any
  for (auto it = codes.begin(); it != codes.end(); ++it) {
    s.addFrameworkExtension(
        static_cast<uint8_t>(FrameworksIds::FIRST_FRAMEWORK),
        static_cast<uint8_t>(it->first), it->second);
  }
  for (auto it = files.begin(); it != files.end(); ++it) {
    std::ifstream codeFile(it->second);
    if (codeFile) {
      std::string code((std::istreambuf_iterator<char>(codeFile)),
                       std::istreambuf_iterator<char>());
      s.addFrameworkExtension(
          static_cast<uint8_t>(FrameworksIds::FIRST_FRAMEWORK),
          static_cast<uint8_t>(it->first), code);
      codeFile.close();
    } else {
      std::cout << "Cannot open the file " << it->second << std::endl;
    }
  }
  try {
    s.send(destination, message);
  } catch (const std::exception &e) {
    std::cout << e.what() << std::endl;
  }
  return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007-2008 Martin Pieuchot
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
 * USA
 */

#include "wx/ogre/rendersystem.h"

#include "wx/ogre/prerequisites.h"
#include "wx/ogre/utils.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
 #ifndef OGRE_PLUGINDIR
 #define OGRE_PLUGINDIR ""
 #endif
#else
 #define OGRE_PLUGINDIR ""
#endif

IMPLEMENT_OGRE_SINGLETON(wxOgreRenderSystem)

//------------------------------------------------------------------------------
wxOgreRenderSystem::wxOgreRenderSystem()
{
#ifndef WXOGRE_DEBUG
	m_root = new Ogre::Root("", "", "");
#else
	m_root = new Ogre::Root("", "", "boot.log");
#endif
}
//------------------------------------------------------------------------------
wxOgreRenderSystem::wxOgreRenderSystem(const Ogre::String& plugins,
                           const Ogre::String& config, const Ogre::String& log)
{
	// Create a new Ogre ROOT
    // Root("plugins.cfg","config.cfg","boot.log");
	m_root = new Ogre::Root(plugins, config, log);
}
//------------------------------------------------------------------------------
wxOgreRenderSystem::~wxOgreRenderSystem()
{
    delete m_root;
    m_root = 0;
}
//------------------------------------------------------------------------------
void wxOgreRenderSystem::LoadPlugin(const Ogre::String& plugin)
{
    try {
#if WXOGRE_DEBUG and OGRE_PLATFORM == OGRE_PLATFORM_WINDOWS
		m_root->loadPlugin(plugin + "_d");
#else
		m_root->loadPlugin(plugin);
#endif
	} catch (Ogre::Exception& e) {
        wxOgreExceptionBox(e);
    }
}
//------------------------------------------------------------------------------
void wxOgreRenderSystem::SelectOgreRenderSystem(const Ogre::String& render)
{
    Ogre::RenderSystemList renderList;
    Ogre::RenderSystemList::iterator it;

    renderList = m_root->getAvailableRenderers();
    // check through all available renderers, if there is one the
    // string is "render"
    for (it = renderList.begin(); it != renderList.end(); ++it) {
        Ogre::RenderSystem* renderSys = *it;
        if (std::string (renderSys->getName()) == render) {
            m_root->setRenderSystem(renderSys);
            break;
        }
    }

}
//------------------------------------------------------------------------------
void wxOgreRenderSystem::Initialise()
{
    m_root->initialise(false);
}
//------------------------------------------------------------------------------
bool wxOgreRenderSystem::HasCapability(const Ogre::Capabilities& c)
{
    return m_root->getRenderSystem()->getCapabilities()->hasCapability(c);
}
//------------------------------------------------------------------------------
<commit_msg>ISIXE-909 fixed warning<commit_after>/*
 * Copyright (C) 2007-2008 Martin Pieuchot
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
 * USA
 */

#include "wx/ogre/rendersystem.h"

#include "wx/ogre/prerequisites.h"
#include "wx/ogre/utils.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
 #ifndef OGRE_PLUGINDIR
 #define OGRE_PLUGINDIR ""
 #endif
#else
 #define OGRE_PLUGINDIR ""
#endif

IMPLEMENT_OGRE_SINGLETON(wxOgreRenderSystem)

//------------------------------------------------------------------------------
wxOgreRenderSystem::wxOgreRenderSystem()
{
#ifndef WXOGRE_DEBUG
	m_root = new Ogre::Root("", "", "");
#else
	m_root = new Ogre::Root("", "", "boot.log");
#endif
}
//------------------------------------------------------------------------------
wxOgreRenderSystem::wxOgreRenderSystem(const Ogre::String& plugins,
                           const Ogre::String& config, const Ogre::String& log)
{
	// Create a new Ogre ROOT
    // Root("plugins.cfg","config.cfg","boot.log");
	m_root = new Ogre::Root(plugins, config, log);
}
//------------------------------------------------------------------------------
wxOgreRenderSystem::~wxOgreRenderSystem()
{
    delete m_root;
    m_root = 0;
}
//------------------------------------------------------------------------------
void wxOgreRenderSystem::LoadPlugin(const Ogre::String& plugin)
{
    try {
#if WXOGRE_DEBUG == 1
		m_root->loadPlugin(plugin + "_d");
#else
		m_root->loadPlugin(plugin);
#endif
	} catch (Ogre::Exception& e) {
        wxOgreExceptionBox(e);
    }
}
//------------------------------------------------------------------------------
void wxOgreRenderSystem::SelectOgreRenderSystem(const Ogre::String& render)
{
    Ogre::RenderSystemList renderList;
    Ogre::RenderSystemList::iterator it;

    renderList = m_root->getAvailableRenderers();
    // check through all available renderers, if there is one the
    // string is "render"
    for (it = renderList.begin(); it != renderList.end(); ++it) {
        Ogre::RenderSystem* renderSys = *it;
        if (std::string (renderSys->getName()) == render) {
            m_root->setRenderSystem(renderSys);
            break;
        }
    }

}
//------------------------------------------------------------------------------
void wxOgreRenderSystem::Initialise()
{
    m_root->initialise(false);
}
//------------------------------------------------------------------------------
bool wxOgreRenderSystem::HasCapability(const Ogre::Capabilities& c)
{
    return m_root->getRenderSystem()->getCapabilities()->hasCapability(c);
}
//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>#pragma once

#include <optional>
#include <tuple>
#include <utility>

#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
#pragma GCC diagnostic ignored "-Wextra-semi-stmt" // fmt/format.h:1242
#pragma GCC diagnostic ignored "-Wundefined-func-template"
#pragma GCC diagnostic ignored "-Wsign-conversion" // fmt/format.h:2699
#pragma GCC diagnostic ignored "-Wdouble-promotion" // fmt/core.h:769
#pragma GCC diagnostic ignored "-Wsigned-enum-bitfield" // fmt/format.h
#pragma GCC diagnostic ignored "-Wshadow" // fmt/chrono.h
#pragma GCC diagnostic ignored "-Wshadow-field" // fmt/core.h
#pragma GCC diagnostic ignored "-Wundef" // fmt/core.h
#pragma GCC diagnostic ignored "-Wunused-template" // fmt/chrono.h
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" // fmt/core.h

// clang 11
#pragma GCC diagnostic ignored "-Wsuggest-override"
#pragma GCC diagnostic ignored "-Wsuggest-destructor-override"
// #pragma GCC diagnostic ignored ""
// #pragma GCC diagnostic ignored ""
// #pragma GCC diagnostic ignored ""
#endif

#ifdef __GNUG__
#pragma GCC diagnostic ignored "-Wdeprecated" // fmt/format.h: implicit capture of ‘this’ via ‘[=]’ is deprecated in C++20
#endif

#include <fmt/format.h>
#include <fmt/ranges.h>
#include <fmt/chrono.h>

#pragma GCC diagnostic pop

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

namespace acmacs::fmt_helper
{
    struct default_formatter
    {
    };

    struct float_formatter
    {
    };
}

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

template <> struct fmt::formatter<acmacs::fmt_helper::default_formatter>
{
    template <typename ParseContext> constexpr auto parse(ParseContext& ctx)
    {
        return ctx.begin();
    }
};

template <> struct fmt::formatter<acmacs::fmt_helper::float_formatter>
{
    template <typename ParseContext> constexpr auto parse(ParseContext& ctx)
    {
        auto it = ctx.begin();
        if (it != ctx.end() && *it == ':')
            ++it;
        const auto end = std::find(it, ctx.end(), '}');
        format_ = fmt::format("{{:{}}}", std::string(it, end));
        return end;
    }

    template <typename Val> std::string format_val(Val&& val)
    {
        return fmt::format(format_, std::forward<Val>(val));
    }

    template <typename Val, typename FormatContext> auto format_val(Val&& val, FormatContext& ctx)
    {
        return format_to(ctx.out(), format_, std::forward<Val>(val));
    }

  private:
    std::string format_;
};

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

template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<std::exception, T>, char>> : fmt::formatter<const char*> {
    template <typename FormatCtx> auto format(const std::exception& err, FormatCtx& ctx) { return fmt::formatter<const char*>::format(err.what(), ctx); }
};

// template <> struct fmt::formatter<std::exception>
// {
//     template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
//     template <typename FormatContext> auto format(const std::exception& err, FormatContext& ctx) { return format_to(ctx.out(), "{}", err.what()); }
// };

// template <> struct fmt::formatter<###> : fmt::formatter<acmacs::fmt_helper::default_formatter> {
//     template <typename FormatCtx> auto format(const ###& value, FormatCtx& ctx)
//     {
//         format_to(ctx.out(), "{} {}", );
//         return format_to(ctx.out(), "{} {}", );
//         return ctx.out();
//     }
// };

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

namespace fmt
{
    template <typename T> std::string format(const std::vector<T>& collection, std::string_view entry_format, std::string_view entry_separator = "\n  ")
    {
        return fmt::format(entry_format, fmt::join(collection, entry_separator));
    }

} // namespace fmt

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

namespace fmt
{
    enum class if_no_substitution_found { leave_as_is, empty };

    std::vector<std::pair<std::string_view, std::string_view>> split_for_formatting(std::string_view source); // pair{key, format}: {"key", "{key:03d}"} {"", "between-format"}

    template <typename FormatMatched, typename FormatNoPattern, typename... Args>
    void substitute_to(FormatMatched&& format_matched, FormatNoPattern&& format_no_pattern, std::string_view pattern, if_no_substitution_found insf, Args&&... args)
    {
        const auto match_and_format = [&format_matched](std::string_view look_for, std::string_view pattern_arg, const auto& en) {
            if (look_for == std::get<0>(en)) {
                format_matched(pattern_arg, en);
                return true;
            }
            else
                return false;
        };

        for (const auto& [key, pattern_arg] : split_for_formatting(pattern)) {
            if (!key.empty()) {
                if (!(match_and_format(key, pattern_arg, args) || ...)) {
                    // not matched
                    switch (insf) {
                        case if_no_substitution_found::leave_as_is:
                            format_no_pattern(pattern_arg);
                            break;
                        case if_no_substitution_found::empty:
                            break;
                    }
                }
            }
            else
                format_no_pattern(pattern_arg);
        }
    }

    template <typename... Args> void substitute_to(memory_buffer& output, std::string_view pattern, if_no_substitution_found insf, Args&&... args)
    {
        const auto format_matched = [&output](std::string_view pattern_arg, const auto& key_value) {
            static_assert(std::is_same_v<std::decay_t<decltype(std::get<0>(key_value))>, const char*>);
            if constexpr (std::tuple_size<std::decay_t<decltype(key_value)>>::value == 2) {
                if constexpr (std::is_invocable_v<decltype(std::get<1>(key_value))>)
                    format_to(output, pattern_arg, arg(std::get<0>(key_value), std::invoke(std::get<1>(key_value))));
                else
                    format_to(output, pattern_arg, arg(std::get<0>(key_value), std::get<1>(key_value)));
            }
            else if constexpr (std::tuple_size<std::decay_t<decltype(key_value)>>::value == 4) {
                format_to(output, pattern_arg, arg(std::get<0>(key_value), std::get<1>(key_value)), arg(std::get<2>(key_value), std::get<3>(key_value)));
            }
            else
                static_assert(
                    std::tuple_size<std::decay_t<decltype(key_value)>>::value == 0,
                    "fmt::substitute arg can be used in the following forms: std::pair<const char*, value>, std::pair<const char*, lambda>, std::tuple<const char*, value, const char*, value>");
        };
        const auto format_no_pattern = [&output](std::string_view no_pattern) { output.append(no_pattern); };
        substitute_to(format_matched, format_no_pattern, pattern, insf, std::forward<Args>(args)...);
    }

    // see acmacs-chart-2/cc/name-format.cc for usage example

    template <typename... Args> std::string substitute(std::string_view pattern, if_no_substitution_found insf, Args&&... args)
    {
        memory_buffer output;
        substitute_to(output, pattern, insf, std::forward<Args>(args)...);
        return to_string(output);
    }

    template <typename... Args> std::string substitute(std::string_view pattern, Args&&... args) { return substitute(pattern, if_no_substitution_found::leave_as_is, std::forward<Args>(args)...); }

} // namespace fmt

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>fmt::substitute description<commit_after>#pragma once

#include <optional>
#include <tuple>
#include <utility>

#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wdocumentation-unknown-command"
#pragma GCC diagnostic ignored "-Wextra-semi-stmt" // fmt/format.h:1242
#pragma GCC diagnostic ignored "-Wundefined-func-template"
#pragma GCC diagnostic ignored "-Wsign-conversion" // fmt/format.h:2699
#pragma GCC diagnostic ignored "-Wdouble-promotion" // fmt/core.h:769
#pragma GCC diagnostic ignored "-Wsigned-enum-bitfield" // fmt/format.h
#pragma GCC diagnostic ignored "-Wshadow" // fmt/chrono.h
#pragma GCC diagnostic ignored "-Wshadow-field" // fmt/core.h
#pragma GCC diagnostic ignored "-Wundef" // fmt/core.h
#pragma GCC diagnostic ignored "-Wunused-template" // fmt/chrono.h
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" // fmt/core.h

// clang 11
#pragma GCC diagnostic ignored "-Wsuggest-override"
#pragma GCC diagnostic ignored "-Wsuggest-destructor-override"
// #pragma GCC diagnostic ignored ""
// #pragma GCC diagnostic ignored ""
// #pragma GCC diagnostic ignored ""
#endif

#ifdef __GNUG__
#pragma GCC diagnostic ignored "-Wdeprecated" // fmt/format.h: implicit capture of ‘this’ via ‘[=]’ is deprecated in C++20
#endif

#include <fmt/format.h>
#include <fmt/ranges.h>
#include <fmt/chrono.h>

#pragma GCC diagnostic pop

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

namespace acmacs::fmt_helper
{
    struct default_formatter
    {
    };

    struct float_formatter
    {
    };
}

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

template <> struct fmt::formatter<acmacs::fmt_helper::default_formatter>
{
    template <typename ParseContext> constexpr auto parse(ParseContext& ctx)
    {
        return ctx.begin();
    }
};

template <> struct fmt::formatter<acmacs::fmt_helper::float_formatter>
{
    template <typename ParseContext> constexpr auto parse(ParseContext& ctx)
    {
        auto it = ctx.begin();
        if (it != ctx.end() && *it == ':')
            ++it;
        const auto end = std::find(it, ctx.end(), '}');
        format_ = fmt::format("{{:{}}}", std::string(it, end));
        return end;
    }

    template <typename Val> std::string format_val(Val&& val)
    {
        return fmt::format(format_, std::forward<Val>(val));
    }

    template <typename Val, typename FormatContext> auto format_val(Val&& val, FormatContext& ctx)
    {
        return format_to(ctx.out(), format_, std::forward<Val>(val));
    }

  private:
    std::string format_;
};

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

template <typename T> struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<std::exception, T>, char>> : fmt::formatter<const char*> {
    template <typename FormatCtx> auto format(const std::exception& err, FormatCtx& ctx) { return fmt::formatter<const char*>::format(err.what(), ctx); }
};

// template <> struct fmt::formatter<std::exception>
// {
//     template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
//     template <typename FormatContext> auto format(const std::exception& err, FormatContext& ctx) { return format_to(ctx.out(), "{}", err.what()); }
// };

// template <> struct fmt::formatter<###> : fmt::formatter<acmacs::fmt_helper::default_formatter> {
//     template <typename FormatCtx> auto format(const ###& value, FormatCtx& ctx)
//     {
//         format_to(ctx.out(), "{} {}", );
//         return format_to(ctx.out(), "{} {}", );
//         return ctx.out();
//     }
// };

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

namespace fmt
{
    template <typename T> std::string format(const std::vector<T>& collection, std::string_view entry_format, std::string_view entry_separator = "\n  ")
    {
        return fmt::format(entry_format, fmt::join(collection, entry_separator));
    }

} // namespace fmt

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

namespace fmt
{
    enum class if_no_substitution_found { leave_as_is, empty };

    std::vector<std::pair<std::string_view, std::string_view>> split_for_formatting(std::string_view source); // pair{key, format}: {"key", "{key:03d}"} {"", "between-format"}

    template <typename FormatMatched, typename FormatNoPattern, typename... Args>
    void substitute_to(FormatMatched&& format_matched, FormatNoPattern&& format_no_pattern, std::string_view pattern, if_no_substitution_found insf, Args&&... args)
    {
        const auto match_and_format = [&format_matched](std::string_view look_for, std::string_view pattern_arg, const auto& en) {
            if (look_for == std::get<0>(en)) {
                format_matched(pattern_arg, en);
                return true;
            }
            else
                return false;
        };

        for (const auto& [key, pattern_arg] : split_for_formatting(pattern)) {
            if (!key.empty()) {
                if (!(match_and_format(key, pattern_arg, args) || ...)) {
                    // not matched
                    switch (insf) {
                        case if_no_substitution_found::leave_as_is:
                            format_no_pattern(pattern_arg);
                            break;
                        case if_no_substitution_found::empty:
                            break;
                    }
                }
            }
            else
                format_no_pattern(pattern_arg);
        }
    }

    // substitute_to args:
    // std::pair{"name", value}                                     -- {name}, {name:3d}
    // std::pair{"name", []() -> decltype(value) { return value; }} -- {name}, {name:3d}
    // std::tuple{"name1", val1, "name2", val2}                     -- {name1:{name2}d}
    template <typename... Args> void substitute_to(memory_buffer& output, std::string_view pattern, if_no_substitution_found insf, Args&&... args)
    {
        const auto format_matched = [&output](std::string_view pattern_arg, const auto& key_value) {
            static_assert(std::is_same_v<std::decay_t<decltype(std::get<0>(key_value))>, const char*>);
            if constexpr (std::tuple_size<std::decay_t<decltype(key_value)>>::value == 2) {
                if constexpr (std::is_invocable_v<decltype(std::get<1>(key_value))>)
                    format_to(output, pattern_arg, arg(std::get<0>(key_value), std::invoke(std::get<1>(key_value))));
                else
                    format_to(output, pattern_arg, arg(std::get<0>(key_value), std::get<1>(key_value)));
            }
            else if constexpr (std::tuple_size<std::decay_t<decltype(key_value)>>::value == 4) {
                format_to(output, pattern_arg, arg(std::get<0>(key_value), std::get<1>(key_value)), arg(std::get<2>(key_value), std::get<3>(key_value)));
            }
            else
                static_assert(
                    std::tuple_size<std::decay_t<decltype(key_value)>>::value == 0,
                    "fmt::substitute arg can be used in the following forms: std::pair<const char*, value>, std::pair<const char*, lambda>, std::tuple<const char*, value, const char*, value>");
        };
        const auto format_no_pattern = [&output](std::string_view no_pattern) { output.append(no_pattern); };
        substitute_to(format_matched, format_no_pattern, pattern, insf, std::forward<Args>(args)...);
    }

    // see acmacs-chart-2/cc/name-format.cc for usage example

    template <typename... Args> std::string substitute(std::string_view pattern, if_no_substitution_found insf, Args&&... args)
    {
        memory_buffer output;
        substitute_to(output, pattern, insf, std::forward<Args>(args)...);
        return to_string(output);
    }

    template <typename... Args> std::string substitute(std::string_view pattern, Args&&... args) { return substitute(pattern, if_no_substitution_found::leave_as_is, std::forward<Args>(args)...); }

} // namespace fmt

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Titolo:
   Autore: Marchetti Matteo
   Data: 16/01/2017
   Classe: 3INA
   Versione 1.0*/

  int main(){
  	int n1; // Numero preso in input che deve essere maggiore di 0 e minore di n2
  	int n2; // Numero preso in input che deve essere minore di 1000 e maggiore di 0
  	int n;  // Numero compreso tra n1 e n2
  	int I; // Contatore
  	int somma1;//
  	int somma; // Somma degli elementi pari
  	int media; // Media degli elementi dispari
  	int v[1000]; // vettore

  	do{
  		printf("Inserie n2 che deve essere minore di 1000 ma maggiore di 0\n");
  		scanf("%d", &n2);                                                                 // Controllo di n2
	  }while(!(n2<1000)&&(n2>0));
  	do{
  		printf("Inserire n1 che deve essere maggiore di 0 ma deve essere minore di n2\n");
  		scanf("%d", &n1);                                                                // Controllo di n1
	  }while(!(n1>0)&&(n1<n2));
	do{
		printf("Inserire n che deve essere compreso tra n1 e n2\n");
		scanf("%d", &n);                                                                // Controllo di n
	  }while(!(n1<n)&&(n<n2));

	  for(I=0;I<n;I++){
	  	 printf("Inserire un numero\n");
	  	 scanf("%d", &v[I]);
	  	 if(I%2!=0){
	  	 	somma1=somma1+v[I];
	  	 	media++;
		   }
		   if((v[I]%2==0)||(v[I]==0)){
		   	 somma=somma+v[I];
		   }
	  }
	  media=somma1/media;
	  printf("La somma degli elementi pari e':\n%d",somma);
	  printf("La media degli elementi di posto dispari e':\n%d",media);
  }

<commit_msg>Delete SenzaTitolo1.cpp<commit_after><|endoftext|>


<commit_before>/*
   Copyright (c) 2010, The Mineserver Project
   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 The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
 */

//
// Mineserver trxlogger.cpp
//

#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <vector>

#include "trxlogger.h"
#include "logger.h"
#include "config.h"

TrxLogger::TrxLogger (std::string filename) {
  log_stream.open(filename.c_str(), std::fstream::in | std::fstream::out );
  if (!log_stream.is_open()) {
    LOG("Problem opening binary log!");
  }
}

TrxLogger &TrxLogger::get()
{
  static TrxLogger instance(Conf::get().sValue("binlog"));
  return instance;
}

// Log action to binary log
void TrxLogger::log(event_t event)
{
  if(log_stream.good()) {

    event.timestamp = time (NULL);
    log_stream.write(reinterpret_cast<char *>(&event), sizeof(event_t));
  } else {
    LOG("Binary log is bad!");
  }
}

// Get logs based on nick and timestamp
bool TrxLogger::getLogs(time_t t, std::string &nick, std::vector<event_t> *logs) {
  event_t event;
  log_stream.flush();
  log_stream.seekg(0, std::ios::beg);

  while(!log_stream.eof()) {
    log_stream.read(reinterpret_cast<char *>(&event), sizeof(event_t));

    if(event.timestamp < t && event.nick == nick) {
      logs->push_back(event);
    }
  }
  return true;
}

// Get logs based on timestamp
bool TrxLogger::getLogs(time_t t, std::vector<event_t> *logs) {
  event_t event;
  log_stream.flush();
  log_stream.seekg(0, std::ios::beg);

  while(!log_stream.eof()) {
    log_stream.read(reinterpret_cast<char *>(&event), sizeof(event_t));

   if(event.timestamp < t) {
     logs->push_back(event);
   }
  }
  return true;
}

TrxLogger::~TrxLogger() {
  log_stream.close();
}
<commit_msg>Binary logging is working, however after running the /rollback command the log_stream file object goes bad :[<commit_after>/*
   Copyright (c) 2010, The Mineserver Project
   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 The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
 */

//
// Mineserver trxlogger.cpp
//

#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <vector>

#include "trxlogger.h"
#include "logger.h"
#include "config.h"

TrxLogger::TrxLogger (std::string filename) {
  log_stream.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::binary );
  if (!log_stream.is_open()) {
    LOG("Problem opening binary log!");
  }
}

TrxLogger &TrxLogger::get()
{
  static TrxLogger instance(Conf::get().sValue("binlog"));
  return instance;
}

// Log action to binary log
void TrxLogger::log(event_t event)
{
  if(log_stream.good()) {

    event.timestamp = time (NULL);
    log_stream.seekg(0, std::ios::end);
    log_stream.write(reinterpret_cast<char *>(&event), sizeof(event_t));

  } else {
    LOG("Binary log is bad!");
  }
}

// Get logs based on nick and timestamp
bool TrxLogger::getLogs(time_t t, std::string &nick, std::vector<event_t> *logs) {
  event_t event;
  log_stream.flush();
  log_stream.seekg(0, std::ios::beg);

  while(!log_stream.eof()) {
    log_stream.read(reinterpret_cast<char *>(&event), sizeof(event_t));

    if(event.timestamp < t && event.nick == nick) {
      logs->push_back(event);
    }
  }
  return true;
}

// Get logs based on timestamp
bool TrxLogger::getLogs(time_t t, std::vector<event_t> *logs) {
  event_t event;
  log_stream.flush();
  log_stream.seekg(0, std::ios::beg);

  while(!log_stream.eof()) {
    log_stream.read(reinterpret_cast<char *>(&event), sizeof(event_t));

   if(event.timestamp < t) {
     logs->push_back(event);
   }
  }
  return true;
}

TrxLogger::~TrxLogger() {
  log_stream.close();
}
<|endoftext|>


<commit_before>/*  wcecompat: Windows CE C Runtime Library "compatibility" library.
 *
 *  Copyright (C) 2001-2002 Essemer Pty Ltd.  All rights reserved.
 *  http://www.essemer.com.au/
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "ts_string.h"
#include <string.h>
#include <windows.h>

void ascii2unicode(const char* ascii, WCHAR* unicode)
{
	if (((unsigned int)unicode & 1) == 0)
	{	// word-aligned
		while (*ascii != '\0')
			*unicode++ = *ascii++;
		*unicode = '\0';
	}
	else
	{	// not word-aligned
		while (*ascii != '\0')
		{
			*(char*)unicode = *ascii++;
			*(((char*)unicode)+1) = 0;
			unicode++;
		}
		*(char*)unicode = 0;
		*(((char*)unicode)+1) = 0;
	}
}

void unicode2ascii(const WCHAR* unicode, char* ascii)
{
	if (((unsigned int)unicode & 1) == 0)
	{	// word-aligned
		while (*unicode != '\0')
			*ascii++ = (char)*unicode++;
		*ascii = '\0';
	}
	else
	{	// not word-aligned
		while (*(char*)unicode != 0 || *(((char*)unicode)+1) != 0)
			*ascii++ = *(char*)unicode++;
		*ascii = '\0';
	}
}

void ascii2unicode(const char* ascii, WCHAR* unicode, int maxChars)
{
	if (((unsigned int)unicode & 1) == 0)
	{	// word-aligned
		for (int i=0; ascii[i] != 0 && i<maxChars; i++)
			unicode[i] = ascii[i];
		unicode[i] = 0;
	}
	else
	{	// not word-aligned
		for (int i=0; ascii[i] != 0 && i<maxChars; i++)
		{
			*(char*)&unicode[i] = ascii[i];
			*(((char*)&unicode[i])+1) = 0;
			unicode++;
		}
		*(char*)&unicode[i] = 0;
		*(((char*)&unicode[i])+1) = 0;
	}
}

void unicode2ascii(const WCHAR* unicode, char* ascii, int maxChars)
{
	if (((unsigned int)unicode & 1) == 0)
	{	// word-aligned
		for (int i=0; unicode[i] != 0 && i<maxChars; i++)
			ascii[i] = (char)unicode[i];
		ascii[i] = 0;
	}
	else
	{	// not word-aligned
		for (int i=0; (*(char*)&unicode[i] != 0 || *(((char*)&unicode[i])+1) != 0) && i<maxChars; i++)
			ascii[i] = *(char*)&unicode[i];
		ascii[i] = 0;
	}
}

//
// ascii/unicode typesafe versions of strcat
//

char* ts_strcat(char* dest, const WCHAR* src)
{
	char* p = dest;
	while (*p != '\0')
		p++;
	unicode2ascii(src, p);
	return dest;
}

WCHAR* ts_strcat(WCHAR* dest, const char* src)
{
	WCHAR* p = dest;
	while (*p != '\0')
		p++;
	ascii2unicode(src, p);
	return dest;
}

//
// ascii/unicode typesafe versions of strdup
//

char* ts_strdup_unicode_to_ascii(const WCHAR* str)
{
	char* result = (char*)malloc(wcslen(str)+1);
	if (result == NULL)
		return NULL;
	unicode2ascii(str, result);
	return result;
}

WCHAR* ts_strdup_ascii_to_unicode(const char* str)
{
	WCHAR* result = (WCHAR*)malloc((strlen(str)+1)*2);
	if (result == NULL)
		return NULL;
	ascii2unicode(str, result);
	return result;
}
<commit_msg>Move the declaration of i outside for loop to extend the scope.<commit_after>/*  wcecompat: Windows CE C Runtime Library "compatibility" library.
 *
 *  Copyright (C) 2001-2002 Essemer Pty Ltd.  All rights reserved.
 *  http://www.essemer.com.au/
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "ts_string.h"
#include <string.h>
#include <windows.h>

void ascii2unicode(const char* ascii, WCHAR* unicode)
{
	if (((unsigned int)unicode & 1) == 0)
	{	// word-aligned
		while (*ascii != '\0')
			*unicode++ = *ascii++;
		*unicode = '\0';
	}
	else
	{	// not word-aligned
		while (*ascii != '\0')
		{
			*(char*)unicode = *ascii++;
			*(((char*)unicode)+1) = 0;
			unicode++;
		}
		*(char*)unicode = 0;
		*(((char*)unicode)+1) = 0;
	}
}

void unicode2ascii(const WCHAR* unicode, char* ascii)
{
	if (((unsigned int)unicode & 1) == 0)
	{	// word-aligned
		while (*unicode != '\0')
			*ascii++ = (char)*unicode++;
		*ascii = '\0';
	}
	else
	{	// not word-aligned
		while (*(char*)unicode != 0 || *(((char*)unicode)+1) != 0)
			*ascii++ = *(char*)unicode++;
		*ascii = '\0';
	}
}

void ascii2unicode(const char* ascii, WCHAR* unicode, int maxChars)
{
	int i;
	if (((unsigned int)unicode & 1) == 0)
	{	// word-aligned
		for (i=0; ascii[i] != 0 && i<maxChars; i++)
			unicode[i] = ascii[i];
		unicode[i] = 0;
	}
	else
	{	// not word-aligned
		for (i=0; ascii[i] != 0 && i<maxChars; i++)
		{
			*(char*)&unicode[i] = ascii[i];
			*(((char*)&unicode[i])+1) = 0;
			unicode++;
		}
		*(char*)&unicode[i] = 0;
		*(((char*)&unicode[i])+1) = 0;
	}
}

void unicode2ascii(const WCHAR* unicode, char* ascii, int maxChars)
{
	int i;
	if (((unsigned int)unicode & 1) == 0)
	{	// word-aligned
		for (i=0; unicode[i] != 0 && i<maxChars; i++)
			ascii[i] = (char)unicode[i];
		ascii[i] = 0;
	}
	else
	{	// not word-aligned
		for (i=0; (*(char*)&unicode[i] != 0 || *(((char*)&unicode[i])+1) != 0) && i<maxChars; i++)
			ascii[i] = *(char*)&unicode[i];
		ascii[i] = 0;
	}
}

//
// ascii/unicode typesafe versions of strcat
//

char* ts_strcat(char* dest, const WCHAR* src)
{
	char* p = dest;
	while (*p != '\0')
		p++;
	unicode2ascii(src, p);
	return dest;
}

WCHAR* ts_strcat(WCHAR* dest, const char* src)
{
	WCHAR* p = dest;
	while (*p != '\0')
		p++;
	ascii2unicode(src, p);
	return dest;
}

//
// ascii/unicode typesafe versions of strdup
//

char* ts_strdup_unicode_to_ascii(const WCHAR* str)
{
	char* result = (char*)malloc(wcslen(str)+1);
	if (result == NULL)
		return NULL;
	unicode2ascii(str, result);
	return result;
}

WCHAR* ts_strdup_ascii_to_unicode(const char* str)
{
	WCHAR* result = (WCHAR*)malloc((strlen(str)+1)*2);
	if (result == NULL)
		return NULL;
	ascii2unicode(str, result);
	return result;
}
<|endoftext|>


<commit_before>#include "client.h"
#include "util.h"
#include <thread>
#include <sys/time.h>
#include "unistd.h"

Client::Client(const std::string id, const User* user, uint16_t keepAlive, const Will* will) : pingDulation(0), Terminal(id, user, keepAlive, will) {}

Client::~Client() {}

MQTT_ERROR Client::ping() {
    MQTT_ERROR err = this->ct->sendMessage(new PingreqMessage());
    gettimeofday(&(this->timeOfPing), NULL);
    return err;
}

void pingLoop(Client* c) {
    while (c->isConnecting) {
        usleep(c->pingDulation);
        c->ct->sendMessage(new PingrespMessage());
        gettimeofday(&(c->timeOfPing), NULL);
    }
}

MQTT_ERROR Client::connect(const std::string addr, int port, bool cs) {
    if (this->ID.size() == 0 && !cs) {
        return CLEANSESSION_MUST_BE_TRUE;
        cs = true;
    }

    this->ct = new Transport(addr, port);
    this->ct->connectTarget();
    this->cleanSession = cs;
    MQTT_ERROR err = this->ct->sendMessage(new ConnectMessage(this->keepAlive, this->ID, this->cleanSession, this->will, this->user));
    if (err != NO_ERROR) {
        return err;
    }
    std::thread t(readLoop, this);
    t.join();
    this->readThread = &t;
    return err;
}

MQTT_ERROR Client::disconnectProcessing() {
    MQTT_ERROR err = NO_ERROR;
    if (this->isConnecting) {
        this->isConnecting = false; // this makes readLoop stop
    }
    err = this->disconnectBase();
    return err;
}

MQTT_ERROR Client::publish(const std::string topic, const std::string data, uint8_t qos, bool retain) {
    if (qos >= 3) {
        return INVALID_QOS_3;
    }
    //if ()

    uint16_t id = 0;
    if (qos > 0) {
        MQTT_ERROR err = getUsablePacketID(&id);
        if (err != NO_ERROR) {
            return err;
        }
    }
    return this->sendMessage(new PublishMessage(false, qos, retain, id, topic, data));
}

MQTT_ERROR Client::subscribe(std::vector<SubscribeTopic*> topics) {
    uint16_t id = 0;
    MQTT_ERROR err = getUsablePacketID(&id);
    if (err != NO_ERROR) {
        return err;
    }
    for (int i = 0; i < topics.size(); i++) {
        std::vector<std::string> parts;
        split(topics[i]->topic, "/", &parts);
        for (int j = 0; i < parts.size(); i++) {
            if (parts[j][0] == '#' && j != parts.size() - 1) {
                return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL;
            } else if (false) {
            } // has suffix of '#' and '+'
        }
    }
    return this->sendMessage(new SubscribeMessage(id, topics));
}

MQTT_ERROR Client::unsubscribe(std::vector<std::string> topics) {
    for (int i = 0; i < topics.size(); i++) {
        std::vector<std::string> parts;
        split(topics[i], "/", &parts);
        for (int j = 0; j < parts.size(); j++) {
            if (parts[j][0] == '#' && j != parts.size() - 1) {
                return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL;
            } else if (parts[j][parts[j].size()-1] == '#' || parts[j][parts[j].size()-1] == '+') {
                return WILDCARD_MUST_NOT_BE_ADJACENT_TO_NAME;
            }
        }
    }
    uint16_t id = 0;
    MQTT_ERROR err = this->getUsablePacketID(&id);
    if (err != NO_ERROR) {
        return err;
    }
    return this->sendMessage(new UnsubscribeMessage(id, topics));
}

MQTT_ERROR Client::disconnect() {
    MQTT_ERROR err = this->sendMessage(new DisconnectMessage());
    // TODO : find out how to use thread
    //std::thread t = std::thread([]{
    usleep(this->pingDulation*2);
    this->disconnectProcessing();
    //});
    return err;
}

MQTT_ERROR Client::recvConnectMessage(ConnectMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvConnackMessage(ConnackMessage* m) {
    if (m->returnCode != CONNECT_ACCEPTED) {
        //return m->ReturnCode;
    }

    this->isConnecting = true;
    if (this->keepAlive != 0) {
        std::thread t(pingLoop, this);
        t.join();
    }

    return this->redelivery();
}

MQTT_ERROR Client::recvPublishMessage(PublishMessage* m) {
    if (m->fh->dup) {
        // re-delivered;
    } else {
        // first time delivery
    }

    if (m->fh->retain) {
        // retained Message
    }

    switch (m->fh->qos) {
    case 0:
        if (m->fh->packetID != 0) {
            return PACKET_ID_SHOULD_BE_ZERO; // packet id should be zero
        }
        break;
    case 1:
        return this->sendMessage(new PubackMessage(m->fh->packetID));
        break;
    case 2:
        return this->sendMessage(new PubrecMessage(m->fh->packetID));
        break;
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvPubackMessage(PubackMessage* m) {
    if (m->fh->packetID > 0) {
        return this->ackMessage(m->fh->packetID);
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvPubrecMessage(PubrecMessage* m) {
    MQTT_ERROR err = this->ackMessage(m->fh->packetID);
    if (err < 0) {
        return err;
    }
    err = this->sendMessage(new PubrelMessage(m->fh->packetID));
    return err;
}
MQTT_ERROR Client::recvPubrelMessage(PubrelMessage* m) {
    MQTT_ERROR err = this->ackMessage(m->fh->packetID);
    if (err < 0) {
        return err;
    }
    err = this->sendMessage(new PubcompMessage(m->fh->packetID));
    return err;
}

MQTT_ERROR Client::recvPubcompMessage(PubcompMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvSubscribeMessage(SubscribeMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvSubackMessage(SubackMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvUnsubscribeMessage(UnsubscribeMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvUnsubackMessage(UnsubackMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvPingreqMessage(PingreqMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvPingrespMessage(PingrespMessage* m) {
    struct timeval tmp;
    gettimeofday(&tmp, NULL);
    this->pingDulation = (tmp.tv_sec - this->timeOfPing.tv_sec)*1000000 + (tmp.tv_usec - this->timeOfPing.tv_usec);
    if (this->pingDulation >= this->keepAlive) {
        this->sendMessage(new DisconnectMessage());
        return SERVER_TIMED_OUT;
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvDisconnectMessage(DisconnectMessage* m) {return INVALID_MESSAGE_CAME;}

<commit_msg>avoid shortcut<commit_after>#include "client.h"
#include "util.h"
#include <thread>
#include <sys/time.h>
#include "unistd.h"

Client::Client(const std::string id, const User* user, uint16_t keepAlive, const Will* will) : pingDulation(0), Terminal(id, user, keepAlive, will) {}

Client::~Client() {}

MQTT_ERROR Client::ping() {
    MQTT_ERROR err = this->sendMessage(new PingreqMessage());
    gettimeofday(&(this->timeOfPing), NULL);
    return err;
}

void pingLoop(Client* c) {
    while (c->isConnecting) {
        usleep(c->pingDulation);
        c->sendMessage(new PingrespMessage());
        gettimeofday(&(c->timeOfPing), NULL);
    }
}

MQTT_ERROR Client::connect(const std::string addr, int port, bool cs) {
    if (this->ID.size() == 0 && !cs) {
        return CLEANSESSION_MUST_BE_TRUE;
        cs = true;
    }

    this->ct = new Transport(addr, port);
    this->ct->connectTarget();
    this->cleanSession = cs;
    MQTT_ERROR err = this->ct->sendMessage(new ConnectMessage(this->keepAlive, this->ID, this->cleanSession, this->will, this->user));
    if (err != NO_ERROR) {
        return err;
    }
    std::thread t(readLoop, this);
    t.join();
    this->readThread = &t;
    return err;
}

MQTT_ERROR Client::disconnectProcessing() {
    MQTT_ERROR err = NO_ERROR;
    if (this->isConnecting) {
        this->isConnecting = false; // this makes readLoop stop
    }
    err = this->disconnectBase();
    return err;
}

MQTT_ERROR Client::publish(const std::string topic, const std::string data, uint8_t qos, bool retain) {
    if (qos >= 3) {
        return INVALID_QOS_3;
    }
    //if ()

    uint16_t id = 0;
    if (qos > 0) {
        MQTT_ERROR err = getUsablePacketID(&id);
        if (err != NO_ERROR) {
            return err;
        }
    }
    return this->sendMessage(new PublishMessage(false, qos, retain, id, topic, data));
}

MQTT_ERROR Client::subscribe(std::vector<SubscribeTopic*> topics) {
    uint16_t id = 0;
    MQTT_ERROR err = getUsablePacketID(&id);
    if (err != NO_ERROR) {
        return err;
    }
    for (int i = 0; i < topics.size(); i++) {
        std::vector<std::string> parts;
        split(topics[i]->topic, "/", &parts);
        for (int j = 0; i < parts.size(); i++) {
            if (parts[j][0] == '#' && j != parts.size() - 1) {
                return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL;
            } else if (false) {
            } // has suffix of '#' and '+'
        }
    }
    return this->sendMessage(new SubscribeMessage(id, topics));
}

MQTT_ERROR Client::unsubscribe(std::vector<std::string> topics) {
    for (int i = 0; i < topics.size(); i++) {
        std::vector<std::string> parts;
        split(topics[i], "/", &parts);
        for (int j = 0; j < parts.size(); j++) {
            if (parts[j][0] == '#' && j != parts.size() - 1) {
                return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL;
            } else if (parts[j][parts[j].size()-1] == '#' || parts[j][parts[j].size()-1] == '+') {
                return WILDCARD_MUST_NOT_BE_ADJACENT_TO_NAME;
            }
        }
    }
    uint16_t id = 0;
    MQTT_ERROR err = this->getUsablePacketID(&id);
    if (err != NO_ERROR) {
        return err;
    }
    return this->sendMessage(new UnsubscribeMessage(id, topics));
}

MQTT_ERROR Client::disconnect() {
    MQTT_ERROR err = this->sendMessage(new DisconnectMessage());
    // TODO : find out how to use thread
    //std::thread t = std::thread([]{
    usleep(this->pingDulation*2);
    this->disconnectProcessing();
    //});
    return err;
}

MQTT_ERROR Client::recvConnectMessage(ConnectMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvConnackMessage(ConnackMessage* m) {
    if (m->returnCode != CONNECT_ACCEPTED) {
        //return m->ReturnCode;
    }

    this->isConnecting = true;
    if (this->keepAlive != 0) {
        std::thread t(pingLoop, this);
        t.join();
    }

    return this->redelivery();
}

MQTT_ERROR Client::recvPublishMessage(PublishMessage* m) {
    if (m->fh->dup) {
        // re-delivered;
    } else {
        // first time delivery
    }

    if (m->fh->retain) {
        // retained Message
    }

    switch (m->fh->qos) {
    case 0:
        if (m->fh->packetID != 0) {
            return PACKET_ID_SHOULD_BE_ZERO; // packet id should be zero
        }
        break;
    case 1:
        return this->sendMessage(new PubackMessage(m->fh->packetID));
        break;
    case 2:
        return this->sendMessage(new PubrecMessage(m->fh->packetID));
        break;
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvPubackMessage(PubackMessage* m) {
    if (m->fh->packetID > 0) {
        return this->ackMessage(m->fh->packetID);
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvPubrecMessage(PubrecMessage* m) {
    MQTT_ERROR err = this->ackMessage(m->fh->packetID);
    if (err < 0) {
        return err;
    }
    err = this->sendMessage(new PubrelMessage(m->fh->packetID));
    return err;
}
MQTT_ERROR Client::recvPubrelMessage(PubrelMessage* m) {
    MQTT_ERROR err = this->ackMessage(m->fh->packetID);
    if (err < 0) {
        return err;
    }
    err = this->sendMessage(new PubcompMessage(m->fh->packetID));
    return err;
}

MQTT_ERROR Client::recvPubcompMessage(PubcompMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvSubscribeMessage(SubscribeMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvSubackMessage(SubackMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvUnsubscribeMessage(UnsubscribeMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvUnsubackMessage(UnsubackMessage* m) {
    return this->ackMessage(m->fh->packetID);
}

MQTT_ERROR Client::recvPingreqMessage(PingreqMessage* m) {return INVALID_MESSAGE_CAME;}

MQTT_ERROR Client::recvPingrespMessage(PingrespMessage* m) {
    struct timeval tmp;
    gettimeofday(&tmp, NULL);
    this->pingDulation = (tmp.tv_sec - this->timeOfPing.tv_sec)*1000000 + (tmp.tv_usec - this->timeOfPing.tv_usec);
    if (this->pingDulation >= this->keepAlive) {
        this->sendMessage(new DisconnectMessage());
        return SERVER_TIMED_OUT;
    }
    return NO_ERROR;
}

MQTT_ERROR Client::recvDisconnectMessage(DisconnectMessage* m) {return INVALID_MESSAGE_CAME;}

<|endoftext|>