<commit_before>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */
#include "file.h"

#include <Poco/File.h>
#include <Poco/FileStream.h>
#include <Poco/Exception.h>

namespace ti
{
	File::File(BoundObject *global, std::string filename) : global(global), filename(filename)
	{
		KR_ADDREF(global);

		this->SetMethod("toString",&File::ToString);
		this->SetMethod("isFile",&File::IsFile);
		this->SetMethod("isDirectory",&File::IsDirectory);
		this->SetMethod("isHidden",&File::IsHidden);

		this->SetMethod("isSymbolicLink",&File::IsSymbolicLink);
		this->SetMethod("exists",&File::Exists);
		this->SetMethod("read",&File::Read);
		this->SetMethod("copy",&File::Copy);
		this->SetMethod("move",&File::Move);
		this->SetMethod("createDirectory",&File::CreateDirectoryX);
		this->SetMethod("deleteDirectory",&File::DeleteDirectory);
		this->SetMethod("deleteFile",&File::DeleteFileX);
		this->SetMethod("getDirectoryListing",&File::GetDirectoryListing);
	}

	File::~File()
	{
		KR_DECREF(global);
	}

	void File::ToString(const ValueList& args, SharedValue result)
	{
		result->SetString(this->filename.c_str());
	}
	void File::IsFile(const ValueList& args, SharedValue result)
	{
		bool isFile = false;

		try
		{
			Poco::File file(this->filename);
			isFile = file.isFile();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(isFile);
	}
	void File::IsDirectory(const ValueList& args, SharedValue result)
	{
		bool isDir = false;

		try
		{
			Poco::File dir(this->filename);
			isDir = dir.isDirectory();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(isDir);
	}
	void File::IsHidden(const ValueList& args, SharedValue result)
	{
		bool isHidden = false;

		try
		{
			Poco::File file(this->filename);
			isHidden = file.isHidden();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(isHidden);
	}
	void File::IsSymbolicLink(const ValueList& args, SharedValue result)
	{
		bool isLink = false;

		try
		{
			Poco::File file(this->filename);
			isLink = file.isLink();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(isLink);
	}
	void File::Exists(const ValueList& args, SharedValue result)
	{
		bool exists = false;

		try
		{
			Poco::File file(this->filename);
			exists = file.exists();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(exists);
	}
	void File::Read(const ValueList& args, SharedValue result)
	{
		try
		{
			Poco::File file(this->filename);
			if(file.canRead())
			{
				Poco::FileInputStream fis(this->filename);

				std::string contents;

				while(! fis.eof())
				{
					std::string s;
					std::getline(fis, s);

					contents.append(s);
				}

				result->SetString(contents.c_str());
			}
			else
			{
				result->SetNull();
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem reading file:::: " << exc.displayText() << std::endl;

			result->SetNull();
		}
	}
	void File::Copy(const ValueList& args, SharedValue result)
	{
		bool success = false;

		try
		{
			std::string dest = args.at(0)->ToString();
			// TODO need to verify parameters

			Poco::File from(this->filename);

			from.copyTo(dest);

			success = true;
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem copying file:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(success);
	}
	void File::Move(const ValueList& args, SharedValue result)
	{
		bool success = false;

		try
		{
			std::string dest = args.at(0)->ToString();
			// TODO need to verify parameters

			Poco::File from(this->filename);

			from.moveTo(dest);

			success = true;
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem moving file:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(success);
	}
	void File::CreateDirectoryX(const ValueList& args, SharedValue result)
	{
		bool created = false;

		try
		{
			bool createParents = false;
			if(args.size() > 0)
			{
				createParents = args.at(0)->ToBool();
			}

			Poco::File dir(this->filename);

			if(! dir.exists())
			{
				if(createParents)
				{
					dir.createDirectories();
					created = true;
				}
				else {
					created = dir.createDirectory();
				}
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem creating directory:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(created);
	}
	void File::DeleteDirectory(const ValueList& args, SharedValue result)
	{
		bool deleted = false;

		try
		{
			bool deleteContents = false;
			if(args.size() > 0)
			{
				deleteContents = args.at(0)->ToBool();
			}

			Poco::File dir(this->filename);

			if(dir.exists() && dir.isDirectory())
			{
				dir.remove(deleteContents);

				deleted = true;
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem deleting directory:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(deleted);
	}
	void File::DeleteFileX(const ValueList& args, SharedValue result)
	{
		bool deleted = false;

		try
		{
			Poco::File file(this->filename);

			if(file.exists() && file.isFile())
			{
				file.remove();

				deleted = true;
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem deleting file:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(deleted);
	}
	void File::GetDirectoryListing(const ValueList& args, SharedValue result)
	{
		try
		{
			Poco::File dir(this->filename);

			if(dir.exists() && dir.isDirectory())
			{
				std::vector<std::string> files;
				dir.list(files);

				SharedPtr<StaticBoundList> fileList = new StaticBoundList();

				for(int i = 0; i < files.size(); i++)
				{
					SharedValue value = new Value(files.at(i));
					fileList->Append(value);
				}

				SharedPtr<BoundList> list = fileList;
				result->SetList(list);
			}
			else
			{
				result->SetNull();
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem deleting file:::: " << exc.displayText() << std::endl;

			result->SetNull();
		}
	}
}
<commit_msg>fixed warning in osx<commit_after>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */
#include "file.h"

#include <Poco/File.h>
#include <Poco/FileStream.h>
#include <Poco/Exception.h>

namespace ti
{
	File::File(BoundObject *global, std::string filename) : global(global), filename(filename)
	{
		KR_ADDREF(global);

		this->SetMethod("toString",&File::ToString);
		this->SetMethod("isFile",&File::IsFile);
		this->SetMethod("isDirectory",&File::IsDirectory);
		this->SetMethod("isHidden",&File::IsHidden);

		this->SetMethod("isSymbolicLink",&File::IsSymbolicLink);
		this->SetMethod("exists",&File::Exists);
		this->SetMethod("read",&File::Read);
		this->SetMethod("copy",&File::Copy);
		this->SetMethod("move",&File::Move);
		this->SetMethod("createDirectory",&File::CreateDirectoryX);
		this->SetMethod("deleteDirectory",&File::DeleteDirectory);
		this->SetMethod("deleteFile",&File::DeleteFileX);
		this->SetMethod("getDirectoryListing",&File::GetDirectoryListing);
	}

	File::~File()
	{
		KR_DECREF(global);
	}

	void File::ToString(const ValueList& args, SharedValue result)
	{
		result->SetString(this->filename.c_str());
	}
	void File::IsFile(const ValueList& args, SharedValue result)
	{
		bool isFile = false;

		try
		{
			Poco::File file(this->filename);
			isFile = file.isFile();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(isFile);
	}
	void File::IsDirectory(const ValueList& args, SharedValue result)
	{
		bool isDir = false;

		try
		{
			Poco::File dir(this->filename);
			isDir = dir.isDirectory();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(isDir);
	}
	void File::IsHidden(const ValueList& args, SharedValue result)
	{
		bool isHidden = false;

		try
		{
			Poco::File file(this->filename);
			isHidden = file.isHidden();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(isHidden);
	}
	void File::IsSymbolicLink(const ValueList& args, SharedValue result)
	{
		bool isLink = false;

		try
		{
			Poco::File file(this->filename);
			isLink = file.isLink();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(isLink);
	}
	void File::Exists(const ValueList& args, SharedValue result)
	{
		bool exists = false;

		try
		{
			Poco::File file(this->filename);
			exists = file.exists();
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem getting file info:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(exists);
	}
	void File::Read(const ValueList& args, SharedValue result)
	{
		try
		{
			Poco::File file(this->filename);
			if(file.canRead())
			{
				Poco::FileInputStream fis(this->filename);

				std::string contents;

				while(! fis.eof())
				{
					std::string s;
					std::getline(fis, s);

					contents.append(s);
				}

				result->SetString(contents.c_str());
			}
			else
			{
				result->SetNull();
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem reading file:::: " << exc.displayText() << std::endl;

			result->SetNull();
		}
	}
	void File::Copy(const ValueList& args, SharedValue result)
	{
		bool success = false;

		try
		{
			std::string dest = args.at(0)->ToString();
			// TODO need to verify parameters

			Poco::File from(this->filename);

			from.copyTo(dest);

			success = true;
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem copying file:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(success);
	}
	void File::Move(const ValueList& args, SharedValue result)
	{
		bool success = false;

		try
		{
			std::string dest = args.at(0)->ToString();
			// TODO need to verify parameters

			Poco::File from(this->filename);

			from.moveTo(dest);

			success = true;
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem moving file:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(success);
	}
	void File::CreateDirectoryX(const ValueList& args, SharedValue result)
	{
		bool created = false;

		try
		{
			bool createParents = false;
			if(args.size() > 0)
			{
				createParents = args.at(0)->ToBool();
			}

			Poco::File dir(this->filename);

			if(! dir.exists())
			{
				if(createParents)
				{
					dir.createDirectories();
					created = true;
				}
				else {
					created = dir.createDirectory();
				}
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem creating directory:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(created);
	}
	void File::DeleteDirectory(const ValueList& args, SharedValue result)
	{
		bool deleted = false;

		try
		{
			bool deleteContents = false;
			if(args.size() > 0)
			{
				deleteContents = args.at(0)->ToBool();
			}

			Poco::File dir(this->filename);

			if(dir.exists() && dir.isDirectory())
			{
				dir.remove(deleteContents);

				deleted = true;
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem deleting directory:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(deleted);
	}
	void File::DeleteFileX(const ValueList& args, SharedValue result)
	{
		bool deleted = false;

		try
		{
			Poco::File file(this->filename);

			if(file.exists() && file.isFile())
			{
				file.remove();

				deleted = true;
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem deleting file:::: " << exc.displayText() << std::endl;
		}

		result->SetBool(deleted);
	}
	void File::GetDirectoryListing(const ValueList& args, SharedValue result)
	{
		try
		{
			Poco::File dir(this->filename);

			if(dir.exists() && dir.isDirectory())
			{
				std::vector<std::string> files;
				dir.list(files);

				SharedPtr<StaticBoundList> fileList = new StaticBoundList();

				for(size_t i = 0; i < files.size(); i++)
				{
					SharedValue value = new Value(files.at(i));
					fileList->Append(value);
				}

				SharedPtr<BoundList> list = fileList;
				result->SetList(list);
			}
			else
			{
				result->SetNull();
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Problem deleting file:::: " << exc.displayText() << std::endl;

			result->SetNull();
		}
	}
}
<|endoftext|>


<commit_before>#include <avr/io.h>
#include <util/delay.h>
#include <avr/sleep.h>
#include <stdio.h>

#include "testHooks.h"
#include "TestStreams.h"

#include "comms/NMEA.h"
//TESTING "comms/NMEA.cpp"
//TESTING "math/GreatCircle.cpp"
//TESTING "math/Waypoint.cpp"
//TESTING "math/SpatialMath.cpp"

bool TestStream(void){
    StringStream ss("I'ma String Stream");
    ss.write((const uint8_t *)"Hello there terminal!", 21);
    while(ss.available()){
        ss.write(ss.read());
    }
    return ss.read() == -1;

}

int main(void){
    TEST(TestStream);
    return 0;
}
<commit_msg>Positive test cases for NMEA library<commit_after>#include <avr/io.h>
#include <util/delay.h>
#include <avr/sleep.h>
#include <stdio.h>

#include "testHooks.h"
#include "TestStreams.h"

#include "comms/NMEA.h"
//TESTING "comms/NMEA.cpp"
//TESTING "math/GreatCircle.cpp"
//TESTING "math/Waypoint.cpp"
//TESTING "math/SpatialMath.cpp"

typedef struct GPRMC{
    const char * desc;
    const char * str;
    float time;
    bool  active;
    float latitude;
    float longitude;
    float speed;
    float trackAngle;
    long  date;
    float magVar;
} GPRMC;

/*
lat/lon is in degrees+decimal minutes, code spec is decimal degrees
function decimalDegrees(degreeDecimalMinutes)
    minutes = degreeDecimalMinutes % 100.0
    degrees = (degreeDecimalMinutes - minutes) / 100.0
    decimalDegrees = degrees + minutes/60.0
    return decimalDegrees
end

speed in GPRMC is in knots, code spec returns mph
mph(knots) = knots * 1.15077945
*/

//examples taken from http://www.gpsinformation.org/dale/nmea.htm
const GPRMC goodData[] {
    { "NE GPRMC",
      "$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A",
      123519, true, 48.11729, 11.51666, 25.77746, 84.4, 230394, 3.1
    },
    { "NW GPRMC",
      "$GPRMC,183729,A,3907.356,N,12102.482,W,000.0,360.0,080301,015.5,E*6F",
      183729, true, 39.12260, -121.04136, 0.0, 360.0, 80301, 15.5
    },
    { "Bad Status",
      "$GPRMC,152926,V,6027.8259,N,02225.6713,E,10.8,0.0,190803,5.9,E,S*22",
      152926, false, 60.46376, 22.42786, 12.428418, 0.0, 190803, 5.9
    },
    { "Empty Fields",
      "$GPRMC,162254.00,A,3723.02837,N,12159.39853,W,0.820,188.36,110706,,,A*74",
      162254, true, 37.38380, -121.98998, 0.94364, 188.36, 110706, 0.0
    },
    { "DecimalTime",
      "$GPRMC,230611.016,V,3907.3813,N,12102.4635,W,0.14,136.40,041002,,*04",
      230611.016, false, 39.12302, -121.04106, 0.161109, 136.40, 41002, 0.0
    },
    { "Surrounded GPRMC",
      "$GPGSV,3,3,09,24,12,282,00*4D"
      "$GPGLL,3553.5295,N,13938.6570,E,002454,A,A*4F"
      "$GPBOD,,T,,M,,*47"
      "$PGRME,8.6,M,9.6,M,12.9,M*15"
      "$PGRMZ,51,f*30"
      "$HCHDG,101.1,,,7.1,W*3C"
      "$GPRTE,1,1,c,*37"
      "$GPRMC,002456,A,3553.5295,N,13938.6570,E,0.0,43.1,180700,7.1,W,A*3D"
      "$GPGGA,002454,3553.5295,N,13938.6570,E,1,05,2.2,18.3,M,39.0,M,,*7F"
      "$GPGSA,A,3,01,04,07,16,20,,,,,,,,3.6,2.2,2.7*35"
      "$GPGSV,3,1,09,01,38,103,37,02,23,215,00,04,38,297,37,05,00,328,00*70"
      "$GPGSV,3,2,09,07,77,299,47,11,07,087,00,16,74,041,47,20,38,044,43*73",
      2456, true, 35.89215, 139.64428, 0.0, 43.1, 180700,7.1
    },
};
const int numGoodData = sizeof(goodData)/sizeof(goodData[0]);

const char * badStrings[] {

};

#define nmeaOfString(s) \
    StringStream ss(s); \
    NMEA nmea(ss); \
    nmea.update(); \
    ss.reset("$"); \
    nmea.update();
    //the extra dollar sign is an artifact of the current NMEA implementation

bool parseTime(){
    for(int i=0; i<numGoodData; i++){
        nmeaOfString(goodData[i].str);
        FPASSERT(nmea.getTimeOfFix(), goodData[i].time);
    }
    return true;
}
bool parseActive(){
    for(int i=0; i<numGoodData; i++){
        nmeaOfString(goodData[i].str);
        CASSERT(nmea.getWarning(), !goodData[i].active);
    }
    return true;
}
bool parseLatitude(){
    for(int i=0; i<numGoodData; i++){
        nmeaOfString(goodData[i].str);
        FPASSERT(nmea.getLatitude(), goodData[i].latitude);
    }
    return true;
}
bool parseLongitude(){
    for(int i=0; i<numGoodData; i++){
        nmeaOfString(goodData[i].str);
        FPASSERT(nmea.getLongitude(), goodData[i].longitude);
    }
    return true;
}
bool parseSpeed(){
    for(int i=0; i<numGoodData; i++){
        nmeaOfString(goodData[i].str);
        FPASSERT(nmea.getGroundSpeed(), goodData[i].speed);
    }
    return true;
}
bool parseTrackAngle(){
    for(int i=0; i<numGoodData; i++){
        nmeaOfString(goodData[i].str);
        FPASSERT(nmea.getCourse(), goodData[i].trackAngle);
    }
    return true;
}
bool parseDate(){
    for(int i=0; i<numGoodData; i++){
        nmeaOfString(goodData[i].str);
        CASSERT(nmea.getDateOfFix(), goodData[i].date);
    }
    return true;
}
bool parseMagVar(){
    for(int i=0; i<numGoodData; i++){
        nmeaOfString(goodData[i].str);
        FPASSERT(nmea.getMagVar(), goodData[i].magVar);
    }
    return true;
}

int main(void){
    TEST(parseTime       );
    TEST(parseActive     );
    TEST(parseLatitude   );
    TEST(parseLongitude  );
    TEST(parseSpeed      );
    TEST(parseTrackAngle );
    TEST(parseDate       );
    TEST(parseMagVar     );
    return 0;
}
<|endoftext|>


<commit_before>/*
==================================================
    Filename:   text2048.cpp

 Description:   Text-based 2048 game. Please
                set your terminal to 80 x 25.

     Version:   1.0
     Created:   2014-10-02
    Revision:   none
    Compiler:   gcc

      Author:   David Amirault
==================================================
*/

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <limits>

using namespace std;

int numDigits(int i)
{
    int digits = 0;
    while (i != 0)
    {
        digits++;
        i = i / 10;
    }
    return digits;
}

void displayBoard(int board[][4], int gameState)
{
    cout << "                  _______        _     ___   ___  _  _   ___   " << endl
         << "                 |__   __|      | |   |__ \\ / _ \\| || | / _ \\  " << endl
         << "                    | | _____  _| |_     ) | | | | || || (_) | " << endl
         << "                    | |/ _ \\ \\/ / __|   / /| | | |__   _> _ <  " << endl
         << "                    | |  __/>  <| |_   / /_| |_| |  | || (_) | " << endl
         << "                    |_|\\___/_/\\_\\\\__| |____|\\___/   |_| \\___/  " << endl
         << "                      ________ ________ ________ ________" << endl;
    int spaces;
    for (int i = 0; i < 4; i++)
    {
        cout << "                     |        |        |        |        |" << endl
             << "                     |";
        for (int j = 0; j < 4; j++)
        {
            spaces = (8 - numDigits(board[i][j])) / 2;
            for (int k = 0; k < spaces; k++)
                cout << " ";
            if (board[i][j] != 0)
                cout << board[i][j];
            if (numDigits(board[i][j]) % 2 == 1)
                cout << " ";
            for (int k = 0; k < spaces; k++)
                cout << " ";
            cout << "|";
        }
        cout << "\n                     |        |        |        |        |" << endl
             << "                     |________|________|________|________|" << endl;
    }
    if (gameState == 1)
        cout << "\n                     Enter direction (w, a, s, d): ";
}

void addNum(int board[][4], int* gameState)
{
    int num = rand() % 2;
    int freeSquares = 0;
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            if (board[i][j] == 0)
                freeSquares++;
        }
    }
    if (freeSquares != 0)
    {
        int square = rand() % freeSquares;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                if (board[i][j] == 0)
                    freeSquares--;
                if (freeSquares == square)
                {
                    if (num == 0)
                        board[i][j] = 2;
                    else
                        board[i][j] = 4;
                    return;
                }
            }
        }
    }
}

void checkState(int board[][4], int* gameState)
{
    (*gameState) = 0;
    for (int  i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            if (i != 3 && board[i][j] == board[i + 1][j])
                (*gameState) = 1;
            if (j != 3 && board[i][j] == board[i][j + 1])
                (*gameState) = 1;
            if (board[i][j] == 0)
                (*gameState) = 1;
            if (board[i][j] == 2048)
            {
                (*gameState) = 2;
                break;
            }
        }
    }
}

void calculate(int board[][4], bool merge[][4], char direction, int* gameState)
{
    bool moved = false;
    if (direction == 'a' || direction == 'w')
    {
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                for (int k = 0; k < 4; k++)
                {
                    if (direction == 'a')
                    {
                        if (k != 0 && board[j][k] != 0)
                        {
                            if (board[j][k] == board[j][k - 1]
                                    && merge[j][k] == false
                                    && merge[j][k - 1] == false)
                            {
                                board[j][k - 1] *= 2;
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k - 1] = true;
                            }
                            if (board[j][k - 1] == 0)
                            {
                                board[j][k - 1] = board[j][k];
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k - 1] = merge[j][k];
                                merge[j][k] = false;
                            }
                        }
                    }
                    if (direction == 'w')
                    {
                        if (j != 0 && board[j][k] != 0)
                        {
                            if (board[j][k] == board[j - 1][k]
                                    && merge[j][k] == false
                                    && merge[j - 1][k] == false)
                            {
                                board[j - 1][k] *= 2;
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k - 1] = true;
                            }
                            if (board[j - 1][k] == 0)
                            {
                                board[j - 1][k] = board[j][k];
                                board[j][k] = 0;
                                moved = true;
                                merge[j - 1][k] = merge[j][k];
                                merge[j][k] = false;
                            }
                        }
                    }
                }
            }
        }
    }
    else
    {
        for (int i = 0; i < 4; i++)
        {
            for (int j = 3; j >= 0; j--)
            {
                for (int k = 3; k >= 0; k--)
                {
                    if (direction == 'd')
                    {
                        if (k != 3 && board[j][k] != 0)
                        {
                            if (board[j][k] == board[j][k + 1]
                                    && merge[j][k] == false
                                    && merge[j][k + 1] == false)
                            {
                                board[j][k + 1] *= 2;
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k + 1] = true;
                            }
                            if (board[j][k + 1] == 0)
                            {
                                board[j][k + 1] = board[j][k];
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k + 1] = merge[j][k];
                                merge[j][k] = false;
                            }
                        }
                    }
                    if (direction == 's')
                    {
                        if (j != 3 && board[j][k] != 0)
                        {
                            if (board[j][k] == board[j + 1][k]
                                    && merge[j][k] == false
                                    && merge[j + 1][k] == false)
                            {
                                board[j + 1][k] *= 2;
                                board[j][k] = 0;
                                moved = true;
                                merge[j + 1][k] = true;
                            }
                            if (board[j + 1][k] == 0)
                            {
                                board[j + 1][k] = board[j][k];
                                board[j][k] = 0;
                                moved = true;
                                merge[j + 1][k] = merge[j][k];
                                merge[j][k] = false;
                            }
                        }
                    }
                }
            }
        }
    }
    if (moved == true)
        addNum(board, gameState);
    checkState(board, gameState);
}

int main()
{
    srand(time(NULL));
    int board[4][4] = {0};
    bool merge[4][4] = {false};
    int gameState = 1;
    addNum(board, &gameState);
    char direction;
    while (gameState == 1)
    {
        displayBoard(board, gameState);
        cin >> direction;
        if (direction == 'w' || direction == 'a' || direction == 's' || direction == 'd')
        {
            calculate(board, merge, direction, &gameState);
            memset(merge, false, sizeof(merge[0][0]) * 4 * 4);
        }
        if (direction == 'q')
            gameState = -1;
        if (gameState == 0)
        {
            displayBoard(board, gameState);
            cout << "\n                     You lose! Better luck next time!";
        }
        if (gameState == 2)
        {
            displayBoard(board, gameState);
            cout << "\n                     You win! Thanks for playing!";
        }
    }

    cout << "\n                     Enter * to continue...";
    cin.ignore(numeric_limits<streamsize>::max(), '*');
    return 0;
}

<commit_msg>resize default terminal<commit_after>/*
==================================================
    Filename:   text2048.cpp

 Description:   Text-based 2048 game. Please
                set your terminal to 80 x 24.

     Version:   1.0
     Created:   2014-10-02
    Revision:   none
    Compiler:   gcc

      Author:   David Amirault
==================================================
*/

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <limits>

using namespace std;

int numDigits(int i)
{
    int digits = 0;
    while (i != 0)
    {
        digits++;
        i = i / 10;
    }
    return digits;
}

void displayBoard(int board[][4], int gameState)
{
    cout << "                  _______        _     ___   ___  _  _   ___   " << endl
         << "                 |__   __|      | |   |__ \\ / _ \\| || | / _ \\  " << endl
         << "                    | | _____  _| |_     ) | | | | || || (_) | " << endl
         << "                    | |/ _ \\ \\/ / __|   / /| | | |__   _> _ <  " << endl
         << "                    | |  __/>  <| |_   / /_| |_| |  | || (_) | " << endl
         << "                    |_|\\___/_/\\_\\\\__| |____|\\___/   |_| \\___/  " << endl
         << "                      ________ ________ ________ ________" << endl;
    int spaces;
    for (int i = 0; i < 4; i++)
    {
        cout << "                     |        |        |        |        |" << endl
             << "                     |";
        for (int j = 0; j < 4; j++)
        {
            spaces = (8 - numDigits(board[i][j])) / 2;
            for (int k = 0; k < spaces; k++)
                cout << " ";
            if (board[i][j] != 0)
                cout << board[i][j];
            if (numDigits(board[i][j]) % 2 == 1)
                cout << " ";
            for (int k = 0; k < spaces; k++)
                cout << " ";
            cout << "|";
        }
        cout << "\n                     |        |        |        |        |" << endl
             << "                     |________|________|________|________|" << endl;
    }
    if (gameState == 1)
        cout << "                     Enter direction (w, a, s, d): ";
}

void addNum(int board[][4], int* gameState)
{
    int num = rand() % 2;
    int freeSquares = 0;
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            if (board[i][j] == 0)
                freeSquares++;
        }
    }
    if (freeSquares != 0)
    {
        int square = rand() % freeSquares;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                if (board[i][j] == 0)
                    freeSquares--;
                if (freeSquares == square)
                {
                    if (num == 0)
                        board[i][j] = 2;
                    else
                        board[i][j] = 4;
                    return;
                }
            }
        }
    }
}

void checkState(int board[][4], int* gameState)
{
    (*gameState) = 0;
    for (int  i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            if (i != 3 && board[i][j] == board[i + 1][j])
                (*gameState) = 1;
            if (j != 3 && board[i][j] == board[i][j + 1])
                (*gameState) = 1;
            if (board[i][j] == 0)
                (*gameState) = 1;
            if (board[i][j] == 2048)
            {
                (*gameState) = 2;
                break;
            }
        }
    }
}

void calculate(int board[][4], bool merge[][4], char direction, int* gameState)
{
    bool moved = false;
    if (direction == 'a' || direction == 'w')
    {
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                for (int k = 0; k < 4; k++)
                {
                    if (direction == 'a')
                    {
                        if (k != 0 && board[j][k] != 0)
                        {
                            if (board[j][k] == board[j][k - 1]
                                    && merge[j][k] == false
                                    && merge[j][k - 1] == false)
                            {
                                board[j][k - 1] *= 2;
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k - 1] = true;
                            }
                            if (board[j][k - 1] == 0)
                            {
                                board[j][k - 1] = board[j][k];
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k - 1] = merge[j][k];
                                merge[j][k] = false;
                            }
                        }
                    }
                    if (direction == 'w')
                    {
                        if (j != 0 && board[j][k] != 0)
                        {
                            if (board[j][k] == board[j - 1][k]
                                    && merge[j][k] == false
                                    && merge[j - 1][k] == false)
                            {
                                board[j - 1][k] *= 2;
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k - 1] = true;
                            }
                            if (board[j - 1][k] == 0)
                            {
                                board[j - 1][k] = board[j][k];
                                board[j][k] = 0;
                                moved = true;
                                merge[j - 1][k] = merge[j][k];
                                merge[j][k] = false;
                            }
                        }
                    }
                }
            }
        }
    }
    else
    {
        for (int i = 0; i < 4; i++)
        {
            for (int j = 3; j >= 0; j--)
            {
                for (int k = 3; k >= 0; k--)
                {
                    if (direction == 'd')
                    {
                        if (k != 3 && board[j][k] != 0)
                        {
                            if (board[j][k] == board[j][k + 1]
                                    && merge[j][k] == false
                                    && merge[j][k + 1] == false)
                            {
                                board[j][k + 1] *= 2;
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k + 1] = true;
                            }
                            if (board[j][k + 1] == 0)
                            {
                                board[j][k + 1] = board[j][k];
                                board[j][k] = 0;
                                moved = true;
                                merge[j][k + 1] = merge[j][k];
                                merge[j][k] = false;
                            }
                        }
                    }
                    if (direction == 's')
                    {
                        if (j != 3 && board[j][k] != 0)
                        {
                            if (board[j][k] == board[j + 1][k]
                                    && merge[j][k] == false
                                    && merge[j + 1][k] == false)
                            {
                                board[j + 1][k] *= 2;
                                board[j][k] = 0;
                                moved = true;
                                merge[j + 1][k] = true;
                            }
                            if (board[j + 1][k] == 0)
                            {
                                board[j + 1][k] = board[j][k];
                                board[j][k] = 0;
                                moved = true;
                                merge[j + 1][k] = merge[j][k];
                                merge[j][k] = false;
                            }
                        }
                    }
                }
            }
        }
    }
    if (moved == true)
        addNum(board, gameState);
    checkState(board, gameState);
}

int main()
{
    srand(time(NULL));
    int board[4][4] = {0};
    bool merge[4][4] = {false};
    int gameState = 1;
    addNum(board, &gameState);
    char direction;
    while (gameState == 1)
    {
        displayBoard(board, gameState);
        cin >> direction;
        if (direction == 'w' || direction == 'a' || direction == 's' || direction == 'd')
        {
            calculate(board, merge, direction, &gameState);
            memset(merge, false, sizeof(merge[0][0]) * 4 * 4);
        }
        if (direction == 'q')
            gameState = -1;
        if (gameState == 0)
        {
            displayBoard(board, gameState);
            cout << "\n                     You lose! Better luck next time!";
        }
        if (gameState == 2)
        {
            displayBoard(board, gameState);
            cout << "\n                     You win! Thanks for playing!";
        }
    }

    cout << "\n                     Enter * to continue...";
    cin.ignore(numeric_limits<streamsize>::max(), '*');
    return 0;
}

<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */

#include "scalar_test.hpp"

namespace {

using namespace std;
using namespace proton;

using test::many;
using test::scalar_test_group;

// Inserting and extracting arrays from a container T of type U
template <class T> void sequence_test(
    type_id tid, const many<typename T::value_type>& values, const string& s)
{
    T x(values.begin(), values.end());

    value vx(x);                // construct
    ASSERT_EQUAL(tid, vx.type());
    ASSERT_EQUAL(x, get<T>(vx));
    ASSERT_EQUAL(x, coerce<T>(vx));
    {
        T y;
        get(vx, y);             // Two argument get.
        ASSERT_EQUAL(x, y);
    }
    {
        T y;
        coerce(vx, y);          // Two argument coerce.
        ASSERT_EQUAL(x, y);
    }
    value v2;                   // assign
    v2 = x;
    ASSERT_EQUAL(tid, v2.type());
    ASSERT_EQUAL(x, get<T>(v2));
    ASSERT_EQUAL(x, coerce<T>(v2));
    ASSERT_EQUAL(vx, v2);

    T y(x);
    *y.begin() = *(++y.begin()); // Second element is bigger so y is lexicographically bigger than x
    value vy(y);
    ASSERT(vx != vy);
    ASSERT(vx < vy);
    ASSERT(vy > vx);

    ASSERT_EQUAL(s, to_string(vx));
}

template <class T, class U> void map_test(const U& values, const string& s) {
    T m(values.begin(), values.end());
    value v(m);
    ASSERT_EQUAL(MAP, v.type());
    T m2(get<T>(v));
    ASSERT_EQUAL(m.size(), m2.size());
    ASSERT_EQUAL(m, m2);
    if (!s.empty())
        ASSERT_EQUAL(s, to_string(v));
}

}

int main(int, char**) {
    int failed = 0;
    scalar_test_group<value>(failed);

    // Sequence tests
    RUN_TEST(failed, sequence_test<list<bool> >(
                 ARRAY, many<bool>() + false + true, "@PN_BOOL[false, true]"));
    RUN_TEST(failed, sequence_test<vector<int> >(
                 ARRAY, many<int>() + -1 + 2, "@PN_INT[-1, 2]"));
    RUN_TEST(failed, sequence_test<deque<string> >(
                 ARRAY, many<string>() + "a" + "b", "@PN_STRING[\"a\", \"b\"]"));
    RUN_TEST(failed, sequence_test<deque<symbol> >(
                 ARRAY, many<symbol>() + "a" + "b", "@PN_SYMBOL[:a, :b]"));
    RUN_TEST(failed, sequence_test<vector<value> >(
                 LIST, many<value>() + value(0) + value("a"), "[0, \"a\"]"));
    RUN_TEST(failed, sequence_test<vector<scalar> >(
                 LIST, many<scalar>() + scalar(0) + scalar("a"), "[0, \"a\"]"));

    // // Map tests
    typedef pair<string, uint64_t> si_pair;
    many<si_pair> si_pairs;
    si_pairs << si_pair("a", 0) << si_pair("b", 1) << si_pair("c", 2);

    RUN_TEST(failed, (map_test<map<string, uint64_t> >(
                          si_pairs, "{\"a\"=0, \"b\"=1, \"c\"=2}")));
    RUN_TEST(failed, (map_test<vector<si_pair> >(
                          si_pairs, "{\"a\"=0, \"b\"=1, \"c\"=2}")));

    many<std::pair<value,value> > value_pairs(si_pairs);
    RUN_TEST(failed, (map_test<map<value, value> >(
                          value_pairs, "{\"a\"=0, \"b\"=1, \"c\"=2}")));

    many<pair<scalar,scalar> > scalar_pairs(si_pairs);
    RUN_TEST(failed, (map_test<map<scalar, scalar> >(
                          scalar_pairs, "{\"a\"=0, \"b\"=1, \"c\"=2}")));

    annotation_key ak(si_pairs[0].first);
    pair<annotation_key, message_id> p(si_pairs[0]);
    many<pair<annotation_key, message_id> > restricted_pairs(si_pairs);
    RUN_TEST(failed, (map_test<map<annotation_key, message_id> >(
                          restricted_pairs, "{:a=0, :b=1, :c=2}")));

#if PN_CPP_HAS_CPP11
    RUN_TEST(failed, sequence_test<forward_list<binary> >(
                 ARRAY, many<binary>() + binary("xx") + binary("yy"), "@PN_BINARY[b\"xx\", b\"yy\"]"));
    RUN_TEST(failed, (map_test<unordered_map<string, uint64_t> >(si_pairs, "")));
#endif
    return failed;
}
<commit_msg>PROTON-1312: c++ Sunstudio does not compile "++vector.begin()"<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */

#include "scalar_test.hpp"

namespace {

using namespace std;
using namespace proton;

using test::many;
using test::scalar_test_group;

// Inserting and extracting arrays from a container T of type U
template <class T> void sequence_test(
    type_id tid, const many<typename T::value_type>& values, const string& s)
{
    T x(values.begin(), values.end());

    value vx(x);                // construct
    ASSERT_EQUAL(tid, vx.type());
    ASSERT_EQUAL(x, get<T>(vx));
    ASSERT_EQUAL(x, coerce<T>(vx));
    {
        T y;
        get(vx, y);             // Two argument get.
        ASSERT_EQUAL(x, y);
    }
    {
        T y;
        coerce(vx, y);          // Two argument coerce.
        ASSERT_EQUAL(x, y);
    }
    value v2;                   // assign
    v2 = x;
    ASSERT_EQUAL(tid, v2.type());
    ASSERT_EQUAL(x, get<T>(v2));
    ASSERT_EQUAL(x, coerce<T>(v2));
    ASSERT_EQUAL(vx, v2);

    T y(x);
    typename T::iterator it = y.begin();
    *y.begin() = *(++it); // Second element is bigger so y is lexicographically bigger than x
    value vy(y);
    ASSERT(vx != vy);
    ASSERT(vx < vy);
    ASSERT(vy > vx);

    ASSERT_EQUAL(s, to_string(vx));
}

template <class T, class U> void map_test(const U& values, const string& s) {
    T m(values.begin(), values.end());
    value v(m);
    ASSERT_EQUAL(MAP, v.type());
    T m2(get<T>(v));
    ASSERT_EQUAL(m.size(), m2.size());
    ASSERT_EQUAL(m, m2);
    if (!s.empty())
        ASSERT_EQUAL(s, to_string(v));
}

}

int main(int, char**) {
    int failed = 0;
    scalar_test_group<value>(failed);

    // Sequence tests
    RUN_TEST(failed, sequence_test<list<bool> >(
                 ARRAY, many<bool>() + false + true, "@PN_BOOL[false, true]"));
    RUN_TEST(failed, sequence_test<vector<int> >(
                 ARRAY, many<int>() + -1 + 2, "@PN_INT[-1, 2]"));
    RUN_TEST(failed, sequence_test<deque<string> >(
                 ARRAY, many<string>() + "a" + "b", "@PN_STRING[\"a\", \"b\"]"));
    RUN_TEST(failed, sequence_test<deque<symbol> >(
                 ARRAY, many<symbol>() + "a" + "b", "@PN_SYMBOL[:a, :b]"));
    RUN_TEST(failed, sequence_test<vector<value> >(
                 LIST, many<value>() + value(0) + value("a"), "[0, \"a\"]"));
    RUN_TEST(failed, sequence_test<vector<scalar> >(
                 LIST, many<scalar>() + scalar(0) + scalar("a"), "[0, \"a\"]"));

    // // Map tests
    typedef pair<string, uint64_t> si_pair;
    many<si_pair> si_pairs;
    si_pairs << si_pair("a", 0) << si_pair("b", 1) << si_pair("c", 2);

    RUN_TEST(failed, (map_test<map<string, uint64_t> >(
                          si_pairs, "{\"a\"=0, \"b\"=1, \"c\"=2}")));
    RUN_TEST(failed, (map_test<vector<si_pair> >(
                          si_pairs, "{\"a\"=0, \"b\"=1, \"c\"=2}")));

    many<std::pair<value,value> > value_pairs(si_pairs);
    RUN_TEST(failed, (map_test<map<value, value> >(
                          value_pairs, "{\"a\"=0, \"b\"=1, \"c\"=2}")));

    many<pair<scalar,scalar> > scalar_pairs(si_pairs);
    RUN_TEST(failed, (map_test<map<scalar, scalar> >(
                          scalar_pairs, "{\"a\"=0, \"b\"=1, \"c\"=2}")));

    annotation_key ak(si_pairs[0].first);
    pair<annotation_key, message_id> p(si_pairs[0]);
    many<pair<annotation_key, message_id> > restricted_pairs(si_pairs);
    RUN_TEST(failed, (map_test<map<annotation_key, message_id> >(
                          restricted_pairs, "{:a=0, :b=1, :c=2}")));

#if PN_CPP_HAS_CPP11
    RUN_TEST(failed, sequence_test<forward_list<binary> >(
                 ARRAY, many<binary>() + binary("xx") + binary("yy"), "@PN_BINARY[b\"xx\", b\"yy\"]"));
    RUN_TEST(failed, (map_test<unordered_map<string, uint64_t> >(si_pairs, "")));
#endif
    return failed;
}
<|endoftext|>


<commit_before>AliCentralitySelectionTask *AddTaskCentrality()
{
// Macro to connect a centrality selection task to an existing analysis manager.
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskCentrality", "No analysis manager to connect to.");
    return NULL;
  }
  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskCentrality", "This task requires an input event handler");
    return NULL;
  }
  TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  if (inputDataType != "ESD") {
    ::Error("AddTaskCentrality", "This task works only on ESD analysis");
    return NULL;
  }
  AliCentralitySelectionTask *centralityTask = new AliCentralitySelectionTask("CentralitySelection");
  centralityTask->SelectCollisionCandidates(AliVEvent::kMB);
  mgr->AddTask(centralityTask);

  AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("CentralityStat",
                TList::Class(), AliAnalysisManager::kOutputContainer,
                "Centrality_temp.root");

  mgr->ConnectInput(centralityTask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(centralityTask,1,coutput1);

  return centralityTask;
}
<commit_msg>reverting previous commit<commit_after>AliCentralitySelectionTask *AddTaskCentrality()
{
// Macro to connect a centrality selection task to an existing analysis manager.
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskCentrality", "No analysis manager to connect to.");
    return NULL;
  }
  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskCentrality", "This task requires an input event handler");
    return NULL;
  }
  TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  if (inputDataType != "ESD") {
    ::Error("AddTaskCentrality", "This task works only on ESD analysis");
    return NULL;
  }
  AliCentralitySelectionTask *centralityTask = new AliCentralitySelectionTask("CentralitySelection");
  centralityTask->SelectCollisionCandidates(AliVEvent::kMB);
  mgr->AddTask(centralityTask);

  AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("CentralityStat",
                TList::Class(), AliAnalysisManager::kOutputContainer,
                "EventStat_temp.root");

  mgr->ConnectInput(centralityTask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(centralityTask,1,coutput1);

  return centralityTask;
}
<|endoftext|>


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

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <timedata.h>

#include <netaddress.h>
#include <sync.h>
#include <ui_interface.h>
#include <util/system.h>
#include <util/translation.h>
#include <warnings.h>

static RecursiveMutex cs_nTimeOffset;
static int64_t nTimeOffset GUARDED_BY(cs_nTimeOffset) = 0;

/**
 * "Never go to sea with two chronometers; take one or three."
 * Our three time sources are:
 *  - System clock
 *  - Median of other nodes clocks
 *  - The user (asking the user to fix the system clock if the first two disagree)
 */
int64_t GetTimeOffset()
{
    LOCK(cs_nTimeOffset);
    return nTimeOffset;
}

int64_t GetAdjustedTime()
{
    return GetTime() + GetTimeOffset();
}

static int64_t abs64(int64_t n)
{
    return (n >= 0 ? n : -n);
}

#define BITCOIN_TIMEDATA_MAX_SAMPLES 200

void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
    LOCK(cs_nTimeOffset);
    // Ignore duplicates
    static std::set<CNetAddr> setKnown;
    if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)
        return;
    if (!setKnown.insert(ip).second)
        return;

    // Add data
    static CMedianFilter<int64_t> vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);
    vTimeOffsets.input(nOffsetSample);
    LogPrint(BCLog::NET,"added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);

    // There is a known issue here (see issue #4521):
    //
    // - The structure vTimeOffsets contains up to 200 elements, after which
    // any new element added to it will not increase its size, replacing the
    // oldest element.
    //
    // - The condition to update nTimeOffset includes checking whether the
    // number of elements in vTimeOffsets is odd, which will never happen after
    // there are 200 elements.
    //
    // But in this case the 'bug' is protective against some attacks, and may
    // actually explain why we've never seen attacks which manipulate the
    // clock offset.
    //
    // So we should hold off on fixing this and clean it up as part of
    // a timing cleanup that strengthens it in a number of other ways.
    //
    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
    {
        int64_t nMedian = vTimeOffsets.median();
        std::vector<int64_t> vSorted = vTimeOffsets.sorted();
        // Only let other nodes change our time by so much
        if (abs64(nMedian) <= std::max<int64_t>(0, gArgs.GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT)))
        {
            nTimeOffset = nMedian;
        }
        else
        {
            nTimeOffset = 0;

            static bool fDone;
            if (!fDone)
            {
                // If nobody has a time different than ours but within 5 minutes of ours, give a warning
                bool fMatch = false;
                for (const int64_t nOffset : vSorted)
                    if (nOffset != 0 && abs64(nOffset) < 5 * 60)
                        fMatch = true;

                if (!fMatch)
                {
                    fDone = true;
                    std::string strMessage = strprintf(_("Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.").translated, PACKAGE_NAME);
                    SetMiscWarning(strMessage);
                    uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
                }
            }
        }

        if (LogAcceptCategory(BCLog::NET)) {
            for (const int64_t n : vSorted) {
                LogPrint(BCLog::NET, "%+d  ", n); /* Continued */
            }
            LogPrint(BCLog::NET, "|  "); /* Continued */

            LogPrint(BCLog::NET, "nTimeOffset = %+d  (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
        }
    }
}
<commit_msg>Avoid the use of abs64 in timedata<commit_after>// Copyright (c) 2014-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <timedata.h>

#include <netaddress.h>
#include <sync.h>
#include <ui_interface.h>
#include <util/system.h>
#include <util/translation.h>
#include <warnings.h>

static RecursiveMutex cs_nTimeOffset;
static int64_t nTimeOffset GUARDED_BY(cs_nTimeOffset) = 0;

/**
 * "Never go to sea with two chronometers; take one or three."
 * Our three time sources are:
 *  - System clock
 *  - Median of other nodes clocks
 *  - The user (asking the user to fix the system clock if the first two disagree)
 */
int64_t GetTimeOffset()
{
    LOCK(cs_nTimeOffset);
    return nTimeOffset;
}

int64_t GetAdjustedTime()
{
    return GetTime() + GetTimeOffset();
}

#define BITCOIN_TIMEDATA_MAX_SAMPLES 200

void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
    LOCK(cs_nTimeOffset);
    // Ignore duplicates
    static std::set<CNetAddr> setKnown;
    if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)
        return;
    if (!setKnown.insert(ip).second)
        return;

    // Add data
    static CMedianFilter<int64_t> vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);
    vTimeOffsets.input(nOffsetSample);
    LogPrint(BCLog::NET,"added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);

    // There is a known issue here (see issue #4521):
    //
    // - The structure vTimeOffsets contains up to 200 elements, after which
    // any new element added to it will not increase its size, replacing the
    // oldest element.
    //
    // - The condition to update nTimeOffset includes checking whether the
    // number of elements in vTimeOffsets is odd, which will never happen after
    // there are 200 elements.
    //
    // But in this case the 'bug' is protective against some attacks, and may
    // actually explain why we've never seen attacks which manipulate the
    // clock offset.
    //
    // So we should hold off on fixing this and clean it up as part of
    // a timing cleanup that strengthens it in a number of other ways.
    //
    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
    {
        int64_t nMedian = vTimeOffsets.median();
        std::vector<int64_t> vSorted = vTimeOffsets.sorted();
        // Only let other nodes change our time by so much
        int64_t max_adjustment = std::max<int64_t>(0, gArgs.GetArg("-maxtimeadjustment", DEFAULT_MAX_TIME_ADJUSTMENT));
        if (nMedian >= -max_adjustment && nMedian <= max_adjustment) {
            nTimeOffset = nMedian;
        }
        else
        {
            nTimeOffset = 0;

            static bool fDone;
            if (!fDone)
            {
                // If nobody has a time different than ours but within 5 minutes of ours, give a warning
                bool fMatch = false;
                for (const int64_t nOffset : vSorted) {
                    if (nOffset != 0 && nOffset > -5 * 60 && nOffset < 5 * 60)
                        fMatch = true;
                }

                if (!fMatch)
                {
                    fDone = true;
                    std::string strMessage = strprintf(_("Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.").translated, PACKAGE_NAME);
                    SetMiscWarning(strMessage);
                    uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
                }
            }
        }

        if (LogAcceptCategory(BCLog::NET)) {
            for (const int64_t n : vSorted) {
                LogPrint(BCLog::NET, "%+d  ", n); /* Continued */
            }
            LogPrint(BCLog::NET, "|  "); /* Continued */

            LogPrint(BCLog::NET, "nTimeOffset = %+d  (%+d minutes)\n", nTimeOffset, nTimeOffset/60);
        }
    }
}
<|endoftext|>


<commit_before>/*
   Copyright 2008 Brain Research Institute, Melbourne, Australia

   Written by J-Donald Tournier, 27/06/08.

   This file is part of MRtrix.

   MRtrix is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   MRtrix is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "app.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "image/threaded_loop.h"
#include "image/adapter/extract.h"
#include "dwi/gradient.h"
#include "math/matrix.h"
#include "math/least_squares.h"
#include "math/SH.h"

#include "dwi/noise_estimator.h"

using namespace MR;
using namespace App;

MRTRIX_APPLICATION

void usage ()
{
  DESCRIPTION
  + "estimate noise level voxel-wise using residuals from a truncated SH fit";

  ARGUMENTS
  + Argument ("dwi",
              "the input diffusion-weighted image.")
  .type_image_in ()

  + Argument ("noise",
              "the output noise map")
  .type_image_out ();

  OPTIONS
  + Option ("lmax",
            "set the maximum harmonic order for the output series. By default, the "
            "program will use the highest possible lmax given the number of "
            "diffusion-weighted images up to lmax = 8.")
  +   Argument ("order").type_integer (0, 8, 8)

  + DWI::GradOption;

}

typedef float value_type;

void run ()
{
  Image::Buffer<value_type> dwi_buffer (argument[0]);
  DWI::NoiseEstimator estimator (dwi_buffer);

  Image::Header header (dwi_buffer);
  header.info() =  estimator.info();
  header.datatype() = DataType::Float32;
  Image::Buffer<value_type> noise_buffer (argument[1], header);

  std::vector<int> dwis, bzeros;
  DWI::guess_DW_directions (dwis, bzeros, dwi_buffer.DW_scheme());
  Math::Matrix<value_type> mapping = DWI::get_SH2amp_mapping<value_type> (dwi_buffer);

  Image::Buffer<value_type>::voxel_type dwi_voxel (dwi_buffer);
  Image::Adapter::Extract1D<Image::Buffer<value_type>::voxel_type> dwi (dwi_voxel, 3, dwis);
  Image::Buffer<value_type>::voxel_type noise (noise_buffer);

  VAR (dwi.info());

  estimator (dwi, noise, mapping);
}

<commit_msg>update to reflect changes in core related to version handling<commit_after>/*
   Copyright 2008 Brain Research Institute, Melbourne, Australia

   Written by J-Donald Tournier, 27/06/08.

   This file is part of MRtrix.

   MRtrix is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   MRtrix is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "command.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "image/threaded_loop.h"
#include "image/adapter/extract.h"
#include "dwi/gradient.h"
#include "math/matrix.h"
#include "math/least_squares.h"
#include "math/SH.h"

#include "dwi/noise_estimator.h"

using namespace MR;
using namespace App;

void usage ()
{
  DESCRIPTION
  + "estimate noise level voxel-wise using residuals from a truncated SH fit";

  ARGUMENTS
  + Argument ("dwi",
              "the input diffusion-weighted image.")
  .type_image_in ()

  + Argument ("noise",
              "the output noise map")
  .type_image_out ();

  OPTIONS
  + Option ("lmax",
            "set the maximum harmonic order for the output series. By default, the "
            "program will use the highest possible lmax given the number of "
            "diffusion-weighted images up to lmax = 8.")
  +   Argument ("order").type_integer (0, 8, 8)

  + DWI::GradOption;

}

typedef float value_type;

void run ()
{
  Image::Buffer<value_type> dwi_buffer (argument[0]);
  DWI::NoiseEstimator estimator (dwi_buffer);

  Image::Header header (dwi_buffer);
  header.info() =  estimator.info();
  header.datatype() = DataType::Float32;
  Image::Buffer<value_type> noise_buffer (argument[1], header);

  std::vector<int> dwis, bzeros;
  DWI::guess_DW_directions (dwis, bzeros, dwi_buffer.DW_scheme());
  Math::Matrix<value_type> mapping = DWI::get_SH2amp_mapping<value_type> (dwi_buffer);

  Image::Buffer<value_type>::voxel_type dwi_voxel (dwi_buffer);
  Image::Adapter::Extract1D<Image::Buffer<value_type>::voxel_type> dwi (dwi_voxel, 3, dwis);
  Image::Buffer<value_type>::voxel_type noise (noise_buffer);

  VAR (dwi.info());

  estimator (dwi, noise, mapping);
}

<|endoftext|>


<commit_before>/*
    Copyright (C) 2001 by Christopher Nelson

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/sysfunc.h"
#include "csutil/cscolor.h"
#include "csutil/csevent.h"
#include "cstool/csfxscr.h"
#include "cstool/csview.h"
#include "cstool/initapp.h"
#include "csutil/cmdhelp.h"
#include "ivideo/graph3d.h"
#include "ivideo/fontserv.h"
#include "ivideo/graph2d.h"
#include "ivideo/natwin.h"
#include "ivaria/conout.h"
#include "iengine/engine.h"
#include "iengine/sector.h"
#include "iengine/light.h"
#include "iengine/camera.h"
#include "iengine/mesh.h"
#include "iengine/movable.h"
#include "iengine/halo.h"
#include "imesh/thing.h"
#include "imesh/particle.h"
#include "imesh/sprite2d.h"
#include "imesh/sprite3d.h"
#include "imesh/ball.h"
#include "imesh/object.h"
#include "imap/reader.h"
#include "igraphic/imageio.h"
#include "imap/loader.h"
#include "iengine/material.h"
#include "ivaria/reporter.h"
#include "iutil/eventq.h"
#include "iutil/virtclk.h"
#include "iutil/plugin.h"
#include "iutil/vfs.h"
#include "csqsqrt.h"

#include "csgeom/csrect.h"
#include "csgeom/csrectrg.h"

#include "awstest.h"
#include "awssktst.h"
#include <stdio.h>

#include "cuscomp.h"

const int AWSTEST_MULTIPROC  = 0;
const int AWSTEST_SINGLEPROC = 1;
const int AWSTEST_SCREEN     = 2;

const int AWSTEST_CANVAS=AWSTEST_SCREEN;
// @@@@@ engine view as window background doesn't work with the proctex canvases
// @@@@@ yes it does! it just doesn't update right.
//-----------------------------------------------------------------------------

#define  QUERY_REG(myPlug, iFace, errMsg) \
  myPlug = CS_QUERY_REGISTRY (object_reg, iFace); \
  if (!myPlug) \
  { \
    Report (CS_REPORTER_SEVERITY_ERROR, errMsg); \
    return false; \
  }

extern awsTest *System;

awsTest::awsTest()
{
}

awsTest::~awsTest()
{
}

static bool AwsEventHandler (iEvent& ev)
{
  if (ev.Type == csevBroadcast && ev.Command.Code == cscmdProcess)
  {
    System->SetupFrame ();
    return true;
  }
  else if (ev.Type == csevBroadcast && ev.Command.Code == cscmdFinalProcess)
  {
    System->FinishFrame ();
    return true;
  }
  else
  {
    return System ? System->HandleEvent (ev) : false;
  }
}

bool
awsTest::Initialize(int argc, const char* const argv[], const char *iConfigName)
{
  object_reg = csInitializer::CreateEnvironment (argc, argv);
  if (!object_reg) return false;

  if (!csInitializer::SetupConfigManager (object_reg, iConfigName))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not init app!");
    return false;
  }

  if (!csInitializer::RequestPlugins (object_reg, CS_REQUEST_END))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not init app!");
    return false;
  }

  if (!csInitializer::SetupEventHandler (object_reg, AwsEventHandler))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not setup event handler!");
    return false;
  }

  // Check for commandline help.
  if (csCommandLineHelper::CheckHelp (object_reg))
  {
    csCommandLineHelper::Help (object_reg);
    exit (0);
  }

  // The virtual clock.
  vc = CS_QUERY_REGISTRY (object_reg, iVirtualClock);
  csRef<iPluginManager> plugin_mgr (
  	CS_QUERY_REGISTRY (object_reg, iPluginManager));

  // Load the engine plugin.
  Report (CS_REPORTER_SEVERITY_NOTIFY, "Loading engine...");
  engine = CS_LOAD_PLUGIN(plugin_mgr, "crystalspace.engine.3d", iEngine);
  if (!engine)
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not load the engine plugin!");
    return false;
  }
  if (!object_reg->Register (engine, "iEngine"))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not register engine!");
    return false;
  }

  QUERY_REG (myG3D, iGraphics3D, "Couldn't load iGraphics3D plugin!");
  QUERY_REG (myG2D, iGraphics2D, "Couldn't load  iGraphics2D plugin!");
  QUERY_REG (myVFS, iVFS, "Couldn't load  iVFS plugin!");
  QUERY_REG (myConsole, iConsoleOutput, "Couldn't load iConsoleOutput plugin!");

  // Load AWS
  Report(CS_REPORTER_SEVERITY_NOTIFY, "Loading AWS...");
  aws = CS_LOAD_PLUGIN(plugin_mgr,
  	"crystalspace.window.alternatemanager", iAws);

  if (!aws)
  {
    Report(CS_REPORTER_SEVERITY_ERROR, "Could not load the AWS plugin!");
    return false;
  }

  loader = CS_LOAD_PLUGIN(plugin_mgr, "crystalspace.level.loader", iLoader);
  if (!loader)
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "No iLoader plugin!");
    return false;
  }
  if (!object_reg->Register (loader, "iLoader"))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not register loader!");
    return false;
  }

  // Open the main system. This will open all the previously loaded plug-ins.
  iNativeWindow* nw = myG2D->GetNativeWindow ();
  if (nw) nw->SetTitle ("AWS Test Harness");

  if (!csInitializer::OpenApplication (object_reg))
  {
    Report(CS_REPORTER_SEVERITY_ERROR, "Error opening system!");
    return false;
  }

  font = myG2D->GetFontServer()->LoadFont (CSFONT_LARGE);

  // Initialize the console
  if (myConsole != 0)
    // Don't let messages before this one appear
    myConsole->Clear ();

  // Some commercials...
  Report (CS_REPORTER_SEVERITY_NOTIFY,
    "The Alternate Window System Test Harness.");

  // First disable the lighting cache. Our app is simple enough
  // not to need this.
  engine->SetLightingCacheMode (0);

  // Create our world.
  Report (CS_REPORTER_SEVERITY_NOTIFY, "Creating world!...");

  if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif"))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Error loading 'stone4' texture!");
    exit (1);
  }
  iMaterialWrapper* tm = engine->GetMaterialList ()->FindByName ("stone");

  room = engine->CreateSector ("room");
  csRef<iMeshWrapper> walls (engine->CreateSectorWallsMesh (room, "walls"));
  csRef<iThingState> ws =
  	SCF_QUERY_INTERFACE (walls->GetMeshObject (), iThingState);
  csRef<iThingFactoryState> walls_state = ws->GetFactory ();
  walls_state->AddInsideBox (csVector3 (-5, 0, -5), csVector3 (5, 20, 5));
  walls_state->SetPolygonMaterial (CS_POLYRANGE_LAST, tm);
  walls_state->SetPolygonTextureMapping (CS_POLYRANGE_LAST, 3);

  csRef<iLight> light;
  iLightList* ll = room->GetLights ();
  light = engine->CreateLight (0, csVector3 (-3, 5, 0), 10,
  	csColor (1, 0, 0));
  ll->Add (light);

  light = engine->CreateLight (0, csVector3 (3, 5,  0), 10,
  	csColor (0, 0, 1));
  ll->Add (light);

  light = engine->CreateLight (0, csVector3 (0, 5, -3), 10,
  	csColor (0, 1, 0));
  ll->Add (light);

  engine->Prepare ();

  Report(CS_REPORTER_SEVERITY_NOTIFY, "--------------------------------------");

  view = csPtr<iView> (new csView (engine, myG3D));
  view->GetCamera ()->SetSector (room);
  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));
  view->SetRectangle (0, 0, myG2D->GetWidth (), myG2D->GetHeight ());

  wview = csPtr<iView> (new csView (engine, myG3D));
  wview->GetCamera ()->SetSector (room);
  wview->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));

  col_red = myG2D->FindRGB (255, 0, 0);
  col_blue = myG2D->FindRGB (0, 0, 255);
  col_white = myG2D->FindRGB (255, 255, 255);
  col_gray = myG2D->FindRGB (50, 50, 50);
  col_black = myG2D->FindRGB (0, 0, 0);
  col_yellow = myG2D->FindRGB (255, 255, 0);
  col_cyan = myG2D->FindRGB (0, 255, 255);
  col_green = myG2D->FindRGB (0, 255, 0);

/*  if (AWSTEST_CANVAS == AWSTEST_SINGLEPROC)
  {
    awsCanvas = aws->CreateDefaultCanvas(engine, myG3D->GetTextureManager(), 512, 512, 0);
    //aws->SetFlag(AWSF_AlwaysEraseWindows);  // Only set for surface or direct-drawing w/o engine
  }
  else if (AWSTEST_CANVAS == AWSTEST_MULTIPROC)
  {
    awsCanvas = aws->CreateDefaultCanvas(engine, myG3D->GetTextureManager());
  }
  else
  {
    awsCanvas = aws->CreateCustomCanvas(myG2D, myG3D);
    aws->SetFlag(AWSF_AlwaysRedrawWindows);     // Only set for direct-drawing with engine
  }*/

  aws->SetupCanvas(0, myG2D, myG3D);

  // next, setup sinks before loading any preferences
  awsTestSink *s = new awsTestSink();
  iAwsSink *sink =aws->GetSinkMgr()->CreateSink((intptr_t)s);

  s->SetSink(sink);
  s->SetWindowManager(aws);

  aws->GetSinkMgr()->RegisterSink("testButtonSink", sink);

  // make the manager aware of our custom component
  // the contructor automatically registers so we only need to create it
  (void) new CustomComponentFactory(aws);

  // now load preferences
  if (!aws->GetPrefMgr()->Load("/aws/awstest.def"))
      Report(CS_REPORTER_SEVERITY_ERROR, "couldn't load definition file!");
  aws->GetPrefMgr()->SelectDefaultSkin("Normal Windows");

  csPrintf("aws-debug: Creating splash window...\n");
  iAwsWindow *test = aws->CreateWindowFrom("Splash");
  iAwsWindow *test2 = aws->CreateWindowFrom("Another");
  iAwsWindow *test3 = aws->CreateWindowFrom("Engine View");
  iAwsWindow *test4 = aws->CreateWindowFrom("Layout Test");
  iAwsWindow *test5 = aws->CreateWindowFrom("Form1");

  if(test3)
  {
    iAwsComponent* engine_view = test3->FindChild("Engine View");
    if(engine_view)
      engine_view->SetProperty("view", (intptr_t)(iView*)wview);
  }

  if (test)  test->Show();
  if (test3) test3->Show();
  if (test4) test4->Show();
  if (test5) test5->Show();

  if (test2) test2->Show();
  //s->SetTestWin(test2);

  /////////

  Report(CS_REPORTER_SEVERITY_NOTIFY, "Init done.");

  return true;
}

void
awsTest::SetupFrame()
{
  static int counter=0;

  iCamera* c = view->GetCamera();
  iCamera* c2 = wview->GetCamera();

  counter++;

  // First get elapsed time from the system driver.
  csTicks elapsed_time, current_time;
  elapsed_time = vc->GetElapsedTicks ();
  current_time = vc->GetCurrentTicks ();

  // Now rotate the camera according to keyboard state
  float speed = (elapsed_time / 1000.0f) * (0.03f * 2);

  c->GetTransform ().RotateThis (CS_VEC_ROT_RIGHT, speed);
  c2->GetTransform ().RotateThis (CS_VEC_ROT_LEFT, speed);

  // Tell 3D driver we're going to display 3D things.
  if (!myG3D->BeginDraw (
      engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS))
      return;

  // Tell the camera to render into the frame buffer.
  view->Draw ();
  wview->Draw();

  // Start drawing 2D graphics.
  if (!myG3D->BeginDraw (CSDRAW_2DGRAPHICS)) return;

  message.Format ("awsTest(%d)", counter);
  myG2D->Write(font, 5, 5, col_green, -1, message);

  aws->Redraw();
  aws->Print(myG3D, 64);
  /*if (AWSTEST_SINGLEPROCTEXCANVAS)
  {
    csRef<iTextureWrapper> tex (SCF_QUERY_INTERFACE(awsCanvas, iTextureWrapper));
    if (tex)
    {
      myG3D->DrawPixmap(tex->GetTextureHandle(),
                    0,0,512,512,
                    0,0,512,512,
                    0);
    }
  }*/
}

void
awsTest::FinishFrame ()
{
  myG3D->FinishDraw ();
  myG3D->Print (0);
}

bool
awsTest::HandleEvent (iEvent &Event)
{
  if ((Event.Type == csevKeyboard) &&
    (csKeyEventHelper::GetEventType (&Event) == csKeyEventTypeDown) &&
    (csKeyEventHelper::GetCookedCode (&Event) == CSKEY_ESC))
  {
    csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
    if (q)
      q->GetEventOutlet()->Broadcast (cscmdQuit);
    return true;
  }

  return aws->HandleEvent(Event);
}

void
awsTest::Report (int severity, const char* msg, ...)
{
  va_list arg;
  va_start (arg, msg);
  csRef<iReporter> rep (CS_QUERY_REGISTRY (object_reg, iReporter));
  if (rep)
    rep->ReportV (severity, "crystalspace.application.awstest", msg, arg);
  else
  {
    csPrintfV (msg, arg);
    csPrintf ("\n");
  }
  va_end (arg);
}

<commit_msg>Added a script execution test to awstest to make sure that the automation is working properly.<commit_after>/*
    Copyright (C) 2001 by Christopher Nelson

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/sysfunc.h"
#include "csutil/cscolor.h"
#include "csutil/csevent.h"
#include "cstool/csfxscr.h"
#include "cstool/csview.h"
#include "cstool/initapp.h"
#include "csutil/cmdhelp.h"
#include "ivideo/graph3d.h"
#include "ivideo/fontserv.h"
#include "ivideo/graph2d.h"
#include "ivideo/natwin.h"
#include "ivaria/conout.h"
#include "iengine/engine.h"
#include "iengine/sector.h"
#include "iengine/light.h"
#include "iengine/camera.h"
#include "iengine/mesh.h"
#include "iengine/movable.h"
#include "iengine/halo.h"
#include "imesh/thing.h"
#include "imesh/particle.h"
#include "imesh/sprite2d.h"
#include "imesh/sprite3d.h"
#include "imesh/ball.h"
#include "imesh/object.h"
#include "imap/reader.h"
#include "igraphic/imageio.h"
#include "imap/loader.h"
#include "iengine/material.h"
#include "ivaria/reporter.h"
#include "iutil/eventq.h"
#include "iutil/virtclk.h"
#include "iutil/plugin.h"
#include "iutil/vfs.h"
#include "csqsqrt.h"

#include "csgeom/csrect.h"
#include "csgeom/csrectrg.h"

#include "awstest.h"
#include "awssktst.h"
#include <stdio.h>

#include "cuscomp.h"

const int AWSTEST_MULTIPROC  = 0;
const int AWSTEST_SINGLEPROC = 1;
const int AWSTEST_SCREEN     = 2;

const int AWSTEST_CANVAS=AWSTEST_SCREEN;
// @@@@@ engine view as window background doesn't work with the proctex canvases
// @@@@@ yes it does! it just doesn't update right.
//-----------------------------------------------------------------------------

#define  QUERY_REG(myPlug, iFace, errMsg) \
  myPlug = CS_QUERY_REGISTRY (object_reg, iFace); \
  if (!myPlug) \
  { \
    Report (CS_REPORTER_SEVERITY_ERROR, errMsg); \
    return false; \
  }

extern awsTest *System;

awsTest::awsTest()
{
}

awsTest::~awsTest()
{
}

static bool AwsEventHandler (iEvent& ev)
{
  if (ev.Type == csevBroadcast && ev.Command.Code == cscmdProcess)
  {
    System->SetupFrame ();
    return true;
  }
  else if (ev.Type == csevBroadcast && ev.Command.Code == cscmdFinalProcess)
  {
    System->FinishFrame ();
    return true;
  }
  else
  {
    return System ? System->HandleEvent (ev) : false;
  }
}

bool
awsTest::Initialize(int argc, const char* const argv[], const char *iConfigName)
{
  object_reg = csInitializer::CreateEnvironment (argc, argv);
  if (!object_reg) return false;

  if (!csInitializer::SetupConfigManager (object_reg, iConfigName))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not init app!");
    return false;
  }

  if (!csInitializer::RequestPlugins (object_reg, CS_REQUEST_END))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not init app!");
    return false;
  }

  if (!csInitializer::SetupEventHandler (object_reg, AwsEventHandler))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not setup event handler!");
    return false;
  }

  // Check for commandline help.
  if (csCommandLineHelper::CheckHelp (object_reg))
  {
    csCommandLineHelper::Help (object_reg);
    exit (0);
  }

  // The virtual clock.
  vc = CS_QUERY_REGISTRY (object_reg, iVirtualClock);
  csRef<iPluginManager> plugin_mgr (
  	CS_QUERY_REGISTRY (object_reg, iPluginManager));

  // Load the engine plugin.
  Report (CS_REPORTER_SEVERITY_NOTIFY, "Loading engine...");
  engine = CS_LOAD_PLUGIN(plugin_mgr, "crystalspace.engine.3d", iEngine);
  if (!engine)
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not load the engine plugin!");
    return false;
  }
  if (!object_reg->Register (engine, "iEngine"))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not register engine!");
    return false;
  }

  QUERY_REG (myG3D, iGraphics3D, "Couldn't load iGraphics3D plugin!");
  QUERY_REG (myG2D, iGraphics2D, "Couldn't load  iGraphics2D plugin!");
  QUERY_REG (myVFS, iVFS, "Couldn't load  iVFS plugin!");
  QUERY_REG (myConsole, iConsoleOutput, "Couldn't load iConsoleOutput plugin!");

  // Load AWS
  Report(CS_REPORTER_SEVERITY_NOTIFY, "Loading AWS...");
  aws = CS_LOAD_PLUGIN(plugin_mgr,
  	"crystalspace.window.alternatemanager", iAws);

  if (!aws)
  {
    Report(CS_REPORTER_SEVERITY_ERROR, "Could not load the AWS plugin!");
    return false;
  }

  loader = CS_LOAD_PLUGIN(plugin_mgr, "crystalspace.level.loader", iLoader);
  if (!loader)
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "No iLoader plugin!");
    return false;
  }
  if (!object_reg->Register (loader, "iLoader"))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Could not register loader!");
    return false;
  }

  // Open the main system. This will open all the previously loaded plug-ins.
  iNativeWindow* nw = myG2D->GetNativeWindow ();
  if (nw) nw->SetTitle ("AWS Test Harness");

  if (!csInitializer::OpenApplication (object_reg))
  {
    Report(CS_REPORTER_SEVERITY_ERROR, "Error opening system!");
    return false;
  }

  font = myG2D->GetFontServer()->LoadFont (CSFONT_LARGE);

  // Initialize the console
  if (myConsole != 0)
    // Don't let messages before this one appear
    myConsole->Clear ();

  // Some commercials...
  Report (CS_REPORTER_SEVERITY_NOTIFY,
    "The Alternate Window System Test Harness.");

  // First disable the lighting cache. Our app is simple enough
  // not to need this.
  engine->SetLightingCacheMode (0);

  // Create our world.
  Report (CS_REPORTER_SEVERITY_NOTIFY, "Creating world!...");

  if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif"))
  {
    Report (CS_REPORTER_SEVERITY_ERROR, "Error loading 'stone4' texture!");
    exit (1);
  }
  iMaterialWrapper* tm = engine->GetMaterialList ()->FindByName ("stone");

  room = engine->CreateSector ("room");
  csRef<iMeshWrapper> walls (engine->CreateSectorWallsMesh (room, "walls"));
  csRef<iThingState> ws =
  	SCF_QUERY_INTERFACE (walls->GetMeshObject (), iThingState);
  csRef<iThingFactoryState> walls_state = ws->GetFactory ();
  walls_state->AddInsideBox (csVector3 (-5, 0, -5), csVector3 (5, 20, 5));
  walls_state->SetPolygonMaterial (CS_POLYRANGE_LAST, tm);
  walls_state->SetPolygonTextureMapping (CS_POLYRANGE_LAST, 3);

  csRef<iLight> light;
  iLightList* ll = room->GetLights ();
  light = engine->CreateLight (0, csVector3 (-3, 5, 0), 10,
  	csColor (1, 0, 0));
  ll->Add (light);

  light = engine->CreateLight (0, csVector3 (3, 5,  0), 10,
  	csColor (0, 0, 1));
  ll->Add (light);

  light = engine->CreateLight (0, csVector3 (0, 5, -3), 10,
  	csColor (0, 1, 0));
  ll->Add (light);

  engine->Prepare ();

  Report(CS_REPORTER_SEVERITY_NOTIFY, "--------------------------------------");

  view = csPtr<iView> (new csView (engine, myG3D));
  view->GetCamera ()->SetSector (room);
  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));
  view->SetRectangle (0, 0, myG2D->GetWidth (), myG2D->GetHeight ());

  wview = csPtr<iView> (new csView (engine, myG3D));
  wview->GetCamera ()->SetSector (room);
  wview->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));

  col_red = myG2D->FindRGB (255, 0, 0);
  col_blue = myG2D->FindRGB (0, 0, 255);
  col_white = myG2D->FindRGB (255, 255, 255);
  col_gray = myG2D->FindRGB (50, 50, 50);
  col_black = myG2D->FindRGB (0, 0, 0);
  col_yellow = myG2D->FindRGB (255, 255, 0);
  col_cyan = myG2D->FindRGB (0, 255, 255);
  col_green = myG2D->FindRGB (0, 255, 0);

/*  if (AWSTEST_CANVAS == AWSTEST_SINGLEPROC)
  {
    awsCanvas = aws->CreateDefaultCanvas(engine, myG3D->GetTextureManager(), 512, 512, 0);
    //aws->SetFlag(AWSF_AlwaysEraseWindows);  // Only set for surface or direct-drawing w/o engine
  }
  else if (AWSTEST_CANVAS == AWSTEST_MULTIPROC)
  {
    awsCanvas = aws->CreateDefaultCanvas(engine, myG3D->GetTextureManager());
  }
  else
  {
    awsCanvas = aws->CreateCustomCanvas(myG2D, myG3D);
    aws->SetFlag(AWSF_AlwaysRedrawWindows);     // Only set for direct-drawing with engine
  }*/

  aws->SetupCanvas(0, myG2D, myG3D);

  // next, setup sinks before loading any preferences
  awsTestSink *s = new awsTestSink();
  iAwsSink *sink =aws->GetSinkMgr()->CreateSink((intptr_t)s);

  s->SetSink(sink);
  s->SetWindowManager(aws);

  aws->GetSinkMgr()->RegisterSink("testButtonSink", sink);

  // make the manager aware of our custom component
  // the contructor automatically registers so we only need to create it
  (void) new CustomComponentFactory(aws);

  // now load preferences
  if (!aws->GetPrefMgr()->Load("/aws/awstest.def"))
      Report(CS_REPORTER_SEVERITY_ERROR, "couldn't load definition file!");
  aws->GetPrefMgr()->SelectDefaultSkin("Normal Windows");

  csPrintf("aws-debug: Creating splash window...\n");
  iAwsWindow *test = aws->CreateWindowFrom("Splash");
  iAwsWindow *test2 = aws->CreateWindowFrom("Another");
  iAwsWindow *test3 = aws->CreateWindowFrom("Engine View");
  iAwsWindow *test4 = aws->CreateWindowFrom("Layout Test");
  iAwsWindow *test5 = aws->CreateWindowFrom("Form1");

  if(test3)
  {
    iAwsComponent* engine_view = test3->FindChild("Engine View");
    if(engine_view)
      engine_view->SetProperty("view", (intptr_t)(iView*)wview);
  }

  if (test)  test->Show();
  if (test3) test3->Show();
  if (test4) test4->Show();
  if (test5) test5->Show();

  if (test2)
  {
	  test2->Show();
	  test2->Execute(":move_to@widget(x=500, y=0)");
  }
  //s->SetTestWin(test2);

  /////////

  Report(CS_REPORTER_SEVERITY_NOTIFY, "Init done.");

  return true;
}

void
awsTest::SetupFrame()
{
  static int counter=0;

  iCamera* c = view->GetCamera();
  iCamera* c2 = wview->GetCamera();

  counter++;

  // First get elapsed time from the system driver.
  csTicks elapsed_time, current_time;
  elapsed_time = vc->GetElapsedTicks ();
  current_time = vc->GetCurrentTicks ();

  // Now rotate the camera according to keyboard state
  float speed = (elapsed_time / 1000.0f) * (0.03f * 2);

  c->GetTransform ().RotateThis (CS_VEC_ROT_RIGHT, speed);
  c2->GetTransform ().RotateThis (CS_VEC_ROT_LEFT, speed);

  // Tell 3D driver we're going to display 3D things.
  if (!myG3D->BeginDraw (
      engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS))
      return;

  // Tell the camera to render into the frame buffer.
  view->Draw ();
  wview->Draw();

  // Start drawing 2D graphics.
  if (!myG3D->BeginDraw (CSDRAW_2DGRAPHICS)) return;

  message.Format ("awsTest(%d)", counter);
  myG2D->Write(font, 5, 5, col_green, -1, message);

  aws->Redraw();
  aws->Print(myG3D, 64);
  /*if (AWSTEST_SINGLEPROCTEXCANVAS)
  {
    csRef<iTextureWrapper> tex (SCF_QUERY_INTERFACE(awsCanvas, iTextureWrapper));
    if (tex)
    {
      myG3D->DrawPixmap(tex->GetTextureHandle(),
                    0,0,512,512,
                    0,0,512,512,
                    0);
    }
  }*/
}

void
awsTest::FinishFrame ()
{
  myG3D->FinishDraw ();
  myG3D->Print (0);
}

bool
awsTest::HandleEvent (iEvent &Event)
{
  if ((Event.Type == csevKeyboard) &&
    (csKeyEventHelper::GetEventType (&Event) == csKeyEventTypeDown) &&
    (csKeyEventHelper::GetCookedCode (&Event) == CSKEY_ESC))
  {
    csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
    if (q)
      q->GetEventOutlet()->Broadcast (cscmdQuit);
    return true;
  }

  return aws->HandleEvent(Event);
}

void
awsTest::Report (int severity, const char* msg, ...)
{
  va_list arg;
  va_start (arg, msg);
  csRef<iReporter> rep (CS_QUERY_REGISTRY (object_reg, iReporter));
  if (rep)
    rep->ReportV (severity, "crystalspace.application.awstest", msg, arg);
  else
  {
    csPrintfV (msg, arg);
    csPrintf ("\n");
  }
  va_end (arg);
}

<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2012-2013 Tokutek Inc.  All rights reserved."
#ident "$Id$"

#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#include "backup.h"
#include "backup_test_helpers.h"

const int TRIES = 4;
const int LEN = 26;
char *dirs[TRIES];

/****
static void setup(void)
{
    for (int i = 0; i < TRIES; ++i) {
        char s[LEN];
        int r = snprintf(s, sizeof(s), "multiple_backups.backup_%d", i);
        check(r<(int)sizeof(s));
        systemf("rm -rf %s", s);
        dirs[i] = strdup(s);
        check(dirs[i]);
    }
}
****/
/****

static void breakdown(void)
{
    // The backup thread helpers free dirs[i].
}
****/

static void write_lots_of_dummy_data(char *src)
{
    const int SIZE = 100;
    const int MB = 1024 * 1024;
    char dummy[MB] = {0};
    char file[SIZE];
    snprintf(file, SIZE, "%s/%s", src, "dummy");
    int fd = open(file, O_CREAT | O_RDWR, 0777);
    check(fd >= 0);
    const int MEGS = 10;
    for (int i = 0; i < MEGS; ++i) {
        int r = write(fd, dummy, MB);
        check(r == MB);
    }
}

static void work_it(char *src, char *magic, int size)
{
    char file[100];
    snprintf(file, 100, "%s/%s", src, magic);

    // 1.  Create a file.
    int fd = open(file, O_CREAT | O_RDWR, 0777);
    check(fd >= 0);
    // 2.  Write magic to the file.
    int r = write(fd, magic, size);
    check(r == size);

    // 3.  Close the file.
    close(fd);

    // 4.  Open the file.
    fd = open(file, O_RDWR);

    // 5.  Read from the file.
    char *buf = (char*)malloc(sizeof(char) * size);
    r = read(fd, buf, size);

    // 6.  Write magic to the file.
    lseek(fd, size, SEEK_SET);
    write(fd, magic, size);

    // 7.  pwrite magic to the file.
    pwrite(fd, magic, size, size * 3);

    // 8.  ftruncate magic from the file.
    ftruncate(fd, size * 3);

    // close the file.
    close(fd);
    free((void*)buf);
}

static int check_it(char *dst, char *magic, int size, int count)
{
    int r = 0;
    int backup_fd = openf(O_RDONLY, 0, "%s/magic%d", dst, count);
    char backup_buf[20] = {0};
    pread(backup_fd, backup_buf, size, 0);
    char magic_buf[20] = {0};
    snprintf(magic_buf, size, "%s%d", magic, count);
    int result = strcmp(backup_buf, magic_buf);
    if (result != 0) {
        printf("Couldn't match: source:%s vs backup:%s\n", magic_buf, backup_buf);
        r = -1;
    }

    return r;
}

/****
//
static int many_directories(void) {
    setup_source();
    setup();
    char * src = get_src();
    write_lots_of_dummy_data(src);

    int result = 0;

    pthread_t thread;
    tokubackup_throttle_backup(1L << 22);
    for (int i = 0; i < TRIES; ++i) {
        setup_directory(dirs[i]);
        start_backup_thread(&thread, dirs[i]);
        const int SIZE = 7;
        char buf[SIZE] = {0};
        snprintf(buf, SIZE, "magic%i", i);
        work_it(src, buf, SIZE);
        finish_backup_thread(thread);
        snprintf(buf, SIZE, "magic");
        int r = check_it(buf, SIZE, i);
        if (r != 0) {
            result = -1 * i;
        }
    }

    free(src);
    if(result < 0) {
        printf("Backup # %d failed.\n", result * -1);
        fail();
        result = -1;
    } else {
        pass();
    }

    breakdown();

    return result;
}
****/

int many_directories(const int directory_count) {
    int result = 0;

    // Set up all the directories.
    set_dir_count(directory_count);
    char **sources = (char**)malloc(sizeof(char**) * directory_count);
    char **destinations = (char**)malloc(sizeof(char**) * directory_count);
    for (int i = 0; i < directory_count; ++i)
    {
        sources[i] = get_src(i);
        destinations[i] = get_dst(i);
        setup_directory(sources[i]);
        setup_directory(destinations[i]);
        write_lots_of_dummy_data(sources[i]);
    }

    pthread_t thread;
    start_backup_thread(&thread);
    // Do work in each directory.
    const int SIZE = 7;
    char buf[SIZE] = {0};
    for (int i = 0; i < directory_count; ++i)
    {
        snprintf(buf, SIZE, "magic%i", i);
        work_it(sources[i], buf, SIZE);
    }

    finish_backup_thread(thread);

    // Check the work done in each directory.
    for (int i = 0; i < directory_count; ++i)
    {
        snprintf(buf, SIZE, "magic");
        int r = check_it(destinations[i], buf, SIZE, i);
        if (r != 0) {
            result = -1 * i;
        }
    }

    // Don't forget to deallocate the strings!
    for (int i = 0; i < directory_count; ++i)
    {
        free((void*)sources[i]);
        free((void*)destinations[i]);
    }

    return result;
}

int test_main(int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) {
    int r = 0;
    const int MAX_DIRS = 8;
    for (int i = 1; i <= MAX_DIRS; i = i << 1)
    {
        r = many_directories(i);
        if (r != 0)
        {
            break;
        }
    }

    return r;
}
<commit_msg>Removed dead code from many_dir test.<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "Copyright (c) 2012-2013 Tokutek Inc.  All rights reserved."
#ident "$Id$"

#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#include "backup.h"
#include "backup_test_helpers.h"

static void write_lots_of_dummy_data(char *src)
{
    const int SIZE = 100;
    const int MB = 1024 * 1024;
    char dummy[MB] = {0};
    char file[SIZE];
    snprintf(file, SIZE, "%s/%s", src, "dummy");
    int fd = open(file, O_CREAT | O_RDWR, 0777);
    check(fd >= 0);
    const int MEGS = 10;
    for (int i = 0; i < MEGS; ++i) {
        int r = write(fd, dummy, MB);
        check(r == MB);
    }
}

static void work_it(char *src, char *magic, int size)
{
    char file[100];
    snprintf(file, 100, "%s/%s", src, magic);

    // 1.  Create a file.
    int fd = open(file, O_CREAT | O_RDWR, 0777);
    check(fd >= 0);
    // 2.  Write magic to the file.
    int r = write(fd, magic, size);
    check(r == size);

    // 3.  Close the file.
    close(fd);

    // 4.  Open the file.
    fd = open(file, O_RDWR);

    // 5.  Read from the file.
    char *buf = (char*)malloc(sizeof(char) * size);
    r = read(fd, buf, size);

    // 6.  Write magic to the file.
    lseek(fd, size, SEEK_SET);
    write(fd, magic, size);

    // 7.  pwrite magic to the file.
    pwrite(fd, magic, size, size * 3);

    // 8.  ftruncate magic from the file.
    ftruncate(fd, size * 3);

    // close the file.
    close(fd);
    free((void*)buf);
}

static int check_it(char *dst, char *magic, int size, int count)
{
    int r = 0;
    int backup_fd = openf(O_RDONLY, 0, "%s/magic%d", dst, count);
    char backup_buf[20] = {0};
    pread(backup_fd, backup_buf, size, 0);
    char magic_buf[20] = {0};
    snprintf(magic_buf, size, "%s%d", magic, count);
    int result = strcmp(backup_buf, magic_buf);
    if (result != 0) {
        printf("Couldn't match: source:%s vs backup:%s\n", magic_buf, backup_buf);
        r = -1;
    }

    return r;
}

int many_directories(const int directory_count) {
    int result = 0;

    // Set up all the directories.
    set_dir_count(directory_count);
    char **sources = (char**)malloc(sizeof(char**) * directory_count);
    char **destinations = (char**)malloc(sizeof(char**) * directory_count);
    for (int i = 0; i < directory_count; ++i)
    {
        sources[i] = get_src(i);
        destinations[i] = get_dst(i);
        setup_directory(sources[i]);
        setup_directory(destinations[i]);
        write_lots_of_dummy_data(sources[i]);
    }

    pthread_t thread;
    start_backup_thread(&thread);
    // Do work in each directory.
    const int SIZE = 7;
    char buf[SIZE] = {0};
    for (int i = 0; i < directory_count; ++i)
    {
        snprintf(buf, SIZE, "magic%i", i);
        work_it(sources[i], buf, SIZE);
    }

    finish_backup_thread(thread);

    // Check the work done in each directory.
    for (int i = 0; i < directory_count; ++i)
    {
        snprintf(buf, SIZE, "magic");
        int r = check_it(destinations[i], buf, SIZE, i);
        if (r != 0) {
            result = -1 * i;
        }
    }

    // Don't forget to deallocate the strings!
    for (int i = 0; i < directory_count; ++i)
    {
        free((void*)sources[i]);
        free((void*)destinations[i]);
    }

    return result;
}

int test_main(int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) {
    int r = 0;
    const int MAX_DIRS = 8;
    for (int i = 1; i <= MAX_DIRS; i = i << 1)
    {
        r = many_directories(i);
        if (r != 0)
        {
            break;
        }
        printf("PASS: with %d directories backed up.", i);
    }

    return r;
}
<|endoftext|>


<commit_before>/*
 * tripolar.cpp
 *
 * Created: 5/12/2015 4:02:05 PM
 *  Author: Alan
 */

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& USER SETUP
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	*/

	#define F_CPU 16000000UL
	//#define DO_DEBUG
/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& INCLUDES
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
*/

#include <avr/io.h>
#include "bldcGimbal.h"

#include "afro_nfet.h"
#include "fets.h"

#include <util/delay.h>
#include "millis.h"

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& FUNCTION PROTOTYPES
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
*/

void setup(void);
void loop(void);

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& VARIABLES
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
*/

bldcGimbal gimbal;

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& FUNCTIONS
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
*/

int main(void)
{
	setup();
    while(1) loop();
}

void setup(void)
{

	boardInit();
	cli();
	redOff();
	greenOn();
	millis_init();
	gimbal.begin();
	gimbal.set_speed_rpm(500);
}

void loop(void)
{
	gimbal.tickle();
}

<commit_msg>Changed testbed to ramp motor up slowely<commit_after>/*
 * tripolar.cpp
 *
 * Created: 5/12/2015 4:02:05 PM
 *  Author: Alan
 */

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& USER SETUP
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
	*/

	#define F_CPU 16000000UL
	//#define DO_DEBUG
/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& INCLUDES
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
*/

#include <avr/io.h>
#include "bldcGimbal.h"

#include "afro_nfet.h"
#include "fets.h"

#include <util/delay.h>
#include "millis.h"

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& FUNCTION PROTOTYPES
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
*/

void setup(void);
void loop(void);

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& VARIABLES
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
*/

bldcGimbal gimbal;

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&& FUNCTIONS
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
*/

int main(void)
{
	setup();
    while(1) loop();
}

void setup(void)
{

	boardInit();
	cli();
	redOff();
	greenOn();
	millis_init();
	gimbal.begin();
}

void loop(void)
{
	static uint32_t lastTime = 0;
	static uint16_t currentSpeed = 0;

	if (_100us-lastTime >=20000)
	{
		lastTime = _100us;
		if (currentSpeed <10) currentSpeed++;
		else currentSpeed += currentSpeed / 10;
		gimbal.set_speed_rpm(currentSpeed);
	}

	gimbal.tickle();
}

<|endoftext|>