<commit_before>#include "ParticleManager.h"

void ParticleManager::setup(int k, int n){
	emittersData.resize(k);
	particles.resize(n);

	initParticles();

	particlesBuffer.allocate(particles, GL_STATIC_DRAW);
	particlesBuffer.bindBase(GL_SHADER_STORAGE_BUFFER, 0);

	vbo.setVertexBuffer(particlesBuffer, 4, sizeof(Particle));

	loadShader();
}

void ParticleManager::initParticles(){
	for(uint i = 0; i < particles.size(); ++i){
		particles[i].pos = ofVec4f(ofGetWidth()/2.0, ofGetHeight()/2.0, 0.0, 1.0);
		particles[i].vel = ofVec4f(0.0);
		particles[i].acc = ofVec4f(0.0);
		particles[i].lifespan.x = ofRandom(0, 120.0);
		// particles[i].lifespan.x = 0.0;
	}
}

void ParticleManager::update(){
	glMemoryBarrier(GL_ALL_BARRIER_BITS);
	shader.begin();
		for(uint i = 0; i < emittersData.size(); ++i){
			string is = ofToString(i);
			EmitterData& e(emittersData[i]);
			shader.setUniform4f("e["+is+"].pos", e.pos.x, e.pos.y, e.pos.z, e.pos.w);
			shader.setUniform4f("e["+is+"].vel", e.vel.x, e.vel.y, e.vel.z, e.vel.w);
			shader.setUniform4f("e["+is+"].acc", e.acc.x, e.acc.y, e.acc.z, e.acc.w);
			shader.setUniform4f("e["+is+"].prevPos", e.prevPos.x, e.prevPos.y, e.prevPos.z, e.prevPos.w);
			shader.setUniform1f("e["+is+"].radius", e.radius);
			shader.setUniform1f("e["+is+"].averageLifespan", e.averageLifespan);
			shader.setUniform1f("e["+is+"].lifespanVariation", e.lifespanVariation);
			shader.setUniform1f("e["+is+"].averageVelocity", e.averageVelocity);
			shader.setUniform1f("e["+is+"].velocityScale", e.velocityScale);
			shader.setUniform1f("e["+is+"].velocityVariation", e.velocityVariation);
			shader.setUniform1f("e["+is+"].useEmitterVelocity", e.useEmitterVelocity);
			shader.setUniform1i("e["+is+"].id", e.id);
		}
		shader.dispatchCompute(particles.size()/WORK_GROUP_SIZE, 1, 1);
	shader.end();
	glMemoryBarrier(GL_ALL_BARRIER_BITS);
}

void ParticleManager::updateEmitter(EmitterData& emitterData){
	emittersData[emitterData.id] = emitterData;
}

void ParticleManager::loadShader(){
	ostringstream cs;
	cs << "#version 430" << endl;
	cs << "#define M_PI 3.1415926535897932384626433832795" << endl;
	cs << "#define EMITTERS_NB " << emittersData.size() << endl;
	cs << "layout(local_size_x = " << WORK_GROUP_SIZE << ", local_size_y = 1, local_size_z = 1) in;" << endl;
	cs << STRINGIFY(

		struct Particle{
		    vec4 pos;
		    vec4 vel;
		    vec4 acc;
		    vec4 lifespan;
		};

		struct Emitter{
			vec4 pos;
			vec4 vel;
			vec4 acc;
			vec4 prevPos;
			float radius;
			float velocityScale;
			float averageLifespan;
			float lifespanVariation;
			float averageVelocity;
			float velocityVariation;
			float useEmitterVelocity;
			int id;
		};

		layout(std430, binding=0) buffer particles{
			Particle p[];
		};

		uniform Emitter e[EMITTERS_NB];

		uint rng_state;

		// Random float number between 0.0 and 1.0
		float rand_xorshift(){
			// Xorshift algorithm from George Marsaglia's paper
			rng_state ^= (rng_state << 13);
			rng_state ^= (rng_state >> 17);
			rng_state ^= (rng_state << 5);
			float r = float(rng_state) / 4294967296.0;
			return r;
		}

		// Random number between min(x, y) and max(x, y)
		float rand(float x, float y){
			float high = 0;
			float low = 0;
			float randNum = 0;
			if (x == y) return x;
			high = max(x,y);
			low = min(x,y);
			randNum = low + (high-low) * rand_xorshift();
			return randNum;
		}

		// Random lifespan based on emitter's parameters
		float newLifespan(Emitter em){
			float var = rand(-em.lifespanVariation, em.lifespanVariation)/100.0;
			return em.averageLifespan*(1.0 + var);
		}

		// Random position based on emitter's parameters
		vec4 newPosition(Emitter em){
			float theta = rand(0.0, 2*M_PI);
			float r = rand(0.0, em.radius);
			float x = r*cos(theta);
			float y = r*sin(theta);
			vec3 intPos = mix(em.pos.xyz, em.prevPos.xyz, rand(0.0, 1.0));
			vec3 newPos = intPos + vec3(x, y, 0.0);
			// vec2 newPos = mix(e[1].pos.xy, em.prevPos.xy, rand(0.0, 1.0));
			// float a = vec2(0.0);
			return vec4(newPos, 1.0);
		}

		// Random velocity based on emitter's parameters
		vec4 newVelocity(Emitter em){
			float theta = rand(0.0, 2*M_PI);
			float velNorm = em.averageVelocity*(1.0 + rand(-em.velocityVariation, em.velocityVariation)/100.0);
			float vx = velNorm*cos(theta);
			float vy = velNorm*sin(theta);
			vec3 newVel;
			if(em.useEmitterVelocity > 0.0){
				newVel.xy = em.vel.xy*em.velocityScale + vec2(vx, vy);
			}
			else{
				newVel.xy = -normalize(em.vel.xy) * vec2(vx, vy);
			}
			return vec4(newVel.xy, 0.0, 1.0);
		}

		// Respawn particle p[gid] at a random emitter position
		void respawn(uint gid){
			uint id = rng_state % EMITTERS_NB;
			Emitter em = e[id];

			p[gid].lifespan.x = newLifespan(em);
			p[gid].pos = newPosition(em);
			p[gid].vel = newVelocity(em);
			p[gid].acc = vec4(0.0, 0.0, 0.0, 1.0);
		}

		void main(){
			uint gid = gl_GlobalInvocationID.x;
			rng_state = gid;

			p[gid].lifespan.x -= 1.0;
			// Dead?
			if(p[gid].lifespan.x < 0.0){
				respawn(gid);
			}
			else{
				p[gid].vel.xyz += p[gid].acc.xyz;
				p[gid].pos.xyz += p[gid].vel.xyz;
			}
		}
	);

	shader.setupShaderFromSource(GL_COMPUTE_SHADER, cs.str());
	shader.linkProgram();
}<commit_msg>Uniform random point on sphere for respawn<commit_after>#include "ParticleManager.h"

void ParticleManager::setup(int k, int n){
	emittersData.resize(k);
	particles.resize(n);

	initParticles();

	particlesBuffer.allocate(particles, GL_STATIC_DRAW);
	particlesBuffer.bindBase(GL_SHADER_STORAGE_BUFFER, 0);

	vbo.setVertexBuffer(particlesBuffer, 4, sizeof(Particle));

	loadShader();
}

void ParticleManager::initParticles(){
	for(uint i = 0; i < particles.size(); ++i){
		particles[i].pos = ofVec4f(ofGetWidth()/2.0, ofGetHeight()/2.0, 0.0, 1.0);
		particles[i].vel = ofVec4f(0.0);
		particles[i].acc = ofVec4f(0.0);
		particles[i].lifespan.x = ofRandom(0, 120.0);
		// particles[i].lifespan.x = 0.0;
	}
}

void ParticleManager::update(){
	glMemoryBarrier(GL_ALL_BARRIER_BITS);
	shader.begin();
		for(uint i = 0; i < emittersData.size(); ++i){
			string is = ofToString(i);
			EmitterData& e(emittersData[i]);
			shader.setUniform4f("e["+is+"].pos", e.pos.x, e.pos.y, e.pos.z, e.pos.w);
			shader.setUniform4f("e["+is+"].vel", e.vel.x, e.vel.y, e.vel.z, e.vel.w);
			shader.setUniform4f("e["+is+"].acc", e.acc.x, e.acc.y, e.acc.z, e.acc.w);
			shader.setUniform4f("e["+is+"].prevPos", e.prevPos.x, e.prevPos.y, e.prevPos.z, e.prevPos.w);
			shader.setUniform1f("e["+is+"].radius", e.radius);
			shader.setUniform1f("e["+is+"].averageLifespan", e.averageLifespan);
			shader.setUniform1f("e["+is+"].lifespanVariation", e.lifespanVariation);
			shader.setUniform1f("e["+is+"].averageVelocity", e.averageVelocity);
			shader.setUniform1f("e["+is+"].velocityScale", e.velocityScale);
			shader.setUniform1f("e["+is+"].velocityVariation", e.velocityVariation);
			shader.setUniform1f("e["+is+"].useEmitterVelocity", (e.bUseEmitterVelocity)? 1.0 : -1.0);
			shader.setUniform1i("e["+is+"].id", e.id);
		}
		shader.dispatchCompute(particles.size()/WORK_GROUP_SIZE, 1, 1);
	shader.end();
	glMemoryBarrier(GL_ALL_BARRIER_BITS);
}

void ParticleManager::updateEmitter(EmitterData& emitterData){
	emittersData[emitterData.id] = emitterData;
}

void ParticleManager::loadShader(){
	ostringstream cs;
	cs << "#version 430" << endl;
	cs << "#define M_PI 3.1415926535897932384626433832795" << endl;
	cs << "#define EMITTERS_NB " << emittersData.size() << endl;
	cs << "layout(local_size_x = " << WORK_GROUP_SIZE << ", local_size_y = 1, local_size_z = 1) in;" << endl;
	cs << STRINGIFY(

		struct Particle{
		    vec4 pos;
		    vec4 vel;
		    vec4 acc;
		    vec4 lifespan;
		};

		struct Emitter{
			vec4 pos;
			vec4 vel;
			vec4 acc;
			vec4 prevPos;
			float radius;
			float velocityScale;
			float averageLifespan;
			float lifespanVariation;
			float averageVelocity;
			float velocityVariation;
			float useEmitterVelocity;
			int id;
		};

		layout(std430, binding=0) buffer particles{
			Particle p[];
		};

		uniform Emitter e[EMITTERS_NB];

		uint rng_state;

		// Random float number between 0.0 and 1.0
		float rand_xorshift(){
			// Xorshift algorithm from George Marsaglia's paper
			rng_state ^= (rng_state << 13);
			rng_state ^= (rng_state >> 17);
			rng_state ^= (rng_state << 5);
			float r = float(rng_state) / 4294967296.0;
			return r;
		}

		// Random number between min(x, y) and max(x, y)
		float rand(float x, float y){
			float high = 0;
			float low = 0;
			float randNum = 0;
			if (x == y) return x;
			high = max(x,y);
			low = min(x,y);
			randNum = low + (high-low) * rand_xorshift();
			return randNum;
		}

		// Random lifespan based on emitter's parameters
		float newLifespan(Emitter em){
			float var = rand(-em.lifespanVariation, em.lifespanVariation)/100.0;
			return em.averageLifespan*(1.0 + var);
		}

		// Random position based on emitter's parameters
		vec4 newPosition(Emitter em){
			float theta = rand(0.0, 2*M_PI);
			// float r = rand(0.0, em.radius);
			// float x = r*cos(theta);
			// float y = r*sin(theta);
			// Uniform random point on sphere
			float u = rand(-1.0, 1.0);
			float x = em.radius*sqrt(1.0-u*u)*cos(theta);
			float y = em.radius*sqrt(1.0-u*u)*sin(theta);
			float z = em.radius*u;
			// float z = 0.0;
			vec3 intPos = mix(em.pos.xyz, em.prevPos.xyz, rand(0.0, 1.0));
			vec3 newPos = intPos + vec3(x, y, z);
			// vec2 newPos = mix(e[1].pos.xy, em.prevPos.xy, rand(0.0, 1.0));
			return vec4(newPos, 1.0);
		}

		// Random velocity based on emitter's parameters
		vec4 newVelocity(Emitter em){
			float theta = rand(0.0, 2*M_PI);
			float velNorm = em.averageVelocity*(1.0 + rand(-em.velocityVariation, em.velocityVariation)/100.0);
			float vx = velNorm*cos(theta);
			float vy = velNorm*sin(theta);
			vec3 newVel;
			if(em.useEmitterVelocity > 0.0){
				newVel.xy = em.vel.xy*em.velocityScale + vec2(vx, vy);
			}
			else{
				newVel.xy = -normalize(em.vel.xy) * vec2(vx, vy);
			}
			return vec4(newVel.xy, 0.0, 1.0);
		}

		// Respawn particle p[gid] at a random emitter position
		void respawn(uint gid){
			uint id = rng_state % EMITTERS_NB;
			Emitter em = e[id];

			p[gid].lifespan.x = newLifespan(em);
			p[gid].pos = newPosition(em);
			p[gid].vel = newVelocity(em);
			p[gid].acc = vec4(0.0, 0.0, 0.0, 1.0);
		}

		void main(){
			uint gid = gl_GlobalInvocationID.x;
			rng_state = gid;

			p[gid].lifespan.x -= 1.0;
			// Dead?
			if(p[gid].lifespan.x < 0.0){
				respawn(gid);
			}
			else{
				p[gid].vel.xyz += p[gid].acc.xyz;
				p[gid].pos.xyz += p[gid].vel.xyz;
			}
		}
	);

	shader.setupShaderFromSource(GL_COMPUTE_SHADER, cs.str());
	shader.linkProgram();
}<|endoftext|>


<commit_before>#include <gp_Pnt.hxx>
#include <gtest/gtest.h>

TEST(gpTestSuite, testgp_PntConstruct)
{
    gp_Pnt P;
    ASSERT_EQ(0.0,P.X());
    ASSERT_EQ(0.0,P.Y());
    ASSERT_EQ(0.0,P.Z());
}

TEST(gpTestSuite, testgp_PntDistance)
{
    gp_Pnt P1(0.,0.,0.);
    gp_Pnt P2(0.,3.,4.);
    float D = P1.Distance(P2);
    ASSERT_EQ(5.,D);
}

TEST(gpTestSuite, testBuildThousandsPoints)
{
    for (int i=1;i<10000;i++) {
        gp_Pnt(1,2,3);
    }
}

int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>New test: testGCC42gp_Trsf<commit_after>#include <gp_Pnt.hxx>
#include <gtest/gtest.h>

TEST(gpTestSuite, testgp_PntConstruct)
{
    gp_Pnt P;
    ASSERT_EQ(0.0,P.X());
    ASSERT_EQ(0.0,P.Y());
    ASSERT_EQ(0.0,P.Z());
}

TEST(gpTestSuite, testgp_PntDistance)
{
    gp_Pnt P1(0.,0.,0.);
    gp_Pnt P2(0.,3.,4.);
    float D = P1.Distance(P2);
    ASSERT_EQ(5.,D);
}

TEST(gpTestSuite, testBuildThousandsPoints)
{
    for (int i=1;i<10000;i++) {
        gp_Pnt(1,2,3);
    }
}

/*  This test fails with OCCT 6.5.1 and GCC 4.2 */
TEST(gpTestSuite, testGCC42gp_Trsf)
{
    gp_Trsf T;
    T.SetValues(
        1.0, 0.0, 0.0, 0.0,
        0.0, 1.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,
        1.e-6, 1.e-6);
    ASSERT_EQ(1.0,T.Value(1,1));
    ASSERT_EQ(1.0,T.Value(2,2));
    ASSERT_EQ(1.0,T.Value(3,3));
}

int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
#include "server.h"
#include "socket/posix/posixsocket.h"
#include "clientconexion.h"
//-----------------------------------------------------------------------------
Server::Server(Configuration* config) {
	this->port = std::stoi(config->port);
	this->ip = config->ip;
	this->max_clients = config->max_clients;
	this->status = false;
	this->socket = 0;

}
//-----------------------------------------------------------------------------
Server::~Server() {
	// TODO Auto-generated destructor stub
}
//----------------------------------------------------------------------------
bool Server::isActive()
{
	return this->status;
}
//-----------------------------------------------------------------------------
void Server::start()
{
	while(this->isActive())
	{
		Socket *socketCLI = 0;

		// Aceptamos nuevo cliente
		socketCLI = this->socket->Accept();

		//Si hubo problemas en el socket salir y loggear
		if(!this->socket->IsActive() || !socketCLI) break;

		// Generamos una nueva conexión para ese cliente
		ClientConexion *conexion = new ClientConexion(socketCLI);

		//el admin podria ser un singleton (depende de como lo usemos luego en "la logica")
		this->adminClients.push_back(conexion);

		// Damos la orden de que comience a ejecutarse el hilo del cliente.
		conexion->start();
	}

}
//-----------------------------------------------------------------------------
bool Server::init()
{
	this->socket =  new PosixSocket();
	this->socket->Listen(this->max_clients);

	//std::thread(start);
	// lo que sucede dentro de start es bloqueante x lo q se deberia ejectuar en un
	//thread aparte.

	this->start();

	return true;
}
//-----------------------------------------------------------------------------
void Server::stop()
{
	//Cambio el estado del server
	this->status = false;

	// Detenemos hilo hay q detener la funcion run
	// analizar si es suficiente con el cambio de estado en el server.

	// Cerramos el socket
	this->socket->deinit();

	// Mensaje de log

}
<commit_msg>mensajes para avanzar con el desarrollo<commit_after>//-----------------------------------------------------------------------------
#include "server.h"
#include "socket/posix/posixsocket.h"
#include "clientconexion.h"
//-----------------------------------------------------------------------------
Server::Server(Configuration* config) {
	this->port = std::stoi(config->port);
	this->ip = config->ip;
	this->max_clients = config->max_clients;
	this->status = false;
	this->socket = 0;

}
//-----------------------------------------------------------------------------
Server::~Server() {
	// TODO Auto-generated destructor stub
}
//----------------------------------------------------------------------------
bool Server::isActive()
{
	return this->status;
}
//-----------------------------------------------------------------------------
void Server::start()
{
	while(this->isActive())
	{
		Socket *socketCLI = 0;

		// Aceptamos nuevo cliente accept es bloqueante
		//cuando se recibe un nuevo cliente, se genera una conexion para atenderlo y se lo carga en el vector
		//de conexiones

		// Fede, en este punto es donde si queres la conexion puede ser un "Cliente... y tener logica"
		//Osea cambiamos esa clase a lo que modela el cliente en el servidor y usa sockets para comunicacion
		socketCLI = this->socket->Accept();

		//Si hubo problemas en el socket salir y loggear
		if(!this->socket->IsActive() || !socketCLI) break;

		// Generamos una nueva conexión para ese cliente
		ClientConexion *conexion = new ClientConexion(socketCLI);

		//el admin podria ser un singleton (depende de como lo usemos luego en "la logica")
		this->adminClients.push_back(conexion);

		// Damos la orden de que comience a ejecutarse el hilo del cliente.
		conexion->start();
	}

}
//-----------------------------------------------------------------------------
bool Server::init()
{
	this->socket =  new PosixSocket();
	this->socket->Listen(this->max_clients);

	//std::thread(start);
	// lo que sucede dentro de start es bloqueante x lo q se deberia ejectuar en un
	//thread aparte.

	this->start();

	return true;
}
//-----------------------------------------------------------------------------
void Server::stop()
{
	//Cambio el estado del server
	this->status = false;

	// Detenemos hilo hay q detener la funcion run
	// analizar si es suficiente con el cambio de estado en el server.

	// Cerramos el socket
	this->socket->deinit();

	// Mensaje de log

}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/compress/zip/Zipper.h"

#include "db/io/FileInputStream.h"
#include "db/io/FileOutputStream.h"
#include "db/rt/Iterator.h"

using namespace db::compress::zip;
using namespace db::io;
using namespace db::rt;
using namespace db::util;

// define zip version
const unsigned short Zipper::ZIP_VERSION = 20;

// define compression method (DEFLATE = 8)
const unsigned short Zipper::COMPRESSION_METHOD = 8;

// define record signatures for ZIP format
const unsigned int Zipper::LFH_SIGNATURE = 'P'|('K'<<8)|(3<<16)|(4<<24);
const unsigned int Zipper::DAD_SIGNATURE = 'P'|('K'<<8)|(7<<16)|(8<<24);
const unsigned int Zipper::CDS_SIGNATURE = 'P'|('K'<<8)|(1<<16)|(2<<24);
const unsigned int Zipper::CDE_SIGNATURE = 'P'|('K'<<8)|(5<<16)|(6<<24);

Zipper::Zipper() :
   mBuffer(2048)
{
   mCentralDirectoryOffset = 0;

   // bit 0 = 0, no encryption
   // bit 1 = 0, normal compression used (deflate default level)
   // bit 2 = 0, normal compression used (deflate default level)
   // bit 3 = 1, local header crc & sizes = 0, data descriptors used, CD used
   // bit 4 = 0, reserved for enhanced deflating
   // bit 5 = 0, not compressed patched data
   // bit 6 = 0, no AES encryption used
   // bit 7 = 0, unused
   // bit 8 = 0, unused
   // bit 9 = 0, unused
   // bit 10 = 0, unused
   // bit 11 = 0, if set, UTF-8 must be used for filenames
   // bit 12 = 0, reserved for PKWARE enhanced compression
   // bit 13 = 0, CD (central directory) not encrypted
   // bit 14 = 0, reserved for PKWARE
   // bit 15 = 0, reserved for PKWARE
   mGpBitFlag = 0x08;
}

Zipper::~Zipper()
{
}

bool Zipper::zip(FileList* fl, File* out)
{
   bool rval = true;

   // clear entry list, reset central directory offset
   mEntries.clear();
   mCentralDirectoryOffset = 0;

   // create file output stream
   FileOutputStream fos(out);

   // create zip entries and write them out
   char b[2048];
   int numBytes;
   IteratorRef<File*> i = fl->getIterator();
   while(rval && i->hasNext())
   {
      File* file = i->next();

      // create entry, set file name
      ZipEntry ze;
      ze->setFilename(file->getName());

      // write entry
      if((rval = writeEntry(ze, &fos)))
      {
         // write data for entry
         FileInputStream fis(file);
         while(rval && (numBytes = fis.read(b, 2048)) > 0)
         {
            rval = write(b, numBytes, &fos);
         }
         fis.close();
      }
   }

   // finish zip archive
   finish(&fos);

   // close file stream
   fos.close();

   return rval;
}

bool Zipper::writeLocalFileHeader(ZipEntry& ze, OutputStream* os)
{
   // FIXME: handle byte ordering (format is little-endian)

   unsigned int dosTime = ze->getDosTime();
   unsigned int crc = 0;
   unsigned int size = 0;
   unsigned short fnLength = strlen(ze->getFilename());
   unsigned short exLength = 0;

   // write local file header signature
   // write version needed to extract
   // write general purpose bit flag
   // write compression method
   // write last mod file time (combined into MS-DOS date & time)
   // write last mod file date (combined into MS-DOS date & time)
   // write crc-32 (0 here since its in the central directory)
   // write compressed size (0 here since its in the central directory)
   // write uncompressed size (0 here since its in the central directory)
   // write file name length
   // write extra field length (0)
   return
      os->write((char*)&LFH_SIGNATURE, 4) &&
      os->write((char*)&ZIP_VERSION, 2) &&
      os->write((char*)&mGpBitFlag, 2) &&
      os->write((char*)&COMPRESSION_METHOD, 2) &&
      os->write((char*)&dosTime, 4) &&
      os->write((char*)&crc, 4) &&
      os->write((char*)&size, 4) &&
      os->write((char*)&size, 4) &&
      os->write((char*)&fnLength, 2) &&
      os->write((char*)&exLength, 2) &&
      os->write(ze->getFilename(), fnLength);
}

bool Zipper::readLocalFileHeader(ZipEntry& ze, InputStream* is)
{
   // FIXME: not implemented
   ExceptionRef e = new Exception(
      "Zipper::readLocalFileHeader() not implemented!");
   Exception::setLast(e, false);
   return false;
}

bool Zipper::writeFileHeader(ZipEntry& ze, OutputStream* os)
{
   // FIXME: handle byte ordering (format is little-endian)

   unsigned int dosTime = ze->getDosTime();
   unsigned int crc = ze->getCrc32();
   unsigned int cSize = ze->getCompressedSize();
   unsigned int ucSize = ze->getUncompressedSize();
   unsigned short fnLength = strlen(ze->getFilename());
   unsigned short exLength = 0;
   unsigned short fcLength = strlen(ze->getFileComment());
   unsigned short diskNumber = 0;
   unsigned short internalAttr = 0;
   unsigned int externalAttr = 0;
   unsigned int offset = ze->getLocalFileHeaderOffset();

   // write central file header signature
   // write version made by
   // write version needed to extract
   // write general purpose bit flag
   // write compression method
   // write last mod file time (combined into MS-DOS date & time)
   // write last mod file date (combined into MS-DOS date & time)
   // write crc-32
   // write compressed size
   // write uncompressed size
   // write file name length
   // write extra field length (0)
   // write file comment length
   // write disk number start
   // write internal file attributes
   // write external file attributes
   // write relative offset of local header
   // write file name
   // write extra field (none)
   // write file comment
   return
      os->write((char*)&CDS_SIGNATURE, 4) &&
      os->write((char*)&ZIP_VERSION, 2) &&
      os->write((char*)&ZIP_VERSION, 2) &&
      os->write((char*)&mGpBitFlag, 2) &&
      os->write((char*)&COMPRESSION_METHOD, 2) &&
      os->write((char*)&dosTime, 4) &&
      os->write((char*)&crc, 4) &&
      os->write((char*)&cSize, 4) &&
      os->write((char*)&ucSize, 4) &&
      os->write((char*)&fnLength, 2) &&
      os->write((char*)&exLength, 2) &&
      os->write((char*)&fcLength, 2) &&
      os->write((char*)&diskNumber, 2) &&
      os->write((char*)&internalAttr, 2) &&
      os->write((char*)&externalAttr, 4) &&
      os->write((char*)&offset, 4) &&
      os->write(ze->getFilename(), fnLength) &&
      // no extra field to write out, write out comment
      os->write(ze->getFileComment(), fcLength);
}

bool Zipper::readFileHeader(ZipEntry& ze, InputStream* is)
{
   // FIXME: not implemented
   ExceptionRef e = new Exception("Zipper::readFileHeader() not implemented!");
   Exception::setLast(e, false);
   return false;
}

bool Zipper::finishCurrentEntry(OutputStream* os)
{
   bool rval = true;

   // write data descriptor for previous entry
   if(!mEntries.empty())
   {
      // get the current entry
      ZipEntry& ze = mEntries.back();

      // write out any remaining deflated data
      mDeflater.setInput(NULL, 0, true);
      mBuffer.clear();
      mDeflater.process(&mBuffer, true);
      if(!mBuffer.isEmpty())
      {
         // ensure data is written to output stream
         rval = (mBuffer.get(os) > 0);
      }

      // set compressed/uncompressed sizes for entry
      ze->setCompressedSize(mDeflater.getTotalOutputBytes());
      ze->setUncompressedSize(mDeflater.getTotalInputBytes());

      // store offset to local file header
      ze->setLocalFileHeaderOffset(mCentralDirectoryOffset);

      // add size of local file header to central directory offset
      mCentralDirectoryOffset += ze->getLocalFileHeaderSize();

      // add size of compressed data to central directory offset
      mCentralDirectoryOffset += mDeflater.getTotalOutputBytes();

      if(rval)
      {
         unsigned int crc = ze->getCrc32();
         unsigned int cSize = ze->getCompressedSize();
         unsigned int ucSize = ze->getUncompressedSize();

         // FIXME: handle byte ordering (format is little-endian)

         // write out data descriptor signature
         // write out crc
         // write out compressed size
         // write out uncompressed size
         rval =
            os->write((char*)&DAD_SIGNATURE, 4) &&
            os->write((char*)&crc, 4) &&
            os->write((char*)&cSize, 4) &&
            os->write((char*)&ucSize, 4);

         // add data descriptor size to central directory offset
         mCentralDirectoryOffset += 16;
      }
   }

   return rval;
}

bool Zipper::writeEntry(ZipEntry& ze, OutputStream* os)
{
   // finish the current entry
   bool rval = finishCurrentEntry(os);

   if(rval)
   {
      // store new entry in list
      mEntries.push_back(ze);

      // reset entry crc
      ze->setCrc32(0);

      // start raw deflation
      mDeflater.startDeflating(-1, true);

      // write out local file header for entry
      rval = writeLocalFileHeader(ze, os);
   }

   return rval;
}

int Zipper::readEntry(ZipEntry& ze, InputStream* is)
{
   int rval = -1;

   // FIXME: not implemented
   ExceptionRef e = new Exception("Zipper::readEntry() not implemented!");
   Exception::setLast(e, false);

   return rval;
}

bool Zipper::write(char* b, int length, OutputStream* os)
{
   bool rval = true;

   // update the entry's crc
   ZipEntry& ze = mEntries.back();
   ze->setCrc32(crc32(ze->getCrc32(), (unsigned char*)b, length));

   // set input for deflater
   mDeflater.setInput(b, length, false);

   // process all input and write it to the output stream
   while(rval && mDeflater.process(&mBuffer, false) > 0)
   {
      // ensure data is written to output stream
      rval = (mBuffer.get(os) > 0);
   }

   return rval;
}

int Zipper::read(char* b, int length)
{
   int rval = -1;

   // FIXME: not implemented
   ExceptionRef e = new Exception("Zipper::read() not implemented!");
   Exception::setLast(e, false);

   return rval;
}

bool Zipper::finish(OutputStream* os)
{
   // finish the current entry
   bool rval = finishCurrentEntry(os);

   // check central directory flag
   if(rval && true)// FIXME: replace "true" with flag check
   {
      // write out the file header for each entry
      unsigned int cdSize = 0;
      for(EntryList::iterator i = mEntries.begin();
          rval && i != mEntries.end(); i++)
      {
         rval = writeFileHeader(*i, os);
         cdSize += (*i)->getFileHeaderSize();
      }

      // write out end of central directory record
      if(rval)
      {
         // FIXME: handle byte ordering (format is little-endian)

         unsigned short diskNumber = 0;
         unsigned short entries = mEntries.size();
         unsigned short zipCommentLength = 0;

         // write out end of central directory record signature
         // write out this disk number (0)
         // write out number of disk with the start of central directory (0)
         // write out number of entries in central directory on this disk
         // write out total number of entries in central directory
         // write out size of central directory
         // write out offset of start of central directory w/respect to disk #
         // write out .ZIP file comment length
         // write out .ZIP file comment
         rval =
            os->write((char*)&CDE_SIGNATURE, 4) &&
            os->write((char*)&diskNumber, 2) &&
            os->write((char*)&diskNumber, 2) &&
            os->write((char*)&entries, 2) &&
            os->write((char*)&entries, 2) &&
            os->write((char*)&cdSize, 4) &&
            os->write((char*)&mCentralDirectoryOffset, 4) &&
            os->write((char*)&zipCommentLength, 2);
      }
   }

   // clear entry list, reset central directory offset
   mEntries.clear();
   mCentralDirectoryOffset = 0;

   return rval;
}
<commit_msg>Made zipper resize internal buffer as necessary.<commit_after>/*
 * Copyright (c) 2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/compress/zip/Zipper.h"

#include "db/io/FileInputStream.h"
#include "db/io/FileOutputStream.h"
#include "db/rt/Iterator.h"

using namespace db::compress::zip;
using namespace db::io;
using namespace db::rt;
using namespace db::util;

// define zip version
const unsigned short Zipper::ZIP_VERSION = 20;

// define compression method (DEFLATE = 8)
const unsigned short Zipper::COMPRESSION_METHOD = 8;

// define record signatures for ZIP format
const unsigned int Zipper::LFH_SIGNATURE = 'P'|('K'<<8)|(3<<16)|(4<<24);
const unsigned int Zipper::DAD_SIGNATURE = 'P'|('K'<<8)|(7<<16)|(8<<24);
const unsigned int Zipper::CDS_SIGNATURE = 'P'|('K'<<8)|(1<<16)|(2<<24);
const unsigned int Zipper::CDE_SIGNATURE = 'P'|('K'<<8)|(5<<16)|(6<<24);

Zipper::Zipper() :
   mBuffer(2048)
{
   mCentralDirectoryOffset = 0;

   // bit 0 = 0, no encryption
   // bit 1 = 0, normal compression used (deflate default level)
   // bit 2 = 0, normal compression used (deflate default level)
   // bit 3 = 1, local header crc & sizes = 0, data descriptors used, CD used
   // bit 4 = 0, reserved for enhanced deflating
   // bit 5 = 0, not compressed patched data
   // bit 6 = 0, no AES encryption used
   // bit 7 = 0, unused
   // bit 8 = 0, unused
   // bit 9 = 0, unused
   // bit 10 = 0, unused
   // bit 11 = 0, if set, UTF-8 must be used for filenames
   // bit 12 = 0, reserved for PKWARE enhanced compression
   // bit 13 = 0, CD (central directory) not encrypted
   // bit 14 = 0, reserved for PKWARE
   // bit 15 = 0, reserved for PKWARE
   mGpBitFlag = 0x08;
}

Zipper::~Zipper()
{
}

bool Zipper::zip(FileList* fl, File* out)
{
   bool rval = true;

   // clear entry list, reset central directory offset
   mEntries.clear();
   mCentralDirectoryOffset = 0;

   // create file output stream
   FileOutputStream fos(out);

   // create zip entries and write them out
   char b[2048];
   int numBytes;
   IteratorRef<File*> i = fl->getIterator();
   while(rval && i->hasNext())
   {
      File* file = i->next();

      // create entry, set file name
      ZipEntry ze;
      ze->setFilename(file->getName());

      // write entry
      if((rval = writeEntry(ze, &fos)))
      {
         // write data for entry
         FileInputStream fis(file);
         while(rval && (numBytes = fis.read(b, 2048)) > 0)
         {
            rval = write(b, numBytes, &fos);
         }
         fis.close();
      }
   }

   // finish zip archive
   finish(&fos);

   // close file stream
   fos.close();

   return rval;
}

bool Zipper::writeLocalFileHeader(ZipEntry& ze, OutputStream* os)
{
   // FIXME: handle byte ordering (format is little-endian)

   unsigned int dosTime = ze->getDosTime();
   unsigned int crc = 0;
   unsigned int size = 0;
   unsigned short fnLength = strlen(ze->getFilename());
   unsigned short exLength = 0;

   // write local file header signature
   // write version needed to extract
   // write general purpose bit flag
   // write compression method
   // write last mod file time (combined into MS-DOS date & time)
   // write last mod file date (combined into MS-DOS date & time)
   // write crc-32 (0 here since its in the central directory)
   // write compressed size (0 here since its in the central directory)
   // write uncompressed size (0 here since its in the central directory)
   // write file name length
   // write extra field length (0)
   return
      os->write((char*)&LFH_SIGNATURE, 4) &&
      os->write((char*)&ZIP_VERSION, 2) &&
      os->write((char*)&mGpBitFlag, 2) &&
      os->write((char*)&COMPRESSION_METHOD, 2) &&
      os->write((char*)&dosTime, 4) &&
      os->write((char*)&crc, 4) &&
      os->write((char*)&size, 4) &&
      os->write((char*)&size, 4) &&
      os->write((char*)&fnLength, 2) &&
      os->write((char*)&exLength, 2) &&
      os->write(ze->getFilename(), fnLength);
}

bool Zipper::readLocalFileHeader(ZipEntry& ze, InputStream* is)
{
   // FIXME: not implemented
   ExceptionRef e = new Exception(
      "Zipper::readLocalFileHeader() not implemented!");
   Exception::setLast(e, false);
   return false;
}

bool Zipper::writeFileHeader(ZipEntry& ze, OutputStream* os)
{
   // FIXME: handle byte ordering (format is little-endian)

   unsigned int dosTime = ze->getDosTime();
   unsigned int crc = ze->getCrc32();
   unsigned int cSize = ze->getCompressedSize();
   unsigned int ucSize = ze->getUncompressedSize();
   unsigned short fnLength = strlen(ze->getFilename());
   unsigned short exLength = 0;
   unsigned short fcLength = strlen(ze->getFileComment());
   unsigned short diskNumber = 0;
   unsigned short internalAttr = 0;
   unsigned int externalAttr = 0;
   unsigned int offset = ze->getLocalFileHeaderOffset();

   // write central file header signature
   // write version made by
   // write version needed to extract
   // write general purpose bit flag
   // write compression method
   // write last mod file time (combined into MS-DOS date & time)
   // write last mod file date (combined into MS-DOS date & time)
   // write crc-32
   // write compressed size
   // write uncompressed size
   // write file name length
   // write extra field length (0)
   // write file comment length
   // write disk number start
   // write internal file attributes
   // write external file attributes
   // write relative offset of local header
   // write file name
   // write extra field (none)
   // write file comment
   return
      os->write((char*)&CDS_SIGNATURE, 4) &&
      os->write((char*)&ZIP_VERSION, 2) &&
      os->write((char*)&ZIP_VERSION, 2) &&
      os->write((char*)&mGpBitFlag, 2) &&
      os->write((char*)&COMPRESSION_METHOD, 2) &&
      os->write((char*)&dosTime, 4) &&
      os->write((char*)&crc, 4) &&
      os->write((char*)&cSize, 4) &&
      os->write((char*)&ucSize, 4) &&
      os->write((char*)&fnLength, 2) &&
      os->write((char*)&exLength, 2) &&
      os->write((char*)&fcLength, 2) &&
      os->write((char*)&diskNumber, 2) &&
      os->write((char*)&internalAttr, 2) &&
      os->write((char*)&externalAttr, 4) &&
      os->write((char*)&offset, 4) &&
      os->write(ze->getFilename(), fnLength) &&
      // no extra field to write out, write out comment
      os->write(ze->getFileComment(), fcLength);
}

bool Zipper::readFileHeader(ZipEntry& ze, InputStream* is)
{
   // FIXME: not implemented
   ExceptionRef e = new Exception("Zipper::readFileHeader() not implemented!");
   Exception::setLast(e, false);
   return false;
}

bool Zipper::finishCurrentEntry(OutputStream* os)
{
   bool rval = true;

   // write data descriptor for previous entry
   if(!mEntries.empty())
   {
      // get the current entry
      ZipEntry& ze = mEntries.back();

      // write out any remaining deflated data
      mDeflater.setInput(NULL, 0, true);
      mBuffer.clear();
      mDeflater.process(&mBuffer, true);
      if(!mBuffer.isEmpty())
      {
         // ensure data is written to output stream
         rval = (mBuffer.get(os) > 0);
      }

      // set compressed/uncompressed sizes for entry
      ze->setCompressedSize(mDeflater.getTotalOutputBytes());
      ze->setUncompressedSize(mDeflater.getTotalInputBytes());

      // store offset to local file header
      ze->setLocalFileHeaderOffset(mCentralDirectoryOffset);

      // add size of local file header to central directory offset
      mCentralDirectoryOffset += ze->getLocalFileHeaderSize();

      // add size of compressed data to central directory offset
      mCentralDirectoryOffset += mDeflater.getTotalOutputBytes();

      if(rval)
      {
         unsigned int crc = ze->getCrc32();
         unsigned int cSize = ze->getCompressedSize();
         unsigned int ucSize = ze->getUncompressedSize();

         // FIXME: handle byte ordering (format is little-endian)

         // write out data descriptor signature
         // write out crc
         // write out compressed size
         // write out uncompressed size
         rval =
            os->write((char*)&DAD_SIGNATURE, 4) &&
            os->write((char*)&crc, 4) &&
            os->write((char*)&cSize, 4) &&
            os->write((char*)&ucSize, 4);

         // add data descriptor size to central directory offset
         mCentralDirectoryOffset += 16;
      }
   }

   return rval;
}

bool Zipper::writeEntry(ZipEntry& ze, OutputStream* os)
{
   // finish the current entry
   bool rval = finishCurrentEntry(os);

   if(rval)
   {
      // store new entry in list
      mEntries.push_back(ze);

      // reset entry crc
      ze->setCrc32(0);

      // start raw deflation
      mDeflater.startDeflating(-1, true);

      // write out local file header for entry
      rval = writeLocalFileHeader(ze, os);
   }

   return rval;
}

int Zipper::readEntry(ZipEntry& ze, InputStream* is)
{
   int rval = -1;

   // FIXME: not implemented
   ExceptionRef e = new Exception("Zipper::readEntry() not implemented!");
   Exception::setLast(e, false);

   return rval;
}

bool Zipper::write(char* b, int length, OutputStream* os)
{
   bool rval = true;

   // update the entry's crc
   ZipEntry& ze = mEntries.back();
   ze->setCrc32(crc32(ze->getCrc32(), (unsigned char*)b, length));

   // set input for deflater
   mDeflater.setInput(b, length, false);

   // process all input and write it to the output stream
   while(rval && mDeflater.process(&mBuffer, true) > 0)
   {
      // ensure data is written to output stream
      rval = (mBuffer.get(os) > 0);
   }

   return rval;
}

int Zipper::read(char* b, int length)
{
   int rval = -1;

   // FIXME: not implemented
   ExceptionRef e = new Exception("Zipper::read() not implemented!");
   Exception::setLast(e, false);

   return rval;
}

bool Zipper::finish(OutputStream* os)
{
   // finish the current entry
   bool rval = finishCurrentEntry(os);

   // check central directory flag
   if(rval && true)// FIXME: replace "true" with flag check
   {
      // write out the file header for each entry
      unsigned int cdSize = 0;
      for(EntryList::iterator i = mEntries.begin();
          rval && i != mEntries.end(); i++)
      {
         rval = writeFileHeader(*i, os);
         cdSize += (*i)->getFileHeaderSize();
      }

      // write out end of central directory record
      if(rval)
      {
         // FIXME: handle byte ordering (format is little-endian)

         unsigned short diskNumber = 0;
         unsigned short entries = mEntries.size();
         unsigned short zipCommentLength = 0;

         // write out end of central directory record signature
         // write out this disk number (0)
         // write out number of disk with the start of central directory (0)
         // write out number of entries in central directory on this disk
         // write out total number of entries in central directory
         // write out size of central directory
         // write out offset of start of central directory w/respect to disk #
         // write out .ZIP file comment length
         // write out .ZIP file comment
         rval =
            os->write((char*)&CDE_SIGNATURE, 4) &&
            os->write((char*)&diskNumber, 2) &&
            os->write((char*)&diskNumber, 2) &&
            os->write((char*)&entries, 2) &&
            os->write((char*)&entries, 2) &&
            os->write((char*)&cdSize, 4) &&
            os->write((char*)&mCentralDirectoryOffset, 4) &&
            os->write((char*)&zipCommentLength, 2);
      }
   }

   // clear entry list, reset central directory offset
   mEntries.clear();
   mCentralDirectoryOffset = 0;

   return rval;
}
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    CCoinsViewDB *pcoinsdbview;

    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        noui_connect();
        bitdb.MakeMock();
        pblocktree = new CBlockTreeDB(true);
        pcoinsdbview = new CCoinsViewDB(true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        LoadBlockIndex();
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        delete pcoinsTip;
        delete pcoinsdbview;
        delete pblocktree;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

<commit_msg>Fix tests after cache tweaks<commit_after>#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    CCoinsViewDB *pcoinsdbview;

    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        noui_connect();
        bitdb.MakeMock();
        pblocktree = new CBlockTreeDB(1 << 20, true);
        pcoinsdbview = new CCoinsViewDB(1 << 23, true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        LoadBlockIndex();
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        delete pcoinsTip;
        delete pcoinsdbview;
        delete pblocktree;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

<|endoftext|>


<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH

#include <map>
#include <algorithm>

#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>

#include <dune/pymor/operators/base.hh>
#include <dune/pymor/operators/affine.hh>
#include <dune/pymor/functionals/affine.hh>

#include <dune/gdt/discretefunction/default.hh>

#include "../../../linearelliptic/discretizations/interfaces.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Discretizations {

// forward
template< class ImpTraits >
class ContainerBasedDefault;

namespace internal {

template< class ImpTraits >
class ContainerBasedDefaultTraits
  : public ImpTraits
{
public:
  typedef ContainerBasedDefault< ImpTraits > derived_type;
  using typename ImpTraits::MatrixType;
  using typename ImpTraits::VectorType;
  typedef Pymor::Operators::LinearAffinelyDecomposedContainerBased< MatrixType, VectorType > OperatorType;
  typedef OperatorType ProductType;
  typedef Pymor::Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType;
}; // class ContainerBasedDefaultTraits

} // namespace internal

template< class ImpTraits >
class CachedDefault
  : public DiscretizationInterface< ImpTraits >
{
  typedef DiscretizationInterface< ImpTraits >  BaseType;
  typedef CachedDefault< ImpTraits >            ThisType;
public:
  using typename BaseType::GridViewType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::ProblemType;
  using typename BaseType::TestSpaceType;
  using typename BaseType::AnsatzSpaceType;
  using typename BaseType::VectorType;

private:
  typedef Stuff::Grid::BoundaryInfoProvider< typename GridViewType::Intersection > BoundaryInfoProvider;

public:
  CachedDefault(const std::shared_ptr< const TestSpaceType >& test_spc,
                const std::shared_ptr< const AnsatzSpaceType > ansatz_spc,
                const Stuff::Common::ConfigTree& bnd_inf_cfg,
                const ProblemType& prb)
    : BaseType(prb)
    , test_space_(test_spc)
    , ansatz_space_(ansatz_spc)
    , boundary_info_cfg_(bnd_inf_cfg)
    , boundary_info_(BoundaryInfoProvider::create(boundary_info_cfg_.get< std::string >("type"), boundary_info_cfg_))
    , problem_(prb)
  {}

  CachedDefault(const ThisType& other) = default;

  ThisType& operator=(const ThisType& other) = delete;

  const std::shared_ptr< const TestSpaceType >& test_space() const
  {
    return test_space_;
  }

  const std::shared_ptr< const AnsatzSpaceType >& ansatz_space() const
  {
    return test_space_;
  }

  const std::shared_ptr< const GridViewType >& grid_view() const
  {
    return test_space_->grid_view();
  }

  const Stuff::Common::ConfigTree& boundary_info_cfg() const
  {
    return boundary_info_cfg_;
  }

  const BoundaryInfoType& boundary_info() const
  {
    return *boundary_info_;
  }

  const ProblemType& problem() const
  {
    return *problem_;
  }

  VectorType create_vector() const
  {
    return VectorType(ansatz_space_->mapper().size());
  }

  void visualize(const VectorType& vector,
                 const std::string filename,
                 const std::string name,
                 Pymor::Parameter mu = Pymor::Parameter()) const
  {
    VectorType tmp = vector.copy();
    const auto vectors = this->available_vectors();
    const auto result = std::find(vectors.begin(), vectors.end(), "dirichlet");
    if (result != vectors.end()) {
      const auto dirichlet_vector = this->get_vector("dirichlet");
      if (dirichlet_vector.parametric()) {
        const Pymor::Parameter mu_dirichlet = this->map_parameter(mu, "dirichlet");
        if (mu_dirichlet.type() != dirichlet_vector.parameter_type())
          DUNE_THROW_COLORFULLY(Pymor::Exceptions::wrong_parameter_type,
                                mu_dirichlet.type() << " vs. " << dirichlet_vector.parameter_type());
        tmp = dirichlet_vector.freeze_parameter(mu);
      } else
        tmp = *(dirichlet_vector.affine_part());
      tmp += vector;
    }
    const GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType >function(*(ansatz_space()), tmp, name);
    function.visualize(filename);
  } // ... visualize(...)

  void solve(VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const
  {
    const auto search_result = cache_.find(mu);
    if (search_result == cache_.end()) {
      uncached_solve(vector, mu);
      cache_.insert(std::make_pair(mu, Stuff::Common::make_unique< VectorType >(vector.copy())));
    } else {
      const auto& result = *(search_result->second);
      vector = result;
    }
  } // ... solve(...)

  void uncached_solve(VectorType& vector, const Pymor::Parameter mu) const
  {
    CHECK_AND_CALL_CRTP(this->as_imp(*this).uncached_solve(vector, mu));
  }

protected:
  const std::shared_ptr< const TestSpaceType > test_space_;
  const std::shared_ptr< const AnsatzSpaceType > ansatz_space_;
  const Stuff::Common::ConfigTree& boundary_info_cfg_;
  const std::shared_ptr< const BoundaryInfoType > boundary_info_;
  const ProblemType& problem_;

  mutable std::map< Pymor::Parameter, std::shared_ptr< VectorType > > cache_;
}; // class CachedDefault

template< class ImpTraits >
class ContainerBasedDefault
  : public CachedDefault< internal::ContainerBasedDefaultTraits< ImpTraits > >
{
  typedef CachedDefault< internal::ContainerBasedDefaultTraits< ImpTraits > > BaseType;
  typedef ContainerBasedDefault< ImpTraits >                                  ThisType;
public:
  typedef internal::ContainerBasedDefaultTraits< ImpTraits > Traits;
  typedef typename Traits::MatrixType     MatrixType;
  typedef typename Traits::OperatorType   OperatorType;
  typedef typename Traits::ProductType    ProductType;
  typedef typename Traits::FunctionalType FunctionalType;

  using typename BaseType::GridViewType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::ProblemType;
  using typename BaseType::TestSpaceType;
  using typename BaseType::AnsatzSpaceType;
  using typename BaseType::VectorType;

protected:
  typedef Pymor::LA::AffinelyDecomposedContainer< MatrixType > AffinelyDecomposedMatrixType;
  typedef Pymor::LA::AffinelyDecomposedContainer< VectorType > AffinelyDecomposedVectorType;

public:
  ContainerBasedDefault(const std::shared_ptr< const TestSpaceType >& test_spc,
                        const std::shared_ptr< const AnsatzSpaceType >& ansatz_spc,
                        const Stuff::Common::ConfigTree& bnd_inf_cfg,
                        const ProblemType& prb)
    : BaseType(test_spc, ansatz_spc, bnd_inf_cfg, prb)
    , container_based_initialized_(false)
  {}

  ContainerBasedDefault(const ThisType& other) = default;

  ThisType& operator=(const ThisType& other) = delete;

  OperatorType get_operator() const
  {
    assert_everything_is_ready();
    return OperatorType(*matrix_);
  }

  FunctionalType get_rhs() const
  {
    assert_everything_is_ready();
    return FunctionalType(*rhs_);
  }

  std::vector< std::string > available_products() const
  {
    if (products_.size() == 0)
      return std::vector< std::string >();
    std::vector< std::string > ret;
    for (const auto& pair : products_)
      ret.push_back(pair.first);
    return ret;
  } // ... available_products(...)

  ProductType get_product(const std::string id) const
  {
    if (products_.size() == 0)
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::you_are_using_this_wrongly,
                            "Do not call get_product() if available_products() is empty!");
    const auto result = products_.find(id);
    if (result == products_.end())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given, id);
    return ProductType(*(result->second));
  } // ... get_product(...)

  std::vector< std::string > available_vectors() const
  {
    if (vectors_.size() == 0)
      return std::vector< std::string >();
    std::vector< std::string > ret;
    for (const auto& pair : vectors_)
      ret.push_back(pair.first);
    return ret;
  } // ... available_vectors(...)

  AffinelyDecomposedVectorType get_vector(const std::string id) const
  {
    if (vectors_.size() == 0)
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::you_are_using_this_wrongly,
                            "Do not call get_vector() if available_vectors() is empty!");
    const auto result = vectors_.find(id);
    if (result == vectors_.end())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given, id);
    return *(result->second);
  } // ... get_vector(...)

  /**
   * \brief solves for u_0
   */
  void uncached_solve(VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const
  {
    assert_everything_is_ready();
    if (mu.type() != this->parameter_type())
      DUNE_THROW_COLORFULLY(Pymor::Exceptions::wrong_parameter_type,
                            mu.type() << " vs. " << this->parameter_type());
    // compute right hand side vector
    const auto& rhs = *(this->rhs_);
    std::shared_ptr< const VectorType > rhs_vector;
    if (!rhs.parametric())
      rhs_vector = rhs.affine_part();
    else {
      const Pymor::Parameter muRhs = this->map_parameter(mu, "rhs");
      rhs_vector = std::make_shared< const VectorType >(rhs.freeze_parameter(muRhs));
    }
    const OperatorType lhsOperator(*(this->matrix_));
    if (lhsOperator.parametric()) {
      const Pymor::Parameter muLhs = Pymor::Parametric::map_parameter(mu, "lhs");
      const auto frozenOperator = lhsOperator.freeze_parameter(muLhs);
      frozenOperator.apply_inverse(*rhs_vector, vector/*, option*/);
    } else {
      const auto nonparametricOperator = lhsOperator.affine_part();
      const std::string option = nonparametricOperator.invert_options()[0];
      nonparametricOperator.apply_inverse(*rhs_vector, vector, option);
    }
  } // ... uncached_solve(...)

protected:
  void assert_everything_is_ready() const
  {
    if (!container_based_initialized_)
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,
                            "The implemented discretization has to fill 'matrix_' and 'rhs_' during init() and set "
                            << "container_based_initialized_ = true!\n"
                            << "The user has to call init() before calling any other method!");
  } // ... assert_everything_is_ready()

  bool container_based_initialized_;
  mutable std::shared_ptr< AffinelyDecomposedMatrixType > matrix_;
  mutable std::shared_ptr< AffinelyDecomposedVectorType > rhs_;
  mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedMatrixType > > products_;
  mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedVectorType > > vectors_;
}; // class ContainerBasedDefault

} // namespace Discretizations
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
<commit_msg>[linearelliptic.discretizations.base] updated exceptions<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH

#include <map>
#include <algorithm>

#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>

#include <dune/pymor/operators/base.hh>
#include <dune/pymor/operators/affine.hh>
#include <dune/pymor/functionals/affine.hh>

#include <dune/gdt/discretefunction/default.hh>

#include "../../../linearelliptic/discretizations/interfaces.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Discretizations {

// forward
template< class ImpTraits >
class ContainerBasedDefault;

namespace internal {

template< class ImpTraits >
class ContainerBasedDefaultTraits
  : public ImpTraits
{
public:
  typedef ContainerBasedDefault< ImpTraits > derived_type;
  using typename ImpTraits::MatrixType;
  using typename ImpTraits::VectorType;
  typedef Pymor::Operators::LinearAffinelyDecomposedContainerBased< MatrixType, VectorType > OperatorType;
  typedef OperatorType ProductType;
  typedef Pymor::Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType;
}; // class ContainerBasedDefaultTraits

} // namespace internal

template< class ImpTraits >
class CachedDefault
  : public DiscretizationInterface< ImpTraits >
{
  typedef DiscretizationInterface< ImpTraits >  BaseType;
  typedef CachedDefault< ImpTraits >            ThisType;
public:
  using typename BaseType::GridViewType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::ProblemType;
  using typename BaseType::TestSpaceType;
  using typename BaseType::AnsatzSpaceType;
  using typename BaseType::VectorType;

private:
  typedef Stuff::Grid::BoundaryInfoProvider< typename GridViewType::Intersection > BoundaryInfoProvider;

public:
  CachedDefault(const std::shared_ptr< const TestSpaceType >& test_spc,
                const std::shared_ptr< const AnsatzSpaceType > ansatz_spc,
                const Stuff::Common::ConfigTree& bnd_inf_cfg,
                const ProblemType& prb)
    : BaseType(prb)
    , test_space_(test_spc)
    , ansatz_space_(ansatz_spc)
    , boundary_info_cfg_(bnd_inf_cfg)
    , boundary_info_(BoundaryInfoProvider::create(boundary_info_cfg_.get< std::string >("type"), boundary_info_cfg_))
    , problem_(prb)
  {}

  CachedDefault(const ThisType& other) = default;

  ThisType& operator=(const ThisType& other) = delete;

  const std::shared_ptr< const TestSpaceType >& test_space() const
  {
    return test_space_;
  }

  const std::shared_ptr< const AnsatzSpaceType >& ansatz_space() const
  {
    return test_space_;
  }

  const std::shared_ptr< const GridViewType >& grid_view() const
  {
    return test_space_->grid_view();
  }

  const Stuff::Common::ConfigTree& boundary_info_cfg() const
  {
    return boundary_info_cfg_;
  }

  const BoundaryInfoType& boundary_info() const
  {
    return *boundary_info_;
  }

  const ProblemType& problem() const
  {
    return *problem_;
  }

  VectorType create_vector() const
  {
    return VectorType(ansatz_space_->mapper().size());
  }

  void visualize(const VectorType& vector,
                 const std::string filename,
                 const std::string name,
                 Pymor::Parameter mu = Pymor::Parameter()) const
  {
    VectorType tmp = vector.copy();
    const auto vectors = this->available_vectors();
    const auto result = std::find(vectors.begin(), vectors.end(), "dirichlet");
    if (result != vectors.end()) {
      const auto dirichlet_vector = this->get_vector("dirichlet");
      if (dirichlet_vector.parametric()) {
        const Pymor::Parameter mu_dirichlet = this->map_parameter(mu, "dirichlet");
        if (mu_dirichlet.type() != dirichlet_vector.parameter_type())
          DUNE_THROW_COLORFULLY(Pymor::Exceptions::wrong_parameter_type,
                                mu_dirichlet.type() << " vs. " << dirichlet_vector.parameter_type());
        tmp = dirichlet_vector.freeze_parameter(mu);
      } else
        tmp = *(dirichlet_vector.affine_part());
      tmp += vector;
    }
    const GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType >function(*(ansatz_space()), tmp, name);
    function.visualize(filename);
  } // ... visualize(...)

  void solve(VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const
  {
    const auto search_result = cache_.find(mu);
    if (search_result == cache_.end()) {
      uncached_solve(vector, mu);
      cache_.insert(std::make_pair(mu, Stuff::Common::make_unique< VectorType >(vector.copy())));
    } else {
      const auto& result = *(search_result->second);
      vector = result;
    }
  } // ... solve(...)

  void uncached_solve(VectorType& vector, const Pymor::Parameter mu) const
  {
    CHECK_AND_CALL_CRTP(this->as_imp(*this).uncached_solve(vector, mu));
  }

protected:
  const std::shared_ptr< const TestSpaceType > test_space_;
  const std::shared_ptr< const AnsatzSpaceType > ansatz_space_;
  const Stuff::Common::ConfigTree& boundary_info_cfg_;
  const std::shared_ptr< const BoundaryInfoType > boundary_info_;
  const ProblemType& problem_;

  mutable std::map< Pymor::Parameter, std::shared_ptr< VectorType > > cache_;
}; // class CachedDefault

template< class ImpTraits >
class ContainerBasedDefault
  : public CachedDefault< internal::ContainerBasedDefaultTraits< ImpTraits > >
{
  typedef CachedDefault< internal::ContainerBasedDefaultTraits< ImpTraits > > BaseType;
  typedef ContainerBasedDefault< ImpTraits >                                  ThisType;
public:
  typedef internal::ContainerBasedDefaultTraits< ImpTraits > Traits;
  typedef typename Traits::MatrixType     MatrixType;
  typedef typename Traits::OperatorType   OperatorType;
  typedef typename Traits::ProductType    ProductType;
  typedef typename Traits::FunctionalType FunctionalType;

  using typename BaseType::GridViewType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::ProblemType;
  using typename BaseType::TestSpaceType;
  using typename BaseType::AnsatzSpaceType;
  using typename BaseType::VectorType;

protected:
  typedef Pymor::LA::AffinelyDecomposedContainer< MatrixType > AffinelyDecomposedMatrixType;
  typedef Pymor::LA::AffinelyDecomposedContainer< VectorType > AffinelyDecomposedVectorType;

public:
  ContainerBasedDefault(const std::shared_ptr< const TestSpaceType >& test_spc,
                        const std::shared_ptr< const AnsatzSpaceType >& ansatz_spc,
                        const Stuff::Common::ConfigTree& bnd_inf_cfg,
                        const ProblemType& prb)
    : BaseType(test_spc, ansatz_spc, bnd_inf_cfg, prb)
    , container_based_initialized_(false)
  {}

  ContainerBasedDefault(const ThisType& other) = default;

  ThisType& operator=(const ThisType& other) = delete;

  OperatorType get_operator() const
  {
    assert_everything_is_ready();
    return OperatorType(*matrix_);
  }

  FunctionalType get_rhs() const
  {
    assert_everything_is_ready();
    return FunctionalType(*rhs_);
  }

  std::vector< std::string > available_products() const
  {
    if (products_.size() == 0)
      return std::vector< std::string >();
    std::vector< std::string > ret;
    for (const auto& pair : products_)
      ret.push_back(pair.first);
    return ret;
  } // ... available_products(...)

  ProductType get_product(const std::string id) const
  {
    if (products_.size() == 0)
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::you_are_using_this_wrong,
                            "Do not call get_product() if available_products() is empty!");
    const auto result = products_.find(id);
    if (result == products_.end())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given, id);
    return ProductType(*(result->second));
  } // ... get_product(...)

  std::vector< std::string > available_vectors() const
  {
    if (vectors_.size() == 0)
      return std::vector< std::string >();
    std::vector< std::string > ret;
    for (const auto& pair : vectors_)
      ret.push_back(pair.first);
    return ret;
  } // ... available_vectors(...)

  AffinelyDecomposedVectorType get_vector(const std::string id) const
  {
    if (vectors_.size() == 0)
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::you_are_using_this_wrong,
                            "Do not call get_vector() if available_vectors() is empty!");
    const auto result = vectors_.find(id);
    if (result == vectors_.end())
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given, id);
    return *(result->second);
  } // ... get_vector(...)

  /**
   * \brief solves for u_0
   */
  void uncached_solve(VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const
  {
    assert_everything_is_ready();
    if (mu.type() != this->parameter_type())
      DUNE_THROW_COLORFULLY(Pymor::Exceptions::wrong_parameter_type,
                            mu.type() << " vs. " << this->parameter_type());
    // compute right hand side vector
    const auto& rhs = *(this->rhs_);
    std::shared_ptr< const VectorType > rhs_vector;
    if (!rhs.parametric())
      rhs_vector = rhs.affine_part();
    else {
      const Pymor::Parameter muRhs = this->map_parameter(mu, "rhs");
      rhs_vector = std::make_shared< const VectorType >(rhs.freeze_parameter(muRhs));
    }
    const OperatorType lhsOperator(*(this->matrix_));
    if (lhsOperator.parametric()) {
      const Pymor::Parameter muLhs = Pymor::Parametric::map_parameter(mu, "lhs");
      const auto frozenOperator = lhsOperator.freeze_parameter(muLhs);
      frozenOperator.apply_inverse(*rhs_vector, vector/*, option*/);
    } else {
      const auto nonparametricOperator = lhsOperator.affine_part();
      const std::string option = nonparametricOperator.invert_options()[0];
      nonparametricOperator.apply_inverse(*rhs_vector, vector, option);
    }
  } // ... uncached_solve(...)

protected:
  void assert_everything_is_ready() const
  {
    if (!container_based_initialized_)
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error,
                            "The implemented discretization has to fill 'matrix_' and 'rhs_' during init() and set "
                            << "container_based_initialized_ = true!\n"
                            << "The user has to call init() before calling any other method!");
  } // ... assert_everything_is_ready()

  bool container_based_initialized_;
  mutable std::shared_ptr< AffinelyDecomposedMatrixType > matrix_;
  mutable std::shared_ptr< AffinelyDecomposedVectorType > rhs_;
  mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedMatrixType > > products_;
  mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedVectorType > > vectors_;
}; // class ContainerBasedDefault

} // namespace Discretizations
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLGraphicsDefaultStyle.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 14:58:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

#ifndef _XMLOFF_FAMILIES_HXX
#include <xmloff/families.hxx>
#endif

#ifndef _XMLOFF_XMLSHAPEPROPERTYSETCONTEXT_HXX
#include "XMLShapePropertySetContext.hxx"
#endif

#ifndef _XMLOFF_XMLGRAPHICSDEFAULTSTYLE_HXX
#include <xmloff/XMLGraphicsDefaultStyle.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::xml::sax;

using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_TEXT_PROPERTIES;
using ::xmloff::token::XML_GRAPHIC_PROPERTIES;
using ::xmloff::token::XML_PARAGRAPH_PROPERTIES;

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

TYPEINIT1( XMLGraphicsDefaultStyle, XMLPropStyleContext );

XMLGraphicsDefaultStyle::XMLGraphicsDefaultStyle( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, SvXMLStylesContext& rStyles )
: XMLPropStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, XML_STYLE_FAMILY_SD_GRAPHICS_ID, sal_True )
{
}

XMLGraphicsDefaultStyle::~XMLGraphicsDefaultStyle()
{
}

SvXMLImportContext *XMLGraphicsDefaultStyle::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if( XML_NAMESPACE_STYLE == nPrefix )
    {
        sal_uInt32 nFamily = 0;
        if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_TEXT;
        else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_PARAGRAPH;
        else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_GRAPHIC;
        if( nFamily )
        {
            UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() );
            if( xImpPrMap.is() )
                pContext = new XMLShapePropertySetContext( GetImport(), nPrefix, rLocalName, xAttrList, nFamily, GetProperties(), xImpPrMap );
        }
    }

    if( !pContext )
        pContext = XMLPropStyleContext::CreateChildContext( nPrefix, rLocalName, xAttrList );

    return pContext;
}

// This method is called for every default style
void XMLGraphicsDefaultStyle::SetDefaults()
{
    Reference< XMultiServiceFactory > xFact( GetImport().GetModel(), UNO_QUERY );
    if( !xFact.is() )
        return;

    Reference< XPropertySet > xDefaults( xFact->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.Defaults") ) ), UNO_QUERY );
    if( !xDefaults.is() )
        return;

    FillPropertySet( xDefaults );
}

<commit_msg>INTEGRATION: CWS impresstables2 (1.5.80); FILE MERGED 2007/08/01 14:08:33 cl 1.5.80.2: RESYNC: (1.5-1.6); FILE MERGED 2007/07/27 09:09:51 cl 1.5.80.1: fixed build issues due to pch and namespace ::rtl<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLGraphicsDefaultStyle.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 10:30:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

#ifndef _XMLOFF_FAMILIES_HXX
#include <xmloff/families.hxx>
#endif

#ifndef _XMLOFF_XMLSHAPEPROPERTYSETCONTEXT_HXX
#include "XMLShapePropertySetContext.hxx"
#endif

#ifndef _XMLOFF_XMLGRAPHICSDEFAULTSTYLE_HXX
#include <xmloff/XMLGraphicsDefaultStyle.hxx>
#endif

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::xml::sax;

using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_TEXT_PROPERTIES;
using ::xmloff::token::XML_GRAPHIC_PROPERTIES;
using ::xmloff::token::XML_PARAGRAPH_PROPERTIES;

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

TYPEINIT1( XMLGraphicsDefaultStyle, XMLPropStyleContext );

XMLGraphicsDefaultStyle::XMLGraphicsDefaultStyle( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, SvXMLStylesContext& rStyles )
: XMLPropStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, XML_STYLE_FAMILY_SD_GRAPHICS_ID, sal_True )
{
}

XMLGraphicsDefaultStyle::~XMLGraphicsDefaultStyle()
{
}

SvXMLImportContext *XMLGraphicsDefaultStyle::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if( XML_NAMESPACE_STYLE == nPrefix )
    {
        sal_uInt32 nFamily = 0;
        if( IsXMLToken( rLocalName, XML_TEXT_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_TEXT;
        else if( IsXMLToken( rLocalName, XML_PARAGRAPH_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_PARAGRAPH;
        else if( IsXMLToken( rLocalName, XML_GRAPHIC_PROPERTIES ) )
            nFamily = XML_TYPE_PROP_GRAPHIC;
        if( nFamily )
        {
            UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() );
            if( xImpPrMap.is() )
                pContext = new XMLShapePropertySetContext( GetImport(), nPrefix, rLocalName, xAttrList, nFamily, GetProperties(), xImpPrMap );
        }
    }

    if( !pContext )
        pContext = XMLPropStyleContext::CreateChildContext( nPrefix, rLocalName, xAttrList );

    return pContext;
}

// This method is called for every default style
void XMLGraphicsDefaultStyle::SetDefaults()
{
    Reference< XMultiServiceFactory > xFact( GetImport().GetModel(), UNO_QUERY );
    if( !xFact.is() )
        return;

    Reference< XPropertySet > xDefaults( xFact->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.Defaults") ) ), UNO_QUERY );
    if( !xDefaults.is() )
        return;

    FillPropertySet( xDefaults );
}

<|endoftext|>


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

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE router

#include <boost/test/unit_test.hpp>

#include "config.h"
#include "json/cJSON.h"
#include "peer.h"
#include "router.h"
#include "state.h"

extern "C" {
	int send_message(struct peer *p, const char *rendered, size_t len)
	{
		return 0;
	}

	void remove_all_states_from_peer(struct peer *p)
	{
	}

	int add_io(struct peer *p)
	{
		return 0;
	}

	void remove_io(const struct peer *p)
	{
		return;
	}

	void remove_all_methods_from_peer(struct peer *p)
	{
	}

	void remove_all_fetchers_from_peer(struct peer *p)
	{
	}
}

static cJSON *create_response_no_id()
{
	cJSON *root = cJSON_CreateObject();
	BOOST_REQUIRE(root != NULL);
	cJSON_AddStringToObject(root, "result", "o.k.");

	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddItemToObject(root, "params", params);
	return root;
}

static cJSON *create_response_wrong_id()
{
	cJSON *root = cJSON_CreateObject();
	BOOST_REQUIRE(root != NULL);
	cJSON_AddTrueToObject(root, "id");
	cJSON_AddStringToObject(root, "result", "o.k.");

	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddItemToObject(root, "params", params);
	return root;
}

struct F {
	F()
	{
		p = alloc_peer(-1);
	}
	~F()
	{
		free_peer(p);
	}

	struct peer *p;
};

BOOST_FIXTURE_TEST_CASE(handle_response, F)
{
	cJSON *response = create_response_no_id();
	cJSON *result = cJSON_GetObjectItem(response, "result");
	int ret = handle_routing_response(response, result, "result", p);
	BOOST_CHECK(ret == -1);

	response = create_response_wrong_id();
	result = cJSON_GetObjectItem(response, "result");
	ret = handle_routing_response(response, result, "result", p);
	BOOST_CHECK(ret == -1);
}

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

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE router

#include <boost/test/unit_test.hpp>

#include "config.h"
#include "json/cJSON.h"
#include "peer.h"
#include "router.h"
#include "state.h"

extern "C" {
	int send_message(struct peer *p, const char *rendered, size_t len)
	{
		return 0;
	}

	void remove_all_states_from_peer(struct peer *p)
	{
	}

	int add_io(struct peer *p)
	{
		return 0;
	}

	void remove_io(const struct peer *p)
	{
		return;
	}

	void remove_all_methods_from_peer(struct peer *p)
	{
	}

	void remove_all_fetchers_from_peer(struct peer *p)
	{
	}
}

static cJSON *create_response_no_id()
{
	cJSON *root = cJSON_CreateObject();
	BOOST_REQUIRE(root != NULL);
	cJSON_AddStringToObject(root, "result", "o.k.");

	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddItemToObject(root, "params", params);
	return root;
}

static cJSON *create_response_wrong_id()
{
	cJSON *root = cJSON_CreateObject();
	BOOST_REQUIRE(root != NULL);
	cJSON_AddTrueToObject(root, "id");
	cJSON_AddStringToObject(root, "result", "o.k.");

	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddItemToObject(root, "params", params);
	return root;
}

struct F {
	F()
	{
		p = alloc_peer(-1);
	}
	~F()
	{
		free_peer(p);
	}

	struct peer *p;
};

BOOST_FIXTURE_TEST_CASE(handle_response, F)
{
	cJSON *response = create_response_no_id();
	cJSON *result = cJSON_GetObjectItem(response, "result");
	int ret = handle_routing_response(response, result, "result", p);
	BOOST_CHECK(ret == -1);
	cJSON_Delete(response);

	response = create_response_wrong_id();
	result = cJSON_GetObjectItem(response, "result");
	ret = handle_routing_response(response, result, "result", p);
	BOOST_CHECK(ret == -1);
	cJSON_Delete(response);
}

<|endoftext|>