text
stringlengths 54
60.6k
|
---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SQLException.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:36:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_
#include "java/sql/SQLException.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//**************************************************************
//************ Class: java.sql.SQLException
//**************************************************************
java_sql_SQLException::java_sql_SQLException( const java_sql_SQLException_BASE& _rException,const Reference< XInterface> & _rContext)
: starsdbc::SQLException( _rException.getMessage(),
_rContext,
_rException.getSQLState(),
_rException.getErrorCode(),
makeAny(_rException.getNextException())
)
{
}
java_sql_SQLException_BASE::java_sql_SQLException_BASE( JNIEnv * pEnv, jobject myObj ) : java_lang_Exception( pEnv, myObj )
{
}
jclass java_sql_SQLException_BASE::theClass = 0;
java_sql_SQLException_BASE::~java_sql_SQLException_BASE()
{}
jclass java_sql_SQLException_BASE::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass("java/sql/SQLException");
OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
if(!tempClass)
{
t.pEnv->ExceptionDescribe();
t.pEnv->ExceptionClear();
}
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_sql_SQLException_BASE::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
starsdbc::SQLException java_sql_SQLException_BASE::getNextException() const
{
jobject out = NULL;
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/sql/Exception;";
static const char * cMethodName = "getNextException";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
if( out )
{
java_sql_SQLException_BASE warn_base(t.pEnv,out);
return (starsdbc::SQLException)java_sql_SQLException(warn_base,0);
}
return starsdbc::SQLException();
}
::rtl::OUString java_sql_SQLException_BASE::getSQLState() const
{
SDBThreadAttach t;
::rtl::OUString aStr;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/lang/String;";
static const char * cMethodName = "getSQLState";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jstring out = (jstring) t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
aStr = JavaString2String(t.pEnv,out);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return aStr;
}
sal_Int32 java_sql_SQLException_BASE::getErrorCode() const
{
jint out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()I";
static const char * cMethodName = "getErrorCode";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallIntMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
return (sal_Int32)out;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.10.60); FILE MERGED 2006/09/01 17:22:21 kaib 1.10.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SQLException.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-17 02:49:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_
#include "java/sql/SQLException.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//**************************************************************
//************ Class: java.sql.SQLException
//**************************************************************
java_sql_SQLException::java_sql_SQLException( const java_sql_SQLException_BASE& _rException,const Reference< XInterface> & _rContext)
: starsdbc::SQLException( _rException.getMessage(),
_rContext,
_rException.getSQLState(),
_rException.getErrorCode(),
makeAny(_rException.getNextException())
)
{
}
java_sql_SQLException_BASE::java_sql_SQLException_BASE( JNIEnv * pEnv, jobject myObj ) : java_lang_Exception( pEnv, myObj )
{
}
jclass java_sql_SQLException_BASE::theClass = 0;
java_sql_SQLException_BASE::~java_sql_SQLException_BASE()
{}
jclass java_sql_SQLException_BASE::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass("java/sql/SQLException");
OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
if(!tempClass)
{
t.pEnv->ExceptionDescribe();
t.pEnv->ExceptionClear();
}
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_sql_SQLException_BASE::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
starsdbc::SQLException java_sql_SQLException_BASE::getNextException() const
{
jobject out = NULL;
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/sql/Exception;";
static const char * cMethodName = "getNextException";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
if( out )
{
java_sql_SQLException_BASE warn_base(t.pEnv,out);
return (starsdbc::SQLException)java_sql_SQLException(warn_base,0);
}
return starsdbc::SQLException();
}
::rtl::OUString java_sql_SQLException_BASE::getSQLState() const
{
SDBThreadAttach t;
::rtl::OUString aStr;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/lang/String;";
static const char * cMethodName = "getSQLState";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jstring out = (jstring) t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
aStr = JavaString2String(t.pEnv,out);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return aStr;
}
sal_Int32 java_sql_SQLException_BASE::getErrorCode() const
{
jint out(0);
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()I";
static const char * cMethodName = "getErrorCode";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallIntMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
return (sal_Int32)out;
}
<|endoftext|>
|
<commit_before>#ifndef __MEDIA_OBJECT_IMPL_HPP__
#define __MEDIA_OBJECT_IMPL_HPP__
#include <Factory.hpp>
#include "MediaObject.hpp"
#include <EventHandler.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <mutex>
#include <map>
#include "Tag.hpp"
#include <gst/gst.h>
namespace kurento
{
class MediaPipelineImpl;
class MediaObjectImpl;
void Serialize (std::shared_ptr<MediaObjectImpl> &object,
JsonSerializer &serializer);
class MediaObjectImpl : public virtual MediaObject
{
public:
MediaObjectImpl (const boost::property_tree::ptree &config);
MediaObjectImpl (const boost::property_tree::ptree &config,
std::shared_ptr <MediaObject> parent);
virtual ~MediaObjectImpl () {}
void addTag (const std::string &key, const std::string &value);
void removeTag (const std::string &key);
std::string getTag (const std::string &key);
std::vector<std::shared_ptr<Tag>> getTags ();
virtual std::shared_ptr<MediaPipeline> getMediaPipeline ();
virtual std::shared_ptr<MediaObject> getParent ()
{
return parent;
}
virtual std::vector<std::shared_ptr<MediaObject>> getChilds ();
virtual std::string getId ();
virtual std::string getName ();
virtual void setName (const std::string &name);
virtual bool getSendTagsInEvents ();
virtual void setSendTagsInEvents (bool sendTagsInEvents);
virtual int getCreationTime ();
virtual void release ()
{
}
/* Next methods are automatically implemented by code generator */
virtual bool connect (const std::string &eventType,
std::shared_ptr<EventHandler> handler);
sigc::signal<void, Error> signalError;
virtual void invoke (std::shared_ptr<MediaObjectImpl> obj,
const std::string &methodName, const Json::Value ¶ms,
Json::Value &response);
virtual void Serialize (JsonSerializer &serializer);
protected:
template <class T>
T getConfigValue (const std::string &key)
{
auto child = config.get_child (key);
std::stringstream ss;
Json::Value val;
Json::Reader reader;
kurento::JsonSerializer serializer (false);
boost::property_tree::ptree array;
array.push_back (std::make_pair ("val", child) );
boost::property_tree::write_json (ss, array);
reader.parse (ss.str(), val);
T ret {};
serializer.JsonValue = val;
serializer.Serialize ("val", ret);
return ret;
}
template <class T>
T getConfigValue (const std::string &key, T defaultValue)
{
try {
return getConfigValue<T> (key);
} catch (boost::property_tree::ptree_bad_path &e) {
/* This case is expected, the config does not have the requested key */
} catch (KurentoException &e) {
GST_WARNING ("Posible error deserializing %s from config", key.c_str() );
} catch (std::exception &e) {
GST_WARNING ("Unknown error getting%s from config", key.c_str() );
}
return defaultValue;
}
template <class T, class C>
T getConfigValue (const std::string &key)
{
auto child = config.get_child ("modules." + dynamic_cast <C *>
(this)->getModule() + "."
+ dynamic_cast <C *> (this)->getType() + "." + key);
std::stringstream ss;
Json::Value val;
Json::Reader reader;
kurento::JsonSerializer serializer (false);
boost::property_tree::ptree array;
array.push_back (std::make_pair ("val", child) );
boost::property_tree::write_json (ss, array);
reader.parse (ss.str(), val);
T ret {};
serializer.JsonValue = val;
serializer.Serialize ("val", ret);
return ret;
}
template <class T, class C>
T getConfigValue (const std::string &key, T defaultValue)
{
try {
return getConfigValue<T, C> (key);
} catch (boost::property_tree::ptree_bad_path &e) {
/* This case is expected, the config does not have the requested key */
} catch (KurentoException &e) {
GST_WARNING ("Posible error deserializing %s from config", key.c_str() );
} catch (std::exception &e) {
GST_WARNING ("Unknown error getting%s from config", key.c_str() );
}
return defaultValue;
}
/*
* This method is intented to perform initialization actions that require
* a call to shared_from_this ()
*/
virtual void postConstructor ();
const boost::property_tree::ptree &config;
private:
std::string initialId;
std::string id;
std::string name;
std::recursive_mutex mutex;
std::shared_ptr<MediaObject> parent;
int64_t creationTime;
std::string createId();
std::map<std::string, std::string> tagsMap;
bool sendTagsInEvents;
class StaticConstructor
{
public:
StaticConstructor();
};
static StaticConstructor staticConstructor;
friend Factory;
};
} /* kurento */
#endif /* __MEDIA_OBJECT_IMPL_HPP__ */
<commit_msg>MediaObject: Unify all the functions to get values from config<commit_after>#ifndef __MEDIA_OBJECT_IMPL_HPP__
#define __MEDIA_OBJECT_IMPL_HPP__
#include <Factory.hpp>
#include "MediaObject.hpp"
#include <EventHandler.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <mutex>
#include <map>
#include "Tag.hpp"
#include <gst/gst.h>
namespace kurento
{
class MediaPipelineImpl;
class MediaObjectImpl;
void Serialize (std::shared_ptr<MediaObjectImpl> &object,
JsonSerializer &serializer);
class MediaObjectImpl : public virtual MediaObject
{
public:
MediaObjectImpl (const boost::property_tree::ptree &config);
MediaObjectImpl (const boost::property_tree::ptree &config,
std::shared_ptr <MediaObject> parent);
virtual ~MediaObjectImpl () {}
void addTag (const std::string &key, const std::string &value);
void removeTag (const std::string &key);
std::string getTag (const std::string &key);
std::vector<std::shared_ptr<Tag>> getTags ();
virtual std::shared_ptr<MediaPipeline> getMediaPipeline ();
virtual std::shared_ptr<MediaObject> getParent ()
{
return parent;
}
virtual std::vector<std::shared_ptr<MediaObject>> getChilds ();
virtual std::string getId ();
virtual std::string getName ();
virtual void setName (const std::string &name);
virtual bool getSendTagsInEvents ();
virtual void setSendTagsInEvents (bool sendTagsInEvents);
virtual int getCreationTime ();
virtual void release ()
{
}
/* Next methods are automatically implemented by code generator */
virtual bool connect (const std::string &eventType,
std::shared_ptr<EventHandler> handler);
sigc::signal<void, Error> signalError;
virtual void invoke (std::shared_ptr<MediaObjectImpl> obj,
const std::string &methodName, const Json::Value ¶ms,
Json::Value &response);
virtual void Serialize (JsonSerializer &serializer);
template <class T>
static T getConfigValue (const boost::property_tree::ptree &config,
const std::string &key)
{
auto child = config.get_child (key);
std::stringstream ss;
Json::Value val;
Json::Reader reader;
kurento::JsonSerializer serializer (false);
boost::property_tree::ptree array;
array.push_back (std::make_pair ("val", child) );
boost::property_tree::write_json (ss, array);
reader.parse (ss.str(), val);
T ret {};
serializer.JsonValue = val;
serializer.Serialize ("val", ret);
return ret;
}
template <class T>
static T getConfigValue (const boost::property_tree::ptree &config,
const std::string &key, T defaultValue)
{
try {
return getConfigValue<T> (config, key);
} catch (boost::property_tree::ptree_bad_path &e) {
/* This case is expected, the config does not have the requested key */
} catch (KurentoException &e) {
GST_WARNING ("Posible error deserializing %s from config", key.c_str() );
} catch (std::exception &e) {
GST_WARNING ("Unknown error getting%s from config", key.c_str() );
}
return defaultValue;
}
protected:
template <class T>
T getConfigValue (const std::string &key)
{
return getConfigValue <T> (config, key);
}
template <class T>
T getConfigValue (const std::string &key, T defaultValue)
{
return getConfigValue <T> (config, key, defaultValue);
}
template <class T, class C>
T getConfigValue (const std::string &key)
{
return getConfigValue <T> ("modules." + dynamic_cast <C *>
(this)->getModule() + "."
+ dynamic_cast <C *> (this)->getType() + "." + key);
}
template <class T, class C>
T getConfigValue (const std::string &key, T defaultValue)
{
return getConfigValue <T> ("modules." + dynamic_cast <C *>
(this)->getModule() + "."
+ dynamic_cast <C *> (this)->getType() + "." + key, defaultValue);
}
/*
* This method is intented to perform initialization actions that require
* a call to shared_from_this ()
*/
virtual void postConstructor ();
const boost::property_tree::ptree &config;
private:
std::string initialId;
std::string id;
std::string name;
std::recursive_mutex mutex;
std::shared_ptr<MediaObject> parent;
int64_t creationTime;
std::string createId();
std::map<std::string, std::string> tagsMap;
bool sendTagsInEvents;
class StaticConstructor
{
public:
StaticConstructor();
};
static StaticConstructor staticConstructor;
friend Factory;
};
} /* kurento */
#endif /* __MEDIA_OBJECT_IMPL_HPP__ */
<|endoftext|>
|
<commit_before>#include "writeback.h"
#include <kernel/kernel.h>
template <typename ISA>
Writeback<ISA>::Writeback( Module* parent, std::endian endian) : Module( parent, "writeback"), endian( endian)
{
rp_mem_datapath = make_read_port<Instr>("MEMORY_2_WRITEBACK", Port::LATENCY);
rp_execute_datapath = make_read_port<Instr>("EXECUTE_2_WRITEBACK", Port::LATENCY);
rp_branch_datapath = make_read_port<Instr>("BRANCH_2_WRITEBACK", Port::LATENCY);
rp_trap = make_read_port<bool>("WRITEBACK_2_ALL_FLUSH", Port::LATENCY);
wp_bypass = make_write_port<InstructionOutput>("WRITEBACK_2_EXECUTE_BYPASS", Port::BW);
wp_halt = make_write_port<Trap>("WRITEBACK_2_CORE_HALT", Port::BW);
wp_trap = make_write_port<bool>("WRITEBACK_2_ALL_FLUSH", Port::BW);
wp_target = make_write_port<Target>("WRITEBACK_2_FETCH_TARGET", Port::BW);
}
template <typename ISA>
Writeback<ISA>::~Writeback() = default;
template <typename ISA>
void Writeback<ISA>::set_kernel( const std::shared_ptr<Kernel>& k, std::string_view isa)
{
kernel = k;
checker.init( endian, kernel.get(), isa);
}
template<typename ISA>
void Writeback<ISA>::set_target( const Target& value, Cycle cycle)
{
set_checker_target( value);
set_writeback_target( value, cycle);
}
template<typename ISA>
void Writeback<ISA>::set_writeback_target( const Target& value, Cycle cycle)
{
next_PC = value.address;
wp_trap->write( true, cycle);
wp_target->write( value, cycle);
}
template<typename ISA>
void Writeback<ISA>::set_checker_target( const Target& value)
{
checker.set_target( value);
}
template <typename ISA>
auto Writeback<ISA>::read_instructions( Cycle cycle)
{
auto ports = { rp_branch_datapath, rp_mem_datapath, rp_execute_datapath };
std::vector<Instr> result;
for ( auto& port : ports)
if ( port->is_ready( cycle))
result.emplace_back( port->read( cycle));
return result;
}
template <typename ISA>
void Writeback<ISA>::clock( Cycle cycle)
{
sout << "wb cycle " << std::dec << cycle << ": ";
if ( rp_trap->is_ready( cycle) && rp_trap->read( cycle)) {
writeback_bubble( cycle);
return;
}
auto instrs = read_instructions( cycle);
if ( instrs.empty())
writeback_bubble( cycle);
else for ( auto& instr : instrs)
writeback_instruction_system( &instr, cycle);
}
template <typename ISA>
void Writeback<ISA>::writeback_instruction_system( Writeback<ISA>::Instr* instr, Cycle cycle)
{
writeback_instruction( *instr, cycle);
bool has_syscall = instr->trap_type() == Trap::SYSCALL;
kernel->handle_instruction( instr);
auto result_trap = driver->handle_trap( *instr);
checker.driver_step( *instr);
if ( executed_instrs >= instrs_to_run)
wp_halt->write( Trap( Trap::BREAKPOINT), cycle);
else
wp_halt->write( result_trap, cycle);
if ( result_trap != Trap::NO_TRAP)
set_target( instr->get_actual_target(), cycle);
if ( has_syscall)
set_writeback_target( instr->get_actual_target(), cycle);
}
template <typename ISA>
void Writeback<ISA>::writeback_bubble( Cycle cycle)
{
sout << "bubble\n";
if ( cycle >= last_writeback_cycle + 100_lt)
throw Deadlock( "");
}
template <typename ISA>
void Writeback<ISA>::writeback_instruction( const Writeback<ISA>::Instr& instr, Cycle cycle)
{
rf->write_dst( instr);
wp_bypass->write( instr.get_v_dst(), cycle);
sout << instr << std::endl;
checker.check( instr);
++executed_instrs;
last_writeback_cycle = cycle;
next_PC = instr.get_actual_target().address;
}
template <typename ISA>
int Writeback<ISA>::get_exit_code() const noexcept
{
return 0;
}
template <typename ISA>
void Writeback<ISA>::enable_driver_hooks()
{
driver = Driver::create_hooked_driver( driver.get());
}
#include <mips/mips.h>
#include <risc_v/risc_v.h>
template class Writeback<MIPSI>;
template class Writeback<MIPSII>;
template class Writeback<MIPSIII>;
template class Writeback<MIPSIV>;
template class Writeback<MIPS32>;
template class Writeback<MIPS64>;
template class Writeback<MARS>;
template class Writeback<MARS64>;
template class Writeback<RISCV32>;
template class Writeback<RISCV64>;
template class Writeback<RISCV128>;
<commit_msg>Fix rv32ui-p-simple test<commit_after>#include "writeback.h"
#include <kernel/kernel.h>
template <typename ISA>
Writeback<ISA>::Writeback( Module* parent, std::endian endian) : Module( parent, "writeback"), endian( endian)
{
rp_mem_datapath = make_read_port<Instr>("MEMORY_2_WRITEBACK", Port::LATENCY);
rp_execute_datapath = make_read_port<Instr>("EXECUTE_2_WRITEBACK", Port::LATENCY);
rp_branch_datapath = make_read_port<Instr>("BRANCH_2_WRITEBACK", Port::LATENCY);
rp_trap = make_read_port<bool>("WRITEBACK_2_ALL_FLUSH", Port::LATENCY);
wp_bypass = make_write_port<InstructionOutput>("WRITEBACK_2_EXECUTE_BYPASS", Port::BW);
wp_halt = make_write_port<Trap>("WRITEBACK_2_CORE_HALT", Port::BW);
wp_trap = make_write_port<bool>("WRITEBACK_2_ALL_FLUSH", Port::BW);
wp_target = make_write_port<Target>("WRITEBACK_2_FETCH_TARGET", Port::BW);
}
template <typename ISA>
Writeback<ISA>::~Writeback() = default;
template <typename ISA>
void Writeback<ISA>::set_kernel( const std::shared_ptr<Kernel>& k, std::string_view isa)
{
kernel = k;
checker.init( endian, kernel.get(), isa);
}
template<typename ISA>
void Writeback<ISA>::set_target( const Target& value, Cycle cycle)
{
set_checker_target( value);
set_writeback_target( value, cycle);
}
template<typename ISA>
void Writeback<ISA>::set_writeback_target( const Target& value, Cycle cycle)
{
next_PC = value.address;
wp_trap->write( true, cycle);
wp_target->write( value, cycle);
}
template<typename ISA>
void Writeback<ISA>::set_checker_target( const Target& value)
{
checker.set_target( value);
}
template <typename ISA>
auto Writeback<ISA>::read_instructions( Cycle cycle)
{
auto ports = { rp_branch_datapath, rp_mem_datapath, rp_execute_datapath };
std::vector<Instr> result;
for ( auto& port : ports)
if ( port->is_ready( cycle))
result.emplace_back( port->read( cycle));
return result;
}
template <typename ISA>
void Writeback<ISA>::clock( Cycle cycle)
{
sout << "wb cycle " << std::dec << cycle << ": ";
if ( rp_trap->is_ready( cycle) && rp_trap->read( cycle)) {
writeback_bubble( cycle);
return;
}
auto instrs = read_instructions( cycle);
if ( instrs.empty())
writeback_bubble( cycle);
else for ( auto& instr : instrs)
writeback_instruction_system( &instr, cycle);
}
template <typename ISA>
void Writeback<ISA>::writeback_instruction_system( Writeback<ISA>::Instr* instr, Cycle cycle)
{
writeback_instruction( *instr, cycle);
bool has_syscall = instr->trap_type() == Trap::SYSCALL;
kernel->handle_instruction( instr);
auto result_trap = driver->handle_trap( *instr);
checker.driver_step( *instr);
if ( executed_instrs >= instrs_to_run)
wp_halt->write( Trap( Trap::BREAKPOINT), cycle);
else
wp_halt->write( result_trap, cycle);
if ( has_syscall)
set_writeback_target( instr->get_actual_target(), cycle);
else if ( result_trap != Trap::NO_TRAP)
set_target( instr->get_actual_target(), cycle);
}
template <typename ISA>
void Writeback<ISA>::writeback_bubble( Cycle cycle)
{
sout << "bubble\n";
if ( cycle >= last_writeback_cycle + 100_lt)
throw Deadlock( "");
}
template <typename ISA>
void Writeback<ISA>::writeback_instruction( const Writeback<ISA>::Instr& instr, Cycle cycle)
{
rf->write_dst( instr);
wp_bypass->write( instr.get_v_dst(), cycle);
sout << instr << std::endl;
checker.check( instr);
++executed_instrs;
last_writeback_cycle = cycle;
next_PC = instr.get_actual_target().address;
}
template <typename ISA>
int Writeback<ISA>::get_exit_code() const noexcept
{
return 0;
}
template <typename ISA>
void Writeback<ISA>::enable_driver_hooks()
{
driver = Driver::create_hooked_driver( driver.get());
}
#include <mips/mips.h>
#include <risc_v/risc_v.h>
template class Writeback<MIPSI>;
template class Writeback<MIPSII>;
template class Writeback<MIPSIII>;
template class Writeback<MIPSIV>;
template class Writeback<MIPS32>;
template class Writeback<MIPS64>;
template class Writeback<MARS>;
template class Writeback<MARS64>;
template class Writeback<RISCV32>;
template class Writeback<RISCV64>;
template class Writeback<RISCV128>;
<|endoftext|>
|
<commit_before><commit_msg>Linux: fix memory leak in new SkFontHost code.<commit_after><|endoftext|>
|
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2017 Darrell Wright
//
// 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.
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
// Use a Monte Carlo method to calculate pi. pi = (4 * points in circle)/count of points
int main( int, char** ) {
intmax_t const radius = 10000;
size_t const num_values = 1'000'000;
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng{ rd( ) }; // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<intmax_t> uni{ -radius, radius }; // guaranteed unbiased
size_t count = 0;
size_t in_circle = 0;
auto const radius2 = radius*radius;
for( intmax_t n=0; n<num_values; ++n ) {
auto const x = uni( rng );
auto const y = uni( rng );
auto const d2 = x*x + y*y;
++count;
if( d2 < radius2 ) {
++in_circle;
}
}
std::cout << "With a radius of " << radius << " and a sample size of " << num_values << '\n';
std::cout << "Estimate = " << (4.0*static_cast<double>(in_circle))/static_cast<double>(count) << '\n';
return EXIT_SUCCESS;
}
<commit_msg>Changed to float random generation and only used the top-right quadrant for testing. Ratio remains the same<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2017 Darrell Wright
//
// 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.
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
// Use a Monte Carlo method to calculate pi. pi = (4 * points in circle)/count of points
int main( int, char** ) {
intmax_t const radius = 1.0;
size_t const num_values = 1'000'000'000;
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng{ rd( ) }; // random-number engine used (Mersenne-Twister in this case)
std::uniform_real_distribution<float> uni{ 0, radius }; // guaranteed unbiased
size_t count = 0;
size_t in_circle = 0;
auto const radius2 = radius*radius;
for( intmax_t n=0; n<num_values; ++n ) {
auto const x = uni( rng );
auto const y = uni( rng );
auto const d2 = x*x + y*y;
++count;
if( d2 < radius2 ) {
++in_circle;
}
}
std::cout << "With a radius of " << radius << " and a sample size of " << num_values << '\n';
std::cout << "Estimate = " << (4.0*static_cast<double>(in_circle))/static_cast<double>(count) << '\n';
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*! \file EulerParameterVector.cpp
*/
#include "EulerParameterVector.h"
namespace numlib{ namespace tensor{
EulerParameterVector::EulerParameterVector(Real q1_, Real q2_, Real q3_, Real q4_):
q1(q1_),
q2(q2_),
q3(q3_),
q4(q4_)
{
}
EulerParameterVector::EulerParameterVector(const TensorR2 & r)
{
using std::sqrt;
Real r12 = r(1,2);
Real r21 = r(2,1);
Real r13 = r(1,3);
Real r31 = r(3,1);
Real r23 = r(2,3);
Real r32 = r(3,2);
q4 = sqrt(0.25*(trace(r) + 1.0));
Real q44 = 4.0*q4;
q1 = (r32 - r23)/q44;
q2 = (r13 - r31)/q44;
q3 = (r21 - r12)/q44;
}
EulerParameterVector::EulerParameterVector(const TensorR1 & e, Real theta)
{
using std::cos;
using std::sin;
Real theta2 = 0.5*theta;
Real c = cos(theta2);
Real s = sin(theta2);
q4 = c;
q1 = e(1)*s;
q2 = e(2)*s;
q3 = e(3)*s;
}
EulerParameterVector::EulerParameterVector(const EulerParameterVector & other):
q1(other.q1),
q2(other.q2),
q3(other.q3),
q4(other.q4)
{
}
EulerParameterVector::~EulerParameterVector()
{
/* nothing to delete */
}
EulerParameterVector & EulerParameterVector::operator=(const EulerParameterVector & other)
{
if(&other == this)
return *this;
q1 = other.q1;
q2 = other.q2;
q3 = other.q3;
q4 = other.q4;
return *this;
}
Real EulerParameterVector::rotationAngle() const
{
using std::acos;
return 2.0*acos(q4);
}
TensorR1 EulerParameterVector::rotationAxis() const
{
using std::sin;
Real theta = rotationAngle();
/* theta should be mod to [0, pi) */
if(theta == 0.0)
return TensorR1(0.0, 0.0, 0.0);
Real s = sin(0.5*theta);
Real e1 = q1/s;
Real e2 = q2/s;
Real e3 = q3/s;
return TensorR1(e1, e2, e3);
}
Real & EulerParameterVector::operator()(Index i)
{
switch(i)
{
case 1:
return q1;
case 2:
return q2;
case 3:
return q3;
case 4:
return q4;
}
}
const Real & EulerParameterVector::operator()(Index i) const
{
switch(i)
{
case 1:
return q1;
case 2:
return q2;
case 3:
return q3;
case 4:
return q4;
}
}
std::ostream & operator<<(std::ostream & os, const EulerParameterVector & ep)
{
os<<std::scientific
<<"( "<<ep.q1
<<", "<<ep.q2
<<", "<<ep.q3
<<", "<<ep.q4
<<" )";
}
}}//::numlib::tensor
<commit_msg>BUG FIX: Fixed error in computation of rotation angle from Euler parameter<commit_after>/*! \file EulerParameterVector.cpp
*/
#include "EulerParameterVector.h"
namespace numlib{ namespace tensor{
EulerParameterVector::EulerParameterVector(Real q1_, Real q2_, Real q3_, Real q4_):
q1(q1_),
q2(q2_),
q3(q3_),
q4(q4_)
{
}
EulerParameterVector::EulerParameterVector(const TensorR2 & r)
{
using std::sqrt;
Real r12 = r(1,2);
Real r21 = r(2,1);
Real r13 = r(1,3);
Real r31 = r(3,1);
Real r23 = r(2,3);
Real r32 = r(3,2);
q4 = sqrt(0.25*(trace(r) + 1.0));
Real q44 = 4.0*q4;
q1 = (r32 - r23)/q44;
q2 = (r13 - r31)/q44;
q3 = (r21 - r12)/q44;
}
EulerParameterVector::EulerParameterVector(const TensorR1 & e, Real theta)
{
using std::cos;
using std::sin;
Real theta2 = 0.5*theta;
Real c = cos(theta2);
Real s = sin(theta2);
q4 = c;
q1 = e(1)*s;
q2 = e(2)*s;
q3 = e(3)*s;
}
EulerParameterVector::EulerParameterVector(const EulerParameterVector & other):
q1(other.q1),
q2(other.q2),
q3(other.q3),
q4(other.q4)
{
}
EulerParameterVector::~EulerParameterVector()
{
/* nothing to delete */
}
EulerParameterVector & EulerParameterVector::operator=(const EulerParameterVector & other)
{
if(&other == this)
return *this;
q1 = other.q1;
q2 = other.q2;
q3 = other.q3;
q4 = other.q4;
return *this;
}
Real EulerParameterVector::rotationAngle() const
{
using std::acos;
return acos(2.0*q4);
}
TensorR1 EulerParameterVector::rotationAxis() const
{
using std::sin;
Real theta = rotationAngle();
/* theta should be mod to [0, pi) */
if(theta == 0.0)
return TensorR1(0.0, 0.0, 0.0);
Real s = sin(0.5*theta);
Real e1 = q1/s;
Real e2 = q2/s;
Real e3 = q3/s;
return TensorR1(e1, e2, e3);
}
Real & EulerParameterVector::operator()(Index i)
{
switch(i)
{
case 1:
return q1;
case 2:
return q2;
case 3:
return q3;
case 4:
return q4;
}
}
const Real & EulerParameterVector::operator()(Index i) const
{
switch(i)
{
case 1:
return q1;
case 2:
return q2;
case 3:
return q3;
case 4:
return q4;
}
}
std::ostream & operator<<(std::ostream & os, const EulerParameterVector & ep)
{
os<<std::scientific
<<"( "<<ep.q1
<<", "<<ep.q2
<<", "<<ep.q3
<<", "<<ep.q4
<<" )";
}
}}//::numlib::tensor
<|endoftext|>
|
<commit_before>/**
* @file simulator_node.cpp
* @author Icaro da Costa Mota
* @author Matheus Vieira Portela
* @date 25/03/2014
*
* @attention Copyright (C) 2014 UnBall Robot Soccer Team
*
* @brief Has a Gazebo plugin for controlling the robots and publish the state of the simulation
*/
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <vector>
void publishVel(ros::Publisher &publisher);
int main(int argc, char **argv){
ros::init(argc, argv, "simulator_node");
ros::NodeHandle n;
ros::Rate loop_rate(10);
ros::Publisher publisher = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
while (ros::ok())
{
publishVel(publisher);
ros::spinOnce();
loop_rate.sleep();
}
return(0);
}
void publishVel(ros::Publisher &publisher)
{
geometry_msgs::Twist msg;
ROS_DEBUG("Publishing cmd vel");
msg.linear.x = 0.0;
msg.linear.y = 0.0;
msg.linear.z = 0.0;
msg.angular.x = 0.0;
msg.angular.y = 0.0;
msg.angular.z = 10.0;
publisher.publish(msg);
}
<commit_msg>Controller is working! For fixed translational and rotational velocities, all robots are making a circle.<commit_after>/**
* @file simulator_node.cpp
* @author Icaro da Costa Mota
* @author Matheus Vieira Portela
* @date 25/03/2014
*
* @attention Copyright (C) 2014 UnBall Robot Soccer Team
*
* @brief Has a Gazebo plugin for controlling the robots and publish the state of the simulation
*/
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <vector>
void publishVel(ros::Publisher &publisher);
int main(int argc, char **argv){
ros::init(argc, argv, "simulator_node");
ros::NodeHandle n;
ros::Rate loop_rate(10);
ros::Publisher publisher = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
while (ros::ok())
{
publishVel(publisher);
ros::spinOnce();
loop_rate.sleep();
}
return(0);
}
void publishVel(ros::Publisher &publisher)
{
geometry_msgs::Twist msg;
ROS_DEBUG("Publishing cmd vel");
msg.linear.x = 0.10; // Set to make the robot turn
msg.linear.y = 0.0;
msg.linear.z = 0.0;
msg.angular.x = 0.0;
msg.angular.y = 0.0;
msg.angular.z = 0.5; // Set to make the robot move
publisher.publish(msg);
}
<|endoftext|>
|
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* BufferV.cpp
*
*/
#include "ChunkV.h"
#include "adios2/toolkit/format/buffer/BufferV.h"
#include <assert.h>
#include <iostream>
#include <stddef.h> // max_align_t
#include <string.h>
namespace adios2
{
namespace format
{
ChunkV::ChunkV(const std::string type, const bool AlwaysCopy,
const size_t ChunkSize)
: BufferV(type, AlwaysCopy), m_ChunkSize(ChunkSize)
{
}
ChunkV::~ChunkV()
{
for (const auto &Chunk : m_Chunks)
{
free((void *)Chunk);
}
}
void ChunkV::CopyExternalToInternal()
{
for (std::size_t i = 0; i < DataV.size(); ++i)
{
if (DataV[i].External)
{
size_t size = DataV[i].Size;
// we can possibly append this entry to the tail if the tail entry
// is internal
bool AppendPossible = DataV.size() && !DataV.back().External;
std::cout << "Cpying external to internal" << std::endl;
if (AppendPossible && (m_TailChunkPos + size > m_ChunkSize))
{
// No room in current chunk, close it out
// realloc down to used size (helpful?) and set size in array
m_Chunks.back() =
(char *)realloc(m_Chunks.back(), m_TailChunkPos);
m_TailChunkPos = 0;
m_TailChunk = NULL;
AppendPossible = false;
}
if (AppendPossible)
{
// We can use current chunk, just append the data and modify the
// DataV entry
memcpy(m_TailChunk + m_TailChunkPos, DataV[i].Base, size);
DataV[i].External = false;
DataV[i].Base = m_TailChunk + m_TailChunkPos;
m_TailChunkPos += size;
}
else
{
// We need a new chunk, get the larger of size or m_ChunkSize
size_t NewSize = m_ChunkSize;
if (size > m_ChunkSize)
NewSize = size;
m_TailChunk = (char *)malloc(NewSize);
m_Chunks.push_back(m_TailChunk);
memcpy(m_TailChunk, DataV[i].Base, size);
m_TailChunkPos = size;
DataV[i] = {false, m_TailChunk, 0, size};
}
}
}
}
size_t ChunkV::AddToVec(const size_t size, const void *buf, int align,
bool CopyReqd)
{
int badAlign = CurOffset % align;
if (badAlign)
{
int addAlign = align - badAlign;
assert(addAlign < sizeof(max_align_t));
static char zero[sizeof(max_align_t)] = {0};
AddToVec(addAlign, zero, 1, true);
}
size_t retOffset = CurOffset;
if (size == 0)
return CurOffset;
if (!CopyReqd && !m_AlwaysCopy)
{
// just add buf to internal version of output vector
VecEntry entry = {true, buf, 0, size};
DataV.push_back(entry);
}
else
{
// we can possibly append this entry to the last if the last was
// internal
bool AppendPossible = DataV.size() && !DataV.back().External;
if (AppendPossible && (m_TailChunkPos + size > m_ChunkSize))
{
// No room in current chunk, close it out
// realloc down to used size (helpful?) and set size in array
m_Chunks.back() = (char *)realloc(m_Chunks.back(), m_TailChunkPos);
m_TailChunkPos = 0;
m_TailChunk = NULL;
AppendPossible = false;
}
if (AppendPossible)
{
// We can use current chunk, just append the data;
memcpy(m_TailChunk + m_TailChunkPos, buf, size);
DataV.back().Size += size;
m_TailChunkPos += size;
}
else
{
// We need a new chunk, get the larger of size or m_ChunkSize
size_t NewSize = m_ChunkSize;
if (size > m_ChunkSize)
NewSize = size;
m_TailChunk = (char *)malloc(NewSize);
m_Chunks.push_back(m_TailChunk);
memcpy(m_TailChunk, buf, size);
m_TailChunkPos = size;
VecEntry entry = {false, m_TailChunk, 0, size};
DataV.push_back(entry);
}
}
CurOffset = retOffset + size;
return retOffset;
}
ChunkV::BufferV_iovec ChunkV::DataVec() noexcept
{
BufferV_iovec ret = new iovec[DataV.size() + 1];
for (std::size_t i = 0; i < DataV.size(); ++i)
{
// For ChunkV, all entries in DataV are actual iov entries.
ret[i].iov_base = DataV[i].Base;
ret[i].iov_len = DataV[i].Size;
}
ret[DataV.size()] = {NULL, 0};
return ret;
}
} // end namespace format
} // end namespace adios2
<commit_msg>Fix append condition<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* BufferV.cpp
*
*/
#include "ChunkV.h"
#include "adios2/toolkit/format/buffer/BufferV.h"
#include <assert.h>
#include <iostream>
#include <stddef.h> // max_align_t
#include <string.h>
namespace adios2
{
namespace format
{
ChunkV::ChunkV(const std::string type, const bool AlwaysCopy,
const size_t ChunkSize)
: BufferV(type, AlwaysCopy), m_ChunkSize(ChunkSize)
{
}
ChunkV::~ChunkV()
{
for (const auto &Chunk : m_Chunks)
{
free((void *)Chunk);
}
}
void ChunkV::CopyExternalToInternal()
{
for (std::size_t i = 0; i < DataV.size(); ++i)
{
if (DataV[i].External)
{
size_t size = DataV[i].Size;
// we can possibly append this entry to the tail if the tail entry
// is internal
bool AppendPossible = DataV.size() && !DataV.back().External;
if (AppendPossible && (m_TailChunkPos + size > m_ChunkSize))
{
// No room in current chunk, close it out
// realloc down to used size (helpful?) and set size in array
m_Chunks.back() =
(char *)realloc(m_Chunks.back(), m_TailChunkPos);
m_TailChunkPos = 0;
m_TailChunk = NULL;
AppendPossible = false;
}
if (AppendPossible)
{
// We can use current chunk, just append the data and modify the
// DataV entry
memcpy(m_TailChunk + m_TailChunkPos, DataV[i].Base, size);
DataV[i].External = false;
DataV[i].Base = m_TailChunk + m_TailChunkPos;
m_TailChunkPos += size;
}
else
{
// We need a new chunk, get the larger of size or m_ChunkSize
size_t NewSize = m_ChunkSize;
if (size > m_ChunkSize)
NewSize = size;
m_TailChunk = (char *)malloc(NewSize);
m_Chunks.push_back(m_TailChunk);
memcpy(m_TailChunk, DataV[i].Base, size);
m_TailChunkPos = size;
DataV[i] = {false, m_TailChunk, 0, size};
}
}
}
}
size_t ChunkV::AddToVec(const size_t size, const void *buf, int align,
bool CopyReqd)
{
int badAlign = CurOffset % align;
if (badAlign)
{
int addAlign = align - badAlign;
assert(addAlign < sizeof(max_align_t));
static char zero[sizeof(max_align_t)] = {0};
AddToVec(addAlign, zero, 1, true);
}
size_t retOffset = CurOffset;
if (size == 0)
return CurOffset;
if (!CopyReqd && !m_AlwaysCopy)
{
// just add buf to internal version of output vector
VecEntry entry = {true, buf, 0, size};
DataV.push_back(entry);
}
else
{
// we can possibly append this entry to the last if the last was
// internal
bool AppendPossible =
DataV.size() && !DataV.back().External &&
(m_TailChunk + m_TailChunkPos - DataV.back().Size ==
DataV.back().Base);
if (AppendPossible && (m_TailChunkPos + size > m_ChunkSize))
{
// No room in current chunk, close it out
// realloc down to used size (helpful?) and set size in array
m_Chunks.back() = (char *)realloc(m_Chunks.back(), m_TailChunkPos);
m_TailChunkPos = 0;
m_TailChunk = NULL;
AppendPossible = false;
}
if (AppendPossible)
{
// We can use current chunk, just append the data;
memcpy(m_TailChunk + m_TailChunkPos, buf, size);
DataV.back().Size += size;
m_TailChunkPos += size;
}
else
{
// We need a new chunk, get the larger of size or m_ChunkSize
size_t NewSize = m_ChunkSize;
if (size > m_ChunkSize)
NewSize = size;
m_TailChunk = (char *)malloc(NewSize);
m_Chunks.push_back(m_TailChunk);
memcpy(m_TailChunk, buf, size);
m_TailChunkPos = size;
VecEntry entry = {false, m_TailChunk, 0, size};
DataV.push_back(entry);
}
}
CurOffset = retOffset + size;
return retOffset;
}
ChunkV::BufferV_iovec ChunkV::DataVec() noexcept
{
BufferV_iovec ret = new iovec[DataV.size() + 1];
for (std::size_t i = 0; i < DataV.size(); ++i)
{
// For ChunkV, all entries in DataV are actual iov entries.
ret[i].iov_base = DataV[i].Base;
ret[i].iov_len = DataV[i].Size;
}
ret[DataV.size()] = {NULL, 0};
return ret;
}
} // end namespace format
} // end namespace adios2
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: adjushdl.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: dvo $ $Date: 2001-06-29 21:07:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_PROPERTYHANDLER_ADJUSTTYPES_HXX
#include <adjushdl.hxx>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PARAGRAPHADJUST_HPP_
#include <com/sun/star/style/ParagraphAdjust.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::xmloff::token;
SvXMLEnumMapEntry __READONLY_DATA pXML_Para_Adjust_Enum[] =
{
{ XML_START, style::ParagraphAdjust_LEFT },
{ XML_END, style::ParagraphAdjust_RIGHT },
{ XML_CENTER, style::ParagraphAdjust_CENTER },
{ XML_JUSTIFY, style::ParagraphAdjust_BLOCK },
{ XML_JUSTIFIED, style::ParagraphAdjust_BLOCK }, // obsolete
{ XML_TOKEN_INVALID, 0 }
};
SvXMLEnumMapEntry __READONLY_DATA pXML_Para_Align_Last_Enum[] =
{
{ XML_START, style::ParagraphAdjust_LEFT },
{ XML_CENTER, style::ParagraphAdjust_CENTER },
{ XML_JUSTIFY, style::ParagraphAdjust_BLOCK },
{ XML_JUSTIFIED, style::ParagraphAdjust_BLOCK }, // obsolete
{ XML_TOKEN_INVALID, 0 }
};
///////////////////////////////////////////////////////////////////////////////
//
// class XMLParaAdjustPropHdl
//
XMLParaAdjustPropHdl::~XMLParaAdjustPropHdl()
{
// nothing to do
}
sal_Bool XMLParaAdjustPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_uInt16 eAdjust;
if( ( bRet = rUnitConverter.convertEnum( eAdjust, rStrImpValue, pXML_Para_Adjust_Enum ) ) )
rValue <<= (sal_Int16)eAdjust;
return bRet;
}
sal_Bool XMLParaAdjustPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
OUStringBuffer aOut;
sal_Int16 nVal;
rValue >>= nVal;
sal_Bool bRet = rUnitConverter.convertEnum( aOut, nVal, pXML_Para_Adjust_Enum, XML_START );
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
///////////////////////////////////////////////////////////////////////////////
//
// class XMLLastLineAdjustPropHdl
//
XMLLastLineAdjustPropHdl::~XMLLastLineAdjustPropHdl()
{
// nothing to do
}
sal_Bool XMLLastLineAdjustPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_uInt16 eAdjust;
if( ( bRet = rUnitConverter.convertEnum( eAdjust, rStrImpValue, pXML_Para_Align_Last_Enum ) ) )
rValue <<= (sal_Int16)eAdjust;
return bRet;
}
sal_Bool XMLLastLineAdjustPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
OUStringBuffer aOut;
sal_Int16 nVal;
sal_Bool bRet = sal_False;
rValue >>= nVal;
if( nVal != style::ParagraphAdjust_LEFT )
bRet = rUnitConverter.convertEnum( aOut, nVal, pXML_Para_Align_Last_Enum, XML_START );
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
<commit_msg>#102407# (on behalf of [email protected]) ParaAdjustHdl: don't export VOID values<commit_after>/*************************************************************************
*
* $RCSfile: adjushdl.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: fs $ $Date: 2002-11-06 10:33:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_PROPERTYHANDLER_ADJUSTTYPES_HXX
#include <adjushdl.hxx>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PARAGRAPHADJUST_HPP_
#include <com/sun/star/style/ParagraphAdjust.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::xmloff::token;
SvXMLEnumMapEntry __READONLY_DATA pXML_Para_Adjust_Enum[] =
{
{ XML_START, style::ParagraphAdjust_LEFT },
{ XML_END, style::ParagraphAdjust_RIGHT },
{ XML_CENTER, style::ParagraphAdjust_CENTER },
{ XML_JUSTIFY, style::ParagraphAdjust_BLOCK },
{ XML_JUSTIFIED, style::ParagraphAdjust_BLOCK }, // obsolete
{ XML_TOKEN_INVALID, 0 }
};
SvXMLEnumMapEntry __READONLY_DATA pXML_Para_Align_Last_Enum[] =
{
{ XML_START, style::ParagraphAdjust_LEFT },
{ XML_CENTER, style::ParagraphAdjust_CENTER },
{ XML_JUSTIFY, style::ParagraphAdjust_BLOCK },
{ XML_JUSTIFIED, style::ParagraphAdjust_BLOCK }, // obsolete
{ XML_TOKEN_INVALID, 0 }
};
///////////////////////////////////////////////////////////////////////////////
//
// class XMLParaAdjustPropHdl
//
XMLParaAdjustPropHdl::~XMLParaAdjustPropHdl()
{
// nothing to do
}
sal_Bool XMLParaAdjustPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_uInt16 eAdjust;
if( ( bRet = rUnitConverter.convertEnum( eAdjust, rStrImpValue, pXML_Para_Adjust_Enum ) ) )
rValue <<= (sal_Int16)eAdjust;
return bRet;
}
sal_Bool XMLParaAdjustPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
if(!rValue.hasValue())
return sal_False; //added by BerryJia for fixing Bug102407 2002-11-5
OUStringBuffer aOut;
sal_Int16 nVal;
rValue >>= nVal;
sal_Bool bRet = rUnitConverter.convertEnum( aOut, nVal, pXML_Para_Adjust_Enum, XML_START );
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
///////////////////////////////////////////////////////////////////////////////
//
// class XMLLastLineAdjustPropHdl
//
XMLLastLineAdjustPropHdl::~XMLLastLineAdjustPropHdl()
{
// nothing to do
}
sal_Bool XMLLastLineAdjustPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_uInt16 eAdjust;
if( ( bRet = rUnitConverter.convertEnum( eAdjust, rStrImpValue, pXML_Para_Align_Last_Enum ) ) )
rValue <<= (sal_Int16)eAdjust;
return bRet;
}
sal_Bool XMLLastLineAdjustPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
OUStringBuffer aOut;
sal_Int16 nVal;
sal_Bool bRet = sal_False;
rValue >>= nVal;
if( nVal != style::ParagraphAdjust_LEFT )
bRet = rUnitConverter.convertEnum( aOut, nVal, pXML_Para_Align_Last_Enum, XML_START );
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
<|endoftext|>
|
<commit_before>/*
* =====================================================================================
*
* Filename: 3.cpp
*
* Description: Solution to the third problem of the `evens' section.
*
* Version: 1.0
* Created: 28.01.2015 6,00,07
* Revision: none
* Compiler: gcc
*
* Author: Radoslav Georgiev (sid), [email protected]
* Company: Faculty of Mathematics and Informatics at Sofia University
*
* =====================================================================================
*/
#include <iostream>
using namespace std;
const int MAX_SIZE = 1000;
const char diff = 'a' - 'A';
bool isWordChar(char c)
{
return c == '(' || c == ')' || c == '-' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
char* skipWhitespaceReverse(const char* s)
{
while (*s == ' ')
s--;
return s;
}
char* goToEnd(const char* s)
{
while (*s)
s++;
return s;
}
char toUpper(char c)
{
return c >= 'a' && c <= 'z' ? c - diff : c;
}
char toLower(char c)
{
return c >= 'A' && c <= 'Z' ? c + diff : c;
}
void swap(char* a, char* b)
{
char x = *a;
*a = *b;
*b = x;
}
// Ако изречението е невалидно, връщаме NULL
char* reverseSentence(const char* s)
{
if (!s)
return NULL;
char* end = goToEnd(s);
end--;
if (end < s || *end != '!' && *end != '.' && *end != '?')
return NULL;
end--;
char rev[MAX_SIZE];
char* beg = end;
bool is_first = true;
while (beg >= s)
{
while (beg >= s && isWordChar(*beg))
beg--;
if (beg == end)
return NULL;
beg++;
if (beg < s)
{
char first[2];
strncat(first, beg, 1);
*first = toLower(*first);
strcat(rev, first);
strncat(rev, beg + 1, end - beg);
}
else
{
strncat(rev, beg, end - beg + 1);
end = beg - 1;
if (*end != ' ')
return NULL;
end--;
if (end < s)
return NULL;
if (*end == ',' || *end == ':' || *end == ';')
strncat(rev, end, 1);
strncat(rev, end + 1, 1);
}
}
*rev = toUpper(*rev);
char *p = rev, *lp = NULL;
int b = 0;
while (p)
{
if (*p == '(')
{
b++;
if (lp && b == 0)
{
swap(p, lp);
lp = NULL;
}
}
else if (*p == ')')
{
b--;
if (b == -1)
lp = p;
}
p++;
}
cout << rev << endl;
return 0;
}
<commit_msg>added constness where necessary<commit_after>/*
* =====================================================================================
*
* Filename: 3.cpp
*
* Description: Solution to the third problem of the `evens' section.
*
* Version: 1.0
* Created: 28.01.2015 6,00,07
* Revision: none
* Compiler: gcc
*
* Author: Radoslav Georgiev (sid), [email protected]
* Company: Faculty of Mathematics and Informatics at Sofia University
*
* =====================================================================================
*/
#include <iostream>
using namespace std;
const int MAX_SIZE = 1000;
const char diff = 'a' - 'A';
bool isWordChar(char c)
{
return c == '(' || c == ')' || c == '-' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
const char* skipWhitespaceReverse(const char* s)
{
while (*s == ' ')
s--;
return s;
}
const char* goToEnd(const char* s)
{
while (*s)
s++;
return s;
}
char toUpper(char c)
{
return c >= 'a' && c <= 'z' ? c - diff : c;
}
char toLower(char c)
{
return c >= 'A' && c <= 'Z' ? c + diff : c;
}
void swap(char* a, char* b)
{
char x = *a;
*a = *b;
*b = x;
}
// Ако изречението е невалидно, връщаме NULL
char* reverseSentence(const char* s)
{
if (!s)
return NULL;
const char* end = goToEnd(s);
end--;
if (end < s || *end != '!' && *end != '.' && *end != '?')
return NULL;
end--;
const char* beg = end;
bool is_first = true;
while (beg >= s)
{
while (beg >= s && isWordChar(*beg))
beg--;
if (beg == end)
return NULL;
beg++;
if (beg < s)
{
char first[2];
strncat(first, beg, 1);
*first = toLower(*first);
strcat(rev, first);
strncat(rev, beg + 1, end - beg);
}
else
{
strncat(rev, beg, end - beg + 1);
end = beg - 1;
if (*end != ' ')
return NULL;
end--;
if (end < s)
return NULL;
if (*end == ',' || *end == ':' || *end == ';')
strncat(rev, end, 1);
strncat(rev, end + 1, 1);
}
}
*rev = toUpper(*rev);
char *p = rev, *lp = NULL;
int b = 0;
while (p)
{
if (*p == '(')
{
b++;
if (lp && b == 0)
{
swap(p, lp);
lp = NULL;
}
}
else if (*p == ')')
{
b--;
if (b == -1)
lp = p;
}
p++;
}
cout << rev << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: postuhdl.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 10:56:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_PROPERTYHANDLER_POSTURETYPES_HXX
#include <postuhdl.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTSLANT_HPP_
#include <com/sun/star/awt/FontSlant.hpp>
#endif
#ifndef _VCL_VCLENUM_HXX
#include <vcl/vclenum.hxx>
#endif
#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
SvXMLEnumMapEntry __READONLY_DATA aPostureGenericMapping[] =
{
{ XML_POSTURE_NORMAL, ITALIC_NONE },
{ XML_POSTURE_ITALIC, ITALIC_NORMAL },
{ XML_POSTURE_OBLIQUE, ITALIC_OBLIQUE },
{ XML_TOKEN_INVALID, 0 }
};
///////////////////////////////////////////////////////////////////////////////
//
// class XMLPosturePropHdl
//
XMLPosturePropHdl::~XMLPosturePropHdl()
{
// nothing to do
}
sal_Bool XMLPosturePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_uInt16 ePosture;
if( ( bRet = rUnitConverter.convertEnum( ePosture, rStrImpValue, aPostureGenericMapping ) ) )
rValue <<= (awt::FontSlant)ePosture;
return bRet;
}
sal_Bool XMLPosturePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
OUStringBuffer aOut;
awt::FontSlant eSlant;
if( !( rValue >>= eSlant ) )
{
sal_Int32 nValue;
if( !( rValue >>= nValue ) )
return sal_False;
eSlant = (awt::FontSlant)nValue;
}
if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_Int32)eSlant, aPostureGenericMapping ) ) )
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
<commit_msg>INTEGRATION: CWS sb59 (1.4.152); FILE MERGED 2006/08/09 12:53:57 sb 1.4.152.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: postuhdl.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-10-12 14:50:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_PROPERTYHANDLER_POSTURETYPES_HXX
#include <postuhdl.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTSLANT_HPP_
#include <com/sun/star/awt/FontSlant.hpp>
#endif
#ifndef _VCL_VCLENUM_HXX
#include <vcl/vclenum.hxx>
#endif
#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
SvXMLEnumMapEntry __READONLY_DATA aPostureGenericMapping[] =
{
{ XML_POSTURE_NORMAL, ITALIC_NONE },
{ XML_POSTURE_ITALIC, ITALIC_NORMAL },
{ XML_POSTURE_OBLIQUE, ITALIC_OBLIQUE },
{ XML_TOKEN_INVALID, 0 }
};
///////////////////////////////////////////////////////////////////////////////
//
// class XMLPosturePropHdl
//
XMLPosturePropHdl::~XMLPosturePropHdl()
{
// nothing to do
}
sal_Bool XMLPosturePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& ) const
{
sal_uInt16 ePosture;
sal_Bool bRet = SvXMLUnitConverter::convertEnum( ePosture, rStrImpValue, aPostureGenericMapping );
if( bRet )
rValue <<= (awt::FontSlant)ePosture;
return bRet;
}
sal_Bool XMLPosturePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& ) const
{
awt::FontSlant eSlant;
if( !( rValue >>= eSlant ) )
{
sal_Int32 nValue;
if( !( rValue >>= nValue ) )
return sal_False;
eSlant = (awt::FontSlant)nValue;
}
OUStringBuffer aOut;
sal_Bool bRet = SvXMLUnitConverter::convertEnum( aOut, (sal_Int32)eSlant, aPostureGenericMapping );
if( bRet )
rStrExpValue = aOut.makeStringAndClear();
return bRet;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "xwalk/application/browser/application_process_manager.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "net/base/net_util.h"
using content::WebContents;
using xwalk::Runtime;
using xwalk::RuntimeContext;
namespace xwalk_application {
ApplicationProcessManager::ApplicationProcessManager(
RuntimeContext* runtime_context)
: weak_ptr_factory_(this) {
}
ApplicationProcessManager::~ApplicationProcessManager() {
}
void ApplicationProcessManager::LaunchApplication(
RuntimeContext* runtime_context,
const Application* application) {
std::string entry_page;
application->manifest()->GetString(
application_manifest_keys::kLaunchLocalPath,
&entry_page);
if (entry_page.empty()) {
// TODO(Xinchao): when there's no start page in manifest.json, please add a
// default one.
}
GURL startup_url = net::FilePathToFileURL(
application->path().Append(entry_page));
Runtime::Create(runtime_context, startup_url);
}
} // namespace xwalk_application
<commit_msg>Removed redundant newline.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "xwalk/application/browser/application_process_manager.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "net/base/net_util.h"
using content::WebContents;
using xwalk::Runtime;
using xwalk::RuntimeContext;
namespace xwalk_application {
ApplicationProcessManager::ApplicationProcessManager(
RuntimeContext* runtime_context)
: weak_ptr_factory_(this) {
}
ApplicationProcessManager::~ApplicationProcessManager() {
}
void ApplicationProcessManager::LaunchApplication(
RuntimeContext* runtime_context,
const Application* application) {
std::string entry_page;
application->manifest()->GetString(
application_manifest_keys::kLaunchLocalPath,
&entry_page);
if (entry_page.empty()) {
// TODO(Xinchao): when there's no start page in manifest.json, please add a
// default one.
}
GURL startup_url = net::FilePathToFileURL(
application->path().Append(entry_page));
Runtime::Create(runtime_context, startup_url);
}
} // namespace xwalk_application
<|endoftext|>
|
<commit_before>#include "test/test_syscoin_services.h"
#include "data/utxo.json.h"
#include "utiltime.h"
#include "rpcserver.h"
#include <boost/test/unit_test.hpp>
#include <univalue.h>
int currentTx = 0;
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
std::string address;
std::string amount;
};
void VerifySnapShot()
{
}
void SendSnapShotPayment(const std::string &strSend)
{
currentTx++;
std::string strSendMany = "sendmany \"\" {" + strSend + "}";
UniValue r;
BOOST_CHECK_THROW(r = CallRPC("mainnet1", strSendMany, false), runtime_error);
}
void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts)
{
// generate snapshot payments and let it mature
printf("Generating 101 blocks to start the mainnet\n");
GenerateMainNetBlocks(101, "mainnet1");
int numberOfTxPerBlock = 250;
double nTotal =0;
std::string sendManyString = "";
for(int i =0;i<paymentAmounts.size();i++)
{
if(sendManyString != "")
sendManyString += ",";
sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount;
nTotal += atof(paymentAmounts[i].amount.c_str());
if(i != 0 && (i%numberOfTxPerBlock) == 0)
{
printf("strSendMany #%d, total %f\n", currentTx, nTotal);
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
sendManyString = "";
nTotal = 0;
}
}
if(sendManyString != "")
{
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
}
}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
PaymentAmount payment;
payment.address = test[0].get_str();
try
{
CAmount amountInSys1 = AmountFromValue(test[1]);
payment.amount = ValueFromAmount(amountInSys1).write();
paymentAmounts.push_back(payment);
}
catch(...)
{
continue;
}
}
}
bool IsMainNetAlreadyCreated()
{
int height;
UniValue r;
BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo", false));
height = find_value(r.get_obj(), "blocks").get_int();
return height > 0;
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
std::vector<PaymentAmount> paymentAmounts;
GetUTXOs(paymentAmounts);
if(IsMainNetAlreadyCreated())
{
VerifySnapShot();
}
else
{
GenerateSnapShot(paymentAmounts);
VerifySnapShot();
}
}
BOOST_AUTO_TEST_SUITE_END ()<commit_msg>detect bad amount<commit_after>#include "test/test_syscoin_services.h"
#include "data/utxo.json.h"
#include "utiltime.h"
#include "rpcserver.h"
#include <boost/test/unit_test.hpp>
#include <univalue.h>
int currentTx = 0;
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
std::string address;
std::string amount;
};
void VerifySnapShot()
{
}
void SendSnapShotPayment(const std::string &strSend)
{
currentTx++;
std::string strSendMany = "sendmany \"\" {" + strSend + "}";
UniValue r;
BOOST_CHECK_THROW(r = CallRPC("mainnet1", strSendMany, false), runtime_error);
}
void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts)
{
// generate snapshot payments and let it mature
printf("Generating 101 blocks to start the mainnet\n");
GenerateMainNetBlocks(101, "mainnet1");
int numberOfTxPerBlock = 250;
double nTotal =0;
std::string sendManyString = "";
for(int i =0;i<paymentAmounts.size();i++)
{
if(sendManyString != "")
sendManyString += ",";
sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount;
nTotal += atof(paymentAmounts[i].amount.c_str());
if(i != 0 && (i%numberOfTxPerBlock) == 0)
{
printf("strSendMany #%d, total %f\n", currentTx, nTotal);
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
sendManyString = "";
nTotal = 0;
}
}
if(sendManyString != "")
{
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
}
}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
PaymentAmount payment;
payment.address = test[0].get_str();
try
{
CAmount amountInSys1 = AmountFromValue(test[1]);
payment.amount = ValueFromAmount(amountInSys1).write();
paymentAmounts.push_back(payment);
}
catch(...)
{
BOOST_ERROR("Invalid amount: " << payment.amount);
continue;
}
}
}
bool IsMainNetAlreadyCreated()
{
int height;
UniValue r;
BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo", false));
height = find_value(r.get_obj(), "blocks").get_int();
return height > 0;
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
std::vector<PaymentAmount> paymentAmounts;
GetUTXOs(paymentAmounts);
if(IsMainNetAlreadyCreated())
{
VerifySnapShot();
}
else
{
GenerateSnapShot(paymentAmounts);
VerifySnapShot();
}
}
BOOST_AUTO_TEST_SUITE_END ()<|endoftext|>
|
<commit_before>#include "test/test_syscoin_services.h"
#include "data/utxo.json.h"
#include "utiltime.h"
#include "rpcserver.h"
#include <boost/test/unit_test.hpp>
#include <univalue.h>
int currentTx = 0;
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
std::string address;
std::string amount;
};
void VerifySnapShot()
{
}
void SendSnapShotPayment(const std::string &strSend)
{
currentTx++;
std::string strSendMany = "sendmany \"\" {" + strSend + "}";
UniValue r;
BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", strSendMany, false));
}
void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts)
{
// generate snapshot payments and let it mature
printf("Generating 100 blocks to start the mainnet\n");
GenerateMainNetBlocks(100, "mainnet1");
int numberOfTxPerBlock = 1000;
double nTotal =0;
std::string sendManyString = "";
for(int i =0;i<paymentAmounts.size();i++)
{
if(sendManyString != "")
sendManyString += ",";
sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount;
nTotal += atof(paymentAmounts[i].amount);
if(i != 0 && (i%numberOfTxPerBlock) == 0)
{
printf("strSendMany #%d, total %f\n", currentTx, nTotal);
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
sendManyString = "";
}
}
if(sendManyString != "")
{
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
}
}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
PaymentAmount payment;
payment.address = test[0].get_str();
CAmount amount = test[1].get_int64() / 299.4f;
payment.amount = ValueFromAmount(amount).write();
paymentAmounts.push_back(payment);
}
}
bool IsMainNetAlreadyCreated()
{
int height;
UniValue r;
BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo", false));
height = find_value(r.get_obj(), "blocks").get_int();
return height > 0;
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
std::vector<PaymentAmount> paymentAmounts;
GetUTXOs(paymentAmounts);
if(IsMainNetAlreadyCreated())
{
VerifySnapShot();
}
else
{
GenerateSnapShot(paymentAmounts);
VerifySnapShot();
}
}
BOOST_AUTO_TEST_SUITE_END ()<commit_msg>fix atof<commit_after>#include "test/test_syscoin_services.h"
#include "data/utxo.json.h"
#include "utiltime.h"
#include "rpcserver.h"
#include <boost/test/unit_test.hpp>
#include <univalue.h>
int currentTx = 0;
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE (syscoin_snapshot_tests, SyscoinMainNetSetup)
struct PaymentAmount
{
std::string address;
std::string amount;
};
void VerifySnapShot()
{
}
void SendSnapShotPayment(const std::string &strSend)
{
currentTx++;
std::string strSendMany = "sendmany \"\" {" + strSend + "}";
UniValue r;
BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", strSendMany, false));
}
void GenerateSnapShot(const std::vector<PaymentAmount> &paymentAmounts)
{
// generate snapshot payments and let it mature
printf("Generating 100 blocks to start the mainnet\n");
GenerateMainNetBlocks(100, "mainnet1");
int numberOfTxPerBlock = 1000;
double nTotal =0;
std::string sendManyString = "";
for(int i =0;i<paymentAmounts.size();i++)
{
if(sendManyString != "")
sendManyString += ",";
sendManyString += "\\\"" + paymentAmounts[i].address + "\\\":" + paymentAmounts[i].amount;
nTotal += atof(paymentAmounts[i].amount.c_str());
if(i != 0 && (i%numberOfTxPerBlock) == 0)
{
printf("strSendMany #%d, total %f\n", currentTx, nTotal);
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
sendManyString = "";
}
}
if(sendManyString != "")
{
SendSnapShotPayment(sendManyString);
GenerateMainNetBlocks(1, "mainnet1");
}
}
void GetUTXOs(std::vector<PaymentAmount> &paymentAmounts)
{
UniValue tests = read_json(std::string(json_tests::utxo, json_tests::utxo + sizeof(json_tests::utxo)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
PaymentAmount payment;
payment.address = test[0].get_str();
CAmount amount = test[1].get_int64() / 299.4f;
payment.amount = ValueFromAmount(amount).write();
paymentAmounts.push_back(payment);
}
}
bool IsMainNetAlreadyCreated()
{
int height;
UniValue r;
BOOST_CHECK_NO_THROW(r = CallRPC("mainnet1", "getinfo", false));
height = find_value(r.get_obj(), "blocks").get_int();
return height > 0;
}
BOOST_AUTO_TEST_CASE (generate_and_verify_snapshot)
{
std::vector<PaymentAmount> paymentAmounts;
GetUTXOs(paymentAmounts);
if(IsMainNetAlreadyCreated())
{
VerifySnapShot();
}
else
{
GenerateSnapShot(paymentAmounts);
VerifySnapShot();
}
}
BOOST_AUTO_TEST_SUITE_END ()<|endoftext|>
|
<commit_before>#include "SynchroProducer.h"
#include <node-manager/SuperNodeManager.h>
#include <node-manager/NodeManagerBase.h>
#include <net/distribute/DataTransfer2.hpp>
#include <boost/thread.hpp>
#include <glog/logging.h>
#include <sstream>
#include <unistd.h> // sleep
using namespace sf1r;
#define SYNCHRO_PRODUCER "[" << syncZkNode_ << "]"
SynchroProducer::SynchroProducer(
boost::shared_ptr<ZooKeeper>& zookeeper,
const std::string& syncZkNode,
DataTransferPolicy transferPolicy)
: transferPolicy_(transferPolicy)
, zookeeper_(zookeeper)
, syncZkNode_(syncZkNode)
, isSynchronizing_(false)
{
if (zookeeper_)
zookeeper_->registerEventHandler(this);
producerZkNode_ = syncZkNode_ + SynchroZkNode::PRODUCER;
init();
}
SynchroProducer::~SynchroProducer()
{
zookeeper_->deleteZNode(syncZkNode_, true);
}
/**
* Synchronizing steps for Producer:
* (1) doProduce()
* Producer ---notify--> ZooKeeper -----> Consumer(s)
* (2) watchConsumers():
* Producer <--watch--- ZooKeeper <----- Consumer
* Producer -----transfer data----> Consumer
* Producer ---notify--> ZooKeeper -----> Consumer
* (3) checkConsumers()
* Producer <--watch--- ZooKeeper <----- Consumer
*/
bool SynchroProducer::produce(SynchroData& syncData, callback_on_consumed_t callback_on_consumed)
{
boost::lock_guard<boost::mutex> lock(produce_mutex_);
// start synchronizing
if (isSynchronizing_)
{
LOG(ERROR) << SYNCHRO_PRODUCER << " is synchronizing!";
return false;
}
else
{
isSynchronizing_ = true;
syncData.setValue(SynchroData::KEY_HOST, SuperNodeManager::get()->getLocalHostIP());
syncData_ = syncData;
init();
}
// produce
if (doProduce(syncData))
{
if (callback_on_consumed != NULL)
callback_on_consumed_ = callback_on_consumed;
watchConsumers(); // wait consumer(s)
checkConsumers(); // check consuming status
return true;
}
else
{
endSynchroning("synchronize error or timeout!");
return false;
}
}
bool SynchroProducer::wait(int timeout)
{
if (!isSynchronizing_)
{
LOG(INFO) << SYNCHRO_PRODUCER << " wait not synchronizing, call produce() first.";
return false;
}
// wait consumer(s) to consume produced data
int step = 1;
int waited = 0;
LOG(INFO) << SYNCHRO_PRODUCER << " waiting for consumer (timeout: " << timeout << ")";
// in order to fix the bug https://ssl.izenesoft.cn/bug/show_bug.cgi?id=88,
// in below while loops, ::sleep() is called instead of
// boost::this_thread::sleep(), that's because on some platforms, it's
// found that boost::this_thread::sleep() returns immediately.
// reference: https://svn.boost.org/trac/boost/ticket/5034
while (!watchedConsumer_)
{
LOG(INFO) << SYNCHRO_PRODUCER << " sleeping for " << step << " seconds ...";
//boost::this_thread::sleep(boost::posix_time::seconds(step));
::sleep(step);
waited += step;
if (waited >= timeout)
{
endSynchroning("timeout: no consumer!");
return false;
}
}
// wait synchronizing to finish
while (isSynchronizing_ && zookeeper_->isConnected())
{
LOG(INFO) << SYNCHRO_PRODUCER << " is synchronizing, finished - total :" <<
consumedCount_ << " - " << consumersMap_.size() << ",sleeping for 1 second ...";
//boost::this_thread::sleep(boost::posix_time::seconds(1));
::sleep(1);
}
return result_on_consumed_;
}
/* virtual */
void SynchroProducer::process(ZooKeeperEvent& zkEvent)
{
boost::lock_guard<boost::mutex> lock(produce_mutex_);
DLOG(INFO) << SYNCHRO_PRODUCER << "process event: "<< zkEvent.toString();
if (zkEvent.type_ == ZOO_SESSION_EVENT && zkEvent.state_ == ZOO_EXPIRED_SESSION_STATE)
{
LOG(WARNING) << "SynchroProducer node disconnected by zookeeper, state : " << zookeeper_->getStateString();
zookeeper_->disconnect();
zookeeper_->connect(true);
}
}
void SynchroProducer::onNodeDeleted(const std::string& path)
{
if (consumersMap_.find(path) != consumersMap_.end())
{
LOG(INFO) << SYNCHRO_PRODUCER << " on node deleted: " << path;
// check if consumer broken down
checkConsumers();
}
}
void SynchroProducer::onDataChanged(const std::string& path)
{
if (consumersMap_.find(path) != consumersMap_.end())
{
LOG(INFO) << SYNCHRO_PRODUCER << " on data changed: " << path;
// check if consumer finished
checkConsumers();
}
}
void SynchroProducer::onChildrenChanged(const std::string& path)
{
if (path == syncZkNode_)
{
LOG(INFO) << SYNCHRO_PRODUCER << " on children changed: " << path;
// whether new consumer comes, or consumer break down.
watchConsumers();
checkConsumers();
}
}
/// private
bool SynchroProducer::doProduce(SynchroData& syncData)
{
bool produced = false;
if (zookeeper_->isConnected())
{
// ensure synchro node
zookeeper_->createZNode(syncZkNode_);
// create producer node (ephemeral)
if (!zookeeper_->createZNode(producerZkNode_, syncData.serialize(), ZooKeeper::ZNODE_EPHEMERAL))
{
if (zookeeper_->getErrorCode() == ZooKeeper::ZERR_ZNODEEXISTS)
{
zookeeper_->setZNodeData(producerZkNode_, syncData.serialize());
LOG(WARNING) << SYNCHRO_PRODUCER << " overwrite " << producerZkNode_;
produced = true;
}
LOG(INFO) << SYNCHRO_PRODUCER << " failed to create " << producerZkNode_
<< " (" << zookeeper_->getErrorString() << ")";
// wait ZooKeeperManager to init
LOG(INFO) << SYNCHRO_PRODUCER << " waiting for znode initialization";
sleep(10);
}
else
{
LOG(INFO) << SYNCHRO_PRODUCER << " created " << producerZkNode_;
produced = true;
}
}
if (!produced)
{
int retryCnt = 0;
while (!zookeeper_->isConnected())
{
LOG(INFO) << SYNCHRO_PRODUCER << " connecting to ZooKeeper ("
<< zookeeper_->getHosts() << ")";
zookeeper_->connect(true);
if ((retryCnt++) > 10)
break;
}
if (!zookeeper_->isConnected())
{
LOG(INFO) << SYNCHRO_PRODUCER << " connect to ZooKeeper timeout!";
}
else
{
produced = doProduce(syncData);
}
}
return produced;
}
void SynchroProducer::watchConsumers()
{
std::vector<std::string> new_added_consume;
{
boost::unique_lock<boost::mutex> lock(consumers_mutex_);
if (!isSynchronizing_)
return;
LOG(INFO) << SYNCHRO_PRODUCER << " watching for consumers";
// [Synchro Node]
// |--- Producer
// |--- Consumer00000000
// |--- Consumer0000000x
//
std::vector<std::string> childrenList;
zookeeper_->getZNodeChildren(syncZkNode_, childrenList, ZooKeeper::WATCH);
// If watched any consumer
if (childrenList.size() > 1)
{
LOG(INFO) << SYNCHRO_PRODUCER << " found (" << childrenList.size() << ") children";
if (!watchedConsumer_)
watchedConsumer_ = true;
for (size_t i = 0; i < childrenList.size(); i++)
{
// Produer is also a child and shoud be excluded.
if (producerZkNode_ != childrenList[i] &&
consumersMap_.find(childrenList[i]) == consumersMap_.end())
{
consumersMap_[childrenList[i]] = std::make_pair(false, false);
new_added_consume.push_back(childrenList[i]);
LOG(INFO) << SYNCHRO_PRODUCER << " watched a new consumer: " << childrenList[i];
}
}
}
}
// transfer data
for (size_t i = 0; i < new_added_consume.size(); i++)
{
if (!transferData(new_added_consume[i]))
{
// xxx set failed status
LOG(WARNING) << SYNCHRO_PRODUCER << " set failed status";
}
}
}
bool SynchroProducer::transferData(const std::string& consumerZnodePath)
{
std::string data;
if (!zookeeper_->getZNodeData(consumerZnodePath, data))
{
LOG(ERROR) << "get consumer node data failed while transfer data : " << consumerZnodePath;
return false;
}
// consumer info
SynchroData consumerInfo;
consumerInfo.loadKvString(data);
std::string consumerHost = consumerInfo.getStrValue(SynchroData::KEY_HOST);
std::string consumerCollection = consumerInfo.getStrValue(SynchroData::KEY_COLLECTION);
// produced info
std::string dataPath = syncData_.getStrValue(SynchroData::KEY_DATA_PATH);
std::string dataType = syncData_.getStrValue(SynchroData::KEY_DATA_TYPE);
bool ret = true;
// to local host
if (consumerHost == SuperNodeManager::get()->getLocalHostIP())
{
LOG(INFO) << SYNCHRO_PRODUCER << " consumerHost: " << consumerHost << " is on localhost";
ret = true;
}
// to remote host
else
{
if (transferPolicy_ == DATA_TRANSFER_POLICY_DFS)
{
// xxx
ret = true;
}
else if (transferPolicy_ == DATA_TRANSFER_POLICY_SOCKET)
{
uint32_t consumerPort = consumerInfo.getUInt32Value(SynchroData::KEY_DATA_PORT);
std::string recvDir;
if (dataType == SynchroData::DATA_TYPE_SCD_INDEX)
{
if (NodeManagerBase::get()->isDistributed())
{
recvDir = consumerCollection+"/scd/master_index";
}
else
{
recvDir = consumerCollection+"/scd/index";
}
}
else if (dataType == SynchroData::COMMENT_TYPE_FLAG)
{
recvDir = consumerCollection+"/scd/summarization";
}
else
{
//xx extend;
}
LOG(INFO) << SYNCHRO_PRODUCER << " transfer data " << dataPath
<< " to " << consumerHost << ":" <<consumerPort;
izenelib::net::distribute::DataTransfer2 transfer(consumerHost, consumerPort);
if (not transfer.syncSend(dataPath, recvDir, false))
{
ret = false;
}
}
}
// notify consumer after transferred
const char* status;
if (ret) {
status = SynchroData::CONSUMER_STATUS_RECEIVE_SUCCESS;
} else {
status = SynchroData::CONSUMER_STATUS_RECEIVE_FAILURE;
}
LOG(INFO) << SYNCHRO_PRODUCER << " setting consumer status to " << status;
consumerInfo.setValue(SynchroData::KEY_CONSUMER_STATUS, status);
zookeeper_->setZNodeData(consumerZnodePath, consumerInfo.serialize());
return ret;
}
void SynchroProducer::checkConsumers()
{
LOG(INFO) << SYNCHRO_PRODUCER << " checking consumers";
boost::unique_lock<boost::mutex> lock(consumers_mutex_);
if (!isSynchronizing_)
return;
LOG(INFO) << SYNCHRO_PRODUCER << " consumers map size: " << consumersMap_.size();
consumermap_t::iterator it;
for (it = consumersMap_.begin(); it != consumersMap_.end(); it++)
{
if (it->second.first == true)
{ // have got result
continue;
}
const std::string& consumer = it->first;
DLOG(INFO) << SYNCHRO_PRODUCER << " checking consumer " << consumer;
std::string sdata;
if (zookeeper_->getZNodeData(consumer, sdata, ZooKeeper::WATCH))
{
DLOG(INFO) << SYNCHRO_PRODUCER << " data: " << sdata;
SynchroData syncData;
syncData.loadKvString(sdata);
std::string syncRet = syncData.getStrValue(SynchroData::KEY_RETURN);
if (syncRet == "success")
{
it->second.first = true; // got consumer result
it->second.second = true; // result is true
}
else if (syncRet == "failure")
{
it->second.first = true; // got consumer result
it->second.second = false; // result is false
}
else
continue;
LOG(INFO) << SYNCHRO_PRODUCER << " " << syncRet << " on consumer " << consumer;
consumedCount_ ++; // how many consumers have finished
zookeeper_->deleteZNode(consumer); // delete node after have got result.
LOG(INFO) << SYNCHRO_PRODUCER << " deleted node " << consumer;
}
else
{
if (!zookeeper_->isZNodeExists(consumer))
{
it->second.first = true;
it->second.second = false;
consumedCount_ ++;
LOG(WARNING) << SYNCHRO_PRODUCER << " lost connection to " << consumer<< "!!";
}
}
}
if (consumedCount_ <= 0)
{
return;
}
else
{
LOG(INFO) << SYNCHRO_PRODUCER << " consumed by "<< consumedCount_
<< "/" << consumersMap_.size() << " consumers";
}
if (consumedCount_ >= consumersMap_.size())
{
result_on_consumed_ = true;
std::string info = "process succeeded";
consumermap_t::iterator it;
for (it = consumersMap_.begin(); it != consumersMap_.end(); it++)
{
// xxx, if one of the consumers failed
if (it->second.second == false)
{
result_on_consumed_ = false;
info = "process failed";
break;
}
}
if (callback_on_consumed_) {
DLOG(INFO) << SYNCHRO_PRODUCER << " calling completion callback";
callback_on_consumed_(result_on_consumed_);
}
// Synchronizing finished
endSynchroning(info);
}
}
void SynchroProducer::init()
{
watchedConsumer_ = false;
consumersMap_.clear();
consumedCount_ = 0;
callback_on_consumed_ = NULL;
result_on_consumed_ = false;
}
void SynchroProducer::endSynchroning(const std::string& info)
{
// Synchronizing finished
isSynchronizing_ = false;
zookeeper_->deleteZNode(syncZkNode_, true);
LOG(INFO) << SYNCHRO_PRODUCER << " synchronizing finished - "<< info;
}
<commit_msg>fix create synchro node<commit_after>#include "SynchroProducer.h"
#include <node-manager/SuperNodeManager.h>
#include <node-manager/NodeManagerBase.h>
#include <net/distribute/DataTransfer2.hpp>
#include <boost/thread.hpp>
#include <glog/logging.h>
#include <sstream>
#include <unistd.h> // sleep
using namespace sf1r;
#define SYNCHRO_PRODUCER "[" << syncZkNode_ << "]"
SynchroProducer::SynchroProducer(
boost::shared_ptr<ZooKeeper>& zookeeper,
const std::string& syncZkNode,
DataTransferPolicy transferPolicy)
: transferPolicy_(transferPolicy)
, zookeeper_(zookeeper)
, syncZkNode_(syncZkNode)
, isSynchronizing_(false)
{
if (zookeeper_)
zookeeper_->registerEventHandler(this);
producerZkNode_ = syncZkNode_ + SynchroZkNode::PRODUCER;
init();
}
SynchroProducer::~SynchroProducer()
{
zookeeper_->deleteZNode(syncZkNode_, true);
}
/**
* Synchronizing steps for Producer:
* (1) doProduce()
* Producer ---notify--> ZooKeeper -----> Consumer(s)
* (2) watchConsumers():
* Producer <--watch--- ZooKeeper <----- Consumer
* Producer -----transfer data----> Consumer
* Producer ---notify--> ZooKeeper -----> Consumer
* (3) checkConsumers()
* Producer <--watch--- ZooKeeper <----- Consumer
*/
bool SynchroProducer::produce(SynchroData& syncData, callback_on_consumed_t callback_on_consumed)
{
boost::lock_guard<boost::mutex> lock(produce_mutex_);
// start synchronizing
if (isSynchronizing_)
{
LOG(ERROR) << SYNCHRO_PRODUCER << " is synchronizing!";
return false;
}
else
{
isSynchronizing_ = true;
syncData.setValue(SynchroData::KEY_HOST, SuperNodeManager::get()->getLocalHostIP());
syncData_ = syncData;
init();
}
// produce
if (doProduce(syncData))
{
if (callback_on_consumed != NULL)
callback_on_consumed_ = callback_on_consumed;
watchConsumers(); // wait consumer(s)
checkConsumers(); // check consuming status
return true;
}
else
{
endSynchroning("synchronize error or timeout!");
return false;
}
}
bool SynchroProducer::wait(int timeout)
{
if (!isSynchronizing_)
{
LOG(INFO) << SYNCHRO_PRODUCER << " wait not synchronizing, call produce() first.";
return false;
}
// wait consumer(s) to consume produced data
int step = 1;
int waited = 0;
LOG(INFO) << SYNCHRO_PRODUCER << " waiting for consumer (timeout: " << timeout << ")";
// in order to fix the bug https://ssl.izenesoft.cn/bug/show_bug.cgi?id=88,
// in below while loops, ::sleep() is called instead of
// boost::this_thread::sleep(), that's because on some platforms, it's
// found that boost::this_thread::sleep() returns immediately.
// reference: https://svn.boost.org/trac/boost/ticket/5034
while (!watchedConsumer_)
{
LOG(INFO) << SYNCHRO_PRODUCER << " sleeping for " << step << " seconds ...";
//boost::this_thread::sleep(boost::posix_time::seconds(step));
::sleep(step);
waited += step;
if (waited >= timeout)
{
endSynchroning("timeout: no consumer!");
return false;
}
}
// wait synchronizing to finish
while (isSynchronizing_ && zookeeper_->isConnected())
{
LOG(INFO) << SYNCHRO_PRODUCER << " is synchronizing, finished - total :" <<
consumedCount_ << " - " << consumersMap_.size() << ",sleeping for 1 second ...";
//boost::this_thread::sleep(boost::posix_time::seconds(1));
::sleep(1);
}
return result_on_consumed_;
}
/* virtual */
void SynchroProducer::process(ZooKeeperEvent& zkEvent)
{
boost::lock_guard<boost::mutex> lock(produce_mutex_);
DLOG(INFO) << SYNCHRO_PRODUCER << "process event: "<< zkEvent.toString();
if (zkEvent.type_ == ZOO_SESSION_EVENT && zkEvent.state_ == ZOO_EXPIRED_SESSION_STATE)
{
LOG(WARNING) << "SynchroProducer node disconnected by zookeeper, state : " << zookeeper_->getStateString();
zookeeper_->disconnect();
zookeeper_->connect(true);
}
}
void SynchroProducer::onNodeDeleted(const std::string& path)
{
if (consumersMap_.find(path) != consumersMap_.end())
{
LOG(INFO) << SYNCHRO_PRODUCER << " on node deleted: " << path;
// check if consumer broken down
checkConsumers();
}
}
void SynchroProducer::onDataChanged(const std::string& path)
{
if (consumersMap_.find(path) != consumersMap_.end())
{
LOG(INFO) << SYNCHRO_PRODUCER << " on data changed: " << path;
// check if consumer finished
checkConsumers();
}
}
void SynchroProducer::onChildrenChanged(const std::string& path)
{
if (path == syncZkNode_)
{
LOG(INFO) << SYNCHRO_PRODUCER << " on children changed: " << path;
// whether new consumer comes, or consumer break down.
watchConsumers();
checkConsumers();
}
}
/// private
bool SynchroProducer::doProduce(SynchroData& syncData)
{
bool produced = false;
if (zookeeper_->isConnected())
{
// ensure synchro node
zookeeper_->createZNode(ZooKeeperNamespace::getSynchroPath());
zookeeper_->createZNode(syncZkNode_);
// create producer node (ephemeral)
if (!zookeeper_->createZNode(producerZkNode_, syncData.serialize(), ZooKeeper::ZNODE_EPHEMERAL))
{
if (zookeeper_->getErrorCode() == ZooKeeper::ZERR_ZNODEEXISTS)
{
zookeeper_->setZNodeData(producerZkNode_, syncData.serialize());
LOG(WARNING) << SYNCHRO_PRODUCER << " overwrite " << producerZkNode_;
produced = true;
}
LOG(INFO) << SYNCHRO_PRODUCER << " failed to create " << producerZkNode_
<< " (" << zookeeper_->getErrorString() << ")";
// wait ZooKeeperManager to init
LOG(INFO) << SYNCHRO_PRODUCER << " waiting for znode initialization";
sleep(10);
}
else
{
LOG(INFO) << SYNCHRO_PRODUCER << " created " << producerZkNode_;
produced = true;
}
}
if (!produced)
{
int retryCnt = 0;
while (!zookeeper_->isConnected())
{
LOG(INFO) << SYNCHRO_PRODUCER << " connecting to ZooKeeper ("
<< zookeeper_->getHosts() << ")";
zookeeper_->connect(true);
if ((retryCnt++) > 10)
break;
}
if (!zookeeper_->isConnected())
{
LOG(INFO) << SYNCHRO_PRODUCER << " connect to ZooKeeper timeout!";
}
else
{
produced = doProduce(syncData);
}
}
return produced;
}
void SynchroProducer::watchConsumers()
{
std::vector<std::string> new_added_consume;
{
boost::unique_lock<boost::mutex> lock(consumers_mutex_);
if (!isSynchronizing_)
return;
LOG(INFO) << SYNCHRO_PRODUCER << " watching for consumers";
// [Synchro Node]
// |--- Producer
// |--- Consumer00000000
// |--- Consumer0000000x
//
std::vector<std::string> childrenList;
zookeeper_->getZNodeChildren(syncZkNode_, childrenList, ZooKeeper::WATCH);
// If watched any consumer
if (childrenList.size() > 1)
{
LOG(INFO) << SYNCHRO_PRODUCER << " found (" << childrenList.size() << ") children";
if (!watchedConsumer_)
watchedConsumer_ = true;
for (size_t i = 0; i < childrenList.size(); i++)
{
// Produer is also a child and shoud be excluded.
if (producerZkNode_ != childrenList[i] &&
consumersMap_.find(childrenList[i]) == consumersMap_.end())
{
consumersMap_[childrenList[i]] = std::make_pair(false, false);
new_added_consume.push_back(childrenList[i]);
LOG(INFO) << SYNCHRO_PRODUCER << " watched a new consumer: " << childrenList[i];
}
}
}
}
// transfer data
for (size_t i = 0; i < new_added_consume.size(); i++)
{
if (!transferData(new_added_consume[i]))
{
// xxx set failed status
LOG(WARNING) << SYNCHRO_PRODUCER << " set failed status";
}
}
}
bool SynchroProducer::transferData(const std::string& consumerZnodePath)
{
std::string data;
if (!zookeeper_->getZNodeData(consumerZnodePath, data))
{
LOG(ERROR) << "get consumer node data failed while transfer data : " << consumerZnodePath;
return false;
}
// consumer info
SynchroData consumerInfo;
consumerInfo.loadKvString(data);
std::string consumerHost = consumerInfo.getStrValue(SynchroData::KEY_HOST);
std::string consumerCollection = consumerInfo.getStrValue(SynchroData::KEY_COLLECTION);
// produced info
std::string dataPath = syncData_.getStrValue(SynchroData::KEY_DATA_PATH);
std::string dataType = syncData_.getStrValue(SynchroData::KEY_DATA_TYPE);
bool ret = true;
// to local host
if (consumerHost == SuperNodeManager::get()->getLocalHostIP())
{
LOG(INFO) << SYNCHRO_PRODUCER << " consumerHost: " << consumerHost << " is on localhost";
ret = true;
}
// to remote host
else
{
if (transferPolicy_ == DATA_TRANSFER_POLICY_DFS)
{
// xxx
ret = true;
}
else if (transferPolicy_ == DATA_TRANSFER_POLICY_SOCKET)
{
uint32_t consumerPort = consumerInfo.getUInt32Value(SynchroData::KEY_DATA_PORT);
std::string recvDir;
if (dataType == SynchroData::DATA_TYPE_SCD_INDEX)
{
if (NodeManagerBase::get()->isDistributed())
{
recvDir = consumerCollection+"/scd/master_index";
}
else
{
recvDir = consumerCollection+"/scd/index";
}
}
else if (dataType == SynchroData::COMMENT_TYPE_FLAG)
{
recvDir = consumerCollection+"/scd/summarization";
}
else
{
//xx extend;
}
LOG(INFO) << SYNCHRO_PRODUCER << " transfer data " << dataPath
<< " to " << consumerHost << ":" <<consumerPort;
izenelib::net::distribute::DataTransfer2 transfer(consumerHost, consumerPort);
if (not transfer.syncSend(dataPath, recvDir, false))
{
ret = false;
}
}
}
// notify consumer after transferred
const char* status;
if (ret) {
status = SynchroData::CONSUMER_STATUS_RECEIVE_SUCCESS;
} else {
status = SynchroData::CONSUMER_STATUS_RECEIVE_FAILURE;
}
LOG(INFO) << SYNCHRO_PRODUCER << " setting consumer status to " << status;
consumerInfo.setValue(SynchroData::KEY_CONSUMER_STATUS, status);
zookeeper_->setZNodeData(consumerZnodePath, consumerInfo.serialize());
return ret;
}
void SynchroProducer::checkConsumers()
{
LOG(INFO) << SYNCHRO_PRODUCER << " checking consumers";
boost::unique_lock<boost::mutex> lock(consumers_mutex_);
if (!isSynchronizing_)
return;
LOG(INFO) << SYNCHRO_PRODUCER << " consumers map size: " << consumersMap_.size();
consumermap_t::iterator it;
for (it = consumersMap_.begin(); it != consumersMap_.end(); it++)
{
if (it->second.first == true)
{ // have got result
continue;
}
const std::string& consumer = it->first;
DLOG(INFO) << SYNCHRO_PRODUCER << " checking consumer " << consumer;
std::string sdata;
if (zookeeper_->getZNodeData(consumer, sdata, ZooKeeper::WATCH))
{
DLOG(INFO) << SYNCHRO_PRODUCER << " data: " << sdata;
SynchroData syncData;
syncData.loadKvString(sdata);
std::string syncRet = syncData.getStrValue(SynchroData::KEY_RETURN);
if (syncRet == "success")
{
it->second.first = true; // got consumer result
it->second.second = true; // result is true
}
else if (syncRet == "failure")
{
it->second.first = true; // got consumer result
it->second.second = false; // result is false
}
else
continue;
LOG(INFO) << SYNCHRO_PRODUCER << " " << syncRet << " on consumer " << consumer;
consumedCount_ ++; // how many consumers have finished
zookeeper_->deleteZNode(consumer); // delete node after have got result.
LOG(INFO) << SYNCHRO_PRODUCER << " deleted node " << consumer;
}
else
{
if (!zookeeper_->isZNodeExists(consumer))
{
it->second.first = true;
it->second.second = false;
consumedCount_ ++;
LOG(WARNING) << SYNCHRO_PRODUCER << " lost connection to " << consumer<< "!!";
}
}
}
if (consumedCount_ <= 0)
{
return;
}
else
{
LOG(INFO) << SYNCHRO_PRODUCER << " consumed by "<< consumedCount_
<< "/" << consumersMap_.size() << " consumers";
}
if (consumedCount_ >= consumersMap_.size())
{
result_on_consumed_ = true;
std::string info = "process succeeded";
consumermap_t::iterator it;
for (it = consumersMap_.begin(); it != consumersMap_.end(); it++)
{
// xxx, if one of the consumers failed
if (it->second.second == false)
{
result_on_consumed_ = false;
info = "process failed";
break;
}
}
if (callback_on_consumed_) {
DLOG(INFO) << SYNCHRO_PRODUCER << " calling completion callback";
callback_on_consumed_(result_on_consumed_);
}
// Synchronizing finished
endSynchroning(info);
}
}
void SynchroProducer::init()
{
watchedConsumer_ = false;
consumersMap_.clear();
consumedCount_ = 0;
callback_on_consumed_ = NULL;
result_on_consumed_ = false;
}
void SynchroProducer::endSynchroning(const std::string& info)
{
// Synchronizing finished
isSynchronizing_ = false;
zookeeper_->deleteZNode(syncZkNode_, true);
LOG(INFO) << SYNCHRO_PRODUCER << " synchronizing finished - "<< info;
}
<|endoftext|>
|
<commit_before>/*!
@file
@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_ALGORITHMS_COUNT_HPP
#define BOOST_BRIGAND_ALGORITHMS_COUNT_HPP
#if __cplusplus >= 201402L
#include <array>
#endif
#include <brigand/config.hpp>
#include <brigand/functions/lambda.hpp>
#include <brigand/types/integer.hpp>
#include <brigand/types/integral_constant.hpp>
namespace brigand
{
namespace detail
{
#if defined(BRIGAND_COMP_GCC) || defined(BRIGAND_COMP_CLANG) // not MSVC
#if __cplusplus >= 201402L
// Clang chokes on the C++11 compatible version of count_bools when C++1z is enable and is fine
// with the std::array version in C++14
template <std::size_t length>
constexpr unsigned int count_bools(const std::array<bool, length> & s) noexcept
{
unsigned int number_of_true_elements = 0;
for (std::size_t i = 0; i < length; ++i)
{
if (s[i])
{
number_of_true_elements++;
}
}
return number_of_true_elements;
}
#else
constexpr unsigned int count_bools(bool const * const begin, bool const * const end,
unsigned int n)
{
return begin == end ? n : detail::count_bools(begin + 1, end, n + *begin);
}
#endif
#endif
template <bool... Bs>
struct template_count_bools
{
using type = ::brigand::size_t<0>;
};
template <bool B, bool... Bs>
struct template_count_bools<B, Bs...>
{
using type = ::brigand::size_t<B + template_count_bools<Bs...>::type::value>;
};
template <bool B1, bool B2, bool B3, bool B4, bool B5, bool B6, bool B7, bool B8, bool B9,
bool B10, bool B11, bool B12, bool B13, bool B14, bool B15, bool B16, bool... Bs>
struct template_count_bools<B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15,
B16, Bs...>
{
using type =
::brigand::size_t<B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8 + B9 + B10 + B11 + B12 + B13 +
B14 + B15 + B16 + template_count_bools<Bs...>::type::value>;
};
}
namespace lazy
{
template <typename List, typename Pred>
struct count_if
{
};
template <template <typename...> class S, typename Pred>
struct count_if<S<>, Pred>
{
using type = ::brigand::size_t<0>;
};
#if defined(BRIGAND_COMP_GCC) || defined(BRIGAND_COMP_CLANG) // not MSVC
template <template <typename...> class S, template <typename...> class F>
struct count_if<S<>, bind<F, _1>>
{
using type = ::brigand::size_t<0>;
};
template <template <typename...> class S, template <typename...> class F>
struct count_if<S<>, F<_1>>
{
using type = ::brigand::size_t<0>;
};
template <template <typename...> class S, typename... Ts, typename Pred>
struct count_if<S<Ts...>, Pred>
{
#if __cplusplus >= 201402L
static constexpr std::array<bool, sizeof...(Ts)> s_v{{::brigand::apply<Pred, Ts>::type::value...}};
using type = brigand::size_t<::brigand::detail::count_bools(s_v)>;
#else
static constexpr bool s_v[] = {::brigand::apply<Pred, Ts>::type::value...};
using type = brigand::size_t<::brigand::detail::count_bools(s_v, s_v + sizeof...(Ts), 0u)>;
#endif
};
template <template <typename...> class S, typename... Ts, template <typename...> class F>
struct count_if<S<Ts...>, bind<F, _1>>
{
#if __cplusplus >= 201402L
static constexpr std::array<bool, sizeof...(Ts)> s_v{{F<Ts>::type::value...}};
using type = brigand::size_t<::brigand::detail::count_bools(s_v)>;
#else
static constexpr bool s_v[] = {F<Ts>::value...};
using type = brigand::size_t<::brigand::detail::count_bools(s_v, s_v + sizeof...(Ts), 0u)>;
#endif
};
template <template <typename...> class S, typename... Ts, template <typename...> class F>
struct count_if<S<Ts...>, F<_1>>
{
#if __cplusplus >= 201402L
static constexpr std::array<bool, sizeof...(Ts)> s_v{{F<Ts>::type::value...}};
using type = brigand::size_t<::brigand::detail::count_bools(s_v)>;
#else
static constexpr bool s_v[] = {F<Ts>::type::value...};
using type = brigand::size_t<::brigand::detail::count_bools(s_v, s_v + sizeof...(Ts), 0u)>;
#endif
};
#else
#if defined(BRIGAND_COMP_MSVC_2015)
template <template <typename...> class S, typename... Ts, typename Pred>
struct count_if<S<Ts...>, Pred>
: ::brigand::detail::template_count_bools<::brigand::apply<Pred, Ts>::value...>
{
};
#else
template <template <typename...> class S, typename... Ts, typename Pred>
struct count_if<S<Ts...>, Pred>
{
template <typename T>
using val_t = brigand::apply<Pred, T>;
using type = typename ::brigand::detail::template_count_bools<val_t<Ts>::value...>::type;
};
#endif
#endif
}
template <typename List, typename Pred>
using count_if = typename lazy::count_if<List, Pred>::type;
template <class... T>
using count = brigand::integral_constant<unsigned int, sizeof...(T)>;
}
#endif
<commit_msg>Delete count.hpp<commit_after><|endoftext|>
|
<commit_before>#include "IGTLinkStreamer.hpp"
#include "FAST/Data/Image.hpp"
#include "FAST/AffineTransformation.hpp"
#include <boost/shared_array.hpp>
#include <boost/lexical_cast.hpp>
#include "igtlOSUtil.h"
#include "igtlMessageHeader.h"
#include "igtlTransformMessage.h"
#include "igtlPositionMessage.h"
#include "igtlImageMessage.h"
#include "igtlStatusMessage.h"
#include "igtlStringMessage.h"
namespace fast {
void IGTLinkStreamer::setConnectionAddress(std::string address) {
mAddress = address;
mIsModified = true;
}
void IGTLinkStreamer::setConnectionPort(uint port) {
mPort = port;
mIsModified = true;
}
void IGTLinkStreamer::setStreamingMode(StreamingMode mode) {
if(mode == STREAMING_MODE_STORE_ALL_FRAMES && !mMaximumNrOfFramesSet)
setMaximumNumberOfFrames(0);
Streamer::setStreamingMode(mode);
}
void IGTLinkStreamer::setMaximumNumberOfFrames(uint nrOfFrames) {
mMaximumNrOfFrames = nrOfFrames;
}
bool IGTLinkStreamer::hasReachedEnd() const {
return mHasReachedEnd;
}
uint IGTLinkStreamer::getNrOfFrames() const {
return mNrOfFrames;
}
inline Image::pointer createFASTImageFromMessage(igtl::ImageMessage::Pointer message, ExecutionDevice::pointer device) {
Image::pointer image = Image::New();
int width, height, depth;
message->GetDimensions(width, height, depth);
void* data = message->GetScalarPointer();
DataType type;
switch(message->GetScalarType()) {
case igtl::ImageMessage::TYPE_INT8:
type = TYPE_INT8;
break;
case igtl::ImageMessage::TYPE_UINT8:
type = TYPE_UINT8;
break;
case igtl::ImageMessage::TYPE_INT16:
type = TYPE_INT16;
break;
case igtl::ImageMessage::TYPE_UINT16:
type = TYPE_UINT16;
break;
case igtl::ImageMessage::TYPE_FLOAT32:
type = TYPE_FLOAT;
break;
default:
throw Exception("Unsupported image data type.");
break;
}
if(depth == 1) {
image->create(width, height, type, message->GetNumComponents(), device, data);
} else {
image->create(width, height, depth, type, message->GetNumComponents(), device, data);
}
boost::shared_array<float> spacing(new float[3]);
boost::shared_array<float> offset(new float[3]);
message->GetSpacing(spacing.get());
message->GetOrigin(offset.get());
igtl::Matrix4x4 matrix;
message->GetMatrix(matrix);
image->setSpacing(Vector3f(spacing[0], spacing[1], spacing[2]));
AffineTransformation T;
T.translation() = Vector3f(offset[0], offset[1], offset[2]);
Matrix3f fastMatrix;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
fastMatrix(i,j) = matrix[i][j];
}}
T.linear() = fastMatrix;
image->getSceneGraphNode()->setTransformation(T);
return image;
}
void IGTLinkStreamer::updateFirstFrameSetFlag() {
// Check that all output ports have got their first frame
bool allHaveGotData = true;
for(uint i = 0; i < getNrOfOutputPorts(); i++) {
DynamicData::pointer data = ProcessObject::getOutputPort(i).getData();
if(data->getSize() == 0) {
allHaveGotData = false;
break;
}
}
if(allHaveGotData) {
{
boost::lock_guard<boost::mutex> lock(mFirstFrameMutex);
mFirstFrameIsInserted = true;
}
mFirstFrameCondition.notify_one();
} else {
reportInfo() << "ALL HAVE NOT GOT DATA" << Reporter::end;
}
}
void IGTLinkStreamer::producerStream() {
mSocket = igtl::ClientSocket::New();
reportInfo() << "Trying to connect to Open IGT Link server " << mAddress << ":" << boost::lexical_cast<std::string>(mPort) << Reporter::end;;
//mSocket->SetTimeout(3); // try to connect for 3 seconds
int r = mSocket->ConnectToServer(mAddress.c_str(), mPort);
if(r != 0) {
connectionLostSignal();
throw Exception("Cannot connect to the Open IGT Link server.");
}
reportInfo() << "Connected to Open IGT Link server" << Reporter::end;;
// Create a message buffer to receive header
igtl::MessageHeader::Pointer headerMsg;
headerMsg = igtl::MessageHeader::New();
// Allocate a time stamp
igtl::TimeStamp::Pointer ts;
ts = igtl::TimeStamp::New();
uint statusMessageCounter = 0;
while(true) {
{
boost::unique_lock<boost::mutex> lock(mStopMutex);
if(mStop) {
mStreamIsStarted = false;
mFirstFrameIsInserted = false;
mHasReachedEnd = false;
break;
}
}
// Initialize receive buffer
headerMsg->InitPack();
// Receive generic header from the socket
int r = mSocket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize());
if(r == 0) {
connectionLostSignal();
mSocket->CloseSocket();
break;
}
if(r != headerMsg->GetPackSize()) {
continue;
}
// Deserialize the header
headerMsg->Unpack();
// Get time stamp
igtlUint32 sec;
igtlUint32 nanosec;
headerMsg->GetTimeStamp(ts);
ts->GetTimeStamp(&sec, &nanosec);
reportInfo() << "Time stamp: "
<< sec << "." << std::setw(9) << std::setfill('0')
<< nanosec << Reporter::end;
reportInfo() << "Device type: " << headerMsg->GetDeviceType() << Reporter::end;
reportInfo() << "Device name: " << headerMsg->GetDeviceName() << Reporter::end;
if(strcmp(headerMsg->GetDeviceType(), "TRANSFORM") == 0) {
if(mInFreezeMode)
unfreezeSignal();
statusMessageCounter = 0;
igtl::TransformMessage::Pointer transMsg;
transMsg = igtl::TransformMessage::New();
transMsg->SetMessageHeader(headerMsg);
transMsg->AllocatePack();
// Receive transform data from the socket
mSocket->Receive(transMsg->GetPackBodyPointer(), transMsg->GetPackBodySize());
// Deserialize the transform data
// If you want to skip CRC check, call Unpack() without argument.
int c = transMsg->Unpack(1);
if(c & igtl::MessageHeader::UNPACK_BODY) { // if CRC check is OK
// Retrive the transform data
igtl::Matrix4x4 matrix;
transMsg->GetMatrix(matrix);
Matrix4f fastMatrix;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
fastMatrix(i,j) = matrix[i][j];
}}
reportInfo() << fastMatrix << Reporter::end;
DynamicData::pointer ptr;
try {
ptr = getOutputDataFromDeviceName<AffineTransformation>(headerMsg->GetDeviceName());
ptr->setStreamer(mPtr.lock());
} catch(Exception &e) {
reportInfo() << "Output port with device name " << headerMsg->GetDeviceName() << " not found" << Reporter::end;
continue;
}
try {
AffineTransformation::pointer T = AffineTransformation::New();
T->matrix() = fastMatrix;
ptr->addFrame(T);
reportInfo() << "Frame added.." << Reporter::end;
} catch(NoMoreFramesException &e) {
throw e;
} catch(Exception &e) {
reportInfo() << "streamer has been deleted, stop" << Reporter::end;
break;
}
if(!mFirstFrameIsInserted) {
updateFirstFrameSetFlag();
}
mNrOfFrames++;
}
} else if(strcmp(headerMsg->GetDeviceType(), "IMAGE") == 0) {
if(mInFreezeMode)
unfreezeSignal();
statusMessageCounter = 0;
reportInfo() << "Receiving IMAGE data type." << Reporter::end;
// Create a message buffer to receive transform data
igtl::ImageMessage::Pointer imgMsg;
imgMsg = igtl::ImageMessage::New();
imgMsg->SetMessageHeader(headerMsg);
imgMsg->AllocatePack();
// Receive transform data from the socket
mSocket->Receive(imgMsg->GetPackBodyPointer(), imgMsg->GetPackBodySize());
// Deserialize the transform data
// If you want to skip CRC check, call Unpack() without argument.
int c = imgMsg->Unpack(1);
if(c & igtl::MessageHeader::UNPACK_BODY) { // if CRC check is OK
// Retrive the image data
int size[3]; // image dimension
float spacing[3]; // spacing (mm/pixel)
int svsize[3]; // sub-volume size
int svoffset[3]; // sub-volume offset
int scalarType; // scalar type
scalarType = imgMsg->GetScalarType();
imgMsg->GetDimensions(size);
imgMsg->GetSpacing(spacing);
imgMsg->GetSubVolume(svsize, svoffset);
DynamicData::pointer ptr;
try {
ptr = getOutputDataFromDeviceName<Image>(headerMsg->GetDeviceName());
ptr->setStreamer(mPtr.lock());
} catch(Exception &e) {
reportInfo() << "Output port with device name " << headerMsg->GetDeviceName() << " not found" << Reporter::end;
continue;
}
try {
Image::pointer image = createFASTImageFromMessage(imgMsg, getMainDevice());
reportInfo() << image->getSceneGraphNode()->getTransformation().matrix() << Reporter::end;
reportInfo() << "SPACING IS " << image->getSpacing().transpose() << Reporter::end;
reportInfo() << "SIZE IS " << image->getSize().transpose() << Reporter::end;
ptr->addFrame(image);
reportInfo() << "Image frame added.." << Reporter::end;
} catch(NoMoreFramesException &e) {
throw e;
} catch(Exception &e) {
reportInfo() << "streamer has been deleted, stop" << Reporter::end;
break;
}
if(!mFirstFrameIsInserted) {
updateFirstFrameSetFlag();
}
mNrOfFrames++;
}
} else if(strcmp(headerMsg->GetDeviceType(), "STATUS") == 0) {
++statusMessageCounter;
reportInfo() << "STATUS MESSAGE recieved" << Reporter::end;
// Receive generic message
igtl::MessageBase::Pointer message;
message = igtl::MessageBase::New();
message->SetMessageHeader(headerMsg);
message->AllocatePack();
// Receive transform data from the socket
mSocket->Receive(message->GetPackBodyPointer(), message->GetPackBodySize());
if(statusMessageCounter > 10) { // If we only recieve status messages, the connection is lost
reportInfo() << "10 STATUS MESSAGE received, freeze detected" << Reporter::end;
mInFreezeMode = true;
freezeSignal();
}
} else {
// Receive generic message
igtl::MessageBase::Pointer message;
message = igtl::MessageBase::New();
message->SetMessageHeader(headerMsg);
message->AllocatePack();
// Receive transform data from the socket
mSocket->Receive(message->GetPackBodyPointer(), message->GetPackBodySize());
// Deserialize the transform data
// If you want to skip CRC check, call Unpack() without argument.
int c = message->Unpack();
}
}
// Make sure we end the waiting thread if first frame has not been inserted
{
boost::lock_guard<boost::mutex> lock(mFirstFrameMutex);
if(!mFirstFrameIsInserted)
mFirstFrameIsInserted = true;
}
mFirstFrameCondition.notify_one();
mSocket->CloseSocket();
}
IGTLinkStreamer::~IGTLinkStreamer() {
if(mStreamIsStarted) {
stop();
if(thread->get_id() != boost::this_thread::get_id()) { // avoid deadlock
thread->join();
}
delete thread;
}
}
IGTLinkStreamer::IGTLinkStreamer() {
mStreamIsStarted = false;
mIsModified = true;
thread = NULL;
mFirstFrameIsInserted = false;
mHasReachedEnd = false;
mStop = false;
mNrOfFrames = 0;
mAddress = "";
mPort = 0;
mMaximumNrOfFramesSet = false;
mInFreezeMode = false;
setMaximumNumberOfFrames(50); // Set default maximum number of frames to 50
}
void IGTLinkStreamer::stop() {
boost::unique_lock<boost::mutex> lock(mStopMutex);
mStop = true;
}
void IGTLinkStreamer::execute() {
if(mAddress == "" || mPort == 0) {
throw Exception("Must call setConnectionAddress and setConnectionPort before executing the IGTLinkStreamer.");
}
if(!mStreamIsStarted) {
for(uint i = 0; i < getNrOfOutputPorts(); i++) {
DynamicData::pointer data = ProcessObject::getOutputPort(i).getData();
data->setMaximumNumberOfFrames(mMaximumNrOfFrames);
}
mStreamIsStarted = true;
thread = new boost::thread(boost::bind(&IGTLinkStreamer::producerStream, this));
}
// Wait here for first frame
boost::unique_lock<boost::mutex> lock(mFirstFrameMutex);
while(!mFirstFrameIsInserted) {
mFirstFrameCondition.wait(lock);
}
{
boost::unique_lock<boost::mutex> lock(mStopMutex);
if(!mStop)
connectionEstablishedSignal(); // send signal
}
}
} // end namespace fast
<commit_msg>some more freeze mode logic in IGTLinkStreamer<commit_after>#include "IGTLinkStreamer.hpp"
#include "FAST/Data/Image.hpp"
#include "FAST/AffineTransformation.hpp"
#include <boost/shared_array.hpp>
#include <boost/lexical_cast.hpp>
#include "igtlOSUtil.h"
#include "igtlMessageHeader.h"
#include "igtlTransformMessage.h"
#include "igtlPositionMessage.h"
#include "igtlImageMessage.h"
#include "igtlStatusMessage.h"
#include "igtlStringMessage.h"
namespace fast {
void IGTLinkStreamer::setConnectionAddress(std::string address) {
mAddress = address;
mIsModified = true;
}
void IGTLinkStreamer::setConnectionPort(uint port) {
mPort = port;
mIsModified = true;
}
void IGTLinkStreamer::setStreamingMode(StreamingMode mode) {
if(mode == STREAMING_MODE_STORE_ALL_FRAMES && !mMaximumNrOfFramesSet)
setMaximumNumberOfFrames(0);
Streamer::setStreamingMode(mode);
}
void IGTLinkStreamer::setMaximumNumberOfFrames(uint nrOfFrames) {
mMaximumNrOfFrames = nrOfFrames;
}
bool IGTLinkStreamer::hasReachedEnd() const {
return mHasReachedEnd;
}
uint IGTLinkStreamer::getNrOfFrames() const {
return mNrOfFrames;
}
inline Image::pointer createFASTImageFromMessage(igtl::ImageMessage::Pointer message, ExecutionDevice::pointer device) {
Image::pointer image = Image::New();
int width, height, depth;
message->GetDimensions(width, height, depth);
void* data = message->GetScalarPointer();
DataType type;
switch(message->GetScalarType()) {
case igtl::ImageMessage::TYPE_INT8:
type = TYPE_INT8;
break;
case igtl::ImageMessage::TYPE_UINT8:
type = TYPE_UINT8;
break;
case igtl::ImageMessage::TYPE_INT16:
type = TYPE_INT16;
break;
case igtl::ImageMessage::TYPE_UINT16:
type = TYPE_UINT16;
break;
case igtl::ImageMessage::TYPE_FLOAT32:
type = TYPE_FLOAT;
break;
default:
throw Exception("Unsupported image data type.");
break;
}
if(depth == 1) {
image->create(width, height, type, message->GetNumComponents(), device, data);
} else {
image->create(width, height, depth, type, message->GetNumComponents(), device, data);
}
boost::shared_array<float> spacing(new float[3]);
boost::shared_array<float> offset(new float[3]);
message->GetSpacing(spacing.get());
message->GetOrigin(offset.get());
igtl::Matrix4x4 matrix;
message->GetMatrix(matrix);
image->setSpacing(Vector3f(spacing[0], spacing[1], spacing[2]));
AffineTransformation T;
T.translation() = Vector3f(offset[0], offset[1], offset[2]);
Matrix3f fastMatrix;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
fastMatrix(i,j) = matrix[i][j];
}}
T.linear() = fastMatrix;
image->getSceneGraphNode()->setTransformation(T);
return image;
}
void IGTLinkStreamer::updateFirstFrameSetFlag() {
// Check that all output ports have got their first frame
bool allHaveGotData = true;
for(uint i = 0; i < getNrOfOutputPorts(); i++) {
DynamicData::pointer data = ProcessObject::getOutputPort(i).getData();
if(data->getSize() == 0) {
allHaveGotData = false;
break;
}
}
if(allHaveGotData) {
{
boost::lock_guard<boost::mutex> lock(mFirstFrameMutex);
mFirstFrameIsInserted = true;
}
mFirstFrameCondition.notify_one();
} else {
reportInfo() << "ALL HAVE NOT GOT DATA" << Reporter::end;
}
}
void IGTLinkStreamer::producerStream() {
mSocket = igtl::ClientSocket::New();
reportInfo() << "Trying to connect to Open IGT Link server " << mAddress << ":" << boost::lexical_cast<std::string>(mPort) << Reporter::end;;
//mSocket->SetTimeout(3); // try to connect for 3 seconds
int r = mSocket->ConnectToServer(mAddress.c_str(), mPort);
if(r != 0) {
connectionLostSignal();
throw Exception("Cannot connect to the Open IGT Link server.");
}
reportInfo() << "Connected to Open IGT Link server" << Reporter::end;;
// Create a message buffer to receive header
igtl::MessageHeader::Pointer headerMsg;
headerMsg = igtl::MessageHeader::New();
// Allocate a time stamp
igtl::TimeStamp::Pointer ts;
ts = igtl::TimeStamp::New();
uint statusMessageCounter = 0;
while(true) {
{
boost::unique_lock<boost::mutex> lock(mStopMutex);
if(mStop) {
mStreamIsStarted = false;
mFirstFrameIsInserted = false;
mHasReachedEnd = false;
break;
}
}
// Initialize receive buffer
headerMsg->InitPack();
// Receive generic header from the socket
int r = mSocket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize());
if(r == 0) {
connectionLostSignal();
mSocket->CloseSocket();
break;
}
if(r != headerMsg->GetPackSize()) {
continue;
}
// Deserialize the header
headerMsg->Unpack();
// Get time stamp
igtlUint32 sec;
igtlUint32 nanosec;
headerMsg->GetTimeStamp(ts);
ts->GetTimeStamp(&sec, &nanosec);
reportInfo() << "Time stamp: "
<< sec << "." << std::setw(9) << std::setfill('0')
<< nanosec << Reporter::end;
reportInfo() << "Device type: " << headerMsg->GetDeviceType() << Reporter::end;
reportInfo() << "Device name: " << headerMsg->GetDeviceName() << Reporter::end;
if(strcmp(headerMsg->GetDeviceType(), "TRANSFORM") == 0) {
if(mInFreezeMode) {
unfreezeSignal();
mInFreezeMode = false;
}
statusMessageCounter = 0;
igtl::TransformMessage::Pointer transMsg;
transMsg = igtl::TransformMessage::New();
transMsg->SetMessageHeader(headerMsg);
transMsg->AllocatePack();
// Receive transform data from the socket
mSocket->Receive(transMsg->GetPackBodyPointer(), transMsg->GetPackBodySize());
// Deserialize the transform data
// If you want to skip CRC check, call Unpack() without argument.
int c = transMsg->Unpack(1);
if(c & igtl::MessageHeader::UNPACK_BODY) { // if CRC check is OK
// Retrive the transform data
igtl::Matrix4x4 matrix;
transMsg->GetMatrix(matrix);
Matrix4f fastMatrix;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
fastMatrix(i,j) = matrix[i][j];
}}
reportInfo() << fastMatrix << Reporter::end;
DynamicData::pointer ptr;
try {
ptr = getOutputDataFromDeviceName<AffineTransformation>(headerMsg->GetDeviceName());
ptr->setStreamer(mPtr.lock());
} catch(Exception &e) {
reportInfo() << "Output port with device name " << headerMsg->GetDeviceName() << " not found" << Reporter::end;
continue;
}
try {
AffineTransformation::pointer T = AffineTransformation::New();
T->matrix() = fastMatrix;
ptr->addFrame(T);
reportInfo() << "Frame added.." << Reporter::end;
} catch(NoMoreFramesException &e) {
throw e;
} catch(Exception &e) {
reportInfo() << "streamer has been deleted, stop" << Reporter::end;
break;
}
if(!mFirstFrameIsInserted) {
updateFirstFrameSetFlag();
}
mNrOfFrames++;
}
} else if(strcmp(headerMsg->GetDeviceType(), "IMAGE") == 0) {
if(mInFreezeMode) {
unfreezeSignal();
mInFreezeMode = false;
}
statusMessageCounter = 0;
reportInfo() << "Receiving IMAGE data type." << Reporter::end;
// Create a message buffer to receive transform data
igtl::ImageMessage::Pointer imgMsg;
imgMsg = igtl::ImageMessage::New();
imgMsg->SetMessageHeader(headerMsg);
imgMsg->AllocatePack();
// Receive transform data from the socket
mSocket->Receive(imgMsg->GetPackBodyPointer(), imgMsg->GetPackBodySize());
// Deserialize the transform data
// If you want to skip CRC check, call Unpack() without argument.
int c = imgMsg->Unpack(1);
if(c & igtl::MessageHeader::UNPACK_BODY) { // if CRC check is OK
// Retrive the image data
int size[3]; // image dimension
float spacing[3]; // spacing (mm/pixel)
int svsize[3]; // sub-volume size
int svoffset[3]; // sub-volume offset
int scalarType; // scalar type
scalarType = imgMsg->GetScalarType();
imgMsg->GetDimensions(size);
imgMsg->GetSpacing(spacing);
imgMsg->GetSubVolume(svsize, svoffset);
DynamicData::pointer ptr;
try {
ptr = getOutputDataFromDeviceName<Image>(headerMsg->GetDeviceName());
ptr->setStreamer(mPtr.lock());
} catch(Exception &e) {
reportInfo() << "Output port with device name " << headerMsg->GetDeviceName() << " not found" << Reporter::end;
continue;
}
try {
Image::pointer image = createFASTImageFromMessage(imgMsg, getMainDevice());
reportInfo() << image->getSceneGraphNode()->getTransformation().matrix() << Reporter::end;
reportInfo() << "SPACING IS " << image->getSpacing().transpose() << Reporter::end;
reportInfo() << "SIZE IS " << image->getSize().transpose() << Reporter::end;
ptr->addFrame(image);
reportInfo() << "Image frame added.." << Reporter::end;
} catch(NoMoreFramesException &e) {
throw e;
} catch(Exception &e) {
reportInfo() << "streamer has been deleted, stop" << Reporter::end;
break;
}
if(!mFirstFrameIsInserted) {
updateFirstFrameSetFlag();
}
mNrOfFrames++;
}
} else if(strcmp(headerMsg->GetDeviceType(), "STATUS") == 0) {
++statusMessageCounter;
reportInfo() << "STATUS MESSAGE recieved" << Reporter::end;
// Receive generic message
igtl::MessageBase::Pointer message;
message = igtl::MessageBase::New();
message->SetMessageHeader(headerMsg);
message->AllocatePack();
// Receive transform data from the socket
mSocket->Receive(message->GetPackBodyPointer(), message->GetPackBodySize());
if(statusMessageCounter > 3 && !mInFreezeMode) {
reportInfo() << "3 STATUS MESSAGE received, freeze detected" << Reporter::end;
mInFreezeMode = true;
freezeSignal();
}
} else {
// Receive generic message
igtl::MessageBase::Pointer message;
message = igtl::MessageBase::New();
message->SetMessageHeader(headerMsg);
message->AllocatePack();
// Receive transform data from the socket
mSocket->Receive(message->GetPackBodyPointer(), message->GetPackBodySize());
// Deserialize the transform data
// If you want to skip CRC check, call Unpack() without argument.
int c = message->Unpack();
}
}
// Make sure we end the waiting thread if first frame has not been inserted
{
boost::lock_guard<boost::mutex> lock(mFirstFrameMutex);
if(!mFirstFrameIsInserted)
mFirstFrameIsInserted = true;
}
mFirstFrameCondition.notify_one();
mSocket->CloseSocket();
}
IGTLinkStreamer::~IGTLinkStreamer() {
if(mStreamIsStarted) {
stop();
if(thread->get_id() != boost::this_thread::get_id()) { // avoid deadlock
thread->join();
}
delete thread;
}
}
IGTLinkStreamer::IGTLinkStreamer() {
mStreamIsStarted = false;
mIsModified = true;
thread = NULL;
mFirstFrameIsInserted = false;
mHasReachedEnd = false;
mStop = false;
mNrOfFrames = 0;
mAddress = "";
mPort = 0;
mMaximumNrOfFramesSet = false;
mInFreezeMode = false;
setMaximumNumberOfFrames(50); // Set default maximum number of frames to 50
}
void IGTLinkStreamer::stop() {
boost::unique_lock<boost::mutex> lock(mStopMutex);
mStop = true;
}
void IGTLinkStreamer::execute() {
if(mAddress == "" || mPort == 0) {
throw Exception("Must call setConnectionAddress and setConnectionPort before executing the IGTLinkStreamer.");
}
if(!mStreamIsStarted) {
for(uint i = 0; i < getNrOfOutputPorts(); i++) {
DynamicData::pointer data = ProcessObject::getOutputPort(i).getData();
data->setMaximumNumberOfFrames(mMaximumNrOfFrames);
}
mStreamIsStarted = true;
thread = new boost::thread(boost::bind(&IGTLinkStreamer::producerStream, this));
}
// Wait here for first frame
boost::unique_lock<boost::mutex> lock(mFirstFrameMutex);
while(!mFirstFrameIsInserted) {
mFirstFrameCondition.wait(lock);
}
{
boost::unique_lock<boost::mutex> lock(mStopMutex);
if(!mStop)
connectionEstablishedSignal(); // send signal
}
}
} // end namespace fast
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: slidebitmap.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-11-26 18:59:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// must be first
#include <canvas/debug.hxx>
#include <slidebitmap.hxx>
#ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XCANVAS_HPP_
#include <drafts/com/sun/star/rendering/XCanvas.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XBITMAP_HPP_
#include <drafts/com/sun/star/rendering/XBitmap.hpp>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#include <canvas/canvastools.hxx>
#include <basegfx/tools/canvastools.hxx>
using namespace ::drafts::com::sun::star;
using namespace ::com::sun::star;
namespace presentation
{
namespace internal
{
SlideBitmap::SlideBitmap( const ::cppcanvas::BitmapSharedPtr& rBitmap ) :
maOutputPos(),
maClipPoly(),
mxBitmap()
{
if( rBitmap.get() )
mxBitmap = rBitmap->getUNOBitmap();
ENSURE_AND_THROW( mxBitmap.is(), "SlideBitmap::SlideBitmap(): Invalid bitmap" );
}
bool SlideBitmap::draw( const ::cppcanvas::CanvasSharedPtr& rCanvas ) const
{
ENSURE_AND_RETURN( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(),
"SlideBitmap::draw(): Invalid canvas" );
// selectively only copy the transformation from current viewstate,
// don't want no clipping here.
rendering::ViewState aViewState;
aViewState.AffineTransform = rCanvas->getViewState().AffineTransform;
rendering::RenderState aRenderState;
::canvas::tools::initRenderState( aRenderState );
::basegfx::B2DHomMatrix aTranslation;
aTranslation.translate( maOutputPos.getX(),
maOutputPos.getY() );
::canvas::tools::setRenderStateTransform( aRenderState, aTranslation );
if( maClipPoly.count() )
{
// TODO(P1): Buffer the clip polygon
aRenderState.Clip =
::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
rCanvas->getUNOCanvas()->getDevice(),
maClipPoly );
}
rCanvas->getUNOCanvas()->drawBitmap( mxBitmap,
aViewState,
aRenderState );
return true;
}
::basegfx::B2ISize SlideBitmap::getSize() const
{
return ::basegfx::unotools::b2ISizeFromIntegerSize2D( mxBitmap->getSize() );
}
void SlideBitmap::move( const ::basegfx::B2DPoint& rNewPos )
{
maOutputPos = rNewPos;
}
void SlideBitmap::clip( const ::basegfx::B2DPolyPolygon& rClipPoly )
{
maClipPoly = rClipPoly;
}
}
}
<commit_msg>INTEGRATION: CWS presfixes01 (1.3.6); FILE MERGED 2005/02/16 11:17:45 fs 1.3.6.1: #i42558# drafts.com.sun.star.drawing/rendering/geometry moved to com.sun.star.*<commit_after>/*************************************************************************
*
* $RCSfile: slidebitmap.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2005-03-10 13:45:00 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// must be first
#include <canvas/debug.hxx>
#include <slidebitmap.hxx>
#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP_
#include <com/sun/star/rendering/XCanvas.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XBITMAP_HPP_
#include <com/sun/star/rendering/XBitmap.hpp>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#include <canvas/canvastools.hxx>
#include <basegfx/tools/canvastools.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star;
namespace presentation
{
namespace internal
{
SlideBitmap::SlideBitmap( const ::cppcanvas::BitmapSharedPtr& rBitmap ) :
maOutputPos(),
maClipPoly(),
mxBitmap()
{
if( rBitmap.get() )
mxBitmap = rBitmap->getUNOBitmap();
ENSURE_AND_THROW( mxBitmap.is(), "SlideBitmap::SlideBitmap(): Invalid bitmap" );
}
bool SlideBitmap::draw( const ::cppcanvas::CanvasSharedPtr& rCanvas ) const
{
ENSURE_AND_RETURN( rCanvas.get() != NULL && rCanvas->getUNOCanvas().is(),
"SlideBitmap::draw(): Invalid canvas" );
// selectively only copy the transformation from current viewstate,
// don't want no clipping here.
rendering::ViewState aViewState;
aViewState.AffineTransform = rCanvas->getViewState().AffineTransform;
rendering::RenderState aRenderState;
::canvas::tools::initRenderState( aRenderState );
::basegfx::B2DHomMatrix aTranslation;
aTranslation.translate( maOutputPos.getX(),
maOutputPos.getY() );
::canvas::tools::setRenderStateTransform( aRenderState, aTranslation );
if( maClipPoly.count() )
{
// TODO(P1): Buffer the clip polygon
aRenderState.Clip =
::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
rCanvas->getUNOCanvas()->getDevice(),
maClipPoly );
}
rCanvas->getUNOCanvas()->drawBitmap( mxBitmap,
aViewState,
aRenderState );
return true;
}
::basegfx::B2ISize SlideBitmap::getSize() const
{
return ::basegfx::unotools::b2ISizeFromIntegerSize2D( mxBitmap->getSize() );
}
void SlideBitmap::move( const ::basegfx::B2DPoint& rNewPos )
{
maOutputPos = rNewPos;
}
void SlideBitmap::clip( const ::basegfx::B2DPolyPolygon& rClipPoly )
{
maClipPoly = rClipPoly;
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wakeupevent.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:31:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
// must be first
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <wakeupevent.hxx>
namespace presentation
{
namespace internal
{
WakeupEvent::WakeupEvent(
boost::shared_ptr<canvas::tools::ElapsedTime> const & pTimeBase,
ActivitiesQueue& rActivityQueue ) :
maTimer(pTimeBase),
mnNextTime(0.0),
mpActivity(),
mrActivityQueue( rActivityQueue )
{
}
void WakeupEvent::dispose()
{
mpActivity.reset();
}
bool WakeupEvent::fire()
{
if( !mpActivity.get() )
return false;
return mrActivityQueue.addActivity( mpActivity );
}
bool WakeupEvent::isCharged() const
{
// this event won't expire, we fire everytime we're
// re-inserted into the event queue.
return true;
}
double WakeupEvent::getActivationTime( double nCurrentTime ) const
{
const double nElapsedTime( maTimer.getElapsedTime() );
return ::std::max( nCurrentTime,
nCurrentTime - nElapsedTime + mnNextTime );
}
void WakeupEvent::start()
{
// start timer
maTimer.reset();
}
void WakeupEvent::setNextTimeout( double rNextTime )
{
mnNextTime = rNextTime;
}
void WakeupEvent::setActivity( const ActivitySharedPtr& rActivity )
{
mpActivity = rActivity;
}
}
}
<commit_msg>INTEGRATION: CWS presfixes09 (1.5.18); FILE MERGED 2006/10/18 19:52:34 thb 1.5.18.3: RESYNC: (1.5-1.6); FILE MERGED 2006/04/12 20:40:05 thb 1.5.18.2: #i37778# Replaced all shared_ptr.get() != NULL places with the more elegant automatic-conversion-to-bool version (at least where the compiler tolerated that) 2006/03/24 18:23:12 thb 1.5.18.1: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wakeupevent.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-12-13 15:23:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
// must be first
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <wakeupevent.hxx>
namespace slideshow
{
namespace internal
{
WakeupEvent::WakeupEvent(
boost::shared_ptr<canvas::tools::ElapsedTime> const & pTimeBase,
ActivitiesQueue& rActivityQueue ) :
maTimer(pTimeBase),
mnNextTime(0.0),
mpActivity(),
mrActivityQueue( rActivityQueue )
{
}
void WakeupEvent::dispose()
{
mpActivity.reset();
}
bool WakeupEvent::fire()
{
if( !mpActivity )
return false;
return mrActivityQueue.addActivity( mpActivity );
}
bool WakeupEvent::isCharged() const
{
// this event won't expire, we fire everytime we're
// re-inserted into the event queue.
return true;
}
double WakeupEvent::getActivationTime( double nCurrentTime ) const
{
const double nElapsedTime( maTimer.getElapsedTime() );
return ::std::max( nCurrentTime,
nCurrentTime - nElapsedTime + mnNextTime );
}
void WakeupEvent::start()
{
// start timer
maTimer.reset();
}
void WakeupEvent::setNextTimeout( double rNextTime )
{
mnNextTime = rNextTime;
}
void WakeupEvent::setActivity( const ActivitySharedPtr& rActivity )
{
mpActivity = rActivity;
}
}
}
<|endoftext|>
|
<commit_before>
#include <gloperate-qt/base/GLContextFactory.h>
#include <QOpenGLContext>
#include <QSurfaceFormat>
#include <cppassist/memory/make_unique.h>
#include <gloperate-qt/base/GLContext.h>
namespace gloperate_qt
{
GLContextFactory::GLContextFactory(QWindow * window)
: m_window(window)
{
}
GLContextFactory::~GLContextFactory()
{
}
std::unique_ptr<gloperate::AbstractGLContext> GLContextFactory::createContext(const gloperate::GLContextFormat & format) const
{
// Create OpenGL context
auto qContext = cppassist::make_unique<QOpenGLContext>();
qContext->setFormat(toQSurfaceFormat(format));
// Create and check context
if (!qContext->create())
{
return nullptr;
}
return cppassist::make_unique<GLContext>(m_window, qContext.release());
}
QSurfaceFormat GLContextFactory::toQSurfaceFormat(const gloperate::GLContextFormat & format)
{
QSurfaceFormat qFormat;
qFormat.setRenderableType(QSurfaceFormat::OpenGL);
// Set OpenGL version
qFormat.setVersion(format.majorVersion(), format.minorVersion());
// Set OpenGL context flags
if (format.version() >= glbinding::Version(3, 0))
{
qFormat.setOption(QSurfaceFormat::DeprecatedFunctions, !format.forwardCompatible());
qFormat.setOption(QSurfaceFormat::DebugContext, format.debugContext());
}
// Set OpenGL profile
switch (format.profile())
{
case gloperate::GLContextFormat::Profile::Core:
qFormat.setProfile(QSurfaceFormat::CoreProfile);
break;
case gloperate::GLContextFormat::Profile::Compatibility:
qFormat.setProfile(QSurfaceFormat::CompatibilityProfile);
break;
default:
qFormat.setProfile(QSurfaceFormat::NoProfile);
break;
}
// Set buffer options
qFormat.setRedBufferSize(format.redBufferSize());
qFormat.setGreenBufferSize(format.greenBufferSize());
qFormat.setBlueBufferSize(format.blueBufferSize());
qFormat.setAlphaBufferSize(format.alphaBufferSize());
qFormat.setDepthBufferSize(format.depthBufferSize());
qFormat.setStencilBufferSize(format.stencilBufferSize());
qFormat.setStereo(format.stereo());
qFormat.setSamples(format.samples());
// Handle swap behavior
switch (format.swapBehavior())
{
case gloperate::GLContextFormat::SwapBehavior::DoubleBuffering:
qFormat.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
break;
case gloperate::GLContextFormat::SwapBehavior::SingleBuffering:
qFormat.setSwapBehavior(QSurfaceFormat::SingleBuffer);
break;
default:
qFormat.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
}
// Return format description
return qFormat;
}
} // namespace gloperate_qt
<commit_msg>Fix compilation for Qt < 5.3<commit_after>
#include <gloperate-qt/base/GLContextFactory.h>
#include <QtGlobal>
#include <QOpenGLContext>
#include <QSurfaceFormat>
#include <cppassist/memory/make_unique.h>
#include <gloperate-qt/base/GLContext.h>
namespace gloperate_qt
{
GLContextFactory::GLContextFactory(QWindow * window)
: m_window(window)
{
}
GLContextFactory::~GLContextFactory()
{
}
std::unique_ptr<gloperate::AbstractGLContext> GLContextFactory::createContext(const gloperate::GLContextFormat & format) const
{
// Create OpenGL context
auto qContext = cppassist::make_unique<QOpenGLContext>();
qContext->setFormat(toQSurfaceFormat(format));
// Create and check context
if (!qContext->create())
{
return nullptr;
}
return cppassist::make_unique<GLContext>(m_window, qContext.release());
}
QSurfaceFormat GLContextFactory::toQSurfaceFormat(const gloperate::GLContextFormat & format)
{
QSurfaceFormat qFormat;
qFormat.setRenderableType(QSurfaceFormat::OpenGL);
// Set OpenGL version
qFormat.setVersion(format.majorVersion(), format.minorVersion());
// Set OpenGL context flags
if (format.version() >= glbinding::Version(3, 0))
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0))
qFormat.setOption(QSurfaceFormat::DeprecatedFunctions, !format.forwardCompatible());
qFormat.setOption(QSurfaceFormat::DebugContext, format.debugContext());
#else
auto options = static_cast<QSurfaceFormat::FormatOptions>(0);
if (!format.forwardCompatible())
{
options |= QSurfaceFormat::DeprecatedFunctions;
}
if (format.debugContext())
{
options |= QSurfaceFormat::DebugContext;
}
qFormat.setOption(options);
#endif
}
// Set OpenGL profile
switch (format.profile())
{
case gloperate::GLContextFormat::Profile::Core:
qFormat.setProfile(QSurfaceFormat::CoreProfile);
break;
case gloperate::GLContextFormat::Profile::Compatibility:
qFormat.setProfile(QSurfaceFormat::CompatibilityProfile);
break;
default:
qFormat.setProfile(QSurfaceFormat::NoProfile);
break;
}
// Set buffer options
qFormat.setRedBufferSize(format.redBufferSize());
qFormat.setGreenBufferSize(format.greenBufferSize());
qFormat.setBlueBufferSize(format.blueBufferSize());
qFormat.setAlphaBufferSize(format.alphaBufferSize());
qFormat.setDepthBufferSize(format.depthBufferSize());
qFormat.setStencilBufferSize(format.stencilBufferSize());
qFormat.setStereo(format.stereo());
qFormat.setSamples(format.samples());
// Handle swap behavior
switch (format.swapBehavior())
{
case gloperate::GLContextFormat::SwapBehavior::DoubleBuffering:
qFormat.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
break;
case gloperate::GLContextFormat::SwapBehavior::SingleBuffering:
qFormat.setSwapBehavior(QSurfaceFormat::SingleBuffer);
break;
default:
qFormat.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
}
// Return format description
return qFormat;
}
} // namespace gloperate_qt
<|endoftext|>
|
<commit_before>// Created by 乔磊 on 2015/8/7.
// Copyright (c) 2015年 乔磊. All rights reserved.
//
#include <NSolver/linearVelocityPotential/linearVelocityPotential.h>
namespace velocityPotential
{
using namespace dealii;
template <int dim>
void LinearVelocityPotential<dim>::transfer_solution (
const FESystem<dim> &fe_NS,
const DoFHandler<dim> &dof_handler_NS,
LA::MPI::Vector &NS_solution) const
{
// Set quadrature points on NS FE supporting points.
// Then extact desired values on these qudrature points.
// If the quadrature points and the supporting points are arranged in
// the same order, then we can loop through all the qudrature points and
// assign corresponding values the NS solution vector.
const FE_Q<dim> &fe_potential = fe;
const DoFHandler<dim> &dof_handler_potential =dof_handler;
const LA::MPI::Vector &potential_solution = locally_relevant_solution;
// Here we assume all Finite Element types are the same in the NS system.
Quadrature<dim> quadrature_on_NS_support_points (fe_NS.base_element (0).get_unit_support_points());
FEValues<dim> fe_values_potential (fe_potential, quadrature_on_NS_support_points,
update_values | update_gradients |
update_quadrature_points);
const unsigned int n_q_points = quadrature_on_NS_support_points.size();
const unsigned int dofs_per_cell = fe_NS.dofs_per_cell;
std::vector<types::global_dof_index> global_indices_of_local_dofs (dofs_per_cell);
std::vector< Tensor<1,dim,double> > potential_grad_on_cell (n_q_points);
// The two DoFHandlers are initialized from the same triangulation
typename DoFHandler<dim>::active_cell_iterator
cell_potential = dof_handler_potential.begin_active(),
cell_NS = dof_handler_NS.begin_active(),
endc_NS = dof_handler_NS.end();
for (; cell_NS!=endc_NS; ++cell_NS, ++cell_potential)
if (cell_NS->is_locally_owned())
{
fe_values_potential.reinit (cell_potential);
fe_values_potential.get_function_gradients (
potential_solution,
potential_grad_on_cell);
cell_NS->get_dof_indices (global_indices_of_local_dofs);
// Since the quadrature is extracted accroding to the target FE supporting
// points, we just have to loop through all the quadrature points.
// We assume that the quadrature points and supporting points are
// arranged in the same order.
for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
{
double Mach_local = 0.0;
for (unsigned d=0; d<dim; ++d)
{
const double velocity =
velocity_infty[d] + potential_grad_on_cell[q_point][d];
Mach_local += velocity * velocity;
const unsigned int system_index = fe_NS.component_to_system_index (d, q_point);
NS_solution[global_indices_of_local_dofs[system_index]] = velocity;
}
const double gas_gamma (1.4);
const double Mach_infty (velocity_infty.square());
const double Mach_ratio =
(1.0 + 0.5* (gas_gamma-1.0) * Mach_infty) /
(1.0 + 0.5* (gas_gamma-1.0) * Mach_local);
{
// Density component
const unsigned int system_index = fe_NS.component_to_system_index (dim, q_point);
NS_solution[global_indices_of_local_dofs[system_index]] =
std::pow (Mach_ratio, 1.0/ (gas_gamma - 1.0));
}
{
//Pressure component
const unsigned int system_index = fe_NS.component_to_system_index (dim+1, q_point);
NS_solution[global_indices_of_local_dofs[system_index]] =
std::pow (Mach_ratio, gas_gamma/ (gas_gamma - 1.0)) / gas_gamma;
}
}
}
}
#include "linearVelocityPotential.inst.in"
}
<commit_msg>add an Assert in loop through triangulation<commit_after>// Created by 乔磊 on 2015/8/7.
// Copyright (c) 2015年 乔磊. All rights reserved.
//
#include <NSolver/linearVelocityPotential/linearVelocityPotential.h>
namespace velocityPotential
{
using namespace dealii;
template <int dim>
void LinearVelocityPotential<dim>::transfer_solution (
const FESystem<dim> &fe_NS,
const DoFHandler<dim> &dof_handler_NS,
LA::MPI::Vector &NS_solution) const
{
// Set quadrature points on NS FE supporting points.
// Then extact desired values on these qudrature points.
// If the quadrature points and the supporting points are arranged in
// the same order, then we can loop through all the qudrature points and
// assign corresponding values the NS solution vector.
const FE_Q<dim> &fe_potential = fe;
const DoFHandler<dim> &dof_handler_potential =dof_handler;
const LA::MPI::Vector &potential_solution = locally_relevant_solution;
// Here we assume all Finite Element types are the same in the NS system.
Quadrature<dim> quadrature_on_NS_support_points (fe_NS.base_element (0).get_unit_support_points());
FEValues<dim> fe_values_potential (fe_potential, quadrature_on_NS_support_points,
update_values | update_gradients |
update_quadrature_points);
const unsigned int n_q_points = quadrature_on_NS_support_points.size();
const unsigned int dofs_per_cell = fe_NS.dofs_per_cell;
std::vector<types::global_dof_index> global_indices_of_local_dofs (dofs_per_cell);
std::vector< Tensor<1,dim,double> > potential_grad_on_cell (n_q_points);
// The two DoFHandlers are initialized from the same triangulation
typename DoFHandler<dim>::active_cell_iterator
cell_potential = dof_handler_potential.begin_active(),
cell_NS = dof_handler_NS.begin_active(),
endc_NS = dof_handler_NS.end();
for (; cell_NS!=endc_NS; ++cell_NS, ++cell_potential)
{
Assert (cell_potential != dof_handler_potential.end(),
ExcMessage ("Reached end of tria for potential equation before NS equation!"));
if (cell_NS->is_locally_owned())
{
fe_values_potential.reinit (cell_potential);
fe_values_potential.get_function_gradients (
potential_solution,
potential_grad_on_cell);
cell_NS->get_dof_indices (global_indices_of_local_dofs);
// Since the quadrature is extracted accroding to the target FE supporting
// points, we just have to loop through all the quadrature points.
// We assume that the quadrature points and supporting points are
// arranged in the same order.
for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
{
double Mach_local = 0.0;
for (unsigned d=0; d<dim; ++d)
{
const double velocity =
velocity_infty[d] + potential_grad_on_cell[q_point][d];
Mach_local += velocity * velocity;
const unsigned int system_index = fe_NS.component_to_system_index (d, q_point);
NS_solution[global_indices_of_local_dofs[system_index]] = velocity;
}
const double gas_gamma (1.4);
const double Mach_infty (velocity_infty.square());
const double Mach_ratio =
(1.0 + 0.5* (gas_gamma-1.0) * Mach_infty) /
(1.0 + 0.5* (gas_gamma-1.0) * Mach_local);
{
// Density component
const unsigned int system_index = fe_NS.component_to_system_index (dim, q_point);
NS_solution[global_indices_of_local_dofs[system_index]] =
std::pow (Mach_ratio, 1.0/ (gas_gamma - 1.0));
}
{
//Pressure component
const unsigned int system_index = fe_NS.component_to_system_index (dim+1, q_point);
NS_solution[global_indices_of_local_dofs[system_index]] =
std::pow (Mach_ratio, gas_gamma/ (gas_gamma - 1.0)) / gas_gamma;
}
}
}
}
}
#include "linearVelocityPotential.inst.in"
}
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file eegref.cpp
* @author Viktor Klüber <[email protected]>;
* Lorenz Esch <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date January, 2017
*
* @section LICENSE
*
* Copyright (C) 2017, Viktor Klüber, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief EEGRef class definition.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "eegref.h"
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <Eigen/Dense>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace REFERENCEPLUGIN;
using namespace Eigen;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
EEGRef::EEGRef()
{
}
//*************************************************************************************************************
MatrixXd EEGRef::applyCAR(MatrixXd &matIER, FIFFLIB::FiffInfo::SPtr &pFiffInfo)
{
unsigned int numTrueCh = 0;
unsigned int numCh = pFiffInfo->chs.size();
MatrixXd matOnes = MatrixXd::Ones(numCh, numCh);
MatrixXd matCenter = MatrixXd::Identity(numCh, numCh);
//determine the number of true channels
for(unsigned int i = 0; i < numCh; ++i)
{
if(pFiffInfo->chs.at(i).ch_name.contains("EEG") && !pFiffInfo->bads.contains(pFiffInfo->chs.at(i).ch_name))
{
numTrueCh++;
}
else
{
// excluding non-EEG channels from the centering matrix
matOnes.row(i).setZero();
matOnes.col(i).setZero();
matCenter.row(i).setZero();
matCenter.col(i).setZero();
}
}
//detrmine centering matrix
matCenter = matCenter - (1/double(numTrueCh))*matOnes;
// determine EEG CAR data matrix
MatrixXd matCAR = matCenter*matIER;
//add former excluded non-EEG channels to the EEG CAR data matrix
for(unsigned int i = 0; i < numCh; ++i)
{
if(!pFiffInfo->chs.at(i).ch_name.contains("EEG"))
{
matCAR.row(i) = matIER.row(i);
}
}
return matCAR;
}
<commit_msg>added check for numTrueCh if matrix is of size 0 to avoid dividing by 0 -- cov175338<commit_after>//=============================================================================================================
/**
* @file eegref.cpp
* @author Viktor Klüber <[email protected]>;
* Lorenz Esch <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date January, 2017
*
* @section LICENSE
*
* Copyright (C) 2017, Viktor Klüber, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief EEGRef class definition.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "eegref.h"
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <Eigen/Dense>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace REFERENCEPLUGIN;
using namespace Eigen;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
EEGRef::EEGRef()
{
}
//*************************************************************************************************************
MatrixXd EEGRef::applyCAR(MatrixXd &matIER, FIFFLIB::FiffInfo::SPtr &pFiffInfo)
{
unsigned int numTrueCh = 0;
unsigned int numCh = pFiffInfo->chs.size();
MatrixXd matOnes = MatrixXd::Ones(numCh, numCh);
MatrixXd matCenter = MatrixXd::Identity(numCh, numCh);
//determine the number of true channels
for(unsigned int i = 0; i < numCh; ++i)
{
if(pFiffInfo->chs.at(i).ch_name.contains("EEG") && !pFiffInfo->bads.contains(pFiffInfo->chs.at(i).ch_name))
{
numTrueCh++;
}
else
{
// excluding non-EEG channels from the centering matrix
matOnes.row(i).setZero();
matOnes.col(i).setZero();
matCenter.row(i).setZero();
matCenter.col(i).setZero();
}
}
//detrmine centering matrix
if (numTrueCh != 0){
matCenter = matCenter - (1/double(numTrueCh))*matOnes;
} else {
qDebug() << "Unable to determine centering matrix";
}
// determine EEG CAR data matrix
MatrixXd matCAR = matCenter*matIER;
//add former excluded non-EEG channels to the EEG CAR data matrix
for(unsigned int i = 0; i < numCh; ++i)
{
if(!pFiffInfo->chs.at(i).ch_name.contains("EEG"))
{
matCAR.row(i) = matIER.row(i);
}
}
return matCAR;
}
<|endoftext|>
|
<commit_before>//Eric is sleeping
#include "PivotKick.hpp"
#include <Utils.hpp>
using namespace std;
using namespace Geometry2d;
namespace Gameplay
{
namespace Behaviors
{
REGISTER_CONFIGURABLE(PivotKick)
}
}
ConfigDouble *Gameplay::Behaviors::PivotKick::_aim_Speed;
ConfigDouble *Gameplay::Behaviors::PivotKick::_kick_Completed_Threshold;
ConfigDouble *Gameplay::Behaviors::PivotKick::_initial_Accuracy;
ConfigDouble *Gameplay::Behaviors::PivotKick::_accuracy_Delta;
ConfigDouble *Gameplay::Behaviors::PivotKick::_fireNowThreshold;
ConfigDouble *Gameplay::Behaviors::PivotKick::_a0;
ConfigDouble *Gameplay::Behaviors::PivotKick::_a1;
ConfigDouble *Gameplay::Behaviors::PivotKick::_a2;
ConfigDouble *Gameplay::Behaviors::PivotKick::_a3;
ConfigDouble *Gameplay::Behaviors::PivotKick::_dribble_speed;
void Gameplay::Behaviors::PivotKick::createConfiguration(Configuration* cfg)
{
_aim_Speed = new ConfigDouble(cfg, "PivotKick/Aim Speed", 0.5 * M_PI);
_kick_Completed_Threshold = new ConfigDouble(cfg, "PivotKick/Kick Completed Threshold", 0.5);
_initial_Accuracy = new ConfigDouble(cfg, "PivotKick/Initial Accuracy", cos(10 * DegreesToRadians));
_accuracy_Delta = new ConfigDouble(cfg, "PivotKick/Accuracy Delta", 0.000);
_fireNowThreshold = new ConfigDouble(cfg, "PivotKick/Fire Now Threshold", cos(3 * DegreesToRadians));
_a0 = new ConfigDouble(cfg, "PivotKick/_a0", -78.3635);
_a1 = new ConfigDouble(cfg, "PivotKick/_a0", 3.30802);
_a2 = new ConfigDouble(cfg, "PivotKick/_a0", -0.0238479);
_a3 = new ConfigDouble(cfg, "PivotKick/_a0", 0.000613888);
_dribble_speed = new ConfigDouble(cfg, "PivotKick/Dribble Speed", 40);
}
Gameplay::Behaviors::PivotKick::PivotKick(GameplayModule *gameplay):
SingleRobotBehavior(gameplay), _capture(gameplay)
{
restart();
target.pt[0] = Point(Field_GoalWidth / 2, Field_Length);
target.pt[1] = Point(-Field_GoalWidth / 2, Field_Length);
_capture.target = target.pt[0];
}
void Gameplay::Behaviors::PivotKick::restart()
{
_state = State_Capture;
_kicked = false;
_ccw = true;
_capture.restart();
_capture.target = target.pt[0];
enable_kick = true;
enable_desparate_kick = true;
dribble_speed = 50;
use_chipper = false;
kick_power = 255;
}
uint8_t Gameplay::Behaviors::PivotKick::compute_kickpower(double dist)
{
double a0 = *_a0;
double a1 = *_a1;
double a2 = *_a2;
double a3 = *_a3;
double x = dist*(dist*(dist*(a3) + a2) + a1) + a0;
int kickpower = std::min(std::max(x, 0), 255);
return kickpower;
}
bool Gameplay::Behaviors::PivotKick::run()
{
if (!robot || !robot->visible)
{
return false;
}
// force sub-behavior to have its robot assigned
_capture.robot = robot;
// The direction we're facing
const Point dir = Point::direction(robot->angle * DegreesToRadians);
uint64_t now = timestamp();
// track kick time
if ( _state != State_Aim ) {
_lastKickTime = robot->lastKickTime();
}
// State changes
Point toBall = (ball().pos - robot->pos).normalized();
if (_state == State_Capture)
{
kick_ready = false;
if (_capture.done())
{
_state = State_Aim;
_lastError = 0;
_lastDelta = 0;
_ccw = ((target.pt[0] - ball().pos).cross(target.pt[1] - ball().pos) > 0);
}
_accuracy = *_initial_Accuracy;
} else if (_state == State_Aim)
{
// _lastBallTime is the last time we had the ball
if (robot->hasBall())
{
_lastBallTime = now;
}
// watch for ball leaving the robot
if ((!robot->hasBall() && (state()->timestamp - _lastBallTime) > 500000) || !ball().pos.nearPoint(robot->pos, *_kick_Completed_Threshold))
//if ( robot->lastKickTime() > _lastKickTime )
{
if (_kicked)
{
_state = State_Done;
} else {
_state = State_Capture;
_capture.restart();
}
}
}
state()->drawLine(ball().pos, target.pt[0], Qt::red);
state()->drawLine(ball().pos, target.pt[1], Qt::black);
state()->drawLine(target, Qt::yellow);
// Driving
if (_state == State_Capture)
{
robot->addText("Capturing");
_capture.target = target.pt[0];
_capture.run();
} else if (_state == State_Aim)
{
state()->drawLine(robot->pos, robot->pos + dir * 8, Qt::white);
state()->drawLine(ball().pos, target.center(), Qt::yellow);
state()->drawLine(robot->pos, (ball().pos - robot->pos).normalized() * 8, Qt::green);
// See if it's time to kick
float error = dir.dot((target.center() - ball().pos).normalized());
float delta = error - _lastError;
if ((error >= *_fireNowThreshold || (error >= _accuracy && _lastDelta > 0 && delta <= 0)))
{
if(enable_kick)
{
if (use_chipper)
{
robot->chip(kick_power);
robot->addText("CHIP");
} else
{
robot->kick(kick_power);
robot->addText("KICK");
}
_kicked = true;
}
kick_ready = true;
} else {
robot->addText("Aim");
kick_ready = false;
}
_lastError = error;
_lastDelta = delta;
// Decide which direction to rotate around the ball
Point rb = ball().pos - robot->pos;
if (rb.cross(target.pt[0] - ball().pos) > 0)
{
_ccw = true;
} else if ((target.pt[1] - ball().pos).cross(rb) > 0)
{
_ccw = false;
}
robot->addText(QString("Aim %1 %2 %3 %4").arg(
QString::number(acos(error) * RadiansToDegrees),
QString::number(delta),
QString::number(_accuracy),
QString::number(_ccw ? 1 : 0)));
_accuracy -= *_accuracy_Delta;
_accuracy = max(0.0f, _accuracy);
robot->pivot(*_aim_Speed * (_ccw ? 1 : -1), ball().pos);
robot->dribble(dribble_speed);
} else {
robot->addText("Done");
return false;
}
return true;
}
<commit_msg>Fix compilation error in PivotKick<commit_after>//Eric is sleeping
#include "PivotKick.hpp"
#include <Utils.hpp>
using namespace std;
using namespace Geometry2d;
namespace Gameplay
{
namespace Behaviors
{
REGISTER_CONFIGURABLE(PivotKick)
}
}
ConfigDouble *Gameplay::Behaviors::PivotKick::_aim_Speed;
ConfigDouble *Gameplay::Behaviors::PivotKick::_kick_Completed_Threshold;
ConfigDouble *Gameplay::Behaviors::PivotKick::_initial_Accuracy;
ConfigDouble *Gameplay::Behaviors::PivotKick::_accuracy_Delta;
ConfigDouble *Gameplay::Behaviors::PivotKick::_fireNowThreshold;
ConfigDouble *Gameplay::Behaviors::PivotKick::_a0;
ConfigDouble *Gameplay::Behaviors::PivotKick::_a1;
ConfigDouble *Gameplay::Behaviors::PivotKick::_a2;
ConfigDouble *Gameplay::Behaviors::PivotKick::_a3;
ConfigDouble *Gameplay::Behaviors::PivotKick::_dribble_speed;
void Gameplay::Behaviors::PivotKick::createConfiguration(Configuration* cfg)
{
_aim_Speed = new ConfigDouble(cfg, "PivotKick/Aim Speed", 0.5 * M_PI);
_kick_Completed_Threshold = new ConfigDouble(cfg, "PivotKick/Kick Completed Threshold", 0.5);
_initial_Accuracy = new ConfigDouble(cfg, "PivotKick/Initial Accuracy", cos(10 * DegreesToRadians));
_accuracy_Delta = new ConfigDouble(cfg, "PivotKick/Accuracy Delta", 0.000);
_fireNowThreshold = new ConfigDouble(cfg, "PivotKick/Fire Now Threshold", cos(3 * DegreesToRadians));
_a0 = new ConfigDouble(cfg, "PivotKick/_a0", -78.3635);
_a1 = new ConfigDouble(cfg, "PivotKick/_a0", 3.30802);
_a2 = new ConfigDouble(cfg, "PivotKick/_a0", -0.0238479);
_a3 = new ConfigDouble(cfg, "PivotKick/_a0", 0.000613888);
_dribble_speed = new ConfigDouble(cfg, "PivotKick/Dribble Speed", 40);
}
Gameplay::Behaviors::PivotKick::PivotKick(GameplayModule *gameplay):
SingleRobotBehavior(gameplay), _capture(gameplay)
{
restart();
target.pt[0] = Point(Field_GoalWidth / 2, Field_Length);
target.pt[1] = Point(-Field_GoalWidth / 2, Field_Length);
_capture.target = target.pt[0];
}
void Gameplay::Behaviors::PivotKick::restart()
{
_state = State_Capture;
_kicked = false;
_ccw = true;
_capture.restart();
_capture.target = target.pt[0];
enable_kick = true;
enable_desparate_kick = true;
dribble_speed = 50;
use_chipper = false;
kick_power = 255;
}
uint8_t Gameplay::Behaviors::PivotKick::compute_kickpower(double dist)
{
double a0 = *_a0;
double a1 = *_a1;
double a2 = *_a2;
double a3 = *_a3;
double x = dist*(dist*(dist*(a3) + a2) + a1) + a0;
int kickpower = std::min(std::max((int)x, 0), 255);
return kickpower;
}
bool Gameplay::Behaviors::PivotKick::run()
{
if (!robot || !robot->visible)
{
return false;
}
// force sub-behavior to have its robot assigned
_capture.robot = robot;
// The direction we're facing
const Point dir = Point::direction(robot->angle * DegreesToRadians);
uint64_t now = timestamp();
// track kick time
if ( _state != State_Aim ) {
_lastKickTime = robot->lastKickTime();
}
// State changes
Point toBall = (ball().pos - robot->pos).normalized();
if (_state == State_Capture)
{
kick_ready = false;
if (_capture.done())
{
_state = State_Aim;
_lastError = 0;
_lastDelta = 0;
_ccw = ((target.pt[0] - ball().pos).cross(target.pt[1] - ball().pos) > 0);
}
_accuracy = *_initial_Accuracy;
} else if (_state == State_Aim)
{
// _lastBallTime is the last time we had the ball
if (robot->hasBall())
{
_lastBallTime = now;
}
// watch for ball leaving the robot
if ((!robot->hasBall() && (state()->timestamp - _lastBallTime) > 500000) || !ball().pos.nearPoint(robot->pos, *_kick_Completed_Threshold))
//if ( robot->lastKickTime() > _lastKickTime )
{
if (_kicked)
{
_state = State_Done;
} else {
_state = State_Capture;
_capture.restart();
}
}
}
state()->drawLine(ball().pos, target.pt[0], Qt::red);
state()->drawLine(ball().pos, target.pt[1], Qt::black);
state()->drawLine(target, Qt::yellow);
// Driving
if (_state == State_Capture)
{
robot->addText("Capturing");
_capture.target = target.pt[0];
_capture.run();
} else if (_state == State_Aim)
{
state()->drawLine(robot->pos, robot->pos + dir * 8, Qt::white);
state()->drawLine(ball().pos, target.center(), Qt::yellow);
state()->drawLine(robot->pos, (ball().pos - robot->pos).normalized() * 8, Qt::green);
// See if it's time to kick
float error = dir.dot((target.center() - ball().pos).normalized());
float delta = error - _lastError;
if ((error >= *_fireNowThreshold || (error >= _accuracy && _lastDelta > 0 && delta <= 0)))
{
if(enable_kick)
{
if (use_chipper)
{
robot->chip(kick_power);
robot->addText("CHIP");
} else
{
robot->kick(kick_power);
robot->addText("KICK");
}
_kicked = true;
}
kick_ready = true;
} else {
robot->addText("Aim");
kick_ready = false;
}
_lastError = error;
_lastDelta = delta;
// Decide which direction to rotate around the ball
Point rb = ball().pos - robot->pos;
if (rb.cross(target.pt[0] - ball().pos) > 0)
{
_ccw = true;
} else if ((target.pt[1] - ball().pos).cross(rb) > 0)
{
_ccw = false;
}
robot->addText(QString("Aim %1 %2 %3 %4").arg(
QString::number(acos(error) * RadiansToDegrees),
QString::number(delta),
QString::number(_accuracy),
QString::number(_ccw ? 1 : 0)));
_accuracy -= *_accuracy_Delta;
_accuracy = max(0.0f, _accuracy);
robot->pivot(*_aim_Speed * (_ccw ? 1 : -1), ball().pos);
robot->dribble(dribble_speed);
} else {
robot->addText("Done");
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>
#include <yuni/yuni.h>
#include <yuni/core/string.h>
#include <yuni/io/file.h>
#include <yuni/core/getopt.h>
#include <yuni/core/logs.h>
#include <yuni/parser/peg/grammar.h>
#include <yuni/core/variant.h>
using namespace Yuni;
//! logger
static Yuni::Logs::Logger<> logs;
class Settings final
{
public:
enum Format
{
sfCPP,
};
public:
Settings() :
format(sfCPP)
{}
public:
//! All filenames
String::Vector filenames;
//! Namespace
String namespaceName;
//! Export format
Format format;
}; // class Settings
static void ParseWarning(const AnyString& message)
{
logs.warning() << message;
}
static void ParseError(const AnyString& message)
{
logs.error() << message;
}
static inline void ParseCommandLine(int argc, char** argv, Settings& settings)
{
GetOpt::Parser options;
String::Vector optFilenames;
ShortString16 format;
options.add(optFilenames, 'i', "input", "The input grammar");
options.add(settings.namespaceName, 'n', "namespace", "The target namespace (mandatory)");
options.add(format, 'f', "format", "Output format [cpp]");
options.remainingArguments(optFilenames);
if (not options(argc, argv))
{
if (options.errors())
{
std::cout << "Abort due to error" << std::endl;
exit(EXIT_FAILURE);
}
exit(0);
}
if (optFilenames.empty())
{
logs.error() << "please provide a grammar file";
exit(EXIT_FAILURE);
}
settings.namespaceName.trim(" \t\r\n.:");
if (settings.namespaceName.empty())
{
logs.error() << "no namespace provided";
exit(EXIT_FAILURE);
}
format.trim();
format.toLower();
if (format == "cpp")
{
settings.format = Settings::sfCPP;
}
else
{
logs.error() << "invalid output format";
exit(EXIT_FAILURE);
}
settings.filenames.resize((uint) optFilenames.size());
for (uint i = 0; i != (uint) optFilenames.size(); ++i)
IO::Canonicalize(settings.filenames[i], optFilenames[i]);
}
#include <yuni/uuid/uuid.h>
#include <map>
int main(int argc, char** argv)
{
// All settings
Settings settings;
// arguments parsing
ParseCommandLine(argc, argv, settings);
Parser::PEG::Grammar grammar;
grammar.onWarning.connect(& ParseWarning);
grammar.onError.connect(& ParseError);
bool hasError = false;
String output;
for (uint i = 0; i != (uint) settings.filenames.size(); ++i)
{
const String& url = settings.filenames[i];
if (not IO::File::Exists(url))
{
logs.error() << "io error: \"" << url << "\" not found";
hasError = true;
continue;
}
if (grammar.loadFromFile(url))
{
//std::cout << grammar << std::endl;
output = url;
IO::ReplaceExtension(output, ".");
switch (settings.format)
{
case Settings::sfCPP:
{
logs.info() << "generating c++ parser from " << url;
grammar.exportToCPP(output, settings.namespaceName);
break;
}
}
}
else
{
logs.error() << "impossible to load the grammar " << url;
hasError = true;
}
}
return (not hasError) ? 0 : EXIT_FAILURE;
}
<commit_msg>parser generator: invalid return status when an error occurs<commit_after>
#include <yuni/yuni.h>
#include <yuni/core/string.h>
#include <yuni/io/file.h>
#include <yuni/core/getopt.h>
#include <yuni/core/logs.h>
#include <yuni/parser/peg/grammar.h>
#include <yuni/core/variant.h>
using namespace Yuni;
//! logger
static Yuni::Logs::Logger<> logs;
class Settings final
{
public:
enum Format
{
sfCPP,
};
public:
Settings() :
format(sfCPP)
{}
public:
//! All filenames
String::Vector filenames;
//! Namespace
String namespaceName;
//! Export format
Format format;
}; // class Settings
static bool hasError = false;
static void ParseWarning(const AnyString& message)
{
logs.warning() << message;
}
static void ParseError(const AnyString& message)
{
logs.error() << message;
hasError = true;
}
static inline void ParseCommandLine(int argc, char** argv, Settings& settings)
{
GetOpt::Parser options;
String::Vector optFilenames;
ShortString16 format;
options.add(optFilenames, 'i', "input", "The input grammar");
options.add(settings.namespaceName, 'n', "namespace", "The target namespace (mandatory)");
options.add(format, 'f', "format", "Output format [cpp]");
options.remainingArguments(optFilenames);
if (not options(argc, argv))
{
if (options.errors())
{
std::cout << "Abort due to error" << std::endl;
exit(EXIT_FAILURE);
}
exit(0);
}
if (optFilenames.empty())
{
logs.error() << "please provide a grammar file";
exit(EXIT_FAILURE);
}
settings.namespaceName.trim(" \t\r\n.:");
if (settings.namespaceName.empty())
{
logs.error() << "no namespace provided";
exit(EXIT_FAILURE);
}
format.trim();
format.toLower();
if (format == "cpp")
{
settings.format = Settings::sfCPP;
}
else
{
logs.error() << "invalid output format";
exit(EXIT_FAILURE);
}
settings.filenames.resize((uint) optFilenames.size());
for (uint i = 0; i != (uint) optFilenames.size(); ++i)
IO::Canonicalize(settings.filenames[i], optFilenames[i]);
}
#include <yuni/uuid/uuid.h>
#include <map>
int main(int argc, char** argv)
{
// All settings
Settings settings;
// arguments parsing
ParseCommandLine(argc, argv, settings);
Parser::PEG::Grammar grammar;
grammar.onWarning.connect(& ParseWarning);
grammar.onError.connect(& ParseError);
String output;
for (uint i = 0; i != (uint) settings.filenames.size(); ++i)
{
const String& url = settings.filenames[i];
if (not IO::File::Exists(url))
{
logs.error() << "error: \"" << url << "\" file not found";
hasError = true;
continue;
}
if (grammar.loadFromFile(url))
{
//std::cout << grammar << std::endl;
output = url;
IO::ReplaceExtension(output, ".");
switch (settings.format)
{
case Settings::sfCPP:
{
logs.info() << "generating c++ parser from " << url;
grammar.exportToCPP(output, settings.namespaceName);
break;
}
}
}
else
{
logs.error() << "impossible to load the grammar " << url;
hasError = true;
}
}
return (not hasError) ? 0 : EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EnhancedCustomShapeEngine.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:25:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#define _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#ifndef __RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STACK_HXX
#include <tools/stack.hxx>
#endif
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef __com_sun_star_awt_Rectangle_hpp_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONBEZIERCOORDS_HPP_
#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XCUSTOMSHAPEENGINE_HPP_
#include <com/sun/star/drawing/XCustomShapeEngine.hpp>
#endif
// -----------------------------------------------------------------------------
#define NMSP_IO com::sun::star::io
#define NMSP_UNO com::sun::star::uno
#define NMSP_BEANS com::sun::star::beans
#define NMSP_LANG com::sun::star::lang
#define NMSP_UTIL com::sun::star::util
#define NMSP_SAX com::sun::star::xml::sax
#define NMSP_LOGGING NMSP_UTIL::logging
#define REF( _def_Obj ) NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj ) NMSP_UNO::Sequence< _def_Obj >
#define B2UCONST( _def_pChar ) (rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))
// ---------------------------
// - EnhancedCustomShapeEngine -
// ---------------------------
//
class SdrObject;
class SdrObjCustomShape;
class EnhancedCustomShapeEngine : public cppu::WeakImplHelper3
<
com::sun::star::lang::XInitialization,
com::sun::star::lang::XServiceInfo,
com::sun::star::drawing::XCustomShapeEngine
>
{
REF( NMSP_LANG::XMultiServiceFactory ) mxFact;
REF( com::sun::star::drawing::XShape ) mxShape;
sal_Bool mbForceGroupWithText;
SdrObject* ImplForceGroupWithText( const SdrObjCustomShape* pCustoObj, SdrObject* pRenderedShape );
public:
EnhancedCustomShapeEngine( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr );
virtual ~EnhancedCustomShapeEngine();
// XInterface
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XInitialization
virtual void SAL_CALL initialize( const SEQ( NMSP_UNO::Any )& aArguments )
throw ( NMSP_UNO::Exception, NMSP_UNO::RuntimeException );
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName()
throw ( NMSP_UNO::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& rServiceName )
throw ( NMSP_UNO::RuntimeException );
virtual SEQ( rtl::OUString ) SAL_CALL getSupportedServiceNames()
throw ( NMSP_UNO::RuntimeException );
// XCustomShapeEngine
virtual REF( com::sun::star::drawing::XShape ) SAL_CALL render()
throw ( NMSP_UNO::RuntimeException );
virtual com::sun::star::awt::Rectangle SAL_CALL getTextBounds()
throw ( NMSP_UNO::RuntimeException );
virtual com::sun::star::drawing::PolyPolygonBezierCoords SAL_CALL getLineGeometry()
throw ( NMSP_UNO::RuntimeException );
virtual SEQ( REF( com::sun::star::drawing::XCustomShapeHandle ) ) SAL_CALL getInteraction()
throw ( NMSP_UNO::RuntimeException );
};
rtl::OUString EnhancedCustomShapeEngine_getImplementationName()
throw ( NMSP_UNO::RuntimeException );
sal_Bool SAL_CALL EnhancedCustomShapeEngine_supportsService( const rtl::OUString& rServiceName )
throw( NMSP_UNO::RuntimeException );
SEQ( rtl::OUString ) SAL_CALL EnhancedCustomShapeEngine_getSupportedServiceNames()
throw( NMSP_UNO::RuntimeException );
#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.5.222); FILE MERGED 2006/03/10 14:33:16 cl 1.5.222.1: removed some warnings, mostly shadowed variables<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EnhancedCustomShapeEngine.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 14:56:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#define _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STACK_HXX
#include <tools/stack.hxx>
#endif
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef __com_sun_star_awt_Rectangle_hpp_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONBEZIERCOORDS_HPP_
#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XCUSTOMSHAPEENGINE_HPP_
#include <com/sun/star/drawing/XCustomShapeEngine.hpp>
#endif
// -----------------------------------------------------------------------------
#define NMSP_IO com::sun::star::io
#define NMSP_UNO com::sun::star::uno
#define NMSP_BEANS com::sun::star::beans
#define NMSP_LANG com::sun::star::lang
#define NMSP_UTIL com::sun::star::util
#define NMSP_SAX com::sun::star::xml::sax
#define NMSP_LOGGING NMSP_UTIL::logging
#define REF( _def_Obj ) NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj ) NMSP_UNO::Sequence< _def_Obj >
#define B2UCONST( _def_pChar ) (rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))
// ---------------------------
// - EnhancedCustomShapeEngine -
// ---------------------------
//
class SdrObject;
class SdrObjCustomShape;
class EnhancedCustomShapeEngine : public cppu::WeakImplHelper3
<
com::sun::star::lang::XInitialization,
com::sun::star::lang::XServiceInfo,
com::sun::star::drawing::XCustomShapeEngine
>
{
REF( NMSP_LANG::XMultiServiceFactory ) mxFact;
REF( com::sun::star::drawing::XShape ) mxShape;
sal_Bool mbForceGroupWithText;
SdrObject* ImplForceGroupWithText( const SdrObjCustomShape* pCustoObj, SdrObject* pRenderedShape );
public:
EnhancedCustomShapeEngine( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr );
virtual ~EnhancedCustomShapeEngine();
// XInterface
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XInitialization
virtual void SAL_CALL initialize( const SEQ( NMSP_UNO::Any )& aArguments )
throw ( NMSP_UNO::Exception, NMSP_UNO::RuntimeException );
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName()
throw ( NMSP_UNO::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& rServiceName )
throw ( NMSP_UNO::RuntimeException );
virtual SEQ( rtl::OUString ) SAL_CALL getSupportedServiceNames()
throw ( NMSP_UNO::RuntimeException );
// XCustomShapeEngine
virtual REF( com::sun::star::drawing::XShape ) SAL_CALL render()
throw ( NMSP_UNO::RuntimeException );
virtual com::sun::star::awt::Rectangle SAL_CALL getTextBounds()
throw ( NMSP_UNO::RuntimeException );
virtual com::sun::star::drawing::PolyPolygonBezierCoords SAL_CALL getLineGeometry()
throw ( NMSP_UNO::RuntimeException );
virtual SEQ( REF( com::sun::star::drawing::XCustomShapeHandle ) ) SAL_CALL getInteraction()
throw ( NMSP_UNO::RuntimeException );
};
rtl::OUString EnhancedCustomShapeEngine_getImplementationName()
throw ( NMSP_UNO::RuntimeException );
sal_Bool SAL_CALL EnhancedCustomShapeEngine_supportsService( const rtl::OUString& rServiceName )
throw( NMSP_UNO::RuntimeException );
SEQ( rtl::OUString ) SAL_CALL EnhancedCustomShapeEngine_getSupportedServiceNames()
throw( NMSP_UNO::RuntimeException );
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <string>
#include "gflags/gflags.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/common_audio/channel_buffer.h"
#include "webrtc/common_audio/wav_file.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/modules/audio_processing/test/audio_file_processor.h"
#include "webrtc/modules/audio_processing/test/protobuf_utils.h"
#include "webrtc/modules/audio_processing/test/test_utils.h"
#include "webrtc/system_wrappers/include/tick_util.h"
#include "webrtc/test/testsupport/trace_to_stderr.h"
DEFINE_string(dump, "", "Name of the aecdump debug file to read from.");
DEFINE_string(i, "", "Name of the capture input stream file to read from.");
DEFINE_string(
o,
"out.wav",
"Name of the output file to write the processed capture stream to.");
DEFINE_int32(out_channels, 1, "Number of output channels.");
DEFINE_int32(out_sample_rate, 48000, "Output sample rate in Hz.");
DEFINE_string(mic_positions, "",
"Space delimited cartesian coordinates of microphones in meters. "
"The coordinates of each point are contiguous. "
"For a two element array: \"x1 y1 z1 x2 y2 z2\"");
DEFINE_double(
target_angle_degrees,
90,
"The azimuth of the target in degrees. Only applies to beamforming.");
DEFINE_bool(aec, false, "Enable echo cancellation.");
DEFINE_bool(agc, false, "Enable automatic gain control.");
DEFINE_bool(hpf, false, "Enable high-pass filtering.");
DEFINE_bool(ns, false, "Enable noise suppression.");
DEFINE_bool(ts, false, "Enable transient suppression.");
DEFINE_bool(bf, false, "Enable beamforming.");
DEFINE_bool(ie, false, "Enable intelligibility enhancer.");
DEFINE_bool(all, false, "Enable all components.");
DEFINE_int32(ns_level, -1, "Noise suppression level [0 - 3].");
DEFINE_bool(perf, false, "Enable performance tests.");
namespace webrtc {
namespace {
const int kChunksPerSecond = 100;
const char kUsage[] =
"Command-line tool to run audio processing on WAV files. Accepts either\n"
"an input capture WAV file or protobuf debug dump and writes to an output\n"
"WAV file.\n"
"\n"
"All components are disabled by default. If any bi-directional components\n"
"are enabled, only debug dump files are permitted.";
} // namespace
int main(int argc, char* argv[]) {
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (!((FLAGS_i.empty()) ^ (FLAGS_dump.empty()))) {
fprintf(stderr,
"An input file must be specified with either -i or -dump.\n");
return 1;
}
if (FLAGS_dump.empty() && (FLAGS_aec || FLAGS_ie)) {
fprintf(stderr, "-aec and -ie require a -dump file.\n");
return 1;
}
if (FLAGS_ie) {
fprintf(stderr,
"FIXME(ajm): The intelligibility enhancer output is not dumped.\n");
return 1;
}
test::TraceToStderr trace_to_stderr(true);
Config config;
if (FLAGS_bf || FLAGS_all) {
if (FLAGS_mic_positions.empty()) {
fprintf(stderr, "-mic_positions must be specified when -bf is used.\n");
return 1;
}
config.Set<Beamforming>(new Beamforming(
true, ParseArrayGeometry(FLAGS_mic_positions),
SphericalPointf(DegreesToRadians(FLAGS_target_angle_degrees), 0.f,
1.f)));
}
config.Set<ExperimentalNs>(new ExperimentalNs(FLAGS_ts || FLAGS_all));
config.Set<Intelligibility>(new Intelligibility(FLAGS_ie || FLAGS_all));
rtc::scoped_ptr<AudioProcessing> ap(AudioProcessing::Create(config));
RTC_CHECK_EQ(kNoErr, ap->echo_cancellation()->Enable(FLAGS_aec || FLAGS_all));
RTC_CHECK_EQ(kNoErr, ap->gain_control()->Enable(FLAGS_agc || FLAGS_all));
RTC_CHECK_EQ(kNoErr, ap->high_pass_filter()->Enable(FLAGS_hpf || FLAGS_all));
RTC_CHECK_EQ(kNoErr, ap->noise_suppression()->Enable(FLAGS_ns || FLAGS_all));
if (FLAGS_ns_level != -1) {
RTC_CHECK_EQ(kNoErr,
ap->noise_suppression()->set_level(
static_cast<NoiseSuppression::Level>(FLAGS_ns_level)));
}
rtc::scoped_ptr<AudioFileProcessor> processor;
auto out_file = rtc_make_scoped_ptr(
new WavWriter(FLAGS_o, FLAGS_out_sample_rate, FLAGS_out_channels));
std::cout << FLAGS_o << ": " << out_file->FormatAsString() << std::endl;
if (FLAGS_dump.empty()) {
auto in_file = rtc_make_scoped_ptr(new WavReader(FLAGS_i));
std::cout << FLAGS_i << ": " << in_file->FormatAsString() << std::endl;
processor.reset(
new WavFileProcessor(ap.Pass(), in_file.Pass(), out_file.Pass()));
} else {
processor.reset(new AecDumpFileProcessor(
ap.Pass(), fopen(FLAGS_dump.c_str(), "rb"), out_file.Pass()));
}
int num_chunks = 0;
while (processor->ProcessChunk()) {
trace_to_stderr.SetTimeSeconds(num_chunks * 1.f / kChunksPerSecond);
++num_chunks;
}
if (FLAGS_perf) {
const auto& proc_time = processor->proc_time();
int64_t exec_time_us = proc_time.sum.Microseconds();
printf(
"\nExecution time: %.3f s, File time: %.2f s\n"
"Time per chunk (mean, max, min):\n%.0f us, %.0f us, %.0f us\n",
exec_time_us * 1e-6, num_chunks * 1.f / kChunksPerSecond,
exec_time_us * 1.f / num_chunks, 1.f * proc_time.max.Microseconds(),
1.f * proc_time.min.Microseconds());
}
return 0;
}
} // namespace webrtc
int main(int argc, char* argv[]) {
return webrtc::main(argc, argv);
}
<commit_msg>Fix TransientSuppression in audioproc_float<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <string>
#include "gflags/gflags.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/common_audio/channel_buffer.h"
#include "webrtc/common_audio/wav_file.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/modules/audio_processing/test/audio_file_processor.h"
#include "webrtc/modules/audio_processing/test/protobuf_utils.h"
#include "webrtc/modules/audio_processing/test/test_utils.h"
#include "webrtc/system_wrappers/include/tick_util.h"
#include "webrtc/test/testsupport/trace_to_stderr.h"
DEFINE_string(dump, "", "Name of the aecdump debug file to read from.");
DEFINE_string(i, "", "Name of the capture input stream file to read from.");
DEFINE_string(
o,
"out.wav",
"Name of the output file to write the processed capture stream to.");
DEFINE_int32(out_channels, 1, "Number of output channels.");
DEFINE_int32(out_sample_rate, 48000, "Output sample rate in Hz.");
DEFINE_string(mic_positions, "",
"Space delimited cartesian coordinates of microphones in meters. "
"The coordinates of each point are contiguous. "
"For a two element array: \"x1 y1 z1 x2 y2 z2\"");
DEFINE_double(
target_angle_degrees,
90,
"The azimuth of the target in degrees. Only applies to beamforming.");
DEFINE_bool(aec, false, "Enable echo cancellation.");
DEFINE_bool(agc, false, "Enable automatic gain control.");
DEFINE_bool(hpf, false, "Enable high-pass filtering.");
DEFINE_bool(ns, false, "Enable noise suppression.");
DEFINE_bool(ts, false, "Enable transient suppression.");
DEFINE_bool(bf, false, "Enable beamforming.");
DEFINE_bool(ie, false, "Enable intelligibility enhancer.");
DEFINE_bool(all, false, "Enable all components.");
DEFINE_int32(ns_level, -1, "Noise suppression level [0 - 3].");
DEFINE_bool(perf, false, "Enable performance tests.");
namespace webrtc {
namespace {
const int kChunksPerSecond = 100;
const char kUsage[] =
"Command-line tool to run audio processing on WAV files. Accepts either\n"
"an input capture WAV file or protobuf debug dump and writes to an output\n"
"WAV file.\n"
"\n"
"All components are disabled by default. If any bi-directional components\n"
"are enabled, only debug dump files are permitted.";
} // namespace
int main(int argc, char* argv[]) {
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (!((FLAGS_i.empty()) ^ (FLAGS_dump.empty()))) {
fprintf(stderr,
"An input file must be specified with either -i or -dump.\n");
return 1;
}
if (FLAGS_dump.empty() && (FLAGS_aec || FLAGS_ie)) {
fprintf(stderr, "-aec and -ie require a -dump file.\n");
return 1;
}
if (FLAGS_ie) {
fprintf(stderr,
"FIXME(ajm): The intelligibility enhancer output is not dumped.\n");
return 1;
}
test::TraceToStderr trace_to_stderr(true);
Config config;
if (FLAGS_bf || FLAGS_all) {
if (FLAGS_mic_positions.empty()) {
fprintf(stderr, "-mic_positions must be specified when -bf is used.\n");
return 1;
}
config.Set<Beamforming>(new Beamforming(
true, ParseArrayGeometry(FLAGS_mic_positions),
SphericalPointf(DegreesToRadians(FLAGS_target_angle_degrees), 0.f,
1.f)));
}
config.Set<ExperimentalNs>(new ExperimentalNs(FLAGS_ts || FLAGS_all));
config.Set<Intelligibility>(new Intelligibility(FLAGS_ie || FLAGS_all));
rtc::scoped_ptr<AudioProcessing> ap(AudioProcessing::Create(config));
RTC_CHECK_EQ(kNoErr, ap->echo_cancellation()->Enable(FLAGS_aec || FLAGS_all));
RTC_CHECK_EQ(kNoErr, ap->gain_control()->Enable(FLAGS_agc || FLAGS_all));
RTC_CHECK_EQ(kNoErr, ap->high_pass_filter()->Enable(FLAGS_hpf || FLAGS_all));
RTC_CHECK_EQ(kNoErr, ap->noise_suppression()->Enable(FLAGS_ns || FLAGS_all));
if (FLAGS_ns_level != -1) {
RTC_CHECK_EQ(kNoErr,
ap->noise_suppression()->set_level(
static_cast<NoiseSuppression::Level>(FLAGS_ns_level)));
}
ap->set_stream_key_pressed(FLAGS_ts);
rtc::scoped_ptr<AudioFileProcessor> processor;
auto out_file = rtc_make_scoped_ptr(
new WavWriter(FLAGS_o, FLAGS_out_sample_rate, FLAGS_out_channels));
std::cout << FLAGS_o << ": " << out_file->FormatAsString() << std::endl;
if (FLAGS_dump.empty()) {
auto in_file = rtc_make_scoped_ptr(new WavReader(FLAGS_i));
std::cout << FLAGS_i << ": " << in_file->FormatAsString() << std::endl;
processor.reset(
new WavFileProcessor(ap.Pass(), in_file.Pass(), out_file.Pass()));
} else {
processor.reset(new AecDumpFileProcessor(
ap.Pass(), fopen(FLAGS_dump.c_str(), "rb"), out_file.Pass()));
}
int num_chunks = 0;
while (processor->ProcessChunk()) {
trace_to_stderr.SetTimeSeconds(num_chunks * 1.f / kChunksPerSecond);
++num_chunks;
}
if (FLAGS_perf) {
const auto& proc_time = processor->proc_time();
int64_t exec_time_us = proc_time.sum.Microseconds();
printf(
"\nExecution time: %.3f s, File time: %.2f s\n"
"Time per chunk (mean, max, min):\n%.0f us, %.0f us, %.0f us\n",
exec_time_us * 1e-6, num_chunks * 1.f / kChunksPerSecond,
exec_time_us * 1.f / num_chunks, 1.f * proc_time.max.Microseconds(),
1.f * proc_time.min.Microseconds());
}
return 0;
}
} // namespace webrtc
int main(int argc, char* argv[]) {
return webrtc::main(argc, argv);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2018 NXP.
*
* 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 the NXP Semiconductor 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 HOLDER 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.
*
*/
#include "trans.h"
#include "libuuu.h"
#include "liberror.h"
extern "C"
{
#include "libusb.h"
}
int USBTrans::open(void *p)
{
m_devhandle = p;
libusb_device_handle * handle = (libusb_device_handle *)m_devhandle;
if (libusb_kernel_driver_active(handle, 0))
{
int ret = libusb_detach_kernel_driver((libusb_device_handle *)m_devhandle, 0);
if(ret <0 && ret != LIBUSB_ERROR_NOT_SUPPORTED)
{
set_last_err_string("detach kernel driver failure");
return -1;
}
}
if (libusb_claim_interface(handle, 0))
{
set_last_err_string("Failure claim interface");
return -1;
}
libusb_config_descriptor *config;
if (libusb_get_active_config_descriptor(libusb_get_device(handle), &config))
{
set_last_err_string("Can't get config descriptor");
return -1;
}
m_EPs.clear();
for (int i = 0; i < config->interface[0].altsetting[0].bNumEndpoints; i++)
m_EPs.push_back(config->interface[0].altsetting[0].endpoint[i].bEndpointAddress);
return 0;
}
int USBTrans::close()
{
libusb_release_interface((libusb_device_handle *)m_devhandle, 0);
return 0;
}
int HIDTrans::write(void *buff, size_t size)
{
int ret;
uint8_t *p = (uint8_t *)buff;
ret = libusb_control_transfer(
(libusb_device_handle *)m_devhandle,
LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
m_set_report,
(2 << 8) | p[0],
0,
p,
size,
1000
);
if (ret < 0)
{
set_last_err_string("HID Write failure");
return ret;
}
return ret;
}
int HIDTrans::read(void *buff, size_t size, size_t *rsize)
{
int ret;
int actual;
ret = libusb_interrupt_transfer(
(libusb_device_handle *)m_devhandle,
0x81,
(uint8_t*)buff,
size,
&actual,
1000
);
*rsize = actual;
if (ret < 0)
{
set_last_err_string("HID Read failure");
return ret;
}
return 0;
}
int BulkTrans::write(void *buff, size_t size)
{
int ret;
int actual_lenght;
uint8_t *p = (uint8_t *)buff;
ret = libusb_bulk_transfer(
(libusb_device_handle *)m_devhandle,
m_ep_out,
p,
size,
&actual_lenght,
1000
);
if (ret < 0)
{
set_last_err_string("Bulk Write failure");
return ret;
}
return ret;
}
int BulkTrans::open(void *p)
{
if (USBTrans::open(p))
return -1;
for (int i = 0; i < m_EPs.size(); i++)
{
if (m_EPs[0] > 0)
{
if ((m_EPs[0] & 0x80) && m_ep_in == 0)
m_ep_in = m_EPs[i];
else if (m_ep_out == 0)
m_ep_out = m_EPs[i];
}
}
return 0;
}
int BulkTrans::read(void *buff, size_t size, size_t *rsize)
{
int ret;
int actual_lenght;
uint8_t *p = (uint8_t *)buff;
ret = libusb_bulk_transfer(
(libusb_device_handle *)m_devhandle,
m_ep_in,
p,
size,
&actual_lenght,
1000
);
*rsize = actual_lenght;
if (ret < 0)
{
set_last_err_string("Bulk read failure");
return ret;
}
return ret;
}
<commit_msg>Close device handle when finish work<commit_after>/*
* Copyright 2018 NXP.
*
* 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 the NXP Semiconductor 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 HOLDER 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.
*
*/
#include "trans.h"
#include "libuuu.h"
#include "liberror.h"
#include "libusb.h"
extern "C"
{
#include "libusb.h"
}
int USBTrans::open(void *p)
{
m_devhandle = p;
libusb_device_handle * handle = (libusb_device_handle *)m_devhandle;
if (libusb_kernel_driver_active(handle, 0))
{
int ret = libusb_detach_kernel_driver((libusb_device_handle *)m_devhandle, 0);
if(ret <0 && ret != LIBUSB_ERROR_NOT_SUPPORTED)
{
set_last_err_string("detach kernel driver failure");
return -1;
}
}
if (libusb_claim_interface(handle, 0))
{
set_last_err_string("Failure claim interface");
return -1;
}
libusb_config_descriptor *config;
if (libusb_get_active_config_descriptor(libusb_get_device(handle), &config))
{
set_last_err_string("Can't get config descriptor");
return -1;
}
m_EPs.clear();
for (int i = 0; i < config->interface[0].altsetting[0].bNumEndpoints; i++)
m_EPs.push_back(config->interface[0].altsetting[0].endpoint[i].bEndpointAddress);
return 0;
}
int USBTrans::close()
{
libusb_release_interface((libusb_device_handle *)m_devhandle, 0);
libusb_close((libusb_device_handle *)m_devhandle);
return 0;
}
int HIDTrans::write(void *buff, size_t size)
{
int ret;
uint8_t *p = (uint8_t *)buff;
ret = libusb_control_transfer(
(libusb_device_handle *)m_devhandle,
LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
m_set_report,
(2 << 8) | p[0],
0,
p,
size,
1000
);
if (ret < 0)
{
set_last_err_string("HID Write failure");
return ret;
}
return ret;
}
int HIDTrans::read(void *buff, size_t size, size_t *rsize)
{
int ret;
int actual;
ret = libusb_interrupt_transfer(
(libusb_device_handle *)m_devhandle,
0x81,
(uint8_t*)buff,
size,
&actual,
1000
);
*rsize = actual;
if (ret < 0)
{
set_last_err_string("HID Read failure");
return ret;
}
return 0;
}
int BulkTrans::write(void *buff, size_t size)
{
int ret;
int actual_lenght;
uint8_t *p = (uint8_t *)buff;
ret = libusb_bulk_transfer(
(libusb_device_handle *)m_devhandle,
m_ep_out,
p,
size,
&actual_lenght,
1000
);
if (ret < 0)
{
set_last_err_string("Bulk Write failure");
return ret;
}
return ret;
}
int BulkTrans::open(void *p)
{
if (USBTrans::open(p))
return -1;
for (int i = 0; i < m_EPs.size(); i++)
{
if (m_EPs[0] > 0)
{
if ((m_EPs[0] & 0x80) && m_ep_in == 0)
m_ep_in = m_EPs[i];
else if (m_ep_out == 0)
m_ep_out = m_EPs[i];
}
}
return 0;
}
int BulkTrans::read(void *buff, size_t size, size_t *rsize)
{
int ret;
int actual_lenght;
uint8_t *p = (uint8_t *)buff;
ret = libusb_bulk_transfer(
(libusb_device_handle *)m_devhandle,
m_ep_in,
p,
size,
&actual_lenght,
1000
);
*rsize = actual_lenght;
if (ret < 0)
{
set_last_err_string("Bulk read failure");
return ret;
}
return ret;
}
<|endoftext|>
|
<commit_before>/*
* InitGaborWeights.hpp
*
* Created on: Aug 13, 2011
* Author: kpeterson
*/
#ifndef INITGABORWEIGHTS_HPP_
#define INITGABORWEIGHTS_HPP_
#include "InitWeights.hpp"
#include "InitGauss2DWeights.hpp"
namespace PV {
class InitWeightsParams;
class InitGaborWeightsParams;
class InitGaborWeights: public PV::InitGauss2DWeights {
public:
InitGaborWeights(HyPerConn * conn);
virtual ~InitGaborWeights();
virtual int calcWeights(/* PVPatch * patch */ pvdata_t * dataStart, int patchIndex, int arborId);
virtual InitWeightsParams * createNewWeightParams();
void calcOtherParams(PVPatch * patch, int patchIndex);
protected:
InitGaborWeights();
int initialize(HyPerConn * conn);
private:
int initialize_base();
int gaborWeights(/* PVPatch * patch */ pvdata_t * dataStart, InitGaborWeightsParams * weightParamPtr);
};
} /* namespace PV */
#endif /* INITGABORWEIGHTS_HPP_ */
<commit_msg>Converting to pvwdata_t for weights.<commit_after>/*
* InitGaborWeights.hpp
*
* Created on: Aug 13, 2011
* Author: kpeterson
*/
#ifndef INITGABORWEIGHTS_HPP_
#define INITGABORWEIGHTS_HPP_
#include "InitWeights.hpp"
#include "InitGauss2DWeights.hpp"
namespace PV {
class InitWeightsParams;
class InitGaborWeightsParams;
class InitGaborWeights: public PV::InitGauss2DWeights {
public:
InitGaborWeights(HyPerConn * conn);
virtual ~InitGaborWeights();
virtual int calcWeights(pvwdata_t * dataStart, int patchIndex, int arborId);
virtual InitWeightsParams * createNewWeightParams();
void calcOtherParams(PVPatch * patch, int patchIndex);
protected:
InitGaborWeights();
int initialize(HyPerConn * conn);
private:
int initialize_base();
int gaborWeights(pvwdata_t * dataStart, InitGaborWeightsParams * weightParamPtr);
};
} /* namespace PV */
#endif /* INITGABORWEIGHTS_HPP_ */
<|endoftext|>
|
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/platform/hadoop/hadoop_file_system.h"
#include <errno.h>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/posix/error.h"
#include "third_party/hadoop/hdfs.h"
namespace tensorflow {
template <typename R, typename... Args>
Status BindFunc(void* handle, const char* name,
std::function<R(Args...)>* func) {
void* symbol_ptr = nullptr;
TF_RETURN_IF_ERROR(
Env::Default()->GetSymbolFromLibrary(handle, name, &symbol_ptr));
*func = reinterpret_cast<R (*)(Args...)>(symbol_ptr);
return Status::OK();
}
class LibHDFS {
public:
static LibHDFS* Load() {
static LibHDFS* lib = []() -> LibHDFS* {
LibHDFS* lib = new LibHDFS;
lib->LoadAndBind();
return lib;
}();
return lib;
}
// The status, if any, from failure to load.
Status status() { return status_; }
std::function<hdfsFS(hdfsBuilder*)> hdfsBuilderConnect;
std::function<hdfsBuilder*()> hdfsNewBuilder;
std::function<void(hdfsBuilder*, const char*)> hdfsBuilderSetNameNode;
std::function<int(hdfsFS, hdfsFile)> hdfsCloseFile;
std::function<tSize(hdfsFS, hdfsFile, tOffset, void*, tSize)> hdfsPread;
std::function<tSize(hdfsFS, hdfsFile, const void*, tSize)> hdfsWrite;
std::function<int(hdfsFS, hdfsFile)> hdfsFlush;
std::function<int(hdfsFS, hdfsFile)> hdfsHSync;
std::function<hdfsFile(hdfsFS, const char*, int, int, short, tSize)>
hdfsOpenFile;
std::function<int(hdfsFS, const char*)> hdfsExists;
std::function<hdfsFileInfo*(hdfsFS, const char*, int*)> hdfsListDirectory;
std::function<void(hdfsFileInfo*, int)> hdfsFreeFileInfo;
std::function<int(hdfsFS, const char*, int recursive)> hdfsDelete;
std::function<int(hdfsFS, const char*)> hdfsCreateDirectory;
std::function<hdfsFileInfo*(hdfsFS, const char*)> hdfsGetPathInfo;
std::function<int(hdfsFS, const char*, const char*)> hdfsRename;
private:
void LoadAndBind() {
auto TryLoadAndBind = [this](const char* name, void** handle) -> Status {
TF_RETURN_IF_ERROR(Env::Default()->LoadLibrary(name, handle));
#define BIND_HDFS_FUNC(function) \
TF_RETURN_IF_ERROR(BindFunc(*handle, #function, &function));
BIND_HDFS_FUNC(hdfsBuilderConnect);
BIND_HDFS_FUNC(hdfsNewBuilder);
BIND_HDFS_FUNC(hdfsBuilderSetNameNode);
BIND_HDFS_FUNC(hdfsCloseFile);
BIND_HDFS_FUNC(hdfsPread);
BIND_HDFS_FUNC(hdfsWrite);
BIND_HDFS_FUNC(hdfsFlush);
BIND_HDFS_FUNC(hdfsHSync);
BIND_HDFS_FUNC(hdfsOpenFile);
BIND_HDFS_FUNC(hdfsExists);
BIND_HDFS_FUNC(hdfsListDirectory);
BIND_HDFS_FUNC(hdfsFreeFileInfo);
BIND_HDFS_FUNC(hdfsDelete);
BIND_HDFS_FUNC(hdfsCreateDirectory);
BIND_HDFS_FUNC(hdfsGetPathInfo);
BIND_HDFS_FUNC(hdfsRename);
#undef BIND_HDFS_FUNC
return Status::OK();
};
// libhdfs.so won't be in the standard locations. Use the path as specified
// in the libhdfs documentation.
char* hdfs_home = getenv("HADOOP_HDFS_HOME");
if (hdfs_home == nullptr) {
status_ = errors::FailedPrecondition(
"Environment variable HADOOP_HDFS_HOME not set");
return;
}
string path = io::JoinPath(hdfs_home, "lib", "native", "libhdfs.so");
status_ = TryLoadAndBind(path.c_str(), &handle_);
return;
}
Status status_;
void* handle_ = nullptr;
};
HadoopFileSystem::HadoopFileSystem() : hdfs_(LibHDFS::Load()) {}
HadoopFileSystem::~HadoopFileSystem() {}
// We rely on HDFS connection caching here. The HDFS client calls
// org.apache.hadoop.fs.FileSystem.get(), which caches the connection
// internally.
Status HadoopFileSystem::Connect(StringPiece fname, hdfsFS* fs) {
TF_RETURN_IF_ERROR(hdfs_->status());
StringPiece scheme, namenode, path;
ParseURI(fname, &scheme, &namenode, &path);
hdfsBuilder* builder = hdfs_->hdfsNewBuilder();
if (scheme == "file") {
hdfs_->hdfsBuilderSetNameNode(builder, nullptr);
} else {
hdfs_->hdfsBuilderSetNameNode(builder, namenode.ToString().c_str());
}
*fs = hdfs_->hdfsBuilderConnect(builder);
if (*fs == nullptr) {
return errors::NotFound(strerror(errno));
}
return Status::OK();
}
string HadoopFileSystem::TranslateName(const string& name) const {
StringPiece scheme, namenode, path;
ParseURI(name, &scheme, &namenode, &path);
return path.ToString();
}
class HDFSRandomAccessFile : public RandomAccessFile {
public:
HDFSRandomAccessFile(const string& fname, LibHDFS* hdfs, hdfsFS fs,
hdfsFile file)
: filename_(fname), hdfs_(hdfs), fs_(fs), file_(file) {}
~HDFSRandomAccessFile() override { hdfs_->hdfsCloseFile(fs_, file_); }
Status Read(uint64 offset, size_t n, StringPiece* result,
char* scratch) const override {
Status s;
char* dst = scratch;
while (n > 0 && s.ok()) {
tSize r = hdfs_->hdfsPread(fs_, file_, static_cast<tOffset>(offset), dst,
static_cast<tSize>(n));
if (r > 0) {
dst += r;
n -= r;
offset += r;
} else if (r == 0) {
s = Status(error::OUT_OF_RANGE, "Read less bytes than requested");
} else if (errno == EINTR || errno == EAGAIN) {
// hdfsPread may return EINTR too. Just retry.
} else {
s = IOError(filename_, errno);
}
}
*result = StringPiece(scratch, dst - scratch);
return s;
}
private:
string filename_;
LibHDFS* hdfs_;
hdfsFS fs_;
hdfsFile file_;
};
Status HadoopFileSystem::NewRandomAccessFile(
const string& fname, std::unique_ptr<RandomAccessFile>* result) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFile file =
hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(), O_RDONLY, 0, 0, 0);
if (file == nullptr) {
return IOError(fname, errno);
}
result->reset(new HDFSRandomAccessFile(fname, hdfs_, fs, file));
return Status::OK();
}
class HDFSWritableFile : public WritableFile {
public:
HDFSWritableFile(const string& fname, LibHDFS* hdfs, hdfsFS fs, hdfsFile file)
: filename_(fname), hdfs_(hdfs), fs_(fs), file_(file) {}
~HDFSWritableFile() override {
if (file_ != nullptr) {
Close();
}
}
Status Append(const StringPiece& data) override {
if (hdfs_->hdfsWrite(fs_, file_, data.data(),
static_cast<tSize>(data.size())) == -1) {
return IOError(filename_, errno);
}
return Status::OK();
}
Status Close() override {
Status result;
if (hdfs_->hdfsCloseFile(fs_, file_) != 0) {
result = IOError(filename_, errno);
}
hdfs_ = nullptr;
fs_ = nullptr;
file_ = nullptr;
return result;
}
Status Flush() override {
if (hdfs_->hdfsFlush(fs_, file_) != 0) {
return IOError(filename_, errno);
}
return Status::OK();
}
Status Sync() override {
if (hdfs_->hdfsHSync(fs_, file_) != 0) {
return IOError(filename_, errno);
}
return Status::OK();
}
private:
string filename_;
LibHDFS* hdfs_;
hdfsFS fs_;
hdfsFile file_;
};
Status HadoopFileSystem::NewWritableFile(
const string& fname, std::unique_ptr<WritableFile>* result) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFile file =
hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(), O_WRONLY, 0, 0, 0);
if (file == nullptr) {
return IOError(fname, errno);
}
result->reset(new HDFSWritableFile(fname, hdfs_, fs, file));
return Status::OK();
}
Status HadoopFileSystem::NewAppendableFile(
const string& fname, std::unique_ptr<WritableFile>* result) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFile file = hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(),
O_WRONLY | O_APPEND, 0, 0, 0);
if (file == nullptr) {
return IOError(fname, errno);
}
result->reset(new HDFSWritableFile(fname, hdfs_, fs, file));
return Status::OK();
}
Status HadoopFileSystem::NewReadOnlyMemoryRegionFromFile(
const string& fname, std::unique_ptr<ReadOnlyMemoryRegion>* result) {
// hadoopReadZero() technically supports this call with the following
// caveats:
// - It only works up to 2 GB. We'd have to Stat() the file to ensure that
// it fits.
// - If not on the local filesystem, the entire file will be read, making
// it inefficient for callers that assume typical mmap() behavior.
return errors::Unimplemented("HDFS does not support ReadOnlyMemoryRegion");
}
bool HadoopFileSystem::FileExists(const string& fname) {
hdfsFS fs = nullptr;
Status status = Connect(fname, &fs);
if (!status.ok()) {
LOG(ERROR) << "Connect failed: " << status.error_message();
return false;
}
return hdfs_->hdfsExists(fs, TranslateName(fname).c_str()) == 0;
}
Status HadoopFileSystem::GetChildren(const string& dir,
std::vector<string>* result) {
result->clear();
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(dir, &fs));
// hdfsListDirectory returns nullptr if the directory is empty. Do a separate
// check to verify the directory exists first.
FileStatistics stat;
TF_RETURN_IF_ERROR(Stat(dir, &stat));
int entries = 0;
hdfsFileInfo* info =
hdfs_->hdfsListDirectory(fs, TranslateName(dir).c_str(), &entries);
if (info == nullptr) {
if (stat.is_directory) {
// Assume it's an empty directory.
return Status::OK();
}
return IOError(dir, errno);
}
for (int i = 0; i < entries; i++) {
result->push_back(io::Basename(info[i].mName).ToString());
}
hdfs_->hdfsFreeFileInfo(info, entries);
return Status::OK();
}
Status HadoopFileSystem::DeleteFile(const string& fname) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
if (hdfs_->hdfsDelete(fs, TranslateName(fname).c_str(),
/*recursive=*/0) != 0) {
return IOError(fname, errno);
}
return Status::OK();
}
Status HadoopFileSystem::CreateDir(const string& dir) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(dir, &fs));
if (hdfs_->hdfsCreateDirectory(fs, TranslateName(dir).c_str()) != 0) {
return IOError(dir, errno);
}
return Status::OK();
}
Status HadoopFileSystem::DeleteDir(const string& dir) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(dir, &fs));
// Count the number of entries in the directory, and only delete if it's
// non-empty. This is consistent with the interface, but note that there's
// a race condition where a file may be added after this check, in which
// case the directory will still be deleted.
int entries = 0;
hdfsFileInfo* info =
hdfs_->hdfsListDirectory(fs, TranslateName(dir).c_str(), &entries);
if (info != nullptr) {
return IOError(dir, errno);
}
hdfs_->hdfsFreeFileInfo(info, entries);
if (entries > 0) {
return errors::FailedPrecondition("Cannot delete a non-empty directory.");
}
if (hdfs_->hdfsDelete(fs, TranslateName(dir).c_str(),
/*recursive=*/1) != 0) {
return IOError(dir, errno);
}
return Status::OK();
}
Status HadoopFileSystem::GetFileSize(const string& fname, uint64* size) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFileInfo* info = hdfs_->hdfsGetPathInfo(fs, TranslateName(fname).c_str());
if (info == nullptr) {
return IOError(fname, errno);
}
*size = static_cast<uint64>(info->mSize);
hdfs_->hdfsFreeFileInfo(info, 1);
return Status::OK();
}
Status HadoopFileSystem::RenameFile(const string& src, const string& target) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(src, &fs));
if (hdfs_->hdfsRename(fs, TranslateName(src).c_str(),
TranslateName(target).c_str()) != 0) {
return IOError(src, errno);
}
return Status::OK();
}
Status HadoopFileSystem::Stat(const string& fname, FileStatistics* stats) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFileInfo* info = hdfs_->hdfsGetPathInfo(fs, TranslateName(fname).c_str());
if (info == nullptr) {
return IOError(fname, errno);
}
stats->length = static_cast<int64>(info->mSize);
stats->mtime_nsec = static_cast<int64>(info->mLastMod) * 1e9;
stats->is_directory = info->mKind == kObjectKindDirectory;
hdfs_->hdfsFreeFileInfo(info, 1);
return Status::OK();
}
REGISTER_FILE_SYSTEM("hdfs", HadoopFileSystem);
} // namespace tensorflow
<commit_msg>Fix usage of a temporary when passing the namenode as a c_str(). Change: 134095364<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/platform/hadoop/hadoop_file_system.h"
#include <errno.h>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/posix/error.h"
#include "third_party/hadoop/hdfs.h"
namespace tensorflow {
template <typename R, typename... Args>
Status BindFunc(void* handle, const char* name,
std::function<R(Args...)>* func) {
void* symbol_ptr = nullptr;
TF_RETURN_IF_ERROR(
Env::Default()->GetSymbolFromLibrary(handle, name, &symbol_ptr));
*func = reinterpret_cast<R (*)(Args...)>(symbol_ptr);
return Status::OK();
}
class LibHDFS {
public:
static LibHDFS* Load() {
static LibHDFS* lib = []() -> LibHDFS* {
LibHDFS* lib = new LibHDFS;
lib->LoadAndBind();
return lib;
}();
return lib;
}
// The status, if any, from failure to load.
Status status() { return status_; }
std::function<hdfsFS(hdfsBuilder*)> hdfsBuilderConnect;
std::function<hdfsBuilder*()> hdfsNewBuilder;
std::function<void(hdfsBuilder*, const char*)> hdfsBuilderSetNameNode;
std::function<int(hdfsFS, hdfsFile)> hdfsCloseFile;
std::function<tSize(hdfsFS, hdfsFile, tOffset, void*, tSize)> hdfsPread;
std::function<tSize(hdfsFS, hdfsFile, const void*, tSize)> hdfsWrite;
std::function<int(hdfsFS, hdfsFile)> hdfsFlush;
std::function<int(hdfsFS, hdfsFile)> hdfsHSync;
std::function<hdfsFile(hdfsFS, const char*, int, int, short, tSize)>
hdfsOpenFile;
std::function<int(hdfsFS, const char*)> hdfsExists;
std::function<hdfsFileInfo*(hdfsFS, const char*, int*)> hdfsListDirectory;
std::function<void(hdfsFileInfo*, int)> hdfsFreeFileInfo;
std::function<int(hdfsFS, const char*, int recursive)> hdfsDelete;
std::function<int(hdfsFS, const char*)> hdfsCreateDirectory;
std::function<hdfsFileInfo*(hdfsFS, const char*)> hdfsGetPathInfo;
std::function<int(hdfsFS, const char*, const char*)> hdfsRename;
private:
void LoadAndBind() {
auto TryLoadAndBind = [this](const char* name, void** handle) -> Status {
TF_RETURN_IF_ERROR(Env::Default()->LoadLibrary(name, handle));
#define BIND_HDFS_FUNC(function) \
TF_RETURN_IF_ERROR(BindFunc(*handle, #function, &function));
BIND_HDFS_FUNC(hdfsBuilderConnect);
BIND_HDFS_FUNC(hdfsNewBuilder);
BIND_HDFS_FUNC(hdfsBuilderSetNameNode);
BIND_HDFS_FUNC(hdfsCloseFile);
BIND_HDFS_FUNC(hdfsPread);
BIND_HDFS_FUNC(hdfsWrite);
BIND_HDFS_FUNC(hdfsFlush);
BIND_HDFS_FUNC(hdfsHSync);
BIND_HDFS_FUNC(hdfsOpenFile);
BIND_HDFS_FUNC(hdfsExists);
BIND_HDFS_FUNC(hdfsListDirectory);
BIND_HDFS_FUNC(hdfsFreeFileInfo);
BIND_HDFS_FUNC(hdfsDelete);
BIND_HDFS_FUNC(hdfsCreateDirectory);
BIND_HDFS_FUNC(hdfsGetPathInfo);
BIND_HDFS_FUNC(hdfsRename);
#undef BIND_HDFS_FUNC
return Status::OK();
};
// libhdfs.so won't be in the standard locations. Use the path as specified
// in the libhdfs documentation.
char* hdfs_home = getenv("HADOOP_HDFS_HOME");
if (hdfs_home == nullptr) {
status_ = errors::FailedPrecondition(
"Environment variable HADOOP_HDFS_HOME not set");
return;
}
string path = io::JoinPath(hdfs_home, "lib", "native", "libhdfs.so");
status_ = TryLoadAndBind(path.c_str(), &handle_);
return;
}
Status status_;
void* handle_ = nullptr;
};
HadoopFileSystem::HadoopFileSystem() : hdfs_(LibHDFS::Load()) {}
HadoopFileSystem::~HadoopFileSystem() {}
// We rely on HDFS connection caching here. The HDFS client calls
// org.apache.hadoop.fs.FileSystem.get(), which caches the connection
// internally.
Status HadoopFileSystem::Connect(StringPiece fname, hdfsFS* fs) {
TF_RETURN_IF_ERROR(hdfs_->status());
StringPiece scheme, namenode, path;
ParseURI(fname, &scheme, &namenode, &path);
const string nn = namenode.ToString();
hdfsBuilder* builder = hdfs_->hdfsNewBuilder();
if (scheme == "file") {
hdfs_->hdfsBuilderSetNameNode(builder, nullptr);
} else {
hdfs_->hdfsBuilderSetNameNode(builder, nn.c_str());
}
*fs = hdfs_->hdfsBuilderConnect(builder);
if (*fs == nullptr) {
return errors::NotFound(strerror(errno));
}
return Status::OK();
}
string HadoopFileSystem::TranslateName(const string& name) const {
StringPiece scheme, namenode, path;
ParseURI(name, &scheme, &namenode, &path);
return path.ToString();
}
class HDFSRandomAccessFile : public RandomAccessFile {
public:
HDFSRandomAccessFile(const string& fname, LibHDFS* hdfs, hdfsFS fs,
hdfsFile file)
: filename_(fname), hdfs_(hdfs), fs_(fs), file_(file) {}
~HDFSRandomAccessFile() override { hdfs_->hdfsCloseFile(fs_, file_); }
Status Read(uint64 offset, size_t n, StringPiece* result,
char* scratch) const override {
Status s;
char* dst = scratch;
while (n > 0 && s.ok()) {
tSize r = hdfs_->hdfsPread(fs_, file_, static_cast<tOffset>(offset), dst,
static_cast<tSize>(n));
if (r > 0) {
dst += r;
n -= r;
offset += r;
} else if (r == 0) {
s = Status(error::OUT_OF_RANGE, "Read less bytes than requested");
} else if (errno == EINTR || errno == EAGAIN) {
// hdfsPread may return EINTR too. Just retry.
} else {
s = IOError(filename_, errno);
}
}
*result = StringPiece(scratch, dst - scratch);
return s;
}
private:
string filename_;
LibHDFS* hdfs_;
hdfsFS fs_;
hdfsFile file_;
};
Status HadoopFileSystem::NewRandomAccessFile(
const string& fname, std::unique_ptr<RandomAccessFile>* result) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFile file =
hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(), O_RDONLY, 0, 0, 0);
if (file == nullptr) {
return IOError(fname, errno);
}
result->reset(new HDFSRandomAccessFile(fname, hdfs_, fs, file));
return Status::OK();
}
class HDFSWritableFile : public WritableFile {
public:
HDFSWritableFile(const string& fname, LibHDFS* hdfs, hdfsFS fs, hdfsFile file)
: filename_(fname), hdfs_(hdfs), fs_(fs), file_(file) {}
~HDFSWritableFile() override {
if (file_ != nullptr) {
Close();
}
}
Status Append(const StringPiece& data) override {
if (hdfs_->hdfsWrite(fs_, file_, data.data(),
static_cast<tSize>(data.size())) == -1) {
return IOError(filename_, errno);
}
return Status::OK();
}
Status Close() override {
Status result;
if (hdfs_->hdfsCloseFile(fs_, file_) != 0) {
result = IOError(filename_, errno);
}
hdfs_ = nullptr;
fs_ = nullptr;
file_ = nullptr;
return result;
}
Status Flush() override {
if (hdfs_->hdfsFlush(fs_, file_) != 0) {
return IOError(filename_, errno);
}
return Status::OK();
}
Status Sync() override {
if (hdfs_->hdfsHSync(fs_, file_) != 0) {
return IOError(filename_, errno);
}
return Status::OK();
}
private:
string filename_;
LibHDFS* hdfs_;
hdfsFS fs_;
hdfsFile file_;
};
Status HadoopFileSystem::NewWritableFile(
const string& fname, std::unique_ptr<WritableFile>* result) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFile file =
hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(), O_WRONLY, 0, 0, 0);
if (file == nullptr) {
return IOError(fname, errno);
}
result->reset(new HDFSWritableFile(fname, hdfs_, fs, file));
return Status::OK();
}
Status HadoopFileSystem::NewAppendableFile(
const string& fname, std::unique_ptr<WritableFile>* result) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFile file = hdfs_->hdfsOpenFile(fs, TranslateName(fname).c_str(),
O_WRONLY | O_APPEND, 0, 0, 0);
if (file == nullptr) {
return IOError(fname, errno);
}
result->reset(new HDFSWritableFile(fname, hdfs_, fs, file));
return Status::OK();
}
Status HadoopFileSystem::NewReadOnlyMemoryRegionFromFile(
const string& fname, std::unique_ptr<ReadOnlyMemoryRegion>* result) {
// hadoopReadZero() technically supports this call with the following
// caveats:
// - It only works up to 2 GB. We'd have to Stat() the file to ensure that
// it fits.
// - If not on the local filesystem, the entire file will be read, making
// it inefficient for callers that assume typical mmap() behavior.
return errors::Unimplemented("HDFS does not support ReadOnlyMemoryRegion");
}
bool HadoopFileSystem::FileExists(const string& fname) {
hdfsFS fs = nullptr;
Status status = Connect(fname, &fs);
if (!status.ok()) {
LOG(ERROR) << "Connect failed: " << status.error_message();
return false;
}
return hdfs_->hdfsExists(fs, TranslateName(fname).c_str()) == 0;
}
Status HadoopFileSystem::GetChildren(const string& dir,
std::vector<string>* result) {
result->clear();
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(dir, &fs));
// hdfsListDirectory returns nullptr if the directory is empty. Do a separate
// check to verify the directory exists first.
FileStatistics stat;
TF_RETURN_IF_ERROR(Stat(dir, &stat));
int entries = 0;
hdfsFileInfo* info =
hdfs_->hdfsListDirectory(fs, TranslateName(dir).c_str(), &entries);
if (info == nullptr) {
if (stat.is_directory) {
// Assume it's an empty directory.
return Status::OK();
}
return IOError(dir, errno);
}
for (int i = 0; i < entries; i++) {
result->push_back(io::Basename(info[i].mName).ToString());
}
hdfs_->hdfsFreeFileInfo(info, entries);
return Status::OK();
}
Status HadoopFileSystem::DeleteFile(const string& fname) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
if (hdfs_->hdfsDelete(fs, TranslateName(fname).c_str(),
/*recursive=*/0) != 0) {
return IOError(fname, errno);
}
return Status::OK();
}
Status HadoopFileSystem::CreateDir(const string& dir) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(dir, &fs));
if (hdfs_->hdfsCreateDirectory(fs, TranslateName(dir).c_str()) != 0) {
return IOError(dir, errno);
}
return Status::OK();
}
Status HadoopFileSystem::DeleteDir(const string& dir) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(dir, &fs));
// Count the number of entries in the directory, and only delete if it's
// non-empty. This is consistent with the interface, but note that there's
// a race condition where a file may be added after this check, in which
// case the directory will still be deleted.
int entries = 0;
hdfsFileInfo* info =
hdfs_->hdfsListDirectory(fs, TranslateName(dir).c_str(), &entries);
if (info != nullptr) {
return IOError(dir, errno);
}
hdfs_->hdfsFreeFileInfo(info, entries);
if (entries > 0) {
return errors::FailedPrecondition("Cannot delete a non-empty directory.");
}
if (hdfs_->hdfsDelete(fs, TranslateName(dir).c_str(),
/*recursive=*/1) != 0) {
return IOError(dir, errno);
}
return Status::OK();
}
Status HadoopFileSystem::GetFileSize(const string& fname, uint64* size) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFileInfo* info = hdfs_->hdfsGetPathInfo(fs, TranslateName(fname).c_str());
if (info == nullptr) {
return IOError(fname, errno);
}
*size = static_cast<uint64>(info->mSize);
hdfs_->hdfsFreeFileInfo(info, 1);
return Status::OK();
}
Status HadoopFileSystem::RenameFile(const string& src, const string& target) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(src, &fs));
if (hdfs_->hdfsRename(fs, TranslateName(src).c_str(),
TranslateName(target).c_str()) != 0) {
return IOError(src, errno);
}
return Status::OK();
}
Status HadoopFileSystem::Stat(const string& fname, FileStatistics* stats) {
hdfsFS fs = nullptr;
TF_RETURN_IF_ERROR(Connect(fname, &fs));
hdfsFileInfo* info = hdfs_->hdfsGetPathInfo(fs, TranslateName(fname).c_str());
if (info == nullptr) {
return IOError(fname, errno);
}
stats->length = static_cast<int64>(info->mSize);
stats->mtime_nsec = static_cast<int64>(info->mLastMod) * 1e9;
stats->is_directory = info->mKind == kObjectKindDirectory;
hdfs_->hdfsFreeFileInfo(info, 1);
return Status::OK();
}
REGISTER_FILE_SYSTEM("hdfs", HadoopFileSystem);
} // namespace tensorflow
<|endoftext|>
|
<commit_before>//
// xec_ssa_print.cpp
//
// Created by Edmund Kapusniak on 10/08/2014.
// Copyright (c) 2014 Edmund Kapusniak. All rights reserved.
//
#include "xec_ssa_print.h"
#include <unordered_map>
#include "xec_ssa.h"
class xec_ssa_printer
{
public:
explicit xec_ssa_printer( xec_ssa* root );
void print( xec_ssa_func* func );
private:
void print_slice( xec_ssa_func* func, xec_ssa_slice* slice );
void print_op( xec_ssa_func* func, xec_ssa_op& op );
void print_names( xec_ssa_func* func, xec_ssa_opref opref );
xec_ssa* root;
};
xec_ssa_printer::xec_ssa_printer( xec_ssa* root )
: root( root )
{
}
void xec_ssa_printer::print( xec_ssa_func* func )
{
// Build ids (if blocks haven't already been ordered).
for ( size_t i = 0; i < func->blocks.size(); ++i )
{
xec_ssa_block* block = func->blocks.at( i );
if ( block->index == -1 )
{
block->index = (int)i;
}
}
// Print function.
printf( "function %p %s\n", func, func->funcname );
printf( " block : [%04X]\n", (int)func->block->index );
printf( " upvalcount : %d\n", func->upvalcount );
printf( " localupcount : %d\n", func->localupcount );
printf( " paramcount : %d\n", func->paramcount );
printf( " varargs : %s\n", func->varargs ? "true" : "false" );
printf( " coroutine : %s\n", func->coroutine ? "true" : "false" );
for ( size_t i = 0; i < func->blocks.size(); ++i )
{
xec_ssa_block* block = func->blocks.at( i );
printf( "\n" );
printf( "[%04X]\n", block->index );
print_slice( func, block->live );
print_slice( func, block->phi );
print_slice( func, block->ops );
if ( block->condition )
{
printf( " ?? %04X:%02X\n",
block->condition.slice, block->condition.value );
printf( " -> [%04X]\n", block->iftrue->index );
printf( " -> [%04X]\n", block->iffalse->index );
}
else if ( block->next )
{
printf( " -> [%04X]\n", block->next->index );
}
}
printf( "\n\n" );
}
class xec_ssa_opnames
{
public:
xec_ssa_opnames()
{
add( XEC_SSA_NOP, "nop" );
add( XEC_SSA_NULL, "null" );
add( XEC_SSA_NUMBER, "number" );
add( XEC_SSA_BOOL, "bool" );
add( XEC_SSA_STRING, "string" );
add( XEC_SSA_REF, "ref" );
add( XEC_SSA_POS, "pos" );
add( XEC_SSA_NEG, "neg" );
add( XEC_SSA_NOT, "not" );
add( XEC_SSA_BITNOT, "bitnot" );
add( XEC_SSA_MUL, "mul" );
add( XEC_SSA_DIV, "div" );
add( XEC_SSA_MOD, "mod" );
add( XEC_SSA_INTDIV, "intdiv" );
add( XEC_SSA_ADD, "add" );
add( XEC_SSA_SUB, "sub" );
add( XEC_SSA_LSL, "lsl" );
add( XEC_SSA_LSR, "lsr" );
add( XEC_SSA_ASR, "asr" );
add( XEC_SSA_BITAND, "bitand" );
add( XEC_SSA_BITXOR, "bitxor" );
add( XEC_SSA_BITOR, "bitor" );
add( XEC_SSA_CONCAT, "concat" );
add( XEC_SSA_EQ, "eq" );
add( XEC_SSA_LT, "lt" );
add( XEC_SSA_LE, "le" );
add( XEC_SSA_IN, "in" );
add( XEC_SSA_IS, "is" );
add( XEC_SSA_XOR, "xor" );
add( XEC_SSA_INKEY, "inkey" );
add( XEC_SSA_INDEX, "index" );
add( XEC_SSA_DELINKEY, "delinkey" );
add( XEC_SSA_OBJECT, "object" );
add( XEC_SSA_ITER, "iter" );
add( XEC_SSA_EACH, "each" );
add( XEC_SSA_APPEND, "append" );
add( XEC_SSA_EXTEND, "extend" );
add( XEC_SSA_CATCH, "catch" );
add( XEC_SSA_RETHROW, "rethrow" );
add( XEC_SSA_KEY, "key" );
add( XEC_SSA_DELKEY, "delkey" );
add( XEC_SSA_GLOBAL, "global" );
add( XEC_SSA_SETGLOBAL, "setglobal" );
add( XEC_SSA_PARAM, "param" );
add( XEC_SSA_VARARG, "vararg" );
add( XEC_SSA_SELECT, "select" );
add( XEC_SSA_UNPACK, "unpack" );
add( XEC_SSA_NEWUP, "newup" );
add( XEC_SSA_REFUP, "refup" );
add( XEC_SSA_SETUP, "setup" );
add( XEC_SSA_CLOSE, "close" );
add( XEC_SSA_ARRAY, "array" );
add( XEC_SSA_TABLE, "table" );
add( XEC_SSA_NEXT, "next" );
add( XEC_SSA_SETINKEY, "setinkey" );
add( XEC_SSA_SETINDEX, "setindex" );
add( XEC_SSA_SETKEY, "setkey" );
add( XEC_SSA_CALL, "call" );
add( XEC_SSA_YCALL, "ycall" );
add( XEC_SSA_YIELD, "yield" );
add( XEC_SSA_NEW, "new" );
add( XEC_SSA_RETURN, "return" );
add( XEC_SSA_LAMBDA, "lambda" );
add( XEC_SSA_PHI, "phi" );
add( XEC_SSA_LIVE, "live" );
}
const char* lookup( xec_ssa_opcode o ) const
{
return map.at( o );
}
private:
void add( xec_ssa_opcode o, const char* n )
{
map.emplace( o, n );
}
std::unordered_map< int, const char* > map;
};
static const xec_ssa_opnames opnames;
void xec_ssa_printer::print_slice( xec_ssa_func* func, xec_ssa_slice* slice )
{
for ( size_t i = 0; i < slice->ops.size(); ++i )
{
xec_ssa_opref opref;
opref.slice = slice->index;
opref.index = (int)i;
printf( "%04X:%02X ", opref.slice, opref.index );
print_op( func, slice->ops.at( i ) );
print_names( func, opref );
printf( "\n" );
}
}
void xec_ssa_printer::print_op( xec_ssa_func* func, xec_ssa_op& op )
{
printf( "[" );
if ( op.opcode >= XEC_SSA_FIRST_SET
&& op.opcode <= XEC_SSA_LAST_SET )
{
printf( "----:--|----:--" );
}
else
{
if ( op.until == XEC_SSA_FOREVER )
{
printf( "vvvv:vv" );
}
else if ( op.until )
{
printf( "%04X:%02X", op.until.slice, op.until.index );
}
else
{
printf( "----:--" );
}
printf( "|" );
if ( op.lnext )
{
printf( "%04X:%02X", op.lnext.slice, op.lnext.index );
}
else
{
printf( "----:--" );
}
}
printf( "] " );
const char* opname = opnames.lookup( op.opcode );
printf( "%-9s", opname );
if ( op.opcode >= XEC_SSA_FIRST_REF
&& op.opcode <= XEC_SSA_LAST_REF )
{
if ( op.operanda )
{
printf( " %04X:%02X", op.operanda.slice, op.operanda.index );
}
if ( op.operandb )
{
printf( " %04X:%02X", op.operandb.slice, op.operandb.index );
}
}
else if ( op.opcode >= XEC_SSA_FIRST_KEY
&& op.opcode <= XEC_SSA_LAST_KEY )
{
if ( op.operanda )
{
printf( " %04X:%02X", op.operanda.slice, op.operanda.index );
}
const char* key = root->keys.at( op.immkey );
printf( " '%s'", key );
}
else if ( op.opcode >= XEC_SSA_FIRST_IMM
&& op.opcode <= XEC_SSA_LAST_IMM )
{
if ( op.operanda )
{
printf( " %04X:%02X", op.operanda.slice, op.operanda.index );
}
printf( " $%d", op.immkey );
}
else if ( op.opcode >= XEC_SSA_FIRST_SET
&& op.opcode <= XEC_SSA_LAST_SET )
{
printf( " %04X:%02X", op.operanda.slice, op.operanda.index );
if ( op.opcode == XEC_SSA_SETKEY )
{
const char* key = root->keys.at( op.immkey );
printf( " '%s'", key );
}
else
{
printf( " %04X:%02X", op.operandb.slice, op.operandb.index );
}
printf( " %04X:%02X", op.operandv.slice, op.operandv.index );
}
else if ( op.opcode >= XEC_SSA_FIRST_ARG
&& op.opcode <= XEC_SSA_LAST_ARG )
{
printf( " $%d", op.args->resultcount );
for ( size_t i = 0; i < op.args->args.size(); ++i )
{
xec_ssa_opref arg = op.args->args.at( i );
printf( " %04X:%02X", arg.slice, arg.index );
}
if ( op.args->unpacked )
{
xec_ssa_opref unpacked = op.args->unpacked;
printf( " %04X:%02X ...", unpacked.slice, unpacked.index );
}
}
else switch ( op.opcode )
{
case XEC_SSA_NOP:
case XEC_SSA_NULL:
break;
case XEC_SSA_NUMBER:
printf( " %g", op.number );
break;
case XEC_SSA_BOOL:
printf( " %s", op.boolean ? "true" : "false" );
break;
case XEC_SSA_STRING:
{
printf( " \"" );
for ( size_t i = 0; i < op.string->length; ++i )
{
char c = op.string->string[ i ];
if ( c >= 0x20 && c <= 0x7E )
{
printf( "%c", c );
}
else switch ( c )
{
case 0x07: printf( "\\a" ); break;
case 0x08: printf( "\\b" ); break;
case 0x09: printf( "\\t" ); break;
case 0x0A: printf( "\\n" ); break;
case 0x0B: printf( "\\v" ); break;
case 0x0C: printf( "\\f" ); break;
case 0x0D: printf( "\\r" ); break;
case '"': printf( "\\\"" ); break;
default: printf( "\\x%02X", c ); break;
}
}
printf( "\"" );
break;
}
case XEC_SSA_PHI:
{
for ( size_t i = 0; i < op.phi->definitions.size(); ++i )
{
xec_ssa_opref def = op.phi->definitions.at( i );
printf( " %04X:%02X", def.slice, def.index );
}
break;
}
case XEC_SSA_LAMBDA:
{
printf( " %p", op.lambda->function );
for ( size_t i = 0; i < op.lambda->upvals.size(); ++i )
{
xec_ssa_opref upval = op.lambda->upvals.at( i );
printf( " %04X:%02X", upval.slice, upval.index );
}
break;
}
case XEC_SSA_LIVE:
break;
default:
break;
}
}
void xec_ssa_printer::print_names( xec_ssa_func* func, xec_ssa_opref opref )
{
auto ii = func->names.equal_range( opref );
for ( auto i = ii.first; i != ii.second; ++i )
{
if ( i == ii.first )
printf( " ( " );
else
printf( ", " );
printf( "%s", i->second->name );
}
if ( ii.first != ii.second )
{
printf( " )" );
}
}
void xec_ssa_print( xec_ssa* ssa )
{
for ( size_t i = 0; i < ssa->functions.size(); ++i )
{
xec_ssa_printer printer( ssa );
printer.print( ssa->functions.at( i ) );
}
}
<commit_msg>appears to do something...<commit_after>//
// xec_ssa_print.cpp
//
// Created by Edmund Kapusniak on 10/08/2014.
// Copyright (c) 2014 Edmund Kapusniak. All rights reserved.
//
#include "xec_ssa_print.h"
#include <unordered_map>
#include "xec_ssa.h"
class xec_ssa_printer
{
public:
explicit xec_ssa_printer( xec_ssa* root );
void print( xec_ssa_func* func );
private:
void print_slice( xec_ssa_func* func, xec_ssa_slice* slice );
void print_op( xec_ssa_func* func, xec_ssa_op& op );
void print_names( xec_ssa_func* func, xec_ssa_opref opref );
xec_ssa* root;
};
xec_ssa_printer::xec_ssa_printer( xec_ssa* root )
: root( root )
{
}
void xec_ssa_printer::print( xec_ssa_func* func )
{
// Build ids (if blocks haven't already been ordered).
for ( size_t i = 0; i < func->blocks.size(); ++i )
{
xec_ssa_block* block = func->blocks.at( i );
if ( block->index == -1 )
{
block->index = (int)i;
}
}
// Print function.
printf( "function %p %s\n", func, func->funcname );
printf( " block : [%04X]\n", (int)func->block->index );
printf( " upvalcount : %d\n", func->upvalcount );
printf( " localupcount : %d\n", func->localupcount );
printf( " paramcount : %d\n", func->paramcount );
printf( " varargs : %s\n", func->varargs ? "true" : "false" );
printf( " coroutine : %s\n", func->coroutine ? "true" : "false" );
for ( size_t i = 0; i < func->blocks.size(); ++i )
{
xec_ssa_block* block = func->blocks.at( i );
printf( "\n" );
printf( "[%04X]\n", block->index );
print_slice( func, block->live );
print_slice( func, block->phi );
print_slice( func, block->ops );
if ( block->condition )
{
printf( " ?? %04X:%02X\n",
block->condition.slice, block->condition.value );
printf( " -> [%04X]\n", block->iftrue->index );
printf( " -> [%04X]\n", block->iffalse->index );
}
else if ( block->next )
{
printf( " -> [%04X]\n", block->next->index );
}
}
printf( "\n\n" );
}
class xec_ssa_opnames
{
public:
xec_ssa_opnames()
{
add( XEC_SSA_NOP, "nop" );
add( XEC_SSA_NULL, "null" );
add( XEC_SSA_NUMBER, "number" );
add( XEC_SSA_BOOL, "bool" );
add( XEC_SSA_STRING, "string" );
add( XEC_SSA_REF, "ref" );
add( XEC_SSA_POS, "pos" );
add( XEC_SSA_NEG, "neg" );
add( XEC_SSA_NOT, "not" );
add( XEC_SSA_BITNOT, "bitnot" );
add( XEC_SSA_MUL, "mul" );
add( XEC_SSA_DIV, "div" );
add( XEC_SSA_MOD, "mod" );
add( XEC_SSA_INTDIV, "intdiv" );
add( XEC_SSA_ADD, "add" );
add( XEC_SSA_SUB, "sub" );
add( XEC_SSA_LSL, "lsl" );
add( XEC_SSA_LSR, "lsr" );
add( XEC_SSA_ASR, "asr" );
add( XEC_SSA_BITAND, "bitand" );
add( XEC_SSA_BITXOR, "bitxor" );
add( XEC_SSA_BITOR, "bitor" );
add( XEC_SSA_CONCAT, "concat" );
add( XEC_SSA_EQ, "eq" );
add( XEC_SSA_LT, "lt" );
add( XEC_SSA_LE, "le" );
add( XEC_SSA_IN, "in" );
add( XEC_SSA_IS, "is" );
add( XEC_SSA_XOR, "xor" );
add( XEC_SSA_INKEY, "inkey" );
add( XEC_SSA_INDEX, "index" );
add( XEC_SSA_DELINKEY, "delinkey" );
add( XEC_SSA_OBJECT, "object" );
add( XEC_SSA_ITER, "iter" );
add( XEC_SSA_EACH, "each" );
add( XEC_SSA_APPEND, "append" );
add( XEC_SSA_EXTEND, "extend" );
add( XEC_SSA_CATCH, "catch" );
add( XEC_SSA_RETHROW, "rethrow" );
add( XEC_SSA_KEY, "key" );
add( XEC_SSA_DELKEY, "delkey" );
add( XEC_SSA_GLOBAL, "global" );
add( XEC_SSA_SETGLOBAL, "setglobal" );
add( XEC_SSA_PARAM, "param" );
add( XEC_SSA_VARARG, "vararg" );
add( XEC_SSA_SELECT, "select" );
add( XEC_SSA_UNPACK, "unpack" );
add( XEC_SSA_NEWUP, "newup" );
add( XEC_SSA_REFUP, "refup" );
add( XEC_SSA_SETUP, "setup" );
add( XEC_SSA_CLOSE, "close" );
add( XEC_SSA_ARRAY, "array" );
add( XEC_SSA_TABLE, "table" );
add( XEC_SSA_NEXT, "next" );
add( XEC_SSA_SETINKEY, "setinkey" );
add( XEC_SSA_SETINDEX, "setindex" );
add( XEC_SSA_SETKEY, "setkey" );
add( XEC_SSA_CALL, "call" );
add( XEC_SSA_YCALL, "ycall" );
add( XEC_SSA_YIELD, "yield" );
add( XEC_SSA_NEW, "new" );
add( XEC_SSA_RETURN, "return" );
add( XEC_SSA_LAMBDA, "lambda" );
add( XEC_SSA_PHI, "phi" );
add( XEC_SSA_LIVE, "live" );
}
const char* lookup( xec_ssa_opcode o ) const
{
return map.at( o );
}
private:
void add( xec_ssa_opcode o, const char* n )
{
map.emplace( o, n );
}
std::unordered_map< int, const char* > map;
};
static const xec_ssa_opnames opnames;
void xec_ssa_printer::print_slice( xec_ssa_func* func, xec_ssa_slice* slice )
{
for ( size_t i = 0; i < slice->ops.size(); ++i )
{
xec_ssa_opref opref;
opref.slice = slice->index;
opref.index = (int)i;
printf( "%04X:%02X ", opref.slice, opref.index );
print_op( func, slice->ops.at( i ) );
print_names( func, opref );
printf( "\n" );
}
}
void xec_ssa_printer::print_op( xec_ssa_func* func, xec_ssa_op& op )
{
printf( "[" );
if ( op.opcode >= XEC_SSA_FIRST_SET
&& op.opcode <= XEC_SSA_LAST_SET )
{
printf( "----:--|----:--" );
}
else
{
if ( op.until == XEC_SSA_FOREVER )
{
printf( "vvvv:vv" );
}
else if ( op.until )
{
printf( "%04X:%02X", op.until.slice, op.until.index );
}
else
{
printf( "----:--" );
}
printf( "|" );
if ( op.lnext )
{
printf( "%04X:%02X", op.lnext.slice, op.lnext.index );
}
else
{
printf( "----:--" );
}
}
printf( "] " );
const char* opname = opnames.lookup( op.opcode );
printf( "%-9s", opname );
if ( ( op.opcode >= XEC_SSA_FIRST_REF
&& op.opcode <= XEC_SSA_LAST_REF )
|| op.opcode == XEC_SSA_LIVE )
{
if ( op.operanda )
{
printf( " %04X:%02X", op.operanda.slice, op.operanda.index );
}
if ( op.operandb )
{
printf( " %04X:%02X", op.operandb.slice, op.operandb.index );
}
}
else if ( op.opcode >= XEC_SSA_FIRST_KEY
&& op.opcode <= XEC_SSA_LAST_KEY )
{
if ( op.operanda )
{
printf( " %04X:%02X", op.operanda.slice, op.operanda.index );
}
const char* key = root->keys.at( op.immkey );
printf( " '%s'", key );
}
else if ( op.opcode >= XEC_SSA_FIRST_IMM
&& op.opcode <= XEC_SSA_LAST_IMM )
{
if ( op.operanda )
{
printf( " %04X:%02X", op.operanda.slice, op.operanda.index );
}
printf( " $%d", op.immkey );
}
else if ( op.opcode >= XEC_SSA_FIRST_SET
&& op.opcode <= XEC_SSA_LAST_SET )
{
printf( " %04X:%02X", op.operanda.slice, op.operanda.index );
if ( op.opcode == XEC_SSA_SETKEY )
{
const char* key = root->keys.at( op.immkey );
printf( " '%s'", key );
}
else
{
printf( " %04X:%02X", op.operandb.slice, op.operandb.index );
}
printf( " %04X:%02X", op.operandv.slice, op.operandv.index );
}
else if ( op.opcode >= XEC_SSA_FIRST_ARG
&& op.opcode <= XEC_SSA_LAST_ARG )
{
printf( " $%d", op.args->resultcount );
for ( size_t i = 0; i < op.args->args.size(); ++i )
{
xec_ssa_opref arg = op.args->args.at( i );
printf( " %04X:%02X", arg.slice, arg.index );
}
if ( op.args->unpacked )
{
xec_ssa_opref unpacked = op.args->unpacked;
printf( " %04X:%02X ...", unpacked.slice, unpacked.index );
}
}
else switch ( op.opcode )
{
case XEC_SSA_NOP:
case XEC_SSA_NULL:
break;
case XEC_SSA_NUMBER:
printf( " %g", op.number );
break;
case XEC_SSA_BOOL:
printf( " %s", op.boolean ? "true" : "false" );
break;
case XEC_SSA_STRING:
{
printf( " \"" );
for ( size_t i = 0; i < op.string->length; ++i )
{
char c = op.string->string[ i ];
if ( c >= 0x20 && c <= 0x7E )
{
printf( "%c", c );
}
else switch ( c )
{
case 0x07: printf( "\\a" ); break;
case 0x08: printf( "\\b" ); break;
case 0x09: printf( "\\t" ); break;
case 0x0A: printf( "\\n" ); break;
case 0x0B: printf( "\\v" ); break;
case 0x0C: printf( "\\f" ); break;
case 0x0D: printf( "\\r" ); break;
case '"': printf( "\\\"" ); break;
default: printf( "\\x%02X", c ); break;
}
}
printf( "\"" );
break;
}
case XEC_SSA_PHI:
{
for ( size_t i = 0; i < op.phi->definitions.size(); ++i )
{
xec_ssa_opref def = op.phi->definitions.at( i );
printf( " %04X:%02X", def.slice, def.index );
}
break;
}
case XEC_SSA_LAMBDA:
{
printf( " %p", op.lambda->function );
for ( size_t i = 0; i < op.lambda->upvals.size(); ++i )
{
xec_ssa_opref upval = op.lambda->upvals.at( i );
printf( " %04X:%02X", upval.slice, upval.index );
}
break;
}
case XEC_SSA_LIVE:
break;
default:
break;
}
}
void xec_ssa_printer::print_names( xec_ssa_func* func, xec_ssa_opref opref )
{
auto ii = func->names.equal_range( opref );
for ( auto i = ii.first; i != ii.second; ++i )
{
if ( i == ii.first )
printf( " ( " );
else
printf( ", " );
printf( "%s", i->second->name );
}
if ( ii.first != ii.second )
{
printf( " )" );
}
}
void xec_ssa_print( xec_ssa* ssa )
{
for ( size_t i = 0; i < ssa->functions.size(); ++i )
{
xec_ssa_printer printer( ssa );
printer.print( ssa->functions.at( i ) );
}
}
<|endoftext|>
|
<commit_before>#ifndef MEAS_DIFFUSION_HPP
#define MEAS_DIFFUSION_HPP
#include<stdio.h>
#include<vector>
#include<map>
class Meas_Diffusion
{
public:
int icall;
bool written;
int delay;
public:
Meas_Diffusion(float Emin=0, float Emax=1, float _Ebin=1);
void init(float Emin, float Emax, float Ebin);
void clear() { old.clear(); for(int i=0; i<NBinE; i++) Emom[i]=0; }
void write();
template<typename MCWalker>
void add_sample(const MCWalker& walker, bool at_equilibrium=true);
private:
float Elo, Ehi, Ebin;
int NBinE;
int bin(float E) const { int ibin=static_cast<int>((E-Elo)/Ebin); if(ibin<0) ibin=0; if(ibin>=NBinE) ibin=NBinE-1; return ibin; }
enum { MAXK = 3 };
std::vector<double> Emom;
std::map<int,double> old;
};
Meas_Diffusion::Meas_Diffusion(float Emin, float Emax, float _Ebin)
{
icall = 0;
written = true;
delay=1000;
init(Emin,Emax,_Ebin);
}
void Meas_Diffusion::init(float Emin, float Emax, float _Ebin)
{
float Erange = Emax - Emin;
Ebin = _Ebin;
NBinE = Erange/Ebin;
Elo = Emin;
Ehi = Elo + Ebin*NBinE;
Emom.resize( MAXK*NBinE );
clear();
}
template<typename MCWalker>
void Meas_Diffusion::add_sample(const MCWalker& walker, bool at_equilibrium)
{
if( !at_equilibrium ) return;
icall++;
long long imcs = walker.imcs;
if( (imcs%delay) != 0 ) return;
int iwalk = walker.iwalk_global;
double Enow = walker.now.E;
std::map<int,double>::iterator iEold = old.find(iwalk);
if( iEold != old.end() )
{
written = false;
double Eold = iEold->second;
double dE = Enow - Eold;
int ibin = bin(Eold);
double Ek = 1;
for(int k=0; k<MAXK; k++)
{
Emom[ ibin*MAXK + k ] += Ek;
Ek *= dE;
}
}
old[iwalk] = Enow;
}
void Meas_Diffusion::write()
{
std::vector<double> Emom_global(Emom.size());
# ifdef USE_MPI
for(int i=0; i<Emom_global.size(); i++) Emom_global[i] = 0;
MPI_Allreduce(&(Emom[0]),&(Emom_global[0]),Emom.size(),MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
int iproc = 0;
MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
if( iproc!=0 ) return;
# else
Emom_global = Emom;
# endif
FILE* fout = fopen("Meas_Diffusion.csv","w");
fprintf(fout,"# Diffusion of Walkers vs Energy for delay of %d mcs\n",delay);
fprintf(fout,"# Column 1: Energy\n");
fprintf(fout,"# Column 2: Mean bias <E1-E0>\n");
fprintf(fout,"# Column 3: Mean-squared change <(E1-E0)^2>\n");
fprintf(fout,"# Column 4: RMS change sqrt(Col 3)\n");
fprintf(fout,"# Column 5: number of cts\n");
fprintf(fout,"# Column 6: accumulated sum deltaE\n");
fprintf(fout,"# Column 7: accumulated sum deltaE^2\n");
for(int ibin=0; ibin<NBinE; ibin++)
{
double N = Emom_global[ibin*MAXK+0];
if( N>1 )
{
double E = Elo + (ibin+0.5)*Ebin;
double mean = Emom_global[ibin*MAXK+1]/N;
double meansq = Emom_global[ibin*MAXK+2]/N;
double rms = std::sqrt(meansq);
fprintf(fout,"%lf %lf %lf %lf",E,mean,meansq,rms);
for(int k=0; k<MAXK; k++) fprintf(fout," %20.16le",Emom_global[ibin*MAXK+k]);
fprintf(fout,"\n");
}
}
}
#endif
<commit_msg>Brought into caledonia.cpp interface<commit_after>#ifndef MEAS_DIFFUSION_HPP
#define MEAS_DIFFUSION_HPP
#include<stdio.h>
#include<vector>
#include<map>
class Meas_Diffusion
{
public:
int icall;
bool written;
int delay;
public:
Meas_Diffusion(float Emin=0, float Emax=1, float _Ebin=1);
void init(float Emin, float Emax, float Ebin);
template<typename SIMULATION> void init(SIMULATION& sim);
void clear() { old.clear(); for(int i=0; i<NBinE; i++) Emom[i]=0; }
void write();
template<typename MCWalker>
void add_sample(const MCWalker& walker, bool at_equilibrium=true);
private:
float Elo, Ehi, Ebin;
int NBinE;
int bin(float E) const { int ibin=static_cast<int>((E-Elo)/Ebin); if(ibin<0) ibin=0; if(ibin>=NBinE) ibin=NBinE-1; return ibin; }
enum { MAXK = 3 };
std::vector<double> Emom;
std::map<int,double> old;
};
Meas_Diffusion::Meas_Diffusion(float Emin, float Emax, float _Ebin)
{
icall = 0;
written = true;
delay=1000;
init(Emin,Emax,_Ebin);
}
void Meas_Diffusion::init(float Emin, float Emax, float _Ebin)
{
float Erange = Emax - Emin;
Ebin = _Ebin;
NBinE = Erange/Ebin;
Elo = Emin;
Ehi = Elo + Ebin*NBinE;
Emom.resize( MAXK*NBinE );
clear();
}
template<typename SIMULATION> void Meas_Diffusion::init(SIMULATION& sim)
{
this->init(sim.Elo,sim.Ehi,sim.Ehi);
}
template<typename MCWalker>
void Meas_Diffusion::add_sample(const MCWalker& walker, bool at_equilibrium)
{
if( !at_equilibrium ) return;
icall++;
long long imcs = walker.imcs;
if( (imcs%delay) != 0 ) return;
int iwalk = walker.iwalk_global;
double Enow = walker.now.E;
std::map<int,double>::iterator iEold = old.find(iwalk);
if( iEold != old.end() )
{
written = false;
double Eold = iEold->second;
double dE = Enow - Eold;
int ibin = bin(Eold);
double Ek = 1;
for(int k=0; k<MAXK; k++)
{
Emom[ ibin*MAXK + k ] += Ek;
Ek *= dE;
}
}
old[iwalk] = Enow;
}
void Meas_Diffusion::write()
{
std::vector<double> Emom_global(Emom.size());
# ifdef USE_MPI
for(int i=0; i<Emom_global.size(); i++) Emom_global[i] = 0;
MPI_Allreduce(&(Emom[0]),&(Emom_global[0]),Emom.size(),MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
int iproc = 0;
MPI_Comm_rank(MPI_COMM_WORLD,&iproc);
if( iproc!=0 ) return;
# else
Emom_global = Emom;
# endif
FILE* fout = fopen("Meas_Diffusion.csv","w");
fprintf(fout,"# Diffusion of Walkers vs Energy for delay of %d mcs\n",delay);
fprintf(fout,"# Column 1: Energy\n");
fprintf(fout,"# Column 2: Mean bias <E1-E0>\n");
fprintf(fout,"# Column 3: Mean-squared change <(E1-E0)^2>\n");
fprintf(fout,"# Column 4: RMS change sqrt(Col 3)\n");
fprintf(fout,"# Column 5: number of cts\n");
fprintf(fout,"# Column 6: accumulated sum deltaE\n");
fprintf(fout,"# Column 7: accumulated sum deltaE^2\n");
for(int ibin=0; ibin<NBinE; ibin++)
{
double N = Emom_global[ibin*MAXK+0];
if( N>1 )
{
double E = Elo + (ibin+0.5)*Ebin;
double mean = Emom_global[ibin*MAXK+1]/N;
double meansq = Emom_global[ibin*MAXK+2]/N;
double rms = std::sqrt(meansq);
fprintf(fout,"%lf %lf %lf %lf",E,mean,meansq,rms);
for(int k=0; k<MAXK; k++) fprintf(fout," %20.16le",Emom_global[ibin*MAXK+k]);
fprintf(fout,"\n");
}
}
}
#endif
<|endoftext|>
|
<commit_before>#include <catch.hpp>
#include <string>
#include <unordered_map>
TEST_CASE("literals encoding strategy") {
char const literal[] = { 0, 1, 2 };
std::string s(literal, sizeof(literal)/sizeof(char));
CHECK(s.size()==3);
}
namespace {
class Resource /*final*/ {
public:
typedef std::string(*ResourceGetter)();
public:
static std::string Test();
static std::string PlainText();
public: // key/value api
static std::string Get(std::string const& key);
public:
static std::string OnNoKey() {
// can be throwing or not
return "";
}
};
std::string Resource::Test() {
static char const literal[] = { 0, 1, 2, 0, 1 };
return std::string(literal, sizeof(literal)/sizeof(char));
}
std::string Resource::PlainText() {
static char const literal[] = "some plain text";
return std::string(literal);
}
std::string Resource::Get(std::string const& key) {
static std::unordered_map<std::string,ResourceGetter> getters = {
{ "Test", Resource::Test },
{ "PlainText", Resource::PlainText },
};
auto getter = getters.find(key);
if (getter == getters.end())
return OnNoKey();
return getter->second();
}
}
TEST_CASE("api") {
auto res=Resource::Test();
char const literal[] = { 0, 1, 2, 0, 1 };
std::string reference(literal, 5);
CHECK( reference == res );
std::string another(literal, 3);
CHECK( another != res );
CHECK( Resource::PlainText() == "some plain text" );
SECTION("key/value api") {
CHECK( Resource::Get("PlainText") == "some plain text" );
CHECK( Resource::Get("Whatever") == "" );
}
}
<commit_msg>get all keys concept<commit_after>#include <catch.hpp>
#include <string>
#include <unordered_map>
TEST_CASE("literals encoding strategy") {
char const literal[] = { 0, 1, 2 };
std::string s(literal, sizeof(literal)/sizeof(char));
CHECK(s.size()==3);
}
namespace {
class Resource /*final*/ {
public:
typedef std::string(*ResourceGetter)();
public:
static std::string Test();
static std::string PlainText();
public: // key/value api
template <typename TInserter>
static void GetKeys(TInserter& inserter) {
static const char* keys[] = {
"Test",
"PlainText"
};
for (auto key : keys)
inserter = key;
}
static std::string Get(std::string const& key);
public:
static std::string OnNoKey() {
// can be throwing or not
return "";
}
};
std::string Resource::Test() {
static char const literal[] = { 0, 1, 2, 0, 1 };
return std::string(literal, sizeof(literal)/sizeof(char));
}
std::string Resource::PlainText() {
static char const literal[] = "some plain text";
return std::string(literal);
}
std::string Resource::Get(std::string const& key) {
static std::unordered_map<std::string,ResourceGetter> getters = {
{ "Test", Resource::Test },
{ "PlainText", Resource::PlainText },
};
auto getter = getters.find(key);
if (getter == getters.end())
return OnNoKey();
return getter->second();
}
}
TEST_CASE("api") {
auto res=Resource::Test();
char const literal[] = { 0, 1, 2, 0, 1 };
std::string reference(literal, 5);
CHECK( reference == res );
std::string another(literal, 3);
CHECK( another != res );
CHECK( Resource::PlainText() == "some plain text" );
SECTION("key/value api") {
CHECK( Resource::Get("PlainText") == "some plain text" );
CHECK( Resource::Get("Whatever") == "" );
}
SECTION("getting all keys") {
std::vector<std::string> keys;
Resource::GetKeys(std::back_inserter(keys));
CHECK(keys.size() == 2);
CHECK(keys[0] == "Test");
CHECK(keys[1] == "PlainText");
}
}
<|endoftext|>
|
<commit_before>
/****************************************************************************
** Copyright (c) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** 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 the LibQxt project 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 <COPYRIGHT HOLDER> 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.
**
** <http://libqxt.org> <[email protected]>
*****************************************************************************/
#include "qxtavahipoll.h"
#include "qxtavahipoll_p.h"
#include <QThread>
#include <QDebug>
#include <avahi-common/timeval.h>
// declare the functions for the struct
// comments copied from watch.h so that I know what they do :P
/* Create a new watch for the specified file descriptor and for
* the specified events. The API will call the callback function
* whenever any of the events happens. */
AvahiWatch* qxtAvahiWatchNew(const AvahiPoll *api, int fd, AvahiWatchEvent event, AvahiWatchCallback callback, void *userdata);
/* Update the events to wait for. It is safe to call this function from an AvahiWatchCallback */
void qxtAvahiWatchUpdate(AvahiWatch *w, AvahiWatchEvent event);
/* Return the events that happened. It is safe to call this function from an AvahiWatchCallback */
AvahiWatchEvent qxtAvahiWatchGetEvents(AvahiWatch *w);
/* Free a watch. It is safe to call this function from an AvahiWatchCallback */
void qxtAvahiWatchFree(AvahiWatch *w);
/* Set a wakeup time for the polling loop. The API will call the
callback function when the absolute time *tv is reached. If tv is
NULL, the timeout is disabled. After the timeout expired the
callback function will be called and the timeout is disabled. You
can reenable it by calling timeout_update() */
AvahiTimeout* qxtAvahiTimeoutNew(const AvahiPoll *api, const struct timeval *tv, AvahiTimeoutCallback callback, void *userdata);
/* Update the absolute expiration time for a timeout, If tv is
* NULL, the timeout is disabled. It is safe to call this function from an AvahiTimeoutCallback */
void qxtAvahiTimeoutUpdate(AvahiTimeout *, const struct timeval *tv);
/* Free a timeout. It is safe to call this function from an AvahiTimeoutCallback */
void qxtAvahiTimeoutFree(AvahiTimeout *t);
const AvahiPoll* qxtAvahiPoll(void)
{
static const AvahiPoll avahiPoll =
{
NULL,
qxtAvahiWatchNew,
qxtAvahiWatchUpdate,
qxtAvahiWatchGetEvents,
qxtAvahiWatchFree,
qxtAvahiTimeoutNew,
qxtAvahiTimeoutUpdate,
qxtAvahiTimeoutFree
};
return &avahiPoll;
}
AvahiWatch* qxtAvahiWatchNew(const AvahiPoll *api, int fd, AvahiWatchEvent event, AvahiWatchCallback callback, void *userdata)
{
return new AvahiWatch(fd, event, callback, userdata);
}
void qxtAvahiWatchUpdate(AvahiWatch *w, AvahiWatchEvent event)
{
w->setEventType(event);
}
AvahiWatchEvent qxtAvahiWatchGetEvents(AvahiWatch *w)
{
return w->lastEvent();
}
void qxtAvahiWatchFree(AvahiWatch *w)
{
if (w->thread() == QThread::currentThread())
delete w;
else
w->deleteLater();
}
AvahiTimeout* qxtAvahiTimeoutNew(const AvahiPoll *api, const struct timeval *tv, AvahiTimeoutCallback callback, void *userdata)
{
return new AvahiTimeout(tv, callback, userdata);
}
void qxtAvahiTimeoutUpdate(AvahiTimeout *t, const struct timeval *tv)
{
t->updateTimeout(tv);
}
void qxtAvahiTimeoutFree(AvahiTimeout *t)
{
if (t->thread() == QThread::currentThread())
delete t;
else
t->deleteLater();
}
/* WATCH */
AvahiWatch::AvahiWatch(int fd, AvahiWatchEvent event, AvahiWatchCallback callback, void *userdata)
: _notifier(0),
_fd(fd),
_event(event),
_lastEvent((AvahiWatchEvent)0),
_callback(callback),
_userdata(userdata)
{
setEventType(event);
}
AvahiWatch::~AvahiWatch()
{
}
void AvahiWatch::setEventType(AvahiWatchEvent event)
{
if (_notifier != 0)
{
if (_notifier->thread() == QThread::currentThread())
delete _notifier;
else
_notifier->deleteLater();
_notifier = 0;
}
_event = event;
switch (_event)
{
case AVAHI_WATCH_IN:
{
_notifier = new QSocketNotifier(_fd, QSocketNotifier::Read, this);
connect(_notifier, SIGNAL(activated(int)), this, SLOT(activated(int)));
break;
}
case AVAHI_WATCH_OUT:
{
_notifier = new QSocketNotifier(_fd, QSocketNotifier::Write, this);
connect(_notifier, SIGNAL(activated(int)), this, SLOT(activated(int)));
break;
}
default: //The constructor should only get in or out...
qWarning("AvahiWatch: Bad event type passed to AvahiWatch constructor");
break;
}
}
void AvahiWatch::activated(int fd)
{
_lastEvent = _event;
_callback(this, fd, _event, _userdata);
_lastEvent = (AvahiWatchEvent)0;
}
AvahiWatchEvent AvahiWatch::lastEvent()
{
return _lastEvent;
}
/* TIMEOUT */
AvahiTimeout::AvahiTimeout(const struct timeval *tv, AvahiTimeoutCallback callback, void* userdata)
: _callback(callback),
_userdata(userdata)
{
connect(&_timer, SIGNAL(timeout()), this, SLOT(timeout()));
updateTimeout(tv);
}
AvahiTimeout::~AvahiTimeout()
{
}
void AvahiTimeout::updateTimeout(const struct timeval *tv)
{
if (tv == 0)
{
_timer.stop();
return;
}
qint64 msecs = (avahi_age(tv)) / 1000;
if (msecs > 0)
msecs = 0;
else
msecs = -msecs;
_timer.setInterval(msecs);
_timer.start();
}
void AvahiTimeout::timeout()
{
_timer.stop();
_callback(this, _userdata);
}
<commit_msg>Supresses compiler warning about unused parameter using Q_UNUSED macro<commit_after>
/****************************************************************************
** Copyright (c) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** 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 the LibQxt project 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 <COPYRIGHT HOLDER> 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.
**
** <http://libqxt.org> <[email protected]>
*****************************************************************************/
#include "qxtavahipoll.h"
#include "qxtavahipoll_p.h"
#include <QThread>
#include <QDebug>
#include <avahi-common/timeval.h>
// declare the functions for the struct
// comments copied from watch.h so that I know what they do :P
/* Create a new watch for the specified file descriptor and for
* the specified events. The API will call the callback function
* whenever any of the events happens. */
AvahiWatch* qxtAvahiWatchNew(const AvahiPoll *api, int fd, AvahiWatchEvent event, AvahiWatchCallback callback, void *userdata);
/* Update the events to wait for. It is safe to call this function from an AvahiWatchCallback */
void qxtAvahiWatchUpdate(AvahiWatch *w, AvahiWatchEvent event);
/* Return the events that happened. It is safe to call this function from an AvahiWatchCallback */
AvahiWatchEvent qxtAvahiWatchGetEvents(AvahiWatch *w);
/* Free a watch. It is safe to call this function from an AvahiWatchCallback */
void qxtAvahiWatchFree(AvahiWatch *w);
/* Set a wakeup time for the polling loop. The API will call the
callback function when the absolute time *tv is reached. If tv is
NULL, the timeout is disabled. After the timeout expired the
callback function will be called and the timeout is disabled. You
can reenable it by calling timeout_update() */
AvahiTimeout* qxtAvahiTimeoutNew(const AvahiPoll *api, const struct timeval *tv, AvahiTimeoutCallback callback, void *userdata);
/* Update the absolute expiration time for a timeout, If tv is
* NULL, the timeout is disabled. It is safe to call this function from an AvahiTimeoutCallback */
void qxtAvahiTimeoutUpdate(AvahiTimeout *, const struct timeval *tv);
/* Free a timeout. It is safe to call this function from an AvahiTimeoutCallback */
void qxtAvahiTimeoutFree(AvahiTimeout *t);
const AvahiPoll* qxtAvahiPoll(void)
{
static const AvahiPoll avahiPoll =
{
NULL,
qxtAvahiWatchNew,
qxtAvahiWatchUpdate,
qxtAvahiWatchGetEvents,
qxtAvahiWatchFree,
qxtAvahiTimeoutNew,
qxtAvahiTimeoutUpdate,
qxtAvahiTimeoutFree
};
return &avahiPoll;
}
AvahiWatch* qxtAvahiWatchNew(const AvahiPoll *api, int fd, AvahiWatchEvent event, AvahiWatchCallback callback, void *userdata)
{
return new AvahiWatch(fd, event, callback, userdata);
}
void qxtAvahiWatchUpdate(AvahiWatch *w, AvahiWatchEvent event)
{
w->setEventType(event);
}
AvahiWatchEvent qxtAvahiWatchGetEvents(AvahiWatch *w)
{
return w->lastEvent();
}
void qxtAvahiWatchFree(AvahiWatch *w)
{
if (w->thread() == QThread::currentThread())
delete w;
else
w->deleteLater();
}
AvahiTimeout* qxtAvahiTimeoutNew(const AvahiPoll *api, const struct timeval *tv, AvahiTimeoutCallback callback, void *userdata)
{
return new AvahiTimeout(tv, callback, userdata);
}
void qxtAvahiTimeoutUpdate(AvahiTimeout *t, const struct timeval *tv)
{
t->updateTimeout(tv);
}
void qxtAvahiTimeoutFree(AvahiTimeout *t)
{
if (t->thread() == QThread::currentThread())
delete t;
else
t->deleteLater();
}
/* WATCH */
AvahiWatch::AvahiWatch(int fd, AvahiWatchEvent event, AvahiWatchCallback callback, void *userdata)
: _notifier(0),
_fd(fd),
_event(event),
_lastEvent((AvahiWatchEvent)0),
_callback(callback),
_userdata(userdata)
{
setEventType(event);
}
AvahiWatch::~AvahiWatch()
{
}
void AvahiWatch::setEventType(AvahiWatchEvent event)
{
if (_notifier != 0)
{
if (_notifier->thread() == QThread::currentThread())
delete _notifier;
else
_notifier->deleteLater();
_notifier = 0;
}
_event = event;
switch (_event)
{
case AVAHI_WATCH_IN:
{
_notifier = new QSocketNotifier(_fd, QSocketNotifier::Read, this);
connect(_notifier, SIGNAL(activated(int)), this, SLOT(activated(int)));
break;
}
case AVAHI_WATCH_OUT:
{
_notifier = new QSocketNotifier(_fd, QSocketNotifier::Write, this);
connect(_notifier, SIGNAL(activated(int)), this, SLOT(activated(int)));
break;
}
default: //The constructor should only get in or out...
qWarning("AvahiWatch: Bad event type passed to AvahiWatch constructor");
break;
}
}
void AvahiWatch::activated(int fd)
{
Q_UNUSED(fd);
_lastEvent = _event;
_callback(this, _fd, _event, _userdata);
_lastEvent = (AvahiWatchEvent)0;
}
AvahiWatchEvent AvahiWatch::lastEvent()
{
return _lastEvent;
}
/* TIMEOUT */
AvahiTimeout::AvahiTimeout(const struct timeval *tv, AvahiTimeoutCallback callback, void* userdata)
: _callback(callback),
_userdata(userdata)
{
connect(&_timer, SIGNAL(timeout()), this, SLOT(timeout()));
updateTimeout(tv);
}
AvahiTimeout::~AvahiTimeout()
{
}
void AvahiTimeout::updateTimeout(const struct timeval *tv)
{
if (tv == 0)
{
_timer.stop();
return;
}
qint64 msecs = (avahi_age(tv)) / 1000;
if (msecs > 0)
msecs = 0;
else
msecs = -msecs;
_timer.setInterval(msecs);
_timer.start();
}
void AvahiTimeout::timeout()
{
_timer.stop();
_callback(this, _userdata);
}
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2016 Sergej Zuyev (sergej.zuyev - at - zz-systems.net)
//
// 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.
//---------------------------------------------------------------------------------
#pragma once
/// @see https://stackoverflow.com/a/22291538/1261537
#if defined(_MSC_VER)
/* Microsoft C/C++-compatible compiler */
#include <intrin.h>
#include <smmintrin.h>
#elif (defined(__GNUC__)) && (defined(__x86_64__) || defined(__i386__))
/* GCC-compatible compiler, targeting x86/x86-64 */
#include <x86intrin.h>
#elif defined(__GNUC__) && defined(__ARM_NEON__)
/* GCC-compatible compiler, targeting ARM with NEON */
#include <arm_neon.h>
#elif defined(__GNUC__) && defined(__IWMMXT__)
/* GCC-compatible compiler, targeting ARM with WMMX */
#include <mmintrin.h>
#elif (defined(__GNUC__) || defined(__xlC__)) && (defined(__VEC__) || defined(__ALTIVEC__))
/* XLC or GCC-compatible compiler, targeting PowerPC with VMX/VSX */
#include <altivec.h>
#elif defined(__GNUC__) && defined(__SPE__)
/* GCC-compatible compiler, targeting PowerPC with SPE */
#include <spe.h>
#endif
#if defined(__clang__)
#elif defined(__GNUC__) || defined(__GNUG__)
#if defined(ZACC_AVX) || defined(ZACC_AVX2)
inline __m256 _mm256_set_m128(__m128 hi, __m128 lo)
{
return _mm256_insertf128_ps(_mm256_castps128_ps256(hi), (lo), 1);
}
inline __m256d _mm256_set_m128d(__m128d hi, __m128d lo)
{
return _mm256_insertf128_pd(_mm256_castpd128_pd256(hi), (lo), 1);
}
#endif
#elif defined(_MSC_VER)
#endif
#if !defined(_MSC_VER) && (defined(ZACC_AVX) || defined(ZACC_AVX2))
inline bool _mm256_test_all_ones(__m256 val)
{
auto ival = _mm256_castps_si256(val);
return _mm256_testc_si256(ival, _mm256_cmpeq_epi32(ival, ival));
}
inline bool _mm256_test_all_ones(__m256i val)
{
return _mm256_testc_si256(val, _mm256_cmpeq_epi32(val, val));
}
#endif
template<typename T>
std::enable_if_t<!zacc::is_zval<T>::value, bool> is_set(T value)
{
return value != 0;
};
void adjust_rounding_mode()
{
#if defined(_MM_SET_ROUNDING_MODE) && defined(_MM_SET_FLUSH_ZERO_MODE)
_MM_SET_ROUNDING_MODE(_MM_ROUND_TOWARD_ZERO);
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
#endif
}<commit_msg>fix inlining...<commit_after>//---------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2016 Sergej Zuyev (sergej.zuyev - at - zz-systems.net)
//
// 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.
//---------------------------------------------------------------------------------
#pragma once
/// @see https://stackoverflow.com/a/22291538/1261537
#if defined(_MSC_VER)
/* Microsoft C/C++-compatible compiler */
#include <intrin.h>
#include <smmintrin.h>
#elif (defined(__GNUC__)) && (defined(__x86_64__) || defined(__i386__))
/* GCC-compatible compiler, targeting x86/x86-64 */
#include <x86intrin.h>
#elif defined(__GNUC__) && defined(__ARM_NEON__)
/* GCC-compatible compiler, targeting ARM with NEON */
#include <arm_neon.h>
#elif defined(__GNUC__) && defined(__IWMMXT__)
/* GCC-compatible compiler, targeting ARM with WMMX */
#include <mmintrin.h>
#elif (defined(__GNUC__) || defined(__xlC__)) && (defined(__VEC__) || defined(__ALTIVEC__))
/* XLC or GCC-compatible compiler, targeting PowerPC with VMX/VSX */
#include <altivec.h>
#elif defined(__GNUC__) && defined(__SPE__)
/* GCC-compatible compiler, targeting PowerPC with SPE */
#include <spe.h>
#endif
#if defined(__clang__)
#elif defined(__GNUC__) || defined(__GNUG__)
#if defined(ZACC_AVX) || defined(ZACC_AVX2)
inline __m256 _mm256_set_m128(__m128 hi, __m128 lo)
{
return _mm256_insertf128_ps(_mm256_castps128_ps256(hi), (lo), 1);
}
inline __m256d _mm256_set_m128d(__m128d hi, __m128d lo)
{
return _mm256_insertf128_pd(_mm256_castpd128_pd256(hi), (lo), 1);
}
#endif
#elif defined(_MSC_VER)
#endif
#if !defined(_MSC_VER) && (defined(ZACC_AVX) || defined(ZACC_AVX2))
inline bool _mm256_test_all_ones(__m256 val)
{
auto ival = _mm256_castps_si256(val);
return _mm256_testc_si256(ival, _mm256_cmpeq_epi32(ival, ival));
}
inline bool _mm256_test_all_ones(__m256i val)
{
return _mm256_testc_si256(val, _mm256_cmpeq_epi32(val, val));
}
#endif
template<typename T>
std::enable_if_t<!zacc::is_zval<T>::value, bool> is_set(T value)
{
return value != 0;
};
inline void adjust_rounding_mode()
{
#if defined(_MM_SET_ROUNDING_MODE) && defined(_MM_SET_FLUSH_ZERO_MODE)
_MM_SET_ROUNDING_MODE(_MM_ROUND_TOWARD_ZERO);
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
#endif
}<|endoftext|>
|
<commit_before>#pragma once
/**
* \file algorithm.hpp
*
* This header providers various high-level functions to perform common
* algorithms and communication patterns found in bulk-synchronous parallel
* programs.
*/
#include <vector>
#include "world.hpp"
#include "coarray.hpp"
#include "communication.hpp"
namespace bulk {
/**
* Perform a left-associative fold over a distributed variable.
*
* This function applies a function to the images of a variable. This function
* should be called in the same step on each processor.
*
* \tparam T the type of the value held by \c x.
* \tparam World the world to which \c x is registered.
* \tparam Func the binary function to apply to the images of \c x.
*
* \param x the variable to fold over
* \param f a binary function that takes two arguments of type `T`.
*
* \returns the result of the expression
* \f[ f(f(f(f(x(0), x(1)), x(2)), ...), x(p-1)). \f]
* which is computed at each core.
*/
template <typename T, typename World, template<typename,class> class var_type, typename Func>
T foldl(var_type<T, World>& x, Func f, T start_value = 0) {
auto& world = x.world();
T result = start_value;
// allocate space to store each remote value locally
std::vector<bulk::future<T, World>> images;
for (int t = 0; t < world.active_processors(); ++t) {
// obtain the remote values
images.push_back(bulk::get<T>(t, x));
}
world.sync();
for (int t = 0; t < world.active_processors(); ++t) {
// apply f iteratively to the current value, and each remote value
f(result, images[t].value());
}
return result;
}
/**
* Creates a co-array with images holding the given value on each processor.
*
* This function takes an argument, and writes it to the appropriate element on
* each remote processor. This function should be called in the same step on
* each processor.
*
* \tparam T the type of the value to put in the co-array
* \tparam World the world in which the communication takes place
*
* \param value the value to write to each remote processor
* \param world the world of the targetted processors
*
* \returns a co-array containing on each processor the argument given by each
* other processor.
*/
template <typename T, typename World>
coarray<T, World> gather_all(World& world, T value) {
auto xs = create_coarray<T>(world, world.active_processors());
for (int t = 0; t < world.active_processors(); ++t) {
xs(t)[world.processor_id()] = value;
}
world.sync();
return xs;
}
} // namespace bulk
<commit_msg>Change gather_all operation return type for custom coarrays<commit_after>#pragma once
/**
* \file algorithm.hpp
*
* This header providers various high-level functions to perform common
* algorithms and communication patterns found in bulk-synchronous parallel
* programs.
*/
#include <vector>
#include "world.hpp"
#include "coarray.hpp"
#include "communication.hpp"
namespace bulk {
/**
* Perform a left-associative fold over a distributed variable.
*
* This function applies a function to the images of a variable. This function
* should be called in the same step on each processor.
*
* \tparam T the type of the value held by \c x.
* \tparam World the world to which \c x is registered.
* \tparam Func the binary function to apply to the images of \c x.
*
* \param x the variable to fold over
* \param f a binary function that takes two arguments of type `T`.
*
* \returns the result of the expression
* \f[ f(f(f(f(x(0), x(1)), x(2)), ...), x(p-1)). \f]
* which is computed at each core.
*/
template <typename T, typename World, template<typename,class> class var_type, typename Func>
T foldl(var_type<T, World>& x, Func f, T start_value = 0) {
auto& world = x.world();
T result = start_value;
// allocate space to store each remote value locally
std::vector<bulk::future<T, World>> images;
for (int t = 0; t < world.active_processors(); ++t) {
// obtain the remote values
images.push_back(bulk::get<T>(t, x));
}
world.sync();
for (int t = 0; t < world.active_processors(); ++t) {
// apply f iteratively to the current value, and each remote value
f(result, images[t].value());
}
return result;
}
/**
* Creates a co-array with images holding the given value on each processor.
*
* This function takes an argument, and writes it to the appropriate element on
* each remote processor. This function should be called in the same step on
* each processor.
*
* \tparam T the type of the value to put in the co-array
* \tparam World the world in which the communication takes place
*
* \param value the value to write to each remote processor
* \param world the world of the targetted processors
*
* \returns a co-array containing on each processor the argument given by each
* other processor.
*/
template <typename T, typename World>
auto gather_all(World& world, T value) {
auto xs = create_coarray<T>(world, world.active_processors());
for (int t = 0; t < world.active_processors(); ++t) {
xs(t)[world.processor_id()] = value;
}
world.sync();
return xs;
}
} // namespace bulk
<|endoftext|>
|
<commit_before><commit_msg>accept svg documents in svg: namespace (hack)<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (C) 2021 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "perf.hh"
#include <seastar/core/reactor.hh>
#include <seastar/core/memory.hh>
#include "seastarx.hh"
void scheduling_latency_measurer::schedule_tick() {
seastar::schedule(make_task(default_scheduling_group(), [self = weak_from_this()] () mutable {
if (self) {
self->tick();
}
}));
}
std::ostream& operator<<(std::ostream& out, const scheduling_latency_measurer& slm) {
auto to_ms = [] (int64_t nanos) {
return float(nanos) / 1e6;
};
return out << sprint("{count: %d, "
//"min: %.6f [ms], "
//"50%%: %.6f [ms], "
//"90%%: %.6f [ms], "
"99%%: %.6f [ms], "
"max: %.6f [ms]}",
slm.histogram().count(),
//to_ms(slm.min().count()),
//to_ms(slm.histogram().percentile(0.5)),
//to_ms(slm.histogram().percentile(0.9)),
to_ms(slm.histogram().percentile(0.99)),
to_ms(slm.max().count()));
}
executor_shard_stats
executor_shard_stats_snapshot() {
return executor_shard_stats{
.allocations = memory::stats().mallocs(),
.tasks_executed = engine().get_sched_stats().tasks_processed,
};
}
std::ostream&
operator<<(std::ostream& os, const perf_result& result) {
fmt::print(os, "{:.2f} tps ({:.0} allocs/op, {:.0} tasks/op)",
result.throughput, result.mallocs_per_op, result.tasks_per_op);
return os;
}
<commit_msg>test: perf: don't truncate allocation/req and tasks/req report<commit_after>/*
* Copyright (C) 2021 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "perf.hh"
#include <seastar/core/reactor.hh>
#include <seastar/core/memory.hh>
#include "seastarx.hh"
void scheduling_latency_measurer::schedule_tick() {
seastar::schedule(make_task(default_scheduling_group(), [self = weak_from_this()] () mutable {
if (self) {
self->tick();
}
}));
}
std::ostream& operator<<(std::ostream& out, const scheduling_latency_measurer& slm) {
auto to_ms = [] (int64_t nanos) {
return float(nanos) / 1e6;
};
return out << sprint("{count: %d, "
//"min: %.6f [ms], "
//"50%%: %.6f [ms], "
//"90%%: %.6f [ms], "
"99%%: %.6f [ms], "
"max: %.6f [ms]}",
slm.histogram().count(),
//to_ms(slm.min().count()),
//to_ms(slm.histogram().percentile(0.5)),
//to_ms(slm.histogram().percentile(0.9)),
to_ms(slm.histogram().percentile(0.99)),
to_ms(slm.max().count()));
}
executor_shard_stats
executor_shard_stats_snapshot() {
return executor_shard_stats{
.allocations = memory::stats().mallocs(),
.tasks_executed = engine().get_sched_stats().tasks_processed,
};
}
std::ostream&
operator<<(std::ostream& os, const perf_result& result) {
fmt::print(os, "{:.2f} tps ({:5.1f} allocs/op, {:5.1f} tasks/op)",
result.throughput, result.mallocs_per_op, result.tasks_per_op);
return os;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015-2018, LAAS-CNRS
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of gepetto-viewer.
// gepetto-viewer 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
// 3 of the License, or (at your option) any later version.
//
// gepetto-viewer is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// gepetto-viewer. If not, see <http://www.gnu.org/licenses/>.
#ifndef GEPETTO_GUI_FWD_HH
#define GEPETTO_GUI_FWD_HH
#include <vector>
#include <QtGui/qopengl.h>
#include <QtGui>
#include <gepetto/viewer/macros.h>
#include <gepetto/viewer/fwd.h>
#include <gepetto/gui/config-dep.hh>
namespace gepetto {
namespace gui {
class MainWindow;
class OSGWidget;
class PickHandler;
class BodyTreeWidget;
class BodyTreeItem;
typedef std::vector<BodyTreeItem*> BodyTreeItems_t;
class ShortcutFactory;
class SelectionHandler;
class SelectionEvent;
class ActionSearchBar;
typedef viewer::NodePtr_t NodePtr_t;
typedef viewer::GroupNodePtr_t GroupNodePtr_t;
typedef viewer::Configuration Configuration;
class ViewerCorbaServer;
class WindowsManager;
typedef viewer::shared_ptr <WindowsManager> WindowsManagerPtr_t;
#if GEPETTO_GUI_HAS_PYTHONQT
class PythonWidget;
#endif
} // namespace gui
} // namespace gepetto
#endif // GEPETTO_GUI_FWD_HH
<commit_msg>Fix Qt4 compilation<commit_after>// Copyright (c) 2015-2018, LAAS-CNRS
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of gepetto-viewer.
// gepetto-viewer 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
// 3 of the License, or (at your option) any later version.
//
// gepetto-viewer is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// gepetto-viewer. If not, see <http://www.gnu.org/licenses/>.
#ifndef GEPETTO_GUI_FWD_HH
#define GEPETTO_GUI_FWD_HH
#include <vector>
#include <QtGlobal>
#if QT_VERSION >= 0x050000
# include <QtGui/qopengl.h>
#endif
#include <QtGui>
#include <gepetto/viewer/macros.h>
#include <gepetto/viewer/fwd.h>
#include <gepetto/gui/config-dep.hh>
namespace gepetto {
namespace gui {
class MainWindow;
class OSGWidget;
class PickHandler;
class BodyTreeWidget;
class BodyTreeItem;
typedef std::vector<BodyTreeItem*> BodyTreeItems_t;
class ShortcutFactory;
class SelectionHandler;
class SelectionEvent;
class ActionSearchBar;
typedef viewer::NodePtr_t NodePtr_t;
typedef viewer::GroupNodePtr_t GroupNodePtr_t;
typedef viewer::Configuration Configuration;
class ViewerCorbaServer;
class WindowsManager;
typedef viewer::shared_ptr <WindowsManager> WindowsManagerPtr_t;
#if GEPETTO_GUI_HAS_PYTHONQT
class PythonWidget;
#endif
} // namespace gui
} // namespace gepetto
#endif // GEPETTO_GUI_FWD_HH
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: statusbarcontroller.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-09-09 17:13:16 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVTOOLS_STATUSBARCONTROLLER_HXX
#define _SVTOOLS_STATUSBARCONTROLLER_HXX
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XUPDATABLE_HPP_
#include <com/sun/star/util/XUpdatable.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSBARCONTROLLER_HPP_
#include <com/sun/star/frame/XStatusbarController.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <drafts/com/sun/star/frame/XLayoutManager.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#include <hash_map>
namespace svt
{
class StatusbarController : public ::com::sun::star::frame::XStatusListener,
public ::com::sun::star::frame::XStatusbarController,
public ::com::sun::star::lang::XInitialization,
public ::com::sun::star::util::XUpdatable,
public ::com::sun::star::lang::XComponent,
public ::comphelper::OBaseMutex,
public ::cppu::OWeakObject
{
public:
StatusbarController( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager,
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame,
const rtl::OUString& aCommandURL,
unsigned short nID );
StatusbarController();
virtual ~StatusbarController();
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > getFrameInterface() const;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getServiceManager() const;
::com::sun::star::uno::Reference< ::drafts::com::sun::star::frame::XLayoutManager > getLayoutManager() const;
::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > getURLTransformer() const;
void updateStatus( const rtl::OUString aCommandURL );
void updateStatus();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw ();
virtual void SAL_CALL release() throw ();
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XUpdatable
virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException);
// XComponent
virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );
// XStatusbarController
virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos,
::sal_Int32 nCommand,
::sal_Bool bMouseEvent,
const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics,
const ::com::sun::star::awt::Rectangle& rOutputRectangle,
::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException);
protected:
struct Listener
{
Listener( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) :
aURL( rURL ), xDispatch( rDispatch ) {}
::com::sun::star::util::URL aURL;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
};
typedef ::std::hash_map< ::rtl::OUString,
com::sun::star::uno::Reference< com::sun::star::frame::XDispatch >,
::rtl::OUStringHash,
::std::equal_to< ::rtl::OUString > > URLToDispatchMap;
// methods to support status forwarder, known by the old sfx2 toolbox controller implementation
void addStatusListener( const rtl::OUString& aCommandURL );
void removeStatusListener( const rtl::OUString& aCommandURL );
void bindListener();
void unbindListener();
sal_Bool isBound() const;
// execute methods
// execute bound status bar controller command/execute various commands
void execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
void execute( const rtl::OUString& aCommand, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
sal_Bool m_bInitialized : 1,
m_bDisposed : 1;
unsigned short m_nID;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xParentWindow;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
rtl::OUString m_aCommandURL;
URLToDispatchMap m_aListenerMap;
::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener
mutable ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > m_xURLTransformer;
};
}
#endif // _SVTOOLS_TOOLBOXCONTROLLER_HXX
<commit_msg>INTEGRATION: CWS removedrafts (1.2.204); FILE MERGED 2005/02/17 14:05:29 cd 1.2.204.1: #i42557# Move UNOIDL types from drafts to com<commit_after>/*************************************************************************
*
* $RCSfile: statusbarcontroller.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2005-03-01 19:50:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVTOOLS_STATUSBARCONTROLLER_HXX
#define _SVTOOLS_STATUSBARCONTROLLER_HXX
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XUPDATABLE_HPP_
#include <com/sun/star/util/XUpdatable.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSBARCONTROLLER_HPP_
#include <com/sun/star/frame/XStatusbarController.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <com/sun/star/frame/XLayoutManager.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#include <hash_map>
namespace svt
{
class StatusbarController : public ::com::sun::star::frame::XStatusListener,
public ::com::sun::star::frame::XStatusbarController,
public ::com::sun::star::lang::XInitialization,
public ::com::sun::star::util::XUpdatable,
public ::com::sun::star::lang::XComponent,
public ::comphelper::OBaseMutex,
public ::cppu::OWeakObject
{
public:
StatusbarController( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager,
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame,
const rtl::OUString& aCommandURL,
unsigned short nID );
StatusbarController();
virtual ~StatusbarController();
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > getFrameInterface() const;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getServiceManager() const;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > getLayoutManager() const;
::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > getURLTransformer() const;
void updateStatus( const rtl::OUString aCommandURL );
void updateStatus();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw ();
virtual void SAL_CALL release() throw ();
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XUpdatable
virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException);
// XComponent
virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );
// XStatusbarController
virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos,
::sal_Int32 nCommand,
::sal_Bool bMouseEvent,
const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics,
const ::com::sun::star::awt::Rectangle& rOutputRectangle,
::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException);
protected:
struct Listener
{
Listener( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) :
aURL( rURL ), xDispatch( rDispatch ) {}
::com::sun::star::util::URL aURL;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
};
typedef ::std::hash_map< ::rtl::OUString,
com::sun::star::uno::Reference< com::sun::star::frame::XDispatch >,
::rtl::OUStringHash,
::std::equal_to< ::rtl::OUString > > URLToDispatchMap;
// methods to support status forwarder, known by the old sfx2 toolbox controller implementation
void addStatusListener( const rtl::OUString& aCommandURL );
void removeStatusListener( const rtl::OUString& aCommandURL );
void bindListener();
void unbindListener();
sal_Bool isBound() const;
// execute methods
// execute bound status bar controller command/execute various commands
void execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
void execute( const rtl::OUString& aCommand, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
sal_Bool m_bInitialized : 1,
m_bDisposed : 1;
unsigned short m_nID;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xParentWindow;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
rtl::OUString m_aCommandURL;
URLToDispatchMap m_aListenerMap;
::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener
mutable ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > m_xURLTransformer;
};
}
#endif // _SVTOOLS_TOOLBOXCONTROLLER_HXX
<|endoftext|>
|
<commit_before>/*******************************************************
* Copyright (c) 2018, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/traits.hpp>
#include <iostream>
#include <complex>
#include <testHelpers.hpp>
#include <limits>
using af::array;
using af::cdouble;
using af::cfloat;
using af::constant;
using af::dim4;
using af::dtype;
using af::dtype_traits;
using af::exception;
using af::identity;
using af::matmul;
using af::max;
using af::pinverse;
using af::randu;
using af::span;
using std::abs;
using std::string;
using std::vector;
template<typename T>
array makeComplex(dim4 dims, const vector<T>& real, const vector<T>& imag) {
array realArr(dims, &real.front());
array imagArr(dims, &imag.front());
return af::complex(realArr, imagArr);
}
template<typename T>
array readTestInput(string testFilePath) {
typedef typename dtype_traits<T>::base_type InBaseType;
dtype outAfType = (dtype) dtype_traits<T>::af_type;
vector<dim4> dimsVec;
vector<vector<InBaseType> > inVec;
vector<vector<InBaseType> > goldVec;
readTestsFromFile<InBaseType, InBaseType>(testFilePath, dimsVec, inVec, goldVec);
dim4 inDims = dimsVec[0];
if (outAfType == c32 || outAfType == c64) {
return makeComplex(inDims, inVec[1], inVec[2]);
}
else {
return array(inDims, &inVec[0].front());
}
}
template<typename T>
array readTestGold(string testFilePath) {
typedef typename dtype_traits<T>::base_type InBaseType;
dtype outAfType = (dtype) dtype_traits<T>::af_type;
vector<dim4> dimsVec;
vector<vector<InBaseType> > inVec;
vector<vector<InBaseType> > goldVec;
readTestsFromFile<InBaseType, InBaseType>(testFilePath, dimsVec, inVec, goldVec);
dim4 goldDims(dimsVec[0][1], dimsVec[0][0]);
if (outAfType == c32 || outAfType == c64) {
return makeComplex(goldDims, goldVec[1], goldVec[2]);
}
else {
return array(goldDims, &goldVec[0].front());
}
}
template<typename T>
class Pinverse : public ::testing::Test
{
};
// Epsilons taken from test/inverse.cpp
template<typename T>
double eps();
template<>
double eps<float>() {
return 0.01f;
}
template<>
double eps<double>() {
return 1e-5;
}
template<>
double eps<cfloat>() {
return 0.01f;
}
template<>
double eps<cdouble>() {
return 1e-5;
}
template<typename T>
double relEps(array in) {
typedef typename af::dtype_traits<T>::base_type InBaseType;
return std::numeric_limits<InBaseType>::epsilon()
* std::max(in.dims(0), in.dims(1)) * af::max<double>(in);
}
typedef ::testing::Types<float, cfloat, double, cdouble> TestTypes;
TYPED_TEST_CASE(Pinverse, TestTypes);
// Test Moore-Penrose conditions in the following first 4 tests
// See https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse#Definition
TYPED_TEST(Pinverse, AApinvA_A) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<TypeParam>());
}
TYPED_TEST(Pinverse, ApinvAApinv_Apinv) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in);
array out = matmul(inpinv, in, inpinv);
ASSERT_ARRAYS_NEAR(inpinv, out, eps<TypeParam>());
}
TYPED_TEST(Pinverse, AApinv_IsHermitian) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in);
array aapinv = matmul(in, inpinv);
array out = matmul(in, inpinv).H();
ASSERT_ARRAYS_NEAR(aapinv, out, eps<TypeParam>());
}
TYPED_TEST(Pinverse, ApinvA_IsHermitian) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in);
array apinva = af::matmul(inpinv, in);
array out = af::matmul(inpinv, in).H();
ASSERT_ARRAYS_NEAR(apinva, out, eps<TypeParam>());
}
TYPED_TEST(Pinverse, Large) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse640x480.test"));
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, relEps<TypeParam>(in));
}
TYPED_TEST(Pinverse, LargeTall) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse640x480.test")).T();
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, relEps<TypeParam>(in));
}
TEST(Pinverse, Square) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x10.test"));
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<float>());
}
TEST(Pinverse, Dim1GtDim0) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse8x10.test"));
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<float>());
}
TEST(Pinverse, CompareWithNumpy) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array gold = readTestGold<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array out = pinverse(in);
ASSERT_ARRAYS_NEAR(gold, out, relEps<float>(gold));
}
TEST(Pinverse, SmallSigValExistsFloat) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
const dim_t dim0 = in.dims(0);
const dim_t dim1 = in.dims(1);
// Generate sigma with small non-zero value
af::array u;
af::array vT;
af::array sVec;
af::svd(u, sVec, vT, in);
dim_t sSize = sVec.elements();
sVec(2) = 1e-12;
af::array s = af::diag(sVec, 0, false);
af::array zeros = af::constant(0,
dim0 > sSize ? dim0 - sSize : sSize,
dim1 > sSize ? dim1 - sSize : sSize);
s = af::join(dim0 > dim1 ? 0 : 1, s, zeros);
// Make new input array that has a small non-zero value in its SVD sigma
in = af::matmul(u, s, vT);
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<float>());
}
TEST(Pinverse, SmallSigValExistsDouble) {
array in = readTestInput<double>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
const dim_t dim0 = in.dims(0);
const dim_t dim1 = in.dims(1);
// Generate sigma with small non-zero value
array u;
array vT;
array sVec;
svd(u, sVec, vT, in);
dim_t sSize = sVec.elements();
sVec(2) = (double) 1e-16;
array s = diag(sVec, 0, false);
array zeros = constant(0,
dim0 > sSize ? dim0 - sSize : sSize,
dim1 > sSize ? dim1 - sSize : sSize,
f64);
s = join(dim0 > dim1 ? 0 : 1, s, zeros);
// Make new input array that has a small non-zero value in its SVD sigma
in = matmul(u, s, vT);
array inpinv = pinverse(in, 1e-15);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<double>());
}
TEST(Pinverse, Batching3D) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8x2.test"));
array inpinv0 = pinverse(in(span, span, 0));
array inpinv1 = pinverse(in(span, span, 1));
array out = pinverse(in);
array out0 = out(span, span, 0);
array out1 = out(span, span, 1);
ASSERT_ARRAYS_NEAR(inpinv0, out0, relEps<float>(inpinv0));
ASSERT_ARRAYS_NEAR(inpinv1, out1, relEps<float>(inpinv1));
}
TEST(Pinverse, Batching4D) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8x2x2.test"));
array inpinv00 = pinverse(in(span, span, 0, 0));
array inpinv01 = pinverse(in(span, span, 0, 1));
array inpinv10 = pinverse(in(span, span, 1, 0));
array inpinv11 = pinverse(in(span, span, 1, 1));
array out = pinverse(in);
array out00 = out(span, span, 0, 0);
array out01 = out(span, span, 0, 1);
array out10 = out(span, span, 1, 0);
array out11 = out(span, span, 1, 1);
ASSERT_ARRAYS_NEAR(inpinv00, out00, relEps<float>(inpinv00));
ASSERT_ARRAYS_NEAR(inpinv01, out01, relEps<float>(inpinv01));
ASSERT_ARRAYS_NEAR(inpinv10, out10, relEps<float>(inpinv10));
ASSERT_ARRAYS_NEAR(inpinv11, out11, relEps<float>(inpinv11));
}
TEST(Pinverse, CustomTol) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in, 1e-12);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<float>());
}
TEST(Pinverse, C) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
af_array inpinv = 0, out = 0;
ASSERT_SUCCESS(af_pinverse(&inpinv, in.get(), 1e-6, AF_MAT_NONE));
ASSERT_SUCCESS(af_matmul(&out, in.get(), inpinv, AF_MAT_NONE, AF_MAT_NONE));
ASSERT_SUCCESS(af_matmul(&out, out, in.get(), AF_MAT_NONE, AF_MAT_NONE));
ASSERT_ARRAYS_NEAR(in.get(), out, eps<float>());
ASSERT_SUCCESS(af_release_array(out));
ASSERT_SUCCESS(af_release_array(inpinv));
}
TEST(Pinverse, C_CustomTol) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
af_array inpinv = 0, out = 0;
ASSERT_SUCCESS(af_pinverse(&inpinv, in.get(), 1e-12, AF_MAT_NONE));
ASSERT_SUCCESS(af_matmul(&out, in.get(), inpinv, AF_MAT_NONE, AF_MAT_NONE));
ASSERT_SUCCESS(af_matmul(&out, out, in.get(), AF_MAT_NONE, AF_MAT_NONE));
ASSERT_ARRAYS_NEAR(in.get(), out, eps<float>());
ASSERT_SUCCESS(af_release_array(out));
ASSERT_SUCCESS(af_release_array(inpinv));
}
TEST(Pinverse, NegativeTol) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array out;
ASSERT_THROW(out = pinverse(in, -1.f), exception);
}
TEST(Pinverse, InvalidType) {
array in = constant(0, 10, 8, u8);
array out;
ASSERT_THROW(out = pinverse(in, -1.f), exception);
}
TEST(Pinverse, InvalidMatProp) {
array in = constant(0.f, 10, 8, f32);
array out;
ASSERT_THROW(out = pinverse(in, -1.f, AF_MAT_SYM), exception);
}
TEST(Pinverse, DocSnippet) {
//! [ex_pinverse]
float hA[] = {0, 1, 2, 3, 4, 5};
array A(3, 2, hA);
// 0.0000 3.0000
// 1.0000 4.0000
// 2.0000 5.0000
array Apinv = pinverse(A);
// -0.7778 -0.1111 0.5556
// 0.2778 0.1111 -0.0556
array MustBeA = matmul(A, Apinv, A);
// 0.0000 3.0000
// 1.0000 4.0000
// 2.0000 5.0000
//! [ex_pinverse]
ASSERT_ARRAYS_NEAR(A, MustBeA, eps<float>());
}
<commit_msg>Fix memory leaks on pinverse C tests<commit_after>/*******************************************************
* Copyright (c) 2018, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/traits.hpp>
#include <iostream>
#include <complex>
#include <testHelpers.hpp>
#include <limits>
using af::array;
using af::cdouble;
using af::cfloat;
using af::constant;
using af::dim4;
using af::dtype;
using af::dtype_traits;
using af::exception;
using af::identity;
using af::matmul;
using af::max;
using af::pinverse;
using af::randu;
using af::span;
using std::abs;
using std::string;
using std::vector;
template<typename T>
array makeComplex(dim4 dims, const vector<T>& real, const vector<T>& imag) {
array realArr(dims, &real.front());
array imagArr(dims, &imag.front());
return af::complex(realArr, imagArr);
}
template<typename T>
array readTestInput(string testFilePath) {
typedef typename dtype_traits<T>::base_type InBaseType;
dtype outAfType = (dtype) dtype_traits<T>::af_type;
vector<dim4> dimsVec;
vector<vector<InBaseType> > inVec;
vector<vector<InBaseType> > goldVec;
readTestsFromFile<InBaseType, InBaseType>(testFilePath, dimsVec, inVec, goldVec);
dim4 inDims = dimsVec[0];
if (outAfType == c32 || outAfType == c64) {
return makeComplex(inDims, inVec[1], inVec[2]);
}
else {
return array(inDims, &inVec[0].front());
}
}
template<typename T>
array readTestGold(string testFilePath) {
typedef typename dtype_traits<T>::base_type InBaseType;
dtype outAfType = (dtype) dtype_traits<T>::af_type;
vector<dim4> dimsVec;
vector<vector<InBaseType> > inVec;
vector<vector<InBaseType> > goldVec;
readTestsFromFile<InBaseType, InBaseType>(testFilePath, dimsVec, inVec, goldVec);
dim4 goldDims(dimsVec[0][1], dimsVec[0][0]);
if (outAfType == c32 || outAfType == c64) {
return makeComplex(goldDims, goldVec[1], goldVec[2]);
}
else {
return array(goldDims, &goldVec[0].front());
}
}
template<typename T>
class Pinverse : public ::testing::Test
{
};
// Epsilons taken from test/inverse.cpp
template<typename T>
double eps();
template<>
double eps<float>() {
return 0.01f;
}
template<>
double eps<double>() {
return 1e-5;
}
template<>
double eps<cfloat>() {
return 0.01f;
}
template<>
double eps<cdouble>() {
return 1e-5;
}
template<typename T>
double relEps(array in) {
typedef typename af::dtype_traits<T>::base_type InBaseType;
return std::numeric_limits<InBaseType>::epsilon()
* std::max(in.dims(0), in.dims(1)) * af::max<double>(in);
}
typedef ::testing::Types<float, cfloat, double, cdouble> TestTypes;
TYPED_TEST_CASE(Pinverse, TestTypes);
// Test Moore-Penrose conditions in the following first 4 tests
// See https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse#Definition
TYPED_TEST(Pinverse, AApinvA_A) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<TypeParam>());
}
TYPED_TEST(Pinverse, ApinvAApinv_Apinv) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in);
array out = matmul(inpinv, in, inpinv);
ASSERT_ARRAYS_NEAR(inpinv, out, eps<TypeParam>());
}
TYPED_TEST(Pinverse, AApinv_IsHermitian) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in);
array aapinv = matmul(in, inpinv);
array out = matmul(in, inpinv).H();
ASSERT_ARRAYS_NEAR(aapinv, out, eps<TypeParam>());
}
TYPED_TEST(Pinverse, ApinvA_IsHermitian) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in);
array apinva = af::matmul(inpinv, in);
array out = af::matmul(inpinv, in).H();
ASSERT_ARRAYS_NEAR(apinva, out, eps<TypeParam>());
}
TYPED_TEST(Pinverse, Large) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse640x480.test"));
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, relEps<TypeParam>(in));
}
TYPED_TEST(Pinverse, LargeTall) {
array in = readTestInput<TypeParam>(string(TEST_DIR"/pinverse/pinverse640x480.test")).T();
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, relEps<TypeParam>(in));
}
TEST(Pinverse, Square) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x10.test"));
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<float>());
}
TEST(Pinverse, Dim1GtDim0) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse8x10.test"));
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<float>());
}
TEST(Pinverse, CompareWithNumpy) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array gold = readTestGold<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array out = pinverse(in);
ASSERT_ARRAYS_NEAR(gold, out, relEps<float>(gold));
}
TEST(Pinverse, SmallSigValExistsFloat) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
const dim_t dim0 = in.dims(0);
const dim_t dim1 = in.dims(1);
// Generate sigma with small non-zero value
af::array u;
af::array vT;
af::array sVec;
af::svd(u, sVec, vT, in);
dim_t sSize = sVec.elements();
sVec(2) = 1e-12;
af::array s = af::diag(sVec, 0, false);
af::array zeros = af::constant(0,
dim0 > sSize ? dim0 - sSize : sSize,
dim1 > sSize ? dim1 - sSize : sSize);
s = af::join(dim0 > dim1 ? 0 : 1, s, zeros);
// Make new input array that has a small non-zero value in its SVD sigma
in = af::matmul(u, s, vT);
array inpinv = pinverse(in);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<float>());
}
TEST(Pinverse, SmallSigValExistsDouble) {
array in = readTestInput<double>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
const dim_t dim0 = in.dims(0);
const dim_t dim1 = in.dims(1);
// Generate sigma with small non-zero value
array u;
array vT;
array sVec;
svd(u, sVec, vT, in);
dim_t sSize = sVec.elements();
sVec(2) = (double) 1e-16;
array s = diag(sVec, 0, false);
array zeros = constant(0,
dim0 > sSize ? dim0 - sSize : sSize,
dim1 > sSize ? dim1 - sSize : sSize,
f64);
s = join(dim0 > dim1 ? 0 : 1, s, zeros);
// Make new input array that has a small non-zero value in its SVD sigma
in = matmul(u, s, vT);
array inpinv = pinverse(in, 1e-15);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<double>());
}
TEST(Pinverse, Batching3D) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8x2.test"));
array inpinv0 = pinverse(in(span, span, 0));
array inpinv1 = pinverse(in(span, span, 1));
array out = pinverse(in);
array out0 = out(span, span, 0);
array out1 = out(span, span, 1);
ASSERT_ARRAYS_NEAR(inpinv0, out0, relEps<float>(inpinv0));
ASSERT_ARRAYS_NEAR(inpinv1, out1, relEps<float>(inpinv1));
}
TEST(Pinverse, Batching4D) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8x2x2.test"));
array inpinv00 = pinverse(in(span, span, 0, 0));
array inpinv01 = pinverse(in(span, span, 0, 1));
array inpinv10 = pinverse(in(span, span, 1, 0));
array inpinv11 = pinverse(in(span, span, 1, 1));
array out = pinverse(in);
array out00 = out(span, span, 0, 0);
array out01 = out(span, span, 0, 1);
array out10 = out(span, span, 1, 0);
array out11 = out(span, span, 1, 1);
ASSERT_ARRAYS_NEAR(inpinv00, out00, relEps<float>(inpinv00));
ASSERT_ARRAYS_NEAR(inpinv01, out01, relEps<float>(inpinv01));
ASSERT_ARRAYS_NEAR(inpinv10, out10, relEps<float>(inpinv10));
ASSERT_ARRAYS_NEAR(inpinv11, out11, relEps<float>(inpinv11));
}
TEST(Pinverse, CustomTol) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array inpinv = pinverse(in, 1e-12);
array out = matmul(in, inpinv, in);
ASSERT_ARRAYS_NEAR(in, out, eps<float>());
}
TEST(Pinverse, C) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
af_array inpinv = 0, identity = 0, out = 0;
ASSERT_SUCCESS(af_pinverse(&inpinv, in.get(), 1e-6, AF_MAT_NONE));
ASSERT_SUCCESS(af_matmul(&identity, in.get(), inpinv, AF_MAT_NONE, AF_MAT_NONE));
ASSERT_SUCCESS(af_matmul(&out, identity, in.get(), AF_MAT_NONE, AF_MAT_NONE));
ASSERT_ARRAYS_NEAR(in.get(), out, eps<float>());
ASSERT_SUCCESS(af_release_array(out));
ASSERT_SUCCESS(af_release_array(identity));
ASSERT_SUCCESS(af_release_array(inpinv));
}
TEST(Pinverse, C_CustomTol) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
af_array inpinv = 0, identity = 0, out = 0;
ASSERT_SUCCESS(af_pinverse(&inpinv, in.get(), 1e-12, AF_MAT_NONE));
ASSERT_SUCCESS(af_matmul(&identity, in.get(), inpinv, AF_MAT_NONE, AF_MAT_NONE));
ASSERT_SUCCESS(af_matmul(&out, identity, in.get(), AF_MAT_NONE, AF_MAT_NONE));
ASSERT_ARRAYS_NEAR(in.get(), out, eps<float>());
ASSERT_SUCCESS(af_release_array(out));
ASSERT_SUCCESS(af_release_array(identity));
ASSERT_SUCCESS(af_release_array(inpinv));
}
TEST(Pinverse, NegativeTol) {
array in = readTestInput<float>(string(TEST_DIR"/pinverse/pinverse10x8.test"));
array out;
ASSERT_THROW(out = pinverse(in, -1.f), exception);
}
TEST(Pinverse, InvalidType) {
array in = constant(0, 10, 8, u8);
array out;
ASSERT_THROW(out = pinverse(in, -1.f), exception);
}
TEST(Pinverse, InvalidMatProp) {
array in = constant(0.f, 10, 8, f32);
array out;
ASSERT_THROW(out = pinverse(in, -1.f, AF_MAT_SYM), exception);
}
TEST(Pinverse, DocSnippet) {
//! [ex_pinverse]
float hA[] = {0, 1, 2, 3, 4, 5};
array A(3, 2, hA);
// 0.0000 3.0000
// 1.0000 4.0000
// 2.0000 5.0000
array Apinv = pinverse(A);
// -0.7778 -0.1111 0.5556
// 0.2778 0.1111 -0.0556
array MustBeA = matmul(A, Apinv, A);
// 0.0000 3.0000
// 1.0000 4.0000
// 2.0000 5.0000
//! [ex_pinverse]
ASSERT_ARRAYS_NEAR(A, MustBeA, eps<float>());
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <complex>
#include <vector>
#include <htool/cluster.hpp>
#include <htool/lrmat.hpp>
#include <htool/fullACA.hpp>
using namespace std;
using namespace htool;
class MyMatrix: public IMatrix<double>{
const vector<R3>& p1;
const vector<R3>& p2;
public:
MyMatrix(const vector<R3>& p10,const vector<R3>& p20 ):IMatrix<double>(p10.size(),p20.size()),p1(p10),p2(p20) {}
double get_coef(const int& i, const int& j)const {return 1./(4*M_PI*norm(p1[i]-p2[j]));}
std::vector<double> operator*(std::vector<double> a){
std::vector<double> result(p1.size(),0);
for (int i=0;i<p1.size();i++){
for (int k=0;k<p2.size();k++){
result[i]+=this->get_coef(i,k)*a[k];
}
}
return result;
}
};
int main(){
const int ndistance = 4;
double distance[ndistance];
distance[0] = 10; distance[1] = 20; distance[2] = 30; distance[3] = 40;
SetNdofPerElt(1);
bool test = 0;
for(int idist=0; idist<ndistance; idist++)
{
cout << "Distance between the clusters: " << distance[idist] << endl;
SetEpsilon(0.0001);
srand (1);
// we set a constant seed for rand because we want always the same result if we run the check many times
// (two different initializations with the same seed will generate the same succession of results in the subsequent calls to rand)
int nr = 500;
int nc = 100;
vector<int> Ir(nr); // row indices for the lrmatrix
vector<int> Ic(nc); // column indices for the lrmatrix
double z1 = 1;
vector<R3> p1(nr);
vector<double> r1(nr);
vector<int> tab1(nr);
for(int j=0; j<nr; j++){
Ir[j] = j;
double rho = ((double) rand() / (double)(RAND_MAX)); // (double) otherwise integer division!
double theta = ((double) rand() / (double)(RAND_MAX));
p1[j][0] = sqrt(rho)*cos(2*M_PI*theta); p1[j][1] = sqrt(rho)*sin(2*M_PI*theta); p1[j][2] = z1;
// sqrt(rho) otherwise the points would be concentrated in the center of the disk
r1[j]=0.;
tab1[j]=j;
}
// p2: points in a unit disk of the plane z=z2
double z2 = 1+distance[idist];
vector<R3> p2(nc);
vector<double> r2(nc);
vector<int> tab2(nc);
for(int j=0; j<nc; j++){
Ic[j] = j;
double rho = ((double) rand() / (RAND_MAX)); // (double) otherwise integer division!
double theta = ((double) rand() / (RAND_MAX));
p2[j][0] = sqrt(rho)*cos(2*M_PI*theta); p2[j][1] = sqrt(rho)*sin(2*M_PI*theta); p2[j][2] = z2;
r2[j]=0.;
tab2[j]=j;
}
MyMatrix A(p1,p2);
// ACA
int reqrank_max = 10;
fullACA<double> A_fullACA(Ir,Ic,reqrank_max);
A_fullACA.build(A);
std::vector<double> fullACA_errors;
for (int k = 0 ; k < A_fullACA.rank_of()+1 ; k++){
fullACA_errors.push_back(Frobenius_absolute_error(A_fullACA,A,k));
}
// Test errors
for (int i =1 ;i<fullACA_errors.size();i++){
test = test || !(fullACA_errors[i-1]>fullACA_errors[i]);
}
cout << "Errors with Frobenius norm: "<<fullACA_errors<<endl;
// Test compression
test = test || !(0.89<A_fullACA.compression() && A_fullACA.compression()<0.9);
cout << "Compression rate : "<<A_fullACA.compression()<<endl;
// Test error on mat vec prod
std::vector<double> f(nc,1);
double error=norm2(A*f-A_fullACA*f);
test = test ||!(error<1e-7);
cout << "Errors on a mat vec prod : "<< error<<endl;
}
return test ;
}
<commit_msg>Tests for fullACA updated<commit_after>#include <iostream>
#include <complex>
#include <vector>
#include <htool/cluster.hpp>
#include <htool/lrmat.hpp>
#include <htool/fullACA.hpp>
using namespace std;
using namespace htool;
class MyMatrix: public IMatrix<double>{
const vector<R3>& p1;
const vector<R3>& p2;
public:
MyMatrix(const vector<R3>& p10,const vector<R3>& p20 ):IMatrix<double>(p10.size(),p20.size()),p1(p10),p2(p20) {}
double get_coef(const int& i, const int& j)const {return 1./(4*M_PI*norm(p1[i]-p2[j]));}
std::vector<double> operator*(std::vector<double> a){
std::vector<double> result(p1.size(),0);
for (int i=0;i<p1.size();i++){
for (int k=0;k<p2.size();k++){
result[i]+=this->get_coef(i,k)*a[k];
}
}
return result;
}
};
int main(){
const int ndistance = 4;
double distance[ndistance];
distance[0] = 10; distance[1] = 20; distance[2] = 30; distance[3] = 40;
SetNdofPerElt(1);
bool test = 0;
for(int idist=0; idist<ndistance; idist++)
{
cout << "Distance between the clusters: " << distance[idist] << endl;
SetEpsilon(0.0001);
srand (1);
// we set a constant seed for rand because we want always the same result if we run the check many times
// (two different initializations with the same seed will generate the same succession of results in the subsequent calls to rand)
int nr = 500;
int nc = 100;
vector<int> Ir(nr); // row indices for the lrmatrix
vector<int> Ic(nc); // column indices for the lrmatrix
double z1 = 1;
vector<R3> p1(nr);
vector<double> r1(nr);
vector<int> tab1(nr);
for(int j=0; j<nr; j++){
Ir[j] = j;
double rho = ((double) rand() / (double)(RAND_MAX)); // (double) otherwise integer division!
double theta = ((double) rand() / (double)(RAND_MAX));
p1[j][0] = sqrt(rho)*cos(2*M_PI*theta); p1[j][1] = sqrt(rho)*sin(2*M_PI*theta); p1[j][2] = z1;
// sqrt(rho) otherwise the points would be concentrated in the center of the disk
r1[j]=0.;
tab1[j]=j;
}
// p2: points in a unit disk of the plane z=z2
double z2 = 1+distance[idist];
vector<R3> p2(nc);
vector<double> r2(nc);
vector<int> tab2(nc);
for(int j=0; j<nc; j++){
Ic[j] = j;
double rho = ((double) rand() / (RAND_MAX)); // (double) otherwise integer division!
double theta = ((double) rand() / (RAND_MAX));
p2[j][0] = sqrt(rho)*cos(2*M_PI*theta); p2[j][1] = sqrt(rho)*sin(2*M_PI*theta); p2[j][2] = z2;
r2[j]=0.;
tab2[j]=j;
}
MyMatrix A(p1,p2);
// ACA
int reqrank_max = 10;
fullACA<double> A_fullACA(Ir,Ic,reqrank_max);
A_fullACA.build(A);
std::vector<double> fullACA_errors;
for (int k = 0 ; k < A_fullACA.rank_of()+1 ; k++){
fullACA_errors.push_back(Frobenius_absolute_error(A_fullACA,A,k));
}
// Test errors
for (int i =1 ;i<fullACA_errors.size();i++){
test = test || !(fullACA_errors[i-1]>fullACA_errors[i]);
}
cout << "Errors with Frobenius norm: "<<fullACA_errors<<endl;
// Test compression
test = test || !(0.87<A_fullACA.compression() && A_fullACA.compression()<0.89);
cout << "Compression rate : "<<A_fullACA.compression()<<endl;
// Test error on mat vec prod
std::vector<double> f(nc,1);
double error=norm2(A*f-A_fullACA*f);
test = test ||!(error<1e-7);
cout << "Errors on a mat vec prod : "<< error<<endl;
}
return test ;
}
<|endoftext|>
|
<commit_before>// https://en.wikipedia.org/wiki/Gray_code
unsigned gray_code(unsigned n) { return n ^ (n >> 1); }
// итерирующий генератор перестановок из 6 элементов
class shuffle6
{
// набор элементов для перестановок в виде 4-х битовых групп
static const unsigned item_set = 0x543210;
// оставшиеся элементы в виде битовой строки
unsigned element_bits;
// состояние генератора от номера перестановки
unsigned factor_state;
// количество оставшихся элементов
unsigned left;
// из битовой строки bits выкусывает n-ую 4-битовую группу
unsigned cutout(unsigned n)
{
assert(n < 6);
const unsigned all1 = ~0u;
const unsigned shift = 4 * n;
const unsigned group = (element_bits >> shift) & 15;
const unsigned higher = element_bits & ((all1 << 4) << shift);
const unsigned lower = element_bits & ~(all1 << shift);
element_bits = lower | (higher >> 4);
return group;
}
public:
// количество перестановок из 6 элементов
static const unsigned factorial = 1 * 2 * 3 * 4 * 5 * 6;
// инициализирует генератор для выдачи последовательности с заданным
// номером
shuffle6(unsigned shuffle_order = 0) { setup(shuffle_order); }
void setup(unsigned shuffle_order)
{
factor_state = shuffle_order % factorial;
element_bits = item_set;
left = 6;
}
// выдает очередной элемент в конкретной перестановке
unsigned next()
{
assert(left > 0);
unsigned n = factor_state % left;
factor_state /= left;
--left;
return cutout(n);
}
bool empty() const { return left == 0; }
// тест посредством полного перебора комбинаций
static bool selftest()
{
for (unsigned n = 0; n < factorial; ++n) {
shuffle6 here(n);
unsigned probe, i;
for (probe = 0, i = 0; i < 6; ++i)
probe |= 1 << here.next();
if (probe != 63)
return false;
}
return true;
}
};
<commit_msg>fptu: minor refine shuffle6.<commit_after>// https://en.wikipedia.org/wiki/Gray_code
unsigned gray_code(unsigned n) { return n ^ (n >> 1); }
/* Итерирующий генератор перестановок из 6 элементов.
*
* В отличии от std::next_permination() и std::next_permination()
* позволяет получить перестановку непосредственно по номеру. */
class shuffle6
{
// набор элементов для перестановок в виде 4-х битовых групп
static const unsigned item_set = 0x543210;
// оставшиеся элементы в виде битовой строки
unsigned element_bits;
// состояние генератора от номера перестановки
unsigned factor_state;
// количество оставшихся элементов
unsigned left;
// из битовой строки bits выкусывает n-ую 4-битовую группу
unsigned cutout(unsigned n)
{
assert(n < 6);
const unsigned all1 = ~0u;
const unsigned shift = 4 * n;
const unsigned group = (element_bits >> shift) & 15;
const unsigned higher = element_bits & ((all1 << 4) << shift);
const unsigned lower = element_bits & ~(all1 << shift);
element_bits = lower | (higher >> 4);
return group;
}
public:
// количество перестановок из 6 элементов
static const unsigned factorial = 1 * 2 * 3 * 4 * 5 * 6;
/* инициализирует генератор для выдачи последовательности
* с заданным номером. */
shuffle6(unsigned shuffle_order = 0) { setup(shuffle_order); }
void setup(unsigned shuffle_order)
{
factor_state = shuffle_order % factorial;
element_bits = item_set;
left = 6;
}
// выдает очередной элемент в конкретной перестановке
unsigned next()
{
assert(left > 0);
unsigned n = factor_state % left;
factor_state /= left;
--left;
return cutout(n);
}
unsigned operator()() { return next(); }
bool empty() const { return left == 0; }
static bool selftest()
{
// сначала проверяем порядок
shuffle6 first(0), last(factorial - 1);
for (unsigned n = 0; n < 6; n++) {
if (first.next() != n)
return false;
if (last.next() != 5 - n)
return false;
}
// теперь полный перебор комбинаций (6! = 720)
for (unsigned n = 0; n < factorial; ++n) {
shuffle6 here(n);
unsigned probe, i;
for (probe = 0, i = 0; i < 6; ++i)
probe |= 1 << here.next();
if (probe != 63)
return false;
}
return true;
}
};
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef UNICODE_HPP
#define UNICODE_HPP
#include <string>
#include <boost/utility.hpp>
#ifdef USE_FRIBIDI
#include <fribidi/fribidi.h>
#endif
#include <iconv.h>
namespace mapnik {
/*
** Use FRIBIDI to encode the string.
** The return value must be freed by the caller.
*/
#ifdef USE_FRIBIDI
inline wchar_t* bidi_string(const wchar_t *logical)
{
FriBidiCharType base = FRIBIDI_TYPE_ON;
size_t len;
len = wcslen(logical);
FriBidiChar *visual;
FriBidiStrIndex *ltov, *vtol;
FriBidiLevel *levels;
FriBidiStrIndex new_len;
fribidi_boolean log2vis;
visual = (FriBidiChar *) malloc (sizeof (FriBidiChar) * (len + 1));
ltov = 0;
vtol = 0;
levels = 0;
/* Create a bidi string. */
log2vis = fribidi_log2vis ((FriBidiChar *)logical, len, &base,
/* output */
visual, ltov, vtol, levels);
if (!log2vis) {
return 0;
}
new_len = len;
return (wchar_t *)visual;
}
#endif
inline std::wstring to_unicode(std::string const& text)
{
std::wstring out;
unsigned long code = 0;
int expect = 0;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
unsigned p = (*itr++) & 0xff;
if ( p >= 0xc0)
{
if ( p < 0xe0) // U+0080 - U+07ff
{
expect = 1;
code = p & 0x1f;
}
else if ( p < 0xf0) // U+0800 - U+ffff
{
expect = 2;
code = p & 0x0f;
}
else if ( p < 0xf8) // U+1000 - U+10ffff
{
expect = 3;
code = p & 0x07;
}
continue;
}
else if (p >= 0x80)
{
--expect;
if (expect >= 0)
{
code <<= 6;
code += p & 0x3f;
}
if (expect > 0)
continue;
expect = 0;
}
else
{
code = p; // U+0000 - U+007f (ascii)
}
out.push_back(wchar_t(code));
}
#ifdef USE_FRIBIDI
wchar_t *bidi_text = bidi_string(out.c_str());
out = bidi_text;
free(bidi_text);
#endif
return out;
}
inline std::wstring latin1_to_unicode(std::string const& text)
{
std::wstring out;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
unsigned p = (*itr++) & 0xff;
out.push_back(wchar_t(p));
}
return out;
}
inline std::string latin1_to_unicode2(std::string const& text)
{
std::string out;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
out.push_back(0x00);
out.push_back(*itr++);
}
return out;
}
class transcoder : private boost::noncopyable
{
public:
explicit transcoder (std::string const& encoding)
{
//desc_ = iconv_open("UCS-2",encoding.c_str());
}
std::wstring transcode(std::string const& input) const
{
//return to_unicode(input);
return to_unicode(input);
/*
std::string buf(input.size() * 2,0);
size_t inleft = input.size();
const char * in = input.data();
size_t outleft = buf.size();
char * out = const_cast<char*>(buf.data());
iconv(desc_,&in,&inleft,&out,&outleft);
std::string::const_iterator itr = buf.begin();
std::string::const_iterator end = buf.end();
wchar_t wch = 0;
bool state = false;
std::wstring unicode;
size_t num_char = buf.size() - outleft;
for ( ; itr != end; ++itr)
{
if (!state)
{
wch = (*itr & 0xff);
state = true;
}
else
{
wch |= *itr << 8 ;
unicode.push_back(wchar_t(wch));
state = false;
}
if (!num_char--) break;
}
#ifdef USE_FRIBIDI
if (unicode.length() > 0)
{
wchar_t *bidi_text = bidi_string(unicode.c_str());
unicode = bidi_text;
free(bidi_text);
}
#endif
return unicode;
*/
}
~transcoder()
{
//iconv_close(desc_);
}
private:
iconv_t desc_;
};
}
#endif // UNICODE_HPP
<commit_msg>applied patch from jonb to use calloc instead of malloc (allocating fribidi buffer)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef UNICODE_HPP
#define UNICODE_HPP
#include <string>
#include <boost/utility.hpp>
#ifdef USE_FRIBIDI
#include <fribidi/fribidi.h>
#endif
#include <iconv.h>
namespace mapnik {
/*
** Use FRIBIDI to encode the string.
** The return value must be freed by the caller.
*/
#ifdef USE_FRIBIDI
inline wchar_t* bidi_string(const wchar_t *logical)
{
FriBidiCharType base = FRIBIDI_TYPE_ON;
size_t len;
len = wcslen(logical);
FriBidiChar *visual;
FriBidiStrIndex *ltov, *vtol;
FriBidiLevel *levels;
FriBidiStrIndex new_len;
fribidi_boolean log2vis;
visual = (FriBidiChar *) calloc (sizeof (FriBidiChar), len + 1);
ltov = 0;
vtol = 0;
levels = 0;
/* Create a bidi string. */
log2vis = fribidi_log2vis ((FriBidiChar *)logical, len, &base,
/* output */
visual, ltov, vtol, levels);
if (!log2vis) {
return 0;
}
new_len = len;
return (wchar_t *)visual;
}
#endif
inline std::wstring to_unicode(std::string const& text)
{
std::wstring out;
unsigned long code = 0;
int expect = 0;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
unsigned p = (*itr++) & 0xff;
if ( p >= 0xc0)
{
if ( p < 0xe0) // U+0080 - U+07ff
{
expect = 1;
code = p & 0x1f;
}
else if ( p < 0xf0) // U+0800 - U+ffff
{
expect = 2;
code = p & 0x0f;
}
else if ( p < 0xf8) // U+1000 - U+10ffff
{
expect = 3;
code = p & 0x07;
}
continue;
}
else if (p >= 0x80)
{
--expect;
if (expect >= 0)
{
code <<= 6;
code += p & 0x3f;
}
if (expect > 0)
continue;
expect = 0;
}
else
{
code = p; // U+0000 - U+007f (ascii)
}
out.push_back(wchar_t(code));
}
#ifdef USE_FRIBIDI
wchar_t *bidi_text = bidi_string(out.c_str());
out = bidi_text;
free(bidi_text);
#endif
return out;
}
inline std::wstring latin1_to_unicode(std::string const& text)
{
std::wstring out;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
unsigned p = (*itr++) & 0xff;
out.push_back(wchar_t(p));
}
return out;
}
inline std::string latin1_to_unicode2(std::string const& text)
{
std::string out;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
out.push_back(0x00);
out.push_back(*itr++);
}
return out;
}
class transcoder : private boost::noncopyable
{
public:
explicit transcoder (std::string const& encoding)
{
//desc_ = iconv_open("UCS-2",encoding.c_str());
}
std::wstring transcode(std::string const& input) const
{
//return to_unicode(input);
return to_unicode(input);
/*
std::string buf(input.size() * 2,0);
size_t inleft = input.size();
const char * in = input.data();
size_t outleft = buf.size();
char * out = const_cast<char*>(buf.data());
iconv(desc_,&in,&inleft,&out,&outleft);
std::string::const_iterator itr = buf.begin();
std::string::const_iterator end = buf.end();
wchar_t wch = 0;
bool state = false;
std::wstring unicode;
size_t num_char = buf.size() - outleft;
for ( ; itr != end; ++itr)
{
if (!state)
{
wch = (*itr & 0xff);
state = true;
}
else
{
wch |= *itr << 8 ;
unicode.push_back(wchar_t(wch));
state = false;
}
if (!num_char--) break;
}
#ifdef USE_FRIBIDI
if (unicode.length() > 0)
{
wchar_t *bidi_text = bidi_string(unicode.c_str());
unicode = bidi_text;
free(bidi_text);
}
#endif
return unicode;
*/
}
~transcoder()
{
//iconv_close(desc_);
}
private:
iconv_t desc_;
};
}
#endif // UNICODE_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: commtest.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2005-01-03 17:05:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SV_SVAPP_HXX //autogen wg. Application
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX //autogen wg. WorkWindow
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX //autogen wg. ToolBox
#include <vcl/toolbox.hxx>
#endif
#ifndef _SIMPLECM_HXX //autogen wg. CommunicationManager
#include <tools/simplecm.hxx>
#endif
#ifndef _COMMUNI_HXX //autogen
#include "communi.hxx"
#endif
#include "brooker.hxx"
//#include <tools/bcst.hxx>
#include "commtest.hrc"
#define TCP_PORT 17612
#define CUniString( constAsciiStr ) UniString( RTL_CONSTASCII_USTRINGPARAM ( constAsciiStr ) )
class PacketSender : public Timer
{
SvStream* mpData;
CommunicationLinkRef mxCL;
public:
PacketSender( ULONG nDelay, SvStream* pData, CommunicationLink* pCL );
virtual void Timeout();
};
PacketSender::PacketSender( ULONG nDelay, SvStream* pData, CommunicationLink* pCL )
: mpData( pData )
, mxCL( pCL )
{
SetTimeout( nDelay );
Start();
}
void PacketSender::Timeout()
{
mxCL->TransferDataStream( mpData );
delete mpData;
delete this;
}
class DelayedDeleter : public Timer
{
CommunicationManager *mpManager;
public:
DelayedDeleter( ULONG nDelay, CommunicationManager *pManager );
virtual void Timeout();
};
DelayedDeleter::DelayedDeleter( ULONG nDelay, CommunicationManager *pManager )
: mpManager( pManager )
{
SetTimeout( nDelay );
Start();
}
void DelayedDeleter::Timeout()
{
delete mpManager;
delete this;
}
class CommunicationTester : public Application
{
DECL_LINK( TBClick, ToolBox* );
DECL_LINK( DataReceived, CommunicationLink* );
DECL_LINK( ConnectionOpened, CommunicationLink* );
DECL_LINK( ConnectionClosed, CommunicationLink* );
CommunicationManager *pClientTcp, *pServerTcp;
InformationBroadcaster *pBCSTSend;
InformationBroadcaster *pBCSTListen;
InformationBrooker *pBCSTBrooker;
public:
CommunicationTester();
virtual void Main();
};
CommunicationTester IchSelber;
CommunicationTester::CommunicationTester()
: pClientTcp( NULL )
, pServerTcp( NULL )
, pBCSTSend( NULL )
, pBCSTListen( NULL )
, pBCSTBrooker( NULL )
{}
void CommunicationTester::Main()
{
ResMgr *pRes = ResMgr::CreateResMgr( "commtest" );
Resource::SetResManager( pRes );
WorkWindow aWW( NULL, WB_APP | WB_STDWORK );
aWW.Show();
ToolBox aTB( &aWW, ResId( TBMenu ) );
aTB.Show();
aTB.RecalcItems();
aTB.SetFloatingMode( TRUE );
aTB.SetFloatingMode( FALSE );
aTB.SetClickHdl( LINK( this, CommunicationTester, TBClick ) );
Execute();
}
#define SWITCH( pManager, ManagerClass ) \
{ \
if ( pManager ) \
{ \
pManager->StopCommunication(); \
new DelayedDeleter( 1000, pManager ); \
pTB->SetItemState( pTB->GetCurItemId(), STATE_NOCHECK ); \
pManager = NULL; \
} \
else \
{ \
pManager = new ManagerClass; \
pManager->SetConnectionOpenedHdl( LINK( this, CommunicationTester, ConnectionOpened ) );\
pManager->SetConnectionClosedHdl( LINK( this, CommunicationTester, ConnectionClosed ) );\
pManager->SetDataReceivedHdl( LINK( this, CommunicationTester, DataReceived ) );\
pTB->SetItemState( pTB->GetCurItemId(), STATE_CHECK ); \
} \
}
IMPL_LINK( CommunicationTester, TBClick, ToolBox*, pTB )
{
switch ( pTB->GetCurItemId() )
{
case SERVER_TCP:
{
SWITCH( pServerTcp, CommunicationManagerServerViaSocket( TCP_PORT, (USHORT) 32000 ) );
if ( pServerTcp )
pServerTcp->StartCommunication(); // Am Port horchen
}
break;
case CLIENT_TCP:
{
SWITCH( pClientTcp, CommunicationManagerClientViaSocket( "localhost", TCP_PORT ) );
if ( pClientTcp )
pClientTcp->StartCommunication(); // Eine Verbindung aufbauen
}
break;
case BCST_BROOKER:
{
if ( pBCSTBrooker )
{
delete pBCSTBrooker;
pBCSTBrooker = NULL;
}
else
{
pBCSTBrooker = new InformationBrooker();
}
}
break;
case BCST_LISTEN:
{
if ( pBCSTListen )
{
delete pBCSTListen;
pBCSTListen = NULL;
}
else
{
pBCSTListen = new InformationBroadcaster();
}
}
case BCST_SEND:
{
if ( pBCSTSend )
{
pBCSTSend->Broadcast( BCST_CAT_PL2X, "Message: BCST_CAT_PL2X" );
pBCSTSend->Broadcast( BCST_CAT_MINORCOPY, "Message: BCST_CAT_MINORCOPY" );
pBCSTSend->Broadcast( BCST_CAT_DELIVER, "Message: BCST_CAT_DELIVER" );
pBCSTSend->Broadcast( BCST_CAT_ALL, "Message: BCST_CAT_ALL" );
}
else
{
pBCSTSend = new InformationBroadcaster();
}
}
break;
}
return 0;
}
IMPL_LINK( CommunicationTester, ConnectionOpened, CommunicationLink*, pCL )
{
SvStream *pData = pCL->GetBestCommunicationStream();
while ( pData->Tell() < 70 ) *pData << 123;
pCL->TransferDataStream( pData );
return 0;
}
IMPL_LINK( CommunicationTester, ConnectionClosed, CommunicationLink*, pCL )
{
return 0;
}
IMPL_LINK( CommunicationTester, DataReceived, CommunicationLink*, pCL )
{
// Find Manager
CommunicationManager* pManager;
if ( pClientTcp && pClientTcp->IsLinkValid( pCL ) )
{
pManager = pClientTcp;
}
if ( pServerTcp && pServerTcp->IsLinkValid( pCL ) )
{
DBG_ASSERT( !pManager, "CommunicationLink bei mehreren Managern eingetragen");
pManager = pServerTcp;
}
DBG_ASSERT( pCL->GetCommunicationManager() == pManager, "Manager des Link != Manager bei dem der Link Valid ist");
// Send Data Back (Echo)
new PacketSender( 1000, pCL->GetServiceData(), pCL );
return 0;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.258); FILE MERGED 2005/09/05 14:54:00 rt 1.3.258.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: commtest.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:38:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SV_SVAPP_HXX //autogen wg. Application
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX //autogen wg. WorkWindow
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX //autogen wg. ToolBox
#include <vcl/toolbox.hxx>
#endif
#ifndef _SIMPLECM_HXX //autogen wg. CommunicationManager
#include <tools/simplecm.hxx>
#endif
#ifndef _COMMUNI_HXX //autogen
#include "communi.hxx"
#endif
#include "brooker.hxx"
//#include <tools/bcst.hxx>
#include "commtest.hrc"
#define TCP_PORT 17612
#define CUniString( constAsciiStr ) UniString( RTL_CONSTASCII_USTRINGPARAM ( constAsciiStr ) )
class PacketSender : public Timer
{
SvStream* mpData;
CommunicationLinkRef mxCL;
public:
PacketSender( ULONG nDelay, SvStream* pData, CommunicationLink* pCL );
virtual void Timeout();
};
PacketSender::PacketSender( ULONG nDelay, SvStream* pData, CommunicationLink* pCL )
: mpData( pData )
, mxCL( pCL )
{
SetTimeout( nDelay );
Start();
}
void PacketSender::Timeout()
{
mxCL->TransferDataStream( mpData );
delete mpData;
delete this;
}
class DelayedDeleter : public Timer
{
CommunicationManager *mpManager;
public:
DelayedDeleter( ULONG nDelay, CommunicationManager *pManager );
virtual void Timeout();
};
DelayedDeleter::DelayedDeleter( ULONG nDelay, CommunicationManager *pManager )
: mpManager( pManager )
{
SetTimeout( nDelay );
Start();
}
void DelayedDeleter::Timeout()
{
delete mpManager;
delete this;
}
class CommunicationTester : public Application
{
DECL_LINK( TBClick, ToolBox* );
DECL_LINK( DataReceived, CommunicationLink* );
DECL_LINK( ConnectionOpened, CommunicationLink* );
DECL_LINK( ConnectionClosed, CommunicationLink* );
CommunicationManager *pClientTcp, *pServerTcp;
InformationBroadcaster *pBCSTSend;
InformationBroadcaster *pBCSTListen;
InformationBrooker *pBCSTBrooker;
public:
CommunicationTester();
virtual void Main();
};
CommunicationTester IchSelber;
CommunicationTester::CommunicationTester()
: pClientTcp( NULL )
, pServerTcp( NULL )
, pBCSTSend( NULL )
, pBCSTListen( NULL )
, pBCSTBrooker( NULL )
{}
void CommunicationTester::Main()
{
ResMgr *pRes = ResMgr::CreateResMgr( "commtest" );
Resource::SetResManager( pRes );
WorkWindow aWW( NULL, WB_APP | WB_STDWORK );
aWW.Show();
ToolBox aTB( &aWW, ResId( TBMenu ) );
aTB.Show();
aTB.RecalcItems();
aTB.SetFloatingMode( TRUE );
aTB.SetFloatingMode( FALSE );
aTB.SetClickHdl( LINK( this, CommunicationTester, TBClick ) );
Execute();
}
#define SWITCH( pManager, ManagerClass ) \
{ \
if ( pManager ) \
{ \
pManager->StopCommunication(); \
new DelayedDeleter( 1000, pManager ); \
pTB->SetItemState( pTB->GetCurItemId(), STATE_NOCHECK ); \
pManager = NULL; \
} \
else \
{ \
pManager = new ManagerClass; \
pManager->SetConnectionOpenedHdl( LINK( this, CommunicationTester, ConnectionOpened ) );\
pManager->SetConnectionClosedHdl( LINK( this, CommunicationTester, ConnectionClosed ) );\
pManager->SetDataReceivedHdl( LINK( this, CommunicationTester, DataReceived ) );\
pTB->SetItemState( pTB->GetCurItemId(), STATE_CHECK ); \
} \
}
IMPL_LINK( CommunicationTester, TBClick, ToolBox*, pTB )
{
switch ( pTB->GetCurItemId() )
{
case SERVER_TCP:
{
SWITCH( pServerTcp, CommunicationManagerServerViaSocket( TCP_PORT, (USHORT) 32000 ) );
if ( pServerTcp )
pServerTcp->StartCommunication(); // Am Port horchen
}
break;
case CLIENT_TCP:
{
SWITCH( pClientTcp, CommunicationManagerClientViaSocket( "localhost", TCP_PORT ) );
if ( pClientTcp )
pClientTcp->StartCommunication(); // Eine Verbindung aufbauen
}
break;
case BCST_BROOKER:
{
if ( pBCSTBrooker )
{
delete pBCSTBrooker;
pBCSTBrooker = NULL;
}
else
{
pBCSTBrooker = new InformationBrooker();
}
}
break;
case BCST_LISTEN:
{
if ( pBCSTListen )
{
delete pBCSTListen;
pBCSTListen = NULL;
}
else
{
pBCSTListen = new InformationBroadcaster();
}
}
case BCST_SEND:
{
if ( pBCSTSend )
{
pBCSTSend->Broadcast( BCST_CAT_PL2X, "Message: BCST_CAT_PL2X" );
pBCSTSend->Broadcast( BCST_CAT_MINORCOPY, "Message: BCST_CAT_MINORCOPY" );
pBCSTSend->Broadcast( BCST_CAT_DELIVER, "Message: BCST_CAT_DELIVER" );
pBCSTSend->Broadcast( BCST_CAT_ALL, "Message: BCST_CAT_ALL" );
}
else
{
pBCSTSend = new InformationBroadcaster();
}
}
break;
}
return 0;
}
IMPL_LINK( CommunicationTester, ConnectionOpened, CommunicationLink*, pCL )
{
SvStream *pData = pCL->GetBestCommunicationStream();
while ( pData->Tell() < 70 ) *pData << 123;
pCL->TransferDataStream( pData );
return 0;
}
IMPL_LINK( CommunicationTester, ConnectionClosed, CommunicationLink*, pCL )
{
return 0;
}
IMPL_LINK( CommunicationTester, DataReceived, CommunicationLink*, pCL )
{
// Find Manager
CommunicationManager* pManager;
if ( pClientTcp && pClientTcp->IsLinkValid( pCL ) )
{
pManager = pClientTcp;
}
if ( pServerTcp && pServerTcp->IsLinkValid( pCL ) )
{
DBG_ASSERT( !pManager, "CommunicationLink bei mehreren Managern eingetragen");
pManager = pServerTcp;
}
DBG_ASSERT( pCL->GetCommunicationManager() == pManager, "Manager des Link != Manager bei dem der Link Valid ist");
// Send Data Back (Echo)
new PacketSender( 1000, pCL->GetServiceData(), pCL );
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_BASE_TYPES_H
#define NIX_BASE_TYPES_H
#include <nix/base/IProperty.hpp>
#include <nix/base/IFeature.hpp>
#include <nix/base/ISection.hpp>
#include <nix/base/ISource.hpp>
#include <nix/base/IBlock.hpp>
#include <nix/base/ISimpleTag.hpp>
#include <nix/base/IDataTag.hpp>
#include <nix/base/IDataArray.hpp>
namespace nix {
namespace base {
template class Entity<base::IProperty>;
template class Entity<base::IFeature>;
template class NamedEntity<base::ISection>;
template class EntityWithMetadata<base::ISource>;
template class EntityWithMetadata<base::IBlock>;
template class EntityWithSources<base::ISimpleTag>;
template class EntityWithSources<base::IDataTag>;
template class EntityWithSources<base::IDataArray>;
}
}
#endif
<commit_msg>Added missing includes to base/types.hpp<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_BASE_TYPES_H
#define NIX_BASE_TYPES_H
#include <nix/base/Entity.hpp>
#include <nix/base/NamedEntity.hpp>
#include <nix/base/EntityWithMetadata.hpp>
#include <nix/base/EntityWithSources.hpp>
#include <nix/base/IProperty.hpp>
#include <nix/base/IFeature.hpp>
#include <nix/base/ISection.hpp>
#include <nix/base/ISource.hpp>
#include <nix/base/IBlock.hpp>
#include <nix/base/ISimpleTag.hpp>
#include <nix/base/IDataTag.hpp>
#include <nix/base/IDataArray.hpp>
namespace nix {
namespace base {
template class Entity<base::IProperty>;
template class Entity<base::IFeature>;
template class NamedEntity<base::ISection>;
template class EntityWithMetadata<base::ISource>;
template class EntityWithMetadata<base::IBlock>;
template class EntityWithSources<base::ISimpleTag>;
template class EntityWithSources<base::IDataTag>;
template class EntityWithSources<base::IDataArray>;
}
}
#endif
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2014 Conrado Miranda
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.
*/
// This file defines a class to store many objects into a file, but a buffer is
// provided for speed.
//
// The object are read from file as needed and, when the buffer is full, they
// are removed in a LRU fashion.
//
// New objects are stored in the buffer until the archive is flushed, when they
// are saved into its file and the buffer cleared, or when some buffer slots are
// freed. When the archive is destroyed, its file is updated to take into
// account the modifications during use (removes and inserts). Hence, if a crash
// that doesn't destroy the archive occurs, the objects aren't saved!
//
// To make sure that the objects are written, the user can call flush(), which
// will completely rebuild the file.
//
// Each object is referenced by a key, whose type must be hashable and
// comparable, as it's used inside as index to an unordered_map. Both the key
// and the object must be serializable through boost.
//
// The default buffer size is zero, so no objects are kept in memory, and a
// temporary file is used as backend. For permanent storage, the user must
// provide its own filename to use.
//
// Note: the maximum buffer size provided isn't the maximum size that will
// actually be used, as there is an overhead for bookkeeping.
//
// Example:
// ObjectArchive<std::string> ar;
// ar.init("path/to/file");
// ar.set_buffer_size("1.5G");
//
// ar.insert("filename", filedata);
// [do some stuff]
// ar.load("filename", filedata);
// [filedata has the previous value again]
// ar.remove("filename");
// [filedata keeps its value]
#ifndef __OBJECT_ARCHIVE_HPP__
#define __OBJECT_ARCHIVE_HPP__
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/predef.h>
#include <fstream>
#include <functional>
#include <list>
#include <sstream>
#include <unordered_map>
template <class Key>
class ObjectArchive {
public:
// Creates an archive with a temporary file as backend, which is deleted on
// destruction. To use a permanent record, call the method init().
ObjectArchive();
// Unloads the buffer using method flush().
~ObjectArchive();
// Passes an object through boost serialize, making it easier to handle.
template <class T> static std::string serialize(T const& val);
template <class T> static void deserialize(std::string const& str, T& val);
// Initializes the archive using a temporary file as backend. As the names
// are random, it's possible to have a collision!
void init();
// Initializes the archive using a new file as backend.
void init(std::string const& filename);
// Resets the buffer size to a certain number of bytes.
void set_buffer_size(size_t max_buffer_size);
// Same as the other, but the string holds the number of bytes for the
// buffer, possibly with modifiers K, M or G. If more than one modifier is
// found, then the first one is used.
void set_buffer_size(std::string const& max_buffer_size);
#if BOOST_OS_LINUX
// Sets the buffer size to a percentage of the FREE memory available in the
// system. Currently only Linux is supported.
void set_buffer_size_scale(float max_buffer_size);
#endif
// Provides information about the maximum and current buffer sizes.
size_t get_max_buffer_size() const;
size_t get_buffer_size() const;
// Removes an object entry if it's present.
void remove(Key const& key);
// Stores an object and associates it with an id and returns the total size
// stored.
// If the object is larger than the buffer's maximum size, it isn't
// kept in memory. The user can choose not to add the object to buffer,
// which is useful if it won't be used again.
template <class T>
size_t insert(Key const& key, T const& obj, bool keep_in_buffer = true);
// Stores an object that has already been serialized.
// If the object is larger than the buffer's maximum size, it isn't
// kept in memory. The user can choose not to add the object to buffer,
// which is useful if it won't be used again.
size_t insert_raw(Key const& key, std::string const& data,
bool keep_in_buffer = true);
size_t insert_raw(Key const& key, std::string&& data,
bool keep_in_buffer = true);
// Loads the object associated with the id and stores at val. Returns the
// total size of the object, which is 0 if the object isn't found.
// If the object is larger than the buffer's maximum size, it isn't
// kept in memory. The user can choose not to add the object to buffer,
// which is useful if it won't be used again.
template <class T>
size_t load(Key const& key, T& obj, bool keep_in_buffer = true);
// Loads the raw serialized data of an object.
// If the object is larger than the buffer's maximum size, it isn't
// kept in memory. The user can choose not to add the object to buffer,
// which is useful if it won't be used again.
size_t load_raw(Key const& key, std::string& data,
bool keep_in_buffer = true);
// Saves the least recently used entries so that the buffer size is at most
// the value given in the argument. By default, frees the full buffer. If
// the argument is larger than the current buffer, does nothing.
void unload(size_t desired_size = 0);
// Checks if there exists an object with this key.
bool is_available(Key const& key) const;
// Gets a list of all the results stored in this archive.
std::list<Key const*> available_objects() const;
// Flushs the archive, guaranteeing that the data is saved to a file, which
// can be used later or continue to be used. The buffer is empty after this
// method, but the archive can still be used.
void flush();
// Removes every object entry from the archive and flushes it.
void clear();
private:
// Same as external flush, but the archive can't be used anymore.
void internal_flush();
// Writes a file back to disk, freeing its buffer space. Returns if the
// object id is inside the buffer.
bool write_back(Key const& key);
// Puts the id in the front of the list, saying it was the last one used.
struct ObjectEntry;
void touch_LRU(ObjectEntry const* entry);
// Holds the entry for one object with all the information required to
// manage it.
struct ObjectEntry {
Key key;
std::string data; // Data for the object
size_t index_in_file; // Index for finding it inside a file
size_t size; // Total object size. data.size() == size if loaded
bool modified; // If modified, the file must be written back to disk
};
std::unordered_map<Key, ObjectEntry> objects_;
std::list<ObjectEntry const*> LRU_; // Most recent elements are on the front
// Inserting or removing files changes the header and it must be rebuilt
bool must_rebuild_file_;
size_t max_buffer_size_, // Argument provided at creation
buffer_size_; // Current buffer size
std::string filename_;
bool temporary_file_;
std::fstream stream_;
};
#include "object_archive_impl.hpp"
#endif
<commit_msg>Prevent copies from being created.<commit_after>/*
The MIT License (MIT)
Copyright (c) 2014 Conrado Miranda
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.
*/
// This file defines a class to store many objects into a file, but a buffer is
// provided for speed.
//
// The object are read from file as needed and, when the buffer is full, they
// are removed in a LRU fashion.
//
// New objects are stored in the buffer until the archive is flushed, when they
// are saved into its file and the buffer cleared, or when some buffer slots are
// freed. When the archive is destroyed, its file is updated to take into
// account the modifications during use (removes and inserts). Hence, if a crash
// that doesn't destroy the archive occurs, the objects aren't saved!
//
// To make sure that the objects are written, the user can call flush(), which
// will completely rebuild the file.
//
// Each object is referenced by a key, whose type must be hashable and
// comparable, as it's used inside as index to an unordered_map. Both the key
// and the object must be serializable through boost.
//
// The default buffer size is zero, so no objects are kept in memory, and a
// temporary file is used as backend. For permanent storage, the user must
// provide its own filename to use.
//
// Note: the maximum buffer size provided isn't the maximum size that will
// actually be used, as there is an overhead for bookkeeping.
//
// Example:
// ObjectArchive<std::string> ar;
// ar.init("path/to/file");
// ar.set_buffer_size("1.5G");
//
// ar.insert("filename", filedata);
// [do some stuff]
// ar.load("filename", filedata);
// [filedata has the previous value again]
// ar.remove("filename");
// [filedata keeps its value]
#ifndef __OBJECT_ARCHIVE_HPP__
#define __OBJECT_ARCHIVE_HPP__
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/predef.h>
#include <fstream>
#include <functional>
#include <list>
#include <sstream>
#include <unordered_map>
template <class Key>
class ObjectArchive {
public:
// Creates an archive with a temporary file as backend, which is deleted on
// destruction. To use a permanent record, call the method init().
ObjectArchive();
// Unloads the buffer using method flush().
~ObjectArchive();
// Passes an object through boost serialize, making it easier to handle.
template <class T> static std::string serialize(T const& val);
template <class T> static void deserialize(std::string const& str, T& val);
// Initializes the archive using a temporary file as backend. As the names
// are random, it's possible to have a collision!
void init();
// Initializes the archive using a new file as backend.
void init(std::string const& filename);
// Resets the buffer size to a certain number of bytes.
void set_buffer_size(size_t max_buffer_size);
// Same as the other, but the string holds the number of bytes for the
// buffer, possibly with modifiers K, M or G. If more than one modifier is
// found, then the first one is used.
void set_buffer_size(std::string const& max_buffer_size);
#if BOOST_OS_LINUX
// Sets the buffer size to a percentage of the FREE memory available in the
// system. Currently only Linux is supported.
void set_buffer_size_scale(float max_buffer_size);
#endif
// Provides information about the maximum and current buffer sizes.
size_t get_max_buffer_size() const;
size_t get_buffer_size() const;
// Removes an object entry if it's present.
void remove(Key const& key);
// Stores an object and associates it with an id and returns the total size
// stored.
// If the object is larger than the buffer's maximum size, it isn't
// kept in memory. The user can choose not to add the object to buffer,
// which is useful if it won't be used again.
template <class T>
size_t insert(Key const& key, T const& obj, bool keep_in_buffer = true);
// Stores an object that has already been serialized.
// If the object is larger than the buffer's maximum size, it isn't
// kept in memory. The user can choose not to add the object to buffer,
// which is useful if it won't be used again.
size_t insert_raw(Key const& key, std::string const& data,
bool keep_in_buffer = true);
size_t insert_raw(Key const& key, std::string&& data,
bool keep_in_buffer = true);
// Loads the object associated with the id and stores at val. Returns the
// total size of the object, which is 0 if the object isn't found.
// If the object is larger than the buffer's maximum size, it isn't
// kept in memory. The user can choose not to add the object to buffer,
// which is useful if it won't be used again.
template <class T>
size_t load(Key const& key, T& obj, bool keep_in_buffer = true);
// Loads the raw serialized data of an object.
// If the object is larger than the buffer's maximum size, it isn't
// kept in memory. The user can choose not to add the object to buffer,
// which is useful if it won't be used again.
size_t load_raw(Key const& key, std::string& data,
bool keep_in_buffer = true);
// Saves the least recently used entries so that the buffer size is at most
// the value given in the argument. By default, frees the full buffer. If
// the argument is larger than the current buffer, does nothing.
void unload(size_t desired_size = 0);
// Checks if there exists an object with this key.
bool is_available(Key const& key) const;
// Gets a list of all the results stored in this archive.
std::list<Key const*> available_objects() const;
// Flushs the archive, guaranteeing that the data is saved to a file, which
// can be used later or continue to be used. The buffer is empty after this
// method, but the archive can still be used.
void flush();
// Removes every object entry from the archive and flushes it.
void clear();
private:
// Not implemented
ObjectArchive(ObjectArchive const& other);
ObjectArchive const& operator=(ObjectArchive const& other);
// Same as external flush, but the archive can't be used anymore.
void internal_flush();
// Writes a file back to disk, freeing its buffer space. Returns if the
// object id is inside the buffer.
bool write_back(Key const& key);
// Puts the id in the front of the list, saying it was the last one used.
struct ObjectEntry;
void touch_LRU(ObjectEntry const* entry);
// Holds the entry for one object with all the information required to
// manage it.
struct ObjectEntry {
Key key;
std::string data; // Data for the object
size_t index_in_file; // Index for finding it inside a file
size_t size; // Total object size. data.size() == size if loaded
bool modified; // If modified, the file must be written back to disk
};
std::unordered_map<Key, ObjectEntry> objects_;
std::list<ObjectEntry const*> LRU_; // Most recent elements are on the front
// Inserting or removing files changes the header and it must be rebuilt
bool must_rebuild_file_;
size_t max_buffer_size_, // Argument provided at creation
buffer_size_; // Current buffer size
std::string filename_;
bool temporary_file_;
std::fstream stream_;
};
#include "object_archive_impl.hpp"
#endif
<|endoftext|>
|
<commit_before>// CxxSwizzle
// Copyright (c) 2013-2015, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com>
#pragma once
#include <array>
#include <swizzle/detail/utils.h>
#include <swizzle/detail/common_binary_operators.h>
#include <utility>
#include <swizzle/vector.hpp>
namespace swizzle
{
template <class ScalarType, size_t NumRows, size_t... Columns >
struct matrix_;
namespace detail
{
template <class ScalarType, size_t NumRows, size_t... Columns>
matrix_<ScalarType, NumRows, Columns...> make_matrix_type_helper(std::index_sequence<Columns...>);
}
template <class ScalarType, size_t NumRows, size_t NumColumns>
using matrix = decltype(detail::make_matrix_type_helper<ScalarType, NumRows>(std::make_index_sequence<NumColumns>{}));
//! A naive matrix implementation.
//! Stores data as an array of vertices.
template <class ScalarType, size_t NumRows, size_t... Columns >
struct matrix_ : detail::common_binary_operators<matrix_<ScalarType, NumRows, Columns...>, ScalarType>
{
public:
static const size_t num_rows = NumRows;
static const size_t num_columns = sizeof...(Columns);
static_assert(num_rows > 1 && num_columns > 1, "1");
typedef matrix_ matrix_type;
typedef vector<ScalarType, num_columns> row_type;
typedef vector<ScalarType, num_rows> column_type;
typedef ScalarType scalar_type;
// CONSTRUCTION
public:
//! Default zeroing constructor.
matrix_()
{}
//! Copying constructor
matrix_(const matrix_& other)
{
data = other.data;
}
template <size_t Index>
column_type set_return(column_type src, ScalarType value)
{
src[Index] = value;
return src;
}
template <size_t NumOfComponents, typename SomeVectorType>
column_type pad_with_zeros(const SomeVectorType& src)
{
return column_type((Columns < NumOfComponents ? src[Columns] : 0)...);
}
// This should work but doesn't (I'm tired)
////! Constructor for matrices smaller than current one
//template <size_t OtherNumColumns, size_t OtherNumRows>
//matrix_(const matrix<VectorType, ScalarType, OtherNumRows, OtherNumColumns>& other)
//{
// static_assert(OtherNumColumns <= num_columns);
// static_assert(OtherNumRows <= num_rows);
// // copy columns
// ((Columns < OtherNumColumns ? data[Columns] = pad_with_zeros<OtherNumRows>(other.data[Columns]) : set_return<Columns>(zero, 1)), ...);
//}
//! Init with s diagonally
matrix_(const scalar_type& s)
{
column_type zero((Columns, 0)...);
((Columns < num_rows ? data[Columns] = set_return<Columns>(zero, s) : zero), ...);
}
template <class T0, class T1, class... T,
class = typename std::enable_if<
!(num_rows*num_columns <= detail::get_total_component_count_v<T0, T1, T...> - detail::get_total_component_count_v<typename detail::last<T0, T1, T...>::type >) &&
(num_rows*num_columns <= detail::get_total_component_count_v<T0, T1, T...>),
void>::type
>
explicit matrix_(T0&& t0, T1&& t1, T&&... ts)
{
construct<0>(std::forward<T0>(t0), std::forward<T1>(t1), std::forward<T>(ts)..., detail::nothing{});
}
template <typename OtherMatrixType>
static matrix_type make_transposed(OtherMatrixType& other)
{
return matrix_type(other.row(Columns)...);
}
// OPERATORS
public:
//! Row accessor.
column_type& operator[](size_t i)
{
return data[i];
}
//! Row accessor.
const column_type& operator[](size_t i) const
{
return data[i];
}
// Scalar operators
matrix_type& operator+=(const scalar_type& v)
{
return ((column(Columns) += v), ..., *this);
}
matrix_type& operator-=(const scalar_type& v)
{
return ((column(Columns) -= v), ..., *this);
}
matrix_type& operator*=(const scalar_type& v)
{
return ((column(Columns) *= v), ..., *this);
}
matrix_type& operator/=(const scalar_type& v)
{
return ((column(Columns) /= v), ..., *this);
}
// Matrix operators
matrix_type& operator+=(const matrix_type& v)
{
return ((column(Columns) += v.column(Columns)), ..., *this);
}
matrix_type& operator-=(const matrix_type& v)
{
return ((column(Columns) -= v.column(Columns)), ..., *this);
}
matrix_type& operator*=(const matrix_type& v)
{
// Matrix multiplication is "special"
return *this = mul<num_columns>(*this, v);
}
matrix_type& operator/=(const matrix_type& v)
{
return ((column(Columns) /= v.column(Columns)), ..., *this);
}
// Other operators
bool operator==(const matrix_type& o) const
{
return ((column(Columns) == o.column(Columns)) && ...);
}
bool operator!=(const matrix_type& o) const
{
return !(*this == o);
}
//! This needs to be a member rather than free function cause in latter case it would
//! fail to be applied in cases of multiplying a proxy
friend column_type operator*(const matrix_type& m, const row_type& row)
{
return mul(m, row);
}
//! As above.
friend row_type operator*(const column_type& col, const matrix_type& m)
{
return mul(col, m);
}
// UTILITY FUNCTIONS
public:
//! \return Column
const column_type& column(size_t i) const
{
return data[i];
}
//! \return Column
column_type& column(size_t i)
{
return data[i];
}
row_type row(size_t i) const
{
return row_type(cell(i, Columns)...);
}
scalar_type& cell(size_t row, size_t col)
{
return data[col][row];
}
const scalar_type& cell(size_t row, size_t col) const
{
return data[col][row];
}
inline friend matrix<ScalarType, num_columns, num_rows> transpose(const matrix_type& m)
{
return matrix<ScalarType, num_columns, num_rows>::make_transposed(m);
}
//! Matrix-vector multiplication.
static column_type mul(const matrix_type& m, const row_type& v)
{
return mul(v, transpose(m));
}
//! Matrix-matrix multiplication.
template <size_t OtherNumRows>
static matrix<ScalarType, OtherNumRows, num_columns> mul(const matrix<ScalarType, OtherNumRows, num_rows>& m1, const matrix_type& m2)
{
// TODO: questionable
auto tr = transpose(m1);
return matrix<ScalarType, OtherNumRows, num_columns>((m2.column(Columns) * tr)...);
}
//! Matrix-vector multiplication.
static row_type mul(const column_type& v, const matrix_type& m)
{
return row_type(v.call_dot(v, m.column(Columns))...);
}
private:
template <size_t offset, class T0, class... Tail>
void construct(T0&& t0, Tail&&... tail)
{
// the pyramid of MSVC shame
compose<offset>(detail::decay(std::forward<T0>(t0)));
construct<offset + detail::get_total_component_count_v<T0> >(std::forward<Tail>(tail)...);
}
template <size_t>
void construct(detail::nothing)
{}
//! Optimised setter used when setting whole column
template <size_t CellIdx>
typename std::enable_if<CellIdx % num_rows == 0, void>::type compose(const column_type& v)
{
column( CellIdx / num_rows ) = v;
}
//! Vector fallback setter, when CellIdx is not aligned
template <size_t CellIdx, class VectorScalarType, size_t VectorSize>
typename std::enable_if<CellIdx % num_rows != 0 || VectorSize != num_rows, void>::type compose(const vector<VectorScalarType, VectorSize>& v)
{
// do not go over the matrix size!
const size_t c_limit = (CellIdx + VectorSize > num_rows * num_columns) ? (num_rows * num_columns) : (CellIdx + VectorSize);
detail::static_for<CellIdx, c_limit>([&](size_t i) -> void { cell(i % num_rows, i / num_rows) = v[i - CellIdx]; });
}
template <size_t CellIdx>
void compose(const scalar_type& s)
{
cell( CellIdx % num_rows, CellIdx / num_rows ) = s;
}
private:
std::array< column_type, num_columns > data;
};
//template <class ScalarType, size_t M, size_t NumRows, size_t OtherNumColumns>
//matrix<VectorType, ScalarType, NumRows, OtherNumColumns> operator*(const matrix<VectorType, ScalarType, N, M>& m1, const matrix<VectorType, ScalarType, M, OtherNumColumns>& m2 )
//{
// return m1.mul(m1, m2);
//}
}<commit_msg>matrix composition works for integers now<commit_after>// CxxSwizzle
// Copyright (c) 2013-2015, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com>
#pragma once
#include <array>
#include <swizzle/detail/utils.h>
#include <swizzle/detail/common_binary_operators.h>
#include <utility>
#include <swizzle/vector.hpp>
namespace swizzle
{
template <class ScalarType, size_t NumRows, size_t... Columns >
struct matrix_;
namespace detail
{
template <class ScalarType, size_t NumRows, size_t... Columns>
matrix_<ScalarType, NumRows, Columns...> make_matrix_type_helper(std::index_sequence<Columns...>);
}
template <class ScalarType, size_t NumRows, size_t NumColumns>
using matrix = decltype(detail::make_matrix_type_helper<ScalarType, NumRows>(std::make_index_sequence<NumColumns>{}));
//! A naive matrix implementation.
//! Stores data as an array of vertices.
template <class ScalarType, size_t NumRows, size_t... Columns >
struct matrix_ : detail::common_binary_operators<matrix_<ScalarType, NumRows, Columns...>, ScalarType>
{
public:
static const size_t num_rows = NumRows;
static const size_t num_columns = sizeof...(Columns);
static_assert(num_rows > 1 && num_columns > 1, "1");
typedef matrix_ matrix_type;
typedef vector<ScalarType, num_columns> row_type;
typedef vector<ScalarType, num_rows> column_type;
typedef ScalarType scalar_type;
// CONSTRUCTION
public:
//! Default zeroing constructor.
matrix_()
{}
//! Copying constructor
matrix_(const matrix_& other)
{
data = other.data;
}
template <size_t Index>
column_type set_return(column_type src, ScalarType value)
{
src[Index] = value;
return src;
}
template <size_t NumOfComponents, typename SomeVectorType>
column_type pad_with_zeros(const SomeVectorType& src)
{
return column_type((Columns < NumOfComponents ? src[Columns] : 0)...);
}
// This should work but doesn't (I'm tired)
////! Constructor for matrices smaller than current one
//template <size_t OtherNumColumns, size_t OtherNumRows>
//matrix_(const matrix<VectorType, ScalarType, OtherNumRows, OtherNumColumns>& other)
//{
// static_assert(OtherNumColumns <= num_columns);
// static_assert(OtherNumRows <= num_rows);
// // copy columns
// ((Columns < OtherNumColumns ? data[Columns] = pad_with_zeros<OtherNumRows>(other.data[Columns]) : set_return<Columns>(zero, 1)), ...);
//}
//! Init with s diagonally
matrix_(const scalar_type& s)
{
column_type zero((Columns, 0)...);
((Columns < num_rows ? data[Columns] = set_return<Columns>(zero, s) : zero), ...);
}
template <class T0, class T1, class... T,
class = typename std::enable_if<
!(num_rows*num_columns <= detail::get_total_component_count_v<T0, T1, T...> - detail::get_total_component_count_v<typename detail::last<T0, T1, T...>::type >) &&
(num_rows*num_columns <= detail::get_total_component_count_v<T0, T1, T...>),
void>::type
>
explicit matrix_(T0&& t0, T1&& t1, T&&... ts)
{
construct<0>(std::forward<T0>(t0), std::forward<T1>(t1), std::forward<T>(ts)..., detail::nothing{});
}
template <typename OtherMatrixType>
static matrix_type make_transposed(OtherMatrixType& other)
{
return matrix_type(other.row(Columns)...);
}
// OPERATORS
public:
//! Row accessor.
column_type& operator[](size_t i)
{
return data[i];
}
//! Row accessor.
const column_type& operator[](size_t i) const
{
return data[i];
}
// Scalar operators
matrix_type& operator+=(const scalar_type& v)
{
return ((column(Columns) += v), ..., *this);
}
matrix_type& operator-=(const scalar_type& v)
{
return ((column(Columns) -= v), ..., *this);
}
matrix_type& operator*=(const scalar_type& v)
{
return ((column(Columns) *= v), ..., *this);
}
matrix_type& operator/=(const scalar_type& v)
{
return ((column(Columns) /= v), ..., *this);
}
// Matrix operators
matrix_type& operator+=(const matrix_type& v)
{
return ((column(Columns) += v.column(Columns)), ..., *this);
}
matrix_type& operator-=(const matrix_type& v)
{
return ((column(Columns) -= v.column(Columns)), ..., *this);
}
matrix_type& operator*=(const matrix_type& v)
{
// Matrix multiplication is "special"
return *this = mul<num_columns>(*this, v);
}
matrix_type& operator/=(const matrix_type& v)
{
return ((column(Columns) /= v.column(Columns)), ..., *this);
}
// Other operators
bool operator==(const matrix_type& o) const
{
return ((column(Columns) == o.column(Columns)) && ...);
}
bool operator!=(const matrix_type& o) const
{
return !(*this == o);
}
//! This needs to be a member rather than free function cause in latter case it would
//! fail to be applied in cases of multiplying a proxy
friend column_type operator*(const matrix_type& m, const row_type& row)
{
return mul(m, row);
}
//! As above.
friend row_type operator*(const column_type& col, const matrix_type& m)
{
return mul(col, m);
}
// UTILITY FUNCTIONS
public:
//! \return Column
const column_type& column(size_t i) const
{
return data[i];
}
//! \return Column
column_type& column(size_t i)
{
return data[i];
}
row_type row(size_t i) const
{
return row_type(cell(i, Columns)...);
}
scalar_type& cell(size_t row, size_t col)
{
return data[col][row];
}
const scalar_type& cell(size_t row, size_t col) const
{
return data[col][row];
}
inline friend matrix<ScalarType, num_columns, num_rows> transpose(const matrix_type& m)
{
return matrix<ScalarType, num_columns, num_rows>::make_transposed(m);
}
//! Matrix-vector multiplication.
static column_type mul(const matrix_type& m, const row_type& v)
{
return mul(v, transpose(m));
}
//! Matrix-matrix multiplication.
template <size_t OtherNumRows>
static matrix<ScalarType, OtherNumRows, num_columns> mul(const matrix<ScalarType, OtherNumRows, num_rows>& m1, const matrix_type& m2)
{
// TODO: questionable
auto tr = transpose(m1);
return matrix<ScalarType, OtherNumRows, num_columns>((m2.column(Columns) * tr)...);
}
//! Matrix-vector multiplication.
static row_type mul(const column_type& v, const matrix_type& m)
{
return row_type(v.call_dot(v, m.column(Columns))...);
}
private:
template <size_t offset, class T0, class... Tail>
void construct(T0&& t0, Tail&&... tail)
{
// the pyramid of MSVC shame
compose<offset>(detail::decay(std::forward<T0>(t0)));
construct<offset + detail::get_total_component_count_v<T0> >(std::forward<Tail>(tail)...);
}
template <size_t>
void construct(detail::nothing)
{}
//! Optimised setter used when setting whole column
template <size_t CellIdx>
typename std::enable_if<CellIdx % num_rows == 0, void>::type compose(const column_type& v)
{
column( CellIdx / num_rows ) = v;
}
//! Vector fallback setter, when CellIdx is not aligned
template <size_t CellIdx, class VectorScalarType, size_t VectorSize>
typename std::enable_if<CellIdx % num_rows != 0 || VectorSize != num_rows, void>::type compose(const vector<VectorScalarType, VectorSize>& v)
{
// do not go over the matrix size!
const size_t c_limit = (CellIdx + VectorSize > num_rows * num_columns) ? (num_rows * num_columns) : (CellIdx + VectorSize);
detail::static_for<CellIdx, c_limit>([&](size_t i) -> void { cell(i % num_rows, i / num_rows) = v[i - CellIdx]; });
}
template <size_t CellIdx, typename SomeScalarType>
void compose(SomeScalarType&& scalar, std::enable_if_t<std::is_constructible_v<scalar_type, SomeScalarType>>* = nullptr)
{
cell(CellIdx % num_rows, CellIdx / num_rows) = scalar_type(std::forward<SomeScalarType>(scalar));
}
private:
std::array< column_type, num_columns > data;
};
//template <class ScalarType, size_t M, size_t NumRows, size_t OtherNumColumns>
//matrix<VectorType, ScalarType, NumRows, OtherNumColumns> operator*(const matrix<VectorType, ScalarType, N, M>& m1, const matrix<VectorType, ScalarType, M, OtherNumColumns>& m2 )
//{
// return m1.mul(m1, m2);
//}
}<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "CommandDefend.h"
CommandDefend::CommandDefend()
{
}
CommandDefend::~CommandDefend()
{
}
bool CommandDefend::ShouldRunThisCommand(ParsedCommand* Parsed)
{
return (Parsed->Words->at(0) == "defend");
}
void CommandDefend::Run(ParsedCommand* Parsed)
{
//There wasn't another word to determine whether we were to start or stop
if (Parsed->Words->size() < 2)
{
string error = "Missing required command argument.";
Console->WriteLine(&error);
return;
}
if (Parsed->Words->at(1) == "start")
{
this->DefendStart();
return;
}
if (Parsed->Words->at(1) == "stop")
{
this->DefendStop();
return;
}
string error = "Invalid command argument";
Console->WriteLine(&error);
}
string* CommandDefend::GetName()
{
return new string("Defend");
}
string* CommandDefend::GetHelp()
{
return new string("Kills all applications that were not running before Defend was started.\r\n Usage: Defend Start to start Defend, Defend Stop to stop Defend.");
}
bool CommandDefend::DoesProcessExistInList(DWORD pID, DWORD numberOfProcesses)
{
register DWORD length = numberOfProcesses;
for (register size_t i = 0; i < numberOfProcesses; i++)
{
if (pID == this->AllowedProcesses[i])
{
return true;
}
}
return false;
}
void CommandDefend::DefendStart()
{
if (!this->DefenseThread)
{
delete this->DefenseThread;
}
this->DefenseThread = new thread(&CommandDefend::Defend, this);
}
void CommandDefend::DefendStop()
{
this->StopThread = true;
}
void CommandDefend::Defend()
{
this->StopThread = false;
// Get the list of process identifiers.
register DWORD aProcesses[1024];
DWORD cbNeeded;
DWORD numberOfProcesses;
EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
numberOfProcesses = cbNeeded / sizeof(DWORD);
//Copies the contents of aProcesses to this->AllowedProcesses.
memcpy(this->AllowedProcesses, aProcesses, sizeof(this->AllowedProcesses));
register size_t i = 0;
HANDLE hProcess;
DWORD CID = GetCurrentProcessId();
while (true)
{
if (this->StopThread)
{
break;
}
EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
i = 0;
numberOfProcesses = cbNeeded / sizeof(DWORD);
for (i = 0; i < numberOfProcesses; i++)
{
if (!this->DoesProcessExistInList(aProcesses[i], numberOfProcesses)&& aProcesses[i] != CID)
{
//Get process handle.
hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, aProcesses[i]);
wchar_t* buffer = new wchar_t();
GetModuleFileNameEx(hProcess, NULL, buffer, MAX_PATH);
wstring ws(buffer);
string converted(ws.begin(), ws.end());
//Kill process.
if (TerminateProcess(hProcess, 1))
{
string msg = "Killed a process: ";
msg.append(converted);
Console->WriteLine(&msg);
}
else
{
string msg = "Failed to kill a process: ";
msg.append(converted);
Console->WriteLine(&msg);
Console->WriteLine(&to_string(GetLastError()));
}
delete buffer;
}
}
}
}
<commit_msg>Not logging when we fail to kill a process.<commit_after>#include "stdafx.h"
#include "CommandDefend.h"
CommandDefend::CommandDefend()
{
}
CommandDefend::~CommandDefend()
{
}
bool CommandDefend::ShouldRunThisCommand(ParsedCommand* Parsed)
{
return (Parsed->Words->at(0) == "defend");
}
void CommandDefend::Run(ParsedCommand* Parsed)
{
//There wasn't another word to determine whether we were to start or stop
if (Parsed->Words->size() < 2)
{
string error = "Missing required command argument.";
Console->WriteLine(&error);
return;
}
if (Parsed->Words->at(1) == "start")
{
this->DefendStart();
return;
}
if (Parsed->Words->at(1) == "stop")
{
this->DefendStop();
return;
}
string error = "Invalid command argument";
Console->WriteLine(&error);
}
string* CommandDefend::GetName()
{
return new string("Defend");
}
string* CommandDefend::GetHelp()
{
return new string("Kills all applications that were not running before Defend was started.\r\n Usage: Defend Start to start Defend, Defend Stop to stop Defend.");
}
bool CommandDefend::DoesProcessExistInList(DWORD pID, DWORD numberOfProcesses)
{
register DWORD length = numberOfProcesses;
for (register size_t i = 0; i < numberOfProcesses; i++)
{
if (pID == this->AllowedProcesses[i])
{
return true;
}
}
return false;
}
void CommandDefend::DefendStart()
{
if (!this->DefenseThread)
{
delete this->DefenseThread;
}
this->DefenseThread = new thread(&CommandDefend::Defend, this);
}
void CommandDefend::DefendStop()
{
this->StopThread = true;
}
void CommandDefend::Defend()
{
this->StopThread = false;
// Get the list of process identifiers.
register DWORD aProcesses[1024];
DWORD cbNeeded;
DWORD numberOfProcesses;
EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
numberOfProcesses = cbNeeded / sizeof(DWORD);
//Copies the contents of aProcesses to this->AllowedProcesses.
memcpy(this->AllowedProcesses, aProcesses, sizeof(this->AllowedProcesses));
register size_t i = 0;
HANDLE hProcess;
DWORD CID = GetCurrentProcessId();
while (true)
{
if (this->StopThread)
{
break;
}
EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded);
i = 0;
numberOfProcesses = cbNeeded / sizeof(DWORD);
for (i = 0; i < numberOfProcesses; i++)
{
if (!this->DoesProcessExistInList(aProcesses[i], numberOfProcesses)&& aProcesses[i] != CID)
{
//Get process handle.
hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, aProcesses[i]);
wchar_t* buffer = new wchar_t();
GetModuleFileNameEx(hProcess, NULL, buffer, MAX_PATH);
wstring ws(buffer);
string converted(ws.begin(), ws.end());
//Kill process.
if (TerminateProcess(hProcess, 1))
{
string msg = "Killed a process: ";
msg.append(converted);
Console->WriteLine(&msg);
}
else
{
//string msg = "Failed to kill a process: ";
//msg.append(converted);
//Console->WriteLine(&msg);
//Console->WriteLine(&to_string(GetLastError()));
}
delete buffer;
}
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>vector<OUString*> to vector<OUString> as a temporary<commit_after><|endoftext|>
|
<commit_before>#ifndef LIBTEN_HTTP_SERVER_HH
#define LIBTEN_HTTP_SERVER_HH
#include <fnmatch.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/compare.hpp>
#include <chrono>
#include <functional>
#include <netinet/tcp.h>
#include "ten/buffer.hh"
#include "ten/logging.hh"
#include "ten/task.hh"
#include "ten/net.hh"
#include "ten/http/http_message.hh"
#include "ten/uri.hh"
namespace ten {
//! http request/response pair; keeps reference to request and socket
// (the term "exchange" appears in the standard)
struct http_exchange {
http_request &req;
netsock &sock;
http_response resp {404};
bool resp_sent {false};
std::chrono::high_resolution_clock::time_point start;
http_exchange(http_request &req_, netsock &sock_)
: req(req_), sock(sock_),
start(std::chrono::steady_clock::now()) {}
~http_exchange() {
if (!resp_sent) {
// ensure a response is sent
resp = {404};
send_response();
}
if (boost::iequals(resp.get("Connection"), "close")) {
sock.close();
}
}
//! compose a uri from the request uri
uri get_uri(std::string host="") const {
if (host.empty()) {
host = req.get("Host");
// TODO: transform to preserve passed in host
if (boost::starts_with(req.uri, "http://")) {
return req.uri;
}
}
if (host.empty()) {
// just make up a host
host = "localhost";
}
uri tmp;
tmp.host = host;
tmp.scheme = "http";
tmp.path = req.uri;
return tmp.compose();
}
//! send response to this request
ssize_t send_response() {
if (resp_sent) return 0;
resp_sent = true;
// TODO: Content-Length might be good to add to normal responses,
// but only if Transfer-Encoding isn't chunked?
if (resp.status_code >= 400 && resp.status_code <= 599
&& resp.get("Content-Length").empty()
&& req.method != "HEAD")
{
resp.set("Content-Length", resp.body.size());
}
// HTTP/1.1 requires Date, so lets add it
if (resp.get("Date").empty()) {
char buf[128];
struct tm tm;
time_t now = std::chrono::system_clock::to_time_t(procnow());
strftime(buf, sizeof(buf)-1, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r(&now, &tm));
resp.set("Date", buf);
}
if (resp.get("Connection").empty()) {
// obey clients wishes if we have none of our own
std::string conn = req.get("Connection");
if (!conn.empty())
resp.set("Connection", conn);
else if (req.version == http_1_0)
resp.set("Connection", "close");
}
auto data = resp.data();
if (!resp.body.empty() && req.method != "HEAD") {
data += resp.body;
}
ssize_t nw = sock.send(data.data(), data.size());
return nw;
}
//! the ip of the host making the request
//! might use the X-Forwarded-For header
std::string agent_ip(bool use_xff=false) const {
if (use_xff) {
std::string xffs = req.get("X-Forwarded-For");
const char *xff = xffs.c_str();
if (xff) {
// pick the first addr
int i;
for (i=0; *xff && i<256 && !isdigit((unsigned char)*xff); i++, xff++) {}
if (*xff && i < 256) {
// now, find the end
const char *e = xff;
for (i = 0; *e && i<256 && (isdigit((unsigned char)*e) || *e == '.'); i++, e++) {}
if (i < 256 && e >= xff + 7 ) {
return std::string(xff, e - xff);
}
}
}
}
address addr;
if (sock.getpeername(addr)) {
char buf[INET6_ADDRSTRLEN];
if (addr.ntop(buf, sizeof(buf))) {
return buf;
}
}
return "";
}
};
//! basic http server
class http_server : public netsock_server {
public:
typedef std::function<void (http_exchange &)> callback_type;
std::function<void ()> connect_watch;
std::function<void ()> disconnect_watch;
protected:
struct route {
std::string pattern;
callback_type callback;
int fnmatch_flags;
route(const std::string &pattern_,
const callback_type &callback_,
int fnmatch_flags_=0)
: pattern(pattern_), callback(callback_), fnmatch_flags(fnmatch_flags_) {}
};
std::vector<route> _routes;
callback_type _log_func;
public:
http_server(size_t stacksize_=default_stacksize, unsigned timeout_ms_=0)
: netsock_server("http", stacksize_, timeout_ms_)
{
}
//! add a callback for a uri with an fnmatch pattern
void add_route(const std::string &pattern,
const callback_type &callback,
int fnmatch_flags = 0)
{
_routes.emplace_back(pattern, callback, fnmatch_flags);
}
//! set logging function, called after every exchange
void set_log_callback(const callback_type &f) {
_log_func = f;
}
private:
virtual void setup_listen_socket(netsock &s) {
netsock_server::setup_listen_socket(s);
s.setsockopt(IPPROTO_TCP, TCP_DEFER_ACCEPT, 30);
}
void on_connection(netsock &s) {
// TODO: tuneable buffer sizes
buffer buf(4*1024);
http_parser parser;
if (connect_watch) {
connect_watch();
}
// TODO: might want to enable this later after
// we know this will be a long-lived connection
s.s.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1);
http_request req;
for (;;) {
req.parser_init(&parser);
bool got_headers = false;
for (;;) {
buf.reserve(4*1024);
ssize_t nr = -1;
if (buf.size() == 0) {
nr = s.recv(buf.back(), buf.available(), _timeout_ms);
if (nr < 0) goto done;
buf.commit(nr);
}
size_t nparse = buf.size();
req.parse(&parser, buf.front(), nparse);
buf.remove(nparse);
if (req.complete) {
// handle request
handle_request(req, s);
break;
}
if (nr == 0) goto done;
if (!got_headers && !req.method.empty()) {
got_headers = true;
if (req.get("Expect") == "100-continue") {
http_response cont_resp(100);
std::string data = cont_resp.data();
ssize_t nw = s.send(data.data(), data.size());
(void)nw;
}
}
}
}
done:
if (disconnect_watch) {
disconnect_watch();
}
}
void handle_request(http_request &req, netsock &s) {
http_exchange ex(req, s);
const auto path = req.path();
DVLOG(5) << "path: " << path;
// not super efficient, but good enough
// note: empty string pattern matches everything
for (const auto &i : _routes) {
DVLOG(5) << "matching pattern: " << i.pattern;
if (i.pattern.empty() || fnmatch(i.pattern.c_str(), path.c_str(), i.fnmatch_flags) == 0) {
try {
i.callback(ex);
} catch (std::exception &e) {
DVLOG(2) << "unhandled exception in route [" << i.pattern << "]: " << e.what();
ex.resp = http_response(500, http_headers{"Connection", "close"});
std::string msg = e.what();
if (!msg.empty() && *msg.rbegin() != '\n')
msg += '\n';
ex.resp.set_body(msg);
ex.send_response();
}
break;
}
}
if (_log_func) {
_log_func(ex);
}
}
};
} // end namespace ten
#endif // LIBTEN_HTTP_SERVER_HH
<commit_msg>set NODELAY on server side of persistent http connections<commit_after>#ifndef LIBTEN_HTTP_SERVER_HH
#define LIBTEN_HTTP_SERVER_HH
#include <fnmatch.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/compare.hpp>
#include <chrono>
#include <functional>
#include <netinet/tcp.h>
#include "ten/buffer.hh"
#include "ten/logging.hh"
#include "ten/task.hh"
#include "ten/net.hh"
#include "ten/http/http_message.hh"
#include "ten/uri.hh"
namespace ten {
//! http request/response pair; keeps reference to request and socket
// (the term "exchange" appears in the standard)
struct http_exchange {
http_request &req;
netsock &sock;
bool will_close;
http_response resp {404};
bool resp_sent {false};
std::chrono::high_resolution_clock::time_point start;
http_exchange(http_request &req_, netsock &sock_)
: req(req_),
sock(sock_),
will_close(req.version < http_1_1 || boost::iequals(resp.get("Connection"), "close")),
start(std::chrono::steady_clock::now())
{}
~http_exchange() {
if (!resp_sent) {
// ensure a response is sent
resp = {404};
send_response();
}
if (will_close) {
sock.close();
}
}
//! compose a uri from the request uri
uri get_uri(std::string host="") const {
if (host.empty()) {
host = req.get("Host");
// TODO: transform to preserve passed in host
if (boost::starts_with(req.uri, "http://")) {
return req.uri;
}
}
if (host.empty()) {
// just make up a host
host = "localhost";
}
uri tmp;
tmp.host = host;
tmp.scheme = "http";
tmp.path = req.uri;
return tmp.compose();
}
//! send response to this request
ssize_t send_response() {
if (resp_sent) return 0;
resp_sent = true;
// TODO: Content-Length might be good to add to normal responses,
// but only if Transfer-Encoding isn't chunked?
if (resp.status_code >= 400 && resp.status_code <= 599
&& resp.get("Content-Length").empty()
&& req.method != "HEAD")
{
resp.set("Content-Length", resp.body.size());
}
// HTTP/1.1 requires Date, so lets add it
if (resp.get("Date").empty()) {
char buf[128];
struct tm tm;
time_t now = std::chrono::system_clock::to_time_t(procnow());
strftime(buf, sizeof(buf)-1, "%a, %d %b %Y %H:%M:%S GMT", gmtime_r(&now, &tm));
resp.set("Date", buf);
}
if (resp.get("Connection").empty()) {
// obey clients wishes if we have none of our own
std::string conn = req.get("Connection");
if (!conn.empty())
resp.set("Connection", conn);
else if (req.version == http_1_0)
resp.set("Connection", "close");
}
auto data = resp.data();
if (!resp.body.empty() && req.method != "HEAD") {
data += resp.body;
}
ssize_t nw = sock.send(data.data(), data.size());
return nw;
}
//! the ip of the host making the request
//! might use the X-Forwarded-For header
std::string agent_ip(bool use_xff=false) const {
if (use_xff) {
std::string xffs = req.get("X-Forwarded-For");
const char *xff = xffs.c_str();
if (xff) {
// pick the first addr
int i;
for (i=0; *xff && i<256 && !isdigit((unsigned char)*xff); i++, xff++) {}
if (*xff && i < 256) {
// now, find the end
const char *e = xff;
for (i = 0; *e && i<256 && (isdigit((unsigned char)*e) || *e == '.'); i++, e++) {}
if (i < 256 && e >= xff + 7 ) {
return std::string(xff, e - xff);
}
}
}
}
address addr;
if (sock.getpeername(addr)) {
char buf[INET6_ADDRSTRLEN];
if (addr.ntop(buf, sizeof(buf))) {
return buf;
}
}
return "";
}
};
//! basic http server
class http_server : public netsock_server {
public:
typedef std::function<void (http_exchange &)> callback_type;
std::function<void ()> connect_watch;
std::function<void ()> disconnect_watch;
protected:
struct route {
std::string pattern;
callback_type callback;
int fnmatch_flags;
route(const std::string &pattern_,
const callback_type &callback_,
int fnmatch_flags_=0)
: pattern(pattern_), callback(callback_), fnmatch_flags(fnmatch_flags_) {}
};
std::vector<route> _routes;
callback_type _log_func;
public:
http_server(size_t stacksize_=default_stacksize, unsigned timeout_ms_=0)
: netsock_server("http", stacksize_, timeout_ms_)
{
}
//! add a callback for a uri with an fnmatch pattern
void add_route(const std::string &pattern,
const callback_type &callback,
int fnmatch_flags = 0)
{
_routes.emplace_back(pattern, callback, fnmatch_flags);
}
//! set logging function, called after every exchange
void set_log_callback(const callback_type &f) {
_log_func = f;
}
private:
virtual void setup_listen_socket(netsock &s) {
netsock_server::setup_listen_socket(s);
s.setsockopt(IPPROTO_TCP, TCP_DEFER_ACCEPT, 30);
}
void on_connection(netsock &s) {
// TODO: tuneable buffer sizes
buffer buf(4*1024);
http_parser parser;
if (connect_watch) {
connect_watch();
}
bool nodelay_set = false;
http_request req;
for (;;) {
req.parser_init(&parser);
bool got_headers = false;
for (;;) {
buf.reserve(4*1024);
ssize_t nr = -1;
if (buf.size() == 0) {
nr = s.recv(buf.back(), buf.available(), _timeout_ms);
if (nr < 0) goto done;
buf.commit(nr);
}
size_t nparse = buf.size();
req.parse(&parser, buf.front(), nparse);
buf.remove(nparse);
if (req.complete) {
// handle http exchange (request -> response)
http_exchange ex(req, s);
if (!nodelay_set && !ex.will_close) {
// this is a persistent connection, so low-latency sending is worth the overh
s.s.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1);
nodelay_set = true;
}
handle_exchange(ex);
break;
}
if (nr == 0) goto done;
if (!got_headers && !req.method.empty()) {
got_headers = true;
if (req.get("Expect") == "100-continue") {
http_response cont_resp(100);
std::string data = cont_resp.data();
ssize_t nw = s.send(data.data(), data.size());
(void)nw;
}
}
}
}
done:
if (disconnect_watch) {
disconnect_watch();
}
}
void handle_exchange(http_exchange &ex) {
const auto path = ex.req.path();
DVLOG(5) << "path: " << path;
// not super efficient, but good enough
// note: empty string pattern matches everything
for (const auto &i : _routes) {
DVLOG(5) << "matching pattern: " << i.pattern;
if (i.pattern.empty() || fnmatch(i.pattern.c_str(), path.c_str(), i.fnmatch_flags) == 0) {
try {
i.callback(ex);
} catch (std::exception &e) {
DVLOG(2) << "unhandled exception in route [" << i.pattern << "]: " << e.what();
ex.resp = http_response(500, http_headers{"Connection", "close"});
std::string msg = e.what();
if (!msg.empty() && *msg.rbegin() != '\n')
msg += '\n';
ex.resp.set_body(msg);
ex.send_response();
}
break;
}
}
if (_log_func) {
_log_func(ex);
}
}
};
} // end namespace ten
#endif // LIBTEN_HTTP_SERVER_HH
<|endoftext|>
|
<commit_before>/*
* AlloSphere Research Group / Media Arts & Technology, UCSB, 2009
*/
/*
Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
All Rights Reserved.
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, the list of contributors, this paragraph and the following two paragraphs
appear in all copies, modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#ifndef INCLUDE_ALLO_TYPES_CPP_H
#define INCLUDE_ALLO_TYPES_CPP_H 1
#include "al_types.h"
#include <stdlib.h>
namespace al {
/*
Partial specialization function to get type
This demonstrates the principle by which a runtime type can be understood by templates
*/
template<typename T> AlloTy getType() { return 0; }
template<> AlloTy getType<uint8_t>() { return AlloUInt8Ty; }
template<> AlloTy getType<uint16_t>() { return AlloUInt16Ty; }
template<> AlloTy getType<uint32_t>() { return AlloUInt32Ty; }
template<> AlloTy getType<uint64_t>() { return AlloUInt64Ty; }
template<> AlloTy getType<int8_t>() { return AlloSInt8Ty; }
template<> AlloTy getType<int16_t>() { return AlloSInt16Ty; }
template<> AlloTy getType<int32_t>() { return AlloSInt32Ty; }
template<> AlloTy getType<int64_t>() { return AlloSInt64Ty; }
template<> AlloTy getType<float>() { return AlloFloat32Ty; }
template<> AlloTy getType<double>() { return AlloFloat64Ty; }
template<> AlloTy getType<AlloLattice>() { return AlloLatticeTy; }
// TODO: #define for platform ptrsize
//template<> AlloTy getType<void *>() { return AlloPointer32Ty; }
//template<> AlloTy getType<void *>() { return AlloPointer32Ty; }
/*
E.g., verify a type:
*/
template<typename T> bool checkType(AlloTy ty) { return getType<T>() && ty == getType<T>(); }
/*
Derived type
N.B. methods and static members only... no additional instance member data!
*/
class Lattice : public AlloLattice {
protected:
public:
inline size_t size() { return allo_lattice_size(this); }
inline void data_calloc() {
data.ptr = (char *)calloc(1, size());
}
inline void data_free() {
free(data.ptr);
}
template<typename T> inline void define1d(uint32_t components, uint32_t dimx, size_t align = 4) {
header.type = getType<T>();
header.components = components;
header.dimcount = 1;
header.dim[0] = dimx;
allo_lattice_setstride(&header, align);
}
template<typename T> inline void define2d(uint32_t components, uint32_t dimx, uint32_t dimy, size_t align = 4) {
header.type = getType<T>();
header.components = components;
header.dimcount = 2;
header.dim[0] = dimx;
header.dim[1] = dimy;
allo_lattice_setstride(&header, align);
}
template<typename T> inline void define3d(uint32_t components, uint32_t dimx, uint32_t dimy, uint32_t dimz, size_t align = 4) {
header.type = getType<T>();
header.components = components;
header.dimcount = 3;
header.dim[0] = dimx;
header.dim[1] = dimy;
header.dim[2] = dimz;
allo_lattice_setstride(&header, align);
}
/*
Use a function to fill a lattice with data:
*/
template<typename T> inline void fill1d(void (*func)(T * values, double normx)) {
int d0 = header.dim[0];
double inv_d0 = 1.0/(double)d0;
int components = header.components;
T * vals = (T *)(data.ptr);
for(int i=0; i < d0; i++) {
for (int c=0; c<components; c++) {
func(vals, inv_d0 * (double)i);
}
vals += components;
}
}
template<typename T> inline T * data1d(uint32_t x) {
uint32_t fieldstride_x = header.stride[0];
return (T *)(data.ptr + x*fieldstride_x);
}
// check whether the internal lattice data is of type T:
template<typename T> inline bool checkType() { return al::checkType<T>(header.type); }
// linear interpolated lookup (virtual lattice index x, y)
// writes the linearly interpolated plane values into val array
template<typename T> inline void interp1d(T* val, double x) {
#define DOUBLE_FLOOR(v) ( (long)(v) - ((v)<0.0 && (v)!=(long)(v)) )
#define DOUBLE_CEIL(v) ( (((v)>0.0)&&((v)!=(long)(v))) ? 1+(v) : (v) )
#define DOUBLE_FRAC(v) ( ((v)>=0.0) ? (v)-(long)(v) : (-v)-(long)(v) )
// convert 0..1 field indices to 0..(d-1) cell indices
uint32_t xa = (uint32_t)DOUBLE_FLOOR(x);
uint32_t xb = (uint32_t)DOUBLE_CEIL (x);
// get the normalized 0..1 interp factors, of x,y,z:
double fa = DOUBLE_FRAC(x);
double fb = 1.f - fa;
// get the cell addresses for each neighbor:
uint32_t fieldstride_x = header.stride[0];
T * pa = (T *)(data.ptr + xa*fieldstride_x);
T * pb = (T *)(data.ptr + xb*fieldstride_x);
// for each plane of the field, do the 3D interp:
for (uint8_t p=0; p<header.components; p++) {
val[p] = (pa[p] * fa) +
(pb[p] * fb);
}
#undef DOUBLE_FLOOR
#undef DOUBLE_CEIL
#undef DOUBLE_FRAC
}
// bilinear interpolated lookup (virtual lattice index x, y)
// writes the linearly interpolated plane values into val array
template<typename T> inline void interp2d(T* val, double x, double y) {
#define DOUBLE_FLOOR(v) ( (long)(v) - ((v)<0.0 && (v)!=(long)(v)) )
#define DOUBLE_CEIL(v) ( (((v)>0.0)&&((v)!=(long)(v))) ? 1+(v) : (v) )
#define DOUBLE_FRAC(v) ( ((v)>=0.0) ? (v)-(long)(v) : (-v)-(long)(v) )
// convert 0..1 field indices to 0..(d-1) cell indices
uint32_t xa = (uint32_t)DOUBLE_FLOOR(x);
uint32_t xb = (uint32_t)DOUBLE_CEIL (x);
uint32_t ya = (uint32_t)DOUBLE_FLOOR(y);
uint32_t yb = (uint32_t)DOUBLE_CEIL (y);
// get the normalized 0..1 interp factors, of x,y,z:
double xbf = DOUBLE_FRAC(x);
double xaf = 1.f - xbf;
double ybf = DOUBLE_FRAC(y);
double yaf = 1.f - ybf;
// get the interpolation corner weights:
double faa = xaf * yaf;
double fab = xaf * ybf;
double fba = xbf * yaf;
double fbb = xbf * ybf;
// get the cell addresses for each neighbor:
uint32_t fieldstride_x = header.stride[0];
uint32_t fieldstride_y = header.stride[1];
T * paa = (T *)(data.ptr + xa*fieldstride_x + ya*fieldstride_y);
T * pab = (T *)(data.ptr + xa*fieldstride_x + yb*fieldstride_y);
T * pba = (T *)(data.ptr + xb*fieldstride_x + ya*fieldstride_y);
T * pbb = (T *)(data.ptr + xb*fieldstride_x + yb*fieldstride_y);
// for each plane of the field, do the 3D interp:
for (uint8_t p=0; p<header.components; p++) {
val[p] = (paa[p] * faa) +
(pba[p] * fba) +
(pab[p] * fab) +
(pbb[p] * fbb);
}
#undef DOUBLE_FLOOR
#undef DOUBLE_CEIL
#undef DOUBLE_FRAC
}
// trilinear interpolated lookup (virtual lattice index x, y, z)
// writes the linearly interpolated plane values into val array
template<typename T> inline void interp3d(T* val, double x, double y, double z) {
#define DOUBLE_FLOOR(v) ( (long)(v) - ((v)<0.0 && (v)!=(long)(v)) )
#define DOUBLE_CEIL(v) ( (((v)>0.0)&&((v)!=(long)(v))) ? 1+(v) : (v) )
#define DOUBLE_FRAC(v) ( ((v)>=0.0) ? (v)-(long)(v) : (-v)-(long)(v) )
// convert 0..1 field indices to 0..(d-1) cell indices
uint32_t xa = (uint32_t)DOUBLE_FLOOR(x);
uint32_t xb = (uint32_t)DOUBLE_CEIL (x);
uint32_t ya = (uint32_t)DOUBLE_FLOOR(y);
uint32_t yb = (uint32_t)DOUBLE_CEIL (y);
uint32_t za = (uint32_t)DOUBLE_FLOOR(z);
uint32_t zb = (uint32_t)DOUBLE_CEIL (z);
// get the normalized 0..1 interp factors, of x,y,z:
double xbf = DOUBLE_FRAC(x);
double xaf = 1.f - xbf;
double ybf = DOUBLE_FRAC(y);
double yaf = 1.f - ybf;
double zbf = DOUBLE_FRAC(z);
double zaf = 1.f - zbf;
// get the interpolation corner weights:
double faaa = xaf * yaf * zaf;
double faab = xaf * yaf * zbf;
double faba = xaf * ybf * zaf;
double fabb = xaf * ybf * zbf;
double fbaa = xbf * yaf * zaf;
double fbab = xbf * yaf * zbf;
double fbba = xbf * ybf * zaf;
double fbbb = xbf * ybf * zbf;
// get the cell addresses for each neighbor:
uint32_t fieldstride_x = header.stride[0];
uint32_t fieldstride_y = header.stride[1];
uint32_t fieldstride_z = header.stride[2];
T * paaa = (T *)(data.ptr + xa*fieldstride_x + ya*fieldstride_y + za*fieldstride_z);
T * paab = (T *)(data.ptr + xa*fieldstride_x + ya*fieldstride_y + zb*fieldstride_z);
T * paba = (T *)(data.ptr + xa*fieldstride_x + yb*fieldstride_y + za*fieldstride_z);
T * pabb = (T *)(data.ptr + xa*fieldstride_x + yb*fieldstride_y + zb*fieldstride_z);
T * pbaa = (T *)(data.ptr + xb*fieldstride_x + ya*fieldstride_y + za*fieldstride_z);
T * pbab = (T *)(data.ptr + xb*fieldstride_x + ya*fieldstride_y + zb*fieldstride_z);
T * pbba = (T *)(data.ptr + xb*fieldstride_x + yb*fieldstride_y + za*fieldstride_z);
T * pbbb = (T *)(data.ptr + xb*fieldstride_x + yb*fieldstride_y + zb*fieldstride_z);
// for each plane of the field, do the 3D interp:
for (uint8_t p=0; p<header.components; p++) {
val[p] = (paaa[p] * faaa) +
(pbaa[p] * fbaa) +
(paba[p] * faba) +
(paab[p] * faab) +
(pbab[p] * fbab) +
(pabb[p] * fabb) +
(pbba[p] * fbba) +
(pbbb[p] * fbbb);
}
#undef DOUBLE_FLOOR
#undef DOUBLE_CEIL
#undef DOUBLE_FRAC
}
};
} // ::allo::
#endif /* INCLUDE_ALLO_TYPES_CPP_H */
<commit_msg>Fixed duplicate symbols error from non-inlined header function implementations.<commit_after>/*
* AlloSphere Research Group / Media Arts & Technology, UCSB, 2009
*/
/*
Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
All Rights Reserved.
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, the list of contributors, this paragraph and the following two paragraphs
appear in all copies, modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#ifndef INCLUDE_ALLO_TYPES_CPP_H
#define INCLUDE_ALLO_TYPES_CPP_H 1
#include "al_types.h"
#include <stdlib.h>
namespace al {
/*
Partial specialization function to get type
This demonstrates the principle by which a runtime type can be understood by templates
*/
template<typename T> inline AlloTy getType() { return 0; }
template<> inline AlloTy getType<uint8_t>() { return AlloUInt8Ty; }
template<> inline AlloTy getType<uint16_t>() { return AlloUInt16Ty; }
template<> inline AlloTy getType<uint32_t>() { return AlloUInt32Ty; }
template<> inline AlloTy getType<uint64_t>() { return AlloUInt64Ty; }
template<> inline AlloTy getType<int8_t>() { return AlloSInt8Ty; }
template<> inline AlloTy getType<int16_t>() { return AlloSInt16Ty; }
template<> inline AlloTy getType<int32_t>() { return AlloSInt32Ty; }
template<> inline AlloTy getType<int64_t>() { return AlloSInt64Ty; }
template<> inline AlloTy getType<float>() { return AlloFloat32Ty; }
template<> inline AlloTy getType<double>() { return AlloFloat64Ty; }
template<> inline AlloTy getType<AlloLattice>() { return AlloLatticeTy; }
// TODO: #define for platform ptrsize
//template<> AlloTy getType<void *>() { return AlloPointer32Ty; }
//template<> AlloTy getType<void *>() { return AlloPointer32Ty; }
/*
E.g., verify a type:
*/
template<typename T> inline bool checkType(AlloTy ty) { return getType<T>() && ty == getType<T>(); }
/*
Derived type
N.B. methods and static members only... no additional instance member data!
*/
class Lattice : public AlloLattice {
protected:
public:
size_t size() { return allo_lattice_size(this); }
void data_calloc() {
data.ptr = (char *)calloc(1, size());
}
void data_free() {
free(data.ptr);
}
template<typename T> void define1d(uint32_t components, uint32_t dimx, size_t align = 4) {
header.type = getType<T>();
header.components = components;
header.dimcount = 1;
header.dim[0] = dimx;
allo_lattice_setstride(&header, align);
}
template<typename T> void define2d(uint32_t components, uint32_t dimx, uint32_t dimy, size_t align = 4) {
header.type = getType<T>();
header.components = components;
header.dimcount = 2;
header.dim[0] = dimx;
header.dim[1] = dimy;
allo_lattice_setstride(&header, align);
}
template<typename T> void define3d(uint32_t components, uint32_t dimx, uint32_t dimy, uint32_t dimz, size_t align = 4) {
header.type = getType<T>();
header.components = components;
header.dimcount = 3;
header.dim[0] = dimx;
header.dim[1] = dimy;
header.dim[2] = dimz;
allo_lattice_setstride(&header, align);
}
/*
Use a function to fill a lattice with data:
*/
template<typename T> void fill1d(void (*func)(T * values, double normx)) {
int d0 = header.dim[0];
double inv_d0 = 1.0/(double)d0;
int components = header.components;
T * vals = (T *)(data.ptr);
for(int i=0; i < d0; i++) {
for (int c=0; c<components; c++) {
func(vals, inv_d0 * (double)i);
}
vals += components;
}
}
template<typename T> T * data1d(uint32_t x) {
uint32_t fieldstride_x = header.stride[0];
return (T *)(data.ptr + x*fieldstride_x);
}
// check whether the internal lattice data is of type T:
template<typename T> bool checkType() { return al::checkType<T>(header.type); }
// linear interpolated lookup (virtual lattice index x, y)
// writes the linearly interpolated plane values into val array
template<typename T> void interp1d(T* val, double x) {
#define DOUBLE_FLOOR(v) ( (long)(v) - ((v)<0.0 && (v)!=(long)(v)) )
#define DOUBLE_CEIL(v) ( (((v)>0.0)&&((v)!=(long)(v))) ? 1+(v) : (v) )
#define DOUBLE_FRAC(v) ( ((v)>=0.0) ? (v)-(long)(v) : (-v)-(long)(v) )
// convert 0..1 field indices to 0..(d-1) cell indices
uint32_t xa = (uint32_t)DOUBLE_FLOOR(x);
uint32_t xb = (uint32_t)DOUBLE_CEIL (x);
// get the normalized 0..1 interp factors, of x,y,z:
double fa = DOUBLE_FRAC(x);
double fb = 1.f - fa;
// get the cell addresses for each neighbor:
uint32_t fieldstride_x = header.stride[0];
T * pa = (T *)(data.ptr + xa*fieldstride_x);
T * pb = (T *)(data.ptr + xb*fieldstride_x);
// for each plane of the field, do the 3D interp:
for (uint8_t p=0; p<header.components; p++) {
val[p] = (pa[p] * fa) +
(pb[p] * fb);
}
#undef DOUBLE_FLOOR
#undef DOUBLE_CEIL
#undef DOUBLE_FRAC
}
// bilinear interpolated lookup (virtual lattice index x, y)
// writes the linearly interpolated plane values into val array
template<typename T> void interp2d(T* val, double x, double y) {
#define DOUBLE_FLOOR(v) ( (long)(v) - ((v)<0.0 && (v)!=(long)(v)) )
#define DOUBLE_CEIL(v) ( (((v)>0.0)&&((v)!=(long)(v))) ? 1+(v) : (v) )
#define DOUBLE_FRAC(v) ( ((v)>=0.0) ? (v)-(long)(v) : (-v)-(long)(v) )
// convert 0..1 field indices to 0..(d-1) cell indices
uint32_t xa = (uint32_t)DOUBLE_FLOOR(x);
uint32_t xb = (uint32_t)DOUBLE_CEIL (x);
uint32_t ya = (uint32_t)DOUBLE_FLOOR(y);
uint32_t yb = (uint32_t)DOUBLE_CEIL (y);
// get the normalized 0..1 interp factors, of x,y,z:
double xbf = DOUBLE_FRAC(x);
double xaf = 1.f - xbf;
double ybf = DOUBLE_FRAC(y);
double yaf = 1.f - ybf;
// get the interpolation corner weights:
double faa = xaf * yaf;
double fab = xaf * ybf;
double fba = xbf * yaf;
double fbb = xbf * ybf;
// get the cell addresses for each neighbor:
uint32_t fieldstride_x = header.stride[0];
uint32_t fieldstride_y = header.stride[1];
T * paa = (T *)(data.ptr + xa*fieldstride_x + ya*fieldstride_y);
T * pab = (T *)(data.ptr + xa*fieldstride_x + yb*fieldstride_y);
T * pba = (T *)(data.ptr + xb*fieldstride_x + ya*fieldstride_y);
T * pbb = (T *)(data.ptr + xb*fieldstride_x + yb*fieldstride_y);
// for each plane of the field, do the 3D interp:
for (uint8_t p=0; p<header.components; p++) {
val[p] = (paa[p] * faa) +
(pba[p] * fba) +
(pab[p] * fab) +
(pbb[p] * fbb);
}
#undef DOUBLE_FLOOR
#undef DOUBLE_CEIL
#undef DOUBLE_FRAC
}
// trilinear interpolated lookup (virtual lattice index x, y, z)
// writes the linearly interpolated plane values into val array
template<typename T> void interp3d(T* val, double x, double y, double z) {
#define DOUBLE_FLOOR(v) ( (long)(v) - ((v)<0.0 && (v)!=(long)(v)) )
#define DOUBLE_CEIL(v) ( (((v)>0.0)&&((v)!=(long)(v))) ? 1+(v) : (v) )
#define DOUBLE_FRAC(v) ( ((v)>=0.0) ? (v)-(long)(v) : (-v)-(long)(v) )
// convert 0..1 field indices to 0..(d-1) cell indices
uint32_t xa = (uint32_t)DOUBLE_FLOOR(x);
uint32_t xb = (uint32_t)DOUBLE_CEIL (x);
uint32_t ya = (uint32_t)DOUBLE_FLOOR(y);
uint32_t yb = (uint32_t)DOUBLE_CEIL (y);
uint32_t za = (uint32_t)DOUBLE_FLOOR(z);
uint32_t zb = (uint32_t)DOUBLE_CEIL (z);
// get the normalized 0..1 interp factors, of x,y,z:
double xbf = DOUBLE_FRAC(x);
double xaf = 1.f - xbf;
double ybf = DOUBLE_FRAC(y);
double yaf = 1.f - ybf;
double zbf = DOUBLE_FRAC(z);
double zaf = 1.f - zbf;
// get the interpolation corner weights:
double faaa = xaf * yaf * zaf;
double faab = xaf * yaf * zbf;
double faba = xaf * ybf * zaf;
double fabb = xaf * ybf * zbf;
double fbaa = xbf * yaf * zaf;
double fbab = xbf * yaf * zbf;
double fbba = xbf * ybf * zaf;
double fbbb = xbf * ybf * zbf;
// get the cell addresses for each neighbor:
uint32_t fieldstride_x = header.stride[0];
uint32_t fieldstride_y = header.stride[1];
uint32_t fieldstride_z = header.stride[2];
T * paaa = (T *)(data.ptr + xa*fieldstride_x + ya*fieldstride_y + za*fieldstride_z);
T * paab = (T *)(data.ptr + xa*fieldstride_x + ya*fieldstride_y + zb*fieldstride_z);
T * paba = (T *)(data.ptr + xa*fieldstride_x + yb*fieldstride_y + za*fieldstride_z);
T * pabb = (T *)(data.ptr + xa*fieldstride_x + yb*fieldstride_y + zb*fieldstride_z);
T * pbaa = (T *)(data.ptr + xb*fieldstride_x + ya*fieldstride_y + za*fieldstride_z);
T * pbab = (T *)(data.ptr + xb*fieldstride_x + ya*fieldstride_y + zb*fieldstride_z);
T * pbba = (T *)(data.ptr + xb*fieldstride_x + yb*fieldstride_y + za*fieldstride_z);
T * pbbb = (T *)(data.ptr + xb*fieldstride_x + yb*fieldstride_y + zb*fieldstride_z);
// for each plane of the field, do the 3D interp:
for (uint8_t p=0; p<header.components; p++) {
val[p] = (paaa[p] * faaa) +
(pbaa[p] * fbaa) +
(paba[p] * faba) +
(paab[p] * faab) +
(pbab[p] * fbab) +
(pabb[p] * fabb) +
(pbba[p] * fbba) +
(pbbb[p] * fbbb);
}
#undef DOUBLE_FLOOR
#undef DOUBLE_CEIL
#undef DOUBLE_FRAC
}
};
} // ::al::
#endif /* INCLUDE_ALLO_TYPES_CPP_H */
<|endoftext|>
|
<commit_before>/************************************************************************/
/* */
/* Copyright 1998-2002 by Ullrich Koethe */
/* Cognitive Systems Group, University of Hamburg, Germany */
/* */
/* This file is part of the VIGRA computer vision library. */
/* You may use, modify, and distribute this software according */
/* to the terms stated in the LICENSE file included in */
/* the VIGRA distribution. */
/* */
/* The VIGRA Website is */
/* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* [email protected] */
/* */
/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */
/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/* */
/************************************************************************/
#ifndef VIGRA_SYMMETRY_HXX
#define VIGRA_SYMMETRY_HXX
#include <vigra/utilities.hxx>
#include <vigra/numerictraits.hxx>
#include <vigra/stdimage.hxx>
#include <vigra/convolution.hxx>
namespace vigra {
/** \addtogroup SymmetryDetection Symmetry Detection
Measure the local symmetry at each pixel.
*/
//@{
/********************************************************/
/* */
/* radialSymmetryTransform */
/* */
/********************************************************/
/** \brief Find centers of radial symmetry in an image.
This algorithm implements the Fast Radial Symmetry Transform according to
[G. Loy, A. Zelinsky: <em> "A Fast Radial Symmetry Transform for Detecting
Points of Interest"</em>, in: A. Heyden et al. (Eds.): Proc. of 7th European
Conf. on Computer Vision, Part 1, pp. 358-368, Springer LNCS 2350, 2002].
Minima of the algorithm response mark dark blobs, maxima correspond to light blobs.
The "radial strictness parameter" is fixed at <TT>alpha</tt> = 2.0, the
spatial spreading of the raw response is done by a Gaussian convolution
at <tt>0.25*scale</TT> (these values are recommendations from the paper).
Loy and Zelinsky additionally propose to add the operator response from several
scales (see usage example below).
<b> Declarations:</b>
pass arguments explicitly:
\code
namespace vigra {
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
void
radialSymmetryTransform(SrcIterator sul, SrcIterator slr, SrcAccessor as,
DestIterator dul, DestAccessor ad,
double scale)
}
\endcode
use argument objects in conjuction with \ref ArgumentObjectFactories:
\code
namespace vigra {
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
inline
void radialSymmetryTransform(
triple<SrcIterator, SrcIterator, SrcAccessor> src,
pair<DestIterator, DestAccessor> dest,
double scale)
}
\endcode
<b> Usage:</b>
<b>\#include</b> "<a href="cornerdetection_8hxx-source.html">vigra/cornerdetection.hxx</a>"<br>
Namespace: vigra
\code
vigra::BImage src(w,h), centers(w,h);
vigra::FImage symmetry(w,h);
// empty result image
centers.init(128);
symmetry.init(0.0);
// input width of edge detection filter
for(double scale = 2.0; scale <= 8.0; scale *= 2.0)
{
vigra::FImage tmp(w,h);
// find centers of symmetry
radialSymmetryTransform(srcImageRange(in), destImage(tmp), scale);
combineTwoImages(srcImageRange(symmetry), srcImage(tmp), destImage(symmetry),
std::plus<float>());
}
localMinima(srcImageRange(symmetry), destImage(centers), 0);
localMaxima(srcImageRange(symmetry), destImage(centers), 255);
\endcode
<b> Required Interface:</b>
\code
SrcImageIterator src_upperleft, src_lowerright;
DestImageIterator dest_upperleft;
SrcAccessor src_accessor;
DestAccessor dest_accessor;
// SrcAccessor::value_type must be a built-in type
SrcAccessor::value_type u = src_accessor(src_upperleft);
dest_accessor.set(u, dest_upperleft);
\endcode
*/
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
void
radialSymmetryTransform(SrcIterator sul, SrcIterator slr, SrcAccessor as,
DestIterator dul, DestAccessor ad,
double scale)
{
vigra_precondition(scale > 0.0,
"radialSymmetryTransform(): Scale must be > 0");
int w = slr.x - sul.x;
int h = slr.y - sul.y;
if(w <= 0 || h <= 0) return;
typedef typename
NumericTraits<typename SrcAccessor::value_type>::RealPromote TmpType;
typedef BasicImage<TmpType> TmpImage;
typedef typename TmpImage::Iterator TmpIterator;
TmpImage gx(w,h);
TmpImage gy(w,h);
IImage orientationCounter(w,h);
TmpImage magnitudeAccumulator(w,h);
gaussianGradient(srcIterRange(sul, slr, as),
destImage(gx), destImage(gy),
scale);
orientationCounter.init(0);
magnitudeAccumulator.init(NumericTraits<TmpType>::zero());
TmpIterator gxi = gx.upperLeft();
TmpIterator gyi = gy.upperLeft();
int y;
for(y=0; y<h; ++y, ++gxi.y, ++gyi.y)
{
typename TmpIterator::row_iterator gxr = gxi.rowIterator();
typename TmpIterator::row_iterator gyr = gyi.rowIterator();
for(int x = 0; x<w; ++x, ++gxr, ++gyr)
{
double angle = VIGRA_CSTD::atan2(-*gyr, *gxr);
double magnitude = VIGRA_CSTD::sqrt(*gxr * *gxr + *gyr * *gyr);
if(magnitude < NumericTraits<TmpType>::epsilon()*10.0)
continue;
int dx = NumericTraits<int>::fromRealPromote(scale * VIGRA_CSTD::cos(angle));
int dy = NumericTraits<int>::fromRealPromote(scale * VIGRA_CSTD::sin(angle));
int xx = x + dx;
int yy = y - dy;
if(xx >= 0 && xx < w && yy >= 0 && yy < h)
{
orientationCounter(xx, yy) += 1;
magnitudeAccumulator(xx, yy) += magnitude;
}
xx = x - dx;
yy = y + dy;
if(xx >= 0 && xx < w && yy >= 0 && yy < h)
{
orientationCounter(xx, yy) -= 1;
magnitudeAccumulator(xx, yy) -= magnitude;
}
}
}
int maxOrientation = 0;
TmpType maxMagnitude = NumericTraits<TmpType>::zero();
for(y=0; y<h; ++y)
{
for(int x = 0; x<w; ++x)
{
int o = VIGRA_CSTD::abs(orientationCounter(x,y));
if(o > maxOrientation)
maxOrientation = o;
TmpType m = VIGRA_CSTD::abs(magnitudeAccumulator(x,y));
if(m > maxMagnitude)
maxMagnitude = m;
}
}
for(y=0; y<h; ++y)
{
for(int x = 0; x<w; ++x)
{
double o = (double)orientationCounter(x, y) / maxOrientation;
magnitudeAccumulator(x, y) = o * o * magnitudeAccumulator(x, y) / maxMagnitude;
}
}
gaussianSmoothing(srcImageRange(magnitudeAccumulator), destIter(dul, ad), 0.25*scale);
}
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
inline
void radialSymmetryTransform(
triple<SrcIterator, SrcIterator, SrcAccessor> src,
pair<DestIterator, DestAccessor> dest,
double scale)
{
radialSymmetryTransform(src.first, src.second, src.third,
dest.first, dest.second,
scale);
}
//@}
} // namespace vigra
#endif /* VIGRA_SYMMETRY_HXX */
<commit_msg>wrong #include and var. name in example code fixed<commit_after>/************************************************************************/
/* */
/* Copyright 1998-2002 by Ullrich Koethe */
/* Cognitive Systems Group, University of Hamburg, Germany */
/* */
/* This file is part of the VIGRA computer vision library. */
/* You may use, modify, and distribute this software according */
/* to the terms stated in the LICENSE file included in */
/* the VIGRA distribution. */
/* */
/* The VIGRA Website is */
/* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* [email protected] */
/* */
/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */
/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/* */
/************************************************************************/
#ifndef VIGRA_SYMMETRY_HXX
#define VIGRA_SYMMETRY_HXX
#include <vigra/utilities.hxx>
#include <vigra/numerictraits.hxx>
#include <vigra/stdimage.hxx>
#include <vigra/convolution.hxx>
namespace vigra {
/** \addtogroup SymmetryDetection Symmetry Detection
Measure the local symmetry at each pixel.
*/
//@{
/********************************************************/
/* */
/* radialSymmetryTransform */
/* */
/********************************************************/
/** \brief Find centers of radial symmetry in an image.
This algorithm implements the Fast Radial Symmetry Transform according to
[G. Loy, A. Zelinsky: <em> "A Fast Radial Symmetry Transform for Detecting
Points of Interest"</em>, in: A. Heyden et al. (Eds.): Proc. of 7th European
Conf. on Computer Vision, Part 1, pp. 358-368, Springer LNCS 2350, 2002].
Minima of the algorithm response mark dark blobs, maxima correspond to light blobs.
The "radial strictness parameter" is fixed at <TT>alpha</tt> = 2.0, the
spatial spreading of the raw response is done by a Gaussian convolution
at <tt>0.25*scale</TT> (these values are recommendations from the paper).
Loy and Zelinsky additionally propose to add the operator response from several
scales (see usage example below).
<b> Declarations:</b>
pass arguments explicitly:
\code
namespace vigra {
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
void
radialSymmetryTransform(SrcIterator sul, SrcIterator slr, SrcAccessor as,
DestIterator dul, DestAccessor ad,
double scale)
}
\endcode
use argument objects in conjuction with \ref ArgumentObjectFactories:
\code
namespace vigra {
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
inline
void radialSymmetryTransform(
triple<SrcIterator, SrcIterator, SrcAccessor> src,
pair<DestIterator, DestAccessor> dest,
double scale)
}
\endcode
<b> Usage:</b>
<b>\#include</b> "<a href="symmetry_8hxx-source.html">vigra/symmetry.hxx</a>"<br>
Namespace: vigra
\code
vigra::BImage src(w,h), centers(w,h);
vigra::FImage symmetry(w,h);
// empty result image
centers.init(128);
symmetry.init(0.0);
// input width of edge detection filter
for(double scale = 2.0; scale <= 8.0; scale *= 2.0)
{
vigra::FImage tmp(w,h);
// find centers of symmetry
radialSymmetryTransform(srcImageRange(src), destImage(tmp), scale);
combineTwoImages(srcImageRange(symmetry), srcImage(tmp), destImage(symmetry),
std::plus<float>());
}
localMinima(srcImageRange(symmetry), destImage(centers), 0);
localMaxima(srcImageRange(symmetry), destImage(centers), 255);
\endcode
<b> Required Interface:</b>
\code
SrcImageIterator src_upperleft, src_lowerright;
DestImageIterator dest_upperleft;
SrcAccessor src_accessor;
DestAccessor dest_accessor;
// SrcAccessor::value_type must be a built-in type
SrcAccessor::value_type u = src_accessor(src_upperleft);
dest_accessor.set(u, dest_upperleft);
\endcode
*/
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
void
radialSymmetryTransform(SrcIterator sul, SrcIterator slr, SrcAccessor as,
DestIterator dul, DestAccessor ad,
double scale)
{
vigra_precondition(scale > 0.0,
"radialSymmetryTransform(): Scale must be > 0");
int w = slr.x - sul.x;
int h = slr.y - sul.y;
if(w <= 0 || h <= 0) return;
typedef typename
NumericTraits<typename SrcAccessor::value_type>::RealPromote TmpType;
typedef BasicImage<TmpType> TmpImage;
typedef typename TmpImage::Iterator TmpIterator;
TmpImage gx(w,h);
TmpImage gy(w,h);
IImage orientationCounter(w,h);
TmpImage magnitudeAccumulator(w,h);
gaussianGradient(srcIterRange(sul, slr, as),
destImage(gx), destImage(gy),
scale);
orientationCounter.init(0);
magnitudeAccumulator.init(NumericTraits<TmpType>::zero());
TmpIterator gxi = gx.upperLeft();
TmpIterator gyi = gy.upperLeft();
int y;
for(y=0; y<h; ++y, ++gxi.y, ++gyi.y)
{
typename TmpIterator::row_iterator gxr = gxi.rowIterator();
typename TmpIterator::row_iterator gyr = gyi.rowIterator();
for(int x = 0; x<w; ++x, ++gxr, ++gyr)
{
double angle = VIGRA_CSTD::atan2(-*gyr, *gxr);
double magnitude = VIGRA_CSTD::sqrt(*gxr * *gxr + *gyr * *gyr);
if(magnitude < NumericTraits<TmpType>::epsilon()*10.0)
continue;
int dx = NumericTraits<int>::fromRealPromote(scale * VIGRA_CSTD::cos(angle));
int dy = NumericTraits<int>::fromRealPromote(scale * VIGRA_CSTD::sin(angle));
int xx = x + dx;
int yy = y - dy;
if(xx >= 0 && xx < w && yy >= 0 && yy < h)
{
orientationCounter(xx, yy) += 1;
magnitudeAccumulator(xx, yy) += magnitude;
}
xx = x - dx;
yy = y + dy;
if(xx >= 0 && xx < w && yy >= 0 && yy < h)
{
orientationCounter(xx, yy) -= 1;
magnitudeAccumulator(xx, yy) -= magnitude;
}
}
}
int maxOrientation = 0;
TmpType maxMagnitude = NumericTraits<TmpType>::zero();
for(y=0; y<h; ++y)
{
for(int x = 0; x<w; ++x)
{
int o = VIGRA_CSTD::abs(orientationCounter(x,y));
if(o > maxOrientation)
maxOrientation = o;
TmpType m = VIGRA_CSTD::abs(magnitudeAccumulator(x,y));
if(m > maxMagnitude)
maxMagnitude = m;
}
}
for(y=0; y<h; ++y)
{
for(int x = 0; x<w; ++x)
{
double o = (double)orientationCounter(x, y) / maxOrientation;
magnitudeAccumulator(x, y) = o * o * magnitudeAccumulator(x, y) / maxMagnitude;
}
}
gaussianSmoothing(srcImageRange(magnitudeAccumulator), destIter(dul, ad), 0.25*scale);
}
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
inline
void radialSymmetryTransform(
triple<SrcIterator, SrcIterator, SrcAccessor> src,
pair<DestIterator, DestAccessor> dest,
double scale)
{
radialSymmetryTransform(src.first, src.second, src.third,
dest.first, dest.second,
scale);
}
//@}
} // namespace vigra
#endif /* VIGRA_SYMMETRY_HXX */
<|endoftext|>
|
<commit_before>#include "indexer/ftypes_matcher.hpp"
#include "indexer/feature.hpp"
#include "indexer/feature_data.hpp"
#include "indexer/classificator.hpp"
#include "std/sstream.hpp"
#include "std/utility.hpp"
namespace ftypes
{
uint32_t BaseChecker::PrepareToMatch(uint32_t type, uint8_t level)
{
ftype::TruncValue(type, level);
return type;
}
bool BaseChecker::IsMatched(uint32_t type) const
{
return (find(m_types.begin(), m_types.end(), PrepareToMatch(type, m_level)) != m_types.end());
}
bool BaseChecker::operator() (feature::TypesHolder const & types) const
{
for (uint32_t t : types)
if (IsMatched(t))
return true;
return false;
}
bool BaseChecker::operator() (FeatureType const & ft) const
{
return this->operator() (feature::TypesHolder(ft));
}
bool BaseChecker::operator() (vector<uint32_t> const & types) const
{
for (size_t i = 0; i < types.size(); ++i)
{
if (IsMatched(types[i]))
return true;
}
return false;
}
bool BaseChecker::HasTypeValue(uint32_t const type) const
{
return find(m_types.begin(), m_types.end(), type) != m_types.end();
}
IsPeakChecker::IsPeakChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "natural", "peak" }));
}
IsPeakChecker const & IsPeakChecker::Instance()
{
static const IsPeakChecker inst;
return inst;
}
IsATMChecker::IsATMChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "amenity", "atm" }));
}
IsATMChecker const & IsATMChecker::Instance()
{
static const IsATMChecker inst;
return inst;
}
IsSpeedCamChecker::IsSpeedCamChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({"highway", "speed_camera"}));
}
// static
IsSpeedCamChecker const & IsSpeedCamChecker::Instance()
{
static const IsSpeedCamChecker instance;
return instance;
}
IsFuelStationChecker::IsFuelStationChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "amenity", "fuel" }));
}
IsFuelStationChecker const & IsFuelStationChecker::Instance()
{
static const IsFuelStationChecker inst;
return inst;
}
IsRailwayStationChecker::IsRailwayStationChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({"railway", "station"}));
}
IsRailwayStationChecker const & IsRailwayStationChecker::Instance()
{
static const IsRailwayStationChecker inst;
return inst;
}
IsStreetChecker::IsStreetChecker()
{
// TODO (@y, @m, @vng): this list must be up-to-date with
// data/categories.txt, so, it's worth it to generate or parse it
// from that file.
Classificator const & c = classif();
char const * arr[][2] = {{"highway", "living_street"},
{"highway", "footway"},
{"highway", "motorway"},
{"highway", "motorway_link"},
{"highway", "path"},
{"highway", "pedestrian"},
{"highway", "primary"},
{"highway", "primary_link"},
{"highway", "residential"},
{"highway", "road"},
{"highway", "secondary"},
{"highway", "secondary_link"},
{"highway", "service"},
{"highway", "tertiary"},
{"highway", "tertiary_link"},
{"highway", "track"},
{"highway", "trunk"},
{"highway", "trunk_link"},
{"highway", "unclassified"}};
for (auto const & p : arr)
m_types.push_back(c.GetTypeByPath({p[0], p[1]}));
}
IsStreetChecker const & IsStreetChecker::Instance()
{
static const IsStreetChecker inst;
return inst;
}
IsAddressObjectChecker::IsAddressObjectChecker() : BaseChecker(1 /* level */)
{
auto const paths = { "building", "amenity", "shop", "tourism", "historic", "office", "craft" };
Classificator const & c = classif();
for (auto const & p : paths)
m_types.push_back(c.GetTypeByPath({p}));
}
IsAddressObjectChecker const & IsAddressObjectChecker::Instance()
{
static const IsAddressObjectChecker inst;
return inst;
}
IsVillageChecker::IsVillageChecker()
{
// TODO (@y, @m, @vng): this list must be up-to-date with
// data/categories.txt, so, it's worth it to generate or parse it
// from that file.
Classificator const & c = classif();
char const * arr[][2] = {{"place", "village"}, {"place", "hamlet"}};
for (auto const & p : arr)
m_types.push_back(c.GetTypeByPath({p[0], p[1]}));
}
IsVillageChecker const & IsVillageChecker::Instance()
{
static const IsVillageChecker inst;
return inst;
}
IsOneWayChecker::IsOneWayChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "hwtag", "oneway" }));
}
IsOneWayChecker const & IsOneWayChecker::Instance()
{
static const IsOneWayChecker inst;
return inst;
}
IsRoundAboutChecker::IsRoundAboutChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "junction", "roundabout" }));
}
IsRoundAboutChecker const & IsRoundAboutChecker::Instance()
{
static const IsRoundAboutChecker inst;
return inst;
}
IsLinkChecker::IsLinkChecker()
{
Classificator const & c = classif();
char const * arr[][2] = {
{ "highway", "motorway_link" },
{ "highway", "trunk_link" },
{ "highway", "primary_link" },
{ "highway", "secondary_link" },
{ "highway", "tertiary_link" }
};
for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2)));
}
IsLinkChecker const & IsLinkChecker::Instance()
{
static const IsLinkChecker inst;
return inst;
}
IsBuildingChecker::IsBuildingChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "building" }));
m_types.push_back(c.GetTypeByPath({ "building", "address" }));
}
IsBuildingChecker const & IsBuildingChecker::Instance()
{
static const IsBuildingChecker inst;
return inst;
}
IsLocalityChecker::IsLocalityChecker()
{
Classificator const & c = classif();
// Note! The order should be equal with constants in Type enum (add other villages to the end).
char const * arr[][2] = {
{ "place", "country" },
{ "place", "state" },
{ "place", "city" },
{ "place", "town" },
{ "place", "village" },
{ "place", "hamlet" }
};
for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2)));
}
IsBuildingPartChecker::IsBuildingPartChecker() : BaseChecker(1)
{
m_types.push_back(classif().GetTypeByPath({"building:part"}));
}
IsBuildingPartChecker const & IsBuildingPartChecker::Instance()
{
static const IsBuildingPartChecker inst;
return inst;
}
IsBridgeChecker::IsBridgeChecker() : BaseChecker(3)
{
}
IsBridgeChecker const & IsBridgeChecker::Instance()
{
static const IsBridgeChecker inst;
return inst;
}
bool IsBridgeChecker::IsMatched(uint32_t type) const
{
return IsTypeConformed(type, {"highway", "*", "bridge"});
}
IsTunnelChecker::IsTunnelChecker() : BaseChecker(3)
{
}
IsTunnelChecker const & IsTunnelChecker::Instance()
{
static const IsTunnelChecker inst;
return inst;
}
bool IsTunnelChecker::IsMatched(uint32_t type) const
{
return IsTypeConformed(type, {"highway", "*", "tunnel"});
}
Type IsLocalityChecker::GetType(feature::TypesHolder const & types) const
{
for (uint32_t t : types)
{
ftype::TruncValue(t, 2);
size_t j = COUNTRY;
for (; j < LOCALITY_COUNT; ++j)
if (t == m_types[j])
return static_cast<Type>(j);
for (; j < m_types.size(); ++j)
if (t == m_types[j])
return VILLAGE;
}
return NONE;
}
Type IsLocalityChecker::GetType(const FeatureType & f) const
{
feature::TypesHolder types(f);
return GetType(types);
}
IsLocalityChecker const & IsLocalityChecker::Instance()
{
static IsLocalityChecker const inst;
return inst;
}
uint32_t GetPopulation(FeatureType const & ft)
{
uint32_t population = ft.GetPopulation();
if (population < 10)
{
switch (IsLocalityChecker::Instance().GetType(ft))
{
case CITY:
case TOWN:
population = 10000;
break;
case VILLAGE:
population = 100;
break;
default:
population = 0;
}
}
return population;
}
double GetRadiusByPopulation(uint32_t p)
{
return pow(static_cast<double>(p), 0.277778) * 550.0;
}
uint32_t GetPopulationByRadius(double r)
{
return my::rounds(pow(r / 550.0, 3.6));
}
bool IsTypeConformed(uint32_t type, StringIL const & path)
{
ClassifObject const * p = classif().GetRoot();
ASSERT(p, ());
uint8_t val = 0, i = 0;
for (char const * s : path)
{
if (!ftype::GetValue(type, i, val))
return false;
p = p->GetObject(val);
if (p == 0)
return false;
if (p->GetName() != s && strcmp(s, "*") != 0)
return false;
++i;
}
return true;
}
string DebugPrint(HighwayClass const cls)
{
stringstream out;
out << "[ ";
switch (cls)
{
case HighwayClass::Undefined:
out << "Undefined";
case HighwayClass::Error:
out << "Error";
case HighwayClass::Trunk:
out << "Trunk";
case HighwayClass::Primary:
out << "Primary";
case HighwayClass::Secondary:
out << "Secondary";
case HighwayClass::Tertiary:
out << "Tertiary";
case HighwayClass::LivingStreet:
out << "LivingStreet";
case HighwayClass::Service:
out << "Service";
case HighwayClass::Count:
out << "Count";
default:
out << "Unknown value of HighwayClass: " << static_cast<int>(cls);
}
out << " ]";
return out.str();
}
HighwayClass GetHighwayClass(feature::TypesHolder const & types)
{
Classificator const & c = classif();
static pair<HighwayClass, uint32_t> const kHighwayClasses[] = {
{HighwayClass::Trunk, c.GetTypeByPath({"highway", "motorway"})},
{HighwayClass::Trunk, c.GetTypeByPath({"highway", "motorway_link"})},
{HighwayClass::Trunk, c.GetTypeByPath({"highway", "trunk"})},
{HighwayClass::Trunk, c.GetTypeByPath({"highway", "trunk_link"})},
{HighwayClass::Trunk, c.GetTypeByPath({"route", "ferry"})},
{HighwayClass::Primary, c.GetTypeByPath({"highway", "primary"})},
{HighwayClass::Primary, c.GetTypeByPath({"highway", "primary_link"})},
{HighwayClass::Secondary, c.GetTypeByPath({"highway", "secondary"})},
{HighwayClass::Secondary, c.GetTypeByPath({"highway", "secondary_link"})},
{HighwayClass::Tertiary, c.GetTypeByPath({"highway", "tertiary"})},
{HighwayClass::Tertiary, c.GetTypeByPath({"highway", "tertiary_link"})},
{HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "unclassified"})},
{HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "residential"})},
{HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "living_street"})},
{HighwayClass::Service, c.GetTypeByPath({"highway", "service"})},
{HighwayClass::Service, c.GetTypeByPath({"highway", "track"})}};
uint8_t const kTruncLevel = 2;
for (auto t : types)
{
ftype::TruncValue(t, kTruncLevel);
for (auto const & cls : kHighwayClasses)
{
if (cls.second == t)
return cls.first;
}
}
return HighwayClass::Error;
}
HighwayClass GetHighwayClass(FeatureType const & ft)
{
return GetHighwayClass(feature::TypesHolder(ft));
}
}
<commit_msg>Better IsBuildingChecker routine.<commit_after>#include "indexer/ftypes_matcher.hpp"
#include "indexer/feature.hpp"
#include "indexer/feature_data.hpp"
#include "indexer/classificator.hpp"
#include "std/sstream.hpp"
#include "std/utility.hpp"
namespace ftypes
{
uint32_t BaseChecker::PrepareToMatch(uint32_t type, uint8_t level)
{
ftype::TruncValue(type, level);
return type;
}
bool BaseChecker::IsMatched(uint32_t type) const
{
return (find(m_types.begin(), m_types.end(), PrepareToMatch(type, m_level)) != m_types.end());
}
bool BaseChecker::operator() (feature::TypesHolder const & types) const
{
for (uint32_t t : types)
if (IsMatched(t))
return true;
return false;
}
bool BaseChecker::operator() (FeatureType const & ft) const
{
return this->operator() (feature::TypesHolder(ft));
}
bool BaseChecker::operator() (vector<uint32_t> const & types) const
{
for (size_t i = 0; i < types.size(); ++i)
{
if (IsMatched(types[i]))
return true;
}
return false;
}
bool BaseChecker::HasTypeValue(uint32_t const type) const
{
return find(m_types.begin(), m_types.end(), type) != m_types.end();
}
IsPeakChecker::IsPeakChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "natural", "peak" }));
}
IsPeakChecker const & IsPeakChecker::Instance()
{
static const IsPeakChecker inst;
return inst;
}
IsATMChecker::IsATMChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "amenity", "atm" }));
}
IsATMChecker const & IsATMChecker::Instance()
{
static const IsATMChecker inst;
return inst;
}
IsSpeedCamChecker::IsSpeedCamChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({"highway", "speed_camera"}));
}
// static
IsSpeedCamChecker const & IsSpeedCamChecker::Instance()
{
static const IsSpeedCamChecker instance;
return instance;
}
IsFuelStationChecker::IsFuelStationChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "amenity", "fuel" }));
}
IsFuelStationChecker const & IsFuelStationChecker::Instance()
{
static const IsFuelStationChecker inst;
return inst;
}
IsRailwayStationChecker::IsRailwayStationChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({"railway", "station"}));
}
IsRailwayStationChecker const & IsRailwayStationChecker::Instance()
{
static const IsRailwayStationChecker inst;
return inst;
}
IsStreetChecker::IsStreetChecker()
{
// TODO (@y, @m, @vng): this list must be up-to-date with
// data/categories.txt, so, it's worth it to generate or parse it
// from that file.
Classificator const & c = classif();
char const * arr[][2] = {{"highway", "living_street"},
{"highway", "footway"},
{"highway", "motorway"},
{"highway", "motorway_link"},
{"highway", "path"},
{"highway", "pedestrian"},
{"highway", "primary"},
{"highway", "primary_link"},
{"highway", "residential"},
{"highway", "road"},
{"highway", "secondary"},
{"highway", "secondary_link"},
{"highway", "service"},
{"highway", "tertiary"},
{"highway", "tertiary_link"},
{"highway", "track"},
{"highway", "trunk"},
{"highway", "trunk_link"},
{"highway", "unclassified"}};
for (auto const & p : arr)
m_types.push_back(c.GetTypeByPath({p[0], p[1]}));
}
IsStreetChecker const & IsStreetChecker::Instance()
{
static const IsStreetChecker inst;
return inst;
}
IsAddressObjectChecker::IsAddressObjectChecker() : BaseChecker(1 /* level */)
{
auto const paths = { "building", "amenity", "shop", "tourism", "historic", "office", "craft" };
Classificator const & c = classif();
for (auto const & p : paths)
m_types.push_back(c.GetTypeByPath({p}));
}
IsAddressObjectChecker const & IsAddressObjectChecker::Instance()
{
static const IsAddressObjectChecker inst;
return inst;
}
IsVillageChecker::IsVillageChecker()
{
// TODO (@y, @m, @vng): this list must be up-to-date with
// data/categories.txt, so, it's worth it to generate or parse it
// from that file.
Classificator const & c = classif();
char const * arr[][2] = {{"place", "village"}, {"place", "hamlet"}};
for (auto const & p : arr)
m_types.push_back(c.GetTypeByPath({p[0], p[1]}));
}
IsVillageChecker const & IsVillageChecker::Instance()
{
static const IsVillageChecker inst;
return inst;
}
IsOneWayChecker::IsOneWayChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "hwtag", "oneway" }));
}
IsOneWayChecker const & IsOneWayChecker::Instance()
{
static const IsOneWayChecker inst;
return inst;
}
IsRoundAboutChecker::IsRoundAboutChecker()
{
Classificator const & c = classif();
m_types.push_back(c.GetTypeByPath({ "junction", "roundabout" }));
}
IsRoundAboutChecker const & IsRoundAboutChecker::Instance()
{
static const IsRoundAboutChecker inst;
return inst;
}
IsLinkChecker::IsLinkChecker()
{
Classificator const & c = classif();
char const * arr[][2] = {
{ "highway", "motorway_link" },
{ "highway", "trunk_link" },
{ "highway", "primary_link" },
{ "highway", "secondary_link" },
{ "highway", "tertiary_link" }
};
for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2)));
}
IsLinkChecker const & IsLinkChecker::Instance()
{
static const IsLinkChecker inst;
return inst;
}
IsBuildingChecker::IsBuildingChecker() : BaseChecker(1 /* level */)
{
m_types.push_back(classif().GetTypeByPath({ "building" }));
}
IsBuildingChecker const & IsBuildingChecker::Instance()
{
static const IsBuildingChecker inst;
return inst;
}
IsLocalityChecker::IsLocalityChecker()
{
Classificator const & c = classif();
// Note! The order should be equal with constants in Type enum (add other villages to the end).
char const * arr[][2] = {
{ "place", "country" },
{ "place", "state" },
{ "place", "city" },
{ "place", "town" },
{ "place", "village" },
{ "place", "hamlet" }
};
for (size_t i = 0; i < ARRAY_SIZE(arr); ++i)
m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2)));
}
IsBuildingPartChecker::IsBuildingPartChecker() : BaseChecker(1 /* level */)
{
m_types.push_back(classif().GetTypeByPath({"building:part"}));
}
IsBuildingPartChecker const & IsBuildingPartChecker::Instance()
{
static const IsBuildingPartChecker inst;
return inst;
}
IsBridgeChecker::IsBridgeChecker() : BaseChecker(3 /* level */)
{
}
IsBridgeChecker const & IsBridgeChecker::Instance()
{
static const IsBridgeChecker inst;
return inst;
}
bool IsBridgeChecker::IsMatched(uint32_t type) const
{
return IsTypeConformed(type, {"highway", "*", "bridge"});
}
IsTunnelChecker::IsTunnelChecker() : BaseChecker(3 /* level */)
{
}
IsTunnelChecker const & IsTunnelChecker::Instance()
{
static const IsTunnelChecker inst;
return inst;
}
bool IsTunnelChecker::IsMatched(uint32_t type) const
{
return IsTypeConformed(type, {"highway", "*", "tunnel"});
}
Type IsLocalityChecker::GetType(feature::TypesHolder const & types) const
{
for (uint32_t t : types)
{
ftype::TruncValue(t, 2);
size_t j = COUNTRY;
for (; j < LOCALITY_COUNT; ++j)
if (t == m_types[j])
return static_cast<Type>(j);
for (; j < m_types.size(); ++j)
if (t == m_types[j])
return VILLAGE;
}
return NONE;
}
Type IsLocalityChecker::GetType(const FeatureType & f) const
{
feature::TypesHolder types(f);
return GetType(types);
}
IsLocalityChecker const & IsLocalityChecker::Instance()
{
static IsLocalityChecker const inst;
return inst;
}
uint32_t GetPopulation(FeatureType const & ft)
{
uint32_t population = ft.GetPopulation();
if (population < 10)
{
switch (IsLocalityChecker::Instance().GetType(ft))
{
case CITY:
case TOWN:
population = 10000;
break;
case VILLAGE:
population = 100;
break;
default:
population = 0;
}
}
return population;
}
double GetRadiusByPopulation(uint32_t p)
{
return pow(static_cast<double>(p), 0.277778) * 550.0;
}
uint32_t GetPopulationByRadius(double r)
{
return my::rounds(pow(r / 550.0, 3.6));
}
bool IsTypeConformed(uint32_t type, StringIL const & path)
{
ClassifObject const * p = classif().GetRoot();
ASSERT(p, ());
uint8_t val = 0, i = 0;
for (char const * s : path)
{
if (!ftype::GetValue(type, i, val))
return false;
p = p->GetObject(val);
if (p == 0)
return false;
if (p->GetName() != s && strcmp(s, "*") != 0)
return false;
++i;
}
return true;
}
string DebugPrint(HighwayClass const cls)
{
stringstream out;
out << "[ ";
switch (cls)
{
case HighwayClass::Undefined:
out << "Undefined";
case HighwayClass::Error:
out << "Error";
case HighwayClass::Trunk:
out << "Trunk";
case HighwayClass::Primary:
out << "Primary";
case HighwayClass::Secondary:
out << "Secondary";
case HighwayClass::Tertiary:
out << "Tertiary";
case HighwayClass::LivingStreet:
out << "LivingStreet";
case HighwayClass::Service:
out << "Service";
case HighwayClass::Count:
out << "Count";
default:
out << "Unknown value of HighwayClass: " << static_cast<int>(cls);
}
out << " ]";
return out.str();
}
HighwayClass GetHighwayClass(feature::TypesHolder const & types)
{
Classificator const & c = classif();
static pair<HighwayClass, uint32_t> const kHighwayClasses[] = {
{HighwayClass::Trunk, c.GetTypeByPath({"highway", "motorway"})},
{HighwayClass::Trunk, c.GetTypeByPath({"highway", "motorway_link"})},
{HighwayClass::Trunk, c.GetTypeByPath({"highway", "trunk"})},
{HighwayClass::Trunk, c.GetTypeByPath({"highway", "trunk_link"})},
{HighwayClass::Trunk, c.GetTypeByPath({"route", "ferry"})},
{HighwayClass::Primary, c.GetTypeByPath({"highway", "primary"})},
{HighwayClass::Primary, c.GetTypeByPath({"highway", "primary_link"})},
{HighwayClass::Secondary, c.GetTypeByPath({"highway", "secondary"})},
{HighwayClass::Secondary, c.GetTypeByPath({"highway", "secondary_link"})},
{HighwayClass::Tertiary, c.GetTypeByPath({"highway", "tertiary"})},
{HighwayClass::Tertiary, c.GetTypeByPath({"highway", "tertiary_link"})},
{HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "unclassified"})},
{HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "residential"})},
{HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "living_street"})},
{HighwayClass::Service, c.GetTypeByPath({"highway", "service"})},
{HighwayClass::Service, c.GetTypeByPath({"highway", "track"})}};
uint8_t const kTruncLevel = 2;
for (auto t : types)
{
ftype::TruncValue(t, kTruncLevel);
for (auto const & cls : kHighwayClasses)
{
if (cls.second == t)
return cls.first;
}
}
return HighwayClass::Error;
}
HighwayClass GetHighwayClass(FeatureType const & ft)
{
return GetHighwayClass(feature::TypesHolder(ft));
}
}
<|endoftext|>
|
<commit_before>#include "rssitem.h"
#include "3rd-party/catch.hpp"
#include "cache.h"
#include "configcontainer.h"
using namespace newsboat;
TEST_CASE("RssItem::sort_flags() cleans up flags", "[RssItem]")
{
ConfigContainer cfg;
Cache rsscache(":memory:", &cfg);
RssItem item(&rsscache);
SECTION("Repeated letters do not erase other letters") {
std::string inputflags = "Abcdecf";
std::string result = "Abcdef";
item.set_flags(inputflags);
REQUIRE(result == item.flags());
}
SECTION("Non alpha characters in input flags are ignored") {
std::string inputflags = "Abcd";
item.set_flags(inputflags + "1234568790^\"#'é(£");
REQUIRE(inputflags == item.flags());
}
}
<commit_msg>Add tests for matchable attributes in RssItem<commit_after>#include "rssitem.h"
#include <unistd.h>
#include "3rd-party/catch.hpp"
#include "cache.h"
#include "configcontainer.h"
#include "rssfeed.h"
#include "test-helpers/envvar.h"
using namespace newsboat;
TEST_CASE("RssItem::sort_flags() cleans up flags", "[RssItem]")
{
ConfigContainer cfg;
Cache rsscache(":memory:", &cfg);
RssItem item(&rsscache);
SECTION("Repeated letters do not erase other letters") {
std::string inputflags = "Abcdecf";
std::string result = "Abcdef";
item.set_flags(inputflags);
REQUIRE(result == item.flags());
}
SECTION("Non alpha characters in input flags are ignored") {
std::string inputflags = "Abcd";
item.set_flags(inputflags + "1234568790^\"#'é(£");
REQUIRE(inputflags == item.flags());
}
}
TEST_CASE("RssItem contains a number of matchable attributes", "[RssItem]")
{
ConfigContainer cfg;
Cache rsscache(":memory:", &cfg);
RssItem item(&rsscache);
SECTION("title") {
const auto attr = "title";
const auto title = "Example title";
item.set_title(title);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == title);
// TODO: check that the result is in the locale charset
}
SECTION("link") {
const auto attr = "link";
const auto url = "http://example.com/newest-update.html";
item.set_link(url);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == url);
}
SECTION("author") {
const auto attr = "author";
const auto name = "John Doe";
item.set_author(name);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == name);
// TODO: check that the result is in the locale charset
}
SECTION("content") {
const auto attr = "content";
const auto description = "First line.\nSecond one.\nAnd finally the third";
item.set_description(description);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == description);
// TODO: check that the result is in the locale charset
}
SECTION("date") {
TestHelpers::EnvVar tzEnv("TZ");
tzEnv.set("UTC");
const auto attr = "date";
item.set_pubDate(1); // 1 second into the Unix epoch
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == "Thu, 01 Jan 1970 00:00:01 +0000");
}
SECTION("guid") {
const auto attr = "guid";
const auto guid = "unique-identifier-of-this-item";
item.set_guid(guid);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == guid);
}
SECTION("unread") {
const auto attr = "unread";
SECTION("for read items, attribute equals \"no\"") {
item.set_unread(false);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == "no");
}
SECTION("for unread items, attribute equals \"yes\"") {
item.set_unread(true);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == "yes");
}
}
SECTION("enclosure_url") {
const auto attr = "enclosure_url";
const auto url = "https://example.com/podcast-ep-01.mp3";
item.set_enclosure_url(url);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == url);
}
SECTION("enclosure_type, MIME type of the enclosure") {
const auto attr = "enclosure_type";
const auto type = "audio/ogg";
item.set_enclosure_type(type);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == type);
}
SECTION("flags") {
const auto attr = "flags";
const auto flags = "abcdefg";
item.set_flags(flags);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == flags);
}
SECTION("age, the number of days since publication") {
const auto attr = "age";
item.set_pubDate(0); // beginning of Unix epoch
const auto check = [&item, &attr]() {
// time() returns seconds since Unix epoch, too
const auto current_time = ::time(nullptr);
const auto seconds_per_day = 24 * 60 * 60;
const auto unix_days = current_time / seconds_per_day;
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == std::to_string(unix_days));
};
// check() evaluates current time twice: once explicitly by calling
// time(), once implicitly by calling get_attribute("age"). On
// a midnight, it's possible for the first call to execute on one day,
// and the second call to execute on the next day. That'll lead to the
// test failing. To avoid that, we perform a dirty trick: we run the
// test once, and if it fails, we immediately re-run it. If the failure
// was indeed caused by the aforementioned corner case, the second run
// can't fail (we're already in the next day, and it's inconceivable
// for code to run so slow that we're at the next midnight already). If
// the second call fails, that failure is going to fail the whole
// TEST_CASE, as it should.
try {
check();
} catch (...) {
check();
}
}
SECTION("articleindex, article's position in the itemlist") {
const auto attr = "articleindex";
const auto check = [&attr, &item](unsigned int index) {
item.set_index(index);
REQUIRE(item.has_attribute(attr));
REQUIRE(item.get_attribute(attr) == std::to_string(index));
};
check(1);
check(3);
check(65535);
check(100500);
}
SECTION("unknown attributes are forwarded to parent feed") {
auto feed = std::make_shared<RssFeed>(&rsscache);
auto item = std::make_shared<RssItem>(&rsscache);
feed->add_item(item);
const auto feedindex = 42;
feed->set_index(feedindex);
const auto attr = "feedindex";
SECTION("no parent feed => attribute unavailable") {
REQUIRE_FALSE(item->has_attribute(attr));
}
SECTION("request forwarded to parent feed") {
item->set_feedptr(feed);
REQUIRE(item->has_attribute(attr));
REQUIRE(item->get_attribute(attr) == std::to_string(feedindex));
}
}
}
<|endoftext|>
|
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <babylon/core/future_then.h>
#define USE_TIMINGS 0
inline std::string thread_id_string(const std::thread::id& threadId)
{
std::stringstream ss;
ss << threadId;
return ss.str();
}
inline size_t string_counter(const std::string& s)
{
#if USE_TIMINGS
std::this_thread::sleep_for(std::chrono::seconds(1));
#endif
return s.size();
}
std::size_t string_count_accumulator(const std::vector<std::string>& strings)
{
std::vector<std::future<size_t>> calcs;
for (auto&& s : strings) {
calcs.push_back(std::async(std::launch::async,
[&s]() -> size_t { return string_counter(s); }));
}
std::size_t total = 0;
for (auto&& fut : calcs) {
total += fut.get();
}
return total;
}
TEST(TestFutureThen, AsyncContinuation)
{
using namespace BABYLON;
{
auto task1
= std::async([] { return thread_id_string(std::this_thread::get_id()); });
auto task2 = then(task1, [](std::future<std::string>& f) {
auto currentThreadId = thread_id_string(std::this_thread::get_id());
EXPECT_NE(f.get(), currentThreadId);
return currentThreadId;
});
auto task3 = then(task2, [](std::future<std::string>& f) {
auto currentThreadId = thread_id_string(std::this_thread::get_id());
EXPECT_NE(f.get(), currentThreadId);
return currentThreadId;
});
task3.wait();
}
{
auto task1 = std::async(std::launch::async, [] { return 1; });
auto task2 = then(task1, std::launch::async,
[](std::future<int>& f) { return f.get() + 2; });
auto task3 = then(task2, std::launch::async,
[](std::future<int>& f) { return f.get() + 3; });
// Check result received from continuation in parent task
EXPECT_EQ(task3.get(), 6);
}
{
#if USE_TIMINGS
// Get Start Time
std::chrono::system_clock::time_point start
= std::chrono::system_clock::now();
#endif
auto task1 = std::async(std::launch::async, [] {
return string_count_accumulator({"this", "is", "task1"});
});
auto task2
= then(task1, std::launch::async, [](std::future<std::size_t>& f) {
return f.get()
+ string_count_accumulator({"and", "this", "is", "task2"});
});
#if USE_TIMINGS
// Get End Time
auto end = std::chrono::system_clock::now();
auto diff
= std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
.count();
std::cout << "Total Time Taken = " << diff << " milliseconds\n";
#endif
// Check result received from continuation in parent task
EXPECT_EQ(task2.get(), 25);
}
}
<commit_msg>disable TestFutureThen.AsyncContinuation under OSX<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <babylon/core/future_then.h>
#define USE_TIMINGS 0
inline std::string thread_id_string(const std::thread::id& threadId)
{
std::stringstream ss;
ss << threadId;
return ss.str();
}
inline size_t string_counter(const std::string& s)
{
#if USE_TIMINGS
std::this_thread::sleep_for(std::chrono::seconds(1));
#endif
return s.size();
}
std::size_t string_count_accumulator(const std::vector<std::string>& strings)
{
std::vector<std::future<size_t>> calcs;
for (auto&& s : strings) {
calcs.push_back(std::async(std::launch::async,
[&s]() -> size_t { return string_counter(s); }));
}
std::size_t total = 0;
for (auto&& fut : calcs) {
total += fut.get();
}
return total;
}
TEST(TestFutureThen, AsyncContinuation)
{
using namespace BABYLON;
#ifndef __APPLE__
// TODO: these tests may fail under OSX (with a 30% chance of failure)
// thread_id might sometimes be the same (even if forcing std::launch::async policy)
{
auto task1
= std::async([] { return thread_id_string(std::this_thread::get_id()); });
auto task2 = then(task1, [](std::future<std::string>& f) {
auto currentThreadId = thread_id_string(std::this_thread::get_id());
EXPECT_NE(f.get(), currentThreadId);
return currentThreadId;
});
auto task3 = then(task2, [](std::future<std::string>& f) {
auto currentThreadId = thread_id_string(std::this_thread::get_id());
EXPECT_NE(f.get(), currentThreadId);
return currentThreadId;
});
task3.wait();
}
#endif
{
auto task1 = std::async(std::launch::async, [] { return 1; });
auto task2 = then(task1, std::launch::async,
[](std::future<int>& f) { return f.get() + 2; });
auto task3 = then(task2, std::launch::async,
[](std::future<int>& f) { return f.get() + 3; });
// Check result received from continuation in parent task
EXPECT_EQ(task3.get(), 6);
}
{
#if USE_TIMINGS
// Get Start Time
std::chrono::system_clock::time_point start
= std::chrono::system_clock::now();
#endif
auto task1 = std::async(std::launch::async, [] {
return string_count_accumulator({"this", "is", "task1"});
});
auto task2
= then(task1, std::launch::async, [](std::future<std::size_t>& f) {
return f.get()
+ string_count_accumulator({"and", "this", "is", "task2"});
});
#if USE_TIMINGS
// Get End Time
auto end = std::chrono::system_clock::now();
auto diff
= std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
.count();
std::cout << "Total Time Taken = " << diff << " milliseconds\n";
#endif
// Check result received from continuation in parent task
EXPECT_EQ(task2.get(), 25);
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, Arvid Norberg
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 the author 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.
*/
#include "libtorrent/session.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/file.hpp"
#include <boost/bind.hpp>
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <iostream>
using namespace libtorrent;
using boost::tuples::ignore;
int const alert_mask = alert::all_categories
& ~alert::progress_notification
& ~alert::stats_notification;
struct test_config_t
{
char const* name;
bool use_ssl_ports;
bool seed_has_cert;
bool downloader_has_cert;
bool expected_to_complete;
};
test_config_t test_config[] =
{
{"nobody has a cert (connect to regular port)", false, false, false, false},
{"nobody has a cert (connect to ssl port)", true, false, false, false},
{"seed has a cert, but not downloader (connect to regular port)", false, true, false, false},
{"seed has a cert, but not downloader (connect to ssl port)", true, true, false, false},
{"downloader has a cert, but not seed (connect to regular port)", false, false, true, false},
{"downloader has a cert, but not seed (connect to ssl port)", true, false, true, false},
{"both downloader and seed has a cert (connect to regular port)", false, true, true, false},
#ifdef TORRENT_USE_OPENSSL
{"both downloader and seed has a cert (connect to ssl port)", true, true, true, true},
#else
{"both downloader and seed has a cert (connect to ssl port)", true, true, true, false},
#endif
};
int peer_disconnects = 0;
bool on_alert(alert* a)
{
if (alert_cast<peer_disconnected_alert>(a))
++peer_disconnects;
if (alert_cast<peer_error_alert>(a))
++peer_disconnects;
return false;
}
void test_ssl(int test_idx)
{
test_config_t const& test = test_config[test_idx];
fprintf(stderr, "\n%s TEST: %s\n\n", time_now_string(), test.name);
// in case the previous run was terminated
error_code ec;
remove_all("tmp1_ssl", ec);
remove_all("tmp2_ssl", ec);
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48075, 49000), "0.0.0.0", 0, alert_mask);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49075, 50000), "0.0.0.0", 0, alert_mask);
session_settings sett;
sett.ssl_listen = 1024 + rand() % 50000;
ses1.set_settings(sett);
if (!test.downloader_has_cert)
// this disables outgoing SSL connections
sett.ssl_listen = 0;
else
sett.ssl_listen += 10;
ses2.set_settings(sett);
torrent_handle tor1;
torrent_handle tor2;
create_directory("tmp1_ssl", ec);
std::ofstream file("tmp1_ssl/temporary");
boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false, "../ssl/root_ca_cert.pem");
file.close();
add_torrent_params addp;
addp.flags &= ~add_torrent_params::flag_paused;
addp.flags &= ~add_torrent_params::flag_auto_managed;
wait_for_listen(ses1, "ses1");
wait_for_listen(ses2, "ses1");
peer_disconnects = 0;
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0
, true, false, true, "_ssl", 16 * 1024, &t, false, NULL, true, test.use_ssl_ports);
if (test.seed_has_cert)
{
tor1.set_ssl_certificate(
combine_path("..", combine_path("ssl", "peer_certificate.pem"))
, combine_path("..", combine_path("ssl", "peer_private_key.pem"))
, combine_path("..", combine_path("ssl", "dhparams.pem"))
, "test");
}
if (test.downloader_has_cert)
{
tor2.set_ssl_certificate(
combine_path("..", combine_path("ssl", "peer_certificate.pem"))
, combine_path("..", combine_path("ssl", "peer_private_key.pem"))
, combine_path("..", combine_path("ssl", "dhparams.pem"))
, "test");
}
for (int i = 0; i < 15; ++i)
{
print_alerts(ses1, "ses1", true, true, true, &on_alert);
print_alerts(ses2, "ses2", true, true, true, &on_alert);
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
if (i % 10 == 0)
{
std::cerr << time_now_string() << " "
<< "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s "
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st1.progress * 100) << "% "
<< st1.num_peers
<< ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers
<< " cc: " << st2.connect_candidates
<< std::endl;
}
if (peer_disconnects >= 2) break;
if (st2.is_finished) break;
if (st2.state != torrent_status::downloading)
{
static char const* state_str[] =
{"checking (q)", "checking", "dl metadata"
, "downloading", "finished", "seeding", "allocating", "checking (r)"};
std::cerr << "st2 state: " << state_str[st2.state] << std::endl;
}
TEST_CHECK(st1.state == torrent_status::seeding
|| st1.state == torrent_status::checking_files);
TEST_CHECK(st2.state == torrent_status::downloading
|| st2.state == torrent_status::checking_resume_data);
test_sleep(100);
}
fprintf(stderr, "%s: EXPECT: %s\n", time_now_string(), test.expected_to_complete ? "SUCCEESS" : "FAILURE");
fprintf(stderr, "%s: RESULT: %s\n", time_now_string(), tor2.status().is_seeding ? "SUCCEESS" : "FAILURE");
TEST_CHECK(tor2.status().is_seeding == test.expected_to_complete);
}
int test_main()
{
using namespace libtorrent;
for (int i = 0; i < sizeof(test_config)/sizeof(test_config[0]); ++i)
test_ssl(i);
error_code ec;
remove_all("tmp1_ssl", ec);
remove_all("tmp2_ssl", ec);
return 0;
}
<commit_msg>relax requirement of test_ssl to allow for longer handshake time<commit_after>/*
Copyright (c) 2013, Arvid Norberg
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 the author 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.
*/
#include "libtorrent/session.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/file.hpp"
#include <boost/bind.hpp>
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <iostream>
using namespace libtorrent;
using boost::tuples::ignore;
int const alert_mask = alert::all_categories
& ~alert::progress_notification
& ~alert::stats_notification;
struct test_config_t
{
char const* name;
bool use_ssl_ports;
bool seed_has_cert;
bool downloader_has_cert;
bool expected_to_complete;
};
test_config_t test_config[] =
{
{"nobody has a cert (connect to regular port)", false, false, false, false},
{"nobody has a cert (connect to ssl port)", true, false, false, false},
{"seed has a cert, but not downloader (connect to regular port)", false, true, false, false},
{"seed has a cert, but not downloader (connect to ssl port)", true, true, false, false},
{"downloader has a cert, but not seed (connect to regular port)", false, false, true, false},
{"downloader has a cert, but not seed (connect to ssl port)", true, false, true, false},
{"both downloader and seed has a cert (connect to regular port)", false, true, true, false},
#ifdef TORRENT_USE_OPENSSL
{"both downloader and seed has a cert (connect to ssl port)", true, true, true, true},
#else
{"both downloader and seed has a cert (connect to ssl port)", true, true, true, false},
#endif
};
int peer_disconnects = 0;
bool on_alert(alert* a)
{
if (alert_cast<peer_disconnected_alert>(a))
++peer_disconnects;
if (alert_cast<peer_error_alert>(a))
++peer_disconnects;
return false;
}
void test_ssl(int test_idx)
{
test_config_t const& test = test_config[test_idx];
fprintf(stderr, "\n%s TEST: %s\n\n", time_now_string(), test.name);
// in case the previous run was terminated
error_code ec;
remove_all("tmp1_ssl", ec);
remove_all("tmp2_ssl", ec);
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48075, 49000), "0.0.0.0", 0, alert_mask);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49075, 50000), "0.0.0.0", 0, alert_mask);
session_settings sett;
sett.ssl_listen = 1024 + rand() % 50000;
ses1.set_settings(sett);
if (!test.downloader_has_cert)
// this disables outgoing SSL connections
sett.ssl_listen = 0;
else
sett.ssl_listen += 10;
ses2.set_settings(sett);
torrent_handle tor1;
torrent_handle tor2;
create_directory("tmp1_ssl", ec);
std::ofstream file("tmp1_ssl/temporary");
boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false, "../ssl/root_ca_cert.pem");
file.close();
add_torrent_params addp;
addp.flags &= ~add_torrent_params::flag_paused;
addp.flags &= ~add_torrent_params::flag_auto_managed;
wait_for_listen(ses1, "ses1");
wait_for_listen(ses2, "ses1");
peer_disconnects = 0;
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0
, true, false, true, "_ssl", 16 * 1024, &t, false, NULL, true, test.use_ssl_ports);
if (test.seed_has_cert)
{
tor1.set_ssl_certificate(
combine_path("..", combine_path("ssl", "peer_certificate.pem"))
, combine_path("..", combine_path("ssl", "peer_private_key.pem"))
, combine_path("..", combine_path("ssl", "dhparams.pem"))
, "test");
}
if (test.downloader_has_cert)
{
tor2.set_ssl_certificate(
combine_path("..", combine_path("ssl", "peer_certificate.pem"))
, combine_path("..", combine_path("ssl", "peer_private_key.pem"))
, combine_path("..", combine_path("ssl", "dhparams.pem"))
, "test");
}
for (int i = 0; i < 40; ++i)
{
print_alerts(ses1, "ses1", true, true, true, &on_alert);
print_alerts(ses2, "ses2", true, true, true, &on_alert);
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
if (i % 10 == 0)
{
std::cerr << time_now_string() << " "
<< "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s "
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st1.progress * 100) << "% "
<< st1.num_peers
<< ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers
<< " cc: " << st2.connect_candidates
<< std::endl;
}
if (peer_disconnects >= 2) break;
if (st2.is_finished) break;
if (st2.state != torrent_status::downloading)
{
static char const* state_str[] =
{"checking (q)", "checking", "dl metadata"
, "downloading", "finished", "seeding", "allocating", "checking (r)"};
std::cerr << "st2 state: " << state_str[st2.state] << std::endl;
}
TEST_CHECK(st1.state == torrent_status::seeding
|| st1.state == torrent_status::checking_files);
TEST_CHECK(st2.state == torrent_status::downloading
|| st2.state == torrent_status::checking_resume_data);
test_sleep(100);
}
fprintf(stderr, "%s: EXPECT: %s\n", time_now_string(), test.expected_to_complete ? "SUCCEESS" : "FAILURE");
fprintf(stderr, "%s: RESULT: %s\n", time_now_string(), tor2.status().is_seeding ? "SUCCEESS" : "FAILURE");
TEST_CHECK(tor2.status().is_seeding == test.expected_to_complete);
}
int test_main()
{
using namespace libtorrent;
for (int i = 0; i < sizeof(test_config)/sizeof(test_config[0]); ++i)
test_ssl(i);
error_code ec;
remove_all("tmp1_ssl", ec);
remove_all("tmp2_ssl", ec);
return 0;
}
<|endoftext|>
|
<commit_before>#include "testutil.hpp"
#include <apollo/stack_balance.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_monitor.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <exception> // std::terminate()
#include <iostream> // std::cerr
// See http://stackoverflow.com/a/5402543/2128694 for boost::exception support
inline void translateBoostException(const boost::exception &e)
{
BOOST_FAIL(boost::diagnostic_information(e));
}
struct boost_exception_fixture
{
boost_exception_fixture()
{
boost::unit_test::unit_test_monitor.register_exception_translator<
boost::exception>(&translateBoostException);
}
};
BOOST_GLOBAL_FIXTURE(boost_exception_fixture)
lstate_fixture::lstate_fixture()
{
L = luaL_newstate();
BOOST_REQUIRE(L);
}
lstate_fixture::~lstate_fixture()
{
BOOST_CHECK_EQUAL(lua_gettop(L), 0);
lua_close(L);
}
void check_dostring(lua_State* L, char const* s)
{
if (luaL_dostring(L, s)) {
BOOST_ERROR(lua_tostring(L, -1));
lua_pop(L, 1);
}
}
void require_dostring(lua_State* L, char const* s)
{
apollo::stack_balance balance(L);
if (luaL_dostring(L, s))
BOOST_FAIL(lua_tostring(L, -1));
}
<commit_msg>testutil: Style.<commit_after>#include "testutil.hpp"
#include <apollo/stack_balance.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_monitor.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <exception> // std::terminate()
#include <iostream> // std::cerr
// See http://stackoverflow.com/a/5402543/2128694 for boost::exception support
namespace {
inline void translateBoostException(const boost::exception &e)
{
BOOST_FAIL(boost::diagnostic_information(e));
}
struct boost_exception_fixture {
boost_exception_fixture()
{
boost::unit_test::unit_test_monitor.register_exception_translator<
boost::exception>(&translateBoostException);
}
};
BOOST_GLOBAL_FIXTURE(boost_exception_fixture)
} // anonymous namespace
lstate_fixture::lstate_fixture()
{
L = luaL_newstate();
BOOST_REQUIRE(L);
}
lstate_fixture::~lstate_fixture()
{
BOOST_CHECK_EQUAL(lua_gettop(L), 0);
lua_close(L);
}
void check_dostring(lua_State* L, char const* s)
{
if (luaL_dostring(L, s)) {
BOOST_ERROR(lua_tostring(L, -1));
lua_pop(L, 1);
}
}
void require_dostring(lua_State* L, char const* s)
{
apollo::stack_balance balance(L);
if (luaL_dostring(L, s))
BOOST_FAIL(lua_tostring(L, -1));
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "catch.hpp"
#define DLL_SVM_SUPPORT
#include "dll/dyn_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/binarize_layer.hpp"
#include "dll/stochastic_gradient_descent.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE( "unit/dbn/mnist/1", "[dbn][unit]" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 125, dll::momentum, dll::batch_size<10>, dll::init_weights>::rbm_t,
dll::rbm_desc<125, 250, dll::momentum, dll::batch_size<10>>::rbm_t,
dll::rbm_desc<250, 10, dll::momentum, dll::batch_size<10>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<10>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
REQUIRE(test_error < 0.2);
}
TEST_CASE( "unit/dbn/mnist/2", "[dbn][unit]" ) {
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
typedef dll::dbn_desc<
dll::dbn_label_layers<
dll::rbm_desc<28 * 28, 200, dll::batch_size<50>, dll::init_weights, dll::momentum>::rbm_t,
dll::rbm_desc<200, 300, dll::batch_size<50>, dll::momentum>::rbm_t,
dll::rbm_desc<310, 500, dll::batch_size<50>, dll::momentum>::rbm_t>
, dll::batch_size<10>
>::dbn_t dbn_simple_t;
auto dbn = std::make_unique<dbn_simple_t>();
dbn->train_with_labels(dataset.training_images, dataset.training_labels, 10, 10);
auto error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::label_predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(error < 0.3);
}
TEST_CASE( "unit/dbn/mnist/3", "[dbn][unit]" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<20>, dll::visible<dll::unit_type::GAUSSIAN>>::rbm_t,
dll::rbm_desc<200, 350, dll::momentum, dll::batch_size<20>>::rbm_t,
dll::rbm_desc<350, 10, dll::momentum, dll::batch_size<20>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<10>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::deque, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::normalize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE( "unit/dbn/mnist/4", "[dbn][cg][unit]" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 150, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<150, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::memory
, dll::batch_size<25>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(
dataset.training_images.begin(), dataset.training_images.end(),
dataset.training_labels.begin(), dataset.training_labels.end(),
5);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
REQUIRE(test_error < 0.25);
//Mostly here to ensure compilation
auto out = dbn->prepare_one_output<std::vector<double>>();
REQUIRE(out.size() > 0);
}
TEST_CASE( "unit/dbn/mnist/5", "[dbn][sgd][unit]" ) {
using dbn_t = dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 150, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<150, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::trainer<dll::sgd_trainer>
, dll::momentum
, dll::batch_size<25>
>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50);
std::cout << "ft_error:" << error << std::endl;
REQUIRE(error < 1e-1);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(test_error < 0.3);
}
TEST_CASE( "unit/dbn/mnist/6", "[dbn][dyn][unit]" ) {
using dbn_t =
dll::dbn_desc<
dll::dbn_layers<
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t,
dll::dyn_rbm_desc<dll::momentum>::rbm_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<25>
>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>(
std::make_tuple(28*28,100),
std::make_tuple(100,200),
std::make_tuple(200,10));
dbn->pretrain(dataset.training_images, 20);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 1.0);
}
TEST_CASE( "unit/dbn/mnist/7", "[dbn][svm][unit]" ) {
using dbn_t = dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t>
, dll::batch_size<25>
>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
REQUIRE(result);
auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE( "unit/dbn/mnist/8", "[dbn][unit]" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::binarize_layer_desc<30>::layer_t,
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<25>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
}
<commit_msg>Stabilize the test<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "catch.hpp"
#define DLL_SVM_SUPPORT
#include "dll/dyn_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/binarize_layer.hpp"
#include "dll/stochastic_gradient_descent.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE( "unit/dbn/mnist/1", "[dbn][unit]" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 150, dll::momentum, dll::batch_size<10>, dll::init_weights>::rbm_t,
dll::rbm_desc<150, 250, dll::momentum, dll::batch_size<10>>::rbm_t,
dll::rbm_desc<250, 10, dll::momentum, dll::batch_size<10>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<10>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(400);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
std::cout << "error:" << error << std::endl;
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE( "unit/dbn/mnist/2", "[dbn][unit]" ) {
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
typedef dll::dbn_desc<
dll::dbn_label_layers<
dll::rbm_desc<28 * 28, 200, dll::batch_size<50>, dll::init_weights, dll::momentum>::rbm_t,
dll::rbm_desc<200, 300, dll::batch_size<50>, dll::momentum>::rbm_t,
dll::rbm_desc<310, 500, dll::batch_size<50>, dll::momentum>::rbm_t>
, dll::batch_size<10>
>::dbn_t dbn_simple_t;
auto dbn = std::make_unique<dbn_simple_t>();
dbn->train_with_labels(dataset.training_images, dataset.training_labels, 10, 10);
auto error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::label_predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(error < 0.3);
}
TEST_CASE( "unit/dbn/mnist/3", "[dbn][unit]" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<20>, dll::visible<dll::unit_type::GAUSSIAN>>::rbm_t,
dll::rbm_desc<200, 350, dll::momentum, dll::batch_size<20>>::rbm_t,
dll::rbm_desc<350, 10, dll::momentum, dll::batch_size<20>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<10>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::deque, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::normalize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE( "unit/dbn/mnist/4", "[dbn][cg][unit]" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 150, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<150, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::memory
, dll::batch_size<25>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(
dataset.training_images.begin(), dataset.training_images.end(),
dataset.training_labels.begin(), dataset.training_labels.end(),
5);
REQUIRE(error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
REQUIRE(test_error < 0.25);
//Mostly here to ensure compilation
auto out = dbn->prepare_one_output<std::vector<double>>();
REQUIRE(out.size() > 0);
}
TEST_CASE( "unit/dbn/mnist/5", "[dbn][sgd][unit]" ) {
using dbn_t = dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 150, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<150, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::trainer<dll::sgd_trainer>
, dll::momentum
, dll::batch_size<25>
>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50);
std::cout << "ft_error:" << error << std::endl;
REQUIRE(error < 1e-1);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(test_error < 0.3);
}
TEST_CASE( "unit/dbn/mnist/6", "[dbn][dyn][unit]" ) {
using dbn_t =
dll::dbn_desc<
dll::dbn_layers<
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t,
dll::dyn_rbm_desc<dll::momentum>::rbm_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<25>
>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>(
std::make_tuple(28*28,100),
std::make_tuple(100,200),
std::make_tuple(200,10));
dbn->pretrain(dataset.training_images, 20);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 1.0);
}
TEST_CASE( "unit/dbn/mnist/7", "[dbn][svm][unit]" ) {
using dbn_t = dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t>
, dll::batch_size<25>
>::dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
REQUIRE(result);
auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
TEST_CASE( "unit/dbn/mnist/8", "[dbn][unit]" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::binarize_layer_desc<30>::layer_t,
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<25>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset<std::vector, std::vector, double>(250);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
}
<|endoftext|>
|
<commit_before>#include <QCommandLineParser>
#include "../DataLayer/DataContainer.h"
#include "../CommunicationLayer/CommunicationContainer.h"
#include "../BusinessLayer/BusinessContainer.h"
#include "../PresenterLayer/PresenterContainer.h"
#include "../ViewLayer/ViewContainer.h"
#include "../InfrastructureLayer/InfrastructureContainer.h"
#include "EpsilonDashboard.h"
#include "../ViewLayer/FontLoader/FontLoader.h"
#include <QString>
namespace
{
const char* RACE_QUEUE = "raceQueue";
const char* DISPLAY_QUEUE = "displayQueue";
const char* DEBUG_QUEUE = "debugQueue";
}
EpsilonDashboard::EpsilonDashboard(int& argc, char** argv)
: QApplication(argc, argv)
, infrastructureContainer_(new InfrastructureContainer())
, dataContainer_(new DataContainer())
, businessContainer_(new BusinessContainer(*dataContainer_))
, presenterContainer_(new PresenterContainer(*dataContainer_))
, fontLoader_(new FontLoader)
{
QCommandLineParser parser;
QCommandLineOption raceModeOption("r");
QCommandLineOption debugModeOption("d");
parser.addOption(raceModeOption);
parser.addOption(debugModeOption);
parser.process(*this);
Mode mode = Mode::DISPLAY;
if (parser.isSet(raceModeOption))
{
mode = Mode::RACE;
infrastructureContainer_->setQueueName(RACE_QUEUE);
}
else if (parser.isSet(debugModeOption))
{
mode = Mode::DEBUG;
infrastructureContainer_->setQueueName(DEBUG_QUEUE);
}
else
{
infrastructureContainer_->setQueueName(DISPLAY_QUEUE);
}
Q_INIT_RESOURCE(fontresources);
QApplication::setFont(fontLoader_->loadFont(Font::BURLINGAME));
viewContainer_.reset(new ViewContainer(*presenterContainer_, mode));
communicationContainer_.reset(new CommunicationContainer(*businessContainer_, *infrastructureContainer_));
}
EpsilonDashboard::~EpsilonDashboard()
{
}
<commit_msg>Astyle<commit_after>#include <QCommandLineParser>
#include "../DataLayer/DataContainer.h"
#include "../CommunicationLayer/CommunicationContainer.h"
#include "../BusinessLayer/BusinessContainer.h"
#include "../PresenterLayer/PresenterContainer.h"
#include "../ViewLayer/ViewContainer.h"
#include "../InfrastructureLayer/InfrastructureContainer.h"
#include "EpsilonDashboard.h"
#include "../ViewLayer/FontLoader/FontLoader.h"
#include <QString>
namespace
{
const char* RACE_QUEUE = "raceQueue";
const char* DISPLAY_QUEUE = "displayQueue";
const char* DEBUG_QUEUE = "debugQueue";
}
EpsilonDashboard::EpsilonDashboard(int& argc, char** argv)
: QApplication(argc, argv)
, infrastructureContainer_(new InfrastructureContainer())
, dataContainer_(new DataContainer())
, businessContainer_(new BusinessContainer(*dataContainer_))
, presenterContainer_(new PresenterContainer(*dataContainer_))
, fontLoader_(new FontLoader)
{
QCommandLineParser parser;
QCommandLineOption raceModeOption("r");
QCommandLineOption debugModeOption("d");
parser.addOption(raceModeOption);
parser.addOption(debugModeOption);
parser.process(*this);
Mode mode = Mode::DISPLAY;
if (parser.isSet(raceModeOption))
{
mode = Mode::RACE;
infrastructureContainer_->setQueueName(RACE_QUEUE);
}
else if (parser.isSet(debugModeOption))
{
mode = Mode::DEBUG;
infrastructureContainer_->setQueueName(DEBUG_QUEUE);
}
else
{
infrastructureContainer_->setQueueName(DISPLAY_QUEUE);
}
Q_INIT_RESOURCE(fontresources);
QApplication::setFont(fontLoader_->loadFont(Font::BURLINGAME));
viewContainer_.reset(new ViewContainer(*presenterContainer_, mode));
communicationContainer_.reset(new CommunicationContainer(*businessContainer_, *infrastructureContainer_));
}
EpsilonDashboard::~EpsilonDashboard()
{
}
<|endoftext|>
|
<commit_before>/* Rapicorn Tests
* Copyright (C) 2008 Tim Janik
*
* 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.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#include <rapicorn/rapicorn.hh>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
namespace {
using namespace Rapicorn;
static void
fill_store (Store1 &s1)
{
String dirname = ".";
DIR *d = opendir (dirname.c_str());
s1.clear();
if (!d)
{
warning ("failed to access directory: %s: %s", dirname.c_str(), strerror (errno));
return;
}
struct dirent *e = readdir (d);
while (e)
{
Array row;
uint n = 0;
row[n++] = e->d_ino;
row[n++] = " - ";
row[n++] = e->d_type;
row[n++] = " - ";
row[n++] = e->d_name;
s1.insert (-1, row);
e = readdir (d);
}
closedir (d);
}
static Store1*
create_store ()
{
Store1 *s1 = Store1::create_memory_store (Type::lookup ("String"));
fill_store (*s1);
return s1;
}
extern "C" int
main (int argc,
char *argv[])
{
/* initialize Rapicorn for X11 */
Application::init_with_x11 (&argc, &argv, "FileView");
/* initialization acquired global Rapicorn mutex */
/* load GUI definition file, relative to argv[0] */
Application::auto_load ("RapicornTest", "fileview.xml", argv[0]);
/* create root item */
Store1 *s1 = create_store();
Window window = Application::create_window ("main-dialog",
Args (""),
Args ("ListModel=" + s1->model().object_url()));
window.show();
Application::execute_loops();
return 0;
}
} // anon
<commit_msg>fileview.cc: use vertical column separators<commit_after>/* Rapicorn Tests
* Copyright (C) 2008 Tim Janik
*
* 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.
*
* A copy of the GNU Lesser General Public License should ship along
* with this library; if not, see http://www.gnu.org/copyleft/.
*/
#include <rapicorn/rapicorn.hh>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
namespace {
using namespace Rapicorn;
static void
fill_store (Store1 &s1)
{
String dirname = ".";
DIR *d = opendir (dirname.c_str());
s1.clear();
if (!d)
{
warning ("failed to access directory: %s: %s", dirname.c_str(), strerror (errno));
return;
}
struct dirent *e = readdir (d);
while (e)
{
Array row;
uint n = 0;
row[n++] = e->d_ino;
row[n++] = " | ";
row[n++] = e->d_type;
row[n++] = " | ";
row[n++] = e->d_name;
s1.insert (-1, row);
e = readdir (d);
}
closedir (d);
}
static Store1*
create_store ()
{
Store1 *s1 = Store1::create_memory_store (Type::lookup ("String"));
fill_store (*s1);
return s1;
}
extern "C" int
main (int argc,
char *argv[])
{
/* initialize Rapicorn for X11 */
Application::init_with_x11 (&argc, &argv, "FileView");
/* initialization acquired global Rapicorn mutex */
/* load GUI definition file, relative to argv[0] */
Application::auto_load ("RapicornTest", "fileview.xml", argv[0]);
/* create root item */
Store1 *s1 = create_store();
Window window = Application::create_window ("main-dialog",
Args (""),
Args ("ListModel=" + s1->model().object_url()));
window.show();
Application::execute_loops();
return 0;
}
} // anon
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680)
#define XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XercesPlatformSupport/XercesPlatformSupportDefinitions.hpp>
#include <cstdio>
#include <vector>
// Base class header file.
#include <PlatformSupport/TextOutputStream.hpp>
#include <XercesPlatformSupport/XercesPlatformSupportException.hpp>
// A base class for all text output streams.
class XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStream : public TextOutputStream
{
public :
virtual
~XercesTextOutputStream();
// These interfaces are inherited from TextOutputStream...
virtual void
flush();
virtual void
write(char theChar);
virtual void
write(XalanDOMChar theChar);
virtual void
write(const char* theBuffer);
virtual void
write(const XalanDOMChar* theBuffer);
virtual void
write(
const char* theBuffer,
unsigned long theBufferLength);
virtual void
write(
const XalanDOMChar* theBuffer,
unsigned long theBufferLength);
enum
{
eDefaultBufferSize = 512
};
typedef std::vector<XalanDOMChar> BufferType;
virtual void
setBufferSize(BufferType::size_type theBufferSize);
protected:
explicit
XercesTextOutputStream(BufferType::size_type theBufferSize = eDefaultBufferSize);
virtual void
writeData(const char* theBuffer,
unsigned long theBufferLength) = 0;
virtual void
doFlush() = 0;
private:
// These are not implemented...
XercesTextOutputStream(const XercesTextOutputStream&);
XercesTextOutputStream&
operator=(const XercesTextOutputStream&);
// Utility functions...
void
flushBuffer();
void
doWrite(const XalanDOMChar* theBuffer);
BufferType m_buffer;
BufferType::size_type m_bufferSize;
};
class XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStreamException : public XercesPlatformSupportException
{
public:
virtual
~XercesTextOutputStreamException();
protected:
XercesTextOutputStreamException(
const DOMString& theMessage,
const DOMString& theType);
};
#endif // TEXTFILEOUTPUTSTREAM_HEADER_GUARD_1357924680
<commit_msg>Added comment.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680)
#define XERCESTEXTOUTPUTSTREAM_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XercesPlatformSupport/XercesPlatformSupportDefinitions.hpp>
#include <cstdio>
#include <vector>
// Base class header file.
#include <PlatformSupport/TextOutputStream.hpp>
#include <XercesPlatformSupport/XercesPlatformSupportException.hpp>
// A base class for all text output streams.
class XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStream : public TextOutputStream
{
public :
virtual
~XercesTextOutputStream();
// These interfaces are inherited from TextOutputStream...
virtual void
flush();
virtual void
write(char theChar);
virtual void
write(XalanDOMChar theChar);
virtual void
write(const char* theBuffer);
virtual void
write(const XalanDOMChar* theBuffer);
virtual void
write(
const char* theBuffer,
unsigned long theBufferLength);
virtual void
write(
const XalanDOMChar* theBuffer,
unsigned long theBufferLength);
enum
{
eDefaultBufferSize = 512
};
typedef std::vector<XalanDOMChar> BufferType;
virtual void
setBufferSize(BufferType::size_type theBufferSize);
protected:
/**
* Constructor.
*
* @param theBufferSize The initial size of the buffer.
*/
explicit
XercesTextOutputStream(BufferType::size_type theBufferSize = eDefaultBufferSize);
virtual void
writeData(const char* theBuffer,
unsigned long theBufferLength) = 0;
virtual void
doFlush() = 0;
private:
// These are not implemented...
XercesTextOutputStream(const XercesTextOutputStream&);
XercesTextOutputStream&
operator=(const XercesTextOutputStream&);
// Utility functions...
void
flushBuffer();
void
doWrite(const XalanDOMChar* theBuffer);
BufferType m_buffer;
BufferType::size_type m_bufferSize;
};
class XALAN_XERCESPLATFORMSUPPORT_EXPORT XercesTextOutputStreamException : public XercesPlatformSupportException
{
public:
virtual
~XercesTextOutputStreamException();
protected:
XercesTextOutputStreamException(
const DOMString& theMessage,
const DOMString& theType);
};
#endif // TEXTFILEOUTPUTSTREAM_HEADER_GUARD_1357924680
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2016 ScyllaDB
*/
#include "loopback_socket.hh"
#include "rpc/rpc.hh"
#include "test-utils.hh"
#include "core/thread.hh"
struct serializer {
};
template <typename T, typename Output>
inline
void write_arithmetic_type(Output& out, T v) {
static_assert(std::is_arithmetic<T>::value, "must be arithmetic type");
return out.write(reinterpret_cast<const char*>(&v), sizeof(T));
}
template <typename T, typename Input>
inline
T read_arithmetic_type(Input& in) {
static_assert(std::is_arithmetic<T>::value, "must be arithmetic type");
T v;
in.read(reinterpret_cast<char*>(&v), sizeof(T));
return v;
}
template <typename Output>
inline void write(serializer, Output& output, int32_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, uint32_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, int64_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, uint64_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, double v) { return write_arithmetic_type(output, v); }
template <typename Input>
inline int32_t read(serializer, Input& input, rpc::type<int32_t>) { return read_arithmetic_type<int32_t>(input); }
template <typename Input>
inline uint32_t read(serializer, Input& input, rpc::type<uint32_t>) { return read_arithmetic_type<uint32_t>(input); }
template <typename Input>
inline uint64_t read(serializer, Input& input, rpc::type<uint64_t>) { return read_arithmetic_type<uint64_t>(input); }
template <typename Input>
inline uint64_t read(serializer, Input& input, rpc::type<int64_t>) { return read_arithmetic_type<int64_t>(input); }
template <typename Input>
inline double read(serializer, Input& input, rpc::type<double>) { return read_arithmetic_type<double>(input); }
template <typename Output>
inline void write(serializer, Output& out, const sstring& v) {
write_arithmetic_type(out, uint32_t(v.size()));
out.write(v.c_str(), v.size());
}
template <typename Input>
inline sstring read(serializer, Input& in, rpc::type<sstring>) {
auto size = read_arithmetic_type<uint32_t>(in);
sstring ret(sstring::initialized_later(), size);
in.read(ret.begin(), size);
return ret;
}
using test_rpc_proto = rpc::protocol<serializer>;
using connect_fn = std::function<test_rpc_proto::client (ipv4_addr addr)>;
future<>
with_rpc_env(rpc::resource_limits resource_limits,
std::function<future<> (test_rpc_proto& proto, test_rpc_proto::server& server, connect_fn connect)> test_fn) {
struct state {
test_rpc_proto proto{serializer()};
loopback_connection_factory lcf;
std::unique_ptr<test_rpc_proto::server> server;
};
return do_with(state(), [=] (state& s) {
s.server = std::make_unique<test_rpc_proto::server>(s.proto, s.lcf.get_server_socket(), resource_limits);
auto make_client = [&s] (ipv4_addr addr) {
return test_rpc_proto::client(s.proto, addr, s.lcf.make_new_connection());
};
return test_fn(s.proto, *s.server, make_client);
});
}
SEASTAR_TEST_CASE(test_rpc_connect) {
return with_rpc_env({}, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {
return seastar::async([&proto, &s, connect] {
auto c1 = connect(ipv4_addr());
auto sum = proto.register_handler(1, [](int a, int b) {
return make_ready_future<int>(a+b);
});
auto result = sum(c1, 2, 3).get0();
BOOST_REQUIRE_EQUAL(result, 2 + 3);
});
});
}
<commit_msg>tests: rpc: stop client and server<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2016 ScyllaDB
*/
#include "loopback_socket.hh"
#include "rpc/rpc.hh"
#include "test-utils.hh"
#include "core/thread.hh"
struct serializer {
};
template <typename T, typename Output>
inline
void write_arithmetic_type(Output& out, T v) {
static_assert(std::is_arithmetic<T>::value, "must be arithmetic type");
return out.write(reinterpret_cast<const char*>(&v), sizeof(T));
}
template <typename T, typename Input>
inline
T read_arithmetic_type(Input& in) {
static_assert(std::is_arithmetic<T>::value, "must be arithmetic type");
T v;
in.read(reinterpret_cast<char*>(&v), sizeof(T));
return v;
}
template <typename Output>
inline void write(serializer, Output& output, int32_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, uint32_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, int64_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, uint64_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, double v) { return write_arithmetic_type(output, v); }
template <typename Input>
inline int32_t read(serializer, Input& input, rpc::type<int32_t>) { return read_arithmetic_type<int32_t>(input); }
template <typename Input>
inline uint32_t read(serializer, Input& input, rpc::type<uint32_t>) { return read_arithmetic_type<uint32_t>(input); }
template <typename Input>
inline uint64_t read(serializer, Input& input, rpc::type<uint64_t>) { return read_arithmetic_type<uint64_t>(input); }
template <typename Input>
inline uint64_t read(serializer, Input& input, rpc::type<int64_t>) { return read_arithmetic_type<int64_t>(input); }
template <typename Input>
inline double read(serializer, Input& input, rpc::type<double>) { return read_arithmetic_type<double>(input); }
template <typename Output>
inline void write(serializer, Output& out, const sstring& v) {
write_arithmetic_type(out, uint32_t(v.size()));
out.write(v.c_str(), v.size());
}
template <typename Input>
inline sstring read(serializer, Input& in, rpc::type<sstring>) {
auto size = read_arithmetic_type<uint32_t>(in);
sstring ret(sstring::initialized_later(), size);
in.read(ret.begin(), size);
return ret;
}
using test_rpc_proto = rpc::protocol<serializer>;
using connect_fn = std::function<test_rpc_proto::client (ipv4_addr addr)>;
future<>
with_rpc_env(rpc::resource_limits resource_limits,
std::function<future<> (test_rpc_proto& proto, test_rpc_proto::server& server, connect_fn connect)> test_fn) {
struct state {
test_rpc_proto proto{serializer()};
loopback_connection_factory lcf;
std::unique_ptr<test_rpc_proto::server> server;
};
return do_with(state(), [=] (state& s) {
s.server = std::make_unique<test_rpc_proto::server>(s.proto, s.lcf.get_server_socket(), resource_limits);
auto make_client = [&s] (ipv4_addr addr) {
return test_rpc_proto::client(s.proto, addr, s.lcf.make_new_connection());
};
return test_fn(s.proto, *s.server, make_client).finally([&] {
return s.server->stop();
});
});
}
SEASTAR_TEST_CASE(test_rpc_connect) {
return with_rpc_env({}, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {
return seastar::async([&proto, &s, connect] {
auto c1 = connect(ipv4_addr());
auto sum = proto.register_handler(1, [](int a, int b) {
return make_ready_future<int>(a+b);
});
auto result = sum(c1, 2, 3).get0();
BOOST_REQUIRE_EQUAL(result, 2 + 3);
c1.stop().get();
});
});
}
<|endoftext|>
|
<commit_before>/* This file is part of the Vc library. {{{
Copyright © 2014 Matthias Kretz <[email protected]>
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 names of contributing organizations 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 <COPYRIGHT HOLDER> 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.
}}}*/
#include "unittest.h"
#include "../common/simdize.h"
TEST(test_simdize)
{
using namespace std;
using namespace Vc;
using Test0 = simdize<float>;
using Test1 = simdize<tuple<float, double>>;
using Test1_0 = typename std::decay<decltype(get<0>(Test1()))>::type;
using Test1_1 = typename tuple_element<1, typename Test1::base_type>::type;
using Test2 = simdize<tuple<double, float>>;
using Test2_0 = typename tuple_element<0, typename Test2::base_type>::type;
using Test2_1 = typename tuple_element<1, typename Test2::base_type>::type;
using Test3 = simdize<tuple<std::string, float>>;
using Test3_1 = typename tuple_element<1, typename Test3::base_type>::type;
using Test4 = simdize<tuple<double, std::string, float>>;
using Test4_0 = typename tuple_element<0, typename Test4::base_type>::type;
using Test4_1 = typename tuple_element<1, typename Test4::base_type>::type;
using Test4_2 = typename tuple_element<2, typename Test4::base_type>::type;
COMPARE(Test0::Size, float_v::Size);
COMPARE(Test1_0::Size, float_v::Size);
COMPARE(Test1_1::Size, float_v::Size);
COMPARE(Test1::Size, float_v::Size);
COMPARE(Test2_0::Size, double_v::Size);
COMPARE(Test2_1::Size, double_v::Size);
COMPARE(Test2::Size, double_v::Size);
COMPARE(Test3_1::Size, float_v::Size);
COMPARE(Test3::Size, float_v::Size);
COMPARE(Test4_0::Size, double_v::Size);
COMPARE(Test4_2::Size, double_v::Size);
COMPARE(Test4::Size, double_v::Size);
COMPARE(typeid(Test4_0), typeid(double_v));
COMPARE(typeid(Test4_1), typeid(std::string));
COMPARE(typeid(Test4_2), typeid(simdize<float, double_v::Size>));
COMPARE(typeid(simdize<tuple<std::string>>), typeid(tuple<std::string>));
COMPARE(typeid(simdize<float>), typeid(float_v));
COMPARE(
typeid(Test1),
typeid(Adapter<tuple<float_v, simdize<double, float_v::Size>>, float_v::Size>));
}
TEST(simdize_bools)
{
using namespace std;
using namespace Vc;
COMPARE(typeid(simdize<bool>), typeid(float_m));
COMPARE(typeid(simdize<bool, float_m::Size>), typeid(float_m));
COMPARE(typeid(simdize<bool, 0, int>), typeid(int_m));
COMPARE(typeid(simdize<bool, int_m::Size, int>), typeid(int_m));
COMPARE(typeid(simdize<bool, float_m::Size + 1>),
typeid(simd_mask_array<float, float_m::Size + 1>));
COMPARE(typeid(simdize<bool, int_m::Size + 1, int>),
typeid(simd_mask_array<int, int_m::Size + 1>));
COMPARE(typeid(simdize<tuple<bool>>), typeid(Adapter<tuple<float_m>, float_m::Size>));
COMPARE(typeid(simdize<tuple<bool>, float_m::Size>),
typeid(Adapter<tuple<float_m>, float_m::Size>));
COMPARE(typeid(simdize<tuple<bool>, float_m::Size + 1>),
typeid(Adapter<tuple<simd_mask_array<float, float_m::Size + 1>>,
float_m::Size + 1>));
COMPARE(typeid(simdize<tuple<int, bool>>), typeid(Adapter<tuple<int_v, int_m>, int_v::Size>));
COMPARE(typeid(simdize<tuple<int, bool>, 3>),
typeid(Adapter<tuple<simdarray<int, 3>, simd_mask_array<float, 3>>, 3>));
COMPARE(typeid(simdize<tuple<bool, double, bool>>),
typeid(Adapter<tuple<float_m, simdarray<double, float_m::Size>, float_m>,
float_m::Size>));
COMPARE(typeid(simdize<tuple<bool, double, bool>, float_m::Size + 1>),
typeid(Adapter<tuple<simd_mask_array<float, float_m::Size + 1>,
simdarray<double, float_m::Size + 1>,
simd_mask_array<float, float_m::Size + 1>>,
float_m::Size + 1>));
COMPARE(typeid(simdize<tuple<bool, double, bool>, 0, double>),
typeid(Adapter<tuple<double_m, double_v, double_m>, double_m::Size>));
COMPARE(typeid(simdize<tuple<int, double, bool>, 0, double>),
typeid(Adapter<
tuple<int_v, simdize<double, int_v::Size>, simdize<bool, int_v::Size, double>>,
int_v::Size>));
}
template <typename, int...> struct Foo
{
};
TEST(nontype_template_parameters)
{
using namespace std;
using namespace Vc;
using std::array;
COMPARE(typeid(simdize<array<float, 3>>),
typeid(Adapter<array<float_v, 3>, float_v::Size>));
COMPARE(typeid(simdize<array<bool, 3>>),
typeid(Adapter<array<float_m, 3>, float_m::Size>));
COMPARE(typeid(simdize<Foo<float, 3, 5, 6>>),
typeid(Adapter<Foo<float_v, 3, 5, 6>, float_v::Size>));
}
TEST(tuple_interface)
{
using namespace Vc;
using V0 = simdize<std::tuple<int, bool>>;
COMPARE(std::tuple_size<V0>::value, 2);
COMPARE(typeid(typename std::tuple_element<0, V0>::type), typeid(int_v));
COMPARE(typeid(typename std::tuple_element<1, V0>::type), typeid(int_m));
V0 v;
COMPARE(typeid(decltype(std::get<0>(v))), typeid(int_v));
COMPARE(typeid(decltype(std::get<1>(v))), typeid(int_m));
std::get<0>(v) = int_v::IndexesFromZero();
COMPARE(std::get<0>(v), int_v::IndexesFromZero());
std::get<0>(v) += 1;
COMPARE(std::get<0>(v), int_v::IndexesFromZero() + 1);
}
// vim: foldmethod=marker
<commit_msg>simdize test: adjust for SimdizeAdapter changes<commit_after>/* This file is part of the Vc library. {{{
Copyright © 2014 Matthias Kretz <[email protected]>
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 names of contributing organizations 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 <COPYRIGHT HOLDER> 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.
}}}*/
#include "unittest.h"
#include "../common/simdize.h"
TEST(test_simdize)
{
using namespace std;
using namespace Vc;
using Test0 = simdize<float>;
using Test1 = simdize<tuple<float, double>>;
using Test1_0 = typename std::decay<decltype(get<0>(Test1()))>::type;
using Test1_1 = typename tuple_element<1, typename Test1::base_type>::type;
using Test2 = simdize<tuple<double, float>>;
using Test2_0 = typename tuple_element<0, typename Test2::base_type>::type;
using Test2_1 = typename tuple_element<1, typename Test2::base_type>::type;
using Test3 = simdize<tuple<std::string, float>>;
using Test3_1 = typename tuple_element<1, typename Test3::base_type>::type;
using Test4 = simdize<tuple<double, std::string, float>>;
using Test4_0 = typename tuple_element<0, typename Test4::base_type>::type;
using Test4_1 = typename tuple_element<1, typename Test4::base_type>::type;
using Test4_2 = typename tuple_element<2, typename Test4::base_type>::type;
COMPARE(Test0::Size, float_v::Size);
COMPARE(Test1_0::Size, float_v::Size);
COMPARE(Test1_1::Size, float_v::Size);
COMPARE(Test1::Size, float_v::Size);
COMPARE(Test2_0::Size, double_v::Size);
COMPARE(Test2_1::Size, double_v::Size);
COMPARE(Test2::Size, double_v::Size);
COMPARE(Test3_1::Size, float_v::Size);
COMPARE(Test3::Size, float_v::Size);
COMPARE(Test4_0::Size, double_v::Size);
COMPARE(Test4_2::Size, double_v::Size);
COMPARE(Test4::Size, double_v::Size);
COMPARE(typeid(Test4_0), typeid(double_v));
COMPARE(typeid(Test4_1), typeid(std::string));
COMPARE(typeid(Test4_2), typeid(simdize<float, double_v::Size>));
COMPARE(typeid(simdize<tuple<std::string>>), typeid(tuple<std::string>));
COMPARE(typeid(simdize<float>), typeid(float_v));
COMPARE(typeid(Test1),
typeid(SimdizeAdapter<tuple<float, double>,
tuple<float_v, simdize<double, float_v::Size>>,
float_v::Size>));
}
TEST(simdize_bools)
{
using namespace std;
using namespace Vc;
COMPARE(typeid(simdize<bool>), typeid(float_m));
COMPARE(typeid(simdize<bool, float_m::Size>), typeid(float_m));
COMPARE(typeid(simdize<bool, 0, int>), typeid(int_m));
COMPARE(typeid(simdize<bool, int_m::Size, int>), typeid(int_m));
COMPARE(typeid(simdize<bool, float_m::Size + 1>),
typeid(simd_mask_array<float, float_m::Size + 1>));
COMPARE(typeid(simdize<bool, int_m::Size + 1, int>),
typeid(simd_mask_array<int, int_m::Size + 1>));
COMPARE(typeid(simdize<tuple<bool>>),
typeid(SimdizeAdapter<tuple<bool>, tuple<float_m>, float_m::Size>));
COMPARE(typeid(simdize<tuple<bool>, float_m::Size>),
typeid(SimdizeAdapter<tuple<bool>, tuple<float_m>, float_m::Size>));
COMPARE(
typeid(simdize<tuple<bool>, float_m::Size + 1>),
typeid(
SimdizeAdapter<tuple<bool>, tuple<simd_mask_array<float, float_m::Size + 1>>,
float_m::Size + 1>));
COMPARE(typeid(simdize<tuple<int, bool>>),
typeid(SimdizeAdapter<tuple<int, bool>, tuple<int_v, int_m>, int_v::Size>));
COMPARE(
typeid(simdize<tuple<int, bool>, 3>),
typeid(SimdizeAdapter<tuple<int, bool>,
tuple<simdarray<int, 3>, simd_mask_array<float, 3>>, 3>));
COMPARE(
typeid(simdize<tuple<bool, double, bool>>),
typeid(SimdizeAdapter<tuple<bool, double, bool>,
tuple<float_m, simdarray<double, float_m::Size>, float_m>,
float_m::Size>));
COMPARE(typeid(simdize<tuple<bool, double, bool>, float_m::Size + 1>),
typeid(SimdizeAdapter<tuple<bool, double, bool>,
tuple<simd_mask_array<float, float_m::Size + 1>,
simdarray<double, float_m::Size + 1>,
simd_mask_array<float, float_m::Size + 1>>,
float_m::Size + 1>));
COMPARE(typeid(simdize<tuple<bool, double, bool>, 0, double>),
typeid(SimdizeAdapter<tuple<bool, double, bool>,
tuple<double_m, double_v, double_m>, double_m::Size>));
COMPARE(typeid(simdize<tuple<int, double, bool>, 0, double>),
typeid(SimdizeAdapter<tuple<int, double, bool>,
tuple<int_v, simdize<double, int_v::Size>,
simdize<bool, int_v::Size, double>>,
int_v::Size>));
}
template <typename, int...> struct Foo
{
};
TEST(nontype_template_parameters)
{
using namespace std;
using namespace Vc;
using std::array;
COMPARE(typeid(simdize<array<float, 3>>),
typeid(SimdizeAdapter<array<float, 3>, array<float_v, 3>, float_v::Size>));
COMPARE(typeid(simdize<array<bool, 3>>),
typeid(SimdizeAdapter<array<bool, 3>, array<float_m, 3>, float_m::Size>));
COMPARE(
typeid(simdize<Foo<float, 3, 5, 6>>),
typeid(
SimdizeAdapter<Foo<float, 3, 5, 6>, Foo<float_v, 3, 5, 6>, float_v::Size>));
}
TEST(tuple_interface)
{
using namespace Vc;
using V0 = simdize<std::tuple<int, bool>>;
COMPARE(std::tuple_size<V0>::value, 2u);
COMPARE(typeid(typename std::tuple_element<0, V0>::type), typeid(int_v));
COMPARE(typeid(typename std::tuple_element<1, V0>::type), typeid(int_m));
V0 v;
COMPARE(typeid(decltype(std::get<0>(v))), typeid(int_v));
COMPARE(typeid(decltype(std::get<1>(v))), typeid(int_m));
std::get<0>(v) = int_v::IndexesFromZero();
COMPARE(std::get<0>(v), int_v::IndexesFromZero());
std::get<0>(v) += 1;
COMPARE(std::get<0>(v), int_v::IndexesFromZero() + 1);
}
// vim: foldmethod=marker
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Common_inl_
#define _Stroika_Foundation_Containers_Common_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <algorithm>
#include "../Math/Common.h"
namespace Stroika::Foundation::Containers {
/*
********************************************************************************
************************************* Start ************************************
********************************************************************************
*/
template <typename CONTAINER>
inline typename CONTAINER::value_type* Start (CONTAINER& c)
{
size_t cnt = c.size ();
return cnt == 0 ? nullptr : &c[0];
}
template <typename CONTAINER>
inline const typename CONTAINER::value_type* Start (const CONTAINER& c)
{
size_t cnt = c.size ();
return cnt == 0 ? nullptr : &c[0];
}
/*
********************************************************************************
************************************* End **************************************
********************************************************************************
*/
template <typename CONTAINER>
inline typename CONTAINER::value_type* End (CONTAINER& c)
{
size_t cnt = c.size ();
return cnt == 0 ? nullptr : &c[0] + cnt;
}
template <typename CONTAINER>
inline const typename CONTAINER::value_type* End (const CONTAINER& c)
{
size_t cnt = c.size ();
return cnt == 0 ? nullptr : &c[0] + cnt;
}
/*
********************************************************************************
****************************** CompareResultNormalizeHelper ********************
********************************************************************************
*/
template <typename FROM_INT_TYPE, typename TO_INT_TYPE>
inline TO_INT_TYPE CompareResultNormalizeHelper (FROM_INT_TYPE f)
{
if (f < 0) {
return static_cast<TO_INT_TYPE> (-1);
}
else if (f > 0) {
return static_cast<TO_INT_TYPE> (1);
}
else {
return static_cast<TO_INT_TYPE> (0);
}
}
/*
********************************************************************************
*************************** ReserveSpeedTweekAdjustCapacity ********************
********************************************************************************
*/
inline size_t ReserveSpeedTweekAdjustCapacity (size_t targetCapacity, size_t minChunk)
{
size_t capacity{targetCapacity};
capacity *= 6;
capacity /= 5;
capacity = Math::RoundUpTo (capacity, minChunk);
return capacity;
}
/*
********************************************************************************
*************************** ReserveSpeedTweekAddNCapacity **********************
********************************************************************************
*/
template <typename CONTAINER>
inline size_t ReserveSpeedTweekAddNCapacity (const CONTAINER& c, size_t n, size_t minChunk)
{
size_t size{c.size () + n};
size_t capacity{c.capacity ()};
if (size >= capacity) {
return ReserveSpeedTweekAdjustCapacity (size, minChunk);
}
return static_cast<size_t> (-1);
}
/*
********************************************************************************
*************************** ReserveSpeedTweekAddN ******************************
********************************************************************************
*/
template <typename CONTAINER>
inline void ReserveSpeedTweekAddN (CONTAINER& c, size_t n, size_t minChunk)
{
size_t size = ReserveSpeedTweekAddNCapacity (c, n, minChunk);
if (size != -1) {
c.reserve (size);
}
}
/*
********************************************************************************
*************************** ReserveSpeedTweekAdd1 ******************************
********************************************************************************
*/
template <typename CONTAINER>
inline void ReserveSpeedTweekAdd1 (CONTAINER& c, size_t minChunk)
{
ReserveSpeedTweekAddN (c, 1, minChunk);
}
}
#endif /*_Stroika_Foundation_Containers_Common_inl_*/
<commit_msg>ReserveSpeedTweekAdjustCapacity () tweak - so grows faster initially. That should help more than it hurts, but I dont have good empirical data for this (and the added computation cost could outweigh)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Common_inl_
#define _Stroika_Foundation_Containers_Common_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <algorithm>
#include "../Math/Common.h"
namespace Stroika::Foundation::Containers {
/*
********************************************************************************
************************************* Start ************************************
********************************************************************************
*/
template <typename CONTAINER>
inline typename CONTAINER::value_type* Start (CONTAINER& c)
{
size_t cnt = c.size ();
return cnt == 0 ? nullptr : &c[0];
}
template <typename CONTAINER>
inline const typename CONTAINER::value_type* Start (const CONTAINER& c)
{
size_t cnt = c.size ();
return cnt == 0 ? nullptr : &c[0];
}
/*
********************************************************************************
************************************* End **************************************
********************************************************************************
*/
template <typename CONTAINER>
inline typename CONTAINER::value_type* End (CONTAINER& c)
{
size_t cnt = c.size ();
return cnt == 0 ? nullptr : &c[0] + cnt;
}
template <typename CONTAINER>
inline const typename CONTAINER::value_type* End (const CONTAINER& c)
{
size_t cnt = c.size ();
return cnt == 0 ? nullptr : &c[0] + cnt;
}
/*
********************************************************************************
****************************** CompareResultNormalizeHelper ********************
********************************************************************************
*/
template <typename FROM_INT_TYPE, typename TO_INT_TYPE>
inline TO_INT_TYPE CompareResultNormalizeHelper (FROM_INT_TYPE f)
{
if (f < 0) {
return static_cast<TO_INT_TYPE> (-1);
}
else if (f > 0) {
return static_cast<TO_INT_TYPE> (1);
}
else {
return static_cast<TO_INT_TYPE> (0);
}
}
/*
********************************************************************************
*************************** ReserveSpeedTweekAdjustCapacity ********************
********************************************************************************
*/
inline size_t ReserveSpeedTweekAdjustCapacity (size_t targetCapacity, size_t minChunk)
{
size_t capacity{targetCapacity};
if (capacity <= 2 * minChunk) {
capacity *= 4;
}
else if (capacity <= 5 * minChunk) {
capacity *= 2;
}
else {
capacity *= 6;
capacity /= 5;
}
capacity = Math::RoundUpTo (capacity, minChunk);
return capacity;
}
/*
********************************************************************************
*************************** ReserveSpeedTweekAddNCapacity **********************
********************************************************************************
*/
template <typename CONTAINER>
inline size_t ReserveSpeedTweekAddNCapacity (const CONTAINER& c, size_t n, size_t minChunk)
{
size_t size{c.size () + n};
size_t capacity{c.capacity ()};
if (size >= capacity) {
return ReserveSpeedTweekAdjustCapacity (size, minChunk);
}
return static_cast<size_t> (-1);
}
/*
********************************************************************************
*************************** ReserveSpeedTweekAddN ******************************
********************************************************************************
*/
template <typename CONTAINER>
inline void ReserveSpeedTweekAddN (CONTAINER& c, size_t n, size_t minChunk)
{
size_t size = ReserveSpeedTweekAddNCapacity (c, n, minChunk);
if (size != -1) {
c.reserve (size);
}
}
/*
********************************************************************************
*************************** ReserveSpeedTweekAdd1 ******************************
********************************************************************************
*/
template <typename CONTAINER>
inline void ReserveSpeedTweekAdd1 (CONTAINER& c, size_t minChunk)
{
ReserveSpeedTweekAddN (c, 1, minChunk);
}
}
#endif /*_Stroika_Foundation_Containers_Common_inl_*/
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2010-03-12 14:05:50 +0100 (Fr, 12 Mrz 2010) $
Version: $Revision: 16010 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <mitkTestingMacros.h>
#include <mitkToFImageRecorder.h>
#include <mitkToFCameraMITKPlayerDevice.h>
#include <mitkToFConfig.h>
#include <mitkPicFileReader.h>
#include <itksys/SystemTools.hxx>
#include <mitkImageDataItem.h>
/**Documentation
* test for the class "ToFImageRecorder".
*/
static bool CompareImages(mitk::Image::Pointer image1, mitk::Image::Pointer image2)
{
//check if epsilon is exceeded
unsigned int sliceDimension = image1->GetDimension(0)*image1->GetDimension(1);
bool picturesEqual = true;
int numOfFrames = image1->GetDimension(2);
for (unsigned int i=0; i<numOfFrames; i++)
{
float* floatArray1 = (float*)image1->GetSliceData(i, 0, 0)->GetData();
float* floatArray2 = (float*)image2->GetSliceData(i, 0, 0)->GetData();
for(unsigned int j = 0; j < sliceDimension; j++)
{
if(!(mitk::Equal(floatArray1[j], floatArray2[j])))
{
picturesEqual = false;
}
}
}
return picturesEqual;
}
int mitkToFImageRecorderTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("ToFImageRecorder");
mitk::ToFImageRecorder::Pointer tofImageRecorder = mitk::ToFImageRecorder::New();
MITK_TEST_OUTPUT(<< "Test itk-Set/Get-Makros");
std::string testFileName_Distance = "test_DistanceImage.pic";
std::string testFileName_Amplitude = "test_AmplitudeImage.pic";
std::string testFileName_Intensity = "test_IntensityImage.pic";
std::string requiredName_Distance;
std::string requiredName_Amplitude;
std::string requiredName_Intensity;
tofImageRecorder->SetDistanceImageFileName(testFileName_Distance);
requiredName_Distance = tofImageRecorder->GetDistanceImageFileName();
MITK_TEST_CONDITION_REQUIRED(requiredName_Distance==testFileName_Distance,"Test for distance image file name");
tofImageRecorder->SetAmplitudeImageFileName(testFileName_Amplitude);
requiredName_Amplitude = tofImageRecorder->GetAmplitudeImageFileName();
MITK_TEST_CONDITION_REQUIRED(requiredName_Amplitude==testFileName_Amplitude,"Test for amplitude image file name");
tofImageRecorder->SetIntensityImageFileName(testFileName_Intensity);
requiredName_Intensity = tofImageRecorder->GetIntensityImageFileName();
MITK_TEST_CONDITION_REQUIRED(requiredName_Intensity==testFileName_Intensity,"Test for intensity image file name");
bool distanceImageSelected = false;
bool amplitudeImageSelected = false;
bool intensityImageSelected = false;
bool requiredDistanceImageSelected = false;
bool requiredAmplitudeImageSelected = false;
bool requiredIntensityImageSelected = false;
tofImageRecorder->SetDistanceImageSelected(distanceImageSelected);
requiredDistanceImageSelected = tofImageRecorder->GetDistanceImageSelected();
MITK_TEST_CONDITION_REQUIRED(distanceImageSelected==requiredDistanceImageSelected,"Test for distance selection");
tofImageRecorder->SetAmplitudeImageSelected(amplitudeImageSelected);
requiredAmplitudeImageSelected = tofImageRecorder->GetAmplitudeImageSelected();
MITK_TEST_CONDITION_REQUIRED(amplitudeImageSelected==requiredAmplitudeImageSelected,"Test for amplitude selection");
tofImageRecorder->SetIntensityImageSelected(intensityImageSelected);
requiredIntensityImageSelected = tofImageRecorder->GetIntensityImageSelected();
MITK_TEST_CONDITION_REQUIRED(intensityImageSelected==requiredIntensityImageSelected,"Test for intensity selection");
int numOfFrames = 7;
tofImageRecorder->SetNumOfFrames(numOfFrames);
MITK_TEST_CONDITION_REQUIRED(numOfFrames==tofImageRecorder->GetNumOfFrames(),"Test for get/set number of frames");
std::string fileFormat = ".pic";
tofImageRecorder->SetFileFormat(fileFormat);
MITK_TEST_CONDITION_REQUIRED(fileFormat==tofImageRecorder->GetFileFormat(),"Test for get/set the file format");
MITK_TEST_OUTPUT(<< "Test other methods");
tofImageRecorder->SetRecordMode(mitk::ToFImageRecorder::Infinite);
MITK_TEST_CONDITION_REQUIRED(mitk::ToFImageRecorder::Infinite==tofImageRecorder->GetRecordMode(),"Test for get/set the record mode");
mitk::ToFCameraDevice* testDevice = NULL;
tofImageRecorder->SetCameraDevice(testDevice);
MITK_TEST_CONDITION_REQUIRED(testDevice == tofImageRecorder->GetCameraDevice(),"Test for get/set the camera device");
tofImageRecorder->SetToFImageType(mitk::ToFImageWriter::ToFImageType2DPlusT);
MITK_TEST_CONDITION_REQUIRED(mitk::ToFImageWriter::ToFImageType2DPlusT==tofImageRecorder->GetToFImageType(), "Testing set/get ToFImageType");
tofImageRecorder->SetToFImageType(mitk::ToFImageWriter::ToFImageType3D);
MITK_TEST_CONDITION_REQUIRED(mitk::ToFImageWriter::ToFImageType3D==tofImageRecorder->GetToFImageType(), "Testing set/get ToFImageType");
MITK_TEST_OUTPUT(<< "Test recording");
tofImageRecorder = mitk::ToFImageRecorder::New();
std::string dirName = MITK_TOF_DATA_DIR;
mitk::ToFCameraMITKPlayerDevice::Pointer tofCameraMITKPlayerDevice = mitk::ToFCameraMITKPlayerDevice::New();
tofImageRecorder->SetCameraDevice(tofCameraMITKPlayerDevice);
MITK_TEST_CONDITION_REQUIRED(tofCameraMITKPlayerDevice == tofImageRecorder->GetCameraDevice(), "Testing set/get CameraDevice with ToFCameraPlayerDevice");
std::string distanceFileName = dirName + "/PMDCamCube2_MF0_IT0_20Images_DistanceImage.pic";
std::string amplitudeFileName = dirName + "/PMDCamCube2_MF0_IT0_20Images_AmplitudeImage.pic";
std::string intensityFileName = dirName + "/PMDCamCube2_MF0_IT0_20Images_IntensityImage.pic";
tofCameraMITKPlayerDevice->SetProperty("DistanceImageFileName",mitk::StringProperty::New(distanceFileName));
tofCameraMITKPlayerDevice->SetProperty("AmplitudeImageFileName",mitk::StringProperty::New(amplitudeFileName));
tofCameraMITKPlayerDevice->SetProperty("IntensityImageFileName",mitk::StringProperty::New(intensityFileName));
tofCameraMITKPlayerDevice->ConnectCamera();
tofCameraMITKPlayerDevice->StartCamera();
std::string distanceTestFileName = "test_distance.pic";
std::string amplitudeTestFileName = "test_amplitude.pic";
std::string intensityTestFileName = "test_intensity.pic";
tofImageRecorder->SetDistanceImageFileName(distanceTestFileName);
tofImageRecorder->SetAmplitudeImageFileName(amplitudeTestFileName);
tofImageRecorder->SetIntensityImageFileName(intensityTestFileName);
tofImageRecorder->SetFileFormat(".pic");
tofImageRecorder->SetRecordMode(mitk::ToFImageRecorder::PerFrames);
tofImageRecorder->SetNumOfFrames(20);
tofImageRecorder->StartRecording();
itksys::SystemTools::Delay(1000); // wait to allow recording
tofImageRecorder->StopRecording();
tofCameraMITKPlayerDevice->StopCamera();
tofCameraMITKPlayerDevice->DisconnectCamera();
// Load images (recorded and original ones) with PicFileReader for comparison
mitk::PicFileReader::Pointer picFileReader = mitk::PicFileReader::New();
mitk::Image::Pointer originalImage = NULL;
mitk::Image::Pointer recordedImage = NULL;
picFileReader->SetFileName(distanceFileName);
picFileReader->Update();
originalImage = picFileReader->GetOutput();
picFileReader->SetFileName(distanceTestFileName);
picFileReader->Update();
recordedImage = picFileReader->GetOutput();
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(0) == tofImageRecorder->GetCaptureWidth(), "Testing capture width");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(1) == tofImageRecorder->GetCaptureHeight(), "Testing capture height");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(2) == recordedImage->GetDimension(2), "Testing number of frames");
MITK_TEST_CONDITION_REQUIRED(CompareImages(originalImage, recordedImage), "Compare original and saved distance image");
picFileReader->SetFileName(amplitudeFileName);
picFileReader->Update();
originalImage = picFileReader->GetOutput();
picFileReader->SetFileName(amplitudeTestFileName);
picFileReader->Update();
recordedImage = picFileReader->GetOutput();
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(0) == tofImageRecorder->GetCaptureWidth(), "Testing capture width");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(1) == tofImageRecorder->GetCaptureHeight(), "Testing capture height");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(2) == recordedImage->GetDimension(2), "Testing number of frames");
MITK_TEST_CONDITION_REQUIRED(CompareImages(originalImage, recordedImage), "Compare original and saved amplitude image");
picFileReader->SetFileName(intensityFileName);
picFileReader->Update();
originalImage = picFileReader->GetOutput();
picFileReader->SetFileName(intensityTestFileName);
picFileReader->Update();
recordedImage = picFileReader->GetOutput();
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(0) == tofImageRecorder->GetCaptureWidth(), "Testing capture width");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(1) == tofImageRecorder->GetCaptureHeight(), "Testing capture height");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(2) == recordedImage->GetDimension(2), "Testing number of frames");
MITK_TEST_CONDITION_REQUIRED(CompareImages(originalImage, recordedImage), "Compare original and saved intensity image");
//clean up and delete saved image files
if( remove( "test_distance.pic" ) != 0 )
{
MITK_ERROR<<"File: test_distance.pic not successfully deleted!";
}
if( remove( "test_amplitude.pic" ) != 0 )
{
MITK_ERROR<<"File: test_amplitude.pic not successfully deleted!";
}
if( remove( "test_intensity.pic" ) != 0 )
{
MITK_ERROR<<"File: test_intensity.pic not successfully deleted!";
}
MITK_TEST_END();
}
<commit_msg>Added some test outputs and missing test cases<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2010-03-12 14:05:50 +0100 (Fr, 12 Mrz 2010) $
Version: $Revision: 16010 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <mitkTestingMacros.h>
#include <mitkToFImageRecorder.h>
#include <mitkToFCameraMITKPlayerDevice.h>
#include <mitkToFConfig.h>
#include <mitkPicFileReader.h>
#include <itksys/SystemTools.hxx>
#include <mitkImageDataItem.h>
/**Documentation
* test for the class "ToFImageRecorder".
*/
static bool CompareImages(mitk::Image::Pointer image1, mitk::Image::Pointer image2)
{
//check if epsilon is exceeded
unsigned int sliceDimension = image1->GetDimension(0)*image1->GetDimension(1);
bool picturesEqual = true;
int numOfFrames = image1->GetDimension(2);
for (unsigned int i=0; i<numOfFrames; i++)
{
float* floatArray1 = (float*)image1->GetSliceData(i, 0, 0)->GetData();
float* floatArray2 = (float*)image2->GetSliceData(i, 0, 0)->GetData();
for(unsigned int j = 0; j < sliceDimension; j++)
{
if(!(mitk::Equal(floatArray1[j], floatArray2[j])))
{
picturesEqual = false;
}
}
}
return picturesEqual;
}
int mitkToFImageRecorderTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("ToFImageRecorder");
mitk::ToFImageRecorder::Pointer tofImageRecorder = mitk::ToFImageRecorder::New();
MITK_TEST_OUTPUT(<< "Test itk-Set/Get-Makros");
std::string testFileName_Distance = "test_DistanceImage.pic";
std::string testFileName_Amplitude = "test_AmplitudeImage.pic";
std::string testFileName_Intensity = "test_IntensityImage.pic";
std::string requiredName_Distance;
std::string requiredName_Amplitude;
std::string requiredName_Intensity;
tofImageRecorder->SetDistanceImageFileName(testFileName_Distance);
requiredName_Distance = tofImageRecorder->GetDistanceImageFileName();
MITK_TEST_CONDITION_REQUIRED(requiredName_Distance==testFileName_Distance,"Test for distance image file name");
tofImageRecorder->SetAmplitudeImageFileName(testFileName_Amplitude);
requiredName_Amplitude = tofImageRecorder->GetAmplitudeImageFileName();
MITK_TEST_CONDITION_REQUIRED(requiredName_Amplitude==testFileName_Amplitude,"Test for amplitude image file name");
tofImageRecorder->SetIntensityImageFileName(testFileName_Intensity);
requiredName_Intensity = tofImageRecorder->GetIntensityImageFileName();
MITK_TEST_CONDITION_REQUIRED(requiredName_Intensity==testFileName_Intensity,"Test for intensity image file name");
bool distanceImageSelected = false;
bool amplitudeImageSelected = false;
bool intensityImageSelected = false;
bool requiredDistanceImageSelected = false;
bool requiredAmplitudeImageSelected = false;
bool requiredIntensityImageSelected = false;
tofImageRecorder->SetDistanceImageSelected(distanceImageSelected);
requiredDistanceImageSelected = tofImageRecorder->GetDistanceImageSelected();
MITK_TEST_CONDITION_REQUIRED(distanceImageSelected==requiredDistanceImageSelected,"Test for distance selection");
tofImageRecorder->SetAmplitudeImageSelected(amplitudeImageSelected);
requiredAmplitudeImageSelected = tofImageRecorder->GetAmplitudeImageSelected();
MITK_TEST_CONDITION_REQUIRED(amplitudeImageSelected==requiredAmplitudeImageSelected,"Test for amplitude selection");
tofImageRecorder->SetIntensityImageSelected(intensityImageSelected);
requiredIntensityImageSelected = tofImageRecorder->GetIntensityImageSelected();
MITK_TEST_CONDITION_REQUIRED(intensityImageSelected==requiredIntensityImageSelected,"Test for intensity selection");
int numOfFrames = 7;
tofImageRecorder->SetNumOfFrames(numOfFrames);
MITK_TEST_CONDITION_REQUIRED(numOfFrames==tofImageRecorder->GetNumOfFrames(),"Test for get/set number of frames");
std::string fileFormat = ".pic";
tofImageRecorder->SetFileFormat(fileFormat);
MITK_TEST_CONDITION_REQUIRED(fileFormat==tofImageRecorder->GetFileFormat(),"Test for get/set the file format");
MITK_TEST_OUTPUT(<< "Test other methods");
tofImageRecorder->SetRecordMode(mitk::ToFImageRecorder::Infinite);
MITK_TEST_CONDITION_REQUIRED(mitk::ToFImageRecorder::Infinite==tofImageRecorder->GetRecordMode(),"Test for get/set the record mode");
mitk::ToFCameraDevice* testDevice = NULL;
tofImageRecorder->SetCameraDevice(testDevice);
MITK_TEST_CONDITION_REQUIRED(testDevice == tofImageRecorder->GetCameraDevice(),"Test for get/set the camera device");
tofImageRecorder->SetToFImageType(mitk::ToFImageWriter::ToFImageType2DPlusT);
MITK_TEST_CONDITION_REQUIRED(mitk::ToFImageWriter::ToFImageType2DPlusT==tofImageRecorder->GetToFImageType(), "Testing set/get ToFImageType");
tofImageRecorder->SetToFImageType(mitk::ToFImageWriter::ToFImageType3D);
MITK_TEST_CONDITION_REQUIRED(mitk::ToFImageWriter::ToFImageType3D==tofImageRecorder->GetToFImageType(), "Testing set/get ToFImageType");
MITK_TEST_OUTPUT(<< "Test recording");
tofImageRecorder = mitk::ToFImageRecorder::New();
std::string dirName = MITK_TOF_DATA_DIR;
mitk::ToFCameraMITKPlayerDevice::Pointer tofCameraMITKPlayerDevice = mitk::ToFCameraMITKPlayerDevice::New();
tofImageRecorder->SetCameraDevice(tofCameraMITKPlayerDevice);
MITK_TEST_CONDITION_REQUIRED(tofCameraMITKPlayerDevice == tofImageRecorder->GetCameraDevice(), "Testing set/get CameraDevice with ToFCameraPlayerDevice");
std::string distanceFileName = dirName + "/PMDCamCube2_MF0_IT0_20Images_DistanceImage.pic";
std::string amplitudeFileName = dirName + "/PMDCamCube2_MF0_IT0_20Images_AmplitudeImage.pic";
std::string intensityFileName = dirName + "/PMDCamCube2_MF0_IT0_20Images_IntensityImage.pic";
tofCameraMITKPlayerDevice->SetProperty("DistanceImageFileName",mitk::StringProperty::New(distanceFileName));
tofCameraMITKPlayerDevice->SetProperty("AmplitudeImageFileName",mitk::StringProperty::New(amplitudeFileName));
tofCameraMITKPlayerDevice->SetProperty("IntensityImageFileName",mitk::StringProperty::New(intensityFileName));
MITK_TEST_OUTPUT(<< "Test ConnectCamera()");
tofCameraMITKPlayerDevice->ConnectCamera();
MITK_TEST_OUTPUT(<< "Test StartCamera()");
tofCameraMITKPlayerDevice->StartCamera();
std::string distanceTestFileName = "test_distance.pic";
std::string amplitudeTestFileName = "test_amplitude.pic";
std::string intensityTestFileName = "test_intensity.pic";
tofImageRecorder->SetDistanceImageFileName(distanceTestFileName);
MITK_TEST_CONDITION_REQUIRED(tofImageRecorder->GetDistanceImageFileName() == distanceTestFileName, "Testing Set/GetDistanceImageFileName()");
tofImageRecorder->SetAmplitudeImageFileName(amplitudeTestFileName);
MITK_TEST_CONDITION_REQUIRED(tofImageRecorder->GetAmplitudeImageFileName() == amplitudeTestFileName, "Testing Set/GetAmplitudeImageFileName()");
tofImageRecorder->SetIntensityImageFileName(intensityTestFileName);
MITK_TEST_CONDITION_REQUIRED(tofImageRecorder->GetIntensityImageFileName() == intensityTestFileName, "Testing Set/GetIntensityImageFileName()");
tofImageRecorder->SetFileFormat(".pic");
MITK_TEST_CONDITION_REQUIRED(tofImageRecorder->GetFileFormat() == ".pic", "Testing Set/GetFileFormat()");
tofImageRecorder->SetRecordMode(mitk::ToFImageRecorder::PerFrames);
MITK_TEST_CONDITION_REQUIRED(tofImageRecorder->GetRecordMode() == mitk::ToFImageRecorder::PerFrames, "Testing Set/GetRecordMode()");
tofImageRecorder->SetNumOfFrames(20);
MITK_TEST_CONDITION_REQUIRED(tofImageRecorder->GetNumOfFrames() == 20, "Testing Set/GetNumOfFrames()");
MITK_TEST_OUTPUT(<< "Test StartRecording()");
tofImageRecorder->StartRecording();
itksys::SystemTools::Delay(1000); // wait to allow recording
MITK_TEST_OUTPUT(<< "Test StopRecording()");
tofImageRecorder->StopRecording();
MITK_TEST_OUTPUT(<< "Test StopCamera()");
tofCameraMITKPlayerDevice->StopCamera();
MITK_TEST_OUTPUT(<< "Test DisconnectCamera()");
tofCameraMITKPlayerDevice->DisconnectCamera();
// Load images (recorded and original ones) with PicFileReader for comparison
mitk::PicFileReader::Pointer picFileReader = mitk::PicFileReader::New();
mitk::Image::Pointer originalImage = NULL;
mitk::Image::Pointer recordedImage = NULL;
MITK_TEST_OUTPUT(<< "Read original distance image using PicFileReader");
picFileReader->SetFileName(distanceFileName);
picFileReader->Update();
originalImage = picFileReader->GetOutput();
MITK_TEST_OUTPUT(<< "Read recorded distance image using PicFileReader");
picFileReader->SetFileName(distanceTestFileName);
picFileReader->Update();
recordedImage = picFileReader->GetOutput();
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(0) == tofImageRecorder->GetCaptureWidth(), "Testing capture width");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(1) == tofImageRecorder->GetCaptureHeight(), "Testing capture height");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(2) == recordedImage->GetDimension(2), "Testing number of frames");
MITK_TEST_CONDITION_REQUIRED(CompareImages(originalImage, recordedImage), "Compare original and saved distance image");
MITK_TEST_OUTPUT(<< "Read original amplitude image using PicFileReader");
picFileReader->SetFileName(amplitudeFileName);
picFileReader->Update();
originalImage = picFileReader->GetOutput();
MITK_TEST_OUTPUT(<< "Read recorded amplitude image using PicFileReader");
picFileReader->SetFileName(amplitudeTestFileName);
picFileReader->Update();
recordedImage = picFileReader->GetOutput();
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(0) == tofImageRecorder->GetCaptureWidth(), "Testing capture width");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(1) == tofImageRecorder->GetCaptureHeight(), "Testing capture height");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(2) == recordedImage->GetDimension(2), "Testing number of frames");
MITK_TEST_CONDITION_REQUIRED(CompareImages(originalImage, recordedImage), "Compare original and saved amplitude image");
MITK_TEST_OUTPUT(<< "Read original intensity image using PicFileReader");
picFileReader->SetFileName(intensityFileName);
picFileReader->Update();
originalImage = picFileReader->GetOutput();
MITK_TEST_OUTPUT(<< "Read recorded intensity image using PicFileReader");
picFileReader->SetFileName(intensityTestFileName);
picFileReader->Update();
recordedImage = picFileReader->GetOutput();
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(0) == tofImageRecorder->GetCaptureWidth(), "Testing capture width");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(1) == tofImageRecorder->GetCaptureHeight(), "Testing capture height");
MITK_TEST_CONDITION_REQUIRED(originalImage->GetDimension(2) == recordedImage->GetDimension(2), "Testing number of frames");
MITK_TEST_CONDITION_REQUIRED(CompareImages(originalImage, recordedImage), "Compare original and saved intensity image");
//clean up and delete saved image files
if( remove( "test_distance.pic" ) != 0 )
{
MITK_ERROR<<"File: test_distance.pic not successfully deleted!";
}
if( remove( "test_amplitude.pic" ) != 0 )
{
MITK_ERROR<<"File: test_amplitude.pic not successfully deleted!";
}
if( remove( "test_intensity.pic" ) != 0 )
{
MITK_ERROR<<"File: test_intensity.pic not successfully deleted!";
}
MITK_TEST_END();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "tensorflowpredict.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* TensorflowPredict::name = "TensorflowPredict";
const char* TensorflowPredict::category = "Machine Learning";
const char* TensorflowPredict::description = DOC("This algorithm runs a Tensorflow graph and stores the desired tensors in a pool.\n"
"The Tensorflow graph should be stored in Protocol Buffer (.pb) binary format [1], and should contain both the architecture and the weights of the model.\n"
"The parameter `inputs` should contain a list with the names of the input nodes that feed the model. The input Pool should contain the tensors corresponding to each input node stored using Essetia tensors."
"The pool namespace for each input tensor has to match the input node's name.\n"
"In the same way, the `outputs` parameter should contain the names of the nodes whose tensors are desired to save. These tensors will be stored inside the output pool under a namespace that matches the name of the node. "
"To print a list with all the available nodes in the graph set the first element of `outputs` as an empty string.\n"
"This algorithm is a wrapper for the Tensorflow C API [2]. The first time it is configured with a non-empty `graphFilename` it will try to load the contained graph and to attach a Tensorflow session to it. "
"The reset method deletes the current session (and the resources attached to it) and creates a new one relying on the available graph. "
"By reconfiguring the algorithm the graph is reloaded and the reset method is called.\n"
"\n"
"References:\n"
" [1] TensorFlow - An open source machine learning library for research and production.\n"
" https://www.tensorflow.org/extend/tool_developers/#protocol_buffers\n\n"
" [2] TensorFlow - An open source machine learning library for research and production.\n"
" https://www.tensorflow.org/api_docs/cc/");
static void DeallocateBuffer(void* data, size_t) {
free(data);
}
void TensorflowPredict::configure() {
_savedModel = parameter("savedModel").toString();
_graphFilename = parameter("graphFilename").toString();
// Do not do anything if we did not get a non-empty model name.
if ((_savedModel.empty()) and (_graphFilename.empty())) return;
_tags = parameter("tags").toVectorString();
_inputNames = parameter("inputs").toVectorString();
_outputNames = parameter("outputs").toVectorString();
_isTraining = parameter("isTraining").toBool();
_isTrainingName = parameter("isTrainingName").toString();
_squeeze = parameter("squeeze").toBool();
(_isTrainingName == "") ? _isTrainingSet = false : _isTrainingSet = true;
_nInputs = _inputNames.size();
_nOutputs = _outputNames.size();
// Allocate input and output tensors.
_inputTensors.resize(_nInputs + int(_isTrainingSet));
_inputNodes.resize(_nInputs + int(_isTrainingSet));
_outputTensors.resize(_nOutputs);
_outputNodes.resize(_nOutputs);
TF_DeleteGraph(_graph);
_graph = TF_NewGraph();
openGraph();
reset();
// If the first output name is empty just print out the list of nodes and return.
if (_outputNames[0] == "") {
E_INFO(availableNodesInfo());
return;
}
// Initialize the list of input and output node names.
for (size_t i = 0; i < _nInputs; i++) {
_inputNodes[i] = graphOperationByName(_inputNames[i]);
}
for (size_t i = 0; i < _nOutputs; i++) {
_outputNodes[i] = graphOperationByName(_outputNames[i]);
}
// Add isTraining flag if needed.
if (_isTrainingSet) {
const int64_t dims[1] = {};
TF_Tensor *isTraining = TF_AllocateTensor(TF_BOOL, dims, 0, 1);
void* isTrainingValue = TF_TensorData(isTraining);
if (isTrainingValue == nullptr) {
TF_DeleteTensor(isTraining);
throw EssentiaException("Error generating traning phase flag");
}
memcpy(isTrainingValue, &_isTraining, sizeof(bool));
_inputTensors[_nInputs] = isTraining;
_inputNodes[_nInputs] = graphOperationByName(_isTrainingName);
}
}
void TensorflowPredict::openGraph() {
// Prioritize savedModel when both are specified.
if (!_savedModel.empty()) {
std::vector<char*> tags_c;
tags_c.reserve(_tags.size());
for (size_t i = 0; i < _tags.size(); i++) {
tags_c.push_back(const_cast<char*>(_tags[i].c_str()));
}
TF_LoadSessionFromSavedModel(_sessionOptions, _runOptions,
_savedModel.c_str(), &tags_c[0], (int)tags_c.size(),
_graph, NULL, _status);
E_INFO("Successfully loaded SavedModel: `" << _savedModel << "`");
return;
}
if (!_graphFilename.empty()) {
// First we load and initialize the model.
const auto f = fopen(_graphFilename.c_str(), "rb");
if (f == nullptr) {
throw EssentiaException(
"TensorflowPredict: could not open the Tensorflow graph file.");
}
fseek(f, 0, SEEK_END);
const auto fsize = ftell(f);
fseek(f, 0, SEEK_SET);
// Graph size sanity check.
if (fsize < 1) {
fclose(f);
throw(EssentiaException("TensorflowPredict: Graph file is empty."));
}
// Reserve memory and read the graph.
const auto data = malloc(fsize);
fread(data, fsize, 1, f);
fclose(f);
TF_Buffer* buffer = TF_NewBuffer();
buffer->data = data;
buffer->length = fsize;
buffer->data_deallocator = DeallocateBuffer;
TF_GraphImportGraphDef(_graph, buffer, _options, _status);
TF_DeleteBuffer(buffer);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error importing graph. ", TF_Message(_status));
}
E_INFO("Successfully loaded graph file: `" << _graphFilename << "`");
}
}
void TensorflowPredict::reset() {
if ((_savedModel.empty()) and (_graphFilename.empty())) return;
TF_CloseSession(_session, _status);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error closing session. ", TF_Message(_status));
}
TF_DeleteSession(_session, _status);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error deleting session. ", TF_Message(_status));
}
_session = TF_NewSession(_graph, _sessionOptions, _status);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error creating new session after reset. ", TF_Message(_status));
}
}
void TensorflowPredict::compute() {
const Pool& poolIn = _poolIn.get();
Pool& poolOut = _poolOut.get();
// Parse the input tensors from the pool into Tensorflow tensors.
for (size_t i = 0; i < _nInputs; i++) {
const Tensor<Real>& inputData =
poolIn.value<Tensor<Real> >(_inputNames[i]);
_inputTensors[i] = TensorToTF(inputData);
}
// Initialize output tensors.
for (size_t i = 0; i < _nOutputs; i++) {
_outputTensors[i] = nullptr;
}
// Run the Tensorflow session.
TF_SessionRun(_session,
nullptr, // Run options.
&_inputNodes[0], // Input node names.
&_inputTensors[0], // input tensor values.
_nInputs + (int)_isTrainingSet, // Number of inputs.
&_outputNodes[0], // Output node names.
&_outputTensors[0], // Output tensor values.
_nOutputs, // Number of outputs.
nullptr, 0, // Target operations, number of targets.
nullptr, // Run metadata.
_status // Output status.
);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error running the Tensorflow session. ", TF_Message(_status));
}
// Copy the desired tensors into the output pool.
for (size_t i = 0; i < _nOutputs; i++) {
poolOut.set(_outputNames[i], TFToTensor(_outputTensors[i], _outputNodes[i]));
}
// Deallocate tensors.
for (size_t i = 0; i < _nInputs; i++) {
TF_DeleteTensor(_inputTensors[i]);
}
for (size_t i = 0; i < _nOutputs; i++) {
TF_DeleteTensor(_outputTensors[i]);
}
}
TF_Tensor* TensorflowPredict::TensorToTF(
const Tensor<Real>& tensorIn) {
int dims = 1;
vector<int64_t> shape;
// Batch dimensions is the only one allowed to be singleton
shape.push_back((int64_t)tensorIn.dimension(0));
if (_squeeze) {
for(int i = 1; i < tensorIn.rank(); i++) {
if (tensorIn.dimension(i) > 1) {
shape.push_back((int64_t)tensorIn.dimension(i));
dims++;
}
}
} else {
dims = tensorIn.rank();
for(int i = 1; i < dims; i++) {
shape.push_back((int64_t)tensorIn.dimension(i));
}
}
TF_Tensor* tensorOut = TF_AllocateTensor(
TF_FLOAT, &shape[0], dims,
(size_t)tensorIn.size() * sizeof(Real));
if (tensorOut == nullptr) {
throw EssentiaException("TensorflowPredict: Error generating input tensor.");
}
// Get a pointer to the data and fill the tensor.
void* tensorData = TF_TensorData(tensorOut);
if (tensorData == nullptr) {
TF_DeleteTensor(tensorOut);
throw EssentiaException("TensorflowPredict: Error generating input tensors data.");
}
memcpy(tensorData, tensorIn.data(),
std::min(tensorIn.size() * sizeof(Real),
TF_TensorByteSize(tensorOut)));
return tensorOut;
}
const Tensor<Real> TensorflowPredict::TFToTensor(
const TF_Tensor* tensor, TF_Output node) {
const Real* outputData = static_cast<Real*>(TF_TensorData(tensor));
// Get the output tensor's shape.
size_t outNDims = TF_GraphGetTensorNumDims(_graph, node, _status);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error getting the output tensor's shape. ", TF_Message(_status));
}
// Create and array to store the shape of the tensor.
array<long int, 4> shape {1, 1, 1, 1};
shape[0] = (int)TF_Dim(tensor, 0);
// We are assuming one of the following cases:
// 1 - outNDims = 2 -> Batch + Feats
// 2 - outNDims = 3 -> Batch + Timestamps + Feats
// 3 - outNDims = 4 -> Batch + Channels + Timestamps + Feats
size_t idx = 1;
for (size_t i = shape.size() - outNDims + 1; i < shape.size(); i++, idx++) {
shape[i] = (int)TF_Dim(tensor, idx);
}
// Return a const reference to the data in Eigen format.
return TensorMap<const Real>(outputData, shape);
}
TF_Output TensorflowPredict::graphOperationByName(const string nodeName) {
int index = 0;
const char* name = nodeName.c_str();
// TensorFlow operations (or nodes from the graph perspective) return tensors named <nodeName:n>, where n goes
// from 0 to the number of outputs. The first output tensor of a node can be extracted implicitly (nodeName)
// or explicitly (nodeName:0). To extract the subsequent tensors, the index has to be specified (nodeName:1,
// nodeName:2).
string::size_type n = nodeName.find(':');
if (n != string::npos) {
index = stoi(nodeName.substr(n + 1));
name = nodeName.substr(0, n).c_str();
}
TF_Output output = {TF_GraphOperationByName(_graph, name), index};
if (output.oper == nullptr) {
throw EssentiaException("TensorflowPredict: '" + string(nodeName) +
"' is not a valid node name of this graph.\n" +
availableNodesInfo());
}
return output;
}
vector<string> TensorflowPredict::nodeNames() {
size_t pos = 0;
TF_Operation *oper;
vector<string> nodeNames;
while ((oper = TF_GraphNextOperation(_graph, &pos)) != nullptr) {
nodeNames.push_back(string(TF_OperationName(oper)));
}
return nodeNames;
}
<commit_msg>Improve documentation<commit_after>/*
* Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "tensorflowpredict.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* TensorflowPredict::name = "TensorflowPredict";
const char* TensorflowPredict::category = "Machine Learning";
const char* TensorflowPredict::description = DOC("This algorithm runs a Tensorflow graph and stores the desired output tensors in a pool.\n"
"The Tensorflow graph should be stored in Protocol Buffer (.pb) binary format [1] or as a SavedModel [2], and should contain both the architecture and the weights of the model.\n"
"The parameter `inputs` should contain a list with the names of the input nodes that feed the model. The input Pool should contain the tensors corresponding to each input node stored using Essetia tensors. "
"The pool namespace for each input tensor has to match the input node's name.\n"
"In the same way, the `outputs` parameter should contain the names of the tensors to save. These tensors will be stored inside the output pool under a namespace that matches the tensor's name. "
"TensorFlow nodes return tensors identified as `nodeName:n`, where `n` goes from 0 to the number of outputs of the node - 1. "
"The first output tensor of a node can be referred implicitly (e.g., `nodeName`) or explicitly (e.g., `nodeName:0`), and the subsequent tensors require the specific index (e.g., nodeName:1, nodeName:2). "
"In TensorFlow 2 SavedModels all the outputs of the model are contained in the `PartitionedCall` node (e.g., `PartitionedCall:0`, `PartitionedCall:1`). "
"You can use TenorFlow's `saved_model_cli` to find the relation of outputs and `PartitionedCall` indices, for example:\n"
"\n"
">>> saved_model_cli show --dir SavedModel/ --all\n"
">>> ...\n"
">>> The given SavedModel SignatureDef contains the following output(s):\n"
">>> outputs['activations'] tensor_info:\n"
">>> dtype: DT_FLOAT\n"
">>> shape: (1, 400)\n"
">>> name: PartitionedCall:0\n"
">>> outputs['embeddings'] tensor_info:\n"
">>> dtype: DT_FLOAT\n"
">>> shape: (1, 1280)\n"
">>> name: PartitionedCall:1\n"
">>> ...\n"
"\n"
"To print a list with all the available nodes in the graph set the first element of `outputs` as an empty string (i.e., \"\")."
"\n"
"This algorithm is a wrapper for the Tensorflow C API [3]. The first time it is configured with a non-empty `graphFilename` it will try to load the contained graph and to attach a Tensorflow session to it. "
"The reset method deletes the current session (and the resources attached to it) and creates a new one relying on the available graph. "
"By reconfiguring the algorithm the graph is reloaded and the reset method is called.\n"
"\n"
"References:\n"
" [1] TensorFlow - An open source machine learning library for research and production.\n"
" https://www.tensorflow.org/extend/tool_developers/#protocol_buffers\n\n"
" [2] TensorFlow - An open source machine learning library for research and production.\n"
" https://www.tensorflow.org/guide/saved_model\n\n"
" [3] TensorFlow - An open source machine learning library for research and production.\n"
" https://www.tensorflow.org/api_docs/cc/");
static void DeallocateBuffer(void* data, size_t) {
free(data);
}
void TensorflowPredict::configure() {
_savedModel = parameter("savedModel").toString();
_graphFilename = parameter("graphFilename").toString();
// Do not do anything if we did not get a non-empty model name.
if ((_savedModel.empty()) and (_graphFilename.empty())) return;
_tags = parameter("tags").toVectorString();
_inputNames = parameter("inputs").toVectorString();
_outputNames = parameter("outputs").toVectorString();
_isTraining = parameter("isTraining").toBool();
_isTrainingName = parameter("isTrainingName").toString();
_squeeze = parameter("squeeze").toBool();
(_isTrainingName == "") ? _isTrainingSet = false : _isTrainingSet = true;
_nInputs = _inputNames.size();
_nOutputs = _outputNames.size();
// Allocate input and output tensors.
_inputTensors.resize(_nInputs + int(_isTrainingSet));
_inputNodes.resize(_nInputs + int(_isTrainingSet));
_outputTensors.resize(_nOutputs);
_outputNodes.resize(_nOutputs);
TF_DeleteGraph(_graph);
_graph = TF_NewGraph();
openGraph();
reset();
// If the first output name is empty just print out the list of nodes and return.
if (_outputNames[0] == "") {
E_INFO(availableNodesInfo());
return;
}
// Initialize the list of input and output node names.
for (size_t i = 0; i < _nInputs; i++) {
_inputNodes[i] = graphOperationByName(_inputNames[i]);
}
for (size_t i = 0; i < _nOutputs; i++) {
_outputNodes[i] = graphOperationByName(_outputNames[i]);
}
// Add isTraining flag if needed.
if (_isTrainingSet) {
const int64_t dims[1] = {};
TF_Tensor *isTraining = TF_AllocateTensor(TF_BOOL, dims, 0, 1);
void* isTrainingValue = TF_TensorData(isTraining);
if (isTrainingValue == nullptr) {
TF_DeleteTensor(isTraining);
throw EssentiaException("Error generating traning phase flag");
}
memcpy(isTrainingValue, &_isTraining, sizeof(bool));
_inputTensors[_nInputs] = isTraining;
_inputNodes[_nInputs] = graphOperationByName(_isTrainingName);
}
}
void TensorflowPredict::openGraph() {
// Prioritize savedModel when both are specified.
if (!_savedModel.empty()) {
std::vector<char*> tags_c;
tags_c.reserve(_tags.size());
for (size_t i = 0; i < _tags.size(); i++) {
tags_c.push_back(const_cast<char*>(_tags[i].c_str()));
}
TF_LoadSessionFromSavedModel(_sessionOptions, _runOptions,
_savedModel.c_str(), &tags_c[0], (int)tags_c.size(),
_graph, NULL, _status);
E_INFO("Successfully loaded SavedModel: `" << _savedModel << "`");
return;
}
if (!_graphFilename.empty()) {
// First we load and initialize the model.
const auto f = fopen(_graphFilename.c_str(), "rb");
if (f == nullptr) {
throw EssentiaException(
"TensorflowPredict: could not open the Tensorflow graph file.");
}
fseek(f, 0, SEEK_END);
const auto fsize = ftell(f);
fseek(f, 0, SEEK_SET);
// Graph size sanity check.
if (fsize < 1) {
fclose(f);
throw(EssentiaException("TensorflowPredict: Graph file is empty."));
}
// Reserve memory and read the graph.
const auto data = malloc(fsize);
fread(data, fsize, 1, f);
fclose(f);
TF_Buffer* buffer = TF_NewBuffer();
buffer->data = data;
buffer->length = fsize;
buffer->data_deallocator = DeallocateBuffer;
TF_GraphImportGraphDef(_graph, buffer, _options, _status);
TF_DeleteBuffer(buffer);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error importing graph. ", TF_Message(_status));
}
E_INFO("Successfully loaded graph file: `" << _graphFilename << "`");
}
}
void TensorflowPredict::reset() {
if ((_savedModel.empty()) and (_graphFilename.empty())) return;
TF_CloseSession(_session, _status);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error closing session. ", TF_Message(_status));
}
TF_DeleteSession(_session, _status);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error deleting session. ", TF_Message(_status));
}
_session = TF_NewSession(_graph, _sessionOptions, _status);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error creating new session after reset. ", TF_Message(_status));
}
}
void TensorflowPredict::compute() {
const Pool& poolIn = _poolIn.get();
Pool& poolOut = _poolOut.get();
// Parse the input tensors from the pool into Tensorflow tensors.
for (size_t i = 0; i < _nInputs; i++) {
const Tensor<Real>& inputData =
poolIn.value<Tensor<Real> >(_inputNames[i]);
_inputTensors[i] = TensorToTF(inputData);
}
// Initialize output tensors.
for (size_t i = 0; i < _nOutputs; i++) {
_outputTensors[i] = nullptr;
}
// Run the Tensorflow session.
TF_SessionRun(_session,
nullptr, // Run options.
&_inputNodes[0], // Input node names.
&_inputTensors[0], // input tensor values.
_nInputs + (int)_isTrainingSet, // Number of inputs.
&_outputNodes[0], // Output node names.
&_outputTensors[0], // Output tensor values.
_nOutputs, // Number of outputs.
nullptr, 0, // Target operations, number of targets.
nullptr, // Run metadata.
_status // Output status.
);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error running the Tensorflow session. ", TF_Message(_status));
}
// Copy the desired tensors into the output pool.
for (size_t i = 0; i < _nOutputs; i++) {
poolOut.set(_outputNames[i], TFToTensor(_outputTensors[i], _outputNodes[i]));
}
// Deallocate tensors.
for (size_t i = 0; i < _nInputs; i++) {
TF_DeleteTensor(_inputTensors[i]);
}
for (size_t i = 0; i < _nOutputs; i++) {
TF_DeleteTensor(_outputTensors[i]);
}
}
TF_Tensor* TensorflowPredict::TensorToTF(
const Tensor<Real>& tensorIn) {
int dims = 1;
vector<int64_t> shape;
// Batch dimensions is the only one allowed to be singleton
shape.push_back((int64_t)tensorIn.dimension(0));
if (_squeeze) {
for(int i = 1; i < tensorIn.rank(); i++) {
if (tensorIn.dimension(i) > 1) {
shape.push_back((int64_t)tensorIn.dimension(i));
dims++;
}
}
} else {
dims = tensorIn.rank();
for(int i = 1; i < dims; i++) {
shape.push_back((int64_t)tensorIn.dimension(i));
}
}
TF_Tensor* tensorOut = TF_AllocateTensor(
TF_FLOAT, &shape[0], dims,
(size_t)tensorIn.size() * sizeof(Real));
if (tensorOut == nullptr) {
throw EssentiaException("TensorflowPredict: Error generating input tensor.");
}
// Get a pointer to the data and fill the tensor.
void* tensorData = TF_TensorData(tensorOut);
if (tensorData == nullptr) {
TF_DeleteTensor(tensorOut);
throw EssentiaException("TensorflowPredict: Error generating input tensors data.");
}
memcpy(tensorData, tensorIn.data(),
std::min(tensorIn.size() * sizeof(Real),
TF_TensorByteSize(tensorOut)));
return tensorOut;
}
const Tensor<Real> TensorflowPredict::TFToTensor(
const TF_Tensor* tensor, TF_Output node) {
const Real* outputData = static_cast<Real*>(TF_TensorData(tensor));
// Get the output tensor's shape.
size_t outNDims = TF_GraphGetTensorNumDims(_graph, node, _status);
if (TF_GetCode(_status) != TF_OK) {
throw EssentiaException("TensorflowPredict: Error getting the output tensor's shape. ", TF_Message(_status));
}
// Create and array to store the shape of the tensor.
array<long int, 4> shape {1, 1, 1, 1};
shape[0] = (int)TF_Dim(tensor, 0);
// We are assuming one of the following cases:
// 1 - outNDims = 2 -> Batch + Feats
// 2 - outNDims = 3 -> Batch + Timestamps + Feats
// 3 - outNDims = 4 -> Batch + Channels + Timestamps + Feats
size_t idx = 1;
for (size_t i = shape.size() - outNDims + 1; i < shape.size(); i++, idx++) {
shape[i] = (int)TF_Dim(tensor, idx);
}
// Return a const reference to the data in Eigen format.
return TensorMap<const Real>(outputData, shape);
}
TF_Output TensorflowPredict::graphOperationByName(const string nodeName) {
int index = 0;
const char* name = nodeName.c_str();
// TensorFlow operations (or nodes from the graph perspective) return tensors named <nodeName:n>, where n goes
// from 0 to the number of outputs. The first output tensor of a node can be extracted implicitly (nodeName)
// or explicitly (nodeName:0). To extract the subsequent tensors, the index has to be specified (nodeName:1,
// nodeName:2).
string::size_type n = nodeName.find(':');
if (n != string::npos) {
index = stoi(nodeName.substr(n + 1));
name = nodeName.substr(0, n).c_str();
}
TF_Output output = {TF_GraphOperationByName(_graph, name), index};
if (output.oper == nullptr) {
throw EssentiaException("TensorflowPredict: '" + string(nodeName) +
"' is not a valid node name of this graph.\n" +
availableNodesInfo());
}
return output;
}
vector<string> TensorflowPredict::nodeNames() {
size_t pos = 0;
TF_Operation *oper;
vector<string> nodeNames;
while ((oper = TF_GraphNextOperation(_graph, &pos)) != nullptr) {
nodeNames.push_back(string(TF_OperationName(oper)));
}
return nodeNames;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "danceability.h"
using namespace std;
namespace essentia {
namespace standard {
const char* Danceability::name = "Danceability";
const char* Danceability::category = "Rhythm";
const char* Danceability::description = DOC("Calculates the danceability vector for a given signal. The algorithm is derived from Detrended Fluctuation Analysis (DFA) described in [1]. The parameters minTau and maxTau are used to define the range of time over which DFA will be performed. The output of this algorithm is the danceability of the audio signal. These values usually range from 0 to 3 (higher values meaning more danceable).\n\n"
"Exception is thrown when minTau is greater than maxTau.\n\n"
"References:\n"
" [1] Streich, S. and Herrera, P., Detrended Fluctuation Analysis of Music\n"
" Signals: Danceability Estimation and further Semantic Characterization,\n"
" Proceedings of the AES 118th Convention, Barcelona, Spain, 2005");
Real Danceability::stddev(const vector<Real>& array, int start, int end) const {
Real mean_array = mean(array, start, end);
Real var = 0.0;
for (int i=start; i<end; i++) {
Real d = array[i] - mean_array;
var += d*d;
}
return sqrt(var / (end - start - 1.0));
}
void Danceability::configure() {
Real minTau = parameter("minTau").toReal();
Real maxTau = parameter("maxTau").toReal();
Real tauIncrement = parameter("tauMultiplier").toReal();
if (minTau > maxTau) {
throw EssentiaException("Danceability: minTau cannot be larger than maximumTauInMs");
}
// tau is the number of blocks of 10ms we calculate each time
_tau.clear();
for (Real tau = minTau; tau <= maxTau; tau *= tauIncrement) {
_tau.push_back(int(tau / 10.0));
}
}
void Danceability::compute() {
const vector<Real>& signal = _signal.get();
Real& danceability = _danceability.get();
Real sampleRate = parameter("sampleRate").toReal();
//---------------------------------------------------------------------
// preprocessing:
// cut up into 10 ms frames and calculate the stddev for each slice
// store in s(n), then integrate
int numSamples = signal.size();
int frameSize = int(0.01 * sampleRate); // 10ms
int numFrames = numSamples / frameSize;
vector<Real> s(numFrames, 0.0);
for (int i=0; i<numFrames; i++) {
int frameBegin = i * frameSize;
int frameEnd = min((i+1) * frameSize, numSamples);
s[i] = stddev(signal, frameBegin, frameEnd);
}
// subtract the mean from the array to make it have 0 DC
Real mean_s = mean(s,0,s.size());
for (int i=0; i<numFrames; i++)
s[i] -= mean_s;
// integrate the signal
for (int i=1; i<(int)s.size(); i++)
s[i] += s[i-1];
//---------------------------------------------------------------------
// processing
vector<Real> F(_tau.size(), 0.0);
int nFValues = 0;
// for each tau (i.e. block size)
for (int i=0; i<(int)_tau.size(); i++) {
int tau = _tau[i];
// the original algorithm slides/jumps the blocks forward with
// one sample, but that's very CPU intensive.
// So, ... for large tau values, lets take larger jumps
int jump = max(tau/50, 1);
// perhaps we're working on a short file, then we don't have all values...
if(numFrames >= tau)
{
// cut up the audio in tau-sized blocks
for(int k=0; k<numFrames - tau; k += jump)
{
int frameBegin = k;
int frameEnd = k + tau;
// find the average residual error in this block
// the residual error is sum( squared( signal - linear_regression ) )
F[i] += residualError(s, frameBegin, frameEnd);
}
// the square root of the total residual error, for all the
// blocks of size tau
if (numFrames == tau) {
F[i] = 0.0;
}
else {
F[i] = sqrt(F[i] / ((Real)(numFrames - tau)/(Real)jump));
}
nFValues++;
}
else
{
break;
}
}
danceability = 0.0;
// the original article tells us: for small tau's we need to adjust alpha (danceability)
for (int i=0; i<nFValues - 1; i++) {
if (F[i+1] != 0.0) {
danceability += log10(F[i+1] / F[i]) / log10( ((Real)_tau[i+1]+3.0) / ((Real)_tau[i]+3.0));
cout << "DEBUG:" << danceability << "log(F[i+1]/F[i])" << log10(F[i+1] / F[i]) << "Denominator" << log10( ((Real)_tau[i+1]+3.0) / ((Real)_tau[i]+3.0)) << endl;
}
else {
danceability = 0.0;
return;
}
}
danceability /= (nFValues-1);
if (danceability != 0.0) {
danceability = 1.0 / danceability;
}
else {
danceability = 0.0;
}
}
} // namespace standard
} // namespace essentia
#include "poolstorage.h"
#include "algorithmfactory.h"
namespace essentia {
namespace streaming {
const char* Danceability::name = standard::Danceability::name;
const char* Danceability::category = standard::Danceability::category;
const char* Danceability::description = standard::Danceability::description;
Danceability::Danceability() : AlgorithmComposite() {
_danceabilityAlgo = standard::AlgorithmFactory::create("Danceability");
_poolStorage = new PoolStorage<Real>(&_pool, "internal.signal");
declareInput(_signal, 1, "signal", "the input signal");
declareOutput(_danceability, 0, "danceability", "the danceability value. Normal values range from 0 to ~3. The higher, the more danceable.");
_signal >> _poolStorage->input("data"); // attach input proxy
}
Danceability::~Danceability() {
delete _danceabilityAlgo;
delete _poolStorage;
}
void Danceability::reset() {
AlgorithmComposite::reset();
_poolStorage->reset();
}
AlgorithmStatus Danceability::process() {
if (!shouldStop()) return PASS;
Real danceability;
_danceabilityAlgo->input("signal").set(_pool.value<vector<Real> >("internal.signal"));
_danceabilityAlgo->output("danceability").set(danceability);
_danceabilityAlgo->compute();
_danceability.push(danceability);
return FINISHED;
}
} // namespace streaming
} // namespace essentia
<commit_msg>Remove debug prints in Danceability<commit_after>/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "danceability.h"
using namespace std;
namespace essentia {
namespace standard {
const char* Danceability::name = "Danceability";
const char* Danceability::category = "Rhythm";
const char* Danceability::description = DOC("Calculates the danceability vector for a given signal. The algorithm is derived from Detrended Fluctuation Analysis (DFA) described in [1]. The parameters minTau and maxTau are used to define the range of time over which DFA will be performed. The output of this algorithm is the danceability of the audio signal. These values usually range from 0 to 3 (higher values meaning more danceable).\n\n"
"Exception is thrown when minTau is greater than maxTau.\n\n"
"References:\n"
" [1] Streich, S. and Herrera, P., Detrended Fluctuation Analysis of Music\n"
" Signals: Danceability Estimation and further Semantic Characterization,\n"
" Proceedings of the AES 118th Convention, Barcelona, Spain, 2005");
Real Danceability::stddev(const vector<Real>& array, int start, int end) const {
Real mean_array = mean(array, start, end);
Real var = 0.0;
for (int i=start; i<end; i++) {
Real d = array[i] - mean_array;
var += d*d;
}
return sqrt(var / (end - start - 1.0));
}
void Danceability::configure() {
Real minTau = parameter("minTau").toReal();
Real maxTau = parameter("maxTau").toReal();
Real tauIncrement = parameter("tauMultiplier").toReal();
if (minTau > maxTau) {
throw EssentiaException("Danceability: minTau cannot be larger than maximumTauInMs");
}
// tau is the number of blocks of 10ms we calculate each time
_tau.clear();
for (Real tau = minTau; tau <= maxTau; tau *= tauIncrement) {
_tau.push_back(int(tau / 10.0));
}
}
void Danceability::compute() {
const vector<Real>& signal = _signal.get();
Real& danceability = _danceability.get();
Real sampleRate = parameter("sampleRate").toReal();
//---------------------------------------------------------------------
// preprocessing:
// cut up into 10 ms frames and calculate the stddev for each slice
// store in s(n), then integrate
int numSamples = signal.size();
int frameSize = int(0.01 * sampleRate); // 10ms
int numFrames = numSamples / frameSize;
vector<Real> s(numFrames, 0.0);
for (int i=0; i<numFrames; i++) {
int frameBegin = i * frameSize;
int frameEnd = min((i+1) * frameSize, numSamples);
s[i] = stddev(signal, frameBegin, frameEnd);
}
// subtract the mean from the array to make it have 0 DC
Real mean_s = mean(s,0,s.size());
for (int i=0; i<numFrames; i++)
s[i] -= mean_s;
// integrate the signal
for (int i=1; i<(int)s.size(); i++)
s[i] += s[i-1];
//---------------------------------------------------------------------
// processing
vector<Real> F(_tau.size(), 0.0);
int nFValues = 0;
// for each tau (i.e. block size)
for (int i=0; i<(int)_tau.size(); i++) {
int tau = _tau[i];
// the original algorithm slides/jumps the blocks forward with
// one sample, but that's very CPU intensive.
// So, ... for large tau values, lets take larger jumps
int jump = max(tau/50, 1);
// perhaps we're working on a short file, then we don't have all values...
if(numFrames >= tau)
{
// cut up the audio in tau-sized blocks
for(int k=0; k<numFrames - tau; k += jump)
{
int frameBegin = k;
int frameEnd = k + tau;
// find the average residual error in this block
// the residual error is sum( squared( signal - linear_regression ) )
F[i] += residualError(s, frameBegin, frameEnd);
}
// the square root of the total residual error, for all the
// blocks of size tau
if (numFrames == tau) {
F[i] = 0.0;
}
else {
F[i] = sqrt(F[i] / ((Real)(numFrames - tau)/(Real)jump));
}
nFValues++;
}
else
{
break;
}
}
danceability = 0.0;
// the original article tells us: for small tau's we need to adjust alpha (danceability)
for (int i=0; i<nFValues - 1; i++) {
if (F[i+1] != 0.0) {
danceability += log10(F[i+1] / F[i]) / log10( ((Real)_tau[i+1]+3.0) / ((Real)_tau[i]+3.0));
}
else {
danceability = 0.0;
return;
}
}
danceability /= (nFValues-1);
if (danceability != 0.0) {
danceability = 1.0 / danceability;
}
else {
danceability = 0.0;
}
}
} // namespace standard
} // namespace essentia
#include "poolstorage.h"
#include "algorithmfactory.h"
namespace essentia {
namespace streaming {
const char* Danceability::name = standard::Danceability::name;
const char* Danceability::category = standard::Danceability::category;
const char* Danceability::description = standard::Danceability::description;
Danceability::Danceability() : AlgorithmComposite() {
_danceabilityAlgo = standard::AlgorithmFactory::create("Danceability");
_poolStorage = new PoolStorage<Real>(&_pool, "internal.signal");
declareInput(_signal, 1, "signal", "the input signal");
declareOutput(_danceability, 0, "danceability", "the danceability value. Normal values range from 0 to ~3. The higher, the more danceable.");
_signal >> _poolStorage->input("data"); // attach input proxy
}
Danceability::~Danceability() {
delete _danceabilityAlgo;
delete _poolStorage;
}
void Danceability::reset() {
AlgorithmComposite::reset();
_poolStorage->reset();
}
AlgorithmStatus Danceability::process() {
if (!shouldStop()) return PASS;
Real danceability;
_danceabilityAlgo->input("signal").set(_pool.value<vector<Real> >("internal.signal"));
_danceabilityAlgo->output("danceability").set(danceability);
_danceabilityAlgo->compute();
_danceability.push(danceability);
return FINISHED;
}
} // namespace streaming
} // namespace essentia
<|endoftext|>
|
<commit_before>/*
* SessionHunspell.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionHunspell.hpp"
#if defined(_WIN32)
#elif defined(__APPLE__)
#include <dlfcn.h>
#else
#endif
#include <boost/utility.hpp>
#include <core/Error.hpp>
using namespace core;
namespace session {
namespace modules {
namespace spelling {
namespace hunspell {
namespace {
typedef struct Hunhandle Hunhandle;
typedef Hunhandle* (*PtrHunspellCreate)(const char*, const char*);
typedef void (*PtrHunspellDestroy)(Hunhandle*);
typedef int (*PtrHunspellSpell)(Hunhandle*,const char*);
typedef int (*PtrHunspellSuggest)(Hunhandle*, char***, const char*);
struct LibHunspell
{
LibHunspell()
: create(NULL),
destroy(NULL),
spell(NULL),
suggest(NULL)
{
}
PtrHunspellCreate create;
PtrHunspellDestroy destroy;
PtrHunspellSpell spell;
PtrHunspellSuggest suggest;
};
} // anonymous namespace
Error initialize()
{
#if defined(_WIN32)
#elif defined(__APPLE__)
LibHunspell hs;
void* pHunspell = ::dlopen("libhunspell-1.2.dylib",
RTLD_LAZY | RTLD_LOCAL | RTLD_FIRST);
if (pHunspell)
{
hs.create = (PtrHunspellCreate)::dlsym(pHunspell,"Hunspell_create");
hs.destroy = (PtrHunspellDestroy)::dlsym(pHunspell, "Hunspell_destroy");
hs.spell = (PtrHunspellSpell)::dlsym(pHunspell, "Hunspell_spell");
hs.suggest = (PtrHunspellSuggest)::dlsym(pHunspell, "Hunspell_suggest");
}
#else
#endif
return Success();
}
} // namespace hunspell
} // namespace spelling
} // namespace modules
} // namespace session
<commit_msg>experiment with dynamic hunspell loading on linux<commit_after>/*
* SessionHunspell.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionHunspell.hpp"
#ifndef _WIN32
#include <dlfcn.h>
#else
#endif
#include <boost/utility.hpp>
#include <core/Error.hpp>
using namespace core;
namespace session {
namespace modules {
namespace spelling {
namespace hunspell {
namespace {
typedef struct Hunhandle Hunhandle;
typedef Hunhandle* (*PtrHunspellCreate)(const char*, const char*);
typedef void (*PtrHunspellDestroy)(Hunhandle*);
typedef int (*PtrHunspellSpell)(Hunhandle*,const char*);
typedef int (*PtrHunspellSuggest)(Hunhandle*, char***, const char*);
struct LibHunspell
{
LibHunspell()
: create(NULL),
destroy(NULL),
spell(NULL),
suggest(NULL)
{
}
PtrHunspellCreate create;
PtrHunspellDestroy destroy;
PtrHunspellSpell spell;
PtrHunspellSuggest suggest;
};
} // anonymous namespace
Error initialize()
{
LibHunspell hs;
#if defined(_WIN32)
#else
#if defined(__APPLE__)
void* pHunspell = ::dlopen("libhunspell-1.2.dylib", RTLD_LAZY | RTLD_LOCAL);
#else
void* pHunspell = ::dlopen("libhunspell-1.2.so.0", RTLD_LAZY | RTLD_LOCAL);
#endif
if (pHunspell)
{
hs.create = (PtrHunspellCreate)::dlsym(pHunspell,"Hunspell_create");
hs.destroy = (PtrHunspellDestroy)::dlsym(pHunspell, "Hunspell_destroy");
hs.spell = (PtrHunspellSpell)::dlsym(pHunspell, "Hunspell_spell");
hs.suggest = (PtrHunspellSuggest)::dlsym(pHunspell, "Hunspell_suggest");
}
#endif
return Success();
}
} // namespace hunspell
} // namespace spelling
} // namespace modules
} // namespace session
<|endoftext|>
|
<commit_before>///
/// @file pi_deleglise_rivat_parallel2.cpp
/// @brief Parallel implementation of the Lagarias-Miller-Odlyzko prime
/// counting algorithm with the improvements of Deleglise and
/// Rivat. In this implementation the easy leaves have been
/// split up into clustered easy leaves and sparse easy leaves.
/// This implementation is based on the paper:
/// Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006,
/// pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <balance_S2_load.hpp>
#include <BitSieve.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>
#include <utils.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
/// For each prime calculate its first multiple >= low.
template <typename T1, typename T2>
void init_next_multiples(T1& next, T2& primes, int64_t size, int64_t low)
{
next.reserve(size);
next.push_back(0);
for (int64_t b = 1; b < size; b++)
{
int64_t prime = primes[b];
int64_t next_multiple = ((low + prime - 1) / prime) * prime;
next_multiple += prime * (~next_multiple & 1);
next.push_back(next_multiple);
}
}
template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Compute the S2 contribution for the interval
/// [low_process, low_process + segments * segment_size[.
/// The missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the calling (parent) S2 function.
///
int64_t S2_thread(int64_t x,
int64_t y,
int64_t z,
int64_t c,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
vector<int32_t>& pi,
vector<int32_t>& primes,
vector<int32_t>& lpf,
vector<int32_t>& mu,
vector<int64_t>& mu_sum,
vector<int64_t>& phi)
{
low += segment_size * segments_per_thread * thread_num;
limit = min(low + segment_size * segments_per_thread, limit);
int64_t pi_y = pi[y];
int64_t pi_sqrty = pi[isqrt(y)];
int64_t max_prime = min(isqrt(x / low), y);
int64_t max_index = pi[max_prime];
int64_t phi_size = pi[min(isqrt(z), max_prime)] + 1;
int64_t S2_thread = 0;
BitSieve sieve(segment_size);
vector<int32_t> counters(segment_size);
vector<int64_t> next;
init_next_multiples(next, primes, phi_size, low);
phi.resize(phi_size, 0);
mu_sum.resize(phi_size, 0);
// Process the segments assigned to the current thread
for (; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = c + 1;
// check if we need the sieve
if (c < phi_size)
{
sieve.memset(low);
// phi(y, i) nodes with i <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (int64_t i = 2; i <= c; i++)
{
int64_t k = next[i];
for (int64_t prime = primes[i]; k < high; k += prime * 2)
sieve.unset(k - low);
next[i] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
}
// For c + 1 <= b <= pi_sqrty
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (int64_t end = min(pi_sqrty, max_index); b <= end; b++)
{
int64_t prime = primes[b];
int64_t min_m = max(x / (prime * high), y / prime);
int64_t max_m = min(x / (prime * low), y);
if (prime >= max_m)
goto next_segment;
for (int64_t m = max_m; m > min_m; m--)
{
if (mu[m] != 0 && prime < lpf[m])
{
int64_t n = prime * m;
int64_t count = cnt_query(counters, (x / n) - low);
int64_t phi_xn = phi[b] + count;
S2_thread -= mu[m] * phi_xn;
mu_sum[b] -= mu[m];
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b < pi_y
// Find all special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (int64_t end = min(pi_y, max_index + 1); b < end; b++)
{
int64_t prime = primes[b];
int64_t l = pi[min(x / (prime * low), y)];
if (prime >= primes[l])
goto next_segment;
int64_t min_hard_leaf = max(x / (prime * high), y / prime);
min_hard_leaf = in_between(prime, min_hard_leaf, y);
int64_t min_trivial_leaf = min(x / (prime * prime), y);
int64_t min_clustered_easy_leaf = min(isqrt(x / prime), y);
int64_t min_sparse_easy_leaf = min(z / prime, y);
min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf);
min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf);
min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf);
// Find all trivial leaves which satisfy:
// phi(x / (primes[b] * primes[l]), b - 1) = 1
if (primes[l] > min_trivial_leaf)
{
int64_t l_min = pi[min_trivial_leaf];
S2_thread += l - l_min;
l = l_min;
}
// Find all clustered easy leaves which satisfy:
// x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
// And phi(x / n, b - 1) == phi(x / m, b - 1)
while (primes[l] > min_clustered_easy_leaf)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t phi_xn = pi[xn] - b + 2;
int64_t m = prime * primes[b + phi_xn - 1];
int64_t xm = max(x / m, min_clustered_easy_leaf);
int64_t l2 = pi[xm];
S2_thread += phi_xn * (l - l2);
l = l2;
}
// Find all sparse easy leaves which satisfy:
// x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
for (; primes[l] > min_sparse_easy_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
S2_thread += pi[xn] - b + 2;
}
if (b < phi_size)
{
// Find all hard leaves which satisfy:
// low <= (x / n) < high
for (; primes[l] > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_thread += phi_xn;
mu_sum[b]++;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
}
next_segment:;
}
return S2_thread;
}
/// Calculate the contribution of the special leaves.
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
int64_t y,
int64_t z,
int64_t c,
vector<int32_t>& primes,
vector<int32_t>& lpf,
vector<int32_t>& mu,
int threads)
{
int64_t limit = z + 1;
threads = validate_threads(threads, limit);
int64_t S2_total = 0;
int64_t low = 1;
int64_t sqrt_limit = isqrt(limit);
int64_t logx = max(1, ilog(x));
int64_t min_segment_size = 1 << 6;
int64_t segments_per_thread = 1;
int64_t segment_size = next_power_of_2(sqrt_limit / (logx * threads));
segment_size = max(segment_size, min_segment_size);
double relative_standard_deviation = 30;
vector<int32_t> pi = make_pi(y);
vector<int64_t> phi_total(pi[min(isqrt(z), y)] + 1, 0);
while (low < limit)
{
int64_t segments = (limit - low + segment_size - 1) / segment_size;
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads);
aligned_vector<vector<int64_t> > phi(threads);
aligned_vector<vector<int64_t> > mu_sum(threads);
aligned_vector<double> timings(threads);
#pragma omp parallel for num_threads(threads) reduction(+: S2_total)
for (int i = 0; i < threads; i++)
{
timings[i] = get_wtime();
S2_total += S2_thread(x, y, z, c, segment_size, segments_per_thread,
i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]);
timings[i] = get_wtime() - timings[i];
}
// Once all threads have finished reconstruct and add the
// missing contribution of all special leaves. This must
// be done in order as each thread (i) requires the sum of
// the phi values from the previous threads.
//
for (int i = 0; i < threads; i++)
{
for (size_t j = 1; j < phi[i].size(); j++)
{
S2_total += phi_total[j] * mu_sum[i][j];
phi_total[j] += phi[i][j];
}
}
low += segments_per_thread * threads * segment_size;
balance_S2_load(&segment_size, &segments_per_thread, min_segment_size,
sqrt_limit, &relative_standard_deviation, timings);
}
return S2_total;
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log x) space.
///
int64_t pi_deleglise_rivat_parallel2(int64_t x, int threads)
{
if (x < 2)
return 0;
// alpha is a tuning factor
double d = (double) x;
double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x));
int64_t y = (int64_t) (alpha * iroot<3>(x));
int64_t z = x / y;
vector<int32_t> mu = make_moebius(y);
vector<int32_t> lpf = make_least_prime_factor(y);
vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_primes(y, &primes);
int64_t pi_y = pi_bsearch(primes, y);
int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
int64_t s1 = S1(x, y, c, primes, lpf , mu);
int64_t s2 = S2(x, y, z, c, primes, lpf , mu, threads);
int64_t p2 = P2(x, y, threads);
int64_t phi = s1 + s2;
int64_t sum = phi + pi_y - 1 - p2;
return sum;
}
} // namespace primecount
<commit_msg>Add assertions for easy leaves<commit_after>///
/// @file pi_deleglise_rivat_parallel2.cpp
/// @brief Parallel implementation of the Lagarias-Miller-Odlyzko prime
/// counting algorithm with the improvements of Deleglise and
/// Rivat. In this implementation the easy leaves have been
/// split up into clustered easy leaves and sparse easy leaves.
/// This implementation is based on the paper:
/// Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006,
/// pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <balance_S2_load.hpp>
#include <BitSieve.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>
#include <utils.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
/// For each prime calculate its first multiple >= low.
template <typename T1, typename T2>
void init_next_multiples(T1& next, T2& primes, int64_t size, int64_t low)
{
next.reserve(size);
next.push_back(0);
for (int64_t b = 1; b < size; b++)
{
int64_t prime = primes[b];
int64_t next_multiple = ((low + prime - 1) / prime) * prime;
next_multiple += prime * (~next_multiple & 1);
next.push_back(next_multiple);
}
}
template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Compute the S2 contribution for the interval
/// [low_process, low_process + segments * segment_size[.
/// The missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the calling (parent) S2 function.
///
int64_t S2_thread(int64_t x,
int64_t y,
int64_t z,
int64_t c,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
vector<int32_t>& pi,
vector<int32_t>& primes,
vector<int32_t>& lpf,
vector<int32_t>& mu,
vector<int64_t>& mu_sum,
vector<int64_t>& phi)
{
low += segment_size * segments_per_thread * thread_num;
limit = min(low + segment_size * segments_per_thread, limit);
int64_t pi_y = pi[y];
int64_t pi_sqrty = pi[isqrt(y)];
int64_t max_prime = min(isqrt(x / low), y);
int64_t max_index = pi[max_prime];
int64_t phi_size = pi[min(isqrt(z), max_prime)] + 1;
int64_t S2_thread = 0;
BitSieve sieve(segment_size);
vector<int32_t> counters(segment_size);
vector<int64_t> next;
init_next_multiples(next, primes, phi_size, low);
phi.resize(phi_size, 0);
mu_sum.resize(phi_size, 0);
// Process the segments assigned to the current thread
for (; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = c + 1;
// check if we need the sieve
if (c < phi_size)
{
sieve.memset(low);
// phi(y, i) nodes with i <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (int64_t i = 2; i <= c; i++)
{
int64_t k = next[i];
for (int64_t prime = primes[i]; k < high; k += prime * 2)
sieve.unset(k - low);
next[i] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
}
// For c + 1 <= b <= pi_sqrty
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (int64_t end = min(pi_sqrty, max_index); b <= end; b++)
{
int64_t prime = primes[b];
int64_t min_m = max(x / (prime * high), y / prime);
int64_t max_m = min(x / (prime * low), y);
if (prime >= max_m)
goto next_segment;
for (int64_t m = max_m; m > min_m; m--)
{
if (mu[m] != 0 && prime < lpf[m])
{
int64_t n = prime * m;
int64_t count = cnt_query(counters, (x / n) - low);
int64_t phi_xn = phi[b] + count;
S2_thread -= mu[m] * phi_xn;
mu_sum[b] -= mu[m];
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b < pi_y
// Find all special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (int64_t end = min(pi_y, max_index + 1); b < end; b++)
{
int64_t prime = primes[b];
int64_t l = pi[min(x / (prime * low), y)];
if (prime >= primes[l])
goto next_segment;
int64_t min_hard_leaf = max(x / (prime * high), y / prime);
min_hard_leaf = in_between(prime, min_hard_leaf, y);
int64_t min_trivial_leaf = min(x / (prime * prime), y);
int64_t min_clustered_easy_leaf = min(isqrt(x / prime), y);
int64_t min_sparse_easy_leaf = min(z / prime, y);
min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf);
min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf);
min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf);
// Find all trivial leaves which satisfy:
// phi(x / (primes[b] * primes[l]), b - 1) = 1
if (primes[l] > min_trivial_leaf)
{
int64_t l_min = pi[min_trivial_leaf];
S2_thread += l - l_min;
l = l_min;
}
// Find all clustered easy leaves which satisfy:
// x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
// And phi(x / n, b - 1) == phi(x / m, b - 1)
while (primes[l] > min_clustered_easy_leaf)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
assert(xn < isquare(primes[b]));
int64_t phi_xn = pi[xn] - b + 2;
int64_t m = prime * primes[b + phi_xn - 1];
int64_t xm = max(x / m, min_clustered_easy_leaf);
int64_t l2 = pi[xm];
S2_thread += phi_xn * (l - l2);
l = l2;
}
// Find all sparse easy leaves which satisfy:
// x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
for (; primes[l] > min_sparse_easy_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
assert(xn < isquare(primes[b]));
S2_thread += pi[xn] - b + 2;
}
if (b < phi_size)
{
// Find all hard leaves which satisfy:
// low <= (x / n) < high
for (; primes[l] > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_thread += phi_xn;
mu_sum[b]++;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
}
next_segment:;
}
return S2_thread;
}
/// Calculate the contribution of the special leaves.
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
int64_t y,
int64_t z,
int64_t c,
vector<int32_t>& primes,
vector<int32_t>& lpf,
vector<int32_t>& mu,
int threads)
{
int64_t limit = z + 1;
threads = validate_threads(threads, limit);
int64_t S2_total = 0;
int64_t low = 1;
int64_t sqrt_limit = isqrt(limit);
int64_t logx = max(1, ilog(x));
int64_t min_segment_size = 1 << 6;
int64_t segments_per_thread = 1;
int64_t segment_size = next_power_of_2(sqrt_limit / (logx * threads));
segment_size = max(segment_size, min_segment_size);
double relative_standard_deviation = 30;
vector<int32_t> pi = make_pi(y);
vector<int64_t> phi_total(pi[min(isqrt(z), y)] + 1, 0);
while (low < limit)
{
int64_t segments = (limit - low + segment_size - 1) / segment_size;
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads);
aligned_vector<vector<int64_t> > phi(threads);
aligned_vector<vector<int64_t> > mu_sum(threads);
aligned_vector<double> timings(threads);
#pragma omp parallel for num_threads(threads) reduction(+: S2_total)
for (int i = 0; i < threads; i++)
{
timings[i] = get_wtime();
S2_total += S2_thread(x, y, z, c, segment_size, segments_per_thread,
i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i]);
timings[i] = get_wtime() - timings[i];
}
// Once all threads have finished reconstruct and add the
// missing contribution of all special leaves. This must
// be done in order as each thread (i) requires the sum of
// the phi values from the previous threads.
//
for (int i = 0; i < threads; i++)
{
for (size_t j = 1; j < phi[i].size(); j++)
{
S2_total += phi_total[j] * mu_sum[i][j];
phi_total[j] += phi[i][j];
}
}
low += segments_per_thread * threads * segment_size;
balance_S2_load(&segment_size, &segments_per_thread, min_segment_size,
sqrt_limit, &relative_standard_deviation, timings);
}
return S2_total;
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log x) space.
///
int64_t pi_deleglise_rivat_parallel2(int64_t x, int threads)
{
if (x < 2)
return 0;
// alpha is a tuning factor
double d = (double) x;
double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x));
int64_t y = (int64_t) (alpha * iroot<3>(x));
int64_t z = x / y;
vector<int32_t> mu = make_moebius(y);
vector<int32_t> lpf = make_least_prime_factor(y);
vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_primes(y, &primes);
int64_t pi_y = pi_bsearch(primes, y);
int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
int64_t s1 = S1(x, y, c, primes, lpf , mu);
int64_t s2 = S2(x, y, z, c, primes, lpf , mu, threads);
int64_t p2 = P2(x, y, threads);
int64_t phi = s1 + s2;
int64_t sum = phi + pi_y - 1 - p2;
return sum;
}
} // namespace primecount
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2012, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "backward_file_reader.h"
BackwardFileReader::BWReaderBuffer::BWReaderBuffer(int cb/*=0*/, char * input /* = NULL*/)
: data(input)
, cbData(cb)
, cbAlloc(cb)
, at_eof(false)
, text_mode(false)
, error(0)
{
if (input) {
cbAlloc = cbData = cb;
} else if (cb > 0) {
data = (char*)malloc(cb);
if (data) memset(data, 17, cb);
cbData = 0;
}
}
void BackwardFileReader::BWReaderBuffer::setsize(int cb)
{
cbData = cb;
ASSERT(cbData <= cbAlloc);
}
bool BackwardFileReader::BWReaderBuffer::reserve(int cb)
{
if (data && cbAlloc >= cb)
return true;
void * pv = realloc(data, cb);
if (pv) {
data = (char*)pv;
cbAlloc = cb;
return true;
}
return false;
}
int BackwardFileReader::BWReaderBuffer::fread_at(FILE * file, off_t offset, int cb)
{
if ( ! reserve(((cb + 16) & ~15) + 16))
return 0;
int ret = fseek(file, offset, SEEK_SET);
if (ret <= 0) {
error = ferror(file);
return 0;
} else {
error = 0;
}
ret = (int)fread(data, 1, cb, file);
cbData = ret;
if (ret <= 0) {
error = ferror(file);
return 0;
} else {
error = 0;
}
// on windows in text mode we can consume more than we read because of \r
// but since we are scanning backward this can cause us to re-read
// the same bytes more than once. So lop off the end of the buffer so
// so we only get back the unique bytes
at_eof = feof(file);
if (text_mode && ! at_eof) {
off_t end_offset = ftell(file);
int extra = (int)(end_offset - (offset + ret));
ret -= extra;
}
if (ret < cbAlloc) {
data[ret] = 0; // force null terminate.
} else {
// this should NOT happen
EXCEPT("BWReadBuffer is unexpectedly too small!");
}
return ret;
}
BackwardFileReader::BackwardFileReader(std::string filename, int open_flags)
: error(0), file(NULL), cbFile(0), cbPos(0)
{
#ifdef WIN32
open_flags |= O_BINARY;
#endif
int fd = safe_open_wrapper_follow(filename.c_str(), open_flags);
if (fd < 0)
error = errno;
else if ( ! OpenFile(fd, "rb"))
close(fd);
}
BackwardFileReader::BackwardFileReader(int fd, const char * open_options)
: error(0), file(NULL), cbFile(0), cbPos(0)
{
OpenFile(fd, open_options);
}
/*
BackwardFileReader::~BackwardFileReader()
{
if (file) fclose(file);
file = NULL;
}
*/
bool BackwardFileReader::PrevLine(std::string & str)
{
str.clear();
// can we get a previous line out of our existing buffer?
// then do that.
if (PrevLineFromBuf(str))
return true;
// no line in the buffer? then return false
if (AtBOF())
return false;
const int cbBack = 512;
while (true) {
int off = cbPos > cbBack ? cbPos - cbBack : 0;
int cbToRead = (int)(cbPos - off);
// we want to read in cbBack chunks at cbBack aligment, of course
// this only makes sense to do if cbBack is a power of 2.
// also, in order to get EOF to register, we have to read a little
// so we may want the first read (from the end, of course) to be a bit
// larger than cbBack so that we read at least cbBack but also end up
// on cbBack alignment.
if (cbFile == cbPos) {
// test to see if cbBack is a power of 2, if it is, then set our
// seek to align on cbBack.
if (!(cbBack & (cbBack-1))) {
// seek to an even multiple of cbBack at least cbBack from the end of the file.
off = (cbFile - cbBack) & ~(cbBack-1);
cbToRead = cbFile - off;
}
cbToRead += 16;
}
if ( ! buf.fread_at(file, off, cbToRead)) {
if (buf.LastError()) {
error = buf.LastError();
return false;
}
}
cbPos = off;
// try again to get some data from the buffer
if (PrevLineFromBuf(str) || AtBOF())
return true;
}
}
bool BackwardFileReader::OpenFile(int fd, const char * open_options)
{
file = fdopen(fd, open_options);
if ( ! file) {
error = errno;
} else {
// seek to the end of the file.
fseek(file, 0, SEEK_END);
cbFile = cbPos = ftell(file);
error = 0;
buf.SetTextMode( ! strchr(open_options,'b'));
}
return error == 0;
}
// prefixes or part of a line into str, and updates internal
// variables to keep track of what parts of the buffer have been returned.
bool BackwardFileReader::PrevLineFromBuf(std::string & str)
{
// if we have no buffered data, then there is nothing to do
int cb = buf.size();
if (cb <= 0)
return false;
// if buffer ends in a newline, convert it to a \0
if (buf[cb-1] == '\n') {
buf[--cb] = 0;
// if the input string is not empty, then the previous
// buffer ended _exactly_ at a newline boundary, so return
// the string rather than concatinating it to the newline.
if ( ! str.empty()) {
if (buf[cb-1] == '\r')
buf[--cb] = 0;
buf.setsize(cb);
return true;
}
}
// because of windows style \r\n, we also tolerate a \r at the end of the line
if (buf[cb-1] == '\r') {
buf[--cb] = 0;
}
// now we walk backward through the buffer until we encounter another newline
// returning all of the characters that we found.
while (cb > 0) {
if (buf[--cb] == '\n') {
str.insert(0, &buf[cb+1]);
buf[cb] = 0;
buf.setsize(cb);
return true;
}
}
// we hit the start of the buffer without finding another newline,
// so return that text, but only return true if we are also at the start
// of the file.
str.insert(0, &buf[0]);
buf[0] = 0;
buf.clear();
return (0 == cbPos);
}
<commit_msg>Fix typo in last commit #6345<commit_after>/***************************************************************
*
* Copyright (C) 1990-2012, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "backward_file_reader.h"
BackwardFileReader::BWReaderBuffer::BWReaderBuffer(int cb/*=0*/, char * input /* = NULL*/)
: data(input)
, cbData(cb)
, cbAlloc(cb)
, at_eof(false)
, text_mode(false)
, error(0)
{
if (input) {
cbAlloc = cbData = cb;
} else if (cb > 0) {
data = (char*)malloc(cb);
if (data) memset(data, 17, cb);
cbData = 0;
}
}
void BackwardFileReader::BWReaderBuffer::setsize(int cb)
{
cbData = cb;
ASSERT(cbData <= cbAlloc);
}
bool BackwardFileReader::BWReaderBuffer::reserve(int cb)
{
if (data && cbAlloc >= cb)
return true;
void * pv = realloc(data, cb);
if (pv) {
data = (char*)pv;
cbAlloc = cb;
return true;
}
return false;
}
int BackwardFileReader::BWReaderBuffer::fread_at(FILE * file, off_t offset, int cb)
{
if ( ! reserve(((cb + 16) & ~15) + 16))
return 0;
int ret = fseek(file, offset, SEEK_SET);
if (ret < 0) {
error = ferror(file);
return 0;
} else {
error = 0;
}
ret = (int)fread(data, 1, cb, file);
cbData = ret;
if (ret <= 0) {
error = ferror(file);
return 0;
} else {
error = 0;
}
// on windows in text mode we can consume more than we read because of \r
// but since we are scanning backward this can cause us to re-read
// the same bytes more than once. So lop off the end of the buffer so
// so we only get back the unique bytes
at_eof = feof(file);
if (text_mode && ! at_eof) {
off_t end_offset = ftell(file);
int extra = (int)(end_offset - (offset + ret));
ret -= extra;
}
if (ret < cbAlloc) {
data[ret] = 0; // force null terminate.
} else {
// this should NOT happen
EXCEPT("BWReadBuffer is unexpectedly too small!");
}
return ret;
}
BackwardFileReader::BackwardFileReader(std::string filename, int open_flags)
: error(0), file(NULL), cbFile(0), cbPos(0)
{
#ifdef WIN32
open_flags |= O_BINARY;
#endif
int fd = safe_open_wrapper_follow(filename.c_str(), open_flags);
if (fd < 0)
error = errno;
else if ( ! OpenFile(fd, "rb"))
close(fd);
}
BackwardFileReader::BackwardFileReader(int fd, const char * open_options)
: error(0), file(NULL), cbFile(0), cbPos(0)
{
OpenFile(fd, open_options);
}
/*
BackwardFileReader::~BackwardFileReader()
{
if (file) fclose(file);
file = NULL;
}
*/
bool BackwardFileReader::PrevLine(std::string & str)
{
str.clear();
// can we get a previous line out of our existing buffer?
// then do that.
if (PrevLineFromBuf(str))
return true;
// no line in the buffer? then return false
if (AtBOF())
return false;
const int cbBack = 512;
while (true) {
int off = cbPos > cbBack ? cbPos - cbBack : 0;
int cbToRead = (int)(cbPos - off);
// we want to read in cbBack chunks at cbBack aligment, of course
// this only makes sense to do if cbBack is a power of 2.
// also, in order to get EOF to register, we have to read a little
// so we may want the first read (from the end, of course) to be a bit
// larger than cbBack so that we read at least cbBack but also end up
// on cbBack alignment.
if (cbFile == cbPos) {
// test to see if cbBack is a power of 2, if it is, then set our
// seek to align on cbBack.
if (!(cbBack & (cbBack-1))) {
// seek to an even multiple of cbBack at least cbBack from the end of the file.
off = (cbFile - cbBack) & ~(cbBack-1);
cbToRead = cbFile - off;
}
cbToRead += 16;
}
if ( ! buf.fread_at(file, off, cbToRead)) {
if (buf.LastError()) {
error = buf.LastError();
return false;
}
}
cbPos = off;
// try again to get some data from the buffer
if (PrevLineFromBuf(str) || AtBOF())
return true;
}
}
bool BackwardFileReader::OpenFile(int fd, const char * open_options)
{
file = fdopen(fd, open_options);
if ( ! file) {
error = errno;
} else {
// seek to the end of the file.
fseek(file, 0, SEEK_END);
cbFile = cbPos = ftell(file);
error = 0;
buf.SetTextMode( ! strchr(open_options,'b'));
}
return error == 0;
}
// prefixes or part of a line into str, and updates internal
// variables to keep track of what parts of the buffer have been returned.
bool BackwardFileReader::PrevLineFromBuf(std::string & str)
{
// if we have no buffered data, then there is nothing to do
int cb = buf.size();
if (cb <= 0)
return false;
// if buffer ends in a newline, convert it to a \0
if (buf[cb-1] == '\n') {
buf[--cb] = 0;
// if the input string is not empty, then the previous
// buffer ended _exactly_ at a newline boundary, so return
// the string rather than concatinating it to the newline.
if ( ! str.empty()) {
if (buf[cb-1] == '\r')
buf[--cb] = 0;
buf.setsize(cb);
return true;
}
}
// because of windows style \r\n, we also tolerate a \r at the end of the line
if (buf[cb-1] == '\r') {
buf[--cb] = 0;
}
// now we walk backward through the buffer until we encounter another newline
// returning all of the characters that we found.
while (cb > 0) {
if (buf[--cb] == '\n') {
str.insert(0, &buf[cb+1]);
buf[cb] = 0;
buf.setsize(cb);
return true;
}
}
// we hit the start of the buffer without finding another newline,
// so return that text, but only return true if we are also at the start
// of the file.
str.insert(0, &buf[0]);
buf[0] = 0;
buf.clear();
return (0 == cbPos);
}
<|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2013-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* 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.
*
*********************************************************************************/
#include <inviwo/core/interaction/pickingcontainer.h>
#include <inviwo/core/interaction/pickingmanager.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/interaction/events/mouseevent.h>
namespace inviwo {
PickingContainer::PickingContainer()
: src_(nullptr)
, mousePickObj_(nullptr)
, prevMouseCoord_(uvec2(0, 0))
, mousePickingOngoing_(false)
, mouseIsDown_(false)
, touchPickingOn_(false)
{}
PickingContainer::~PickingContainer() {}
bool PickingContainer::pickingEnabled() {
return PickingManager::getPtr()->pickingEnabled();
}
bool PickingContainer::performMousePick(MouseEvent* e) {
if (!pickingEnabled() || e->button() == MouseEvent::MOUSE_BUTTON_NONE)
return false;
if (touchPickingOn_)
return true;
if (e->state() == MouseEvent::MOUSE_STATE_RELEASE){
mouseIsDown_ = false;
mousePickingOngoing_ = false;
mousePickObj_ = nullptr;
return false;
}
else if (!mouseIsDown_ || e->state() == MouseEvent::MOUSE_STATE_PRESS){
mouseIsDown_ = true;
uvec2 coord = clampToScreenCoords(e->pos(), e->canvasSize());
prevMouseCoord_ = coord;
mousePickObj_ = findPickingObject(coord);
if (mousePickObj_) {
mousePickingOngoing_ = true;
mousePickObj_->setPickingPosition(normalizedCoordinates(coord));
mousePickObj_->setPickingDepth(e->depth());
mousePickObj_->setPickingMouseEvent(*e);
mousePickObj_->setPickingMove(vec2(0.f, 0.f));
mousePickObj_->picked();
return true;
}
else{
mousePickingOngoing_ = false;
return false;
}
}
else if (e->state() == MouseEvent::MOUSE_STATE_MOVE){
if (mousePickingOngoing_){
uvec2 coord = clampToScreenCoords(e->pos(), e->canvasSize());
mousePickObj_->setPickingMove(normalizedMovement(prevMouseCoord_, coord));
mousePickObj_->setPickingMouseEvent(*e);
prevMouseCoord_ = coord;
mousePickObj_->picked();
return true;
}
else
return false;
}
return false;
}
bool PickingContainer::performTouchPick(TouchEvent* e) {
if (!pickingEnabled())
return false;
std::vector<TouchPoint>& touchPoints = e->getTouchPoints();
// Clear the picked touch point map
pickedTouchPoints_.clear();
if (touchPoints.size() > 1 || touchPoints[0].state() != TouchPoint::TOUCH_STATE_ENDED)
touchPickingOn_ = true;
else
touchPickingOn_ = false;
std::unordered_map<int, PickingObject*>::iterator touchPickObjs_it;
std::unordered_map<PickingObject*, std::vector<TouchPoint>>::iterator pickedTouchPoints_it;
auto touchPoint = touchPoints.begin();
while (touchPoint != touchPoints.end()) {
bool isAssociated = false;
if (touchPoint->state() == TouchPoint::TOUCH_STATE_STARTED) {
// Find out if new touch point is touching inside a picking object
uvec2 coord = clampToScreenCoords(touchPoint->getPos(), e->canvasSize());
PickingObject* pickObj = findPickingObject(coord);
// If it is, put it in the TouchIDPickingMap
if (pickObj) {
touchPickObjs_.insert(std::pair<int, PickingObject*>(touchPoint->getId(), pickObj));
// Associate touch point with picking object
// which can already have other associated touch points.
pickedTouchPoints_it = pickedTouchPoints_.find(pickObj);
if (pickedTouchPoints_it != pickedTouchPoints_.end()){
pickedTouchPoints_it->second.push_back(*touchPoint);
}
else{
pickedTouchPoints_.insert(std::pair<PickingObject*,
std::vector<TouchPoint>>(pickObj, std::vector<TouchPoint>{*touchPoint}));
}
isAssociated = true;
}
}
else if (touchPoint->state() == TouchPoint::TOUCH_STATE_ENDED) {
// Erase touch point from TouchIDPickingMap
size_t numberOfErasedElements = touchPickObjs_.erase(touchPoint->getId());
isAssociated = (numberOfErasedElements > 0);
}
else {
// Find out if touch point is in the TouchIDPickingMap
// If it exists, associate touch point with picking object
touchPickObjs_it = touchPickObjs_.find(touchPoint->getId());
if (touchPickObjs_it != touchPickObjs_.end()){
// Associate touch point with picking object
// which can already have other associated touch points.
pickedTouchPoints_it = pickedTouchPoints_.find(touchPickObjs_it->second);
if (pickedTouchPoints_it != pickedTouchPoints_.end()){
pickedTouchPoints_it->second.push_back(*touchPoint);
}
else{
pickedTouchPoints_.insert(std::pair<PickingObject*,
std::vector<TouchPoint>>(touchPickObjs_it->second, std::vector<TouchPoint>{*touchPoint}));
}
isAssociated = true;
}
}
// Removed touch point from the actual event if it was associated with a picking object
if (isAssociated)
touchPoint = touchPoints.erase(touchPoint);
else
++touchPoint;
}
// Build touch event for all picking objects with associated touch points
for (pickedTouchPoints_it = pickedTouchPoints_.begin(); pickedTouchPoints_it != pickedTouchPoints_.end(); ++pickedTouchPoints_it){
// Treat one touch point the same as mouse event, for now
if (pickedTouchPoints_it->second.size() == 1){
uvec2 coord = clampToScreenCoords(pickedTouchPoints_it->second[0].getPos(), e->canvasSize());
if (pickedTouchPoints_it->second[0].state() & TouchPoint::TOUCH_STATE_STARTED){
pickedTouchPoints_it->first->setPickingPosition(normalizedCoordinates(coord));
pickedTouchPoints_it->first->setPickingDepth(pickedTouchPoints_it->second[0].getDepth());
pickedTouchPoints_it->first->setPickingMove(vec2(0.f, 0.f));
}
else{
uvec2 prevCoord = clampToScreenCoords(pickedTouchPoints_it->second[0].getPrevPos(), e->canvasSize());
pickedTouchPoints_it->first->setPickingMove(normalizedMovement(prevCoord, coord));
}
// One touch point is currently treated as mouse event as well...
// So prepare for that
prevMouseCoord_ = coord;
mousePickObj_ = pickedTouchPoints_it->first;
mousePickingOngoing_ = true;
}
pickedTouchPoints_it->first->setPickingTouchEvent(TouchEvent(pickedTouchPoints_it->second, e->canvasSize()));
}
// One touch point is currently treated as mouse event as well...
// So prepare for that
if (touchPoints.size() == 1){
prevMouseCoord_ = clampToScreenCoords(touchPoints[0].getPos(), e->canvasSize());
touchPickingOn_ = false;
}
// Mark all picking objects in TouchIDPickingMap as picked.
for (touchPickObjs_it = touchPickObjs_.begin(); touchPickObjs_it != touchPickObjs_.end(); ++touchPickObjs_it)
touchPickObjs_it->second->picked();
return !touchPickObjs_.empty();
}
void PickingContainer::setPickingSource(std::shared_ptr<const Image> src) {
src_ = src;
}
PickingObject* PickingContainer::findPickingObject(const uvec2& coord){
if (pickingEnabled() && src_) {
const Layer* pickingLayer = src_->getPickingLayer();
if (pickingLayer) {
const LayerRAM* pickingLayerRAM = pickingLayer->getRepresentation<LayerRAM>();
dvec4 value = pickingLayerRAM->getAsNormalizedDVec4(coord);
dvec3 pickedColor = (value.a > 0.0 ? value.rgb() : dvec3(0.0));
uvec3 color(pickedColor*255.0);
return PickingManager::getPtr()->getPickingObjectFromColor(color);
}
}
return nullptr;
}
vec2 PickingContainer::normalizedMovement(const uvec2& previous, const uvec2& current) const {
return normalizedCoordinates(current - previous);
}
vec2 PickingContainer::normalizedCoordinates(const uvec2& coord) const {
return vec2(coord) / vec2(src_->getDimensions());
}
uvec2 PickingContainer::clampToScreenCoords(ivec2 mpos, ivec2 dim) {
ivec2 pos = mpos;
pos.x = std::max(pos.x - 1, 0);
pos.x = std::min(pos.x, dim.x - 1);
pos.y = std::max(dim.y - pos.y - 1, 0);
pos.y = std::min(pos.y, dim.y - 1);
return uvec2(pos);
}
} // namespace<commit_msg>Core interaction: extended picking events by mouse release, issue inviwo/inviwo-dev#1212<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2013-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* 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.
*
*********************************************************************************/
#include <inviwo/core/interaction/pickingcontainer.h>
#include <inviwo/core/interaction/pickingmanager.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/interaction/events/mouseevent.h>
namespace inviwo {
PickingContainer::PickingContainer()
: src_(nullptr)
, mousePickObj_(nullptr)
, prevMouseCoord_(uvec2(0, 0))
, mousePickingOngoing_(false)
, mouseIsDown_(false)
, touchPickingOn_(false)
{}
PickingContainer::~PickingContainer() {}
bool PickingContainer::pickingEnabled() {
return PickingManager::getPtr()->pickingEnabled();
}
bool PickingContainer::performMousePick(MouseEvent* e) {
if (!pickingEnabled() || e->button() == MouseEvent::MOUSE_BUTTON_NONE)
return false;
if (touchPickingOn_)
return true;
if (e->state() == MouseEvent::MOUSE_STATE_RELEASE){
mouseIsDown_ = false;
if (mousePickingOngoing_) {
uvec2 coord = clampToScreenCoords(e->pos(), e->canvasSize());
mousePickObj_->setPickingMove(normalizedMovement(prevMouseCoord_, coord));
mousePickObj_->setPickingMouseEvent(*e);
prevMouseCoord_ = coord;
mousePickObj_->picked();
mousePickingOngoing_ = false;
return true;
}
else {
mousePickObj_ = nullptr;
return false;
}
}
else if (!mouseIsDown_ || e->state() == MouseEvent::MOUSE_STATE_PRESS){
mouseIsDown_ = true;
uvec2 coord = clampToScreenCoords(e->pos(), e->canvasSize());
prevMouseCoord_ = coord;
mousePickObj_ = findPickingObject(coord);
if (mousePickObj_) {
mousePickingOngoing_ = true;
mousePickObj_->setPickingPosition(normalizedCoordinates(coord));
mousePickObj_->setPickingDepth(e->depth());
mousePickObj_->setPickingMouseEvent(*e);
mousePickObj_->setPickingMove(vec2(0.f, 0.f));
mousePickObj_->picked();
return true;
}
else{
mousePickingOngoing_ = false;
return false;
}
}
else if (e->state() == MouseEvent::MOUSE_STATE_MOVE){
if (mousePickingOngoing_){
uvec2 coord = clampToScreenCoords(e->pos(), e->canvasSize());
mousePickObj_->setPickingMove(normalizedMovement(prevMouseCoord_, coord));
mousePickObj_->setPickingMouseEvent(*e);
prevMouseCoord_ = coord;
mousePickObj_->picked();
return true;
}
else
return false;
}
return false;
}
bool PickingContainer::performTouchPick(TouchEvent* e) {
if (!pickingEnabled())
return false;
std::vector<TouchPoint>& touchPoints = e->getTouchPoints();
// Clear the picked touch point map
pickedTouchPoints_.clear();
if (touchPoints.size() > 1 || touchPoints[0].state() != TouchPoint::TOUCH_STATE_ENDED)
touchPickingOn_ = true;
else
touchPickingOn_ = false;
std::unordered_map<int, PickingObject*>::iterator touchPickObjs_it;
std::unordered_map<PickingObject*, std::vector<TouchPoint>>::iterator pickedTouchPoints_it;
auto touchPoint = touchPoints.begin();
while (touchPoint != touchPoints.end()) {
bool isAssociated = false;
if (touchPoint->state() == TouchPoint::TOUCH_STATE_STARTED) {
// Find out if new touch point is touching inside a picking object
uvec2 coord = clampToScreenCoords(touchPoint->getPos(), e->canvasSize());
PickingObject* pickObj = findPickingObject(coord);
// If it is, put it in the TouchIDPickingMap
if (pickObj) {
touchPickObjs_.insert(std::pair<int, PickingObject*>(touchPoint->getId(), pickObj));
// Associate touch point with picking object
// which can already have other associated touch points.
pickedTouchPoints_it = pickedTouchPoints_.find(pickObj);
if (pickedTouchPoints_it != pickedTouchPoints_.end()){
pickedTouchPoints_it->second.push_back(*touchPoint);
}
else{
pickedTouchPoints_.insert(std::pair<PickingObject*,
std::vector<TouchPoint>>(pickObj, std::vector<TouchPoint>{*touchPoint}));
}
isAssociated = true;
}
}
else if (touchPoint->state() == TouchPoint::TOUCH_STATE_ENDED) {
// Erase touch point from TouchIDPickingMap
size_t numberOfErasedElements = touchPickObjs_.erase(touchPoint->getId());
isAssociated = (numberOfErasedElements > 0);
}
else {
// Find out if touch point is in the TouchIDPickingMap
// If it exists, associate touch point with picking object
touchPickObjs_it = touchPickObjs_.find(touchPoint->getId());
if (touchPickObjs_it != touchPickObjs_.end()){
// Associate touch point with picking object
// which can already have other associated touch points.
pickedTouchPoints_it = pickedTouchPoints_.find(touchPickObjs_it->second);
if (pickedTouchPoints_it != pickedTouchPoints_.end()){
pickedTouchPoints_it->second.push_back(*touchPoint);
}
else{
pickedTouchPoints_.insert(std::pair<PickingObject*,
std::vector<TouchPoint>>(touchPickObjs_it->second, std::vector<TouchPoint>{*touchPoint}));
}
isAssociated = true;
}
}
// Removed touch point from the actual event if it was associated with a picking object
if (isAssociated)
touchPoint = touchPoints.erase(touchPoint);
else
++touchPoint;
}
// Build touch event for all picking objects with associated touch points
for (pickedTouchPoints_it = pickedTouchPoints_.begin(); pickedTouchPoints_it != pickedTouchPoints_.end(); ++pickedTouchPoints_it){
// Treat one touch point the same as mouse event, for now
if (pickedTouchPoints_it->second.size() == 1){
uvec2 coord = clampToScreenCoords(pickedTouchPoints_it->second[0].getPos(), e->canvasSize());
if (pickedTouchPoints_it->second[0].state() & TouchPoint::TOUCH_STATE_STARTED){
pickedTouchPoints_it->first->setPickingPosition(normalizedCoordinates(coord));
pickedTouchPoints_it->first->setPickingDepth(pickedTouchPoints_it->second[0].getDepth());
pickedTouchPoints_it->first->setPickingMove(vec2(0.f, 0.f));
}
else{
uvec2 prevCoord = clampToScreenCoords(pickedTouchPoints_it->second[0].getPrevPos(), e->canvasSize());
pickedTouchPoints_it->first->setPickingMove(normalizedMovement(prevCoord, coord));
}
// One touch point is currently treated as mouse event as well...
// So prepare for that
prevMouseCoord_ = coord;
mousePickObj_ = pickedTouchPoints_it->first;
mousePickingOngoing_ = true;
}
pickedTouchPoints_it->first->setPickingTouchEvent(TouchEvent(pickedTouchPoints_it->second, e->canvasSize()));
}
// One touch point is currently treated as mouse event as well...
// So prepare for that
if (touchPoints.size() == 1){
prevMouseCoord_ = clampToScreenCoords(touchPoints[0].getPos(), e->canvasSize());
touchPickingOn_ = false;
}
// Mark all picking objects in TouchIDPickingMap as picked.
for (touchPickObjs_it = touchPickObjs_.begin(); touchPickObjs_it != touchPickObjs_.end(); ++touchPickObjs_it)
touchPickObjs_it->second->picked();
return !touchPickObjs_.empty();
}
void PickingContainer::setPickingSource(std::shared_ptr<const Image> src) {
src_ = src;
}
PickingObject* PickingContainer::findPickingObject(const uvec2& coord){
if (pickingEnabled() && src_) {
const Layer* pickingLayer = src_->getPickingLayer();
if (pickingLayer) {
const LayerRAM* pickingLayerRAM = pickingLayer->getRepresentation<LayerRAM>();
dvec4 value = pickingLayerRAM->getAsNormalizedDVec4(coord);
dvec3 pickedColor = (value.a > 0.0 ? value.rgb() : dvec3(0.0));
uvec3 color(pickedColor*255.0);
return PickingManager::getPtr()->getPickingObjectFromColor(color);
}
}
return nullptr;
}
vec2 PickingContainer::normalizedMovement(const uvec2& previous, const uvec2& current) const {
return normalizedCoordinates(current - previous);
}
vec2 PickingContainer::normalizedCoordinates(const uvec2& coord) const {
return vec2(coord) / vec2(src_->getDimensions());
}
uvec2 PickingContainer::clampToScreenCoords(ivec2 mpos, ivec2 dim) {
ivec2 pos = mpos;
pos.x = std::max(pos.x - 1, 0);
pos.x = std::min(pos.x, dim.x - 1);
pos.y = std::max(dim.y - pos.y - 1, 0);
pos.y = std::min(pos.y, dim.y - 1);
return uvec2(pos);
}
} // namespace<|endoftext|>
|
<commit_before>//----------------------------------*-C++-*----------------------------------//
/*!
* \file example/Physics_B.cc
* \author Stuart Slattery
* \date Wed Oct 05 09:38:40 2011
* \brief Physics_B member definitions.
*/
//---------------------------------------------------------------------------//
// $Id: template.cc,v 1.3 2008/01/02 17:18:47 9te Exp $
//---------------------------------------------------------------------------//
#include "Physics_B.hh"
#include "Post_Proc.hh"
#include <cassert>
namespace physics_B
{
//---------------------------------------------------------------------------//
// Constructor.
Physics_B::Physics_B(double x_min, double x_max,
double y_min, double y_max,
double x_nodes, double y_nodes)
{
// Make sure max > min.
assert(x_max > x_min);
assert(y_max > y_min);
// Generate the mesh (regular cartesian grid).
x_edges.resize(x_nodes);
y_edges.resize(y_nodes);
// x_edges
double x_width = (x_max - x_min) / (x_nodes-1);
for (int i = 0; i < x_nodes; ++i)
{
x_edges[i] = x_min + i*x_width;
}
// y_edges
double y_width = (y_max - y_min) / (y_nodes-1);
for (int j = 0; j < y_nodes; ++j)
{
y_edges[j] = y_min + j*y_width;
}
// Resize the source vector to correspond to nodal values and fill
// with 0.
b.resize(x_nodes*y_nodes);
Vector_Dbl::iterator it;
for (it = b.begin(); it != b.end(); ++it)
{
*it = 0.0;
}
}
//---------------------------------------------------------------------------//
// Destructor.
Physics_B::~Physics_B()
{ /* ... */ }
//---------------------------------------------------------------------------//
// Set an element in the source vector.
void Physics_B::set_source(int index, double source)
{
assert( index < b.size() );
b[index] = source;
}
//---------------------------------------------------------------------------//
// Plot the source term.
void Physics_B::plot_source()
{
// Make a new post-processing object.
utils::Post_Proc post_proc(x_edges, y_edges);
// Tag the state vector onto the mesh vertices.
post_proc.add_vertex_tag(b, "b");
// Write the database to file.
post_proc.write("Physics_B.vtk");
}
} // end namespace physics_B
//---------------------------------------------------------------------------//
// end of Physics_B.cc
//---------------------------------------------------------------------------//
<commit_msg>working on test implementations<commit_after>//----------------------------------*-C++-*----------------------------------//
/*!
* \file example/Physics_B.cc
* \author Stuart Slattery
* \date Wed Oct 05 09:38:40 2011
* \brief Physics_B member definitions.
*/
//---------------------------------------------------------------------------//
// $Id: template.cc,v 1.3 2008/01/02 17:18:47 9te Exp $
//---------------------------------------------------------------------------//
#include "Physics_B.hh"
#include "Post_Proc.hh"
#include <cassert>
namespace physics_B
{
//---------------------------------------------------------------------------//
// Constructor.
Physics_B::Physics_B(Communicator comm,
double x_min, double x_max,
double y_min, double y_max,
double x_nodes, double y_nodes)
: d_comm(comm)
{
nemesis::set_internal_comm(d_comm);
// Make sure max > min.
assert(x_max > x_min);
assert(y_max > y_min);
// Generate the mesh (regular cartesian grid).
double x_width = (x_max - x_min) / x_cells;
double y_width = (y_max - y_min) / y_cells;
// Local mesh bounds.
double x_min_local;
double x_max_local;
double y_min_local;
double y_max_local;
// 1 process partitioning
if ( nemesis::nodes() == 1 )
{
x_edges.resize(x_cells+1);
y_edges.resize(y_cells+1);
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
// 2 process partitioning
else if ( nemesis::nodes() == 2 )
{
// process 0
if ( nemesis::node() == 0 )
{
x_edges.resize( (int) (x_cells+1) / 2);
y_edges.resize(y_cells+1);
x_min_local = x_min;
x_max_local = x_min_local + (x_edges.size() - 1)*x_width;
y_min_local = y_min;
y_max_local = y_max;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
// process 1
if ( nemesis::node() == 1 )
{
x_edges.resize( (int) x_cells+1 - (x_cells+1) / 2 );
y_edges.resize(y_cells+1);
x_min_local = x_min_local + (x_edges.size() - 1)*x_width;
x_max_local = x_max;
y_min_local = y_min;
y_max_local = y_max;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
}
// 3 process partitioning
else if ( nemesis::nodes() == 3 )
{
// process 0
if ( nemesis::node() == 0 )
{
x_edges.resize( (int) (x_cells+1) / 2);
y_edges.resize( (int) (y_cells+1) / 2);
x_min_local = x_min;
x_max_local = x_min_local + (x_edges.size() - 1)*x_width;
y_min_local = y_min;
y_max_local = y_min_local + (y_edges.size() - 1)*y_width;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
// process 1
if ( nemesis::node() == 1 )
{
x_edges.resize( (int) x_cells+1 - (x_cells+1) / 2 );
y_edges.resize( (int) (y_cells+1) / 2 );
x_min_local = x_min_local + (x_edges.size() - 1)*x_width;
x_max_local = x_max;
y_min_local = y_min;
y_max_local = y_min_local + (y_edges.size() - 1)*y_width;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
// process 2
if ( nemesis::node() == 2 )
{
x_edges.resize( x_cells+1 );
y_edges.resize( (int) y_cells+1 - (y_cells+1) / 2 );
x_min_local = x_min;
x_max_local = x_max;
y_min_local = y_min + (y_edges.size() - 1)*y_width;
y_max_local = y_max;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
}
// 4 process partitioning
else if ( nemesis::nodes() == 4 )
{
// process 0
if ( nemesis::node() == 0 )
{
x_edges.resize( x_cells+1 );
y_edges.resize( (int) y_cells+1 - (y_cells+1) / 2);
x_min_local = x_min;
x_max_local = x_min_local + (x_edges.size() - 1)*x_width;
y_min_local = y_min;
y_max_local = y_min_local + (y_edges.size() - 1)*y_width;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
// process 1
if ( nemesis::node() == 1 )
{
x_edges.resize( (int) x_cells - (x_cells+1) / 2 );
y_edges.resize( (int) y_cells - (y_cells+1) / 2 );
x_min_local = x_min_local + (x_edges.size() - 1)*x_width;
x_max_local = x_max;
y_min_local = y_min;
y_max_local = y_min_local + (y_edges.size() - 1)*y_width;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
// process 2
if ( nemesis::node() == 2 )
{
x_edges.resize( x_cells+1 );
y_edges.resize( (int) y_cells - (y_cells+1) / 2 );
x_min_local = x_min;
x_max_local = x_max;
y_min_local = y_min;
y_max_local = y_min + (y_edges.size() - 1)*y_width;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
// process 3
if (nemesis::node() == 3)
{
x_edges.resize( x_cells+1 );
y_edges.resize( (int) y_cells - (y_cells+1) / 2 );
x_min_local = x_min;
x_max_local = x_max;
y_min_local = y_min + (y_edges.size() - 1)*y_width;
y_max_local = y_max;
// x_edges
for (int i = 0; i < x_cells+1; ++i)
{
x_edges[i] = x_min_local + i*x_width;
}
// y_edges
for (int j = 0; j < y_cells+1; ++j)
{
y_edges[j] = y_min_local + j*y_width;
}
// Resize the data vector to correspond to cell-centered values and fill
// with 0.
X.resize(x_cells*y_cells);
Vector_Dbl::iterator it;
for (it = X.begin(); it != X.end(); ++it)
{
*it = 0.0;
}
}
}
Nemesis::reset_internal_comm();
}
//---------------------------------------------------------------------------//
// Destructor.
Physics_B::~Physics_B()
{ /* ... */ }
//---------------------------------------------------------------------------//
// Set an element in the source vector.
void Physics_B::set_data(int handle, double data)
{
assert( handle < b.size() );
b[handle] = data;
}
} // end namespace physics_B
//---------------------------------------------------------------------------//
// end of Physics_B.cc
//---------------------------------------------------------------------------//
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*
* Please contact the author(s) of this library if you have any questions.
* Authors: Erik Nelson ( [email protected] )
* David Fridovich-Keil ( [email protected] )
*/
#include "pose_estimator_2d_3d.h"
#include <ceres/ceres.h>
#include <Eigen/SVD>
#include <glog/logging.h>
#include "normalization.h"
#include "../optimization/cost_functors.h"
namespace bsfm {
PoseEstimator2D3D::PoseEstimator2D3D()
: T_(Matrix3d::Identity()), U_(Matrix4d::Identity()) {}
PoseEstimator2D3D::~PoseEstimator2D3D() {}
bool PoseEstimator2D3D::Initialize(const FeatureList& points_2d,
const Point3DList& points_3d,
const CameraIntrinsics& intrinsics) {
if (points_2d.size() != points_3d.size()) {
VLOG(1) << "Inputs 'points_2d' and 'points_3d' do not contain the "
"same number of elements.";
return false;
}
// Copy camera intrinsics.
intrinsics_ = intrinsics;
// Normalize the 3D points.
T_ = ComputeNormalization(points_2d);
U_ = ComputeNormalization(points_3d);
points_2d_.clear();
for (size_t ii = 0; ii < points_2d.size(); ++ii) {
// Get (u, v) image-space point and normalize.
double u = points_2d[ii].u_;
double v = points_2d[ii].v_;
u = T_(0, 0) * u + T_(0, 2);
v = T_(1, 1) * v + T_(1, 2);
points_2d_.push_back(Feature(u, v));
}
points_3d_.clear();
for (size_t ii = 0; ii < points_3d.size(); ++ii) {
// Get (x, y, z) world-space point and normalize.
double x = points_3d[ii].X();
double y = points_3d[ii].Y();
double z = points_3d[ii].Z();
x = U_(0, 0) * x + U_(0, 3);
y = U_(1, 1) * y + U_(1, 3);
z = U_(2, 2) * z + U_(2, 3);
points_3d_.push_back(Point3D(x, y, z));
}
return true;
}
bool PoseEstimator2D3D::Solve(Pose& camera_pose) {
// Get an initial P.
Matrix34d P;
if (!ComputeInitialSolution(P)) {
VLOG(1) << "Failed to compute an initial solution for P.";
return false;
}
// Refine P with non-linear optimization.
Matrix34d P_opt = P;
if (!OptimizeSolution(P_opt)) {
VLOG(1) << "Failed to optimize P. Continuing using the initial solution.";
P_opt = P;
}
// Get the camera pose from the computed projection matrix.
if (!ExtractPose(P_opt, camera_pose)) {
VLOG(1) << "Computed rotation is non-invertible.";
return false;
}
return true;
}
bool PoseEstimator2D3D::ComputeInitialSolution(Matrix34d& initial_solution) {
// Use Eq. 7.2 from H&Z: Multiple-View Geometry to determine an
// over-determined solution for the camera projection matrix P.
// First build the A matrix, which is 2n x 12.
MatrixXd A;
A.resize(points_2d_.size() * 2, 12);
for (size_t ii = 0; ii < points_2d_.size(); ii++) {
// Get (u, v) image-space point.
double u = points_2d_[ii].u_;
double v = points_2d_[ii].v_;
// Get (x, y, z) world-space point.
double x = points_3d_[ii].X();
double y = points_3d_[ii].Y();
double z = points_3d_[ii].Z();
// First 4 columns, top row of block.
A(2*ii+0, 0) = 0;
A(2*ii+0, 1) = 0;
A(2*ii+0, 2) = 0;
A(2*ii+0, 3) = 0;
// Second 4 columns, top row of block.
A(2*ii+0, 4) = -x;
A(2*ii+0, 5) = -y;
A(2*ii+0, 6) = -z;
A(2*ii+0, 7) = -1;
// Third 4 columns, top row of block.
A(2*ii+0, 8) = v*x;
A(2*ii+0, 9) = v*y;
A(2*ii+0, 10) = v*z;
A(2*ii+0, 11) = v;
// First 4 columns, bottom row of block.
A(2*ii+1, 0) = x;
A(2*ii+1, 1) = y;
A(2*ii+1, 2) = z;
A(2*ii+1, 3) = 1;
// Second 4 columns, bottom row of block.
A(2*ii+1, 4) = 0;
A(2*ii+1, 5) = 0;
A(2*ii+1, 6) = 0;
A(2*ii+1, 7) = 0;
// Third 4 columns, bottom row of block.
A(2*ii+1, 8) = -u*x;
A(2*ii+1, 9) = -u*y;
A(2*ii+1, 10) = -u*z;
A(2*ii+1, 11) = -u;
}
// Get svd(A). Save some time and compute a thin U. We still need a full V.
Eigen::JacobiSVD<Eigen::MatrixXd> svd;
svd.compute(A, Eigen::ComputeThinU | Eigen::ComputeFullV);
if (!svd.computeV()) {
VLOG(1) << "Failed to compute a singular value decomposition of A matrix.";
return false;
}
// Get the projection matrix elements from the SVD decomposition.
const VectorXd P_vec = svd.matrixV().col(11).normalized();
// Reshape the vector into the initial solution.
initial_solution.row(0) = P_vec.topRows(4).transpose();
initial_solution.row(1) = P_vec.middleRows(4, 4).transpose();
initial_solution.row(2) = P_vec.bottomRows(4).transpose();
return true;
}
bool PoseEstimator2D3D::OptimizeSolution(Matrix34d& solution) {
// Create the cost function.
ceres::Problem problem;
// Create the output container and initialize with the least-squares solution.
double P[12] = {solution(0,0), solution(0,1), solution(0,2), solution(0,3),
solution(1,0), solution(1,1), solution(1,2), solution(1,3),
solution(2,0), solution(2,1), solution(2,2), solution(2,3)};
// Set up the problem and solve it.
const int kNumResiduals = 1; // each correspondence generates 1 residual.
const int kNumVariables = 1; // only optimizing P.
// Make a cost function for each correspondence using the
// GeometricProjectionError cost functor.
for (size_t ii = 0; ii < points_2d_.size(); ++ii) {
problem.AddResidualBlock(new ceres::AutoDiffCostFunction<
GeometricProjectionError, kNumResiduals, kNumVariables>(
new GeometricProjectionError(points_2d_[ii], points_3d_[ii])), NULL, P);
}
ceres::Solver::Summary summary;
ceres::Solver::Options options;
options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;
ceres::Solve(options, &problem, &summary);
// Store the solved variable back in 'solution'.
if (summary.IsSolutionUsable()) {
for (int row = 0; row < 3; ++row)
for (int col = 0; col < 4; ++col)
solution(row, col) = P[row * 4 + col];
}
return summary.IsSolutionUsable();
}
bool PoseEstimator2D3D::ExtractPose(const Matrix34d& P, Pose& pose) {
// Un-normalize the projection matrix.
const Matrix34d P_unnormalized = T_.inverse() * P * U_;
// Extract camera extrinsics matrix.
Matrix34d Rt = intrinsics_.Kinv() * P_unnormalized;
// [R|t] is only determined up to scale. To get this scale, note that det(R)
// must equal 1. Also note that for an nxn matrix, c^n*det(R) = det(cR).
// Use this property to scale our matrix.
double alpha = Rt.block(0, 0, 3, 3).determinant();
if (std::fabs(alpha) < 1e-8) {
LOG(WARNING) << "Computed rotation has a determinant of 0.";
return false;
}
// Make sure the determinant is positive.
if (alpha < 0.0) {
alpha *= -1.0;
Rt *= -1.0;
}
// Normalize the rotation and translation.
Rt *= std::powf(1.0 / alpha, 1.0 / 3.0);
// Initialize the output pose from the rotation and translation blocks.
pose = Pose(Rt);
return true;
}
} //\namespace bsfm
<commit_msg>Nit. Should use abs/pow, not fabs/powf.<commit_after>/*
* Copyright (c) 2015, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*
* Please contact the author(s) of this library if you have any questions.
* Authors: Erik Nelson ( [email protected] )
* David Fridovich-Keil ( [email protected] )
*/
#include "pose_estimator_2d_3d.h"
#include <ceres/ceres.h>
#include <Eigen/SVD>
#include <glog/logging.h>
#include "normalization.h"
#include "../optimization/cost_functors.h"
namespace bsfm {
PoseEstimator2D3D::PoseEstimator2D3D()
: T_(Matrix3d::Identity()), U_(Matrix4d::Identity()) {}
PoseEstimator2D3D::~PoseEstimator2D3D() {}
bool PoseEstimator2D3D::Initialize(const FeatureList& points_2d,
const Point3DList& points_3d,
const CameraIntrinsics& intrinsics) {
if (points_2d.size() != points_3d.size()) {
VLOG(1) << "Inputs 'points_2d' and 'points_3d' do not contain the "
"same number of elements.";
return false;
}
// Copy camera intrinsics.
intrinsics_ = intrinsics;
// Normalize the 3D points.
T_ = ComputeNormalization(points_2d);
U_ = ComputeNormalization(points_3d);
points_2d_.clear();
for (size_t ii = 0; ii < points_2d.size(); ++ii) {
// Get (u, v) image-space point and normalize.
double u = points_2d[ii].u_;
double v = points_2d[ii].v_;
u = T_(0, 0) * u + T_(0, 2);
v = T_(1, 1) * v + T_(1, 2);
points_2d_.push_back(Feature(u, v));
}
points_3d_.clear();
for (size_t ii = 0; ii < points_3d.size(); ++ii) {
// Get (x, y, z) world-space point and normalize.
double x = points_3d[ii].X();
double y = points_3d[ii].Y();
double z = points_3d[ii].Z();
x = U_(0, 0) * x + U_(0, 3);
y = U_(1, 1) * y + U_(1, 3);
z = U_(2, 2) * z + U_(2, 3);
points_3d_.push_back(Point3D(x, y, z));
}
return true;
}
bool PoseEstimator2D3D::Solve(Pose& camera_pose) {
// Get an initial P.
Matrix34d P;
if (!ComputeInitialSolution(P)) {
VLOG(1) << "Failed to compute an initial solution for P.";
return false;
}
// Refine P with non-linear optimization.
Matrix34d P_opt = P;
if (!OptimizeSolution(P_opt)) {
VLOG(1) << "Failed to optimize P. Continuing using the initial solution.";
P_opt = P;
}
// Get the camera pose from the computed projection matrix.
if (!ExtractPose(P_opt, camera_pose)) {
VLOG(1) << "Computed rotation is non-invertible.";
return false;
}
return true;
}
bool PoseEstimator2D3D::ComputeInitialSolution(Matrix34d& initial_solution) {
// Use Eq. 7.2 from H&Z: Multiple-View Geometry to determine an
// over-determined solution for the camera projection matrix P.
// First build the A matrix, which is 2n x 12.
MatrixXd A;
A.resize(points_2d_.size() * 2, 12);
for (size_t ii = 0; ii < points_2d_.size(); ii++) {
// Get (u, v) image-space point.
double u = points_2d_[ii].u_;
double v = points_2d_[ii].v_;
// Get (x, y, z) world-space point.
double x = points_3d_[ii].X();
double y = points_3d_[ii].Y();
double z = points_3d_[ii].Z();
// First 4 columns, top row of block.
A(2*ii+0, 0) = 0;
A(2*ii+0, 1) = 0;
A(2*ii+0, 2) = 0;
A(2*ii+0, 3) = 0;
// Second 4 columns, top row of block.
A(2*ii+0, 4) = -x;
A(2*ii+0, 5) = -y;
A(2*ii+0, 6) = -z;
A(2*ii+0, 7) = -1;
// Third 4 columns, top row of block.
A(2*ii+0, 8) = v*x;
A(2*ii+0, 9) = v*y;
A(2*ii+0, 10) = v*z;
A(2*ii+0, 11) = v;
// First 4 columns, bottom row of block.
A(2*ii+1, 0) = x;
A(2*ii+1, 1) = y;
A(2*ii+1, 2) = z;
A(2*ii+1, 3) = 1;
// Second 4 columns, bottom row of block.
A(2*ii+1, 4) = 0;
A(2*ii+1, 5) = 0;
A(2*ii+1, 6) = 0;
A(2*ii+1, 7) = 0;
// Third 4 columns, bottom row of block.
A(2*ii+1, 8) = -u*x;
A(2*ii+1, 9) = -u*y;
A(2*ii+1, 10) = -u*z;
A(2*ii+1, 11) = -u;
}
// Get svd(A). Save some time and compute a thin U. We still need a full V.
Eigen::JacobiSVD<Eigen::MatrixXd> svd;
svd.compute(A, Eigen::ComputeThinU | Eigen::ComputeFullV);
if (!svd.computeV()) {
VLOG(1) << "Failed to compute a singular value decomposition of A matrix.";
return false;
}
// Get the projection matrix elements from the SVD decomposition.
const VectorXd P_vec = svd.matrixV().col(11).normalized();
// Reshape the vector into the initial solution.
initial_solution.row(0) = P_vec.topRows(4).transpose();
initial_solution.row(1) = P_vec.middleRows(4, 4).transpose();
initial_solution.row(2) = P_vec.bottomRows(4).transpose();
return true;
}
bool PoseEstimator2D3D::OptimizeSolution(Matrix34d& solution) {
// Create the cost function.
ceres::Problem problem;
// Create the output container and initialize with the least-squares solution.
double P[12] = {solution(0,0), solution(0,1), solution(0,2), solution(0,3),
solution(1,0), solution(1,1), solution(1,2), solution(1,3),
solution(2,0), solution(2,1), solution(2,2), solution(2,3)};
// Set up the problem and solve it.
const int kNumResiduals = 1; // each correspondence generates 1 residual.
const int kNumVariables = 1; // only optimizing P.
// Make a cost function for each correspondence using the
// GeometricProjectionError cost functor.
for (size_t ii = 0; ii < points_2d_.size(); ++ii) {
problem.AddResidualBlock(new ceres::AutoDiffCostFunction<
GeometricProjectionError, kNumResiduals, kNumVariables>(
new GeometricProjectionError(points_2d_[ii], points_3d_[ii])), NULL, P);
}
ceres::Solver::Summary summary;
ceres::Solver::Options options;
options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;
ceres::Solve(options, &problem, &summary);
// Store the solved variable back in 'solution'.
if (summary.IsSolutionUsable()) {
for (int row = 0; row < 3; ++row)
for (int col = 0; col < 4; ++col)
solution(row, col) = P[row * 4 + col];
}
return summary.IsSolutionUsable();
}
bool PoseEstimator2D3D::ExtractPose(const Matrix34d& P, Pose& pose) {
// Un-normalize the projection matrix.
const Matrix34d P_unnormalized = T_.inverse() * P * U_;
// Extract camera extrinsics matrix.
Matrix34d Rt = intrinsics_.Kinv() * P_unnormalized;
// [R|t] is only determined up to scale. To get this scale, note that det(R)
// must equal 1. Also note that for an nxn matrix, c^n*det(R) = det(cR).
// Use this property to scale our matrix.
double alpha = Rt.block(0, 0, 3, 3).determinant();
if (std::abs(alpha) < 1e-8) {
LOG(WARNING) << "Computed rotation has a determinant of 0.";
return false;
}
// Make sure the determinant is positive.
if (alpha < 0.0) {
alpha *= -1.0;
Rt *= -1.0;
}
// Normalize the rotation and translation.
Rt *= std::pow(1.0 / alpha, 1.0 / 3.0);
// Initialize the output pose from the rotation and translation blocks.
pose = Pose(Rt);
return true;
}
} //\namespace bsfm
<|endoftext|>
|
<commit_before>/*
* SessionSourceDatabase.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <session/SessionSourceDatabase.hpp>
#include <string>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <core/Log.hpp>
#include <core/Exec.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/Hash.hpp>
#include <core/FileSerializer.hpp>
#include <core/DateTime.hpp>
#include <core/system/System.hpp>
#include <core/http/Util.hpp>
#include <r/RUtil.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>
#include "SessionSourceDatabaseSupervisor.hpp"
// NOTE: if a file is deleted then its properties database entry is not
// deleted. this has two implications:
//
// - storage is not reclaimed
// - the properties can be "resurreced" and re-attached to another
// file with the same path
//
// One way to overcome this might be to use filesystem metadata to store
// properties rather than a side-database
using namespace core;
namespace session {
namespace source_database {
namespace {
struct PropertiesDatabase
{
FilePath path;
FilePath indexFile;
std::map<std::string,std::string> index;
};
Error getPropertiesDatabase(PropertiesDatabase* pDatabase)
{
pDatabase->path = module_context::scopedScratchPath().complete("sdb/prop");
Error error = pDatabase->path.ensureDirectory();
if (error)
return error;
pDatabase->indexFile = pDatabase->path.complete("INDEX");
if (pDatabase->indexFile.exists())
return readStringMapFromFile(pDatabase->indexFile, &(pDatabase->index));
else
return Success();
}
Error putProperties(const std::string& path, const json::Object& properties)
{
// url escape path (so we can use key=value persistence)
std::string escapedPath = http::util::urlEncode(path);
// get properties database
PropertiesDatabase propertiesDB;
Error error = getPropertiesDatabase(&propertiesDB);
if (error)
return error;
// use existing properties file if it exists, otherwise create new
bool updateIndex = false;
std::string propertiesFile = propertiesDB.index[escapedPath];
if (propertiesFile.empty())
{
FilePath propFile = module_context::uniqueFilePath(propertiesDB.path);
propertiesFile = propFile.filename();
propertiesDB.index[escapedPath] = propertiesFile;
updateIndex = true;
}
// write the file
std::ostringstream ostr ;
json::writeFormatted(properties, ostr);
FilePath propertiesFilePath = propertiesDB.path.complete(propertiesFile);
error = writeStringToFile(propertiesFilePath, ostr.str());
if (error)
return error;
// update the index if necessary
if (updateIndex)
return writeStringMapToFile(propertiesDB.indexFile, propertiesDB.index);
else
return Success();
}
Error getProperties(const std::string& path, json::Object* pProperties)
{
// url escape path (so we can use key=value persistence)
std::string escapedPath = http::util::urlEncode(path);
// get properties database
PropertiesDatabase propertiesDB;
Error error = getPropertiesDatabase(&propertiesDB);
if (error)
return error;
// check for properties file
std::string propertiesFile = propertiesDB.index[escapedPath];
if (propertiesFile.empty())
{
// return empty object if there is none
*pProperties = json::Object();
return Success();
}
// read the properties file
std::string contents ;
FilePath propertiesFilePath = propertiesDB.path.complete(propertiesFile);
error = readStringFromFile(propertiesFilePath, &contents,
options().sourceLineEnding());
if (error)
return error;
// parse the json
json::Value value;
if ( !json::parse(contents, &value) )
return systemError(boost::system::errc::bad_message, ERROR_LOCATION);
// return it
if (json::isType<json::Object>(value))
*pProperties = value.get_obj();
return Success();
}
} // anonymous namespace
SourceDocument::SourceDocument(const std::string& type)
{
FilePath srcDBPath = source_database::path();
FilePath docPath = module_context::uniqueFilePath(srcDBPath);
id_ = docPath.filename();
type_ = type;
setContents("");
dirty_ = false;
created_ = date_time::millisecondsSinceEpoch();
sourceOnSave_ = false;
}
std::string SourceDocument::getProperty(const std::string& name) const
{
json::Object::const_iterator it = properties_.find(name);
if (it != properties_.end())
{
json::Value valueJson = it->second;
if (json::isType<std::string>(valueJson))
return valueJson.get_str();
else
return "";
}
else
{
return "";
}
}
bool SourceDocument::isUntitled() const
{
return path().empty() && !getProperty("tempName").empty();
}
// set contents from string
void SourceDocument::setContents(const std::string& contents)
{
contents_ = contents;
hash_ = hash::crc32Hash(contents_);
}
// set contents from file
Error SourceDocument::setPathAndContents(const std::string& path,
bool allowSubstChars)
{
// resolve aliased path
FilePath docPath = module_context::resolveAliasedPath(path);
std::string contents;
Error error = module_context::readAndDecodeFile(docPath,
encoding(),
allowSubstChars,
&contents);
if (error)
return error ;
// update path and contents
path_ = path;
setContents(contents);
lastKnownWriteTime_ = docPath.lastWriteTime();
return Success();
}
Error SourceDocument::updateDirty()
{
if (path().empty())
{
dirty_ = !contents_.empty();
}
else if (dirty_)
{
// This doesn't actually guarantee that dirty state is correct. All
// it does, at the most, is take a dirty document and mark it clean
// if the contents are the same as on disk. This is important because
// the client now has logic to detect when undo/redo causes a document
// to be reverted to its previous state (i.e. a dirty document can
// become clean through undo/redo), but that state doesn't get sent
// back to the server.
// We don't make a clean document dirty here, even if the contents
// on disk are different, because we will do that on the client side
// and the UI logic is a little complicated.
FilePath docPath = module_context::resolveAliasedPath(path());
if (docPath.exists() && docPath.size() <= (1024*1024))
{
std::string contents;
Error error = module_context::readAndDecodeFile(docPath,
encoding(),
true,
&contents);
if (error)
return error;
if (contents_.length() == contents.length() && hash_ == hash::crc32Hash(contents))
dirty_ = false;
}
}
return Success();
}
void SourceDocument::editProperties(json::Object& properties)
{
std::for_each(properties.begin(),
properties.end(),
boost::bind(&SourceDocument::editProperty, this, _1));
}
void SourceDocument::checkForExternalEdit(std::time_t* pTime)
{
*pTime = 0;
if (path_.empty())
return;
if (lastKnownWriteTime_ == 0)
return;
core::FilePath filePath = module_context::resolveAliasedPath(path_);
if (!filePath.exists())
return;
std::time_t newTime = filePath.lastWriteTime();
if (newTime != lastKnownWriteTime_)
*pTime = newTime;
}
void SourceDocument::updateLastKnownWriteTime()
{
lastKnownWriteTime_ = 0;
if (path_.empty())
return;
core::FilePath filePath = module_context::resolveAliasedPath(path_);
if (!filePath.exists())
return;
lastKnownWriteTime_ = filePath.lastWriteTime();
}
Error SourceDocument::readFromJson(json::Object* pDocJson)
{
// NOTE: since this class is the one who presumably persisted the
// json values in the first place we don't do "checked" access to
// the json data elements. if the persistence format differs from
// what we expect things will blow up. therefore if we change the
// persistence format we need to make sure this code is robust
// in the presence of the old format
try
{
json::Object& docJson = *pDocJson;
id_ = docJson["id"].get_str();
json::Value path = docJson["path"];
path_ = !path.is_null() ? path.get_str() : std::string();
json::Value type = docJson["type"];
type_ = !type.is_null() ? type.get_str() : std::string();
setContents(docJson["contents"].get_str());
dirty_ = docJson["dirty"].get_bool();
created_ = docJson["created"].get_real();
sourceOnSave_ = docJson["source_on_save"].get_bool();
// read safely (migration)
json::Value properties = docJson["properties"];
properties_ = !properties.is_null() ? properties.get_obj() : json::Object();
json::Value lastKnownWriteTime = docJson["lastKnownWriteTime"];
lastKnownWriteTime_ = !lastKnownWriteTime.is_null()
? lastKnownWriteTime.get_int64()
: 0;
json::Value encoding = docJson["encoding"];
encoding_ = !encoding.is_null() ? encoding.get_str() : std::string();
return Success();
}
catch(const std::exception& e)
{
return systemError(boost::system::errc::protocol_error,
e.what(),
ERROR_LOCATION);
}
}
void SourceDocument::writeToJson(json::Object* pDocJson) const
{
json::Object& jsonDoc = *pDocJson;
jsonDoc["id"] = id();
jsonDoc["path"] = !path().empty() ? path_ : json::Value();
jsonDoc["type"] = !type().empty() ? type_ : json::Value();
jsonDoc["hash"] = hash();
jsonDoc["contents"] = contents();
jsonDoc["dirty"] = dirty();
jsonDoc["created"] = created();
jsonDoc["source_on_save"] = sourceOnSave();
jsonDoc["properties"] = properties();
jsonDoc["lastKnownWriteTime"] = json::Value(
static_cast<boost::int64_t>(lastKnownWriteTime_));
jsonDoc["encoding"] = encoding_;
}
Error SourceDocument::writeToFile(const FilePath& filePath) const
{
// get json representation
json::Object jsonDoc ;
writeToJson(&jsonDoc);
std::ostringstream ostr ;
json::writeFormatted(jsonDoc, ostr);
// write to file
return writeStringToFile(filePath, ostr.str());
}
void SourceDocument::editProperty(const json::Object::value_type& property)
{
if (property.second.is_null())
{
properties_.erase(property.first);
}
else
{
properties_[property.first] = property.second;
}
}
bool sortByCreated(const boost::shared_ptr<SourceDocument>& pDoc1,
const boost::shared_ptr<SourceDocument>& pDoc2)
{
return pDoc1->created() < pDoc2->created();
}
namespace {
FilePath s_sourceDBPath;
} // anonymous namespace
FilePath path()
{
return s_sourceDBPath;
}
Error get(const std::string& id, boost::shared_ptr<SourceDocument> pDoc)
{
FilePath filePath = source_database::path().complete(id);
if (filePath.exists())
{
// read the contents of the file
std::string contents ;
Error error = readStringFromFile(filePath, &contents,
options().sourceLineEnding());
if (error)
return error;
// parse the json
json::Value value;
if ( !json::parse(contents, &value) )
{
return systemError(boost::system::errc::invalid_argument,
ERROR_LOCATION);
}
// initialize doc from json
json::Object jsonDoc = value.get_obj();
return pDoc->readFromJson(&jsonDoc);
}
else
{
return systemError(boost::system::errc::no_such_file_or_directory,
ERROR_LOCATION);
}
}
Error getDurableProperties(const std::string& path, json::Object* pProperties)
{
return getProperties(path, pProperties);
}
bool isSourceDocument(const FilePath& filePath)
{
if (filePath.isDirectory())
return false;
else if (filePath.filename() == ".DS_Store")
return false;
else if (filePath.filename() == "lock_file")
return false;
else
return true;
}
Error list(std::vector<boost::shared_ptr<SourceDocument> >* pDocs)
{
std::vector<FilePath> files ;
Error error = source_database::path().children(&files);
if (error)
return error ;
BOOST_FOREACH( FilePath& filePath, files )
{
if (isSourceDocument(filePath))
{
// get the source doc
boost::shared_ptr<SourceDocument> pDoc(new SourceDocument()) ;
Error error = source_database::get(filePath.filename(), pDoc);
if (!error)
pDocs->push_back(pDoc);
else
LOG_ERROR(error);
}
}
return Success();
}
Error put(boost::shared_ptr<SourceDocument> pDoc)
{
// write to file
FilePath filePath = source_database::path().complete(pDoc->id());
Error error = pDoc->writeToFile(filePath);
if (error)
return error ;
// write properties to durable storage (if there is a path)
if (!pDoc->path().empty())
{
error = putProperties(pDoc->path(), pDoc->properties());
if (error)
LOG_ERROR(error);
}
return Success();
}
Error remove(const std::string& id)
{
return source_database::path().complete(id).removeIfExists();
}
Error removeAll()
{
std::vector<FilePath> files ;
Error error = source_database::path().children(&files);
if (error)
return error ;
BOOST_FOREACH( FilePath& filePath, files )
{
Error error = filePath.remove();
if (error)
return error ;
}
return Success();
}
namespace {
void onShutdown(bool)
{
Error error = supervisor::detachFromSourceDatabase();
if (error)
LOG_ERROR(error);
}
} // anonymous namespace
Error initialize()
{
// signup for the shutdown event
module_context::events().onShutdown.connect(onShutdown);
// provision a source database directory
return supervisor::attachToSourceDatabase(&s_sourceDBPath);
}
} // namespace source_database
} // namesapce session
<commit_msg>don't detach from source database at shutdown if we never successfully attached<commit_after>/*
* SessionSourceDatabase.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <session/SessionSourceDatabase.hpp>
#include <string>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <core/Log.hpp>
#include <core/Exec.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/Hash.hpp>
#include <core/FileSerializer.hpp>
#include <core/DateTime.hpp>
#include <core/system/System.hpp>
#include <core/http/Util.hpp>
#include <r/RUtil.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>
#include "SessionSourceDatabaseSupervisor.hpp"
// NOTE: if a file is deleted then its properties database entry is not
// deleted. this has two implications:
//
// - storage is not reclaimed
// - the properties can be "resurreced" and re-attached to another
// file with the same path
//
// One way to overcome this might be to use filesystem metadata to store
// properties rather than a side-database
using namespace core;
namespace session {
namespace source_database {
namespace {
struct PropertiesDatabase
{
FilePath path;
FilePath indexFile;
std::map<std::string,std::string> index;
};
Error getPropertiesDatabase(PropertiesDatabase* pDatabase)
{
pDatabase->path = module_context::scopedScratchPath().complete("sdb/prop");
Error error = pDatabase->path.ensureDirectory();
if (error)
return error;
pDatabase->indexFile = pDatabase->path.complete("INDEX");
if (pDatabase->indexFile.exists())
return readStringMapFromFile(pDatabase->indexFile, &(pDatabase->index));
else
return Success();
}
Error putProperties(const std::string& path, const json::Object& properties)
{
// url escape path (so we can use key=value persistence)
std::string escapedPath = http::util::urlEncode(path);
// get properties database
PropertiesDatabase propertiesDB;
Error error = getPropertiesDatabase(&propertiesDB);
if (error)
return error;
// use existing properties file if it exists, otherwise create new
bool updateIndex = false;
std::string propertiesFile = propertiesDB.index[escapedPath];
if (propertiesFile.empty())
{
FilePath propFile = module_context::uniqueFilePath(propertiesDB.path);
propertiesFile = propFile.filename();
propertiesDB.index[escapedPath] = propertiesFile;
updateIndex = true;
}
// write the file
std::ostringstream ostr ;
json::writeFormatted(properties, ostr);
FilePath propertiesFilePath = propertiesDB.path.complete(propertiesFile);
error = writeStringToFile(propertiesFilePath, ostr.str());
if (error)
return error;
// update the index if necessary
if (updateIndex)
return writeStringMapToFile(propertiesDB.indexFile, propertiesDB.index);
else
return Success();
}
Error getProperties(const std::string& path, json::Object* pProperties)
{
// url escape path (so we can use key=value persistence)
std::string escapedPath = http::util::urlEncode(path);
// get properties database
PropertiesDatabase propertiesDB;
Error error = getPropertiesDatabase(&propertiesDB);
if (error)
return error;
// check for properties file
std::string propertiesFile = propertiesDB.index[escapedPath];
if (propertiesFile.empty())
{
// return empty object if there is none
*pProperties = json::Object();
return Success();
}
// read the properties file
std::string contents ;
FilePath propertiesFilePath = propertiesDB.path.complete(propertiesFile);
error = readStringFromFile(propertiesFilePath, &contents,
options().sourceLineEnding());
if (error)
return error;
// parse the json
json::Value value;
if ( !json::parse(contents, &value) )
return systemError(boost::system::errc::bad_message, ERROR_LOCATION);
// return it
if (json::isType<json::Object>(value))
*pProperties = value.get_obj();
return Success();
}
} // anonymous namespace
SourceDocument::SourceDocument(const std::string& type)
{
FilePath srcDBPath = source_database::path();
FilePath docPath = module_context::uniqueFilePath(srcDBPath);
id_ = docPath.filename();
type_ = type;
setContents("");
dirty_ = false;
created_ = date_time::millisecondsSinceEpoch();
sourceOnSave_ = false;
}
std::string SourceDocument::getProperty(const std::string& name) const
{
json::Object::const_iterator it = properties_.find(name);
if (it != properties_.end())
{
json::Value valueJson = it->second;
if (json::isType<std::string>(valueJson))
return valueJson.get_str();
else
return "";
}
else
{
return "";
}
}
bool SourceDocument::isUntitled() const
{
return path().empty() && !getProperty("tempName").empty();
}
// set contents from string
void SourceDocument::setContents(const std::string& contents)
{
contents_ = contents;
hash_ = hash::crc32Hash(contents_);
}
// set contents from file
Error SourceDocument::setPathAndContents(const std::string& path,
bool allowSubstChars)
{
// resolve aliased path
FilePath docPath = module_context::resolveAliasedPath(path);
std::string contents;
Error error = module_context::readAndDecodeFile(docPath,
encoding(),
allowSubstChars,
&contents);
if (error)
return error ;
// update path and contents
path_ = path;
setContents(contents);
lastKnownWriteTime_ = docPath.lastWriteTime();
return Success();
}
Error SourceDocument::updateDirty()
{
if (path().empty())
{
dirty_ = !contents_.empty();
}
else if (dirty_)
{
// This doesn't actually guarantee that dirty state is correct. All
// it does, at the most, is take a dirty document and mark it clean
// if the contents are the same as on disk. This is important because
// the client now has logic to detect when undo/redo causes a document
// to be reverted to its previous state (i.e. a dirty document can
// become clean through undo/redo), but that state doesn't get sent
// back to the server.
// We don't make a clean document dirty here, even if the contents
// on disk are different, because we will do that on the client side
// and the UI logic is a little complicated.
FilePath docPath = module_context::resolveAliasedPath(path());
if (docPath.exists() && docPath.size() <= (1024*1024))
{
std::string contents;
Error error = module_context::readAndDecodeFile(docPath,
encoding(),
true,
&contents);
if (error)
return error;
if (contents_.length() == contents.length() && hash_ == hash::crc32Hash(contents))
dirty_ = false;
}
}
return Success();
}
void SourceDocument::editProperties(json::Object& properties)
{
std::for_each(properties.begin(),
properties.end(),
boost::bind(&SourceDocument::editProperty, this, _1));
}
void SourceDocument::checkForExternalEdit(std::time_t* pTime)
{
*pTime = 0;
if (path_.empty())
return;
if (lastKnownWriteTime_ == 0)
return;
core::FilePath filePath = module_context::resolveAliasedPath(path_);
if (!filePath.exists())
return;
std::time_t newTime = filePath.lastWriteTime();
if (newTime != lastKnownWriteTime_)
*pTime = newTime;
}
void SourceDocument::updateLastKnownWriteTime()
{
lastKnownWriteTime_ = 0;
if (path_.empty())
return;
core::FilePath filePath = module_context::resolveAliasedPath(path_);
if (!filePath.exists())
return;
lastKnownWriteTime_ = filePath.lastWriteTime();
}
Error SourceDocument::readFromJson(json::Object* pDocJson)
{
// NOTE: since this class is the one who presumably persisted the
// json values in the first place we don't do "checked" access to
// the json data elements. if the persistence format differs from
// what we expect things will blow up. therefore if we change the
// persistence format we need to make sure this code is robust
// in the presence of the old format
try
{
json::Object& docJson = *pDocJson;
id_ = docJson["id"].get_str();
json::Value path = docJson["path"];
path_ = !path.is_null() ? path.get_str() : std::string();
json::Value type = docJson["type"];
type_ = !type.is_null() ? type.get_str() : std::string();
setContents(docJson["contents"].get_str());
dirty_ = docJson["dirty"].get_bool();
created_ = docJson["created"].get_real();
sourceOnSave_ = docJson["source_on_save"].get_bool();
// read safely (migration)
json::Value properties = docJson["properties"];
properties_ = !properties.is_null() ? properties.get_obj() : json::Object();
json::Value lastKnownWriteTime = docJson["lastKnownWriteTime"];
lastKnownWriteTime_ = !lastKnownWriteTime.is_null()
? lastKnownWriteTime.get_int64()
: 0;
json::Value encoding = docJson["encoding"];
encoding_ = !encoding.is_null() ? encoding.get_str() : std::string();
return Success();
}
catch(const std::exception& e)
{
return systemError(boost::system::errc::protocol_error,
e.what(),
ERROR_LOCATION);
}
}
void SourceDocument::writeToJson(json::Object* pDocJson) const
{
json::Object& jsonDoc = *pDocJson;
jsonDoc["id"] = id();
jsonDoc["path"] = !path().empty() ? path_ : json::Value();
jsonDoc["type"] = !type().empty() ? type_ : json::Value();
jsonDoc["hash"] = hash();
jsonDoc["contents"] = contents();
jsonDoc["dirty"] = dirty();
jsonDoc["created"] = created();
jsonDoc["source_on_save"] = sourceOnSave();
jsonDoc["properties"] = properties();
jsonDoc["lastKnownWriteTime"] = json::Value(
static_cast<boost::int64_t>(lastKnownWriteTime_));
jsonDoc["encoding"] = encoding_;
}
Error SourceDocument::writeToFile(const FilePath& filePath) const
{
// get json representation
json::Object jsonDoc ;
writeToJson(&jsonDoc);
std::ostringstream ostr ;
json::writeFormatted(jsonDoc, ostr);
// write to file
return writeStringToFile(filePath, ostr.str());
}
void SourceDocument::editProperty(const json::Object::value_type& property)
{
if (property.second.is_null())
{
properties_.erase(property.first);
}
else
{
properties_[property.first] = property.second;
}
}
bool sortByCreated(const boost::shared_ptr<SourceDocument>& pDoc1,
const boost::shared_ptr<SourceDocument>& pDoc2)
{
return pDoc1->created() < pDoc2->created();
}
namespace {
FilePath s_sourceDBPath;
} // anonymous namespace
FilePath path()
{
return s_sourceDBPath;
}
Error get(const std::string& id, boost::shared_ptr<SourceDocument> pDoc)
{
FilePath filePath = source_database::path().complete(id);
if (filePath.exists())
{
// read the contents of the file
std::string contents ;
Error error = readStringFromFile(filePath, &contents,
options().sourceLineEnding());
if (error)
return error;
// parse the json
json::Value value;
if ( !json::parse(contents, &value) )
{
return systemError(boost::system::errc::invalid_argument,
ERROR_LOCATION);
}
// initialize doc from json
json::Object jsonDoc = value.get_obj();
return pDoc->readFromJson(&jsonDoc);
}
else
{
return systemError(boost::system::errc::no_such_file_or_directory,
ERROR_LOCATION);
}
}
Error getDurableProperties(const std::string& path, json::Object* pProperties)
{
return getProperties(path, pProperties);
}
bool isSourceDocument(const FilePath& filePath)
{
if (filePath.isDirectory())
return false;
else if (filePath.filename() == ".DS_Store")
return false;
else if (filePath.filename() == "lock_file")
return false;
else
return true;
}
Error list(std::vector<boost::shared_ptr<SourceDocument> >* pDocs)
{
std::vector<FilePath> files ;
Error error = source_database::path().children(&files);
if (error)
return error ;
BOOST_FOREACH( FilePath& filePath, files )
{
if (isSourceDocument(filePath))
{
// get the source doc
boost::shared_ptr<SourceDocument> pDoc(new SourceDocument()) ;
Error error = source_database::get(filePath.filename(), pDoc);
if (!error)
pDocs->push_back(pDoc);
else
LOG_ERROR(error);
}
}
return Success();
}
Error put(boost::shared_ptr<SourceDocument> pDoc)
{
// write to file
FilePath filePath = source_database::path().complete(pDoc->id());
Error error = pDoc->writeToFile(filePath);
if (error)
return error ;
// write properties to durable storage (if there is a path)
if (!pDoc->path().empty())
{
error = putProperties(pDoc->path(), pDoc->properties());
if (error)
LOG_ERROR(error);
}
return Success();
}
Error remove(const std::string& id)
{
return source_database::path().complete(id).removeIfExists();
}
Error removeAll()
{
std::vector<FilePath> files ;
Error error = source_database::path().children(&files);
if (error)
return error ;
BOOST_FOREACH( FilePath& filePath, files )
{
Error error = filePath.remove();
if (error)
return error ;
}
return Success();
}
namespace {
void onShutdown(bool)
{
Error error = supervisor::detachFromSourceDatabase();
if (error)
LOG_ERROR(error);
}
} // anonymous namespace
Error initialize()
{
// provision a source database directory
Error error = supervisor::attachToSourceDatabase(&s_sourceDBPath);
if (error)
return error;
// signup for the shutdown event
module_context::events().onShutdown.connect(onShutdown);
return Success();
}
} // namespace source_database
} // namesapce session
<|endoftext|>
|
<commit_before>/* $Id$
*
* Copyright (c) 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com).
*
* This file is part of OpenCAMlib
* (see https://github.com/aewallin/opencamlib).
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/foreach.hpp>
#include "millingcutter.hpp"
#include "clpoint.hpp"
#include "pointdropcutter.hpp"
#include "adaptivepathdropcutter.hpp"
namespace ocl
{
//******** ********************** */
AdaptivePathDropCutter::AdaptivePathDropCutter() {
cutter = NULL;
surf = NULL;
path = NULL;
minimumZ = 0.0;
subOp.clear();
subOp.push_back( new PointDropCutter() ); // we delegate to PointDropCutter, who does the heavy lifting
sampling = 0.1;
min_sampling = 0.01;
cosLimit = 0.999;
}
AdaptivePathDropCutter::~AdaptivePathDropCutter() {
//std::cout << " ~AdaptivePathDropCutter() \n";
delete subOp[0];
}
void AdaptivePathDropCutter::run() {
adaptive_sampling_run();
}
void AdaptivePathDropCutter::adaptive_sampling_run() {
//std::cout << " apdc::adaptive_sampling_run()... ";
clpoints.clear();
BOOST_FOREACH( const Span* span, path->span_list ) { // this loop could run in parallel, since spans don't depend on eachother
CLPoint start = span->getPoint(0.0);
CLPoint stop = span->getPoint(1.0);
subOp[0]->run(start);
subOp[0]->run(stop);
clpoints.push_back(start);
adaptive_sample( span, 0.0, 1.0, start, stop);
}
//std::cout << " DONE clpoints.size()=" << clpoints.size() << "\n";
}
void AdaptivePathDropCutter::adaptive_sample(const Span* span, double start_t, double stop_t, CLPoint start_cl, CLPoint stop_cl) {
const double mid_t = start_t + (stop_t-start_t)/2.0; // mid point sample
assert( mid_t > start_t ); assert( mid_t < stop_t );
CLPoint mid_cl = span->getPoint(mid_t);
//std::cout << " apdc sampling at " << mid_t << "\n";
subOp[0]->run( mid_cl );
double fw_step = (stop_cl-start_cl).xyNorm();
if ( (fw_step > sampling) || // above minimum step-forward, need to sample more
( (!flat(start_cl,mid_cl,stop_cl)) && (fw_step > min_sampling) ) ) { // OR not flat, and not max sampling
adaptive_sample( span, start_t, mid_t , start_cl, mid_cl );
adaptive_sample( span, mid_t , stop_t, mid_cl , stop_cl );
} else {
clpoints.push_back(stop_cl);
}
}
bool AdaptivePathDropCutter::flat(CLPoint& start_cl, CLPoint& mid_cl, CLPoint& stop_cl) {
CLPoint v1 = mid_cl-start_cl;
CLPoint v2 = stop_cl-mid_cl;
v1.normalize();
v2.normalize();
return (v1.dot(v2) > cosLimit);
}
} // end namespace
<commit_msg>Clear all subOps in adaptivePathDropCutter<commit_after>/* $Id$
*
* Copyright (c) 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com).
*
* This file is part of OpenCAMlib
* (see https://github.com/aewallin/opencamlib).
*
* This program 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/foreach.hpp>
#include "millingcutter.hpp"
#include "clpoint.hpp"
#include "pointdropcutter.hpp"
#include "adaptivepathdropcutter.hpp"
namespace ocl
{
//******** ********************** */
AdaptivePathDropCutter::AdaptivePathDropCutter() {
// std::cout << " AdaptivePathDropCutter() " << std::endl;
cutter = NULL;
surf = NULL;
path = NULL;
minimumZ = 0.0;
subOp.clear();
subOp.push_back( new PointDropCutter() ); // we delegate to PointDropCutter, who does the heavy lifting
sampling = 0.1;
min_sampling = 0.01;
cosLimit = 0.999;
}
AdaptivePathDropCutter::~AdaptivePathDropCutter() {
// std::cout << " ~AdaptivePathDropCutter() " << std::endl;
subOp.clear();
}
void AdaptivePathDropCutter::run() {
adaptive_sampling_run();
}
void AdaptivePathDropCutter::adaptive_sampling_run() {
//std::cout << " apdc::adaptive_sampling_run()... ";
clpoints.clear();
BOOST_FOREACH( const Span* span, path->span_list ) { // this loop could run in parallel, since spans don't depend on eachother
CLPoint start = span->getPoint(0.0);
CLPoint stop = span->getPoint(1.0);
subOp[0]->run(start);
subOp[0]->run(stop);
clpoints.push_back(start);
adaptive_sample( span, 0.0, 1.0, start, stop);
}
//std::cout << " DONE clpoints.size()=" << clpoints.size() << "\n";
}
void AdaptivePathDropCutter::adaptive_sample(const Span* span, double start_t, double stop_t, CLPoint start_cl, CLPoint stop_cl) {
const double mid_t = start_t + (stop_t-start_t)/2.0; // mid point sample
assert( mid_t > start_t ); assert( mid_t < stop_t );
CLPoint mid_cl = span->getPoint(mid_t);
//std::cout << " apdc sampling at " << mid_t << "\n";
subOp[0]->run( mid_cl );
double fw_step = (stop_cl-start_cl).xyNorm();
if ( (fw_step > sampling) || // above minimum step-forward, need to sample more
( (!flat(start_cl,mid_cl,stop_cl)) && (fw_step > min_sampling) ) ) { // OR not flat, and not max sampling
adaptive_sample( span, start_t, mid_t , start_cl, mid_cl );
adaptive_sample( span, mid_t , stop_t, mid_cl , stop_cl );
} else {
clpoints.push_back(stop_cl);
}
}
bool AdaptivePathDropCutter::flat(CLPoint& start_cl, CLPoint& mid_cl, CLPoint& stop_cl) {
CLPoint v1 = mid_cl-start_cl;
CLPoint v2 = stop_cl-mid_cl;
v1.normalize();
v2.normalize();
return (v1.dot(v2) > cosLimit);
}
} // end namespace
<|endoftext|>
|
<commit_before>/*
The MIT License
Copyright (c) 2012 by Jorrit Tyberghein
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.
*/
#include <crystalspace.h>
#include "helpframe.h"
#include <wx/html/htmlwin.h>
SCF_IMPLEMENT_FACTORY (HelpFrame)
//--------------------------------------------------------------------------
BEGIN_EVENT_TABLE(HelpFrame, wxFrame)
EVT_CLOSE(HelpFrame :: OnClose)
//EVT_TOOL(id, func)
END_EVENT_TABLE()
//--------------------------------------------------------------------------
HelpFrame::HelpFrame (iBase* parent) :
scfImplementationType (this, parent)
{
}
void HelpFrame::OnClose (wxCloseEvent& event)
{
if (event.CanVeto ())
{
wxFrame::Show (false);
event.Veto ();
}
else
{
Destroy ();
}
}
void HelpFrame::Show ()
{
wxFrame::Show (true);
wxHtmlWindow* help_Html = XRCCTRL (*this, "help_Html", wxHtmlWindow);
help_Html->LoadPage (wxString::FromUTF8 ("docs/html/manual/index.html"));
}
void HelpFrame::About ()
{
wxFrame::Show (true);
wxHtmlWindow* help_Html = XRCCTRL (*this, "help_Html", wxHtmlWindow);
help_Html->LoadPage (wxString::FromUTF8 ("docs/html/manual/About.html"));
}
bool HelpFrame::Initialize (iObjectRegistry* object_reg)
{
HelpFrame::object_reg = object_reg;
return true;
}
void HelpFrame::SetApplication (iAresEditor* app)
{
HelpFrame::app = app;
}
void HelpFrame::SetParent (wxWindow* parent)
{
wxXmlResource::Get()->LoadFrame (this, parent, wxT ("HelpFrame"));
wxHtmlWindow* help_Html = XRCCTRL (*this, "help_Html", wxHtmlWindow);
help_Html->LoadPage (wxString::FromUTF8 ("docs/html/manual/index.html"));
SetSize (700, 600);
Layout ();
Fit ();
}
HelpFrame::~HelpFrame ()
{
}
<commit_msg>Fixed size of help window.<commit_after>/*
The MIT License
Copyright (c) 2012 by Jorrit Tyberghein
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.
*/
#include <crystalspace.h>
#include "helpframe.h"
#include <wx/html/htmlwin.h>
SCF_IMPLEMENT_FACTORY (HelpFrame)
//--------------------------------------------------------------------------
BEGIN_EVENT_TABLE(HelpFrame, wxFrame)
EVT_CLOSE(HelpFrame :: OnClose)
//EVT_TOOL(id, func)
END_EVENT_TABLE()
//--------------------------------------------------------------------------
HelpFrame::HelpFrame (iBase* parent) :
scfImplementationType (this, parent)
{
}
void HelpFrame::OnClose (wxCloseEvent& event)
{
if (event.CanVeto ())
{
wxFrame::Show (false);
event.Veto ();
}
else
{
Destroy ();
}
}
void HelpFrame::Show ()
{
wxFrame::Show (true);
wxHtmlWindow* help_Html = XRCCTRL (*this, "help_Html", wxHtmlWindow);
help_Html->LoadPage (wxString::FromUTF8 ("docs/html/manual/index.html"));
}
void HelpFrame::About ()
{
wxFrame::Show (true);
wxHtmlWindow* help_Html = XRCCTRL (*this, "help_Html", wxHtmlWindow);
help_Html->LoadPage (wxString::FromUTF8 ("docs/html/manual/About.html"));
}
bool HelpFrame::Initialize (iObjectRegistry* object_reg)
{
HelpFrame::object_reg = object_reg;
return true;
}
void HelpFrame::SetApplication (iAresEditor* app)
{
HelpFrame::app = app;
}
void HelpFrame::SetParent (wxWindow* parent)
{
wxXmlResource::Get()->LoadFrame (this, parent, wxT ("HelpFrame"));
wxHtmlWindow* help_Html = XRCCTRL (*this, "help_Html", wxHtmlWindow);
help_Html->LoadPage (wxString::FromUTF8 ("docs/html/manual/index.html"));
Layout ();
Fit ();
SetSize (700, 600);
}
HelpFrame::~HelpFrame ()
{
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureDomainEffect.h"
#include "GrTBackendEffectFactory.h"
#include "gl/GrGLEffect.h"
#include "gl/GrGLEffectMatrix.h"
#include "SkFloatingPoint.h"
class GrGLTextureDomainEffect : public GrGLEffect {
public:
GrGLTextureDomainEffect(const GrBackendEffectFactory&, const GrEffect&);
virtual void emitCode(GrGLShaderBuilder*,
const GrEffectStage&,
EffectKey,
const char* vertexCoords,
const char* outputColor,
const char* inputColor,
const TextureSamplerArray&) SK_OVERRIDE;
virtual void setData(const GrGLUniformManager&, const GrEffectStage&) SK_OVERRIDE;
static inline EffectKey GenKey(const GrEffectStage&, const GrGLCaps&);
private:
GrGLUniformManager::UniformHandle fNameUni;
GrGLEffectMatrix fEffectMatrix;
GrGLfloat fPrevDomain[4];
typedef GrGLEffect INHERITED;
};
GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrBackendEffectFactory& factory,
const GrEffect&)
: INHERITED(factory)
, fNameUni(GrGLUniformManager::kInvalidUniformHandle) {
fPrevDomain[0] = SK_FloatNaN;
}
void GrGLTextureDomainEffect::emitCode(GrGLShaderBuilder* builder,
const GrEffectStage&,
EffectKey key,
const char* vertexCoords,
const char* outputColor,
const char* inputColor,
const TextureSamplerArray& samplers) {
const char* coords;
fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, vertexCoords, &coords);
fNameUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
kVec4f_GrSLType, "TexDom");
builder->fFSCode.appendf("\tvec2 clampCoord = clamp(%s, %s.xy, %s.zw);\n",
coords,
builder->getUniformCStr(fNameUni),
builder->getUniformCStr(fNameUni));
builder->fFSCode.appendf("\t%s = ", outputColor);
builder->appendTextureLookupAndModulate(&builder->fFSCode,
inputColor,
samplers[0],
"clampCoord");
builder->fFSCode.append(";\n");
}
void GrGLTextureDomainEffect::setData(const GrGLUniformManager& uman, const GrEffectStage& stage) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
const GrRect& domain = effect.domain();
float values[4] = {
SkScalarToFloat(domain.left()),
SkScalarToFloat(domain.top()),
SkScalarToFloat(domain.right()),
SkScalarToFloat(domain.bottom())
};
// vertical flip if necessary
if (GrSurface::kBottomLeft_Origin == effect.texture(0)->origin()) {
values[1] = 1.0f - values[1];
values[3] = 1.0f - values[3];
// The top and bottom were just flipped, so correct the ordering
// of elements so that values = (l, t, r, b).
SkTSwap(values[1], values[3]);
}
if (0 != memcmp(values, fPrevDomain, 4 * sizeof(GrGLfloat))) {
uman.set4fv(fNameUni, 0, 1, values);
}
fEffectMatrix.setData(uman,
effect.getMatrix(),
stage.getCoordChangeMatrix(),
effect.texture(0));
}
GrGLEffect::EffectKey GrGLTextureDomainEffect::GenKey(const GrEffectStage& stage, const GrGLCaps&) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
return GrGLEffectMatrix::GenKey(effect.getMatrix(), effect.getMatrix(), effect.texture(0));
}
///////////////////////////////////////////////////////////////////////////////
GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture, const GrRect& domain)
: GrSingleTextureEffect(texture)
, fTextureDomain(domain) {
}
GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture,
const GrRect& domain,
const GrTextureParams& params)
: GrSingleTextureEffect(texture, params)
, fTextureDomain(domain) {
}
GrTextureDomainEffect::~GrTextureDomainEffect() {
}
const GrBackendEffectFactory& GrTextureDomainEffect::getFactory() const {
return GrTBackendEffectFactory<GrTextureDomainEffect>::getInstance();
}
bool GrTextureDomainEffect::isEqual(const GrEffect& sBase) const {
const GrTextureDomainEffect& s = static_cast<const GrTextureDomainEffect&>(sBase);
return (INHERITED::isEqual(sBase) && this->fTextureDomain == s.fTextureDomain);
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_EFFECT_TEST(GrTextureDomainEffect);
GrEffect* GrTextureDomainEffect::TestCreate(SkRandom* random,
GrContext* context,
GrTexture* textures[]) {
int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :
GrEffectUnitTest::kAlphaTextureIdx;
GrRect domain;
domain.fLeft = random->nextUScalar1();
domain.fRight = random->nextRangeScalar(domain.fLeft, SK_Scalar1);
domain.fTop = random->nextUScalar1();
domain.fBottom = random->nextRangeScalar(domain.fTop, SK_Scalar1);
return SkNEW_ARGS(GrTextureDomainEffect, (textures[texIdx], domain));
}
<commit_msg>Fix dumb mistake of passing the same matrix to both matrix params of GrGLMatrixEffect::GenKey in texture domain effect.<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureDomainEffect.h"
#include "GrTBackendEffectFactory.h"
#include "gl/GrGLEffect.h"
#include "gl/GrGLEffectMatrix.h"
#include "SkFloatingPoint.h"
class GrGLTextureDomainEffect : public GrGLEffect {
public:
GrGLTextureDomainEffect(const GrBackendEffectFactory&, const GrEffect&);
virtual void emitCode(GrGLShaderBuilder*,
const GrEffectStage&,
EffectKey,
const char* vertexCoords,
const char* outputColor,
const char* inputColor,
const TextureSamplerArray&) SK_OVERRIDE;
virtual void setData(const GrGLUniformManager&, const GrEffectStage&) SK_OVERRIDE;
static inline EffectKey GenKey(const GrEffectStage&, const GrGLCaps&);
private:
GrGLUniformManager::UniformHandle fNameUni;
GrGLEffectMatrix fEffectMatrix;
GrGLfloat fPrevDomain[4];
typedef GrGLEffect INHERITED;
};
GrGLTextureDomainEffect::GrGLTextureDomainEffect(const GrBackendEffectFactory& factory,
const GrEffect&)
: INHERITED(factory)
, fNameUni(GrGLUniformManager::kInvalidUniformHandle) {
fPrevDomain[0] = SK_FloatNaN;
}
void GrGLTextureDomainEffect::emitCode(GrGLShaderBuilder* builder,
const GrEffectStage&,
EffectKey key,
const char* vertexCoords,
const char* outputColor,
const char* inputColor,
const TextureSamplerArray& samplers) {
const char* coords;
fEffectMatrix.emitCodeMakeFSCoords2D(builder, key, vertexCoords, &coords);
fNameUni = builder->addUniform(GrGLShaderBuilder::kFragment_ShaderType,
kVec4f_GrSLType, "TexDom");
builder->fFSCode.appendf("\tvec2 clampCoord = clamp(%s, %s.xy, %s.zw);\n",
coords,
builder->getUniformCStr(fNameUni),
builder->getUniformCStr(fNameUni));
builder->fFSCode.appendf("\t%s = ", outputColor);
builder->appendTextureLookupAndModulate(&builder->fFSCode,
inputColor,
samplers[0],
"clampCoord");
builder->fFSCode.append(";\n");
}
void GrGLTextureDomainEffect::setData(const GrGLUniformManager& uman, const GrEffectStage& stage) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
const GrRect& domain = effect.domain();
float values[4] = {
SkScalarToFloat(domain.left()),
SkScalarToFloat(domain.top()),
SkScalarToFloat(domain.right()),
SkScalarToFloat(domain.bottom())
};
// vertical flip if necessary
if (GrSurface::kBottomLeft_Origin == effect.texture(0)->origin()) {
values[1] = 1.0f - values[1];
values[3] = 1.0f - values[3];
// The top and bottom were just flipped, so correct the ordering
// of elements so that values = (l, t, r, b).
SkTSwap(values[1], values[3]);
}
if (0 != memcmp(values, fPrevDomain, 4 * sizeof(GrGLfloat))) {
uman.set4fv(fNameUni, 0, 1, values);
}
fEffectMatrix.setData(uman,
effect.getMatrix(),
stage.getCoordChangeMatrix(),
effect.texture(0));
}
GrGLEffect::EffectKey GrGLTextureDomainEffect::GenKey(const GrEffectStage& stage, const GrGLCaps&) {
const GrTextureDomainEffect& effect =
static_cast<const GrTextureDomainEffect&>(*stage.getEffect());
return GrGLEffectMatrix::GenKey(effect.getMatrix(), stage.getCoordChangeMatrix(), effect.texture(0));
}
///////////////////////////////////////////////////////////////////////////////
GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture, const GrRect& domain)
: GrSingleTextureEffect(texture)
, fTextureDomain(domain) {
}
GrTextureDomainEffect::GrTextureDomainEffect(GrTexture* texture,
const GrRect& domain,
const GrTextureParams& params)
: GrSingleTextureEffect(texture, params)
, fTextureDomain(domain) {
}
GrTextureDomainEffect::~GrTextureDomainEffect() {
}
const GrBackendEffectFactory& GrTextureDomainEffect::getFactory() const {
return GrTBackendEffectFactory<GrTextureDomainEffect>::getInstance();
}
bool GrTextureDomainEffect::isEqual(const GrEffect& sBase) const {
const GrTextureDomainEffect& s = static_cast<const GrTextureDomainEffect&>(sBase);
return (INHERITED::isEqual(sBase) && this->fTextureDomain == s.fTextureDomain);
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_EFFECT_TEST(GrTextureDomainEffect);
GrEffect* GrTextureDomainEffect::TestCreate(SkRandom* random,
GrContext* context,
GrTexture* textures[]) {
int texIdx = random->nextBool() ? GrEffectUnitTest::kSkiaPMTextureIdx :
GrEffectUnitTest::kAlphaTextureIdx;
GrRect domain;
domain.fLeft = random->nextUScalar1();
domain.fRight = random->nextRangeScalar(domain.fLeft, SK_Scalar1);
domain.fTop = random->nextUScalar1();
domain.fBottom = random->nextRangeScalar(domain.fTop, SK_Scalar1);
return SkNEW_ARGS(GrTextureDomainEffect, (textures[texIdx], domain));
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2019, Marcus Rowe <[email protected]>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#pragma once
#include "abstractaccessors.h"
#include "listundohelper.h"
namespace UnTech {
namespace GuiQt {
namespace Accessor {
template <class T, class RI>
VectorSingleSelectionAccessor<T, RI>::VectorSingleSelectionAccessor(RI* resourceItem, size_t maxSize)
: AbstractListSingleSelectionAccessor(resourceItem, maxSize)
, _resourceItem(resourceItem)
{
}
template <class T, class RI>
std::tuple<> VectorSingleSelectionAccessor<T, RI>::selectedListTuple() const
{
return std::make_tuple();
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::listExists() const
{
return list() != nullptr;
}
template <class T, class RI>
size_t VectorSingleSelectionAccessor<T, RI>::size() const
{
if (const std::vector<T>* l = list()) {
return l->size();
}
return 0;
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::addItem(size_t index)
{
return UndoHelper(this).addItem(index);
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::cloneItem(size_t index)
{
return UndoHelper(this).cloneItem(index);
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::removeItem(size_t index)
{
return UndoHelper(this).removeItem(index);
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::moveItem(size_t from, size_t to)
{
return UndoHelper(this).moveItem(from, to);
}
template <class T, class RI>
NamedListAccessor<T, RI>::NamedListAccessor(RI* resourceItem, size_t maxSize)
: AbstractNamedListAccessor(resourceItem, maxSize)
{
}
template <class T, class RI>
std::tuple<> NamedListAccessor<T, RI>::selectedListTuple() const
{
return std::make_tuple();
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::listExists() const
{
return list() != nullptr;
}
template <class T, class RI>
size_t NamedListAccessor<T, RI>::size() const
{
if (const NamedList<T>* l = list()) {
return l->size();
}
return 0;
}
template <class T, class RI>
QStringList NamedListAccessor<T, RI>::itemNames() const
{
QStringList qsl;
if (const NamedList<T>* nl = list()) {
qsl.reserve(nl->size());
std::transform(nl->begin(), nl->end(), std::back_inserter(qsl),
[](const T& i) { return QString::fromStdString(i.name); });
}
return qsl;
}
template <class T, class RI>
QString NamedListAccessor<T, RI>::itemName(size_t index) const
{
if (auto* l = list()) {
if (index < l->size()) {
return QString::fromStdString(l->at(index).name);
}
}
return QString();
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::edit_setName(NamedListAccessor::index_type index, const UnTech::idstring& name)
{
return UndoHelper(this).editField(
index, name,
tr("Edit name"),
[](DataT& d) -> idstring& { return d.name; },
[](NamedListAccessor* a, index_type i) { emit a->nameChanged(i); });
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::addItem(size_t index)
{
return UndoHelper(this).addItem(index);
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::addItemWithName(size_t index, const UnTech::idstring& name)
{
T newItem;
newItem.name = name;
return UndoHelper(this).addItem(index, newItem);
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::cloneItem(size_t index)
{
return UndoHelper(this).cloneItem(index);
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::cloneItemWithName(size_t index, const idstring& name)
{
if (auto* item = selectedItem()) {
T newItem = *item;
newItem.name = name;
QString text = tr("Clone %1").arg(typeName());
return UndoHelper(this).addItem(index, newItem, text);
}
return false;
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::removeItem(size_t index)
{
return UndoHelper(this).removeItem(index);
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::moveItem(size_t from, size_t to)
{
return UndoHelper(this).moveItem(from, to);
}
template <class T, class RI>
ChildVectorAccessor<T, RI>::ChildVectorAccessor(AbstractListSingleSelectionAccessor* parentAccessor, RI* resourceItem, size_t maxSize)
: AbstractChildListSingleSelectionAccessor(parentAccessor, maxSize)
{
Q_ASSERT(AbstractListAccessor::resourceItem() == resourceItem);
}
template <class T, class RI>
const std::vector<T>* ChildVectorAccessor<T, RI>::childList() const
{
return list(parentIndex());
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::listExists() const
{
return childList() != nullptr;
}
template <class T, class RI>
size_t ChildVectorAccessor<T, RI>::size() const
{
if (const std::vector<T>* l = childList()) {
return l->size();
}
return 0;
}
template <class T, class RI>
std::tuple<size_t> ChildVectorAccessor<T, RI>::selectedListTuple() const
{
return std::make_tuple(parentIndex());
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::addItem(size_t index)
{
return UndoHelper(this).addItem(index);
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::cloneItem(size_t index)
{
return UndoHelper(this).cloneItem(index);
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::removeItem(size_t index)
{
return UndoHelper(this).removeItem(index);
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::moveItem(size_t from, size_t to)
{
return UndoHelper(this).moveItem(from, to);
}
template <class T, class RI>
ChildVectorMultipleSelectionAccessor<T, RI>::ChildVectorMultipleSelectionAccessor(AbstractListSingleSelectionAccessor* parentAccessor, RI* resourceItem, size_t maxSize)
: AbstractChildListMultipleSelectionAccessor(parentAccessor, maxSize)
{
Q_ASSERT(AbstractListAccessor::resourceItem() == resourceItem);
}
template <class T, class RI>
const std::vector<T>* ChildVectorMultipleSelectionAccessor<T, RI>::childList() const
{
return list(parentIndex());
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::listExists() const
{
return childList() != nullptr;
}
template <class T, class RI>
size_t ChildVectorMultipleSelectionAccessor<T, RI>::size() const
{
if (auto* l = childList()) {
return l->size();
}
return 0;
}
template <class T, class RI>
std::tuple<size_t> ChildVectorMultipleSelectionAccessor<T, RI>::selectedListTuple() const
{
return std::make_tuple(parentIndex());
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::addItem(size_t index)
{
return UndoHelper(this).addItem(index);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::cloneItem(size_t index)
{
return UndoHelper(this).cloneItem(index);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::cloneMultipleItems(const vectorset<size_t>& indexes)
{
return UndoHelper(this).cloneMultipleItems(indexes);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::removeItem(size_t index)
{
return UndoHelper(this).removeItem(index);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::removeMultipleItems(const vectorset<size_t>& indexes)
{
return UndoHelper(this).removeMultipleItems(indexes);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::moveItem(size_t from, size_t to)
{
return UndoHelper(this).moveItem(from, to);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::moveMultipleItems(const vectorset<size_t>& indexes, int offset)
{
return UndoHelper(this).moveMultipleItems(indexes, offset);
}
}
}
}
<commit_msg>Fix NamedListAccessor::cloneItemWithName<commit_after>/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2019, Marcus Rowe <[email protected]>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#pragma once
#include "abstractaccessors.h"
#include "listundohelper.h"
namespace UnTech {
namespace GuiQt {
namespace Accessor {
template <class T, class RI>
VectorSingleSelectionAccessor<T, RI>::VectorSingleSelectionAccessor(RI* resourceItem, size_t maxSize)
: AbstractListSingleSelectionAccessor(resourceItem, maxSize)
, _resourceItem(resourceItem)
{
}
template <class T, class RI>
std::tuple<> VectorSingleSelectionAccessor<T, RI>::selectedListTuple() const
{
return std::make_tuple();
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::listExists() const
{
return list() != nullptr;
}
template <class T, class RI>
size_t VectorSingleSelectionAccessor<T, RI>::size() const
{
if (const std::vector<T>* l = list()) {
return l->size();
}
return 0;
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::addItem(size_t index)
{
return UndoHelper(this).addItem(index);
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::cloneItem(size_t index)
{
return UndoHelper(this).cloneItem(index);
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::removeItem(size_t index)
{
return UndoHelper(this).removeItem(index);
}
template <class T, class RI>
bool VectorSingleSelectionAccessor<T, RI>::moveItem(size_t from, size_t to)
{
return UndoHelper(this).moveItem(from, to);
}
template <class T, class RI>
NamedListAccessor<T, RI>::NamedListAccessor(RI* resourceItem, size_t maxSize)
: AbstractNamedListAccessor(resourceItem, maxSize)
{
}
template <class T, class RI>
std::tuple<> NamedListAccessor<T, RI>::selectedListTuple() const
{
return std::make_tuple();
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::listExists() const
{
return list() != nullptr;
}
template <class T, class RI>
size_t NamedListAccessor<T, RI>::size() const
{
if (const NamedList<T>* l = list()) {
return l->size();
}
return 0;
}
template <class T, class RI>
QStringList NamedListAccessor<T, RI>::itemNames() const
{
QStringList qsl;
if (const NamedList<T>* nl = list()) {
qsl.reserve(nl->size());
std::transform(nl->begin(), nl->end(), std::back_inserter(qsl),
[](const T& i) { return QString::fromStdString(i.name); });
}
return qsl;
}
template <class T, class RI>
QString NamedListAccessor<T, RI>::itemName(size_t index) const
{
if (auto* l = list()) {
if (index < l->size()) {
return QString::fromStdString(l->at(index).name);
}
}
return QString();
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::edit_setName(NamedListAccessor::index_type index, const UnTech::idstring& name)
{
return UndoHelper(this).editField(
index, name,
tr("Edit name"),
[](DataT& d) -> idstring& { return d.name; },
[](NamedListAccessor* a, index_type i) { emit a->nameChanged(i); });
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::addItem(size_t index)
{
return UndoHelper(this).addItem(index);
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::addItemWithName(size_t index, const UnTech::idstring& name)
{
T newItem;
newItem.name = name;
return UndoHelper(this).addItem(index, newItem);
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::cloneItem(size_t index)
{
return UndoHelper(this).cloneItem(index);
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::cloneItemWithName(size_t index, const idstring& name)
{
if (auto* item = selectedItem()) {
T newItem = *item;
newItem.name = name;
QString text = tr("Clone %1").arg(typeName());
return UndoHelper(this).addItem(index + 1, newItem, text);
}
return false;
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::removeItem(size_t index)
{
return UndoHelper(this).removeItem(index);
}
template <class T, class RI>
bool NamedListAccessor<T, RI>::moveItem(size_t from, size_t to)
{
return UndoHelper(this).moveItem(from, to);
}
template <class T, class RI>
ChildVectorAccessor<T, RI>::ChildVectorAccessor(AbstractListSingleSelectionAccessor* parentAccessor, RI* resourceItem, size_t maxSize)
: AbstractChildListSingleSelectionAccessor(parentAccessor, maxSize)
{
Q_ASSERT(AbstractListAccessor::resourceItem() == resourceItem);
}
template <class T, class RI>
const std::vector<T>* ChildVectorAccessor<T, RI>::childList() const
{
return list(parentIndex());
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::listExists() const
{
return childList() != nullptr;
}
template <class T, class RI>
size_t ChildVectorAccessor<T, RI>::size() const
{
if (const std::vector<T>* l = childList()) {
return l->size();
}
return 0;
}
template <class T, class RI>
std::tuple<size_t> ChildVectorAccessor<T, RI>::selectedListTuple() const
{
return std::make_tuple(parentIndex());
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::addItem(size_t index)
{
return UndoHelper(this).addItem(index);
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::cloneItem(size_t index)
{
return UndoHelper(this).cloneItem(index);
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::removeItem(size_t index)
{
return UndoHelper(this).removeItem(index);
}
template <class T, class RI>
bool ChildVectorAccessor<T, RI>::moveItem(size_t from, size_t to)
{
return UndoHelper(this).moveItem(from, to);
}
template <class T, class RI>
ChildVectorMultipleSelectionAccessor<T, RI>::ChildVectorMultipleSelectionAccessor(AbstractListSingleSelectionAccessor* parentAccessor, RI* resourceItem, size_t maxSize)
: AbstractChildListMultipleSelectionAccessor(parentAccessor, maxSize)
{
Q_ASSERT(AbstractListAccessor::resourceItem() == resourceItem);
}
template <class T, class RI>
const std::vector<T>* ChildVectorMultipleSelectionAccessor<T, RI>::childList() const
{
return list(parentIndex());
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::listExists() const
{
return childList() != nullptr;
}
template <class T, class RI>
size_t ChildVectorMultipleSelectionAccessor<T, RI>::size() const
{
if (auto* l = childList()) {
return l->size();
}
return 0;
}
template <class T, class RI>
std::tuple<size_t> ChildVectorMultipleSelectionAccessor<T, RI>::selectedListTuple() const
{
return std::make_tuple(parentIndex());
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::addItem(size_t index)
{
return UndoHelper(this).addItem(index);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::cloneItem(size_t index)
{
return UndoHelper(this).cloneItem(index);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::cloneMultipleItems(const vectorset<size_t>& indexes)
{
return UndoHelper(this).cloneMultipleItems(indexes);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::removeItem(size_t index)
{
return UndoHelper(this).removeItem(index);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::removeMultipleItems(const vectorset<size_t>& indexes)
{
return UndoHelper(this).removeMultipleItems(indexes);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::moveItem(size_t from, size_t to)
{
return UndoHelper(this).moveItem(from, to);
}
template <class T, class RI>
bool ChildVectorMultipleSelectionAccessor<T, RI>::moveMultipleItems(const vectorset<size_t>& indexes, int offset)
{
return UndoHelper(this).moveMultipleItems(indexes, offset);
}
}
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "evaluatorscriptclass.h"
#include "builtinvalue.h"
#include "evaluationdata.h"
#include "evaluator.h"
#include "item.h"
#include "filecontext.h"
#include <tools/qbsassert.h>
#include <QScriptEngine>
#include <QScriptString>
#include <QScriptValue>
#include <QDebug>
namespace qbs {
namespace Internal {
class SVConverter : ValueHandler
{
EvaluatorScriptClass *const scriptClass;
QScriptEngine *const engine;
QScriptContext *const scriptContext;
const QScriptValue *object;
const ValuePtr &valuePtr;
const bool inPrototype;
char pushedScopesCount;
public:
const QScriptString *propertyName;
const EvaluationData *data;
QScriptValue *result;
SVConverter(EvaluatorScriptClass *esc, const QScriptValue *obj, const ValuePtr &v,
bool _inPrototype)
: scriptClass(esc)
, engine(esc->engine())
, scriptContext(esc->engine()->currentContext())
, object(obj)
, valuePtr(v)
, inPrototype(_inPrototype)
, pushedScopesCount(0)
{
}
void start()
{
valuePtr->apply(this);
}
private:
void setupConvenienceProperty(const QString &conveniencePropertyName, QScriptValue *extraScope,
const QScriptValue &scriptValue)
{
if (!extraScope->isObject())
*extraScope = scriptClass->engine()->newObject();
if (!scriptValue.isValid() || scriptValue.isUndefined()) {
// If there's no such value, use an empty array to have the convenience property
// still available.
extraScope->setProperty(conveniencePropertyName, engine->newArray());
} else {
extraScope->setProperty(conveniencePropertyName, scriptValue);
}
}
void pushScope(const QScriptValue &scope)
{
if (scope.isObject()) {
scriptContext->pushScope(scope);
++pushedScopesCount;
}
}
void pushItemScopes(const Item *item)
{
const ItemConstPtr scope = item->scope();
if (scope) {
pushItemScopes(scope.data());
pushScope(data->evaluator->scriptValue(scope));
}
}
void popScopes()
{
for (; pushedScopesCount-- > 0;)
scriptContext->popScope();
}
void handle(JSSourceValue *value)
{
ItemConstPtr conditionScopeItem;
QScriptValue conditionScope;
QScriptValue conditionFileScope;
ItemPtr outerItem = data->item->outerItem();
for (int i = 0; i < value->alternatives().count(); ++i) {
const JSSourceValue::Alternative *alternative = 0;
alternative = &value->alternatives().at(i);
if (conditionScopeItem != alternative->conditionScopeItem) {
conditionScopeItem = alternative->conditionScopeItem;
conditionScope = data->evaluator->scriptValue(alternative->conditionScopeItem);
QBS_ASSERT(conditionScope.isObject(), return);
conditionFileScope = data->evaluator->fileScope(conditionScopeItem->file());
}
engine->currentContext()->pushScope(conditionFileScope);
pushItemScopes(conditionScopeItem.data());
engine->currentContext()->pushScope(conditionScope);
const QScriptValue cr = engine->evaluate(alternative->condition);
engine->currentContext()->popScope();
engine->currentContext()->popScope();
popScopes();
if (cr.isError()) {
*result = cr;
return;
}
if (cr.toBool()) {
// condition is true, let's use the value of this alternative
if (alternative->value->sourceUsesOuter()) {
// Clone value but without alternatives.
JSSourceValuePtr outerValue = JSSourceValue::create();
outerValue->setFile(value->file());
outerValue->setSourceCode(value->sourceCode());
outerValue->setBaseValue(value->baseValue());
outerValue->setLocation(value->location());
outerItem = Item::create();
outerItem->setProperty(propertyName->toString(), outerValue);
}
value = alternative->value.data();
break;
}
}
QScriptValue extraScope;
if (value->sourceUsesBase()) {
QScriptValue baseValue;
if (value->baseValue()) {
SVConverter converter(scriptClass, object, value->baseValue(), inPrototype);
converter.propertyName = propertyName;
converter.data = data;
converter.result = &baseValue;
converter.start();
}
setupConvenienceProperty(QLatin1String("base"), &extraScope, baseValue);
}
if (value->sourceUsesOuter() && outerItem)
setupConvenienceProperty(QLatin1String("outer"), &extraScope,
data->evaluator->property(outerItem, *propertyName));
pushScope(data->evaluator->fileScope(value->file()));
pushItemScopes(data->item);
if (inPrototype || !data->item->isModuleInstance()) {
// Own properties of module instances must not have the instance itself in the scope.
pushScope(*object);
}
pushScope(extraScope);
*result = engine->evaluate(value->sourceCode());
popScopes();
}
void handle(ItemValue *value)
{
const ItemPtr &item = value->item();
if (!item)
qDebug() << "SVConverter got null item" << propertyName->toString();
*result = data->evaluator->scriptValue(item);
if (!result->isValid())
qDebug() << "SVConverter returned invalid script value.";
}
void handle(VariantValue *variantValue)
{
*result = scriptClass->engine()->toScriptValue(variantValue->value());
}
void handle(BuiltinValue *builtinValue)
{
*result = scriptClass->scriptValueForBuiltin(builtinValue->builtin());
}
};
bool debugProperties = false;
enum QueryPropertyType
{
QPTDefault,
QPTParentProperty
};
EvaluatorScriptClass::EvaluatorScriptClass(QScriptEngine *scriptEngine, const Logger &logger)
: QScriptClass(scriptEngine)
, m_logger(logger)
{
m_getenvBuiltin = scriptEngine->newFunction(js_getenv, 1);
m_getHostOSBuiltin = scriptEngine->newFunction(js_getHostOS, 1);
}
QScriptClass::QueryFlags EvaluatorScriptClass::queryProperty(const QScriptValue &object,
const QScriptString &name,
QScriptClass::QueryFlags flags,
uint *id)
{
Q_UNUSED(flags);
// We assume that it's safe to save the result of the query in a member of the scriptclass.
// It must be cleared in the property method before doing any further lookup.
QBS_ASSERT(m_queryResult.isNull(), return QueryFlags());
if (debugProperties)
m_logger.qbsTrace() << "[SC] queryProperty " << object.objectId() << " " << name;
EvaluationData *const data = EvaluationData::get(object);
const QString nameString = name.toString();
if (nameString == QLatin1String("parent")) {
*id = QPTParentProperty;
m_queryResult.data = data;
return QScriptClass::HandlesReadAccess;
}
*id = QPTDefault;
if (!data) {
if (debugProperties)
m_logger.qbsTrace() << "[SC] queryProperty: no data attached";
return QScriptClass::QueryFlags();
}
return queryItemProperty(data, nameString);
}
QScriptClass::QueryFlags EvaluatorScriptClass::queryItemProperty(const EvaluationData *data,
const QString &name,
bool ignoreParent)
{
for (const Item *item = data->item; item; item = item->prototype().data()) {
m_queryResult.value = item->properties().value(name);
if (!m_queryResult.value.isNull()) {
m_queryResult.data = data;
if (data->item != item)
m_queryResult.inPrototype = true;
return HandlesReadAccess;
}
}
if (!ignoreParent && !data->item->parent().isNull()) {
if (debugProperties)
m_logger.qbsTrace() << "[SC] queryProperty: query parent";
EvaluationData parentdata = *data;
parentdata.item = data->item->parent().data();
const QueryFlags qf = queryItemProperty(&parentdata, name, true);
if (qf.testFlag(HandlesReadAccess)) {
m_queryResult.data = data;
return qf;
}
}
if (debugProperties)
m_logger.qbsTrace() << "[SC] queryProperty: no such property";
return QScriptClass::QueryFlags();
}
QString EvaluatorScriptClass::resultToString(const QScriptValue &scriptValue)
{
return (scriptValue.isObject()
? QLatin1String("[Object: ")
+ QString::number(scriptValue.objectId(), 16) + QLatin1Char(']')
: scriptValue.toVariant().toString());
}
ItemPtr EvaluatorScriptClass::findParentOfType(const Item *item, const QString &typeName)
{
for (ItemPtr it = item->parent(); it; it = it->parent()) {
if (it->typeName() == typeName)
return it;
}
return ItemPtr();
}
QScriptValue EvaluatorScriptClass::property(const QScriptValue &object, const QScriptString &name,
uint id)
{
const EvaluationData *data = m_queryResult.data;
const bool inPrototype = m_queryResult.inPrototype;
m_queryResult.data = 0;
m_queryResult.inPrototype = false;
QBS_ASSERT(data, return QScriptValue());
const QueryPropertyType qpt = static_cast<QueryPropertyType>(id);
if (qpt == QPTParentProperty) {
return data->item->parent().isNull() ?
engine()->undefinedValue() : data->evaluator->scriptValue(data->item->parent());
}
ValuePtr value;
m_queryResult.value.swap(value);
QBS_ASSERT(value, return QScriptValue());
QBS_ASSERT(m_queryResult.isNull(), return QScriptValue());
if (debugProperties)
m_logger.qbsTrace() << "[SC] property " << name;
QScriptValue result = data->valueCache.value(name);
if (result.isValid()) {
if (debugProperties)
m_logger.qbsTrace() << "[SC] cache hit " << name << ": " << resultToString(result);
return result;
}
SVConverter converter(this, &object, value, inPrototype);
converter.propertyName = &name;
converter.data = data;
converter.result = &result;
converter.start();
if (debugProperties)
m_logger.qbsTrace() << "[SC] cache miss " << name << ": " << resultToString(result);
data->valueCache.insert(name, result);
return result;
}
QScriptValue EvaluatorScriptClass::scriptValueForBuiltin(BuiltinValue::Builtin builtin) const
{
switch (builtin) {
case BuiltinValue::GetEnvFunction:
return m_getenvBuiltin;
case BuiltinValue::GetHostOSFunction:
return m_getHostOSBuiltin;
}
QBS_ASSERT(!"unhandled builtin", ;);
return QScriptValue();
}
QScriptValue EvaluatorScriptClass::js_getenv(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 1) {
return context->throwError(QScriptContext::SyntaxError,
QLatin1String("getenv expects 1 argument"));
}
const QByteArray name = context->argument(0).toString().toLocal8Bit();
const QByteArray value = qgetenv(name);
return value.isNull() ? engine->undefinedValue() : QString::fromLocal8Bit(value);
}
QScriptValue EvaluatorScriptClass::js_getHostOS(QScriptContext *context, QScriptEngine *engine)
{
Q_UNUSED(context);
QString hostSystem;
#if defined(Q_OS_WIN)
hostSystem = "windows";
#elif defined(Q_OS_MAC)
hostSystem = "mac";
#elif defined(Q_OS_LINUX)
hostSystem = "linux";
#elif defined(Q_OS_UNIX)
hostSystem = "unix";
#else
# error unknown host platform
#endif
return engine->toScriptValue(hostSystem);
}
} // namespace Internal
} // namespace qbs
<commit_msg>make SVConverter::popScopes reusable<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "evaluatorscriptclass.h"
#include "builtinvalue.h"
#include "evaluationdata.h"
#include "evaluator.h"
#include "item.h"
#include "filecontext.h"
#include <tools/qbsassert.h>
#include <QScriptEngine>
#include <QScriptString>
#include <QScriptValue>
#include <QDebug>
namespace qbs {
namespace Internal {
class SVConverter : ValueHandler
{
EvaluatorScriptClass *const scriptClass;
QScriptEngine *const engine;
QScriptContext *const scriptContext;
const QScriptValue *object;
const ValuePtr &valuePtr;
const bool inPrototype;
char pushedScopesCount;
public:
const QScriptString *propertyName;
const EvaluationData *data;
QScriptValue *result;
SVConverter(EvaluatorScriptClass *esc, const QScriptValue *obj, const ValuePtr &v,
bool _inPrototype)
: scriptClass(esc)
, engine(esc->engine())
, scriptContext(esc->engine()->currentContext())
, object(obj)
, valuePtr(v)
, inPrototype(_inPrototype)
, pushedScopesCount(0)
{
}
void start()
{
valuePtr->apply(this);
}
private:
void setupConvenienceProperty(const QString &conveniencePropertyName, QScriptValue *extraScope,
const QScriptValue &scriptValue)
{
if (!extraScope->isObject())
*extraScope = scriptClass->engine()->newObject();
if (!scriptValue.isValid() || scriptValue.isUndefined()) {
// If there's no such value, use an empty array to have the convenience property
// still available.
extraScope->setProperty(conveniencePropertyName, engine->newArray());
} else {
extraScope->setProperty(conveniencePropertyName, scriptValue);
}
}
void pushScope(const QScriptValue &scope)
{
if (scope.isObject()) {
scriptContext->pushScope(scope);
++pushedScopesCount;
}
}
void pushItemScopes(const Item *item)
{
const ItemConstPtr scope = item->scope();
if (scope) {
pushItemScopes(scope.data());
pushScope(data->evaluator->scriptValue(scope));
}
}
void popScopes()
{
for (; pushedScopesCount; --pushedScopesCount)
scriptContext->popScope();
}
void handle(JSSourceValue *value)
{
ItemConstPtr conditionScopeItem;
QScriptValue conditionScope;
QScriptValue conditionFileScope;
ItemPtr outerItem = data->item->outerItem();
for (int i = 0; i < value->alternatives().count(); ++i) {
const JSSourceValue::Alternative *alternative = 0;
alternative = &value->alternatives().at(i);
if (conditionScopeItem != alternative->conditionScopeItem) {
conditionScopeItem = alternative->conditionScopeItem;
conditionScope = data->evaluator->scriptValue(alternative->conditionScopeItem);
QBS_ASSERT(conditionScope.isObject(), return);
conditionFileScope = data->evaluator->fileScope(conditionScopeItem->file());
}
engine->currentContext()->pushScope(conditionFileScope);
pushItemScopes(conditionScopeItem.data());
engine->currentContext()->pushScope(conditionScope);
const QScriptValue cr = engine->evaluate(alternative->condition);
engine->currentContext()->popScope();
engine->currentContext()->popScope();
popScopes();
if (cr.isError()) {
*result = cr;
return;
}
if (cr.toBool()) {
// condition is true, let's use the value of this alternative
if (alternative->value->sourceUsesOuter()) {
// Clone value but without alternatives.
JSSourceValuePtr outerValue = JSSourceValue::create();
outerValue->setFile(value->file());
outerValue->setSourceCode(value->sourceCode());
outerValue->setBaseValue(value->baseValue());
outerValue->setLocation(value->location());
outerItem = Item::create();
outerItem->setProperty(propertyName->toString(), outerValue);
}
value = alternative->value.data();
break;
}
}
QScriptValue extraScope;
if (value->sourceUsesBase()) {
QScriptValue baseValue;
if (value->baseValue()) {
SVConverter converter(scriptClass, object, value->baseValue(), inPrototype);
converter.propertyName = propertyName;
converter.data = data;
converter.result = &baseValue;
converter.start();
}
setupConvenienceProperty(QLatin1String("base"), &extraScope, baseValue);
}
if (value->sourceUsesOuter() && outerItem)
setupConvenienceProperty(QLatin1String("outer"), &extraScope,
data->evaluator->property(outerItem, *propertyName));
pushScope(data->evaluator->fileScope(value->file()));
pushItemScopes(data->item);
if (inPrototype || !data->item->isModuleInstance()) {
// Own properties of module instances must not have the instance itself in the scope.
pushScope(*object);
}
pushScope(extraScope);
*result = engine->evaluate(value->sourceCode());
popScopes();
}
void handle(ItemValue *value)
{
const ItemPtr &item = value->item();
if (!item)
qDebug() << "SVConverter got null item" << propertyName->toString();
*result = data->evaluator->scriptValue(item);
if (!result->isValid())
qDebug() << "SVConverter returned invalid script value.";
}
void handle(VariantValue *variantValue)
{
*result = scriptClass->engine()->toScriptValue(variantValue->value());
}
void handle(BuiltinValue *builtinValue)
{
*result = scriptClass->scriptValueForBuiltin(builtinValue->builtin());
}
};
bool debugProperties = false;
enum QueryPropertyType
{
QPTDefault,
QPTParentProperty
};
EvaluatorScriptClass::EvaluatorScriptClass(QScriptEngine *scriptEngine, const Logger &logger)
: QScriptClass(scriptEngine)
, m_logger(logger)
{
m_getenvBuiltin = scriptEngine->newFunction(js_getenv, 1);
m_getHostOSBuiltin = scriptEngine->newFunction(js_getHostOS, 1);
}
QScriptClass::QueryFlags EvaluatorScriptClass::queryProperty(const QScriptValue &object,
const QScriptString &name,
QScriptClass::QueryFlags flags,
uint *id)
{
Q_UNUSED(flags);
// We assume that it's safe to save the result of the query in a member of the scriptclass.
// It must be cleared in the property method before doing any further lookup.
QBS_ASSERT(m_queryResult.isNull(), return QueryFlags());
if (debugProperties)
m_logger.qbsTrace() << "[SC] queryProperty " << object.objectId() << " " << name;
EvaluationData *const data = EvaluationData::get(object);
const QString nameString = name.toString();
if (nameString == QLatin1String("parent")) {
*id = QPTParentProperty;
m_queryResult.data = data;
return QScriptClass::HandlesReadAccess;
}
*id = QPTDefault;
if (!data) {
if (debugProperties)
m_logger.qbsTrace() << "[SC] queryProperty: no data attached";
return QScriptClass::QueryFlags();
}
return queryItemProperty(data, nameString);
}
QScriptClass::QueryFlags EvaluatorScriptClass::queryItemProperty(const EvaluationData *data,
const QString &name,
bool ignoreParent)
{
for (const Item *item = data->item; item; item = item->prototype().data()) {
m_queryResult.value = item->properties().value(name);
if (!m_queryResult.value.isNull()) {
m_queryResult.data = data;
if (data->item != item)
m_queryResult.inPrototype = true;
return HandlesReadAccess;
}
}
if (!ignoreParent && !data->item->parent().isNull()) {
if (debugProperties)
m_logger.qbsTrace() << "[SC] queryProperty: query parent";
EvaluationData parentdata = *data;
parentdata.item = data->item->parent().data();
const QueryFlags qf = queryItemProperty(&parentdata, name, true);
if (qf.testFlag(HandlesReadAccess)) {
m_queryResult.data = data;
return qf;
}
}
if (debugProperties)
m_logger.qbsTrace() << "[SC] queryProperty: no such property";
return QScriptClass::QueryFlags();
}
QString EvaluatorScriptClass::resultToString(const QScriptValue &scriptValue)
{
return (scriptValue.isObject()
? QLatin1String("[Object: ")
+ QString::number(scriptValue.objectId(), 16) + QLatin1Char(']')
: scriptValue.toVariant().toString());
}
ItemPtr EvaluatorScriptClass::findParentOfType(const Item *item, const QString &typeName)
{
for (ItemPtr it = item->parent(); it; it = it->parent()) {
if (it->typeName() == typeName)
return it;
}
return ItemPtr();
}
QScriptValue EvaluatorScriptClass::property(const QScriptValue &object, const QScriptString &name,
uint id)
{
const EvaluationData *data = m_queryResult.data;
const bool inPrototype = m_queryResult.inPrototype;
m_queryResult.data = 0;
m_queryResult.inPrototype = false;
QBS_ASSERT(data, return QScriptValue());
const QueryPropertyType qpt = static_cast<QueryPropertyType>(id);
if (qpt == QPTParentProperty) {
return data->item->parent().isNull() ?
engine()->undefinedValue() : data->evaluator->scriptValue(data->item->parent());
}
ValuePtr value;
m_queryResult.value.swap(value);
QBS_ASSERT(value, return QScriptValue());
QBS_ASSERT(m_queryResult.isNull(), return QScriptValue());
if (debugProperties)
m_logger.qbsTrace() << "[SC] property " << name;
QScriptValue result = data->valueCache.value(name);
if (result.isValid()) {
if (debugProperties)
m_logger.qbsTrace() << "[SC] cache hit " << name << ": " << resultToString(result);
return result;
}
SVConverter converter(this, &object, value, inPrototype);
converter.propertyName = &name;
converter.data = data;
converter.result = &result;
converter.start();
if (debugProperties)
m_logger.qbsTrace() << "[SC] cache miss " << name << ": " << resultToString(result);
data->valueCache.insert(name, result);
return result;
}
QScriptValue EvaluatorScriptClass::scriptValueForBuiltin(BuiltinValue::Builtin builtin) const
{
switch (builtin) {
case BuiltinValue::GetEnvFunction:
return m_getenvBuiltin;
case BuiltinValue::GetHostOSFunction:
return m_getHostOSBuiltin;
}
QBS_ASSERT(!"unhandled builtin", ;);
return QScriptValue();
}
QScriptValue EvaluatorScriptClass::js_getenv(QScriptContext *context, QScriptEngine *engine)
{
if (context->argumentCount() < 1) {
return context->throwError(QScriptContext::SyntaxError,
QLatin1String("getenv expects 1 argument"));
}
const QByteArray name = context->argument(0).toString().toLocal8Bit();
const QByteArray value = qgetenv(name);
return value.isNull() ? engine->undefinedValue() : QString::fromLocal8Bit(value);
}
QScriptValue EvaluatorScriptClass::js_getHostOS(QScriptContext *context, QScriptEngine *engine)
{
Q_UNUSED(context);
QString hostSystem;
#if defined(Q_OS_WIN)
hostSystem = "windows";
#elif defined(Q_OS_MAC)
hostSystem = "mac";
#elif defined(Q_OS_LINUX)
hostSystem = "linux";
#elif defined(Q_OS_UNIX)
hostSystem = "unix";
#else
# error unknown host platform
#endif
return engine->toScriptValue(hostSystem);
}
} // namespace Internal
} // namespace qbs
<|endoftext|>
|
<commit_before>extern "C" {
#include "halide_hexagon_remote.h"
#include <sys/mman.h>
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FARF_LOW 1
#include "HAP_farf.h"
}
#define DEBUG_PRINT(x) FARF(LOW, "%s", x);
#include "elf.h"
#include "../HalideRuntime.h"
typedef halide_hexagon_remote_handle_t handle_t;
typedef halide_hexagon_remote_buffer buffer;
void halide_print(void *user_context, const char *str) {
FARF(LOW, "%s", str);
}
void halide_error(void *user_context, const char *str) {
halide_print(user_context, str);
}
void *halide_malloc(void *user_context, size_t x) {
// Allocate enough space for aligning the pointer we return.
const size_t alignment = 128;
void *orig = malloc(x + alignment);
if (orig == NULL) {
// Will result in a failed assertion and a call to halide_error
return NULL;
}
// We want to store the original pointer prior to the pointer we return.
void *ptr = (void *)(((size_t)orig + alignment + sizeof(void*) - 1) & ~(alignment - 1));
((void **)ptr)[-1] = orig;
return ptr;
}
void halide_free(void *user_context, void *ptr) {
free(((void**)ptr)[-1]);
}
int halide_do_task(void *user_context, halide_task_t f, int idx,
uint8_t *closure) {
return f(user_context, idx, closure);
}
int halide_do_par_for(void *user_context, halide_task_t f,
int min, int size, uint8_t *closure) {
for (int x = min; x < min + size; x++) {
int result = halide_do_task(user_context, f, x, closure);
if (result) {
return result;
}
}
return 0;
}
extern "C" {
const int map_alignment = 4096;
typedef int (*init_runtime_t)(halide_malloc_t user_malloc,
halide_free_t custom_free,
halide_print_t print,
halide_error_handler_t error_handler,
halide_do_par_for_t do_par_for,
halide_do_task_t do_task);
int halide_hexagon_remote_initialize_kernels(const unsigned char *code, int codeLen,
handle_t *module_ptr) {
#if 1 // Use shared object
#if 1 // Use shared object from file
const char *filename = (const char *)code;
#else
const char *filename = "/data/halide_kernels.so";
FILE* fd = fopen(filename, "w");
if (!fd) {
FARF(LOW, "fopen failed");
return -1;
}
fwrite(code, codeLen, 1, fd);
fclose(fd);
#endif
void *lib = dlopen(filename, RTLD_LOCAL | RTLD_LAZY);
if (!lib) {
FARF(LOW, "dlopen failed");
return -1;
}
// Initialize the runtime. The Hexagon runtime can't call any
// system functions (because we can't link them), so we put all
// the implementations that need to do so here, and pass poiners
// to them in here.
init_runtime_t init_runtime = (init_runtime_t)dlsym(lib, "halide_noos_init_runtime");
if (!init_runtime) {
dlclose(lib);
FARF(LOW, "halide_noos_init_runtime not found in shared object");
return -1;
}
int result = init_runtime(halide_malloc,
halide_free,
halide_print,
halide_error,
halide_do_par_for,
halide_do_task);
if (result != 0) {
dlclose(lib);
FARF(LOW, "init_runtime failed %d", result);
return result;
}
*module_ptr = reinterpret_cast<handle_t>(lib);
return 0;
#else
// Map some memory for the code and copy it in.
int aligned_codeLen = (codeLen + map_alignment - 1) & ~(map_alignment - 1);
void *executable = mmap(0, aligned_codeLen, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
if (executable == MAP_FAILED) {
FARF(LOW, "mmap failed");
return -1;
}
memcpy(executable, code, codeLen);
Elf::Object<uint32_t> obj;
result = obj.init(executable);
if (result != 0) {
FARF(LOW, "obj.init failed");
return result;
}
result = obj.do_relocations();
if (result != 0) {
FARF(LOW, "obj.do_relocations failed");
return result;
}
handle_t base_addr = (handle_t)executable;
// Change memory to be executable (but not writable).
if (mprotect(executable, aligned_codeLen, PROT_READ | PROT_EXEC) < 0) {
munmap(executable, aligned_codeLen);
FARF(LOW, "mprotect failed");
return -1;
}
// Initialize the runtime. The Hexagon runtime can't call any
// system functions (because we can't link them), so we put all
// the implementations that need to do so here, and pass poiners
// to them in here.
init_runtime_t init_runtime = (init_runtime_t)obj.symbol_address("halide_noos_init_runtime");
if (init_runtime == 0) {
munmap(executable, aligned_codeLen);
FARF(LOW, "Failed to find symbol halide_noos_init_runtime");
return -1;
}
int result = init_runtime(halide_malloc,
halide_free,
halide_print,
halide_error,
halide_do_par_for,
halide_do_task);
if (result != 0) {
munmap(executable, aligned_codeLen);
FARF(LOW, "init_runtime failed %d", result);
return result;
}
*module_ptr = base_addr;
return 0;
#endif
}
handle_t halide_hexagon_remote_get_symbol(handle_t module_ptr, const char* name, int nameLen) {
#if 1
return reinterpret_cast<handle_t>(dlsym(reinterpret_cast<void*>(module_ptr), name));
#else
Elf::Object<uint32_t> obj;
int result = obj.init((void*)module_ptr);
if (result != 0) {
FARF(LOW, "Object::init failed: %d", result);
return 0;
}
return (handle_t)obj.symbol_address(name);
#endif
}
int halide_hexagon_remote_run(handle_t module_ptr, handle_t function,
const buffer *arg_ptrs, int arg_ptrsLen,
buffer *outputs, int outputsLen) {
// Get a pointer to the argv version of the pipeline.
typedef int (*pipeline_argv_t)(void **);
pipeline_argv_t pipeline = reinterpret_cast<pipeline_argv_t>(function);
// Construct a list of arguments.
void **args = (void **)__builtin_alloca((arg_ptrsLen + outputsLen) * sizeof(void *));
for (int i = 0; i < arg_ptrsLen; i++) {
args[i] = arg_ptrs[i].data;
}
for (int i = 0; i < outputsLen; i++) {
args[i + arg_ptrsLen] = outputs[i].data;
}
// Call the pipeline and return the result.
return pipeline(args);
}
int halide_hexagon_remote_release_kernels(handle_t module_ptr, int codeLen) {
#if 1
dlclose(reinterpret_cast<void*>(module_ptr));
#else
void *executable = (void *)module_ptr;
codeLen = (codeLen + map_alignment - 1) & (map_alignment - 1);
munmap(executable, codeLen);
#endif
return 0;
}
} // extern "C"
<commit_msg>Make fake buffer_t objects for outputs.<commit_after>extern "C" {
#include "halide_hexagon_remote.h"
#include <sys/mman.h>
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FARF_LOW 1
#include "HAP_farf.h"
}
#define DEBUG_PRINT(x) FARF(LOW, "%s", x);
#include "elf.h"
#include "../HalideRuntime.h"
typedef halide_hexagon_remote_handle_t handle_t;
typedef halide_hexagon_remote_buffer buffer;
void halide_print(void *user_context, const char *str) {
FARF(LOW, "%s", str);
}
void halide_error(void *user_context, const char *str) {
halide_print(user_context, str);
}
void *halide_malloc(void *user_context, size_t x) {
// Allocate enough space for aligning the pointer we return.
const size_t alignment = 128;
void *orig = malloc(x + alignment);
if (orig == NULL) {
// Will result in a failed assertion and a call to halide_error
return NULL;
}
// We want to store the original pointer prior to the pointer we return.
void *ptr = (void *)(((size_t)orig + alignment + sizeof(void*) - 1) & ~(alignment - 1));
((void **)ptr)[-1] = orig;
return ptr;
}
void halide_free(void *user_context, void *ptr) {
free(((void**)ptr)[-1]);
}
int halide_do_task(void *user_context, halide_task_t f, int idx,
uint8_t *closure) {
return f(user_context, idx, closure);
}
int halide_do_par_for(void *user_context, halide_task_t f,
int min, int size, uint8_t *closure) {
for (int x = min; x < min + size; x++) {
int result = halide_do_task(user_context, f, x, closure);
if (result) {
return result;
}
}
return 0;
}
extern "C" {
const int map_alignment = 4096;
typedef int (*init_runtime_t)(halide_malloc_t user_malloc,
halide_free_t custom_free,
halide_print_t print,
halide_error_handler_t error_handler,
halide_do_par_for_t do_par_for,
halide_do_task_t do_task);
int halide_hexagon_remote_initialize_kernels(const unsigned char *code, int codeLen,
handle_t *module_ptr) {
#if 1 // Use shared object
#if 1 // Use shared object from file
const char *filename = (const char *)code;
#else
const char *filename = "/data/halide_kernels.so";
FILE* fd = fopen(filename, "w");
if (!fd) {
FARF(LOW, "fopen failed");
return -1;
}
fwrite(code, codeLen, 1, fd);
fclose(fd);
#endif
void *lib = dlopen(filename, RTLD_LOCAL | RTLD_LAZY);
if (!lib) {
FARF(LOW, "dlopen failed");
return -1;
}
// Initialize the runtime. The Hexagon runtime can't call any
// system functions (because we can't link them), so we put all
// the implementations that need to do so here, and pass poiners
// to them in here.
init_runtime_t init_runtime = (init_runtime_t)dlsym(lib, "halide_noos_init_runtime");
if (!init_runtime) {
dlclose(lib);
FARF(LOW, "halide_noos_init_runtime not found in shared object");
return -1;
}
int result = init_runtime(halide_malloc,
halide_free,
halide_print,
halide_error,
halide_do_par_for,
halide_do_task);
if (result != 0) {
dlclose(lib);
FARF(LOW, "init_runtime failed %d", result);
return result;
}
*module_ptr = reinterpret_cast<handle_t>(lib);
return 0;
#else
// Map some memory for the code and copy it in.
int aligned_codeLen = (codeLen + map_alignment - 1) & ~(map_alignment - 1);
void *executable = mmap(0, aligned_codeLen, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
if (executable == MAP_FAILED) {
FARF(LOW, "mmap failed");
return -1;
}
memcpy(executable, code, codeLen);
Elf::Object<uint32_t> obj;
result = obj.init(executable);
if (result != 0) {
FARF(LOW, "obj.init failed");
return result;
}
result = obj.do_relocations();
if (result != 0) {
FARF(LOW, "obj.do_relocations failed");
return result;
}
handle_t base_addr = (handle_t)executable;
// Change memory to be executable (but not writable).
if (mprotect(executable, aligned_codeLen, PROT_READ | PROT_EXEC) < 0) {
munmap(executable, aligned_codeLen);
FARF(LOW, "mprotect failed");
return -1;
}
// Initialize the runtime. The Hexagon runtime can't call any
// system functions (because we can't link them), so we put all
// the implementations that need to do so here, and pass poiners
// to them in here.
init_runtime_t init_runtime = (init_runtime_t)obj.symbol_address("halide_noos_init_runtime");
if (init_runtime == 0) {
munmap(executable, aligned_codeLen);
FARF(LOW, "Failed to find symbol halide_noos_init_runtime");
return -1;
}
int result = init_runtime(halide_malloc,
halide_free,
halide_print,
halide_error,
halide_do_par_for,
halide_do_task);
if (result != 0) {
munmap(executable, aligned_codeLen);
FARF(LOW, "init_runtime failed %d", result);
return result;
}
*module_ptr = base_addr;
return 0;
#endif
}
handle_t halide_hexagon_remote_get_symbol(handle_t module_ptr, const char* name, int nameLen) {
#if 1
return reinterpret_cast<handle_t>(dlsym(reinterpret_cast<void*>(module_ptr), name));
#else
Elf::Object<uint32_t> obj;
int result = obj.init((void*)module_ptr);
if (result != 0) {
FARF(LOW, "Object::init failed: %d", result);
return 0;
}
return (handle_t)obj.symbol_address(name);
#endif
}
int halide_hexagon_remote_run(handle_t module_ptr, handle_t function,
const buffer *arg_ptrs, int arg_ptrsLen,
buffer *outputs, int outputsLen) {
// Get a pointer to the argv version of the pipeline.
typedef int (*pipeline_argv_t)(void **);
pipeline_argv_t pipeline = reinterpret_cast<pipeline_argv_t>(function);
// Construct a list of arguments. This is only part of a
// buffer_t. We know that the only field of buffer_t that the
// generated code should access is the host field (any other
// fields should be passed as their own parameters) so we can just
// make this dummy buffer_t type.
struct fake_buffer_t {
uint64_t dev;
uint8_t* host;
};
void **args = (void **)__builtin_alloca((arg_ptrsLen + outputsLen) * sizeof(void *));
fake_buffer_t *buffers = (fake_buffer_t *)__builtin_alloca((arg_ptrsLen + outputsLen) * sizeof(fake_buffer_t));
for (int i = 0; i < arg_ptrsLen; i++) {
args[i] = arg_ptrs[i].data;
}
for (int i = 0; i < outputsLen; i++) {
buffers[i].host = outputs[i].data;
args[i + arg_ptrsLen] = &buffers[i];
}
// Call the pipeline and return the result.
return pipeline(args);
}
int halide_hexagon_remote_release_kernels(handle_t module_ptr, int codeLen) {
#if 1
dlclose(reinterpret_cast<void*>(module_ptr));
#else
void *executable = (void *)module_ptr;
codeLen = (codeLen + map_alignment - 1) & (map_alignment - 1);
munmap(executable, codeLen);
#endif
return 0;
}
} // extern "C"
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/hwpf/hwp/sbe_centaur_init/sbe_centaur_init.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2015 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file sbe_centaur_init.C
*
* Support file for IStep:
* sbe_centaur_init
*
*
*
* HWP_IGNORE_VERSION_CHECK
*
*/
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <trace/interface.H>
#include <initservice/taskargs.H>
#include <errl/errlentry.H>
#include <initservice/isteps_trace.H>
#include <targeting/common/commontargeting.H>
#include <targeting/common/utilFilter.H>
#include <fapi.H>
#include <fapiPoreVeArg.H>
#include <fapiTarget.H>
#include <fapi.H>
#include <fapiPlatHwpInvoker.H>
#include <vfs/vfs.H>
#include "sbe_centaur_init.H"
#include <hwpisteperror.H>
#include <errl/errludtarget.H>
#include <sbe/sbeif.H>
#include "cen_xip_customize.H"
#include <util/align.H>
extern fapi::ReturnCode fapiPoreVe(const fapi::Target i_target,
std::list<uint64_t> & io_sharedObjectArgs);
const uint64_t REPAIR_LOADER_RETRY_CTR_MASK = 0x000007FC00000000ull;
// Constants
// Memory Relocation Register for Centaur SBE image
const uint64_t CENTAUR_SBE_PNOR_MRR = 0;
// Max SBE image buffer size
const uint32_t MAX_SBE_IMG_SIZE = 48 * 1024;
namespace SBE_CENTAUR_INIT
{
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
using namespace TARGETING;
using namespace fapi;
using namespace vsbe;
//
// Wrapper function to call step 10
//
void* call_sbe_centaur_init( void *io_pArgs )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init entry");
// Get target list to pass in procedure
TARGETING::TargetHandleList l_membufTargetList;
getAllChips(l_membufTargetList, TYPE_MEMBUF);
size_t l_sbePnorSize = 0;
void* l_sbePnorAddr = NULL;
errlHndl_t l_errl = NULL;
IStepError l_StepError;
// Loop thru all Centaurs in list
for (TargetHandleList::const_iterator
l_membuf_iter = l_membufTargetList.begin();
l_membuf_iter != l_membufTargetList.end();
++l_membuf_iter)
{
TARGETING::Target* l_membuf_target = *l_membuf_iter;
HwasState l_hwasState = l_membuf_target->getAttr<ATTR_HWAS_STATE>();
TARGETING::ATTR_MSS_INIT_STATE_type l_attr_mss_init_state=
l_membuf_target->getAttr<TARGETING::ATTR_MSS_INIT_STATE>();
//run SBE init on functional OR previously functional centaurs
if ( l_hwasState.functional ||
(l_hwasState.present &&
(l_attr_mss_init_state != ENUM_ATTR_MSS_INIT_STATE_COLD)) )
{
l_membuf_target->setAttr<TARGETING::ATTR_MSS_INIT_STATE>(
ENUM_ATTR_MSS_INIT_STATE_COLD);
}
else
{
//go to the next membuf in the list because this present membuf is
//not functional or has not gone through an IPL once
continue;
}
//find SBE image in PNOR
uint8_t cur_ec = (*l_membuf_iter)->getAttr<TARGETING::ATTR_EC>();
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK,
"call_sbe_centaur_init() - Find SBE image in PNOR");
l_errl = SBE::findSBEInPnor(l_membuf_target,
l_sbePnorAddr,
l_sbePnorSize,
NULL);
if (l_errl)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK,
"call_sbe_centaur_init() - Error getting image from PNOR. "
"Target 0x%.8X, EC=0x%.2X",
TARGETING::get_huid(l_membuf_target), cur_ec );
// capture the target data in the elog
ErrlUserDetailsTarget(l_membuf_target).addToLog( l_errl );
// Create IStep error log and cross reference error that occurred
l_StepError.addErrorDetails( l_errl );
// Commit Error
errlCommit( l_errl, HWPF_COMP_ID );
continue;
}
char l_header[10];
memcpy (l_header, l_sbePnorAddr, 9);
l_header[9] = '\0';
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init - Loading "
"centaur sbe from pnor, Addr 0x%llX, Size %d, Header %s",
l_sbePnorAddr, l_sbePnorSize, l_header);
// Create a FAPI Target
const fapi::Target l_fapiTarget( fapi::TARGET_TYPE_MEMBUF_CHIP,
(const_cast<TARGETING::Target*>(l_membuf_target)));
// Expand buffer for new image size
const uint32_t l_customizedMaxSize = ALIGN_POW2(MAX_SBE_IMG_SIZE);
const uint32_t l_buf1Size = ALIGN_POW2(MAX_SBE_IMG_SIZE);
const uint32_t l_buf2Size = ALIGN_POW2(MAX_SBE_IMG_SIZE);
uint32_t l_customizedSize = l_customizedMaxSize;
char * l_pCustomizedImage = (char *)malloc(l_customizedMaxSize);
void * l_pBuf1 = malloc(l_buf1Size);
void * l_pBuf2 = malloc(l_buf2Size);
// Setup args
std::list<uint64_t> myArgs;
// Set FapiPoreVeOtherArg: run unlimited instructions
FapiPoreVeOtherArg *l_otherArg =
new FapiPoreVeOtherArg(vsbe::RUN_UNLIMITED, vsbe::PORE_SBE);
// Entry point
l_otherArg->iv_entryPoint = const_cast<char*>("pnor::_sbe_pnor_start");
l_otherArg->iv_mrr = CENTAUR_SBE_PNOR_MRR;
myArgs.push_back(reinterpret_cast<uint64_t>(l_otherArg));
// Set FapiPoreVeMemArg for pnor option, base address = 0
uint32_t base_addr = 0;
char* l_dataPnor = const_cast<char*>(l_pCustomizedImage);
FapiPoreVeMemArg* l_memArg = new FapiPoreVeMemArg(ARG_PNOR,
base_addr, l_customizedSize,
static_cast<void*>(l_dataPnor));
myArgs.push_back(reinterpret_cast<uint64_t>(l_memArg));
// Create state argument to dump out state for debugging purpose
FapiPoreVeStateArg *l_stateArg = new FapiPoreVeStateArg(NULL);
l_stateArg->iv_installState = false;
l_stateArg->iv_extractState = true;
myArgs.push_back(reinterpret_cast<uint64_t>(l_stateArg));
// Put out info on target
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Running call_sbe_centaur_init on Centaur "
" target HUID %.8X", TARGETING::get_huid(l_membuf_target));
// XIP customize is going to look for a PLL ring with a "stub"
// mem freq -- so set to a default, then clear it (so as not
// to mess up MSS HWP later
l_membuf_target->setAttr<TARGETING::ATTR_MSS_FREQ>(1600);
FAPI_INVOKE_HWP( l_errl, cen_xip_customize,
l_fapiTarget, l_sbePnorAddr,
l_pCustomizedImage, l_customizedSize,
l_pBuf1, l_buf1Size,
l_pBuf2, l_buf2Size );
l_membuf_target->setAttr<TARGETING::ATTR_MSS_FREQ>(0);
if (l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR 0x%.8X call_sbe_centaur_init - Error returned from"
" cen_xip_customize, l_rc 0x%llX", l_errl->reasonCode());
}
else
{
// Run the engine
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init - Start VSBE engine...");
FAPI_INVOKE_HWP(l_errl, fapiPoreVe, l_fapiTarget, myArgs);
if (l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR 0x%.8X call_sbe_centaur_init - Error returned from"
" VSBE engine on this Centaur, l_rc 0x%llX",
l_errl->reasonCode());
l_errl->collectTrace(FAPI_IMP_TRACE_NAME, 1024);
l_errl->collectTrace("ISTEPS_TRACE", 512);
}
// Remove 0x0104000A reading, per Joe, the IPL procedures are no
// longer writing information related to the repair loader into
// this register
}
// Freeing memory
delete l_otherArg;
delete l_memArg;
delete l_stateArg;
free( l_pCustomizedImage );
free( l_pBuf1 );
free( l_pBuf2 );
if (l_errl )
{
// capture the target data in the elog
ErrlUserDetailsTarget(l_membuf_target).addToLog( l_errl );
// Create IStep error log and cross reference error that occurred
l_StepError.addErrorDetails( l_errl );
// Commit Error
errlCommit( l_errl, HWPF_COMP_ID );
}
else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init - VSBE engine runs successfully "
"on this Centaur");
}
} // end for
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init exit" );
return l_StepError.getErrorHandle();
}
}; // end namespace
<commit_msg>Set MSS_FREQ attribute based on capable and booted nest freq<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/hwpf/hwp/sbe_centaur_init/sbe_centaur_init.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2015 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file sbe_centaur_init.C
*
* Support file for IStep:
* sbe_centaur_init
*
*
*
* HWP_IGNORE_VERSION_CHECK
*
*/
/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>
#include <trace/interface.H>
#include <initservice/taskargs.H>
#include <errl/errlentry.H>
#include <initservice/isteps_trace.H>
#include <targeting/common/commontargeting.H>
#include <targeting/common/utilFilter.H>
#include <fapi.H>
#include <fapiPoreVeArg.H>
#include <fapiTarget.H>
#include <fapi.H>
#include <fapiPlatHwpInvoker.H>
#include <vfs/vfs.H>
#include "sbe_centaur_init.H"
#include <hwpisteperror.H>
#include <errl/errludtarget.H>
#include <sbe/sbeif.H>
#include "cen_xip_customize.H"
#include <util/align.H>
extern fapi::ReturnCode fapiPoreVe(const fapi::Target i_target,
std::list<uint64_t> & io_sharedObjectArgs);
const uint64_t REPAIR_LOADER_RETRY_CTR_MASK = 0x000007FC00000000ull;
// Constants
// Memory Relocation Register for Centaur SBE image
const uint64_t CENTAUR_SBE_PNOR_MRR = 0;
// Max SBE image buffer size
const uint32_t MAX_SBE_IMG_SIZE = 48 * 1024;
// Low MSS freq for 32x32 machines
const uint32_t MSS_FREQ_32x32_CONFIG = 1066;
// Low Nest Freq
const uint32_t LOW_NEST_FREQ = 2000;
namespace SBE_CENTAUR_INIT
{
using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
using namespace TARGETING;
using namespace fapi;
using namespace vsbe;
//
// Wrapper function to call step 10
//
void* call_sbe_centaur_init( void *io_pArgs )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init entry");
// Get target list to pass in procedure
TARGETING::TargetHandleList l_membufTargetList;
getAllChips(l_membufTargetList, TYPE_MEMBUF);
// Get sys target to check capable nest frequencies
TARGETING::Target* l_sys = NULL;
targetService().getTopLevelTarget(l_sys);
assert(l_sys != NULL, "sbe_centaur_init: sys target is NULL");
size_t l_sbePnorSize = 0;
void* l_sbePnorAddr = NULL;
errlHndl_t l_errl = NULL;
uint32_t l_booted_nest_freq = 0;
MRW_NEST_CAPABLE_FREQUENCIES_SYS l_mrw_nest_capable;
IStepError l_StepError;
// Loop thru all Centaurs in list
for (TargetHandleList::const_iterator
l_membuf_iter = l_membufTargetList.begin();
l_membuf_iter != l_membufTargetList.end();
++l_membuf_iter)
{
TARGETING::Target* l_membuf_target = *l_membuf_iter;
HwasState l_hwasState = l_membuf_target->getAttr<ATTR_HWAS_STATE>();
TARGETING::ATTR_MSS_INIT_STATE_type l_attr_mss_init_state=
l_membuf_target->getAttr<TARGETING::ATTR_MSS_INIT_STATE>();
//run SBE init on functional OR previously functional centaurs
if ( l_hwasState.functional ||
(l_hwasState.present &&
(l_attr_mss_init_state != ENUM_ATTR_MSS_INIT_STATE_COLD)) )
{
l_membuf_target->setAttr<TARGETING::ATTR_MSS_INIT_STATE>(
ENUM_ATTR_MSS_INIT_STATE_COLD);
}
else
{
//go to the next membuf in the list because this present membuf is
//not functional or has not gone through an IPL once
continue;
}
//find SBE image in PNOR
uint8_t cur_ec = (*l_membuf_iter)->getAttr<TARGETING::ATTR_EC>();
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK,
"call_sbe_centaur_init() - Find SBE image in PNOR");
l_errl = SBE::findSBEInPnor(l_membuf_target,
l_sbePnorAddr,
l_sbePnorSize,
NULL);
if (l_errl)
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK,
"call_sbe_centaur_init() - Error getting image from PNOR. "
"Target 0x%.8X, EC=0x%.2X",
TARGETING::get_huid(l_membuf_target), cur_ec );
// capture the target data in the elog
ErrlUserDetailsTarget(l_membuf_target).addToLog( l_errl );
// Create IStep error log and cross reference error that occurred
l_StepError.addErrorDetails( l_errl );
// Commit Error
errlCommit( l_errl, HWPF_COMP_ID );
continue;
}
char l_header[10];
memcpy (l_header, l_sbePnorAddr, 9);
l_header[9] = '\0';
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init - Loading "
"centaur sbe from pnor, Addr 0x%llX, Size %d, Header %s",
l_sbePnorAddr, l_sbePnorSize, l_header);
// Create a FAPI Target
const fapi::Target l_fapiTarget( fapi::TARGET_TYPE_MEMBUF_CHIP,
(const_cast<TARGETING::Target*>(l_membuf_target)));
// Expand buffer for new image size
const uint32_t l_customizedMaxSize = ALIGN_POW2(MAX_SBE_IMG_SIZE);
const uint32_t l_buf1Size = ALIGN_POW2(MAX_SBE_IMG_SIZE);
const uint32_t l_buf2Size = ALIGN_POW2(MAX_SBE_IMG_SIZE);
uint32_t l_customizedSize = l_customizedMaxSize;
char * l_pCustomizedImage = (char *)malloc(l_customizedMaxSize);
void * l_pBuf1 = malloc(l_buf1Size);
void * l_pBuf2 = malloc(l_buf2Size);
// Setup args
std::list<uint64_t> myArgs;
// Set FapiPoreVeOtherArg: run unlimited instructions
FapiPoreVeOtherArg *l_otherArg =
new FapiPoreVeOtherArg(vsbe::RUN_UNLIMITED, vsbe::PORE_SBE);
// Entry point
l_otherArg->iv_entryPoint = const_cast<char*>("pnor::_sbe_pnor_start");
l_otherArg->iv_mrr = CENTAUR_SBE_PNOR_MRR;
myArgs.push_back(reinterpret_cast<uint64_t>(l_otherArg));
// Set FapiPoreVeMemArg for pnor option, base address = 0
uint32_t base_addr = 0;
char* l_dataPnor = const_cast<char*>(l_pCustomizedImage);
FapiPoreVeMemArg* l_memArg = new FapiPoreVeMemArg(ARG_PNOR,
base_addr, l_customizedSize,
static_cast<void*>(l_dataPnor));
myArgs.push_back(reinterpret_cast<uint64_t>(l_memArg));
// Create state argument to dump out state for debugging purpose
FapiPoreVeStateArg *l_stateArg = new FapiPoreVeStateArg(NULL);
l_stateArg->iv_installState = false;
l_stateArg->iv_extractState = true;
myArgs.push_back(reinterpret_cast<uint64_t>(l_stateArg));
// Put out info on target
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Running call_sbe_centaur_init on Centaur "
" target HUID %.8X", TARGETING::get_huid(l_membuf_target));
// XIP customize is going to look for a PLL ring with a "stub"
// mem freq -- so set to a default, then clear it (so as not
// to mess up MSS HWP later
// Grab capable frequencies
l_mrw_nest_capable =
l_sys->getAttr<ATTR_MRW_NEST_CAPABLE_FREQUENCIES_SYS>();
// Get the nest freq we booted with
l_booted_nest_freq = l_sys->getAttr<TARGETING::ATTR_NEST_FREQ_MHZ>();
// If we are running nest at 2.0, and we support 2.0 and 2.4, we
// need to drop MSS freq to 1066
if ((l_mrw_nest_capable ==
MRW_NEST_CAPABLE_FREQUENCIES_SYS_2000_MHZ_OR_2400_MHZ) &&
(l_booted_nest_freq == LOW_NEST_FREQ))
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Reducing MSS frequency in sbe_centaur_init to %d based on "
"nest frequency", MSS_FREQ_32x32_CONFIG);
l_membuf_target->setAttr
<TARGETING::ATTR_MSS_FREQ>(MSS_FREQ_32x32_CONFIG);
}
else //boot as normal
{
l_membuf_target->setAttr<TARGETING::ATTR_MSS_FREQ>(1600);
}
FAPI_INVOKE_HWP( l_errl, cen_xip_customize,
l_fapiTarget, l_sbePnorAddr,
l_pCustomizedImage, l_customizedSize,
l_pBuf1, l_buf1Size,
l_pBuf2, l_buf2Size );
l_membuf_target->setAttr<TARGETING::ATTR_MSS_FREQ>(0);
if (l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR 0x%.8X call_sbe_centaur_init - Error returned from"
" cen_xip_customize, l_rc 0x%llX", l_errl->reasonCode());
}
else
{
// Run the engine
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init - Start VSBE engine...");
FAPI_INVOKE_HWP(l_errl, fapiPoreVe, l_fapiTarget, myArgs);
if (l_errl)
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ERROR 0x%.8X call_sbe_centaur_init - Error returned from"
" VSBE engine on this Centaur, l_rc 0x%llX",
l_errl->reasonCode());
l_errl->collectTrace(FAPI_IMP_TRACE_NAME, 1024);
l_errl->collectTrace("ISTEPS_TRACE", 512);
}
// Remove 0x0104000A reading, per Joe, the IPL procedures are no
// longer writing information related to the repair loader into
// this register
}
// Freeing memory
delete l_otherArg;
delete l_memArg;
delete l_stateArg;
free( l_pCustomizedImage );
free( l_pBuf1 );
free( l_pBuf2 );
if (l_errl )
{
// capture the target data in the elog
ErrlUserDetailsTarget(l_membuf_target).addToLog( l_errl );
// Create IStep error log and cross reference error that occurred
l_StepError.addErrorDetails( l_errl );
// Commit Error
errlCommit( l_errl, HWPF_COMP_ID );
}
else
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init - VSBE engine runs successfully "
"on this Centaur");
}
} // end for
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_sbe_centaur_init exit" );
return l_StepError.getErrorHandle();
}
}; // end namespace
<|endoftext|>
|
<commit_before>/*******************************************************
Lightwave Scene Loader for OSG
Copyright (C) 2004 Marco Jez <[email protected]>
OpenSceneGraph is (C) 2004 Robert Osfield
********************************************************/
#include "SceneLoader.h"
#include <osg/Notify>
#include <osg/PositionAttitudeTransform>
#include <osg/AnimationPath>
#include <osg/io_utils>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/fstream>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <sstream>
#include <stdlib.h>
using namespace lwosg;
namespace
{
int str_to_int(const std::string &s)
{
std::istringstream iss(s);
int n;
iss >> n;
return n;
}
int hex_to_int(const std::string &s)
{
std::istringstream iss(s);
int n;
iss >> std::hex >> n;
return n;
}
osg::Quat rotate_ypr(const osg::Vec3 &ypr, const osg::Vec3 pivot_rot = osg::Vec3(0, 0, 0))
{
osg::Quat Q1(ypr.z(), osg::Vec3(0, -1, 0));
osg::Quat Q2(ypr.y(), osg::Vec3(-1, 0, 0));
osg::Quat Q3(ypr.x(), osg::Vec3(0, 0, -1));
osg::Quat Q4(pivot_rot.z(), osg::Vec3(0, -1, 0));
osg::Quat Q5(pivot_rot.y(), osg::Vec3(-1, 0, 0));
osg::Quat Q6(pivot_rot.x(), osg::Vec3(0, 0, -1));
return Q1 * Q2 * Q3 * Q4 * Q5 * Q6;
}
void trim(std::string& str)
{
// trim any trailing control characters.
//std::cout<<"trim string "<<str<<std::endl;
while (!str.empty() && str[str.size()-1]<32)
{
// removing control character
//std::cout<<" removing control character "<<(int)str[str.size()-1]<<std::endl;
str.erase(str.size()-1);
}
}
}
SceneLoader::SceneLoader()
: capture_obj_motion_(false),
capture_cam_motion_(false)
{
}
SceneLoader::SceneLoader(const Options &options)
: capture_obj_motion_(false),
capture_cam_motion_(false),
options_(options)
{
}
osg::Group *SceneLoader::load(const std::string &filename, const osgDB::ReaderWriter::Options *options, bool search)
{
std::string fname;
if (search) {
fname = osgDB::findDataFile(filename, options);
if (fname.empty()) return 0;
} else {
fname = filename;
}
osgDB::ifstream ifs(fname.c_str());
if (!ifs.is_open()) return 0;
clear();
std::string field;
std::getline(ifs, field);
if (field.substr(0,4) != "LWSC") {
osg::notify(osg::WARN) << filename << " is not a LWSC file, " << field << std::endl;
return 0;
}
std::getline(ifs, field);
version_ = atoi(field.c_str());
std::string identifier;
while (ifs >> identifier) {
if (identifier == "{") {
ifs >> identifier;
std::ws(ifs);
std::vector<std::string> data;
std::string data_line;
while (std::getline(ifs, data_line)) {
trim(data_line);
if (data_line == "}") {
std::ws(ifs);
break;
}
data.push_back(data_line);
std::ws(ifs);
}
if (!data.empty()) {
if (!parse_block(identifier, data)) {
return 0;
}
}
} else {
std::string data;
std::getline(ifs, data);
trim(data);
std::istringstream iss(data);
std::ws(iss);
std::getline(iss, data);
trim(data);
if (!parse_block(identifier, data)) {
return 0;
}
}
}
// build camera animations
for (Scene_camera_list::iterator ci=scene_cameras_.begin(); ci!=scene_cameras_.end(); ++ci) {
if (!ci->motion.keys.empty()) {
osg::ref_ptr<osg::AnimationPath> ap = new osg::AnimationPath;
for (Motion_envelope::Key_map::const_iterator j=ci->motion.keys.begin(); j!=ci->motion.keys.end(); ++j) {
osg::Vec3 pos(options_.csf->fix_point(j->second.position));
//const osg::Vec3 &ypr = j->second.ypr;
osg::AnimationPath::ControlPoint cp(pos, osg::Quat(osg::PI_2, osg::Vec3(1, 0, 0)) * rotate_ypr(j->second.ypr), j->second.scale);
OSG_NOTICE<<"scale = "<<j->second.scale<<std::endl;
ap->insert(j->first, cp);
}
camera_animations_.push_back(ap.get());
}
}
// build objects and object animations
typedef std::map<int, osg::ref_ptr<osg::PositionAttitudeTransform> > PAT_map;
PAT_map pats;
int p = 0;
for (Scene_object_list::iterator i=scene_objects_.begin(); i!=scene_objects_.end(); ++i, ++p) {
osg::ref_ptr<osg::PositionAttitudeTransform> pat = pats[p];
if (!pat.valid()) {
pat = new osg::PositionAttitudeTransform;
pats[p] = pat;
}
pat->setName(i->name);
pat->addChild(i->layer_node.get());
pat->setPivotPoint(options_.csf->fix_point(i->pivot));
// still
if (!i->motion.keys.empty()) {
pat->setPosition(options_.csf->fix_point(i->motion.keys.begin()->second.position));
pat->setAttitude(rotate_ypr(i->motion.keys.begin()->second.ypr, i->pivot_rot));
}
// animation
if (i->motion.keys.size() > 1) {
osg::ref_ptr<osg::AnimationPath> ap = new osg::AnimationPath;
for (Motion_envelope::Key_map::const_iterator j=i->motion.keys.begin(); j!=i->motion.keys.end(); ++j) {
osg::Vec3 pos(options_.csf->fix_point(j->second.position));
osg::AnimationPath::ControlPoint cp(pos, rotate_ypr(j->second.ypr, i->pivot_rot), j->second.scale);
ap->insert(j->first, cp);
}
osg::ref_ptr<osg::AnimationPathCallback> apc = new osg::AnimationPathCallback(ap.get());
apc->setPivotPoint(options_.csf->fix_point(i->pivot));
pat->setUpdateCallback(apc.get());
}
if (i->parent == -1) {
root_->addChild(pat.get());
} else {
if (i->parent < static_cast<int>(scene_objects_.size())) {
osg::ref_ptr<osg::PositionAttitudeTransform> parent = pats[i->parent];
if (!parent.valid()) {
parent = new osg::PositionAttitudeTransform;
pats[i->parent] = parent;
}
parent->addChild(pat.get());
} else {
OSG_WARN << "Warning: lwosg::SceneLoader: invalid parent" << std::endl;
}
}
}
return root_.get();
}
bool SceneLoader::parse_block(const std::string &name, const std::string &data)
{
std::istringstream iss(data);
if (name == "AddCamera") {
scene_cameras_.push_back(Scene_camera());
}
if (name == "AddNullObject") {
osg::ref_ptr<osg::Group> nullobjnode = new osg::Group;
nullobjnode->setName(data);
objects_[data] = nullobjnode;
Scene_object so;
so.layer_node = nullobjnode.get();
scene_objects_.push_back(so);
}
if (name == "LoadObjectLayer") {
unsigned layer;
iss >> layer;
std::string id;
if (version_ >= 5) {
iss >> id;
}
std::ws(iss);
std::string filename;
std::getline(iss, filename);
// trim any trailing control characters.
trim(filename);
if (!filename.empty())
{
osg::ref_ptr<osg::Group> objnode;
Object_map::const_iterator i = objects_.find(filename);
if (i == objects_.end()) {
OSG_NOTICE << "Loading object \"" << filename << "\"" << std::endl;
objnode = osgDB::readRefFile<osg::Group>(filename);
if (!objnode.valid()) return false;
objects_[filename] = objnode;
} else {
objnode = i->second;
}
if (layer > objnode->getNumChildren()) {
OSG_WARN << "Warning: lwosg::SceneLoader: layer " << layer << " does not exist in object " << filename << std::endl;
return 0;
}
Scene_object so;
std::ostringstream oss;
oss << filename << "." << layer;
so.name = oss.str();
so.layer_node = objnode->getChild(layer-1);
if (so.layer_node.valid()) {
scene_objects_.push_back(so);
}
}
}
if (name == "PivotPosition") {
if (!scene_objects_.empty()) {
osg::Vec3 pivot;
iss >> pivot.x() >> pivot.y() >> pivot.z();
scene_objects_.back().pivot = pivot;
}
}
if (name == "PivotRotation") {
if (!scene_objects_.empty()) {
osg::Vec3 pivot;
iss >> pivot.x() >> pivot.y() >> pivot.z();
scene_objects_.back().pivot_rot = pivot * (osg::PI / 180.0f);
}
}
if (name == "ParentItem") {
if (!scene_objects_.empty()) {
std::string id;
iss >> id;
if (id.length() == 8) {
if (id[0] == '1') {
id.erase(0, 1);
scene_objects_.back().parent = hex_to_int(id);
}
} else {
scene_objects_.back().parent = str_to_int(id);
}
}
}
if (name == "NumChannels") {
iss >> channel_count_;
}
if (name == "Channel") {
iss >> current_channel_;
}
if (name == "ObjectMotion") {
capture_obj_motion_ = true;
}
if (name == "CameraMotion") {
capture_cam_motion_ = true;
}
return true;
}
bool SceneLoader::parse_block(const std::string &name, const std::vector<std::string> &data)
{
if (name == "Envelope") {
if (((capture_obj_motion_ && !scene_objects_.empty()) ||
(capture_cam_motion_ && !scene_cameras_.empty())) &&
(data.size() >= 2)) {
Motion_envelope::Key_map &keys = capture_obj_motion_ ? scene_objects_.back().motion.keys : scene_cameras_.back().motion.keys;
if (current_channel_ >= (channel_count_ - 1)) {
capture_obj_motion_ = false;
capture_cam_motion_ = false;
}
for (unsigned i=1; i<data.size(); ++i) {
std::istringstream iss(data[i]);
std::string key_id;
iss >> key_id;
if (key_id == "Key") {
float value;
double time;
if (iss >> value >> time) {
switch (current_channel_) {
case 0: keys[time].position.x() = value; break;
case 1: keys[time].position.y() = value; break;
case 2: keys[time].position.z() = value; break;
case 3: keys[time].ypr.x() = value; break;
case 4: keys[time].ypr.y() = value; break;
case 5: keys[time].ypr.z() = value; break;
case 6: keys[time].scale.x() = value; break;
case 7: keys[time].scale.y() = value; break;
case 8: keys[time].scale.z() = value; break;
default: ;
}
}
}
}
}
}
return true;
}
void SceneLoader::clear()
{
root_ = new osg::Group;
objects_.clear();
scene_objects_.clear();
scene_cameras_.clear();
camera_animations_.clear();
channel_count_ = 0;
current_channel_ = 0;
}
<commit_msg>Added initializers<commit_after>/*******************************************************
Lightwave Scene Loader for OSG
Copyright (C) 2004 Marco Jez <[email protected]>
OpenSceneGraph is (C) 2004 Robert Osfield
********************************************************/
#include "SceneLoader.h"
#include <osg/Notify>
#include <osg/PositionAttitudeTransform>
#include <osg/AnimationPath>
#include <osg/io_utils>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/fstream>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <sstream>
#include <stdlib.h>
using namespace lwosg;
namespace
{
int str_to_int(const std::string &s)
{
std::istringstream iss(s);
int n;
iss >> n;
return n;
}
int hex_to_int(const std::string &s)
{
std::istringstream iss(s);
int n;
iss >> std::hex >> n;
return n;
}
osg::Quat rotate_ypr(const osg::Vec3 &ypr, const osg::Vec3 pivot_rot = osg::Vec3(0, 0, 0))
{
osg::Quat Q1(ypr.z(), osg::Vec3(0, -1, 0));
osg::Quat Q2(ypr.y(), osg::Vec3(-1, 0, 0));
osg::Quat Q3(ypr.x(), osg::Vec3(0, 0, -1));
osg::Quat Q4(pivot_rot.z(), osg::Vec3(0, -1, 0));
osg::Quat Q5(pivot_rot.y(), osg::Vec3(-1, 0, 0));
osg::Quat Q6(pivot_rot.x(), osg::Vec3(0, 0, -1));
return Q1 * Q2 * Q3 * Q4 * Q5 * Q6;
}
void trim(std::string& str)
{
// trim any trailing control characters.
//std::cout<<"trim string "<<str<<std::endl;
while (!str.empty() && str[str.size()-1]<32)
{
// removing control character
//std::cout<<" removing control character "<<(int)str[str.size()-1]<<std::endl;
str.erase(str.size()-1);
}
}
}
SceneLoader::SceneLoader():
current_channel_(0),
channel_count_(0),
capture_obj_motion_(false),
capture_cam_motion_(false),
version_(0)
{
}
SceneLoader::SceneLoader(const Options &options):
current_channel_(0),
channel_count_(0),
capture_obj_motion_(false),
capture_cam_motion_(false),
options_(options),
version_(0)
{
}
osg::Group *SceneLoader::load(const std::string &filename, const osgDB::ReaderWriter::Options *options, bool search)
{
std::string fname;
if (search) {
fname = osgDB::findDataFile(filename, options);
if (fname.empty()) return 0;
} else {
fname = filename;
}
osgDB::ifstream ifs(fname.c_str());
if (!ifs.is_open()) return 0;
clear();
std::string field;
std::getline(ifs, field);
if (field.substr(0,4) != "LWSC") {
osg::notify(osg::WARN) << filename << " is not a LWSC file, " << field << std::endl;
return 0;
}
std::getline(ifs, field);
version_ = atoi(field.c_str());
std::string identifier;
while (ifs >> identifier) {
if (identifier == "{") {
ifs >> identifier;
std::ws(ifs);
std::vector<std::string> data;
std::string data_line;
while (std::getline(ifs, data_line)) {
trim(data_line);
if (data_line == "}") {
std::ws(ifs);
break;
}
data.push_back(data_line);
std::ws(ifs);
}
if (!data.empty()) {
if (!parse_block(identifier, data)) {
return 0;
}
}
} else {
std::string data;
std::getline(ifs, data);
trim(data);
std::istringstream iss(data);
std::ws(iss);
std::getline(iss, data);
trim(data);
if (!parse_block(identifier, data)) {
return 0;
}
}
}
// build camera animations
for (Scene_camera_list::iterator ci=scene_cameras_.begin(); ci!=scene_cameras_.end(); ++ci) {
if (!ci->motion.keys.empty()) {
osg::ref_ptr<osg::AnimationPath> ap = new osg::AnimationPath;
for (Motion_envelope::Key_map::const_iterator j=ci->motion.keys.begin(); j!=ci->motion.keys.end(); ++j) {
osg::Vec3 pos(options_.csf->fix_point(j->second.position));
//const osg::Vec3 &ypr = j->second.ypr;
osg::AnimationPath::ControlPoint cp(pos, osg::Quat(osg::PI_2, osg::Vec3(1, 0, 0)) * rotate_ypr(j->second.ypr), j->second.scale);
OSG_NOTICE<<"scale = "<<j->second.scale<<std::endl;
ap->insert(j->first, cp);
}
camera_animations_.push_back(ap.get());
}
}
// build objects and object animations
typedef std::map<int, osg::ref_ptr<osg::PositionAttitudeTransform> > PAT_map;
PAT_map pats;
int p = 0;
for (Scene_object_list::iterator i=scene_objects_.begin(); i!=scene_objects_.end(); ++i, ++p) {
osg::ref_ptr<osg::PositionAttitudeTransform> pat = pats[p];
if (!pat.valid()) {
pat = new osg::PositionAttitudeTransform;
pats[p] = pat;
}
pat->setName(i->name);
pat->addChild(i->layer_node.get());
pat->setPivotPoint(options_.csf->fix_point(i->pivot));
// still
if (!i->motion.keys.empty()) {
pat->setPosition(options_.csf->fix_point(i->motion.keys.begin()->second.position));
pat->setAttitude(rotate_ypr(i->motion.keys.begin()->second.ypr, i->pivot_rot));
}
// animation
if (i->motion.keys.size() > 1) {
osg::ref_ptr<osg::AnimationPath> ap = new osg::AnimationPath;
for (Motion_envelope::Key_map::const_iterator j=i->motion.keys.begin(); j!=i->motion.keys.end(); ++j) {
osg::Vec3 pos(options_.csf->fix_point(j->second.position));
osg::AnimationPath::ControlPoint cp(pos, rotate_ypr(j->second.ypr, i->pivot_rot), j->second.scale);
ap->insert(j->first, cp);
}
osg::ref_ptr<osg::AnimationPathCallback> apc = new osg::AnimationPathCallback(ap.get());
apc->setPivotPoint(options_.csf->fix_point(i->pivot));
pat->setUpdateCallback(apc.get());
}
if (i->parent == -1) {
root_->addChild(pat.get());
} else {
if (i->parent < static_cast<int>(scene_objects_.size())) {
osg::ref_ptr<osg::PositionAttitudeTransform> parent = pats[i->parent];
if (!parent.valid()) {
parent = new osg::PositionAttitudeTransform;
pats[i->parent] = parent;
}
parent->addChild(pat.get());
} else {
OSG_WARN << "Warning: lwosg::SceneLoader: invalid parent" << std::endl;
}
}
}
return root_.get();
}
bool SceneLoader::parse_block(const std::string &name, const std::string &data)
{
std::istringstream iss(data);
if (name == "AddCamera") {
scene_cameras_.push_back(Scene_camera());
}
if (name == "AddNullObject") {
osg::ref_ptr<osg::Group> nullobjnode = new osg::Group;
nullobjnode->setName(data);
objects_[data] = nullobjnode;
Scene_object so;
so.layer_node = nullobjnode.get();
scene_objects_.push_back(so);
}
if (name == "LoadObjectLayer") {
unsigned layer;
iss >> layer;
std::string id;
if (version_ >= 5) {
iss >> id;
}
std::ws(iss);
std::string filename;
std::getline(iss, filename);
// trim any trailing control characters.
trim(filename);
if (!filename.empty())
{
osg::ref_ptr<osg::Group> objnode;
Object_map::const_iterator i = objects_.find(filename);
if (i == objects_.end()) {
OSG_NOTICE << "Loading object \"" << filename << "\"" << std::endl;
objnode = osgDB::readRefFile<osg::Group>(filename);
if (!objnode.valid()) return false;
objects_[filename] = objnode;
} else {
objnode = i->second;
}
if (layer > objnode->getNumChildren()) {
OSG_WARN << "Warning: lwosg::SceneLoader: layer " << layer << " does not exist in object " << filename << std::endl;
return 0;
}
Scene_object so;
std::ostringstream oss;
oss << filename << "." << layer;
so.name = oss.str();
so.layer_node = objnode->getChild(layer-1);
if (so.layer_node.valid()) {
scene_objects_.push_back(so);
}
}
}
if (name == "PivotPosition") {
if (!scene_objects_.empty()) {
osg::Vec3 pivot;
iss >> pivot.x() >> pivot.y() >> pivot.z();
scene_objects_.back().pivot = pivot;
}
}
if (name == "PivotRotation") {
if (!scene_objects_.empty()) {
osg::Vec3 pivot;
iss >> pivot.x() >> pivot.y() >> pivot.z();
scene_objects_.back().pivot_rot = pivot * (osg::PI / 180.0f);
}
}
if (name == "ParentItem") {
if (!scene_objects_.empty()) {
std::string id;
iss >> id;
if (id.length() == 8) {
if (id[0] == '1') {
id.erase(0, 1);
scene_objects_.back().parent = hex_to_int(id);
}
} else {
scene_objects_.back().parent = str_to_int(id);
}
}
}
if (name == "NumChannels") {
iss >> channel_count_;
}
if (name == "Channel") {
iss >> current_channel_;
}
if (name == "ObjectMotion") {
capture_obj_motion_ = true;
}
if (name == "CameraMotion") {
capture_cam_motion_ = true;
}
return true;
}
bool SceneLoader::parse_block(const std::string &name, const std::vector<std::string> &data)
{
if (name == "Envelope") {
if (((capture_obj_motion_ && !scene_objects_.empty()) ||
(capture_cam_motion_ && !scene_cameras_.empty())) &&
(data.size() >= 2)) {
Motion_envelope::Key_map &keys = capture_obj_motion_ ? scene_objects_.back().motion.keys : scene_cameras_.back().motion.keys;
if (current_channel_ >= (channel_count_ - 1)) {
capture_obj_motion_ = false;
capture_cam_motion_ = false;
}
for (unsigned i=1; i<data.size(); ++i) {
std::istringstream iss(data[i]);
std::string key_id;
iss >> key_id;
if (key_id == "Key") {
float value;
double time;
if (iss >> value >> time) {
switch (current_channel_) {
case 0: keys[time].position.x() = value; break;
case 1: keys[time].position.y() = value; break;
case 2: keys[time].position.z() = value; break;
case 3: keys[time].ypr.x() = value; break;
case 4: keys[time].ypr.y() = value; break;
case 5: keys[time].ypr.z() = value; break;
case 6: keys[time].scale.x() = value; break;
case 7: keys[time].scale.y() = value; break;
case 8: keys[time].scale.z() = value; break;
default: ;
}
}
}
}
}
}
return true;
}
void SceneLoader::clear()
{
root_ = new osg::Group;
objects_.clear();
scene_objects_.clear();
scene_cameras_.clear();
camera_animations_.clear();
channel_count_ = 0;
current_channel_ = 0;
}
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/ApplicationUsage>
#include <osg/Timer>
#include <osg/Notify>
#include <osgUtil/DisplayRequirementsVisitor>
#include <osgDB/FileUtils>
#include <osgProducer/OsgCameraGroup>
using namespace Producer;
using namespace osgProducer;
class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback
{
public:
RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):
_cameraGroup(cameraGroup),
_sceneHandler(sceneHandler) {}
virtual void operator()( const Producer::RenderSurface & rs)
{
osg::Timer timer;
osg::Timer_t start_t = timer.tick();
if (_cameraGroup->getRealizeCallback())
{
(*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);
}
else if (_sceneHandler) _sceneHandler->init();
osg::Timer_t end_t = timer.tick();
double time = timer.delta_m(start_t,end_t);
osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl;
}
OsgCameraGroup* _cameraGroup;
OsgSceneHandler* _sceneHandler;
};
std::string findCameraConfigFile(const std::string& configFile)
{
std::string foundFile = osgDB::findDataFile(configFile);
if (foundFile.empty()) return "";
else return foundFile;
}
std::string extractCameraConfigFile(osg::ArgumentParser& arguments)
{
// report the usage options.
if (arguments.getApplicationUsage())
{
arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file");
}
std::string filename;
if (arguments.read("-c",filename)) return findCameraConfigFile(filename);
char *ptr;
if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) )
{
osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl;
return findCameraConfigFile(ptr);
}
return "";
}
OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup()
{
_init();
_applicationUsage = osg::ApplicationUsage::instance();
}
OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg):
Producer::CameraGroup(cfg)
{
_init();
_applicationUsage = osg::ApplicationUsage::instance();
}
OsgCameraGroup::OsgCameraGroup(const std::string& configFile):
Producer::CameraGroup(findCameraConfigFile(configFile))
{
_init();
_applicationUsage = osg::ApplicationUsage::instance();
}
OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments):
Producer::CameraGroup(extractCameraConfigFile(arguments))
{
_init();
_applicationUsage = arguments.getApplicationUsage();
}
void OsgCameraGroup::_init()
{
_thread_model = ThreadPerCamera;
_scene_data = NULL;
_global_stateset = NULL;
_background_color.set( 0.2f, 0.2f, 0.4f, 1.0f );
_LODScale = 1.0f;
_fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE;
_fusionDistanceValue = 1.0f;
_initialized = false;
if (!_frameStamp) _frameStamp = new osg::FrameStamp;
// set up the maximum number of graphics contexts, before loading the scene graph
// to ensure that texture objects and display buffers are configured to the correct size.
osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() );
}
void OsgCameraGroup::setSceneData( osg::Node *scene )
{
if (_scene_data==scene) return;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->removeChild(_scene_data.get());
}
_scene_data = scene;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->addChild(scene);
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setSceneDecorator( osg::Group* decorator)
{
if (_scene_decorator==decorator) return;
_scene_decorator = decorator;
if (_scene_data.valid() && decorator)
{
decorator->addChild(_scene_data.get());
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setUpSceneViewsWithData()
{
for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )
{
if (_scene_decorator.valid())
{
(*p)->setSceneData( _scene_decorator.get() );
}
else if (_scene_data.valid())
{
(*p)->setSceneData( _scene_data.get() );
}
else
{
(*p)->setSceneData( 0 );
}
(*p)->setFrameStamp( _frameStamp.get() );
(*p)->setGlobalStateSet( _global_stateset.get() );
(*p)->setBackgroundColor( _background_color );
(*p)->setLODScale( _LODScale );
(*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
(*p)->getState()->reset();
}
}
void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )
{
_frameStamp = fs;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset )
{
_global_stateset = sset;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor )
{
_background_color = backgroundColor;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setLODScale( float scale )
{
// need to set a local variable?
_LODScale = scale;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)
{
// need to set a local variable?
_fusionDistanceMode = mode;
_fusionDistanceValue = value;
setUpSceneViewsWithData();
}
void OsgCameraGroup::advance()
{
if( !_initialized ) return;
CameraGroup::advance();
}
bool OsgCameraGroup::realize( ThreadingModel thread_model )
{
if( _realized ) return _realized;
_thread_model = thread_model;
return realize();
}
// small visitor to check for the existance of particle systems,
// which currently arn't thread safe, so we would need to disable
// multithreading of cull and draw.
class SearchForParticleNodes : public osg::NodeVisitor
{
public:
SearchForParticleNodes():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_foundParticles(false)
{
}
virtual void apply(osg::Node& node)
{
if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true;
if (!_foundParticles) traverse(node);
}
bool _foundParticles;
};
bool OsgCameraGroup::realize()
{
if( _initialized ) return _realized;
if (!_ds) _ds = osg::DisplaySettings::instance();
_ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );
_shvec.clear();
osg::Node* node = getTopMostSceneData();
if (node)
{
// traverse the scene graphs gathering the requirements of the OpenGL buffers.
osgUtil::DisplayRequirementsVisitor drv;
drv.setDisplaySettings(_ds.get());
node->accept(drv);
}
unsigned int numMultiSamples = 0;
#ifdef __sgi
// switch on anti-aliasing by default, just in case we have an Onyx :-)
numMultiSamples = 4;
#endif
// set up each render stage to clear the appropriate buffers.
GLbitfield clear_mask=0;
if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT;
if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT;
if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT;
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
// create the scene handler.
osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
sh->setDefaults();
sh->getState()->setContextID(i);
_shvec.push_back( sh );
cam->setSceneHandler( sh );
// set up the clear mask.
osgUtil::RenderStage *stage = sh->getRenderStage();
if (stage) stage->setClearMask(clear_mask);
// set the realize callback.
Producer::RenderSurface* rs = cam->getRenderSurface();
rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));
// set up the visual chooser.
if (_ds.valid() || numMultiSamples!=0)
{
Producer::VisualChooser* rs_vc = rs->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
rs_vc->setSimpleConfiguration();
rs->setVisualChooser(rs_vc);
}
if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();
if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());
if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());
rs_vc->setDepthSize(24);
if (numMultiSamples)
{
#if defined( GLX_SAMPLES_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples);
#endif
#if defined( GLX_SAMPLES_BUFFER_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1);
#endif
}
}
}
if( _global_stateset == NULL && _shvec.size() > 0 )
{
SceneHandlerList::iterator p = _shvec.begin();
_global_stateset = (*p)->getGlobalStateSet();
}
setUpSceneViewsWithData();
if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)
{
SearchForParticleNodes sfpn;
getTopMostSceneData()->accept(sfpn);
if (sfpn._foundParticles)
{
osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl;
osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl;
_thread_model = Producer::CameraGroup::SingleThreaded;
}
}
_initialized = CameraGroup::realize();
return _initialized;
}
osg::Node* OsgCameraGroup::getTopMostSceneData()
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
const osg::Node* OsgCameraGroup::getTopMostSceneData() const
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
void OsgCameraGroup::setView(const osg::Matrix& matrix)
{
Producer::Matrix pm(matrix.ptr());
CameraGroup::setView(pm);
}
const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
osg::Matrix matrix;
if (_cfg && _cfg->getNumberOfCameras()>=1)
{
Producer::Camera *cam = _cfg->getCamera(0);
matrix.set(cam->getViewMatrix());
}
return matrix;
}
void OsgCameraGroup::frame()
{
osg::Node* node = getTopMostSceneData();
if (node) node->getBound();
CameraGroup::frame();
_frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 );
}
<commit_msg>Added a setting of OsgCameraGroup::_applicateUsage to ApplicationUsage::instance() by default.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/ApplicationUsage>
#include <osg/Timer>
#include <osg/Notify>
#include <osgUtil/DisplayRequirementsVisitor>
#include <osgDB/FileUtils>
#include <osgProducer/OsgCameraGroup>
using namespace Producer;
using namespace osgProducer;
class RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback
{
public:
RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):
_cameraGroup(cameraGroup),
_sceneHandler(sceneHandler) {}
virtual void operator()( const Producer::RenderSurface & rs)
{
osg::Timer timer;
osg::Timer_t start_t = timer.tick();
if (_cameraGroup->getRealizeCallback())
{
(*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);
}
else if (_sceneHandler) _sceneHandler->init();
osg::Timer_t end_t = timer.tick();
double time = timer.delta_m(start_t,end_t);
osg::notify(osg::INFO) << "Time to init = "<<time<<std::endl;
}
OsgCameraGroup* _cameraGroup;
OsgSceneHandler* _sceneHandler;
};
std::string findCameraConfigFile(const std::string& configFile)
{
std::string foundFile = osgDB::findDataFile(configFile);
if (foundFile.empty()) return "";
else return foundFile;
}
std::string extractCameraConfigFile(osg::ArgumentParser& arguments)
{
// report the usage options.
if (arguments.getApplicationUsage())
{
arguments.getApplicationUsage()->addCommandLineOption("-c <filename>","Specify camera config file");
}
std::string filename;
if (arguments.read("-c",filename)) return findCameraConfigFile(filename);
char *ptr;
if( (ptr = getenv( "PRODUCER_CAMERA_CONFIG_FILE" )) )
{
osg::notify(osg::DEBUG_INFO) << "PRODUCER_CAMERA_CONFIG_FILE("<<ptr<<")"<<std::endl;
return findCameraConfigFile(ptr);
}
return "";
}
OsgCameraGroup::OsgCameraGroup() : Producer::CameraGroup()
{
_init();
}
OsgCameraGroup::OsgCameraGroup(Producer::CameraConfig *cfg):
Producer::CameraGroup(cfg)
{
_init();
}
OsgCameraGroup::OsgCameraGroup(const std::string& configFile):
Producer::CameraGroup(findCameraConfigFile(configFile))
{
_init();
}
OsgCameraGroup::OsgCameraGroup(osg::ArgumentParser& arguments):
Producer::CameraGroup(extractCameraConfigFile(arguments))
{
_init();
_applicationUsage = arguments.getApplicationUsage();
}
void OsgCameraGroup::_init()
{
_thread_model = ThreadPerCamera;
_scene_data = NULL;
_global_stateset = NULL;
_background_color.set( 0.2f, 0.2f, 0.4f, 1.0f );
_LODScale = 1.0f;
_fusionDistanceMode = osgUtil::SceneView::USE_CAMERA_FUSION_DISTANCE;
_fusionDistanceValue = 1.0f;
_initialized = false;
if (!_frameStamp) _frameStamp = new osg::FrameStamp;
// set up the maximum number of graphics contexts, before loading the scene graph
// to ensure that texture objects and display buffers are configured to the correct size.
osg::DisplaySettings::instance()->setMaxNumberOfGraphicsContexts( getNumberOfCameras() );
_applicationUsage = osg::ApplicationUsage::instance();
}
void OsgCameraGroup::setSceneData( osg::Node *scene )
{
if (_scene_data==scene) return;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->removeChild(_scene_data.get());
}
_scene_data = scene;
if (_scene_decorator.valid() && _scene_data.valid())
{
_scene_decorator->addChild(scene);
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setSceneDecorator( osg::Group* decorator)
{
if (_scene_decorator==decorator) return;
_scene_decorator = decorator;
if (_scene_data.valid() && decorator)
{
decorator->addChild(_scene_data.get());
}
setUpSceneViewsWithData();
}
void OsgCameraGroup::setUpSceneViewsWithData()
{
for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )
{
if (_scene_decorator.valid())
{
(*p)->setSceneData( _scene_decorator.get() );
}
else if (_scene_data.valid())
{
(*p)->setSceneData( _scene_data.get() );
}
else
{
(*p)->setSceneData( 0 );
}
(*p)->setFrameStamp( _frameStamp.get() );
(*p)->setGlobalStateSet( _global_stateset.get() );
(*p)->setBackgroundColor( _background_color );
(*p)->setLODScale( _LODScale );
(*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );
(*p)->getState()->reset();
}
}
void OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )
{
_frameStamp = fs;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset )
{
_global_stateset = sset;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor )
{
_background_color = backgroundColor;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setLODScale( float scale )
{
// need to set a local variable?
_LODScale = scale;
setUpSceneViewsWithData();
}
void OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)
{
// need to set a local variable?
_fusionDistanceMode = mode;
_fusionDistanceValue = value;
setUpSceneViewsWithData();
}
void OsgCameraGroup::advance()
{
if( !_initialized ) return;
CameraGroup::advance();
}
bool OsgCameraGroup::realize( ThreadingModel thread_model )
{
if( _realized ) return _realized;
_thread_model = thread_model;
return realize();
}
// small visitor to check for the existance of particle systems,
// which currently arn't thread safe, so we would need to disable
// multithreading of cull and draw.
class SearchForParticleNodes : public osg::NodeVisitor
{
public:
SearchForParticleNodes():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_foundParticles(false)
{
}
virtual void apply(osg::Node& node)
{
if (strcmp(node.libraryName(),"osgParticle")==0) _foundParticles = true;
if (!_foundParticles) traverse(node);
}
bool _foundParticles;
};
bool OsgCameraGroup::realize()
{
if( _initialized ) return _realized;
if (!_ds) _ds = osg::DisplaySettings::instance();
_ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );
_shvec.clear();
osg::Node* node = getTopMostSceneData();
if (node)
{
// traverse the scene graphs gathering the requirements of the OpenGL buffers.
osgUtil::DisplayRequirementsVisitor drv;
drv.setDisplaySettings(_ds.get());
node->accept(drv);
}
unsigned int numMultiSamples = 0;
#ifdef __sgi
// switch on anti-aliasing by default, just in case we have an Onyx :-)
numMultiSamples = 4;
#endif
// set up each render stage to clear the appropriate buffers.
GLbitfield clear_mask=0;
if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT;
if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT;
if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT;
for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )
{
Producer::Camera *cam = _cfg->getCamera(i);
// create the scene handler.
osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());
sh->setDefaults();
sh->getState()->setContextID(i);
_shvec.push_back( sh );
cam->setSceneHandler( sh );
// set up the clear mask.
osgUtil::RenderStage *stage = sh->getRenderStage();
if (stage) stage->setClearMask(clear_mask);
// set the realize callback.
Producer::RenderSurface* rs = cam->getRenderSurface();
rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));
// set up the visual chooser.
if (_ds.valid() || numMultiSamples!=0)
{
Producer::VisualChooser* rs_vc = rs->getVisualChooser();
if (!rs_vc)
{
rs_vc = new Producer::VisualChooser;
rs_vc->setSimpleConfiguration();
rs->setVisualChooser(rs_vc);
}
if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();
if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());
if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());
rs_vc->setDepthSize(24);
if (numMultiSamples)
{
#if defined( GLX_SAMPLES_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples);
#endif
#if defined( GLX_SAMPLES_BUFFER_SGIS )
rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1);
#endif
}
}
}
if( _global_stateset == NULL && _shvec.size() > 0 )
{
SceneHandlerList::iterator p = _shvec.begin();
_global_stateset = (*p)->getGlobalStateSet();
}
setUpSceneViewsWithData();
if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)
{
SearchForParticleNodes sfpn;
getTopMostSceneData()->accept(sfpn);
if (sfpn._foundParticles)
{
osg::notify(osg::INFO)<<"Warning: disabling multi-threading of cull and draw"<<std::endl;
osg::notify(osg::INFO)<<" to avoid threading problems in osgParticle."<<std::endl;
_thread_model = Producer::CameraGroup::SingleThreaded;
}
}
_initialized = CameraGroup::realize();
return _initialized;
}
osg::Node* OsgCameraGroup::getTopMostSceneData()
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
const osg::Node* OsgCameraGroup::getTopMostSceneData() const
{
if (_scene_decorator.valid())
return _scene_decorator.get();
else
return _scene_data.get();
}
void OsgCameraGroup::setView(const osg::Matrix& matrix)
{
Producer::Matrix pm(matrix.ptr());
CameraGroup::setView(pm);
}
const osg::Matrix OsgCameraGroup::getViewMatrix() const
{
osg::Matrix matrix;
if (_cfg && _cfg->getNumberOfCameras()>=1)
{
Producer::Camera *cam = _cfg->getCamera(0);
matrix.set(cam->getViewMatrix());
}
return matrix;
}
void OsgCameraGroup::frame()
{
osg::Node* node = getTopMostSceneData();
if (node) node->getBound();
CameraGroup::frame();
_frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 );
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "OrbitSshQt/Tunnel.h"
#include <QHostAddress>
#include <QTimer>
#include "OrbitBase/Logging.h"
#include "OrbitSshQt/Error.h"
/**
* Schedules a task in the currently running event loop.
*
* This task checks first whether parent still exists and afterwards destructs
* the content of opt (which is supposed to be a member of parent.)
*
* parent needs to be derived from QObject.
**/
template <typename P, typename T>
static void deleteByEventLoop(P* parent, std::optional<T>* opt) {
if (opt) {
QTimer::singleShot(0, [opt, parent = QPointer<P>(parent)]() {
if (parent && opt) {
*opt = std::nullopt;
}
});
}
}
namespace OrbitSshQt {
Tunnel::Tunnel(Session* session, std::string remote_host, uint16_t remote_port, QObject* parent)
: StateMachineHelper(parent),
session_(session),
remote_host_(std::move(remote_host)),
remote_port_(remote_port) {
about_to_shutdown_connection_.emplace(
QObject::connect(session_, &Session::aboutToShutdown, this, &Tunnel::HandleSessionShutdown));
}
void Tunnel::Start() {
if (CurrentState() == State::kInitial) {
SetState(State::kNoChannel);
OnEvent();
}
}
void Tunnel::Stop() {
if (CurrentState() == State::kError) {
return;
}
if (CurrentState() < State::kStarted) {
SetState(State::kDone);
deleteByEventLoop(this, &local_server_);
channel_ = std::nullopt;
}
if (CurrentState() == State::kServerListening) {
SetState(State::kFlushing);
OnEvent();
}
}
outcome::result<void> Tunnel::startup() {
if (!data_event_connection_) {
data_event_connection_.emplace(
QObject::connect(session_, &Session::dataEvent, this, &Tunnel::OnEvent));
}
switch (CurrentState()) {
case State::kInitial:
case State::kNoChannel: {
OUTCOME_TRY(channel, OrbitSsh::Channel::OpenTcpIpTunnel(session_->GetRawSession(),
remote_host_, remote_port_));
channel_ = std::move(channel);
SetState(State::kChannelInitialized);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kChannelInitialized: {
local_server_.emplace(this);
const auto result = local_server_->listen(QHostAddress{QHostAddress::LocalHost});
if (!result) {
return Error::kCouldNotListen;
}
QObject::connect(&local_server_.value(), &QTcpServer::newConnection, this, [&]() {
if (!local_socket_) {
local_socket_ = local_server_->nextPendingConnection();
local_server_->pauseAccepting();
QObject::connect(local_socket_, &QTcpSocket::readyRead, this,
&Tunnel::HandleIncomingDataLocalSocket);
QObject::connect(local_socket_, &QTcpSocket::disconnected, this, [&]() { Stop(); });
}
});
SetState(State::kServerListening);
emit tunnelOpened(GetListenPort());
break;
}
case State::kStarted:
case State::kServerListening:
case State::kShutdown:
case State::kFlushing:
case State::kSendEOF:
case State::kClosingChannel:
case State::kWaitRemoteClosed:
case State::kDone:
case State::kError:
UNREACHABLE();
}
return outcome::success();
}
outcome::result<void> Tunnel::shutdown() {
switch (CurrentState()) {
case State::kInitial:
case State::kNoChannel:
case State::kChannelInitialized:
case State::kStarted:
case State::kServerListening:
UNREACHABLE();
case State::kShutdown:
case State::kFlushing: {
OUTCOME_TRY(writeToChannel());
SetState(State::kSendEOF);
// local_server_ might have triggered this shutdown iteration and we can't
// delete it when it's still somewhere up in the callstack.
deleteByEventLoop(this, &local_server_);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kSendEOF: {
OUTCOME_TRY(channel_->SendEOF());
SetState(State::kClosingChannel);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kClosingChannel: {
OUTCOME_TRY(channel_->Close());
SetState(State::kWaitRemoteClosed);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kWaitRemoteClosed: {
OUTCOME_TRY(channel_->WaitClosed());
SetState(State::kDone);
data_event_connection_ = std::nullopt;
about_to_shutdown_connection_ = std::nullopt;
channel_ = std::nullopt;
ABSL_FALLTHROUGH_INTENDED;
}
case State::kDone:
break;
case State::kError:
UNREACHABLE();
}
return outcome::success();
}
outcome::result<void> Tunnel::readFromChannel() {
while (true) {
const size_t kChunkSize = 1024 * 1024;
const auto result = channel_->ReadStdOut(kChunkSize);
if (!result && !OrbitSsh::ShouldITryAgain(result)) {
return outcome::failure(result.error());
} else if (!result) {
// That's the EAGAIN case
HandleEagain();
break;
} else if (result && result.value().empty()) {
// Empty result means remote socket was closed.
return Error::kRemoteSocketClosed;
} else if (result) {
read_buffer_.append(result.value());
}
}
if (local_socket_ && !read_buffer_.empty()) {
const auto bytes_written = local_socket_->write(read_buffer_.data(), read_buffer_.size());
if (bytes_written == -1) {
SetError(Error::kLocalSocketClosed);
} else {
CHECK(static_cast<size_t>(bytes_written) <= read_buffer_.size());
read_buffer_.erase(read_buffer_.begin(), read_buffer_.begin() + bytes_written);
}
}
return outcome::success();
}
outcome::result<void> Tunnel::writeToChannel() {
if (!write_buffer_.empty()) {
const std::string_view buffer_view{write_buffer_.data(), write_buffer_.size()};
OUTCOME_TRY(bytes_written, channel_->Write(buffer_view));
CHECK(static_cast<size_t>(bytes_written) <= write_buffer_.size());
write_buffer_.erase(write_buffer_.begin(), write_buffer_.begin() + bytes_written);
}
return outcome::success();
}
outcome::result<void> Tunnel::run() {
OUTCOME_TRY(readFromChannel());
OUTCOME_TRY(writeToChannel());
return outcome::success();
}
void Tunnel::SetError(std::error_code e) {
data_event_connection_ = std::nullopt;
about_to_shutdown_connection_ = std::nullopt;
StateMachineHelper::SetError(e);
// local_server_ might have triggered this error and we can't delete it when
// it's still somewhere up in the callstack.
deleteByEventLoop(this, &local_server_);
channel_ = std::nullopt;
}
// local_socket -> write_buffer_
void Tunnel::HandleIncomingDataLocalSocket() {
const auto data = local_socket_->readAll();
write_buffer_.append(data.toStdString());
const auto result = writeToChannel();
if (!result && !OrbitSsh::ShouldITryAgain(result)) {
SetError(result.error());
return;
} else if (!result) {
HandleEagain();
}
}
void Tunnel::HandleSessionShutdown() {
if (CurrentState() >= State::kChannelInitialized && CurrentState() < State::kDone) {
SetError(Error::kUncleanSessionShutdown);
}
}
void Tunnel::HandleEagain() {
if (session_) {
session_->HandleEagain();
}
}
} // namespace OrbitSshQt
<commit_msg>Avoid temporary std::string in OrbitSshQt::Tunnel<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "OrbitSshQt/Tunnel.h"
#include <QHostAddress>
#include <QTimer>
#include "OrbitBase/Logging.h"
#include "OrbitSshQt/Error.h"
/**
* Schedules a task in the currently running event loop.
*
* This task checks first whether parent still exists and afterwards destructs
* the content of opt (which is supposed to be a member of parent.)
*
* parent needs to be derived from QObject.
**/
template <typename P, typename T>
static void deleteByEventLoop(P* parent, std::optional<T>* opt) {
if (opt) {
QTimer::singleShot(0, [opt, parent = QPointer<P>(parent)]() {
if (parent && opt) {
*opt = std::nullopt;
}
});
}
}
namespace OrbitSshQt {
Tunnel::Tunnel(Session* session, std::string remote_host, uint16_t remote_port, QObject* parent)
: StateMachineHelper(parent),
session_(session),
remote_host_(std::move(remote_host)),
remote_port_(remote_port) {
about_to_shutdown_connection_.emplace(
QObject::connect(session_, &Session::aboutToShutdown, this, &Tunnel::HandleSessionShutdown));
}
void Tunnel::Start() {
if (CurrentState() == State::kInitial) {
SetState(State::kNoChannel);
OnEvent();
}
}
void Tunnel::Stop() {
if (CurrentState() == State::kError) {
return;
}
if (CurrentState() < State::kStarted) {
SetState(State::kDone);
deleteByEventLoop(this, &local_server_);
channel_ = std::nullopt;
}
if (CurrentState() == State::kServerListening) {
SetState(State::kFlushing);
OnEvent();
}
}
outcome::result<void> Tunnel::startup() {
if (!data_event_connection_) {
data_event_connection_.emplace(
QObject::connect(session_, &Session::dataEvent, this, &Tunnel::OnEvent));
}
switch (CurrentState()) {
case State::kInitial:
case State::kNoChannel: {
OUTCOME_TRY(channel, OrbitSsh::Channel::OpenTcpIpTunnel(session_->GetRawSession(),
remote_host_, remote_port_));
channel_ = std::move(channel);
SetState(State::kChannelInitialized);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kChannelInitialized: {
local_server_.emplace(this);
const auto result = local_server_->listen(QHostAddress{QHostAddress::LocalHost});
if (!result) {
return Error::kCouldNotListen;
}
QObject::connect(&local_server_.value(), &QTcpServer::newConnection, this, [&]() {
if (!local_socket_) {
local_socket_ = local_server_->nextPendingConnection();
local_server_->pauseAccepting();
QObject::connect(local_socket_, &QTcpSocket::readyRead, this,
&Tunnel::HandleIncomingDataLocalSocket);
QObject::connect(local_socket_, &QTcpSocket::disconnected, this, [&]() { Stop(); });
}
});
SetState(State::kServerListening);
emit tunnelOpened(GetListenPort());
break;
}
case State::kStarted:
case State::kServerListening:
case State::kShutdown:
case State::kFlushing:
case State::kSendEOF:
case State::kClosingChannel:
case State::kWaitRemoteClosed:
case State::kDone:
case State::kError:
UNREACHABLE();
}
return outcome::success();
}
outcome::result<void> Tunnel::shutdown() {
switch (CurrentState()) {
case State::kInitial:
case State::kNoChannel:
case State::kChannelInitialized:
case State::kStarted:
case State::kServerListening:
UNREACHABLE();
case State::kShutdown:
case State::kFlushing: {
OUTCOME_TRY(writeToChannel());
SetState(State::kSendEOF);
// local_server_ might have triggered this shutdown iteration and we can't
// delete it when it's still somewhere up in the callstack.
deleteByEventLoop(this, &local_server_);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kSendEOF: {
OUTCOME_TRY(channel_->SendEOF());
SetState(State::kClosingChannel);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kClosingChannel: {
OUTCOME_TRY(channel_->Close());
SetState(State::kWaitRemoteClosed);
ABSL_FALLTHROUGH_INTENDED;
}
case State::kWaitRemoteClosed: {
OUTCOME_TRY(channel_->WaitClosed());
SetState(State::kDone);
data_event_connection_ = std::nullopt;
about_to_shutdown_connection_ = std::nullopt;
channel_ = std::nullopt;
ABSL_FALLTHROUGH_INTENDED;
}
case State::kDone:
break;
case State::kError:
UNREACHABLE();
}
return outcome::success();
}
outcome::result<void> Tunnel::readFromChannel() {
while (true) {
const size_t kChunkSize = 1024 * 1024;
const auto result = channel_->ReadStdOut(kChunkSize);
if (!result && !OrbitSsh::ShouldITryAgain(result)) {
return outcome::failure(result.error());
} else if (!result) {
// That's the EAGAIN case
HandleEagain();
break;
} else if (result && result.value().empty()) {
// Empty result means remote socket was closed.
return Error::kRemoteSocketClosed;
} else if (result) {
read_buffer_.append(result.value());
}
}
if (local_socket_ && !read_buffer_.empty()) {
const auto bytes_written = local_socket_->write(read_buffer_.data(), read_buffer_.size());
if (bytes_written == -1) {
SetError(Error::kLocalSocketClosed);
} else {
CHECK(static_cast<size_t>(bytes_written) <= read_buffer_.size());
read_buffer_.erase(read_buffer_.begin(), read_buffer_.begin() + bytes_written);
}
}
return outcome::success();
}
outcome::result<void> Tunnel::writeToChannel() {
if (!write_buffer_.empty()) {
const std::string_view buffer_view{write_buffer_.data(), write_buffer_.size()};
OUTCOME_TRY(bytes_written, channel_->Write(buffer_view));
CHECK(static_cast<size_t>(bytes_written) <= write_buffer_.size());
write_buffer_.erase(write_buffer_.begin(), write_buffer_.begin() + bytes_written);
}
return outcome::success();
}
outcome::result<void> Tunnel::run() {
OUTCOME_TRY(readFromChannel());
OUTCOME_TRY(writeToChannel());
return outcome::success();
}
void Tunnel::SetError(std::error_code e) {
data_event_connection_ = std::nullopt;
about_to_shutdown_connection_ = std::nullopt;
StateMachineHelper::SetError(e);
// local_server_ might have triggered this error and we can't delete it when
// it's still somewhere up in the callstack.
deleteByEventLoop(this, &local_server_);
channel_ = std::nullopt;
}
// local_socket -> write_buffer_
void Tunnel::HandleIncomingDataLocalSocket() {
const auto data = local_socket_->readAll();
write_buffer_.insert(write_buffer_.end(), data.begin(), data.end());
const auto result = writeToChannel();
if (!result && !OrbitSsh::ShouldITryAgain(result)) {
SetError(result.error());
return;
} else if (!result) {
HandleEagain();
}
}
void Tunnel::HandleSessionShutdown() {
if (CurrentState() >= State::kChannelInitialized && CurrentState() < State::kDone) {
SetError(Error::kUncleanSessionShutdown);
}
}
void Tunnel::HandleEagain() {
if (session_) {
session_->HandleEagain();
}
}
} // namespace OrbitSshQt
<|endoftext|>
|
<commit_before>/*********************************************************************
* Thinker *
* *
* Logistic-function neural network with backpropagation. *
* *
* (c) Jack Peterson, 9/9/2008 *
*********************************************************************/
#include "thinker.h"
#include "test.h"
namespace Thinker {
MTRand_open rand((unsigned)time(0));
NeuralNetwork::NeuralNetwork(const int n_inputs,
const int n_hidden,
const int n_outputs)
: n_inputs(n_inputs + 1)
, n_hidden(n_hidden)
, n_outputs(n_outputs)
{
// Initialize each neural layer
input_layer.assign(n_inputs, 0.0);
hidden_layer.assign(n_hidden, 0.0);
output_layer.assign(n_outputs, 0.0);
// Add a bias term to the input layer
input_layer.push_back(1.0);
}
void NeuralNetwork::innervate()
{
// Build weight matrices
for (int i = 0; i < n_inputs; i++) {
input_weights.push_back(nerve());
for (int j = 0; j < n_hidden; j++) {
input_weights[i].push_back(rzero(2.0*rand() - 1.0));
}
}
for (int i = 0; i < n_hidden; i++) {
output_weights.push_back(nerve());
for (int j = 0; j < n_outputs; j++) {
output_weights[i].push_back(rzero(2.0*rand() - 1.0));
}
}
// Build feedback matrices
for (int i = 0; i < n_inputs; i++) {
hidden_feedback.push_back(nerve());
for (int j = 0; j < n_hidden; j++) {
hidden_feedback[i].push_back(0.0);
}
}
for (int i = 0; i < n_hidden; i++) {
output_feedback.push_back(nerve());
for (int j = 0; j < n_outputs; j++) {
output_feedback[i].push_back(0.0);
}
}
}
nerve NeuralNetwork::feedforward(const nerve& pattern)
{
double weighted_sum;
// Update input nodes (except bias term)
for (int i = 0; i < n_inputs - 1; i++) {
input_layer[i] = pattern[i];
}
// Update hidden nodes
for (int i = 0; i < n_hidden; i++) {
weighted_sum = 0.0;
for (int j = 0; j < n_inputs; j++) {
weighted_sum += input_layer[j] * input_weights[j][i];
}
hidden_layer[i] = logistic(weighted_sum);
}
// Update output nodes
for (int i = 0; i < n_outputs; i++) {
weighted_sum = 0.0;
for (int j = 0; j < n_hidden; j++) {
weighted_sum += hidden_layer[j] * output_weights[j][i];
}
output_layer[i] = logistic(weighted_sum);
}
return output_layer;
}
double NeuralNetwork::backpropagate(const nerve& target,
const double learning_rate)
{
double error;
double sigmoid;
double feedback_weight;
double RMSE; // root mean squared error
nerve output_feedback_updated;
nerve hidden_feedback_updated;
// Calculate updated output feedback vector
for (int i = 0; i < n_outputs; i++) {
error = rzero(target[i] - output_layer[i]);
sigmoid = logistic(output_layer[i]);
output_feedback_updated.push_back(rzero(error * sigmoid * (1.0 - sigmoid)));
}
// Calculate updated hidden feedback vector
for (int i = 0; i < n_hidden; i++) {
error = 0.0;
for (int j = 0; j < n_outputs; j++) {
error += rzero(output_feedback_updated[j] * output_weights[i][j]);
}
sigmoid = logistic(hidden_layer[i]);
hidden_feedback_updated.push_back(rzero(error * sigmoid * (1.0 - sigmoid)));
}
// Update the hidden-to-output weights
for (int i = 0; i < n_hidden; i++) {
for (int j = 0; j < n_outputs; j++) {
feedback_weight = rzero(output_feedback_updated[j] * hidden_layer[i]);
output_weights[i][j] += rzero(learning_rate * feedback_weight);
output_feedback[i][j] = feedback_weight;
}
}
// Update the input-to-hidden weights
for (int i = 0; i < n_inputs; i++) {
for (int j = 0; j < n_hidden; j++) {
feedback_weight = hidden_feedback_updated[j] * input_layer[i];
input_weights[i][j] += rzero(learning_rate * feedback_weight);
hidden_feedback[i][j] = feedback_weight;
}
}
// Root mean squared error (RMSE) between desired and actual output
RMSE = 0.0;
for (int i = 0; i < n_outputs; i++) {
RMSE += std::sqrt(std::pow(target[i] - output_layer[i], 2));
}
return RMSE / n_outputs;
}
inline double NeuralNetwork::logistic(const double x) const
{
return rzero(1.0 / (1.0 + exp(-x)));
}
void NeuralNetwork::train(const synapse& input_grid,
const synapse& output_grid,
const int num_iterations,
const double learning_rate)
{
double error;
DEBUG("Training: %d iterations, %f learning rate\n",
num_iterations, learning_rate);
for (int i = 0; i < num_iterations; i++) {
error = 0.0;
for (unsigned j = 0; j < input_grid.size(); j++) {
feedforward(input_grid[j]);
error += backpropagate(output_grid[j], learning_rate);
}
if (i == 0) {
DEBUG("Error [%d]: %f\n", i, error);
}
}
DEBUG("Final error: %f\n", error);
DEBUG("Training complete!\n");
}
void NeuralNetwork::test(const synapse& input_grid, const synapse& output_grid)
{
nerve result;
DEBUG("\nTesting [input --> output]:\n");
for (unsigned i = 0; i < input_grid.size(); i++) {
result = feedforward(input_grid[i]);
for (unsigned j = 0; j < input_grid[i].size(); j++) {
DEBUG("%f ", input_grid[i][j]);
}
DEBUG("--> ");
for (unsigned j = 0; j < output_grid[i].size(); j++) {
DEBUG("%f ", result[j]);
}
DEBUG("\n");
}
print_layers();
}
void NeuralNetwork::print_layers() const
{
DEBUG("\nInputs [%d nodes]: ", n_inputs);
print(input_layer);
DEBUG("Hidden [%d nodes]: ", n_hidden);
print(hidden_layer);
DEBUG("Output [%d nodes]: ", n_outputs);
print(output_layer);
DEBUG("\n");
}
void NeuralNetwork::print_weights() const
{
DEBUG("\nInput-to-hidden weights:");
print(input_weights);
DEBUG("\nHidden-to-output weights:");
print(output_weights);
DEBUG("\nInput-to-hidden deltas:");
print(hidden_feedback);
DEBUG("\nHidden-to-output deltas:");
print(output_feedback);
}
void NeuralNetwork::print(const nerve& n) const
{
for (unsigned i = 0; i < n.size(); i++) {
DEBUG("%f ", n[i]);
}
DEBUG("\n");
}
void NeuralNetwork::print(const synapse& s) const
{
for (unsigned i = 0; i < s.size(); i++) {
for (unsigned j = 0; j < s[i].size(); j++) {
DEBUG("%f ", s[i][j]);
}
DEBUG("\n");
}
DEBUG("\n");
}
double rzero(const double x)
{
if (x < EPSILON && x > -EPSILON) {
return 0.0;
}
return x;
}
} // namespace
int main()
{
const int INPUT_NODES = 7;
const int HIDDEN_NODES = 4;
const int OUTPUT_NODES = 7;
// Create and initialize the neural network
Thinker::NeuralNetwork neural_network(INPUT_NODES, HIDDEN_NODES, OUTPUT_NODES);
neural_network.innervate();
// Test drive the network
Thinker::identity_matrix(neural_network, INPUT_NODES, OUTPUT_NODES);
return 0;
}
<commit_msg>inlining<commit_after>/*********************************************************************
* Thinker *
* *
* Logistic-function neural network with backpropagation. *
* *
* (c) Jack Peterson, 9/9/2008 *
*********************************************************************/
#include "thinker.h"
#include "test.h"
namespace Thinker {
MTRand_open rand((unsigned)time(0));
NeuralNetwork::NeuralNetwork(const int n_inputs,
const int n_hidden,
const int n_outputs)
: n_inputs(n_inputs + 1)
, n_hidden(n_hidden)
, n_outputs(n_outputs)
{
// Initialize each neural layer
input_layer.assign(n_inputs, 0.0);
hidden_layer.assign(n_hidden, 0.0);
output_layer.assign(n_outputs, 0.0);
// Add a bias term to the input layer
input_layer.push_back(1.0);
}
void NeuralNetwork::innervate()
{
// Build weight matrices
for (int i = 0; i < n_inputs; i++) {
input_weights.push_back(nerve());
for (int j = 0; j < n_hidden; j++) {
input_weights[i].push_back(rzero(2.0*rand() - 1.0));
}
}
for (int i = 0; i < n_hidden; i++) {
output_weights.push_back(nerve());
for (int j = 0; j < n_outputs; j++) {
output_weights[i].push_back(rzero(2.0*rand() - 1.0));
}
}
// Build feedback matrices
for (int i = 0; i < n_inputs; i++) {
hidden_feedback.push_back(nerve());
for (int j = 0; j < n_hidden; j++) {
hidden_feedback[i].push_back(0.0);
}
}
for (int i = 0; i < n_hidden; i++) {
output_feedback.push_back(nerve());
for (int j = 0; j < n_outputs; j++) {
output_feedback[i].push_back(0.0);
}
}
}
nerve NeuralNetwork::feedforward(const nerve& pattern)
{
double weighted_sum;
// Update input nodes (except bias term)
for (int i = 0; i < n_inputs - 1; i++) {
input_layer[i] = pattern[i];
}
// Update hidden nodes
for (int i = 0; i < n_hidden; i++) {
weighted_sum = 0.0;
for (int j = 0; j < n_inputs; j++) {
weighted_sum += input_layer[j] * input_weights[j][i];
}
hidden_layer[i] = logistic(weighted_sum);
}
// Update output nodes
for (int i = 0; i < n_outputs; i++) {
weighted_sum = 0.0;
for (int j = 0; j < n_hidden; j++) {
weighted_sum += hidden_layer[j] * output_weights[j][i];
}
output_layer[i] = logistic(weighted_sum);
}
return output_layer;
}
double NeuralNetwork::backpropagate(const nerve& target,
const double learning_rate)
{
double error;
double sigmoid;
double feedback_weight;
double RMSE; // root mean squared error
nerve output_feedback_updated;
nerve hidden_feedback_updated;
// Calculate updated output feedback vector
for (int i = 0; i < n_outputs; i++) {
error = rzero(target[i] - output_layer[i]);
sigmoid = logistic(output_layer[i]);
output_feedback_updated.push_back(rzero(error * sigmoid * (1.0 - sigmoid)));
}
// Calculate updated hidden feedback vector
for (int i = 0; i < n_hidden; i++) {
error = 0.0;
for (int j = 0; j < n_outputs; j++) {
error += rzero(output_feedback_updated[j] * output_weights[i][j]);
}
sigmoid = logistic(hidden_layer[i]);
hidden_feedback_updated.push_back(rzero(error * sigmoid * (1.0 - sigmoid)));
}
// Update the hidden-to-output weights
for (int i = 0; i < n_hidden; i++) {
for (int j = 0; j < n_outputs; j++) {
feedback_weight = rzero(output_feedback_updated[j] * hidden_layer[i]);
output_weights[i][j] += rzero(learning_rate * feedback_weight);
output_feedback[i][j] = feedback_weight;
}
}
// Update the input-to-hidden weights
for (int i = 0; i < n_inputs; i++) {
for (int j = 0; j < n_hidden; j++) {
feedback_weight = hidden_feedback_updated[j] * input_layer[i];
input_weights[i][j] += rzero(learning_rate * feedback_weight);
hidden_feedback[i][j] = feedback_weight;
}
}
// Root mean squared error (RMSE) between desired and actual output
RMSE = 0.0;
for (int i = 0; i < n_outputs; i++) {
RMSE += std::sqrt(std::pow(target[i] - output_layer[i], 2));
}
return RMSE / n_outputs;
}
inline double NeuralNetwork::logistic(const double x) const
{
return 1.0 / (1.0 + exp(-x));
}
void NeuralNetwork::train(const synapse& input_grid,
const synapse& output_grid,
const int num_iterations,
const double learning_rate)
{
double error;
DEBUG("Training: %d iterations, %f learning rate\n",
num_iterations, learning_rate);
for (int i = 0; i < num_iterations; i++) {
error = 0.0;
for (unsigned j = 0; j < input_grid.size(); j++) {
feedforward(input_grid[j]);
error += backpropagate(output_grid[j], learning_rate);
}
if (i == 0) {
DEBUG("Error [%d]: %f\n", i, error);
}
}
DEBUG("Final error: %f\n", error);
DEBUG("Training complete!\n");
}
void NeuralNetwork::test(const synapse& input_grid, const synapse& output_grid)
{
nerve result;
DEBUG("\nTesting [input --> output]:\n");
for (unsigned i = 0; i < input_grid.size(); i++) {
result = feedforward(input_grid[i]);
for (unsigned j = 0; j < input_grid[i].size(); j++) {
DEBUG("%f ", input_grid[i][j]);
}
DEBUG("--> ");
for (unsigned j = 0; j < output_grid[i].size(); j++) {
DEBUG("%f ", result[j]);
}
DEBUG("\n");
}
print_layers();
}
void NeuralNetwork::print_layers() const
{
DEBUG("\nInputs [%d nodes]: ", n_inputs);
print(input_layer);
DEBUG("Hidden [%d nodes]: ", n_hidden);
print(hidden_layer);
DEBUG("Output [%d nodes]: ", n_outputs);
print(output_layer);
DEBUG("\n");
}
void NeuralNetwork::print_weights() const
{
DEBUG("\nInput-to-hidden weights:");
print(input_weights);
DEBUG("\nHidden-to-output weights:");
print(output_weights);
DEBUG("\nInput-to-hidden deltas:");
print(hidden_feedback);
DEBUG("\nHidden-to-output deltas:");
print(output_feedback);
}
void NeuralNetwork::print(const nerve& n) const
{
for (unsigned i = 0; i < n.size(); i++) {
DEBUG("%f ", n[i]);
}
DEBUG("\n");
}
void NeuralNetwork::print(const synapse& s) const
{
for (unsigned i = 0; i < s.size(); i++) {
for (unsigned j = 0; j < s[i].size(); j++) {
DEBUG("%f ", s[i][j]);
}
DEBUG("\n");
}
DEBUG("\n");
}
double rzero(const double x)
{
if (x < EPSILON && x > -EPSILON) {
return 0.0;
}
return x;
}
} // namespace
int main()
{
const int INPUT_NODES = 7;
const int HIDDEN_NODES = 4;
const int OUTPUT_NODES = 7;
// Create and initialize the neural network
Thinker::NeuralNetwork neural_network(INPUT_NODES, HIDDEN_NODES, OUTPUT_NODES);
neural_network.innervate();
// Test drive the network
Thinker::identity_matrix(neural_network, INPUT_NODES, OUTPUT_NODES);
return 0;
}
<|endoftext|>
|
<commit_before>/*!
* \file File tileSet.cpp
* \brief Implementation of the class TileSet
*
* Auxiliary documentation
* \sa tileSet.hpp
*/
#include <tileSet.hpp>
#include <assert.h>
/*!
@class TileSet
@brief This class provides the tile sets to the game
*/
//! A constructor.
/*!
* This is a constructor method of TileSet class
* \param width
* \brief A positive integer, that represents width of a tile
* \param height
* \brief A positive integer, that represents height of a tile
* \param file_path
* \brief A string, that represents path of the file with the tile set
*/
TileSet::TileSet(int width, int height, string file_path) {
LOG_METHOD_START("TileSet::TileSet");
LOG_VARIABLE("width",width);
assert(width >= 0);
LOG_VARIABLE("height",height);
assert(height >= 0);
LOG_VARIABLE("file_path",file_path);
assert(file_path != NULL)
LOG_MSG("This is a constructor method of TileSet class");
load(width, height, file_path);
LOG_METHOD_CLOSE("TileSet::TileSet","constructor");
}
//! A constructor.
/*!
This is a empty constructor method of TileSet class
*/
TileSet::TileSet() {
LOG_METHOD_START("TileSet::TileSet");
LOG_METHOD_CLOSE("TileSet::TileSet","constructor");
}
/*!
@fn void TileSet::render(unsigned int index,float position_x,float position_y, float extended_scale)
@brief Method that renders the tile set
@param index
@brief A unsigned integer
@param position_x
@brief A float
@param position_y
@brief A float
@param extended_scale
@brief A float
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void TileSet::render(unsigned int index,float position_x,float position_y, float extended_scale) {
LOG_METHOD_START("TileSet::render");
LOG_VARIABLE("index",index);
LOG_VARIABLE("position_x",position_x);
LOG_VARIABLE("position_y",position_y);
LOG_VARIABLE("extended_scale",extended_scale);
//! Checks if the number of tiles is bigger that the index
if ((int)index<(rows*columns)) {
tileSet.SetClip(tile_width*(index%columns),(tile_height*(index/columns)),tile_width,tile_height);
tileSet.render(position_x,position_y,0,extended_scale);
}
//! \warning else (do nothing)
LOG_METHOD_CLOSE("TileSet::render","void");
}
/*!
@fn void TileSet::load(int width, int height, string file_path)
@brief Method that loads the tile set from the file
@param width
@brief A positive integer, that represents width of a tile
@param height
@brief A positive integer, that represents height of a tile
@param file_path
@brief A string, that represents path of the file with the tile set
@return The execution of this method returns no value
*/
void TileSet::load(int width, int height, string file_path) {
LOG_METHOD_START("TileSet::load");
LOG_VARIABLE("width",width);
assert(width >= 0);
LOG_VARIABLE("height",height);
assert(height >= 0);
LOG_VARIABLE("file_path",file_path);
assert(file_path != NULL);
//! Attributes the value of the width and height of a tile
tile_width = width;
tile_height = height;
//! Opens the file with the tile set
tileSet.Open(file_path);
//! Defines the numbers of rows and columns of the tile set
rows = tileSet.GetHeight()/tile_height;
assert(rows >= 0);
columns = tileSet.GetWidth()/tile_width;
assert(columns >= 0);
LOG_METHOD_CLOSE("TileSet::load","void");
}
/*!
@fn int TileSet::get_width()
@brief A getter of the attribute tileWidth
@return A positive integer, that represents the width of a tile
*/
int TileSet::get_width() {
LOG_METHOD_START("TileSet::get_width");
LOG_METHOD_CLOSE("TileSet::get_width",tile_width);
assert(tile_width >= 0);
return tile_width;
}
/*!
@fn int TileSet::get_height()
@brief A getter of the attribute tileHeight
@return A positive integer, that represents the height of a tile
*/
int TileSet::get_height() {
LOG_METHOD_START("TileSet::get_height");
LOG_METHOD_CLOSE("TileSet::get_height",tile_height);
assert(tile_height >= 0);
return tile_height;
}
/*!
@fn int TileSet::get_tile_count()
@brief Method that returns the number of tiles in the tile set
@return A positive integer, that number of tiles in the tile set
*/
int TileSet::get_tile_count() {
LOG_METHOD_START("TileSet::get_tile_count");
LOG_METHOD_CLOSE("TileSet::get_tile_count",rows*colums);
assert(rows * colums >= 0);
return rows*columns;
}
<commit_msg>Applies simple code technique<commit_after>/*!
* \file File tileSet.cpp
* \brief Implementation of the class TileSet
*
* Auxiliary documentation
* \sa tileSet.hpp
*/
#include <tileSet.hpp>
#include <assert.h>
/*!
@class TileSet
@brief This class provides the tile sets to the game
*/
//! A constructor.
/*!
* This is a constructor method of TileSet class
* \param width
* \brief A positive integer, that represents width of a tile
* \param height
* \brief A positive integer, that represents height of a tile
* \param file_path
* \brief A string, that represents path of the file with the tile set
*/
TileSet::TileSet(int width, int height, string file_path) {
LOG_METHOD_START("TileSet::TileSet");
LOG_VARIABLE("width",width);
assert(width >= 0);
LOG_VARIABLE("height",height);
assert(height >= 0);
LOG_VARIABLE("file_path",file_path);
assert(file_path != NULL)
LOG_MSG("This is a constructor method of TileSet class");
load(width, height, file_path);
LOG_METHOD_CLOSE("TileSet::TileSet","constructor");
}
//! A constructor.
/*!
This is a empty constructor method of TileSet class
*/
TileSet::TileSet() {
LOG_METHOD_START("TileSet::TileSet");
LOG_METHOD_CLOSE("TileSet::TileSet","constructor");
}
/*!
@fn void TileSet::render(unsigned int index,float position_x,float position_y, float extended_scale)
@brief Method that renders the tile set
@param index
@brief A unsigned integer
@param position_x
@brief A float
@param position_y
@brief A float
@param extended_scale
@brief A float
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void TileSet::render(unsigned int index,float position_x,float position_y, float extended_scale) {
LOG_METHOD_START("TileSet::render");
LOG_VARIABLE("index",index);
LOG_VARIABLE("position_x",position_x);
LOG_VARIABLE("position_y",position_y);
LOG_VARIABLE("extended_scale",extended_scale);
//! Checks if the number of tiles is bigger that the index
if ((int)index<(rows*columns)) {
//! var sprite_start_x
//!< A positive integer that represents the start of the sprite in x
int setclip_start_x = tile_width*(index%columns);
//! var sprite_start_y
//!< A positive integer that represents the start of the sprite in y
int setclip_start_y = tile_height*(index/columns);
tileSet.SetClip(setclip_start_x,setclip_start_y,tile_width,tile_height);
tileSet.render(position_x,position_y,0,extended_scale);
}
//! \warning else (do nothing)
LOG_METHOD_CLOSE("TileSet::render","void");
}
/*!
@fn void TileSet::load(int width, int height, string file_path)
@brief Method that loads the tile set from the file
@param width
@brief A positive integer, that represents width of a tile
@param height
@brief A positive integer, that represents height of a tile
@param file_path
@brief A string, that represents path of the file with the tile set
@return The execution of this method returns no value
*/
void TileSet::load(int width, int height, string file_path) {
LOG_METHOD_START("TileSet::load");
LOG_VARIABLE("width",width);
assert(width >= 0);
LOG_VARIABLE("height",height);
assert(height >= 0);
LOG_VARIABLE("file_path",file_path);
assert(file_path != NULL);
//! Attributes the value of the width and height of a tile
tile_width = width;
tile_height = height;
//! Opens the file with the tile set
tileSet.Open(file_path);
//! Defines the numbers of rows and columns of the tile set
rows = tileSet.GetHeight()/tile_height;
assert(rows >= 0);
columns = tileSet.GetWidth()/tile_width;
assert(columns >= 0);
LOG_METHOD_CLOSE("TileSet::load","void");
}
/*!
@fn int TileSet::get_width()
@brief A getter of the attribute tileWidth
@return A positive integer, that represents the width of a tile
*/
int TileSet::get_width() {
LOG_METHOD_START("TileSet::get_width");
LOG_METHOD_CLOSE("TileSet::get_width",tile_width);
assert(tile_width >= 0);
return tile_width;
}
/*!
@fn int TileSet::get_height()
@brief A getter of the attribute tileHeight
@return A positive integer, that represents the height of a tile
*/
int TileSet::get_height() {
LOG_METHOD_START("TileSet::get_height");
LOG_METHOD_CLOSE("TileSet::get_height",tile_height);
assert(tile_height >= 0);
return tile_height;
}
/*!
@fn int TileSet::get_tile_count()
@brief Method that returns the number of tiles in the tile set
@return A positive integer, that number of tiles in the tile set
*/
int TileSet::get_tile_count() {
LOG_METHOD_START("TileSet::get_tile_count");
LOG_METHOD_CLOSE("TileSet::get_tile_count",rows*colums);
assert(rows * colums >= 0);
return rows*columns;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2002-2009 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* XSEC
*
* c14n := tool to dump a XML file to the console after canonacalising it thru
* c14n
*
* $Id$
*
*/
//XSEC includes
//#include <Include/PlatformDefinitions.hpp>
//#include <cassert>
#include <memory.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/util/XMLException.hpp>
// XSEC
#include <xsec/canon/XSECC14n20010315.hpp>
#include <xsec/utils/XSECNameSpaceExpander.hpp>
#include <xsec/utils/XSECPlatformUtils.hpp>
XERCES_CPP_NAMESPACE_USE
using std::endl;
using std::cout;
using std::cerr;
void printUsage(void) {
cerr << "\nUsage: c14n [-n] [-id ID] <input file name>\n";
cerr << " -n = No comments\n";
cerr << " -id ID = References node to canonicalize by ID\n\n";
}
int main(int argc, char **argv) {
const char* id = NULL;
bool printComments = true; // By default print comments
// Check arguments
if (argc < 2) {
printUsage();
exit (1);
}
if (argc > 2) {
for (int i = 1; i < argc - 1; ++i) {
if (!strcmp(argv[i], "-n") || !strcmp(argv[i], "-N"))
printComments = false;
else if (!strcmp(argv[i], "-id") && argc > i + 1)
id = argv[++i];
else {
cerr << "Unknown option %s\n\n";
printUsage();
exit (1);
}
}
}
// Initialise the XML system
try {
XMLPlatformUtils::Initialize();
XSECPlatformUtils::Initialise();
}
catch (const XMLException &e) {
cerr << "Error during initialisation of Xerces" << endl;
cerr << "Error Message = : "
<< e.getMessage() << endl;
}
// Create and set up the parser
XercesDOMParser * parser = new XercesDOMParser;
parser->setDoNamespaces(true);
parser->setValidationScheme(XercesDOMParser::Val_Never);
parser->setDoSchema(false);
parser->setCreateEntityReferenceNodes(false);
// Now parse out file
bool errorsOccured = false;
xsecsize_t errorCount = 0;
try
{
parser->parse(argv[argc-1]);
errorCount = parser->getErrorCount();
if (errorCount > 0)
errorsOccured = true;
}
catch (const XMLException& e)
{
cerr << "An error occured during parsing\n Message: "
<< e.getMessage() << endl;
errorsOccured = true;
}
catch (const DOMException& e)
{
cerr << "A DOM error occured during parsing\n DOMException code: "
<< e.code << endl;
errorsOccured = true;
}
if (errorsOccured) {
cout << "Errors during parse" << endl;
exit (1);
}
/*
Now that we have the parsed file, get the DOM document and start looking at it
*/
DOMNode *subtree = NULL;
DOMDocument *theDOM = parser->getDocument();
if (id) {
XMLCh* temp = XMLString::transcode(id);
subtree = theDOM->getElementById(temp);
XMLString::release(&temp);
if (!subtree) {
cerr << "ID reference did not resolve" << endl;
exit(1);
}
}
// Create the canonicalizer
XSECC14n20010315* canon=NULL;
if (subtree)
canon = new XSECC14n20010315(theDOM, subtree);
else
canon = new XSECC14n20010315(theDOM);
canon->setCommentsProcessing(printComments);
canon->setUseNamespaceStack(true);
// canon->XPathSelectNodes("(/descendant-or-self::node() | /descendant-or-self::node()/attribute::* | /descendant-or-self::node()/namespace::*)[ self::ietf:e1 or (parent::ietf:e1 and not(self::text() or self::e2)) or count (id(\"E3\") | ancestor-or-self::node()) = count (ancestor-or-self::node())]");
char buffer[512];
xsecsize_t res = canon->outputBuffer((unsigned char *) buffer, 128);
while (res != 0) {
buffer[res] = '\0';
cout << buffer;
res = canon->outputBuffer((unsigned char *) buffer, 128);
}
cout << endl;
delete canon;
delete parser;
XSECPlatformUtils::Terminate();
XMLPlatformUtils::Terminate();
return 0;
}
<commit_msg>Add options for enabling 1.1 and exclusive c14n modes.<commit_after>/*
* Copyright 2002-2009 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* XSEC
*
* c14n := tool to dump a XML file to the console after canonacalising it thru
* c14n
*
* $Id$
*
*/
//XSEC includes
//#include <Include/PlatformDefinitions.hpp>
//#include <cassert>
#include <memory.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/util/XMLException.hpp>
// XSEC
#include <xsec/canon/XSECC14n20010315.hpp>
#include <xsec/utils/XSECNameSpaceExpander.hpp>
#include <xsec/utils/XSECPlatformUtils.hpp>
XERCES_CPP_NAMESPACE_USE
using std::endl;
using std::cout;
using std::cerr;
void printUsage(void) {
cerr << "\nUsage: c14n [-n] [-x] [-1.1] [-id ID] <input file name>\n";
cerr << " -n = No comments\n";
cerr << " -1.1 = Use c14n 1.1\n";
cerr << " -x = Use exclusive c14n\n";
cerr << " -id ID = References node to canonicalize by ID\n\n";
}
int main(int argc, char **argv) {
const char* id = NULL;
bool printComments = true;
bool exclusive = false;
bool inclusive11 = false;
// Check arguments
if (argc < 2) {
printUsage();
exit (1);
}
if (argc > 2) {
for (int i = 1; i < argc - 1; ++i) {
if (!strcmp(argv[i], "-n") || !strcmp(argv[i], "-N"))
printComments = false;
else if (!strcmp(argv[i], "-x") || !strcmp(argv[i], "-X"))
exclusive = true;
else if (!strcmp(argv[i], "-1.1"))
inclusive11 = true;
else if (!strcmp(argv[i], "-id") && argc > i + 1)
id = argv[++i];
else {
cerr << "Unknown option %s\n\n";
printUsage();
exit (1);
}
}
}
// Initialise the XML system
try {
XMLPlatformUtils::Initialize();
XSECPlatformUtils::Initialise();
}
catch (const XMLException &e) {
cerr << "Error during initialisation of Xerces" << endl;
cerr << "Error Message = : "
<< e.getMessage() << endl;
}
// Create and set up the parser
XercesDOMParser * parser = new XercesDOMParser;
parser->setDoNamespaces(true);
parser->setValidationScheme(XercesDOMParser::Val_Never);
parser->setDoSchema(false);
parser->setCreateEntityReferenceNodes(false);
// Now parse out file
bool errorsOccured = false;
xsecsize_t errorCount = 0;
try
{
parser->parse(argv[argc-1]);
errorCount = parser->getErrorCount();
if (errorCount > 0)
errorsOccured = true;
}
catch (const XMLException& e)
{
cerr << "An error occured during parsing\n Message: "
<< e.getMessage() << endl;
errorsOccured = true;
}
catch (const DOMException& e)
{
cerr << "A DOM error occured during parsing\n DOMException code: "
<< e.code << endl;
errorsOccured = true;
}
if (errorsOccured) {
cout << "Errors during parse" << endl;
exit (1);
}
/*
Now that we have the parsed file, get the DOM document and start looking at it
*/
DOMNode *subtree = NULL;
DOMDocument *theDOM = parser->getDocument();
if (id) {
XMLCh* temp = XMLString::transcode(id);
subtree = theDOM->getElementById(temp);
XMLString::release(&temp);
if (!subtree) {
cerr << "ID reference did not resolve" << endl;
exit(1);
}
}
// Create the canonicalizer
XSECC14n20010315* canon=NULL;
if (subtree)
canon = new XSECC14n20010315(theDOM, subtree);
else
canon = new XSECC14n20010315(theDOM);
canon->setCommentsProcessing(printComments);
canon->setUseNamespaceStack(true);
if (inclusive11)
canon->setInclusive11();
else if (exclusive)
canon->setExclusive();
// canon->XPathSelectNodes("(/descendant-or-self::node() | /descendant-or-self::node()/attribute::* | /descendant-or-self::node()/namespace::*)[ self::ietf:e1 or (parent::ietf:e1 and not(self::text() or self::e2)) or count (id(\"E3\") | ancestor-or-self::node()) = count (ancestor-or-self::node())]");
char buffer[512];
xsecsize_t res = canon->outputBuffer((unsigned char *) buffer, 128);
while (res != 0) {
buffer[res] = '\0';
cout << buffer;
res = canon->outputBuffer((unsigned char *) buffer, 128);
}
cout << endl;
delete canon;
delete parser;
XSECPlatformUtils::Terminate();
XMLPlatformUtils::Terminate();
return 0;
}
<|endoftext|>
|
<commit_before>#include "Compute.h"
#include "ImageLogger.h"
#include "VideoSource.h"
#include <iostream>
#include <opencv2/imgproc.hpp>
#define countof(v) (sizeof v / sizeof v[0])
static int redChannel = 2;
static int greenChannel = 1;
static int blueChannel = 0;
static int grayChannels = -1;
enum SegMethod {Hough, LSD, Contours};
void Compute::BackgroundLoop() {
const SegMethod seg = Contours;
const int HoughThreshold = cap->imageWidth * cap->imageHeight / 6500;
const double HoughMinLineLength = cap->imageHeight / 4.;
const double HoughMaxGap = cap->imageHeight / 50.;
const double HoughRho = 2.;
#if 1
const double CannyThreshold1 = 50.;
const double CannyThreshold2 = 100.;
const double HoughTheta = 0.05;
const int colorChannels = redChannel;
#else
const double CannyThreshold1 = 100.;
const double CannyThreshold2 = 200.;
const double HoughTheta = 0.02;
const int colorChannels = grayChannels;
#endif
cv::Ptr<cv::LineSegmentDetector> lsd;
if (seg == LSD) {
lsd = cv::createLineSegmentDetector();
}
cv::Mat gray(cap->imageHeight, cap->imageWidth, CV_8UC1), whiteLines;
for (int i = 0; ! cap->imagesCaptured.quitting; ++i) {
cv::Mat inp(cap->imagesCaptured.Dequeue());
if (! inp.empty()) {
if (log && i % 10 == 0 && log->imagesToLog.size < log->imagesToLog.Capacity()) {
log->imagesToLog.Enqueue(inp.clone());
}
OutputData out(cap->imageWidth, cap->imageHeight);
if (seg == Contours) {
cv::cvtColor(inp, whiteLines, cv::COLOR_BGR2HSV_FULL);
cv::inRange(whiteLines, cv::Scalar(124, 50, 50), cv::Scalar(174, 255, 255), gray);
typedef std::vector<std::vector<cv::Point> > ContoursT;
ContoursT contours;
cv::findContours(gray, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for (ContoursT::iterator i = contours.begin(); i != contours.end(); ++i) {
cv::approxPolyDP(*i, *i, 5., true);
}
out.image = inp;
cv::drawContours(out.image, contours, -1, cv::Scalar(0,0,255));
}
else {
if (colorChannels == grayChannels) {
cv::cvtColor(inp, gray, cv::COLOR_BGR2GRAY);
} else {
const int colorFromTo[] = {colorChannels,0};
cv::mixChannels(&inp, 1, &gray, 1, colorFromTo, countof(colorFromTo)/2);
}
if (seg == LSD) {
lsd->detect(gray, out.lines);
} else if (seg == Hough) {
cv::Canny(gray, whiteLines, CannyThreshold1, CannyThreshold2);
cv::HoughLinesP(whiteLines, out.lines, HoughRho, HoughTheta, HoughThreshold, HoughMinLineLength, HoughMaxGap);
}
static const int grayTo3Ch[] = {0,0, 0,1, 0,2};
cv::mixChannels(&gray, 1, &out.image, 1, grayTo3Ch, countof(grayTo3Ch)/2);
}
SwapOutputData(out);
}
}
}
static void* ComputeThread(void* compute) {
((Compute*)compute)->BackgroundLoop();
return 0;
}
void Compute::Start() {
pthread_create(&thread, NULL, ComputeThread, this);
}
void Compute::Stop() {
cap->imagesCaptured.Quit();
pthread_join(thread, NULL);
}
Compute::Compute(VideoSource* c, ImageLogger* lg): cap(c), log(lg) {
pthread_mutex_init(&dataMutex, NULL);
}
Compute::~Compute() {
pthread_mutex_destroy(&dataMutex);
}
void Compute::SwapOutputData(OutputData& data) {
OutputData x = data;
pthread_mutex_lock(&dataMutex);
data = outputData;
outputData = x;
pthread_mutex_unlock(&dataMutex);
}
<commit_msg>fit contour line<commit_after>#include "Compute.h"
#include "ImageLogger.h"
#include "VideoSource.h"
#include <iostream>
#include <opencv2/imgproc.hpp>
#define countof(v) (sizeof v / sizeof v[0])
static int redChannel = 2;
static int greenChannel = 1;
static int blueChannel = 0;
static int grayChannels = -1;
enum SegMethod {Hough, LSD, Contours};
typedef std::vector<cv::Point> Polygon;
typedef std::vector<Polygon> ContoursT;
void Compute::BackgroundLoop() {
const SegMethod seg = Contours;
const int HoughThreshold = cap->imageWidth * cap->imageHeight / 6500;
const double HoughMinLineLength = cap->imageHeight / 4.;
const double HoughMaxGap = cap->imageHeight / 50.;
const double HoughRho = 2.;
#if 1
const double CannyThreshold1 = 50.;
const double CannyThreshold2 = 100.;
const double HoughTheta = 0.05;
const int colorChannels = redChannel;
#else
const double CannyThreshold1 = 100.;
const double CannyThreshold2 = 200.;
const double HoughTheta = 0.02;
const int colorChannels = grayChannels;
#endif
cv::Ptr<cv::LineSegmentDetector> lsd;
if (seg == LSD) {
lsd = cv::createLineSegmentDetector();
}
cv::Mat gray(cap->imageHeight, cap->imageWidth, CV_8UC1), whiteLines;
cv::Vec4f line;
for (int i = 0; ! cap->imagesCaptured.quitting; ++i) {
cv::Mat inp(cap->imagesCaptured.Dequeue());
if (! inp.empty()) {
if (log && i % 10 == 0 && log->imagesToLog.size < log->imagesToLog.Capacity()) {
log->imagesToLog.Enqueue(inp.clone());
}
OutputData out(cap->imageWidth, cap->imageHeight);
if (seg == Contours) {
cv::cvtColor(inp, whiteLines, cv::COLOR_BGR2HSV_FULL);
cv::inRange(whiteLines, cv::Scalar(124, 50, 50), cv::Scalar(174, 255, 255), gray);
ContoursT contours;
cv::findContours(gray, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for (ContoursT::iterator p = contours.begin(); p != contours.end(); ++p) {
Polygon& poly = *p;
//cv::approxPolyDP(poly, poly, 5., true);
cv::fitLine(poly, line, cv::DIST_L2, 0., HoughRho, HoughTheta);
cv::Point p1(-9999*line(0) + line(2), -9999*line(1) + line(3)),
p2( 9999*line(0) + line(2), 9999*line(1) + line(3));
cv::clipLine(cv::boundingRect(poly), p1, p2);
out.lines.push_back(cv::Vec4i(p1.x, p1.y, p2.x, p2.y));
}
out.image = inp;
cv::drawContours(out.image, contours, -1, cv::Scalar(0,255,0));
}
else {
if (colorChannels == grayChannels) {
cv::cvtColor(inp, gray, cv::COLOR_BGR2GRAY);
} else {
const int colorFromTo[] = {colorChannels,0};
cv::mixChannels(&inp, 1, &gray, 1, colorFromTo, countof(colorFromTo)/2);
}
if (seg == LSD) {
lsd->detect(gray, out.lines);
} else if (seg == Hough) {
cv::Canny(gray, whiteLines, CannyThreshold1, CannyThreshold2);
cv::HoughLinesP(whiteLines, out.lines, HoughRho, HoughTheta, HoughThreshold, HoughMinLineLength, HoughMaxGap);
}
static const int grayTo3Ch[] = {0,0, 0,1, 0,2};
cv::mixChannels(&gray, 1, &out.image, 1, grayTo3Ch, countof(grayTo3Ch)/2);
}
SwapOutputData(out);
}
}
}
static void* ComputeThread(void* compute) {
((Compute*)compute)->BackgroundLoop();
return 0;
}
void Compute::Start() {
pthread_create(&thread, NULL, ComputeThread, this);
}
void Compute::Stop() {
cap->imagesCaptured.Quit();
pthread_join(thread, NULL);
}
Compute::Compute(VideoSource* c, ImageLogger* lg): cap(c), log(lg) {
pthread_mutex_init(&dataMutex, NULL);
}
Compute::~Compute() {
pthread_mutex_destroy(&dataMutex);
}
void Compute::SwapOutputData(OutputData& data) {
OutputData x = data;
pthread_mutex_lock(&dataMutex);
data = outputData;
outputData = x;
pthread_mutex_unlock(&dataMutex);
}
<|endoftext|>
|
<commit_before>/**
* @file thread.cpp
* @brief Brief description of file.
*
*/
#include <angort/angort.h>
#include <pthread.h>
#include <unistd.h>
#include "../wrappers.h"
using namespace angort;
// thread hook object Angort uses to do... stuff.
class MyThreadHookObject : public ThreadHookObject {
// a big global lock
pthread_mutex_t mutex;
public:
MyThreadHookObject(){
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex,&attr);
}
~MyThreadHookObject(){
pthread_mutex_destroy(&mutex);
}
// single global mutex, nestable
virtual void globalLock(){
pthread_mutex_lock(&mutex);
}
virtual void globalUnlock(){
pthread_mutex_unlock(&mutex);
}
};
static MyThreadHookObject hook;
class MsgBuffer {
static const int size=8;
Value msgs[size];
int wr,rd;
int length;
pthread_mutex_t mutex,mutex2;
pthread_cond_t cond,cond2;
bool isEmpty(){
return length==0;
}
bool isFull(){
return length==size;
}
void _read(Value *v){
if(isEmpty())printf("NO MESSAGE\n");
v->copy(msgs+rd);
rd++;
rd %= size;
length--;
}
bool _write(Value *v){
if(isFull())return false;
wr++;
wr %= size;
msgs[wr].copy(v);
length++;
return true;
}
public:
MsgBuffer(){
wr=size-1;
rd=0;
length=0;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex2,NULL);
pthread_cond_init(&cond2,NULL);
}
~MsgBuffer(){
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex2);
pthread_cond_destroy(&cond2);
}
// wait for a message, blocking if we have to
void waitAndRead(Value *dest){
pthread_mutex_lock(&mutex);
while(isEmpty())
pthread_cond_wait(&cond,&mutex);
_read(dest);
pthread_cond_signal(&cond2);
// printf("%d SIGNALLING.\n",snark);
pthread_mutex_unlock(&mutex);
// printf("%d read ok\n",snark);
}
// write a message, return false if no room
bool writeNoWait(Value *v){
bool ok;
pthread_mutex_lock(&mutex);
ok = _write(v);
if(ok)pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
return ok;
}
// write a message, blocking if we're full.
void writeWait(Value *v){
// printf("%d write \n",snark);
pthread_mutex_lock(&mutex2);
while(isFull()){
// printf("%d FULL.\n",snark);
pthread_cond_wait(&cond2,&mutex2);
}
pthread_mutex_lock(&mutex);
_write(v);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
// printf("%d write ok\n",snark);
pthread_mutex_unlock(&mutex2);
}
};
void *_threadfunc(void *);
namespace angort {
class Thread : public GarbageCollected {
// our run environment
Runtime *runtime;
public:
Value func;
Value retval; // the returned value
pthread_t thread;
MsgBuffer msgs;
int id;
bool isRunning(){
return runtime != NULL;
}
Thread(Angort *ang,Value *v,Value *arg) : GarbageCollected(){
incRefCt(); // make sure we don't get deleted until complete
func.copy(v);
runtime = new Runtime(ang,"<thread>");
id = runtime->id;
runtime->thread = this;
runtime->pushval()->copy(arg);
// printf("Creating thread at %p/%s\n",this,func.t->name);
pthread_create(&thread,NULL,_threadfunc,this);
}
~Thread(){
// printf("Thread destroyed at %p\n",this);
}
void run(){
const StringBuffer& buf = func.toString();
try {
runtime->runValue(&func);
} catch(Exception e){
hook.globalLock();
printf("Exception in thread %d\n",runtime->id);
hook.globalUnlock();
}
hook.globalLock();
// pop the last value off the thread runtime
// and copy it into the return value, if there is one.
if(!runtime->stack.isempty()){
retval.copy(runtime->stack.popptr());
}
delete runtime;
runtime = NULL;
// decrement refct, and delete this if it's zero. This is kind
// of OK, here - it's the last thing that happens.
if(decRefCt())delete this;
hook.globalUnlock();
}
};
}
void *_threadfunc(void *p){
Thread *t = (Thread *)p;
// printf("starting thread at %p/%s\n",t,t->func.t->name);
t->run();
// printf("Thread func terminated OK?\n");
return NULL;
}
%name thread
%shared
// crude hack - this is the message buffer for the default thread.
static MsgBuffer defaultMsgs;
class ThreadType : public GCType {
public:
ThreadType(){
add("thread","THRD");
}
Thread *get(Value *v){
if(v->t!=this)
throw RUNT(EX_TYPE,"not a thread");
return (Thread *)(v->v.gc);
}
// create a new thread!
void set(Value *v,Angort *ang,Value *func,Value *pass){
if(func->t != Types::tCode)
throw RUNT(EX_TYPE,"not a codeblock (can't be a closure)");
hook.globalLock();
v->clr();
v->t=this;
v->v.gc = new Thread(ang,func,pass);
incRef(v);
hook.globalUnlock();
}
// set a value to a thread
void set(Value *v, Thread *t){
hook.globalLock();
v->clr();
v->t = this;
v->v.gc = t;
incRef(v);
hook.globalUnlock();
}
};
static ThreadType tThread;
// mutex wrapper class
struct Mutex {
pthread_mutex_t m;
Mutex(){
// make the mutex recursive
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&m,&attr);
}
~Mutex(){
pthread_mutex_destroy(&m);
}
};
// the wrapper has a wrapper type..
static WrapperType<pthread_mutex_t> tMutex("MUTX");
%type mutex tMutex pthread_mutex_t
%type thread tThread Thread
// words
%wordargs create vc (arg func --) start a new thread
{
Value v,p;
p.copy(p0);
v.copy(p1);
tThread.set(a->pushval(),a->ang,&v,&p);
}
%word glock (--) global lock
{
hook.globalLock();
}
%word unglock (--) global unlock
{
hook.globalUnlock();
}
%wordargs join l (threadlist --) wait for threads to complete
{
ArrayListIterator<Value> iter(p0);
// check types first
for(iter.first();!iter.isDone();iter.next()){
Value *p = iter.current();
if(p->t != &tThread)
throw RUNT(EX_TYPE,"expected threads only in thread list");
}
// then join each in turn.
for(iter.first();!iter.isDone();iter.next()){
Value *p = iter.current();
pthread_join(tThread.get(p)->thread,NULL);
}
}
%word mutex (-- mutex) create a recursive mutex
{
pthread_mutex_t *v = new pthread_mutex_t();
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(v,&attr);
tMutex.set(a->pushval(),v);
}
%wordargs lock A|mutex (mutex -- ) lock a mutex
{
pthread_mutex_lock(p0);
}
%wordargs unlock A|mutex (mutex -- ) unlock a mutex
{
pthread_mutex_unlock(p0);
}
%wordargs retval A|thread (thread -- val) get return of a finished thread
One way of communicating with a thread is to send data into it with
the function parameter, and receive the result (after the thread has
completed) using thread$retval. If the thread is still running an
exception will be thrown. Use thread$join to wait for thread completion.
{
hook.globalLock();
if(p0->isRunning()){
hook.globalUnlock();
throw RUNT("ex$threadrunning","thread is still running");
}
a->pushval()->copy(&p0->retval);
hook.globalUnlock();
}
%wordargs sendnoblock vv|thread (msg thread|none -- bool) send a message value to a thread
Send a message to a thread. The default thread is indicated by "none".
Will return a boolean indicating the send was successful.
{
MsgBuffer *b;
if(p1->isNone())
b = &defaultMsgs;
else {
Thread *t = tThread.get(p1);
b = &t->msgs;
}
a->pushInt(b->writeNoWait(p0)?1:0);
}
%wordargs send vv|thread (msg thread|none --) send a message value to a thread
Send a message to a thread. The default thread is indicated by "none".
Will wait if the buffer is full.
{
MsgBuffer *b;
if(p1->isNone())
b = &defaultMsgs;
else {
Thread *t = tThread.get(p1);
b = &t->msgs;
}
b->writeWait(p0);
}
%word waitrecv (--- msg) blocking message read
Wait for a message to arrive on this thread and return it.
{
MsgBuffer *b;
if(a->thread)
b = &a->thread->msgs;
else
b = &defaultMsgs;
Value v;
b->waitAndRead(&v);
a->pushval()->copy(&v);
}
%word cur (-- thread) return current thread
{
tThread.set(a->pushval(),a->thread);
}
%wordargs id A|thread (thread -- id) get ID from thread
{
a->pushInt(p0->id);
}
%init
{
fprintf(stderr,"Initialising THREAD plugin, %s %s\n",__DATE__,__TIME__);
fprintf(stderr,
"Todo: \n"
"-make sure threads die correctly on end of function,\n"
"-signal handling in both Angort and here\n"
"-thread kill and join (list of threads)\n"
"-thread data stored in Runtime so we can get thread\n"
"-finer grained lock object\n"
);
Angort::setThreadHookObject(&hook);
}
<commit_msg>thread arguments/returns and messages are cloned (but not deeply). This avoids GC screwups, or should.<commit_after>/**
* @file thread.cpp
* @brief Brief description of file.
*
*/
#include <angort/angort.h>
#include <pthread.h>
#include "../wrappers.h"
using namespace angort;
// thread hook object Angort uses to do... stuff.
class MyThreadHookObject : public ThreadHookObject {
// a big global lock
pthread_mutex_t mutex;
public:
MyThreadHookObject(){
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex,&attr);
}
~MyThreadHookObject(){
pthread_mutex_destroy(&mutex);
}
// single global mutex, nestable
virtual void globalLock(){
pthread_mutex_lock(&mutex);
}
virtual void globalUnlock(){
pthread_mutex_unlock(&mutex);
}
};
static MyThreadHookObject hook;
class MsgBuffer {
static const int size=8;
Value msgs[size];
int wr,rd;
int length;
pthread_mutex_t mutex,mutex2;
pthread_cond_t cond,cond2;
bool isEmpty(){
return length==0;
}
bool isFull(){
return length==size;
}
void _read(Value *v){
if(isEmpty())printf("NO MESSAGE\n");
msgs[rd].t->clone(v,msgs+rd);
// v->copy(msgs+rd);
rd++;
rd %= size;
length--;
}
bool _write(Value *v){
if(isFull())return false;
wr++;
wr %= size;
// msgs[wr].copy(v);
v->t->clone(msgs+wr,v);
length++;
return true;
}
public:
MsgBuffer(){
wr=size-1;
rd=0;
length=0;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex2,NULL);
pthread_cond_init(&cond2,NULL);
}
~MsgBuffer(){
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex2);
pthread_cond_destroy(&cond2);
}
// wait for a message, blocking if we have to
void waitAndRead(Value *dest){
pthread_mutex_lock(&mutex);
while(isEmpty())
pthread_cond_wait(&cond,&mutex);
_read(dest);
pthread_cond_signal(&cond2);
// printf("%d SIGNALLING.\n",snark);
pthread_mutex_unlock(&mutex);
// printf("%d read ok\n",snark);
}
// write a message, return false if no room
bool writeNoWait(Value *v){
bool ok;
pthread_mutex_lock(&mutex);
ok = _write(v);
if(ok)pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
return ok;
}
// write a message, blocking if we're full.
void writeWait(Value *v){
// printf("%d write \n",snark);
pthread_mutex_lock(&mutex2);
while(isFull()){
// printf("%d FULL.\n",snark);
pthread_cond_wait(&cond2,&mutex2);
}
pthread_mutex_lock(&mutex);
_write(v);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
// printf("%d write ok\n",snark);
pthread_mutex_unlock(&mutex2);
}
};
void *_threadfunc(void *);
namespace angort {
class Thread : public GarbageCollected {
// our run environment
Runtime *runtime;
public:
Value func;
Value retval; // the returned value
Value arg;
pthread_t thread;
MsgBuffer msgs;
int id;
bool isRunning(){
return runtime != NULL;
}
Thread(Angort *ang,Value *v,Value *_arg) : GarbageCollected(){
incRefCt(); // make sure we don't get deleted until complete
func.copy(v);
_arg->t->clone(&arg,_arg); // clone the argument
// printf("%p %p\n",arg.v.gc,_arg->v.gc);
runtime = new Runtime(ang,"<thread>");
id = runtime->id;
runtime->thread = this;
runtime->pushval()->copy(&arg);
pthread_create(&thread,NULL,_threadfunc,this);
// printf("Created thread %d[%lu] at %p/%s runtime at %p\n",id,thread,this,func.t->name,runtime);
}
~Thread(){
if(runtime)throw WTF;
// printf("Thread %d destroyed at %p\n",id,this);
}
void run(){
try {
runtime->runValue(&func);
} catch(Exception e){
hook.globalLock();
printf("Exception in thread %d\n",runtime->id);
hook.globalUnlock();
}
hook.globalLock();
// pop the last value off the thread runtime
// and copy it into the return value, if there is one.
if(!runtime->stack.isempty()){
retval.copy(runtime->stack.popptr());
}
// printf("Deleting runtime of thread %d at %p\n",id,runtime);
delete runtime;
// printf("Deleting OK\n");
runtime = NULL;
// decrement refct, and delete this if it's zero. This is kind
// of OK, here - it's the last thing that happens.
if(decRefCt()){
delete this;
}
func.clr();
hook.globalUnlock();
}
};
}
void *_threadfunc(void *p){
Thread *t = (Thread *)p;
// printf("starting thread at %p/%s\n",t,t->func.t->name);
t->run();
// printf("Thread func terminated OK?\n");
return NULL;
}
%name thread
%shared
// crude hack - this is the message buffer for the default thread.
static MsgBuffer defaultMsgs;
class ThreadType : public GCType {
public:
ThreadType(){
add("thread","THRD");
}
Thread *get(Value *v){
if(v->t!=this)
throw RUNT(EX_TYPE,"not a thread");
return (Thread *)(v->v.gc);
}
// create a new thread!
void set(Value *v,Angort *ang,Value *func,Value *pass){
if(func->t != Types::tCode)
throw RUNT(EX_TYPE,"not a codeblock (can't be a closure)");
hook.globalLock();
v->clr();
v->t=this;
v->v.gc = new Thread(ang,func,pass);
incRef(v);
hook.globalUnlock();
}
// set a value to a thread
void set(Value *v, Thread *t){
hook.globalLock();
v->clr();
v->t = this;
v->v.gc = t;
incRef(v);
hook.globalUnlock();
}
};
static ThreadType tThread;
// mutex wrapper class
struct Mutex {
pthread_mutex_t m;
Mutex(){
// make the mutex recursive
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&m,&attr);
}
~Mutex(){
pthread_mutex_destroy(&m);
}
};
// the wrapper has a wrapper type..
static WrapperType<pthread_mutex_t> tMutex("MUTX");
%type mutex tMutex pthread_mutex_t
%type thread tThread Thread
// words
%wordargs create vc (arg func --) start a new thread
{
Value v,p;
p.copy(p0);
v.copy(p1);
tThread.set(a->pushval(),a->ang,&v,&p);
}
%word glock (--) global lock
{
hook.globalLock();
}
%word unglock (--) global unlock
{
hook.globalUnlock();
}
%wordargs join l (threadlist --) wait for threads to complete
{
ArrayListIterator<Value> iter(p0);
// check types first
for(iter.first();!iter.isDone();iter.next()){
Value *p = iter.current();
if(p->t != &tThread)
throw RUNT(EX_TYPE,"expected threads only in thread list");
}
// then join each in turn.
for(iter.first();!iter.isDone();iter.next()){
Value *p = iter.current();
pthread_join(tThread.get(p)->thread,NULL);
}
}
%word mutex (-- mutex) create a recursive mutex
{
pthread_mutex_t *v = new pthread_mutex_t();
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(v,&attr);
tMutex.set(a->pushval(),v);
}
%wordargs lock A|mutex (mutex -- ) lock a mutex
{
pthread_mutex_lock(p0);
}
%wordargs unlock A|mutex (mutex -- ) unlock a mutex
{
pthread_mutex_unlock(p0);
}
%wordargs retval A|thread (thread -- val) get return of a finished thread
One way of communicating with a thread is to send data into it with
the function parameter, and receive the result (after the thread has
completed) using thread$retval. If the thread is still running an
exception will be thrown. Use thread$join to wait for thread completion.
{
hook.globalLock();
if(p0->isRunning()){
hook.globalUnlock();
throw RUNT("ex$threadrunning","thread is still running");
}
a->pushval()->copy(&p0->retval);
hook.globalUnlock();
}
%wordargs sendnoblock vv|thread (msg thread|none -- bool) send a message value to a thread
Send a message to a thread. The default thread is indicated by "none".
Will return a boolean indicating the send was successful.
{
MsgBuffer *b;
if(p1->isNone())
b = &defaultMsgs;
else {
Thread *t = tThread.get(p1);
b = &t->msgs;
}
a->pushInt(b->writeNoWait(p0)?1:0);
}
%wordargs send vv|thread (msg thread|none --) send a message value to a thread
Send a message to a thread. The default thread is indicated by "none".
Will wait if the buffer is full.
{
MsgBuffer *b;
if(p1->isNone())
b = &defaultMsgs;
else {
Thread *t = tThread.get(p1);
b = &t->msgs;
}
b->writeWait(p0);
}
%word waitrecv (--- msg) blocking message read
Wait for a message to arrive on this thread and return it.
{
MsgBuffer *b;
if(a->thread)
b = &a->thread->msgs;
else
b = &defaultMsgs;
Value v;
b->waitAndRead(&v);
a->pushval()->copy(&v);
}
%word cur (-- thread|none) return current thread or none for main thread
{
if(a->thread)
tThread.set(a->pushval(),a->thread);
else
a->pushNone();
}
%wordargs id v|thread (none|thread -- id) get ID from thread, -1 for none
{
if(p0->isNone())
a->pushNone();
else {
Thread *t = tThread.get(p0);
a->pushInt(t->id);
}
}
%init
{
fprintf(stderr,"Initialising THREAD plugin, %s %s\n",__DATE__,__TIME__);
fprintf(stderr,
"Todo: \n"
"-make sure threads die correctly on end of function,\n"
"-signal handling in both Angort and here\n"
"-thread kill and join (list of threads)\n"
"-thread data stored in Runtime so we can get thread\n"
"-finer grained lock object\n"
);
Angort::setThreadHookObject(&hook);
}
<|endoftext|>
|
<commit_before>#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;
#include "QTRSensors.h"
#include <wiringPi.h>
class WrapperFuncs{
public:
static boost::shared_ptr<QTRSensorsRC> init(
list _pins, unsigned int timeout, unsigned char emitterPin){
wiringPiSetup();
unsigned char __pins[QTRSensors::QTR_MAX_SENSORS];
for(int i=0; i<len(_pins); i++)
__pins[i]=extract<int>(_pins[i]);
return boost::shared_ptr<QTRSensorsRC>(
new QTRSensorsRC(__pins, (unsigned char)len(_pins), timeout, emitterPin)
);
}
static unsigned int readLine(QTRSensorsRC &qtrrc, list sensorValues){
unsigned int _sv[QTRSensors::QTR_MAX_SENSORS];
for(int i=0; i<len(sensorValues); i++)
_sv[i]=extract<unsigned int>(sensorValues[i]);
int result=qtrrc.readLine(_sv);
for(int i=0; i<len(sensorValues); i++)
sensorValues[i]=_sv[i];
return result;
}
static void read(QTRSensorsRC &qtrrc, list sensorValues, unsigned char readMode=QTR_EMITTERS_ON){
unsigned int _sv[QTRSensors::QTR_MAX_SENSORS];
for(int i=0; i<len(sensorValues); i++)
_sv[i]=extract<unsigned int>(sensorValues[i]);
qtrrc.read(_sv, readMode);
for(int i=0; i<len(sensorValues); i++)
sensorValues[i]=_sv[i];
}
static void readCalibrated(QTRSensorsRC &qtrrc, list sensorValues, unsigned char readMode=QTR_EMITTERS_ON){
unsigned int _sv[QTRSensors::QTR_MAX_SENSORS];
for(int i=0; i<len(sensorValues); i++)
_sv[i]=extract<unsigned int>(sensorValues[i]);
qtrrc.readCalibrated(_sv, readMode);
for(int i=0; i<len(sensorValues); i++)
sensorValues[i]=_sv[i];
}
};
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
calibrate_overloads, QTRSensors::calibrate, 0, 1
)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
read_overloads, WrapperFuncs::read, 1, 2
)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
readCalibrated_overloads, WrapperFuncs::readCalibrated, 1, 2
)
BOOST_PYTHON_MODULE(QTRSensors){
class_<QTRSensors>
("QTRSensors", no_init)
// 'Normal' methods
.def("calibrate", &QTRSensors::calibrate, calibrate_overloads())
.def("emittersOff", &QTRSensors::emittersOff)
.def("emittersOn", &QTRSensors::emittersOn)
.def("resetCalibration", &QTRSensors::resetCalibration)
;
class_<QTRSensorsRC, bases<QTRSensors>, boost::shared_ptr<QTRSensorsRC> >
("QTRSensorsRC", no_init)
.def("__init__", make_constructor(WrapperFuncs::init))
// Wrapped methods
.def("read", &WrapperFuncs::read, read_overloads())
.def("readCalibrated", &WrapperFuncs::readCalibrated, readCalibrated_overloads())
.def("readLine", &WrapperFuncs::readLine)
;
}
<commit_msg>Bug fixes<commit_after>#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;
#include "QTRSensors.h"
#include <wiringPi.h>
class WrapperFuncs{
public:
static boost::shared_ptr<QTRSensorsRC> init(
list _pins, unsigned int timeout, unsigned char emitterPin){
wiringPiSetup();
unsigned char __pins[QTRSensors::QTR_MAX_SENSORS];
for(int i=0; i<len(_pins); i++)
__pins[i]=extract<int>(_pins[i]);
return boost::shared_ptr<QTRSensorsRC>(
new QTRSensorsRC(__pins, (unsigned char)len(_pins), timeout, emitterPin)
);
}
static unsigned int readLine(QTRSensorsRC &qtrrc, list sensorValues){
unsigned int _sv[QTRSensors::QTR_MAX_SENSORS];
for(int i=0; i<len(sensorValues); i++)
_sv[i]=extract<unsigned int>(sensorValues[i]);
int result=qtrrc.readLine(_sv);
for(int i=0; i<len(sensorValues); i++)
sensorValues[i]=_sv[i];
return result;
}
static void read(QTRSensorsRC &qtrrc, list sensorValues, unsigned char readMode=QTRSensors::QTR_EMITTERS_ON){
unsigned int _sv[QTRSensors::QTR_MAX_SENSORS];
for(int i=0; i<len(sensorValues); i++)
_sv[i]=extract<unsigned int>(sensorValues[i]);
qtrrc.read(_sv, readMode);
for(int i=0; i<len(sensorValues); i++)
sensorValues[i]=_sv[i];
}
static void readCalibrated(QTRSensorsRC &qtrrc, list sensorValues, unsigned char readMode=QTRSensors::QTR_EMITTERS_ON){
unsigned int _sv[QTRSensors::QTR_MAX_SENSORS];
for(int i=0; i<len(sensorValues); i++)
_sv[i]=extract<unsigned int>(sensorValues[i]);
qtrrc.readCalibrated(_sv, readMode);
for(int i=0; i<len(sensorValues); i++)
sensorValues[i]=_sv[i];
}
};
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
calibrate_overloads, QTRSensors::calibrate, 0, 1
)
BOOST_PYTHON_MODULE(QTRSensors){
class_<QTRSensors>
("QTRSensors", no_init)
// 'Normal' methods
.def("calibrate", &QTRSensors::calibrate, calibrate_overloads())
.def("emittersOff", &QTRSensors::emittersOff)
.def("emittersOn", &QTRSensors::emittersOn)
.def("resetCalibration", &QTRSensors::resetCalibration)
;
class_<QTRSensorsRC, bases<QTRSensors>, boost::shared_ptr<QTRSensorsRC> >
("QTRSensorsRC", no_init)
.def("__init__", make_constructor(WrapperFuncs::init))
// Wrapped methods
.def("read", &WrapperFuncs::read)
.def("readCalibrated", &WrapperFuncs::readCalibrated)
.def("readLine", &WrapperFuncs::readLine)
;
}
<|endoftext|>
|
<commit_before>#include "StableHeaders.h"
#include "UICanvas.h"
#include "Profiler.h"
#ifndef Q_WS_WIN
#include <QX11Info>
#endif
#include <QCoreApplication>
#include <QPicture>
#include <QGraphicsSceneEvent>
#include <QUuid>
#include <QWidget>
#include <QGraphicsProxyWidget>
#include <Ogre.h>
#include <OgreHardwarePixelBuffer.h>
#include <OgreTexture.h>
#include <OgreMaterial.h>
#include <OgreTextAreaOverlayElement.h>
#include <OgreFontManager.h>
#include <OgrePanelOverlayElement.h>
#include <OgreTextureUnitState.h>
#include "MemoryLeakCheck.h"
namespace QtUI
{
UICanvas::UICanvas(): overlay_(0),
container_(0),
dirty_(true),
surfaceName_(""),
mode_(External),
id_(QUuid::createUuid().toString()),
widgets_(0),
locked_(false)
{
setScene(new QGraphicsScene);
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
QObject::connect(this->scene(),SIGNAL(changed(const QList<QRectF>&)),this,SLOT(Dirty()));
}
UICanvas::UICanvas(Mode mode, const QSize& parentWindowSize): overlay_(0),
container_(0),
dirty_(true),
renderWindowSize_(parentWindowSize),
mode_(mode),
id_(QUuid::createUuid().toString()),
widgets_(0)
{
setScene(new QGraphicsScene);
if (mode_ == External)
{
// Deal canvas as normal QWidget.
// Currently do nothing
}
else if (mode_ == Internal)
{
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
QSize size = this->size();
CreateOgreResources(size.width(), size.height());
QObject::connect(this->scene(),SIGNAL(changed(const QList<QRectF>&)),this,SLOT(Dirty()));
}
}
UICanvas::~UICanvas()
{
for (int i = scene_widgets_.size(); i--;)
{
QGraphicsProxyWidget* widget = scene_widgets_.takeAt(i);
delete widget;
}
if (mode_ != External)
{
Ogre::TextureManager::getSingleton().remove(surfaceName_.toStdString().c_str());
QString surfaceMaterial = QString("mat") + id_;
Ogre::MaterialManager::getSingleton().remove(surfaceMaterial.toStdString().c_str());
QString containerName = QString("con") + id_;
Ogre::OverlayManager::getSingleton().destroyOverlayElement(containerName.toStdString().c_str());
QString overlayName = QString("over") + id_;
Ogre::OverlayManager::getSingleton().destroy(overlayName.toStdString().c_str());
}
container_ = 0;
overlay_ = 0;
QGraphicsScene* scene = this->scene();
delete scene;
scene = 0;
}
void UICanvas::AddWidget(QWidget* widget)
{
switch(mode_)
{
case Internal:
{
QGraphicsScene* scene = this->scene();
scene_widgets_.append(scene->addWidget(widget));
++widgets_;
break;
}
case External:
{
///todo Here lies a desing flaw do it better, this does not work.
if ( widgets_ != 0)
{
// Possible memory LEAK !!!
QGraphicsScene* scene = this->scene();
if(widgets_ == 1)
{
QWidget* viewport = this->viewport();
scene_widgets_.append(scene->addWidget(viewport));
scene_widgets_.append(scene->addWidget(widget));
setViewport(new QWidget);
}
else
scene_widgets_.append(scene->addWidget(widget));
}
else
setViewport(widget);
++widgets_;
break;
}
default:
break;
}
}
void UICanvas::SetPosition(int x, int y)
{
switch (mode_)
{
case External:
{
move(x,y);
break;
}
case Internal:
{
float relX = x/double(renderWindowSize_.width()), relY = y/double(renderWindowSize_.height());
container_->setPosition(relX, relY);
emit RequestArrange();
dirty_ = true;
break;
}
default:
break;
}
}
QPoint UICanvas::MapToCanvas(int x, int y)
{
if ( mode_ != External)
{
x -= container_->getLeft() * renderWindowSize_.width();
y -= container_->getTop() * renderWindowSize_.height();
}
return QPoint(x,y);
}
QPointF UICanvas::GetPosition() const
{
QPointF position;
switch(mode_)
{
case External:
{
position = pos();
break;
}
case Internal:
{
double width = container_->getLeft();
double height = container_->getTop();
// Calculate position in render window coordinate frame.
position.rx() = width * renderWindowSize_.width();
position.ry() = height * renderWindowSize_.height();
break;
}
default:
break;
}
return position;
}
void UICanvas::SetCanvasSize(int width, int height)
{
move(0, 0);
resize(width, height);
if ( mode_ != External)
{
CreateOgreResources(width, height);
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
container_->setDimensions(relWidth, relHeight);
}
// Repaint canvas.
dirty_ = true;
RenderSceneToOgreSurface();
}
void UICanvas::ResizeOgreTexture(int width, int height)
{
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
texture->freeInternalResources();
texture->setWidth(width);
texture->setHeight(height);
texture->createInternalResources();
}
void UICanvas::CreateOgreResources(int width, int height)
{
// If we've already created the resources, just resize the texture to a new size.
if ( surfaceName_ != "")
{
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
if (width == texture->getWidth() && height == texture->getHeight())
return;
ResizeOgreTexture(width, height);
assert(overlay_);
assert(container_);
return;
}
QString overlayName = QString("over") + id_;
overlay_ = Ogre::OverlayManager::getSingleton().create(overlayName.toStdString().c_str());
QString containerName = QString("con") + id_;
container_ = static_cast<Ogre::OverlayContainer*>(Ogre::OverlayManager::getSingleton()
.createOverlayElement("Panel", containerName.toStdString().c_str()));
// This is not done so currently -- tuoki
// Make the overlay cover 100% of the render window. Note that the UI surface will be
// rendered pixel perfect without stretching only if the GraphicsView surface dimension
// matches the render window size.
//container_->setDimensions(1.0,1.0);
container_->setPosition(0,0);
// Add container in default overlay
overlay_->add2D(container_);
///\todo Tell Ogre not to generate a mipmap chain. This texture only needs to have only one
/// mip level.
surfaceName_ = QString("tex") + id_;
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(surfaceName_.toStdString().c_str(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, width, height, 0,
Ogre::PF_A8R8G8B8, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
QString surfaceMaterial = QString("mat") + id_;
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(surfaceMaterial.toStdString().c_str(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::TextureUnitState *state = material->getTechnique(0)->getPass(0)->createTextureUnitState();
material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBF_SOURCE_ALPHA, Ogre::SBF_ONE_MINUS_SOURCE_ALPHA);
state->setTextureName(surfaceName_.toStdString().c_str());
// Generate pixel perfect texture.
float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
container_->setDimensions(relWidth, relHeight);
container_->setMaterialName(surfaceMaterial .toStdString().c_str());
container_->show();
container_->setEnabled(true);
container_->setColour(Ogre::ColourValue(1,1,1,1));
overlay_->show();
}
void UICanvas::Show()
{
if ( mode_ != External)
{
QList<QGraphicsProxyWidget* >::iterator iter = scene_widgets_.begin();
for (; iter != scene_widgets_.end(); ++iter)
(*iter)->show();
container_->show();
overlay_->show();
dirty_ = true;
RenderSceneToOgreSurface();
}
else
show();
}
void UICanvas::Hide()
{
if ( mode_ != External)
{
QList<QGraphicsProxyWidget* >::iterator iter = scene_widgets_.begin();
for (; iter != scene_widgets_.end(); ++iter)
(*iter)->hide();
container_->hide();
overlay_->hide();
dirty_ = true;
RenderSceneToOgreSurface();
}
else
hide();
}
void UICanvas::drawBackground(QPainter *painter, const QRectF &rect)
{
QBrush black(Qt::transparent);
painter->fillRect(rect, black);
}
void UICanvas::RenderSceneToOgreSurface()
{
// Render if and only if scene is dirty.
if (!dirty_ || mode_ == External)
return;
PROFILE(RenderSceneToOgre);
// We draw the GraphicsView area to an offscreen QPixmap and blit that onto the Ogre GPU surface.
QPixmap pixmap(this->size());
{
PROFILE(FillEmpty);
pixmap.fill(Qt::transparent);
}
assert(pixmap.hasAlphaChannel());
QImage img = pixmap.toImage();
QPainter painter(&img);
QRectF destRect(0, 0, pixmap.width(), pixmap.height());
QRect sourceRect(0, 0, pixmap.width(), pixmap.height());
{
PROFILE(RenderUI);
this->render(&painter, destRect, sourceRect);
}
assert(img.hasAlphaChannel());
///\todo Can optimize an extra blit away if we paint directly onto the GPU surface.
Ogre::Box dimensions(0,0, img.rect().width(), img.rect().height());
Ogre::PixelBox pixel_box(dimensions, Ogre::PF_A8R8G8B8, (void*)img.bits());
{
PROFILE(UIToOgreBlit);
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
texture->getBuffer()->blitFromMemory(pixel_box);
}
dirty_ = false;
}
void UICanvas::Render()
{
RenderSceneToOgreSurface();
}
}
<commit_msg>Fix small bug fix (now canvases are not automagically locked). <commit_after>#include "StableHeaders.h"
#include "UICanvas.h"
#include "Profiler.h"
#ifndef Q_WS_WIN
#include <QX11Info>
#endif
#include <QCoreApplication>
#include <QPicture>
#include <QGraphicsSceneEvent>
#include <QUuid>
#include <QWidget>
#include <QGraphicsProxyWidget>
#include <Ogre.h>
#include <OgreHardwarePixelBuffer.h>
#include <OgreTexture.h>
#include <OgreMaterial.h>
#include <OgreTextAreaOverlayElement.h>
#include <OgreFontManager.h>
#include <OgrePanelOverlayElement.h>
#include <OgreTextureUnitState.h>
#include "MemoryLeakCheck.h"
namespace QtUI
{
UICanvas::UICanvas(): overlay_(0),
container_(0),
dirty_(true),
surfaceName_(""),
mode_(External),
id_(QUuid::createUuid().toString()),
widgets_(0),
locked_(false)
{
setScene(new QGraphicsScene);
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
QObject::connect(this->scene(),SIGNAL(changed(const QList<QRectF>&)),this,SLOT(Dirty()));
}
UICanvas::UICanvas(Mode mode, const QSize& parentWindowSize): overlay_(0),
container_(0),
dirty_(true),
renderWindowSize_(parentWindowSize),
mode_(mode),
id_(QUuid::createUuid().toString()),
widgets_(0),
locked_(false)
{
setScene(new QGraphicsScene);
if (mode_ == External)
{
// Deal canvas as normal QWidget.
// Currently do nothing
}
else if (mode_ == Internal)
{
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
QSize size = this->size();
CreateOgreResources(size.width(), size.height());
QObject::connect(this->scene(),SIGNAL(changed(const QList<QRectF>&)),this,SLOT(Dirty()));
}
}
UICanvas::~UICanvas()
{
for (int i = scene_widgets_.size(); i--;)
{
QGraphicsProxyWidget* widget = scene_widgets_.takeAt(i);
delete widget;
}
if (mode_ != External)
{
Ogre::TextureManager::getSingleton().remove(surfaceName_.toStdString().c_str());
QString surfaceMaterial = QString("mat") + id_;
Ogre::MaterialManager::getSingleton().remove(surfaceMaterial.toStdString().c_str());
QString containerName = QString("con") + id_;
Ogre::OverlayManager::getSingleton().destroyOverlayElement(containerName.toStdString().c_str());
QString overlayName = QString("over") + id_;
Ogre::OverlayManager::getSingleton().destroy(overlayName.toStdString().c_str());
}
container_ = 0;
overlay_ = 0;
QGraphicsScene* scene = this->scene();
delete scene;
scene = 0;
}
void UICanvas::AddWidget(QWidget* widget)
{
switch(mode_)
{
case Internal:
{
QGraphicsScene* scene = this->scene();
scene_widgets_.append(scene->addWidget(widget));
++widgets_;
break;
}
case External:
{
///todo Here lies a desing flaw do it better, this does not work.
if ( widgets_ != 0)
{
// Possible memory LEAK !!!
QGraphicsScene* scene = this->scene();
if(widgets_ == 1)
{
QWidget* viewport = this->viewport();
scene_widgets_.append(scene->addWidget(viewport));
scene_widgets_.append(scene->addWidget(widget));
setViewport(new QWidget);
}
else
scene_widgets_.append(scene->addWidget(widget));
}
else
setViewport(widget);
++widgets_;
break;
}
default:
break;
}
}
void UICanvas::SetPosition(int x, int y)
{
switch (mode_)
{
case External:
{
move(x,y);
break;
}
case Internal:
{
float relX = x/double(renderWindowSize_.width()), relY = y/double(renderWindowSize_.height());
container_->setPosition(relX, relY);
emit RequestArrange();
dirty_ = true;
break;
}
default:
break;
}
}
QPoint UICanvas::MapToCanvas(int x, int y)
{
if ( mode_ != External)
{
x -= container_->getLeft() * renderWindowSize_.width();
y -= container_->getTop() * renderWindowSize_.height();
}
return QPoint(x,y);
}
QPointF UICanvas::GetPosition() const
{
QPointF position;
switch(mode_)
{
case External:
{
position = pos();
break;
}
case Internal:
{
double width = container_->getLeft();
double height = container_->getTop();
// Calculate position in render window coordinate frame.
position.rx() = width * renderWindowSize_.width();
position.ry() = height * renderWindowSize_.height();
break;
}
default:
break;
}
return position;
}
void UICanvas::SetCanvasSize(int width, int height)
{
move(0, 0);
resize(width, height);
if ( mode_ != External)
{
CreateOgreResources(width, height);
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
container_->setDimensions(relWidth, relHeight);
}
// Repaint canvas.
dirty_ = true;
RenderSceneToOgreSurface();
}
void UICanvas::ResizeOgreTexture(int width, int height)
{
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
texture->freeInternalResources();
texture->setWidth(width);
texture->setHeight(height);
texture->createInternalResources();
}
void UICanvas::CreateOgreResources(int width, int height)
{
// If we've already created the resources, just resize the texture to a new size.
if ( surfaceName_ != "")
{
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
if (width == texture->getWidth() && height == texture->getHeight())
return;
ResizeOgreTexture(width, height);
assert(overlay_);
assert(container_);
return;
}
QString overlayName = QString("over") + id_;
overlay_ = Ogre::OverlayManager::getSingleton().create(overlayName.toStdString().c_str());
QString containerName = QString("con") + id_;
container_ = static_cast<Ogre::OverlayContainer*>(Ogre::OverlayManager::getSingleton()
.createOverlayElement("Panel", containerName.toStdString().c_str()));
// This is not done so currently -- tuoki
// Make the overlay cover 100% of the render window. Note that the UI surface will be
// rendered pixel perfect without stretching only if the GraphicsView surface dimension
// matches the render window size.
//container_->setDimensions(1.0,1.0);
container_->setPosition(0,0);
// Add container in default overlay
overlay_->add2D(container_);
///\todo Tell Ogre not to generate a mipmap chain. This texture only needs to have only one
/// mip level.
surfaceName_ = QString("tex") + id_;
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(surfaceName_.toStdString().c_str(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, width, height, 0,
Ogre::PF_A8R8G8B8, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
QString surfaceMaterial = QString("mat") + id_;
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(surfaceMaterial.toStdString().c_str(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::TextureUnitState *state = material->getTechnique(0)->getPass(0)->createTextureUnitState();
material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBF_SOURCE_ALPHA, Ogre::SBF_ONE_MINUS_SOURCE_ALPHA);
state->setTextureName(surfaceName_.toStdString().c_str());
// Generate pixel perfect texture.
float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
container_->setDimensions(relWidth, relHeight);
container_->setMaterialName(surfaceMaterial .toStdString().c_str());
container_->show();
container_->setEnabled(true);
container_->setColour(Ogre::ColourValue(1,1,1,1));
overlay_->show();
}
void UICanvas::Show()
{
if ( mode_ != External)
{
QList<QGraphicsProxyWidget* >::iterator iter = scene_widgets_.begin();
for (; iter != scene_widgets_.end(); ++iter)
(*iter)->show();
container_->show();
overlay_->show();
dirty_ = true;
RenderSceneToOgreSurface();
}
else
show();
}
void UICanvas::Hide()
{
if ( mode_ != External)
{
QList<QGraphicsProxyWidget* >::iterator iter = scene_widgets_.begin();
for (; iter != scene_widgets_.end(); ++iter)
(*iter)->hide();
container_->hide();
overlay_->hide();
dirty_ = true;
RenderSceneToOgreSurface();
}
else
hide();
}
void UICanvas::drawBackground(QPainter *painter, const QRectF &rect)
{
QBrush black(Qt::transparent);
painter->fillRect(rect, black);
}
void UICanvas::RenderSceneToOgreSurface()
{
// Render if and only if scene is dirty.
if (!dirty_ || mode_ == External)
return;
PROFILE(RenderSceneToOgre);
// We draw the GraphicsView area to an offscreen QPixmap and blit that onto the Ogre GPU surface.
QPixmap pixmap(this->size());
{
PROFILE(FillEmpty);
pixmap.fill(Qt::transparent);
}
assert(pixmap.hasAlphaChannel());
QImage img = pixmap.toImage();
QPainter painter(&img);
QRectF destRect(0, 0, pixmap.width(), pixmap.height());
QRect sourceRect(0, 0, pixmap.width(), pixmap.height());
{
PROFILE(RenderUI);
this->render(&painter, destRect, sourceRect);
}
assert(img.hasAlphaChannel());
///\todo Can optimize an extra blit away if we paint directly onto the GPU surface.
Ogre::Box dimensions(0,0, img.rect().width(), img.rect().height());
Ogre::PixelBox pixel_box(dimensions, Ogre::PF_A8R8G8B8, (void*)img.bits());
{
PROFILE(UIToOgreBlit);
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
texture->getBuffer()->blitFromMemory(pixel_box);
}
dirty_ = false;
}
void UICanvas::Render()
{
RenderSceneToOgreSurface();
}
}
<|endoftext|>
|
<commit_before>#include <Scenes/IntegrationTestScene.hpp>
namespace asc {
IntegrationTestScene::IntegrationTestScene(void)
: Scene("IntegrationTestScene") {
m_AddedCallbackId = m_EntityManager.OnEntityAdded.registerCallback(std::bind(
&EntityRepresentationManager::handleRegisterEntity,
&m_EntityRepresentationManager,
std::placeholders::_1));
m_RemovedCallbackId = m_EntityManager.OnEntityRemoved.registerCallback(std::bind(
&EntityRepresentationManager::handleUnregisterEntity,
&m_EntityRepresentationManager,
std::placeholders::_1));
}
IntegrationTestScene::~IntegrationTestScene(void) {
m_EntityManager.OnEntityAdded.unregisterCallback(m_RemovedCallbackId);
m_EntityManager.OnEntityRemoved.unregisterCallback(m_RemovedCallbackId);
}
void IntegrationTestScene::update(float _delta) {
m_EntityManager.updateEntities(_delta);
m_EntityRepresentationManager.update(_delta);
}
bool IntegrationTestScene::handleEvent(const sf::Event& _event) {
if (_event.type == sf::Event::KeyPressed) {
if (_event.key.code == sf::Keyboard::Left) {
Application::getCamera().move(sf::Vector2f(-20.0f, +0.0f));
return true;
}
if (_event.key.code == sf::Keyboard::Right) {
Application::getCamera().move(sf::Vector2f(+20.0f, +0.0f));
return true;
}
if (_event.key.code == sf::Keyboard::Up) {
Application::getCamera().move(sf::Vector2f(+0.0f, +20.0f));
return true;
}
if (_event.key.code == sf::Keyboard::Down) {
Application::getCamera().move(sf::Vector2f(+0.0f, -20.0f));
return true;
}
if (_event.key.code == sf::Keyboard::F1) {
Application::getCamera().setPosition(sf::Vector2f());
Application::getCamera().setZoom(1.0f);
return true;
}
}
if (_event.type == sf::Event::MouseWheelMoved) {
if (_event.mouseWheel.delta > 0) {
Application::getCamera().zoom(std::pow(1.1f, std::fabsf(static_cast<float>(_event.mouseWheel.delta))));
return true;
}
if (_event.mouseWheel.delta < 0) {
Application::getCamera().zoom(std::pow(1.0f / 1.1f, std::fabsf(static_cast<float>(_event.mouseWheel.delta))));
return true;
}
}
return false;
}
void IntegrationTestScene::draw(sf::RenderTarget& _target, sf::RenderStates _states) const {
sf::CircleShape c(32.0f);
c.setOrigin(32.0f, 32.0f);
_target.draw(c, _states);
m_EntityRepresentationManager.draw(_target, _states);
}
}<commit_msg>add cmath header<commit_after>#include <Scenes/IntegrationTestScene.hpp>
#include <cmath>
namespace asc {
IntegrationTestScene::IntegrationTestScene(void)
: Scene("IntegrationTestScene") {
m_AddedCallbackId = m_EntityManager.OnEntityAdded.registerCallback(std::bind(
&EntityRepresentationManager::handleRegisterEntity,
&m_EntityRepresentationManager,
std::placeholders::_1));
m_RemovedCallbackId = m_EntityManager.OnEntityRemoved.registerCallback(std::bind(
&EntityRepresentationManager::handleUnregisterEntity,
&m_EntityRepresentationManager,
std::placeholders::_1));
}
IntegrationTestScene::~IntegrationTestScene(void) {
m_EntityManager.OnEntityAdded.unregisterCallback(m_RemovedCallbackId);
m_EntityManager.OnEntityRemoved.unregisterCallback(m_RemovedCallbackId);
}
void IntegrationTestScene::update(float _delta) {
m_EntityManager.updateEntities(_delta);
m_EntityRepresentationManager.update(_delta);
}
bool IntegrationTestScene::handleEvent(const sf::Event& _event) {
if (_event.type == sf::Event::KeyPressed) {
if (_event.key.code == sf::Keyboard::Left) {
Application::getCamera().move(sf::Vector2f(-20.0f, +0.0f));
return true;
}
if (_event.key.code == sf::Keyboard::Right) {
Application::getCamera().move(sf::Vector2f(+20.0f, +0.0f));
return true;
}
if (_event.key.code == sf::Keyboard::Up) {
Application::getCamera().move(sf::Vector2f(+0.0f, +20.0f));
return true;
}
if (_event.key.code == sf::Keyboard::Down) {
Application::getCamera().move(sf::Vector2f(+0.0f, -20.0f));
return true;
}
if (_event.key.code == sf::Keyboard::F1) {
Application::getCamera().setPosition(sf::Vector2f());
Application::getCamera().setZoom(1.0f);
return true;
}
}
if (_event.type == sf::Event::MouseWheelMoved) {
if (_event.mouseWheel.delta > 0) {
Application::getCamera().zoom(std::pow(1.1f, std::fabsf(static_cast<float>(_event.mouseWheel.delta))));
return true;
}
if (_event.mouseWheel.delta < 0) {
Application::getCamera().zoom(std::pow(1.0f / 1.1f, std::fabsf(static_cast<float>(_event.mouseWheel.delta))));
return true;
}
}
return false;
}
void IntegrationTestScene::draw(sf::RenderTarget& _target, sf::RenderStates _states) const {
sf::CircleShape c(32.0f);
c.setOrigin(32.0f, 32.0f);
_target.draw(c, _states);
m_EntityRepresentationManager.draw(_target, _states);
}
}<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//TESTED_COMPONENT=src/documentgallery
#include <qdocumentgallery.h>
#include <QtTest/QtTest>
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QGalleryProperty::Attributes)
class tst_QDocumentGallery : public QObject
{
Q_OBJECT
private Q_SLOTS:
void isRequestSupported();
void itemTypeProperties_data();
void itemTypeProperties();
void propertyAttributes_data();
void propertyAttributes();
private:
QDocumentGallery gallery;
};
void tst_QDocumentGallery::isRequestSupported()
{
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
const bool platformSupported = true;
#else
const bool platformSupported = false;
#endif
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::QueryRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::ItemRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::TypeRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::RequestType(1000)), false);
}
void tst_QDocumentGallery::itemTypeProperties_data()
{
QTest::addColumn<QString>("itemType");
QTest::addColumn<QStringList>("propertyNames");
QTest::newRow("null item type") << QString() << QStringList();
QTest::newRow("non-existent item type") << QString::fromLatin1("Hello") << QStringList();
const QStringList fileProperties = QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::copyright
<< QDocumentGallery::fileName
<< QDocumentGallery::path
<< QDocumentGallery::filePath
<< QDocumentGallery::url
<< QDocumentGallery::fileSize
<< QDocumentGallery::language
<< QDocumentGallery::lastAccessed
<< QDocumentGallery::lastModified
<< QDocumentGallery::mimeType;
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::url
<< QDocumentGallery::fileName
<< QDocumentGallery::filePath
<< QDocumentGallery::fileSize
<< QDocumentGallery::lastModified
<< QDocumentGallery::title
<< QDocumentGallery::mimeType
<< QDocumentGallery::author
<< QDocumentGallery::copyright
<< QDocumentGallery::description
<< QDocumentGallery::comments
<< QDocumentGallery::rating
#endif
;
QTest::newRow("File") << QString(QDocumentGallery::File) << (QStringList(fileProperties)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::author
<< QDocumentGallery::description
<< QDocumentGallery::keywords
<< QDocumentGallery::rating
<< QDocumentGallery::subject
<< QDocumentGallery::title
#endif
);
QTest::newRow("Audio") << QString(QDocumentGallery::Audio) << (QStringList(fileProperties)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::albumArtist
<< QDocumentGallery::albumTitle
<< QDocumentGallery::artist
<< QDocumentGallery::audioBitRate
<< QDocumentGallery::audioCodec
<< QDocumentGallery::channelCount
<< QDocumentGallery::description
<< QDocumentGallery::discNumber
<< QDocumentGallery::duration
<< QDocumentGallery::genre
<< QDocumentGallery::lastPlayed
<< QDocumentGallery::lyrics
<< QDocumentGallery::performer
<< QDocumentGallery::playCount
<< QDocumentGallery::sampleRate
<< QDocumentGallery::title
<< QDocumentGallery::trackNumber
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::audioCodec
<< QDocumentGallery::audioBitRate
<< QDocumentGallery::playCount
<< QDocumentGallery::sampleRate
<< QDocumentGallery::albumTitle
<< QDocumentGallery::trackNumber
<< QDocumentGallery::albumArtist
<< QDocumentGallery::artist
<< QDocumentGallery::composer
<< QDocumentGallery::genre
#endif
);
QTest::newRow("Album") << QString(QDocumentGallery::Album) << (QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::albumArtist
<< QDocumentGallery::albumTitle
<< QDocumentGallery::artist
<< QDocumentGallery::duration
<< QDocumentGallery::title
<< QDocumentGallery::trackCount
#endif
);
QTest::newRow("PhotoAlbum") << QString(QDocumentGallery::PhotoAlbum) << (QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::title
<< QDocumentGallery::trackCount
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::url
<< QDocumentGallery::fileSize
<< QDocumentGallery::lastModified
<< QDocumentGallery::title
<< QDocumentGallery::mimeType
#endif
);
#if defined (Q_OS_SYMBIAN)
QTest::newRow("Image") << QString(QDocumentGallery::Image) << (QStringList(fileProperties)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::playCount
<< QDocumentGallery::width
<< QDocumentGallery::height
<< QDocumentGallery::orientation
<< QDocumentGallery::dateTaken
<< QDocumentGallery::cameraManufacturer
<< QDocumentGallery::cameraModel
<< QDocumentGallery::exposureProgram
<< QDocumentGallery::exposureTime
<< QDocumentGallery::fNumber
<< QDocumentGallery::flashEnabled
<< QDocumentGallery::focalLength
<< QDocumentGallery::meteringMode
<< QDocumentGallery::whiteBalance
);
QTest::newRow("Video") << QString(QDocumentGallery::Video) << (QStringList(fileProperties)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::videoBitRate
<< QDocumentGallery::playCount
<< QDocumentGallery::width
<< QDocumentGallery::height
<< QDocumentGallery::language
<< QDocumentGallery::frameRate
<< QDocumentGallery::resumePosition
);
#endif
}
void tst_QDocumentGallery::itemTypeProperties()
{
QFETCH(QString, itemType);
QFETCH(QStringList, propertyNames);
QStringList galleryPropertyNames = gallery.itemTypePropertyNames(itemType);
propertyNames.sort();
galleryPropertyNames.sort();
QCOMPARE(galleryPropertyNames, propertyNames);
}
void tst_QDocumentGallery::propertyAttributes_data()
{
QTest::addColumn<QString>("itemType");
QTest::addColumn<QString>("propertyName");
QTest::addColumn<QGalleryProperty::Attributes>("propertyAttributes");
QTest::newRow("Null itemType, propertyName")
<< QString()
<< QString()
<< QGalleryProperty::Attributes();
QTest::newRow("Null itemType, invalid propertyName")
<< QString()
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("Null itemType, valid propertyName")
<< QString()
<< QString(QDocumentGallery::fileName)
<< QGalleryProperty::Attributes();
QTest::newRow("Invalid itemType, invalid propertyName")
<< QString::fromLatin1("Hello")
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("Invalid itemType, valid propertyName")
<< QString::fromLatin1("Hello")
<< QString(QDocumentGallery::fileName)
<< QGalleryProperty::Attributes();
QTest::newRow("Valid itemType, invalid propertyName")
<< QString(QDocumentGallery::File)
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("File.fileName")
<< QString(QDocumentGallery::File)
<< QString(QDocumentGallery::fileName)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("File.filePath")
<< QString(QDocumentGallery::File)
<< QString(QDocumentGallery::filePath)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead | QGalleryProperty::CanFilter);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("Audio.albumTitle")
<< QString(QDocumentGallery::Audio)
<< QString(QDocumentGallery::albumTitle)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanWrite
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("Album.duration")
<< QString(QDocumentGallery::Album)
<< QString(QDocumentGallery::duration)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QGalleryProperty::Attributes(QGalleryProperty::CanRead);
#else
#ifndef Q_OS_SYMBIAN
<< QGalleryProperty::Attributes();
#else
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanWrite
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#endif
#endif
}
void tst_QDocumentGallery::propertyAttributes()
{
QFETCH(QString, itemType);
QFETCH(QString, propertyName);
QFETCH(QGalleryProperty::Attributes, propertyAttributes);
QCOMPARE(int(gallery.propertyAttributes(propertyName, itemType)), int(propertyAttributes));
}
#include "tst_qdocumentgallery.moc"
QTEST_MAIN(tst_QDocumentGallery)
<commit_msg>Symbian: fix qdocumentgallery test to pass.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//TESTED_COMPONENT=src/documentgallery
#include <qdocumentgallery.h>
#include <QtTest/QtTest>
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QGalleryProperty::Attributes)
class tst_QDocumentGallery : public QObject
{
Q_OBJECT
private Q_SLOTS:
void isRequestSupported();
void itemTypeProperties_data();
void itemTypeProperties();
void propertyAttributes_data();
void propertyAttributes();
private:
QDocumentGallery gallery;
};
void tst_QDocumentGallery::isRequestSupported()
{
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
const bool platformSupported = true;
#else
const bool platformSupported = false;
#endif
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::QueryRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::ItemRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::TypeRequest), platformSupported);
QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::RequestType(1000)), false);
}
void tst_QDocumentGallery::itemTypeProperties_data()
{
QTest::addColumn<QString>("itemType");
QTest::addColumn<QStringList>("propertyNames");
QTest::newRow("null item type") << QString() << QStringList();
QTest::newRow("non-existent item type") << QString::fromLatin1("Hello") << QStringList();
const QStringList fileProperties = QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::copyright
<< QDocumentGallery::fileName
<< QDocumentGallery::path
<< QDocumentGallery::filePath
<< QDocumentGallery::url
<< QDocumentGallery::fileSize
<< QDocumentGallery::language
<< QDocumentGallery::lastAccessed
<< QDocumentGallery::lastModified
<< QDocumentGallery::mimeType;
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::url
<< QDocumentGallery::fileName
<< QDocumentGallery::filePath
<< QDocumentGallery::fileSize
<< QDocumentGallery::lastModified
<< QDocumentGallery::title
<< QDocumentGallery::mimeType
<< QDocumentGallery::author
<< QDocumentGallery::copyright
<< QDocumentGallery::description
<< QDocumentGallery::comments
<< QDocumentGallery::rating
#endif
;
QTest::newRow("File") << QString(QDocumentGallery::File) << (QStringList(fileProperties)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::author
<< QDocumentGallery::description
<< QDocumentGallery::keywords
<< QDocumentGallery::rating
<< QDocumentGallery::subject
<< QDocumentGallery::title
#endif
);
QTest::newRow("Audio") << QString(QDocumentGallery::Audio) << (QStringList(fileProperties)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::albumArtist
<< QDocumentGallery::albumTitle
<< QDocumentGallery::artist
<< QDocumentGallery::audioBitRate
<< QDocumentGallery::audioCodec
<< QDocumentGallery::channelCount
<< QDocumentGallery::description
<< QDocumentGallery::discNumber
<< QDocumentGallery::duration
<< QDocumentGallery::genre
<< QDocumentGallery::lastPlayed
<< QDocumentGallery::lyrics
<< QDocumentGallery::performer
<< QDocumentGallery::playCount
<< QDocumentGallery::sampleRate
<< QDocumentGallery::title
<< QDocumentGallery::trackNumber
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::audioCodec
<< QDocumentGallery::audioBitRate
<< QDocumentGallery::playCount
<< QDocumentGallery::sampleRate
<< QDocumentGallery::albumTitle
<< QDocumentGallery::trackNumber
<< QDocumentGallery::albumArtist
<< QDocumentGallery::artist
<< QDocumentGallery::composer
<< QDocumentGallery::genre
#endif
);
QTest::newRow("Album") << QString(QDocumentGallery::Album) << (QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::albumArtist
<< QDocumentGallery::albumTitle
<< QDocumentGallery::artist
<< QDocumentGallery::duration
<< QDocumentGallery::title
<< QDocumentGallery::trackCount
#endif
);
QTest::newRow("PhotoAlbum") << QString(QDocumentGallery::PhotoAlbum) << (QStringList()
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QDocumentGallery::title
<< QDocumentGallery::trackCount
#elif defined (Q_OS_SYMBIAN)
<< QDocumentGallery::url
<< QDocumentGallery::fileSize
<< QDocumentGallery::lastModified
<< QDocumentGallery::title
<< QDocumentGallery::mimeType
#endif
);
#if defined (Q_OS_SYMBIAN)
QTest::newRow("Image") << QString(QDocumentGallery::Image) << (QStringList(fileProperties)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::playCount
<< QDocumentGallery::width
<< QDocumentGallery::height
<< QDocumentGallery::orientation
<< QDocumentGallery::dateTaken
<< QDocumentGallery::cameraManufacturer
<< QDocumentGallery::cameraModel
<< QDocumentGallery::exposureProgram
<< QDocumentGallery::exposureTime
<< QDocumentGallery::fNumber
<< QDocumentGallery::flashEnabled
<< QDocumentGallery::focalLength
<< QDocumentGallery::meteringMode
<< QDocumentGallery::whiteBalance
);
QTest::newRow("Video") << QString(QDocumentGallery::Video) << (QStringList(fileProperties)
<< QDocumentGallery::duration
<< QDocumentGallery::performer
<< QDocumentGallery::videoBitRate
<< QDocumentGallery::playCount
<< QDocumentGallery::width
<< QDocumentGallery::height
<< QDocumentGallery::language
<< QDocumentGallery::frameRate
<< QDocumentGallery::resumePosition
);
#endif
}
void tst_QDocumentGallery::itemTypeProperties()
{
QFETCH(QString, itemType);
QFETCH(QStringList, propertyNames);
QStringList galleryPropertyNames = gallery.itemTypePropertyNames(itemType);
propertyNames.sort();
galleryPropertyNames.sort();
QCOMPARE(galleryPropertyNames, propertyNames);
}
void tst_QDocumentGallery::propertyAttributes_data()
{
QTest::addColumn<QString>("itemType");
QTest::addColumn<QString>("propertyName");
QTest::addColumn<QGalleryProperty::Attributes>("propertyAttributes");
QTest::newRow("Null itemType, propertyName")
<< QString()
<< QString()
<< QGalleryProperty::Attributes();
QTest::newRow("Null itemType, invalid propertyName")
<< QString()
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("Null itemType, valid propertyName")
<< QString()
<< QString(QDocumentGallery::fileName)
<< QGalleryProperty::Attributes();
QTest::newRow("Invalid itemType, invalid propertyName")
<< QString::fromLatin1("Hello")
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("Invalid itemType, valid propertyName")
<< QString::fromLatin1("Hello")
<< QString(QDocumentGallery::fileName)
<< QGalleryProperty::Attributes();
QTest::newRow("Valid itemType, invalid propertyName")
<< QString(QDocumentGallery::File)
<< QString::fromLatin1("Goodbye")
<< QGalleryProperty::Attributes();
QTest::newRow("File.fileName")
<< QString(QDocumentGallery::File)
<< QString(QDocumentGallery::fileName)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("File.filePath")
<< QString(QDocumentGallery::File)
<< QString(QDocumentGallery::filePath)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead | QGalleryProperty::CanFilter);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("Audio.albumTitle")
<< QString(QDocumentGallery::Audio)
<< QString(QDocumentGallery::albumTitle)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) || defined (Q_OS_SYMBIAN)
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanWrite
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#else
<< QGalleryProperty::Attributes();
#endif
QTest::newRow("Album.duration")
<< QString(QDocumentGallery::Album)
<< QString(QDocumentGallery::duration)
#if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS)
<< QGalleryProperty::Attributes(QGalleryProperty::CanRead);
#else
#ifdef Q_OS_SYMBIAN
<< QGalleryProperty::Attributes();
#else
<< (QGalleryProperty::CanRead
| QGalleryProperty::CanWrite
| QGalleryProperty::CanFilter
| QGalleryProperty::CanSort);
#endif
#endif
}
void tst_QDocumentGallery::propertyAttributes()
{
QFETCH(QString, itemType);
QFETCH(QString, propertyName);
QFETCH(QGalleryProperty::Attributes, propertyAttributes);
QCOMPARE(int(gallery.propertyAttributes(propertyName, itemType)), int(propertyAttributes));
}
#include "tst_qdocumentgallery.moc"
QTEST_MAIN(tst_QDocumentGallery)
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qgeopositioninfo.h>
#include <QMetaType>
#include <QObject>
#include <QDebug>
#include <QTest>
#include <float.h>
Q_DECLARE_METATYPE(QGeoCoordinate)
Q_DECLARE_METATYPE(QGeoPositionInfo)
Q_DECLARE_METATYPE(QGeoPositionInfo::Property)
QByteArray tst_qgeopositioninfo_debug;
void tst_qgeopositioninfo_messageHandler(QtMsgType type, const char *msg)
{
switch(type) {
case QtDebugMsg :
tst_qgeopositioninfo_debug = QByteArray(msg);
break;
default:
break;
}
}
QList<qreal> tst_qgeopositioninfo_qrealTestValues()
{
QList<qreal> values;
if (qreal(DBL_MIN) == DBL_MIN)
values << DBL_MIN;
values << FLT_MIN;
values << -1.0 << 0.0 << 1.0;
values << FLT_MAX;
if (qreal(DBL_MAX) == DBL_MAX)
values << DBL_MAX;
return values;
}
QList<QGeoPositionInfo::Property> tst_qgeopositioninfo_getProperties()
{
QList<QGeoPositionInfo::Property> properties;
properties << QGeoPositionInfo::Heading
<< QGeoPositionInfo::GroundSpeed
<< QGeoPositionInfo::VerticalSpeed
<< QGeoPositionInfo::MagneticVariation
<< QGeoPositionInfo::HorizontalAccuracy
<< QGeoPositionInfo::VerticalAccuracy;
return properties;
}
class tst_QGeoPositionInfo : public QObject
{
Q_OBJECT
private:
QGeoPositionInfo infoWithProperty(QGeoPositionInfo::Property property, qreal value)
{
QGeoPositionInfo info;
info.setProperty(property, value);
return info;
}
void addTestData_info()
{
QTest::addColumn<QGeoPositionInfo>("info");
QTest::newRow("invalid") << QGeoPositionInfo();
QTest::newRow("coord") << QGeoPositionInfo(QGeoCoordinate(-27.3422,150.2342), QDateTime());
QTest::newRow("datetime") << QGeoPositionInfo(QGeoCoordinate(), QDateTime::currentDateTime());
QList<QGeoPositionInfo::Property> properties = tst_qgeopositioninfo_getProperties();
QList<qreal> values = tst_qgeopositioninfo_qrealTestValues();
for (int i=0; i<properties.count(); i++) {
QTest::newRow(qPrintable(QString("Property %1 = %2").arg(properties[i]).arg(values[i])))
<< infoWithProperty(properties[i], values[i]);
}
}
private slots:
void constructor()
{
QGeoPositionInfo info;
QVERIFY(!info.isValid());
QVERIFY(!info.coordinate().isValid());
QVERIFY(info.dateTime().isNull());
}
void constructor_coord_dateTime()
{
QFETCH(QGeoCoordinate, coord);
QFETCH(QDateTime, dateTime);
QFETCH(bool, valid);
QGeoPositionInfo info(coord, dateTime);
QCOMPARE(info.coordinate(), coord);
QCOMPARE(info.dateTime(), dateTime);
QCOMPARE(info.isValid(), valid);
}
void constructor_coord_dateTime_data()
{
QTest::addColumn<QGeoCoordinate>("coord");
QTest::addColumn<QDateTime>("dateTime");
QTest::addColumn<bool>("valid");
QTest::newRow("both null") << QGeoCoordinate() << QDateTime() << false;
QTest::newRow("both valid") << QGeoCoordinate(1,1) << QDateTime::currentDateTime() << true;
QTest::newRow("valid coord") << QGeoCoordinate(1,1) << QDateTime() << false;
QTest::newRow("valid datetime") << QGeoCoordinate() << QDateTime::currentDateTime() << false;
QTest::newRow("valid time but not date == invalid")
<< QGeoCoordinate() << QDateTime(QDate(), QTime::currentTime()) << false;
QTest::newRow("valid date but not time == valid due to QDateTime constructor")
<< QGeoCoordinate() << QDateTime(QDate::currentDate(), QTime()) << false;
}
void constructor_copy()
{
QFETCH(QGeoPositionInfo, info);
QCOMPARE(QGeoPositionInfo(info), info);
}
void constructor_copy_data()
{
addTestData_info();
}
void operator_assign()
{
QFETCH(QGeoPositionInfo, info);
QGeoPositionInfo info2 = info;
QCOMPARE(info2, info);
}
void operator_assign_data()
{
addTestData_info();
}
void operator_equals()
{
QFETCH(QGeoPositionInfo, info);
QVERIFY(info == info);
if (info.isValid())
QCOMPARE(info == QGeoPositionInfo(), false);
}
void operator_equals_data()
{
addTestData_info();
}
void operator_notEquals()
{
QFETCH(QGeoPositionInfo, info);
QCOMPARE(info != info, false);
if (info.isValid())
QCOMPARE(info != QGeoPositionInfo(), true);
}
void operator_notEquals_data()
{
addTestData_info();
}
void setDateTime()
{
QFETCH(QDateTime, dateTime);
QGeoPositionInfo info;
info.setDateTime(dateTime);
QCOMPARE(info.dateTime(), dateTime);
}
void setDateTime_data()
{
QTest::addColumn<QDateTime>("dateTime");
QTest::newRow("invalid") << QDateTime();
QTest::newRow("now") << QDateTime::currentDateTime();
}
void dateTime()
{
QGeoPositionInfo info;
QVERIFY(info.dateTime().isNull());
}
void setCoordinate()
{
QFETCH(QGeoCoordinate, coord);
QGeoPositionInfo info;
info.setCoordinate(coord);
QCOMPARE(info.coordinate(), coord);
}
void setCoordinate_data()
{
QTest::addColumn<QGeoCoordinate>("coord");
QTest::newRow("invalid") << QGeoCoordinate();
QTest::newRow("valid") << QGeoCoordinate(30,30);
}
void property()
{
QFETCH(QGeoPositionInfo::Property, property);
QFETCH(qreal, value);
QGeoPositionInfo info;
QCOMPARE(info.property(property), qreal(-1.0));
info.setProperty(property, value);
QCOMPARE(info.property(property), value);
info.removeProperty(property);
QCOMPARE(info.property(property), qreal(-1.0));
}
void property_data()
{
QTest::addColumn<QGeoPositionInfo::Property>("property");
QTest::addColumn<qreal>("value");
QList<QGeoPositionInfo::Property> properties = tst_qgeopositioninfo_getProperties();
QList<qreal> values = tst_qgeopositioninfo_qrealTestValues();
for (int i=0; i<properties.count(); i++) {
QTest::newRow(qPrintable(QString("Property %1 = %2").arg(properties[i]).arg(values[i])))
<< properties[i] << values[i];
}
}
void hasProperty()
{
QFETCH(QGeoPositionInfo::Property, property);
QFETCH(qreal, value);
QGeoPositionInfo info;
QVERIFY(!info.hasProperty(property));
info.setProperty(property, value);
QVERIFY(info.hasProperty(property));
info.removeProperty(property);
QVERIFY(!info.hasProperty(property));
}
void hasProperty_data()
{
property_data();
}
void removeProperty()
{
QFETCH(QGeoPositionInfo::Property, property);
QFETCH(qreal, value);
QGeoPositionInfo info;
QVERIFY(!info.hasProperty(property));
info.setProperty(property, value);
QVERIFY(info.hasProperty(property));
info.removeProperty(property);
QVERIFY(!info.hasProperty(property));
info.setProperty(property, value);
QVERIFY(info.hasProperty(property));
}
void removeProperty_data()
{
property_data();
}
void datastream()
{
QFETCH(QGeoPositionInfo, info);
QByteArray ba;
QDataStream out(&ba, QIODevice::WriteOnly);
out << info;
QDataStream in(&ba, QIODevice::ReadOnly);
QGeoPositionInfo inInfo;
in >> inInfo;
QCOMPARE(inInfo, info);
}
void datastream_data()
{
addTestData_info();
}
void debug()
{
QFETCH(QGeoPositionInfo, info);
QFETCH(QByteArray, debugStringEnd);
qInstallMsgHandler(tst_qgeopositioninfo_messageHandler);
qDebug() << info;
qInstallMsgHandler(0);
// use endsWith() so we don't depend on QDateTime's debug() implementation
QVERIFY(tst_qgeopositioninfo_debug.endsWith(debugStringEnd));
}
void debug_data()
{
QTest::addColumn<QGeoPositionInfo>("info");
QTest::addColumn<QByteArray>("debugStringEnd");
QTest::newRow("no values") << QGeoPositionInfo()
<< QString("QGeoCoordinate(?, ?))").toLatin1();
QGeoCoordinate coord(1, 1);
QTest::newRow("coord, time") << QGeoPositionInfo(coord, QDateTime::currentDateTime())
<< QByteArray("QGeoCoordinate(1, 1))");
QGeoPositionInfo info;
info.setProperty(QGeoPositionInfo::Heading, 1.1);
info.setProperty(QGeoPositionInfo::GroundSpeed, 2.1);
info.setProperty(QGeoPositionInfo::VerticalSpeed, 3.1);
info.setProperty(QGeoPositionInfo::MagneticVariation, 4.1);
info.setProperty(QGeoPositionInfo::HorizontalAccuracy, 5.1);
info.setProperty(QGeoPositionInfo::VerticalAccuracy, 6.1);
QTest::newRow("all properties") << info
<< QByteArray("QGeoCoordinate(?, ?), Heading=1.1, GroundSpeed=2.1, VerticalSpeed=3.1, MagneticVariation=4.1, HorizontalAccuracy=5.1, VerticalAccuracy=6.1)");
}
};
QTEST_MAIN(tst_QGeoPositionInfo)
#include "tst_qgeopositioninfo.moc"
<commit_msg>Fix addTestData_info() to test property values correctly.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qgeopositioninfo.h>
#include <QMetaType>
#include <QObject>
#include <QDebug>
#include <QTest>
#include <float.h>
Q_DECLARE_METATYPE(QGeoCoordinate)
Q_DECLARE_METATYPE(QGeoPositionInfo)
Q_DECLARE_METATYPE(QGeoPositionInfo::Property)
QByteArray tst_qgeopositioninfo_debug;
void tst_qgeopositioninfo_messageHandler(QtMsgType type, const char *msg)
{
switch(type) {
case QtDebugMsg :
tst_qgeopositioninfo_debug = QByteArray(msg);
break;
default:
break;
}
}
QList<qreal> tst_qgeopositioninfo_qrealTestValues()
{
QList<qreal> values;
if (qreal(DBL_MIN) == DBL_MIN)
values << DBL_MIN;
values << FLT_MIN;
values << -1.0 << 0.0 << 1.0;
values << FLT_MAX;
if (qreal(DBL_MAX) == DBL_MAX)
values << DBL_MAX;
return values;
}
QList<QGeoPositionInfo::Property> tst_qgeopositioninfo_getProperties()
{
QList<QGeoPositionInfo::Property> properties;
properties << QGeoPositionInfo::Heading
<< QGeoPositionInfo::GroundSpeed
<< QGeoPositionInfo::VerticalSpeed
<< QGeoPositionInfo::MagneticVariation
<< QGeoPositionInfo::HorizontalAccuracy
<< QGeoPositionInfo::VerticalAccuracy;
return properties;
}
class tst_QGeoPositionInfo : public QObject
{
Q_OBJECT
private:
QGeoPositionInfo infoWithProperty(QGeoPositionInfo::Property property, qreal value)
{
QGeoPositionInfo info;
info.setProperty(property, value);
return info;
}
void addTestData_info()
{
QTest::addColumn<QGeoPositionInfo>("info");
QTest::newRow("invalid") << QGeoPositionInfo();
QTest::newRow("coord") << QGeoPositionInfo(QGeoCoordinate(-27.3422,150.2342), QDateTime());
QTest::newRow("datetime") << QGeoPositionInfo(QGeoCoordinate(), QDateTime::currentDateTime());
QList<QGeoPositionInfo::Property> properties = tst_qgeopositioninfo_getProperties();
QList<qreal> values = tst_qgeopositioninfo_qrealTestValues();
for (int i=0; i<properties.count(); i++) {
for (int j=0; j<values.count(); j++) {
QTest::newRow(qPrintable(QString("Property %1 = %2").arg(properties[i]).arg(values[j])))
<< infoWithProperty(properties[i], values[j]);
}
}
}
private slots:
void constructor()
{
QGeoPositionInfo info;
QVERIFY(!info.isValid());
QVERIFY(!info.coordinate().isValid());
QVERIFY(info.dateTime().isNull());
}
void constructor_coord_dateTime()
{
QFETCH(QGeoCoordinate, coord);
QFETCH(QDateTime, dateTime);
QFETCH(bool, valid);
QGeoPositionInfo info(coord, dateTime);
QCOMPARE(info.coordinate(), coord);
QCOMPARE(info.dateTime(), dateTime);
QCOMPARE(info.isValid(), valid);
}
void constructor_coord_dateTime_data()
{
QTest::addColumn<QGeoCoordinate>("coord");
QTest::addColumn<QDateTime>("dateTime");
QTest::addColumn<bool>("valid");
QTest::newRow("both null") << QGeoCoordinate() << QDateTime() << false;
QTest::newRow("both valid") << QGeoCoordinate(1,1) << QDateTime::currentDateTime() << true;
QTest::newRow("valid coord") << QGeoCoordinate(1,1) << QDateTime() << false;
QTest::newRow("valid datetime") << QGeoCoordinate() << QDateTime::currentDateTime() << false;
QTest::newRow("valid time but not date == invalid")
<< QGeoCoordinate() << QDateTime(QDate(), QTime::currentTime()) << false;
QTest::newRow("valid date but not time == valid due to QDateTime constructor")
<< QGeoCoordinate() << QDateTime(QDate::currentDate(), QTime()) << false;
}
void constructor_copy()
{
QFETCH(QGeoPositionInfo, info);
QCOMPARE(QGeoPositionInfo(info), info);
}
void constructor_copy_data()
{
addTestData_info();
}
void operator_assign()
{
QFETCH(QGeoPositionInfo, info);
QGeoPositionInfo info2 = info;
QCOMPARE(info2, info);
}
void operator_assign_data()
{
addTestData_info();
}
void operator_equals()
{
QFETCH(QGeoPositionInfo, info);
QVERIFY(info == info);
if (info.isValid())
QCOMPARE(info == QGeoPositionInfo(), false);
}
void operator_equals_data()
{
addTestData_info();
}
void operator_notEquals()
{
QFETCH(QGeoPositionInfo, info);
QCOMPARE(info != info, false);
if (info.isValid())
QCOMPARE(info != QGeoPositionInfo(), true);
}
void operator_notEquals_data()
{
addTestData_info();
}
void setDateTime()
{
QFETCH(QDateTime, dateTime);
QGeoPositionInfo info;
info.setDateTime(dateTime);
QCOMPARE(info.dateTime(), dateTime);
}
void setDateTime_data()
{
QTest::addColumn<QDateTime>("dateTime");
QTest::newRow("invalid") << QDateTime();
QTest::newRow("now") << QDateTime::currentDateTime();
}
void dateTime()
{
QGeoPositionInfo info;
QVERIFY(info.dateTime().isNull());
}
void setCoordinate()
{
QFETCH(QGeoCoordinate, coord);
QGeoPositionInfo info;
info.setCoordinate(coord);
QCOMPARE(info.coordinate(), coord);
}
void setCoordinate_data()
{
QTest::addColumn<QGeoCoordinate>("coord");
QTest::newRow("invalid") << QGeoCoordinate();
QTest::newRow("valid") << QGeoCoordinate(30,30);
}
void property()
{
QFETCH(QGeoPositionInfo::Property, property);
QFETCH(qreal, value);
QGeoPositionInfo info;
QCOMPARE(info.property(property), qreal(-1.0));
info.setProperty(property, value);
QCOMPARE(info.property(property), value);
info.removeProperty(property);
QCOMPARE(info.property(property), qreal(-1.0));
}
void property_data()
{
QTest::addColumn<QGeoPositionInfo::Property>("property");
QTest::addColumn<qreal>("value");
QList<QGeoPositionInfo::Property> properties = tst_qgeopositioninfo_getProperties();
QList<qreal> values = tst_qgeopositioninfo_qrealTestValues();
for (int i=0; i<properties.count(); i++) {
QTest::newRow(qPrintable(QString("Property %1 = %2").arg(properties[i]).arg(values[i])))
<< properties[i] << values[i];
}
}
void hasProperty()
{
QFETCH(QGeoPositionInfo::Property, property);
QFETCH(qreal, value);
QGeoPositionInfo info;
QVERIFY(!info.hasProperty(property));
info.setProperty(property, value);
QVERIFY(info.hasProperty(property));
info.removeProperty(property);
QVERIFY(!info.hasProperty(property));
}
void hasProperty_data()
{
property_data();
}
void removeProperty()
{
QFETCH(QGeoPositionInfo::Property, property);
QFETCH(qreal, value);
QGeoPositionInfo info;
QVERIFY(!info.hasProperty(property));
info.setProperty(property, value);
QVERIFY(info.hasProperty(property));
info.removeProperty(property);
QVERIFY(!info.hasProperty(property));
info.setProperty(property, value);
QVERIFY(info.hasProperty(property));
}
void removeProperty_data()
{
property_data();
}
void datastream()
{
QFETCH(QGeoPositionInfo, info);
QByteArray ba;
QDataStream out(&ba, QIODevice::WriteOnly);
out << info;
QDataStream in(&ba, QIODevice::ReadOnly);
QGeoPositionInfo inInfo;
in >> inInfo;
QCOMPARE(inInfo, info);
}
void datastream_data()
{
addTestData_info();
}
void debug()
{
QFETCH(QGeoPositionInfo, info);
QFETCH(QByteArray, debugStringEnd);
qInstallMsgHandler(tst_qgeopositioninfo_messageHandler);
qDebug() << info;
qInstallMsgHandler(0);
// use endsWith() so we don't depend on QDateTime's debug() implementation
QVERIFY(tst_qgeopositioninfo_debug.endsWith(debugStringEnd));
}
void debug_data()
{
QTest::addColumn<QGeoPositionInfo>("info");
QTest::addColumn<QByteArray>("debugStringEnd");
QTest::newRow("no values") << QGeoPositionInfo()
<< QString("QGeoCoordinate(?, ?))").toLatin1();
QGeoCoordinate coord(1, 1);
QTest::newRow("coord, time") << QGeoPositionInfo(coord, QDateTime::currentDateTime())
<< QByteArray("QGeoCoordinate(1, 1))");
QGeoPositionInfo info;
info.setProperty(QGeoPositionInfo::Heading, 1.1);
info.setProperty(QGeoPositionInfo::GroundSpeed, 2.1);
info.setProperty(QGeoPositionInfo::VerticalSpeed, 3.1);
info.setProperty(QGeoPositionInfo::MagneticVariation, 4.1);
info.setProperty(QGeoPositionInfo::HorizontalAccuracy, 5.1);
info.setProperty(QGeoPositionInfo::VerticalAccuracy, 6.1);
QTest::newRow("all properties") << info
<< QByteArray("QGeoCoordinate(?, ?), Heading=1.1, GroundSpeed=2.1, VerticalSpeed=3.1, MagneticVariation=4.1, HorizontalAccuracy=5.1, VerticalAccuracy=6.1)");
}
};
QTEST_MAIN(tst_QGeoPositionInfo)
#include "tst_qgeopositioninfo.moc"
<|endoftext|>
|
<commit_before>#include "trainer.h"
namespace multiverso
{
namespace wordembedding
{
Trainer::Trainer(int trainer_id, Option *option,
multiverso::Barrier *barrier,
Dictionary* dictionary, WordEmbedding* WordEmbedding,
MemoryManager* memory_mamanger)
{
trainer_id_ = trainer_id;
option_ = option;
word_count = 0;
WordEmbedding_ = WordEmbedding;
barrier_ = barrier;
dictionary_ = dictionary;
memory_mamanger_ = memory_mamanger;
hidden_act_ = (real *)calloc(option_->embeding_size, sizeof(real));
hidden_err_ = (real *)calloc(option_->embeding_size, sizeof(real));
process_count_ = -1;
process_id_ = -1;
assert(hidden_act_ != nullptr);
assert(hidden_err_ != nullptr);
start_ = 0;
train_count_ = 0;
if (trainer_id_ == 0)
{
//The log which recordes the begin and end time of TrainIteration()
char log_name[100];
sprintf(log_name, "trainer%s.txt", g_log_suffix.c_str());
log_file_ = fopen(log_name, "w");
}
}
void Trainer::TrainIteration(multiverso::DataBlockBase *data_block)
{
if (process_id_ == -1)
process_id_ = multiverso::Multiverso::ProcessRank();
if (trainer_id_ == 0)
//Record the starting time of the Trainiteration
fprintf(log_file_, "%lf\n", (clock()) / (double)CLOCKS_PER_SEC);
multiverso::Log::Info("Rank %d Train %d Begin TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
++train_count_;
//Compute the total number of processes
if (process_count_ == -1)
process_count_ = multiverso::Multiverso::TotalProcessCount();
DataBlock *data = reinterpret_cast<DataBlock*>(data_block);
std::vector<int> input_nodes(data->input_nodes.begin(), data->input_nodes.end());
std::vector<int> output_nodes(data->output_nodes.begin(), data->output_nodes.end());
//A trainer only copy or add apart of parameters
//This trainer should copy or add the parameters according to
//local_input_nodes and local_output_nodes
std::vector<int> local_input_nodes;
std::vector<int> local_output_nodes;
for (int i = trainer_id_; i < input_nodes.size(); i += option_->thread_cnt)
local_input_nodes.push_back(input_nodes[i]);
for (int i = trainer_id_; i < output_nodes.size(); i += option_->thread_cnt)
local_output_nodes.push_back(output_nodes[i]);
if (trainer_id_ == 0)
{
multiverso::Log::Info("Rank %d input_size=%d, output_size=%d\n",
process_id_, input_nodes.size(), output_nodes.size());
}
//Step 1, Copy the parameter from multiverso to WordEmbedding_
//One trainer only copy a part of parameters
multiverso::Log::Debug("Rank %d Train %d Copyparameter Begin TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
CopyParameter(local_input_nodes, local_output_nodes);
if (trainer_id_ == 0)
{
multiverso::Row<int64> ©_row = GetRow<int64>(kWordCountActualTableId, 0);
WordEmbedding_->word_count_actual = copy_row.At(0);
WordEmbedding_->UpdateLearningRate();
}
multiverso::Log::Debug("Rank %d Train %d Copyparameter end TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
//Wait for all the trainers to finish copying parameter
barrier_->Wait();
//Step 2, After finishing copying parameter,
//Use WordEmbedding_ to train a part of data_block
int64 last_word_count = word_count;
clock_t start = clock();
multiverso::Log::Debug("Rank %d Train %d TrainNN Begin TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
WordEmbedding_->Train(data, trainer_id_, option_->thread_cnt,
word_count, hidden_act_, hidden_err_);
if (word_count > last_word_count)
{
multiverso::Log::Info("TrainNNSpeed: Words/thread/second %lfk\n",
((double)word_count - last_word_count) /
(clock() - start) * (double)CLOCKS_PER_SEC / 1000);
}
multiverso::Log::Debug("Rank %d Train %d TrainNN end TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
//Wait for all the trainers to finish training
barrier_->Wait();
multiverso::Log::Debug("Rank %d Train %d AddDeltaParameter Begin TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
//Step 3, After finishing training, add the delta of parameters to multiverso
AddDeltaParameter(local_input_nodes, local_output_nodes);
if (trainer_id_ == 0)
{
multiverso::Row<int64> ©_row = GetRow<int64>(kWordCountActualTableId, 0);
Add<int64>(kWordCountActualTableId, 0, 0, WordEmbedding_->word_count_actual - copy_row.At(0));
}
multiverso::Log::Debug("Rank %d Train %d AddDeltaParameter end TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
//If the data_block is the last one,Dump the input-embedding weights
if (data->Type() == DataBlockType::Test && trainer_id_ == 0)
{
SaveEmbedding(option_->output_file, option_->output_binary);
}
if (trainer_id_ == 0)
{
fprintf(log_file_, "%lf\n",
(clock()) / (double)CLOCKS_PER_SEC);
fflush(log_file_);
}
}
void Trainer::CopyRow(real* ptr, multiverso::Row<real>& row, int size)
{
for (int i = 0; i < size; ++i)
ptr[i] = row.At(i);
}
void Trainer::CopyParameter(std::vector<int>& input_nodes,
std::vector<int>& output_nodes)
{
//Compute the number of necessary memory blocks to store parameter
std::vector<real*> blocks;
int current_block = 0;
size_t total_blocks = (input_nodes.size() + output_nodes.size());
if (option_->use_adagrad)
total_blocks *= 2;
//Request blocks to store parameters
memory_mamanger_->RequestBlocks(total_blocks, blocks);
assert(blocks.size() == total_blocks);
if (blocks.size() != total_blocks)
{
multiverso::Log::Error("Rank %d Trainer %d Error to requestBlocks to CopyParameter, allocated_blocks_num=%lld, needed_blocks_num=%lld\n",
multiverso::Multiverso::ProcessRank(), trainer_id_, blocks.size(), total_blocks);
return;
}
//Copy input-embedding weights from multiverso to WordEmbedding
for (int i = 0; i < input_nodes.size(); ++i)
{
real* ptr = blocks[current_block++];
assert(ptr != nullptr);
CopyRow(ptr, GetRow<real>(kInputEmbeddingTableId,
input_nodes[i]), option_->embeding_size);
WordEmbedding_->SetWeightIE(input_nodes[i], ptr);
}
//Copy embedding-output weights from multiverso to WordEmbedding
for (int i = 0; i < output_nodes.size(); ++i)
{
real* ptr = blocks[current_block++];
assert(ptr != nullptr);
CopyRow(ptr, GetRow<real>(kEmbeddingOutputTableId,
output_nodes[i]), option_->embeding_size);
WordEmbedding_->SetWeightEO(output_nodes[i], ptr);
}
if (option_->use_adagrad)
{
//Copy input-embedding sum of squarsh of gradient
for (int i = 0; i < input_nodes.size(); ++i)
{
real* ptr = blocks[current_block++];
assert(ptr != nullptr);
CopyRow(ptr, GetRow<real>(kSumGradient2IETableId,
input_nodes[i]), option_->embeding_size);
WordEmbedding_->SetSumGradient2IE(input_nodes[i], ptr);
}
//Copy embedding-output sum of squarsh of gradient
for (int i = 0; i < output_nodes.size(); ++i)
{
real* ptr = blocks[current_block++];
assert(ptr != nullptr);
CopyRow(ptr, GetRow<real>(kSumGradient2EOTableId,
output_nodes[i]), option_->embeding_size);
WordEmbedding_->SetSumGradient2EO(output_nodes[i], ptr);
}
}
}
void Trainer::AddRow(real* ptr, int table_id, int row_id, int size)
{
multiverso::Row<real>& row = GetRow<real>(table_id, row_id);
for (int i = 0; i < size; ++i)
{
real delta = (ptr[i] - row.At(i)) / process_count_;
if (fabs(delta) > kEps)
Add<real>(table_id, row_id, i, delta);
}
}
//Add delta to local buffer and send it to the parameter sever
void Trainer::AddDeltaParameter(std::vector<int>& input_nodes,
std::vector<int>& output_nodes)
{
std::vector<real*> blocks;
for (int i = 0; i < input_nodes.size(); ++i)
{
real* ptr = WordEmbedding_->GetWeightIE(input_nodes[i]);
assert(ptr != nullptr);
AddRow(ptr, kInputEmbeddingTableId, input_nodes[i],
option_->embeding_size);
blocks.push_back(ptr);
}
for (int i = 0; i < output_nodes.size(); ++i)
{
real* ptr = WordEmbedding_->GetWeightEO(output_nodes[i]);
assert(ptr != nullptr);
AddRow(ptr, kEmbeddingOutputTableId, output_nodes[i],
option_->embeding_size);
blocks.push_back(ptr);
}
if (option_->use_adagrad)
{
for (int i = 0; i < input_nodes.size(); ++i)
{
real* ptr = WordEmbedding_->GetSumGradient2IE(input_nodes[i]);
assert(ptr != nullptr);
AddRow(ptr, kSumGradient2IETableId, input_nodes[i],
option_->embeding_size);
blocks.push_back(ptr);
}
for (int i = 0; i < output_nodes.size(); ++i)
{
real* ptr = WordEmbedding_->GetSumGradient2EO(output_nodes[i]);
assert(ptr != nullptr);
AddRow(ptr, kSumGradient2EOTableId, output_nodes[i],
option_->embeding_size);
blocks.push_back(ptr);
}
}
//Return all the memory blocks
memory_mamanger_->ReturnBlocks(blocks);
}
void Trainer::SaveEmbedding(const char *file_path, bool is_binary)
{
FILE* fid = nullptr;
if (is_binary)
{
fid = fopen(file_path, "wb");
fprintf(fid, "%d %d\n", dictionary_->Size(),option_->embeding_size);
for (int i = 0; i < dictionary_->Size(); ++i)
{
fprintf(fid, "%s ",
dictionary_->GetWordInfo(i)->word.c_str());
multiverso::Row<real>& embedding = GetRow<real>(
kInputEmbeddingTableId, i);
for (int j = 0; j < option_->embeding_size; ++j)
{
real tmp = embedding.At(j);
fwrite(&tmp, sizeof(real), 1, fid);
}
fprintf(fid, "\n");
}
fclose(fid);
}
else
{
fid = fopen(file_path, "wt");
fprintf(fid, "%d %d\n", dictionary_->Size(), option_->embeding_size);
for (int i = 0; i < dictionary_->Size(); ++i)
{
fprintf(fid, "%s ", dictionary_->GetWordInfo(i)->word.c_str());
multiverso::Row<real>& embedding = GetRow<real>(kInputEmbeddingTableId, i);
for (int j = 0; j < option_->embeding_size; ++j)
fprintf(fid, "%lf ", embedding.At(j));
fprintf(fid, "\n");
}
fclose(fid);
}
}
}
}<commit_msg>Update trainer.cpp<commit_after>#include "trainer.h"
namespace multiverso
{
namespace wordembedding
{
Trainer::Trainer(int trainer_id, Option *option,
multiverso::Barrier *barrier,
Dictionary* dictionary, WordEmbedding* WordEmbedding,
MemoryManager* memory_mamanger)
{
trainer_id_ = trainer_id;
option_ = option;
word_count = 0;
WordEmbedding_ = WordEmbedding;
barrier_ = barrier;
dictionary_ = dictionary;
memory_mamanger_ = memory_mamanger;
hidden_act_ = (real *)calloc(option_->embeding_size, sizeof(real));
hidden_err_ = (real *)calloc(option_->embeding_size, sizeof(real));
process_count_ = -1;
process_id_ = -1;
assert(hidden_act_ != nullptr);
assert(hidden_err_ != nullptr);
start_ = 0;
train_count_ = 0;
if (trainer_id_ == 0)
{
//The log which recordes the begin and end time of TrainIteration()
char log_name[100];
sprintf(log_name, "trainer%s.txt", g_log_suffix.c_str());
log_file_ = fopen(log_name, "w");
}
}
void Trainer::TrainIteration(multiverso::DataBlockBase *data_block)
{
if (process_id_ == -1)
process_id_ = multiverso::Multiverso::ProcessRank();
if (trainer_id_ == 0)
//Record the starting time of the Trainiteration
fprintf(log_file_, "%lf\n", (clock()) / (double)CLOCKS_PER_SEC);
multiverso::Log::Info("Rank %d Train %d Begin TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
++train_count_;
//Compute the total number of processes
if (process_count_ == -1)
process_count_ = multiverso::Multiverso::TotalProcessCount();
DataBlock *data = reinterpret_cast<DataBlock*>(data_block);
std::vector<int> input_nodes(data->input_nodes.begin(), data->input_nodes.end());
std::vector<int> output_nodes(data->output_nodes.begin(), data->output_nodes.end());
//A trainer only copy or add apart of parameters
//This trainer should copy or add the parameters according to
//local_input_nodes and local_output_nodes
std::vector<int> local_input_nodes;
std::vector<int> local_output_nodes;
for (int i = trainer_id_; i < input_nodes.size(); i += option_->thread_cnt)
local_input_nodes.push_back(input_nodes[i]);
for (int i = trainer_id_; i < output_nodes.size(); i += option_->thread_cnt)
local_output_nodes.push_back(output_nodes[i]);
if (trainer_id_ == 0)
{
multiverso::Log::Info("Rank %d input_size=%d, output_size=%d\n",
process_id_, input_nodes.size(), output_nodes.size());
}
//Step 1, Copy the parameter from multiverso to WordEmbedding_
//One trainer only copy a part of parameters
multiverso::Log::Debug("Rank %d Train %d Copyparameter Begin TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
CopyParameter(local_input_nodes, local_output_nodes);
if (trainer_id_ == 0)
{
multiverso::Row<int64> ©_row = GetRow<int64>(kWordCountActualTableId, 0);
WordEmbedding_->word_count_actual = copy_row.At(0);
WordEmbedding_->UpdateLearningRate();
}
multiverso::Log::Debug("Rank %d Train %d Copyparameter end TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
//Wait for all the trainers to finish copying parameter
barrier_->Wait();
//Step 2, After finishing copying parameter,
//Use WordEmbedding_ to train a part of data_block
int64 last_word_count = word_count;
clock_t start = clock();
multiverso::Log::Debug("Rank %d Train %d TrainNN Begin TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
WordEmbedding_->Train(data, trainer_id_, option_->thread_cnt,
word_count, hidden_act_, hidden_err_);
if (word_count > last_word_count)
{
multiverso::Log::Info("TrainNNSpeed: Words/thread/second %lfk\n",
((double)word_count - last_word_count) /
(clock() - start) * (double)CLOCKS_PER_SEC / 1000);
}
multiverso::Log::Debug("Rank %d Train %d TrainNN end TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
//Wait for all the trainers to finish training
barrier_->Wait();
multiverso::Log::Debug("Rank %d Train %d AddDeltaParameter Begin TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
//Step 3, After finishing training, add the delta of parameters to multiverso
AddDeltaParameter(local_input_nodes, local_output_nodes);
if (trainer_id_ == 0)
{
multiverso::Row<int64> ©_row = GetRow<int64>(kWordCountActualTableId, 0);
Add<int64>(kWordCountActualTableId, 0, 0, WordEmbedding_->word_count_actual - copy_row.At(0));
}
multiverso::Log::Debug("Rank %d Train %d AddDeltaParameter end TrainIteration%d ...\n",
process_id_, trainer_id_, train_count_);
//If the data_block is the last one,Dump the input-embedding weights
if (data->Type() == DataBlockType::Test && trainer_id_ == 0)
{
SaveEmbedding(option_->output_file, option_->output_binary);
}
if (trainer_id_ == 0)
{
fprintf(log_file_, "%lf\n",
(clock()) / (double)CLOCKS_PER_SEC);
fflush(log_file_);
}
}
void Trainer::CopyRow(real* ptr, multiverso::Row<real>& row, int size)
{
for (int i = 0; i < size; ++i)
ptr[i] = row.At(i);
}
void Trainer::CopyParameter(std::vector<int>& input_nodes,
std::vector<int>& output_nodes)
{
//Compute the number of necessary memory blocks to store parameter
std::vector<real*> blocks;
int current_block = 0;
size_t total_blocks = (input_nodes.size() + output_nodes.size());
if (option_->use_adagrad)
total_blocks *= 2;
//Request blocks to store parameters
memory_mamanger_->RequestBlocks(total_blocks, blocks);
assert(blocks.size() == total_blocks);
if (blocks.size() != total_blocks)
{
multiverso::Log::Error("Rank %d Trainer %d Error to requestBlocks to CopyParameter, allocated_blocks_num=%lld, needed_blocks_num=%lld\n",
multiverso::Multiverso::ProcessRank(), trainer_id_, blocks.size(), total_blocks);
return;
}
//Copy input-embedding weights from multiverso to WordEmbedding
for (int i = 0; i < input_nodes.size(); ++i)
{
real* ptr = blocks[current_block++];
assert(ptr != nullptr);
CopyRow(ptr, GetRow<real>(kInputEmbeddingTableId,
input_nodes[i]), option_->embeding_size);
WordEmbedding_->SetWeightIE(input_nodes[i], ptr);
}
//Copy embedding-output weights from multiverso to WordEmbedding
for (int i = 0; i < output_nodes.size(); ++i)
{
real* ptr = blocks[current_block++];
assert(ptr != nullptr);
CopyRow(ptr, GetRow<real>(kEmbeddingOutputTableId,
output_nodes[i]), option_->embeding_size);
WordEmbedding_->SetWeightEO(output_nodes[i], ptr);
}
if (option_->use_adagrad)
{
//Copy input-embedding sum of squarsh of gradient
for (int i = 0; i < input_nodes.size(); ++i)
{
real* ptr = blocks[current_block++];
assert(ptr != nullptr);
CopyRow(ptr, GetRow<real>(kSumGradient2IETableId,
input_nodes[i]), option_->embeding_size);
WordEmbedding_->SetSumGradient2IE(input_nodes[i], ptr);
}
//Copy embedding-output sum of squarsh of gradient
for (int i = 0; i < output_nodes.size(); ++i)
{
real* ptr = blocks[current_block++];
assert(ptr != nullptr);
CopyRow(ptr, GetRow<real>(kSumGradient2EOTableId,
output_nodes[i]), option_->embeding_size);
WordEmbedding_->SetSumGradient2EO(output_nodes[i], ptr);
}
}
}
void Trainer::AddRow(real* ptr, int table_id, int row_id, int size)
{
multiverso::Row<real>& row = GetRow<real>(table_id, row_id);
for (int i = 0; i < size; ++i)
{
real delta = (ptr[i] - row.At(i)) / process_count_;
if (fabs(delta) > kEps)
Add<real>(table_id, row_id, i, delta);
}
}
//Add delta to local buffer and send it to the parameter sever
void Trainer::AddDeltaParameter(std::vector<int>& input_nodes,
std::vector<int>& output_nodes)
{
std::vector<real*> blocks;
for (int i = 0; i < input_nodes.size(); ++i)
{
real* ptr = WordEmbedding_->GetWeightIE(input_nodes[i]);
assert(ptr != nullptr);
AddRow(ptr, kInputEmbeddingTableId, input_nodes[i],
option_->embeding_size);
blocks.push_back(ptr);
}
for (int i = 0; i < output_nodes.size(); ++i)
{
real* ptr = WordEmbedding_->GetWeightEO(output_nodes[i]);
assert(ptr != nullptr);
AddRow(ptr, kEmbeddingOutputTableId, output_nodes[i],
option_->embeding_size);
blocks.push_back(ptr);
}
if (option_->use_adagrad)
{
for (int i = 0; i < input_nodes.size(); ++i)
{
real* ptr = WordEmbedding_->GetSumGradient2IE(input_nodes[i]);
assert(ptr != nullptr);
AddRow(ptr, kSumGradient2IETableId, input_nodes[i],
option_->embeding_size);
blocks.push_back(ptr);
}
for (int i = 0; i < output_nodes.size(); ++i)
{
real* ptr = WordEmbedding_->GetSumGradient2EO(output_nodes[i]);
assert(ptr != nullptr);
AddRow(ptr, kSumGradient2EOTableId, output_nodes[i],
option_->embeding_size);
blocks.push_back(ptr);
}
}
//Return all the memory blocks
memory_mamanger_->ReturnBlocks(blocks);
}
void Trainer::SaveEmbedding(const char *file_path, bool is_binary)
{
FILE* fid = nullptr;
if (is_binary)
{
fid = fopen(file_path, "wb");
fprintf(fid, "%d %d\n", dictionary_->Size(),option_->embeding_size);
for (int i = 0; i < dictionary_->Size(); ++i)
{
fprintf(fid, "%s ",
dictionary_->GetWordInfo(i)->word.c_str());
multiverso::Row<real>& embedding = GetRow<real>(
kInputEmbeddingTableId, i);
for (int j = 0; j < option_->embeding_size; ++j)
{
real tmp = embedding.At(j);
fwrite(&tmp, sizeof(real), 1, fid);
}
fprintf(fid, "\n");
}
fclose(fid);
}
else
{
fid = fopen(file_path, "wt");
fprintf(fid, "%d %d\n", dictionary_->Size(), option_->embeding_size);
for (int i = 0; i < dictionary_->Size(); ++i)
{
fprintf(fid, "%s ", dictionary_->GetWordInfo(i)->word.c_str());
multiverso::Row<real>& embedding = GetRow<real>(kInputEmbeddingTableId, i);
for (int j = 0; j < option_->embeding_size; ++j)
fprintf(fid, "%lf ", embedding.At(j));
fprintf(fid, "\n");
}
fclose(fid);
}
}
}
}
<|endoftext|>
|
<commit_before>#include "twister.h"
const unsigned CYCLE = 0x100;
//Suggest we wrap these arrays inside an fsm or test base class
const unsigned C_TRANS_ = 0xff;
int block_units[][0x10] = {
0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65
};
int triad_units[][0x03] = {
0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53, 0xa9, 0xc3, 0x08, 0xaf, 0x08, 0xf0
};
const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,
0xcf, 0xad, 0xdf, 0xff, 0xce,
0x32, 0x40, 0xd3, 0x27, 0x82,
0xda, 0xee, 0xff, 0xfc, 0xbf,
0x1c, 0x90, 0x13, 0x4a, 0xa5,
0xe0, 0x21, 0x9f, 0xe1, 0xc6,
0xaf, 0x05, 0x81, 0xf0, 0xee,
0xe4, 0x38, 0x1f, 0x60, 0x24,
0x0c, 0x35, 0x51, 0x32, 0xcf,
0x12, 0x9a, 0x30, 0x44, 0x72,
0x51, 0x3c, 0x61, 0x2d, 0x5f,
0x04, 0x1c, 0x52, 0xca, 0xdf,
0x12, 0x0b, 0x30, 0xa0, 0x1e,
0x03, 0x14, 0x09, 0x73, 0x23,
0xf2, 0xca, 0xa2, 0x51, 0xc6,
0x01, 0xdf, 0x41, 0x96, 0xa0,
0x51, 0x19, 0x71, 0x23, 0x47,
0xcb, 0xbd, 0xba, 0xac, 0xdf,
0xdf, 0xde, 0xcd, 0xfd, 0xca };
int ENTRY_LINK__ = 0x05;
int ENTRY_LINK__TEST = 0x09;
int ENTRY_C_REF_ECM = 0x10;
int ENTRY_C_REF_ECM_TEST = 0x03;
int ENTRY_C_OUTER = 0x51;
int ENTRY_C_OUTER_PROD = 0x41;
int ENTRY_C_OUTER_PROD_TEST = 0x33;
int ENTRY_C_OUTER_PROD_TOR_TEST = 0x57;
int ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9;
int ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf;
int ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1;
int ENTRY_C_INNER_PROD_EUC_TEST = 0xc5;
int ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2;
int ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5;
int ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff;
int ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff;
unsigned reflect(unsigned center, unsigned (*r)(unsigned))
{
return (*r)(center)^center;
}
unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)
{
return (*s)(pos)^a;
}
void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d)^base(d, g, d);
}
data[i] = d;
}
}
void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d)^(*g)(d);
}
data[i] = d;
}
}
void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d);
}
data[i] = d;
}
}
vector<double> f_dist(vector<unsigned char>& in)
{
vector<double> fdist;
fdist.resize(256);
for(unsigned i = 0; i<in.size(); i++)
{
fdist[in[i]]++;
}
for(unsigned i=0; i<fdist.size(); i++)
{
fdist[i] = (fdist[i] / in.size()) * 100;
}
return fdist;
}
double s_entropy(vector<double>& v)
{
double entropy = 0;
double p;
for(unsigned i = 0; i < v.size(); i++)
{
p = v[i] / 100;
if (p == 0) continue;
entropy += p * std::log(p) / std::log(2);
}
return -entropy;
}
void rms(const string& s, string& r)
{
for(unsigned int i=0; i<s.size(); i++)
{
if(::isspace(s[i])) continue;
r+= s[i];
}
}
//add extended euc
double sw(double weight, int i, int j, int (*inv)(int, int))
{
return weight*(*inv)(i, j);
}
//Suggest we wrap these routines in a base class in particular for testing
//and expose test api
void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int), void (*center)(int))
{
if(transition_seq[ENTRY_C_INNER_PROD_RELAY_TEST] == s)
{
(*center)(s);
return;
}
if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s)
{
(*p)(s);
return;
}
if(s == 1)
{
(*p)(n);
return;
}
for(int i=0; i< s; i++)
{
hPerm(s-1, n, p, inv, p);
if(s%2 == 1)
(*inv)(0, s-1);
else
(*inv)(i, s-1);
}
}
double ic(const string& t)
{
string text; rms(t, text);
vector<double> freq(256,0);
for(unsigned int i=0; i<text.size(); i++)
{
if(text[i] == ' ') continue;
freq[text[i]] ++;
}
double sum=0;
for(unsigned int i=0; i<freq.size(); i++)
{
if(freq[i] != 0)
{
double c = freq[i];
if(c != 0)
sum += c * (c - 1);
}
}
double ic = 26 * sum / (text.size() * (text.size() - 1));
return ic;
}
int outer_sect(int (*s)(int), int (*t)(int), int r, int q)
{
return (*s)(r) * (*t)(q);
}
//chain cross ref - test -
void multiChan(unsigned char* (*p)(unsigned char, unsigned char), unsigned char m)
{
unsigned char* chanIndicator = (*p)(transition_seq[ENTRY_C_REF_ECM], m);
unsigned char* crossCh = (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST], m);
*chanIndicator = *chanIndicator ^ *crossCh;
*crossCh = *chanIndicator ^ *crossCh;
*chanIndicator = *chanIndicator ^ *crossCh;
}
void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)
{
//test seq
(*p)(transition_seq[ENTRY_LINK__], m);
(*p)(transition_seq[ENTRY_LINK__TEST], m);
//stream test , suggest these tests should be moved to a state transition class
//
//
//
(*p)(transition_seq[ENTRY_C_REF_ECM], m ^ 0xff );
(*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ], m);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_LINK__TEST]);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_REF_ECM]);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST]);
}
//Suggest we wrap these in util base class, abstract col cont
std::tuple<int, int, int> extended_gcd(int __alpha, int __beta, int (*col)(int x, int y))
{
if(__alpha == 0) return make_tuple(__beta,0,1);
int __com=0;
int x=0;
int y=0;
tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col);
return make_tuple(__com, y-(__beta/__alpha)*x, x);
}
//frmwk wrapper pending nh release, util base
//
std::tuple<int, int, int> extended_gcd(int __alpha, int __beta)
{
if(__alpha == 0) return make_tuple(__beta,0,1);
int __com=0;
int x=0;
int y=0;
tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha);
return make_tuple(__com, y-(__beta/__alpha)*x, x);
}
<commit_msg>stch table<commit_after>#include "twister.h"
const unsigned CYCLE = 0x100;
//Suggest we wrap these arrays inside an fsm or test base class
const unsigned C_TRANS_ = 0xff;
int block_units[][0x10] = {
0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65
};
int triad_units[][0x03] = {
0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53, 0xa9, 0xc3, 0x08, 0xaf, 0x08, 0xf0, 0xf3, 0x24, 0x91
};
const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,
0xcf, 0xad, 0xdf, 0xff, 0xce,
0x32, 0x40, 0xd3, 0x27, 0x82,
0xda, 0xee, 0xff, 0xfc, 0xbf,
0x1c, 0x90, 0x13, 0x4a, 0xa5,
0xe0, 0x21, 0x9f, 0xe1, 0xc6,
0xaf, 0x05, 0x81, 0xf0, 0xee,
0xe4, 0x38, 0x1f, 0x60, 0x24,
0x0c, 0x35, 0x51, 0x32, 0xcf,
0x12, 0x9a, 0x30, 0x44, 0x72,
0x51, 0x3c, 0x61, 0x2d, 0x5f,
0x04, 0x1c, 0x52, 0xca, 0xdf,
0x12, 0x0b, 0x30, 0xa0, 0x1e,
0x03, 0x14, 0x09, 0x73, 0x23,
0xf2, 0xca, 0xa2, 0x51, 0xc6,
0x01, 0xdf, 0x41, 0x96, 0xa0,
0x51, 0x19, 0x71, 0x23, 0x47,
0xcb, 0xbd, 0xba, 0xac, 0xdf,
0xdf, 0xde, 0xcd, 0xfd, 0xca };
int ENTRY_LINK__ = 0x05;
int ENTRY_LINK__TEST = 0x09;
int ENTRY_C_REF_ECM = 0x10;
int ENTRY_C_REF_ECM_TEST = 0x03;
int ENTRY_C_OUTER = 0x51;
int ENTRY_C_OUTER_PROD = 0x41;
int ENTRY_C_OUTER_PROD_TEST = 0x33;
int ENTRY_C_OUTER_PROD_TOR_TEST = 0x57;
int ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9;
int ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf;
int ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1;
int ENTRY_C_INNER_PROD_EUC_TEST = 0xc5;
int ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2;
int ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5;
int ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff;
int ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff;
unsigned reflect(unsigned center, unsigned (*r)(unsigned))
{
return (*r)(center)^center;
}
unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)
{
return (*s)(pos)^a;
}
void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d)^base(d, g, d);
}
data[i] = d;
}
}
void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d)^(*g)(d);
}
data[i] = d;
}
}
void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))
{
for(unsigned i = 0; i<data.size(); i++)
{
unsigned char d = data[i];
for(unsigned j=0; j<CYCLE; j++)
{
d = (*f)(d);
}
data[i] = d;
}
}
vector<double> f_dist(vector<unsigned char>& in)
{
vector<double> fdist;
fdist.resize(256);
for(unsigned i = 0; i<in.size(); i++)
{
fdist[in[i]]++;
}
for(unsigned i=0; i<fdist.size(); i++)
{
fdist[i] = (fdist[i] / in.size()) * 100;
}
return fdist;
}
double s_entropy(vector<double>& v)
{
double entropy = 0;
double p;
for(unsigned i = 0; i < v.size(); i++)
{
p = v[i] / 100;
if (p == 0) continue;
entropy += p * std::log(p) / std::log(2);
}
return -entropy;
}
void rms(const string& s, string& r)
{
for(unsigned int i=0; i<s.size(); i++)
{
if(::isspace(s[i])) continue;
r+= s[i];
}
}
//add extended euc
double sw(double weight, int i, int j, int (*inv)(int, int))
{
return weight*(*inv)(i, j);
}
//Suggest we wrap these routines in a base class in particular for testing
//and expose test api
void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int), void (*center)(int))
{
if(transition_seq[ENTRY_C_INNER_PROD_RELAY_TEST] == s)
{
(*center)(s);
return;
}
if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s)
{
(*p)(s);
return;
}
if(s == 1)
{
(*p)(n);
return;
}
for(int i=0; i< s; i++)
{
hPerm(s-1, n, p, inv, p);
if(s%2 == 1)
(*inv)(0, s-1);
else
(*inv)(i, s-1);
}
}
double ic(const string& t)
{
string text; rms(t, text);
vector<double> freq(256,0);
for(unsigned int i=0; i<text.size(); i++)
{
if(text[i] == ' ') continue;
freq[text[i]] ++;
}
double sum=0;
for(unsigned int i=0; i<freq.size(); i++)
{
if(freq[i] != 0)
{
double c = freq[i];
if(c != 0)
sum += c * (c - 1);
}
}
double ic = 26 * sum / (text.size() * (text.size() - 1));
return ic;
}
int outer_sect(int (*s)(int), int (*t)(int), int r, int q)
{
return (*s)(r) * (*t)(q);
}
//chain cross ref - test -
void multiChan(unsigned char* (*p)(unsigned char, unsigned char), unsigned char m)
{
unsigned char* chanIndicator = (*p)(transition_seq[ENTRY_C_REF_ECM], m);
unsigned char* crossCh = (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST], m);
*chanIndicator = *chanIndicator ^ *crossCh;
*crossCh = *chanIndicator ^ *crossCh;
*chanIndicator = *chanIndicator ^ *crossCh;
}
void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)
{
//test seq
(*p)(transition_seq[ENTRY_LINK__], m);
(*p)(transition_seq[ENTRY_LINK__TEST], m);
//stream test , suggest these tests should be moved to a state transition class
//
//
//
(*p)(transition_seq[ENTRY_C_REF_ECM], m ^ 0xff );
(*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ], m);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_LINK__TEST]);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_REF_ECM]);
(*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST]);
}
//Suggest we wrap these in util base class, abstract col cont
std::tuple<int, int, int> extended_gcd(int __alpha, int __beta, int (*col)(int x, int y))
{
if(__alpha == 0) return make_tuple(__beta,0,1);
int __com=0;
int x=0;
int y=0;
tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col);
return make_tuple(__com, y-(__beta/__alpha)*x, x);
}
//frmwk wrapper pending nh release, util base
//
std::tuple<int, int, int> extended_gcd(int __alpha, int __beta)
{
if(__alpha == 0) return make_tuple(__beta,0,1);
int __com=0;
int x=0;
int y=0;
tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha);
return make_tuple(__com, y-(__beta/__alpha)*x, x);
}
<|endoftext|>
|
<commit_before>#include "stdio.h"
#include "stdlib.h"
#include <iostream>
#define MAXSTRLEN 255 // 用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1]; // 0号单元存放串的长度
void get_next(SString T,int next[]){
int i,j;
next[1]=0;
j=0;
while(i<T[0]){
printf("%d\n ??",j);
if(j == 0 || T[i]==T[j]){
++i;
++j;
next[i]=j;}
else{
j=next[j];
}
}
}
int main(){
int next[MAXSTRLEN];
SString S;
int n,i,j;
char ch;
scanf("%d",&n); // 指定要验证NEXT值的字符串个数
ch=getchar();
for(i=1;i<=n;i++)
{
ch=getchar();
for(j=1;j<=MAXSTRLEN&&(ch!='\n');j++) // 录入字符串
{
S[j]=ch;
ch=getchar();
}
S[0]=j-1; // S[0]用于存储字符串中字符个数
//printf("%s",S+1);
get_next(S,next);
printf("NEXT J is:");
for(j=1;j<=S[0];j++)
printf("%d",next[j]);
printf("\n");
}
}
<commit_msg>update uoj8591<commit_after>#include "stdio.h"
#include "stdlib.h"
#include <iostream>
#define MAXSTRLEN 255 // 用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1]; // 0号单元存放串的长度
void get_next(SString T,int next[]){
int i,j;
next[1]=0;
j=0;
printf("%d\n ??",j);
while(i<T[0]){
if(j == 0 || T[i]==T[j]){
++i;
++j;
next[i]=j;}
else{
j=next[j];
}
}
}
int main(){
int next[MAXSTRLEN];
SString S;
int n,i,j;
char ch;
scanf("%d",&n); // 指定要验证NEXT值的字符串个数
ch=getchar();
for(i=1;i<=n;i++)
{
ch=getchar();
for(j=1;j<=MAXSTRLEN&&(ch!='\n');j++) // 录入字符串
{
S[j]=ch;
ch=getchar();
}
S[0]=j-1; // S[0]用于存储字符串中字符个数
//printf("%s",S+1);
get_next(S,next);
printf("NEXT J is:");
for(j=1;j<=S[0];j++)
printf("%d",next[j]);
printf("\n");
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-Caps2.0"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "9f71e235"
# define GIT_COMMIT_DAdTE "Sun Jan 18 14:24:00 2015"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-Caps2.0"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "418187240"
# define GIT_COMMIT_DAdTE "Wed Jun 24 22:12:00 2015"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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.
*/
#include "flusspferd/xml/xml.hpp"
#include "flusspferd/xml/parse.hpp"
#include "flusspferd/xml/push_parser.hpp"
#include "flusspferd/xml/node.hpp"
#include "flusspferd/xml/document.hpp"
#include "flusspferd/xml/text.hpp"
#include "flusspferd/xml/namespace.hpp"
#include "flusspferd/xml/reference.hpp"
#include "flusspferd/xml/attribute.hpp"
#include "flusspferd/xml/processing_instruction.hpp"
#include "flusspferd/function_adapter.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/string.hpp"
using namespace flusspferd;
using namespace flusspferd::xml;
extern "C" value flusspferd_load(object container)
{
return load_xml(container);
}
object flusspferd::xml::load_xml(object container) {
local_root_scope scope;
value previous = container.get_property("XML");
if (previous.is_object())
return previous.to_object();
LIBXML_TEST_VERSION
object XML = flusspferd::create_object();
load_class<node>(XML);
load_class<document>(XML);
load_class<text>(XML);
load_class<comment>(XML);
load_class<cdata_section>(XML);
load_class<reference_>(XML);
load_class<processing_instruction>(XML);
load_class<attribute_>(XML);
load_class<namespace_>(XML);
load_class<push_parser>(XML);
create_native_function(XML, "parseBlob", &parse_blob);
create_native_function(XML, "parseFile", &parse_file);
container.define_property(
"XML",
XML,
object::read_only_property | object::dont_enumerate);
return XML;
}
<commit_msg>XML: add stub for safety I/O callbacks<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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.
*/
#include "flusspferd/xml/xml.hpp"
#include "flusspferd/xml/parse.hpp"
#include "flusspferd/xml/push_parser.hpp"
#include "flusspferd/xml/node.hpp"
#include "flusspferd/xml/document.hpp"
#include "flusspferd/xml/text.hpp"
#include "flusspferd/xml/namespace.hpp"
#include "flusspferd/xml/reference.hpp"
#include "flusspferd/xml/attribute.hpp"
#include "flusspferd/xml/processing_instruction.hpp"
#include "flusspferd/function_adapter.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/string.hpp"
#include <libxml/xmlIO.h>
using namespace flusspferd;
using namespace flusspferd::xml;
extern "C" value flusspferd_load(object container)
{
return load_xml(container);
}
static void safety_io_callbacks();
object flusspferd::xml::load_xml(object container) {
safety_io_callbacks();
local_root_scope scope;
value previous = container.get_property("XML");
if (previous.is_object())
return previous.to_object();
LIBXML_TEST_VERSION
object XML = flusspferd::create_object();
load_class<node>(XML);
load_class<document>(XML);
load_class<text>(XML);
load_class<comment>(XML);
load_class<cdata_section>(XML);
load_class<reference_>(XML);
load_class<processing_instruction>(XML);
load_class<attribute_>(XML);
load_class<namespace_>(XML);
load_class<push_parser>(XML);
create_native_function(XML, "parseBlob", &parse_blob);
create_native_function(XML, "parseFile", &parse_file);
container.define_property(
"XML",
XML,
object::read_only_property | object::dont_enumerate);
return XML;
}
static void safety_io_callbacks() {
xmlCleanupInputCallbacks();
xmlCleanupOutputCallbacks();
// TODO - add safe callbacks
}
<|endoftext|>
|
<commit_before>#include "pstream.h"
#include <iostream>
template class redi::pstreambuf;
template class redi::pstream_common<char>;
template class redi::pstream;
template class redi::ipstream;
template class redi::opstream;
template class redi::rpstream;
int main()
{
using namespace redi;
char c;
ipstream who("whoami");
if (!(who >> c))
return 1;
redi::opstream cat("cat");
if (!(cat << c))
return 2;
while (who >> c)
cat << c;
cat << '\n' << peof;
pstream fail("ghghghg", pstreambuf::pstderr);
std::string s;
if (!std::getline(fail, s))
return 3;
std::cerr << s << '\n';
rpstream who2("whoami");
if (!(who2.out() >> c))
return 4;
return 0;
}
<commit_msg>Don't use typedef names for explicit instantiation.<commit_after>#include "pstream.h"
#include <iostream>
template class redi::basic_pstreambuf<char>;
template class redi::pstream_common<char>;
template class redi::basic_pstream<char>;
template class redi::basic_ipstream<char>;
template class redi::basic_opstream<char>;
template class redi::basic_rpstream<char>;
int main()
{
using namespace redi;
char c;
ipstream who("whoami");
if (!(who >> c))
return 1;
redi::opstream cat("cat");
if (!(cat << c))
return 2;
while (who >> c)
cat << c;
cat << '\n' << peof;
pstream fail("ghghghg", pstreambuf::pstderr);
std::string s;
if (!std::getline(fail, s))
return 3;
std::cerr << s << '\n';
rpstream who2("whoami");
if (!(who2.out() >> c))
return 4;
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.