<commit_before>/*
 * MIPS.hpp
 *
 *  Created on: Jun 14, 2014
 *      Author: Pimenta
 */

#ifndef MIPS_HPP_
#define MIPS_HPP_

// lib
#include <systemc.h>

// local
#include "Context.hpp"
#include "Thread.hpp"
#include "readwrite_if.hpp"

struct Bitmap {
  short magic_number;
  int file_size;
  int reserved;
  int header_size;
  int data_distance;
  int width;
  int height;
  short planes;
  short bpp;
  int compression;
  int data_size;
  int horizontal_resolution;
  int vertical_resolution;
  int palette_size;
  int important_colors;
  uint32_t* buf;
};

SC_MODULE(MIPS) {
  sc_in<bool> clk;
  sc_port<readwrite_if> ioController;

  uint32_t breg[32];

  Bitmap bg;

  SC_CTOR(MIPS) {
    SC_METHOD(exec);
    sensitive << clk.pos();

    const char fn[] = "teste.bmp";
    const char mode[] = "rb";

    breg[4] = (uint32_t)fn; breg[5] = (uint32_t)mode;
    fileOpen();
    breg[4] = breg[2];

    breg[5] = (uint32_t)&bg.magic_number; breg[6] = 2;
    fileRead();
    breg[5] = (uint32_t)&bg.file_size; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.reserved; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.header_size; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.data_distance; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.width; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.height; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.planes; breg[6] = 2;
    fileRead();
    breg[5] = (uint32_t)&bg.bpp; breg[6] = 2;
    fileRead();
    breg[5] = (uint32_t)&bg.compression; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.data_size; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.horizontal_resolution; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.vertical_resolution; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.palette_size; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.important_colors; breg[6] = 4;
    fileRead();

    bg.buf = new uint32_t[bg.width*bg.height];
    breg[5] = (uint32_t)bg.buf; breg[6] = bg.width*bg.height*bg.bpp/8;
    fileRead();

    fileClose();
  }

  ~MIPS() {
    delete[] bg.buf;
  }

  void exec() {
    static bool inited = false;
    if (!inited) {
      inited = true;
      int wSize = ioController->read(0x10), w = wSize >> 16, h = wSize & 0xFFFF;
      for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
          ioController->write(0x0, bg.buf[(bg.height - 1 - y)*bg.width + x]);
          ioController->write(0x4, 0x10010000 + (y*w + x)*4);
        }
      }
    }
    if (ioController->read(0x30))
      exit();
    Thread::sleep(33);
  }

  // ===========================================================================
  // syscalls (code in v0)
  // ===========================================================================
  // v0: 2
  // a0: 4
  // a1: 5
  // a2: 6
  void exit() { // v0 = 10
    sc_stop();
  }
  void fileOpen() { // v0 = 13
    breg[2] = (uint32_t)fopen((const char*)breg[4], (const char*)breg[5]);
  }
  void fileRead() { // v0 = 14
    breg[2] = (uint32_t)fread((void*)breg[5], breg[6], 1, (FILE*)breg[4]);
  }
  void fileWrite() { // v0 = 15
    breg[2] = (uint32_t)fwrite((const void*)breg[5], breg[6], 1, (FILE*)breg[4]);
  }
  void fileClose() { // v0 = 16
    fclose((FILE*)breg[4]);
  }
};

#endif /* MIPS_HPP_ */
<commit_msg>Adicionando syscall de sleep<commit_after>/*
 * MIPS.hpp
 *
 *  Created on: Jun 14, 2014
 *      Author: Pimenta
 */

#ifndef MIPS_HPP_
#define MIPS_HPP_

// lib
#include <systemc.h>

// local
#include "Context.hpp"
#include "Thread.hpp"
#include "readwrite_if.hpp"

struct Bitmap {
  short magic_number;
  int file_size;
  int reserved;
  int header_size;
  int data_distance;
  int width;
  int height;
  short planes;
  short bpp;
  int compression;
  int data_size;
  int horizontal_resolution;
  int vertical_resolution;
  int palette_size;
  int important_colors;
  uint32_t* buf;
};

SC_MODULE(MIPS) {
  sc_in<bool> clk;
  sc_port<readwrite_if> ioController;

  uint32_t breg[32];

  Bitmap bg;

  SC_CTOR(MIPS) {
    SC_METHOD(exec);
    sensitive << clk.pos();

    const char fn[] = "teste.bmp";
    const char mode[] = "rb";

    breg[4] = (uint32_t)fn; breg[5] = (uint32_t)mode;
    fileOpen();
    breg[4] = breg[2];

    breg[5] = (uint32_t)&bg.magic_number; breg[6] = 2;
    fileRead();
    breg[5] = (uint32_t)&bg.file_size; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.reserved; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.header_size; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.data_distance; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.width; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.height; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.planes; breg[6] = 2;
    fileRead();
    breg[5] = (uint32_t)&bg.bpp; breg[6] = 2;
    fileRead();
    breg[5] = (uint32_t)&bg.compression; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.data_size; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.horizontal_resolution; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.vertical_resolution; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.palette_size; breg[6] = 4;
    fileRead();
    breg[5] = (uint32_t)&bg.important_colors; breg[6] = 4;
    fileRead();

    bg.buf = new uint32_t[bg.width*bg.height];
    breg[5] = (uint32_t)bg.buf; breg[6] = bg.width*bg.height*bg.bpp/8;
    fileRead();

    fileClose();
  }

  ~MIPS() {
    delete[] bg.buf;
  }

  void exec() {
    static bool inited = false;
    if (!inited) {
      inited = true;
      int wSize = ioController->read(0x10), w = wSize >> 16, h = wSize & 0xFFFF;
      for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
          ioController->write(0x0, bg.buf[(bg.height - 1 - y)*bg.width + x]);
          ioController->write(0x4, 0x10010000 + (y*w + x)*4);
        }
      }
    }

    if (ioController->read(0x30))
      exit();

    breg[4] = 33;
    sleep();
  }

  // ===========================================================================
  // syscalls (code in v0)
  // ===========================================================================
  // v0: 2
  // a0: 4
  // a1: 5
  // a2: 6
  void exit() { // v0 = 10
    sc_stop();
  }
  void fileOpen() { // v0 = 13
    breg[2] = (uint32_t)fopen((const char*)breg[4], (const char*)breg[5]);
  }
  void fileRead() { // v0 = 14
    breg[2] = (uint32_t)fread((void*)breg[5], breg[6], 1, (FILE*)breg[4]);
  }
  void fileWrite() { // v0 = 15
    breg[2] = (uint32_t)fwrite((const void*)breg[5], breg[6], 1, (FILE*)breg[4]);
  }
  void fileClose() { // v0 = 16
    fclose((FILE*)breg[4]);
  }
  void sleep() { // v0 = 32
    Thread::sleep(breg[4]);
  }
};

#endif /* MIPS_HPP_ */
<|endoftext|>


<commit_before>// Util.cpp
// Util class member-functions definition.
//
// Author: yat0 - https://github.com/yat0

#include "Util.h"
#include "App.h"
#include <cmath>

// render cross on board field (row, col)
void Util::drawCross(int row, int col)
{
    int fieldW = App::SCREEN_WIDTH/3;
    int fieldH = App::SCREEN_HEIGHT/3;

    // top left to bottom right
    SDL_SetRenderDrawColor(App::getRenderer(),//SDL_Render_DrawLine
        col*fieldW, row*fieldH,
        col*fieldW+fieldW, row*fieldH+fieldH);

    // top right to bottom left
    SDL_RenderDrawLine(App::getRenderer(),
        col*fieldW, row*fieldH+fieldH,
        col*fieldW+fieldW, row*fieldH);
}

// render circle on board field (boardX, boardY)
void Util::drawCircle(int row, int col)
{
    int fieldW = App::SCREEN_WIDTH/3;
    int fieldH = App::SCREEN_HEIGHT/3;

    // calculate circle center
    int centerX = col*fieldW+(fieldW/2);
    int centerY = row*fieldH+(fieldH/2);

    int r = fieldW/2;

    double step = 2*M_PI/30;
    int endX = centerX + r;
    int endY = centerY;

    // draw circle.. Multiple straight lines between consecutive
    // points of the desired circle
    for(double angle=0; angle<2*M_PI; angle+=step)
    {
        int startX = endX;
        int startY = endY;
        endX = r * cos(angle) + centerX;
        endY = r * sin(angle) + centerY;
        SDL_RenderDrawLine(App::getRenderer(), startX, startY, endX, endY);
    }
}
<commit_msg>Displays a nuclear letter X now<commit_after>// Util.cpp
// Util class member-functions definition.
//
// Author: yat0 - https://github.com/yat0

#include "Util.h"
#include "App.h"
#include <cmath>

// render cross on board field (row, col)
void Util::drawCross(int row, int col)
{
    int fieldW = App::SCREEN_WIDTH/3;
    int fieldH = App::SCREEN_HEIGHT/3;

    // top left to bottom right
    SDL_SetRenderDrawColor(App::getRenderer(),//SDL_Render_DrawLine
        col*fieldW, row*fieldH,
        col*fieldW+fieldW, row*fieldH+fieldH);

    // top right to bottom left

    SDL_RenderDrawLine(App::getRenderer(),
        col*fieldW, row*fieldH+fieldH,
        col*fieldW+fieldW, row*fieldH);

    SDL_RenderDrawLine(App::getRenderer(),
        col*fieldW, row*fieldH,
        col*fieldW+fieldW, row*fieldH+fieldH);

}

// render circle on board field (boardX, boardY)
void Util::drawCircle(int row, int col)
{
    int fieldW = App::SCREEN_WIDTH/3;
    int fieldH = App::SCREEN_HEIGHT/3;

    // calculate circle center
    int centerX = col*fieldW+(fieldW/2);
    int centerY = row*fieldH+(fieldH/2);

    int r = fieldW/2;

    double step = 2*M_PI/30;
    int endX = centerX + r;
    int endY = centerY;

    // draw circle.. Multiple straight lines between consecutive
    // points of the desired circle
    for(double angle=0; angle<2*M_PI; angle+=step)
    {
        int startX = endX;
        int startY = endY;
        endX = r * cos(angle) + centerX;
        endY = r * sin(angle) + centerY;
        SDL_RenderDrawLine(App::getRenderer(), startX, startY, endX, endY);
    }
}
<|endoftext|>


<commit_before>/**
 * @file		Wave.cpp
 * @author  	Sebastian Ritterbusch <ospac@ritterbusch.de>
 * @version 	1.0
 * @date		5.2.2016
 * @copyright	MIT License (see LICENSE file)
 * @brief		Wave file management via libsndfile
 */

#include <iostream>
#include <fstream>

extern "C" {
	#include <sndfile.h>
}

#include "Wave.h"
#include "Log.h"

Channels & Wave::load(const std::string &name, Channels & channels,float skip,float length)
{
	LOG(logINFO) << "Loading "<< name << std::endl;

	SNDFILE *sf;
	SF_INFO  info;
	info.format = 0;
	sf = sf_open(name.c_str(),SFM_READ,&info);
	if(sf==NULL)
	{
		LOG(logERROR) << "Could not read " << name << std::endl;
		return channels;
	}

	//if(info.frames>44100*60*10)
	//	info.frames=44100*60*10;

	short * buf=new short[info.channels*65536];

	LOG(logINFO) << "Reading "<<info.frames<<" frames with "<<info.channels<<" channels with rate "<< info.samplerate << std::endl;
	//std::cerr << info.format << std::endl;

	unsigned o=channels.size();

	unsigned skiplen=skip*(int)info.samplerate;
	unsigned fulllen=length*(int)info.samplerate;

	if(skiplen>info.frames)
		skiplen=info.frames;
	if(fulllen>info.frames-skiplen || length>1e+90)
		fulllen=info.frames-skiplen;

	for(int i=0;i<info.channels;i++)
		channels.push_back(Channel((int)info.samplerate,std::vector<float>(fulllen)));

	for(unsigned i=0;i<info.frames && i<skiplen+fulllen;)
	{
		int items=65536;

		if(i+items>=info.frames)
			items=info.frames-i;

		//LOG(logDEBUG) << i << ": Reading "<< items << " ";

		int hasread=sf_read_short(sf,buf,items*info.channels);
		hasread=hasread+0;

		LOG(logDEBUG2) << i << ": Read    "<< hasread << std::endl;

		for(int j=0,t=0;j<items;i++,j++)
			for(int c=0;c<info.channels;c++)
				if(i>=skiplen && i<=skiplen+fulllen)
					channels[o+c][i-skiplen]=buf[t++];
	}

	delete [] buf;

	sf_close(sf);
	LOG(logDEBUG) << "Loading done" << std::endl;
	return channels;
}

Channels & Wave::loadAscii(const std::string &name,int samplerate,Channels & channels,float skip,float maxlength)
{
	unsigned length=0;
	double min=1e99;
	double max=-1e99;
	double sum=0;
	unsigned count=0;

	unsigned skiplen=skip*samplerate;
	unsigned fulllen=maxlength*samplerate;

	{
		std::ifstream in(name.c_str());

		if(in.fail())
			return channels;

		double dummy;
		for(;!in.eof();length++)
		{
			while(!in.eof() && (in.peek()=='#' || in.peek()==' '
			   || in.peek()=='\n' || in.peek()=='\r'
			   || in.peek()=='\t'))
			{
				char c;
				c=in.get();

				if(c=='#')
				{
					while(!in.eof() && in.peek()!='\n' && in.peek()!='\r')
						in.get();
				}
			}
			in >> dummy;
			if(length>=skiplen && (length<fulllen || maxlength>1e+90))
			{
				sum+=dummy;
				count++;
				if(dummy>max)
				{
					max=dummy;
				}
				if(dummy<min)
				{
					min=dummy;
				}
			}
		}
	}
	if(skip>length)
		skip=length;
	if(fulllen>length-skip || maxlength>1e+90)
		fulllen=length-skip;

	if(count==0)
		count=1;
	double null=sum/count;
	if(min>null)
		min=null-1;
	if(max<null)
		max=null+1;

	// Kill DC signal...
	if(2*null-min>max)
		max=2*null-min;
	if(2*null-max<min)
		min=2*null-max;

	unsigned o=channels.size();
	channels.push_back(Channel(samplerate,fulllen));
	std::ifstream in(name.c_str());
	unsigned i=0;
	for(;!in.eof() && i<length && i<skiplen+fulllen;i++)
	{
		while(!in.eof() && (in.peek()=='#' || in.peek()==' '
		   || in.peek()=='\n' || in.peek()=='\r'
		   || in.peek()=='\t'))
		{
			char c;
			c=in.get();

			if(c=='#')
			{
				while(!in.eof() && in.peek()!='\n' && in.peek()!='\r')
					in.get();
			}
		}

		double d;
		in >> d;
		if(i>=skiplen && i<skiplen+fulllen)
		channels[o][i-skiplen]=(d-min)/(max-min)*64000-32000;
	}

	return channels;
}

Channels Wave::load(const std::string &name,float skip,float length)
{
	std::vector<Channel> channels;

	LOG(logINFO) << "Loading "<< name << std::endl;

	return load(name,channels,skip,length);
}

int Wave::save(const std::string &name,Channel & channel)
{
	Channels channels=Channels(1);
	channels[0]=channel;
	return save(name,channels);
}

int Wave::save(const std::string &name,Channels & channels)
{
	SF_INFO  info;
	if(channels.size()==0)
		return 1;

	int no_channels=info.channels=channels.size();
	info.samplerate=channels[0].samplerate();
	int frames=info.frames=channels[0].size();

	LOG(logINFO) << "Writing " << name << " with "<< info.channels << " channels in " << info.samplerate << "Hz and " << info.frames << "frames " << std::endl;

	for(unsigned i=0;i<channels.size();i++)
	{
		if(channels[i].samplerate()!=(unsigned)info.samplerate)
			channels[i]=channels[i].resampleTo(info.samplerate);
		if(channels[i].size()!=info.frames)
			channels[i]=channels[i].resizeTo(info.frames);
	}

	SNDFILE *sf;

	info.format=SF_FORMAT_WAV | SF_FORMAT_PCM_16;
	info.sections=1;
	info.seekable=1;

	//std::cerr << info.format << std::endl;

	sf=sf_open(name.c_str(),SFM_WRITE,&info);

	if(sf==NULL)
	{
		LOG(logERROR) << "Could not write " << name << std::endl;
		return 1;
	}

	short * buf=new short[info.channels*65536];

	//std::cerr << "Starting" << std::endl;

	for(int i=0;i<frames;)
	{
		int items=65536;

		if(i+items>=frames)
			items=frames-i;

		//std::cerr << items << std::endl;

		for(int j=0,t=0;j<items;i++,j++)
			for(int c=0;c<no_channels;c++)
			{
				if(((int)channels[c][i])<-32767)
					buf[t++]=-32767;
				else if(((int)channels[c][i])>32767)
					buf[t++]=32767;
				else
					buf[t++]=channels[c][i];
			}

		int haswritten=sf_write_short(sf,buf,items*no_channels);
		//std::cerr << "wrote " << haswritten << std::endl;
		haswritten=haswritten+0;
	}

	delete [] buf;

	sf_close(sf);

	return 0;
}
<commit_msg>Added logging of length of target file.<commit_after>/**
 * @file		Wave.cpp
 * @author  	Sebastian Ritterbusch <ospac@ritterbusch.de>
 * @version 	1.0
 * @date		5.2.2016
 * @copyright	MIT License (see LICENSE file)
 * @brief		Wave file management via libsndfile
 */

#include <iostream>
#include <fstream>

extern "C" {
	#include <sndfile.h>
}

#include "Wave.h"
#include "Log.h"

Channels & Wave::load(const std::string &name, Channels & channels,float skip,float length)
{
	LOG(logINFO) << "Loading "<< name << std::endl;

	SNDFILE *sf;
	SF_INFO  info;
	info.format = 0;
	sf = sf_open(name.c_str(),SFM_READ,&info);
	if(sf==NULL)
	{
		LOG(logERROR) << "Could not read " << name << std::endl;
		return channels;
	}

	//if(info.frames>44100*60*10)
	//	info.frames=44100*60*10;

	short * buf=new short[info.channels*65536];

	LOG(logINFO) << "Reading "<<info.frames<<" frames with "<<info.channels<<" channels with rate "<< info.samplerate << std::endl;
	//std::cerr << info.format << std::endl;

	unsigned o=channels.size();

	unsigned skiplen=skip*(int)info.samplerate;
	unsigned fulllen=length*(int)info.samplerate;

	if(skiplen>info.frames)
		skiplen=info.frames;
	if(fulllen>info.frames-skiplen || length>1e+90)
		fulllen=info.frames-skiplen;

	for(int i=0;i<info.channels;i++)
		channels.push_back(Channel((int)info.samplerate,std::vector<float>(fulllen)));

	for(unsigned i=0;i<info.frames && i<skiplen+fulllen;)
	{
		int items=65536;

		if(i+items>=info.frames)
			items=info.frames-i;

		//LOG(logDEBUG) << i << ": Reading "<< items << " ";

		int hasread=sf_read_short(sf,buf,items*info.channels);
		hasread=hasread+0;

		LOG(logDEBUG2) << i << ": Read    "<< hasread << std::endl;

		for(int j=0,t=0;j<items;i++,j++)
			for(int c=0;c<info.channels;c++)
				if(i>=skiplen && i<=skiplen+fulllen)
					channels[o+c][i-skiplen]=buf[t++];
	}

	delete [] buf;

	sf_close(sf);
	LOG(logDEBUG) << "Loading done" << std::endl;
	return channels;
}

Channels & Wave::loadAscii(const std::string &name,int samplerate,Channels & channels,float skip,float maxlength)
{
	unsigned length=0;
	double min=1e99;
	double max=-1e99;
	double sum=0;
	unsigned count=0;

	unsigned skiplen=skip*samplerate;
	unsigned fulllen=maxlength*samplerate;

	{
		std::ifstream in(name.c_str());

		if(in.fail())
			return channels;

		double dummy;
		for(;!in.eof();length++)
		{
			while(!in.eof() && (in.peek()=='#' || in.peek()==' '
			   || in.peek()=='\n' || in.peek()=='\r'
			   || in.peek()=='\t'))
			{
				char c;
				c=in.get();

				if(c=='#')
				{
					while(!in.eof() && in.peek()!='\n' && in.peek()!='\r')
						in.get();
				}
			}
			in >> dummy;
			if(length>=skiplen && (length<fulllen || maxlength>1e+90))
			{
				sum+=dummy;
				count++;
				if(dummy>max)
				{
					max=dummy;
				}
				if(dummy<min)
				{
					min=dummy;
				}
			}
		}
	}
	if(skip>length)
		skip=length;
	if(fulllen>length-skip || maxlength>1e+90)
		fulllen=length-skip;

	if(count==0)
		count=1;
	double null=sum/count;
	if(min>null)
		min=null-1;
	if(max<null)
		max=null+1;

	// Kill DC signal...
	if(2*null-min>max)
		max=2*null-min;
	if(2*null-max<min)
		min=2*null-max;

	unsigned o=channels.size();
	channels.push_back(Channel(samplerate,fulllen));
	std::ifstream in(name.c_str());
	unsigned i=0;
	for(;!in.eof() && i<length && i<skiplen+fulllen;i++)
	{
		while(!in.eof() && (in.peek()=='#' || in.peek()==' '
		   || in.peek()=='\n' || in.peek()=='\r'
		   || in.peek()=='\t'))
		{
			char c;
			c=in.get();

			if(c=='#')
			{
				while(!in.eof() && in.peek()!='\n' && in.peek()!='\r')
					in.get();
			}
		}

		double d;
		in >> d;
		if(i>=skiplen && i<skiplen+fulllen)
		channels[o][i-skiplen]=(d-min)/(max-min)*64000-32000;
	}

	return channels;
}

Channels Wave::load(const std::string &name,float skip,float length)
{
	std::vector<Channel> channels;

	LOG(logINFO) << "Loading "<< name << std::endl;

	return load(name,channels,skip,length);
}

int Wave::save(const std::string &name,Channel & channel)
{
	Channels channels=Channels(1);
	channels[0]=channel;
	return save(name,channels);
}

int Wave::save(const std::string &name,Channels & channels)
{
	SF_INFO  info;
	if(channels.size()==0)
		return 1;

	int no_channels=info.channels=channels.size();
	info.samplerate=channels[0].samplerate();
	int frames=info.frames=channels[0].size();

	char lengthString[40];

	float secs=frames/float(info.samplerate);
	int   mins=secs/60;
	secs-=mins*60;
	int   hours=mins/60;
	mins-=hours*60;

	if(hours>0)
		sprintf(lengthString,"%d:%02d:%05.2f",hours,mins,secs);
	else
		sprintf(lengthString,"%d:%05.2f",mins,secs);

	LOG(logINFO) << "Writing " << name << " with "<< info.channels << " channels in " << info.samplerate << "Hz and " << info.frames << "frames" << std::endl;
	LOG(logINFO) << "Final length: " <<lengthString << std::endl;

	for(unsigned i=0;i<channels.size();i++)
	{
		if(channels[i].samplerate()!=(unsigned)info.samplerate)
			channels[i]=channels[i].resampleTo(info.samplerate);
		if(channels[i].size()!=info.frames)
			channels[i]=channels[i].resizeTo(info.frames);
	}

	SNDFILE *sf;

	info.format=SF_FORMAT_WAV | SF_FORMAT_PCM_16;
	info.sections=1;
	info.seekable=1;

	//std::cerr << info.format << std::endl;

	sf=sf_open(name.c_str(),SFM_WRITE,&info);

	if(sf==NULL)
	{
		LOG(logERROR) << "Could not write " << name << std::endl;
		return 1;
	}

	short * buf=new short[info.channels*65536];

	//std::cerr << "Starting" << std::endl;

	for(int i=0;i<frames;)
	{
		int items=65536;

		if(i+items>=frames)
			items=frames-i;

		//std::cerr << items << std::endl;

		for(int j=0,t=0;j<items;i++,j++)
			for(int c=0;c<no_channels;c++)
			{
				if(((int)channels[c][i])<-32767)
					buf[t++]=-32767;
				else if(((int)channels[c][i])>32767)
					buf[t++]=32767;
				else
					buf[t++]=channels[c][i];
			}

		int haswritten=sf_write_short(sf,buf,items*no_channels);
		//std::cerr << "wrote " << haswritten << std::endl;
		haswritten=haswritten+0;
	}

	delete [] buf;

	sf_close(sf);

	return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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 "itkRLEImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
#include <cstdlib>
#include <string>

template <typename ImageType1, typename ImageType2>
void compare(itk::SmartPointer<ImageType1> im1, itk::SmartPointer<ImageType2> im2)
{
  itk::ImageRegionConstIterator<ImageType1> it1(im1, im1->GetLargestPossibleRegion());
  itk::ImageRegionConstIterator<ImageType2> it2(im2, im2->GetLargestPossibleRegion());
  while (!it1.IsAtEnd())
    {
    if (it1.Get() != it2.Get())
      {
      itkGenericExceptionMacro(<< "Images differ. Val1: "  << it1.Get() << "  Val2: " << it2.Get()
        << "\nInd1: " << it1.GetIndex() << "  Ind2: " << it2.GetIndex());
      }
    ++it1;
    ++it2;
    }
}

template <typename ImageType>
void roiTest(itk::SmartPointer<itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension> > orig)
{
  using myRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension>;
  using charRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension, char>;
  using charConverterType = itk::RegionOfInterestImageFilter<myRLEImage, charRLEImage>;
  typename charConverterType::Pointer cConv = charConverterType::New();
  cConv->SetInput(orig);
  cConv->SetRegionOfInterest(orig->GetLargestPossibleRegion());
  cConv->Update();
  typename charRLEImage::Pointer cIn = cConv->GetOutput();
  cIn->DisconnectPipeline();

  using ucharRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension, unsigned char>;
  using ucharConverterType = itk::RegionOfInterestImageFilter<myRLEImage, ucharRLEImage>;
  typename ucharConverterType::Pointer ucConv = ucharConverterType::New();
  ucConv->SetInput(orig);
  ucConv->SetRegionOfInterest(orig->GetLargestPossibleRegion());
  ucConv->Update();
  typename ucharRLEImage::Pointer ucIn = ucConv->GetOutput();
  ucIn->DisconnectPipeline();

  std::cout << "Comparing direct conversions...";
  compare(cIn, ucIn);
  std::cout << "OK" << std::endl;

  typename myRLEImage::RegionType reg = orig->GetLargestPossibleRegion();
  typename myRLEImage::RegionType rNeg = reg;
  for (unsigned i = 0; i < ImageType::ImageDimension; i++)
    {
    rNeg.SetIndex(i, -typename myRLEImage::IndexValueType(reg.GetSize(i)) * 3 / 4);
    }
  cIn->SetRegions(rNeg);
  ucIn->SetRegions(rNeg);
  std::cout << "Comparing LPR with negative indices...";
  compare(cIn, ucIn);
  std::cout << "OK" << std::endl;

  //region for partial coverage, skip X due to RLE representation constraints
  for (unsigned i = 1; i < ImageType::ImageDimension; i++)
    {
    reg.GetModifiableIndex()[i] += (reg.GetSize(i) - 1) / 4;
    rNeg.GetModifiableIndex()[i] += typename myRLEImage::IndexValueType(rNeg.GetSize(i) - 1) / 4;
    reg.SetSize(i, (reg.GetSize(i) + 1) / 2);
    rNeg.SetSize(i, (rNeg.GetSize(i) + 1) / 2);
    }

  using myConverterType = itk::RegionOfInterestImageFilter<myRLEImage, myRLEImage>;
  typename myConverterType::Pointer myConv = myConverterType::New();
  myConv->SetInput(orig);
  myConv->SetRegionOfInterest(reg);
  myConv->Update();
  typename myRLEImage::Pointer myIn = myConv->GetOutput();

  using cRoIType = itk::RegionOfInterestImageFilter<charRLEImage, charRLEImage>;
  typename cRoIType::Pointer cRoI = cRoIType::New();
  cRoI->SetInput(cIn);
  cRoI->SetRegionOfInterest(rNeg);
  cRoI->Update();
  cIn = cRoI->GetOutput();
  cIn->DisconnectPipeline();

  using ucRoIType = itk::RegionOfInterestImageFilter<ucharRLEImage, ucharRLEImage>;
  typename ucRoIType::Pointer ucRoI = ucRoIType::New();
  ucRoI->SetInput(ucIn);
  ucRoI->SetRegionOfInterest(rNeg);
  ucRoI->Update();
  ucIn = ucRoI->GetOutput();
  ucIn->DisconnectPipeline();

  std::cout << "Comparing RoIs with negative indices...";
  compare(cIn, ucIn);
  std::cout << "OK" << std::endl;

  std::cout << "Comparing RoIs with negative and positive indices...";
  compare(cIn, myIn);
  compare(ucIn, myIn);
  std::cout << "OK" << std::endl;
}

template <typename ImageType>
int doTest(std::string inFilename, std::string outFilename)
{
  using ReaderType = itk::ImageFileReader < ImageType >;
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(inFilename);
  std::cout << "Reading " << inFilename << std::endl;
  reader->Update();

  using myRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension>;
  using inConverterType = itk::RegionOfInterestImageFilter<ImageType, myRLEImage>;
  typename inConverterType::Pointer inConv = inConverterType::New();
  inConv->SetInput(reader->GetOutput());
  inConv->SetRegionOfInterest(reader->GetOutput()->GetLargestPossibleRegion());
  std::cout << "Converting regular image to RLEImage" << std::endl;
  inConv->Update();
  typename myRLEImage::Pointer test = inConv->GetOutput();
  itk::SizeValueType xSize = test->GetLargestPossibleRegion().GetSize(0);

  std::cout << "Running region of interest tests" << std::endl;
  if (xSize > 127)
    {
    std::cout << "\n  xSize>127 (CHAR_MAX)" << std::endl;
    ITK_TRY_EXPECT_EXCEPTION(roiTest<myRLEImage>(test));
    }
  else
    {
    ITK_TRY_EXPECT_NO_EXCEPTION(roiTest<myRLEImage>(test));
    }

  using outConverterType = itk::RegionOfInterestImageFilter<myRLEImage, ImageType>;
  typename outConverterType::Pointer outConv = outConverterType::New();
  outConv->SetInput(test);
  outConv->SetRegionOfInterest(test->GetLargestPossibleRegion());
  std::cout << "Converting RLEImage to regular image" << std::endl;
  outConv->Update();

  using WriterType = itk::ImageFileWriter< ImageType >;
  typename WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(outFilename);
  writer->SetInput(outConv->GetOutput());
  writer->SetUseCompression(true);
  std::cout << "Writing " << outFilename << std::endl;
  writer->Update();
  std::cout << "Test finished" << std::endl;

  return EXIT_SUCCESS;
}

void dimTest()
{
  using S2Type = itk::RLEImage<short, 2>; //2D
  using S3Type = itk::RLEImage<short, 3>; //3D
  S2Type::Pointer s2=S2Type::New();
  S3Type::Pointer s3=S3Type::New();

  //instantiation of "RoIType" is dissalowed due to different dimension
  //uncommenting the lines below should give a meaningful error message
  //using RoIType = itk::RegionOfInterestImageFilter<S3Type, S2Type>;
  //typename RoIType::Pointer roi = RoIType::New();
}

int itkRLEImageTest( int argc, char* argv[] )
{
  if( argc < 3 )
    {
    std::cerr << "Usage: " << argv[0] << " inputImage outputImage" << std::endl;
    return EXIT_FAILURE;
    }
  const char * inputImageFileName = argv[1];
  const char * outputImageFileName = argv[2];

  using ScalarPixelType = itk::ImageIOBase::IOComponentType;
  itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(
    inputImageFileName, itk::ImageIOFactory::FileModeType::ReadMode);
  if (!imageIO)
    {
    std::cerr << "Could not CreateImageIO for: " << inputImageFileName << std::endl;
    return EXIT_FAILURE;
    }
  imageIO->SetFileName(inputImageFileName);
  imageIO->ReadImageInformation();
  const ScalarPixelType pixelType = imageIO->GetComponentType();
  const size_t numDimensions = imageIO->GetNumberOfDimensions();

  try
    {
    //unused cases are not instantiated because they greatly increase compile time
    if (numDimensions==2 && pixelType == itk::ImageIOBase::UCHAR)
      {
      return doTest<itk::Image<unsigned char, 2> >(inputImageFileName, outputImageFileName);
      }
    if (numDimensions==3 && (pixelType == itk::ImageIOBase::SHORT
      || pixelType == itk::ImageIOBase::USHORT))
      {
      return doTest<itk::Image<short, 3> >(inputImageFileName, outputImageFileName);
      }
    if (numDimensions==3) //if not (u)short, then interpret as uint
      {
      return doTest<itk::Image<unsigned int, 3> >(inputImageFileName, outputImageFileName);
      }
    if (numDimensions==4 && pixelType == itk::ImageIOBase::UCHAR)
      {
      return doTest<itk::Image<unsigned char, 4> >(inputImageFileName, outputImageFileName);
      }

    std::cerr << "Unsupported image type:\n  Dimensions: " << numDimensions;
    std::cerr<< "\n  Pixel type:" << imageIO->GetComponentTypeAsString(pixelType) << std::endl;
    return EXIT_FAILURE;
    }
  catch( itk::ExceptionObject & error )
    {
    std::cerr << "Error: " << error << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<commit_msg>COMP: follow rename of ImageIOFactory FileModeType into FileModeEnum<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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 "itkRLEImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"
#include <cstdlib>
#include <string>

template <typename ImageType1, typename ImageType2>
void compare(itk::SmartPointer<ImageType1> im1, itk::SmartPointer<ImageType2> im2)
{
  itk::ImageRegionConstIterator<ImageType1> it1(im1, im1->GetLargestPossibleRegion());
  itk::ImageRegionConstIterator<ImageType2> it2(im2, im2->GetLargestPossibleRegion());
  while (!it1.IsAtEnd())
    {
    if (it1.Get() != it2.Get())
      {
      itkGenericExceptionMacro(<< "Images differ. Val1: "  << it1.Get() << "  Val2: " << it2.Get()
        << "\nInd1: " << it1.GetIndex() << "  Ind2: " << it2.GetIndex());
      }
    ++it1;
    ++it2;
    }
}

template <typename ImageType>
void roiTest(itk::SmartPointer<itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension> > orig)
{
  using myRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension>;
  using charRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension, char>;
  using charConverterType = itk::RegionOfInterestImageFilter<myRLEImage, charRLEImage>;
  typename charConverterType::Pointer cConv = charConverterType::New();
  cConv->SetInput(orig);
  cConv->SetRegionOfInterest(orig->GetLargestPossibleRegion());
  cConv->Update();
  typename charRLEImage::Pointer cIn = cConv->GetOutput();
  cIn->DisconnectPipeline();

  using ucharRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension, unsigned char>;
  using ucharConverterType = itk::RegionOfInterestImageFilter<myRLEImage, ucharRLEImage>;
  typename ucharConverterType::Pointer ucConv = ucharConverterType::New();
  ucConv->SetInput(orig);
  ucConv->SetRegionOfInterest(orig->GetLargestPossibleRegion());
  ucConv->Update();
  typename ucharRLEImage::Pointer ucIn = ucConv->GetOutput();
  ucIn->DisconnectPipeline();

  std::cout << "Comparing direct conversions...";
  compare(cIn, ucIn);
  std::cout << "OK" << std::endl;

  typename myRLEImage::RegionType reg = orig->GetLargestPossibleRegion();
  typename myRLEImage::RegionType rNeg = reg;
  for (unsigned i = 0; i < ImageType::ImageDimension; i++)
    {
    rNeg.SetIndex(i, -typename myRLEImage::IndexValueType(reg.GetSize(i)) * 3 / 4);
    }
  cIn->SetRegions(rNeg);
  ucIn->SetRegions(rNeg);
  std::cout << "Comparing LPR with negative indices...";
  compare(cIn, ucIn);
  std::cout << "OK" << std::endl;

  //region for partial coverage, skip X due to RLE representation constraints
  for (unsigned i = 1; i < ImageType::ImageDimension; i++)
    {
    reg.GetModifiableIndex()[i] += (reg.GetSize(i) - 1) / 4;
    rNeg.GetModifiableIndex()[i] += typename myRLEImage::IndexValueType(rNeg.GetSize(i) - 1) / 4;
    reg.SetSize(i, (reg.GetSize(i) + 1) / 2);
    rNeg.SetSize(i, (rNeg.GetSize(i) + 1) / 2);
    }

  using myConverterType = itk::RegionOfInterestImageFilter<myRLEImage, myRLEImage>;
  typename myConverterType::Pointer myConv = myConverterType::New();
  myConv->SetInput(orig);
  myConv->SetRegionOfInterest(reg);
  myConv->Update();
  typename myRLEImage::Pointer myIn = myConv->GetOutput();

  using cRoIType = itk::RegionOfInterestImageFilter<charRLEImage, charRLEImage>;
  typename cRoIType::Pointer cRoI = cRoIType::New();
  cRoI->SetInput(cIn);
  cRoI->SetRegionOfInterest(rNeg);
  cRoI->Update();
  cIn = cRoI->GetOutput();
  cIn->DisconnectPipeline();

  using ucRoIType = itk::RegionOfInterestImageFilter<ucharRLEImage, ucharRLEImage>;
  typename ucRoIType::Pointer ucRoI = ucRoIType::New();
  ucRoI->SetInput(ucIn);
  ucRoI->SetRegionOfInterest(rNeg);
  ucRoI->Update();
  ucIn = ucRoI->GetOutput();
  ucIn->DisconnectPipeline();

  std::cout << "Comparing RoIs with negative indices...";
  compare(cIn, ucIn);
  std::cout << "OK" << std::endl;

  std::cout << "Comparing RoIs with negative and positive indices...";
  compare(cIn, myIn);
  compare(ucIn, myIn);
  std::cout << "OK" << std::endl;
}

template <typename ImageType>
int doTest(std::string inFilename, std::string outFilename)
{
  using ReaderType = itk::ImageFileReader < ImageType >;
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(inFilename);
  std::cout << "Reading " << inFilename << std::endl;
  reader->Update();

  using myRLEImage = itk::RLEImage<typename ImageType::PixelType, ImageType::ImageDimension>;
  using inConverterType = itk::RegionOfInterestImageFilter<ImageType, myRLEImage>;
  typename inConverterType::Pointer inConv = inConverterType::New();
  inConv->SetInput(reader->GetOutput());
  inConv->SetRegionOfInterest(reader->GetOutput()->GetLargestPossibleRegion());
  std::cout << "Converting regular image to RLEImage" << std::endl;
  inConv->Update();
  typename myRLEImage::Pointer test = inConv->GetOutput();
  itk::SizeValueType xSize = test->GetLargestPossibleRegion().GetSize(0);

  std::cout << "Running region of interest tests" << std::endl;
  if (xSize > 127)
    {
    std::cout << "\n  xSize>127 (CHAR_MAX)" << std::endl;
    ITK_TRY_EXPECT_EXCEPTION(roiTest<myRLEImage>(test));
    }
  else
    {
    ITK_TRY_EXPECT_NO_EXCEPTION(roiTest<myRLEImage>(test));
    }

  using outConverterType = itk::RegionOfInterestImageFilter<myRLEImage, ImageType>;
  typename outConverterType::Pointer outConv = outConverterType::New();
  outConv->SetInput(test);
  outConv->SetRegionOfInterest(test->GetLargestPossibleRegion());
  std::cout << "Converting RLEImage to regular image" << std::endl;
  outConv->Update();

  using WriterType = itk::ImageFileWriter< ImageType >;
  typename WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(outFilename);
  writer->SetInput(outConv->GetOutput());
  writer->SetUseCompression(true);
  std::cout << "Writing " << outFilename << std::endl;
  writer->Update();
  std::cout << "Test finished" << std::endl;

  return EXIT_SUCCESS;
}

void dimTest()
{
  using S2Type = itk::RLEImage<short, 2>; //2D
  using S3Type = itk::RLEImage<short, 3>; //3D
  S2Type::Pointer s2=S2Type::New();
  S3Type::Pointer s3=S3Type::New();

  //instantiation of "RoIType" is dissalowed due to different dimension
  //uncommenting the lines below should give a meaningful error message
  //using RoIType = itk::RegionOfInterestImageFilter<S3Type, S2Type>;
  //typename RoIType::Pointer roi = RoIType::New();
}

int itkRLEImageTest( int argc, char* argv[] )
{
  if( argc < 3 )
    {
    std::cerr << "Usage: " << argv[0] << " inputImage outputImage" << std::endl;
    return EXIT_FAILURE;
    }
  const char * inputImageFileName = argv[1];
  const char * outputImageFileName = argv[2];

  using ScalarPixelType = itk::ImageIOBase::IOComponentType;
  itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(
    inputImageFileName, itk::ImageIOFactory::FileModeEnum::ReadMode);
  if (!imageIO)
    {
    std::cerr << "Could not CreateImageIO for: " << inputImageFileName << std::endl;
    return EXIT_FAILURE;
    }
  imageIO->SetFileName(inputImageFileName);
  imageIO->ReadImageInformation();
  const ScalarPixelType pixelType = imageIO->GetComponentType();
  const size_t numDimensions = imageIO->GetNumberOfDimensions();

  try
    {
    //unused cases are not instantiated because they greatly increase compile time
    if (numDimensions==2 && pixelType == itk::ImageIOBase::UCHAR)
      {
      return doTest<itk::Image<unsigned char, 2> >(inputImageFileName, outputImageFileName);
      }
    if (numDimensions==3 && (pixelType == itk::ImageIOBase::SHORT
      || pixelType == itk::ImageIOBase::USHORT))
      {
      return doTest<itk::Image<short, 3> >(inputImageFileName, outputImageFileName);
      }
    if (numDimensions==3) //if not (u)short, then interpret as uint
      {
      return doTest<itk::Image<unsigned int, 3> >(inputImageFileName, outputImageFileName);
      }
    if (numDimensions==4 && pixelType == itk::ImageIOBase::UCHAR)
      {
      return doTest<itk::Image<unsigned char, 4> >(inputImageFileName, outputImageFileName);
      }

    std::cerr << "Unsupported image type:\n  Dimensions: " << numDimensions;
    std::cerr<< "\n  Pixel type:" << imageIO->GetComponentTypeAsString(pixelType) << std::endl;
    return EXIT_FAILURE;
    }
  catch( itk::ExceptionObject & error )
    {
    std::cerr << "Error: " << error << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>[DF][NFC] Add npartitions kwarg to RDF docs<commit_after><|endoftext|>


<commit_before><commit_msg>[tree] Fix memory leak in TTreeCacheUnzip #7429<commit_after><|endoftext|>


<commit_before>/*
    This file is part of the KDE alarm daemon.
    Copyright (c) 1997-1999 Preston Brown
    Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>
    Copyright (c) 2001 David Jarvie <software@astrojar.org.uk>

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

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

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

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

// $Id$
//
// KOrganizer/KAlarm alarm daemon main program
//

#include <stdlib.h>
#include <kdebug.h>

#include <klocale.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>

#include "alarmapp.h"

static const char* kalarmdVersion = "3.1";
static const KCmdLineOptions options[] =
{
   { "login", I18N_NOOP("Application is being auto-started at KDE session start"), 0L },
   { 0L, 0L, 0L }
};

int main(int argc, char **argv)
{
  KAboutData aboutData("kalarmd", I18N_NOOP("Alarm Daemon"),
      kalarmdVersion, I18N_NOOP("KOrganizer/KAlarm Alarm Daemon"), KAboutData::License_GPL,
      "(c) 1997-1999 Preston Brown\n(c) 2000-2001 Cornelius Schumacher\n(c) 2001 David Jarvie", 0L,
      "http://korganizer.kde.org");
  aboutData.addAuthor("Cornelius Schumacher",I18N_NOOP("Maintainer"),
                      "schumacher@kde.org");
  aboutData.addAuthor("David Jarvie",I18N_NOOP("KAlarm Author"),
                      "software@astrojar.org.uk");
  aboutData.addAuthor("Preston Brown",I18N_NOOP("Original Author"),
                      "pbrown@kde.org");

  KCmdLineArgs::init(argc,argv,&aboutData);
  KCmdLineArgs::addCmdLineOptions(options);
  KUniqueApplication::addCmdLineOptions();

  if (!AlarmApp::start())
    exit(0);

  AlarmApp app;

  return app.exec();
}
<commit_msg>Update version number to 3.2<commit_after>/*
    This file is part of the KDE alarm daemon.
    Copyright (c) 1997-1999 Preston Brown
    Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>
    Copyright (c) 2001 David Jarvie <software@astrojar.org.uk>

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

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

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

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

// $Id$
//
// KOrganizer/KAlarm alarm daemon main program
//

#include <stdlib.h>
#include <kdebug.h>

#include <klocale.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>

#include "alarmapp.h"

static const char* kalarmdVersion = "3.2";
static const KCmdLineOptions options[] =
{
   { "login", I18N_NOOP("Application is being auto-started at KDE session start"), 0L },
   { 0L, 0L, 0L }
};

int main(int argc, char **argv)
{
  KAboutData aboutData("kalarmd", I18N_NOOP("Alarm Daemon"),
      kalarmdVersion, I18N_NOOP("KOrganizer/KAlarm Alarm Daemon"), KAboutData::License_GPL,
      "(c) 1997-1999 Preston Brown\n(c) 2000-2001 Cornelius Schumacher\n(c) 2001 David Jarvie", 0L,
      "http://korganizer.kde.org");
  aboutData.addAuthor("Cornelius Schumacher",I18N_NOOP("Maintainer"),
                      "schumacher@kde.org");
  aboutData.addAuthor("David Jarvie",I18N_NOOP("KAlarm Author"),
                      "software@astrojar.org.uk");
  aboutData.addAuthor("Preston Brown",I18N_NOOP("Original Author"),
                      "pbrown@kde.org");

  KCmdLineArgs::init(argc,argv,&aboutData);
  KCmdLineArgs::addCmdLineOptions(options);
  KUniqueApplication::addCmdLineOptions();

  if (!AlarmApp::start())
    exit(0);

  AlarmApp app;

  return app.exec();
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "Lex.h"
#include "JZFileUtil.h"
#include <string.h>

TEST(LexUtil, eraseLineSeperator){
  //these cases are a little complex in input because they are full of special charactor.

  //don't remove \n if it doesn't have "\"
  const char* input0 = "this is a test!\n this is a test";
  uint64 bufSize0 = strlen(input0);
  const char* eraseRet0 = LexUtil::eraseLineSeperator((const char*)input0, &bufSize0);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet0);

  //remove \ \n if it has a \ at the end of line
  const char* input1 = "this is a test!\\ \n this is a test";
  uint64 bufSize1 = strlen(input1);
  const char* eraseRet1 = LexUtil::eraseLineSeperator((const char*)input1, &bufSize1);
  ASSERT_STREQ("this is a test! this is a test", eraseRet1);

  //remove \ \n if it has a \ at the end of line event if it's inside the ""
  const char* input2 = "\"this is a test!\\ \n this is a test\"";
  uint64 bufSize2 = strlen(input2);
  const char* eraseRet2 = LexUtil::eraseLineSeperator((const char*)input2, &bufSize2);
  ASSERT_STREQ("\"this is a test! this is a test\"", eraseRet2);

  //don't remove \ \n if it is escaped by a \ before the last one
  const char* input3 = "\"this is a test!\\\\ \n this is a test\"";
  uint64 bufSize3 = strlen(input3);
  const char* eraseRet3 = LexUtil::eraseLineSeperator((const char*)input3, &bufSize3);
  ASSERT_STREQ("\"this is a test!\\\\ \n this is a test\"", eraseRet3);

  //remove \ \n even if it is inside a comment
  const char* input4 = "//this is a test!\\ \n this is a test";
  uint64 bufSize4 = strlen(input4);
  const char* eraseRet4 = LexUtil::eraseLineSeperator((const char*)input4, &bufSize4);
  ASSERT_STREQ("//this is a test! this is a test", eraseRet4);
}

TEST(LexUtil, eraseComment){
  //erase the comment until the end of line
  const char* input0 = "this is a test!\n this is a test// this is a comment";
  uint64 bufSize0 = strlen(input0);
  const char* eraseRet0 = LexUtil::eraseComment((const char*)input0, &bufSize0);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet0);

  const char* input1 = "this is a test!\n this is a test/* this is a comment*/";
  uint64 bufSize1 = strlen(input1);
  const char* eraseRet1 = LexUtil::eraseComment((const char*)input1, &bufSize1);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet1);

  const char* input2 = "this is a test!\n this is a test// this is a comment\nthis is a new line";
  uint64 bufSize2 = strlen(input2);
  const char* eraseRet2 = LexUtil::eraseComment((const char*)input2, &bufSize2);
  ASSERT_STREQ("this is a test!\n this is a test\nthis is a new line", eraseRet2);

  const char* input3 = "this is a test!\n this /*this is a comment*/is a test";
  uint64 bufSize3 = strlen(input3);
  const char* eraseRet3 = LexUtil::eraseComment((const char*)input3, &bufSize3);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet3);

  const char* input4 = "this is a test!\n this is a test\n\"//don't erase this comment\"";
  uint64 bufSize4 = strlen(input4);
  const char* eraseRet4 = LexUtil::eraseComment((const char*)input4, &bufSize4);
  ASSERT_STREQ("this is a test!\n this is a test\n\"//don't erase this comment\"", eraseRet4);
}

TEST(LexUtil, smallTestCase){
  EXPECT_EQ(true, LexUtil::isLineEnder('\n'));
  EXPECT_EQ(false, LexUtil::isLineEnder('\t'));

  EXPECT_EQ(true, LexUtil::isEmptyInput('\t'));
  EXPECT_EQ(true, LexUtil::isEmptyInput('\n'));
  EXPECT_EQ(true, LexUtil::isEmptyInput(' '));
  EXPECT_EQ(false, LexUtil::isEmptyInput('.'));

  EXPECT_EQ(true, LexUtil::isBackSlant('\\'));
  EXPECT_EQ(false, LexUtil::isBackSlant('/'));

  EXPECT_EQ(true, LexUtil::isEmptyInput("\t    \n   "));
  EXPECT_EQ(false, LexUtil::isEmptyInput("    a   \n \t"));

  EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\      \n"));
  EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\\t\n"));
  EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\\t \n"));
  EXPECT_EQ(false, LexUtil::isEndWithBackSlant("\\n      \n"));

  EXPECT_EQ('\'', LexUtil::seperatorMatcher('\''));
  EXPECT_EQ('\"', LexUtil::seperatorMatcher('\"'));
  EXPECT_EQ('}', LexUtil::seperatorMatcher('{'));
  EXPECT_EQ(']', LexUtil::seperatorMatcher('['));
  EXPECT_EQ(')', LexUtil::seperatorMatcher('('));

  EXPECT_EQ(true, LexUtil::isConstNumberChar('0'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('1'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('2'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('3'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('4'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('5'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('6'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('7'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('8'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('9'));
  EXPECT_EQ(false, LexUtil::isConstNumberChar('.'));
  EXPECT_EQ(false, LexUtil::isConstNumberChar('-'));
  EXPECT_EQ(false, LexUtil::isConstNumberChar('+'));
  EXPECT_EQ(false, LexUtil::isConstNumberChar('='));

  ASSERT_STREQ("abce", LexUtil::eatLREmptyInput("  abce   ").c_str());
  ASSERT_STREQ("", LexUtil::eatLREmptyInput("  \t\n ").c_str());
  ASSERT_STREQ("abce", LexUtil::eatLREmptyInput("abce   ").c_str());
  ASSERT_STREQ("abce", LexUtil::eatLREmptyInput("  abce").c_str());

  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("if"));
  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("ifdef"));
  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("ifndef"));
  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("endif"));
  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("else"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("define"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("param"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("include"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("once"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("warning"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("error"));
}
<commit_msg>add more test case on comment<commit_after>#include <gtest/gtest.h>
#include "Lex.h"
#include "JZFileUtil.h"
#include <string.h>
#include "JZMacroFunc.h"

TEST(LexUtil, eraseLineSeperator){
  //these cases are a little complex in input because they are full of special charactor.

  //don't remove \n if it doesn't have "\"
  const char* input0 = "this is a test!\n this is a test";
  uint64 bufSize0 = strlen(input0);
  const char* eraseRet0 = LexUtil::eraseLineSeperator((const char*)input0, &bufSize0);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet0);

  //remove \ \n if it has a \ at the end of line
  const char* input1 = "this is a test!\\ \n this is a test";
  uint64 bufSize1 = strlen(input1);
  const char* eraseRet1 = LexUtil::eraseLineSeperator((const char*)input1, &bufSize1);
  ASSERT_STREQ("this is a test! this is a test", eraseRet1);

  //remove \ \n if it has a \ at the end of line event if it's inside the ""
  const char* input2 = "\"this is a test!\\ \n this is a test\"";
  uint64 bufSize2 = strlen(input2);
  const char* eraseRet2 = LexUtil::eraseLineSeperator((const char*)input2, &bufSize2);
  ASSERT_STREQ("\"this is a test! this is a test\"", eraseRet2);

  //don't remove \ \n if it is escaped by a \ before the last one
  const char* input3 = "\"this is a test!\\\\ \n this is a test\"";
  uint64 bufSize3 = strlen(input3);
  const char* eraseRet3 = LexUtil::eraseLineSeperator((const char*)input3, &bufSize3);
  ASSERT_STREQ("\"this is a test!\\\\ \n this is a test\"", eraseRet3);

  //remove \ \n even if it is inside a comment
  const char* input4 = "//this is a test!\\ \n this is a test";
  uint64 bufSize4 = strlen(input4);
  const char* eraseRet4 = LexUtil::eraseLineSeperator((const char*)input4, &bufSize4);
  ASSERT_STREQ("//this is a test! this is a test", eraseRet4);

  JZSAFE_DELETE(eraseRet0);
  JZSAFE_DELETE(eraseRet1);
  JZSAFE_DELETE(eraseRet2);
  JZSAFE_DELETE(eraseRet3);
  JZSAFE_DELETE(eraseRet4);
}

TEST(LexUtil, eraseComment){
  //erase the comment until the end of line
  const char* input0 = "this is a test!\n this is a test// this is a comment";
  uint64 bufSize0 = strlen(input0);
  const char* eraseRet0 = LexUtil::eraseComment((const char*)input0, &bufSize0);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet0);

  //erase the /*abc*/ comment
  const char* input1 = "this is a test!\n this is a test/* this is a comment*/";
  uint64 bufSize1 = strlen(input1);
  const char* eraseRet1 = LexUtil::eraseComment((const char*)input1, &bufSize1);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet1);

  //do not erase the \n and next line
  const char* input2 = "this is a test!\n this is a test// this is a comment\nthis is a new line";
  uint64 bufSize2 = strlen(input2);
  const char* eraseRet2 = LexUtil::eraseComment((const char*)input2, &bufSize2);
  ASSERT_STREQ("this is a test!\n this is a test\nthis is a new line", eraseRet2);

  // the /**/ comment should not effect the input
  const char* input3 = "this is a test!\n this /*this is a comment*/is a test";
  uint64 bufSize3 = strlen(input3);
  const char* eraseRet3 = LexUtil::eraseComment((const char*)input3, &bufSize3);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet3);

  //comment is disabled in string
  const char* input4 = "this is a test!\n this is a test\n\"//don't erase this comment\"";
  uint64 bufSize4 = strlen(input4);
  const char* eraseRet4 = LexUtil::eraseComment((const char*)input4, &bufSize4);
  ASSERT_STREQ("this is a test!\n this is a test\n\"//don't erase this comment\"", eraseRet4);

  //comment is disabled in string
  const char* input5 = "this is a test!\n this is a test\n\"/*don't erase this comment*/\"";
  uint64 bufSize5 = strlen(input5);
  const char* eraseRet5 = LexUtil::eraseComment((const char*)input5, &bufSize5);
  ASSERT_STREQ("this is a test!\n this is a test\n\"/*don't erase this comment*/\"", eraseRet5);

  //erase the comment with "
  const char* input6 = "this is a test!\n this is a test// this is a comment//\"this is a comment with \"\"";
  uint64 bufSize6 = strlen(input6);
  const char* eraseRet6 = LexUtil::eraseComment((const char*)input6, &bufSize6);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet6);

  //erasee the comment with "
  const char* input7 = "this is a test!\n /*\"this is a comment inside\"*/this is a test// this is a comment";
  uint64 bufSize7 = strlen(input7);
  const char* eraseRet7 = LexUtil::eraseComment((const char*)input7, &bufSize7);
  ASSERT_STREQ("this is a test!\n this is a test", eraseRet7);

  JZSAFE_DELETE(eraseRet0);
  JZSAFE_DELETE(eraseRet1);
  JZSAFE_DELETE(eraseRet2);
  JZSAFE_DELETE(eraseRet3);
  JZSAFE_DELETE(eraseRet4);
  JZSAFE_DELETE(eraseRet5);
  JZSAFE_DELETE(eraseRet6);
  JZSAFE_DELETE(eraseRet7);
//  JZSAFE_DELETE(eraseRet8);
//  JZSAFE_DELETE(eraseRet9);
}

TEST(LexUtil, smallTestCase){
  EXPECT_EQ(true, LexUtil::isLineEnder('\n'));
  EXPECT_EQ(false, LexUtil::isLineEnder('\t'));

  EXPECT_EQ(true, LexUtil::isEmptyInput('\t'));
  EXPECT_EQ(true, LexUtil::isEmptyInput('\n'));
  EXPECT_EQ(true, LexUtil::isEmptyInput(' '));
  EXPECT_EQ(false, LexUtil::isEmptyInput('.'));

  EXPECT_EQ(true, LexUtil::isBackSlant('\\'));
  EXPECT_EQ(false, LexUtil::isBackSlant('/'));

  EXPECT_EQ(true, LexUtil::isEmptyInput("\t    \n   "));
  EXPECT_EQ(false, LexUtil::isEmptyInput("    a   \n \t"));

  EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\      \n"));
  EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\\t\n"));
  EXPECT_EQ(true, LexUtil::isEndWithBackSlant("\\\t \n"));
  EXPECT_EQ(false, LexUtil::isEndWithBackSlant("\\n      \n"));

  EXPECT_EQ('\'', LexUtil::seperatorMatcher('\''));
  EXPECT_EQ('\"', LexUtil::seperatorMatcher('\"'));
  EXPECT_EQ('}', LexUtil::seperatorMatcher('{'));
  EXPECT_EQ(']', LexUtil::seperatorMatcher('['));
  EXPECT_EQ(')', LexUtil::seperatorMatcher('('));

  EXPECT_EQ(true, LexUtil::isConstNumberChar('0'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('1'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('2'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('3'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('4'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('5'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('6'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('7'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('8'));
  EXPECT_EQ(true, LexUtil::isConstNumberChar('9'));
  EXPECT_EQ(false, LexUtil::isConstNumberChar('.'));
  EXPECT_EQ(false, LexUtil::isConstNumberChar('-'));
  EXPECT_EQ(false, LexUtil::isConstNumberChar('+'));
  EXPECT_EQ(false, LexUtil::isConstNumberChar('='));

  ASSERT_STREQ("abce", LexUtil::eatLREmptyInput("  abce   ").c_str());
  ASSERT_STREQ("", LexUtil::eatLREmptyInput("  \t\n ").c_str());
  ASSERT_STREQ("abce", LexUtil::eatLREmptyInput("abce   ").c_str());
  ASSERT_STREQ("abce", LexUtil::eatLREmptyInput("  abce").c_str());

  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("if"));
  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("ifdef"));
  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("ifndef"));
  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("endif"));
  EXPECT_EQ(false, LexUtil::ignoreMacroWhenStreamIsOff("else"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("define"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("param"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("include"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("once"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("warning"));
  EXPECT_EQ(true, LexUtil::ignoreMacroWhenStreamIsOff("error"));
}
<|endoftext|>


<commit_before>/*
 @ 0xCCCCCCCC
*/

#include "kbase/pickle.h"

#include <algorithm>

#include "kbase/string_util.h"

namespace {

// Rounds up `num` to the nearest multiple of `factor`.
constexpr size_t RoundToMultiple(size_t num, size_t factor)
{
    return factor == 0 ? 0 : (num - 1 - (num - 1) % factor + factor);
}

// Zeros padding memory; otherwise some memory detectors may complain about
// uninitialized memory.
void SanitizePadding(byte* padding_begin, size_t padding_size)
{
    if (padding_size != 0) {
        memset(padding_begin, 0, padding_size);
    }
}

}   // namespace

namespace kbase {

PickleReader::PickleReader(const void* pickled_data, size_t size_in_bytes)
    : read_ptr_(static_cast<const byte*>(pickled_data) + sizeof(Pickle::Header)),
      data_end_(read_ptr_ + size_in_bytes - sizeof(Pickle::Header))
{}

PickleReader::PickleReader(const Pickle& pickle)
    : read_ptr_(pickle.payload()),
      data_end_(pickle.end_of_payload())
{}

PickleReader& PickleReader::operator>>(std::string& value)
{
    PickleReader& reader = *this;
    size_t length;
    reader >> length;
    auto* dest = WriteInto(value, length + 1);
    Read(dest, sizeof(std::string::value_type) * length);
    return reader;
}

PickleReader& PickleReader::operator>>(std::wstring& value)
{
    PickleReader& reader = *this;
    size_t length;
    reader >> length;
    auto* dest = WriteInto(value, length + 1);
    Read(dest, sizeof(std::wstring::value_type) * length);
    return reader;
}

void PickleReader::Read(void* dest, size_t size_in_bytes)
{
    ENSURE(CHECK, !!*this).Require();
    memcpy_s(dest, size_in_bytes, read_ptr_, size_in_bytes);
    SeekReadPosition(size_in_bytes);
}

void PickleReader::SeekReadPosition(size_t data_size) noexcept
{
    size_t rounded_size = RoundToMultiple(data_size, sizeof(uint32_t));
    if (read_ptr_ + rounded_size > data_end_) {
        read_ptr_ += data_size;
    } else {
        read_ptr_ += rounded_size;
    }
}

void PickleReader::SkipData(size_t data_size) noexcept
{
    SeekReadPosition(data_size);
}

// -*- Pickle -*-

Pickle::Pickle()
    : header_(nullptr), capacity_(0)
{
    ResizeCapacity(kCapacityUnit);
    header_->payload_size = 0;
}

Pickle::Pickle(const void* data, size_t size_in_bytes)
    : header_(nullptr), capacity_(0)
{
    ENSURE(CHECK, data != nullptr && size_in_bytes > 0).Require();
    ResizeCapacity(size_in_bytes);
    memcpy_s(header_, capacity_, data, size_in_bytes);
}

Pickle::Pickle(const Pickle& other)
    : header_(nullptr), capacity_(0)
{
    ResizeCapacity(other.size());
    memcpy_s(header_, capacity_, other.header_, other.size());
}

Pickle::Pickle(Pickle&& other) noexcept
    : header_(other.header_), capacity_(other.capacity_)
{
    other.header_ = nullptr;
    other.capacity_ = 0;
}

Pickle::~Pickle()
{
    // Technically, only pickles having been moved have null header.
    if (header_ != nullptr) {
        free(header_);
    }
}

Pickle& Pickle::operator=(const Pickle& rhs)
{
    if (this != &rhs) {
        if (capacity_ < rhs.size()) {
            ResizeCapacity(rhs.size());
        }

        memcpy_s(header_, capacity_, rhs.header_, rhs.size());
    }

    return *this;
}

Pickle& Pickle::operator=(Pickle&& rhs) noexcept
{
    if (this != &rhs) {
        Header* old_header = header_;

        header_ = rhs.header_;
        capacity_ = rhs.capacity_;
        rhs.header_ = nullptr;
        rhs.capacity_ = 0;

        free(old_header);
    }

    return *this;
}

void Pickle::ResizeCapacity(size_t new_capacity)
{
    ENSURE(CHECK, new_capacity > capacity_).Require();

    new_capacity = RoundToMultiple(new_capacity, kCapacityUnit);
    void* ptr = realloc(header_, new_capacity);

    ENSURE(RAISE, ptr != nullptr).Require("Failed to realloc a new memory block!");
    header_ = static_cast<Header*>(ptr);
    capacity_ = new_capacity;
}

Pickle& Pickle::operator<<(const std::string& value)
{
    Pickle& pickle = *this;
    auto length = value.length();
    pickle << length;
    Write(value.data(), length * sizeof(char));
    return pickle;
}

Pickle& Pickle::operator<<(const std::wstring& value)
{
    Pickle& pickle = *this;
    auto length = value.length();
    pickle << length;
    Write(value.data(), length * sizeof(wchar_t));
    return pickle;
}

void Pickle::Write(const void* data, size_t size_in_bytes)
{
    size_t last_payload_size = payload_size();
    byte* dest = SeekWritePosition(size_in_bytes);
    size_t free_buf_size = capacity_ - (dest - reinterpret_cast<byte*>(header_));
    memcpy_s(dest, free_buf_size, data, size_in_bytes);
    size_t padding_size = payload_size() - last_payload_size - size_in_bytes;
    SanitizePadding(dest - padding_size, padding_size);
}

byte* Pickle::SeekWritePosition(size_t length)
{
    // Writing starts at a uint32-aligned offset.
    size_t offset = RoundToMultiple(header_->payload_size, sizeof(uint32_t));
    size_t required_size = offset + length;
    size_t required_total_size = required_size + sizeof(Header);

    if (required_total_size > capacity_) {
        ResizeCapacity(std::max(capacity_ << 1, required_total_size));
    }

    ENSURE(CHECK, required_size <= std::numeric_limits<uint32_t>::max())(required_size).Require();
    header_->payload_size = static_cast<uint32_t>(required_size);

    return mutable_payload() + offset;
}

}   // namespace kbase<commit_msg>Pickle: Fix the bug that couldn't de-serialize an empty std::string correctly.<commit_after>/*
 @ 0xCCCCCCCC
*/

#include "kbase/pickle.h"

#include <algorithm>

#include "kbase/string_util.h"

namespace {

// Rounds up `num` to the nearest multiple of `factor`.
constexpr size_t RoundToMultiple(size_t num, size_t factor)
{
    return factor == 0 ? 0 : (num - 1 - (num - 1) % factor + factor);
}

// Zeros padding memory; otherwise some memory detectors may complain about
// uninitialized memory.
void SanitizePadding(byte* padding_begin, size_t padding_size)
{
    if (padding_size != 0) {
        memset(padding_begin, 0, padding_size);
    }
}

}   // namespace

namespace kbase {

PickleReader::PickleReader(const void* pickled_data, size_t size_in_bytes)
    : read_ptr_(static_cast<const byte*>(pickled_data) + sizeof(Pickle::Header)),
      data_end_(read_ptr_ + size_in_bytes - sizeof(Pickle::Header))
{}

PickleReader::PickleReader(const Pickle& pickle)
    : read_ptr_(pickle.payload()),
      data_end_(pickle.end_of_payload())
{}

PickleReader& PickleReader::operator>>(std::string& value)
{
    PickleReader& reader = *this;
    size_t length;
    reader >> length;
	if (length != 0) {
		auto* dest = WriteInto(value, length + 1);
		Read(dest, sizeof(std::string::value_type) * length);
	}

    return reader;
}

PickleReader& PickleReader::operator>>(std::wstring& value)
{
    PickleReader& reader = *this;
    size_t length;
    reader >> length;
	if (length != 0) {
		auto* dest = WriteInto(value, length + 1);
		Read(dest, sizeof(std::wstring::value_type) * length);
	}

    return reader;
}

void PickleReader::Read(void* dest, size_t size_in_bytes)
{
    ENSURE(CHECK, !!*this).Require();
    memcpy_s(dest, size_in_bytes, read_ptr_, size_in_bytes);
    SeekReadPosition(size_in_bytes);
}

void PickleReader::SeekReadPosition(size_t data_size) noexcept
{
    size_t rounded_size = RoundToMultiple(data_size, sizeof(uint32_t));
    if (read_ptr_ + rounded_size > data_end_) {
        read_ptr_ += data_size;
    } else {
        read_ptr_ += rounded_size;
    }
}

void PickleReader::SkipData(size_t data_size) noexcept
{
    SeekReadPosition(data_size);
}

// -*- Pickle -*-

Pickle::Pickle()
    : header_(nullptr), capacity_(0)
{
    ResizeCapacity(kCapacityUnit);
    header_->payload_size = 0;
}

Pickle::Pickle(const void* data, size_t size_in_bytes)
    : header_(nullptr), capacity_(0)
{
    ENSURE(CHECK, data != nullptr && size_in_bytes > 0).Require();
    ResizeCapacity(size_in_bytes);
    memcpy_s(header_, capacity_, data, size_in_bytes);
}

Pickle::Pickle(const Pickle& other)
    : header_(nullptr), capacity_(0)
{
    ResizeCapacity(other.size());
    memcpy_s(header_, capacity_, other.header_, other.size());
}

Pickle::Pickle(Pickle&& other) noexcept
    : header_(other.header_), capacity_(other.capacity_)
{
    other.header_ = nullptr;
    other.capacity_ = 0;
}

Pickle::~Pickle()
{
    // Technically, only pickles having been moved have null header.
    if (header_ != nullptr) {
        free(header_);
    }
}

Pickle& Pickle::operator=(const Pickle& rhs)
{
    if (this != &rhs) {
        if (capacity_ < rhs.size()) {
            ResizeCapacity(rhs.size());
        }

        memcpy_s(header_, capacity_, rhs.header_, rhs.size());
    }

    return *this;
}

Pickle& Pickle::operator=(Pickle&& rhs) noexcept
{
    if (this != &rhs) {
        Header* old_header = header_;

        header_ = rhs.header_;
        capacity_ = rhs.capacity_;
        rhs.header_ = nullptr;
        rhs.capacity_ = 0;

        free(old_header);
    }

    return *this;
}

void Pickle::ResizeCapacity(size_t new_capacity)
{
    ENSURE(CHECK, new_capacity > capacity_).Require();

    new_capacity = RoundToMultiple(new_capacity, kCapacityUnit);
    void* ptr = realloc(header_, new_capacity);

    ENSURE(RAISE, ptr != nullptr).Require("Failed to realloc a new memory block!");
    header_ = static_cast<Header*>(ptr);
    capacity_ = new_capacity;
}

Pickle& Pickle::operator<<(const std::string& value)
{
    Pickle& pickle = *this;
    auto length = value.length();
    pickle << length;
    Write(value.data(), length * sizeof(char));
    return pickle;
}

Pickle& Pickle::operator<<(const std::wstring& value)
{
    Pickle& pickle = *this;
    auto length = value.length();
    pickle << length;
    Write(value.data(), length * sizeof(wchar_t));
    return pickle;
}

void Pickle::Write(const void* data, size_t size_in_bytes)
{
    size_t last_payload_size = payload_size();
    byte* dest = SeekWritePosition(size_in_bytes);
    size_t free_buf_size = capacity_ - (dest - reinterpret_cast<byte*>(header_));
    memcpy_s(dest, free_buf_size, data, size_in_bytes);
    size_t padding_size = payload_size() - last_payload_size - size_in_bytes;
    SanitizePadding(dest - padding_size, padding_size);
}

byte* Pickle::SeekWritePosition(size_t length)
{
    // Writing starts at a uint32-aligned offset.
    size_t offset = RoundToMultiple(header_->payload_size, sizeof(uint32_t));
    size_t required_size = offset + length;
    size_t required_total_size = required_size + sizeof(Header);

    if (required_total_size > capacity_) {
        ResizeCapacity(std::max(capacity_ << 1, required_total_size));
    }

    ENSURE(CHECK, required_size <= std::numeric_limits<uint32_t>::max())(required_size).Require();
    header_->payload_size = static_cast<uint32_t>(required_size);

    return mutable_payload() + offset;
}

}   // namespace kbase<|endoftext|>


<commit_before>/**
* @file FDTD_1D.cpp
* @brief Implementation of the FDTD_1D class
* @author Ben Frazier
* @date 08/12/2017 */

#include "FDTD_1D.h"
#include <math.h>

namespace CEM
{

 /** \brief FDTD_1D Overloaded Constructor
 *
 *  Standard Constructor
 */
  FDTD_1D::FDTD_1D(InputDataInterface * input):
    initialized(false),
    ABC(SimpleABC),
    imp_(377.0),
    dataSize_(0)
  {
    InitializeEngine(input);
  }

  /**
   * \brief Initialize the FDTD_1D engine
   *
   * This function sets the size of the E and H vectors
   * @param input The input structure read in from the input file*/
  void FDTD_1D::InitializeEngine(InputDataInterface * input)
  {

    dataSize_ = input->getVectorLength();

    ABC = SimpleABC;

    H.resize(dataSize_);
    E.resize(dataSize_);

    sourceAmplitude_ = input->getSourceAmplitude();
    sourceType_ = input->getSourceType();
    pulseWidth_ = input->getPulseWidth();
    sourceDelay_ = input->getSourceDelay();
    sourceIndex_ = input->getSpatialIndex();

    pulseWidth2_ = pulseWidth_*pulseWidth_;

    initialized = true;
  }

  /**
   * \brief Update the E and H fields
   *
   * This function updates the E and H fields by stepping to the specified time index
   * @param time The next time step to update*/
  void FDTD_1D::UpdateFields(double time)
  {
    applyBC_H();

    //update the H Field
    for (int mm = 0; mm < dataSize_ - 1; mm++)
      H[mm] = H[mm] + (E[mm + 1] - E[mm]) / imp_;

    //correct H field --> TFSF
    H[sourceIndex_ -1] -= computeSourceAmplitude(time,0)/imp_;

    applyBC_E();

    //Now update the E Field
    for (int mm = 1; mm < dataSize_; mm++)
      E[mm] = E[mm] + (H[mm] - H[mm - 1]) * imp_;

    //update the source
    E[sourceIndex_] += computeSourceAmplitude(time,1.0);
  }

   /**
   * \brief Compute the amplitude of the source
   *
   * @param time The time to compute the source
  * @param shift The value to shift the time (TFSF)*/
  double FDTD_1D::computeSourceAmplitude(double time, double shift)
  {
    double val = sourceAmplitude_ *exp(-(time - sourceDelay_ + shift) * (time - sourceDelay_ + shift) / pulseWidth2_);
    return val;
  }

  /**
   * \brief Return the E field at a specified index
   *
   * This function gets the E field at a given index and returns 0 if the requested
   * index exceeds the size of the array
   * @param index The index of the E field to retrieve*/
  double FDTD_1D::getEField(int index)
  {
    if (index < dataSize_)
      return E[index];
    else
      return 0;
  }

  /**
   * \brief Return the H field at a specified index
   *
   * This function gets the H field at a given index and returns 0 if the requested
   * index exceeds the size of the array
   * @param index The index of the H field to retrieve*/
  double FDTD_1D::getHField(int index)
  {
    if (index < dataSize_)
      return H[index];
    else
      return 0;
  }

  void FDTD_1D::simpleABC_E()
  {
    E[0] = E[1];
  }

  void FDTD_1D::simpleABC_H()
  {
    H[dataSize_-1] = H[dataSize_-2];
  }

  void FDTD_1D::applyBC_E()
  {
    switch (ABC)
      {
      case NoABC:
	break;

      case SimpleABC:
	simpleABC_E();
	break;

      case TFSF_ABC:
	break;
      default:
	break;
      }
  }

  void FDTD_1D::applyBC_H()
  {
    switch (ABC)
      {
      case NoABC:
	break;

      case SimpleABC:
	simpleABC_H();
	break;

      case TFSF_ABC:
	break;
      default:
	break;
      }
  }

}//end of namespace
<commit_msg>FDTD now initializes the impedance from the namespace constant<commit_after>/**
* @file FDTD_1D.cpp
* @brief Implementation of the FDTD_1D class
* @author Ben Frazier
* @date 08/12/2017 */

#include "FDTD_1D.h"
#include <math.h>
#include "CEMdefs.h"

namespace CEM
{

 /** \brief FDTD_1D Overloaded Constructor
 *
 *  Standard Constructor
 */
  FDTD_1D::FDTD_1D(InputDataInterface * input):
    initialized(false),
    ABC(SimpleABC),
    imp_(CEM::imp0),
    dataSize_(0)
  {
    InitializeEngine(input);
  }

  /**
   * \brief Initialize the FDTD_1D engine
   *
   * This function sets the size of the E and H vectors
   * @param input The input structure read in from the input file*/
  void FDTD_1D::InitializeEngine(InputDataInterface * input)
  {

    dataSize_ = input->getVectorLength();

    ABC = SimpleABC;

    H.resize(dataSize_);
    E.resize(dataSize_);

    sourceAmplitude_ = input->getSourceAmplitude();
    sourceType_ = input->getSourceType();
    pulseWidth_ = input->getPulseWidth();
    sourceDelay_ = input->getSourceDelay();
    sourceIndex_ = input->getSpatialIndex();

    pulseWidth2_ = pulseWidth_*pulseWidth_;

    initialized = true;
  }

  /**
   * \brief Update the E and H fields
   *
   * This function updates the E and H fields by stepping to the specified time index
   * @param time The next time step to update*/
  void FDTD_1D::UpdateFields(double time)
  {
    applyBC_H();

    //update the H Field
    for (int mm = 0; mm < dataSize_ - 1; mm++)
      H[mm] = H[mm] + (E[mm + 1] - E[mm]) / imp_;

    //correct H field --> TFSF
    H[sourceIndex_ -1] -= computeSourceAmplitude(time,0)/imp_;

    applyBC_E();

    //Now update the E Field
    for (int mm = 1; mm < dataSize_; mm++)
      E[mm] = E[mm] + (H[mm] - H[mm - 1]) * imp_;

    //update the source
    E[sourceIndex_] += computeSourceAmplitude(time,1.0);
  }

   /**
   * \brief Compute the amplitude of the source
   *
   * @param time The time to compute the source
  * @param shift The value to shift the time (TFSF)*/
  double FDTD_1D::computeSourceAmplitude(double time, double shift)
  {
    double val = sourceAmplitude_ *exp(-(time - sourceDelay_ + shift) * (time - sourceDelay_ + shift) / pulseWidth2_);
    return val;
  }

  /**
   * \brief Return the E field at a specified index
   *
   * This function gets the E field at a given index and returns 0 if the requested
   * index exceeds the size of the array
   * @param index The index of the E field to retrieve*/
  double FDTD_1D::getEField(int index)
  {
    if (index < dataSize_)
      return E[index];
    else
      return 0;
  }

  /**
   * \brief Return the H field at a specified index
   *
   * This function gets the H field at a given index and returns 0 if the requested
   * index exceeds the size of the array
   * @param index The index of the H field to retrieve*/
  double FDTD_1D::getHField(int index)
  {
    if (index < dataSize_)
      return H[index];
    else
      return 0;
  }

  void FDTD_1D::simpleABC_E()
  {
    E[0] = E[1];
  }

  void FDTD_1D::simpleABC_H()
  {
    H[dataSize_-1] = H[dataSize_-2];
  }

  void FDTD_1D::applyBC_E()
  {
    switch (ABC)
      {
      case NoABC:
	break;

      case SimpleABC:
	simpleABC_E();
	break;

      case TFSF_ABC:
	break;
      default:
	break;
      }
  }

  void FDTD_1D::applyBC_H()
  {
    switch (ABC)
      {
      case NoABC:
	break;

      case SimpleABC:
	simpleABC_H();
	break;

      case TFSF_ABC:
	break;
      default:
	break;
      }
  }

}//end of namespace
<|endoftext|>


<commit_before>/* Optional packages.  You might want to integrate this with your build system e.g. config.h from ./configure. */
#ifndef UTIL_HAVE__
#define UTIL_HAVE__

#ifndef HAVE_ICU
//#define HAVE_ICU
#endif

#ifndef HAVE_BOOST
//#define HAVE_BOOST
#endif

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#endif // UTIL_HAVE__
<commit_msg>Patch up build for now, still no compressed support<commit_after>/* Optional packages.  You might want to integrate this with your build system e.g. config.h from ./configure. */
#ifndef UTIL_HAVE__
#define UTIL_HAVE__

#ifndef HAVE_ICU
//#define HAVE_ICU
#endif

#ifndef HAVE_BOOST
//#define HAVE_BOOST
#endif

#ifdef HAVE_CONFIG_H
// Chris; uncomment this line.
//#include "config.h"
#endif

#endif // UTIL_HAVE__
<|endoftext|>


<commit_before>#include <stdio.h>
#include <eigen3/Eigen/Dense>

#include "common.h"

#include "mem_dense_matrix.h"

using namespace fm;

class set_col_operate: public type_set_operate<double>
{
	size_t num_cols;
public:
	set_col_operate(size_t num_cols) {
		this->num_cols = num_cols;
	}

	void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const {
		for (size_t i = 0; i < num_eles; i++) {
			arr[i] = (row_idx + i) * num_cols + col_idx;
		}
	}
};

class set_row_operate: public type_set_operate<double>
{
	size_t num_cols;
public:
	set_row_operate(size_t num_cols) {
		this->num_cols = num_cols;
	}

	void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const {
		for (size_t i = 0; i < num_eles; i++) {
			arr[i] = row_idx * num_cols + col_idx + i;
		}
	}
};

/*
 * This function is to compare the performance of inner product between
 * in-memory column-wise dense matrix and Eigen matrix.
 * I assume Eigen matrix should give us the best performance.
 */
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test1(size_t nrow, size_t ncol,
		size_t right_ncol)
{
	struct timeval start, end;

	gettimeofday(&start, NULL);
	typename type_mem_dense_matrix<Type>::ptr m1
		= type_mem_dense_matrix<Type>::create(nrow, ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol));
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to construct input column matrix\n",
			time_diff(start, end));
	typename type_mem_dense_matrix<Type>::ptr m2
		= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol));

	gettimeofday(&start, NULL);
	Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_m1(nrow, ncol);
#pragma omp parallel for
	for (size_t i = 0; i < nrow; i++) {
		for (size_t j = 0; j < ncol; j++)
			eigen_m1(i, j) = i * ncol + j;
	}
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to construct input Eigen matrix\n",
			time_diff(start, end));

	Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_m2(ncol, right_ncol);
	for (size_t i = 0; i < ncol; i++) {
		for (size_t j = 0; j < right_ncol; j++)
			eigen_m2(i, j) = i * right_ncol + j;
	}

	start = end;
	typename type_mem_dense_matrix<Type>::ptr res1
		= multiply<Type, Type, Type>(*m1, *m2);
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to multiply column matrix\n",
			time_diff(start, end));
	assert(res1->get_num_rows() == m1->get_num_rows());
	assert(res1->get_num_cols() == m2->get_num_cols());
	printf("The result matrix has %ld rows and %ld columns\n",
			res1->get_num_rows(), res1->get_num_cols());

	start = end;
	Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_res = eigen_m1 * eigen_m2;
	gettimeofday(&end, NULL);
	assert((size_t) eigen_res.rows() == res1->get_num_rows());
	assert((size_t) eigen_res.cols() == res1->get_num_cols());
	printf("It takes %.3f seconds to multiply Eigen matrix\n",
			time_diff(start, end));

#pragma omp parallel for
	for (size_t i = 0; i < res1->get_num_rows(); i++) {
		for (size_t j = 0; j < res1->get_num_cols(); j++) {
			assert(res1->get(i, j) == eigen_res(i, j));
		}
	}
	return res1;
}

/*
 * This multiplies a large row-wise matrix with a small column-wise matrix.
 * It should give us the best performance.
 */
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test2(size_t nrow, size_t ncol,
		size_t right_ncol)
{
	struct timeval start, end;

	gettimeofday(&start, NULL);
	typename type_mem_dense_matrix<Type>::ptr m1
		= type_mem_dense_matrix<Type>::create(nrow, ncol,
				matrix_layout_t::L_ROW, set_row_operate(ncol));
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to construct input row matrix\n",
			time_diff(start, end));
	typename type_mem_dense_matrix<Type>::ptr m2
		= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol));

	typename type_mem_dense_matrix<Type>::ptr res_m
		= type_mem_dense_matrix<Type>::create(nrow, right_ncol,
				matrix_layout_t::L_ROW);

	gettimeofday(&start, NULL);
	const mem_row_dense_matrix &row_m
		= (const mem_row_dense_matrix &) m1->get_matrix();
	const mem_col_dense_matrix &col_m
		= (const mem_col_dense_matrix &) m2->get_matrix();
	const mem_row_dense_matrix &res_row_m
		= (const mem_row_dense_matrix &) res_m->get_matrix();
#pragma omp parallel for
	for (size_t i = 0; i < nrow; i++) {
		const Type *in_row = (const Type *) row_m.get_row(i);
		Type *out_row = (Type *) res_row_m.get_row(i);
		for (size_t j = 0; j < right_ncol; j++) {
			const Type *in_col = (const Type *) col_m.get_col(j);
			out_row[j] = 0;
			for (size_t k = 0; k < ncol; k++)
				out_row[j] += in_row[k] * in_col[k];
		}
	}
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to multiply row matrix\n",
			time_diff(start, end));
	return res_m;
}

/*
 * This multiplies a large column-wise matrix with a small column-wise matrix
 * directly. This implementation should have good performance.
 */
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test3(size_t nrow, size_t ncol,
		size_t right_ncol)
{
	struct timeval start, end;

	gettimeofday(&start, NULL);
	typename type_mem_dense_matrix<Type>::ptr m1
		= type_mem_dense_matrix<Type>::create(nrow, ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol));
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to construct input column matrix\n",
			time_diff(start, end));
	typename type_mem_dense_matrix<Type>::ptr m2
		= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol));

	typename type_mem_dense_matrix<Type>::ptr res_m
		= type_mem_dense_matrix<Type>::create(nrow, right_ncol,
				matrix_layout_t::L_COL);

	gettimeofday(&start, NULL);
	const mem_col_dense_matrix &left_m
		= (const mem_col_dense_matrix &) m1->get_matrix();
	const mem_col_dense_matrix &right_m
		= (const mem_col_dense_matrix &) m2->get_matrix();
	const mem_col_dense_matrix &res_col_m
		= (const mem_col_dense_matrix &) res_m->get_matrix();
#pragma omp parallel for
	for (size_t i = 0; i < nrow; i++) {
		for (size_t j = 0; j < right_ncol; j++) {
			const Type *right_col = (const Type *) right_m.get_col(j);
			Type *out_col = (Type *) res_col_m.get_col(j);
			out_col[i] = 0;
			for (size_t k = 0; k < ncol; k++) {
				const Type *left_col = (const Type *) left_m.get_col(k);
				out_col[i] += left_col[i] * right_col[k];
			}
		}
	}
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to multiply column matrix\n",
			time_diff(start, end));
	return res_m;
}

template<class Type>
void check_result(typename type_mem_dense_matrix<Type>::ptr m1,
		typename type_mem_dense_matrix<Type>::ptr m2)
{
	assert(m1->get_num_rows() == m2->get_num_rows());
	assert(m1->get_num_cols() == m2->get_num_cols());
#pragma omp parallel for
	for (size_t i = 0; i < m1->get_num_rows(); i++) {
		for (size_t j = 0; j < m1->get_num_cols(); j++) {
			assert(m1->get(i, j) == m2->get(i, j));
		}
	}
}

int main()
{
	size_t nrow = 1024 * 1024 * 124;
	size_t ncol = 5;
	D_mem_dense_matrix::ptr res1 = test1<double>(nrow, ncol, ncol);
	D_mem_dense_matrix::ptr res2 = test2<double>(nrow, ncol, ncol);
	check_result<double>(res1, res2);
	res2 = test3<double>(nrow, ncol, ncol);
	check_result<double>(res1, res2);
}
<commit_msg>[Matrix]: reconstruct the test for matrix multiplication.<commit_after>#include <stdio.h>
#include <eigen3/Eigen/Dense>

#include "common.h"

#include "mem_dense_matrix.h"

using namespace fm;

class set_col_operate: public type_set_operate<double>
{
	size_t num_cols;
public:
	set_col_operate(size_t num_cols) {
		this->num_cols = num_cols;
	}

	void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const {
		for (size_t i = 0; i < num_eles; i++) {
			arr[i] = (row_idx + i) * num_cols + col_idx;
		}
	}
};

class set_row_operate: public type_set_operate<double>
{
	size_t num_cols;
public:
	set_row_operate(size_t num_cols) {
		this->num_cols = num_cols;
	}

	void set(double *arr, size_t num_eles, off_t row_idx, off_t col_idx) const {
		for (size_t i = 0; i < num_eles; i++) {
			arr[i] = row_idx * num_cols + col_idx + i;
		}
	}
};

template<class Type>
void test_eigen(size_t nrow, size_t ncol, size_t right_ncol)
{
	struct timeval start, end;

	printf("test eigen: M(%ld x %ld) * M(%ld %ld)\n", nrow, ncol, ncol, right_ncol);
	gettimeofday(&start, NULL);
	Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_m1(nrow, ncol);
#pragma omp parallel for
	for (size_t i = 0; i < nrow; i++) {
		for (size_t j = 0; j < ncol; j++)
			eigen_m1(i, j) = i * ncol + j;
	}
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to construct input Eigen matrix\n",
			time_diff(start, end));

	Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_m2(ncol, right_ncol);
	for (size_t i = 0; i < ncol; i++) {
		for (size_t j = 0; j < right_ncol; j++)
			eigen_m2(i, j) = i * right_ncol + j;
	}

	start = end;
	Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> eigen_res = eigen_m1 * eigen_m2;
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to multiply Eigen matrix\n",
			time_diff(start, end));
}

/*
 * This function is to compare the performance of inner product between
 * in-memory column-wise dense matrix and Eigen matrix.
 * I assume Eigen matrix should give us the best performance.
 */
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test_MM1(size_t nrow, size_t ncol,
		size_t right_ncol)
{
	struct timeval start, end;

	printf("test tall col-wise matrix: M(%ld x %ld) * M(%ld %ld)\n",
			nrow, ncol, ncol, right_ncol);
	gettimeofday(&start, NULL);
	typename type_mem_dense_matrix<Type>::ptr m1
		= type_mem_dense_matrix<Type>::create(nrow, ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol), true);
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to construct input column matrix\n",
			time_diff(start, end));
	typename type_mem_dense_matrix<Type>::ptr m2
		= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol));

	gettimeofday(&start, NULL);
	typename type_mem_dense_matrix<Type>::ptr res1
		= par_multiply<Type, Type, Type>(*m1, *m2);
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to multiply column matrix in parallel\n",
			time_diff(start, end));
	assert(res1->get_num_rows() == m1->get_num_rows());
	assert(res1->get_num_cols() == m2->get_num_cols());
	printf("The result matrix has %ld rows and %ld columns\n",
			res1->get_num_rows(), res1->get_num_cols());

	return res1;
}

/*
 * This multiplies a large (tall and narrow) row-wise matrix with a small
 * column-wise matrix. It should give us the best performance.
 */
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test_MM2(size_t nrow, size_t ncol,
		size_t right_ncol)
{
	struct timeval start, end;

	printf("test tall row-wise matrix (best case): M(%ld x %ld) * M(%ld %ld)\n",
			nrow, ncol, ncol, right_ncol);
	gettimeofday(&start, NULL);
	typename type_mem_dense_matrix<Type>::ptr m1
		= type_mem_dense_matrix<Type>::create(nrow, ncol,
				matrix_layout_t::L_ROW, set_row_operate(ncol), true);
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to construct input row matrix\n",
			time_diff(start, end));
	typename type_mem_dense_matrix<Type>::ptr m2
		= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol));

	typename type_mem_dense_matrix<Type>::ptr res_m
		= type_mem_dense_matrix<Type>::create(nrow, right_ncol,
				matrix_layout_t::L_ROW);

	gettimeofday(&start, NULL);
	const mem_row_dense_matrix &row_m
		= (const mem_row_dense_matrix &) m1->get_matrix();
	const mem_col_dense_matrix &col_m
		= (const mem_col_dense_matrix &) m2->get_matrix();
	const mem_row_dense_matrix &res_row_m
		= (const mem_row_dense_matrix &) res_m->get_matrix();
#pragma omp parallel for
	for (size_t i = 0; i < nrow; i++) {
		const Type *in_row = (const Type *) row_m.get_row(i);
		Type *out_row = (Type *) res_row_m.get_row(i);
		for (size_t j = 0; j < right_ncol; j++) {
			const Type *in_col = (const Type *) col_m.get_col(j);
			out_row[j] = 0;
			for (size_t k = 0; k < ncol; k++)
				out_row[j] += in_row[k] * in_col[k];
		}
	}
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to multiply row matrix in parallel\n",
			time_diff(start, end));
	return res_m;
}

/*
 * This multiplies a large column-wise matrix with a small column-wise matrix
 * directly. So this implementation potentially generates many CPU cache misses.
 */
template<class Type>
typename type_mem_dense_matrix<Type>::ptr test_MM3(size_t nrow, size_t ncol,
		size_t right_ncol)
{
	struct timeval start, end;

	printf("test tall col-wise matrix (bad impl): M(%ld x %ld) * M(%ld %ld)\n",
			nrow, ncol, ncol, right_ncol);
	gettimeofday(&start, NULL);
	typename type_mem_dense_matrix<Type>::ptr m1
		= type_mem_dense_matrix<Type>::create(nrow, ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol), true);
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to construct input column matrix\n",
			time_diff(start, end));
	typename type_mem_dense_matrix<Type>::ptr m2
		= type_mem_dense_matrix<Type>::create(ncol, right_ncol,
				matrix_layout_t::L_COL, set_col_operate(ncol));

	typename type_mem_dense_matrix<Type>::ptr res_m
		= type_mem_dense_matrix<Type>::create(nrow, right_ncol,
				matrix_layout_t::L_COL);

	gettimeofday(&start, NULL);
	const mem_col_dense_matrix &left_m
		= (const mem_col_dense_matrix &) m1->get_matrix();
	const mem_col_dense_matrix &right_m
		= (const mem_col_dense_matrix &) m2->get_matrix();
	const mem_col_dense_matrix &res_col_m
		= (const mem_col_dense_matrix &) res_m->get_matrix();
#pragma omp parallel for
	for (size_t i = 0; i < nrow; i++) {
		for (size_t j = 0; j < right_ncol; j++) {
			const Type *right_col = (const Type *) right_m.get_col(j);
			Type *out_col = (Type *) res_col_m.get_col(j);
			out_col[i] = 0;
			for (size_t k = 0; k < ncol; k++) {
				const Type *left_col = (const Type *) left_m.get_col(k);
				out_col[i] += left_col[i] * right_col[k];
			}
		}
	}
	gettimeofday(&end, NULL);
	printf("It takes %.3f seconds to multiply column matrix in parallel\n",
			time_diff(start, end));
	return res_m;
}

template<class Type>
void check_result(typename type_mem_dense_matrix<Type>::ptr m1,
		typename type_mem_dense_matrix<Type>::ptr m2)
{
	assert(m1->get_num_rows() == m2->get_num_rows());
	assert(m1->get_num_cols() == m2->get_num_cols());
#pragma omp parallel for
	for (size_t i = 0; i < m1->get_num_rows(); i++) {
		for (size_t j = 0; j < m1->get_num_cols(); j++) {
			assert(m1->get(i, j) == m2->get(i, j));
		}
	}
}

void matrix_mul_tests()
{
	size_t nrow = 1024 * 1024 * 124;
	size_t ncol = 20;
	printf("Multiplication of a large and tall matrix and a small square matrix\n");
	test_eigen<double>(nrow, ncol, ncol);
	D_mem_dense_matrix::ptr res1 = test_MM1<double>(nrow, ncol, ncol);
	D_mem_dense_matrix::ptr res2 = test_MM2<double>(nrow, ncol, ncol);
	check_result<double>(res1, res2);
	res2 = test_MM3<double>(nrow, ncol, ncol);
	check_result<double>(res1, res2);
}

int main()
{
	matrix_mul_tests();
}
<|endoftext|>