<commit_before>#define _IRR_STATIC_LIB_
#include <irrlicht.h>
#include "driverChoice.h"

#include "../source/Irrlicht/CGeometryCreator.h"
#include "../source/Irrlicht/CBAWMeshWriter.h"

using namespace irr;
using namespace core;

//!Same As Last Example
class MyEventReceiver : public IEventReceiver
{
public:

	MyEventReceiver()
	{
	}

	bool OnEvent(const SEvent& event)
	{
        if (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown)
        {
            switch (event.KeyInput.Key)
            {
            case irr::KEY_KEY_Q: // switch wire frame mode
                exit(0);
                return true;
            default:
                break;
            }
        }

		return false;
	}

private:
};

class SimpleCallBack : public video::IShaderConstantSetCallBack
{
    int32_t mvpUniformLocation;
    int32_t cameraDirUniformLocation;
    int32_t texUniformLocation[4];
    video::E_SHADER_CONSTANT_TYPE mvpUniformType;
    video::E_SHADER_CONSTANT_TYPE cameraDirUniformType;
    video::E_SHADER_CONSTANT_TYPE texUniformType[4];
public:
    SimpleCallBack() : cameraDirUniformLocation(-1), cameraDirUniformType(video::ESCT_FLOAT_VEC3) {}

    virtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::array<video::SConstantLocationNamePair>& constants)
    {
        for (size_t i=0; i<constants.size(); i++)
        {
            if (constants[i].name=="MVP")
            {
                mvpUniformLocation = constants[i].location;
                mvpUniformType = constants[i].type;
            }
            else if (constants[i].name=="cameraPos")
            {
                cameraDirUniformLocation = constants[i].location;
                cameraDirUniformType = constants[i].type;
            }
            else if (constants[i].name=="tex0")
            {
                texUniformLocation[0] = constants[i].location;
                texUniformType[0] = constants[i].type;
            }
            else if (constants[i].name=="tex3")
            {
                texUniformLocation[3] = constants[i].location;
                texUniformType[3] = constants[i].type;
            }
        }
    }

    virtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData)
    {
        core::vectorSIMDf modelSpaceCamPos;
        modelSpaceCamPos.set(services->getVideoDriver()->getTransform(video::E4X3TS_WORLD_VIEW_INVERSE).getTranslation());
        services->setShaderConstant(&modelSpaceCamPos,cameraDirUniformLocation,cameraDirUniformType,1);
        services->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(),mvpUniformLocation,mvpUniformType,1);
/*
        int32_t id[] = {0,1,2,3};
        services->setShaderTextures(id+0,texUniformLocation[0],texUniformType[0],1);
        services->setShaderTextures(id+3,texUniformLocation[3],texUniformType[3],1);*/
    }

    virtual void OnUnsetMaterial() {}
};

int main()
{
	// create device with full flexibility over creation parameters
	// you can add more parameters if desired, check irr::SIrrlichtCreationParameters
	irr::SIrrlichtCreationParameters params;
	params.Bits = 24; //may have to set to 32bit for some platforms
	params.ZBufferBits = 24; //we'd like 32bit here
	params.DriverType = video::EDT_OPENGL; //! Only Well functioning driver, software renderer left for sake of 2D image drawing
	params.WindowSize = dimension2d<uint32_t>(1280, 720);
	params.Fullscreen = false;
	params.Vsync = true; //! If supported by target platform
	params.Doublebuffer = true;
	params.Stencilbuffer = false; //! This will not even be a choice soon
	IrrlichtDevice* device = createDeviceEx(params);

	if (device == 0)
		return 1; // could not create selected driver.

	video::IVideoDriver* driver = device->getVideoDriver();

    SimpleCallBack* cb = new SimpleCallBack();
    video::E_MATERIAL_TYPE newMaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles("../mesh.vert",
                                                        "","","", //! No Geometry or Tessellation Shaders
                                                        "../mesh.frag",
                                                        3,video::EMT_SOLID, //! 3 vertices per primitive (this is tessellation shader relevant only
                                                        cb, //! Our Shader Callback
                                                        0); //! No custom user data
    cb->drop();

	scene::ISceneManager* smgr = device->getSceneManager();
	driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
	scene::ICameraSceneNode* camera =
		smgr->addCameraSceneNodeFPS(0,100.0f,0.01f);
	camera->setPosition(core::vector3df(-4,0,0));
	camera->setTarget(core::vector3df(0,0,0));
	camera->setNearValue(0.01f);
	camera->setFarValue(100.0f);
    smgr->setActiveCamera(camera);
	device->getCursorControl()->setVisible(false);
	MyEventReceiver receiver;
	device->setEventReceiver(&receiver);

	io::IFileSystem* fs = device->getFileSystem();
	scene::IMeshWriter* writer = smgr->createMeshWriter(irr::scene::EMWT_BAW);

	//! Test Loading of Obj
    scene::ICPUMesh* cpumesh = smgr->getMesh("../../media/extrusionLogo_TEST_fixed.stl");
	// export mesh
	io::IWriteFile* file = fs->createAndWriteFile("extrusionLogo_TEST_fixed.baw");
	writer->writeMesh(file, cpumesh);
	file->drop();
	// end export
    if (cpumesh)
    {
        scene::IGPUMesh* gpumesh = driver->createGPUMeshFromCPU(dynamic_cast<scene::SCPUMesh*>(cpumesh));
        smgr->getMeshCache()->removeMesh(cpumesh);
        smgr->addMeshSceneNode(gpumesh)->setMaterialType(newMaterialType);
        gpumesh->drop();
    }

    cpumesh = smgr->getMesh("../../media/cow.obj");
	// export mesh
	file = fs->createAndWriteFile("cow.baw");
	writer->writeMesh(file, cpumesh);
	file->drop();
	writer->drop();
	// end export
    if (cpumesh)
    {
        scene::IGPUMesh* gpumesh = driver->createGPUMeshFromCPU(dynamic_cast<scene::SCPUMesh*>(cpumesh));
        smgr->getMeshCache()->removeMesh(cpumesh);
        smgr->addMeshSceneNode(gpumesh,0,-1,core::vector3df(3.f,1.f,0.f))->setMaterialType(newMaterialType);
        gpumesh->drop();
    }

	uint64_t lastFPSTime = 0;

	while(device->run())
	//if (device->isWindowActive())
	{
		driver->beginScene(true, true, video::SColor(255,0,0,255) );

        //! This animates (moves) the camera and sets the transforms
        //! Also draws the meshbuffer
        smgr->drawAll();

        //! Stress test for memleaks aside from demo how to create meshes that live on the GPU RAM
        {/*
            scene::IGPUMeshBuffer* mb = new scene::IGPUMeshBuffer();
            scene::IGPUMeshDataFormatDesc* desc = driver->createGPUMeshDataFormatDesc();
            mb->setMeshDataAndFormat(desc);
            desc->drop();

            uint16_t indices_indexed16[] = {
                0,1,2,1,2,3,
                4,5,6,5,6,7,
                0,1,4,1,4,5,
                2,3,6,3,6,7,
                0,2,4,2,4,6,
                1,3,5,3,5,7
            };
            video::IGPUBuffer* index = driver->createGPUBuffer(sizeof(indices_indexed16),indices_indexed16);
            desc->mapIndexBuffer(index);
            mb->setIndexType(video::EIT_16BIT);
            mb->setIndexCount(2*3*6);
            mb->setIndexRange(0,7);
            index->drop();

            float attrArr[] = {
                -1.f,-1.f,-1.f,0.f,0.f,
                 1.f,-1.f,-1.f,0.5f,0.f,
                -1.f, 1.f,-1.f,1.f,0.f,
                 1.f, 1.f,-1.f,0.f,0.5f,
                -1.f,-1.f, 1.f,0.5f,0.5f,
                 1.f,-1.f, 1.f,1.f,0.5f,
                -1.f, 1.f, 1.f,0.f,1.f,
                 1.f, 1.f, 1.f,0.5f,1.f
            };
            video::IGPUBuffer* attr0 = driver->createGPUBuffer(sizeof(attrArr),attrArr);
            desc->mapVertexAttrBuffer(attr0,scene::EVAI_ATTR0,scene::ECPA_THREE,scene::ECT_FLOAT,20,0);
            desc->mapVertexAttrBuffer(attr0,scene::EVAI_ATTR1,scene::ECPA_TWO,scene::ECT_FLOAT,20,3*4);
            attr0->drop();

            driver->setTransform(video::ETS_WORLD,core::matrix4());
            driver->setMaterial(material);
            driver->drawMeshBuffer(mb);
            mb->drop();*/
        }

		driver->endScene();

		// display frames per second in window title
		uint64_t time = device->getTimer()->getRealTime();
		if (time-lastFPSTime > 1000)
		{
			std::wostringstream sstr;
			sstr << L"Builtin Nodes Demo - Irrlicht Engine FPS:" << driver->getFPS() << " PrimitvesDrawn:" << driver->getPrimitiveCountDrawn();

			device->setWindowCaption(sstr.str().c_str());
			lastFPSTime = time;
		}
	}

	device->drop();

	return 0;
}
<commit_msg>Modified MeshLoaders example to test BAW mesh loader<commit_after>#define _IRR_STATIC_LIB_
#include <irrlicht.h>
#include "driverChoice.h"

#include "../source/Irrlicht/CGeometryCreator.h"
#include "../source/Irrlicht/CBAWMeshWriter.h"

using namespace irr;
using namespace core;

//!Same As Last Example
class MyEventReceiver : public IEventReceiver
{
public:

	MyEventReceiver()
	{
	}

	bool OnEvent(const SEvent& event)
	{
        if (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown)
        {
            switch (event.KeyInput.Key)
            {
            case irr::KEY_KEY_Q: // switch wire frame mode
                exit(0);
                return true;
            default:
                break;
            }
        }

		return false;
	}

private:
};

class SimpleCallBack : public video::IShaderConstantSetCallBack
{
    int32_t mvpUniformLocation;
    int32_t cameraDirUniformLocation;
    int32_t texUniformLocation[4];
    video::E_SHADER_CONSTANT_TYPE mvpUniformType;
    video::E_SHADER_CONSTANT_TYPE cameraDirUniformType;
    video::E_SHADER_CONSTANT_TYPE texUniformType[4];
public:
    SimpleCallBack() : cameraDirUniformLocation(-1), cameraDirUniformType(video::ESCT_FLOAT_VEC3) {}

    virtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::array<video::SConstantLocationNamePair>& constants)
    {
        for (size_t i=0; i<constants.size(); i++)
        {
            if (constants[i].name=="MVP")
            {
                mvpUniformLocation = constants[i].location;
                mvpUniformType = constants[i].type;
            }
            else if (constants[i].name=="cameraPos")
            {
                cameraDirUniformLocation = constants[i].location;
                cameraDirUniformType = constants[i].type;
            }
            else if (constants[i].name=="tex0")
            {
                texUniformLocation[0] = constants[i].location;
                texUniformType[0] = constants[i].type;
            }
            else if (constants[i].name=="tex3")
            {
                texUniformLocation[3] = constants[i].location;
                texUniformType[3] = constants[i].type;
            }
        }
    }

    virtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData)
    {
        core::vectorSIMDf modelSpaceCamPos;
        modelSpaceCamPos.set(services->getVideoDriver()->getTransform(video::E4X3TS_WORLD_VIEW_INVERSE).getTranslation());
        services->setShaderConstant(&modelSpaceCamPos,cameraDirUniformLocation,cameraDirUniformType,1);
        services->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(),mvpUniformLocation,mvpUniformType,1);
/*
        int32_t id[] = {0,1,2,3};
        services->setShaderTextures(id+0,texUniformLocation[0],texUniformType[0],1);
        services->setShaderTextures(id+3,texUniformLocation[3],texUniformType[3],1);*/
    }

    virtual void OnUnsetMaterial() {}
};

int main()
{
	// create device with full flexibility over creation parameters
	// you can add more parameters if desired, check irr::SIrrlichtCreationParameters
	irr::SIrrlichtCreationParameters params;
	params.Bits = 24; //may have to set to 32bit for some platforms
	params.ZBufferBits = 24; //we'd like 32bit here
	params.DriverType = video::EDT_OPENGL; //! Only Well functioning driver, software renderer left for sake of 2D image drawing
	params.WindowSize = dimension2d<uint32_t>(1280, 720);
	params.Fullscreen = false;
	params.Vsync = true; //! If supported by target platform
	params.Doublebuffer = true;
	params.Stencilbuffer = false; //! This will not even be a choice soon
	IrrlichtDevice* device = createDeviceEx(params);

	if (device == 0)
		return 1; // could not create selected driver.

	video::IVideoDriver* driver = device->getVideoDriver();

    SimpleCallBack* cb = new SimpleCallBack();
    video::E_MATERIAL_TYPE newMaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles("../mesh.vert",
                                                        "","","", //! No Geometry or Tessellation Shaders
                                                        "../mesh.frag",
                                                        3,video::EMT_SOLID, //! 3 vertices per primitive (this is tessellation shader relevant only
                                                        cb, //! Our Shader Callback
                                                        0); //! No custom user data
    cb->drop();

	scene::ISceneManager* smgr = device->getSceneManager();
	driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
	scene::ICameraSceneNode* camera =
		smgr->addCameraSceneNodeFPS(0,100.0f,0.01f);
	camera->setPosition(core::vector3df(-4,0,0));
	camera->setTarget(core::vector3df(0,0,0));
	camera->setNearValue(0.01f);
	camera->setFarValue(100.0f);
    smgr->setActiveCamera(camera);
	device->getCursorControl()->setVisible(false);
	MyEventReceiver receiver;
	device->setEventReceiver(&receiver);

	io::IFileSystem* fs = device->getFileSystem();
	scene::IMeshWriter* writer = smgr->createMeshWriter(irr::scene::EMWT_BAW);

	// from Criss:
	// here i'm testing baw mesh writer and loader
	// (import from .stl/.obj, then export to .baw, then import from .baw :D)
	// Seems to work for those two simple meshes, but need more testing!

	//! Test Loading of Obj
    scene::ICPUMesh* cpumesh = smgr->getMesh("../../media/extrusionLogo_TEST_fixed.stl");
	// export mesh
	io::IWriteFile* file = fs->createAndWriteFile("extrusionLogo_TEST_fixed.baw");
	writer->writeMesh(file, cpumesh);
	file->drop();
	// end export

	// import .baw mesh (test)
	cpumesh = smgr->getMesh("extrusionLogo_TEST_fixed.baw");
	// end import

    if (cpumesh)
    {
        scene::IGPUMesh* gpumesh = driver->createGPUMeshFromCPU(dynamic_cast<scene::SCPUMesh*>(cpumesh));
        smgr->getMeshCache()->removeMesh(cpumesh);
        smgr->addMeshSceneNode(gpumesh)->setMaterialType(newMaterialType);
        gpumesh->drop();
    }

    cpumesh = smgr->getMesh("../../media/cow.obj");
	// export mesh
	file = fs->createAndWriteFile("cow.baw");
	writer->writeMesh(file, cpumesh);
	file->drop();
	writer->drop();
	// end export

	// import .baw mesh (test)
	cpumesh = smgr->getMesh("cow.baw");
	// end import

    if (cpumesh)
    {
        scene::IGPUMesh* gpumesh = driver->createGPUMeshFromCPU(dynamic_cast<scene::SCPUMesh*>(cpumesh));
        smgr->getMeshCache()->removeMesh(cpumesh);
        smgr->addMeshSceneNode(gpumesh,0,-1,core::vector3df(3.f,1.f,0.f))->setMaterialType(newMaterialType);
        gpumesh->drop();
    }

	uint64_t lastFPSTime = 0;

	while(device->run())
	//if (device->isWindowActive())
	{
		driver->beginScene(true, true, video::SColor(255,0,0,255) );

        //! This animates (moves) the camera and sets the transforms
        //! Also draws the meshbuffer
        smgr->drawAll();

        //! Stress test for memleaks aside from demo how to create meshes that live on the GPU RAM
        {/*
            scene::IGPUMeshBuffer* mb = new scene::IGPUMeshBuffer();
            scene::IGPUMeshDataFormatDesc* desc = driver->createGPUMeshDataFormatDesc();
            mb->setMeshDataAndFormat(desc);
            desc->drop();

            uint16_t indices_indexed16[] = {
                0,1,2,1,2,3,
                4,5,6,5,6,7,
                0,1,4,1,4,5,
                2,3,6,3,6,7,
                0,2,4,2,4,6,
                1,3,5,3,5,7
            };
            video::IGPUBuffer* index = driver->createGPUBuffer(sizeof(indices_indexed16),indices_indexed16);
            desc->mapIndexBuffer(index);
            mb->setIndexType(video::EIT_16BIT);
            mb->setIndexCount(2*3*6);
            mb->setIndexRange(0,7);
            index->drop();

            float attrArr[] = {
                -1.f,-1.f,-1.f,0.f,0.f,
                 1.f,-1.f,-1.f,0.5f,0.f,
                -1.f, 1.f,-1.f,1.f,0.f,
                 1.f, 1.f,-1.f,0.f,0.5f,
                -1.f,-1.f, 1.f,0.5f,0.5f,
                 1.f,-1.f, 1.f,1.f,0.5f,
                -1.f, 1.f, 1.f,0.f,1.f,
                 1.f, 1.f, 1.f,0.5f,1.f
            };
            video::IGPUBuffer* attr0 = driver->createGPUBuffer(sizeof(attrArr),attrArr);
            desc->mapVertexAttrBuffer(attr0,scene::EVAI_ATTR0,scene::ECPA_THREE,scene::ECT_FLOAT,20,0);
            desc->mapVertexAttrBuffer(attr0,scene::EVAI_ATTR1,scene::ECPA_TWO,scene::ECT_FLOAT,20,3*4);
            attr0->drop();

            driver->setTransform(video::ETS_WORLD,core::matrix4());
            driver->setMaterial(material);
            driver->drawMeshBuffer(mb);
            mb->drop();*/
        }

		driver->endScene();

		// display frames per second in window title
		uint64_t time = device->getTimer()->getRealTime();
		if (time-lastFPSTime > 1000)
		{
			std::wostringstream sstr;
			sstr << L"Builtin Nodes Demo - Irrlicht Engine FPS:" << driver->getFPS() << " PrimitvesDrawn:" << driver->getPrimitiveCountDrawn();

			device->setWindowCaption(sstr.str().c_str());
			lastFPSTime = time;
		}
	}

	device->drop();

	return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbRadiometricAttributesLabelMapFilter.h"
#include "otbVectorImage.h"
#include "itkLabelMap.h"
#include "otbAttributesMapLabelObject.h"

int otbRadiometricAttributesLabelMapFilterNew(int argc, char * argv[])
{
  const unsigned int Dimension = 2;
  typedef unsigned short                         LabelType;
  typedef double                         PixelType;

  typedef otb::AttributesMapLabelObject<LabelType,Dimension,double>      LabelObjectType;
  typedef itk::LabelMap<LabelObjectType>                                 LabelMapType;
  typedef otb::VectorImage<PixelType,Dimension>                          VectorImageType;
  typedef otb::RadiometricAttributesLabelMapFilter<LabelMapType,VectorImageType> RadiometricLabelMapFilterType;

  // Instantiation
  RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();

  return EXIT_SUCCESS;
}<commit_msg>ENH : add newline at the end<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbRadiometricAttributesLabelMapFilter.h"
#include "otbVectorImage.h"
#include "itkLabelMap.h"
#include "otbAttributesMapLabelObject.h"

int otbRadiometricAttributesLabelMapFilterNew(int argc, char * argv[])
{
  const unsigned int Dimension = 2;
  typedef unsigned short                         LabelType;
  typedef double                         PixelType;

  typedef otb::AttributesMapLabelObject<LabelType,Dimension,double>      LabelObjectType;
  typedef itk::LabelMap<LabelObjectType>                                 LabelMapType;
  typedef otb::VectorImage<PixelType,Dimension>                          VectorImageType;
  typedef otb::RadiometricAttributesLabelMapFilter<LabelMapType,VectorImageType> RadiometricLabelMapFilterType;

  // Instantiation
  RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "UnixSocketTransport.hpp"

namespace Eth{

bool UnixSocketConnector::connect(UnixSocket &socket, const char *path)
{
    UnixEndpoint endpoint(path);
    boost::system::error_code ec;
    socket.connect(endpoint, ec);
    return !ec;
}

}

<commit_msg>log connection error<commit_after>#include "UnixSocketTransport.hpp"

namespace Eth{

bool UnixSocketConnector::connect(UnixSocket &socket, const char *path)
{
    UnixEndpoint endpoint(path);
    boost::system::error_code ec;
    socket.connect(endpoint, ec);

    if(ec)
    {
        LOG_DEBUG("connection to "<<path<<" failed : "<<ec);

        return false;
    }

    return true;
}

}

<|endoftext|>


<commit_before>
#include "DatabaseBinarySerialiser.h"
#include "Database.h"
#include "DatabaseMetadata.h"

#include <vector>

namespace
{
	template <typename TYPE, int SIZE>
	void CopyInteger(const crdb::Database&, char* dest, const char* source, int)
	{
		// Ensure the assumed size is the same as the machine size
		int assert_size_is_correct[sizeof(TYPE) == SIZE];
		(void)assert_size_is_correct;

		// Quick assign copy
		*(TYPE*)dest = *(TYPE*)source;
	}

	void MemCopy(const crdb::Database&, char* dest, const char* source, int size)
	{
		memcpy(dest, source, size);
	}

	void CopyName(const crdb::Database& db, char* dest, const char* source, int)
	{
		// Copy the hash
		crdb::Name& name = *(crdb::Name*)source;
		*(crdb::u32*)dest = name == db.GetNoName() ? 0 : name->first;
	}

	template <void PACK_FUNC(const crdb::Database&, char*, const char*, int)>
	void PackStridedData(const crdb::Database& db, char* dest, const char* source, int nb_entries, int dest_stride, int source_stride, int field_size)
	{
		// The compiler should be able to inline the call the PACK_FUNC for each entry
		for (int i = 0; i < nb_entries; i++)
		{
			PACK_FUNC(db, dest, source, field_size);
			dest += dest_stride;
			source += source_stride;
		}
	}

	void PackBasicFields(const crdb::Database& db, char* dest, const char* source, int nb_entries, const crdb::meta::DatabaseType& type, const crdb::meta::DatabaseField& field)
	{
		// Use memcpy as a last resort - try at least to use some big machine-size types
		switch (field.size)
		{
		case (1): PackStridedData< CopyInteger<bool, 1> >(db, dest, source, nb_entries, type.packed_size, type.size, 0); break;
		case (2): PackStridedData< CopyInteger<short, 2> >(db, dest, source, nb_entries, type.packed_size, type.size, 0); break;
		case (4): PackStridedData< CopyInteger<int, 4> >(db, dest, source, nb_entries, type.packed_size, type.size, 0); break;
		case (8): PackStridedData< CopyInteger<__int64, 8> >(db, dest, source, nb_entries, type.packed_size, type.size, 0); break;
		default: PackStridedData< MemCopy >(db, dest, source, nb_entries, type.packed_size, type.size, field.size); break;
		}
	}

	void PackNameFields(const crdb::Database& db, char* dest, const char* source, int nb_entries, const crdb::meta::DatabaseType& type, const crdb::meta::DatabaseField& field)
	{
		PackStridedData< CopyName >(db, dest, source, nb_entries, type.packed_size, type.size, 0);
	}

	template <typename TYPE>
	void CopyPrimitiveStoreToTable(const crdb::PrimitiveStore<TYPE>& store, std::vector<TYPE>& table, bool named)
	{
		int dest_index = 0;

		// Make a local copy of all entries in the table
		if (named)
		{
			table.resize(store.named.size());
			for (crdb::PrimitiveStore<TYPE>::NamedStore::const_iterator i = store.named.begin(); i != store.named.end(); ++i)
			{
				table[dest_index++] = i->second;
			}
		}
		else
		{
			table.resize(store.unnamed.size());
			for (crdb::PrimitiveStore<TYPE>::UnnamedStore::const_iterator i = store.unnamed.begin(); i != store.unnamed.end(); ++i)
			{
				table[dest_index++] = *i;
			}
		}
	}

	template <typename TYPE>
	void PackTable(const crdb::Database& db, const std::vector<TYPE>& table, const crdb::meta::DatabaseType& type, char* output)
	{
		// Walk up through the inheritance hierarhcy
		for (const crdb::meta::DatabaseType* cur_type = &type; cur_type; cur_type = cur_type->base_type)
		{
			// Pack a field at a time
			for (size_t i = 0; i < cur_type->fields.size(); i++)
			{
				const crdb::meta::DatabaseField& field = cur_type->fields[i];

				// Start at the offset from the field within the first object
				char* dest = output + field.packed_offset;
				char* source = (char*)&table.front() + field.offset;

				// Perform strided copies depending on field type - pass information about the root type
				switch (field.type)
				{
				case (crdb::meta::FIELD_TYPE_BASIC): PackBasicFields(db, dest, source, table.size(), type, field); break;
				case (crdb::meta::FIELD_TYPE_NAME): PackNameFields(db, dest, source, table.size(), type, field); break;
				}
			}
		}
	}

	template <typename TYPE>
	void WriteTable(FILE* fp, const crdb::Database& db, const crdb::meta::DatabaseTypes& dbtypes, bool named)
	{
		// Generate a memory-contiguous table
		std::vector<TYPE> table;
		CopyPrimitiveStoreToTable(db.GetPrimitiveStore<TYPE>(), table, named);

		// Record the table size
		int table_size = table.size();
		fwrite(&table_size, sizeof(int), 1, fp);

		if (table_size)
		{
			// Allocate enough memory to store the table in packed binary format
			const crdb::meta::DatabaseType& type = dbtypes.GetType<TYPE>();
			int packed_size = table_size * type.packed_size;
			char* data = new char[packed_size];

			// Binary pack the table
			PackTable(db, table, type, data);

			// Write to file and cleanup
			fwrite(data, packed_size, 1, fp);
			delete [] data;
		}
	}

	template <typename TYPE>
	void WriteTable(FILE* fp, const crdb::Database& db, const crdb::meta::DatabaseTypes& dbtypes)
	{
		// Write both named and unnamed tables
		// The unnamed tables contain the empty names, but this makes the code much simpler
		// at the expense of file sizes that are little larger
		WriteTable<TYPE>(fp, db, dbtypes, true);
		WriteTable<TYPE>(fp, db, dbtypes, false);
	}
}

void crdb::WriteBinaryDatabase(const char* filename, const Database& db)
{
	FILE* fp = fopen(filename, "wb");

	crdb::meta::DatabaseTypes dbtypes;
	WriteTable<crdb::Namespace>(fp, db, dbtypes);
	WriteTable<crdb::Type>(fp, db, dbtypes);
	WriteTable<crdb::Class>(fp, db, dbtypes);
	WriteTable<crdb::Enum>(fp, db, dbtypes);
	WriteTable<crdb::EnumConstant>(fp, db, dbtypes);
	WriteTable<crdb::Function>(fp, db, dbtypes);
	WriteTable<crdb::Field>(fp, db, dbtypes);

	fclose(fp);
}<commit_msg>Added writing of the name table. Binary size is very similar to the text size!<commit_after>
#include "DatabaseBinarySerialiser.h"
#include "Database.h"
#include "DatabaseMetadata.h"

#include <vector>

namespace
{
	template <typename TYPE, int SIZE>
	void CopyInteger(const crdb::Database&, char* dest, const char* source, int)
	{
		// Ensure the assumed size is the same as the machine size
		int assert_size_is_correct[sizeof(TYPE) == SIZE];
		(void)assert_size_is_correct;

		// Quick assign copy
		*(TYPE*)dest = *(TYPE*)source;
	}

	void MemCopy(const crdb::Database&, char* dest, const char* source, int size)
	{
		memcpy(dest, source, size);
	}

	void CopyName(const crdb::Database& db, char* dest, const char* source, int)
	{
		// Copy the hash
		crdb::Name& name = *(crdb::Name*)source;
		*(crdb::u32*)dest = name == db.GetNoName() ? 0 : name->first;
	}

	template <void PACK_FUNC(const crdb::Database&, char*, const char*, int)>
	void PackStridedData(const crdb::Database& db, char* dest, const char* source, int nb_entries, int dest_stride, int source_stride, int field_size)
	{
		// The compiler should be able to inline the call the PACK_FUNC for each entry
		for (int i = 0; i < nb_entries; i++)
		{
			PACK_FUNC(db, dest, source, field_size);
			dest += dest_stride;
			source += source_stride;
		}
	}

	void PackBasicFields(const crdb::Database& db, char* dest, const char* source, int nb_entries, const crdb::meta::DatabaseType& type, const crdb::meta::DatabaseField& field)
	{
		// Use memcpy as a last resort - try at least to use some big machine-size types
		switch (field.size)
		{
		case (1): PackStridedData< CopyInteger<bool, 1> >(db, dest, source, nb_entries, type.packed_size, type.size, 0); break;
		case (2): PackStridedData< CopyInteger<short, 2> >(db, dest, source, nb_entries, type.packed_size, type.size, 0); break;
		case (4): PackStridedData< CopyInteger<int, 4> >(db, dest, source, nb_entries, type.packed_size, type.size, 0); break;
		case (8): PackStridedData< CopyInteger<__int64, 8> >(db, dest, source, nb_entries, type.packed_size, type.size, 0); break;
		default: PackStridedData< MemCopy >(db, dest, source, nb_entries, type.packed_size, type.size, field.size); break;
		}
	}

	void PackNameFields(const crdb::Database& db, char* dest, const char* source, int nb_entries, const crdb::meta::DatabaseType& type, const crdb::meta::DatabaseField& field)
	{
		PackStridedData< CopyName >(db, dest, source, nb_entries, type.packed_size, type.size, 0);
	}

	template <typename TYPE>
	void CopyPrimitiveStoreToTable(const crdb::PrimitiveStore<TYPE>& store, std::vector<TYPE>& table, bool named)
	{
		int dest_index = 0;

		// Make a local copy of all entries in the table
		if (named)
		{
			table.resize(store.named.size());
			for (crdb::PrimitiveStore<TYPE>::NamedStore::const_iterator i = store.named.begin(); i != store.named.end(); ++i)
			{
				table[dest_index++] = i->second;
			}
		}
		else
		{
			table.resize(store.unnamed.size());
			for (crdb::PrimitiveStore<TYPE>::UnnamedStore::const_iterator i = store.unnamed.begin(); i != store.unnamed.end(); ++i)
			{
				table[dest_index++] = *i;
			}
		}
	}

	template <typename TYPE>
	void PackTable(const crdb::Database& db, const std::vector<TYPE>& table, const crdb::meta::DatabaseType& type, char* output)
	{
		// Walk up through the inheritance hierarhcy
		for (const crdb::meta::DatabaseType* cur_type = &type; cur_type; cur_type = cur_type->base_type)
		{
			// Pack a field at a time
			for (size_t i = 0; i < cur_type->fields.size(); i++)
			{
				const crdb::meta::DatabaseField& field = cur_type->fields[i];

				// Start at the offset from the field within the first object
				char* dest = output + field.packed_offset;
				char* source = (char*)&table.front() + field.offset;

				// Perform strided copies depending on field type - pass information about the root type
				switch (field.type)
				{
				case (crdb::meta::FIELD_TYPE_BASIC): PackBasicFields(db, dest, source, table.size(), type, field); break;
				case (crdb::meta::FIELD_TYPE_NAME): PackNameFields(db, dest, source, table.size(), type, field); break;
				}
			}
		}
	}

	template <typename TYPE>
	void WriteTable(FILE* fp, const crdb::Database& db, const crdb::meta::DatabaseTypes& dbtypes, bool named)
	{
		// Generate a memory-contiguous table
		std::vector<TYPE> table;
		CopyPrimitiveStoreToTable(db.GetPrimitiveStore<TYPE>(), table, named);

		// Record the table size
		int table_size = table.size();
		fwrite(&table_size, sizeof(int), 1, fp);

		if (table_size)
		{
			// Allocate enough memory to store the table in packed binary format
			const crdb::meta::DatabaseType& type = dbtypes.GetType<TYPE>();
			int packed_size = table_size * type.packed_size;
			char* data = new char[packed_size];

			// Binary pack the table
			PackTable(db, table, type, data);

			// Write to file and cleanup
			fwrite(data, packed_size, 1, fp);
			delete [] data;
		}
	}

	template <typename TYPE>
	void WriteTable(FILE* fp, const crdb::Database& db, const crdb::meta::DatabaseTypes& dbtypes)
	{
		// Write both named and unnamed tables
		// The unnamed tables contain the empty names, but this makes the code much simpler
		// at the expense of file sizes that are little larger
		WriteTable<TYPE>(fp, db, dbtypes, true);
		WriteTable<TYPE>(fp, db, dbtypes, false);
	}

	void WriteNameTable(FILE* fp, const crdb::Database& db)
	{
		// Write the table header
		int nb_names = db.m_Names.size();
		fwrite(&nb_names, sizeof(int), 1, fp);

		// Write each name
		for (crdb::Name i = db.m_Names.begin(); i != db.m_Names.end(); ++i)
		{
			fwrite(&i->first, sizeof(int), 1, fp);
			int len = i->second.length();
			fwrite(&len, sizeof(int), 1, fp);
			fwrite(i->second.c_str(), len, 1, fp);
		}
	}
}

void crdb::WriteBinaryDatabase(const char* filename, const Database& db)
{
	FILE* fp = fopen(filename, "wb");

	// Write each table with explicit ordering
	crdb::meta::DatabaseTypes dbtypes;
	WriteNameTable(fp, db);
	WriteTable<crdb::Namespace>(fp, db, dbtypes);
	WriteTable<crdb::Type>(fp, db, dbtypes);
	WriteTable<crdb::Class>(fp, db, dbtypes);
	WriteTable<crdb::Enum>(fp, db, dbtypes);
	WriteTable<crdb::EnumConstant>(fp, db, dbtypes);
	WriteTable<crdb::Function>(fp, db, dbtypes);
	WriteTable<crdb::Field>(fp, db, dbtypes);

	fclose(fp);
}<|endoftext|>


<commit_before>#include <cstring>
#include <iostream>
#include <map>
#include <vector>

int choose(int n,int k)
{
    if(k==0) return 1;
    return (int)(n%(int)(1e9+7)*choose(n-1,k-1))/k;
}

int main()
{
    int number_of_test_cases=0;
    std::cin>>number_of_test_cases;

    for(int test=0;test<number_of_test_cases;++test){
        int N,Q;
        std::cin>>N>>Q;
        std::vector<int> q(Q,0);
        std::string query_string;
        std::cin>>query_string;
        for(int i=0;i<Q;++i) std::cin>>q[i];

        //std::cout<<"N: "<<N<<", Q: "<<Q<<std::endl;
        //std::cout<<"String: "<<query_string<<std::endl;
        //std::cout<<"Q:";
        //for(int i=0;i<Q;++i) std::cout<<" "<<q[i];
        //std::cout<<std::endl;

        // create data structure
        std::vector<std::map<std::string,int> > occurences(query_string.size()+1);
        for(int i=1;i<=query_string.size();++i){
            for(int j=0;j<=query_string.size()-i;++j){
                std::string key=query_string.substr(j,i);
                if(occurences[i].find(key)==occurences[i].end()) occurences[i][key]=1;
                else ++occurences[i][key];
            }
        }

        /*
        // output data structure
        std::cout<<"Occurences:"<<std::endl;
        for(int i=0;i<occurences.size();++i){
            std::cout<<i<<":";
            for(std::map<std::string,int>::iterator it=occurences[i].begin();it!=occurences[i].end();++it) std::cout<<" ("<<it->first<<","<<it->second<<")";
            std::cout<<std::endl;
        }
        */

        for(int t=0;t<Q;++t){int k=q[t],sum=0;
            for(int i=0;i<occurences.size();++i){
                for(std::map<std::string,int>::iterator it=occurences[i].begin();it!=occurences[i].end();++it){
                    if(it->second >= k) sum+=choose(it->second,k);
                }
            }
            std::cout<<sum<<std::endl;
        }
    }

    return 0;
}
<commit_msg>remove<commit_after><|endoftext|>


<commit_before>#include <map>
#include <vector>
#include <string>
#include <time.h>
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include "NFComm/NFCore/NFQueue.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFPlatform.h"

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>

#if NF_PLATFORM == NF_PLATFORM_WIN
#include <io.h>
#include <windows.h>
#include <conio.h>
#else
#include <iconv.h>
#include <unistd.h>
#include <cstdio>
#include <dirent.h>
#include <sys/stat.h>
#endif

bool GetPluginNameList(std::string& strPlugin, std::vector<std::string>& pluginList, std::string& configPath)
{
	rapidxml::file<> fdoc(strPlugin.c_str());
	rapidxml::xml_document<>  doc;
	doc.parse<0>(fdoc.data());

	rapidxml::xml_node<>* pRoot = doc.first_node();
	for (rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin"))
	{
		const char* strPluginName = pPluginNode->first_attribute("Name")->value();
		const char* strMain = pPluginNode->first_attribute("Main")->value();
		pluginList.push_back(std::string(strPluginName));
	}

	rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
	if (!pPluginAppNode)
	{
		//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
		return false;
	}

	const char* strAppID = pPluginAppNode->first_attribute("Name")->value();
	if (!strAppID)
	{
		//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
		return false;
	}

	rapidxml::xml_node<>* pPluginConfigPathNode = pRoot->first_node("ConfigPath");
	if (!pPluginConfigPathNode)
	{
		//NFASSERT(0, "There are no ConfigPath", __FILE__, __FUNCTION__);
		return false;
	}

	if (NULL == pPluginConfigPathNode->first_attribute("Name"))
	{
		//NFASSERT(0, "There are no ConfigPath.Name", __FILE__, __FUNCTION__);
		return false;
	}

	configPath = pPluginConfigPathNode->first_attribute("Name")->value();

	return true;
}

int CopyFile(std::string& SourceFile, std::string& NewFile)
{
	ifstream in;
	ofstream out;
	in.open(SourceFile.c_str(), ios::binary);//Դļ
	if (in.fail())//Դļʧ
	{
		cout << "Error 1: Fail to open the source file." << endl;
		in.close();
		out.close();
		return 0;
	}
	out.open(NewFile.c_str(), ios::binary);//Ŀļ
	if (out.fail())//ļʧ
	{
		cout << "Error 2: Fail to create the new file." << endl;
		out.close();
		in.close();
		return 0;
	}
	else//ļ
	{
		out << in.rdbuf();
		out.close();
		in.close();
		return 1;
	}
}

std::vector<std::string> GetFileListInFolder(std::string folderPath, int depth)
{
	std::vector<std::string> result;
#if NF_PLATFORM == NF_PLATFORM_WIN
	_finddata_t FileInfo;
	std::string strfind = folderPath + "\\*";
	long long Handle = _findfirst(strfind.c_str(), &FileInfo);

	if (Handle == -1L)
	{
		std::cerr << "can not match the folder path" << std::endl;
		exit(-1);
	}
	do {
		//жǷĿ¼
		if (FileInfo.attrib & _A_SUBDIR)
		{
			//Ҫ
			if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
			{
				std::string newPath = folderPath + "\\" + FileInfo.name;
				//dfsFolder(newPath, depth);
				auto newResult = GetFileListInFolder(newPath, depth);
				result.insert(result.begin(), newResult.begin(), newResult.end());
			}
		}
		else
		{

			std::string filename = (folderPath + "\\" + FileInfo.name);
			result.push_back(filename);
		}
	} while (_findnext(Handle, &FileInfo) == 0);

	_findclose(Handle);
#else
	DIR *dp;
	struct dirent *entry;
	struct stat statbuf;
	char absolutepath[512];

	if ((dp = opendir(folderPath.c_str())) == NULL) {
		fprintf(stderr, "Can`t open directory %s\n", folderPath.c_str());
		return result;
	}

	while ((entry = readdir(dp)) != NULL) {
		std::string strEntry = folderPath + entry->d_name;
		lstat(strEntry.c_str(), &statbuf);
		if (S_ISDIR(statbuf.st_mode)) {
			if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
			{
				continue;
			}
			std::string childpath = folderPath + "/" + entry->d_name;
			auto newResult = GetFileListInFolder(childpath, depth);
			result.insert(result.begin(), newResult.begin(), newResult.end());
		}
		else
		{
			sprintf(absolutepath, "%s/%s", folderPath.c_str(), entry->d_name);
			result.push_back(absolutepath);
		}
	}
	closedir(dp);
	sort(result.begin(), result.end());//
#endif
	return result;
}

void StringReplace(std::string &strBig, const std::string &strsrc, const std::string &strdst)
{
	std::string::size_type pos = 0;
	std::string::size_type srclen = strsrc.size();
	std::string::size_type dstlen = strdst.size();

	while ((pos = strBig.find(strsrc, pos)) != std::string::npos)
	{
		strBig.replace(pos, srclen, strdst);
		pos += dstlen;
	}
}

void printResult(int result, std::string& strName)
{
	if (result == 1)
	{
		printf("Copy file: %s success!\n", strName.c_str());
	}
	else
	{
		printf("Copy file: %s failed!\n", strName.c_str());
	}
}

int main()
{
	std::vector<std::string> fileList;
	std::vector<std::string> errorFileList;
#if NF_PLATFORM == NF_PLATFORM_WIN
	printf("NFAutoCopyDll is Running in Windows...\n");
#else
	printf("NFAutoCopyDll is Running in Linux...\n");
#endif
#ifdef NF_DEBUG_MODE
	fileList = GetFileListInFolder("../../Debug/", 10);
	printf("Debug Mode, And fileList size == %d\n", fileList.size());
#else
	fileList = GetFileListInFolder("../../Release/", 10);
	printf("Release Mode, And fileList size == %d\n", fileList.size());
#endif

	for (auto fileName : fileList)
	{
		if (fileName.find("Plugin.xml") != std::string::npos)
		{
			StringReplace(fileName, "\\", "/");
			StringReplace(fileName, "//", "/");
			printf("Reading xml file: %s\n", fileName.c_str());

			std::vector<std::string> pluginList;
			std::string configPath = "";
			GetPluginNameList(fileName, pluginList, configPath);
			if (pluginList.size() > 0 && configPath != "")
			{
#if NF_PLATFORM == NF_PLATFORM_WIN
				pluginList.push_back("libprotobuf");
				pluginList.push_back("NFMessageDefine");
#else
				pluginList.push_back("NFMessageDefine");
#endif
				pluginList.push_back("NFPluginLoader");
				configPath = "../" + configPath;
				configPath = fileName.substr(0, fileName.find_last_of("/")) + "/" + configPath;

				for (std::string name : pluginList)
				{
					int result = 0;
					if (name == "NFPluginLoader")
					{
						int result = 0;
#if NF_PLATFORM == NF_PLATFORM_WIN

#ifdef NF_DEBUG_MODE
						std::string src = configPath + "Comm/Debug/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + "_d.exe";
						auto strDes = des + "_d.exe";
						auto strSrcPDB = src + "_d.pdb";
						auto strDesPDB = des + "_d.pdb";

						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);

						result = CopyFile(strSrcPDB, strDesPDB);
						if (result != 1)
						{
							errorFileList.push_back(strSrcPDB);
						}
						printResult(result, strSrcPDB);
#else
						std::string src = configPath + "Comm/Release/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + ".exe";
						auto strDes = des + ".exe";
						int result = 0;
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);
#endif

#else
						std::string src = configPath + "Comm/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + "_d";
						auto strDes = des + "_d";
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);
#endif

					}
					else
					{
#if NF_PLATFORM == NF_PLATFORM_WIN

#ifdef NF_DEBUG_MODE
						std::string src = configPath + "Comm/Debug/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + "_d.dll";
						auto strDes = des + "_d.dll";
						auto strSrcPDB = src + "_d.pdb";
						auto strDesPDB = des + "_d.pdb";
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);

						result = CopyFile(strSrcPDB, strDesPDB);
						if (result != 1)
						{
							errorFileList.push_back(strSrcPDB);
						}
						printResult(result, strSrcPDB);
#else
						std::string src = configPath + "Comm/Release/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + ".dll";
						auto strDes = des + ".dll";
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);
#endif

#else
						std::string src = configPath + "Comm/lib" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + "_d.so";
						auto strDes = des + "_d.so";
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);
#endif
					}
				}
			}
		}
	}
	if (errorFileList.size() <= 0)
	{
		printf("File Copy Done with NO ERROR!\n");
	}
	else
	{
		printf("File Copy Done with %d errors as follow:\n", (int)errorFileList.size());
		for (auto errFile : errorFileList)
		{
			printf("\t%s\n", errFile.c_str());
		}
	}
#if NF_PLATFORM == NF_PLATFORM_WIN
	printf("Press any Key to Exit!");
	getch();
#else

#endif
	return 0;
}<commit_msg>fixed for compile NFAutoCopyDll<commit_after>#include <map>
#include <vector>
#include <string>
#include <time.h>
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include "NFComm/NFCore/NFQueue.h"
#include "Dependencies/RapidXML/rapidxml.hpp"
#include "Dependencies/RapidXML/rapidxml_iterators.hpp"
#include "Dependencies/RapidXML/rapidxml_print.hpp"
#include "Dependencies/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFPlatform.h"

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>

#if NF_PLATFORM == NF_PLATFORM_WIN
#include <io.h>
#include <windows.h>
#include <conio.h>
#else
#include <iconv.h>
#include <unistd.h>
#include <cstdio>
#include <dirent.h>
#include <sys/stat.h>
#endif

bool GetPluginNameList(std::string& strPlugin, std::vector<std::string>& pluginList, std::string& configPath)
{
	rapidxml::file<> fdoc(strPlugin.c_str());
	rapidxml::xml_document<>  doc;
	doc.parse<0>(fdoc.data());

	rapidxml::xml_node<>* pRoot = doc.first_node();
	for (rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin"))
	{
		const char* strPluginName = pPluginNode->first_attribute("Name")->value();
		const char* strMain = pPluginNode->first_attribute("Main")->value();
		pluginList.push_back(std::string(strPluginName));
	}

	rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
	if (!pPluginAppNode)
	{
		//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
		return false;
	}

	const char* strAppID = pPluginAppNode->first_attribute("Name")->value();
	if (!strAppID)
	{
		//NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
		return false;
	}

	rapidxml::xml_node<>* pPluginConfigPathNode = pRoot->first_node("ConfigPath");
	if (!pPluginConfigPathNode)
	{
		//NFASSERT(0, "There are no ConfigPath", __FILE__, __FUNCTION__);
		return false;
	}

	if (NULL == pPluginConfigPathNode->first_attribute("Name"))
	{
		//NFASSERT(0, "There are no ConfigPath.Name", __FILE__, __FUNCTION__);
		return false;
	}

	configPath = pPluginConfigPathNode->first_attribute("Name")->value();

	return true;
}

int CopyFile(std::string& SourceFile, std::string& NewFile)
{
	ifstream in;
	ofstream out;
	in.open(SourceFile.c_str(), ios::binary);//Դļ
	if (in.fail())//Դļʧ
	{
		cout << "Error 1: Fail to open the source file." << endl;
		in.close();
		out.close();
		return 0;
	}
	out.open(NewFile.c_str(), ios::binary);//Ŀļ
	if (out.fail())//ļʧ
	{
		cout << "Error 2: Fail to create the new file." << endl;
		out.close();
		in.close();
		return 0;
	}
	else//ļ
	{
		out << in.rdbuf();
		out.close();
		in.close();
		return 1;
	}
}

std::vector<std::string> GetFileListInFolder(std::string folderPath, int depth)
{
	std::vector<std::string> result;
#if NF_PLATFORM == NF_PLATFORM_WIN
	_finddata_t FileInfo;
	std::string strfind = folderPath + "\\*";
	long long Handle = _findfirst(strfind.c_str(), &FileInfo);

	if (Handle == -1L)
	{
		std::cerr << "can not match the folder path" << std::endl;
		exit(-1);
	}
	do {
		//жǷĿ¼
		if (FileInfo.attrib & _A_SUBDIR)
		{
			//Ҫ
			if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
			{
				std::string newPath = folderPath + "\\" + FileInfo.name;
				//dfsFolder(newPath, depth);
				auto newResult = GetFileListInFolder(newPath, depth);
				result.insert(result.begin(), newResult.begin(), newResult.end());
			}
		}
		else
		{

			std::string filename = (folderPath + "\\" + FileInfo.name);
			result.push_back(filename);
		}
	} while (_findnext(Handle, &FileInfo) == 0);

	_findclose(Handle);
#else
	DIR *dp;
	struct dirent *entry;
	struct stat statbuf;
	char absolutepath[512];

	if ((dp = opendir(folderPath.c_str())) == NULL) {
		fprintf(stderr, "Can`t open directory %s\n", folderPath.c_str());
		return result;
	}

	while ((entry = readdir(dp)) != NULL) {
		std::string strEntry = folderPath + entry->d_name;
		lstat(strEntry.c_str(), &statbuf);
		if (S_ISDIR(statbuf.st_mode)) {
			if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
			{
				continue;
			}
			std::string childpath = folderPath + "/" + entry->d_name;
			auto newResult = GetFileListInFolder(childpath, depth);
			result.insert(result.begin(), newResult.begin(), newResult.end());
		}
		else
		{
			sprintf(absolutepath, "%s/%s", folderPath.c_str(), entry->d_name);
			result.push_back(absolutepath);
		}
	}
	closedir(dp);
	sort(result.begin(), result.end());//
#endif
	return result;
}

void StringReplace(std::string &strBig, const std::string &strsrc, const std::string &strdst)
{
	std::string::size_type pos = 0;
	std::string::size_type srclen = strsrc.size();
	std::string::size_type dstlen = strdst.size();

	while ((pos = strBig.find(strsrc, pos)) != std::string::npos)
	{
		strBig.replace(pos, srclen, strdst);
		pos += dstlen;
	}
}

void printResult(int result, std::string& strName)
{
	if (result == 1)
	{
		printf("Copy file: %s success!\n", strName.c_str());
	}
	else
	{
		printf("Copy file: %s failed!\n", strName.c_str());
	}
}

int main()
{
	std::vector<std::string> fileList;
	std::vector<std::string> errorFileList;
#if NF_PLATFORM == NF_PLATFORM_WIN
	printf("NFAutoCopyDll is Running in Windows...\n");
#else
	printf("NFAutoCopyDll is Running in Linux...\n");
#endif
#ifdef NF_DEBUG_MODE
	fileList = GetFileListInFolder("../../Debug/", 10);
	printf("Debug Mode, And fileList size == %d\n", fileList.size());
#else
	fileList = GetFileListInFolder("../../Release/", 10);
	printf("Release Mode, And fileList size == %d\n", fileList.size());
#endif

	for (auto fileName : fileList)
	{
		if (fileName.find("Plugin.xml") != std::string::npos)
		{
			StringReplace(fileName, "\\", "/");
			StringReplace(fileName, "//", "/");
			printf("Reading xml file: %s\n", fileName.c_str());

			std::vector<std::string> pluginList;
			std::string configPath = "";
			GetPluginNameList(fileName, pluginList, configPath);
			if (pluginList.size() > 0 && configPath != "")
			{
#if NF_PLATFORM == NF_PLATFORM_WIN
				pluginList.push_back("libprotobuf");
				pluginList.push_back("NFMessageDefine");
#else
				pluginList.push_back("NFMessageDefine");
#endif
				pluginList.push_back("NFPluginLoader");
				configPath = "../" + configPath;
				configPath = fileName.substr(0, fileName.find_last_of("/")) + "/" + configPath;

				for (std::string name : pluginList)
				{
					int result = 0;
					if (name == "NFPluginLoader")
					{
						int result = 0;
#if NF_PLATFORM == NF_PLATFORM_WIN

#ifdef NF_DEBUG_MODE
						std::string src = configPath + "Comm/Debug/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + "_d.exe";
						auto strDes = des + "_d.exe";
						auto strSrcPDB = src + "_d.pdb";
						auto strDesPDB = des + "_d.pdb";

						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);

						result = CopyFile(strSrcPDB, strDesPDB);
						if (result != 1)
						{
							errorFileList.push_back(strSrcPDB);
						}
						printResult(result, strSrcPDB);
#else
						std::string src = configPath + "Comm/Release/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + ".exe";
						auto strDes = des + ".exe";
						int result = 0;
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);
#endif

#else
						std::string src = configPath + "Comm/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + "_d";
						auto strDes = des + "_d";
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);
#endif

					}
					else
					{
#if NF_PLATFORM == NF_PLATFORM_WIN

#ifdef NF_DEBUG_MODE
						std::string src = configPath + "Comm/Debug/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + "_d.dll";
						auto strDes = des + "_d.dll";
						auto strSrcPDB = src + "_d.pdb";
						auto strDesPDB = des + "_d.pdb";
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);

						result = CopyFile(strSrcPDB, strDesPDB);
						if (result != 1)
						{
							errorFileList.push_back(strSrcPDB);
						}
						printResult(result, strSrcPDB);
#else
						std::string src = configPath + "Comm/Release/" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + ".dll";
						auto strDes = des + ".dll";
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);
#endif

#else
						std::string src = configPath + "Comm/lib" + name;
						std::string des = fileName.substr(0, fileName.find_last_of("/")) + "/" + name;
						auto strSrc = src + "_d.so";
						auto strDes = des + "_d.so";
						result = CopyFile(strSrc, strDes);
						if (result != 1)
						{
							errorFileList.push_back(strSrc);
						}
						printResult(result, strSrc);
#endif
					}
				}
			}
		}
	}
	if (errorFileList.size() <= 0)
	{
		printf("File Copy Done with NO ERROR!\n");
	}
	else
	{
		printf("File Copy Done with %d errors as follow:\n", (int)errorFileList.size());
		for (auto errFile : errorFileList)
		{
			printf("\t%s\n", errFile.c_str());
		}
	}
#if NF_PLATFORM == NF_PLATFORM_WIN
	printf("Press any Key to Exit!");
	getch();
#else

#endif
	return 0;
}<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "main.h"
#include "bitcoinrpc.h"

using namespace json_spirit;
using namespace std;

extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;

double GetDifficulty(const CBlockIndex* blockindex)
{
    // Floating point number that is a multiple of the minimum difficulty,
    // minimum difficulty = 1.0.
    if (blockindex == NULL)
    {
        if (pindexBest == NULL)
            return 1.0;
        else
            blockindex = GetLastBlockIndex(pindexBest, false);
    }

    int nShift = (blockindex->nBits >> 24) & 0xff;

    double dDiff =
        (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);

    while (nShift < 29)
    {
        dDiff *= 256.0;
        nShift++;
    }
    while (nShift > 29)
    {
        dDiff /= 256.0;
        nShift--;
    }

    return dDiff;
}

double GetPoWMHashPS()
{
    if (nBestHeight >= LAST_POW_BLOCK)
        return 0;

    int nPoWInterval = 72;
    int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;

    CBlockIndex* pindex = pindexGenesisBlock;
    CBlockIndex* pindexPrevWork = pindexGenesisBlock;

    while (pindex)
    {
        if (pindex->IsProofOfWork())
        {
            int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
            nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
            nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
            pindexPrevWork = pindex;
        }

        pindex = pindex->pnext;
    }

    return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}

double GetPoSKernelPS(CBlockIndex* pindexPrev)
{
    int nPoSInterval = 72;
    double dStakeKernelsTriedAvg = 0;
    int nStakesHandled = 0, nStakesTime = 0;

    CBlockIndex* pindexPrevStake = NULL;

    while (pindexPrev && nStakesHandled < nPoSInterval)
    {
        if (nBestHeight >= LAST_POW_BLOCK)
        {
            dStakeKernelsTriedAvg += GetDifficulty(pindexPrev) * 4294967296.0;
            nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindexPrev->nTime) : 0;
            pindexPrevStake = pindexPrev;
            nStakesHandled++;
        }

        pindexPrev = pindexPrev->pprev;
    }

   return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0;
}
double GetPoSKernelPS()
{
    return GetPoSKernelPS(pindexBest);
}

Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
    Object result;
    result.push_back(Pair("hash", block.GetHash().GetHex()));
    CMerkleTx txGen(block.vtx[0]);
    txGen.SetMerkleBranch(&block);
    result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
    result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
    result.push_back(Pair("height", blockindex->nHeight));
    result.push_back(Pair("version", block.nVersion));
    result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
    result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
    result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
    result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
    result.push_back(Pair("bits", HexBits(block.nBits)));
    result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
    result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
    result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
    if (blockindex->pprev)
        result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
    if (blockindex->pnext)
        result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));

    result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
    result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
    result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
    result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier)));
    result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
    Array txinfo;
    BOOST_FOREACH (const CTransaction& tx, block.vtx)
    {
        if (fPrintTransactionDetail)
        {
            Object entry;

            entry.push_back(Pair("txid", tx.GetHash().GetHex()));
            TxToJSON(tx, 0, entry);

            txinfo.push_back(entry);
        }
        else
        {
            txinfo.push_back(tx.GetHash().GetHex());
        }
    }

    result.push_back(Pair("tx", txinfo));

    if (block.IsProofOfStake())
        result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));

    return result;
}

Value getbestblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getbestblockhash\n"
            "Returns the hash of the best block in the longest block chain.");

    return hashBestChain.GetHex();
}

Value getblockcount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getblockcount\n"
            "Returns the number of blocks in the longest block chain.");

    return nBestHeight;
}

Value getdifficulty(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getdifficulty\n"
            "Returns the difficulty as a multiple of the minimum difficulty.");

    Object obj;
    obj.push_back(Pair("proof-of-work",        GetDifficulty()));
    obj.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    obj.push_back(Pair("search-interval",      (int)nLastCoinStakeSearchInterval));
    return obj;
}

Value settxfee(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
        throw runtime_error(
            "settxfee <amount>\n"
            "<amount> is a real and is rounded to the nearest 0.01");

    nTransactionFee = AmountFromValue(params[0]);
    nTransactionFee = (nTransactionFee / CENT) * CENT;  // round to cent

    return true;
}

Value getrawmempool(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getrawmempool\n"
            "Returns all transaction ids in memory pool.");

    vector<uint256> vtxid;
    mempool.queryHashes(vtxid);

    Array a;
    BOOST_FOREACH(const uint256& hash, vtxid)
        a.push_back(hash.ToString());

    return a;
}

Value getblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getblockhash <index>\n"
            "Returns hash of block in best-block-chain at <index>.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
    return pblockindex->phashBlock->GetHex();
}

Value getblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock <hash> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-hash.");

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

Value getblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock <number> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    uint256 hash = *pblockindex->phashBlock;

    pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getcheckpoint\n"
            "Show info of synchronized checkpoint.\n");

    Object result;
    CBlockIndex* pindexCheckpoint;

    result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
    pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
    result.push_back(Pair("height", pindexCheckpoint->nHeight));
    result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));

    // Check that the block satisfies synchronized checkpoint
    if (CheckpointsMode == Checkpoints::CPSTRICT)
        result.push_back(Pair("policy", "strict"));

    if (CheckpointsMode == Checkpoints::CPADVISORY)
        result.push_back(Pair("policy", "advisory"));

    if (CheckpointsMode == Checkpoints::CPPERMISSIVE)
        result.push_back(Pair("policy", "permissive"));

    if (mapArgs.count("-checkpointkey"))
        result.push_back(Pair("checkpointmaster", true));

    return result;
}
<commit_msg>set pow difficulty<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "main.h"
#include "bitcoinrpc.h"

using namespace json_spirit;
using namespace std;

extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;

double GetDifficulty(const CBlockIndex* blockindex)
{
    // Floating point number that is a multiple of the minimum difficulty,
    // minimum difficulty = 1.0.
    if (blockindex == NULL)
    {
        if (pindexBest == NULL)
            return 1.0;
        else
            blockindex = GetLastBlockIndex(pindexBest, false);
    }

    if (!blockindex->IsProofOfStake())
        return 1.0;

    int nShift = (blockindex->nBits >> 24) & 0xff;

    double dDiff =
        (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);

    while (nShift < 29)
    {
        dDiff *= 256.0;
        nShift++;
    }
    while (nShift > 29)
    {
        dDiff /= 256.0;
        nShift--;
    }

    return dDiff;
}

double GetPoWMHashPS()
{
    if (nBestHeight >= LAST_POW_BLOCK)
        return 0;

    int nPoWInterval = 72;
    int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;

    CBlockIndex* pindex = pindexGenesisBlock;
    CBlockIndex* pindexPrevWork = pindexGenesisBlock;

    while (pindex)
    {
        if (pindex->IsProofOfWork())
        {
            int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
            nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
            nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
            pindexPrevWork = pindex;
        }

        pindex = pindex->pnext;
    }

    return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}

double GetPoSKernelPS(CBlockIndex* pindexPrev)
{
    int nPoSInterval = 72;
    double dStakeKernelsTriedAvg = 0;
    int nStakesHandled = 0, nStakesTime = 0;

    CBlockIndex* pindexPrevStake = NULL;

    while (pindexPrev && nStakesHandled < nPoSInterval)
    {
        dStakeKernelsTriedAvg += GetDifficulty(pindexPrev) * 4294967296.0;
        nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindexPrev->nTime) : 0;
        pindexPrevStake = pindexPrev;
        nStakesHandled++;

        pindexPrev = pindexPrev->pprev;
    }

   return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0;
}
double GetPoSKernelPS()
{
    return GetPoSKernelPS(pindexBest);
}

Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
    Object result;
    result.push_back(Pair("hash", block.GetHash().GetHex()));
    CMerkleTx txGen(block.vtx[0]);
    txGen.SetMerkleBranch(&block);
    result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
    result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
    result.push_back(Pair("height", blockindex->nHeight));
    result.push_back(Pair("version", block.nVersion));
    result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
    result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
    result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
    result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
    result.push_back(Pair("bits", HexBits(block.nBits)));
    result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
    result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
    result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
    if (blockindex->pprev)
        result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
    if (blockindex->pnext)
        result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));

    result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
    result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
    result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
    result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier)));
    result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
    Array txinfo;
    BOOST_FOREACH (const CTransaction& tx, block.vtx)
    {
        if (fPrintTransactionDetail)
        {
            Object entry;

            entry.push_back(Pair("txid", tx.GetHash().GetHex()));
            TxToJSON(tx, 0, entry);

            txinfo.push_back(entry);
        }
        else
        {
            txinfo.push_back(tx.GetHash().GetHex());
        }
    }

    result.push_back(Pair("tx", txinfo));

    if (block.IsProofOfStake())
        result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));

    return result;
}

Value getbestblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getbestblockhash\n"
            "Returns the hash of the best block in the longest block chain.");

    return hashBestChain.GetHex();
}

Value getblockcount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getblockcount\n"
            "Returns the number of blocks in the longest block chain.");

    return nBestHeight;
}

Value getdifficulty(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getdifficulty\n"
            "Returns the difficulty as a multiple of the minimum difficulty.");

    Object obj;
    obj.push_back(Pair("proof-of-work",        GetDifficulty()));
    obj.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    obj.push_back(Pair("search-interval",      (int)nLastCoinStakeSearchInterval));
    return obj;
}

Value settxfee(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
        throw runtime_error(
            "settxfee <amount>\n"
            "<amount> is a real and is rounded to the nearest 0.01");

    nTransactionFee = AmountFromValue(params[0]);
    nTransactionFee = (nTransactionFee / CENT) * CENT;  // round to cent

    return true;
}

Value getrawmempool(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getrawmempool\n"
            "Returns all transaction ids in memory pool.");

    vector<uint256> vtxid;
    mempool.queryHashes(vtxid);

    Array a;
    BOOST_FOREACH(const uint256& hash, vtxid)
        a.push_back(hash.ToString());

    return a;
}

Value getblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getblockhash <index>\n"
            "Returns hash of block in best-block-chain at <index>.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
    return pblockindex->phashBlock->GetHex();
}

Value getblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock <hash> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-hash.");

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

Value getblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock <number> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    uint256 hash = *pblockindex->phashBlock;

    pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getcheckpoint\n"
            "Show info of synchronized checkpoint.\n");

    Object result;
    CBlockIndex* pindexCheckpoint;

    result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
    pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
    result.push_back(Pair("height", pindexCheckpoint->nHeight));
    result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));

    // Check that the block satisfies synchronized checkpoint
    if (CheckpointsMode == Checkpoints::CPSTRICT)
        result.push_back(Pair("policy", "strict"));

    if (CheckpointsMode == Checkpoints::CPADVISORY)
        result.push_back(Pair("policy", "advisory"));

    if (CheckpointsMode == Checkpoints::CPPERMISSIVE)
        result.push_back(Pair("policy", "permissive"));

    if (mapArgs.count("-checkpointkey"))
        result.push_back(Pair("checkpointmaster", true));

    return result;
}
<|endoftext|>


<commit_before>// This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.

#include "mistream.h"	// for istream_iterator, referenced in utf8.h
#include "sostream.h"
#include "ustring.h"
#include "ulimits.h"
#include <stdio.h>

namespace ustl {

/// Creates an output string stream linked to the given memory area.
ostringstream::ostringstream (void* p, size_t n) noexcept
: ostream()
,_buffer()
,_flags (0)
,_width (0)
,_precision (2)
{
    exceptions (goodbit);
    link (p, n);
}

/// Creates an output string stream, initializing the buffer with v.
ostringstream::ostringstream (const string& v)
: ostream()
,_buffer (v)
,_flags (0)
,_width (0)
,_precision (2)
{
    exceptions (goodbit);
    ostream::link (_buffer);
}

/// Copies \p s to the internal buffer.
void ostringstream::str (const string& s)
{
    _buffer = s;
    ostream::link (_buffer);
    SetPos (_buffer.size());
}

/// Writes a single character into the stream.
void ostringstream::iwrite (unsigned char v)
{
    if (remaining() >= 1 || overflow() >= 1)
	ostream::iwrite (v);
}

/// Writes the contents of \p buffer of \p size into the stream.
ostringstream& ostringstream::write (const void* buffer, size_type sz)
{
    const char* buf = (const char*) buffer;
    for (size_type bw = 0; (bw = min(sz, remaining() ? remaining() : overflow(sz))); buf += bw, sz -= bw)
	ostream::write (buf, bw);
    return *this;
}

/// Simple decimal encoding of \p n into \p fmt.
inline char* ostringstream::encode_dec (char* fmt, uint32_t n) const noexcept
{
    do {
	*fmt++ = '0' + n % 10;
    } while (n /= 10);
    return fmt;
}

/// Generates a sprintf format string for the given type.
void ostringstream::fmtstring (char* fmt, const char* typestr, bool bInteger) const
{
    *fmt++ = '%';
    if (_width) {
	if (_fill == '0')
	    *fmt++ = '0';
	fmt = encode_dec (fmt, _width);
    }
    if (_flags & left)
	*fmt++ = '-';
    if (bInteger) {
	if (_flags & showpos)
	    *fmt++ = '+';
	if (_flags & showbase)
	    *fmt++ = '#';
    } else {
	*fmt++ = '.';
	fmt = encode_dec (fmt, _precision);
    }
    while (*typestr)
	*fmt++ = *typestr++;
    if (bInteger) {
	if (_flags & hex)
	    fmt[-1] = (_flags & uppercase) ? 'X' : 'x';
	else if (_flags & oct)
	    fmt[-1] = 'o';
    } else if (_flags & scientific)
	fmt[-1] = 'E';
    *fmt = 0;
}

/// Writes \p v into the stream as utf8
void ostringstream::iwrite (wchar_t v)
{
    char buffer [8];
    *utf8out(buffer) = v;
    write (buffer, Utf8Bytes(v));
}

/// Writes value \p v into the stream as text.
void ostringstream::iwrite (bool v)
{
    static const char tf[2][8] = { "false", "true" };
    write (tf[v], 5 - v);
}

/// Equivalent to a vsprintf on the string.
int ostringstream::vformat (const char* fmt, va_list args)
{
#if HAVE_VA_COPY
    va_list args2;
#else
    #define args2 args
    #undef __va_copy
    #define __va_copy(x,y)
#endif
    int rv, space;
    do {
	space = remaining();
	__va_copy (args2, args);
	if (0 > (rv = vsnprintf (ipos(), space, fmt, args2)))
	    return rv;
    } while (rv >= space && rv < (int)overflow(rv+1));
    SetPos (pos() + min (rv, space));
    return rv;
}

/// Equivalent to a sprintf on the string.
int ostringstream::format (const char* fmt, ...)
{
    va_list args;
    va_start (args, fmt);
    const int rv = vformat (fmt, args);
    va_end (args);
    return rv;
}

/// Links to string \p l as resizable.
void ostringstream::link (void* p, size_type n) noexcept
{
    assert ((p || !n) && "The output string buffer must not be read-only");
    ostream::link (p, n);
    _buffer.link (p, n);
}

/// Attempts to create more output space. Returns remaining().
ostringstream::size_type ostringstream::overflow (size_type n)
{
    if (n > remaining() && (good() || n <= capacity() - pos())) {
	const uoff_t oldPos (pos());
	_buffer.reserve (oldPos + n, false);
	_buffer.resize (oldPos + n);
	ostream::link (_buffer);
	SetPos (oldPos);
    }
    verify_remaining ("write", "text", n);
    return remaining();
}

const Sendl endl;
const Sflush flush;

} // namespace ustl
<commit_msg>Set default stream fill to space.<commit_after>// This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.

#include "mistream.h"	// for istream_iterator, referenced in utf8.h
#include "sostream.h"
#include "ustring.h"
#include "ulimits.h"
#include <stdio.h>

namespace ustl {

/// Creates an output string stream linked to the given memory area.
ostringstream::ostringstream (void* p, size_t n) noexcept
: ostream()
,_buffer()
,_flags (0)
,_width (0)
,_precision (2)
,_fill (' ')
{
    exceptions (goodbit);
    link (p, n);
}

/// Creates an output string stream, initializing the buffer with v.
ostringstream::ostringstream (const string& v)
: ostream()
,_buffer (v)
,_flags (0)
,_width (0)
,_precision (2)
,_fill (' ')
{
    exceptions (goodbit);
    ostream::link (_buffer);
}

/// Copies \p s to the internal buffer.
void ostringstream::str (const string& s)
{
    _buffer = s;
    ostream::link (_buffer);
    SetPos (_buffer.size());
}

/// Writes a single character into the stream.
void ostringstream::iwrite (unsigned char v)
{
    if (remaining() >= 1 || overflow() >= 1)
	ostream::iwrite (v);
}

/// Writes the contents of \p buffer of \p size into the stream.
ostringstream& ostringstream::write (const void* buffer, size_type sz)
{
    const char* buf = (const char*) buffer;
    for (size_type bw = 0; (bw = min(sz, remaining() ? remaining() : overflow(sz))); buf += bw, sz -= bw)
	ostream::write (buf, bw);
    return *this;
}

/// Simple decimal encoding of \p n into \p fmt.
inline char* ostringstream::encode_dec (char* fmt, uint32_t n) const noexcept
{
    do {
	*fmt++ = '0' + n % 10;
    } while (n /= 10);
    return fmt;
}

/// Generates a sprintf format string for the given type.
void ostringstream::fmtstring (char* fmt, const char* typestr, bool bInteger) const
{
    *fmt++ = '%';
    if (_width) {
	if (_fill == '0')
	    *fmt++ = '0';
	fmt = encode_dec (fmt, _width);
    }
    if (_flags & left)
	*fmt++ = '-';
    if (bInteger) {
	if (_flags & showpos)
	    *fmt++ = '+';
	if (_flags & showbase)
	    *fmt++ = '#';
    } else {
	*fmt++ = '.';
	fmt = encode_dec (fmt, _precision);
    }
    while (*typestr)
	*fmt++ = *typestr++;
    if (bInteger) {
	if (_flags & hex)
	    fmt[-1] = (_flags & uppercase) ? 'X' : 'x';
	else if (_flags & oct)
	    fmt[-1] = 'o';
    } else if (_flags & scientific)
	fmt[-1] = 'E';
    *fmt = 0;
}

/// Writes \p v into the stream as utf8
void ostringstream::iwrite (wchar_t v)
{
    char buffer [8];
    *utf8out(buffer) = v;
    write (buffer, Utf8Bytes(v));
}

/// Writes value \p v into the stream as text.
void ostringstream::iwrite (bool v)
{
    static const char tf[2][8] = { "false", "true" };
    write (tf[v], 5 - v);
}

/// Equivalent to a vsprintf on the string.
int ostringstream::vformat (const char* fmt, va_list args)
{
#if HAVE_VA_COPY
    va_list args2;
#else
    #define args2 args
    #undef __va_copy
    #define __va_copy(x,y)
#endif
    int rv, space;
    do {
	space = remaining();
	__va_copy (args2, args);
	if (0 > (rv = vsnprintf (ipos(), space, fmt, args2)))
	    return rv;
    } while (rv >= space && rv < (int)overflow(rv+1));
    SetPos (pos() + min (rv, space));
    return rv;
}

/// Equivalent to a sprintf on the string.
int ostringstream::format (const char* fmt, ...)
{
    va_list args;
    va_start (args, fmt);
    const int rv = vformat (fmt, args);
    va_end (args);
    return rv;
}

/// Links to string \p l as resizable.
void ostringstream::link (void* p, size_type n) noexcept
{
    assert ((p || !n) && "The output string buffer must not be read-only");
    ostream::link (p, n);
    _buffer.link (p, n);
}

/// Attempts to create more output space. Returns remaining().
ostringstream::size_type ostringstream::overflow (size_type n)
{
    if (n > remaining() && (good() || n <= capacity() - pos())) {
	const uoff_t oldPos (pos());
	_buffer.reserve (oldPos + n, false);
	_buffer.resize (oldPos + n);
	ostream::link (_buffer);
	SetPos (oldPos);
    }
    verify_remaining ("write", "text", n);
    return remaining();
}

const Sendl endl;
const Sflush flush;

} // namespace ustl
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#ifndef VCF2MULTIALIGN_TYPES_HH
#define VCF2MULTIALIGN_TYPES_HH

#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <set>
#include <vector>

namespace vcf2multialign {
	typedef std::vector <char> vector_type;
	typedef std::set <std::size_t> variant_set;

	struct sample_count
	{
		std::size_t handled_count{0};
		std::size_t total_count{0};

		void reset() { handled_count = 0; total_count = 0; }
	};

	typedef boost::iostreams::stream <boost::iostreams::file_descriptor_source>	file_istream;
	typedef boost::iostreams::stream <boost::iostreams::file_descriptor_sink>	file_ostream;
}

#endif
<commit_msg>Add previously missing VCF field enums<commit_after>/*
 * Copyright (c) 2017 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#ifndef VCF2MULTIALIGN_TYPES_HH
#define VCF2MULTIALIGN_TYPES_HH

#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <set>
#include <vector>

namespace vcf2multialign {
	typedef std::vector <char> vector_type;
	typedef std::set <std::size_t> variant_set;

	struct sample_count
	{
		std::size_t handled_count{0};
		std::size_t total_count{0};

		void reset() { handled_count = 0; total_count = 0; }
	};

	typedef boost::iostreams::stream <boost::iostreams::file_descriptor_source>	file_istream;
	typedef boost::iostreams::stream <boost::iostreams::file_descriptor_sink>	file_ostream;

	enum class vcf_field : uint8_t {
		CHROM	= 0,
		POS		= 1,
		ID		= 2,
		REF		= 3,
		ALT		= 4,
		QUAL	= 5,
		FILTER	= 6,
		INFO	= 7,
		FORMAT	= 8,
		ALL		= 9,
		VARY	= 10
	};

	enum class format_field : uint8_t {
		GT		= 0,
		DP,
		GQ,
		PS,
		PQ,
		MQ
	};

	enum { NULL_ALLELE = std::numeric_limits <uint8_t>::max() };
}

#endif
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    NeighborhoodIterators4.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIterator.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkGaussianOperator.h"
#include "itkNeighborhoodInnerProduct.h"

// Software Guide : BeginLatex
//
//
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

// Software Guide : EndCodeSnippet

int main( int argc, char ** argv )
{
  if ( argc < 3 )
    {
    std::cerr << "Missing parameters. " << std::endl;
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0]
              << " inputImageFile outputImageFile sigma"
              << std::endl;
    return -1;
    }

  typedef float PixelType;
  typedef itk::Image< PixelType, 2 >  ImageType;
  typedef itk::ImageFileReader< ImageType > ReaderType;

  typedef itk::ConstNeighborhoodIterator< ImageType > NeighborhoodIteratorType;
  typedef itk::ImageRegionIterator< ImageType>        IteratorType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );
  try
    {
    reader->Update();
    }
  catch ( itk::ExceptionObject &err)
    {
    std::cout << "ExceptionObject caught !" << std::endl;
    std::cout << err << std::endl;
    return -1;
    }

  ImageType::Pointer output = ImageType::New();
  output->SetRegions(reader->GetOutput()->GetRequestedRegion());
  output->Allocate();

  itk::NeighborhoodInnerProduct<ImageType> innerProduct;

  typedef itk::NeighborhoodAlgorithm
    ::ImageBoundaryFacesCalculator< ImageType > FaceCalculatorType;

  FaceCalculatorType faceCalculator;
  FaceCalculatorType::FaceListType faceList;
  FaceCalculatorType::FaceListType::iterator fit;

  IteratorType out;
  NeighborhoodIteratorType it;

  itk::GaussianOperator< PixelType, 2 > gaussianOperator;
  gaussianOperator.SetVariance( ::atof(argv[3]) * ::atof(argv[3]) );

  ImageType::Pointer input = reader->GetOutput();
  for (unsigned int i = 0; i < ImageType::ImageDimension; ++i)
    {
    gaussianOperator.SetDirection(i);
    gaussianOperator.CreateDirectional();
    gaussianOperator.Print(std::cout);

    faceList = faceCalculator(input, output->GetRequestedRegion(),
                              gaussianOperator.GetRadius());

    for ( fit=faceList.begin(); fit != faceList.end(); ++fit )
      {
      it = NeighborhoodIteratorType( gaussianOperator.GetRadius(),
                                     input, *fit );
      std::cout << it << std::endl;

      out = IteratorType( output, *fit );

      for (it.GoToBegin(), out.GoToBegin(); ! it.IsAtEnd(); ++it, ++out)
        {
        out.Set( innerProduct(it, gaussianOperator) );
        }
      }

    // Swap the input and output buffers
    if (i != ImageType::ImageDimension - 1)
      {
      ImageType::Pointer tmp = input;
      input = output;
      output = tmp;
      }
    }

// Software Guide : BeginLatex
//
// The output is rescaled and written as in the previous example.  Filter the
// BLAH BLAH image in the $X$ direction give the same result as in Figure~BLAH BLAH
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

  typedef unsigned char WritePixelType;
  typedef itk::Image< WritePixelType, 2 > WriteImageType;
  typedef itk::ImageFileWriter< WriteImageType > WriterType;

  typedef itk::RescaleIntensityImageFilter<
    ImageType, WriteImageType > RescaleFilterType;

  RescaleFilterType::Pointer rescaler = RescaleFilterType::New();

  rescaler->SetOutputMinimum(   0 );
  rescaler->SetOutputMaximum( 255 );
  rescaler->SetInput(output);

  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( argv[2] );
  writer->SetInput( rescaler->GetOutput() );
  try
    {
    writer->Update();
    }
  catch ( itk::ExceptionObject &err)
    {
    std::cout << "ExceptionObject caught !" << std::endl;
    std::cout << err << std::endl;
    return -1;
    }
// Software Guide : EndCodeSnippet

  return 0;
}
<commit_msg>FIX: Bug fix.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    NeighborhoodIterators4.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkImageRegionIterator.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkGaussianOperator.h"
#include "itkNeighborhoodInnerProduct.h"

// Software Guide : BeginLatex
//
//
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

// Software Guide : EndCodeSnippet

int main( int argc, char ** argv )
{
  if ( argc < 4 )
    {
    std::cerr << "Missing parameters. " << std::endl;
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0]
              << " inputImageFile outputImageFile sigma"
              << std::endl;
    return -1;
    }

  typedef float PixelType;
  typedef itk::Image< PixelType, 2 >  ImageType;
  typedef itk::ImageFileReader< ImageType > ReaderType;

  typedef itk::ConstNeighborhoodIterator< ImageType > NeighborhoodIteratorType;
  typedef itk::ImageRegionIterator< ImageType>        IteratorType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );
  try
    {
    reader->Update();
    }
  catch ( itk::ExceptionObject &err)
    {
    std::cout << "ExceptionObject caught !" << std::endl;
    std::cout << err << std::endl;
    return -1;
    }

  ImageType::Pointer output = ImageType::New();
  output->SetRegions(reader->GetOutput()->GetRequestedRegion());
  output->Allocate();

  itk::NeighborhoodInnerProduct<ImageType> innerProduct;

  typedef itk::NeighborhoodAlgorithm
    ::ImageBoundaryFacesCalculator< ImageType > FaceCalculatorType;

  FaceCalculatorType faceCalculator;
  FaceCalculatorType::FaceListType faceList;
  FaceCalculatorType::FaceListType::iterator fit;

  IteratorType out;
  NeighborhoodIteratorType it;

  itk::GaussianOperator< PixelType, 2 > gaussianOperator;
  gaussianOperator.SetVariance( ::atof(argv[3]) * ::atof(argv[3]) );

  ImageType::Pointer input = reader->GetOutput();
  for (unsigned int i = 0; i < ImageType::ImageDimension; ++i)
    {
    gaussianOperator.SetDirection(i);
    gaussianOperator.CreateDirectional();

    faceList = faceCalculator(input, output->GetRequestedRegion(),
                              gaussianOperator.GetRadius());

    for ( fit=faceList.begin(); fit != faceList.end(); ++fit )
      {
      it = NeighborhoodIteratorType( gaussianOperator.GetRadius(),
                                     input, *fit );

      out = IteratorType( output, *fit );

      for (it.GoToBegin(), out.GoToBegin(); ! it.IsAtEnd(); ++it, ++out)
        {
        out.Set( innerProduct(it, gaussianOperator) );
        }
      }

    // Swap the input and output buffers
    if (i != ImageType::ImageDimension - 1)
      {
      ImageType::Pointer tmp = input;
      input = output;
      output = tmp;
      }
    }

// Software Guide : BeginLatex
//
// The output is rescaled and written as in the previous example.  Filter the
// BLAH BLAH image in the $X$ direction give the same result as in Figure~BLAH BLAH
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

  typedef unsigned char WritePixelType;
  typedef itk::Image< WritePixelType, 2 > WriteImageType;
  typedef itk::ImageFileWriter< WriteImageType > WriterType;

  typedef itk::RescaleIntensityImageFilter<
    ImageType, WriteImageType > RescaleFilterType;

  RescaleFilterType::Pointer rescaler = RescaleFilterType::New();

  rescaler->SetOutputMinimum(   0 );
  rescaler->SetOutputMaximum( 255 );
  rescaler->SetInput(output);

  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( argv[2] );
  writer->SetInput( rescaler->GetOutput() );
  try
    {
    writer->Update();
    }
  catch ( itk::ExceptionObject &err)
    {
    std::cout << "ExceptionObject caught !" << std::endl;
    std::cout << err << std::endl;
    return -1;
    }
// Software Guide : EndCodeSnippet

  return 0;
}
<|endoftext|>