<commit_before>
#pragma once

#include <sstream>
#include <type_traits>

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <reflectionzeug/Property.h>

namespace reflectionzeug
{

template <typename T, unsigned Count>
std::string glmToString(const T * data)
{
    std::stringstream ss;

    ss << "(";

    for (unsigned i = 0; i < Count; ++i)
    {
        if (i > 0)
            ss << ", ";

        ss << data[i];
    }

    ss << ")";

    return ss.str();
}

template <typename T, unsigned Count>
bool glmFromString(const std::string & string, T * data)
{
    std::string elementRegex = std::is_integral<T>::value ? "(-|\\+)?\\d+" : "(-|\\+)?\\d+\\.?\\d*";

    std::stringstream ss;
    ss << "\\s*\\(";
    for (unsigned i=0; i<Count-1; ++i)
    {
        ss << "(" << elementRegex << ")";
        ss << "\\s*,\\s*";
    }
    ss << elementRegex << "\\)\\s*";

    if (!reflectionzeug::util::matchesRegex(string, ss.str()))
        return false;

    std::vector<std::string> parts = reflectionzeug::util::extract(string, elementRegex);

    assert(parts.size() == Count);

    for (unsigned i = 0; i < Count; ++i)
    {
        const std::string & part = parts[i];
        data[i] = std::is_integral<T>::value ? static_cast<T>(std::stoi(part)) : static_cast<T>(std::stod(part));
    }

    return true;
}

class Vec2Property : public reflectionzeug::ValueProperty<glm::vec2>
{
public:
    using Type = glm::vec2;

public:
    template <typename... Arguments>
    Vec2Property(Arguments&&... args)
    : reflectionzeug::ValueProperty<glm::vec2>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::vec2::value_type, 2>(glm::value_ptr(this->value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::vec2 value;
        if (!glmFromString<glm::vec2::value_type, 2>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class IVec2Property : public reflectionzeug::ValueProperty<glm::ivec2>
{
public:
    using Type = glm::ivec2;

public:
    template <typename... Arguments>
    IVec2Property(Arguments&&... args)
    : reflectionzeug::ValueProperty<glm::ivec2>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::ivec2::value_type, 2>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::ivec2 value;
        if (!glmFromString<glm::ivec2::value_type, 2>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class Vec3Property : public reflectionzeug::ValueProperty<glm::vec3>
{
public:
    using Type = glm::vec3;

public:
    template <typename... Arguments>
    Vec3Property(Arguments&&... args)
    : reflectionzeug::ValueProperty<glm::vec3>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::vec3::value_type, 3>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::vec3 value;
        if (!glmFromString<glm::vec3::value_type, 3>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class IVec3Property : public reflectionzeug::ValueProperty<glm::ivec3>
{
public:
    using Type = glm::ivec3;

public:
    template <typename... Arguments>
    IVec3Property(Arguments&&... args)
    : reflectionzeug::ValueProperty<glm::ivec3>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::ivec3::value_type, 3>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::ivec3 value;
        if (!glmFromString<glm::ivec3::value_type, 3>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class Vec4Property : public reflectionzeug::ValueProperty<glm::vec4>
{
public:
    using Type = glm::vec4;

public:
    template <typename... Arguments>
    Vec4Property(Arguments&&... args)
    : reflectionzeug::ValueProperty<glm::vec4>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::vec4::value_type, 4>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::vec4 value;
        if (!glmFromString<glm::vec4::value_type, 4>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class IVec4Property : public reflectionzeug::ValueProperty<glm::ivec4>
{
public:
    using Type = glm::ivec4;

public:
    template <typename... Arguments>
    IVec4Property(Arguments&&... args)
    : reflectionzeug::ValueProperty<glm::ivec4>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::ivec4::value_type, 4>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::ivec4 value;
        if (!glmFromString<glm::ivec4::value_type, 4>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

template <>
struct PropertyClass<Vec2Property::Type>
{
    using Type = Vec2Property;
};

template <>
struct PropertyClass<IVec2Property::Type>
{
    using Type = IVec2Property;
};

template <>
struct PropertyClass<Vec3Property::Type>
{
    using Type = Vec3Property;
};

template <>
struct PropertyClass<IVec3Property::Type>
{
    using Type = IVec3Property;
};

template <>
struct PropertyClass<Vec4Property::Type>
{
    using Type = Vec4Property;
};

template <>
struct PropertyClass<IVec4Property::Type>
{
    using Type = IVec4Property;
};

} // namespace reflectionzeug
<commit_msg>Adjust GlmProperties.hpp to reflectionzeug changes (PropertyClass --> PropertyTypeSelector).<commit_after>
#pragma once

#include <sstream>
#include <type_traits>

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <reflectionzeug/property/Property.h>

namespace reflectionzeug
{

template <typename T, unsigned Count>
std::string glmToString(const T * data)
{
    std::stringstream ss;

    ss << "(";

    for (unsigned i = 0; i < Count; ++i)
    {
        if (i > 0)
            ss << ", ";

        ss << data[i];
    }

    ss << ")";

    return ss.str();
}

template <typename T, unsigned Count>
bool glmFromString(const std::string & string, T * data)
{
    std::string elementRegex = std::is_integral<T>::value ? "(-|\\+)?\\d+" : "(-|\\+)?\\d+\\.?\\d*";

    std::stringstream ss;
    ss << "\\s*\\(";
    for (unsigned i=0; i<Count-1; ++i)
    {
        ss << "(" << elementRegex << ")";
        ss << "\\s*,\\s*";
    }
    ss << elementRegex << "\\)\\s*";

    if (!reflectionzeug::util::matchesRegex(string, ss.str()))
        return false;

    std::vector<std::string> parts = reflectionzeug::util::extract(string, elementRegex);

    assert(parts.size() == Count);

    for (unsigned i = 0; i < Count; ++i)
    {
        const std::string & part = parts[i];
        data[i] = std::is_integral<T>::value ? static_cast<T>(std::stoi(part)) : static_cast<T>(std::stod(part));
    }

    return true;
}

class Vec2Property : public reflectionzeug::AbstractValueProperty<glm::vec2>
{
public:
    template <typename... Arguments>
    Vec2Property(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<glm::vec2>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::vec2::value_type, 2>(glm::value_ptr(this->value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::vec2 value;
        if (!glmFromString<glm::vec2::value_type, 2>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class IVec2Property : public reflectionzeug::AbstractValueProperty<glm::ivec2>
{
public:
    template <typename... Arguments>
    IVec2Property(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<glm::ivec2>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::ivec2::value_type, 2>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::ivec2 value;
        if (!glmFromString<glm::ivec2::value_type, 2>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class Vec3Property : public reflectionzeug::AbstractValueProperty<glm::vec3>
{
public:
    template <typename... Arguments>
    Vec3Property(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<glm::vec3>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::vec3::value_type, 3>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::vec3 value;
        if (!glmFromString<glm::vec3::value_type, 3>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class IVec3Property : public reflectionzeug::AbstractValueProperty<glm::ivec3>
{
public:
    template <typename... Arguments>
    IVec3Property(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<glm::ivec3>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::ivec3::value_type, 3>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::ivec3 value;
        if (!glmFromString<glm::ivec3::value_type, 3>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class Vec4Property : public reflectionzeug::AbstractValueProperty<glm::vec4>
{
public:
    template <typename... Arguments>
    Vec4Property(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<glm::vec4>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::vec4::value_type, 4>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::vec4 value;
        if (!glmFromString<glm::vec4::value_type, 4>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

class IVec4Property : public reflectionzeug::AbstractValueProperty<glm::ivec4>
{
public:
    template <typename... Arguments>
    IVec4Property(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<glm::ivec4>(std::forward<Arguments>(args)...) {}

    virtual std::string toString() const override
    {
        return glmToString<glm::ivec4::value_type, 4>(glm::value_ptr(value()));
    }

    virtual bool fromString(const std::string & string) override
    {
        glm::ivec4 value;
        if (!glmFromString<glm::ivec4::value_type, 4>(string, glm::value_ptr(value)))
            return false;

        setValue(value);
        return true;
    }
};

template <>
struct PropertyTypeSelector<glm::vec2>
{
    using Type = Vec2Property;
};

template <>
struct PropertyTypeSelector<glm::ivec2>
{
    using Type = IVec2Property;
};

template <>
struct PropertyTypeSelector<glm::vec3>
{
    using Type = Vec3Property;
};

template <>
struct PropertyTypeSelector<glm::ivec3>
{
    using Type = IVec3Property;
};

template <>
struct PropertyTypeSelector<glm::vec4>
{
    using Type = Vec4Property;
};

template <>
struct PropertyTypeSelector<glm::ivec4>
{
    using Type = IVec4Property;
};

} // namespace reflectionzeug
<|endoftext|>


<commit_before>/*
This file is part of the CVD Library.

Copyright (C) 2005 The Authors

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
/*
 *  qtbuffer.cpp
 *  libcvd
 *
 *  FIXME:
 *  - check if carbon events and WaitForNextEvent are necessary, or if we can just drive SGIdle directly
 *  - check how to set video input properties such as brightness, saturation, etc
 *  - support other video formats (potentially from other hardware) as well
 */

// build for carbon
#define TARGET_API_MAC_CARBON 1

#if __APPLE_CC__
#include <Carbon/Carbon.h>
#include <QuickTime/QuickTime.h>
#else
#include <ConditionalMacros.h>
#include <QuickTimeComponents.h>
#endif

#include <iostream>

using namespace std;

#include <cvd/image_ref.h>
#include <cvd/OSX/qtbuffer.h>

using namespace CVD;
using namespace QT;

Exceptions::QTBUFFER::DeviceOpen::DeviceOpen(string msg)
{
    what = "QTBuffer: failed to open video sequence grabber: "+msg;
}

class CVD::QT::RawQTPimpl {
public:
	int number;
	ImageRef mySize;

	Rect 				bounds;		// bounds rect
    SeqGrabComponent 	seqGrab;	// sequence grabber
	SGChannel			chanVideo;	// video channel
	TimeValue 		 	lastTime;   // time stamp of last frame, FIXME figure out how that is a real timestamp
	unsigned char *		lastFrame;  // pointer to the frame data of the last frame received
	long				length;     // length of the frame data
	bool				newFrame;   // do we have a new frame since the last get_frame call?

	static bool isInitialized;  // flag to init Carbon and QuickTime

	static pascal OSErr GrabDataProc(SGChannel c, Ptr p, long len, long *offset, long chRefCon, TimeValue time, short writeType, long refCon);
};

bool RawQTPimpl::isInitialized = false;

pascal OSErr RawQTPimpl::GrabDataProc(SGChannel /* c */, Ptr p, long len, long * /* offset */, long /* chRefCon */, TimeValue time, short /* writeType */, long refCon){
	ComponentResult err = noErr;
	RawQTPimpl * self = (RawQTPimpl *)refCon;
	self->lastFrame = (unsigned char *) p;
	self->length = len;
	self->lastTime = time;
	self->newFrame = true;
	return err;
}

RawQT::RawQT(const ImageRef & size, unsigned int /* mode */, unsigned int /* num */, bool showSettingsDialog) : pimpl(NULL)
{
	if( !RawQTPimpl::isInitialized ){
		EnterMovies();
		RawQTPimpl::isInitialized = true;
	}

	pimpl = new RawQTPimpl;
	pimpl->bounds.left = 0;
	pimpl->bounds.top = 0;
	pimpl->bounds.right = size.x;
	pimpl->bounds.bottom = size.y;
	pimpl->lastFrame = NULL;
	pimpl->newFrame = false;

	pimpl->seqGrab = OpenDefaultComponent(SeqGrabComponentType, 0);
	if( pimpl->seqGrab == NULL ){
		throw Exceptions::QTBUFFER::DeviceOpen("Error opening SequenceGrabber");
	}

	OSErr err = noErr;

	err = SGInitialize(pimpl->seqGrab);
	if(err != noErr){
		throw Exceptions::QTBUFFER::DeviceOpen("SGInitialize returned error");
	}
	err = SGSetGWorld(pimpl->seqGrab,  GetWindowPort(NULL), NULL);
	if(err != noErr){
		throw Exceptions::QTBUFFER::DeviceOpen("SGSetGWorld returned error");
	}
	// specify the destination data reference for a record operation
	// tell it we're not making a movie
	// if the flag seqGrabDontMakeMovie is used, the sequence grabber still calls
	// your data function, but does not write any data to the movie file
	// writeType will always be set to seqGrabWriteAppend
	err = SGSetDataRef(pimpl->seqGrab, 0, 0, seqGrabDontMakeMovie);
	if(err != noErr){
		throw Exceptions::QTBUFFER::DeviceOpen("SGSetDataRef returned error");
	}

	err = SGNewChannel(pimpl->seqGrab, VideoMediaType, &pimpl->chanVideo);
	if(err != noErr){
		throw Exceptions::QTBUFFER::DeviceOpen("SGNewChannel returned error");
	}

	if(showSettingsDialog)
	  {
	    err = SGSettingsDialog(pimpl->seqGrab, pimpl->chanVideo, 0, NULL, 0L, NULL, 0);
	    if(err != noErr)
	      throw Exceptions::QTBUFFER::DeviceOpen("SGSettingsDialog returned an error");
	  }

    try {
	    err = SGSetChannelBounds(pimpl->chanVideo, &pimpl->bounds);
	    if (err != noErr) {
			throw Exceptions::QTBUFFER::DeviceOpen("SGSetChannelBounds returned error");
		}
		// set usage for new video channel to avoid playthrough
		// note we don't set seqGrabPlayDuringRecord
		err = SGSetChannelUsage(pimpl->chanVideo, seqGrabRecord);
		if( err != noErr) {
			throw CVD::Exceptions::QTBUFFER::DeviceOpen("SGSetChannelUsage returned error");
		}

		err = SGSetDataProc(pimpl->seqGrab, NewSGDataUPP(RawQTPimpl::GrabDataProc), (long)pimpl);
		if(err != noErr){
			throw Exceptions::QTBUFFER::DeviceOpen("SGSetDataProc returned error");
		}

		// lights...camera...
		err = SGPrepare(pimpl->seqGrab, false, true);
		// ...action
		err = SGStartRecord(pimpl->seqGrab);

	        // What format are the images?
		ImageDescriptionHandle imageDesc = (ImageDescriptionHandle)NewHandle(0);
		err = SGGetChannelSampleDescription(pimpl->chanVideo, (Handle)imageDesc);
		if(err != noErr){
		  throw Exceptions::QTBUFFER::DeviceOpen("SGGetChannelSampleDescription returned error");
		}
		// Convert pascal string to stl string..
		for(char i=1; i<=(**imageDesc).name[0]; i++)
			frame_format_string = frame_format_string + (char) (**imageDesc).name[i];

	}
	catch(Exceptions::QTBUFFER::DeviceOpen){
		// clean up on failure
		SGDisposeChannel(pimpl->seqGrab, pimpl->chanVideo);
		pimpl->chanVideo = NULL;
		throw;
	}
}

string RawQT::get_frame_format_string()
{
	return frame_format_string;
}

RawQT::~RawQT(){
	if(pimpl){
		if (pimpl->seqGrab)
    		CloseComponent(pimpl->seqGrab);
		delete pimpl;
		pimpl = NULL;
	}
}

ImageRef RawQT::get_size() const {
	return ImageRef(pimpl->bounds.right, pimpl->bounds.bottom);
}

unsigned char* RawQT::get_frame(){
	while(pimpl->newFrame == false){
		OSErr err = SGIdle(pimpl->seqGrab);
		if (err) {
			SGStop(pimpl->seqGrab);
			SGStartRecord(pimpl->seqGrab);
		}
	}
	pimpl->newFrame = false;
	return pimpl->lastFrame;
}

void RawQT::put_frame( unsigned char * ){
	// do nothing here because we cannot protect the frames anyway
}

double RawQT::frame_rate(){
	// FIXME actually determine framerate from VideoDigitizer or something
	return 30;
}

bool RawQT::frame_pending(){
	OSErr err = SGIdle(pimpl->seqGrab);
	if (err) {
		SGStop(pimpl->seqGrab);
		SGStartRecord(pimpl->seqGrab);
	}
	return pimpl->newFrame;
}
<commit_msg>undef some Carbon macro that clashes with TooN2<commit_after>/*
This file is part of the CVD Library.

Copyright (C) 2005 The Authors

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
/*
 *  qtbuffer.cpp
 *  libcvd
 *
 *  FIXME:
 *  - check if carbon events and WaitForNextEvent are necessary, or if we can just drive SGIdle directly
 *  - check how to set video input properties such as brightness, saturation, etc
 *  - support other video formats (potentially from other hardware) as well
 */

// build for carbon
#define TARGET_API_MAC_CARBON 1

#if __APPLE_CC__
#include <Carbon/Carbon.h>
#include <QuickTime/QuickTime.h>
#else
#include <ConditionalMacros.h>
#include <QuickTimeComponents.h>
#endif

#undef check

#include <iostream>

using namespace std;

#include <cvd/image_ref.h>
#include <cvd/OSX/qtbuffer.h>

using namespace CVD;
using namespace QT;

Exceptions::QTBUFFER::DeviceOpen::DeviceOpen(string msg)
{
    what = "QTBuffer: failed to open video sequence grabber: "+msg;
}

class CVD::QT::RawQTPimpl {
public:
	int number;
	ImageRef mySize;

	Rect 				bounds;		// bounds rect
    SeqGrabComponent 	seqGrab;	// sequence grabber
	SGChannel			chanVideo;	// video channel
	TimeValue 		 	lastTime;   // time stamp of last frame, FIXME figure out how that is a real timestamp
	unsigned char *		lastFrame;  // pointer to the frame data of the last frame received
	long				length;     // length of the frame data
	bool				newFrame;   // do we have a new frame since the last get_frame call?

	static bool isInitialized;  // flag to init Carbon and QuickTime

	static pascal OSErr GrabDataProc(SGChannel c, Ptr p, long len, long *offset, long chRefCon, TimeValue time, short writeType, long refCon);
};

bool RawQTPimpl::isInitialized = false;

pascal OSErr RawQTPimpl::GrabDataProc(SGChannel /* c */, Ptr p, long len, long * /* offset */, long /* chRefCon */, TimeValue time, short /* writeType */, long refCon){
	ComponentResult err = noErr;
	RawQTPimpl * self = (RawQTPimpl *)refCon;
	self->lastFrame = (unsigned char *) p;
	self->length = len;
	self->lastTime = time;
	self->newFrame = true;
	return err;
}

RawQT::RawQT(const ImageRef & size, unsigned int /* mode */, unsigned int /* num */, bool showSettingsDialog) : pimpl(NULL)
{
	if( !RawQTPimpl::isInitialized ){
		EnterMovies();
		RawQTPimpl::isInitialized = true;
	}

	pimpl = new RawQTPimpl;
	pimpl->bounds.left = 0;
	pimpl->bounds.top = 0;
	pimpl->bounds.right = size.x;
	pimpl->bounds.bottom = size.y;
	pimpl->lastFrame = NULL;
	pimpl->newFrame = false;

	pimpl->seqGrab = OpenDefaultComponent(SeqGrabComponentType, 0);
	if( pimpl->seqGrab == NULL ){
		throw Exceptions::QTBUFFER::DeviceOpen("Error opening SequenceGrabber");
	}

	OSErr err = noErr;

	err = SGInitialize(pimpl->seqGrab);
	if(err != noErr){
		throw Exceptions::QTBUFFER::DeviceOpen("SGInitialize returned error");
	}
	err = SGSetGWorld(pimpl->seqGrab,  GetWindowPort(NULL), NULL);
	if(err != noErr){
		throw Exceptions::QTBUFFER::DeviceOpen("SGSetGWorld returned error");
	}
	// specify the destination data reference for a record operation
	// tell it we're not making a movie
	// if the flag seqGrabDontMakeMovie is used, the sequence grabber still calls
	// your data function, but does not write any data to the movie file
	// writeType will always be set to seqGrabWriteAppend
	err = SGSetDataRef(pimpl->seqGrab, 0, 0, seqGrabDontMakeMovie);
	if(err != noErr){
		throw Exceptions::QTBUFFER::DeviceOpen("SGSetDataRef returned error");
	}

	err = SGNewChannel(pimpl->seqGrab, VideoMediaType, &pimpl->chanVideo);
	if(err != noErr){
		throw Exceptions::QTBUFFER::DeviceOpen("SGNewChannel returned error");
	}

	if(showSettingsDialog)
	  {
	    err = SGSettingsDialog(pimpl->seqGrab, pimpl->chanVideo, 0, NULL, 0L, NULL, 0);
	    if(err != noErr)
	      throw Exceptions::QTBUFFER::DeviceOpen("SGSettingsDialog returned an error");
	  }

    try {
	    err = SGSetChannelBounds(pimpl->chanVideo, &pimpl->bounds);
	    if (err != noErr) {
			throw Exceptions::QTBUFFER::DeviceOpen("SGSetChannelBounds returned error");
		}
		// set usage for new video channel to avoid playthrough
		// note we don't set seqGrabPlayDuringRecord
		err = SGSetChannelUsage(pimpl->chanVideo, seqGrabRecord);
		if( err != noErr) {
			throw CVD::Exceptions::QTBUFFER::DeviceOpen("SGSetChannelUsage returned error");
		}

		err = SGSetDataProc(pimpl->seqGrab, NewSGDataUPP(RawQTPimpl::GrabDataProc), (long)pimpl);
		if(err != noErr){
			throw Exceptions::QTBUFFER::DeviceOpen("SGSetDataProc returned error");
		}

		// lights...camera...
		err = SGPrepare(pimpl->seqGrab, false, true);
		// ...action
		err = SGStartRecord(pimpl->seqGrab);

	        // What format are the images?
		ImageDescriptionHandle imageDesc = (ImageDescriptionHandle)NewHandle(0);
		err = SGGetChannelSampleDescription(pimpl->chanVideo, (Handle)imageDesc);
		if(err != noErr){
		  throw Exceptions::QTBUFFER::DeviceOpen("SGGetChannelSampleDescription returned error");
		}
		// Convert pascal string to stl string..
		for(char i=1; i<=(**imageDesc).name[0]; i++)
			frame_format_string = frame_format_string + (char) (**imageDesc).name[i];

	}
	catch(Exceptions::QTBUFFER::DeviceOpen){
		// clean up on failure
		SGDisposeChannel(pimpl->seqGrab, pimpl->chanVideo);
		pimpl->chanVideo = NULL;
		throw;
	}
}

string RawQT::get_frame_format_string()
{
	return frame_format_string;
}

RawQT::~RawQT(){
	if(pimpl){
		if (pimpl->seqGrab)
    		CloseComponent(pimpl->seqGrab);
		delete pimpl;
		pimpl = NULL;
	}
}

ImageRef RawQT::get_size() const {
	return ImageRef(pimpl->bounds.right, pimpl->bounds.bottom);
}

unsigned char* RawQT::get_frame(){
	while(pimpl->newFrame == false){
		OSErr err = SGIdle(pimpl->seqGrab);
		if (err) {
			SGStop(pimpl->seqGrab);
			SGStartRecord(pimpl->seqGrab);
		}
	}
	pimpl->newFrame = false;
	return pimpl->lastFrame;
}

void RawQT::put_frame( unsigned char * ){
	// do nothing here because we cannot protect the frames anyway
}

double RawQT::frame_rate(){
	// FIXME actually determine framerate from VideoDigitizer or something
	return 30;
}

bool RawQT::frame_pending(){
	OSErr err = SGIdle(pimpl->seqGrab);
	if (err) {
		SGStop(pimpl->seqGrab);
		SGStartRecord(pimpl->seqGrab);
	}
	return pimpl->newFrame;
}
<|endoftext|>


<commit_before>// Copyright (c) 2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "electrum/electrs.h"
#include "netaddress.h"
#include "util.h"
#include "utilhttp.h"
#include "utilprocess.h"
#include "xversionkeys.h"
#include "xversionmessage.h"

#include <map>
#include <regex>
#include <sstream>

#include <boost/filesystem.hpp>

constexpr char ELECTRSCASH_BIN[] = "electrscash";

static std::string monitoring_port() { return GetArg("-electrum.monitoring.port", "4224"); }
static std::string monitoring_host() { return GetArg("-electrum.monitoring.host", "127.0.0.1"); }
static std::string rpc_host() { return GetArg("-electrum.host", "127.0.0.1"); }
static std::string rpc_port(const std::string &network)
{
    std::map<std::string, std::string> portmap = {{"main", "50001"}, {"test", "60001"}, {"regtest", "60401"}};

    auto defaultPort = portmap.find(network);
    if (defaultPort == end(portmap))
    {
        std::stringstream ss;
        ss << "Electrum server does not support '" << network << "' network.";
        throw std::invalid_argument(ss.str());
    }

    return GetArg("-electrum.port", defaultPort->second);
}

static bool is_electrum_server_public()
{
    const auto host = rpc_host();

    // Special case, CNetAddr treats "0.0.0.0" as local, but electrs
    // treats it as listen on all IPs.
    if (host == "0.0.0.0")
    {
        return true;
    }

    // Assume the server is public if it's not listening on localhost and
    // not listening on a private network (RFC1918)
    const CNetAddr listenaddr(host);

    return !listenaddr.IsLocal() && !listenaddr.IsRFC1918();
}

static void remove_conflicting_arg(std::vector<std::string> &args, const std::string &override_arg)
{
    // special case: verboseness argument
    const std::regex verbose("^-v+$");
    if (std::regex_search(override_arg, verbose))
    {
        auto it = begin(args);
        while (it != end(args))
        {
            if (!std::regex_search(*it, verbose))
            {
                ++it;
                continue;
            }
            LOGA("Electrum: Argument '%s' overrides '%s'", override_arg, *it);
            it = args.erase(it);
        }
        return;
    }

    // normal case
    auto separator = override_arg.find_first_of("=");
    if (separator == std::string::npos)
    {
        throw std::invalid_argument("Invalid format for argument '" + override_arg + "'");
    }
    separator++; // include '=' when matching argument names below

    auto it = begin(args);
    while (it != end(args))
    {
        if (it->size() < separator)
        {
            ++it;
            continue;
        }
        if (it->substr(0, separator) != override_arg.substr(0, separator))
        {
            ++it;
            continue;
        }
        LOGA("Electrum: Argument '%s' overrides '%s'", override_arg, *it);
        it = args.erase(it);
    }
}
namespace electrum
{
std::string electrs_path()
{
    // look for electrs in same path as bitcoind
    boost::filesystem::path bitcoind_dir(this_process_path());
    bitcoind_dir = bitcoind_dir.remove_filename();

    auto default_path = bitcoind_dir / ELECTRSCASH_BIN;
    const std::string path = GetArg("-electrum.exec", default_path.string());

    if (path.empty())
    {
        throw std::runtime_error("Path to electrum server executable not found. "
                                 "You can specify full path with -electrum.exec");
    }
    if (!boost::filesystem::exists(path))
    {
        std::stringstream ss;
        ss << "Cannot find electrum executable at " << path;
        throw std::runtime_error(ss.str());
    }
    return path;
}

//! Arguments to start electrs server with
std::vector<std::string> electrs_args(int rpcport, const std::string &network)
{
    std::vector<std::string> args;

    if (Logging::LogAcceptCategory(ELECTRUM))
    {
        // increase verboseness when electrum logging is enabled
        args.push_back("-vvvv");
    }

    // address to bitcoind rpc interface
    {
        rpcport = GetArg("-rpcport", rpcport);
        std::stringstream ss;
        ss << "--daemon-rpc-addr=" << GetArg("-electrum.daemon.host", "127.0.0.1") << ":" << rpcport;
        args.push_back(ss.str());
    }

    args.push_back("--electrum-rpc-addr=" + rpc_host() + ":" + rpc_port(network));

    // bitcoind data dir (for cookie file)
    args.push_back("--daemon-dir=" + GetDataDir(false).string());

    // Use rpc interface instead of attempting to parse *blk files
    args.push_back("--jsonrpc-import");

    // Where to store electrs database files.
    const std::string defaultDir = (GetDataDir() / ELECTRSCASH_BIN).string();
    args.push_back("--db-dir=" + GetArg("-electrum.dir", defaultDir));

    // Tell electrs what network we're on
    const std::map<std::string, std::string> netmapping = {
        {"main", "bitcoin"}, {"test", "testnet"}, {"regtest", "regtest"}};
    if (!netmapping.count(network))
    {
        std::stringstream ss;
        ss << "Electrum server does not support '" << network << "' network.";
        throw std::invalid_argument(ss.str());
    }
    args.push_back("--network=" + netmapping.at(network));
    args.push_back("--monitoring-addr=" + monitoring_host() + ":" + monitoring_port());

    if (!GetArg("-rpcpassword", "").empty())
    {
        args.push_back("--cookie=" + GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", ""));
    }

    // max txs to look up per address
    args.push_back("--txid-limit=" + GetArg("-electrum.addr.limit", "500"));

    for (auto &a : mapMultiArgs["-electrum.rawarg"])
    {
        remove_conflicting_arg(args, a);
        args.push_back(a);
    }

    return args;
}

std::map<std::string, int64_t> fetch_electrs_info()
{
    if (!GetBoolArg("-electrum", false))
    {
        throw std::runtime_error("Electrum server is disabled");
    }

    std::stringstream infostream = http_get(monitoring_host(), std::stoi(monitoring_port()), "/");

    const std::regex keyval("^([a-z_]+)\\s(\\d+)\\s*$");
    std::map<std::string, int64_t> info;
    std::string line;
    std::smatch match;
    while (std::getline(infostream, line, '\n'))
    {
        if (!std::regex_match(line, match, keyval))
        {
            continue;
        }
        try
        {
            info[match[1].str()] = std::stol(match[2].str());
        }
        catch (const std::exception &e)
        {
            LOG(ELECTRUM, "%s error: %s", __func__, e.what());
        }
    }
    return info;
}

void set_xversion_flags(CXVersionMessage &xver, const std::string &network)
{
    if (!GetBoolArg("-electrum", false))
    {
        return;
    }
    if (!is_electrum_server_public())
    {
        return;
    }

    constexpr double PROTOCOL_VERSION = 1.4;

    xver.set_u64c(XVer::BU_ELECTRUM_SERVER_PORT_TCP, std::stoul(rpc_port(network)));
    xver.set_u64c(XVer::BU_ELECTRUM_SERVER_PROTOCOL_VERSION, static_cast<uint64_t>(PROTOCOL_VERSION * 1000000));
}
} // ns electrum
<commit_msg>[electrum] More debug info in `getelectruminfo`<commit_after>// Copyright (c) 2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "electrum/electrs.h"
#include "netaddress.h"
#include "util.h"
#include "utilhttp.h"
#include "utilprocess.h"
#include "xversionkeys.h"
#include "xversionmessage.h"

#include <map>
#include <regex>
#include <sstream>

#include <boost/filesystem.hpp>

constexpr char ELECTRSCASH_BIN[] = "electrscash";

static std::string monitoring_port() { return GetArg("-electrum.monitoring.port", "4224"); }
static std::string monitoring_host() { return GetArg("-electrum.monitoring.host", "127.0.0.1"); }
static std::string rpc_host() { return GetArg("-electrum.host", "127.0.0.1"); }
static std::string rpc_port(const std::string &network)
{
    std::map<std::string, std::string> portmap = {{"main", "50001"}, {"test", "60001"}, {"regtest", "60401"}};

    auto defaultPort = portmap.find(network);
    if (defaultPort == end(portmap))
    {
        std::stringstream ss;
        ss << "Electrum server does not support '" << network << "' network.";
        throw std::invalid_argument(ss.str());
    }

    return GetArg("-electrum.port", defaultPort->second);
}

static bool is_electrum_server_public()
{
    const auto host = rpc_host();

    // Special case, CNetAddr treats "0.0.0.0" as local, but electrs
    // treats it as listen on all IPs.
    if (host == "0.0.0.0")
    {
        return true;
    }

    // Assume the server is public if it's not listening on localhost and
    // not listening on a private network (RFC1918)
    const CNetAddr listenaddr(host);

    return !listenaddr.IsLocal() && !listenaddr.IsRFC1918();
}

static void remove_conflicting_arg(std::vector<std::string> &args, const std::string &override_arg)
{
    // special case: verboseness argument
    const std::regex verbose("^-v+$");
    if (std::regex_search(override_arg, verbose))
    {
        auto it = begin(args);
        while (it != end(args))
        {
            if (!std::regex_search(*it, verbose))
            {
                ++it;
                continue;
            }
            LOGA("Electrum: Argument '%s' overrides '%s'", override_arg, *it);
            it = args.erase(it);
        }
        return;
    }

    // normal case
    auto separator = override_arg.find_first_of("=");
    if (separator == std::string::npos)
    {
        throw std::invalid_argument("Invalid format for argument '" + override_arg + "'");
    }
    separator++; // include '=' when matching argument names below

    auto it = begin(args);
    while (it != end(args))
    {
        if (it->size() < separator)
        {
            ++it;
            continue;
        }
        if (it->substr(0, separator) != override_arg.substr(0, separator))
        {
            ++it;
            continue;
        }
        LOGA("Electrum: Argument '%s' overrides '%s'", override_arg, *it);
        it = args.erase(it);
    }
}
namespace electrum
{
std::string electrs_path()
{
    // look for electrs in same path as bitcoind
    boost::filesystem::path bitcoind_dir(this_process_path());
    bitcoind_dir = bitcoind_dir.remove_filename();

    auto default_path = bitcoind_dir / ELECTRSCASH_BIN;
    const std::string path = GetArg("-electrum.exec", default_path.string());

    if (path.empty())
    {
        throw std::runtime_error("Path to electrum server executable not found. "
                                 "You can specify full path with -electrum.exec");
    }
    if (!boost::filesystem::exists(path))
    {
        std::stringstream ss;
        ss << "Cannot find electrum executable at " << path;
        throw std::runtime_error(ss.str());
    }
    return path;
}

//! Arguments to start electrs server with
std::vector<std::string> electrs_args(int rpcport, const std::string &network)
{
    std::vector<std::string> args;

    if (Logging::LogAcceptCategory(ELECTRUM))
    {
        // increase verboseness when electrum logging is enabled
        args.push_back("-vvvv");
    }

    // address to bitcoind rpc interface
    {
        rpcport = GetArg("-rpcport", rpcport);
        std::stringstream ss;
        ss << "--daemon-rpc-addr=" << GetArg("-electrum.daemon.host", "127.0.0.1") << ":" << rpcport;
        args.push_back(ss.str());
    }

    args.push_back("--electrum-rpc-addr=" + rpc_host() + ":" + rpc_port(network));

    // bitcoind data dir (for cookie file)
    args.push_back("--daemon-dir=" + GetDataDir(false).string());

    // Use rpc interface instead of attempting to parse *blk files
    args.push_back("--jsonrpc-import");

    // Where to store electrs database files.
    const std::string defaultDir = (GetDataDir() / ELECTRSCASH_BIN).string();
    args.push_back("--db-dir=" + GetArg("-electrum.dir", defaultDir));

    // Tell electrs what network we're on
    const std::map<std::string, std::string> netmapping = {
        {"main", "bitcoin"}, {"test", "testnet"}, {"regtest", "regtest"}};
    if (!netmapping.count(network))
    {
        std::stringstream ss;
        ss << "Electrum server does not support '" << network << "' network.";
        throw std::invalid_argument(ss.str());
    }
    args.push_back("--network=" + netmapping.at(network));
    args.push_back("--monitoring-addr=" + monitoring_host() + ":" + monitoring_port());

    if (!GetArg("-rpcpassword", "").empty())
    {
        args.push_back("--cookie=" + GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", ""));
    }

    // max txs to look up per address
    args.push_back("--txid-limit=" + GetArg("-electrum.addr.limit", "500"));

    for (auto &a : mapMultiArgs["-electrum.rawarg"])
    {
        remove_conflicting_arg(args, a);
        args.push_back(a);
    }

    return args;
}

std::map<std::string, int64_t> fetch_electrs_info()
{
    if (!GetBoolArg("-electrum", false))
    {
        throw std::runtime_error("Electrum server is disabled");
    }

    std::stringstream infostream = http_get(monitoring_host(), std::stoi(monitoring_port()), "/");

    const std::regex keyval("^([a-z_{}=\"\\+]+)\\s(\\d+)\\s*$");
    std::map<std::string, int64_t> info;
    std::string line;
    std::smatch match;
    while (std::getline(infostream, line, '\n'))
    {
        if (!std::regex_match(line, match, keyval))
        {
            continue;
        }
        try
        {
            info[match[1].str()] = std::stol(match[2].str());
        }
        catch (const std::exception &e)
        {
            LOG(ELECTRUM, "%s error: %s", __func__, e.what());
        }
    }
    return info;
}

void set_xversion_flags(CXVersionMessage &xver, const std::string &network)
{
    if (!GetBoolArg("-electrum", false))
    {
        return;
    }
    if (!is_electrum_server_public())
    {
        return;
    }

    constexpr double PROTOCOL_VERSION = 1.4;

    xver.set_u64c(XVer::BU_ELECTRUM_SERVER_PORT_TCP, std::stoul(rpc_port(network)));
    xver.set_u64c(XVer::BU_ELECTRUM_SERVER_PROTOCOL_VERSION, static_cast<uint64_t>(PROTOCOL_VERSION * 1000000));
}
} // ns electrum
<|endoftext|>


<commit_before>#include <optics.h>

typedef std::vector<double> point; //A list of n cartesian coordinates makes a point
std::vector<point> points; //Your list of points goes here

int main(){
   auto reach_dists = optics::compute_reachability_dists( points, 10, 100 );
   optics::draw_reachability_plot( reach_dists, "D:/reachdists.bmp" );
}
<commit_msg>Update main.cpp<commit_after>#include <optics.h>

typedef std::vector<double> point; //A list of n cartesian coordinates makes a point
std::vector<point> points; //Your list of points goes here

int main(){
   points = { {100,100}, {102,100}, {101,101},           //cluster 1
               {-1,0}, {1,0}, {0,1},                     //cluster 2
               {-100,-100}, {-102,-100}, {-101,-101}     //cluster 3
   };
   auto reach_dists = optics::compute_reachability_dists( points, 10, 100 );
   optics::draw_reachability_plot( reach_dists, "D:/reachdists.bmp" );
}
<|endoftext|>


<commit_before>#include "gtest/gtest.h"

TEST(Test, EqualityCheck){
	EXPECT_EQ(true, false);
}

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

TEST(Test, EqualityCheck){
	EXPECT_EQ(true, true);
}

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


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

#include <cmake.h>
#include <stdlib.h>
#include <Context.h>
#include <RX.h>
#include <test.h>

Context context;

int main (int argc, char** argv)
{
  UnitTest ut (24);

  // Ensure environment has no influence.
  unsetenv ("TASKDATA");
  unsetenv ("TASKRC");

  std::string text = "This is a test.";

  RX r1 ("i. ", true);
  ut.ok (r1.match (text), text + " =~ /i. /");

  std::vector <std::string> matches;
  ut.ok (r1.match (matches, text), text + " =~ /i. /");
  ut.ok (matches.size () == 2, "2 match");
  ut.is (matches[0], "is ", "$1 == is\\s");
  ut.is (matches[1], "is ", "$1 == is\\s");

  text = "abcdefghijklmnopqrstuvwxyz";

  RX r3 ("t..", true);
  ut.ok (r3.match (text), "t..");

  RX r4 ("T..", false);
  ut.ok (r4.match (text), "T..");

  RX r5 ("T..", true);
  ut.ok (!r5.match (text), "! T..");

  text = "this is a test of the regex engine.";
  //      |...:....|....:....|....:....|....:

  RX r6 ("^this");
  ut.ok (r6.match (text),      "^this matches");

  RX r7 ("engine\\.$");
  ut.ok (r7.match (text), "engine\\.$ matches");

  std::vector <std::string> results;
  std::vector <int> start;
  std::vector <int> end;
  RX r8 ("e..", true);
  ut.ok (r8.match (results, text), "e.. there are matches");
  ut.ok (r8.match (start, end, text), "e.. there are matches");
  ut.is (results.size (), (size_t) 4, "e.. == 4 matches");
  ut.is (results[0], "est", "e..[0] == 'est'");
  ut.is (start[0],      11, "e..[0] == 11->");
  ut.is (end[0],        14, "e..[0] == ->14");

  results.clear ();
  RX r9 ("e", true);
  ut.ok (r9.match (results, text),           "e there are matches");
  ut.is (results.size (), (size_t) 6,        "e == 6 matches");

  start.clear ();
  end.clear ();
  ut.ok (r9.match (start, end, text),        "e there are matches");
  ut.is (start.size (), (size_t) 6,          "e == 6 matches");

#if defined(DARWIN) || defined(CYGWIN) || defined(FREEBSD) || defined(OPENBSD)
  text = "this is the end.";
  ut.pass (text + " =~ /\\bthe/");
  ut.pass (text + " =~ /the\\b/");
  ut.pass (text + " =~ /\\bthe\\b/");
#elif defined(SOLARIS)
  RX r10 ("\\<the");
  text = "this is the end.";
  ut.ok (r10.match (text), text + " =~ /\\<the/");

  RX r11 ("the\\>");
  ut.ok (r11.match (text), text + " =~ /the\\>/");

  RX r12 ("\\<the\\>");
  ut.ok (r12.match (text), text + " =~ /\\<the\\>/");
#else
  RX r10 ("\\bthe");
  text = "this is the end.";
  ut.ok (r10.match (text), text + " =~ /\\bthe/");

  RX r11 ("the\\b");
  ut.ok (r11.match (text), text + " =~ /the\\b/");

  RX r12 ("\\bthe\\b");
  ut.ok (r12.match (text), text + " =~ /\\bthe\\b/");
#endif

  text = "D0";
  RX r13 ("D\\d");
  ut.ok (r13.match (text), text + " =~ /D\\d/");

  return 0;
}

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

<commit_msg>Test: Made \d a DARWIN-only test and added portable alternatives<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <stdlib.h>
#include <Context.h>
#include <RX.h>
#include <test.h>

Context context;

int main (int argc, char** argv)
{
  UnitTest ut (26);

  // Ensure environment has no influence.
  unsetenv ("TASKDATA");
  unsetenv ("TASKRC");

  std::string text = "This is a test.";

  RX r1 ("i. ", true);
  ut.ok (r1.match (text), text + " =~ /i. /");

  std::vector <std::string> matches;
  ut.ok (r1.match (matches, text), text + " =~ /i. /");
  ut.ok (matches.size () == 2, "2 match");
  ut.is (matches[0], "is ", "$1 == is\\s");
  ut.is (matches[1], "is ", "$1 == is\\s");

  text = "abcdefghijklmnopqrstuvwxyz";

  RX r3 ("t..", true);
  ut.ok (r3.match (text), "t..");

  RX r4 ("T..", false);
  ut.ok (r4.match (text), "T..");

  RX r5 ("T..", true);
  ut.ok (!r5.match (text), "! T..");

  text = "this is a test of the regex engine.";
  //      |...:....|....:....|....:....|....:

  RX r6 ("^this");
  ut.ok (r6.match (text),      "^this matches");

  RX r7 ("engine\\.$");
  ut.ok (r7.match (text), "engine\\.$ matches");

  std::vector <std::string> results;
  std::vector <int> start;
  std::vector <int> end;
  RX r8 ("e..", true);
  ut.ok (r8.match (results, text), "e.. there are matches");
  ut.ok (r8.match (start, end, text), "e.. there are matches");
  ut.is (results.size (), (size_t) 4, "e.. == 4 matches");
  ut.is (results[0], "est", "e..[0] == 'est'");
  ut.is (start[0],      11, "e..[0] == 11->");
  ut.is (end[0],        14, "e..[0] == ->14");

  results.clear ();
  RX r9 ("e", true);
  ut.ok (r9.match (results, text),           "e there are matches");
  ut.is (results.size (), (size_t) 6,        "e == 6 matches");

  start.clear ();
  end.clear ();
  ut.ok (r9.match (start, end, text),        "e there are matches");
  ut.is (start.size (), (size_t) 6,          "e == 6 matches");

#if defined(DARWIN) || defined(CYGWIN) || defined(FREEBSD) || defined(OPENBSD)
  text = "this is the end.";
  ut.pass (text + " =~ /\\bthe/");
  ut.pass (text + " =~ /the\\b/");
  ut.pass (text + " =~ /\\bthe\\b/");
#elif defined(SOLARIS)
  RX r10 ("\\<the");
  text = "this is the end.";
  ut.ok (r10.match (text), text + " =~ /\\<the/");

  RX r11 ("the\\>");
  ut.ok (r11.match (text), text + " =~ /the\\>/");

  RX r12 ("\\<the\\>");
  ut.ok (r12.match (text), text + " =~ /\\<the\\>/");
#else
  RX r10 ("\\bthe");
  text = "this is the end.";
  ut.ok (r10.match (text), text + " =~ /\\bthe/");

  RX r11 ("the\\b");
  ut.ok (r11.match (text), text + " =~ /the\\b/");

  RX r12 ("\\bthe\\b");
  ut.ok (r12.match (text), text + " =~ /\\bthe\\b/");
#endif

#if defined(DARWIN)
  text = "D0";
  RX r13 ("D\\d");
  ut.ok (r13.match (text), text + " =~ /D\\d/");
#else
  ut.skip (" =~ /D\\d/"")
#endif

  text = "D0";
  RX r14 ("D[[:digit:]]");
  ut.ok (r14.match (text), text + " =~ /D[[:digit:]]/");

  text = "D0";
  RX r15 ("D[0-9]");
  ut.ok (r15.match (text), text + " =~ /D[0-9]/");

  return 0;
}

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

<|endoftext|>


<commit_before>#include <Windows.h>
#include <iostream>
#include "..\breakpoint.h"

// globals
int g_val = 0;
HANDLE g_hEvent1, g_hEvent2;

void tryWrite()
{
	std::cout << "thread " << std::hex << ::GetCurrentThreadId() << " trying to write...";

	__try
    {
		g_val = 1;
	}
	__except (EXCEPTION_EXECUTE_HANDLER)
	{
		std::cout << "\tcatch write attempt [ok]" << std::endl << std::endl;
	}
}

DWORD WINAPI ThreadWriteFunc()
{
    // inform main thread to set breakpoint
	::SetEvent(g_hEvent2);

    // wait for main thread to finish setting the BP
	::WaitForSingleObject(g_hEvent1, INFINITE);

	tryWrite();

	return 0;
}

int main()
{
	HANDLE hTrd;
	DWORD threadId;

	g_hEvent1 = ::CreateEvent(NULL, TRUE, FALSE, NULL);
	g_hEvent2 = ::CreateEvent(NULL, TRUE, FALSE, NULL);

    // multi-thread testing:
	std::cout << std::endl << std::endl << "test 1: existing thread before the BP has setting" << std::endl;
	std::cout << "=============================================================================" << std::endl;
	hTrd = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWriteFunc, NULL, 0, &threadId);

    // wait for new thread creation
    ::WaitForSingleObject(g_hEvent2, INFINITE);

    // print out the new thread id
	std::cout << "thread " << std::hex << threadId << " has created" << std::endl;

    // set the BP
	HWBreakpoint::Set(&g_val, sizeof(int), HWBreakpoint::Write);

    // signal the thread to continue exection (try to write)
	::SetEvent(g_hEvent1);

    // wait for thread completion
	::WaitForSingleObject(hTrd, INFINITE);
	::CloseHandle(hTrd);

	std::cout << std::endl << std::endl << "test 2: new thread after setting the BP" << std::endl;
	std::cout << "=============================================================================" << std::endl;
	hTrd = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWriteFunc, NULL, 0, &threadId);

    // wait for new thread creation
	::WaitForSingleObject(g_hEvent2, INFINITE);

    // print out the new thread id
	std::cout << "thread " << std::hex << threadId << " has created" << std::endl;

    // signal the thread to continue execution
	::SetEvent(g_hEvent1);

    // wait for thread completion
	::WaitForSingleObject(hTrd, INFINITE);
	::CloseHandle(hTrd);

    // reset the BP
	HWBreakpoint::Clear(&g_val);

    // wait for user input
	std::cin.ignore();
}<commit_msg>cosmetics<commit_after>#include <Windows.h>
#include <iostream>
#include "..\breakpoint.h"

// globals
int g_val = 0;
HANDLE g_hEvent1, g_hEvent2;

void tryWrite()
{
	std::cout << "thread " << std::hex << ::GetCurrentThreadId() << " trying to write...";

	__try
    	{
		g_val = 1;
	}
	__except (EXCEPTION_EXECUTE_HANDLER)
	{
		std::cout << "\tcatch write attempt [ok]" << std::endl << std::endl;
	}
}

DWORD WINAPI ThreadWriteFunc()
{
    	// inform main thread to set breakpoint
	::SetEvent(g_hEvent2);

    	// wait for main thread to finish setting the BP
	::WaitForSingleObject(g_hEvent1, INFINITE);

	tryWrite();

	return 0;
}

int main()
{
	HANDLE hTrd;
	DWORD threadId;

	g_hEvent1 = ::CreateEvent(NULL, TRUE, FALSE, NULL);
	g_hEvent2 = ::CreateEvent(NULL, TRUE, FALSE, NULL);

    	// multi-thread testing:
	std::cout << std::endl << std::endl << "test 1: existing thread before the BP has setting" << std::endl;
	std::cout << "=============================================================================" << std::endl;
	hTrd = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWriteFunc, NULL, 0, &threadId);

    	// wait for new thread creation
    	::WaitForSingleObject(g_hEvent2, INFINITE);

    	// print out the new thread id
	std::cout << "thread " << std::hex << threadId << " has created" << std::endl;

    	// set the BP
	HWBreakpoint::Set(&g_val, sizeof(int), HWBreakpoint::Write);

    	// signal the thread to continue exection (try to write)
	::SetEvent(g_hEvent1);

    	// wait for thread completion
	::WaitForSingleObject(hTrd, INFINITE);
	::CloseHandle(hTrd);

	std::cout << std::endl << std::endl << "test 2: new thread after setting the BP" << std::endl;
	std::cout << "=============================================================================" << std::endl;
	hTrd = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWriteFunc, NULL, 0, &threadId);

    	// wait for new thread creation
	::WaitForSingleObject(g_hEvent2, INFINITE);

    	// print out the new thread id
	std::cout << "thread " << std::hex << threadId << " has created" << std::endl;

    	// signal the thread to continue execution
	::SetEvent(g_hEvent1);

    	// wait for thread completion
	::WaitForSingleObject(hTrd, INFINITE);
	::CloseHandle(hTrd);

    	// reset the BP
	HWBreakpoint::Clear(&g_val);

    	// wait for user input
	std::cin.ignore();
}
<|endoftext|>


<commit_before>#include "details.h"
#include "ui_details.h"

Details::Details(QWidget* parent, Scientist* scientist) :
    QDialog(parent),
    ui(new Ui::Details)
{
    ui->setupUi(this);
    _scientist = *scientist;

    ScientistDetails();
}

Details::Details(QWidget* parent, Computer* computer) :
    QDialog(parent),
    ui(new Ui::Details)
{
    ui->setupUi(this);
    _computer = *computer;

    ComputerDetails();
}

Details::~Details()
{
    delete ui;
}

void Details::ScientistDetails()
{
    ui->label_name->setText(QString::fromStdString("
" + _scientist.getName() + "
"));
    ui->first_detail->setText(QString::fromStdString("Gender: " + _scientist.getGender()));
    ui->second_detail->setText(QString::fromStdString("Year Of Birth: ") + QString::number(_scientist.getYearOfBirth()));

    if (_scientist.getYearOfDeath())
    {
        ui->third_detail->setText(QString::fromStdString("Year Of Death: ") + QString::number(_scientist.getYearOfDeath()));
    }

    ui->fourth_detail->setText(QString::fromStdString("Age: ") + QString::number(_scientist.getAge()));
}

void Details::ComputerDetails()
{
    ui->label_name->setText(QString::fromStdString("
" + _computer.getName() + "
"));
    ui->first_detail->setText(QString::fromStdString("Year built: ") + QString::number(_computer.getYearBuilt()));
    ui->second_detail->setText(QString::fromStdString("Type: " + _computer.getType()));
    if (_computer.getBuilt())
    {
        ui->third_detail->setText(QString::fromStdString("Existed: Yes"));
    }
    else
    {
        ui->third_detail->setText(QString::fromStdString("Existed: No"));
    }

    ui->fourth_detail->setText("");
}
<commit_msg>Right click detail functional<commit_after>#include "details.h"
#include "ui_details.h"

Details::Details(QWidget* parent, Scientist* scientist) :
    QDialog(parent),
    ui(new Ui::Details)
{
    ui->setupUi(this);
    _scientist = *scientist;

    ScientistDetails();
}

Details::Details(QWidget* parent, Computer* computer) :
    QDialog(parent),
    ui(new Ui::Details)
{
    ui->setupUi(this);
    _computer = *computer;

    ComputerDetails();
}

Details::~Details()
{
    delete ui;
}

void Details::ScientistDetails()
{
    ui->label_name->setText(QString::fromStdString("
" + _scientist.getName() + "
"));
    ui->first_detail->setText(QString::fromStdString("Gender: " + _scientist.getGender()));
    ui->second_detail->setText(QString::fromStdString("Year Of Birth: ") + QString::number(_scientist.getYearOfBirth()));

    if (_scientist.getYearOfDeath())
    {
        ui->third_detail->setText(QString::fromStdString("Year Of Death: ") + QString::number(_scientist.getYearOfDeath()));
    }
    else
    {
        ui->third_detail->setText("Alive and well (I think)");
    }

    ui->fourth_detail->setText(QString::fromStdString("Age: ") + QString::number(_scientist.getAge()));
}

void Details::ComputerDetails()
{
    ui->label_name->setText(QString::fromStdString("
" + _computer.getName() + "
"));
    ui->first_detail->setText(QString::fromStdString("Year built: ") + QString::number(_computer.getYearBuilt()));
    ui->second_detail->setText(QString::fromStdString("Type: " + _computer.getType()));
    if (_computer.getBuilt())
    {
        ui->third_detail->setText(QString::fromStdString("Existed: Yes"));
    }
    else
    {
        ui->third_detail->setText(QString::fromStdString("Existed: No"));
    }

    ui->fourth_detail->setText("");
}
<|endoftext|>


<commit_before>#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>

int main()
{
	CppUnit::TextTestRunner runner;
	CppUnit::TestFactoryRegistry & registry(
		CppUnit::TestFactoryRegistry::getRegistry());
	CppUnit::Test *test(registry.makeTest());
	runner.addTest(test);

	CppUnit::BriefTestProgressListener progress;
	runner.eventManager().addListener(&progress);

	return runner.run() ? 0 : 1;
}
<commit_msg>tests: add compiler outputter<commit_after>#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/CompilerOutputter.h>

int main()
{
	CppUnit::TextTestRunner runner;
	CppUnit::TestFactoryRegistry & registry(
		CppUnit::TestFactoryRegistry::getRegistry());
	CppUnit::Test *test(registry.makeTest());
	runner.addTest(test);

	CppUnit::BriefTestProgressListener progress;
	runner.eventManager().addListener(&progress);

	runner.setOutputter(new CppUnit::CompilerOutputter(
		&runner.result(), std::cerr, "%p:%l:"));

	return runner.run() ? 0 : 1;
}
<|endoftext|>


<commit_before>void loadlibs ()
{
  gSystem->Load("libMC");

  // libraries required by EVGEN
  // (commented libraries are already loaded in prevoius sequence)

  gSystem->Load("libmicrocern");
  gSystem->Load("libSTEER");
  gSystem->Load("libEG");
  gSystem->Load("libEGPythia6");
  gSystem->Load("libdummypythia6");
  gSystem->Load("libdummyhijing");
  gSystem->Load("libTHijing");
  gSystem->Load("libdummyHBTP");
  gSystem->Load("libTHbtp");
  gSystem->Load("libdummymevsim");
  gSystem->Load("libTMevSim");
  gSystem->Load("libEVGEN");

  gSystem->Load("libPhysics");

  gSystem->Load("libCONTAINERS");
  gSystem->Load("libFMD");
  gSystem->Load("libMUON");
  gSystem->Load("libPHOS");
  gSystem->Load("libPMD");
  gSystem->Load("libRICH");
  gSystem->Load("libSTRUCT");
  gSystem->Load("libTOF");
  gSystem->Load("libTPC");
  gSystem->Load("libTRD");
  gSystem->Load("libZDC");
  gSystem->Load("libITS");
  gSystem->Load("libCRT");
  gSystem->Load("libSTART");
  gSystem->Load("libEMCAL");
  gSystem->Load("libVZERO");
  gSystem->Load("libdummyherwig");
  gSystem->Load("libTHerwig");
}
<commit_msg>Correcting the order and the names of libraries<commit_after>void loadlibs ()
{
  gSystem->Load("libMC");

  // libraries required by EVGEN
  // (commented libraries are already loaded in prevoius sequence)

  gSystem->Load("libmicrocern");
  gSystem->Load("libEG");
  gSystem->Load("libSTEER");
  gSystem->Load("libEGPythia6");
  gSystem->Load("libdummypythia6");
  gSystem->Load("libdummyhijing");
  gSystem->Load("libTHijing");
  gSystem->Load("libdummyHBTP");
  gSystem->Load("libTHbtp");
  gSystem->Load("libdummymevsim");
  gSystem->Load("libTMEVSIM");
  gSystem->Load("libEVGEN");

  gSystem->Load("libPhysics");

  gSystem->Load("libCONTAINERS");
  gSystem->Load("libFMD");
  gSystem->Load("libMUON");
  gSystem->Load("libPHOS");
  gSystem->Load("libPMD");
  gSystem->Load("libRICH");
  gSystem->Load("libSTRUCT");
  gSystem->Load("libTPC");
  gSystem->Load("libTRD");
  gSystem->Load("libTOF");
  gSystem->Load("libZDC");
  gSystem->Load("libITS");
  gSystem->Load("libCRT");
  gSystem->Load("libSTART");
  gSystem->Load("libEMCAL");
  gSystem->Load("libVZERO");
  gSystem->Load("libdummyherwig");
  gSystem->Load("libTHerwig");
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com)
 */

#ifndef _PCL_TEST_GPU_OCTREE_DATAGEN_
#define _PCL_TEST_GPU_OCTREE_DATAGEN_

#include <vector>
#include <algorithm>
#include <iostream>
#include <opencv2/core/core.hpp>

#include <Eigen/StdVector>

/** BROKEN EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(pcl::PointXYZ)*/

struct DataGenerator
{
    typedef pcl::gpu::Octree::PointType PointType;

    size_t data_size;
    size_t tests_num;

    float cube_size;
    float max_radius;

    float shared_radius;

    std::vector<PointType> points;
    std::vector<PointType> queries;
    std::vector<float> radiuses;
    std::vector< std::vector<int> > bfresutls;

    DataGenerator() : data_size(871000), tests_num(10000), cube_size(1024.f)
    {
        max_radius    = cube_size/15.f;
        shared_radius = cube_size/20.f;
    }

    void operator()()
    {
        cv::RNG& rng = cv::theRNG();

        points.resize(data_size);
        for(size_t i = 0; i < data_size; ++i)
        {
            points[i].x = (float)rng * cube_size;
            points[i].y = (float)rng * cube_size;
            points[i].z = (float)rng * cube_size;
        }

        queries.resize(tests_num);
        radiuses.resize(tests_num);
        for (size_t i = 0; i < tests_num; ++i)
        {
            queries[i].x = (float)rng * cube_size;
            queries[i].y = (float)rng * cube_size;
            queries[i].z = (float)rng * cube_size;
            radiuses[i]  = (float)rng * max_radius;
        };
    }

    void bruteForceSearch(bool log = false, float radius = -1.f)
    {
        if (log)
            std::cout << "BruteForceSearch";

        int value100 = std::min<int>(tests_num, 50);
        int step = tests_num/value100;

        bfresutls.resize(tests_num);
        for(size_t i = 0; i < tests_num; ++i)
        {
            if (log && i % step == 0)
                std::cout << ".";

            std::vector<int>& curr_res = bfresutls[i];
            curr_res.clear();

            float query_radius = radius > 0 ? radius : radiuses[i];
            const PointType& query = queries[i];

            for(size_t ind = 0; ind < points.size(); ++ind)
            {
                const PointType& point = points[ind];

                float dx = query.x - point.x;
                float dy = query.y - point.y;
                float dz = query.z - point.z;

                if (dx*dx + dy*dy + dz*dz < query_radius * query_radius)
                    curr_res.push_back(ind);
            }

            std::sort(curr_res.begin(), curr_res.end());
        }
        if (log)
            std::cout << "Done" << std::endl;
    }

    void printParams() const
    {
        std::cout << "Points number  = " << data_size << std::endl;
        std::cout << "Queries number = " << tests_num << std::endl;
        std::cout << "Cube size      = " << cube_size << std::endl;
        std::cout << "Max radius     = " << max_radius << std::endl;
        std::cout << "Shared radius  = " << shared_radius << std::endl;
    }

    template<typename Dst>
    struct ConvPoint
    {
        Dst operator()(const PointType& src) const
        {
            Dst dst;
            dst.x = src.x;
            dst.y = src.y;
            dst.z = src.z;
            return dst;
        }
    };

};

#endif  /* _PCL_TEST_GPU_OCTREE_DATAGEN_ */

<commit_msg>revert<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *  Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com)
 */

#ifndef _PCL_TEST_GPU_OCTREE_DATAGEN_
#define _PCL_TEST_GPU_OCTREE_DATAGEN_

#include <vector>
#include <algorithm>
#include <iostream>
#include <opencv2/core/core.hpp>

#include <Eigen/StdVector>

EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(pcl::PointXYZ)

struct DataGenerator
{
    typedef pcl::gpu::Octree::PointType PointType;

    size_t data_size;
    size_t tests_num;

    float cube_size;
    float max_radius;

    float shared_radius;

    std::vector<PointType> points;
    std::vector<PointType> queries;
    std::vector<float> radiuses;
    std::vector< std::vector<int> > bfresutls;

    DataGenerator() : data_size(871000), tests_num(10000), cube_size(1024.f)
    {
        max_radius    = cube_size/15.f;
        shared_radius = cube_size/20.f;
    }

    void operator()()
    {
        cv::RNG& rng = cv::theRNG();

        points.resize(data_size);
        for(size_t i = 0; i < data_size; ++i)
        {
            points[i].x = (float)rng * cube_size;
            points[i].y = (float)rng * cube_size;
            points[i].z = (float)rng * cube_size;
        }

        queries.resize(tests_num);
        radiuses.resize(tests_num);
        for (size_t i = 0; i < tests_num; ++i)
        {
            queries[i].x = (float)rng * cube_size;
            queries[i].y = (float)rng * cube_size;
            queries[i].z = (float)rng * cube_size;
            radiuses[i]  = (float)rng * max_radius;
        };
    }

    void bruteForceSearch(bool log = false, float radius = -1.f)
    {
        if (log)
            std::cout << "BruteForceSearch";

        int value100 = std::min<int>(tests_num, 50);
        int step = tests_num/value100;

        bfresutls.resize(tests_num);
        for(size_t i = 0; i < tests_num; ++i)
        {
            if (log && i % step == 0)
                std::cout << ".";

            std::vector<int>& curr_res = bfresutls[i];
            curr_res.clear();

            float query_radius = radius > 0 ? radius : radiuses[i];
            const PointType& query = queries[i];

            for(size_t ind = 0; ind < points.size(); ++ind)
            {
                const PointType& point = points[ind];

                float dx = query.x - point.x;
                float dy = query.y - point.y;
                float dz = query.z - point.z;

                if (dx*dx + dy*dy + dz*dz < query_radius * query_radius)
                    curr_res.push_back(ind);
            }

            std::sort(curr_res.begin(), curr_res.end());
        }
        if (log)
            std::cout << "Done" << std::endl;
    }

    void printParams() const
    {
        std::cout << "Points number  = " << data_size << std::endl;
        std::cout << "Queries number = " << tests_num << std::endl;
        std::cout << "Cube size      = " << cube_size << std::endl;
        std::cout << "Max radius     = " << max_radius << std::endl;
        std::cout << "Shared radius  = " << shared_radius << std::endl;
    }

    template<typename Dst>
    struct ConvPoint
    {
        Dst operator()(const PointType& src) const
        {
            Dst dst;
            dst.x = src.x;
            dst.y = src.y;
            dst.z = src.z;
            return dst;
        }
    };

};

#endif  /* _PCL_TEST_GPU_OCTREE_DATAGEN_ */

<|endoftext|>


<commit_before><commit_msg>Edit comments.<commit_after><|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkCommon.h"
#include "mitkTestingMacros.h"
#include <mitkLog.h>
#include <itksys/SystemTools.hxx>
#include <mitkStandardFileLocations.h>

#include <QtConcurrentRun>

void LogMessages(unsigned int threadID, unsigned int numberOfTimes = 5000)
{
  unsigned int times = 0;

  while(times < numberOfTimes)
  {
    MITK_INFO << "Test info stream in thread" << threadID << "\n even with newlines";
    MITK_WARN << "Test warning stream in thread " << threadID <<". "
      << "Even with a very long text, even without meaning or implied meaning or content, just a long sentence to see whether something has problems with long sentences or output in files or into windows or commandlines or whatever.";
    MITK_DEBUG << "Test debugging stream in thread " << threadID;
    MITK_ERROR << "Test error stream in thread " << threadID;
    MITK_FATAL << "Test fatal stream in thread " << threadID;

    times= 5;
  }
}

/**
  \brief Test logging from Qt threads
*/
static void TestThreadSaveLog(bool toFile)
{
  bool testSucceded = true;

  try
  {
    if (toFile)
    {
      std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() "/qtestthreadlog.log";
      mitk::LoggingBackend::SetLogFile(filename.c_str());
    }

    unsigned int numberOfThreads = 20;
    unsigned int threadRuntimeInMilliseconds = 4000;
    QVector< QFuture<void> > threads;

    // Spawn some threads
    for (unsigned int threadIdx = 0; threadIdx < numberOfThreads;+threadIdx)
    {
      threads.push_back( QtConcurrent::run( LogMessages, threadIdx, 1000 ) );
      std::cout << "Created " << threadIdx << ". thread." << std::endl;
    }

    //wait for some time (milliseconds)
    itksys::SystemTools::Delay( threadRuntimeInMilliseconds );

    // Wait for all to finish
    for (unsigned int threadIdx = 0; threadIdx < numberOfThreads;+threadIdx)
    {
      threads[threadIdx].waitForFinished();
      std::cout << threadIdx << ". thread has finished" << std::endl;
    }
  }
  catch(std::exception e)
  {
    MITK_ERROR << "exception during 'TestThreadSaveLog': "<<e.what();
    testSucceded = false;
  }
  catch(...)
  {
    MITK_ERROR << "unknown exception during 'TestThreadSaveLog'";
    testSucceded = false;
  }

  //if no error occured until now, everything is ok
  MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging in different threads.");
}

int QmitkThreadedLogTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("QmitkThreadedLogTest")

  MITK_TEST_OUTPUT(<<"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!")

  TestThreadSaveLog( false ); // false = to console
  TestThreadSaveLog( true );  // true = to file

  MITK_TEST_OUTPUT(<<"Number of threads in QThreadPool: " << QThreadPool::globalInstance()->maxThreadCount() )

  // always end with this!
  MITK_TEST_END()
}
<commit_msg>COMP: Fix syntax error<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkCommon.h"
#include "mitkTestingMacros.h"
#include <mitkLog.h>
#include <itksys/SystemTools.hxx>
#include <mitkStandardFileLocations.h>

#include <string>

#include <QtConcurrentRun>

void LogMessages(unsigned int threadID, unsigned int numberOfTimes = 5000)
{
  unsigned int times = 0;

  while(times < numberOfTimes)
  {
    MITK_INFO << "Test info stream in thread" << threadID << "\n even with newlines";
    MITK_WARN << "Test warning stream in thread " << threadID <<". "
      << "Even with a very long text, even without meaning or implied meaning or content, just a long sentence to see whether something has problems with long sentences or output in files or into windows or commandlines or whatever.";
    MITK_DEBUG << "Test debugging stream in thread " << threadID;
    MITK_ERROR << "Test error stream in thread " << threadID;
    MITK_FATAL << "Test fatal stream in thread " << threadID;

    times= 5;
  }
}

/**
  \brief Test logging from Qt threads
*/
static void TestThreadSaveLog(bool toFile)
{
  bool testSucceded = true;

  try
  {
    if (toFile)
    {
      std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/qtestthreadlog.log";
      mitk::LoggingBackend::SetLogFile(filename.c_str());
    }

    unsigned int numberOfThreads = 20;
    unsigned int threadRuntimeInMilliseconds = 4000;
    QVector< QFuture<void> > threads;

    // Spawn some threads
    for (unsigned int threadIdx = 0; threadIdx < numberOfThreads;+threadIdx)
    {
      threads.push_back( QtConcurrent::run( LogMessages, threadIdx, 1000 ) );
      std::cout << "Created " << threadIdx << ". thread." << std::endl;
    }

    //wait for some time (milliseconds)
    itksys::SystemTools::Delay( threadRuntimeInMilliseconds );

    // Wait for all to finish
    for (unsigned int threadIdx = 0; threadIdx < numberOfThreads;+threadIdx)
    {
      threads[threadIdx].waitForFinished();
      std::cout << threadIdx << ". thread has finished" << std::endl;
    }
  }
  catch(std::exception e)
  {
    MITK_ERROR << "exception during 'TestThreadSaveLog': "<<e.what();
    testSucceded = false;
  }
  catch(...)
  {
    MITK_ERROR << "unknown exception during 'TestThreadSaveLog'";
    testSucceded = false;
  }

  //if no error occured until now, everything is ok
  MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging in different threads.");
}

int QmitkThreadedLogTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("QmitkThreadedLogTest")

  MITK_TEST_OUTPUT(<<"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!")

  TestThreadSaveLog( false ); // false = to console
  TestThreadSaveLog( true );  // true = to file

  MITK_TEST_OUTPUT(<<"Number of threads in QThreadPool: " << QThreadPool::globalInstance()->maxThreadCount() )

  // always end with this!
  MITK_TEST_END()
}
<|endoftext|>


<commit_before>#include "TIndexTable.h"

//////////////////////////////////////////////////////////////////////////////
// TIndexTable class is helper class to keep the list of the referencs to the
// TTable rows and iterate over it.
// TIndexTable is a persistent class.
// The pointer to the TIndexTable object may be used as an element
// of the TTable row and saved with the table all together.
//
// For example, the track table may contain a member to the "map" of the hits
//  struct {
//    float helix;
//    TIndexTable *hits;
//  } tracks_t;
//
//   // Create track table:
//   LArTrackTable *tracks = new LArTrackTable(...);
//
//   // Get pointer to the hit table
//   LArHitTable *hits = GiveMeHits();
//   // Loop over all tracks
//   LArTrackTable::iterator track = tracks->begin();
//   LArTrackTable::iterator last = tracks->end();
//   for (;track != last;track++) {
//     // Find all hits of this track
//      LArHitTable::iterator hit     = hits->begin();
//      LArHitTable::iterator lastHit = hits->end();
//      Long_t hitIndx = 0;
//      // Create an empty list of this track hits
//      (*track).hits = new TIndexTable(hits);
//      for(;hit != lastHit;hit++,hitIndx) {
//        if (IsMyHit(*hit)) {  // add this hit index to the current track
//           (*track).hits->push_back(hitIndx);
//        }
//      }
//   }
//___________________________________________________________________

// TableClassImpl(TIndexTable,int);
  TTableDescriptor *TIndexTable::fgColDescriptors = TIndexTable::CreateDescriptor();
  ClassImp(TIndexTable)
#if 0
  void TIndexTable::Dictionary()
   {
      TClass *c = CreateClass(_QUOTE_(className), Class_Version(),
                              DeclFileName(), ImplFileName(),
                              DeclFileLine(), ImplFileLine());

      char *structBuf = new char[strlen(_QUOTE2_(structName,.h))+2];
      strcpy(structBuf,_QUOTE2_(structName,.h));
      char *s = strstr(structBuf,"_st.h");
      if (s) { *s = 0;  strcat(structBuf,".h"); }
      TClass *r = CreateClass(_QUOTE_(structName), Class_Version(),
                              structBuf, structBuf, 1,  1 );
      fgIsA = c;
      fgColDescriptors = new TTableDescriptor(r);
   }
   _TableClassImp_(TIndexTable,int)
#endif
  TableClassStreamerImp(TIndexTable)

//___________________________________________________________________
     TIndexTable::TIndexTable(const TTable *table):TTable("Index",-1), fRefTable(table)
{
   if (!fgColDescriptors)    CreateDescriptor();
   fSize = fgColDescriptors->Sizeof();
  // Add refered table to this index.
   // yf  if (table) Add((TDataSet *)table);
}
//___________________________________________________________________
TTableDescriptor *TIndexTable::CreateDescriptor()
{
  if (!fgColDescriptors) {
     // Set an empty descriptor
     fgColDescriptors= new TTableDescriptor("int");
      // Create one
     if (fgColDescriptors) {
       TTableDescriptor  &dsc = *fgColDescriptors;
       tableDescriptor_st row;

       memset(&row,0,sizeof(row));
       strncpy(row.fColumnName,"index",sizeof(row.fColumnName));

       row.fType = kInt;
       row.fTypeSize = sizeof(Int_t);
       row.fSize = row.fTypeSize;
       dsc.AddAt(&row);
     }
  }
  return fgColDescriptors;
}

//___________________________________________________________________
const TTable *TIndexTable::Table() const
{
  return fRefTable;
}
<commit_msg>add missing cvs identification line.<commit_after>// @(#)root/table:$Name:$:$Id:$
// Author: Valery Fine(fine@bnl.gov)   01/03/2001

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * Copyright (C) 2001 [BNL] Brookhaven National Laboratory.              *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TIndexTable.h"

//////////////////////////////////////////////////////////////////////////////
// TIndexTable class is helper class to keep the list of the referencs to the
// TTable rows and iterate over it.
// TIndexTable is a persistent class.
// The pointer to the TIndexTable object may be used as an element
// of the TTable row and saved with the table all together.
//
// For example, the track table may contain a member to the "map" of the hits
//  struct {
//    float helix;
//    TIndexTable *hits;
//  } tracks_t;
//
//   // Create track table:
//   LArTrackTable *tracks = new LArTrackTable(...);
//
//   // Get pointer to the hit table
//   LArHitTable *hits = GiveMeHits();
//   // Loop over all tracks
//   LArTrackTable::iterator track = tracks->begin();
//   LArTrackTable::iterator last = tracks->end();
//   for (;track != last;track++) {
//     // Find all hits of this track
//      LArHitTable::iterator hit     = hits->begin();
//      LArHitTable::iterator lastHit = hits->end();
//      Long_t hitIndx = 0;
//      // Create an empty list of this track hits
//      (*track).hits = new TIndexTable(hits);
//      for(;hit != lastHit;hit++,hitIndx) {
//        if (IsMyHit(*hit)) {  // add this hit index to the current track
//           (*track).hits->push_back(hitIndx);
//        }
//      }
//   }
//___________________________________________________________________

// TableClassImpl(TIndexTable,int);
  TTableDescriptor *TIndexTable::fgColDescriptors = TIndexTable::CreateDescriptor();
  ClassImp(TIndexTable)
#if 0
  void TIndexTable::Dictionary()
   {
      TClass *c = CreateClass(_QUOTE_(className), Class_Version(),
                              DeclFileName(), ImplFileName(),
                              DeclFileLine(), ImplFileLine());

      char *structBuf = new char[strlen(_QUOTE2_(structName,.h))+2];
      strcpy(structBuf,_QUOTE2_(structName,.h));
      char *s = strstr(structBuf,"_st.h");
      if (s) { *s = 0;  strcat(structBuf,".h"); }
      TClass *r = CreateClass(_QUOTE_(structName), Class_Version(),
                              structBuf, structBuf, 1,  1 );
      fgIsA = c;
      fgColDescriptors = new TTableDescriptor(r);
   }
   _TableClassImp_(TIndexTable,int)
#endif
  TableClassStreamerImp(TIndexTable)

//___________________________________________________________________
     TIndexTable::TIndexTable(const TTable *table):TTable("Index",-1), fRefTable(table)
{
   if (!fgColDescriptors)    CreateDescriptor();
   fSize = fgColDescriptors->Sizeof();
  // Add refered table to this index.
   // yf  if (table) Add((TDataSet *)table);
}
//___________________________________________________________________
TTableDescriptor *TIndexTable::CreateDescriptor()
{
  if (!fgColDescriptors) {
     // Set an empty descriptor
     fgColDescriptors= new TTableDescriptor("int");
      // Create one
     if (fgColDescriptors) {
       TTableDescriptor  &dsc = *fgColDescriptors;
       tableDescriptor_st row;

       memset(&row,0,sizeof(row));
       strncpy(row.fColumnName,"index",sizeof(row.fColumnName));

       row.fType = kInt;
       row.fTypeSize = sizeof(Int_t);
       row.fSize = row.fTypeSize;
       dsc.AddAt(&row);
     }
  }
  return fgColDescriptors;
}

//___________________________________________________________________
const TTable *TIndexTable::Table() const
{
  return fRefTable;
}
<|endoftext|>


<commit_before>
// Simple macro showing capabilities of TGSpeedo widget.

#include "TSystem.h"
#include "TGFrame.h"
#include "TGWindow.h"
#include "TGSpeedo.h"

class TGShapedMain : public TGMainFrame {

protected:
   TGSpeedo          *fSpeedo;          // analog meter
   Int_t              fActInfo;         // actual information value
   Bool_t             fRunning;         // kTRUE while updating infos

public:
   TGShapedMain(const TGWindow *p, int w, int h);
   virtual ~TGShapedMain();

   void              CloseWindow();
   TGSpeedo         *GetSpeedo() const { return fSpeedo; }
   Int_t             GetActInfo() const { return fActInfo; }
   Bool_t            IsRunning() const { return fRunning; }
   void              ToggleInfos();
};

//______________________________________________________________________________
TGShapedMain::TGShapedMain(const TGWindow *p, int w, int h) :
   TGMainFrame(p, w, h)
{
   // Constructor.

   fActInfo = 1;
   fRunning = kTRUE;

   fSpeedo = new TGSpeedo(this, 0.0, 100.0, "CPU", "[%]");
   fSpeedo->Connect("OdoClicked()", "TGShapedMain", this, "ToggleInfos()");
   fSpeedo->Connect("LedClicked()", "TGShapedMain", this, "CloseWindow()");
   TGMainFrame::Connect("CloseWindow()", "TGShapedMain", this, "CloseWindow()");
   AddFrame(fSpeedo, new TGLayoutHints(kLHintsCenterX | kLHintsCenterX, 0, 0, 0, 0));
   fSpeedo->SetDisplayText("Used RAM", "[MB]");

   MapSubwindows();
   MapWindow();
   // To avoid closing the window while TGSpeedo is drawing
   DontCallClose();
   Resize(GetDefaultSize());
   // Set fixed size
   SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 1, 1);
   SetWindowName("ROOT CPU Load Meter");
}

//______________________________________________________________________________
void TGShapedMain::ToggleInfos()
{
   // Toggle information displayed in Analog Meter

   if (fActInfo < 2)
      fActInfo++;
   else
      fActInfo = 0;
   if (fActInfo == 0)
      fSpeedo->SetDisplayText("Total RAM", "[MB]");
   else if (fActInfo == 1)
      fSpeedo->SetDisplayText("Used RAM", "[MB]");
   else if (fActInfo == 2)
      fSpeedo->SetDisplayText("Free RAM", "[MB]");
}

//______________________________________________________________________________
TGShapedMain::~TGShapedMain()
{
   // Destructor.

}

//______________________________________________________________________________
void TGShapedMain::CloseWindow()
{
   // Close Window.

   // stop updating
   fRunning = kFALSE;
   // reset kDontCallClose bit to be able to really close the window
   ResetBit(kDontCallClose);
}

//______________________________________________________________________________
void CPUMeter()
{
   // Main application.

   MemInfo_t memInfo;
   CpuInfo_t cpuInfo;
   Float_t act_load, prev_load = 0.0;
   Int_t i, memUsage, old_memUsage = 0;

   TGShapedMain *mainWindow = new TGShapedMain(gClient->GetRoot(), 500, 200);
   TGSpeedo *speedo = mainWindow->GetSpeedo();

   // set threshold values
   speedo->SetThresholds(12.5, 50.0, 87.5);
   // set threshold colors
   speedo->SetThresholdColors(TGSpeedo::kGreen, TGSpeedo::kOrange, TGSpeedo::kRed);
   // enable threshold
   speedo->EnableThreshold();
   speedo->SetScaleValue(0.0, 5);
   // enable peak marker
   speedo->EnablePeakMark();
   // update the TGSpeedo widget
   gSystem->ProcessEvents();
   while (mainWindow->IsRunning() && mainWindow->IsMapped()) {
      // Get CPU informations
      gSystem->GetCpuInfo(&cpuInfo);
      // actual CPU load
      act_load = cpuInfo.fTotal;
      // Get Memory informations
      gSystem->GetMemInfo(&memInfo);
      // choose which value to display
      if (mainWindow->GetActInfo() == 0)
         memUsage = memInfo.fMemTotal;
      else if (mainWindow->GetActInfo() == 1)
         memUsage = memInfo.fMemUsed;
      else if (mainWindow->GetActInfo() == 2)
         memUsage = memInfo.fMemFree;
      // small threshold to avoid "trembling" needle
      if (fabs(act_load-prev_load) > 0.9) {
         speedo->SetScaleValue(act_load, 5);
         prev_load = act_load;
      }
      // update only if value has changed
      if (memUsage != old_memUsage) {
         speedo->SetOdoValue(memUsage);
         old_memUsage = memUsage;
      }
      // sleep a bit
      gSystem->Sleep(250);
      gSystem->ProcessEvents();
   }
   mainWindow->CloseWindow();
}

<commit_msg>From Bertrand: added some protections.<commit_after>
// Simple macro showing capabilities of TGSpeedo widget.

#include "TSystem.h"
#include "TGFrame.h"
#include "TGWindow.h"
#include "TGSpeedo.h"

class TGShapedMain : public TGMainFrame {

protected:
   TGSpeedo          *fSpeedo;          // analog meter
   Int_t              fActInfo;         // actual information value
   Bool_t             fRunning;         // kTRUE while updating infos

public:
   TGShapedMain(const TGWindow *p, int w, int h);
   virtual ~TGShapedMain();

   void              CloseWindow();
   TGSpeedo         *GetSpeedo() const { return fSpeedo; }
   Int_t             GetActInfo() const { return fActInfo; }
   Bool_t            IsRunning() const { return fRunning; }
   void              ToggleInfos();
};

//______________________________________________________________________________
TGShapedMain::TGShapedMain(const TGWindow *p, int w, int h) :
   TGMainFrame(p, w, h)
{
   // Constructor.

   fActInfo = 1;
   fRunning = kTRUE;

   fSpeedo = new TGSpeedo(this, 0.0, 100.0, "CPU", "[%]");
   fSpeedo->Connect("OdoClicked()", "TGShapedMain", this, "ToggleInfos()");
   fSpeedo->Connect("LedClicked()", "TGShapedMain", this, "CloseWindow()");
   TGMainFrame::Connect("CloseWindow()", "TGShapedMain", this, "CloseWindow()");
   AddFrame(fSpeedo, new TGLayoutHints(kLHintsCenterX | kLHintsCenterX, 0, 0, 0, 0));
   fSpeedo->SetDisplayText("Used RAM", "[MB]");

   MapSubwindows();
   MapWindow();
   // To avoid closing the window while TGSpeedo is drawing
   DontCallClose();
   Resize(GetDefaultSize());
   // Set fixed size
   SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 1, 1);
   SetWindowName("ROOT CPU Load Meter");
}

//______________________________________________________________________________
void TGShapedMain::ToggleInfos()
{
   // Toggle information displayed in Analog Meter

   if (fActInfo < 2)
      fActInfo++;
   else
      fActInfo = 0;
   if (fActInfo == 0)
      fSpeedo->SetDisplayText("Total RAM", "[MB]");
   else if (fActInfo == 1)
      fSpeedo->SetDisplayText("Used RAM", "[MB]");
   else if (fActInfo == 2)
      fSpeedo->SetDisplayText("Free RAM", "[MB]");
}

//______________________________________________________________________________
TGShapedMain::~TGShapedMain()
{
   // Destructor.

}

//______________________________________________________________________________
void TGShapedMain::CloseWindow()
{
   // Close Window.

   // stop updating
   fRunning = kFALSE;
   // reset kDontCallClose bit to be able to really close the window
   ResetBit(kDontCallClose);
}

//______________________________________________________________________________
void CPUMeter()
{
   // Main application.

   MemInfo_t memInfo;
   CpuInfo_t cpuInfo;
   Float_t act_load, prev_load = 0.0;
   Int_t i, memUsage, old_memUsage = 0;

   TGShapedMain *mainWindow = new TGShapedMain(gClient->GetRoot(), 500, 200);
   TGSpeedo *speedo = mainWindow->GetSpeedo();

   // set threshold values
   speedo->SetThresholds(12.5, 50.0, 87.5);
   // set threshold colors
   speedo->SetThresholdColors(TGSpeedo::kGreen, TGSpeedo::kOrange, TGSpeedo::kRed);
   // enable threshold
   speedo->EnableThreshold();
   speedo->SetScaleValue(0.0, 5);
   // enable peak marker
   speedo->EnablePeakMark();
   // update the TGSpeedo widget
   gSystem->GetCpuInfo(&cpuInfo);
   gSystem->GetMemInfo(&memInfo);
   gSystem->ProcessEvents();
   while (mainWindow->IsRunning() && mainWindow->IsMapped()) {
      // Get CPU informations
      gSystem->GetCpuInfo(&cpuInfo);
      // actual CPU load
      act_load = cpuInfo.fTotal;
      // Get Memory informations
      gSystem->GetMemInfo(&memInfo);
      // choose which value to display
      if (mainWindow->GetActInfo() == 0)
         memUsage = memInfo.fMemTotal;
      else if (mainWindow->GetActInfo() == 1)
         memUsage = memInfo.fMemUsed;
      else if (mainWindow->GetActInfo() == 2)
         memUsage = memInfo.fMemFree;
      // small threshold to avoid "trembling" needle
      if (fabs(act_load-prev_load) > 0.9) {
         speedo->SetScaleValue(act_load, 5);
         prev_load = act_load;
      }
      // update only if value has changed
      if (memUsage != old_memUsage) {
         speedo->SetOdoValue(memUsage);
         old_memUsage = memUsage;
      }
      // sleep a bit
      gSystem->ProcessEvents();
      gSystem->Sleep(250);
   }
   mainWindow->CloseWindow();
}

<|endoftext|>