commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
ccaf5370d585824fbd9a5aa71e36c3af7848b2f6
|
test/core/test_rectangular_box_interaction.cpp
|
test/core/test_rectangular_box_interaction.cpp
|
#define BOOST_TEST_MODULE "test_recutangular_box_interaction"
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/forcefield/external/RectangularBoxInteraction.hpp>
#include <mjolnir/forcefield/external/ExcludedVolumeWallPotential.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <random>
BOOST_AUTO_TEST_CASE(PositionRestraint_Harmonic)
{
mjolnir::LoggerManager::set_default_logger(
"test_recutangular_box_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
using coordinate_type = traits_type::coordinate_type;
using boundary_type = traits_type::boundary_type;
using system_type = mjolnir::System<traits_type>;
using potential_type = mjolnir::ExcludedVolumeWallPotential<real_type>;
using interaction_type = mjolnir::RectangularBoxInteraction<traits_type, potential_type>;
auto normalize = [](const coordinate_type& v){return v / mjolnir::math::length(v);};
coordinate_type lower( 0.0, 0.0, 0.0);
coordinate_type upper(10.0, 10.0, 10.0);
interaction_type interaction(lower, upper, /*margin = */0.5,
potential_type(/*epsilon = */1.0, /* cutoff = */2.0, {
{0, 1.0}, {1, 1.0}
}));
system_type sys(2, boundary_type{});
sys.at(0).mass = 1.0;
sys.at(1).mass = 1.0;
sys.at(0).rmass = 1.0;
sys.at(1).rmass = 1.0;
sys.at(0).position = coordinate_type( 1.0, 9.0, 1.0);
sys.at(1).position = coordinate_type( 9.0, 1.0, 9.0);
sys.at(0).velocity = coordinate_type( 0.0, 0.0, 0.0);
sys.at(1).velocity = coordinate_type( 0.0, 0.0, 0.0);
sys.at(0).force = coordinate_type( 0.0, 0.0, 0.0);
sys.at(1).force = coordinate_type( 0.0, 0.0, 0.0);
sys.at(0).name = "X";
sys.at(1).name = "X";
sys.at(0).group = "NONE";
sys.at(1).group = "NONE";
std::mt19937 mt(123456789);
std::uniform_real_distribution<real_type> uni(-1.0, 1.0);
std::normal_distribution<real_type> gauss(0.0, 1.0);
for(int i = 0; i < 10000; ++i)
{
sys.at(0).position = coordinate_type( 1.0, 9.0, 1.0);
sys.at(1).position = coordinate_type( 9.0, 1.0, 9.0);
// move particles a bit, randomly. and reset forces.
for(std::size_t idx=0; idx<sys.size(); ++idx)
{
sys.position(idx) += coordinate_type(0.01 * uni(mt), 0.01 * uni(mt), 0.01 * uni(mt));
sys.force(idx) = coordinate_type(0.0, 0.0, 0.0);
}
const system_type init = sys;
// compare between numerical diff and force implementation
constexpr real_type tol = 1e-4;
constexpr real_type dr = 1e-5;
for(std::size_t idx=0; idx<sys.size(); ++idx)
{
{
// ----------------------------------------------------------------
// reset positions
sys = init;
// calc U(x-dx)
const auto E0 = interaction.calc_energy(sys);
mjolnir::math::X(sys.position(idx)) += dr;
// calc F(x)
interaction.calc_force(sys);
mjolnir::math::X(sys.position(idx)) += dr;
// calc U(x+dx)
const auto E1 = interaction.calc_energy(sys);
// central difference
const auto dE = (E1 - E0) * 0.5;
BOOST_TEST(-dE / dr == mjolnir::math::X(sys.force(idx)),
boost::test_tools::tolerance(tol));
}
{
// ----------------------------------------------------------------
// reset positions
sys = init;
// calc U(x-dx)
const auto E0 = interaction.calc_energy(sys);
mjolnir::math::Y(sys.position(idx)) += dr;
// calc F(x)
interaction.calc_force(sys);
mjolnir::math::Y(sys.position(idx)) += dr;
// calc U(x+dx)
const auto E1 = interaction.calc_energy(sys);
// central difference
const auto dE = (E1 - E0) * 0.5;
BOOST_TEST(-dE / dr == mjolnir::math::Y(sys.force(idx)),
boost::test_tools::tolerance(tol));
}
{
// ----------------------------------------------------------------
// reset positions
sys = init;
// calc U(x-dx)
const auto E0 = interaction.calc_energy(sys);
mjolnir::math::Z(sys.position(idx)) += dr;
// calc F(x)
interaction.calc_force(sys);
mjolnir::math::Z(sys.position(idx)) += dr;
// calc U(x+dx)
const auto E1 = interaction.calc_energy(sys);
// central difference
const auto dE = (E1 - E0) * 0.5;
BOOST_TEST(-dE / dr == mjolnir::math::Z(sys.force(idx)),
boost::test_tools::tolerance(tol));
}
}
}
}
|
#define BOOST_TEST_MODULE "test_recutangular_box_interaction"
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/forcefield/external/RectangularBoxInteraction.hpp>
#include <mjolnir/forcefield/external/ExcludedVolumeWallPotential.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <random>
BOOST_AUTO_TEST_CASE(PositionRestraint_Harmonic)
{
mjolnir::LoggerManager::set_default_logger(
"test_recutangular_box_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
using coordinate_type = traits_type::coordinate_type;
using boundary_type = traits_type::boundary_type;
using system_type = mjolnir::System<traits_type>;
using potential_type = mjolnir::ExcludedVolumeWallPotential<real_type>;
using interaction_type = mjolnir::RectangularBoxInteraction<traits_type, potential_type>;
coordinate_type lower( 0.0, 0.0, 0.0);
coordinate_type upper(10.0, 10.0, 10.0);
interaction_type interaction(lower, upper, /*margin = */0.5,
potential_type(/*epsilon = */1.0, /* cutoff = */2.0, {
{0, 1.0}, {1, 1.0}
}));
system_type sys(2, boundary_type{});
sys.at(0).mass = 1.0;
sys.at(1).mass = 1.0;
sys.at(0).rmass = 1.0;
sys.at(1).rmass = 1.0;
sys.at(0).position = coordinate_type( 1.0, 9.0, 1.0);
sys.at(1).position = coordinate_type( 9.0, 1.0, 9.0);
sys.at(0).velocity = coordinate_type( 0.0, 0.0, 0.0);
sys.at(1).velocity = coordinate_type( 0.0, 0.0, 0.0);
sys.at(0).force = coordinate_type( 0.0, 0.0, 0.0);
sys.at(1).force = coordinate_type( 0.0, 0.0, 0.0);
sys.at(0).name = "X";
sys.at(1).name = "X";
sys.at(0).group = "NONE";
sys.at(1).group = "NONE";
std::mt19937 mt(123456789);
std::uniform_real_distribution<real_type> uni(-1.0, 1.0);
std::normal_distribution<real_type> gauss(0.0, 1.0);
for(int i = 0; i < 10000; ++i)
{
sys.at(0).position = coordinate_type( 1.0, 9.0, 1.0);
sys.at(1).position = coordinate_type( 9.0, 1.0, 9.0);
// move particles a bit, randomly. and reset forces.
for(std::size_t idx=0; idx<sys.size(); ++idx)
{
sys.position(idx) += coordinate_type(0.01 * uni(mt), 0.01 * uni(mt), 0.01 * uni(mt));
sys.force(idx) = coordinate_type(0.0, 0.0, 0.0);
}
const system_type init = sys;
// compare between numerical diff and force implementation
constexpr real_type tol = 1e-4;
constexpr real_type dr = 1e-5;
for(std::size_t idx=0; idx<sys.size(); ++idx)
{
{
// ----------------------------------------------------------------
// reset positions
sys = init;
// calc U(x-dx)
const auto E0 = interaction.calc_energy(sys);
mjolnir::math::X(sys.position(idx)) += dr;
// calc F(x)
interaction.calc_force(sys);
mjolnir::math::X(sys.position(idx)) += dr;
// calc U(x+dx)
const auto E1 = interaction.calc_energy(sys);
// central difference
const auto dE = (E1 - E0) * 0.5;
BOOST_TEST(-dE / dr == mjolnir::math::X(sys.force(idx)),
boost::test_tools::tolerance(tol));
}
{
// ----------------------------------------------------------------
// reset positions
sys = init;
// calc U(x-dx)
const auto E0 = interaction.calc_energy(sys);
mjolnir::math::Y(sys.position(idx)) += dr;
// calc F(x)
interaction.calc_force(sys);
mjolnir::math::Y(sys.position(idx)) += dr;
// calc U(x+dx)
const auto E1 = interaction.calc_energy(sys);
// central difference
const auto dE = (E1 - E0) * 0.5;
BOOST_TEST(-dE / dr == mjolnir::math::Y(sys.force(idx)),
boost::test_tools::tolerance(tol));
}
{
// ----------------------------------------------------------------
// reset positions
sys = init;
// calc U(x-dx)
const auto E0 = interaction.calc_energy(sys);
mjolnir::math::Z(sys.position(idx)) += dr;
// calc F(x)
interaction.calc_force(sys);
mjolnir::math::Z(sys.position(idx)) += dr;
// calc U(x+dx)
const auto E1 = interaction.calc_energy(sys);
// central difference
const auto dE = (E1 - E0) * 0.5;
BOOST_TEST(-dE / dr == mjolnir::math::Z(sys.force(idx)),
boost::test_tools::tolerance(tol));
}
}
}
}
|
remove unused lambda
|
fix: remove unused lambda
|
C++
|
mit
|
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
|
2ce3c8485d2cea310cb84d7b5983293ddf5e288a
|
libsrc/XdmfValuesBinary.cxx
|
libsrc/XdmfValuesBinary.cxx
|
/*******************************************************************/
/* XDMF */
/* eXtensible Data Model and Format */
/* */
/* Id : Id */
/* Date : $Date$ */
/* Version : $Revision$ */
/* */
/* Author:Kenji Takizawa (Team for Advanced Flow Simulation and Modeling) */
/* */
/* Copyright @ 2008 US Army Research Laboratory */
/* All Rights Reserved */
/* See Copyright.txt or http://www.arl.hpc.mil/ice 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 notice */
/* for more information. */
/* */
/*******************************************************************/
#include "XdmfValuesBinary.h"
#include "XdmfDataStructure.h"
#include "XdmfArray.h"
//#include "XdmfHDF.h"
#include "XdmfDOM.h"
#include <exception>
#ifdef XDMF_USE_GZIP
#include "gzstream.h"
#endif
#ifdef XDMF_USE_BZIP2
#include "bz2stream.h"
#endif
//#include <sys/stat.h>
//#include <cassert>
template<size_t T>
struct ByteSwaper {
static inline void swap(void*p){}
static inline void swap(void*p,XdmfInt64 length){
char* data = static_cast<char*>(p);
for(XdmfInt64 i=0;i<length;++i, data+=T){
ByteSwaper<T>::swap(data);
}
}
};
template<>
void ByteSwaper<2>::swap(void*p){
char one_byte;
char* data = static_cast<char*>(p);
one_byte = data[0]; data[0] = data[1]; data[1] = one_byte;
};
template<>
void ByteSwaper<4>::swap(void*p){
char one_byte;
char* data = static_cast<char*>(p);
one_byte = data[0]; data[0] = data[3]; data[3] = one_byte;
one_byte = data[1]; data[1] = data[2]; data[2] = one_byte;
};
template<>
void ByteSwaper<8>::swap(void*p){
char one_byte;
char* data = static_cast<char*>(p);
one_byte = data[0]; data[0] = data[7]; data[7] = one_byte;
one_byte = data[1]; data[1] = data[6]; data[6] = one_byte;
one_byte = data[2]; data[2] = data[5]; data[5] = one_byte;
one_byte = data[3]; data[3] = data[4]; data[4] = one_byte;
};
void XdmfValuesBinary::byteSwap(XdmfArray * RetArray){
if(needByteSwap()){
switch(RetArray->GetElementSize()){
case 1:
break;
case 2:
ByteSwaper<2>::swap(RetArray->GetDataPointer(),RetArray->GetNumberOfElements());
break;
case 4:
ByteSwaper<4>::swap(RetArray->GetDataPointer(),RetArray->GetNumberOfElements());
break;
case 8:
ByteSwaper<8>::swap(RetArray->GetDataPointer(),RetArray->GetNumberOfElements());
break;
default:
break;
}
}
}
size_t XdmfValuesBinary::getSeek(){
if(this->Seek==NULL)return 0;
return static_cast<size_t>(atoi(this->Seek));
}
enum XdmfValuesBinary::CompressionType XdmfValuesBinary::getCompressionType(){
if(this->Compression==NULL||XDMF_WORD_CMP(Compression, "Raw")){
return Raw;
}
if(XDMF_WORD_CMP(Compression, "Zlib")){
return Zlib;
}
if(XDMF_WORD_CMP(Compression, "BZip2")){
return BZip2;
}
return Raw;
}
XdmfValuesBinary::XdmfValuesBinary() {
this->Endian = NULL;
this->Seek = NULL;
this->Compression = NULL;
this->SetFormat(XDMF_FORMAT_BINARY);
}
XdmfValuesBinary::~XdmfValuesBinary() {
}
XdmfArray *
XdmfValuesBinary::Read(XdmfArray *anArray){
if(!this->DataDesc){
XdmfErrorMessage("DataDesc has not been set");
return(NULL);
}
XdmfArray *RetArray = anArray;
// Allocate anArray if Necessary
if(!RetArray){
RetArray = new XdmfArray();
RetArray->CopyType(this->DataDesc);
RetArray->CopyShape(this->DataDesc);
}
XdmfDebug("Accessing Binary CDATA");
{
XdmfConstString Value = this->Get("Endian");
if(Value){
this->SetEndian(Value);
}else{
this->Endian = NULL;
}
}
{
XdmfConstString Value = this->Get("Seek");
if(Value){
this->SetSeek(Value);
}else{
this->Seek = NULL;
}
}
{
XdmfConstString Value = this->Get("Compression");
if(Value){
this->SetCompression(Value);
}else{
this->Compression = NULL;
}
}
XdmfString DataSetName = 0;
XDMF_STRING_DUPLICATE(DataSetName, this->Get("CDATA"));
XDMF_WORD_TRIM(DataSetName);
XdmfDebug("Opening Binary Data for Reading : " << DataSetName);
XdmfInt64 dims[XDMF_MAX_DIMENSION];
XdmfInt32 rank = this->DataDesc->GetShape(dims);
XdmfInt64 total = 1;
for(XdmfInt32 i=0;i<rank;++i){
total *= dims[i];
}
XdmfDebug("Data Size : " << total);
XdmfDebug("Size[Byte]: " << RetArray->GetCoreLength());
//check
// struct stat buf;
// stat(DataSetName, &buf);
// assert(buf.st_size == RetArray->GetCoreLength());
//ifstream fs(DataSetName,std::ios::binary);
if( RetArray->GetDataPointer() == NULL ){
XdmfErrorMessage("Memory Object Array has no data storage");
return( NULL );
}
istream * fs = NULL;
char * path = new char [ strlen(this->DOM->GetWorkingDirectory())+strlen(DataSetName) + 1 ];
strcpy(path, this->DOM->GetWorkingDirectory());
strcpy(path+strlen(this->DOM->GetWorkingDirectory()), DataSetName);
try{
size_t seek = this->getSeek();
switch(getCompressionType()){
case Zlib:
XdmfDebug("Compression: Zlib");
#ifdef XDMF_USE_GZIP
fs = new igzstream(path, std::ios::binary|std::ios::in);
if(seek!=0){
XdmfDebug("Seek has not supported with Zlib.");
}
break;
#else
XdmfDebug("GZip Lib is needed.");
#endif
case BZip2:
XdmfDebug("Compression: Bzip2");
#ifdef XDMF_USE_BZIP2
fs = new ibz2stream(path);//, std::ios::binary|std::ios::in);
if(seek!=0){
XdmfDebug("Seek has not supported with Bzip2.");
}
break;
#else
XdmfDebug("BZIP2 LIBRARY IS NEEDED.");
#endif
default:
fs = new ifstream(path, std::ios::binary);
fs->seekg(seek);
XdmfDebug("Seek: " << seek);
break;
}
fs->exceptions( ios::failbit | ios::badbit );
if(!fs->good()){
XdmfErrorMessage("Can't Open File " << DataSetName);
//return(NULL);
}
fs->read(reinterpret_cast<char*>(RetArray->GetDataPointer()), RetArray->GetCoreLength());
} catch( std::exception& ){
delete fs;
delete path;
return( NULL );
}
//fs->close();?
delete fs;
delete path;
byteSwap(RetArray);
return RetArray;
}
XdmfInt32
XdmfValuesBinary::Write(XdmfArray *anArray, XdmfConstString aHeavyDataSetName){
if(!aHeavyDataSetName) aHeavyDataSetName = this->GetHeavyDataSetName();
if(anArray->GetHeavyDataSetName()){
aHeavyDataSetName = (XdmfConstString)anArray->GetHeavyDataSetName();
}else{
return(XDMF_FAIL);
}
XdmfDebug("Writing Values to " << aHeavyDataSetName);
if(!this->DataDesc ){
XdmfErrorMessage("DataDesc has not been set");
return(XDMF_FAIL);
}
if(!anArray){
XdmfErrorMessage("Array to Write is NULL");
return(XDMF_FAIL);
}
if( anArray->GetDataPointer() == NULL ){
XdmfErrorMessage("Memory Object Array has no data storage");
return(XDMF_FAIL);
}
char* hds;
XDMF_STRING_DUPLICATE(hds, aHeavyDataSetName);
XDMF_WORD_TRIM( hds );
this->Set("CDATA", hds);
byteSwap(anArray);
ostream * fs = NULL;
char * path = new char [ strlen(this->DOM->GetWorkingDirectory())+strlen(aHeavyDataSetName) + 1 ];
strcpy(path, this->DOM->GetWorkingDirectory());
strcpy(path+strlen(this->DOM->GetWorkingDirectory()), aHeavyDataSetName);
try{
//ofstream fs(aHeavyDataSetName,std::ios::binary);
switch(getCompressionType()){
case Zlib:
XdmfDebug("Compression: ZLIB");
#ifdef XDMF_USE_GZIP
// fs = gzip(fs);
fs = new ogzstream(path, std::ios::binary|std::ios::out);
break;
#else
XdmfDebug("GZIP LIBRARY IS NEEDED.");
#endif
case BZip2:
XdmfDebug("Compression: BZIP2");
#ifdef XDMF_USE_BZIP2
fs = new obz2stream(path);//, std::ios::binary|std::ios::out);
break;
#else
XdmfDebug("BZIP2 LIBRARY IS NEEDED.");
#endif
default:
fs = new ofstream(path, std::ios::binary);
//fs->seekg(seek);
//XdmfDebug("Seek: " << seek);
break;
}
fs->exceptions( ios::failbit | ios::badbit );
if(!fs->good()){
XdmfErrorMessage("Can't Open File " << aHeavyDataSetName);
}
fs->write(reinterpret_cast<char*>(anArray->GetDataPointer()), anArray->GetCoreLength());
}catch( std::exception& ){
//fs.close();
byteSwap(anArray);
delete [] fs;
delete [] hds;
delete [] path;
return(XDMF_FAIL);
}
byteSwap(anArray);
delete [] fs;
delete [] hds;
delete [] path;
return(XDMF_SUCCESS);
}
#ifdef CMAKE_WORDS_BIGENDIAN
bool XdmfValuesBinary::needByteSwap(){
return XDMF_WORD_CMP(Endian, "Little");
}
#else
bool XdmfValuesBinary::needByteSwap(){
return XDMF_WORD_CMP(Endian, "Big");
}
#endif
// vim: expandtab sw=4 :
|
/*******************************************************************/
/* XDMF */
/* eXtensible Data Model and Format */
/* */
/* Id : Id */
/* Date : $Date$ */
/* Version : $Revision$ */
/* */
/* Author:Kenji Takizawa (Team for Advanced Flow Simulation and Modeling) */
/* */
/* Copyright @ 2008 US Army Research Laboratory */
/* All Rights Reserved */
/* See Copyright.txt or http://www.arl.hpc.mil/ice 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 notice */
/* for more information. */
/* */
/*******************************************************************/
#include "XdmfValuesBinary.h"
#include "XdmfDataStructure.h"
#include "XdmfArray.h"
//#include "XdmfHDF.h"
#include "XdmfDOM.h"
#include <exception>
#include <cassert>
#ifdef XDMF_USE_GZIP
#include "gzstream.h"
#endif
#ifdef XDMF_USE_BZIP2
#include "bz2stream.h"
#endif
//#include <sys/stat.h>
//#include <cassert>
//Internal Classes
template<size_t T>
struct ByteSwaper {
static inline void swap(void*p){}
static inline void swap(void*p,XdmfInt64 length){
char* data = static_cast<char*>(p);
for(XdmfInt64 i=0;i<length;++i, data+=T){
ByteSwaper<T>::swap(data);
}
}
};
template<>
void ByteSwaper<2>::swap(void*p){
char one_byte;
char* data = static_cast<char*>(p);
one_byte = data[0]; data[0] = data[1]; data[1] = one_byte;
};
template<>
void ByteSwaper<4>::swap(void*p){
char one_byte;
char* data = static_cast<char*>(p);
one_byte = data[0]; data[0] = data[3]; data[3] = one_byte;
one_byte = data[1]; data[1] = data[2]; data[2] = one_byte;
};
template<>
void ByteSwaper<8>::swap(void*p){
char one_byte;
char* data = static_cast<char*>(p);
one_byte = data[0]; data[0] = data[7]; data[7] = one_byte;
one_byte = data[1]; data[1] = data[6]; data[6] = one_byte;
one_byte = data[2]; data[2] = data[5]; data[5] = one_byte;
one_byte = data[3]; data[3] = data[4]; data[4] = one_byte;
};
void XdmfValuesBinary::byteSwap(XdmfArray * RetArray){
if(needByteSwap()){
switch(RetArray->GetElementSize()){
case 1:
break;
case 2:
ByteSwaper<2>::swap(RetArray->GetDataPointer(),RetArray->GetNumberOfElements());
break;
case 4:
ByteSwaper<4>::swap(RetArray->GetDataPointer(),RetArray->GetNumberOfElements());
break;
case 8:
ByteSwaper<8>::swap(RetArray->GetDataPointer(),RetArray->GetNumberOfElements());
break;
default:
break;
}
}
}
class HyperSlabReader:public XdmfObject{//
XdmfInt64 ncontiguous;//byte
XdmfInt64 start[XDMF_MAX_DIMENSION];//byte
XdmfInt64 stride[XDMF_MAX_DIMENSION];//byte
XdmfInt64 last[XDMF_MAX_DIMENSION];//byte
XdmfInt64 count[XDMF_MAX_DIMENSION];//size
XdmfInt64 rank;
void toTotal(const XdmfInt64 * dims, XdmfInt32 byte, XdmfInt64 * data){
data[this->rank-1] *= byte;
for(XdmfInt32 i = 1; i< this->rank; ++i){
for(XdmfInt32 j=i; j<this->rank; ++j){
data[i-1] *= dims[j];
}
data[i-1] *= byte;
}
}
void read(XdmfInt32 k, char *& pointer, istream &is){
is.seekg(this->start[k], std::ios::cur);
//XdmfDebug("Skip: " << this->start[k]<<", "<<k );
if(k==rank-1){
XdmfDebug("Read: " << ncontiguous);
is.read(pointer, ncontiguous);
pointer += ncontiguous;
for(XdmfInt64 i=1,l=this->count[k];i<l;++i){
//XdmfDebug("Skip: " << this->stride[k] <<", " << k );
is.seekg(this->stride[k], std::ios::cur);
is.read(pointer, ncontiguous);
//XdmfDebug("Read: " << ncontiguous);
pointer += ncontiguous;
}
}else{
read(k+1,pointer,is);
for(XdmfInt64 i=1,l=this->count[k];i<l;++i){
is.seekg(this->stride[k], std::ios::cur);
//XdmfDebug("Skip: " << this->stride[k] << ", "<< k);
read(k+1,pointer,is);
}
}
//XdmfDebug("Skip: " << this->last[k] << ", " << k);
is.seekg(this->last[k], std::ios::cur);
}
public:
HyperSlabReader(XdmfInt32 rank, XdmfInt32 byte, const XdmfInt64 * dims, const XdmfInt64 * start, const XdmfInt64 * stride, const XdmfInt64 * count){
assert(rank>0 && rank<XDMF_MAX_DIMENSION);
this->rank = rank;
XdmfInt64 d[XDMF_MAX_DIMENSION];
for(XdmfInt32 i =0;i<rank;++i){
this->start[i] = start[i];
this->stride[i] = stride[i]-1;
this->count[i] = count[i];
d[i] = dims[i];
}
//reduce rank
for(XdmfInt32 i =rank-1;i>0;--i){
if(this->start[i]==0 && this->stride[i]==0 && this->count[i]==dims[i]){
--this->rank;
}else{
break;
}
}
if(this->rank != rank){
XdmfDebug("Reduce Rank: " << rank << " to " << this->rank);
XdmfInt32 k = this->rank-1;
for(XdmfInt32 i = this->rank;i<rank;++i){
byte *= count[i];
}
}
for(XdmfInt32 i =0;i<this->rank;++i){
this->last[i] = d[i] - (this->start[i] + (this->stride[i]+1)*(this->count[i]-1) + 1);
}
toTotal(d,byte, this->start);
toTotal(d,byte, this->stride);
toTotal(d,byte, this->last);
ncontiguous=byte;
if(this->stride[this->rank-1]==0){
ncontiguous *= this->count[this->rank-1];
this->count[this->rank-1] = 1;
}
XdmfDebug("Contiguous byte: " << ncontiguous);
}
~HyperSlabReader(){
}
void read(char * pointer, istream &is){
read(static_cast<XdmfInt32>(0),pointer,is);
}
};
size_t XdmfValuesBinary::getSeek(){
if(this->Seek==NULL)return 0;
return static_cast<size_t>(atoi(this->Seek));
}
enum XdmfValuesBinary::CompressionType XdmfValuesBinary::getCompressionType(){
if(this->Compression==NULL||XDMF_WORD_CMP(Compression, "Raw")){
return Raw;
}
if(XDMF_WORD_CMP(Compression, "Zlib")){
return Zlib;
}
if(XDMF_WORD_CMP(Compression, "BZip2")){
return BZip2;
}
return Raw;
}
XdmfValuesBinary::XdmfValuesBinary() {
this->Endian = NULL;
this->Seek = NULL;
this->Compression = NULL;
this->SetFormat(XDMF_FORMAT_BINARY);
}
XdmfValuesBinary::~XdmfValuesBinary() {
}
XdmfArray *
XdmfValuesBinary::Read(XdmfArray *anArray){
if(!this->DataDesc){
XdmfErrorMessage("DataDesc has not been set");
return(NULL);
}
XdmfArray *RetArray = anArray;
// Allocate anArray if Necessary
if(!RetArray){
RetArray = new XdmfArray();
RetArray->CopyType(this->DataDesc);
RetArray->CopyShape(this->DataDesc);
RetArray->CopySelection(this->DataDesc);
RetArray->Allocate();
}
XdmfDebug("Accessing Binary CDATA");
{
XdmfConstString Value = this->Get("Endian");
if(Value){
this->SetEndian(Value);
}else{
this->Endian = NULL;
}
}
{
XdmfConstString Value = this->Get("Seek");
if(Value){
this->SetSeek(Value);
}else{
this->Seek = NULL;
}
}
{
XdmfConstString Value = this->Get("Compression");
if(Value){
this->SetCompression(Value);
}else{
this->Compression = NULL;
}
}
XdmfString DataSetName = 0;
XDMF_STRING_DUPLICATE(DataSetName, this->Get("CDATA"));
XDMF_WORD_TRIM(DataSetName);
XdmfDebug("Opening Binary Data for Reading : " << DataSetName);
XdmfInt64 dims[XDMF_MAX_DIMENSION];
XdmfInt32 rank = this->DataDesc->GetShape(dims);
XdmfInt64 total = 1;
for(XdmfInt32 i=0;i<rank;++i){
total *= dims[i];
}
XdmfDebug("Data Size : " << total);
XdmfInt32 byte = RetArray->GetCoreLength()/total;
XdmfDebug("Size[Byte]: " << RetArray->GetCoreLength());
XdmfDebug(" Byte " << RetArray->GetElementSize());
//check
// struct stat buf;
// stat(DataSetName, &buf);
// assert(buf.st_size == RetArray->GetCoreLength());
//ifstream fs(DataSetName,std::ios::binary);
if( RetArray->GetDataPointer() == NULL ){
XdmfErrorMessage("Memory Object Array has no data storage");
return( NULL );
}
istream * fs = NULL;
char * path = new char [ strlen(this->DOM->GetWorkingDirectory())+strlen(DataSetName) + 1 ];
strcpy(path, this->DOM->GetWorkingDirectory());
strcpy(path+strlen(this->DOM->GetWorkingDirectory()), DataSetName);
try{
size_t seek = this->getSeek();
switch(getCompressionType()){
case Zlib:
XdmfDebug("Compression: Zlib");
#ifdef XDMF_USE_GZIP
fs = new igzstream(path, std::ios::binary|std::ios::in);
if(seek!=0){
XdmfDebug("Seek has not supported with Zlib.");
}
break;
#else
XdmfDebug("GZip Lib is needed.");
#endif
case BZip2:
XdmfDebug("Compression: Bzip2");
#ifdef XDMF_USE_BZIP2
fs = new ibz2stream(path);//, std::ios::binary|std::ios::in);
if(seek!=0){
XdmfDebug("Seek has not supported with Bzip2.");
}
break;
#else
XdmfDebug("BZIP2 LIBRARY IS NEEDED.");
#endif
default:
fs = new ifstream(path, std::ios::binary);
fs->seekg(seek);
XdmfDebug("Seek: " << seek);
break;
}
fs->exceptions( ios::failbit | ios::badbit );
if(!fs->good()){
XdmfErrorMessage("Can't Open File " << DataSetName);
//return(NULL);
}
if( this->DataDesc->GetSelectionType() == XDMF_HYPERSLAB ){
XdmfDebug("Hyperslab data");
XdmfInt32 Rank;
XdmfInt64 Start[ XDMF_MAX_DIMENSION ];
XdmfInt64 Stride[ XDMF_MAX_DIMENSION ];
XdmfInt64 Count[ XDMF_MAX_DIMENSION ];
Rank = this->DataDesc->GetHyperSlab( Start, Stride, Count );
HyperSlabReader wrapper(Rank,RetArray->GetElementSize(),dims,Start,Stride, Count);
wrapper.read(reinterpret_cast<char*>(RetArray->GetDataPointer()), *fs);
}else{
XdmfDebug("Regular data");
fs->read(reinterpret_cast<char*>(RetArray->GetDataPointer()), RetArray->GetCoreLength());
}
} catch( std::exception& e){
XdmfErrorMessage(e.what());
delete fs;
delete path;
return( NULL );
}
//fs->close();?
delete fs;
delete path;
byteSwap(RetArray);
return RetArray;
}
XdmfInt32
XdmfValuesBinary::Write(XdmfArray *anArray, XdmfConstString aHeavyDataSetName){
if(!aHeavyDataSetName) aHeavyDataSetName = this->GetHeavyDataSetName();
if(anArray->GetHeavyDataSetName()){
aHeavyDataSetName = (XdmfConstString)anArray->GetHeavyDataSetName();
}else{
return(XDMF_FAIL);
}
XdmfDebug("Writing Values to " << aHeavyDataSetName);
if(!this->DataDesc ){
XdmfErrorMessage("DataDesc has not been set");
return(XDMF_FAIL);
}
if(!anArray){
XdmfErrorMessage("Array to Write is NULL");
return(XDMF_FAIL);
}
if( anArray->GetDataPointer() == NULL ){
XdmfErrorMessage("Memory Object Array has no data storage");
return(XDMF_FAIL);
}
char* hds;
XDMF_STRING_DUPLICATE(hds, aHeavyDataSetName);
XDMF_WORD_TRIM( hds );
this->Set("CDATA", hds);
byteSwap(anArray);
ostream * fs = NULL;
char * path = new char [ strlen(this->DOM->GetWorkingDirectory())+strlen(aHeavyDataSetName) + 1 ];
strcpy(path, this->DOM->GetWorkingDirectory());
strcpy(path+strlen(this->DOM->GetWorkingDirectory()), aHeavyDataSetName);
try{
//ofstream fs(aHeavyDataSetName,std::ios::binary);
switch(getCompressionType()){
case Zlib:
XdmfDebug("Compression: ZLIB");
#ifdef XDMF_USE_GZIP
// fs = gzip(fs);
fs = new ogzstream(path, std::ios::binary|std::ios::out);
break;
#else
XdmfDebug("GZIP LIBRARY IS NEEDED.");
#endif
case BZip2:
XdmfDebug("Compression: BZIP2");
#ifdef XDMF_USE_BZIP2
fs = new obz2stream(path);//, std::ios::binary|std::ios::out);
break;
#else
XdmfDebug("BZIP2 LIBRARY IS NEEDED.");
#endif
default:
fs = new ofstream(path, std::ios::binary);
//fs->seekg(seek);
//XdmfDebug("Seek: " << seek);
break;
}
fs->exceptions( ios::failbit | ios::badbit );
if(!fs->good()){
XdmfErrorMessage("Can't Open File " << aHeavyDataSetName);
}
fs->write(reinterpret_cast<char*>(anArray->GetDataPointer()), anArray->GetCoreLength());
}catch( std::exception& ){
//fs.close();
byteSwap(anArray);
delete [] fs;
delete [] hds;
delete [] path;
return(XDMF_FAIL);
}
byteSwap(anArray);
delete [] fs;
delete [] hds;
delete [] path;
return(XDMF_SUCCESS);
}
#ifdef CMAKE_WORDS_BIGENDIAN
bool XdmfValuesBinary::needByteSwap(){
return XDMF_WORD_CMP(Endian, "Little");
}
#else
bool XdmfValuesBinary::needByteSwap(){
return XDMF_WORD_CMP(Endian, "Big");
}
#endif
// vim: expandtab sw=4 :
|
apply Kenji's hyperslab patch
|
apply Kenji's hyperslab patch
|
C++
|
bsd-3-clause
|
cjh1/Xdmf2,cjh1/Xdmf2,cjh1/Xdmf2
|
fbb445358039d86a06142cae87e1bf33ca9e053e
|
test/unit/math/mix/fun/quad_form_diag_test.cpp
|
test/unit/math/mix/fun/quad_form_diag_test.cpp
|
#include <test/unit/math/test_ad.hpp>
TEST(MathMixMatFun, quadFormDiag) {
auto f = [](const auto& x, const auto& y) {
return stan::math::quad_form_diag(x, y);
};
Eigen::MatrixXd m00(0, 0);
Eigen::VectorXd v0(0);
Eigen::MatrixXd m11(1, 1);
m11 << 1;
Eigen::VectorXd v1(1);
v1 << 2;
Eigen::MatrixXd m22(2, 2);
m22 << 2, 3, 4, 5;
Eigen::VectorXd v2(2);
v2 << 100, 10;
Eigen::MatrixXd m33(3, 3);
m33 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
Eigen::VectorXd v3(3);
v3 << 1, 2, 3;
// matched sizes
stan::test::expect_ad(f, m00, v0);
stan::test::expect_ad(f, m11, v1);
stan::test::expect_ad(f, m22, v2);
stan::test::expect_ad(f, m33, v3);
// exceptions from mismached sizes
stan::test::expect_ad(f, m33, v2);
stan::test::expect_ad(f, m22, v3);
}
|
#include <test/unit/math/test_ad.hpp>
TEST(MathMixMatFun, quadFormDiag) {
using stan::test::relative_tolerance;
auto f = [](const auto& x, const auto& y) {
return stan::math::quad_form_diag(x, y);
};
Eigen::MatrixXd m00(0, 0);
Eigen::VectorXd v0(0);
Eigen::MatrixXd m11(1, 1);
m11 << 1;
Eigen::VectorXd v1(1);
v1 << 2;
Eigen::MatrixXd m22(2, 2);
m22 << 2, 3, 4, 5;
Eigen::VectorXd v2(2);
v2 << 100, 10;
Eigen::MatrixXd m33(3, 3);
m33 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
Eigen::VectorXd v3(3);
v3 << 1, 2, 3;
stan::test::ad_tolerances tols;
tols.hessian_hessian_ = relative_tolerance(5e-4, 1e-3);
tols.hessian_fvar_hessian_ = relative_tolerance(5e-4, 1e-3);
// matched sizes
stan::test::expect_ad(f, m00, v0);
stan::test::expect_ad(f, m11, v1);
stan::test::expect_ad(f, m22, v2);
stan::test::expect_ad(f, m33, v3);
// exceptions from mismached sizes
stan::test::expect_ad(f, m33, v2);
stan::test::expect_ad(f, m22, v3);
}
|
Increase tolerance in quad_form_diag_test
|
Increase tolerance in quad_form_diag_test
|
C++
|
bsd-3-clause
|
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
|
8157b81b68b7f267542e65c140147df8f5434c8a
|
src/compiler/build_tables/lex_table_builder.cc
|
src/compiler/build_tables/lex_table_builder.cc
|
#include "compiler/build_tables/lex_table_builder.h"
#include <climits>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "compiler/build_tables/lex_conflict_manager.h"
#include "compiler/build_tables/lex_item.h"
#include "compiler/parse_table.h"
#include "compiler/lexical_grammar.h"
#include "compiler/rule.h"
namespace tree_sitter {
namespace build_tables {
using std::map;
using std::pair;
using std::set;
using std::string;
using std::vector;
using std::unordered_map;
using std::unique_ptr;
using rules::Rule;
using rules::Blank;
using rules::Choice;
using rules::CharacterSet;
using rules::Repeat;
using rules::Symbol;
using rules::Metadata;
using rules::Seq;
class StartingCharacterAggregator {
public:
void apply(const Rule &rule) {
rule.match(
[this](const Seq &sequence) {
apply(*sequence.left);
},
[this](const rules::Choice &rule) {
for (const auto &element : rule.elements) {
apply(element);
}
},
[this](const rules::Repeat &rule) {
apply(*rule.rule);
},
[this](const rules::Metadata &rule) {
apply(*rule.rule);
},
[this](const rules::CharacterSet &rule) {
result.add_set(rule);
},
[this](const rules::Blank) {},
[](auto) {}
);
}
CharacterSet result;
};
class LexTableBuilderImpl : public LexTableBuilder {
LexTable lex_table;
const LexicalGrammar grammar;
vector<Rule> separator_rules;
CharacterSet separator_start_characters;
CharacterSet token_start_characters;
LexConflictManager conflict_manager;
unordered_map<LexItemSet, LexStateId> lex_state_ids;
public:
vector<bool> shadowed_token_indices;
LexTableBuilderImpl(const LexicalGrammar &grammar) : grammar(grammar) {
StartingCharacterAggregator separator_character_aggregator;
for (const auto &rule : grammar.separators) {
separator_rules.push_back(Repeat{rule});
separator_character_aggregator.apply(rule);
}
separator_rules.push_back(Blank{});
separator_start_characters = separator_character_aggregator.result;
StartingCharacterAggregator token_start_character_aggregator;
for (const auto &variable : grammar.variables) {
token_start_character_aggregator.apply(variable.rule);
}
token_start_characters = token_start_character_aggregator.result;
token_start_characters
.exclude('a', 'z')
.exclude('A', 'Z')
.exclude('0', '9')
.exclude('_')
.exclude('$');
shadowed_token_indices.resize(grammar.variables.size());
}
LexTable build(ParseTable *parse_table) {
for (ParseState &parse_state : parse_table->states) {
parse_state.lex_state_id = add_lex_state(
item_set_for_terminals(parse_state.terminal_entries)
);
}
mark_fragile_tokens(parse_table);
remove_duplicate_lex_states(parse_table);
return lex_table;
}
bool detect_conflict(Symbol::Index left, Symbol::Index right) {
clear();
map<Symbol, ParseTableEntry> terminals;
terminals[Symbol::terminal(left)];
terminals[Symbol::terminal(right)];
if (grammar.variables[left].is_string && grammar.variables[right].is_string) {
StartingCharacterAggregator left_starting_characters;
left_starting_characters.apply(grammar.variables[left].rule);
StartingCharacterAggregator right_starting_characters;
right_starting_characters.apply(grammar.variables[right].rule);
if (!(left_starting_characters.result == right_starting_characters.result)) {
return false;
}
}
add_lex_state(item_set_for_terminals(terminals));
return shadowed_token_indices[right];
}
LexStateId add_lex_state(const LexItemSet &item_set) {
const auto &pair = lex_state_ids.find(item_set);
if (pair == lex_state_ids.end()) {
LexStateId state_id = lex_table.states.size();
lex_table.states.push_back(LexState());
lex_state_ids[item_set] = state_id;
add_accept_token_actions(item_set, state_id);
add_advance_actions(item_set, state_id);
return state_id;
} else {
return pair->second;
}
}
void clear() {
lex_table.states.clear();
lex_state_ids.clear();
shadowed_token_indices.assign(grammar.variables.size(), false);
}
private:
void add_advance_actions(const LexItemSet &item_set, LexStateId state_id) {
for (const auto &pair : item_set.transitions()) {
const CharacterSet &characters = pair.first;
const LexItemSet::Transition &transition = pair.second;
AdvanceAction action(-1, transition.precedence, transition.in_main_token);
AcceptTokenAction &accept_action = lex_table.states[state_id].accept_action;
if (accept_action.is_present()) {
bool prefer_advancing = conflict_manager.resolve(transition.destination, action, accept_action);
bool can_advance_for_accepted_token = false;
for (const LexItem &item : transition.destination.entries) {
if (item.lhs == accept_action.symbol) {
can_advance_for_accepted_token = true;
} else if (!prefer_advancing && !transition.in_main_token && !item.lhs.is_built_in()) {
shadowed_token_indices[item.lhs.index] = true;
}
}
if (!can_advance_for_accepted_token) {
if (characters.intersects(separator_start_characters) ||
(grammar.variables[accept_action.symbol.index].is_string &&
characters.intersects(token_start_characters))) {
shadowed_token_indices[accept_action.symbol.index] = true;
}
}
if (!prefer_advancing) continue;
}
action.state_index = add_lex_state(transition.destination);
lex_table.states[state_id].advance_actions[characters] = action;
}
}
void add_accept_token_actions(const LexItemSet &item_set, LexStateId state_id) {
for (const LexItem &item : item_set.entries) {
LexItem::CompletionStatus completion_status = item.completion_status();
if (completion_status.is_done) {
AcceptTokenAction action(item.lhs, completion_status.precedence.max,
item.lhs.is_built_in() ||
grammar.variables[item.lhs.index].is_string);
auto current_action = lex_table.states[state_id].accept_action;
if (current_action.is_present()) {
if (!conflict_manager.resolve(action, current_action)) {
continue;
}
}
lex_table.states[state_id].accept_action = action;
}
}
}
void mark_fragile_tokens(ParseTable *parse_table) {
for (ParseState &state : parse_table->states) {
for (auto &entry : state.terminal_entries) {
Symbol symbol = entry.first;
if (symbol.is_terminal()) {
auto homonyms = conflict_manager.possible_homonyms.find(symbol.index);
if (homonyms != conflict_manager.possible_homonyms.end())
for (Symbol::Index homonym : homonyms->second)
if (state.terminal_entries.count(Symbol::terminal(homonym))) {
entry.second.reusable = false;
break;
}
if (!entry.second.reusable)
continue;
auto extensions = conflict_manager.possible_extensions.find(symbol.index);
if (extensions != conflict_manager.possible_extensions.end())
for (Symbol::Index extension : extensions->second)
if (state.terminal_entries.count(Symbol::terminal(extension))) {
entry.second.depends_on_lookahead = true;
break;
}
}
}
}
}
void remove_duplicate_lex_states(ParseTable *parse_table) {
for (LexState &state : lex_table.states) {
state.accept_action.is_string = false;
state.accept_action.precedence = 0;
}
map<LexStateId, LexStateId> replacements;
while (true) {
map<LexStateId, LexStateId> duplicates;
for (LexStateId i = 0, size = lex_table.states.size(); i < size; i++) {
for (LexStateId j = 0; j < i; j++) {
if (!duplicates.count(j) && lex_table.states[j] == lex_table.states[i]) {
duplicates.insert({ i, j });
break;
}
}
}
if (duplicates.empty()) break;
map<size_t, size_t> new_replacements;
for (LexStateId i = 0, size = lex_table.states.size(); i < size; i++) {
LexStateId new_state_index = i;
auto duplicate = duplicates.find(i);
if (duplicate != duplicates.end()) {
new_state_index = duplicate->second;
}
size_t prior_removed = 0;
for (const auto &duplicate : duplicates) {
if (duplicate.first >= new_state_index) break;
prior_removed++;
}
new_state_index -= prior_removed;
new_replacements.insert({ i, new_state_index });
replacements.insert({ i, new_state_index });
for (auto &replacement : replacements) {
if (replacement.second == i) {
replacement.second = new_state_index;
}
}
}
for (auto &state : lex_table.states) {
for (auto &entry : state.advance_actions) {
auto new_replacement = new_replacements.find(entry.second.state_index);
if (new_replacement != new_replacements.end()) {
entry.second.state_index = new_replacement->second;
}
}
}
for (auto i = duplicates.rbegin(); i != duplicates.rend(); ++i) {
lex_table.states.erase(lex_table.states.begin() + i->first);
}
}
for (ParseState &parse_state : parse_table->states) {
auto replacement = replacements.find(parse_state.lex_state_id);
if (replacement != replacements.end()) {
parse_state.lex_state_id = replacement->second;
}
}
}
LexItemSet item_set_for_terminals(const map<Symbol, ParseTableEntry> &terminals) {
LexItemSet result;
for (const auto &pair : terminals) {
Symbol symbol = pair.first;
if (symbol.is_terminal()) {
for (const auto &rule : rules_for_symbol(symbol)) {
for (const auto &separator_rule : separator_rules) {
result.entries.insert(LexItem(
symbol,
Metadata::separator(
Rule::seq({
separator_rule,
Metadata::main_token(rule)
})
)
));
}
}
}
}
return result;
}
vector<Rule> rules_for_symbol(const rules::Symbol &symbol) {
if (symbol == rules::END_OF_INPUT()) {
return { CharacterSet().include(0) };
}
return grammar.variables[symbol.index].rule.match(
[](const Choice &choice) {
return choice.elements;
},
[](auto rule) {
return vector<Rule>{ rule };
}
);
}
};
unique_ptr<LexTableBuilder> LexTableBuilder::create(const LexicalGrammar &grammar) {
return unique_ptr<LexTableBuilder>(new LexTableBuilderImpl(grammar));
}
LexTable LexTableBuilder::build(ParseTable *parse_table) {
return static_cast<LexTableBuilderImpl *>(this)->build(parse_table);
}
bool LexTableBuilder::detect_conflict(Symbol::Index left, Symbol::Index right) {
return static_cast<LexTableBuilderImpl *>(this)->detect_conflict(left, right);
}
} // namespace build_tables
} // namespace tree_sitter
|
#include "compiler/build_tables/lex_table_builder.h"
#include <climits>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "compiler/build_tables/lex_conflict_manager.h"
#include "compiler/build_tables/lex_item.h"
#include "compiler/parse_table.h"
#include "compiler/lexical_grammar.h"
#include "compiler/rule.h"
namespace tree_sitter {
namespace build_tables {
using std::map;
using std::pair;
using std::set;
using std::string;
using std::vector;
using std::unordered_map;
using std::unique_ptr;
using rules::Rule;
using rules::Blank;
using rules::Choice;
using rules::CharacterSet;
using rules::Repeat;
using rules::Symbol;
using rules::Metadata;
using rules::Seq;
class StartingCharacterAggregator {
public:
void apply(const Rule &rule) {
rule.match(
[this](const Seq &sequence) {
apply(*sequence.left);
},
[this](const rules::Choice &rule) {
for (const auto &element : rule.elements) {
apply(element);
}
},
[this](const rules::Repeat &rule) {
apply(*rule.rule);
},
[this](const rules::Metadata &rule) {
apply(*rule.rule);
},
[this](const rules::CharacterSet &rule) {
result.add_set(rule);
},
[this](const rules::Blank) {},
[](auto) {}
);
}
CharacterSet result;
};
class LexTableBuilderImpl : public LexTableBuilder {
LexTable lex_table;
const LexicalGrammar grammar;
vector<Rule> separator_rules;
CharacterSet separator_start_characters;
CharacterSet token_start_characters;
LexConflictManager conflict_manager;
unordered_map<LexItemSet, LexStateId> lex_state_ids;
public:
vector<bool> shadowed_token_indices;
LexTableBuilderImpl(const LexicalGrammar &grammar) : grammar(grammar) {
StartingCharacterAggregator separator_character_aggregator;
for (const auto &rule : grammar.separators) {
separator_rules.push_back(Repeat{rule});
separator_character_aggregator.apply(rule);
}
separator_rules.push_back(Blank{});
separator_start_characters = separator_character_aggregator.result;
StartingCharacterAggregator token_start_character_aggregator;
for (const auto &variable : grammar.variables) {
token_start_character_aggregator.apply(variable.rule);
}
token_start_characters = token_start_character_aggregator.result;
token_start_characters
.exclude('a', 'z')
.exclude('A', 'Z')
.exclude('0', '9')
.exclude('_')
.exclude('$');
shadowed_token_indices.resize(grammar.variables.size());
}
LexTable build(ParseTable *parse_table) {
for (ParseState &parse_state : parse_table->states) {
parse_state.lex_state_id = add_lex_state(
item_set_for_terminals(parse_state.terminal_entries)
);
}
mark_fragile_tokens(parse_table);
remove_duplicate_lex_states(parse_table);
return lex_table;
}
bool detect_conflict(Symbol::Index left, Symbol::Index right) {
StartingCharacterAggregator left_starting_characters;
StartingCharacterAggregator right_starting_characters;
left_starting_characters.apply(grammar.variables[left].rule);
right_starting_characters.apply(grammar.variables[right].rule);
if (!left_starting_characters.result.intersects(right_starting_characters.result) &&
!left_starting_characters.result.intersects(separator_start_characters) &&
!right_starting_characters.result.intersects(separator_start_characters)) {
return false;
}
clear();
map<Symbol, ParseTableEntry> terminals;
terminals[Symbol::terminal(left)];
terminals[Symbol::terminal(right)];
add_lex_state(item_set_for_terminals(terminals));
return shadowed_token_indices[right];
}
LexStateId add_lex_state(const LexItemSet &item_set) {
const auto &pair = lex_state_ids.find(item_set);
if (pair == lex_state_ids.end()) {
LexStateId state_id = lex_table.states.size();
lex_table.states.push_back(LexState());
lex_state_ids[item_set] = state_id;
add_accept_token_actions(item_set, state_id);
add_advance_actions(item_set, state_id);
return state_id;
} else {
return pair->second;
}
}
void clear() {
lex_table.states.clear();
lex_state_ids.clear();
shadowed_token_indices.assign(grammar.variables.size(), false);
}
private:
void add_advance_actions(const LexItemSet &item_set, LexStateId state_id) {
for (const auto &pair : item_set.transitions()) {
const CharacterSet &characters = pair.first;
const LexItemSet::Transition &transition = pair.second;
AdvanceAction action(-1, transition.precedence, transition.in_main_token);
AcceptTokenAction &accept_action = lex_table.states[state_id].accept_action;
if (accept_action.is_present()) {
bool prefer_advancing = conflict_manager.resolve(transition.destination, action, accept_action);
bool can_advance_for_accepted_token = false;
for (const LexItem &item : transition.destination.entries) {
if (item.lhs == accept_action.symbol) {
can_advance_for_accepted_token = true;
} else if (!prefer_advancing && !transition.in_main_token && !item.lhs.is_built_in()) {
shadowed_token_indices[item.lhs.index] = true;
}
}
if (!can_advance_for_accepted_token) {
if (characters.intersects(separator_start_characters) ||
(grammar.variables[accept_action.symbol.index].is_string &&
characters.intersects(token_start_characters))) {
shadowed_token_indices[accept_action.symbol.index] = true;
}
}
if (!prefer_advancing) continue;
}
action.state_index = add_lex_state(transition.destination);
lex_table.states[state_id].advance_actions[characters] = action;
}
}
void add_accept_token_actions(const LexItemSet &item_set, LexStateId state_id) {
for (const LexItem &item : item_set.entries) {
LexItem::CompletionStatus completion_status = item.completion_status();
if (completion_status.is_done) {
AcceptTokenAction action(item.lhs, completion_status.precedence.max,
item.lhs.is_built_in() ||
grammar.variables[item.lhs.index].is_string);
auto current_action = lex_table.states[state_id].accept_action;
if (current_action.is_present()) {
if (!conflict_manager.resolve(action, current_action)) {
continue;
}
}
lex_table.states[state_id].accept_action = action;
}
}
}
void mark_fragile_tokens(ParseTable *parse_table) {
for (ParseState &state : parse_table->states) {
for (auto &entry : state.terminal_entries) {
Symbol symbol = entry.first;
if (symbol.is_terminal()) {
auto homonyms = conflict_manager.possible_homonyms.find(symbol.index);
if (homonyms != conflict_manager.possible_homonyms.end())
for (Symbol::Index homonym : homonyms->second)
if (state.terminal_entries.count(Symbol::terminal(homonym))) {
entry.second.reusable = false;
break;
}
if (!entry.second.reusable)
continue;
auto extensions = conflict_manager.possible_extensions.find(symbol.index);
if (extensions != conflict_manager.possible_extensions.end())
for (Symbol::Index extension : extensions->second)
if (state.terminal_entries.count(Symbol::terminal(extension))) {
entry.second.depends_on_lookahead = true;
break;
}
}
}
}
}
void remove_duplicate_lex_states(ParseTable *parse_table) {
for (LexState &state : lex_table.states) {
state.accept_action.is_string = false;
state.accept_action.precedence = 0;
}
map<LexStateId, LexStateId> replacements;
while (true) {
map<LexStateId, LexStateId> duplicates;
for (LexStateId i = 0, size = lex_table.states.size(); i < size; i++) {
for (LexStateId j = 0; j < i; j++) {
if (!duplicates.count(j) && lex_table.states[j] == lex_table.states[i]) {
duplicates.insert({ i, j });
break;
}
}
}
if (duplicates.empty()) break;
map<size_t, size_t> new_replacements;
for (LexStateId i = 0, size = lex_table.states.size(); i < size; i++) {
LexStateId new_state_index = i;
auto duplicate = duplicates.find(i);
if (duplicate != duplicates.end()) {
new_state_index = duplicate->second;
}
size_t prior_removed = 0;
for (const auto &duplicate : duplicates) {
if (duplicate.first >= new_state_index) break;
prior_removed++;
}
new_state_index -= prior_removed;
new_replacements.insert({ i, new_state_index });
replacements.insert({ i, new_state_index });
for (auto &replacement : replacements) {
if (replacement.second == i) {
replacement.second = new_state_index;
}
}
}
for (auto &state : lex_table.states) {
for (auto &entry : state.advance_actions) {
auto new_replacement = new_replacements.find(entry.second.state_index);
if (new_replacement != new_replacements.end()) {
entry.second.state_index = new_replacement->second;
}
}
}
for (auto i = duplicates.rbegin(); i != duplicates.rend(); ++i) {
lex_table.states.erase(lex_table.states.begin() + i->first);
}
}
for (ParseState &parse_state : parse_table->states) {
auto replacement = replacements.find(parse_state.lex_state_id);
if (replacement != replacements.end()) {
parse_state.lex_state_id = replacement->second;
}
}
}
LexItemSet item_set_for_terminals(const map<Symbol, ParseTableEntry> &terminals) {
LexItemSet result;
for (const auto &pair : terminals) {
Symbol symbol = pair.first;
if (symbol.is_terminal()) {
for (const auto &rule : rules_for_symbol(symbol)) {
for (const auto &separator_rule : separator_rules) {
result.entries.insert(LexItem(
symbol,
Metadata::separator(
Rule::seq({
separator_rule,
Metadata::main_token(rule)
})
)
));
}
}
}
}
return result;
}
vector<Rule> rules_for_symbol(const rules::Symbol &symbol) {
if (symbol == rules::END_OF_INPUT()) {
return { CharacterSet().include(0) };
}
return grammar.variables[symbol.index].rule.match(
[](const Choice &choice) {
return choice.elements;
},
[](auto rule) {
return vector<Rule>{ rule };
}
);
}
};
unique_ptr<LexTableBuilder> LexTableBuilder::create(const LexicalGrammar &grammar) {
return unique_ptr<LexTableBuilder>(new LexTableBuilderImpl(grammar));
}
LexTable LexTableBuilder::build(ParseTable *parse_table) {
return static_cast<LexTableBuilderImpl *>(this)->build(parse_table);
}
bool LexTableBuilder::detect_conflict(Symbol::Index left, Symbol::Index right) {
return static_cast<LexTableBuilderImpl *>(this)->detect_conflict(left, right);
}
} // namespace build_tables
} // namespace tree_sitter
|
Improve logic for short-circuiting trivial lexing conflict detection
|
Improve logic for short-circuiting trivial lexing conflict detection
|
C++
|
mit
|
tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter
|
f9ce7014427a506248657b64f50848c5cdf14f9a
|
src/topics/lda_model.cpp
|
src/topics/lda_model.cpp
|
/**
* @file lda_model.cpp
* @author Chase Geigle
*/
#include "topics/lda_model.h"
namespace meta
{
namespace topics
{
lda_model::lda_model(std::shared_ptr<index::forward_index> idx,
uint64_t num_topics)
: idx_{std::move(idx)},
num_topics_{num_topics},
num_words_{idx_->unique_terms()}
{
/* nothing */
}
void lda_model::save_doc_topic_distributions(const std::string& filename) const
{
std::ofstream file{filename};
for (const auto& d_id : idx_->docs())
{
file << d_id << "\t";
for (topic_id j{0}; j < num_topics_; ++j)
{
double prob = compute_doc_topic_probability(d_id, j);
if (prob > 0)
file << j << ":" << prob << "\t";
}
file << "\n";
}
}
void lda_model::save_topic_term_distributions(const std::string& filename) const
{
std::ofstream file{filename};
// first, compute the denominators for each term's normalized score
std::vector<double> denoms;
denoms.reserve(idx_->unique_terms());
for (term_id t_id{0}; t_id < idx_->unique_terms(); ++t_id)
{
std::vector<double> probs;
double denom = 1.0;
for (topic_id j{0}; j < num_topics_; ++j)
denom *= compute_term_topic_probability(t_id, j);
denom = std::pow(denom, 1.0 / num_topics_);
denoms.push_back(denom);
}
// then, calculate and save each term's score
for (topic_id j{0}; j < num_topics_; ++j)
{
file << j << "\t";
for (term_id t_id{0}; t_id < idx_->unique_terms(); ++t_id)
{
double prob = compute_term_topic_probability(t_id, j);
double norm_prob = prob * std::log(prob / denoms[t_id]);
if (norm_prob > 0)
file << t_id << ":" << norm_prob << "\t";
}
file << "\n";
}
}
void lda_model::save(const std::string& prefix) const
{
save_doc_topic_distributions(prefix + ".theta");
save_topic_term_distributions(prefix + ".phi");
}
}
}
|
/**
* @file lda_model.cpp
* @author Chase Geigle
*/
#include "topics/lda_model.h"
namespace meta
{
namespace topics
{
lda_model::lda_model(std::shared_ptr<index::forward_index> idx,
uint64_t num_topics)
: idx_{std::move(idx)},
num_topics_{num_topics},
num_words_{idx_->unique_terms()}
{
/* nothing */
}
void lda_model::save_doc_topic_distributions(const std::string& filename) const
{
std::ofstream file{filename};
for (const auto& d_id : idx_->docs())
{
file << d_id << "\t";
for (topic_id j{0}; j < num_topics_; ++j)
{
double prob = compute_doc_topic_probability(d_id, j);
if (prob > 0)
file << j << ":" << prob << "\t";
}
file << "\n";
}
}
void lda_model::save_topic_term_distributions(const std::string& filename) const
{
std::ofstream file{filename};
// first, compute the denominators for each term's normalized score
std::vector<double> denoms;
denoms.reserve(idx_->unique_terms());
for (term_id t_id{0}; t_id < idx_->unique_terms(); ++t_id)
{
double denom = 1.0;
for (topic_id j{0}; j < num_topics_; ++j)
denom *= compute_term_topic_probability(t_id, j);
denom = std::pow(denom, 1.0 / num_topics_);
denoms.push_back(denom);
}
// then, calculate and save each term's score
for (topic_id j{0}; j < num_topics_; ++j)
{
file << j << "\t";
for (term_id t_id{0}; t_id < idx_->unique_terms(); ++t_id)
{
double prob = compute_term_topic_probability(t_id, j);
double norm_prob = prob * std::log(prob / denoms[t_id]);
if (norm_prob > 0)
file << t_id << ":" << norm_prob << "\t";
}
file << "\n";
}
}
void lda_model::save(const std::string& prefix) const
{
save_doc_topic_distributions(prefix + ".theta");
save_topic_term_distributions(prefix + ".phi");
}
}
}
|
remove unused variable that didn't generate a warning
|
remove unused variable that didn't generate a warning
|
C++
|
mit
|
esparza83/meta,husseinhazimeh/meta,husseinhazimeh/meta,gef756/meta,esparza83/meta,husseinhazimeh/meta,esparza83/meta,gef756/meta,gef756/meta,esparza83/meta,saq7/MeTA,husseinhazimeh/meta,saq7/MeTA,gef756/meta,saq7/MeTA,husseinhazimeh/meta,gef756/meta,esparza83/meta
|
485620abcf87dee1725e1d0f40f3dd27e9b54887
|
cql3/statements/parsed_statement.hh
|
cql3/statements/parsed_statement.hh
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*
* Copyright 2014 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_STATEMENTS_PARSED_STATEMENT_HH
#define CQL3_STATEMENTS_PARSED_STATEMENT_HH
#include "cql3/variable_specifications.hh"
#include "cql3/column_specification.hh"
#include "cql3/column_identifier.hh"
#include "cql3/cql_statement.hh"
#include "core/shared_ptr.hh"
#include <experimental/optional>
#include <vector>
namespace cql3 {
namespace statements {
class parsed_statement {
private:
::shared_ptr<variable_specifications> _variables;
public:
virtual ~parsed_statement()
{ }
shared_ptr<variable_specifications> get_bound_variables() {
return _variables;
}
// Used by the parser and preparable statement
void set_bound_variables(const std::vector<std::experimental::optional<::shared_ptr<column_identifier>>>& bound_names)
{
_variables = ::make_shared<variable_specifications>(bound_names);
}
class prepared {
public:
const ::shared_ptr<cql_statement> statement;
const std::vector<::shared_ptr<column_specification>> bound_names;
prepared(::shared_ptr<cql_statement> statement_, const std::vector<::shared_ptr<column_specification>>& bound_names_)
: statement(std::move(statement_))
, bound_names(bound_names_)
{ }
prepared(::shared_ptr<cql_statement> statement_, const variable_specifications& names)
: prepared(statement_, names.get_specifications())
{ }
prepared(::shared_ptr<cql_statement>&& statement_)
: prepared(statement_, std::vector<::shared_ptr<column_specification>>())
{ }
};
virtual std::unique_ptr<prepared> prepare() = 0;
virtual bool uses_function(sstring ks_name, sstring function_name) {
return false;
}
};
}
}
#endif
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*
* Copyright 2014 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#ifndef CQL3_STATEMENTS_PARSED_STATEMENT_HH
#define CQL3_STATEMENTS_PARSED_STATEMENT_HH
#include "cql3/variable_specifications.hh"
#include "cql3/column_specification.hh"
#include "cql3/column_identifier.hh"
#include "cql3/cql_statement.hh"
#include "core/shared_ptr.hh"
#include <experimental/optional>
#include <vector>
namespace cql3 {
namespace statements {
class parsed_statement : public virtual cql_statement {
private:
::shared_ptr<variable_specifications> _variables;
public:
virtual ~parsed_statement()
{ }
shared_ptr<variable_specifications> get_bound_variables() {
return _variables;
}
// Used by the parser and preparable statement
void set_bound_variables(const std::vector<std::experimental::optional<::shared_ptr<column_identifier>>>& bound_names)
{
_variables = ::make_shared<variable_specifications>(bound_names);
}
class prepared {
public:
const ::shared_ptr<cql_statement> statement;
const std::vector<::shared_ptr<column_specification>> bound_names;
prepared(::shared_ptr<cql_statement> statement_, const std::vector<::shared_ptr<column_specification>>& bound_names_)
: statement(std::move(statement_))
, bound_names(bound_names_)
{ }
prepared(::shared_ptr<cql_statement> statement_, const variable_specifications& names)
: prepared(statement_, names.get_specifications())
{ }
prepared(::shared_ptr<cql_statement>&& statement_)
: prepared(statement_, std::vector<::shared_ptr<column_specification>>())
{ }
};
virtual std::unique_ptr<prepared> prepare() = 0;
virtual bool uses_function(sstring ks_name, sstring function_name) override {
return false;
}
};
}
}
#endif
|
Fix cql_statement and parsed_statement confusion
|
cql3: Fix cql_statement and parsed_statement confusion
Cassandra's ParsedStatement does not implement CqlStatement. Classes
such as UseStatement extend ParsedStatement and implement CqlStatement
which causes JVM to dispatch methods such as usesFunction to
ParsedStatement.
This doesn't happen in C++, of course, which leaves classes such as
use_statement abstract and thus uninstantiable.
Signed-off-by: Pekka Enberg <[email protected]>
|
C++
|
agpl-3.0
|
kjniemi/scylla,stamhe/scylla,capturePointer/scylla,scylladb/scylla,acbellini/scylla,victorbriz/scylla,senseb/scylla,glommer/scylla,victorbriz/scylla,justintung/scylla,glommer/scylla,rentongzhang/scylla,scylladb/scylla,duarten/scylla,dwdm/scylla,senseb/scylla,aruanruan/scylla,eklitzke/scylla,rentongzhang/scylla,victorbriz/scylla,linearregression/scylla,tempbottle/scylla,gwicke/scylla,linearregression/scylla,raphaelsc/scylla,wildinto/scylla,rluta/scylla,wildinto/scylla,gwicke/scylla,bowlofstew/scylla,raphaelsc/scylla,phonkee/scylla,rluta/scylla,kjniemi/scylla,kangkot/scylla,tempbottle/scylla,acbellini/scylla,respu/scylla,duarten/scylla,aruanruan/scylla,bowlofstew/scylla,scylladb/scylla,avikivity/scylla,eklitzke/scylla,aruanruan/scylla,stamhe/scylla,asias/scylla,kjniemi/scylla,eklitzke/scylla,glommer/scylla,asias/scylla,avikivity/scylla,guiquanz/scylla,stamhe/scylla,asias/scylla,scylladb/scylla,senseb/scylla,bowlofstew/scylla,justintung/scylla,raphaelsc/scylla,dwdm/scylla,shaunstanislaus/scylla,kangkot/scylla,wildinto/scylla,kangkot/scylla,guiquanz/scylla,respu/scylla,shaunstanislaus/scylla,rluta/scylla,tempbottle/scylla,guiquanz/scylla,capturePointer/scylla,rentongzhang/scylla,shaunstanislaus/scylla,respu/scylla,duarten/scylla,gwicke/scylla,phonkee/scylla,linearregression/scylla,capturePointer/scylla,justintung/scylla,dwdm/scylla,avikivity/scylla,acbellini/scylla,phonkee/scylla
|
eba418e4a9a87c8780e519cf09bffebafb94cf71
|
tests/init.cpp
|
tests/init.cpp
|
#include <matrix.hpp>
#include <catch.hpp>
SCENARIO("matrix init without parametrs", "[init wp]") {
Matrix matrix;
REQUIRE(matrix.rows() == 4);
REQUIRE(matrix.columns() == 4);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix[i][j] == 0);
}
}
}
SCENARIO("matrix init with parametrs", "[init withp]") {
Matrix matrix(6,6);
REQUIRE(matrix.rows() == 6);
REQUIRE(matrix.columns() == 6);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix[i][j] == 0);
}
}
}
SCENARIO("matrix init copy", "[init copy]") {
Matrix matrix(6,6);
Matrix matrix1(matrix);
REQUIRE(matrix1.rows() == matrix.rows());
REQUIRE(matrix1.columns() == matrix.columns());
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix[i][j] == matrix1[i][j]);
}
}
}
SCENARIO("matrix fill", "[fill]") {
Matrix matrix(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
REQUIRE(matrix[0][0] == 1);
REQUIRE(matrix[0][1] == 2);
REQUIRE(matrix[1][0] == 3);
REQUIRE(matrix[1][1] == 4);
}
/*SCENARIO("matrix sum", "[sum]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);*/
|
#include <matrix.hpp>
#include <catch.hpp>
SCENARIO("matrix init without parametrs", "[init wp]") {
Matrix matrix;
REQUIRE(matrix.rows() == 4);
REQUIRE(matrix.columns() == 4);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix[i][j] == 0);
}
}
}
SCENARIO("matrix init with parametrs", "[init withp]") {
Matrix matrix(6,6);
REQUIRE(matrix.rows() == 6);
REQUIRE(matrix.columns() == 6);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix[i][j] == 0);
}
}
}
SCENARIO("matrix init copy", "[init copy]") {
Matrix matrix(6,6);
Matrix matrix1(matrix);
REQUIRE(matrix1.rows() == matrix.rows());
REQUIRE(matrix1.columns() == matrix.columns());
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix[i][j] == matrix1[i][j]);
}
}
}
SCENARIO("matrix fill", "[fill]") {
Matrix matrix(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
REQUIRE(matrix[0][0] == 1);
REQUIRE(matrix[0][1] == 2);
REQUIRE(matrix[1][0] == 3);
REQUIRE(matrix[1][1] == 4);
}
SCENARIO("matrix sum", "[sum]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix sum(2,2);
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
ofstream sum("sum.txt");
sum << "2 4 6 8";
sum.fill("sum.txt")
REQUIRE(sum == matrix + matrix1);
}
|
Update init.cpp
|
Update init.cpp
|
C++
|
mit
|
Bozey98/BST
|
dc23b62de09475050f9a33db5892f022aa2377f9
|
src/vw/Core/ConfigParser.cc
|
src/vw/Core/ConfigParser.cc
|
// __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is 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.
// __END_LICENSE__
#include <vw/Core/ConfigParser.h>
#include <vw/Core/Exception.h>
#include <vw/Core/FundamentalTypes.h>
#include <vw/Core/Log.h>
#include <vw/Core/Settings.h>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/program_options/errors.hpp>
#include <boost/program_options/option.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
namespace po = boost::program_options;
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
using namespace vw;
namespace {
int32 name2level(std::string name) {
typedef std::map<std::string, MessageLevel> MapType;
static MapType name_map;
if (name_map.empty()) {
name_map["NoMessage"] = NoMessage;
name_map["InfoMessage"] = InfoMessage;
name_map["ErrorMessage"] = ErrorMessage;
name_map["WarningMessage"] = WarningMessage;
name_map["DebugMessage"] = DebugMessage;
name_map["VerboseDebugMessage"] = VerboseDebugMessage;
name_map["EveryMessage"] = EveryMessage;
name_map["*"] = EveryMessage;
}
MapType::const_iterator level = name_map.find(name);
if (level != name_map.end())
return level->second;
return boost::lexical_cast<int32>(name);
}
}
void vw::parse_config_file(const char* fn, vw::Settings& settings) {
std::ifstream file(fn);
if (!file.is_open())
vw_throw(IOErr() << "Could not open logfile: " << fn);
parse_config(file, settings);
}
void vw::parse_config(std::basic_istream<char>& stream,
vw::Settings& settings) {
// DO NOT try to log with vw_log! It will cause a deadlock because we're
// holding locks inside reload_config, and the loggers will call
// reload_config first.
po::parsed_options opts(0);
po::options_description desc("All options");
desc.add_options()("*", "All");
try {
opts = po::parse_config_file( stream, desc );
} catch (const po::invalid_syntax& e) {
std::cerr << "Could not parse config file. Ignoring. ("
<< e.what() << ")" << std::endl;
} catch (const boost::program_options::unknown_option& /*e*/) {
// Swallow this one. We don't care about unknown options.
vw_throw(LogicErr() << "We should be accepting all options. This shouldn't happen.");
}
shared_ptr<LogInstance> current_log;
std::string current_logname = "console";
typedef std::vector<po::option> OptionVec;
for (OptionVec::const_iterator i=opts.options.begin(), end=opts.options.end(); i < end; ++i) {
const po::option& o = *i;
//cerr << "Looking at " << o.string_key << endl;
try {
if (o.string_key == "general.default_num_threads")
settings.set_default_num_threads(boost::lexical_cast<uint32>(o.value[0]));
else if (o.string_key == "general.system_cache_size")
settings.set_system_cache_size(boost::lexical_cast<size_t>(o.value[0]));
else if (o.string_key == "general.default_tile_size")
settings.set_default_tile_size(boost::lexical_cast<uint32>(o.value[0]));
else if (o.string_key == "general.write_pool_size")
settings.set_write_pool_size(boost::lexical_cast<uint32>(o.value[0]));
else if (o.string_key == "general.tmp_directory")
settings.set_tmp_directory(o.value[0]);
else if (o.string_key.compare(0, 8, "logfile ") == 0) {
size_t sep = o.string_key.find_last_of('.');
assert(sep != std::string::npos);
std::string logname = o.string_key.substr(8, sep-8);
std::string level_s = o.string_key.substr(sep+1);
std::string domain = o.value[0];
//cerr << "Logname[" << logname << "] level_s[" << level_s << "] domain[" << domain << "]" << endl;
if (logname.empty() || level_s.empty() || domain.empty())
continue;
if (logname != current_logname) {
current_logname = logname;
if (current_logname == "console")
current_log.reset();
else {
current_log = shared_ptr<LogInstance>( new LogInstance(logname) );
vw_log().add(current_log);
}
}
int32 level = name2level(level_s);
if (level >= DebugMessage)
std::cerr << "Warning! Your current config file enables debug logging. This will be slow." << std::endl;
//cerr << "Adding rule: " << level << " " << domain << "\n";
if (current_log)
current_log->rule_set().add_rule(level, domain);
else
vw_log().console_log().rule_set().add_rule(level, domain);
}
else {
//cerr << "Skipping " << o.string_key << endl;
continue;
}
} catch (const boost::bad_lexical_cast& /*e*/) {
std::cerr << "Could not parse line in config file near "
<< o.string_key << ". skipping." << std::endl;
}
}
}
|
// __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is 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.
// __END_LICENSE__
#include <vw/Core/ConfigParser.h>
#include <vw/Core/Exception.h>
#include <vw/Core/FundamentalTypes.h>
#include <vw/Core/Log.h>
#include <vw/Core/Settings.h>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/program_options/errors.hpp>
#include <boost/program_options/option.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
namespace po = boost::program_options;
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
using namespace vw;
namespace {
int32 name2level(std::string name) {
typedef std::map<std::string, MessageLevel> MapType;
static MapType name_map;
if (name_map.empty()) {
name_map["NoMessage"] = NoMessage;
name_map["InfoMessage"] = InfoMessage;
name_map["ErrorMessage"] = ErrorMessage;
name_map["WarningMessage"] = WarningMessage;
name_map["DebugMessage"] = DebugMessage;
name_map["VerboseDebugMessage"] = VerboseDebugMessage;
name_map["EveryMessage"] = EveryMessage;
name_map["*"] = EveryMessage;
}
MapType::const_iterator level = name_map.find(name);
if (level != name_map.end())
return level->second;
return boost::lexical_cast<int32>(name);
}
}
void vw::parse_config_file(const char* fn, vw::Settings& settings) {
std::ifstream file(fn);
if (!file.is_open())
vw_throw(IOErr() << "Could not open logfile: " << fn);
parse_config(file, settings);
}
void vw::parse_config(std::basic_istream<char>& stream,
vw::Settings& settings) {
// DO NOT try to log with vw_log! It will cause a deadlock because we're
// holding locks inside reload_config, and the loggers will call
// reload_config first.
po::parsed_options opts(0);
po::options_description desc("All options");
desc.add_options()("*", "All");
try {
opts = po::parse_config_file( stream, desc );
} catch (const po::invalid_syntax& e) {
std::cerr << "Could not parse config file. Ignoring. ("
<< e.what() << ")" << std::endl;
} catch (const boost::program_options::unknown_option& /*e*/) {
// Swallow this one. We don't care about unknown options.
vw_throw(LogicErr() << "We should be accepting all options. This shouldn't happen.");
}
shared_ptr<LogInstance> current_log;
std::string current_logname = "console";
typedef std::vector<po::option> OptionVec;
int warning_counter = 0;
for (OptionVec::const_iterator i=opts.options.begin(), end=opts.options.end(); i < end; ++i) {
const po::option& o = *i;
//cerr << "Looking at " << o.string_key << endl;
try {
if (o.string_key == "general.default_num_threads")
settings.set_default_num_threads(boost::lexical_cast<uint32>(o.value[0]));
else if (o.string_key == "general.system_cache_size")
settings.set_system_cache_size(boost::lexical_cast<size_t>(o.value[0]));
else if (o.string_key == "general.default_tile_size")
settings.set_default_tile_size(boost::lexical_cast<uint32>(o.value[0]));
else if (o.string_key == "general.write_pool_size")
settings.set_write_pool_size(boost::lexical_cast<uint32>(o.value[0]));
else if (o.string_key == "general.tmp_directory")
settings.set_tmp_directory(o.value[0]);
else if (o.string_key.compare(0, 8, "logfile ") == 0) {
size_t sep = o.string_key.find_last_of('.');
assert(sep != std::string::npos);
std::string logname = o.string_key.substr(8, sep-8);
std::string level_s = o.string_key.substr(sep+1);
std::string domain = o.value[0];
//cerr << "Logname[" << logname << "] level_s[" << level_s << "] domain[" << domain << "]" << endl;
if (logname.empty() || level_s.empty() || domain.empty())
continue;
if (logname != current_logname) {
current_logname = logname;
if (current_logname == "console")
current_log.reset();
else {
current_log = shared_ptr<LogInstance>( new LogInstance(logname) );
vw_log().add(current_log);
}
}
int32 level = name2level(level_s);
if (level >= DebugMessage && warning_counter == 0){
std::cerr << "Warning! Your current config file enables debug logging. This will be slow." << std::endl;
warning_counter++; // print warnings just once
}
//cerr << "Adding rule: " << level << " " << domain << "\n";
if (current_log)
current_log->rule_set().add_rule(level, domain);
else
vw_log().console_log().rule_set().add_rule(level, domain);
}
else {
//cerr << "Skipping " << o.string_key << endl;
continue;
}
} catch (const boost::bad_lexical_cast& /*e*/) {
std::cerr << "Could not parse line in config file near "
<< o.string_key << ". skipping." << std::endl;
}
}
}
|
Print warnings just once
|
ConfigParser: Print warnings just once
|
C++
|
apache-2.0
|
fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,DougFirErickson/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,AveRapina/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,DougFirErickson/visionworkbench,DougFirErickson/visionworkbench,AveRapina/visionworkbench
|
97d60b5234649a5ee7829889d0c0275edfde36f3
|
tests/init.cpp
|
tests/init.cpp
|
#include <matrix.hpp>
#include <catch.hpp>
SCENARIO("matrix init without parametrs", "[init wp]") {
Matrix matrix;
REQUIRE(matrix.rows() == 4);
REQUIRE(matrix.columns() == 4);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == 0);
}
}
}
SCENARIO("matrix init with parametrs", "[init withp]") {
Matrix matrix(2,2);
REQUIRE(matrix.rows() == 2);
REQUIRE(matrix.columns() == 2);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == 0);
}
}
}
SCENARIO("matrix init copy", "[init copy]") {
Matrix matrix(2,2);
Matrix matrix1(matrix);
REQUIRE(matrix1.rows() == matrix.rows());
REQUIRE(matrix1.columns() == matrix.columns());
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
}
}
}
SCENARIO("matrix fill", "[fill]") {
Matrix matrix(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
REQUIRE(matrix.Element(0,0) == 1);
REQUIRE(matrix.Element(0,1) == 2);
REQUIRE(matrix.Element(1,0) == 3);
REQUIRE(matrix.Element(1,1) == 4);
}
SCENARIO("matrix sum", "[sum]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix sum(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
//ofstream sumfile("sumfile.txt");
//sumfile << "2 4 6 8";
//sum.fill("sumfile.txt");
//sumfile.close();
REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);
}
SCENARIO("matrix Proizv", "[Pro]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix Pro(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
//ofstream sumfile("sumfile.txt");
//sumfile << "2 4 6 8";
//sum.fill("sumfile.txt");
//sumfile.close();
REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.Element(0,1) == 7);
REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.Element(1,1) == 15);
REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.Element(0,1) == 15);
REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.Element(1,1) == 22);
}
|
#include <matrix.hpp>
#include <catch.hpp>
SCENARIO("matrix init without parametrs", "[init wp]") {
Matrix matrix;
REQUIRE(matrix.rows() == 4);
REQUIRE(matrix.columns() == 4);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == 0);
}
}
}
SCENARIO("matrix init with parametrs", "[init withp]") {
Matrix matrix(2,2);
REQUIRE(matrix.rows() == 2);
REQUIRE(matrix.columns() == 2);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == 0);
}
}
}
SCENARIO("matrix init copy", "[init copy]") {
Matrix matrix(2,2);
Matrix matrix1(matrix);
REQUIRE(matrix1.rows() == matrix.rows());
REQUIRE(matrix1.columns() == matrix.columns());
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
}
}
}
SCENARIO("matrix fill", "[fill]") {
Matrix matrix(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
REQUIRE(matrix.Element(0,0) == 1);
REQUIRE(matrix.Element(0,1) == 2);
REQUIRE(matrix.Element(1,0) == 3);
REQUIRE(matrix.Element(1,1) == 4);
}
SCENARIO("matrix sum", "[sum]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix sum(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
//ofstream sumfile("sumfile.txt");
//sumfile << "2 4 6 8";
//sum.fill("sumfile.txt");
//sumfile.close();
REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);
}
SCENARIO("matrix Proizv", "[Pro]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix Pro(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
//ofstream sumfile("sumfile.txt");
//sumfile << "2 4 6 8";
//sum.fill("sumfile.txt");
//sumfile.close();
REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.Element(0,1) == 7);
REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.Element(0,1) == 10);
REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.Element(1,1) == 15);
REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.Element(1,1) == 22);
}
|
Update init.cpp
|
Update init.cpp
|
C++
|
mit
|
Bozey98/BST
|
85bd8f93c60a9433559239cfab3eb8297c00abb2
|
opencog/atoms/base/ClassServer.cc
|
opencog/atoms/base/ClassServer.cc
|
/*
* opencog/atoms/base/ClassServer.cc
*
* Copyright (C) 2002-2007 Novamente LLC
* Copyright (C) 2008 by OpenCog Foundation
* Copyright (C) 2009,2017 Linas Vepstas <[email protected]>
* All Rights Reserved
*
* Written by Thiago Maia <[email protected]>
* Andre Senna <[email protected]>
* Gustavo Gama <[email protected]>
* Linas Vepstas <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "ClassServer.h"
#include <exception>
#include <opencog/atoms/base/types.h>
#include <opencog/atoms/base/atom_types.h>
#include <opencog/atoms/base/Atom.h>
#include <opencog/atoms/base/ProtoAtom.h>
//#define DPRINTF printf
#define DPRINTF(...)
using namespace opencog;
ClassServer::ClassServer(void)
{
nTypes = 0;
_maxDepth = 0;
_is_init = false;
}
static int tmod = 0;
void ClassServer::beginTypeDecls(void)
{
tmod++;
_is_init = false;
}
void ClassServer::endTypeDecls(void)
{
// Valid types are odd-numbered.
tmod++;
}
Type ClassServer::declType(const Type parent, const std::string& name)
{
if (1 != tmod%2)
throw InvalidParamException(TRACE_INFO,
"Improper type declararition; must call beginTypeDecls() first\n");
// Check if a type with this name already exists. If it does, then
// the second and subsequent calls are to be interpreted as defining
// multiple inheritance for this type. A real-life example is the
// GroundedSchemeNode, which inherits from several types.
Type type = getType(name);
if (type != NOTYPE) {
std::lock_guard<std::mutex> l(type_mutex);
// ... unless someone is accidentally declaring the same type
// in some different place. In that case, we throw an error.
if (_mod[type] != tmod)
throw InvalidParamException(TRACE_INFO,
"Type \"%s\" has already been declared (%d)\n",
name.c_str(), type);
inheritanceMap[parent][type] = true;
Type maxd = 1;
setParentRecursively(parent, type, maxd);
if (_maxDepth < maxd) _maxDepth = maxd;
return type;
}
std::unique_lock<std::mutex> l(type_mutex);
// Assign type code and increment type counter.
type = nTypes++;
// Resize inheritanceMap container.
inheritanceMap.resize(nTypes);
recursiveMap.resize(nTypes);
_code2NameMap.resize(nTypes);
_mod.resize(nTypes);
_atomFactory.resize(nTypes);
_validator.resize(nTypes);
for (auto& bv: inheritanceMap) bv.resize(nTypes, false);
for (auto& bv: recursiveMap) bv.resize(nTypes, false);
inheritanceMap[type][type] = true;
inheritanceMap[parent][type] = true;
recursiveMap[type][type] = true;
name2CodeMap[name] = type;
_code2NameMap[type] = &(name2CodeMap.find(name)->first);
_mod[type] = tmod;
Type maxd = 1;
setParentRecursively(parent, type, maxd);
if (_maxDepth < maxd) _maxDepth = maxd;
// unlock mutex before sending signal which could call
l.unlock();
// Emit add type signal.
_addTypeSignal.emit(type);
return type;
}
void ClassServer::setParentRecursively(Type parent, Type type, Type& maxd)
{
if (recursiveMap[parent][type]) return;
bool incr = false;
recursiveMap[parent][type] = true;
for (Type i = 0; i < nTypes; ++i) {
if ((recursiveMap[i][parent]) and (i != parent)) {
incr = true;
setParentRecursively(i, type, maxd);
}
}
if (incr) maxd++;
}
TypeSignal& ClassServer::typeAddedSignal()
{
return _addTypeSignal;
}
void ClassServer::addFactory(Type t, AtomFactory* fact)
{
std::unique_lock<std::mutex> l(type_mutex);
_atomFactory[t] = fact;
// Find all the factories that belong to parents of this type.
std::set<AtomFactory*> ok_to_clobber;
for (Type parent=0; parent < t; parent++)
{
if (recursiveMap[parent][t] and _atomFactory[parent])
ok_to_clobber.insert(_atomFactory[parent]);
}
// Set the factory for all children of this type. Be careful
// not to clobber any factories that might have been previously
// declared.
for (Type chi=t+1; chi < nTypes; chi++)
{
if (recursiveMap[t][chi] and
(nullptr == _atomFactory[chi] or
ok_to_clobber.end() != ok_to_clobber.find(_atomFactory[chi])))
{
_atomFactory[chi] = fact;
}
}
}
Handle validating_factory(const Handle& atom_to_check)
{
ClassServer::Validator* checker =
classserver().getValidator(atom_to_check->get_type());
/* Well, is it OK, or not? */
if (not checker(atom_to_check))
throw SyntaxException(TRACE_INFO,
"Invalid Atom syntax: %s",
atom_to_check->to_string().c_str());
return atom_to_check;
}
void ClassServer::addValidator(Type t, Validator* checker)
{
std::unique_lock<std::mutex> l(type_mutex);
_validator[t] = checker;
if (not _atomFactory[t])
_atomFactory[t] = validating_factory;
_is_init = false;
}
// Perform a depth-first recursive search for a factory,
// up to a maximum depth.
template<typename RTN_TYPE>
RTN_TYPE* ClassServer::searchToDepth(const std::vector<RTN_TYPE*>& vect,
Type t, int depth) const
{
// If there is a factory, then return it.
RTN_TYPE* fpr = vect[t];
if (fpr) return fpr;
// Perhaps one of the parent types has a factory.
// Perform a depth-first recursion.
depth--;
if (depth < 0) return nullptr;
// Do any of the immediate parents of this type
// have a factory?
for (Type p = 0; p < t; ++p)
{
if (inheritanceMap[p][t])
{
RTN_TYPE* fact = searchToDepth<RTN_TYPE>(vect, p, depth);
if (fact) return fact;
}
}
return nullptr;
}
template<typename RTN_TYPE>
RTN_TYPE* ClassServer::getOper(const std::vector<RTN_TYPE*>& vect,
Type t) const
{
if (nTypes <= t) return nullptr;
// If there is a factory, then return it.
RTN_TYPE* fpr = vect[t];
if (fpr) return fpr;
// Perhaps one of the parent types has a factory.
//
// We want to use a breadth-first recursion, and not
// the simpler-to-code depth-first recursion. That is,
// we do NOT want some deep parent factory, when there
// is some factory at a shallower level.
//
for (int search_depth = 1; search_depth <= _maxDepth; search_depth++)
{
RTN_TYPE* fact = searchToDepth<RTN_TYPE>(vect, t, search_depth);
if (fact) return fact;
}
return nullptr;
}
ClassServer::AtomFactory* ClassServer::getFactory(Type t) const
{
if (not _is_init) init();
return _atomFactory[t];
}
ClassServer::Validator* ClassServer::getValidator(Type t) const
{
if (not _is_init) init();
return _validator[t];
}
void ClassServer::init() const
{
// The goal here is to cache the various factories that child
// nodes might run. The getOper<AtomFactory>() is too expensive
// to run for every node creation. It damages performance by
// 10x per Node creation, and 5x for every link creation.
//
// Unfortunately, creating this cache is tricky. It can't be
// done one at a time, because the factories get added in
// random order, can can clobber one-another. Instead, we have
// to wait to do this until after all factories have been
// declared.
for (Type parent = 0; parent < nTypes; parent++)
{
#if 0
if (_atomFactory[parent])
{
for (Type chi = parent+1; chi < nTypes; ++chi)
{
if (inheritanceMap[parent][chi] and
nullptr == _atomFactory[chi])
{
_atomFactory[chi] = getOper<AtomFactory>(_atomFactory, chi);
}
}
}
#endif
if (_validator[parent])
{
for (Type chi = parent+1; chi < nTypes; ++chi)
{
if (inheritanceMap[parent][chi] and
nullptr == _validator[chi])
{
_validator[chi] = getOper<Validator>(_validator, chi);
}
}
}
}
_is_init = true;
}
Handle ClassServer::factory(const Handle& h) const
{
// If there is a factory, then use it.
AtomFactory* fact = getFactory(h->get_type());
if (fact)
return (*fact)(h);
return h;
}
Type ClassServer::getNumberOfClasses() const
{
return nTypes;
}
bool ClassServer::isA_non_recursive(Type type, Type parent) const
{
std::lock_guard<std::mutex> l(type_mutex);
if ((type >= nTypes) || (parent >= nTypes)) return false;
return inheritanceMap[parent][type];
}
bool ClassServer::isDefined(const std::string& typeName) const
{
std::lock_guard<std::mutex> l(type_mutex);
return name2CodeMap.find(typeName) != name2CodeMap.end();
}
Type ClassServer::getType(const std::string& typeName) const
{
std::lock_guard<std::mutex> l(type_mutex);
std::unordered_map<std::string, Type>::const_iterator it = name2CodeMap.find(typeName);
if (it == name2CodeMap.end()) {
return NOTYPE;
}
return it->second;
}
const std::string& ClassServer::getTypeName(Type type) const
{
static std::string nullString = "*** Unknown Type! ***";
if (nTypes <= type) return nullString;
std::lock_guard<std::mutex> l(type_mutex);
const std::string* name = _code2NameMap[type];
if (name) return *name;
return nullString;
}
ClassServer& opencog::classserver()
{
static std::unique_ptr<ClassServer> instance(new ClassServer());
return *instance;
}
|
/*
* opencog/atoms/base/ClassServer.cc
*
* Copyright (C) 2002-2007 Novamente LLC
* Copyright (C) 2008 by OpenCog Foundation
* Copyright (C) 2009,2017 Linas Vepstas <[email protected]>
* All Rights Reserved
*
* Written by Thiago Maia <[email protected]>
* Andre Senna <[email protected]>
* Gustavo Gama <[email protected]>
* Linas Vepstas <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "ClassServer.h"
#include <exception>
#include <opencog/atoms/base/types.h>
#include <opencog/atoms/base/atom_types.h>
#include <opencog/atoms/base/Atom.h>
#include <opencog/atoms/base/ProtoAtom.h>
//#define DPRINTF printf
#define DPRINTF(...)
using namespace opencog;
ClassServer::ClassServer(void)
{
nTypes = 0;
_maxDepth = 0;
_is_init = false;
}
static int tmod = 0;
void ClassServer::beginTypeDecls(void)
{
tmod++;
_is_init = false;
}
void ClassServer::endTypeDecls(void)
{
// Valid types are odd-numbered.
tmod++;
}
Type ClassServer::declType(const Type parent, const std::string& name)
{
if (1 != tmod%2)
throw InvalidParamException(TRACE_INFO,
"Improper type declararition; must call beginTypeDecls() first\n");
// Check if a type with this name already exists. If it does, then
// the second and subsequent calls are to be interpreted as defining
// multiple inheritance for this type. A real-life example is the
// GroundedSchemeNode, which inherits from several types.
Type type = getType(name);
if (type != NOTYPE) {
std::lock_guard<std::mutex> l(type_mutex);
// ... unless someone is accidentally declaring the same type
// in some different place. In that case, we throw an error.
if (_mod[type] != tmod)
throw InvalidParamException(TRACE_INFO,
"Type \"%s\" has already been declared (%d)\n",
name.c_str(), type);
inheritanceMap[parent][type] = true;
Type maxd = 1;
setParentRecursively(parent, type, maxd);
if (_maxDepth < maxd) _maxDepth = maxd;
return type;
}
std::unique_lock<std::mutex> l(type_mutex);
// Assign type code and increment type counter.
type = nTypes++;
// Resize inheritanceMap container.
inheritanceMap.resize(nTypes);
recursiveMap.resize(nTypes);
_code2NameMap.resize(nTypes);
_mod.resize(nTypes);
_atomFactory.resize(nTypes);
_validator.resize(nTypes);
for (auto& bv: inheritanceMap) bv.resize(nTypes, false);
for (auto& bv: recursiveMap) bv.resize(nTypes, false);
inheritanceMap[type][type] = true;
inheritanceMap[parent][type] = true;
recursiveMap[type][type] = true;
name2CodeMap[name] = type;
_code2NameMap[type] = &(name2CodeMap.find(name)->first);
_mod[type] = tmod;
Type maxd = 1;
setParentRecursively(parent, type, maxd);
if (_maxDepth < maxd) _maxDepth = maxd;
// unlock mutex before sending signal which could call
l.unlock();
// Emit add type signal.
_addTypeSignal.emit(type);
return type;
}
void ClassServer::setParentRecursively(Type parent, Type type, Type& maxd)
{
if (recursiveMap[parent][type]) return;
bool incr = false;
recursiveMap[parent][type] = true;
for (Type i = 0; i < nTypes; ++i) {
if ((recursiveMap[i][parent]) and (i != parent)) {
incr = true;
setParentRecursively(i, type, maxd);
}
}
if (incr) maxd++;
}
TypeSignal& ClassServer::typeAddedSignal()
{
return _addTypeSignal;
}
static Handle validating_factory(const Handle& atom_to_check)
{
ClassServer::Validator* checker =
classserver().getValidator(atom_to_check->get_type());
/* Well, is it OK, or not? */
if (not checker(atom_to_check))
throw SyntaxException(TRACE_INFO,
"Invalid Atom syntax: %s",
atom_to_check->to_string().c_str());
return atom_to_check;
}
void ClassServer::addFactory(Type t, AtomFactory* fact)
{
std::unique_lock<std::mutex> l(type_mutex);
_atomFactory[t] = fact;
// Find all the factories that belong to parents of this type.
std::set<AtomFactory*> ok_to_clobber;
ok_to_clobber.insert(validating_factory);
for (Type parent=0; parent < t; parent++)
{
if (recursiveMap[parent][t] and _atomFactory[parent])
ok_to_clobber.insert(_atomFactory[parent]);
}
// Set the factory for all children of this type. Be careful
// not to clobber any factories that might have been previously
// declared.
for (Type chi=t+1; chi < nTypes; chi++)
{
if (recursiveMap[t][chi] and
(nullptr == _atomFactory[chi] or
ok_to_clobber.end() != ok_to_clobber.find(_atomFactory[chi])))
{
_atomFactory[chi] = fact;
}
}
}
void ClassServer::addValidator(Type t, Validator* checker)
{
std::unique_lock<std::mutex> l(type_mutex);
_validator[t] = checker;
if (not _atomFactory[t])
_atomFactory[t] = validating_factory;
_is_init = false;
}
// Perform a depth-first recursive search for a factory,
// up to a maximum depth.
template<typename RTN_TYPE>
RTN_TYPE* ClassServer::searchToDepth(const std::vector<RTN_TYPE*>& vect,
Type t, int depth) const
{
// If there is a factory, then return it.
RTN_TYPE* fpr = vect[t];
if (fpr) return fpr;
// Perhaps one of the parent types has a factory.
// Perform a depth-first recursion.
depth--;
if (depth < 0) return nullptr;
// Do any of the immediate parents of this type
// have a factory?
for (Type p = 0; p < t; ++p)
{
if (inheritanceMap[p][t])
{
RTN_TYPE* fact = searchToDepth<RTN_TYPE>(vect, p, depth);
if (fact) return fact;
}
}
return nullptr;
}
template<typename RTN_TYPE>
RTN_TYPE* ClassServer::getOper(const std::vector<RTN_TYPE*>& vect,
Type t) const
{
if (nTypes <= t) return nullptr;
// If there is a factory, then return it.
RTN_TYPE* fpr = vect[t];
if (fpr) return fpr;
// Perhaps one of the parent types has a factory.
//
// We want to use a breadth-first recursion, and not
// the simpler-to-code depth-first recursion. That is,
// we do NOT want some deep parent factory, when there
// is some factory at a shallower level.
//
for (int search_depth = 1; search_depth <= _maxDepth; search_depth++)
{
RTN_TYPE* fact = searchToDepth<RTN_TYPE>(vect, t, search_depth);
if (fact) return fact;
}
return nullptr;
}
ClassServer::AtomFactory* ClassServer::getFactory(Type t) const
{
return _atomFactory[t];
}
ClassServer::Validator* ClassServer::getValidator(Type t) const
{
if (not _is_init) init();
return _validator[t];
}
void ClassServer::init() const
{
// The goal here is to cache the various factories that child
// nodes might run. The getOper<AtomFactory>() is too expensive
// to run for every node creation. It damages performance by
// 10x per Node creation, and 5x for every link creation.
//
// Unfortunately, creating this cache is tricky. It can't be
// done one at a time, because the factories get added in
// random order, can can clobber one-another. Instead, we have
// to wait to do this until after all factories have been
// declared.
for (Type parent = 0; parent < nTypes; parent++)
{
if (_validator[parent])
{
for (Type chi = parent+1; chi < nTypes; ++chi)
{
if (inheritanceMap[parent][chi] and
nullptr == _validator[chi])
{
_validator[chi] = getOper<Validator>(_validator, chi);
}
}
}
}
_is_init = true;
}
Handle ClassServer::factory(const Handle& h) const
{
// If there is a factory, then use it.
AtomFactory* fact = getFactory(h->get_type());
if (fact)
return (*fact)(h);
return h;
}
Type ClassServer::getNumberOfClasses() const
{
return nTypes;
}
bool ClassServer::isA_non_recursive(Type type, Type parent) const
{
std::lock_guard<std::mutex> l(type_mutex);
if ((type >= nTypes) || (parent >= nTypes)) return false;
return inheritanceMap[parent][type];
}
bool ClassServer::isDefined(const std::string& typeName) const
{
std::lock_guard<std::mutex> l(type_mutex);
return name2CodeMap.find(typeName) != name2CodeMap.end();
}
Type ClassServer::getType(const std::string& typeName) const
{
std::lock_guard<std::mutex> l(type_mutex);
std::unordered_map<std::string, Type>::const_iterator it = name2CodeMap.find(typeName);
if (it == name2CodeMap.end()) {
return NOTYPE;
}
return it->second;
}
const std::string& ClassServer::getTypeName(Type type) const
{
static std::string nullString = "*** Unknown Type! ***";
if (nTypes <= type) return nullString;
std::lock_guard<std::mutex> l(type_mutex);
const std::string* name = _code2NameMap[type];
if (name) return *name;
return nullString;
}
ClassServer& opencog::classserver()
{
static std::unique_ptr<ClassServer> instance(new ClassServer());
return *instance;
}
|
Remove the dead code, and allow clobber of validators too.
|
Remove the dead code, and allow clobber of validators too.
|
C++
|
agpl-3.0
|
rTreutlein/atomspace,AmeBel/atomspace,AmeBel/atomspace,rTreutlein/atomspace,misgeatgit/atomspace,rTreutlein/atomspace,misgeatgit/atomspace,misgeatgit/atomspace,AmeBel/atomspace,misgeatgit/atomspace,AmeBel/atomspace,misgeatgit/atomspace,rTreutlein/atomspace,rTreutlein/atomspace,AmeBel/atomspace
|
2f6703f17ec7b4c6cb71bf20590f6518c79df006
|
tests/init.cpp
|
tests/init.cpp
|
#include <BinaryTree.hpp>
#include <catch.hpp>
SCENARIO ("init", "[init]")
{
BinaryTree<int> obj;
REQUIRE(obj.root_() == nullptr);
}
SCENARIO ("output to cout", "<<")
{
BinaryTree<int> tree;
tree.insert_node(3);
REQUIRE(tree.show(3, obj.root_()) != nullptr);
}
SCENARIO("insert", "[insert]")
{
BinaryTree<int> obj;
obj.insert_node(3);
REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}
SCENARIO("find_node", "[find_node]")
{
BinaryTree<int> obj;
obj.insert_node(2);
REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}
SCENARIO("get root", "[get root]")
{
BinaryTree<int> obj;
obj.insert_node(4);
REQUIRE(obj.root_() != 0);
}
|
#include <BinaryTree.hpp>
#include <catch.hpp>
SCENARIO ("init", "[init]")
{
BinaryTree<int> obj;
REQUIRE(obj.root_() == nullptr);
}
SCENARIO ("output to cout", "<<")
{
BinaryTree<int> tree;
tree.insert_node(3);
REQUIRE(tree.show(tree.root_()) != nullptr, 3);
}
SCENARIO("insert", "[insert]")
{
BinaryTree<int> obj;
obj.insert_node(3);
REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}
SCENARIO("find_node", "[find_node]")
{
BinaryTree<int> obj;
obj.insert_node(2);
REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}
SCENARIO("get root", "[get root]")
{
BinaryTree<int> obj;
obj.insert_node(4);
REQUIRE(obj.root_() != 0);
}
|
Update init.cpp
|
Update init.cpp
|
C++
|
mit
|
rtv22/BinaryTree_S
|
5fa98e5b15771523374a18d2b792adfc7b43d8ef
|
tests/init.cpp
|
tests/init.cpp
|
#include <tree.hpp>
#include <catch.hpp>
SCENARIO("null")
{
Tree<int> a;
REQURE(a.tree_one()=NULL);
}
SCENARIO("add")
{
Tree<int> a;
bool b=a.add(5);
REQURE(b == 1);
}
SCENARIO("find")
{
Tree<int> a;
a.add(5);
bool b = a.find(5);
REQURE(b == 1);
}
|
#include <tree.hpp>
#include <catch.hpp>
SCENARIO("null")
{
Tree<int> a;
REQUIRE(a.tree_one()=NULL);
}
SCENARIO("add")
{
Tree<int> a;
bool b=a.add(5);
REQUIRE(b == 1);
}
SCENARIO("find")
{
Tree<int> a;
a.add(5);
bool b = a.find(5);
REQUIRE(b == 1);
}
|
Update init.cpp
|
Update init.cpp
|
C++
|
mit
|
NeverMore27/Tree
|
fb557e1070fbe009eb1bea7c0b855a426e399fe6
|
tests/init.cpp
|
tests/init.cpp
|
#include "stack.hpp"
#include <catch.hpp>
#include <iostream>
#include <fstream>
SCENARIO("Stack init", "[init]") {
stack<int> Stack;
REQUIRE(Stack.count() == 0);
}
SCENARIO("Stack push and top", "[push and top]") {
stack<int> Stack;
Stack.push(3);
REQUIRE(Stack.top() == 3);
}
SCENARIO("Stack pop", "[pop]") {
stack<int> Stack;
for (int i = 0; i < 10; i++) {
Stack.push(i);
}
Stack.pop();
REQUIRE(Stack.count() == 9);
}
SCENARIO("Stack count", "[count]") {
stack<int> Stack;
for (int i = 0; i < 10; i++) {
Stack.push(i);
}
REQUIRE(Stack.count() == 10);
}
SCENARIO("operator =", "[operator =]") {
stack<int> Stack;
Stack.push(221);
stack<int> Stack_ = Stack;
REQUIRE(Stack_.top() == 221);
}
SCENARIO("copy constructor", "[copy constructor]") {
stack<int> Stack;
Stack.push(221);
stack<int> Stack_(Stack);
REQUIRE(Stack_.top() == 221);
}
SCENARIO("empty", "[empty]") {
stack<int> Stack;
REQUIRE(Stack.empty());
}
|
#include "stack.hpp"
#include <catch.hpp>
#include <iostream>
#include <thread>
#include<mutex>
using namespace std;
SCENARIO("count", "[count]"){
stack<int> s;
s.push(1);
REQUIRE(s.count()==1);
}
SCENARIO("top", "[top]"){
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.pop();
REQUIRE(s.top()==2);
}
SCENARIO("empty", "[empty]"){
stack<int> s1;
s1.push(1);
REQUIRE(s1.empty()==false);
}
SCENARIO("empty2", "[empty2]"){
stack<int> s1;
s1.push(1);
s1.pop();
REQUIRE(s1.empty()==true);
}
SCENARIO("empty3", "[empty3]"){
stack<int> s1;
s1.push(1);
s1.push(2);
s1.pop();
s1.top();
REQUIRE(s1.empty()==false);
}
SCENARIO("mutex", "[mutex]"){
stack<int> s1;
s1.push(1);
s1.push(2);
thread potok_1(&stack<int>::push, &s1, 3);
potok_1.join();
REQUIRE(s1.top()==3);
thread potok_2(&stack<int>::pop, &s1);
potok_2.join();
REQUIRE(s1.top()==2);
}
|
Update init.cpp
|
Update init.cpp
|
C++
|
mit
|
anastasiya0304/stack
|
346d64e863ca103b6cf7b305e94ee586487536f6
|
tests/root.cpp
|
tests/root.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>
namespace blackhole {
namespace testing {
using ::testing::_;
namespace mock {
namespace {
class handler_t : public ::blackhole::handler_t {
public:
MOCK_METHOD1(execute, void(const record_t&));
};
} // namespace
} // namespace mock
TEST(RootLogger, Log) {
// Can be initialized with none handlers, does nothing.
root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, ConstLog) {
const root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, DispatchRecordToHandlers) {
std::vector<std::unique_ptr<handler_t>> handlers;
std::vector<mock::handler_t*> handlers_view;
for (int i = 0; i < 4; ++i) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
handlers_view.push_back(handler.get());
handlers.push_back(std::move(handler));
}
const root_logger_t logger(std::move(handlers));
for (auto handler : handlers_view) {
EXPECT_CALL(*handler, execute(_))
.Times(1);
}
logger.log(0, "GET /porn.png HTTP/1.1");
}
} // namespace testing
} // namespace blackhole
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>
namespace blackhole {
namespace testing {
using ::testing::Invoke;
using ::testing::_;
namespace mock {
namespace {
class handler_t : public ::blackhole::handler_t {
public:
MOCK_METHOD1(execute, void(const record_t&));
};
} // namespace
} // namespace mock
TEST(RootLogger, Log) {
// Can be initialized with none handlers, does nothing.
root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, ConstLog) {
const root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, DispatchRecordToHandlers) {
std::vector<std::unique_ptr<handler_t>> handlers;
std::vector<mock::handler_t*> handlers_view;
for (int i = 0; i < 4; ++i) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
handlers_view.push_back(handler.get());
handlers.push_back(std::move(handler));
}
const root_logger_t logger(std::move(handlers));
for (auto handler : handlers_view) {
EXPECT_CALL(*handler, execute(_))
.Times(1)
.WillOnce(Invoke([](const record_t& record) {
EXPECT_EQ(0, record.severity());
EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
}));
}
logger.log(0, "GET /porn.png HTTP/1.1");
}
} // namespace testing
} // namespace blackhole
|
check record argument also
|
chore(tests): check record argument also
|
C++
|
mit
|
3Hren/blackhole,noxiouz/blackhole
|
1c60eae9458fffecab98a683bb280eb5e21974db
|
ArcGISRuntimeSDKQt_CppSamples/Scenes/DisplayScenesInTabletopAR/DisplayScenesInTabletopAR.cpp
|
ArcGISRuntimeSDKQt_CppSamples/Scenes/DisplayScenesInTabletopAR/DisplayScenesInTabletopAR.cpp
|
// [WriteFile Name=DisplayScenesInTabletopAR, Category=Scenes]
// [Legal]
// Copyright 2019 Esri.
// 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.
// [Legal]
#include "DisplayScenesInTabletopAR.h"
#include "ArcGISTiledElevationSource.h"
#include "Scene.h"
#include "SceneQuickView.h"
#include "ArcGISSceneLayer.h"
#include "Error.h"
#include "MobileScenePackage.h"
#include <QDir>
#include <QtCore/qglobal.h>
#ifdef Q_OS_IOS
#include <QStandardPaths>
#endif // Q_OS_IOS
using namespace Esri::ArcGISRuntime;
// helper method to get cross platform data path
namespace
{
QString defaultDataPath()
{
QString dataPath;
#ifdef Q_OS_ANDROID
dataPath = "/sdcard";
#elif defined Q_OS_IOS
dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#else
dataPath = QDir::homePath();
#endif
return dataPath;
}
} // namespace
using namespace Esri::ArcGISRuntime;
using namespace Esri::ArcGISRuntime::Toolkit;
ArcGISArView* DisplayScenesInTabletopAR::arcGISArView() const
{
return m_arcGISArView;
}
void DisplayScenesInTabletopAR::setArcGISArView(ArcGISArView* arcGISArView)
{
if (!arcGISArView || arcGISArView == m_arcGISArView)
return;
m_arcGISArView = arcGISArView;
emit arcGISArViewChanged();
}
DisplayScenesInTabletopAR::DisplayScenesInTabletopAR(QObject* parent /* = nullptr */):
QObject(parent),
m_scene(new Scene(SceneViewTilingScheme::Geographic, this))
{
// Display an empty scene
m_scene->baseSurface()->setOpacity(0.0);
const QString dataPath = defaultDataPath() + "/ArcGIS/Runtime/Data/mspk/philadelphia.mspk";
// Connect to the Mobile Scene Package instance to know when errors occur
connect(MobileScenePackage::instance(), &MobileScenePackage::errorOccurred, [] (Error e)
{
if (e.isEmpty())
return;
qDebug() << QString("Error: %1 %2").arg(e.message(), e.additionalMessage());
});
// Create the Scene Package
createScenePackage(dataPath);
}
DisplayScenesInTabletopAR::~DisplayScenesInTabletopAR() = default;
void DisplayScenesInTabletopAR::init()
{
// Register classes for QML
qmlRegisterType<SceneQuickView>("Esri.Samples", 1, 0, "SceneView");
qmlRegisterType<DisplayScenesInTabletopAR>("Esri.Samples", 1, 0, "DisplayScenesInTabletopARSample");
}
SceneQuickView* DisplayScenesInTabletopAR::sceneView() const
{
return m_sceneView;
}
// Set the view (created in QML)
void DisplayScenesInTabletopAR::setSceneView(SceneQuickView* sceneView)
{
if (!sceneView || sceneView == m_sceneView)
return;
m_sceneView = sceneView;
// Connect the mouse clicked events.
connect(m_sceneView, &SceneQuickView::mouseClicked, this, &DisplayScenesInTabletopAR::onMouseClicked);
m_sceneView->setArcGISScene(m_scene);
emit sceneViewChanged();
}
// Slot for handling when the package loads
void DisplayScenesInTabletopAR::packageLoaded(const Error& e)
{
if (!e.isEmpty())
{
qDebug() << QString("Package load error: %1 %2").arg(e.message(), e.additionalMessage());
return;
}
if (m_scenePackage->scenes().isEmpty())
return;
// Get the first scene
m_scene = m_scenePackage->scenes().at(0);
// Create a camera at the bottom and center of the scene.
// This camera is the point at which the scene is pinned to the real-world surface.
m_originCamera = Camera(39.95787000283599, -75.16996728256345, 8.813445091247559, 0, 90, 0);
}
// Create scene package and connect to signals
void DisplayScenesInTabletopAR::createScenePackage(const QString& path)
{
m_scenePackage = new MobileScenePackage(path, this);
connect(m_scenePackage, &MobileScenePackage::doneLoading, this, &DisplayScenesInTabletopAR::packageLoaded);
m_scenePackage->load();
}
void DisplayScenesInTabletopAR::onMouseClicked(QMouseEvent& event)
{
Q_CHECK_PTR(m_arcGISArView);
const QPoint screenPoint = event.localPos().toPoint();
if (!m_scene && !m_sceneView)
return;
// Display the scene
if (m_sceneView->arcGISScene() != m_scene)
{
m_sceneView->setArcGISScene(m_scene);
m_dialogVisible = false;
emit dialogVisibleChanged();
}
// Hide the base surface.
m_sceneView->arcGISScene()->baseSurface()->setOpacity(0.0f);
// Enable subsurface navigation. This allows you to look at the scene from below.
m_sceneView->arcGISScene()->baseSurface()->setNavigationConstraint(NavigationConstraint::None);
// Set the initial transformation using the point clicked on the screen
m_arcGISArView->setInitialTransformation(screenPoint);
// Set the origin camera.
m_arcGISArView->setOriginCamera(m_originCamera);
// Set the translation factor based on the scene content width and desired physical size.
m_arcGISArView->setTranslationFactor(m_sceneWidth/m_tableTopWidth);
emit sceneViewChanged();
emit arcGISArViewChanged();
}
|
// [WriteFile Name=DisplayScenesInTabletopAR, Category=Scenes]
// [Legal]
// Copyright 2019 Esri.
// 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.
// [Legal]
#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD
#include "DisplayScenesInTabletopAR.h"
#include "ArcGISTiledElevationSource.h"
#include "Scene.h"
#include "SceneQuickView.h"
#include "ArcGISSceneLayer.h"
#include "Error.h"
#include "MobileScenePackage.h"
#include <QDir>
#include <QtCore/qglobal.h>
#ifdef Q_OS_IOS
#include <QStandardPaths>
#endif // Q_OS_IOS
using namespace Esri::ArcGISRuntime;
// helper method to get cross platform data path
namespace
{
QString defaultDataPath()
{
QString dataPath;
#ifdef Q_OS_ANDROID
dataPath = "/sdcard";
#elif defined Q_OS_IOS
dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#else
dataPath = QDir::homePath();
#endif
return dataPath;
}
} // namespace
using namespace Esri::ArcGISRuntime;
using namespace Esri::ArcGISRuntime::Toolkit;
ArcGISArView* DisplayScenesInTabletopAR::arcGISArView() const
{
return m_arcGISArView;
}
void DisplayScenesInTabletopAR::setArcGISArView(ArcGISArView* arcGISArView)
{
if (!arcGISArView || arcGISArView == m_arcGISArView)
return;
m_arcGISArView = arcGISArView;
emit arcGISArViewChanged();
}
DisplayScenesInTabletopAR::DisplayScenesInTabletopAR(QObject* parent /* = nullptr */):
QObject(parent),
m_scene(new Scene(SceneViewTilingScheme::Geographic, this))
{
// Display an empty scene
m_scene->baseSurface()->setOpacity(0.0);
const QString dataPath = defaultDataPath() + "/ArcGIS/Runtime/Data/mspk/philadelphia.mspk";
// Connect to the Mobile Scene Package instance to know when errors occur
connect(MobileScenePackage::instance(), &MobileScenePackage::errorOccurred, [] (Error e)
{
if (e.isEmpty())
return;
qDebug() << QString("Error: %1 %2").arg(e.message(), e.additionalMessage());
});
// Create the Scene Package
createScenePackage(dataPath);
}
DisplayScenesInTabletopAR::~DisplayScenesInTabletopAR() = default;
void DisplayScenesInTabletopAR::init()
{
// Register classes for QML
qmlRegisterType<SceneQuickView>("Esri.Samples", 1, 0, "SceneView");
qmlRegisterType<DisplayScenesInTabletopAR>("Esri.Samples", 1, 0, "DisplayScenesInTabletopARSample");
}
SceneQuickView* DisplayScenesInTabletopAR::sceneView() const
{
return m_sceneView;
}
// Set the view (created in QML)
void DisplayScenesInTabletopAR::setSceneView(SceneQuickView* sceneView)
{
if (!sceneView || sceneView == m_sceneView)
return;
m_sceneView = sceneView;
// Connect the mouse clicked events.
connect(m_sceneView, &SceneQuickView::mouseClicked, this, &DisplayScenesInTabletopAR::onMouseClicked);
m_sceneView->setArcGISScene(m_scene);
emit sceneViewChanged();
}
// Slot for handling when the package loads
void DisplayScenesInTabletopAR::packageLoaded(const Error& e)
{
if (!e.isEmpty())
{
qDebug() << QString("Package load error: %1 %2").arg(e.message(), e.additionalMessage());
return;
}
if (m_scenePackage->scenes().isEmpty())
return;
// Get the first scene
m_scene = m_scenePackage->scenes().at(0);
// Create a camera at the bottom and center of the scene.
// This camera is the point at which the scene is pinned to the real-world surface.
m_originCamera = Camera(39.95787000283599, -75.16996728256345, 8.813445091247559, 0, 90, 0);
}
// Create scene package and connect to signals
void DisplayScenesInTabletopAR::createScenePackage(const QString& path)
{
m_scenePackage = new MobileScenePackage(path, this);
connect(m_scenePackage, &MobileScenePackage::doneLoading, this, &DisplayScenesInTabletopAR::packageLoaded);
m_scenePackage->load();
}
void DisplayScenesInTabletopAR::onMouseClicked(QMouseEvent& event)
{
Q_CHECK_PTR(m_arcGISArView);
const QPoint screenPoint = event.localPos().toPoint();
if (!m_scene && !m_sceneView)
return;
// Display the scene
if (m_sceneView->arcGISScene() != m_scene)
{
m_sceneView->setArcGISScene(m_scene);
m_dialogVisible = false;
emit dialogVisibleChanged();
}
// Hide the base surface.
m_sceneView->arcGISScene()->baseSurface()->setOpacity(0.0f);
// Enable subsurface navigation. This allows you to look at the scene from below.
m_sceneView->arcGISScene()->baseSurface()->setNavigationConstraint(NavigationConstraint::None);
// Set the initial transformation using the point clicked on the screen
m_arcGISArView->setInitialTransformation(screenPoint);
// Set the origin camera.
m_arcGISArView->setOriginCamera(m_originCamera);
// Set the translation factor based on the scene content width and desired physical size.
m_arcGISArView->setTranslationFactor(m_sceneWidth/m_tableTopWidth);
emit sceneViewChanged();
emit arcGISArViewChanged();
}
|
enable pch
|
enable pch
|
C++
|
apache-2.0
|
Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt
|
6797bb10f28c7263e7965adeb424f9c5f9569ff8
|
src/zbase/zen-csv-upload.cc
|
src/zbase/zen-csv-upload.cc
|
/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "stx/stdtypes.h"
#include "stx/application.h"
#include "stx/cli/flagparser.h"
#include "stx/cli/CLI.h"
#include "stx/csv/CSVInputStream.h"
#include "stx/csv/BinaryCSVOutputStream.h"
#include "stx/io/file.h"
#include "stx/inspect.h"
#include "stx/human.h"
#include "stx/http/httpclient.h"
#include "stx/util/SimpleRateLimit.h"
#include "stx/protobuf/MessageSchema.h"
using namespace stx;
void run(const cli::FlagParser& flags) {
auto table_name = flags.getString("table_name");
auto input_file = flags.getString("input_file");
auto api_token = flags.getString("api_token");
String api_url = "http://api.zbase.io/api/v1";
auto shard_size = flags.getInt("shard_size");
stx::logInfo("dx-csv-upload", "Opening CSV file '$0'", input_file);
auto csv = CSVInputStream::openFile(
input_file,
'\t',
'\n');
stx::logInfo(
"dx-csv-upload",
"Analyzing the input file. This might take a few minutes...");
Vector<String> columns;
csv->readNextRow(&columns);
HashMap<String, HumanDataType> column_types;
for (const auto& hdr : columns) {
column_types[hdr] = HumanDataType::UNKNOWN;
}
Vector<String> row;
size_t num_rows = 0;
size_t num_rows_uploaded = 0;
while (csv->readNextRow(&row)) {
++num_rows;
for (size_t i = 0; i < row.size() && i < columns.size(); ++i) {
auto& ctype = column_types[columns[i]];
ctype = Human::detectDataTypeSeries(row[i], ctype);
}
}
Vector<msg::MessageSchemaField> schema_fields;
size_t field_num = 0;
for (const auto& col : columns) {
switch (column_types[col]) {
case HumanDataType::UNSIGNED_INTEGER:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::UINT64,
0,
false,
false);
break;
case HumanDataType::UNSIGNED_INTEGER_NULLABLE:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::UINT64,
0,
false,
true);
break;
case HumanDataType::SIGNED_INTEGER:
case HumanDataType::FLOAT:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::DOUBLE,
0,
false,
false);
break;
case HumanDataType::SIGNED_INTEGER_NULLABLE:
case HumanDataType::FLOAT_NULLABLE:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::DOUBLE,
0,
false,
true);
break;
case HumanDataType::BOOLEAN:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::BOOLEAN,
0,
false,
false);
break;
case HumanDataType::BOOLEAN_NULLABLE:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::BOOLEAN,
0,
false,
true);
break;
case HumanDataType::DATETIME:
case HumanDataType::DATETIME_NULLABLE:
case HumanDataType::URL:
case HumanDataType::URL_NULLABLE:
case HumanDataType::CURRENCY:
case HumanDataType::CURRENCY_NULLABLE:
case HumanDataType::TEXT:
case HumanDataType::NULL_OR_EMPTY:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::STRING,
0,
false,
true);
break;
case HumanDataType::UNKNOWN:
case HumanDataType::BINARY:
RAISEF(kTypeError, "invalid column type for column '$0'", col);
}
}
csv->rewind();
auto schema = mkRef(new msg::MessageSchema("<anonymous>", schema_fields));
stx::logDebug("dx-csv-upload", "Detected schema:\n$0", schema->toString());
auto num_shards = (num_rows + shard_size - 1) / shard_size;
stx::logDebug("dx-csv-upload", "Splitting into $0 shards", num_shards);
http::HTTPClient http_client;
http::HTTPMessage::HeaderList auth_headers;
auth_headers.emplace_back(
"Authorization",
StringUtil::format("Token $0", api_token));
/* build create table request */
Buffer create_req;
{
json::JSONOutputStream j(BufferOutputStream::fromBuffer(&create_req));
j.beginObject();
j.addObjectEntry("table_name");
j.addString(table_name);
j.addComma();
j.addObjectEntry("update");
j.addTrue();
j.addComma();
j.addObjectEntry("num_shards");
j.addInteger(num_shards);
j.addComma();
j.addObjectEntry("schema");
schema->toJSON(&j);
j.endObject();
}
auto create_res = http_client.executeRequest(
http::HTTPRequest::mkPost(
api_url + "/tables/create_table",
create_req,
auth_headers));
if (create_res.statusCode() != 201) {
RAISE(kRuntimeError, create_res.body().toString());
}
/* status line */
util::SimpleRateLimitedFn status_line(
kMicrosPerSecond,
[&num_rows_uploaded, num_rows] () {
stx::logInfo(
"dx-csv-upload",
"[$0%] Uploading... $1/$2 rows",
(size_t) ((num_rows_uploaded / (double) num_rows) * 100),
num_rows_uploaded,
num_rows);
});
csv->skipNextRow();
for (size_t nshard = 0; num_rows_uploaded < num_rows; ++nshard) {
Buffer shard_data;
BinaryCSVOutputStream shard_csv(
BufferOutputStream::fromBuffer(&shard_data));
shard_csv.appendRow(columns);
size_t num_rows_shard = 0;
while (num_rows_shard < shard_size && csv->readNextRow(&row)) {
++num_rows_uploaded;
++num_rows_shard;
shard_csv.appendRow(row);
status_line.runMaybe();
}
auto upload_uri = StringUtil::format(
"$0/tables/upload_table?table=$1&shard=$2",
api_url,
URI::urlEncode(table_name),
nshard);
auto upload_res = http_client.executeRequest(
http::HTTPRequest::mkPost(
upload_uri,
shard_data,
auth_headers));
if (upload_res.statusCode() != 201) {
RAISE(kRuntimeError, upload_res.body().toString());
}
}
status_line.runForce();
stx::logInfo("dx-csv-upload", "Upload finished successfully :)");
}
int main(int argc, const char** argv) {
stx::Application::init();
stx::Application::logToStderr();
stx::cli::FlagParser flags;
flags.defineFlag(
"loglevel",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.defineFlag(
"input_file",
stx::cli::FlagParser::T_STRING,
true,
"i",
NULL,
"input CSV file",
"<filename>");
flags.defineFlag(
"table_name",
stx::cli::FlagParser::T_STRING,
true,
"t",
NULL,
"table name",
"<name>");
flags.defineFlag(
"api_token",
stx::cli::FlagParser::T_STRING,
true,
"x",
NULL,
"DeepAnalytics API Token",
"<token>");
flags.defineFlag(
"shard_size",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"262144",
"shard size",
"<num>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
try {
run(flags);
} catch (const StandardException& e) {
stx::logError("dx-csv-upload", "[FATAL ERROR] $0", e.what());
}
return 0;
}
|
/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "stx/stdtypes.h"
#include "stx/application.h"
#include "stx/cli/flagparser.h"
#include "stx/cli/CLI.h"
#include "stx/csv/CSVInputStream.h"
#include "stx/csv/BinaryCSVOutputStream.h"
#include "stx/io/file.h"
#include "stx/inspect.h"
#include "stx/human.h"
#include "stx/http/httpclient.h"
#include "stx/util/SimpleRateLimit.h"
#include "stx/protobuf/MessageSchema.h"
using namespace stx;
void run(const cli::FlagParser& flags) {
auto table_name = flags.getString("table_name");
auto input_file = flags.getString("input_file");
auto api_token = flags.getString("api_token");
auto api_host = flags.getString("api_host");
auto shard_size = flags.getInt("shard_size");
stx::logInfo("dx-csv-upload", "Opening CSV file '$0'", input_file);
auto csv = CSVInputStream::openFile(
input_file,
'\t',
'\n');
stx::logInfo(
"dx-csv-upload",
"Analyzing the input file. This might take a few minutes...");
Vector<String> columns;
csv->readNextRow(&columns);
HashMap<String, HumanDataType> column_types;
for (const auto& hdr : columns) {
column_types[hdr] = HumanDataType::UNKNOWN;
}
Vector<String> row;
size_t num_rows = 0;
size_t num_rows_uploaded = 0;
while (csv->readNextRow(&row)) {
++num_rows;
for (size_t i = 0; i < row.size() && i < columns.size(); ++i) {
auto& ctype = column_types[columns[i]];
ctype = Human::detectDataTypeSeries(row[i], ctype);
}
}
Vector<msg::MessageSchemaField> schema_fields;
size_t field_num = 0;
for (const auto& col : columns) {
switch (column_types[col]) {
case HumanDataType::UNSIGNED_INTEGER:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::UINT64,
0,
false,
false);
break;
case HumanDataType::UNSIGNED_INTEGER_NULLABLE:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::UINT64,
0,
false,
true);
break;
case HumanDataType::SIGNED_INTEGER:
case HumanDataType::FLOAT:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::DOUBLE,
0,
false,
false);
break;
case HumanDataType::SIGNED_INTEGER_NULLABLE:
case HumanDataType::FLOAT_NULLABLE:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::DOUBLE,
0,
false,
true);
break;
case HumanDataType::BOOLEAN:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::BOOLEAN,
0,
false,
false);
break;
case HumanDataType::BOOLEAN_NULLABLE:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::BOOLEAN,
0,
false,
true);
break;
case HumanDataType::DATETIME:
case HumanDataType::DATETIME_NULLABLE:
case HumanDataType::URL:
case HumanDataType::URL_NULLABLE:
case HumanDataType::CURRENCY:
case HumanDataType::CURRENCY_NULLABLE:
case HumanDataType::TEXT:
case HumanDataType::NULL_OR_EMPTY:
schema_fields.emplace_back(
++field_num,
col,
msg::FieldType::STRING,
0,
false,
true);
break;
case HumanDataType::UNKNOWN:
case HumanDataType::BINARY:
RAISEF(kTypeError, "invalid column type for column '$0'", col);
}
}
csv->rewind();
auto schema = mkRef(new msg::MessageSchema("<anonymous>", schema_fields));
stx::logDebug("dx-csv-upload", "Detected schema:\n$0", schema->toString());
auto num_shards = (num_rows + shard_size - 1) / shard_size;
stx::logDebug("dx-csv-upload", "Splitting into $0 shards", num_shards);
http::HTTPClient http_client;
http::HTTPMessage::HeaderList auth_headers;
auth_headers.emplace_back(
"Authorization",
StringUtil::format("Token $0", api_token));
/* build create table request */
Buffer create_req;
{
json::JSONOutputStream j(BufferOutputStream::fromBuffer(&create_req));
j.beginObject();
j.addObjectEntry("table_name");
j.addString(table_name);
j.addComma();
j.addObjectEntry("update");
j.addTrue();
j.addComma();
j.addObjectEntry("num_shards");
j.addInteger(num_shards);
j.addComma();
j.addObjectEntry("schema");
schema->toJSON(&j);
j.endObject();
}
auto create_res = http_client.executeRequest(
http::HTTPRequest::mkPost(
"http://" + api_host + "/api/v1/tables/create_table",
create_req,
auth_headers));
if (create_res.statusCode() != 201) {
RAISE(kRuntimeError, create_res.body().toString());
}
/* status line */
util::SimpleRateLimitedFn status_line(
kMicrosPerSecond,
[&num_rows_uploaded, num_rows] () {
stx::logInfo(
"dx-csv-upload",
"[$0%] Uploading... $1/$2 rows",
(size_t) ((num_rows_uploaded / (double) num_rows) * 100),
num_rows_uploaded,
num_rows);
});
csv->skipNextRow();
for (size_t nshard = 0; num_rows_uploaded < num_rows; ++nshard) {
Buffer shard_data;
BinaryCSVOutputStream shard_csv(
BufferOutputStream::fromBuffer(&shard_data));
shard_csv.appendRow(columns);
size_t num_rows_shard = 0;
while (num_rows_shard < shard_size && csv->readNextRow(&row)) {
++num_rows_uploaded;
++num_rows_shard;
shard_csv.appendRow(row);
status_line.runMaybe();
}
auto upload_uri = StringUtil::format(
"http://$0/api/v1/tables/upload_table?table=$1&shard=$2",
api_host,
URI::urlEncode(table_name),
nshard);
auto upload_res = http_client.executeRequest(
http::HTTPRequest::mkPost(
upload_uri,
shard_data,
auth_headers));
if (upload_res.statusCode() != 201) {
RAISE(kRuntimeError, upload_res.body().toString());
}
}
status_line.runForce();
stx::logInfo("dx-csv-upload", "Upload finished successfully :)");
}
int main(int argc, const char** argv) {
stx::Application::init();
stx::Application::logToStderr();
stx::cli::FlagParser flags;
flags.defineFlag(
"loglevel",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.defineFlag(
"input_file",
stx::cli::FlagParser::T_STRING,
true,
"i",
NULL,
"input CSV file",
"<filename>");
flags.defineFlag(
"table_name",
stx::cli::FlagParser::T_STRING,
true,
"t",
NULL,
"table name",
"<name>");
flags.defineFlag(
"api_token",
stx::cli::FlagParser::T_STRING,
true,
"x",
NULL,
"DeepAnalytics API Token",
"<token>");
flags.defineFlag(
"api_host",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"api.zbase.io"
"DeepAnalytics API Host",
"<host>");
flags.defineFlag(
"shard_size",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"262144",
"shard size",
"<num>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
try {
run(flags);
} catch (const StandardException& e) {
stx::logError("dx-csv-upload", "[FATAL ERROR] $0", e.what());
}
return 0;
}
|
add --api_host flag in zen-csv-upload
|
add --api_host flag in zen-csv-upload
|
C++
|
agpl-3.0
|
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
|
0a2b73f6f620420105641e20237d5698e771a5c5
|
src/utils/EntryModel.hxx
|
src/utils/EntryModel.hxx
|
/** @copyright
* Copyright (c) 2017, Stuart W. Baker
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are strictly prohibited without written consent.
*
* 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.
*
* @file EntryModel.hxx
* This file represents a decimal/hex number entry field in text.
*
* @author Stuart W. Baker
* @date 1 December 2017
*/
#ifndef _UTILS_ENTRYMODEL_HXX_
#define _UTILS_ENTRYMODEL_HXX_
#include <algorithm>
#include <cstring>
#include <type_traits>
#include "utils/format_utils.hxx"
/** Implementation of a text entry menu.
* @tparam T the data type up to 64-bits in size
* @tparam N the size of the entry in max number of visible digits.
*/
template <class T, size_t N> class EntryModel
{
public:
/** Constructor.
* @param transform force characters to be upper case
*/
EntryModel(bool transform = false)
: digits_(0)
, index_(0)
, hasInitial_(false)
, transform_(transform)
, base_(10)
{
clear();
data_[N] = '\0';
}
/** Initialize empty.
* @param digits max number of significant digits in the base type
* @param base base type, 10 or 16
*/
void init(unsigned digits, int base)
{
HASSERT(digits > 0 && digits <= N);
digits_ = digits;
clear();
hasInitial_ = true;
}
/** Initialize with a value.
* @param digits max number of significant digits in the base type
* @param base base type, 10 or 16
* @param value value to initialize with
*/
void init(unsigned digits, int base, T value)
{
HASSERT(digits > 0 && digits <= N);
digits_ = digits;
clear();
string str;
switch (base)
{
default:
HASSERT(0);
case 10:
if (std::is_signed<T>::value)
{
str = int64_to_string(value, digits);
}
else
{
str = uint64_to_string(value, digits);
}
break;
case 16:
if (std::is_signed<T>::value)
{
str = int64_to_string_hex(value, digits);
}
else
{
str = uint64_to_string_hex(value, digits);
}
if (transform_)
{
/* equires all characters in upper case */
transform(str.begin(), str.end(), str.begin(), toupper);
}
break;
}
strncpy(data_, str.c_str(), sizeof(data_) - 1);
data_[sizeof(data_) - 1] = '\0';
hasInitial_ = true;
}
/** Clear the entry string.
* @param data data to fill in the buffer with
*/
void clear(const char *data = nullptr)
{
memset(data_, ' ', digits_);
if (data)
{
memcpy(data_, data, strlen(data));
}
data_[digits_] = '\0';
index_ = 0;
}
/** Get the current index.
* @return current cursor index
*/
unsigned cursor_index()
{
return index_;
}
/** Test if cursor is visible.
* @return true if cursor is visiable, else false
*/
bool cursor_visible()
{
return index_ < digits_;
}
/** Put a character at the current index, and increment the index by 1.
* @param c Character to place
* @return true if the string was cleared out and an LCD refresh is
* may be required.
*/
bool putc_inc(char c)
{
bool refresh = false;
if (index_ >= digits_)
{
refresh = true;
clear();
}
else
{
if (hasInitial_)
{
hasInitial_ = false;
refresh = true;
clear();
}
data_[index_++] = transform_ ? toupper(c) : c;
}
clamp();
return refresh;
}
/** Delete a character off the end.
*/
void backspace()
{
if (index_ > 0)
{
data_[--index_] = ' ';
hasInitial_ = false;
}
clamp();
}
/** Set the radix base.
* @param base new radix base to set.
*/
void set_base(int base)
{
HASSERT(base == 10 || base == 16);
base_ = base;
}
/** Set the value, keep the digits and base the same.
* @param value value to initialize with
*/
void set_value(T value)
{
init(digits_, base_, value);
}
/** Get the entry as an unsigned integer value.
* @param start_index starting index in string to start conversion
* @return value representation of the string
*/
T get_value(unsigned start_index = 0)
{
if (std::is_signed<T>::value)
{
return strtoll(data_ + start_index, NULL, base_);
}
else
{
return strtoull(data_ + start_index, NULL, base_);
}
}
/** Get the C style string representing the menu entry.
* @return the string data representing the menu entry
*/
const char *c_str()
{
return data_;
}
/** Get a copy of the string without any whitespace.
* @param strip_leading true to also strip off leading '0' or ' '
* @return the string data representing the menu entry
*/
string parsed(bool strip_leading = false)
{
const char *parse = data_;
string result;
result.reserve(N);
if (strip_leading)
{
while (*parse == '0' || *parse == ' ')
{
++parse;
}
}
while (*parse != ' ' && *parse != '\0')
{
result.push_back(*parse++);
}
return result;
}
/** Copy the entry data into the middle of a buffer.
* @param buf pointer to destination buffer
* @param start_index starting index of buffer for the copy destination
* @param digits number of digits to copy
*/
void copy_to_buffer(char *buf, int start_index, int digits)
{
HASSERT(digits <= digits_);
memcpy(buf + start_index, data_, digits);
}
/** Change the sign of the data.
*/
void change_sign()
{
HASSERT(std::is_signed<T>::value);
if (hasInitial_)
{
set_value(-get_value());
}
else if (data_[0] == '-')
{
memmove(data_, data_ + 1, digits_ - 1);
data_[digits_] = ' ';
}
else
{
memmove(data_ + 1, data_, digits_ - 1);
data_[0] = '-';
}
clamp();
}
/// Get the number of significant digits
/// @return number of significant digits
unsigned digits()
{
return digits_;
}
/// Determine if this object is holding an initial or modified value.
/// @return true if holding an initial value, else false if modified
bool has_initial()
{
return hasInitial_;
}
protected:
/// Clamp the value at the min or max.
virtual void clamp()
{
}
private:
unsigned digits_ : 5; /**< number of significant digits */
unsigned index_ : 5; /**< present write index */
unsigned hasInitial_ : 1; /**< has an initial value */
unsigned transform_ : 1; /**< force characters to be upper case */
unsigned reserved_ : 20; /**< reserved bit space */
int base_; /**< radix base */
char data_[N + 1]; /**< data string */
DISALLOW_COPY_AND_ASSIGN(EntryModel);
};
/** Specialization of EntryModel with upper and lower bounds
* @tparam T the data type up to 64-bits in size
* @tparam N the size of the entry in max number of visible digits.
*/
template <class T, size_t N> class EntryModelBounded : public EntryModel<T, N>
{
public:
/** Constructor.
* @param transform force characters to be upper case
*/
EntryModelBounded(bool transform = false)
: EntryModel<T, N>(transform)
{
}
/** Initialize with a value.
* @param digits max number of significant digits in the base type
* @param base base type, 10 or 16
* @param value unsigned value to initialize with
* @param min minumum value
* @param max maximum value
* @param default_val default value
*/
void init(unsigned digits, int base, T value, T min, T max, T default_val)
{
min_ = min;
max_ = max;
default_ = default_val;
EntryModel<T, N>::init(digits, base, value);
}
/// Set the value to the minimum.
void set_min()
{
EntryModel<T, N>::set_value(min_);
}
/// Set the value to the maximum.
void set_max()
{
EntryModel<T, N>::set_value(max_);
}
/// Set the value to the default.
void set_default()
{
EntryModel<T, N>::set_value(default_);
}
private:
/// Clamp the value at the min or max.
void clamp() override
{
T value = EntryModel<T, N>::get_value();
if (value < min_)
{
EntryModel<T, N>::set_value(min_);
}
else if (value > max_)
{
EntryModel<T, N>::set_value(max_);
}
}
T min_; ///< minimum value
T max_; ///< maximum value
T default_; ///< default value
DISALLOW_COPY_AND_ASSIGN(EntryModelBounded);
};
#endif /* _UTILS_ENTRYMODEL_HXX_ */
|
/** @copyright
* Copyright (c) 2017, Stuart W. Baker
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are strictly prohibited without written consent.
*
* 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.
*
* @file EntryModel.hxx
* This file represents a decimal/hex number entry field in text.
*
* @author Stuart W. Baker
* @date 1 December 2017
*/
#ifndef _UTILS_ENTRYMODEL_HXX_
#define _UTILS_ENTRYMODEL_HXX_
#include <algorithm>
#include <cstring>
#include <functional>
#include <type_traits>
#include "utils/format_utils.hxx"
/** Implementation of a text entry menu.
* @tparam T the data type up to 64-bits in size
* @tparam N the size of the entry in max number of visible digits.
*/
template <class T, size_t N>
class EntryModel
{
public:
/** Constructor.
* @param transform force characters to be upper case
* @param clamp_callback callback method to clamp min/max
*/
EntryModel(bool transform = false,
std::function<void()> clamp_callback = nullptr)
: clampCallback_(clamp_callback)
, digits_(0)
, index_(0)
, hasInitial_(false)
, transform_(transform)
, base_(10)
{
clear();
data_[N] = '\0';
}
/** Initialize empty.
* @param digits max number of significant digits in the base type
* @param base base type, 10 or 16
*/
void init(unsigned digits, int base)
{
HASSERT(digits <= N);
digits_ = digits;
clear();
hasInitial_ = true;
}
/** Initialize with a value.
* @param digits max number of significant digits in the base type
* @param base base type, 10 or 16
* @param value value to initialize with
*/
void init(unsigned digits, int base, T value)
{
HASSERT(digits <= N);
digits_ = digits;
clear();
string str;
switch (base)
{
default:
HASSERT(0);
case 10:
if (std::is_signed<T>::value)
{
str = int64_to_string(value, digits);
}
else
{
str = uint64_to_string(value, digits);
}
break;
case 16:
if (std::is_signed<T>::value)
{
str = int64_to_string_hex(value, digits);
}
else
{
str = uint64_to_string_hex(value, digits);
}
if (transform_)
{
/* equires all characters in upper case */
transform(str.begin(), str.end(), str.begin(), toupper);
}
break;
}
strncpy(data_, str.c_str(), sizeof(data_) - 1);
data_[sizeof(data_) - 1] = '\0';
hasInitial_ = true;
}
/** Clear the entry string.
* @param data data to fill in the buffer with
*/
void clear(const char *data = nullptr)
{
memset(data_, ' ', digits_);
if (data)
{
memcpy(data_, data, strlen(data));
}
data_[digits_] = '\0';
index_ = 0;
}
/** Get the current index.
* @return current cursor index
*/
unsigned cursor_index()
{
return index_;
}
/** Test if cursor is visible.
* @return true if cursor is visiable, else false
*/
bool cursor_visible()
{
return index_ < digits_;
}
/** Put a character at the current index, and increment the index by 1.
* @param c Character to place
* @return true if the string was cleared out and an LCD refresh is
* may be required.
*/
bool putc_inc(char c)
{
bool refresh = false;
if (index_ >= digits_)
{
refresh = true;
clear();
}
else
{
if (hasInitial_)
{
hasInitial_ = false;
refresh = true;
clear();
}
data_[index_++] = transform_ ? toupper(c) : c;
}
clamp();
return refresh;
}
/** Delete a character off the end.
*/
void backspace()
{
if (index_ > 0)
{
data_[--index_] = ' ';
hasInitial_ = false;
}
clamp();
}
/** Set the radix base.
* @param base new radix base to set.
*/
void set_base(int base)
{
HASSERT(base == 10 || base == 16);
base_ = base;
}
/** Set the value, keep the digits and base the same.
* @param value value to initialize with
*/
void set_value(T value)
{
init(digits_, base_, value);
}
/** Get the entry as an unsigned integer value.
* @param start_index starting index in string to start conversion
* @return value representation of the string
*/
T get_value(unsigned start_index = 0)
{
HASSERT(start_index < digits_);
if (std::is_signed<T>::value)
{
return strtoll(data_ + start_index, NULL, base_);
}
else
{
return strtoull(data_ + start_index, NULL, base_);
}
}
/** Get the C style string representing the menu entry.
* @return the string data representing the menu entry
*/
const char *c_str()
{
return data_;
}
/** Get a copy of the string without any whitespace.
* @param strip_leading true to also strip off leading '0' or ' '
* @return the string data representing the menu entry
*/
string parsed(bool strip_leading = false)
{
const char *parse = data_;
string result;
result.reserve(N);
if (strip_leading)
{
while (*parse == '0' || *parse == ' ')
{
++parse;
}
}
while (*parse != ' ' && *parse != '\0')
{
result.push_back(*parse++);
}
return result;
}
/** Copy the entry data into the middle of a buffer.
* @param buf pointer to destination buffer
* @param start_index starting index of buffer for the copy destination
* @param digits number of digits to copy
*/
void copy_to_buffer(char *buf, int start_index, int digits)
{
HASSERT(digits <= digits_);
memcpy(buf + start_index, data_, digits);
}
/** Change the sign of the data.
*/
void change_sign()
{
HASSERT(std::is_signed<T>::value);
if (hasInitial_)
{
set_value(-get_value());
}
else if (data_[0] == '-')
{
memmove(data_, data_ + 1, digits_ - 1);
data_[digits_] = ' ';
}
else
{
memmove(data_ + 1, data_, digits_ - 1);
data_[0] = '-';
}
clamp();
}
/// Get the number of significant digits
/// @return number of significant digits
unsigned digits()
{
return digits_;
}
/// Determine if this object is holding an initial or modified value.
/// @return true if holding an initial value, else false if modified
bool has_initial()
{
return hasInitial_;
}
/// Clamp the value at the min or max.
void clamp()
{
if (clampCallback_)
{
clampCallback_();
}
}
private:
std::function<void()> clampCallback_; /**< callback to clamp value */
unsigned digits_ : 5; /**< number of significant digits */
unsigned index_ : 5; /**< present write index */
unsigned hasInitial_ : 1; /**< has an initial value */
unsigned transform_ : 1; /**< force characters to be upper case */
unsigned reserved_ : 20; /**< reserved bit space */
int base_; /**< radix base */
char data_[N + 1]; /**< data string */
DISALLOW_COPY_AND_ASSIGN(EntryModel);
};
/** Specialization of EntryModel with upper and lower bounds
* @tparam T the data type up to 64-bits in size
* @tparam N the size of the entry in max number of visible digits.
*/
template <class T, size_t N> class EntryModelBounded : public EntryModel<T, N>
{
public:
/** Constructor.
* @param transform force characters to be upper case
*/
EntryModelBounded(bool transform = false)
: EntryModel<T, N>(transform,
std::bind(&EntryModelBounded::clamp, this))
{
}
/** Initialize with a value.
* @param digits max number of significant digits in the base type
* @param base base type, 10 or 16
* @param value unsigned value to initialize with
* @param min minumum value
* @param max maximum value
* @param default_val default value
*/
void init(unsigned digits, int base, T value, T min, T max, T default_val)
{
min_ = min;
max_ = max;
default_ = default_val;
EntryModel<T, N>::init(digits, base, value);
}
/// Set the value to the minimum.
void set_min()
{
EntryModel<T, N>::set_value(min_);
}
/// Set the value to the maximum.
void set_max()
{
EntryModel<T, N>::set_value(max_);
}
/// Set the value to the default.
void set_default()
{
EntryModel<T, N>::set_value(default_);
}
private:
/// Clamp the value at the min or max.
void clamp()
{
volatile T value = EntryModel<T, N>::get_value();
if (value < min_)
{
EntryModel<T, N>::set_value(min_);
}
else if (value > max_)
{
EntryModel<T, N>::set_value(max_);
}
}
T min_; ///< minimum value
T max_; ///< maximum value
T default_; ///< default value
DISALLOW_COPY_AND_ASSIGN(EntryModelBounded);
};
#endif /* _UTILS_ENTRYMODEL_HXX_ */
|
fix ill formed clamp method.
|
fix ill formed clamp method.
|
C++
|
bsd-2-clause
|
bakerstu/openmrn,bakerstu/openmrn,bakerstu/openmrn,bakerstu/openmrn,bakerstu/openmrn,bakerstu/openmrn
|
166e50ead5757ecc39ebd8e49acca68d52898ec2
|
src/views/ds3_browser.cc
|
src/views/ds3_browser.cc
|
/*
* *****************************************************************************
* Copyright 2014-2015 Spectra Logic Corporation. 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. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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 <QMenu>
#include "lib/client.h"
#include "lib/logger.h"
#include "models/ds3_browser_model.h"
#include "models/session.h"
#include "views/ds3_delete_dialog.h"
#include "views/buckets/new_bucket_dialog.h"
#include "views/buckets/delete_bucket_dialog.h"
#include "views/objects/delete_objects_dialog.h"
#include "views/ds3_browser.h"
#include "views/jobs_view.h"
static const QString BUCKET = "Bucket";
DS3Browser::DS3Browser(Client* client, JobsView* jobsView,
QWidget* parent, Qt::WindowFlags flags)
: Browser(client, parent, flags),
m_jobsView(jobsView)
{
AddCustomToolBarActions();
m_model = new DS3BrowserModel(m_client, this);
m_model->SetView(m_treeView);
m_treeView->setModel(m_model);
m_searchBar = new QLineEdit();
m_searchBar->setPlaceholderText("Search");
m_searchBar->setToolTip("Search in current folder");
m_layout->addWidget(m_searchBar,1,2,1,1);
m_searchModel = new DS3SearchModel(m_client, this);
m_searchView = new DS3SearchTree();
// Remove the focus rectangle around the search view on OSX.
m_searchView->setAttribute(Qt::WA_MacShowFocusRect, 0);
connect(m_treeView, SIGNAL(clicked(const QModelIndex&)),
this, SLOT(OnModelItemClick(const QModelIndex&)));
connect(m_client, SIGNAL(JobProgressUpdate(const Job)),
this, SLOT(HandleJobUpdate(const Job)));
connect(m_client, SIGNAL(JobProgressUpdate(const Job)),
m_jobsView, SLOT(UpdateJob(const Job)));
connect(m_searchBar, SIGNAL(returnPressed()),
this, SLOT(BeginSearch()));
}
void
DS3Browser::HandleJobUpdate(const Job job)
{
Job::State state = job.GetState();
if (state == Job::FINISHED) {
Refresh();
}
}
void
DS3Browser::AddCustomToolBarActions()
{
m_rootAction = new QAction(QIcon(":/resources/icons/root_directory.png"),
"Root directory", this);
connect(m_rootAction, SIGNAL(triggered()), this, SLOT(GoToRoot()));
m_toolBar->addAction(m_rootAction);
m_refreshAction = new QAction(style()->standardIcon(QStyle::SP_BrowserReload),
"Refresh", this);
connect(m_refreshAction, SIGNAL(triggered()), this, SLOT(Refresh()));
m_toolBar->addAction(m_refreshAction);
QString searchIcon = QString::fromUtf8("\uf002");
m_searchAction = new QAction(searchIcon, this);
m_searchAction->setFont(QFont("FontAwesome", 16));
m_searchAction->setText(searchIcon);
m_searchAction->setToolTip("Search");
connect(m_searchAction, SIGNAL(triggered()), this, SLOT(BeginSearch()));
m_toolBar->addAction(m_searchAction);
QString leftArrow = QString::fromUtf8("\uf060");
m_transferAction = new QAction(leftArrow, this);
m_transferAction->setFont(QFont("FontAwesome", 16));
m_transferAction->setText(leftArrow);
m_transferAction->setEnabled(false);
m_transferAction->setToolTip("Transfer to Host");
connect(m_transferAction, SIGNAL(triggered()), this, SLOT(PrepareTransfer()));
m_toolBar->addAction(m_transferAction);
}
QString
DS3Browser::IndexToPath(const QModelIndex& index) const
{
return m_model->GetPath(index);
}
void
DS3Browser::OnContextMenuRequested(const QPoint& /*pos*/)
{
QMenu menu;
QAction newBucketAction("New Bucket", &menu);
QAction deleteAction("Delete", &menu);
QModelIndex index = m_treeView->rootIndex();
bool atBucketListingLevel = !index.isValid();
if (atBucketListingLevel) {
menu.addAction(&newBucketAction);
}
menu.addAction(&deleteAction);
if (m_treeView->selectionModel()->selectedRows().count() == 0) {
// We could also disable the delete action for other conditions
// (selecting a folder object), however, we don't currently
// have a good way to inform the user why it's disabled.
// Maybe if we had a delete action to the toolbar, we can
// add a tooltip but we can't add a tooltip to a QAction that's
// in a QMenu.
deleteAction.setEnabled(false);
}
QAction* selectedAction = menu.exec(QCursor::pos());
if (!selectedAction) {
return;
}
if (selectedAction == &newBucketAction) {
CreateBucket();
} else if (selectedAction == &deleteAction) {
DeleteSelected();
}
}
void
DS3Browser::OnModelItemDoubleClick(const QModelIndex& index)
{
if (m_model->IsBucketOrFolder(index)) {
QString path = IndexToPath(index);
m_treeView->setRootIndex(index);
UpdatePathLabel(path);
}
}
void
DS3Browser::Refresh()
{
QModelIndex index = m_treeView->rootIndex();
if (m_model->IsFetching(index)) {
return;
}
m_model->Refresh(index);
QString path = IndexToPath(index);
UpdatePathLabel(path);
m_treeView->setRootIndex(index);
}
void
DS3Browser::OnModelItemClick(const QModelIndex& index)
{
if (m_model->IsPageBreak(index)) {
m_model->fetchMore(index.parent());
}
emit Transferable();
}
void
DS3Browser::CreateBucket()
{
NewBucketDialog newBucketDialog(m_client);
if (newBucketDialog.exec() == QDialog::Rejected) {
return;
}
Refresh();
}
void
DS3Browser::DeleteSelected()
{
QModelIndexList selectedIndexes = m_treeView->selectionModel()->selectedRows();
if (selectedIndexes.count() == 0) {
LOG_ERROR("ERROR: DELETE OBJECT failed, nothing selected to delete");
return;
}
QModelIndex selectedIndex = selectedIndexes[0];
DS3DeleteDialog* dialog;
QString bucketName = m_model->GetBucketName(selectedIndex);
QStringList objectList, folderList;
for (int i=0; i<selectedIndexes.size(); i++) {
if (m_model->IsBucket(selectedIndexes[i])) {
QString name = m_model->GetFullName(selectedIndexes[i]);
dialog = new DeleteBucketDialog(m_client, name);
if (dialog->exec() == QDialog::Accepted) {
Refresh();
}
delete dialog;
return;
} else if (m_model->IsFolder(selectedIndexes[i])) {
folderList << m_model->GetFullName(selectedIndexes[i]);
objectList << m_model->GetFullName(selectedIndexes[i])+"/";
} else {
objectList << m_model->GetFullName(selectedIndexes[i]);
}
}
objectList.sort();
if(objectList.size() > 0) {
dialog = new DeleteObjectsDialog(m_client, bucketName, objectList);
if (dialog->exec() == QDialog::Accepted) {
if(folderList.size() > 0) {
m_client->DeleteFolders(bucketName, folderList);
}
Refresh();
}
delete dialog;
}
}
bool
DS3Browser::IsBucketSelectedOnly() const
{
QModelIndexList selectedIndexes = m_treeView->selectionModel()->selectedRows(0);
bool bucketSelected = false;
if (selectedIndexes.count() == 1) {
QModelIndex selectedIndex = selectedIndexes[0];
if (m_model->IsBucket(selectedIndex)) {
bucketSelected = true;
}
}
return bucketSelected;
}
// This is called when enter is pressed in the search bar
void
DS3Browser::BeginSearch()
{
// Recreate the search model and view
delete m_searchModel;
delete m_searchView;
m_searchModel = new DS3SearchModel(m_client, this);
m_searchView = new DS3SearchTree();
// Remove the focus rectangle around the search view on OSX.
m_searchView->setAttribute(Qt::WA_MacShowFocusRect, 0);
// Connect the slot to display the search results for later
connect(m_searchModel, SIGNAL(DoneSearching(bool)), this, SLOT(CreateSearchTree(bool)));
// Retrieve the index for the DS3 view
QModelIndex index = m_treeView->rootIndex();
// If the current root has children, run the search
if(m_model->hasChildren(index)) {
GetServiceWatcher* watcher = new GetServiceWatcher(index);
connect(watcher, SIGNAL(finished()), this, SLOT(RunSearch()));
QFuture<ds3_get_service_response*> future = m_client->GetService();
watcher->setFuture(future);
}
}
// This slot starts the actual search
void
DS3Browser::RunSearch() {
// Watcher has to be set here in order to pass it to the search model
GetServiceWatcher* watcher = static_cast<GetServiceWatcher*>(sender());
// Passing through the search term, tree view, ds3 model, and the watcher
m_searchModel->HandleGetServiceResponse(m_searchBar->text(), m_treeView, m_model, watcher);
// Delete watcher when complete
delete watcher;
}
// This slot is run when the search model is done searching
void
DS3Browser::CreateSearchTree(bool found) {
// If nothing was found, then don't let users drag the warning message off of list
if(!found)
m_searchView->setDragEnabled(false);
// Set the model and tree to use each other
m_searchModel->SetView(m_searchView);
m_searchView->setModel(m_searchModel);
// Add the widget to the GUI
m_layout->addWidget(m_searchView,4,1,1,2);
}
DS3SearchTree::DS3SearchTree() : QTreeView::QTreeView()
{
// Lets the user drag files off of search
this->setDragEnabled(true);
// Since this is a flat list, we don't need indentation
this->setIndentation(0);
// Sorts the search results alphabetically
this->sortByColumn(0, Qt::AscendingOrder);
}
bool
DS3Browser::CanReceive(QModelIndex& index)
{
bool able = false;
QModelIndexList indicies = GetSelected();
if (indicies.isEmpty()) {
index = m_treeView->rootIndex();
} else if (indicies.count() == 1) {
index = indicies[0];
}
if ((index.isValid()) && (m_model->IsBucket(index) || m_model->IsFolder(index))) {
able = true;
}
return able;
}
void
DS3Browser::CanTransfer(bool enable)
{
m_transferAction->setEnabled(enable);
}
QModelIndexList
DS3Browser::GetSelected()
{
return m_treeView->selectionModel()->selectedRows(0);
}
void
DS3Browser::PrepareTransfer()
{
emit StartTransfer(m_model->mimeData(GetSelected()));
}
void
DS3Browser::GetData(QMimeData* data)
{
// Row and column for this call are -1 so that the data is "dropped" directly
// on the parent index given
m_model->dropMimeData(data, Qt::CopyAction, -1, -1, m_treeView->rootIndex());
}
void
DS3Browser::SetViewRoot(const QModelIndex& index)
{
OnModelItemDoubleClick(index);
}
|
/*
* *****************************************************************************
* Copyright 2014-2015 Spectra Logic Corporation. 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. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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 <QMenu>
#include "lib/client.h"
#include "lib/logger.h"
#include "models/ds3_browser_model.h"
#include "models/session.h"
#include "views/ds3_delete_dialog.h"
#include "views/buckets/new_bucket_dialog.h"
#include "views/buckets/delete_bucket_dialog.h"
#include "views/objects/delete_objects_dialog.h"
#include "views/ds3_browser.h"
#include "views/jobs_view.h"
static const QString BUCKET = "Bucket";
DS3Browser::DS3Browser(Client* client, JobsView* jobsView,
QWidget* parent, Qt::WindowFlags flags)
: Browser(client, parent, flags),
m_jobsView(jobsView)
{
AddCustomToolBarActions();
m_model = new DS3BrowserModel(m_client, this);
m_model->SetView(m_treeView);
m_treeView->setModel(m_model);
m_searchBar = new QLineEdit();
m_searchBar->setPlaceholderText("Search");
m_searchBar->setToolTip("Search in current folder");
m_layout->addWidget(m_searchBar,1,2,1,1);
m_searchModel = new DS3SearchModel(m_client, this);
m_searchView = new DS3SearchTree();
// Remove the focus rectangle around the search view on OSX.
m_searchView->setAttribute(Qt::WA_MacShowFocusRect, 0);
connect(m_treeView, SIGNAL(clicked(const QModelIndex&)),
this, SLOT(OnModelItemClick(const QModelIndex&)));
connect(m_client, SIGNAL(JobProgressUpdate(const Job)),
this, SLOT(HandleJobUpdate(const Job)));
connect(m_client, SIGNAL(JobProgressUpdate(const Job)),
m_jobsView, SLOT(UpdateJob(const Job)));
connect(m_searchBar, SIGNAL(returnPressed()),
this, SLOT(BeginSearch()));
}
void
DS3Browser::HandleJobUpdate(const Job job)
{
Job::State state = job.GetState();
if (state == Job::FINISHED) {
Refresh();
}
}
void
DS3Browser::AddCustomToolBarActions()
{
m_rootAction = new QAction(QIcon(":/resources/icons/root_directory.png"),
"Root directory", this);
connect(m_rootAction, SIGNAL(triggered()), this, SLOT(GoToRoot()));
m_toolBar->addAction(m_rootAction);
m_refreshAction = new QAction(style()->standardIcon(QStyle::SP_BrowserReload),
"Refresh", this);
connect(m_refreshAction, SIGNAL(triggered()), this, SLOT(Refresh()));
m_toolBar->addAction(m_refreshAction);
QString searchIcon = QString::fromUtf8("\uf002");
m_searchAction = new QAction(searchIcon, this);
m_searchAction->setFont(QFont("FontAwesome", 16));
m_searchAction->setText(searchIcon);
m_searchAction->setToolTip("Search");
connect(m_searchAction, SIGNAL(triggered()), this, SLOT(BeginSearch()));
m_toolBar->addAction(m_searchAction);
QString leftArrow = QString::fromUtf8("\uf060");
m_transferAction = new QAction(leftArrow, this);
m_transferAction->setFont(QFont("FontAwesome", 16));
m_transferAction->setText(leftArrow);
m_transferAction->setEnabled(false);
m_transferAction->setToolTip("Transfer to Host");
connect(m_transferAction, SIGNAL(triggered()), this, SLOT(PrepareTransfer()));
m_toolBar->addAction(m_transferAction);
}
QString
DS3Browser::IndexToPath(const QModelIndex& index) const
{
return m_model->GetPath(index);
}
void
DS3Browser::OnContextMenuRequested(const QPoint& /*pos*/)
{
QMenu menu;
QAction newBucketAction("New Bucket", &menu);
QAction deleteAction("Delete", &menu);
QModelIndex index = m_treeView->rootIndex();
bool atBucketListingLevel = !index.isValid();
if (atBucketListingLevel) {
menu.addAction(&newBucketAction);
}
menu.addAction(&deleteAction);
if (m_treeView->selectionModel()->selectedRows().count() == 0) {
// We could also disable the delete action for other conditions
// (selecting a folder object), however, we don't currently
// have a good way to inform the user why it's disabled.
// Maybe if we had a delete action to the toolbar, we can
// add a tooltip but we can't add a tooltip to a QAction that's
// in a QMenu.
deleteAction.setEnabled(false);
}
QAction* selectedAction = menu.exec(QCursor::pos());
if (!selectedAction) {
return;
}
if (selectedAction == &newBucketAction) {
CreateBucket();
} else if (selectedAction == &deleteAction) {
DeleteSelected();
}
}
void
DS3Browser::OnModelItemDoubleClick(const QModelIndex& index)
{
if (m_model->IsBucketOrFolder(index)) {
QString path = IndexToPath(index);
m_treeView->setRootIndex(index);
UpdatePathLabel(path);
}
}
void
DS3Browser::Refresh()
{
QModelIndex index = m_treeView->rootIndex();
if (m_model->IsFetching(index)) {
return;
}
m_model->Refresh(index);
QString path = IndexToPath(index);
UpdatePathLabel(path);
m_treeView->setRootIndex(index);
}
void
DS3Browser::OnModelItemClick(const QModelIndex& index)
{
if (m_model->IsPageBreak(index)) {
m_model->fetchMore(index.parent());
}
emit Transferable();
}
void
DS3Browser::CreateBucket()
{
NewBucketDialog newBucketDialog(m_client);
if (newBucketDialog.exec() == QDialog::Rejected) {
return;
}
Refresh();
}
void
DS3Browser::DeleteSelected()
{
QModelIndexList selectedIndexes = m_treeView->selectionModel()->selectedRows();
if (selectedIndexes.count() == 0) {
LOG_ERROR("ERROR: DELETE OBJECT failed, nothing selected to delete");
return;
}
QModelIndex selectedIndex = selectedIndexes[0];
DS3DeleteDialog* dialog;
QString bucketName = m_model->GetBucketName(selectedIndex);
QStringList objectList, folderList;
for (int i=0; i<selectedIndexes.size(); i++) {
if (m_model->IsBucket(selectedIndexes[i])) {
QString name = m_model->GetFullName(selectedIndexes[i]);
dialog = new DeleteBucketDialog(m_client, name);
if (dialog->exec() == QDialog::Accepted) {
Refresh();
}
delete dialog;
return;
} else if (m_model->IsFolder(selectedIndexes[i])) {
folderList << m_model->GetFullName(selectedIndexes[i]);
objectList << m_model->GetFullName(selectedIndexes[i])+"/";
} else {
objectList << m_model->GetFullName(selectedIndexes[i]);
}
}
objectList.sort();
if(objectList.size() > 0) {
dialog = new DeleteObjectsDialog(m_client, bucketName, objectList);
if (dialog->exec() == QDialog::Accepted) {
if(folderList.size() > 0) {
m_client->DeleteFolders(bucketName, folderList);
}
Refresh();
}
delete dialog;
}
}
bool
DS3Browser::IsBucketSelectedOnly() const
{
QModelIndexList selectedIndexes = m_treeView->selectionModel()->selectedRows(0);
bool bucketSelected = false;
if (selectedIndexes.count() == 1) {
QModelIndex selectedIndex = selectedIndexes[0];
if (m_model->IsBucket(selectedIndex)) {
bucketSelected = true;
}
}
return bucketSelected;
}
// This is called when enter is pressed in the search bar
void
DS3Browser::BeginSearch()
{
// Recreate the search model and view
delete m_searchModel;
delete m_searchView;
m_searchModel = new DS3SearchModel(m_client, this);
m_searchView = new DS3SearchTree();
// Remove the focus rectangle around the search view on OSX.
m_searchView->setAttribute(Qt::WA_MacShowFocusRect, 0);
// Connect the slot to display the search results for later
connect(m_searchModel, SIGNAL(DoneSearching(bool)), this, SLOT(CreateSearchTree(bool)));
// Retrieve the index for the DS3 view
QModelIndex index = m_treeView->rootIndex();
// If the current root has children, run the search
if(m_model->hasChildren(index)) {
GetServiceWatcher* watcher = new GetServiceWatcher(index);
connect(watcher, SIGNAL(finished()), this, SLOT(RunSearch()));
QFuture<ds3_get_service_response*> future = m_client->GetService();
watcher->setFuture(future);
}
}
// This slot starts the actual search
void
DS3Browser::RunSearch() {
// Watcher has to be set here in order to pass it to the search model
GetServiceWatcher* watcher = static_cast<GetServiceWatcher*>(sender());
// Passing through the search term, tree view, ds3 model, and the watcher
m_searchModel->HandleGetServiceResponse(m_searchBar->text(), m_treeView, m_model, watcher);
// Delete watcher when complete
delete watcher;
}
// This slot is run when the search model is done searching
void
DS3Browser::CreateSearchTree(bool found) {
// If nothing was found, then don't let users drag the warning message off of list
if(!found)
m_searchView->setDragEnabled(false);
// Set the model and tree to use each other
m_searchModel->SetView(m_searchView);
m_searchView->setModel(m_searchModel);
// Add the widget to the GUI
m_layout->addWidget(m_searchView,4,1,1,2);
}
DS3SearchTree::DS3SearchTree()
: QTreeView()
{
// Lets the user drag files off of search
setDragEnabled(true);
// Since this is a flat list, we don't need indentation
setIndentation(0);
// Sorts the search results alphabetically
sortByColumn(0, Qt::AscendingOrder);
}
bool
DS3Browser::CanReceive(QModelIndex& index)
{
bool able = false;
QModelIndexList indicies = GetSelected();
if (indicies.isEmpty()) {
index = m_treeView->rootIndex();
} else if (indicies.count() == 1) {
index = indicies[0];
}
if ((index.isValid()) && (m_model->IsBucket(index) || m_model->IsFolder(index))) {
able = true;
}
return able;
}
void
DS3Browser::CanTransfer(bool enable)
{
m_transferAction->setEnabled(enable);
}
QModelIndexList
DS3Browser::GetSelected()
{
return m_treeView->selectionModel()->selectedRows(0);
}
void
DS3Browser::PrepareTransfer()
{
emit StartTransfer(m_model->mimeData(GetSelected()));
}
void
DS3Browser::GetData(QMimeData* data)
{
// Row and column for this call are -1 so that the data is "dropped" directly
// on the parent index given
m_model->dropMimeData(data, Qt::CopyAction, -1, -1, m_treeView->rootIndex());
}
void
DS3Browser::SetViewRoot(const QModelIndex& index)
{
OnModelItemDoubleClick(index);
}
|
Fix the DS3SearchTree constructor definition to eliminate a warning on Windows. Eliminate unnecessary "this->" references.
|
Fix the DS3SearchTree constructor definition to eliminate a warning
on Windows. Eliminate unnecessary "this->" references.
|
C++
|
apache-2.0
|
Klopsch/ds3_browser,Klopsch/ds3_browser,SpectraLogic/ds3_browser,SpectraLogic/ds3_browser,SpectraLogic/ds3_browser,Klopsch/ds3_browser
|
f5e6ccbcfe219ca2830664080a1a6ea87d30015d
|
src/Clazy.cpp
|
src/Clazy.cpp
|
/*
This file is part of the clazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected]
Author: Sérgio Martins <[email protected]>
Copyright (C) 2015-2017 Sergio Martins <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "Utils.h"
#include "Clazy.h"
#include "StringUtils.h"
#include "clazy_stl.h"
#include "checkbase.h"
#include "AccessSpecifierManager.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/ParentMap.h"
#include <llvm/Config/llvm-config.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
using namespace clang;
using namespace std;
using namespace clang::ast_matchers;
static void manuallyPopulateParentMap(ParentMap *map, Stmt *s)
{
if (!s)
return;
for (Stmt *child : s->children()) {
llvm::errs() << "Patching " << child->getStmtClassName() << "\n";
map->setParent(child, s);
manuallyPopulateParentMap(map, child);
}
}
ClazyASTConsumer::ClazyASTConsumer(ClazyContext *context)
: m_context(context)
{
}
void ClazyASTConsumer::addCheck(CheckBase *check)
{
check->registerASTMatchers(m_matchFinder);
m_createdChecks.push_back(check);
}
ClazyASTConsumer::~ClazyASTConsumer()
{
delete m_context;
}
bool ClazyASTConsumer::VisitDecl(Decl *decl)
{
const bool isInSystemHeader = m_context->sm.isInSystemHeader(decl->getLocStart());
if (AccessSpecifierManager *a = m_context->accessSpecifierManager)
a->VisitDeclaration(decl);
for (CheckBase *check : m_createdChecks) {
if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
check->VisitDeclaration(decl);
}
return true;
}
bool ClazyASTConsumer::VisitStmt(Stmt *stm)
{
if (!m_context->parentMap) {
if (m_context->ci.getDiagnostics().hasUnrecoverableErrorOccurred())
return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST.
m_context->parentMap = new ParentMap(stm);
}
ParentMap *parentMap = m_context->parentMap;
// Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.
if (lastStm && isa<CXXCatchStmt>(lastStm) && !parentMap->hasParent(stm)) {
parentMap->setParent(stm, lastStm);
manuallyPopulateParentMap(parentMap, stm);
}
lastStm = stm;
// clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration
// So add to parent map each time we go into a different hierarchy
if (!parentMap->hasParent(stm))
parentMap->addStmt(stm);
const bool isInSystemHeader = m_context->sm.isInSystemHeader(stm->getLocStart());
for (CheckBase *check : m_createdChecks) {
if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
check->VisitStatement(stm);
}
return true;
}
void ClazyASTConsumer::HandleTranslationUnit(ASTContext &ctx)
{
// Run our RecursiveAstVisitor based checks:
TraverseDecl(ctx.getTranslationUnitDecl());
// Run our AstMatcher base checks:
m_matchFinder.matchAST(ctx);
}
static bool parseArgument(const string &arg, vector<string> &args)
{
auto it = clazy_std::find(args, arg);
if (it != args.end()) {
args.erase(it, it + 1);
return true;
}
return false;
}
static CheckLevel parseLevel(vector<std::string> &args)
{
static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" };
const int numLevels = levels.size();
for (int i = 0; i < numLevels; ++i) {
if (parseArgument(levels.at(i), args)) {
return static_cast<CheckLevel>(i);
}
}
return CheckLevelUndefined;
}
static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
return c1.name < c2.name;
}
static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
if (c1.level == c2.level)
return checkLessThan(c1, c2);
return c1.level < c2.level;
}
ClazyASTAction::ClazyASTAction()
: PluginASTAction()
, m_checkManager(CheckManager::instance())
{
}
std::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)
{
ClazyContext::ClazyOptions options = ClazyContext::ClazyOption_None;
if (m_inplaceFixits)
options |= ClazyContext::ClazyOption_FixitsAreInplace;
if (m_checkManager->fixitsEnabled())
options |= ClazyContext::ClazyOption_FixitsEnabled;
if (m_checkManager->allFixitsEnabled())
options |= ClazyContext::ClazyOption_AllFixitsEnabled;
auto context = new ClazyContext(ci, options);
auto astConsumer = llvm::make_unique<ClazyASTConsumer>(context);
CheckBase::List createdChecks = m_checkManager->createChecks(m_checks, context);
for (CheckBase *check : createdChecks)
astConsumer->addCheck(check);
return astConsumer;
}
bool ClazyASTAction::ParseArgs(const CompilerInstance &, const std::vector<std::string> &args_)
{
std::vector<std::string> args = args_;
if (parseArgument("help", args)) {
PrintHelp(llvm::errs(), HelpMode_Normal);
return true;
}
if (parseArgument("generateAnchorHeader", args)) {
PrintHelp(llvm::errs(), HelpMode_AnchorHeader);
return true;
}
if (parseArgument("no-inplace-fixits", args)) {
// Unit-tests don't use inplace fixits
m_inplaceFixits = false;
}
// This argument is for debugging purposes
const bool printRequestedChecks = parseArgument("print-requested-checks", args);
const CheckLevel requestedLevel = parseLevel(/*by-ref*/args);
if (requestedLevel != CheckLevelUndefined) {
m_checkManager->setRequestedLevel(requestedLevel);
}
if (parseArgument("enable-all-fixits", args)) {
// This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.
m_checkManager->enableAllFixIts();
}
if (args.size() > 1) {
// Too many arguments.
llvm::errs() << "Too many arguments: ";
for (const std::string &a : args)
llvm::errs() << a << ' ';
llvm::errs() << "\n";
PrintHelp(llvm::errs());
return false;
} else if (args.size() == 1) {
vector<string> userDisabledChecks;
m_checks = m_checkManager->checksForCommaSeparatedString(args[0], /*by-ref=*/userDisabledChecks);
if (m_checks.empty()) {
llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
PrintHelp(llvm::errs());
return false;
}
}
vector<string> userDisabledChecks;
// Append checks specified from env variable
RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(/*by-ref*/userDisabledChecks);
copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks));
if (m_checks.empty() && requestedLevel == CheckLevelUndefined) {
// No check or level specified, lets use the default level
m_checkManager->setRequestedLevel(DefaultCheckLevel);
}
// Add checks from requested level
auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel();
clazy_std::append(checksFromRequestedLevel, m_checks);
clazy_std::sort_and_remove_dups(m_checks, checkLessThan);
CheckManager::removeChecksFromList(m_checks, userDisabledChecks);
if (printRequestedChecks) {
llvm::errs() << "Requested checks: ";
const unsigned int numChecks = m_checks.size();
for (unsigned int i = 0; i < numChecks; ++i) {
llvm::errs() << m_checks.at(i).name;
const bool isLast = i == numChecks - 1;
if (!isLast) {
llvm::errs() << ", ";
}
}
llvm::errs() << "\n";
}
return true;
}
void ClazyASTAction::PrintAnchorHeader(llvm::raw_ostream &ros, RegisteredCheck::List &checks)
{
// Generates ClazyAnchorHeader.h.
// Needed so we can support a static build of clazy without the linker discarding our checks.
// You can generate with:
// $ echo | clang -Xclang -load -Xclang ClangLazy.so -Xclang -add-plugin -Xclang clang-lazy -Xclang -plugin-arg-clang-lazy -Xclang generateAnchorHeader -c -xc -
ros << "// This file was autogenerated.\n\n";
ros << "#ifndef CLAZY_ANCHOR_HEADER_H\n#define CLAZY_ANCHOR_HEADER_H\n\n";
for (auto &check : checks) {
ros << string("extern volatile int ClazyAnchor_") + check.className + ";\n";
}
ros << "\n";
ros << "int clazy_dummy()\n{\n";
ros << " return\n";
for (auto &check : checks) {
ros << string(" ClazyAnchor_") + check.className + " +\n";
}
ros << " 0;\n";
ros << "}\n\n";
ros << "#endif\n";
}
void ClazyASTAction::PrintHelp(llvm::raw_ostream &ros, HelpMode helpMode)
{
RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);
clazy_std::sort(checks, checkLessThanByLevel);
if (helpMode == HelpMode_AnchorHeader) {
PrintAnchorHeader(ros, checks);
return;
}
ros << "Available checks and FixIts:\n\n";
const bool useMarkdown = getenv("CLAZY_HELP_USE_MARKDOWN");
int lastPrintedLevel = -1;
const auto numChecks = checks.size();
for (unsigned int i = 0; i < numChecks; ++i) {
const RegisteredCheck &check = checks[i];
const string levelStr = "level" + to_string(check.level);
if (lastPrintedLevel < check.level) {
lastPrintedLevel = check.level;
if (check.level > 0)
ros << "\n";
ros << "- Checks from " << levelStr << ":\n";
}
const string relativeReadmePath = "src/checks/" + levelStr + "/README-" + check.name + ".md";
auto padded = check.name;
padded.insert(padded.end(), 39 - padded.size(), ' ');
ros << " - " << (useMarkdown ? "[" : "") << check.name << (useMarkdown ? "](" + relativeReadmePath + ")" : "");
auto fixits = m_checkManager->availableFixIts(check.name);
if (!fixits.empty()) {
ros << " (";
bool isFirst = true;
for (const auto& fixit : fixits) {
if (isFirst) {
isFirst = false;
} else {
ros << ',';
}
ros << fixit.name;
}
ros << ')';
}
ros << "\n";
}
ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n";
ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
ros << " export CLAZY_CHECKS=\"level0\"\n";
ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n";
ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n";
ros << "or pass as compiler arguments, for example:\n";
ros << " -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n";
ros << "\n";
ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n";
ros << " export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n";
ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n";
}
static FrontendPluginRegistry::Add<ClazyASTAction>
X("clang-lazy", "clang lazy plugin");
|
/*
This file is part of the clazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected]
Author: Sérgio Martins <[email protected]>
Copyright (C) 2015-2017 Sergio Martins <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "Utils.h"
#include "Clazy.h"
#include "StringUtils.h"
#include "clazy_stl.h"
#include "checkbase.h"
#include "AccessSpecifierManager.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/ParentMap.h"
#include <llvm/Config/llvm-config.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
using namespace clang;
using namespace std;
using namespace clang::ast_matchers;
static void manuallyPopulateParentMap(ParentMap *map, Stmt *s)
{
if (!s)
return;
for (Stmt *child : s->children()) {
llvm::errs() << "Patching " << child->getStmtClassName() << "\n";
map->setParent(child, s);
manuallyPopulateParentMap(map, child);
}
}
ClazyASTConsumer::ClazyASTConsumer(ClazyContext *context)
: m_context(context)
{
}
void ClazyASTConsumer::addCheck(CheckBase *check)
{
check->registerASTMatchers(m_matchFinder);
m_createdChecks.push_back(check);
}
ClazyASTConsumer::~ClazyASTConsumer()
{
delete m_context;
}
bool ClazyASTConsumer::VisitDecl(Decl *decl)
{
const bool isInSystemHeader = m_context->sm.isInSystemHeader(decl->getLocStart());
if (AccessSpecifierManager *a = m_context->accessSpecifierManager)
a->VisitDeclaration(decl);
for (CheckBase *check : m_createdChecks) {
if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
check->VisitDeclaration(decl);
}
return true;
}
bool ClazyASTConsumer::VisitStmt(Stmt *stm)
{
if (!m_context->parentMap) {
if (m_context->ci.getDiagnostics().hasUnrecoverableErrorOccurred())
return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST.
m_context->parentMap = new ParentMap(stm);
}
ParentMap *parentMap = m_context->parentMap;
// Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.
if (lastStm && isa<CXXCatchStmt>(lastStm) && !parentMap->hasParent(stm)) {
parentMap->setParent(stm, lastStm);
manuallyPopulateParentMap(parentMap, stm);
}
lastStm = stm;
// clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration
// So add to parent map each time we go into a different hierarchy
if (!parentMap->hasParent(stm))
parentMap->addStmt(stm);
const bool isInSystemHeader = m_context->sm.isInSystemHeader(stm->getLocStart());
for (CheckBase *check : m_createdChecks) {
if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
check->VisitStatement(stm);
}
return true;
}
void ClazyASTConsumer::HandleTranslationUnit(ASTContext &ctx)
{
// Run our RecursiveAstVisitor based checks:
TraverseDecl(ctx.getTranslationUnitDecl());
// Run our AstMatcher base checks:
m_matchFinder.matchAST(ctx);
}
static bool parseArgument(const string &arg, vector<string> &args)
{
auto it = clazy_std::find(args, arg);
if (it != args.end()) {
args.erase(it, it + 1);
return true;
}
return false;
}
static CheckLevel parseLevel(vector<std::string> &args)
{
static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" };
const int numLevels = levels.size();
for (int i = 0; i < numLevels; ++i) {
if (parseArgument(levels.at(i), args)) {
return static_cast<CheckLevel>(i);
}
}
return CheckLevelUndefined;
}
static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
return c1.name < c2.name;
}
static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
if (c1.level == c2.level)
return checkLessThan(c1, c2);
return c1.level < c2.level;
}
ClazyASTAction::ClazyASTAction()
: PluginASTAction()
, m_checkManager(CheckManager::instance())
{
}
std::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)
{
ClazyContext::ClazyOptions options = ClazyContext::ClazyOption_None;
if (m_inplaceFixits)
options |= ClazyContext::ClazyOption_FixitsAreInplace;
if (m_checkManager->fixitsEnabled())
options |= ClazyContext::ClazyOption_FixitsEnabled;
if (m_checkManager->allFixitsEnabled())
options |= ClazyContext::ClazyOption_AllFixitsEnabled;
auto context = new ClazyContext(ci, options);
auto astConsumer = new ClazyASTConsumer(context);
CheckBase::List createdChecks = m_checkManager->createChecks(m_checks, context);
for (CheckBase *check : createdChecks) {
astConsumer->addCheck(check);
}
return std::unique_ptr<ASTConsumer>(astConsumer);
}
bool ClazyASTAction::ParseArgs(const CompilerInstance &, const std::vector<std::string> &args_)
{
std::vector<std::string> args = args_;
if (parseArgument("help", args)) {
PrintHelp(llvm::errs(), HelpMode_Normal);
return true;
}
if (parseArgument("generateAnchorHeader", args)) {
PrintHelp(llvm::errs(), HelpMode_AnchorHeader);
return true;
}
if (parseArgument("no-inplace-fixits", args)) {
// Unit-tests don't use inplace fixits
m_inplaceFixits = false;
}
// This argument is for debugging purposes
const bool printRequestedChecks = parseArgument("print-requested-checks", args);
const CheckLevel requestedLevel = parseLevel(/*by-ref*/args);
if (requestedLevel != CheckLevelUndefined) {
m_checkManager->setRequestedLevel(requestedLevel);
}
if (parseArgument("enable-all-fixits", args)) {
// This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.
m_checkManager->enableAllFixIts();
}
if (args.size() > 1) {
// Too many arguments.
llvm::errs() << "Too many arguments: ";
for (const std::string &a : args)
llvm::errs() << a << ' ';
llvm::errs() << "\n";
PrintHelp(llvm::errs());
return false;
} else if (args.size() == 1) {
vector<string> userDisabledChecks;
m_checks = m_checkManager->checksForCommaSeparatedString(args[0], /*by-ref=*/userDisabledChecks);
if (m_checks.empty()) {
llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
PrintHelp(llvm::errs());
return false;
}
}
vector<string> userDisabledChecks;
// Append checks specified from env variable
RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(/*by-ref*/userDisabledChecks);
copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks));
if (m_checks.empty() && requestedLevel == CheckLevelUndefined) {
// No check or level specified, lets use the default level
m_checkManager->setRequestedLevel(DefaultCheckLevel);
}
// Add checks from requested level
auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel();
clazy_std::append(checksFromRequestedLevel, m_checks);
clazy_std::sort_and_remove_dups(m_checks, checkLessThan);
CheckManager::removeChecksFromList(m_checks, userDisabledChecks);
if (printRequestedChecks) {
llvm::errs() << "Requested checks: ";
const unsigned int numChecks = m_checks.size();
for (unsigned int i = 0; i < numChecks; ++i) {
llvm::errs() << m_checks.at(i).name;
const bool isLast = i == numChecks - 1;
if (!isLast) {
llvm::errs() << ", ";
}
}
llvm::errs() << "\n";
}
return true;
}
void ClazyASTAction::PrintAnchorHeader(llvm::raw_ostream &ros, RegisteredCheck::List &checks)
{
// Generates ClazyAnchorHeader.h.
// Needed so we can support a static build of clazy without the linker discarding our checks.
// You can generate with:
// $ echo | clang -Xclang -load -Xclang ClangLazy.so -Xclang -add-plugin -Xclang clang-lazy -Xclang -plugin-arg-clang-lazy -Xclang generateAnchorHeader -c -xc -
ros << "// This file was autogenerated.\n\n";
ros << "#ifndef CLAZY_ANCHOR_HEADER_H\n#define CLAZY_ANCHOR_HEADER_H\n\n";
for (auto &check : checks) {
ros << string("extern volatile int ClazyAnchor_") + check.className + ";\n";
}
ros << "\n";
ros << "int clazy_dummy()\n{\n";
ros << " return\n";
for (auto &check : checks) {
ros << string(" ClazyAnchor_") + check.className + " +\n";
}
ros << " 0;\n";
ros << "}\n\n";
ros << "#endif\n";
}
void ClazyASTAction::PrintHelp(llvm::raw_ostream &ros, HelpMode helpMode)
{
RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);
clazy_std::sort(checks, checkLessThanByLevel);
if (helpMode == HelpMode_AnchorHeader) {
PrintAnchorHeader(ros, checks);
return;
}
ros << "Available checks and FixIts:\n\n";
const bool useMarkdown = getenv("CLAZY_HELP_USE_MARKDOWN");
int lastPrintedLevel = -1;
const auto numChecks = checks.size();
for (unsigned int i = 0; i < numChecks; ++i) {
const RegisteredCheck &check = checks[i];
const string levelStr = "level" + to_string(check.level);
if (lastPrintedLevel < check.level) {
lastPrintedLevel = check.level;
if (check.level > 0)
ros << "\n";
ros << "- Checks from " << levelStr << ":\n";
}
const string relativeReadmePath = "src/checks/" + levelStr + "/README-" + check.name + ".md";
auto padded = check.name;
padded.insert(padded.end(), 39 - padded.size(), ' ');
ros << " - " << (useMarkdown ? "[" : "") << check.name << (useMarkdown ? "](" + relativeReadmePath + ")" : "");
auto fixits = m_checkManager->availableFixIts(check.name);
if (!fixits.empty()) {
ros << " (";
bool isFirst = true;
for (const auto& fixit : fixits) {
if (isFirst) {
isFirst = false;
} else {
ros << ',';
}
ros << fixit.name;
}
ros << ')';
}
ros << "\n";
}
ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n";
ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
ros << " export CLAZY_CHECKS=\"level0\"\n";
ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n";
ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n";
ros << "or pass as compiler arguments, for example:\n";
ros << " -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n";
ros << "\n";
ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n";
ros << " export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n";
ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n";
}
static FrontendPluginRegistry::Add<ClazyASTAction>
X("clang-lazy", "clang lazy plugin");
|
Fix build with clang 3.8
|
Fix build with clang 3.8
|
C++
|
lgpl-2.1
|
nyalldawson/clazy,nyalldawson/clazy,nyalldawson/clazy,nyalldawson/clazy
|
69389ee74326a2cad3e1a321fef42e2e630976e0
|
src/webview/HWebView.cpp
|
src/webview/HWebView.cpp
|
#include "HWebView.h"
#include "cookiejar.h"
#include "ZulipWebBridge.h"
#include "Config.h"
#include "ZulipApplication.h"
#include "Utils.h"
#include <QDir>
#include <QDesktopServices>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QWebView>
#include <QWebFrame>
#include <QVBoxLayout>
#include <QBuffer>
class ZulipNAM : public QNetworkAccessManager
{
Q_OBJECT
public:
ZulipNAM(QWebView *webView, QObject *parent = 0)
: QNetworkAccessManager(parent)
, m_zulipWebView(webView)
, m_csrfWebView(0)
, m_redirectedRequest(false)
{
}
protected:
QNetworkReply* createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData)
{
QNetworkReply* origRequest = QNetworkAccessManager::createRequest(op, request, outgoingData);
// If this is an original login to the app, we preflight the user
// to redirect to the site-local Zulip instance if appropriate
if (!m_redirectedRequest && !APP->explicitDomain() && op == PostOperation &&
outgoingData && request.url().path() == "/accounts/login/") {
m_redirectedRequest = false;
QString postBody = QString::fromUtf8(outgoingData->readAll());
m_savedPayload = Utils::parseURLParameters(postBody);
QString email = m_savedPayload.value("username", QString());
if (email.size() == 0) {
return origRequest;
}
m_siteBaseUrl = Utils::baseUrlForEmail(this, email);
QUrl baseSite(m_siteBaseUrl);
if (baseSite.host() == request.url().host()) {
return origRequest;
}
qDebug() << "Got different base URL, redirecting" << baseSite;
APP->setExplicitDomain(m_siteBaseUrl);
QUrl newUrl(request.url());
newUrl.setHost(baseSite.host());
m_savedRequest = QNetworkRequest(request);
m_savedRequest.setUrl(newUrl);
m_savedRequest.setRawHeader("Origin", newUrl.toEncoded());
m_savedRequest.setRawHeader("Referer", newUrl.toEncoded());
// Steal CSRF token
// This will asynchronously load the webpage in the background
// and then redirect the user
snatchCSRFToken();
// Create new dummy request
return QNetworkAccessManager::createRequest(op, QNetworkRequest(QUrl("")), 0);
}
if (op == PostOperation && request.url().path().contains("/accounts/logout")) {
APP->setExplicitDomain(QString());
}
return origRequest;
}
private slots:
void csrfLoadFinished() {
QList<QNetworkCookie> cookies = m_csrfWebView->page()->networkAccessManager()->cookieJar()->cookiesForUrl(QUrl(m_siteBaseUrl));
foreach (const QNetworkCookie &cookie, cookies) {
if (cookie.name() == "csrftoken") {
m_savedPayload["csrfmiddlewaretoken"] = cookie.value();
loginToRealHost();
break;
}
}
m_siteBaseUrl.clear();
m_csrfWebView->deleteLater();
m_csrfWebView = 0;
}
private:
QString snatchCSRFToken() {
// Load the login page for the target Zulip server and extract the CSRF token
m_csrfWebView = new QWebView();
// Make sure to share the same NAM---then we use the same Cookie Jar and when we
// make our redirected POST request, our CSRF token in our cookie matches with
// the value in the POST
m_csrfWebView->page()->setNetworkAccessManager(this);
QUrl loginUrl(m_siteBaseUrl + "login/");
QObject::connect(m_csrfWebView, SIGNAL(loadFinished(bool)), this, SLOT(csrfLoadFinished()));
m_csrfWebView->load(loginUrl);
return QString();
}
void loginToRealHost() {
QString rebuiltPayload = Utils::parametersDictToString(m_savedPayload);
m_redirectedRequest = true;
m_zulipWebView->load(m_savedRequest, QNetworkAccessManager::PostOperation, rebuiltPayload.toUtf8());
}
QString m_siteBaseUrl;
QWebView *m_zulipWebView;
QWebView *m_csrfWebView;
QNetworkRequest m_savedRequest;
QHash<QString, QString> m_savedPayload;
bool m_redirectedRequest;
};
class HWebViewPrivate : public QObject {
Q_OBJECT
public:
HWebViewPrivate(HWebView* qq)
: QObject(qq),
webView(new QWebView(qq)),
q(qq),
bridge(new ZulipWebBridge(qq))
{
webView->page()->setLinkDelegationPolicy(QWebPage::DelegateExternalLinks);
QDir data_dir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
CookieJar *m_cookies = new CookieJar(data_dir.absoluteFilePath("default.dat"));
ZulipNAM* nam = new ZulipNAM(webView, this);
webView->page()->setNetworkAccessManager(nam);
webView->page()->networkAccessManager()->setCookieJar(m_cookies);
connect(webView, SIGNAL(linkClicked(QUrl)), q, SIGNAL(linkClicked(QUrl)));
connect(bridge, SIGNAL(doDesktopNotification(QString,QString)), q, SIGNAL(desktopNotification(QString,QString)));
connect(bridge, SIGNAL(doUpdateCount(int)), q, SIGNAL(updateCount(int)));
connect(bridge, SIGNAL(doUpdatePMCount(int)), q, SIGNAL(updatePMCount(int)));
connect(bridge, SIGNAL(doBell()), q, SIGNAL(bell()));
connect(webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJavaScriptObject()));
}
~HWebViewPrivate() {}
private slots:
void addJavaScriptObject() {
// Ref: http://www.developer.nokia.com/Community/Wiki/Exposing_QObjects_to_Qt_Webkit
// Don't expose the JS bridge outside our start domain
if (webView->url().host() != startUrl.host()) {
return;
}
webView->page()->mainFrame()->addToJavaScriptWindowObject("bridge", bridge);
// QtWebkit has a bug where it won't fall back properly on fonts.
// If the first font listed in a CSS font-family declaration isn't
// found, instead of trying the others it simply resorts to a
// default font immediately.
//
// This workaround ensures we still get a fixed-width font for
// code blocks. jQuery isn't loaded yet when this is run,
// so we use a DOM method instead of $(...)
webView->page()->mainFrame()->evaluateJavaScript(
"document.addEventListener('DOMContentLoaded',"
" function () {"
" var css = '<style type=\"text/css\">'"
" + 'code,pre{font-family:monospace !important;}'"
" + '</style>';"
" $('head').append(css);"
" }"
");"
);
}
public:
QWebView* webView;
HWebView* q;
ZulipWebBridge* bridge;
QUrl startUrl;
};
HWebView::HWebView(QWidget *parent)
: QWidget(parent)
, dptr(new HWebViewPrivate(this))
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setMargin(0);
setLayout(layout);
layout->addWidget(dptr->webView);
}
HWebView::~HWebView()
{
}
void HWebView::load(const QUrl &url) {
dptr->startUrl = url;
dptr->webView->load(url);
}
void HWebView::setUrl(const QUrl &url) {
load(url);
}
QUrl HWebView::url() const {
return dptr->webView->url();
}
void HWebView::loadHTML(const QString &html) {
dptr->webView->setHtml(html);
}
#include "HWebView.moc"
|
#include "HWebView.h"
#include "cookiejar.h"
#include "ZulipWebBridge.h"
#include "Config.h"
#include "ZulipApplication.h"
#include "Utils.h"
#include <QDir>
#include <QDesktopServices>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QWebView>
#include <QWebFrame>
#include <QVBoxLayout>
#include <QBuffer>
class ZulipNAM : public QNetworkAccessManager
{
Q_OBJECT
public:
ZulipNAM(QWebView *webView, QObject *parent = 0)
: QNetworkAccessManager(parent)
, m_zulipWebView(webView)
, m_csrfWebView(0)
, m_redirectedRequest(false)
{
}
protected:
QNetworkReply* createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData)
{
QNetworkReply* origRequest = QNetworkAccessManager::createRequest(op, request, outgoingData);
// If this is an original login to the app, we preflight the user
// to redirect to the site-local Zulip instance if appropriate
if (!m_redirectedRequest && !APP->explicitDomain() && op == PostOperation &&
outgoingData && request.url().path() == "/accounts/login/") {
m_redirectedRequest = false;
QString postBody = QString::fromUtf8(outgoingData->readAll());
m_savedPayload = Utils::parseURLParameters(postBody);
QString email = m_savedPayload.value("username", QString());
if (email.size() == 0) {
return origRequest;
}
m_siteBaseUrl = Utils::baseUrlForEmail(this, email);
m_savedOriginalRequest = request;
if (m_siteBaseUrl == "") {
// Failed to load, so we ask the user directly
APP->askForCustomServer([=](QString domain) {
m_siteBaseUrl = domain;
snatchCSRFAndRedirect();
});
}
snatchCSRFAndRedirect();
// Create new dummy request
return QNetworkAccessManager::createRequest(op, QNetworkRequest(QUrl("")), 0);
}
if (op == PostOperation && request.url().path().contains("/accounts/logout")) {
APP->setExplicitDomain(QString());
}
return origRequest;
}
private slots:
void csrfLoadFinished() {
QList<QNetworkCookie> cookies = m_csrfWebView->page()->networkAccessManager()->cookieJar()->cookiesForUrl(QUrl(m_siteBaseUrl));
foreach (const QNetworkCookie &cookie, cookies) {
if (cookie.name() == "csrftoken") {
m_savedPayload["csrfmiddlewaretoken"] = cookie.value();
loginToRealHost();
break;
}
}
m_siteBaseUrl.clear();
m_csrfWebView->deleteLater();
m_csrfWebView = 0;
}
private:
QString snatchCSRFToken() {
// Load the login page for the target Zulip server and extract the CSRF token
m_csrfWebView = new QWebView();
// Make sure to share the same NAM---then we use the same Cookie Jar and when we
// make our redirected POST request, our CSRF token in our cookie matches with
// the value in the POST
m_csrfWebView->page()->setNetworkAccessManager(this);
QUrl loginUrl(m_siteBaseUrl + "login/");
QObject::connect(m_csrfWebView, SIGNAL(loadFinished(bool)), this, SLOT(csrfLoadFinished()));
m_csrfWebView->load(loginUrl);
return QString();
}
void loginToRealHost() {
QString rebuiltPayload = Utils::parametersDictToString(m_savedPayload);
m_redirectedRequest = true;
m_zulipWebView->load(m_savedRequest, QNetworkAccessManager::PostOperation, rebuiltPayload.toUtf8());
}
void snatchCSRFAndRedirect() {
QUrl baseSite(m_siteBaseUrl);
if (baseSite.host() == m_savedOriginalRequest.url().host()) {
return;
}
qDebug() << "Got different base URL, redirecting" << baseSite;
APP->setExplicitDomain(m_siteBaseUrl);
QUrl newUrl(m_savedOriginalRequest.url());
newUrl.setHost(baseSite.host());
m_savedRequest = QNetworkRequest(m_savedOriginalRequest);
m_savedRequest.setUrl(newUrl);
m_savedRequest.setRawHeader("Origin", newUrl.toEncoded());
m_savedRequest.setRawHeader("Referer", newUrl.toEncoded());
// Steal CSRF token
// This will asynchronously load the webpage in the background
// and then redirect the user
snatchCSRFToken();
}
QString m_siteBaseUrl;
QWebView *m_zulipWebView;
QWebView *m_csrfWebView;
QNetworkRequest m_savedOriginalRequest;
QNetworkRequest m_savedRequest;
QHash<QString, QString> m_savedPayload;
bool m_redirectedRequest;
};
class HWebViewPrivate : public QObject {
Q_OBJECT
public:
HWebViewPrivate(HWebView* qq)
: QObject(qq),
webView(new QWebView(qq)),
q(qq),
bridge(new ZulipWebBridge(qq))
{
webView->page()->setLinkDelegationPolicy(QWebPage::DelegateExternalLinks);
QDir data_dir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
CookieJar *m_cookies = new CookieJar(data_dir.absoluteFilePath("default.dat"));
ZulipNAM* nam = new ZulipNAM(webView, this);
webView->page()->setNetworkAccessManager(nam);
webView->page()->networkAccessManager()->setCookieJar(m_cookies);
connect(webView, SIGNAL(linkClicked(QUrl)), q, SIGNAL(linkClicked(QUrl)));
connect(webView, SIGNAL(loadFinished(bool)), this, SLOT(zulipLoadFinished(bool)));
connect(bridge, SIGNAL(doDesktopNotification(QString,QString)), q, SIGNAL(desktopNotification(QString,QString)));
connect(bridge, SIGNAL(doUpdateCount(int)), q, SIGNAL(updateCount(int)));
connect(bridge, SIGNAL(doUpdatePMCount(int)), q, SIGNAL(updatePMCount(int)));
connect(bridge, SIGNAL(doBell()), q, SIGNAL(bell()));
connect(webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJavaScriptObject()));
}
~HWebViewPrivate() {}
private slots:
void addJavaScriptObject() {
// Ref: http://www.developer.nokia.com/Community/Wiki/Exposing_QObjects_to_Qt_Webkit
// Don't expose the JS bridge outside our start domain
if (webView->url().host() != startUrl.host()) {
return;
}
webView->page()->mainFrame()->addToJavaScriptWindowObject("bridge", bridge);
// QtWebkit has a bug where it won't fall back properly on fonts.
// If the first font listed in a CSS font-family declaration isn't
// found, instead of trying the others it simply resorts to a
// default font immediately.
//
// This workaround ensures we still get a fixed-width font for
// code blocks. jQuery isn't loaded yet when this is run,
// so we use a DOM method instead of $(...)
webView->page()->mainFrame()->evaluateJavaScript(
"document.addEventListener('DOMContentLoaded',"
" function () {"
" var css = '<style type=\"text/css\">'"
" + 'code,pre{font-family:monospace !important;}'"
" + '</style>';"
" $('head').append(css);"
" }"
");"
);
}
void zulipLoadFinished(bool successful) {
if (!successful && !APP->explicitDomain()) {
qDebug() << "Failed to load initial Zulip login page, asking directly";
APP->askForCustomServer([=](QString domain) {
qDebug() << "Got manually entered domain" << domain << ", redirecting";
webView->load(QUrl(domain));
});
}
}
public:
QWebView* webView;
HWebView* q;
ZulipWebBridge* bridge;
QUrl startUrl;
};
HWebView::HWebView(QWidget *parent)
: QWidget(parent)
, dptr(new HWebViewPrivate(this))
{
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setMargin(0);
setLayout(layout);
layout->addWidget(dptr->webView);
}
HWebView::~HWebView()
{
}
void HWebView::load(const QUrl &url) {
dptr->startUrl = url;
dptr->webView->load(url);
}
void HWebView::setUrl(const QUrl &url) {
load(url);
}
QUrl HWebView::url() const {
return dptr->webView->url();
}
void HWebView::loadHTML(const QString &html) {
dptr->webView->setHtml(html);
}
#include "HWebView.moc"
|
Handle zulip.com/api.zulip.com being unreachable on Linux
|
Handle zulip.com/api.zulip.com being unreachable on Linux
|
C++
|
apache-2.0
|
zofuthan/zulip-desktop,zofuthan/zulip-desktop,zofuthan/zulip-desktop,zofuthan/zulip-desktop,zofuthan/zulip-desktop,zofuthan/zulip-desktop,zofuthan/zulip-desktop
|
30dc191603a06c84410f6c367e4e3b8980166621
|
src/Genre.cpp
|
src/Genre.cpp
|
/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<[email protected]>
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "Genre.h"
#include "Album.h"
#include "AlbumTrack.h"
#include "Artist.h"
namespace medialibrary
{
namespace policy
{
const std::string GenreTable::Name = "Genre";
const std::string GenreTable::PrimaryKeyColumn = "id_genre";
int64_t Genre::* const GenreTable::PrimaryKey = &Genre::m_id;
}
Genre::Genre( MediaLibraryPtr ml, sqlite::Row& row )
: m_ml( ml )
{
row >> m_id
>> m_name
>> m_nbTracks;
}
Genre::Genre( MediaLibraryPtr ml, const std::string& name )
: m_ml( ml )
, m_id( 0 )
, m_name( name )
, m_nbTracks( 0 )
{
}
int64_t Genre::id() const
{
return m_id;
}
const std::string& Genre::name() const
{
return m_name;
}
uint32_t Genre::nbTracks() const
{
return m_nbTracks;
}
void Genre::updateCachedNbTracks( int increment )
{
m_nbTracks += increment;
}
std::vector<ArtistPtr> Genre::artists( SortingCriteria, bool desc ) const
{
std::string req = "SELECT a.* FROM " + policy::ArtistTable::Name + " a "
"INNER JOIN " + policy::AlbumTrackTable::Name + " att ON att.artist_id = a.id_artist "
"WHERE att.genre_id = ? GROUP BY att.artist_id"
" ORDER BY a.name";
if ( desc == true )
req += " DESC";
return Artist::fetchAll<IArtist>( m_ml, req, m_id );
}
std::vector<MediaPtr> Genre::tracks( SortingCriteria sort, bool desc ) const
{
return AlbumTrack::fromGenre( m_ml, m_id, sort, desc );
}
std::vector<AlbumPtr> Genre::albums( SortingCriteria sort, bool desc ) const
{
return Album::fromGenre( m_ml, m_id, sort, desc );
}
void Genre::createTable( sqlite::Connection* dbConn )
{
const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::GenreTable::Name +
"("
"id_genre INTEGER PRIMARY KEY AUTOINCREMENT,"
"name TEXT COLLATE NOCASE UNIQUE ON CONFLICT FAIL,"
"nb_tracks INTEGER NOT NULL DEFAULT 0"
")";
const std::string vtableReq = "CREATE VIRTUAL TABLE IF NOT EXISTS "
+ policy::GenreTable::Name + "Fts USING FTS3("
"name"
")";
const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_genre_fts"
" AFTER INSERT ON " + policy::GenreTable::Name +
" BEGIN"
" INSERT INTO " + policy::GenreTable::Name + "Fts(rowid,name) VALUES(new.id_genre, new.name);"
" END";
const std::string vtableDeleteTrigger = "CREATE TRIGGER IF NOT EXISTS delete_genre_fts"
" BEFORE DELETE ON " + policy::GenreTable::Name +
" BEGIN"
" DELETE FROM " + policy::GenreTable::Name + "Fts WHERE rowid = old.id_genre;"
" END";
sqlite::Tools::executeRequest( dbConn, req );
sqlite::Tools::executeRequest( dbConn, vtableReq );
sqlite::Tools::executeRequest( dbConn, vtableInsertTrigger );
sqlite::Tools::executeRequest( dbConn, vtableDeleteTrigger );
}
void Genre::createTriggers( sqlite::Connection* dbConn )
{
const std::string onGenreChanged = "CREATE TRIGGER IF NOT EXISTS on_track_genre_changed AFTER UPDATE OF "
" genre_id ON " + policy::AlbumTrackTable::Name +
" BEGIN"
" UPDATE " + policy::GenreTable::Name + " SET nb_tracks = nb_tracks + 1 WHERE id_genre = new.genre_id;"
" UPDATE " + policy::GenreTable::Name + " SET nb_tracks = nb_tracks - 1 WHERE id_genre = old.genre_id;"
" DELETE FROM " + policy::GenreTable::Name + " WHERE nb_tracks = 0;"
" END";
const std::string onTrackCreated = "CREATE TRIGGER IF NOT EXISTS update_genre_on_new_track"
" AFTER INSERT ON " + policy::AlbumTrackTable::Name +
" WHEN new.genre_id IS NOT NULL"
" BEGIN"
" UPDATE " + policy::GenreTable::Name + " SET nb_tracks = nb_tracks + 1 WHERE id_genre = new.genre_id;"
" END";
const std::string onTrackDeleted = "CREATE TRIGGER IF NOT EXISTS update_genre_on_track_deleted"
" AFTER DELETE ON " + policy::AlbumTrackTable::Name +
" WHEN old.genre_id IS NOT NULL"
" BEGIN"
" UPDATE " + policy::GenreTable::Name + " SET nb_tracks = nb_tracks - 1 WHERE id_genre = old.genre_id;"
" DELETE FROM " + policy::GenreTable::Name + " WHERE nb_tracks = 0;"
" END";
sqlite::Tools::executeRequest( dbConn, onGenreChanged );
sqlite::Tools::executeRequest( dbConn, onTrackCreated );
sqlite::Tools::executeRequest( dbConn, onTrackDeleted );
}
std::shared_ptr<Genre> Genre::create( MediaLibraryPtr ml, const std::string& name )
{
static const std::string req = "INSERT INTO " + policy::GenreTable::Name + "(name)"
"VALUES(?)";
auto self = std::make_shared<Genre>( ml, name );
if ( insert( ml, self, req, name ) == false )
return nullptr;
return self;
}
std::shared_ptr<Genre> Genre::fromName( MediaLibraryPtr ml, const std::string& name )
{
static const std::string req = "SELECT * FROM " + policy::GenreTable::Name + " WHERE name = ?";
return fetch( ml, req, name );
}
std::vector<GenrePtr> Genre::search( MediaLibraryPtr ml, const std::string& name )
{
static const std::string req = "SELECT * FROM " + policy::GenreTable::Name + " WHERE id_genre IN "
"(SELECT rowid FROM " + policy::GenreTable::Name + "Fts WHERE name MATCH '*' || ? || '*')";
return fetchAll<IGenre>( ml, req, name );
}
std::vector<GenrePtr> Genre::listAll( MediaLibraryPtr ml, SortingCriteria, bool desc )
{
std::string req = "SELECT * FROM " + policy::GenreTable::Name + " ORDER BY name";
if ( desc == true )
req += " DESC";
return fetchAll<IGenre>( ml, req );
}
}
|
/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<[email protected]>
*
* 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "Genre.h"
#include "Album.h"
#include "AlbumTrack.h"
#include "Artist.h"
namespace medialibrary
{
namespace policy
{
const std::string GenreTable::Name = "Genre";
const std::string GenreTable::PrimaryKeyColumn = "id_genre";
int64_t Genre::* const GenreTable::PrimaryKey = &Genre::m_id;
}
Genre::Genre( MediaLibraryPtr ml, sqlite::Row& row )
: m_ml( ml )
{
row >> m_id
>> m_name
>> m_nbTracks;
}
Genre::Genre( MediaLibraryPtr ml, const std::string& name )
: m_ml( ml )
, m_id( 0 )
, m_name( name )
, m_nbTracks( 0 )
{
}
int64_t Genre::id() const
{
return m_id;
}
const std::string& Genre::name() const
{
return m_name;
}
uint32_t Genre::nbTracks() const
{
return m_nbTracks;
}
void Genre::updateCachedNbTracks( int increment )
{
m_nbTracks += increment;
}
std::vector<ArtistPtr> Genre::artists( SortingCriteria, bool desc ) const
{
std::string req = "SELECT a.* FROM " + policy::ArtistTable::Name + " a "
"INNER JOIN " + policy::AlbumTrackTable::Name + " att ON att.artist_id = a.id_artist "
"WHERE att.genre_id = ? GROUP BY att.artist_id"
" ORDER BY a.name";
if ( desc == true )
req += " DESC";
return Artist::fetchAll<IArtist>( m_ml, req, m_id );
}
std::vector<MediaPtr> Genre::tracks( SortingCriteria sort, bool desc ) const
{
return AlbumTrack::fromGenre( m_ml, m_id, sort, desc );
}
std::vector<AlbumPtr> Genre::albums( SortingCriteria sort, bool desc ) const
{
return Album::fromGenre( m_ml, m_id, sort, desc );
}
void Genre::createTable( sqlite::Connection* dbConn )
{
const std::string req = "CREATE TABLE IF NOT EXISTS " + policy::GenreTable::Name +
"("
"id_genre INTEGER PRIMARY KEY AUTOINCREMENT,"
"name TEXT COLLATE NOCASE UNIQUE ON CONFLICT FAIL,"
"nb_tracks INTEGER NOT NULL DEFAULT 0"
")";
const std::string vtableReq = "CREATE VIRTUAL TABLE IF NOT EXISTS "
+ policy::GenreTable::Name + "Fts USING FTS3("
"name"
")";
sqlite::Tools::executeRequest( dbConn, req );
sqlite::Tools::executeRequest( dbConn, vtableReq );
}
void Genre::createTriggers( sqlite::Connection* dbConn )
{
const std::string vtableInsertTrigger = "CREATE TRIGGER IF NOT EXISTS insert_genre_fts"
" AFTER INSERT ON " + policy::GenreTable::Name +
" BEGIN"
" INSERT INTO " + policy::GenreTable::Name + "Fts(rowid,name) VALUES(new.id_genre, new.name);"
" END";
const std::string vtableDeleteTrigger = "CREATE TRIGGER IF NOT EXISTS delete_genre_fts"
" BEFORE DELETE ON " + policy::GenreTable::Name +
" BEGIN"
" DELETE FROM " + policy::GenreTable::Name + "Fts WHERE rowid = old.id_genre;"
" END";
const std::string onGenreChanged = "CREATE TRIGGER IF NOT EXISTS on_track_genre_changed AFTER UPDATE OF "
" genre_id ON " + policy::AlbumTrackTable::Name +
" BEGIN"
" UPDATE " + policy::GenreTable::Name + " SET nb_tracks = nb_tracks + 1 WHERE id_genre = new.genre_id;"
" UPDATE " + policy::GenreTable::Name + " SET nb_tracks = nb_tracks - 1 WHERE id_genre = old.genre_id;"
" DELETE FROM " + policy::GenreTable::Name + " WHERE nb_tracks = 0;"
" END";
const std::string onTrackCreated = "CREATE TRIGGER IF NOT EXISTS update_genre_on_new_track"
" AFTER INSERT ON " + policy::AlbumTrackTable::Name +
" WHEN new.genre_id IS NOT NULL"
" BEGIN"
" UPDATE " + policy::GenreTable::Name + " SET nb_tracks = nb_tracks + 1 WHERE id_genre = new.genre_id;"
" END";
const std::string onTrackDeleted = "CREATE TRIGGER IF NOT EXISTS update_genre_on_track_deleted"
" AFTER DELETE ON " + policy::AlbumTrackTable::Name +
" WHEN old.genre_id IS NOT NULL"
" BEGIN"
" UPDATE " + policy::GenreTable::Name + " SET nb_tracks = nb_tracks - 1 WHERE id_genre = old.genre_id;"
" DELETE FROM " + policy::GenreTable::Name + " WHERE nb_tracks = 0;"
" END";
sqlite::Tools::executeRequest( dbConn, vtableInsertTrigger );
sqlite::Tools::executeRequest( dbConn, vtableDeleteTrigger );
sqlite::Tools::executeRequest( dbConn, onGenreChanged );
sqlite::Tools::executeRequest( dbConn, onTrackCreated );
sqlite::Tools::executeRequest( dbConn, onTrackDeleted );
}
std::shared_ptr<Genre> Genre::create( MediaLibraryPtr ml, const std::string& name )
{
static const std::string req = "INSERT INTO " + policy::GenreTable::Name + "(name)"
"VALUES(?)";
auto self = std::make_shared<Genre>( ml, name );
if ( insert( ml, self, req, name ) == false )
return nullptr;
return self;
}
std::shared_ptr<Genre> Genre::fromName( MediaLibraryPtr ml, const std::string& name )
{
static const std::string req = "SELECT * FROM " + policy::GenreTable::Name + " WHERE name = ?";
return fetch( ml, req, name );
}
std::vector<GenrePtr> Genre::search( MediaLibraryPtr ml, const std::string& name )
{
static const std::string req = "SELECT * FROM " + policy::GenreTable::Name + " WHERE id_genre IN "
"(SELECT rowid FROM " + policy::GenreTable::Name + "Fts WHERE name MATCH '*' || ? || '*')";
return fetchAll<IGenre>( ml, req, name );
}
std::vector<GenrePtr> Genre::listAll( MediaLibraryPtr ml, SortingCriteria, bool desc )
{
std::string req = "SELECT * FROM " + policy::GenreTable::Name + " ORDER BY name";
if ( desc == true )
req += " DESC";
return fetchAll<IGenre>( ml, req );
}
}
|
Move all triggers creation to the createTriggers method
|
Genre: Move all triggers creation to the createTriggers method
|
C++
|
lgpl-2.1
|
chouquette/medialibrary,chouquette/medialibrary,chouquette/medialibrary,chouquette/medialibrary
|
80f9ad3f8be6d4a6c679f240e72488ae3e6cd378
|
subsys/tire/ChLugreTire.cpp
|
subsys/tire/ChLugreTire.cpp
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Aki Mikkola
// =============================================================================
//
// Template for a tire model based on LuGre friction
//
// Ref: C.Canudas de Wit, P.Tsiotras, E.Velenis, M.Basset and
// G.Gissinger.Dynamics friction models for longitudinal road / tire
// interaction.Vehicle System Dynamics.Oct 14, 2002.
//
// =============================================================================
#include "ChLugreTire.h"
namespace chrono {
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
ChLugreTire::ChLugreTire(const ChTerrain& terrain)
: ChTire(terrain),
m_stepsize(1e-3)
{
m_tireForce.force = ChVector<>(0, 0, 0);
m_tireForce.point = ChVector<>(0, 0, 0);
m_tireForce.moment = ChVector<>(0, 0, 0);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChLugreTire::Initialize()
{
m_data.resize(getNumDiscs());
m_state.resize(getNumDiscs());
SetLugreParams();
// Initialize disc states
for (int id = 0; id < getNumDiscs(); id++) {
m_state[id].z0 = 0;
m_state[id].z1 = 0;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChLugreTire::Update(double time,
const ChBodyState& wheel_state)
{
double disc_radius = getRadius();
const double* disc_locs = getDiscLocations();
// Clear the force accumulators and set the application point to the wheel
// center.
m_tireForce.force = ChVector<>(0, 0, 0);
m_tireForce.moment = ChVector<>(0, 0, 0);
m_tireForce.point = wheel_state.pos;
// Extract the wheel normal (expressed in global frame)
ChMatrix33<> A(wheel_state.rot);
ChVector<> disc_normal = A.Get_A_Yaxis();
// Loop over all discs, check contact with terrain and accumulate normal tire
// forces.
double depth;
for (int id = 0; id < getNumDiscs(); id++) {
// Calculate center of disk (expressed in global frame)
ChVector<> disc_center = wheel_state.pos + disc_locs[id] * disc_normal;
// Check contact with terrain and calculate contact points.
m_data[id].in_contact = disc_terrain_contact(disc_center, disc_normal, disc_radius,
m_data[id].frame, depth);
if (!m_data[id].in_contact)
continue;
// Relative velocity at contact point (expressed in global frame and in the contact frame)
ChVector<> vel = wheel_state.lin_vel + Vcross(wheel_state.ang_vel, m_data[id].frame.pos - wheel_state.pos);
m_data[id].vel = m_data[id].frame.TransformDirectionParentToLocal(vel);
// Generate normal contact force and add to accumulators (recall, all forces
// are reduced to the wheel center)
double Fn_mag = getNormalStiffness() * depth - getNormalDamping() * m_data[id].vel.z;
ChVector<> Fn = Fn_mag * m_data[id].frame.rot.GetZaxis();
m_data[id].normal_force = Fn_mag;
m_tireForce.force += Fn;
m_tireForce.moment += Vcross(m_data[id].frame.pos - m_tireForce.point, Fn);
// ODE coefficients for longitudinal direction: z' = a + b * z
{
double v = abs(m_data[id].vel.x);
double g = m_Fc[0] + (m_Fs[0] - m_Fc[0]) * exp(-sqrt(v / m_vs[0]));
m_data[id].ode_coef_a[0] = v;
m_data[id].ode_coef_b[0] = -m_sigma0[0] * v / g;
}
// ODE coefficients for lateral direction: z' = a + b * z
{
double v = abs(m_data[id].vel.y);
double g = m_Fc[1] + (m_Fs[1] - m_Fc[1]) * exp(-sqrt(v / m_vs[1]));
m_data[id].ode_coef_a[1] = v;
m_data[id].ode_coef_b[1] = -m_sigma0[1] * v / g;
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChLugreTire::Advance(double step)
{
for (int id = 0; id < getNumDiscs(); id++) {
if (!m_data[id].in_contact)
continue;
// Magnitude of normal contact force for this disc
double Fn_mag = m_data[id].normal_force;
// Advance disc state (using trapezoidal integration scheme):
// z_{n+1} = alpha * z_{n} + beta
// Evaluate friction force
// Add to accumulators for tire force
// Longitudinal direction
{
double denom = (2 - m_data[id].ode_coef_b[0] * m_stepsize);
double alpha = (2 + m_data[id].ode_coef_b[0] * m_stepsize) / denom;
double beta = 2 * m_data[id].ode_coef_a[0] * m_stepsize / denom;
double z = alpha * m_state[id].z0 + beta;
double zd = m_data[id].ode_coef_a[0] + m_data[id].ode_coef_b[0] * z;
m_state[id].z0 = z;
double v = m_data[id].vel.x;
double Ft_mag = Fn_mag * (m_sigma0[0] * z + m_sigma1[0] * zd + m_sigma2[0] * abs(v));
ChVector<> dir = (v < 0) ? m_data[id].frame.rot.GetXaxis() : -m_data[id].frame.rot.GetXaxis();
ChVector<> Ft = -Ft_mag * dir;
// Include tangential forces in accumulators
//m_tireForce.force += Ft;
//m_tireForce.moment += Vcross(m_data[id].frame.pos - m_tireForce.point, Ft);
}
// Lateral direction
{
double denom = (2 - m_data[id].ode_coef_b[1] * m_stepsize);
double alpha = (2 + m_data[id].ode_coef_b[1] * m_stepsize) / denom;
double beta = 2 * m_data[id].ode_coef_a[1] * m_stepsize / denom;
double z = alpha * m_state[id].z1 + beta;
double zd = m_data[id].ode_coef_a[1] + m_data[id].ode_coef_b[1] * z;
m_state[id].z1 = z;
double v = m_data[id].vel.y;
double Ft_mag = Fn_mag * (m_sigma0[1] * z + m_sigma1[1] * zd + m_sigma2[1] * abs(v));
ChVector<> dir = (v < 0) ? m_data[id].frame.rot.GetYaxis() : -m_data[id].frame.rot.GetYaxis();
ChVector<> Ft = -Ft_mag * dir;
// Include tangential forces in accumulators
//m_tireForce.force += Ft;
//m_tireForce.moment += Vcross(m_data[id].frame.pos - m_tireForce.point, Ft);
}
}
}
} // end namespace chrono
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Aki Mikkola
// =============================================================================
//
// Template for a tire model based on LuGre friction
//
// Ref: C.Canudas de Wit, P.Tsiotras, E.Velenis, M.Basset and
// G.Gissinger.Dynamics friction models for longitudinal road / tire
// interaction.Vehicle System Dynamics.Oct 14, 2002.
//
// =============================================================================
#include "ChLugreTire.h"
namespace chrono {
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
ChLugreTire::ChLugreTire(const ChTerrain& terrain)
: ChTire(terrain),
m_stepsize(1e-3)
{
m_tireForce.force = ChVector<>(0, 0, 0);
m_tireForce.point = ChVector<>(0, 0, 0);
m_tireForce.moment = ChVector<>(0, 0, 0);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChLugreTire::Initialize()
{
m_data.resize(getNumDiscs());
m_state.resize(getNumDiscs());
SetLugreParams();
// Initialize disc states
for (int id = 0; id < getNumDiscs(); id++) {
m_state[id].z0 = 0;
m_state[id].z1 = 0;
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChLugreTire::Update(double time,
const ChBodyState& wheel_state)
{
double disc_radius = getRadius();
const double* disc_locs = getDiscLocations();
// Clear the force accumulators and set the application point to the wheel
// center.
m_tireForce.force = ChVector<>(0, 0, 0);
m_tireForce.moment = ChVector<>(0, 0, 0);
m_tireForce.point = wheel_state.pos;
// Extract the wheel normal (expressed in global frame)
ChMatrix33<> A(wheel_state.rot);
ChVector<> disc_normal = A.Get_A_Yaxis();
// Loop over all discs, check contact with terrain and accumulate normal tire
// forces.
double depth;
for (int id = 0; id < getNumDiscs(); id++) {
// Calculate center of disk (expressed in global frame)
ChVector<> disc_center = wheel_state.pos + disc_locs[id] * disc_normal;
// Check contact with terrain and calculate contact points.
m_data[id].in_contact = disc_terrain_contact(disc_center, disc_normal, disc_radius,
m_data[id].frame, depth);
if (!m_data[id].in_contact)
continue;
// Relative velocity at contact point (expressed in global frame and in the contact frame)
ChVector<> vel = wheel_state.lin_vel + Vcross(wheel_state.ang_vel, m_data[id].frame.pos - wheel_state.pos);
m_data[id].vel = m_data[id].frame.TransformDirectionParentToLocal(vel);
// Generate normal contact force and add to accumulators (recall, all forces
// are reduced to the wheel center)
double Fn_mag = getNormalStiffness() * depth - getNormalDamping() * m_data[id].vel.z;
ChVector<> Fn = Fn_mag * m_data[id].frame.rot.GetZaxis();
m_data[id].normal_force = Fn_mag;
m_tireForce.force += Fn;
m_tireForce.moment += Vcross(m_data[id].frame.pos - m_tireForce.point, Fn);
// ODE coefficients for longitudinal direction: z' = a + b * z
{
double v = abs(m_data[id].vel.x);
double g = m_Fc[0] + (m_Fs[0] - m_Fc[0]) * exp(-sqrt(v / m_vs[0]));
m_data[id].ode_coef_a[0] = v;
m_data[id].ode_coef_b[0] = -m_sigma0[0] * v / g;
}
// ODE coefficients for lateral direction: z' = a + b * z
{
double v = abs(m_data[id].vel.y);
double g = m_Fc[1] + (m_Fs[1] - m_Fc[1]) * exp(-sqrt(v / m_vs[1]));
m_data[id].ode_coef_a[1] = v;
m_data[id].ode_coef_b[1] = -m_sigma0[1] * v / g;
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChLugreTire::Advance(double step)
{
for (int id = 0; id < getNumDiscs(); id++) {
if (!m_data[id].in_contact)
continue;
// Magnitude of normal contact force for this disc
double Fn_mag = m_data[id].normal_force;
// Advance disc state (using trapezoidal integration scheme):
// z_{n+1} = alpha * z_{n} + beta
// Evaluate friction force
// Add to accumulators for tire force
// Longitudinal direction
{
double denom = (2 - m_data[id].ode_coef_b[0] * m_stepsize);
double alpha = (2 + m_data[id].ode_coef_b[0] * m_stepsize) / denom;
double beta = 2 * m_data[id].ode_coef_a[0] * m_stepsize / denom;
double z = alpha * m_state[id].z0 + beta;
double zd = m_data[id].ode_coef_a[0] + m_data[id].ode_coef_b[0] * z;
m_state[id].z0 = z;
double v = m_data[id].vel.x;
double Ft_mag = Fn_mag * (m_sigma0[0] * z + m_sigma1[0] * zd + m_sigma2[0] * abs(v));
ChVector<> dir = (v > 0) ? m_data[id].frame.rot.GetXaxis() : -m_data[id].frame.rot.GetXaxis();
ChVector<> Ft = -Ft_mag * dir;
// Include tangential forces in accumulators
//m_tireForce.force += Ft;
//m_tireForce.moment += Vcross(m_data[id].frame.pos - m_tireForce.point, Ft);
}
// Lateral direction
{
double denom = (2 - m_data[id].ode_coef_b[1] * m_stepsize);
double alpha = (2 + m_data[id].ode_coef_b[1] * m_stepsize) / denom;
double beta = 2 * m_data[id].ode_coef_a[1] * m_stepsize / denom;
double z = alpha * m_state[id].z1 + beta;
double zd = m_data[id].ode_coef_a[1] + m_data[id].ode_coef_b[1] * z;
m_state[id].z1 = z;
double v = m_data[id].vel.y;
double Ft_mag = Fn_mag * (m_sigma0[1] * z + m_sigma1[1] * zd + m_sigma2[1] * abs(v));
ChVector<> dir = (v > 0) ? m_data[id].frame.rot.GetYaxis() : -m_data[id].frame.rot.GetYaxis();
ChVector<> Ft = -Ft_mag * dir;
// Include tangential forces in accumulators
//m_tireForce.force += Ft;
//m_tireForce.moment += Vcross(m_data[id].frame.pos - m_tireForce.point, Ft);
}
}
}
} // end namespace chrono
|
Fix bug in direction of friction forces.
|
Fix bug in direction of friction forces.
|
C++
|
bsd-3-clause
|
hsu/chrono-vehicle,hsu/chrono-vehicle,hsu/chrono-vehicle
|
9b352aa82877be653ba908222b0c490ff8b13925
|
test/CodeUnloading/Simple.C
|
test/CodeUnloading/Simple.C
|
// RUN: cat %s | %cling | FileCheck %s
// Test the ability of unloading the last transaction. Here as a matter of fact
// we unload the wrapper as well and TODO: decrement the unique wrapper counter.
int f = 0;
.U
.rawInput 1
extern "C" int printf(const char* fmt, ...);
int f() {
printf("Now f is a function\n");
return 0;
} int a = f();
.U
.rawInput 0
//CHECK: Now f is a function
double f = 3.14
//CHECK: (double) 3.14
|
// RUN: cat %s | %cling 2>&1 | FileCheck %s
// Test the ability of unloading the last transaction. Here as a matter of fact
// we unload the wrapper as well and TODO: decrement the unique wrapper counter.
extern "C" int printf(const char* fmt, ...);
printf("Force printf codegeneration. Otherwise CG will defer it and .storeState will be unhappy.\n");
//CHECK: Force printf codegeneration. Otherwise CG will defer it and .storeState will be unhappy.
.storeState "preUnload"
int f = 0;
.U
.rawInput 1
int f() {
printf("Now f is a function\n");
return 0;
} int a = f();
.U
.rawInput 0
//CHECK: Now f is a function
.compareState "preUnload"
//CHECK-NOT: Differences
double f = 3.14
//CHECK: (double) 3.14
|
Use store/compare state for detailed verification.
|
Use store/compare state for detailed verification.
|
C++
|
lgpl-2.1
|
root-mirror/cling,marsupial/cling,karies/cling,marsupial/cling,perovic/cling,root-mirror/cling,karies/cling,root-mirror/cling,perovic/cling,root-mirror/cling,karies/cling,karies/cling,marsupial/cling,marsupial/cling,perovic/cling,marsupial/cling,perovic/cling,root-mirror/cling,karies/cling,root-mirror/cling,marsupial/cling,perovic/cling,karies/cling
|
4b51a69e6a0f86a139b3a7247f5eba20e3c04e8a
|
test/common/VariantTest.cpp
|
test/common/VariantTest.cpp
|
/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2014-2017 Kim Kulling
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 <gtest/gtest.h>
#include <cppcore/Common/Variant.h>
using namespace CPPCore;
//-------------------------------------------------------------------------------------------------
/// @class ::VariantTest
/// @ingroup Test
///
/// @brief This class implements the variant unit-tests.
//-------------------------------------------------------------------------------------------------
class VariantTest : public testing::Test {
protected:
//---------------------------------------------------------------------------------------------
int *createInt( size_t buffersize ) {
int *pData = new int[ buffersize ];
for ( size_t i=0; i<buffersize; i++ ) {
pData[ i ] = ( int ) i * 1;
}
return pData;
}
//---------------------------------------------------------------------------------------------
float *createFloatData( size_t buffersize ) {
float *pData = new float[ buffersize ];
for ( size_t i=0; i<buffersize; i++ ) {
pData[ i ] = (float)i * 1.0f;
}
return pData;
}
//---------------------------------------------------------------------------------------------
bool validateIntData( size_t buffersize, int *pData, int *pRes ) {
bool equal = true;
for( size_t i = 0; i<buffersize; i++ ) {
if ( *pRes != pData[ i ] ) {
equal = false;
break;
}
++pRes;
}
return equal;
}
//---------------------------------------------------------------------------------------------
bool validateFloatData( size_t buffersize, float *pData, float *pRes ) {
bool equal = true;
for( size_t i = 0; i<buffersize; i++ ) {
if ( *pRes != pData[ i ] ) {
equal = false;
break;
}
++pRes;
}
return equal;
}
};
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, createTest ) {
int data = 1;
Variant test1( Variant::Int, (void*)&data, 1 );
EXPECT_TRUE ( true );
Variant test2;
EXPECT_TRUE ( true );
Variant *pTest3 = new Variant;
delete pTest3;
EXPECT_TRUE( true );
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, copyTest ) {
int data = 1;
Variant test1( Variant::Int, (void*)&data, 1 );
EXPECT_TRUE ( true );
Variant test2( test1 );
EXPECT_EQ( test2, test1 );
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, accessIntTest ) {
int data = 1;
Variant test( Variant::Int, (void*)&data, 1 );
int res = test.getInt( );
EXPECT_EQ ( res, data );
data = 2;
test.setInt( data );
res = test.getInt();
EXPECT_EQ ( res, data );
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, accessInt3Test ) {
static const size_t bufferSize = 3;
int *pData = createInt( bufferSize );
Variant test( Variant::Int3, (void*) pData, bufferSize );
int *pRes = test.getInt3( );
EXPECT_NE( nullptr, pRes );
EXPECT_TRUE( validateIntData( bufferSize, pData, pRes ) );
delete [] pData;
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, accessInt4Test ) {
const size_t bufferSize = 4;
int *pData = createInt( bufferSize );
Variant test( Variant::Int4, (void*) pData, bufferSize );
int *pRes = test.getInt4( );
EXPECT_NE( nullptr, pRes );
EXPECT_TRUE( validateIntData( bufferSize, pData, pRes ) );
delete [] pData;
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, accessFloatTest ) {
float data = 1.0f;
Variant test( Variant::Float, (void*)&data, 1 );
float res = test.getFloat( );
EXPECT_EQ( res, data );
data = 2.0f;
test.setFloat( data );
res = test.getFloat();
EXPECT_EQ( res, data );
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, accessFloat3Test ) {
const size_t bufferSize = 3;
float *pData = createFloatData( bufferSize );
Variant test( Variant::Float3, (void*) pData, bufferSize );
float *pRes = test.getFloat3( );
EXPECT_NE( pRes, nullptr );
EXPECT_TRUE( validateFloatData( bufferSize, pData, pRes ) );
delete [] pData;
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, accessFloat4Test ) {
const size_t bufferSize = 4;
float *pData = createFloatData( bufferSize );
Variant test( Variant::Float4, (void*) pData, bufferSize );
float *pRes = test.getFloat4( );
EXPECT_NE( pRes, nullptr );
validateFloatData( bufferSize, pData, pRes );
float data[ 4 ] = {
1.0f, 2.0f, 3.0f, 4.0f
};
test.setFloat4( data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ] );
pRes = test.getFloat4();
EXPECT_TRUE( validateFloatData( 4, data, pRes ) );
delete [] pData;
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, accessStringTest ) {
CString str( "test" );
Variant test( Variant::String, (void*) str.c_str(), str.size() );
const CString buffer( test.getString() );
EXPECT_TRUE( !buffer.isEmpty() );
bool equal( true );
for ( size_t i=0; i<buffer.size(); i++ ) {
if ( buffer[ i ] != str[ i ] ) {
equal = false;
}
}
EXPECT_TRUE( equal );
EXPECT_TRUE( buffer == str );
}
//---------------------------------------------------------------------------------------------
TEST_F( VariantTest, accessBooleanTest ) {
bool value( true );
Variant test( value );
EXPECT_EQ( test.getBool(), value );
test.setBool( false );
EXPECT_EQ( test.getBool(), false );
Variant test1( test );
EXPECT_EQ( test1, test );
}
//---------------------------------------------------------------------------------------------
|
/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2014-2017 Kim Kulling
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 <gtest/gtest.h>
#include <cppcore/Common/Variant.h>
using namespace CPPCore;
//-------------------------------------------------------------------------------------------------
/// @class ::VariantTest
/// @ingroup Test
///
/// @brief This class implements the variant unit-tests.
//-------------------------------------------------------------------------------------------------
class VariantTest : public testing::Test {
protected:
int *createInt( size_t buffersize ) {
int *pData = new int[ buffersize ];
for ( size_t i=0; i<buffersize; i++ ) {
pData[ i ] = ( int ) i * 1;
}
return pData;
}
float *createFloatData( size_t buffersize ) {
float *pData = new float[ buffersize ];
for ( size_t i=0; i<buffersize; i++ ) {
pData[ i ] = (float)i * 1.0f;
}
return pData;
}
bool validateIntData( size_t buffersize, int *pData, int *pRes ) {
bool equal = true;
for( size_t i = 0; i<buffersize; i++ ) {
if ( *pRes != pData[ i ] ) {
equal = false;
break;
}
++pRes;
}
return equal;
}
bool validateFloatData( size_t buffersize, float *pData, float *pRes ) {
bool equal = true;
for( size_t i = 0; i<buffersize; i++ ) {
if ( *pRes != pData[ i ] ) {
equal = false;
break;
}
++pRes;
}
return equal;
}
};
TEST_F( VariantTest, createTest ) {
int data = 1;
Variant test1( Variant::Int, (void*)&data, 1 );
EXPECT_TRUE ( true );
Variant test2;
EXPECT_TRUE ( true );
Variant *pTest3 = new Variant;
delete pTest3;
EXPECT_TRUE( true );
}
TEST_F( VariantTest, copyTest ) {
int data = 1;
Variant test1( Variant::Int, (void*)&data, 1 );
EXPECT_TRUE ( true );
Variant test2( test1 );
EXPECT_EQ( test2, test1 );
}
TEST_F( VariantTest, accessIntTest ) {
int data = 1;
Variant test( Variant::Int, (void*)&data, 1 );
int res = test.getInt( );
EXPECT_EQ ( res, data );
data = 2;
test.setInt( data );
res = test.getInt();
EXPECT_EQ ( res, data );
}
TEST_F( VariantTest, accessInt3Test ) {
static const size_t bufferSize = 3;
int *pData = createInt( bufferSize );
Variant test( Variant::Int3, (void*) pData, bufferSize );
int *pRes = test.getInt3( );
EXPECT_NE( nullptr, pRes );
EXPECT_TRUE( validateIntData( bufferSize, pData, pRes ) );
delete [] pData;
}
TEST_F( VariantTest, accessInt4Test ) {
const size_t bufferSize = 4;
int *pData = createInt( bufferSize );
Variant test( Variant::Int4, (void*) pData, bufferSize );
int *pRes = test.getInt4( );
EXPECT_NE( nullptr, pRes );
EXPECT_TRUE( validateIntData( bufferSize, pData, pRes ) );
delete [] pData;
}
TEST_F( VariantTest, accessFloatTest ) {
float data = 1.0f;
Variant test( Variant::Float, (void*)&data, 1 );
float res = test.getFloat( );
EXPECT_EQ( res, data );
data = 2.0f;
test.setFloat( data );
res = test.getFloat();
EXPECT_EQ( res, data );
}
TEST_F( VariantTest, accessFloat3Test ) {
const size_t bufferSize = 3;
float *pData = createFloatData( bufferSize );
Variant test( Variant::Float3, (void*) pData, bufferSize );
float *pRes = test.getFloat3( );
EXPECT_NE( pRes, nullptr );
EXPECT_TRUE( validateFloatData( bufferSize, pData, pRes ) );
delete [] pData;
}
TEST_F( VariantTest, accessFloat4Test ) {
const size_t bufferSize = 4;
float *pData = createFloatData( bufferSize );
Variant test( Variant::Float4, (void*) pData, bufferSize );
float *pRes = test.getFloat4( );
EXPECT_NE( pRes, nullptr );
validateFloatData( bufferSize, pData, pRes );
float data[ 4 ] = {
1.0f, 2.0f, 3.0f, 4.0f
};
test.setFloat4( data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ] );
pRes = test.getFloat4();
EXPECT_TRUE( validateFloatData( 4, data, pRes ) );
delete [] pData;
}
TEST_F( VariantTest, accessStringTest ) {
CString str( "test" );
Variant test( Variant::String, (void*) str.c_str(), str.size() );
const CString buffer( test.getString() );
EXPECT_TRUE( !buffer.isEmpty() );
bool equal( true );
for ( size_t i=0; i<buffer.size(); i++ ) {
if ( buffer[ i ] != str[ i ] ) {
equal = false;
}
}
EXPECT_TRUE( equal );
EXPECT_TRUE( buffer == str );
}
TEST_F( VariantTest, accessBooleanTest ) {
bool value( true );
Variant test( value );
EXPECT_EQ( test.getBool(), value );
test.setBool( false );
EXPECT_EQ( test.getBool(), false );
Variant test1( test );
EXPECT_EQ( test1, test );
}
|
Update VariantTest.cpp
|
Update VariantTest.cpp
Remove comments
|
C++
|
mit
|
kimkulling/cppcore,kimkulling/cppcore,kimkulling/cppcore,kimkulling/cppcore
|
31ab77ec42f8a6fd6e442c915b399230d860ff53
|
test/common/common_test.cpp
|
test/common/common_test.cpp
|
#include "gtest/gtest.h"
#include "../test_common.h"
class ProcTest : public ExpectOutput {};
template <typename Func>
static Output spawnAndWait(IOConfig config, Func func, bool remove = false) {
return ProcBuilder::spawn(config, func).waitAndGetResult(remove);
}
TEST_F(ProcTest, status) {
auto ret = spawnAndWait(IOConfig{}, [&]{
return 100;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 100));
IOConfig config;
config.out = IOConfig::PIPE;
ret = spawnAndWait(config, [&]{
return 10;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 10));
ret = spawnAndWait(IOConfig{}, [&]()-> int {
abort();
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, SIGABRT, WaitStatus::SIGNALED));
}
TEST_F(ProcTest, pipe) {
IOConfig config;
config.out = IOConfig::PIPE;
auto ret = spawnAndWait(config, [&]{
return 10;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 10));
config.err = IOConfig::PIPE;
ret = spawnAndWait(config, [&]{
fprintf(stdout, "hello");
fprintf(stderr, "world");
return 10;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 10, WaitStatus::EXITED, "hello", "world"));
}
TEST_F(ProcTest, pty1) {
IOConfig config;
config.in = IOConfig::PTY;
config.out = IOConfig::PTY;
config.err = IOConfig::PIPE;
auto ret = spawnAndWait(config, [&]{
if(!isatty(STDIN_FILENO)) {
return 10;
}
if(!isatty(STDOUT_FILENO)) {
return 20;
}
if(isatty(STDERR_FILENO)) {
return 30;
}
return 0;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret));
}
TEST_F(ProcTest, pty2) {
IOConfig config;
config.in = IOConfig::PTY;
config.out = IOConfig::PTY;
config.err = IOConfig::PIPE;
auto handle = ProcBuilder::spawn(config, [&]{
char buf[64];
auto size = read(STDIN_FILENO, buf, 64);
if(size > 0) {
buf[size] = '\0';
printf("%s\n", buf);
return 0;
}
return 1;
});
std::string str = "hello";
auto r = write(handle.in(), str.c_str(), str.size());
(void) r;
auto ret2 = handle.waitAndGetResult(false);
ASSERT_NO_FATAL_FAILURE(this->expect(ret2, 0, WaitStatus::EXITED, "hello\n"));
}
TEST_F(ProcTest, pty3) {
IOConfig config;
config.in = IOConfig::PTY;
config.out = IOConfig::PTY;
auto handle = ProcBuilder::spawn(config, [&]{
char buf[1];
while(read(STDIN_FILENO, buf, 1) > 0) {
if(buf[0] == 'p') {
printf("print\n");
} else if(buf[0] == 'b') {
printf("break!!\n");
break;
} else {
printf("ignore %c\n", buf[0]);
}
fflush(stdout);
}
return 0;
});
auto r = write(handle.in(), "p", 1);
(void) r;
auto output = handle.readAll(5);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ("print\n", output.first));
r = write(handle.in(), "x", 1);
(void) r;
output = handle.readAll(5);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ("ignore x\n", output.first));
r = write(handle.in(), "b", 1);
(void) r;
auto ret = handle.waitAndGetResult(false);
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 0, WaitStatus::EXITED, "break!!\n"));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#include "gtest/gtest.h"
#include "../test_common.h"
class ProcTest : public ExpectOutput {};
template <typename Func>
static Output spawnAndWait(IOConfig config, Func func, bool remove = false) {
return ProcBuilder::spawn(config, func).waitAndGetResult(remove);
}
TEST_F(ProcTest, status) {
auto ret = spawnAndWait(IOConfig{}, [&]{
return 100;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 100));
IOConfig config;
config.out = IOConfig::PIPE;
ret = spawnAndWait(config, [&]{
return 10;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 10));
ret = spawnAndWait(IOConfig{}, [&]()-> int {
abort();
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, SIGABRT, WaitStatus::SIGNALED));
}
TEST_F(ProcTest, pipe) {
IOConfig config;
config.out = IOConfig::PIPE;
auto ret = spawnAndWait(config, [&]{
return 10;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 10));
config.err = IOConfig::PIPE;
ret = spawnAndWait(config, [&]{
fprintf(stdout, "hello");
fprintf(stderr, "world");
return 10;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 10, WaitStatus::EXITED, "hello", "world"));
}
TEST_F(ProcTest, pty1) {
IOConfig config;
config.in = IOConfig::PTY;
config.out = IOConfig::PTY;
config.err = IOConfig::PIPE;
auto ret = spawnAndWait(config, [&]{
if(!isatty(STDIN_FILENO)) {
return 10;
}
if(!isatty(STDOUT_FILENO)) {
return 20;
}
if(isatty(STDERR_FILENO)) {
return 30;
}
return 0;
});
ASSERT_NO_FATAL_FAILURE(this->expect(ret));
}
TEST_F(ProcTest, pty2) {
IOConfig config;
config.in = IOConfig::PTY;
config.out = IOConfig::PTY;
config.err = IOConfig::PIPE;
auto handle = ProcBuilder::spawn(config, [&]{
char buf[64];
auto size = read(STDIN_FILENO, buf, 64);
if(size > 0) {
buf[size] = '\0';
printf("%s\n", buf);
return 0;
}
return 1;
});
std::string str = "hello";
auto r = write(handle.in(), str.c_str(), str.size());
(void) r;
auto ret2 = handle.waitAndGetResult(false);
ASSERT_NO_FATAL_FAILURE(this->expect(ret2, 0, WaitStatus::EXITED, "hello\n"));
}
TEST_F(ProcTest, pty3) {
IOConfig config;
config.in = IOConfig::PTY;
config.out = IOConfig::PTY;
auto handle = ProcBuilder::spawn(config, [&]{
char buf[1];
while(read(STDIN_FILENO, buf, 1) > 0) {
if(buf[0] == 'p') {
printf("print\n");
} else if(buf[0] == 'b') {
printf("break!!\n");
break;
} else {
printf("ignore %c\n", buf[0]);
}
fflush(stdout);
}
return 0;
});
auto r = write(handle.in(), "p", 1);
(void) r;
auto output = handle.readAll(20);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ("print\n", output.first));
r = write(handle.in(), "x", 1);
(void) r;
output = handle.readAll(20);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ("ignore x\n", output.first));
r = write(handle.in(), "b", 1);
(void) r;
auto ret = handle.waitAndGetResult(false);
ASSERT_NO_FATAL_FAILURE(this->expect(ret, 0, WaitStatus::EXITED, "break!!\n"));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
fix poll interval
|
fix poll interval
|
C++
|
apache-2.0
|
sekiguchi-nagisa/ydsh,sekiguchi-nagisa/ydsh,sekiguchi-nagisa/ydsh
|
c163d2ca0e699ab577c50a27fea4e3222790a1b6
|
test/cpp/db/test/Tester.cpp
|
test/cpp/db/test/Tester.cpp
|
/*
* Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/test/Tester.h"
#include <iostream>
#include <sstream>
#include <cstdlib>
#include "db/test/Test.h"
#include "db/rt/Exception.h"
#include "db/rt/Thread.h"
using namespace std;
using namespace db::app;
using namespace db::config;
using namespace db::rt;
using namespace db::test;
Tester::Tester()
{
mName = NULL;
setName("");
mApp = NULL;
}
Tester::~Tester()
{
setName(NULL);
for(list<Tester*>::iterator i = mTesters.begin();
i != mTesters.end();
i++)
{
delete *i;
}
}
void Tester::registeredForApp(db::app::App* app)
{
mApp = app;
for(list<Tester*>::iterator i = mTesters.begin();
i != mTesters.end();
i++)
{
(*i)->registeredForApp(mApp);
}
}
DynamicObject Tester::getCommandLineSpec()
{
DynamicObject spec;
spec["help"] =
"Test options:\n"
" -l, --level LEVEL Adjust test output level to LEVEL. (default: 3)\n"
" 0: No output.\n"
" 1: Final results.\n"
" 2: Progress (.=success, W=warning, F=failure).\n"
" 3: Test names and PASS/WARNING/FAIL status.\n"
" 4: Same as 3, plus test time.\n"
" All levels have exit status of 0 on success.\n"
" -c Continue after failure. (default: true).\n"
" -i, --interactive Do only interactive tests. (default: false).\n"
" -a, --automatic Do only automatic tests. (default: true).\n"
" Note: -i and -a can be combined to do both types.\n"
"\n";
DynamicObject opt;
Config& cfg = mApp->getConfig();
opt = spec["options"]->append();
opt["short"] = "-l";
opt["long"] = "--level";
opt["arg"] = cfg["db.test.Tester"]["level"];
opt = spec["options"]->append();
opt["short"] = "-c";
opt["setTrue"] = cfg["db.test.Tester"]["continueAfterException"];
opt = spec["options"]->append();
opt["short"] = "-a";
opt["long"] = "--automatic";
opt["setTrue"] = cfg["db.test.Tester"]["__cl_automatic"];
opt = spec["options"]->append();
opt["short"] = "-i";
opt["long"] = "--interactive";
opt["setTrue"] = cfg["db.test.Tester"]["__cl_interactive"];
return spec;
}
bool Tester::willParseCommandLine(std::vector<const char*>* args)
{
bool rval = true;
mApp->getConfig()["db.test.Tester"]["level"] = 3;
mApp->getConfig()["db.test.Tester"]["continueAfterException"] = false;
return rval;
}
bool Tester::didParseCommandLine()
{
bool rval = true;
Config& cfg = mApp->getConfig()["db.test.Tester"];
// if interactive, assume no automatic, else only automatic enabled
if(cfg->hasMember("__cl_interactive") && cfg["__cl_interactive"]->getBoolean())
{
cfg["interactive"] = true;
cfg["automatic"] = false;
}
else
{
cfg["interactive"] = false;
cfg["automatic"] = true;
}
// if auto set, override interactive setting
if(cfg->hasMember("__cl_automatic") && cfg["__cl_automatic"]->getBoolean())
{
cfg["automatic"] = true;
}
return rval;
}
void Tester::setName(const char* name)
{
if(mName)
{
free(mName);
}
mName = name ? strdup(name) : NULL;
}
const char* Tester::getName()
{
return mName;
}
db::config::Config& Tester::getConfig()
{
return mApp->getConfig();
}
void Tester::setup(TestRunner& tr)
{
}
void Tester::teardown(TestRunner& tr)
{
}
void Tester::addTester(Tester* tester)
{
mTesters.push_back(tester);
}
int Tester::runAutomaticTests(TestRunner& tr)
{
return 0;
}
int Tester::runInteractiveTests(TestRunner& tr)
{
return 0;
}
int Tester::runTests(TestRunner& tr)
{
int rval = 0;
Config& cfg = mApp->getConfig()["db.test.Tester"];
tr.group(mName);
setup(tr);
assertNoException();
// run all sub-tester tests
for(list<Tester*>::iterator i = mTesters.begin();
rval == 0 && i != mTesters.end();
i++)
{
rval = (*i)->runTests(tr);
}
if(rval == 0 && cfg["interactive"]->getBoolean())
{
rval = runInteractiveTests(tr);
assertNoException();
}
if(rval == 0 && cfg["automatic"]->getBoolean())
{
rval = runAutomaticTests(tr);
assertNoException();
}
teardown(tr);
assertNoException();
tr.ungroup();
return rval;
}
bool Tester::runApp()
{
bool rval = true;
Config& cfg = mApp->getConfig()["db.test.Tester"];
bool cont = cfg["continueAfterException"]->getBoolean();
uint32_t cfgLevel = cfg["level"]->getUInt32();
TestRunner::OutputLevel level;
switch(cfgLevel)
{
case 0: level = TestRunner::None; break;
case 1: level = TestRunner::Final; break;
case 2: level = TestRunner::Progress; break;
case 3: level = TestRunner::Names; break;
default: level = TestRunner::Times; break;
}
TestRunner tr(mApp, cont, level);
int exitStatus = runTests(tr);
mApp->setExitStatus(exitStatus);
rval = (exitStatus == 0);
assertNoException();
tr.done();
return rval;
}
|
/*
* Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/test/Tester.h"
#include <iostream>
#include <sstream>
#include <cstdlib>
#include "db/test/Test.h"
#include "db/rt/Exception.h"
#include "db/rt/Thread.h"
using namespace std;
using namespace db::app;
using namespace db::config;
using namespace db::rt;
using namespace db::test;
Tester::Tester()
{
mName = NULL;
setName("");
mApp = NULL;
}
Tester::~Tester()
{
setName(NULL);
for(list<Tester*>::iterator i = mTesters.begin();
i != mTesters.end();
i++)
{
delete *i;
}
}
void Tester::registeredForApp(db::app::App* app)
{
mApp = app;
for(list<Tester*>::iterator i = mTesters.begin();
i != mTesters.end();
i++)
{
(*i)->registeredForApp(mApp);
}
}
DynamicObject Tester::getCommandLineSpec()
{
DynamicObject spec;
spec["help"] =
"Test options:\n"
" -l, --level LEVEL Adjust test output level to LEVEL. (default: 3)\n"
" 0: No output.\n"
" 1: Final results.\n"
" 2: Progress (.=success, W=warning, F=failure).\n"
" 3: Test names and PASS/WARNING/FAIL status.\n"
" 4: Same as 3, plus test time.\n"
" All levels have exit status of 0 on success.\n"
" -c Continue after failure. (default: true).\n"
" -i, --interactive Do only interactive tests. (default: false).\n"
" -a, --automatic Do only automatic tests. (default: true).\n"
" Note: -i and -a can be combined to do both types.\n"
" -t, --test TEST Run a specific test if supported. (default: \"all\")\n"
"\n";
DynamicObject opt;
Config& cfg = mApp->getConfig();
opt = spec["options"]->append();
opt["short"] = "-l";
opt["long"] = "--level";
opt["arg"] = cfg["db.test.Tester"]["level"];
opt = spec["options"]->append();
opt["short"] = "-c";
opt["setTrue"] = cfg["db.test.Tester"]["continueAfterException"];
opt = spec["options"]->append();
opt["short"] = "-a";
opt["long"] = "--automatic";
opt["setTrue"] = cfg["db.test.Tester"]["__cl_automatic"];
opt = spec["options"]->append();
opt["short"] = "-i";
opt["long"] = "--interactive";
opt["setTrue"] = cfg["db.test.Tester"]["__cl_interactive"];
opt = spec["options"]->append();
opt["short"] = "-t";
opt["long"] = "--test";
opt["arg"] = cfg["db.test.Tester"]["test"];
return spec;
}
bool Tester::willParseCommandLine(std::vector<const char*>* args)
{
bool rval = true;
mApp->getConfig()["db.test.Tester"]["level"] = TestRunner::Names;
mApp->getConfig()["db.test.Tester"]["continueAfterException"] = false;
mApp->getConfig()["db.test.Tester"]["test"] = "all";
return rval;
}
bool Tester::didParseCommandLine()
{
bool rval = true;
Config& cfg = mApp->getConfig()["db.test.Tester"];
// if interactive, assume no automatic, else only automatic enabled
if(cfg->hasMember("__cl_interactive") &&
cfg["__cl_interactive"]->getBoolean())
{
cfg["interactive"] = true;
cfg["automatic"] = false;
}
else
{
cfg["interactive"] = false;
cfg["automatic"] = true;
}
// if auto set, override interactive setting
if(cfg->hasMember("__cl_automatic") &&
cfg["__cl_automatic"]->getBoolean())
{
cfg["automatic"] = true;
}
return rval;
}
void Tester::setName(const char* name)
{
if(mName)
{
free(mName);
}
mName = name ? strdup(name) : NULL;
}
const char* Tester::getName()
{
return mName;
}
db::config::Config& Tester::getConfig()
{
return mApp->getConfig();
}
void Tester::setup(TestRunner& tr)
{
}
void Tester::teardown(TestRunner& tr)
{
}
void Tester::addTester(Tester* tester)
{
mTesters.push_back(tester);
}
int Tester::runAutomaticTests(TestRunner& tr)
{
return 0;
}
int Tester::runInteractiveTests(TestRunner& tr)
{
return 0;
}
int Tester::runTests(TestRunner& tr)
{
int rval = 0;
Config& cfg = mApp->getConfig()["db.test.Tester"];
tr.group(mName);
setup(tr);
assertNoException();
// run all sub-tester tests
for(list<Tester*>::iterator i = mTesters.begin();
rval == 0 && i != mTesters.end();
i++)
{
rval = (*i)->runTests(tr);
}
if(rval == 0 && cfg["interactive"]->getBoolean())
{
rval = runInteractiveTests(tr);
assertNoException();
}
if(rval == 0 && cfg["automatic"]->getBoolean())
{
rval = runAutomaticTests(tr);
assertNoException();
}
teardown(tr);
assertNoException();
tr.ungroup();
return rval;
}
bool Tester::runApp()
{
bool rval = true;
Config& cfg = mApp->getConfig()["db.test.Tester"];
bool cont = cfg["continueAfterException"]->getBoolean();
uint32_t cfgLevel = cfg["level"]->getUInt32();
TestRunner::OutputLevel level;
switch(cfgLevel)
{
case 0: level = TestRunner::None; break;
case 1: level = TestRunner::Final; break;
case 2: level = TestRunner::Progress; break;
case 3: level = TestRunner::Names; break;
default: level = TestRunner::Times; break;
}
TestRunner tr(mApp, cont, level);
int exitStatus = runTests(tr);
mApp->setExitStatus(exitStatus);
rval = (exitStatus == 0);
assertNoException();
tr.done();
return rval;
}
|
Add standard option to specify a specific test.
|
Add standard option to specify a specific test.
|
C++
|
agpl-3.0
|
digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch
|
817d0a414d63f6faca28fbf197b9dcd557b6ae0a
|
xcodec/xcodec_encoder_pipe.cc
|
xcodec/xcodec_encoder_pipe.cc
|
#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/pipe.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_encoder_pipe.h>
XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec)
: PipeSimple("/xcodec/encoder/pipe"),
encoder_(codec)
{
encoder_.set_pipe(this);
}
XCodecEncoderPipe::~XCodecEncoderPipe()
{
encoder_.set_pipe(NULL);
}
void
XCodecEncoderPipe::output_ready(void)
{
PipeSimple::output_spontaneous();
}
bool
XCodecEncoderPipe::process(Buffer *out, Buffer *in)
{
encoder_.encode(out, in);
return (true);
}
|
#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/pipe.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_encoder_pipe.h>
XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec)
: PipeSimple("/xcodec/encoder/pipe"),
encoder_(codec)
{
encoder_.set_pipe(this);
}
XCodecEncoderPipe::~XCodecEncoderPipe()
{
encoder_.set_pipe(NULL);
}
void
XCodecEncoderPipe::output_ready(void)
{
}
bool
XCodecEncoderPipe::process(Buffer *out, Buffer *in)
{
encoder_.encode(out, in);
return (true);
}
|
Remove output_spontaneous use for now.
|
Remove output_spontaneous use for now.
git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@568 4068ffdb-0463-0410-8185-8cc71e3bd399
|
C++
|
bsd-2-clause
|
diegows/wanproxy,splbio/wanproxy,splbio/wanproxy,diegows/wanproxy,diegows/wanproxy,splbio/wanproxy
|
1f8d555056ea4b9759695e0cd932080fd19fa8c5
|
engine/src/expressions/constants/constant.cc
|
engine/src/expressions/constants/constant.cc
|
#include <monsoon/expressions/constants/constant.h>
#include <stdexcept>
namespace monsoon {
namespace expressions {
namespace constants {
constant::constant(metric_value v)
: value_(std::move(v))
{
if (!v.get().is_present())
throw std::invalid_argument("metric_value may not be nil");
}
constant::~constant() noexcept {}
auto constant::evaluate(const context&) const -> expr_result {
return expr_result(value_);
}
auto constant::do_ostream(std::ostream& out) const -> void {
out << value_;
}
}}} /* namespace monsoon::expressions::constants */
|
#include <monsoon/expressions/constants/constant.h>
#include <stdexcept>
namespace monsoon {
namespace expressions {
namespace constants {
constant::constant(metric_value v)
: value_(std::move(v))
{
if (visit(
[](const auto& v) {
return std::is_same_v<metric_value::empty, std::decay_t<decltype(v)>>;
},
v.get()))
throw std::invalid_argument("metric_value may not be nil");
}
constant::~constant() noexcept {}
auto constant::evaluate(const context&) const -> expr_result {
return expr_result(value_);
}
auto constant::do_ostream(std::ostream& out) const -> void {
out << value_;
}
}}} /* namespace monsoon::expressions::constants */
|
Fix constants.
|
Fix constants.
|
C++
|
bsd-2-clause
|
nahratzah/monsoon_plus_plus,nahratzah/monsoon_plus_plus,nahratzah/monsoon_plus_plus
|
cf89871eb6e8a88821e842f411439fd3bd92f7e6
|
tests/ep_testsuite_common.cc
|
tests/ep_testsuite_common.cc
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, Inc
*
* 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 "ep_testsuite_common.h"
#include "ep_test_apis.h"
#include <cstring>
#include <iostream>
#include <string>
#include <sstream>
#include <sys/stat.h>
#ifdef _MSC_VER
#include <direct.h>
#define mkdir(a, b) _mkdir(a)
#else
#include <sys/wait.h>
#endif
#include <platform/dirutils.h>
static const char *default_dbname = "./test";
const char *dbname_env = NULL;
static enum test_result skipped_test_function(ENGINE_HANDLE *h,
ENGINE_HANDLE_V1 *h1);
BaseTestCase::BaseTestCase(const char *_name, const char *_cfg, bool _skip)
: name(_name),
cfg(_cfg),
skip(_skip) {
}
BaseTestCase::BaseTestCase(const BaseTestCase &o)
: name(o.name),
cfg(o.cfg),
skip(o.skip) {
memset(&test, 0, sizeof(test));
test = o.test;
}
TestCase::TestCase(const char *_name,
enum test_result(*_tfun)(ENGINE_HANDLE *, ENGINE_HANDLE_V1 *),
bool(*_test_setup)(ENGINE_HANDLE *, ENGINE_HANDLE_V1 *),
bool(*_test_teardown)(ENGINE_HANDLE *, ENGINE_HANDLE_V1 *),
const char *_cfg,
enum test_result (*_prepare)(engine_test_t *test),
void (*_cleanup)(engine_test_t *test, enum test_result result),
bool _skip)
: BaseTestCase(_name, _cfg, _skip) {
memset(&test, 0, sizeof(test));
test.tfun = _tfun;
test.test_setup = _test_setup;
test.test_teardown = _test_teardown;
test.prepare = _prepare;
test.cleanup = _cleanup;
}
TestCaseV2::TestCaseV2(const char *_name,
enum test_result(*_tfun)(engine_test_t *),
bool(*_test_setup)(engine_test_t *),
bool(*_test_teardown)(engine_test_t *),
const char *_cfg,
enum test_result (*_prepare)(engine_test_t *test),
void (*_cleanup)(engine_test_t *test, enum test_result result),
bool _skip)
: BaseTestCase(_name, _cfg, _skip) {
memset(&test, 0, sizeof(test));
test.api_v2.tfun = _tfun;
test.api_v2.test_setup = _test_setup;
test.api_v2.test_teardown = _test_teardown;
test.prepare = _prepare;
test.cleanup = _cleanup;
}
engine_test_t* BaseTestCase::getTest() {
engine_test_t *ret = &test;
std::string nm(name);
std::stringstream ss;
if (cfg != 0) {
ss << cfg << ";";
} else {
ss << "flushall_enabled=true;";
}
if (skip) {
nm.append(" (skipped)");
ret->tfun = skipped_test_function;
} else {
nm.append(" (couchstore)");
}
ret->name = strdup(nm.c_str());
std::string config = ss.str();
if (config.length() == 0) {
ret->cfg = 0;
} else {
ret->cfg = strdup(config.c_str());
}
return ret;
}
static enum test_result skipped_test_function(ENGINE_HANDLE *h,
ENGINE_HANDLE_V1 *h1) {
(void) h;
(void) h1;
return SKIPPED;
}
enum test_result rmdb(const char* path) {
CouchbaseDirectoryUtilities::rmrf(path);
if (access(path, F_OK) != -1) {
std::cerr << "Failed to remove: " << path << " " << std::endl;
return FAIL;
}
return SUCCESS;
}
bool test_setup(ENGINE_HANDLE *h, ENGINE_HANDLE_V1 *h1) {
wait_for_warmup_complete(h, h1);
check(h1->get_stats(h, NULL, "prev-vbucket", 12, add_stats) == ENGINE_SUCCESS,
"Failed to get the previous state of vbuckets");
if (vals.find("vb_0") == vals.end()) {
check(set_vbucket_state(h, h1, 0, vbucket_state_active),
"Failed to set VB0 state.");
}
wait_for_stat_change(h, h1, "ep_vb_snapshot_total", 0);
// warmup is complete, notify ep engine that it must now enable
// data traffic
protocol_binary_request_header *pkt = createPacket(PROTOCOL_BINARY_CMD_ENABLE_TRAFFIC);
check(h1->unknown_command(h, NULL, pkt, add_response) == ENGINE_SUCCESS,
"Failed to enable data traffic");
free(pkt);
return true;
}
bool teardown(ENGINE_HANDLE *h, ENGINE_HANDLE_V1 *h1) {
(void)h; (void)h1;
vals.clear();
return true;
}
bool teardown_v2(engine_test_t* test) {
(void)test;
vals.clear();
return true;
}
std::string get_dbname(const char* test_cfg) {
std::string dbname;
if (!test_cfg) {
dbname.assign(dbname_env);
return dbname;
}
const char *nm = strstr(test_cfg, "dbname=");
if (nm == NULL) {
dbname.assign(dbname_env);
} else {
dbname.assign(nm + 7);
std::string::size_type end = dbname.find(';');
if (end != dbname.npos) {
dbname = dbname.substr(0, end);
}
}
return dbname;
}
enum test_result prepare(engine_test_t *test) {
#ifdef __sun
// Some of the tests doesn't work on Solaris.. Don't know why yet..
if (strstr(test->name, "concurrent set") != NULL ||
strstr(test->name, "retain rowid over a soft delete") != NULL)
{
return SKIPPED;
}
#endif
std::string dbname = get_dbname(test->cfg);
/* Remove if the same DB directory already exists */
rmdb(dbname.c_str());
mkdir(dbname.c_str(), 0777);
return SUCCESS;
}
void cleanup(engine_test_t *test, enum test_result result) {
(void)result;
// Nuke the database files we created
std::string dbname = get_dbname(test->cfg);
/* Remove only the db file this test created */
rmdb(dbname.c_str());
}
// Array of testcases to return back to engine_testapp.
static engine_test_t *testcases;
// Should only one test be run, and if so which number? If -1 then all tests
// are run.
static int oneTestIdx;
struct test_harness testHarness;
extern BaseTestCase testsuite_testcases[];
// Examines the list of tests provided by the specific testsuite
// via the testsuite_testcases[] array, populates `testcases` and returns it.
MEMCACHED_PUBLIC_API
engine_test_t* get_tests(void) {
// Calculate the size of the tests..
int num = 0;
while (testsuite_testcases[num].getName() != NULL) {
++num;
}
oneTestIdx = -1;
char *testNum = getenv("EP_TEST_NUM");
if (testNum) {
sscanf(testNum, "%d", &oneTestIdx);
if (oneTestIdx < 0 || oneTestIdx > num) {
oneTestIdx = -1;
}
}
dbname_env = getenv("EP_TEST_DIR");
if (!dbname_env) {
dbname_env = default_dbname;
}
if (oneTestIdx == -1) {
testcases = static_cast<engine_test_t*>(calloc(num + 1, sizeof(engine_test_t)));
int ii = 0;
for (int jj = 0; jj < num; ++jj) {
engine_test_t *r = testsuite_testcases[jj].getTest();
if (r != 0) {
testcases[ii++] = *r;
}
}
} else {
testcases = static_cast<engine_test_t*>(calloc(1 + 1, sizeof(engine_test_t)));
engine_test_t *r = testsuite_testcases[oneTestIdx].getTest();
if (r != 0) {
testcases[0] = *r;
}
}
return testcases;
}
MEMCACHED_PUBLIC_API
bool setup_suite(struct test_harness *th) {
testHarness = *th;
return true;
}
MEMCACHED_PUBLIC_API
bool teardown_suite() {
for (int i = 0; testcases[i].name != nullptr; i++) {
free((char*)testcases[i].name);
free((char*)testcases[i].cfg);
}
free(testcases);
testcases = NULL;
return true;
}
/*
* Create n_buckets and return how many were actually created.
*/
int create_buckets(const char* cfg, int n_buckets, std::vector<BucketHolder> &buckets) {
std::string dbname = get_dbname(cfg);
for (int ii = 0; ii < n_buckets; ii++) {
std::stringstream config, dbpath;
dbpath << dbname.c_str() << ii;
std::string str_cfg(cfg);
/* Find the position of "dbname=" in str_cfg */
size_t pos = str_cfg.find("dbname=");
if (pos != std::string::npos) {
/* Move till end of the dbname */
size_t new_pos = str_cfg.find(';', pos);
str_cfg.insert(new_pos, std::to_string(ii));
config << str_cfg;
} else {
config << str_cfg << "dbname=" << dbpath.str();
}
rmdb(dbpath.str().c_str());
ENGINE_HANDLE_V1* handle = testHarness.create_bucket(true, config.str().c_str());
if (handle) {
buckets.push_back(BucketHolder((ENGINE_HANDLE*)handle, handle, dbpath.str()));
} else {
return ii;
}
}
return n_buckets;
}
void destroy_buckets(std::vector<BucketHolder> &buckets) {
for(auto bucket : buckets) {
testHarness.destroy_bucket(bucket.h, bucket.h1, false);
rmdb(bucket.dbpath.c_str());
}
}
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, Inc
*
* 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 "ep_testsuite_common.h"
#include "ep_test_apis.h"
#include <cstring>
#include <iostream>
#include <string>
#include <sstream>
#include <sys/stat.h>
#ifdef _MSC_VER
#include <direct.h>
#define mkdir(a, b) _mkdir(a)
#else
#include <sys/wait.h>
#endif
#include <platform/dirutils.h>
static const char *default_dbname = "./test";
const char *dbname_env = NULL;
static enum test_result skipped_test_function(ENGINE_HANDLE *h,
ENGINE_HANDLE_V1 *h1);
BaseTestCase::BaseTestCase(const char *_name, const char *_cfg, bool _skip)
: name(_name),
cfg(_cfg),
skip(_skip) {
}
BaseTestCase::BaseTestCase(const BaseTestCase &o)
: name(o.name),
cfg(o.cfg),
skip(o.skip) {
memset(&test, 0, sizeof(test));
test = o.test;
}
TestCase::TestCase(const char *_name,
enum test_result(*_tfun)(ENGINE_HANDLE *, ENGINE_HANDLE_V1 *),
bool(*_test_setup)(ENGINE_HANDLE *, ENGINE_HANDLE_V1 *),
bool(*_test_teardown)(ENGINE_HANDLE *, ENGINE_HANDLE_V1 *),
const char *_cfg,
enum test_result (*_prepare)(engine_test_t *test),
void (*_cleanup)(engine_test_t *test, enum test_result result),
bool _skip)
: BaseTestCase(_name, _cfg, _skip) {
memset(&test, 0, sizeof(test));
test.tfun = _tfun;
test.test_setup = _test_setup;
test.test_teardown = _test_teardown;
test.prepare = _prepare;
test.cleanup = _cleanup;
}
TestCaseV2::TestCaseV2(const char *_name,
enum test_result(*_tfun)(engine_test_t *),
bool(*_test_setup)(engine_test_t *),
bool(*_test_teardown)(engine_test_t *),
const char *_cfg,
enum test_result (*_prepare)(engine_test_t *test),
void (*_cleanup)(engine_test_t *test, enum test_result result),
bool _skip)
: BaseTestCase(_name, _cfg, _skip) {
memset(&test, 0, sizeof(test));
test.api_v2.tfun = _tfun;
test.api_v2.test_setup = _test_setup;
test.api_v2.test_teardown = _test_teardown;
test.prepare = _prepare;
test.cleanup = _cleanup;
}
engine_test_t* BaseTestCase::getTest() {
engine_test_t *ret = &test;
std::string nm(name);
std::stringstream ss;
if (cfg != 0) {
ss << cfg << ";";
} else {
ss << "flushall_enabled=true;";
}
if (skip) {
nm.append(" (skipped)");
ret->tfun = skipped_test_function;
} else {
nm.append(" (couchstore)");
}
ret->name = strdup(nm.c_str());
std::string config = ss.str();
if (config.length() == 0) {
ret->cfg = 0;
} else {
ret->cfg = strdup(config.c_str());
}
return ret;
}
static enum test_result skipped_test_function(ENGINE_HANDLE *h,
ENGINE_HANDLE_V1 *h1) {
(void) h;
(void) h1;
return SKIPPED;
}
enum test_result rmdb(const char* path) {
CouchbaseDirectoryUtilities::rmrf(path);
if (access(path, F_OK) != -1) {
std::cerr << "Failed to remove: " << path << " " << std::endl;
return FAIL;
}
return SUCCESS;
}
bool test_setup(ENGINE_HANDLE *h, ENGINE_HANDLE_V1 *h1) {
wait_for_warmup_complete(h, h1);
check(set_vbucket_state(h, h1, 0, vbucket_state_active),
"Failed to set VB0 state.");
wait_for_stat_change(h, h1, "ep_vb_snapshot_total", 0);
// warmup is complete, notify ep engine that it must now enable
// data traffic
protocol_binary_request_header *pkt = createPacket(PROTOCOL_BINARY_CMD_ENABLE_TRAFFIC);
check(h1->unknown_command(h, NULL, pkt, add_response) == ENGINE_SUCCESS,
"Failed to enable data traffic");
free(pkt);
return true;
}
bool teardown(ENGINE_HANDLE *h, ENGINE_HANDLE_V1 *h1) {
(void)h; (void)h1;
vals.clear();
return true;
}
bool teardown_v2(engine_test_t* test) {
(void)test;
vals.clear();
return true;
}
std::string get_dbname(const char* test_cfg) {
std::string dbname;
if (!test_cfg) {
dbname.assign(dbname_env);
return dbname;
}
const char *nm = strstr(test_cfg, "dbname=");
if (nm == NULL) {
dbname.assign(dbname_env);
} else {
dbname.assign(nm + 7);
std::string::size_type end = dbname.find(';');
if (end != dbname.npos) {
dbname = dbname.substr(0, end);
}
}
return dbname;
}
enum test_result prepare(engine_test_t *test) {
#ifdef __sun
// Some of the tests doesn't work on Solaris.. Don't know why yet..
if (strstr(test->name, "concurrent set") != NULL ||
strstr(test->name, "retain rowid over a soft delete") != NULL)
{
return SKIPPED;
}
#endif
std::string dbname = get_dbname(test->cfg);
/* Remove if the same DB directory already exists */
rmdb(dbname.c_str());
mkdir(dbname.c_str(), 0777);
return SUCCESS;
}
void cleanup(engine_test_t *test, enum test_result result) {
(void)result;
// Nuke the database files we created
std::string dbname = get_dbname(test->cfg);
/* Remove only the db file this test created */
rmdb(dbname.c_str());
}
// Array of testcases to return back to engine_testapp.
static engine_test_t *testcases;
// Should only one test be run, and if so which number? If -1 then all tests
// are run.
static int oneTestIdx;
struct test_harness testHarness;
extern BaseTestCase testsuite_testcases[];
// Examines the list of tests provided by the specific testsuite
// via the testsuite_testcases[] array, populates `testcases` and returns it.
MEMCACHED_PUBLIC_API
engine_test_t* get_tests(void) {
// Calculate the size of the tests..
int num = 0;
while (testsuite_testcases[num].getName() != NULL) {
++num;
}
oneTestIdx = -1;
char *testNum = getenv("EP_TEST_NUM");
if (testNum) {
sscanf(testNum, "%d", &oneTestIdx);
if (oneTestIdx < 0 || oneTestIdx > num) {
oneTestIdx = -1;
}
}
dbname_env = getenv("EP_TEST_DIR");
if (!dbname_env) {
dbname_env = default_dbname;
}
if (oneTestIdx == -1) {
testcases = static_cast<engine_test_t*>(calloc(num + 1, sizeof(engine_test_t)));
int ii = 0;
for (int jj = 0; jj < num; ++jj) {
engine_test_t *r = testsuite_testcases[jj].getTest();
if (r != 0) {
testcases[ii++] = *r;
}
}
} else {
testcases = static_cast<engine_test_t*>(calloc(1 + 1, sizeof(engine_test_t)));
engine_test_t *r = testsuite_testcases[oneTestIdx].getTest();
if (r != 0) {
testcases[0] = *r;
}
}
return testcases;
}
MEMCACHED_PUBLIC_API
bool setup_suite(struct test_harness *th) {
testHarness = *th;
return true;
}
MEMCACHED_PUBLIC_API
bool teardown_suite() {
for (int i = 0; testcases[i].name != nullptr; i++) {
free((char*)testcases[i].name);
free((char*)testcases[i].cfg);
}
free(testcases);
testcases = NULL;
return true;
}
/*
* Create n_buckets and return how many were actually created.
*/
int create_buckets(const char* cfg, int n_buckets, std::vector<BucketHolder> &buckets) {
std::string dbname = get_dbname(cfg);
for (int ii = 0; ii < n_buckets; ii++) {
std::stringstream config, dbpath;
dbpath << dbname.c_str() << ii;
std::string str_cfg(cfg);
/* Find the position of "dbname=" in str_cfg */
size_t pos = str_cfg.find("dbname=");
if (pos != std::string::npos) {
/* Move till end of the dbname */
size_t new_pos = str_cfg.find(';', pos);
str_cfg.insert(new_pos, std::to_string(ii));
config << str_cfg;
} else {
config << str_cfg << "dbname=" << dbpath.str();
}
rmdb(dbpath.str().c_str());
ENGINE_HANDLE_V1* handle = testHarness.create_bucket(true, config.str().c_str());
if (handle) {
buckets.push_back(BucketHolder((ENGINE_HANDLE*)handle, handle, dbpath.str()));
} else {
return ii;
}
}
return n_buckets;
}
void destroy_buckets(std::vector<BucketHolder> &buckets) {
for(auto bucket : buckets) {
testHarness.destroy_bucket(bucket.h, bucket.h1, false);
rmdb(bucket.dbpath.c_str());
}
}
|
Remove check for previous vbucket states in test_setup
|
Remove check for previous vbucket states in test_setup
After warmup, we need not necessarily check that there are no
previous states in order to set the vbucket state to active.
CouchKVStore doesn't populate any vbucket states in memory but
ForestKVStore does initialize to dead state.
Change-Id: Ia55b5853f94e23cead32574475420c1562055eea
Reviewed-on: http://review.couchbase.org/56030
Tested-by: buildbot <[email protected]>
Reviewed-by: Chiyoung Seo <[email protected]>
|
C++
|
apache-2.0
|
daverigby/ep-engine,daverigby/kv_engine,hisundar/ep-engine,owendCB/ep-engine,couchbase/ep-engine,membase/ep-engine,daverigby/kv_engine,couchbase/ep-engine,daverigby/ep-engine,hisundar/ep-engine,owendCB/ep-engine,couchbase/ep-engine,daverigby/ep-engine,membase/ep-engine,membase/ep-engine,couchbase/ep-engine,daverigby/ep-engine,teligent-ru/ep-engine,owendCB/ep-engine,hisundar/ep-engine,hisundar/ep-engine,teligent-ru/ep-engine,daverigby/kv_engine,teligent-ru/ep-engine,daverigby/kv_engine,teligent-ru/ep-engine,owendCB/ep-engine,membase/ep-engine
|
590e1a4b24e00ac2a1922c0e0d7e60e0e7c9a2e4
|
tests/lac/sparse_matrices.cc
|
tests/lac/sparse_matrices.cc
|
//---------------------------- testmatrix.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000, 2002 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- testmatrix.cc ---------------------------
//TODO: [GK] Produce some useful output!
#include "testmatrix.h"
#include <base/logstream.h>
#include <lac/sparse_matrix.h>
#include <lac/sparse_matrix_ez.h>
#include <lac/vector.h>
#include <lac/solver_richardson.h>
#include <lac/precondition.h>
#include <lac/sparse_matrix_ez.templates.h>
#include <fstream>
#define PREC_CHECK(solver, method, precond) try \
{ solver.method (A, u, f, precond); } catch (...) {} \
residuals.push_back(control.last_value())
template<class MATRIX>
void
check_vmult_quadratic(std::vector<double>& residuals,
const MATRIX& A,
const char* prefix)
{
deallog.push(prefix);
Vector<double> u(A.n());
Vector<double> f(A.m());
GrowingVectorMemory<> mem;
SolverControl control(10, 1.e-13, false);
SolverRichardson<> rich(control, mem, .01);
SolverRichardson<> prich(control, mem, 1.);
PreconditionIdentity identity;
PreconditionJacobi<MATRIX> jacobi;
jacobi.initialize(A, .5);
PreconditionSOR<MATRIX> sor;
sor.initialize(A, 1.2);
PreconditionSSOR<MATRIX> ssor;
ssor.initialize(A, 1.2);
u = 0.;
f = 1.;
PREC_CHECK(rich, solve, identity);
PREC_CHECK(prich, solve, jacobi);
PREC_CHECK(prich, solve, ssor);
PREC_CHECK(prich, solve, sor);
u = 0.;
deallog << "Transpose" << std::endl;
PREC_CHECK(rich, Tsolve, identity);
PREC_CHECK(prich, Tsolve, jacobi);
PREC_CHECK(prich, Tsolve, ssor);
PREC_CHECK(prich, Tsolve, sor);
deallog.pop();
}
template <class MATRIX>
void
check_iterator (const MATRIX& A)
{
for (typename MATRIX::const_iterator i = A.begin(); i!= A.end(); ++i)
deallog << '\t' << i->row()
<< '\t' << i->column()
<< '\t' << i->index()
<< '\t' << i->value()
<< std::endl;
deallog << "Repeat row 2" << std::endl;
for (typename MATRIX::const_iterator i = A.begin(2); i!= A.end(2); ++i)
deallog << '\t' << i->row()
<< '\t' << i->column()
<< '\t' << i->index()
<< '\t' << i->value()
<< std::endl;
}
int main()
{
std::ofstream logfile("sparse_matrices.output");
logfile.setf(std::ios::fixed);
logfile.precision(2);
deallog.attach(logfile);
// Switch between regression test
// and benchmark
#ifdef DEBUG
deallog.depth_console(0);
const unsigned int size = 5;
const unsigned int row_length = 3;
#else
deallog.depth_console(1000);
deallog.log_execution_time(true);
deallog.log_time_differences(true);
const unsigned int size = 500;
const unsigned int row_length = 9;
#endif
FDMatrix testproblem (size, size);
unsigned int dim = (size-1)*(size-1);
std::vector<double> A_res;
std::vector<double> E_res;
deallog << "Structure" << std::endl;
SparsityPattern structure(dim, dim, 5);
testproblem.five_point_structure(structure);
structure.compress();
SparseMatrix<double> A(structure);
deallog << "Assemble" << std::endl;
testproblem.five_point(A, true);
check_vmult_quadratic(A_res, A, "5-SparseMatrix<double>");
SparseMatrixEZ<double> E(dim,dim,row_length,2);
deallog << "Assemble" << std::endl;
testproblem.five_point(E, true);
check_vmult_quadratic(E_res, E, "5-SparseMatrixEZ<double>");
#ifdef DEBUG
check_iterator(E);
#endif
A.clear();
deallog << "Structure" << std::endl;
structure.reinit(dim, dim, 9);
testproblem.nine_point_structure(structure);
structure.compress();
A.reinit(structure);
deallog << "Assemble" << std::endl;
testproblem.nine_point(A);
check_vmult_quadratic(A_res, A, "9-SparseMatrix<double>");
E.clear();
E.reinit(dim,dim,row_length,2);
deallog << "Assemble" << std::endl;
testproblem.nine_point(E);
check_vmult_quadratic(E_res, E, "9-SparseMatrixEZ<double>");
for (unsigned int i=0;i<A_res.size();++i)
if (std::fabs(A_res[i] - E_res[i]) > 1.e-14)
deallog << "SparseMatrix and SparseMatrixEZ differ!!!"
<< std::endl;
// dump A into a file, and re-read
// it, then check equality
std::ofstream tmp_write ("sparse_matrices.tmp");
A.block_write (tmp_write);
tmp_write.close ();
std::ifstream tmp_read ("sparse_matrices.tmp");
SparseMatrix<double> A_tmp;
A_tmp.reinit (A.get_sparsity_pattern());
A_tmp.block_read (tmp_read);
tmp_read.close ();
for (unsigned int i=0; i<A.n_nonzero_elements(); ++i)
Assert (std::fabs(A.global_entry(i) - A_tmp.global_entry(i)) <=
std::fabs(1e-14*A.global_entry(i)),
ExcInternalError());
}
|
//---------------------------- testmatrix.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000, 2002 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- testmatrix.cc ---------------------------
//TODO: [GK] Produce some useful output!
#include "testmatrix.h"
#include <base/logstream.h>
#include <lac/sparse_matrix.h>
#include <lac/sparse_matrix_ez.h>
#include <lac/vector.h>
#include <lac/solver_richardson.h>
#include <lac/precondition.h>
#include <lac/sparse_matrix_ez.templates.h>
#include <fstream>
#include <cstdio>
#define PREC_CHECK(solver, method, precond) try \
{ solver.method (A, u, f, precond); } catch (...) {} \
residuals.push_back(control.last_value())
template<class MATRIX>
void
check_vmult_quadratic(std::vector<double>& residuals,
const MATRIX& A,
const char* prefix)
{
deallog.push(prefix);
Vector<double> u(A.n());
Vector<double> f(A.m());
GrowingVectorMemory<> mem;
SolverControl control(10, 1.e-13, false);
SolverRichardson<> rich(control, mem, .01);
SolverRichardson<> prich(control, mem, 1.);
PreconditionIdentity identity;
PreconditionJacobi<MATRIX> jacobi;
jacobi.initialize(A, .5);
PreconditionSOR<MATRIX> sor;
sor.initialize(A, 1.2);
PreconditionSSOR<MATRIX> ssor;
ssor.initialize(A, 1.2);
u = 0.;
f = 1.;
PREC_CHECK(rich, solve, identity);
PREC_CHECK(prich, solve, jacobi);
PREC_CHECK(prich, solve, ssor);
PREC_CHECK(prich, solve, sor);
u = 0.;
deallog << "Transpose" << std::endl;
PREC_CHECK(rich, Tsolve, identity);
PREC_CHECK(prich, Tsolve, jacobi);
PREC_CHECK(prich, Tsolve, ssor);
PREC_CHECK(prich, Tsolve, sor);
deallog.pop();
}
template <class MATRIX>
void
check_iterator (const MATRIX& A)
{
for (typename MATRIX::const_iterator i = A.begin(); i!= A.end(); ++i)
deallog << '\t' << i->row()
<< '\t' << i->column()
<< '\t' << i->index()
<< '\t' << i->value()
<< std::endl;
deallog << "Repeat row 2" << std::endl;
for (typename MATRIX::const_iterator i = A.begin(2); i!= A.end(2); ++i)
deallog << '\t' << i->row()
<< '\t' << i->column()
<< '\t' << i->index()
<< '\t' << i->value()
<< std::endl;
}
int main()
{
std::ofstream logfile("sparse_matrices.output");
logfile.setf(std::ios::fixed);
logfile.precision(2);
deallog.attach(logfile);
// Switch between regression test
// and benchmark
#ifdef DEBUG
deallog.depth_console(0);
const unsigned int size = 5;
const unsigned int row_length = 3;
#else
deallog.depth_console(1000);
deallog.log_execution_time(true);
deallog.log_time_differences(true);
const unsigned int size = 500;
const unsigned int row_length = 9;
#endif
FDMatrix testproblem (size, size);
unsigned int dim = (size-1)*(size-1);
std::vector<double> A_res;
std::vector<double> E_res;
deallog << "Structure" << std::endl;
SparsityPattern structure(dim, dim, 5);
testproblem.five_point_structure(structure);
structure.compress();
SparseMatrix<double> A(structure);
deallog << "Assemble" << std::endl;
testproblem.five_point(A, true);
check_vmult_quadratic(A_res, A, "5-SparseMatrix<double>");
SparseMatrixEZ<double> E(dim,dim,row_length,2);
deallog << "Assemble" << std::endl;
testproblem.five_point(E, true);
check_vmult_quadratic(E_res, E, "5-SparseMatrixEZ<double>");
#ifdef DEBUG
check_iterator(E);
#endif
A.clear();
deallog << "Structure" << std::endl;
structure.reinit(dim, dim, 9);
testproblem.nine_point_structure(structure);
structure.compress();
A.reinit(structure);
deallog << "Assemble" << std::endl;
testproblem.nine_point(A);
check_vmult_quadratic(A_res, A, "9-SparseMatrix<double>");
E.clear();
E.reinit(dim,dim,row_length,2);
deallog << "Assemble" << std::endl;
testproblem.nine_point(E);
check_vmult_quadratic(E_res, E, "9-SparseMatrixEZ<double>");
for (unsigned int i=0;i<A_res.size();++i)
if (std::fabs(A_res[i] - E_res[i]) > 1.e-14)
deallog << "SparseMatrix and SparseMatrixEZ differ!!!"
<< std::endl;
// dump A into a file, and re-read
// it, then delete tmp file and
// check equality
std::ofstream tmp_write ("sparse_matrices.tmp");
A.block_write (tmp_write);
tmp_write.close ();
std::ifstream tmp_read ("sparse_matrices.tmp");
SparseMatrix<double> A_tmp;
A_tmp.reinit (A.get_sparsity_pattern());
A_tmp.block_read (tmp_read);
tmp_read.close ();
remove ("sparse_matrices.tmp");
for (unsigned int i=0; i<A.n_nonzero_elements(); ++i)
Assert (std::fabs(A.global_entry(i) - A_tmp.global_entry(i)) <=
std::fabs(1e-14*A.global_entry(i)),
ExcInternalError());
}
|
Remove tmp file again.
|
Remove tmp file again.
git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@6380 0785d39b-7218-0410-832d-ea1e28bc413d
|
C++
|
lgpl-2.1
|
kalj/dealii,danshapero/dealii,mtezzele/dealii,sriharisundar/dealii,lpolster/dealii,sairajat/dealii,angelrca/dealii,ibkim11/dealii,pesser/dealii,YongYang86/dealii,msteigemann/dealii,angelrca/dealii,kalj/dealii,rrgrove6/dealii,sriharisundar/dealii,natashasharma/dealii,shakirbsm/dealii,angelrca/dealii,maieneuro/dealii,adamkosik/dealii,adamkosik/dealii,pesser/dealii,spco/dealii,naliboff/dealii,spco/dealii,shakirbsm/dealii,msteigemann/dealii,EGP-CIG-REU/dealii,natashasharma/dealii,shakirbsm/dealii,sairajat/dealii,lpolster/dealii,nicolacavallini/dealii,ESeNonFossiIo/dealii,msteigemann/dealii,gpitton/dealii,mac-a/dealii,johntfoster/dealii,rrgrove6/dealii,pesser/dealii,naliboff/dealii,spco/dealii,jperryhouts/dealii,pesser/dealii,flow123d/dealii,nicolacavallini/dealii,sriharisundar/dealii,ESeNonFossiIo/dealii,johntfoster/dealii,msteigemann/dealii,Arezou-gh/dealii,mac-a/dealii,flow123d/dealii,danshapero/dealii,rrgrove6/dealii,nicolacavallini/dealii,sairajat/dealii,maieneuro/dealii,Arezou-gh/dealii,mtezzele/dealii,rrgrove6/dealii,ESeNonFossiIo/dealii,ibkim11/dealii,lpolster/dealii,naliboff/dealii,sairajat/dealii,ibkim11/dealii,andreamola/dealii,natashasharma/dealii,ibkim11/dealii,Arezou-gh/dealii,kalj/dealii,angelrca/dealii,shakirbsm/dealii,adamkosik/dealii,shakirbsm/dealii,lue/dealii,maieneuro/dealii,jperryhouts/dealii,sairajat/dealii,johntfoster/dealii,naliboff/dealii,mtezzele/dealii,JaeryunYim/dealii,Arezou-gh/dealii,andreamola/dealii,lue/dealii,danshapero/dealii,ESeNonFossiIo/dealii,JaeryunYim/dealii,angelrca/dealii,lpolster/dealii,natashasharma/dealii,JaeryunYim/dealii,EGP-CIG-REU/dealii,ibkim11/dealii,andreamola/dealii,lue/dealii,nicolacavallini/dealii,shakirbsm/dealii,EGP-CIG-REU/dealii,adamkosik/dealii,nicolacavallini/dealii,YongYang86/dealii,rrgrove6/dealii,natashasharma/dealii,msteigemann/dealii,kalj/dealii,flow123d/dealii,andreamola/dealii,rrgrove6/dealii,mac-a/dealii,gpitton/dealii,sriharisundar/dealii,johntfoster/dealii,EGP-CIG-REU/dealii,flow123d/dealii,lpolster/dealii,ibkim11/dealii,Arezou-gh/dealii,nicolacavallini/dealii,angelrca/dealii,pesser/dealii,danshapero/dealii,sriharisundar/dealii,spco/dealii,gpitton/dealii,mac-a/dealii,flow123d/dealii,ESeNonFossiIo/dealii,spco/dealii,JaeryunYim/dealii,Arezou-gh/dealii,johntfoster/dealii,gpitton/dealii,kalj/dealii,jperryhouts/dealii,maieneuro/dealii,nicolacavallini/dealii,jperryhouts/dealii,spco/dealii,JaeryunYim/dealii,EGP-CIG-REU/dealii,natashasharma/dealii,adamkosik/dealii,jperryhouts/dealii,mtezzele/dealii,mac-a/dealii,lpolster/dealii,natashasharma/dealii,flow123d/dealii,YongYang86/dealii,msteigemann/dealii,flow123d/dealii,mtezzele/dealii,YongYang86/dealii,kalj/dealii,ibkim11/dealii,maieneuro/dealii,danshapero/dealii,mtezzele/dealii,gpitton/dealii,andreamola/dealii,johntfoster/dealii,jperryhouts/dealii,sairajat/dealii,jperryhouts/dealii,andreamola/dealii,lue/dealii,naliboff/dealii,shakirbsm/dealii,sriharisundar/dealii,EGP-CIG-REU/dealii,spco/dealii,YongYang86/dealii,lue/dealii,ESeNonFossiIo/dealii,danshapero/dealii,kalj/dealii,sriharisundar/dealii,pesser/dealii,maieneuro/dealii,andreamola/dealii,lue/dealii,Arezou-gh/dealii,lpolster/dealii,YongYang86/dealii,ESeNonFossiIo/dealii,msteigemann/dealii,adamkosik/dealii,JaeryunYim/dealii,YongYang86/dealii,angelrca/dealii,maieneuro/dealii,mtezzele/dealii,pesser/dealii,johntfoster/dealii,sairajat/dealii,naliboff/dealii,lue/dealii,rrgrove6/dealii,gpitton/dealii,mac-a/dealii,danshapero/dealii,gpitton/dealii,mac-a/dealii,JaeryunYim/dealii,EGP-CIG-REU/dealii,naliboff/dealii,adamkosik/dealii
|
d796c7da23ceff0338c22636af7e4bc232726861
|
groups/bsl/bsls/bsls_atomicoperations_x64_all_gcc.t.cpp
|
groups/bsl/bsls/bsls_atomicoperations_x64_all_gcc.t.cpp
|
// bsls_atomicoperations_x64_all_gcc.t.cpp -*-C++-*-
#include <bsls_atomicoperations_x64_all_gcc.h>
#include <cstdlib>
using namespace BloombergLP;
using namespace std;
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
switch (test) { case 0:
return 0;
default:
return -1;
}
}
// ----------------------------------------------------------------------------
// Copyright (C) 2013 Bloomberg L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
|
// bsls_atomicoperations_x64_all_gcc.t.cpp -*-C++-*-
#include <bsls_atomicoperations_x64_all_gcc.h>
// For thread support
#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h>
typedef HANDLE thread_t;
#else
#include <pthread.h>
#include <unistd.h>
typedef pthread_t thread_t;
#endif
// For timer support
#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <sys/timeb.h> // ftime(struct timeb *)
#else
#include <sys/time.h>
#endif
#include <cstdlib>
#include <iostream>
using namespace BloombergLP;
using namespace std;
typedef void *(*thread_func)(void *arg);
typedef bsls::Atomic_TypeTraits<bsls::AtomicOperations_X64_ALL_GCC>::Int
atomic_int;
struct thread_args
{
atomic_int *d_obj_p;
bsls::Types::Int64 d_iterations;
bsls::Types::Int64 d_runtimeMs;
};
bsls::Types::Int64 getTimerMs() {
#if defined(BSLS_PLATFORM_OS_UNIX)
timeval native;
gettimeofday(&native, 0);
return ((bsls::Types::Int64) native.tv_sec * 1000 +
native.tv_usec / 1000);
#elif defined(BSLS_PLATFORM_OS_WINDOWS)
timeb t;
::ftime(&t);
return = static_cast<bsls::Types::Int64>(t.time) * 1000 + t.millitm;
#else
#error "Don't know how to get nanosecond time for this platform"
#endif
}
thread_t createThread(thread_func func, void *arg)
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
return CreateThread(0, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, 0);
#else
thread_t thr;
pthread_create(&thr, 0, func, arg);
return thr;
#endif
}
void joinThread(thread_t thr)
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
WaitForSingleObject(thr, INFINITE);
CloseHandle(thr);
#else
pthread_join(thr, 0);
#endif
}
struct atomic_get_mfence
{
int operator()(atomic_int * obj)
{
int ret;
asm volatile (
" mfence \n\t"
" movl %[obj], %[ret] \n\t"
: [ret] "=r" (ret)
: [obj] "m" (*obj)
: "memory");
return ret;
}
};
struct atomic_get_free
{
int operator()(const atomic_int * obj)
{
int ret;
asm volatile (
" movl %[obj], %[ret] \n\t"
: [ret] "=r" (ret)
: [obj] "m" (*obj)
: "memory");
return ret;
}
};
struct atomic_set_mfence
{
void operator()(atomic_int * obj, int value)
{
asm volatile (
" movl %[val], %[obj] \n\t"
" mfence \n\t"
: [obj] "=m" (*obj)
: [val] "r" (value)
: "memory");
}
};
struct atomic_set_lock
{
void operator()(atomic_int * obj, int value)
{
asm volatile (
" movl %[val], %[obj] \n\t"
" lock addq $0, 0(%%rsp) \n\t"
: [obj] "=m" (*obj)
: [val] "r" (value)
: "memory", "cc");
}
};
struct atomic_set_xchg
{
void operator()(atomic_int * obj, int value)
{
asm volatile (
" xchg %[obj], %[val] \n\t"
: [obj] "=m" (*obj)
: [val] "r" (value)
: "memory");
}
};
template <typename AtomicGet>
void * test_atomics_get_thread(void * args)
{
thread_args * thr_args = reinterpret_cast<thread_args *>(args);
atomic_int *obj = thr_args->d_obj_p;
AtomicGet get_fun;
bsls::Types::Int64 i;
bsls::Types::Int64 start = getTimerMs();
for (i = 0; get_fun(obj) != -1; ++i)
;
thr_args->d_runtimeMs = getTimerMs() - start;
thr_args->d_iterations = i;
return 0;
}
template <typename AtomicGet>
void * test_atomics_set_thread(void * args)
{
thread_args * thr_args = reinterpret_cast<thread_args *>(args);
atomic_int *obj = thr_args->d_obj_p;
AtomicGet set_fun;
bsls::Types::Int64 start = getTimerMs();
for (bsls::Types::Int64 i = thr_args->d_iterations; i > 0; --i)
set_fun(obj, (int)i);
// signal finish
set_fun(obj, -1);
thr_args->d_runtimeMs = getTimerMs() - start;
return 0;
}
template <typename AtomicGet, typename AtomicSet>
void test_atomics(bsls::Types::Int64 iterations) {
enum {
NUM_READERS = 3
};
thread_t readers[NUM_READERS];
thread_args readerArgs[NUM_READERS];
thread_args args;
args.d_obj_p = new atomic_int;
args.d_iterations = iterations;
for (int i = 0 ; i < NUM_READERS; ++i) {
readerArgs[i] = args;
readers[i] = createThread(&test_atomics_get_thread<AtomicGet>,
&readerArgs[i]);
}
thread_t writer;
writer = createThread(&test_atomics_set_thread<AtomicSet>, &args);
for (int i = 0; i < NUM_READERS; ++i) {
joinThread(readers[i]);
}
joinThread(writer);
bsls::Types::Int64 totalReadIter = 0, totalReadTime = 0;
for (int i = 0; i < NUM_READERS; ++i) {
totalReadIter += readerArgs[i].d_iterations;
totalReadTime += readerArgs[i].d_runtimeMs;
}
static const double MS_PER_SEC = 1000;
double readPerSec = (double)totalReadIter / totalReadTime * MS_PER_SEC;
double writePerSec = (double)iterations / args.d_runtimeMs * MS_PER_SEC;
cout << " " << readPerSec << " / " << writePerSec << endl;
delete args.d_obj_p;
}
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
switch (test) { case 0:
return 0;
case -1: {
////////////////////////////////////////////
// Benchmark test
//
// Time get/set operations for several possible implementations
// of get and set. To simulate the typical reader/writer
// configuration, run 1 "setter" thread and 3 "getter" threads.
// The "setter" thread will run a fixed number of iterations and
// the "getter" threads will run until they see a value indicating
// the setter has stopped.
///////////////////////////////////////////
enum {
NUM_ITER = 20 * 1000 * 1000
};
cout << "get mfence / set mfence: ";
test_atomics<atomic_get_mfence, atomic_set_mfence>(NUM_ITER);
cout << "get free / set mfence: ";
test_atomics<atomic_get_free, atomic_set_mfence>(NUM_ITER);
cout << "get free / set lock: ";
test_atomics<atomic_get_free, atomic_set_lock>(NUM_ITER);
cout << "get free / set xchg: ";
test_atomics<atomic_get_free, atomic_set_xchg>(NUM_ITER);
} break;
default:
return -1;
}
}
// ----------------------------------------------------------------------------
// Copyright (C) 2013 Bloomberg L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
|
Add benchmark test
|
Add benchmark test
|
C++
|
apache-2.0
|
mversche/bde,mversche/bde,idispatch/bde,dbremner/bde,bloomberg/bde-allocator-benchmarks,saxena84/bde,che2/bde,gbleaney/Allocator-Benchmarks,idispatch/bde,gbleaney/Allocator-Benchmarks,che2/bde,mversche/bde,saxena84/bde,bowlofstew/bde,apaprocki/bde,bloomberg/bde,apaprocki/bde,dbremner/bde,apaprocki/bde,minhlongdo/bde,jmptrader/bde,bloomberg/bde,jmptrader/bde,minhlongdo/bde,dharesign/bde,minhlongdo/bde,bloomberg/bde-allocator-benchmarks,bloomberg/bde-allocator-benchmarks,dharesign/bde,osubboo/bde,apaprocki/bde,bloomberg/bde-allocator-benchmarks,bloomberg/bde,frutiger/bde,RMGiroux/bde-allocator-benchmarks,jmptrader/bde,RMGiroux/bde-allocator-benchmarks,idispatch/bde,che2/bde,apaprocki/bde,minhlongdo/bde,RMGiroux/bde-allocator-benchmarks,abeels/bde,osubboo/bde,abeels/bde,che2/bde,dbremner/bde,bowlofstew/bde,bloomberg/bde,osubboo/bde,saxena84/bde,mversche/bde,saxena84/bde,idispatch/bde,dharesign/bde,abeels/bde,dbremner/bde,bloomberg/bde-allocator-benchmarks,RMGiroux/bde-allocator-benchmarks,frutiger/bde,abeels/bde,jmptrader/bde,frutiger/bde,frutiger/bde,osubboo/bde,abeels/bde,bowlofstew/bde,bloomberg/bde,gbleaney/Allocator-Benchmarks,dharesign/bde,abeels/bde,bowlofstew/bde,gbleaney/Allocator-Benchmarks,RMGiroux/bde-allocator-benchmarks
|
c0fb1470966103b308d4a346c0022f7545fd7e37
|
editeng/inc/editeng/AccessibleContextBase.hxx
|
editeng/inc/editeng/AccessibleContextBase.hxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_CONTEXT_BASE_HXX
#define _SVX_ACCESSIBILITY_ACCESSIBLE_CONTEXT_BASE_HXX
#include <com/sun/star/accessibility/XAccessible.hpp>
#include <com/sun/star/accessibility/XAccessibleContext.hpp>
#include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#include <com/sun/star/accessibility/XAccessibleStateSet.hpp>
#include <com/sun/star/accessibility/XAccessibleRelationSet.hpp>
#include <com/sun/star/accessibility/AccessibleEventObject.hpp>
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#include <com/sun/star/accessibility/IllegalAccessibleComponentStateException.hpp>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/lang/XComponent.hpp>
#include <cppuhelper/weak.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <osl/mutex.hxx>
#include <cppuhelper/compbase4.hxx>
#include <editeng/editengdllapi.h>
namespace accessibility {
struct MutexOwner {mutable ::osl::Mutex maMutex;};
/** @descr
This base class provides an implementation of the
<type>AccessibleContext</type> service. Appart from the
<type>XXAccessible<type> and <type>XAccessibleContextContext</type>
interfaces it supports the <type>XServiceInfo</type> interface.
*/
class EDITENG_DLLPUBLIC AccessibleContextBase
: public MutexOwner,
public cppu::WeakComponentImplHelper4<
::com::sun::star::accessibility::XAccessible,
::com::sun::star::accessibility::XAccessibleContext,
::com::sun::star::accessibility::XAccessibleEventBroadcaster,
::com::sun::star::lang::XServiceInfo
>
{
public:
//===== internal ========================================================
/** The origin of the accessible name or description.
*/
enum StringOrigin {
ManuallySet,
FromShape,
AutomaticallyCreated,
NotSet
};
AccessibleContextBase (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent,
const sal_Int16 aRole);
virtual ~AccessibleContextBase (void);
/** Call all accessiblity event listeners to inform them about the
specified event.
@param aEventId
Id of the event type.
@param rNewValue
New value of the modified attribute. Pass empty structure if
not applicable.
@param rOldValue
Old value of the modified attribute. Pass empty structure if
not applicable.
*/
void CommitChange (sal_Int16 aEventId,
const ::com::sun::star::uno::Any& rNewValue,
const ::com::sun::star::uno::Any& rOldValue);
/** Set a new description and, provided that the new name differs from
the old one, broadcast an accessibility event.
@param rsDescription
The new description.
@param eDescriptionOrigin
The origin of the description. This is used to determine
whether the given description overrules the existing one. An
origin with a lower numerical value overrides one with a higher
value.
*/
void SetAccessibleDescription (
const ::rtl::OUString& rsDescription,
StringOrigin eDescriptionOrigin)
throw (::com::sun::star::uno::RuntimeException);
/** Set a new description and, provided that the new name differs from
the old one, broadcast an accessibility event.
@param rsName
The new name.
@param eNameOrigin
The origin of the name. This is used to determine whether the
given name overrules the existing one. An origin with a lower
numerical value overrides one with a higher value.
*/
void SetAccessibleName (
const ::rtl::OUString& rsName,
StringOrigin eNameOrigin)
throw (::com::sun::star::uno::RuntimeException);
/** Set the specified state (turn it on) and send events to all
listeners to inform them of the change.
@param aState
The state to turn on.
@return
If the specified state changed its value due to this call
<TRUE/> is returned, otherwise <FALSE/>.
*/
virtual sal_Bool SetState (sal_Int16 aState);
/** Reset the specified state (turn it off) and send events to all
listeners to inform them of the change.
@param aState
The state to turn off.
@return
If the specified state changed its value due to this call
<TRUE/> is returned, otherwise <FALSE/>.
*/
virtual sal_Bool ResetState (sal_Int16 aState);
/** Return the state of the specified state.
@param aState
The state for which to return its value.
@return
A value of <TRUE/> indicates that the state is set. A <FALSE/>
value indicates an unset state.
*/
sal_Bool GetState (sal_Int16 aState);
/** Replace the current relation set with the specified one. Send
events for relations that are not in both sets.
@param rRelationSet
The new relation set that replaces the old one.
*/
virtual void SetRelationSet (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleRelationSet>& rxRelationSet)
throw (::com::sun::star::uno::RuntimeException);
//===== XAccessible =====================================================
/// Return the XAccessibleContext.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleContext> SAL_CALL
getAccessibleContext (void) throw (::com::sun::star::uno::RuntimeException);
//===== XAccessibleContext ==============================================
/// Return the number of currently visible children.
virtual sal_Int32 SAL_CALL
getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException);
/// Return the specified child or throw exception.
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleChild (sal_Int32 nIndex)
throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
/// Return a reference to the parent.
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleParent (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return this objects index among the parents children.
virtual sal_Int32 SAL_CALL
getAccessibleIndexInParent (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return this object's role.
virtual sal_Int16 SAL_CALL
getAccessibleRole (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return this object's description.
virtual ::rtl::OUString SAL_CALL
getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current name.
virtual ::rtl::OUString SAL_CALL
getAccessibleName (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return NULL to indicate that an empty relation set.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL
getAccessibleRelationSet (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the set of current states.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
getAccessibleStateSet (void)
throw (::com::sun::star::uno::RuntimeException);
/** Return the parents locale or throw exception if this object has no
parent yet/anymore.
*/
virtual ::com::sun::star::lang::Locale SAL_CALL
getLocale (void)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::accessibility::IllegalAccessibleComponentStateException);
//===== XComponent ========================================================
using WeakComponentImplHelperBase::addEventListener;
using WeakComponentImplHelperBase::removeEventListener;
//===== XAccessibleEventBroadcaster ========================================
virtual void SAL_CALL
addEventListener (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleEventListener >& xListener)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
removeEventListener (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleEventListener >& xListener)
throw (::com::sun::star::uno::RuntimeException);
//===== XServiceInfo ====================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
/** Return whether the specified service is supported by this class.
*/
virtual sal_Bool SAL_CALL
supportsService (const ::rtl::OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a list of all supported services. In this case that is just
the AccessibleContext service.
*/
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException);
//===== XTypeProvider ===================================================
/** Returns a sequence of all supported interfaces.
*/
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> SAL_CALL
getTypes (void)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a implementation id.
*/
virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
getImplementationId (void)
throw (::com::sun::star::uno::RuntimeException);
protected:
/** The state set.
*/
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet> mxStateSet;
/** The relation set. Relations can be set or removed by calling the
<member>AddRelation</member> and <member>RemoveRelation</member> methods.
*/
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleRelationSet> mxRelationSet;
// This method is called from the component helper base class while disposing.
virtual void SAL_CALL disposing (void);
/** Create the accessible object's name. This method may be called more
than once for a single object.
@return
The returned string is a unique (among the accessible object's
siblings) name.
*/
virtual ::rtl::OUString CreateAccessibleName (void)
throw (::com::sun::star::uno::RuntimeException);
/** Create the accessible object's descriptive string. May be called
more than once.
@return
Descriptive string. Not necessarily unique.
*/
virtual ::rtl::OUString
CreateAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException);
void FireEvent (const ::com::sun::star::accessibility::AccessibleEventObject& aEvent);
/** Check whether or not the object has been disposed (or is in the
state of beeing disposed). If that is the case then
DisposedException is thrown to inform the (indirect) caller of the
foul deed.
*/
void ThrowIfDisposed (void)
throw (::com::sun::star::lang::DisposedException);
/** Check whether or not the object has been disposed (or is in the
state of beeing disposed).
@return TRUE, if the object is disposed or in the course
of being disposed. Otherwise, FALSE is returned.
*/
sal_Bool IsDisposed (void);
/** sets the role as returned by XaccessibleContext::getAccessibleRole
<p>Caution: This is only to be used in the construction phase (means within
the ctor or late ctor), <em>never</em> when the object is still alive and part
of an Accessibility hierarchy.</p>
*/
void SetAccessibleRole( sal_Int16 _nRole );
private:
/// Reference to the parent object.
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> mxParent;
/** Description of this object. This is not a constant because it can
be set from the outside. Furthermore, it changes according the the
draw page's display mode.
*/
::rtl::OUString msDescription;
/** The origin of the description is used to determine whether new
descriptions given to the SetAccessibleDescription is ignored or
whether that replaces the old value in msDescription.
*/
StringOrigin meDescriptionOrigin;
/** Name of this object. It changes according the the draw page's
display mode.
*/
::rtl::OUString msName;
/** The origin of the name is used to determine whether new
name given to the SetAccessibleName is ignored or
whether that replaces the old value in msName.
*/
StringOrigin meNameOrigin;
/** client id in the AccessibleEventNotifier queue
*/
sal_uInt32 mnClientId;
/** This is the role of this object.
*/
sal_Int16 maRole;
};
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_CONTEXT_BASE_HXX
#define _SVX_ACCESSIBILITY_ACCESSIBLE_CONTEXT_BASE_HXX
#include <com/sun/star/accessibility/XAccessible.hpp>
#include <com/sun/star/accessibility/XAccessibleContext.hpp>
#include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#include <com/sun/star/accessibility/XAccessibleStateSet.hpp>
#include <com/sun/star/accessibility/XAccessibleRelationSet.hpp>
#include <com/sun/star/accessibility/AccessibleEventObject.hpp>
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#include <com/sun/star/accessibility/IllegalAccessibleComponentStateException.hpp>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/lang/XComponent.hpp>
#include <cppuhelper/weak.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <osl/mutex.hxx>
#include <cppuhelper/compbase4.hxx>
#include <editeng/editengdllapi.h>
namespace accessibility {
struct MutexOwner {mutable ::osl::Mutex maMutex;};
/** @descr
This base class provides an implementation of the
<type>AccessibleContext</type> service. Appart from the
<type>XXAccessible<type> and <type>XAccessibleContextContext</type>
interfaces it supports the <type>XServiceInfo</type> interface.
*/
class EDITENG_DLLPUBLIC AccessibleContextBase
: public MutexOwner,
public cppu::PartialWeakComponentImplHelper4<
::com::sun::star::accessibility::XAccessible,
::com::sun::star::accessibility::XAccessibleContext,
::com::sun::star::accessibility::XAccessibleEventBroadcaster,
::com::sun::star::lang::XServiceInfo
>
{
public:
//===== internal ========================================================
/** The origin of the accessible name or description.
*/
enum StringOrigin {
ManuallySet,
FromShape,
AutomaticallyCreated,
NotSet
};
AccessibleContextBase (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent,
const sal_Int16 aRole);
virtual ~AccessibleContextBase (void);
/** Call all accessiblity event listeners to inform them about the
specified event.
@param aEventId
Id of the event type.
@param rNewValue
New value of the modified attribute. Pass empty structure if
not applicable.
@param rOldValue
Old value of the modified attribute. Pass empty structure if
not applicable.
*/
void CommitChange (sal_Int16 aEventId,
const ::com::sun::star::uno::Any& rNewValue,
const ::com::sun::star::uno::Any& rOldValue);
/** Set a new description and, provided that the new name differs from
the old one, broadcast an accessibility event.
@param rsDescription
The new description.
@param eDescriptionOrigin
The origin of the description. This is used to determine
whether the given description overrules the existing one. An
origin with a lower numerical value overrides one with a higher
value.
*/
void SetAccessibleDescription (
const ::rtl::OUString& rsDescription,
StringOrigin eDescriptionOrigin)
throw (::com::sun::star::uno::RuntimeException);
/** Set a new description and, provided that the new name differs from
the old one, broadcast an accessibility event.
@param rsName
The new name.
@param eNameOrigin
The origin of the name. This is used to determine whether the
given name overrules the existing one. An origin with a lower
numerical value overrides one with a higher value.
*/
void SetAccessibleName (
const ::rtl::OUString& rsName,
StringOrigin eNameOrigin)
throw (::com::sun::star::uno::RuntimeException);
/** Set the specified state (turn it on) and send events to all
listeners to inform them of the change.
@param aState
The state to turn on.
@return
If the specified state changed its value due to this call
<TRUE/> is returned, otherwise <FALSE/>.
*/
virtual sal_Bool SetState (sal_Int16 aState);
/** Reset the specified state (turn it off) and send events to all
listeners to inform them of the change.
@param aState
The state to turn off.
@return
If the specified state changed its value due to this call
<TRUE/> is returned, otherwise <FALSE/>.
*/
virtual sal_Bool ResetState (sal_Int16 aState);
/** Return the state of the specified state.
@param aState
The state for which to return its value.
@return
A value of <TRUE/> indicates that the state is set. A <FALSE/>
value indicates an unset state.
*/
sal_Bool GetState (sal_Int16 aState);
/** Replace the current relation set with the specified one. Send
events for relations that are not in both sets.
@param rRelationSet
The new relation set that replaces the old one.
*/
virtual void SetRelationSet (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleRelationSet>& rxRelationSet)
throw (::com::sun::star::uno::RuntimeException);
//===== XAccessible =====================================================
/// Return the XAccessibleContext.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleContext> SAL_CALL
getAccessibleContext (void) throw (::com::sun::star::uno::RuntimeException);
//===== XAccessibleContext ==============================================
/// Return the number of currently visible children.
virtual sal_Int32 SAL_CALL
getAccessibleChildCount (void) throw (::com::sun::star::uno::RuntimeException);
/// Return the specified child or throw exception.
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleChild (sal_Int32 nIndex)
throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
/// Return a reference to the parent.
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
getAccessibleParent (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return this objects index among the parents children.
virtual sal_Int32 SAL_CALL
getAccessibleIndexInParent (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return this object's role.
virtual sal_Int16 SAL_CALL
getAccessibleRole (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return this object's description.
virtual ::rtl::OUString SAL_CALL
getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the object's current name.
virtual ::rtl::OUString SAL_CALL
getAccessibleName (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return NULL to indicate that an empty relation set.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL
getAccessibleRelationSet (void)
throw (::com::sun::star::uno::RuntimeException);
/// Return the set of current states.
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
getAccessibleStateSet (void)
throw (::com::sun::star::uno::RuntimeException);
/** Return the parents locale or throw exception if this object has no
parent yet/anymore.
*/
virtual ::com::sun::star::lang::Locale SAL_CALL
getLocale (void)
throw (::com::sun::star::uno::RuntimeException,
::com::sun::star::accessibility::IllegalAccessibleComponentStateException);
//===== XComponent ========================================================
using WeakComponentImplHelperBase::addEventListener;
using WeakComponentImplHelperBase::removeEventListener;
//===== XAccessibleEventBroadcaster ========================================
virtual void SAL_CALL
addEventListener (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleEventListener >& xListener)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
removeEventListener (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleEventListener >& xListener)
throw (::com::sun::star::uno::RuntimeException);
//===== XServiceInfo ====================================================
/** Returns an identifier for the implementation of this object.
*/
virtual ::rtl::OUString SAL_CALL
getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException);
/** Return whether the specified service is supported by this class.
*/
virtual sal_Bool SAL_CALL
supportsService (const ::rtl::OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a list of all supported services. In this case that is just
the AccessibleContext service.
*/
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException);
//===== XTypeProvider ===================================================
/** Returns a sequence of all supported interfaces.
*/
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> SAL_CALL
getTypes (void)
throw (::com::sun::star::uno::RuntimeException);
/** Returns a implementation id.
*/
virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
getImplementationId (void)
throw (::com::sun::star::uno::RuntimeException);
protected:
/** The state set.
*/
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleStateSet> mxStateSet;
/** The relation set. Relations can be set or removed by calling the
<member>AddRelation</member> and <member>RemoveRelation</member> methods.
*/
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessibleRelationSet> mxRelationSet;
// This method is called from the component helper base class while disposing.
virtual void SAL_CALL disposing (void);
/** Create the accessible object's name. This method may be called more
than once for a single object.
@return
The returned string is a unique (among the accessible object's
siblings) name.
*/
virtual ::rtl::OUString CreateAccessibleName (void)
throw (::com::sun::star::uno::RuntimeException);
/** Create the accessible object's descriptive string. May be called
more than once.
@return
Descriptive string. Not necessarily unique.
*/
virtual ::rtl::OUString
CreateAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException);
void FireEvent (const ::com::sun::star::accessibility::AccessibleEventObject& aEvent);
/** Check whether or not the object has been disposed (or is in the
state of beeing disposed). If that is the case then
DisposedException is thrown to inform the (indirect) caller of the
foul deed.
*/
void ThrowIfDisposed (void)
throw (::com::sun::star::lang::DisposedException);
/** Check whether or not the object has been disposed (or is in the
state of beeing disposed).
@return TRUE, if the object is disposed or in the course
of being disposed. Otherwise, FALSE is returned.
*/
sal_Bool IsDisposed (void);
/** sets the role as returned by XaccessibleContext::getAccessibleRole
<p>Caution: This is only to be used in the construction phase (means within
the ctor or late ctor), <em>never</em> when the object is still alive and part
of an Accessibility hierarchy.</p>
*/
void SetAccessibleRole( sal_Int16 _nRole );
private:
/// Reference to the parent object.
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> mxParent;
/** Description of this object. This is not a constant because it can
be set from the outside. Furthermore, it changes according the the
draw page's display mode.
*/
::rtl::OUString msDescription;
/** The origin of the description is used to determine whether new
descriptions given to the SetAccessibleDescription is ignored or
whether that replaces the old value in msDescription.
*/
StringOrigin meDescriptionOrigin;
/** Name of this object. It changes according the the draw page's
display mode.
*/
::rtl::OUString msName;
/** The origin of the name is used to determine whether new
name given to the SetAccessibleName is ignored or
whether that replaces the old value in msName.
*/
StringOrigin meNameOrigin;
/** client id in the AccessibleEventNotifier queue
*/
sal_uInt32 mnClientId;
/** This is the role of this object.
*/
sal_Int16 maRole;
};
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
add PartialWeakComponentImplHelperX for overloaded-virtual
|
add PartialWeakComponentImplHelperX for overloaded-virtual
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
c6b89667cdf92e8936f389543fe12ae021d5b41f
|
kmail/kmmainwin.cpp
|
kmail/kmmainwin.cpp
|
#include "kmmainwin.h"
#include "kmmainwidget.h"
#include "kstatusbar.h"
#include "messagesender.h"
#include "progressdialog.h"
#include "statusbarprogresswidget.h"
#include "accountwizard.h"
#include "broadcaststatus.h"
#include "accountmanager.h"
#include <kapplication.h>
#include <klocale.h>
#include <kedittoolbar.h>
#include <kconfig.h>
#include <kmessagebox.h>
#include <kstringhandler.h>
#include <kstandardaction.h>
#include <kdebug.h>
#include <ktip.h>
#include <kicon.h>
#include "kmmainwin.moc"
KMMainWin::KMMainWin(QWidget *)
: KXmlGuiWindow( 0 ),
mReallyClose( false )
{
setObjectName( "kmail-mainwindow#" );
// Set this to be the group leader for all subdialogs - this means
// modal subdialogs will only affect this dialog, not the other windows
setAttribute( Qt::WA_GroupLeader );
KGlobal::ref();
KAction *action = new KAction( KIcon("window-new"), i18n("New &Window"), this );
actionCollection()->addAction( "new_mail_client", action );
connect( action, SIGNAL( triggered(bool) ), SLOT( slotNewMailReader() ) );
// Reading the config has to be done before setting up the main widget,
// because that needs a correct size
resize( 700, 500 ); // The default size
applyMainWindowSettings( KMKernel::config()->group( "Main Window") );
mKMMainWidget = new KMMainWidget( this, this, actionCollection() );
setCentralWidget( mKMMainWidget );
setupStatusBar();
if ( kmkernel->xmlGuiInstance().isValid() )
setComponentData( kmkernel->xmlGuiInstance() );
setStandardToolBarMenuEnabled( true );
KStandardAction::configureToolbars( this, SLOT( slotEditToolbars() ),
actionCollection() );
KStandardAction::keyBindings( mKMMainWidget, SLOT( slotEditKeys() ),
actionCollection() );
KStandardAction::quit( this, SLOT( slotQuit() ), actionCollection() );
createGUI( "kmmainwin.rc" );
// Don't use conserveMemory() because this renders dynamic plugging
// of actions unusable!
connect( KPIM::BroadcastStatus::instance(), SIGNAL( statusMsg( const QString& ) ),
this, SLOT( displayStatusMsg(const QString&) ) );
connect( mKMMainWidget, SIGNAL( captionChangeRequest(const QString&) ),
SLOT( setCaption(const QString&) ) );
// Enable mail checks again (see destructor)
kmkernel->enableMailCheck();
if ( kmkernel->firstStart() )
AccountWizard::start( kmkernel, this );
if ( kmkernel->firstInstance() )
QTimer::singleShot( 200, this, SLOT( slotShowTipOnStart() ) );
}
KMMainWin::~KMMainWin()
{
saveMainWindowSettings( KMKernel::config()->group( "Main Window") );
KMKernel::config()->sync();
KGlobal::deref();
if ( !kmkernel->haveSystemTrayApplet() ) {
// Check if this was the last KMMainWin
uint not_withdrawn = 0;
foreach ( KMainWindow* window, KMainWindow::memberList() ) {
if ( !window->isHidden() && window->isTopLevel() &&
window != this && ::qobject_cast<KMMainWin *>( window ) )
not_withdrawn++;
}
if ( not_withdrawn == 0 ) {
kDebug(5006) <<"Closing last KMMainWin: stopping mail check";
// Running KIO jobs prevent kapp from exiting, so we need to kill them
// if they are only about checking mail (not important stuff like moving messages)
kmkernel->abortMailCheck();
kmkernel->acctMgr()->cancelMailCheck();
}
}
}
void KMMainWin::displayStatusMsg(const QString& aText)
{
if ( !statusBar() || !mLittleProgress) return;
int statusWidth = statusBar()->width() - mLittleProgress->width()
- fontMetrics().maxWidth();
QString text = fontMetrics().elidedText( ' ' + aText, Qt::ElideRight,
statusWidth );
// ### FIXME: We should disable richtext/HTML (to avoid possible denial of service attacks),
// but this code would double the size of the satus bar if the user hovers
// over an <[email protected]>-style email address :-(
// text.replace("&", "&");
// text.replace("<", "<");
// text.replace(">", ">");
statusBar()->changeItem(text, mMessageStatusId);
}
//-----------------------------------------------------------------------------
void KMMainWin::slotNewMailReader()
{
KMMainWin *d;
d = new KMMainWin();
d->show();
d->resize( d->size() );
}
void KMMainWin::slotEditToolbars()
{
saveMainWindowSettings(KMKernel::config()->group( "Main Window") );
KEditToolBar dlg(actionCollection(), this);
dlg.setResourceFile( "kmmainwin.rc" );
connect( &dlg, SIGNAL(newToolbarConfig()),
SLOT(slotUpdateToolbars()) );
dlg.exec();
}
void KMMainWin::slotUpdateToolbars()
{
// remove dynamically created actions before editing
mKMMainWidget->clearFilterActions();
mKMMainWidget->clearMessageTagActions();//OnurAdd
createGUI("kmmainwin.rc");
applyMainWindowSettings(KMKernel::config()->group( "Main Window") );
// plug dynamically created actions again
mKMMainWidget->initializeFilterActions();
mKMMainWidget->initializeMessageTagActions();
}
void KMMainWin::setupStatusBar()
{
mMessageStatusId = 1;
/* Create a progress dialog and hide it. */
mProgressDialog = new KPIM::ProgressDialog( statusBar(), this );
mProgressDialog->hide();
mLittleProgress = new StatusbarProgressWidget( mProgressDialog, statusBar() );
mLittleProgress->show();
statusBar()->insertItem( i18n("Starting...") , 1, 4 );
statusBar()->setItemAlignment( 1, Qt::AlignLeft | Qt::AlignVCenter );
statusBar()->addPermanentWidget( mKMMainWidget->vacationScriptIndicator() );
statusBar()->addPermanentWidget( mLittleProgress );
mLittleProgress->show();
}
void KMMainWin::slotQuit()
{
mReallyClose = true;
close();
}
//-----------------------------------------------------------------------------
bool KMMainWin::queryClose()
{
if ( kmkernel->shuttingDown() || kapp->sessionSaving() || mReallyClose )
return true;
return kmkernel->canQueryClose();
}
void KMMainWin::slotShowTipOnStart()
{
KTipDialog::showTip( this );
}
|
#include "kmmainwin.h"
#include "kmmainwidget.h"
#include "kstatusbar.h"
#include "messagesender.h"
#include "progressdialog.h"
#include "statusbarprogresswidget.h"
#include "accountwizard.h"
#include "broadcaststatus.h"
#include "accountmanager.h"
#include <kapplication.h>
#include <klocale.h>
#include <kedittoolbar.h>
#include <kconfig.h>
#include <kmessagebox.h>
#include <kstringhandler.h>
#include <kstandardaction.h>
#include <kdebug.h>
#include <ktip.h>
#include <kicon.h>
#include "kmmainwin.moc"
KMMainWin::KMMainWin(QWidget *)
: KXmlGuiWindow( 0 ),
mReallyClose( false )
{
setObjectName( "kmail-mainwindow#" );
// Set this to be the group leader for all subdialogs - this means
// modal subdialogs will only affect this dialog, not the other windows
setAttribute( Qt::WA_GroupLeader );
KGlobal::ref();
KAction *action = new KAction( KIcon("window-new"), i18n("New &Window"), this );
actionCollection()->addAction( "new_mail_client", action );
connect( action, SIGNAL( triggered(bool) ), SLOT( slotNewMailReader() ) );
resize( 700, 500 ); // The default size
mKMMainWidget = new KMMainWidget( this, this, actionCollection() );
setCentralWidget( mKMMainWidget );
setupStatusBar();
if ( kmkernel->xmlGuiInstance().isValid() )
setComponentData( kmkernel->xmlGuiInstance() );
setStandardToolBarMenuEnabled( true );
KStandardAction::configureToolbars( this, SLOT( slotEditToolbars() ),
actionCollection() );
KStandardAction::keyBindings( mKMMainWidget, SLOT( slotEditKeys() ),
actionCollection() );
KStandardAction::quit( this, SLOT( slotQuit() ), actionCollection() );
createGUI( "kmmainwin.rc" );
// Don't use conserveMemory() because this renders dynamic plugging
// of actions unusable!
//must be after createGUI, otherwise e.g toolbar settings are not loaded
applyMainWindowSettings( KMKernel::config()->group( "Main Window") );
connect( KPIM::BroadcastStatus::instance(), SIGNAL( statusMsg( const QString& ) ),
this, SLOT( displayStatusMsg(const QString&) ) );
connect( mKMMainWidget, SIGNAL( captionChangeRequest(const QString&) ),
SLOT( setCaption(const QString&) ) );
// Enable mail checks again (see destructor)
kmkernel->enableMailCheck();
if ( kmkernel->firstStart() )
AccountWizard::start( kmkernel, this );
if ( kmkernel->firstInstance() )
QTimer::singleShot( 200, this, SLOT( slotShowTipOnStart() ) );
}
KMMainWin::~KMMainWin()
{
saveMainWindowSettings( KMKernel::config()->group( "Main Window") );
KMKernel::config()->sync();
KGlobal::deref();
if ( !kmkernel->haveSystemTrayApplet() ) {
// Check if this was the last KMMainWin
uint not_withdrawn = 0;
foreach ( KMainWindow* window, KMainWindow::memberList() ) {
if ( !window->isHidden() && window->isTopLevel() &&
window != this && ::qobject_cast<KMMainWin *>( window ) )
not_withdrawn++;
}
if ( not_withdrawn == 0 ) {
kDebug(5006) <<"Closing last KMMainWin: stopping mail check";
// Running KIO jobs prevent kapp from exiting, so we need to kill them
// if they are only about checking mail (not important stuff like moving messages)
kmkernel->abortMailCheck();
kmkernel->acctMgr()->cancelMailCheck();
}
}
}
void KMMainWin::displayStatusMsg(const QString& aText)
{
if ( !statusBar() || !mLittleProgress) return;
int statusWidth = statusBar()->width() - mLittleProgress->width()
- fontMetrics().maxWidth();
QString text = fontMetrics().elidedText( ' ' + aText, Qt::ElideRight,
statusWidth );
// ### FIXME: We should disable richtext/HTML (to avoid possible denial of service attacks),
// but this code would double the size of the satus bar if the user hovers
// over an <[email protected]>-style email address :-(
// text.replace("&", "&");
// text.replace("<", "<");
// text.replace(">", ">");
statusBar()->changeItem(text, mMessageStatusId);
}
//-----------------------------------------------------------------------------
void KMMainWin::slotNewMailReader()
{
KMMainWin *d;
d = new KMMainWin();
d->show();
d->resize( d->size() );
}
void KMMainWin::slotEditToolbars()
{
saveMainWindowSettings(KMKernel::config()->group( "Main Window") );
KEditToolBar dlg(actionCollection(), this);
dlg.setResourceFile( "kmmainwin.rc" );
connect( &dlg, SIGNAL(newToolbarConfig()),
SLOT(slotUpdateToolbars()) );
dlg.exec();
}
void KMMainWin::slotUpdateToolbars()
{
// remove dynamically created actions before editing
mKMMainWidget->clearFilterActions();
mKMMainWidget->clearMessageTagActions();//OnurAdd
createGUI("kmmainwin.rc");
applyMainWindowSettings(KMKernel::config()->group( "Main Window") );
// plug dynamically created actions again
mKMMainWidget->initializeFilterActions();
mKMMainWidget->initializeMessageTagActions();
}
void KMMainWin::setupStatusBar()
{
mMessageStatusId = 1;
/* Create a progress dialog and hide it. */
mProgressDialog = new KPIM::ProgressDialog( statusBar(), this );
mProgressDialog->hide();
mLittleProgress = new StatusbarProgressWidget( mProgressDialog, statusBar() );
mLittleProgress->show();
statusBar()->insertItem( i18n("Starting...") , 1, 4 );
statusBar()->setItemAlignment( 1, Qt::AlignLeft | Qt::AlignVCenter );
statusBar()->addPermanentWidget( mKMMainWidget->vacationScriptIndicator() );
statusBar()->addPermanentWidget( mLittleProgress );
mLittleProgress->show();
}
void KMMainWin::slotQuit()
{
mReallyClose = true;
close();
}
//-----------------------------------------------------------------------------
bool KMMainWin::queryClose()
{
if ( kmkernel->shuttingDown() || kapp->sessionSaving() || mReallyClose )
return true;
return kmkernel->canQueryClose();
}
void KMMainWin::slotShowTipOnStart()
{
KTipDialog::showTip( this );
}
|
Apply the user toolbar setting on startup.
|
Apply the user toolbar setting on startup.
svn path=/trunk/KDE/kdepim/; revision=772414
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
869d3304491debb767488de19ba9e624b0d17203
|
PWGJE/macros/examples/pythia6FastjetExample.C
|
PWGJE/macros/examples/pythia6FastjetExample.C
|
void run(Int_t nEvent = 50, Float_t e_cms = 2760) {
// example macro for on-the-fly generation of PYTHIA6 events
// and analysis with new reader interface and FastJet
// M. van Leeuwen
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libCGAL");
gSystem->Load("libfastjet");
gSystem->Load("libsiscone");
gSystem->Load("libSISConePlugin");
gSystem->Load("libJETANdev");
gSystem->Load("libFASTJETANdev");
gSystem->Load("libpythia6.so");
gSystem->Load("libEGPythia6.so");
gSystem->Load("libAliPythia6.so");
AliPDG::AddParticlesToPdgDataBase(); // to add some PDF codes to TDatabasePDG
// Create random number generator and set seed
AliPythiaRndm::SetPythiaRandom(new TRandom3());
AliPythiaRndm::GetPythiaRandom()->SetSeed(clock()+gSystem->GetPid());
AliPythia6 *pythia=AliPythia6::Instance();
pythia->SetCKIN(3,10); // minimum hard pt
pythia->SetCKIN(4,1000); // maximum hard pt
pythia->SetMDCY(pythia->Pycomp(111),1,0); // switch off pi0 decay
pythia->Initialize("CMS","p","p",e_cms);
AliFastJetHeaderV1 *header = new AliFastJetHeaderV1;
header->SetBGMode(0);
// header->SetRadius(0.4);
header->SetRparam(0.4);
//header->SetGhostEtaMax(2);
//header->SetGhostArea(0.05);
header->SetAlgorithm(2); // antikt_algorithm = 2, kt = 0 (see fastjet/fastjet/JetDefinition.hh
AliFastJetFinder *FastJet = new AliFastJetFinder;
FastJet->SetJetHeader(header);
AliAODEvent *aod = new AliAODEvent();
aod->CreateStdContent();
FastJet->ConnectAOD(aod);
AliJetCalTrkEvent JetFinderEvent(0,1);
TClonesArray *plist = new TClonesArray("TParticle");
TClonesArray aliplist("AliMCParticle",1000);
for (Int_t iEvent = 0; iEvent < nEvent; iEvent++) {
TProcessID::SetObjectCount(0); // Needed for TRefs in AliCalTrkTrack and AliAODJet
pythia->GenerateEvent();
pythia->GetParticles(plist);
aliplist.Clear();
JetFinderEvent.Clear();
Int_t n_part = plist->GetEntries();
for (Int_t i_part = 0; i_part < n_part; i_part++) {
part=(TParticle*) plist->At(i_part);
if (part->GetStatusCode() >= 10) // Not a final state particle
continue;
new (aliplist[i_part]) AliMCParticle(part);
JetFinderEvent.AddCalTrkTrackKine((AliMCParticle*)aliplist[i_part],1,1);
}
aod->ClearStd();
FastJet->Reset();
FastJet->SetCalTrkEvent(JetFinderEvent);
FastJet->ProcessEvent();
if (aod->GetNJets() > 0) {
cout << "event " << iEvent << " " << aod->GetNJets() << " jets found" << endl;
for (Int_t iJet = 0; iJet < aod->GetNJets(); iJet++) {
jet = aod->GetJet(iJet);
cout << "\t jet " << iJet << " pt " << jet->Pt() << " eta " << jet->Eta() << " phi " << jet->Phi() << endl;
}
}
}
}
|
void run(Int_t nEvent = 50, Float_t e_cms = 2760) {
// example macro for on-the-fly generation of PYTHIA6 events
// and analysis with new reader interface and FastJet
// M. van Leeuwen
gSystem->Load("libANALYSIS");
gSystem->Load("libANALYSISalice");
gSystem->Load("libCGAL");
gSystem->Load("libfastjet");
gSystem->Load("libsiscone");
gSystem->Load("libSISConePlugin");
gSystem->Load("libJETAN");
gSystem->Load("libFASTJETAN");
gSystem->Load("libpythia6.so");
gSystem->Load("libEGPythia6.so");
gSystem->Load("libAliPythia6.so");
AliPDG::AddParticlesToPdgDataBase(); // to add some PDF codes to TDatabasePDG
// Create random number generator and set seed
AliPythiaRndm::SetPythiaRandom(new TRandom3());
AliPythiaRndm::GetPythiaRandom()->SetSeed(clock()+gSystem->GetPid());
AliPythia6 *pythia=AliPythia6::Instance();
pythia->SetCKIN(3,10); // minimum hard pt
pythia->SetCKIN(4,1000); // maximum hard pt
pythia->SetMDCY(pythia->Pycomp(111),1,0); // switch off pi0 decay
pythia->Initialize("CMS","p","p",e_cms);
AliFastJetHeaderV1 *header = new AliFastJetHeaderV1;
header->SetBGMode(0);
// header->SetRadius(0.4);
header->SetRparam(0.4);
//header->SetGhostEtaMax(2);
//header->SetGhostArea(0.05);
header->SetAlgorithm(2); // antikt_algorithm = 2, kt = 0 (see fastjet/fastjet/JetDefinition.hh
AliFastJetFinder *FastJet = new AliFastJetFinder;
FastJet->SetJetHeader(header);
AliAODEvent *aod = new AliAODEvent();
aod->CreateStdContent();
FastJet->ConnectAOD(aod);
AliJetCalTrkEvent JetFinderEvent(0,1);
TClonesArray *plist = new TClonesArray("TParticle");
TClonesArray aliplist("AliMCParticle",1000);
for (Int_t iEvent = 0; iEvent < nEvent; iEvent++) {
TProcessID::SetObjectCount(0); // Needed for TRefs in AliCalTrkTrack and AliAODJet
pythia->GenerateEvent();
pythia->GetParticles(plist);
aliplist.Clear();
JetFinderEvent.Clear();
Int_t n_part = plist->GetEntries();
for (Int_t i_part = 0; i_part < n_part; i_part++) {
part=(TParticle*) plist->At(i_part);
if (part->GetStatusCode() >= 10) // Not a final state particle
continue;
new (aliplist[i_part]) AliMCParticle(part);
JetFinderEvent.AddCalTrkTrackKine((AliMCParticle*)aliplist[i_part],1,1);
}
aod->ClearStd();
FastJet->Reset();
FastJet->SetCalTrkEvent(JetFinderEvent);
FastJet->ProcessEvent();
if (aod->GetNJets() > 0) {
cout << "event " << iEvent << " " << aod->GetNJets() << " jets found" << endl;
for (Int_t iJet = 0; iJet < aod->GetNJets(); iJet++) {
jet = aod->GetJet(iJet);
cout << "\t jet " << iJet << " pt " << jet->Pt() << " eta " << jet->Eta() << " phi " << jet->Phi() << endl;
}
}
}
}
|
Fix library names: JETANdev --> JETAN
|
Fix library names: JETANdev --> JETAN
|
C++
|
bsd-3-clause
|
lcunquei/AliPhysics,ppribeli/AliPhysics,mkrzewic/AliPhysics,kreisl/AliPhysics,kreisl/AliPhysics,hcab14/AliPhysics,pchrista/AliPhysics,sebaleh/AliPhysics,victor-gonzalez/AliPhysics,alisw/AliPhysics,alisw/AliPhysics,pbatzing/AliPhysics,nschmidtALICE/AliPhysics,victor-gonzalez/AliPhysics,pbuehler/AliPhysics,fcolamar/AliPhysics,lfeldkam/AliPhysics,jmargutt/AliPhysics,pbatzing/AliPhysics,carstooon/AliPhysics,rbailhac/AliPhysics,pbuehler/AliPhysics,fbellini/AliPhysics,aaniin/AliPhysics,mazimm/AliPhysics,amatyja/AliPhysics,pchrista/AliPhysics,yowatana/AliPhysics,mazimm/AliPhysics,aaniin/AliPhysics,dstocco/AliPhysics,adriansev/AliPhysics,mpuccio/AliPhysics,AMechler/AliPhysics,pbatzing/AliPhysics,mpuccio/AliPhysics,mpuccio/AliPhysics,lcunquei/AliPhysics,nschmidtALICE/AliPhysics,hzanoli/AliPhysics,dlodato/AliPhysics,pchrista/AliPhysics,rihanphys/AliPhysics,akubera/AliPhysics,AMechler/AliPhysics,amatyja/AliPhysics,mkrzewic/AliPhysics,AMechler/AliPhysics,preghenella/AliPhysics,ALICEHLT/AliPhysics,amaringarcia/AliPhysics,pchrista/AliPhysics,mazimm/AliPhysics,mpuccio/AliPhysics,hzanoli/AliPhysics,lfeldkam/AliPhysics,amatyja/AliPhysics,sebaleh/AliPhysics,ppribeli/AliPhysics,AudreyFrancisco/AliPhysics,rbailhac/AliPhysics,jmargutt/AliPhysics,hcab14/AliPhysics,lcunquei/AliPhysics,lcunquei/AliPhysics,mvala/AliPhysics,dstocco/AliPhysics,mkrzewic/AliPhysics,mpuccio/AliPhysics,rbailhac/AliPhysics,hcab14/AliPhysics,rbailhac/AliPhysics,amaringarcia/AliPhysics,akubera/AliPhysics,carstooon/AliPhysics,alisw/AliPhysics,dlodato/AliPhysics,nschmidtALICE/AliPhysics,yowatana/AliPhysics,sebaleh/AliPhysics,fcolamar/AliPhysics,ALICEHLT/AliPhysics,sebaleh/AliPhysics,mbjadhav/AliPhysics,btrzecia/AliPhysics,ALICEHLT/AliPhysics,amaringarcia/AliPhysics,mkrzewic/AliPhysics,aaniin/AliPhysics,mvala/AliPhysics,kreisl/AliPhysics,mvala/AliPhysics,victor-gonzalez/AliPhysics,mpuccio/AliPhysics,ALICEHLT/AliPhysics,mpuccio/AliPhysics,btrzecia/AliPhysics,dstocco/AliPhysics,ppribeli/AliPhysics,jmargutt/AliPhysics,SHornung1/AliPhysics,victor-gonzalez/AliPhysics,fcolamar/AliPhysics,nschmidtALICE/AliPhysics,AudreyFrancisco/AliPhysics,rihanphys/AliPhysics,amaringarcia/AliPhysics,AudreyFrancisco/AliPhysics,preghenella/AliPhysics,yowatana/AliPhysics,rihanphys/AliPhysics,btrzecia/AliPhysics,carstooon/AliPhysics,rderradi/AliPhysics,jgronefe/AliPhysics,fbellini/AliPhysics,jmargutt/AliPhysics,victor-gonzalez/AliPhysics,AudreyFrancisco/AliPhysics,yowatana/AliPhysics,preghenella/AliPhysics,dlodato/AliPhysics,lfeldkam/AliPhysics,alisw/AliPhysics,ppribeli/AliPhysics,mvala/AliPhysics,pbatzing/AliPhysics,jgronefe/AliPhysics,ppribeli/AliPhysics,ppribeli/AliPhysics,adriansev/AliPhysics,dstocco/AliPhysics,pbatzing/AliPhysics,rderradi/AliPhysics,amatyja/AliPhysics,hcab14/AliPhysics,hzanoli/AliPhysics,dstocco/AliPhysics,sebaleh/AliPhysics,dlodato/AliPhysics,hzanoli/AliPhysics,preghenella/AliPhysics,lfeldkam/AliPhysics,alisw/AliPhysics,SHornung1/AliPhysics,mazimm/AliPhysics,mvala/AliPhysics,btrzecia/AliPhysics,mbjadhav/AliPhysics,ALICEHLT/AliPhysics,amatyja/AliPhysics,rderradi/AliPhysics,fcolamar/AliPhysics,mkrzewic/AliPhysics,kreisl/AliPhysics,nschmidtALICE/AliPhysics,carstooon/AliPhysics,rderradi/AliPhysics,kreisl/AliPhysics,lfeldkam/AliPhysics,mbjadhav/AliPhysics,dmuhlhei/AliPhysics,pbuehler/AliPhysics,preghenella/AliPhysics,dmuhlhei/AliPhysics,rderradi/AliPhysics,SHornung1/AliPhysics,adriansev/AliPhysics,preghenella/AliPhysics,lcunquei/AliPhysics,rbailhac/AliPhysics,fbellini/AliPhysics,dmuhlhei/AliPhysics,amaringarcia/AliPhysics,hzanoli/AliPhysics,sebaleh/AliPhysics,AMechler/AliPhysics,AMechler/AliPhysics,dmuhlhei/AliPhysics,pchrista/AliPhysics,carstooon/AliPhysics,rderradi/AliPhysics,yowatana/AliPhysics,carstooon/AliPhysics,dlodato/AliPhysics,akubera/AliPhysics,kreisl/AliPhysics,rihanphys/AliPhysics,hcab14/AliPhysics,mbjadhav/AliPhysics,rderradi/AliPhysics,SHornung1/AliPhysics,AudreyFrancisco/AliPhysics,yowatana/AliPhysics,jgronefe/AliPhysics,dstocco/AliPhysics,pbatzing/AliPhysics,pchrista/AliPhysics,amaringarcia/AliPhysics,ALICEHLT/AliPhysics,victor-gonzalez/AliPhysics,mvala/AliPhysics,kreisl/AliPhysics,adriansev/AliPhysics,fbellini/AliPhysics,dlodato/AliPhysics,aaniin/AliPhysics,alisw/AliPhysics,lfeldkam/AliPhysics,mkrzewic/AliPhysics,jmargutt/AliPhysics,carstooon/AliPhysics,btrzecia/AliPhysics,dmuhlhei/AliPhysics,mbjadhav/AliPhysics,mazimm/AliPhysics,AMechler/AliPhysics,jgronefe/AliPhysics,rihanphys/AliPhysics,fcolamar/AliPhysics,akubera/AliPhysics,fbellini/AliPhysics,victor-gonzalez/AliPhysics,jgronefe/AliPhysics,amatyja/AliPhysics,pbatzing/AliPhysics,amaringarcia/AliPhysics,adriansev/AliPhysics,rihanphys/AliPhysics,btrzecia/AliPhysics,btrzecia/AliPhysics,jmargutt/AliPhysics,jgronefe/AliPhysics,hzanoli/AliPhysics,rihanphys/AliPhysics,pbuehler/AliPhysics,dmuhlhei/AliPhysics,hzanoli/AliPhysics,alisw/AliPhysics,mbjadhav/AliPhysics,aaniin/AliPhysics,pchrista/AliPhysics,mbjadhav/AliPhysics,preghenella/AliPhysics,jmargutt/AliPhysics,AudreyFrancisco/AliPhysics,sebaleh/AliPhysics,akubera/AliPhysics,mazimm/AliPhysics,pbuehler/AliPhysics,fbellini/AliPhysics,ALICEHLT/AliPhysics,akubera/AliPhysics,rbailhac/AliPhysics,ppribeli/AliPhysics,lcunquei/AliPhysics,mvala/AliPhysics,yowatana/AliPhysics,nschmidtALICE/AliPhysics,aaniin/AliPhysics,rbailhac/AliPhysics,akubera/AliPhysics,pbuehler/AliPhysics,lcunquei/AliPhysics,aaniin/AliPhysics,adriansev/AliPhysics,adriansev/AliPhysics,SHornung1/AliPhysics,jgronefe/AliPhysics,SHornung1/AliPhysics,dstocco/AliPhysics,amatyja/AliPhysics,nschmidtALICE/AliPhysics,dmuhlhei/AliPhysics,lfeldkam/AliPhysics,hcab14/AliPhysics,fcolamar/AliPhysics,fcolamar/AliPhysics,fbellini/AliPhysics,pbuehler/AliPhysics,AudreyFrancisco/AliPhysics,hcab14/AliPhysics,dlodato/AliPhysics,mazimm/AliPhysics,mkrzewic/AliPhysics,AMechler/AliPhysics,SHornung1/AliPhysics
|
eb27f40350b303c3dd279c1fad3e9dfda34dbaa7
|
src/asp/Tools/wv_correct.cc
|
src/asp/Tools/wv_correct.cc
|
// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
/// \file wv_correct.cc
///
// Correct CCD artifacts in WorldView2 images with TDI 16.
// To do:
// Verify that the input image satisfies the above assumptions.
// Add documentation.
// Print default offsets.
// The problem: A WV2 image is obtained by mosaicking from left to
// right image blocks which are as tall is the entire image (each
// block comes from an individual CCD image sensor). Blocks are
// slightly misplaced in respect to each other by some unknown
// subpixel offset. The goal of this tool is to locate these CCD
// artifact boundary locations, and undo the offsets.
//
// Observations:
// 1. The CCD artifact locations are periodic, but the starting offset
// is not positioned at exactly one period. It is less by one fixed
// value which we name 'shift'.
// 2. There are CCD offsets in both x and y at each location.
// 3. The magnitude of all CCD offsets in x is the same, but their sign
// alternates. The same is true in y.
// 4. The period of CCD offsets is inversely proportional to the detector
// pitch.
// 5. The CCD offsets are pretty consistent among all images of given
// scan direction (forward or reverse).
// We used all these and a lot of images to heuristically find the
// period and offset of the artifacts, and the 'shift' value. We
// correct these below. We allow the user to override the value of CCD
// offsets if desired.
#include <vw/FileIO.h>
#include <vw/Image.h>
#include <vw/Cartography.h>
#include <vw/Math.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
#include <asp/Sessions/DG/XML.h>
#include <asp/Sessions/RPC/RPCModel.h>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/sax/HandlerBase.hpp>
#include <xercesc/util/PlatformUtils.hpp>
namespace po = boost::program_options;
using namespace vw;
using namespace asp;
using namespace vw::cartography;
using namespace xercesc;
using namespace std;
// Allows FileIO to correctly read/write these pixel types
namespace vw {
typedef Vector<float64,6> Vector6;
template<> struct PixelFormatID<Vector3> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };
template<> struct PixelFormatID<Vector3f> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };
template<> struct PixelFormatID<Vector4> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_4_CHANNEL; };
template<> struct PixelFormatID<Vector6> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_6_CHANNEL; };
}
struct Options : asp::BaseOptions {
double xoffset, yoffset;
double xoffset_forward, yoffset_forward;
double xoffset_reverse, yoffset_reverse;
std::string camera_image_file, camera_model_file, output_image;
Options(){}
};
void handle_arguments( int argc, char *argv[], Options& opt ) {
// These quantities were heuristically obtained by averaging
// over a large set of runs while removing outliers and giving
// more weight to more reliable data.
double default_xoffset_forward = 0.2842;
double default_yoffset_forward = 0.2369;
double default_xoffset_reverse = 0.3396;
double default_yoffset_reverse = 0.3725;
po::options_description general_options("");
general_options.add_options()
("xoffset", po::value(&opt.xoffset), "Specify the CCD offset correction to apply in the x direction.")
("yoffset", po::value(&opt.yoffset), "Specify the CCD offset correction to apply in the y direction.");
general_options.add( asp::BaseOptionsDescription(opt) );
po::options_description positional("");
positional.add_options()
("camera-image", po::value(&opt.camera_image_file))
("camera-model", po::value(&opt.camera_model_file))
("output-image", po::value(&opt.output_image));
po::positional_options_description positional_desc;
positional_desc.add("camera-image",1);
positional_desc.add("camera-model",1);
positional_desc.add("output-image",1);
std::string usage("[options] <camera-image> <camera-model> <output-image>");
po::variables_map vm =
asp::check_command_line( argc, argv, opt, general_options, general_options,
positional, positional_desc, usage );
if ( !vm.count("camera-image") || !vm.count("camera-model") || !vm.count("output-image") )
vw_throw( ArgumentErr() << "Requires <camera-image>, <camera-model> and <output-image> "
<< "in order to proceed.\n\n"
<< usage << general_options );
if (vm.count("xoffset")){
opt.xoffset_forward = opt.xoffset;
opt.xoffset_reverse = opt.xoffset;
}else{
opt.xoffset_forward = default_xoffset_forward;
opt.xoffset_reverse = default_xoffset_reverse;
}
if (vm.count("yoffset")){
opt.yoffset_forward = opt.yoffset;
opt.yoffset_reverse = opt.yoffset;
}else{
opt.yoffset_forward = default_yoffset_forward;
opt.yoffset_reverse = default_yoffset_reverse;
}
}
template <class ImageT>
class WVCorrectView: public ImageViewBase< WVCorrectView<ImageT> >{
ImageT m_img;
double m_shift, m_period, m_xoffset, m_yoffset;
typedef typename ImageT::pixel_type PixelT;
public:
WVCorrectView( ImageT const& img,
double shift, double period, double xoffset, double yoffset):
m_img(img), m_shift(shift), m_period(period),
m_xoffset(xoffset), m_yoffset(yoffset){}
typedef PixelT pixel_type;
typedef PixelT result_type;
typedef ProceduralPixelAccessor<WVCorrectView> pixel_accessor;
inline int32 cols() const { return m_img.cols(); }
inline int32 rows() const { return m_img.rows(); }
inline int32 planes() const { return 1; }
inline pixel_accessor origin() const { return pixel_accessor( *this, 0, 0 ); }
inline pixel_type operator()( double/*i*/, double/*j*/, int32/*p*/ = 0 ) const {
vw_throw(NoImplErr() << "WVCorrectView::operator()(...) is not implemented");
return pixel_type();
}
typedef CropView<ImageView<pixel_type> > prerasterize_type;
inline prerasterize_type prerasterize(BBox2i const& bbox) const {
// Need to see a bit more of the input image for the purpose
// of interpolation.
int bias = (int)ceil(std::max(std::abs(m_xoffset), std::abs(m_yoffset)))
+ BilinearInterpolation::pixel_buffer + 1;
BBox2i biased_box = bbox;
biased_box.expand(bias);
biased_box.crop(bounding_box(m_img));
ImageView<result_type> cropped_img = crop(m_img, biased_box);
InterpolationView<EdgeExtensionView< ImageView<result_type>, ValueEdgeExtension<result_type> >, BilinearInterpolation> interp_img
= interpolate(cropped_img, BilinearInterpolation(),
ValueEdgeExtension<result_type>(result_type()));
ImageView<result_type> tile(bbox.width(), bbox.height());
for (int col = bbox.min().x(); col < bbox.max().x(); col++){
// The sign of CCD offsets alternates as one moves along the image
// columns. As such, at "even" blocks, the offsets accumulated so
// far cancel each other, so we need to correct the "odd" blocks
// only.
int block_index = (int)floor((col - m_shift)/m_period);
double valx = 0, valy = 0;
if (block_index % 2 ){
valx = -m_xoffset;
valy = -m_yoffset;
}
for (int row = bbox.min().y(); row < bbox.max().y(); row++){
tile(col - bbox.min().x(), row - bbox.min().y() )
= interp_img(col - biased_box.min().x() + valx,
row - biased_box.min().y() + valy);
}
}
return prerasterize_type(tile, -bbox.min().x(), -bbox.min().y(),
cols(), rows() );
}
template <class DestT>
inline void rasterize(DestT const& dest, BBox2i bbox) const {
vw::rasterize(prerasterize(bbox), dest, bbox);
}
};
template <class ImageT>
WVCorrectView<ImageT> wv_correct(ImageT const& img, double shift,
double period, double xoffset, double yoffset){
return WVCorrectView<ImageT>(img, shift, period, xoffset, yoffset);
}
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
GeometricXML geo;
AttitudeXML att;
EphemerisXML eph;
ImageXML img;
RPCXML rpc;
std::string scan_dir;
try{
XMLPlatformUtils::Initialize();
read_xml( opt.camera_model_file, geo, att, eph, img, rpc );
scan_dir = boost::to_lower_copy( img.scan_direction );
if (scan_dir != "forward" && scan_dir != "reverse"){
vw_throw( ArgumentErr() << "XML file \"" << opt.camera_model_file
<< "\" is lacking a valid image scan direction.\n" );
}
if (geo.detector_pixel_pitch <= 0.0){
vw_throw( ArgumentErr() << "XML file \"" << opt.camera_model_file
<< "\" has a non-positive pixel pitch.\n" );
}
}catch(...){
vw_throw( ArgumentErr() << "XML file \"" << opt.camera_model_file << "\" is invalid.\n" );
}
// The first CCD artifact is at column period + shift,
// then they repeat with given period.
double shift = -30.0;
double period = 5.64/geo.detector_pixel_pitch;
// The offsets at the first CCD artifact location.
// The offsets keep the same magnitude but their sign
// alternates as one moves along image columns.
double xoffset, yoffset;
if (scan_dir == "forward"){
xoffset = opt.xoffset_forward;
yoffset = opt.yoffset_forward;
}else{
xoffset = opt.xoffset_reverse;
yoffset = opt.yoffset_reverse;
}
vw_out() << "Using x offset: " << xoffset << std::endl;
vw_out() << "Using y offset: " << yoffset << std::endl;
// Internal sign adjustments
if (scan_dir == "forward"){
yoffset = -yoffset;
}else{
xoffset = -xoffset;
}
DiskImageView<float> input_img(opt.camera_image_file);
bool has_nodata = false;
double nodata = numeric_limits<double>::quiet_NaN();
boost::shared_ptr<DiskImageResource> img_rsrc
( new DiskImageResourceGDAL(opt.camera_image_file) );
if (img_rsrc->has_nodata_read()){
has_nodata = true;
nodata = img_rsrc->nodata_read();
}
vw_out() << "Writing: " << opt.output_image << std::endl;
if (has_nodata){
asp::block_write_gdal_image(opt.output_image,
apply_mask
(wv_correct(create_mask(input_img,
nodata),
shift, period, xoffset, yoffset),
nodata),
nodata, opt,
TerminalProgressCallback("asp", "\t-->: "));
}else{
asp::block_write_gdal_image(opt.output_image,
wv_correct(input_img, shift, period,
xoffset, yoffset),
opt,
TerminalProgressCallback("asp", "\t-->: "));
}
} ASP_STANDARD_CATCHES;
return 0;
}
|
// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
/// \file wv_correct.cc
///
// Correct CCD artifacts in WorldView2 images with TDI 16.
// To do:
// Verify that the input image satisfies the above assumptions.
// Add documentation.
// Print default offsets.
// The problem: A WV2 image is obtained by mosaicking from left to
// right image blocks which are as tall is the entire image (each
// block comes from an individual CCD image sensor). Blocks are
// slightly misplaced in respect to each other by some unknown
// subpixel offset. The goal of this tool is to locate these CCD
// artifact boundary locations, and undo the offsets.
//
// Observations:
// 1. The CCD artifact locations are periodic, but the starting offset
// is not positioned at exactly one period. It is less by one fixed
// value which we name 'shift'.
// 2. There are CCD offsets in both x and y at each location.
// 3. The magnitude of all CCD offsets in x is the same, but their sign
// alternates. The same is true in y.
// 4. The period of CCD offsets is inversely proportional to the detector
// pitch.
// 5. The CCD offsets are pretty consistent among all images of given
// scan direction (forward or reverse).
// We used all these and a lot of images to heuristically find the
// period and offset of the artifacts, and the 'shift' value. We
// correct these below. We allow the user to override the value of CCD
// offsets if desired.
#include <vw/FileIO.h>
#include <vw/Image.h>
#include <vw/Cartography.h>
#include <vw/Math.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
#include <asp/Sessions/DG/XML.h>
#include <asp/Sessions/RPC/RPCModel.h>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/sax/HandlerBase.hpp>
#include <xercesc/util/PlatformUtils.hpp>
namespace po = boost::program_options;
using namespace vw;
using namespace asp;
using namespace vw::cartography;
using namespace xercesc;
using namespace std;
// Allows FileIO to correctly read/write these pixel types
namespace vw {
typedef Vector<float64,6> Vector6;
template<> struct PixelFormatID<Vector3> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };
template<> struct PixelFormatID<Vector3f> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };
template<> struct PixelFormatID<Vector4> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_4_CHANNEL; };
template<> struct PixelFormatID<Vector6> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_6_CHANNEL; };
}
struct Options : asp::BaseOptions {
double xoffset, yoffset;
double xoffset_forward, yoffset_forward;
double xoffset_reverse, yoffset_reverse;
std::string camera_image_file, camera_model_file, output_image;
Options(){}
};
void handle_arguments( int argc, char *argv[], Options& opt ) {
// These quantities were heuristically obtained by averaging
// over a large set of runs while removing outliers and giving
// more weight to more reliable data.
double default_xoffset_forward = 0.2842;
double default_yoffset_forward = 0.2369;
double default_xoffset_reverse = 0.3396;
double default_yoffset_reverse = 0.3725;
po::options_description general_options("");
general_options.add_options()
("xoffset", po::value(&opt.xoffset), "Specify the CCD offset correction to apply in the x direction (optional).")
("yoffset", po::value(&opt.yoffset), "Specify the CCD offset correction to apply in the y direction (optional).");
general_options.add( asp::BaseOptionsDescription(opt) );
po::options_description positional("");
positional.add_options()
("camera-image", po::value(&opt.camera_image_file))
("camera-model", po::value(&opt.camera_model_file))
("output-image", po::value(&opt.output_image));
po::positional_options_description positional_desc;
positional_desc.add("camera-image",1);
positional_desc.add("camera-model",1);
positional_desc.add("output-image",1);
std::string usage("[options] <camera-image> <camera-model> <output-image>");
po::variables_map vm =
asp::check_command_line( argc, argv, opt, general_options, general_options,
positional, positional_desc, usage );
if ( !vm.count("camera-image") || !vm.count("camera-model") || !vm.count("output-image") )
vw_throw( ArgumentErr() << "Requires <camera-image>, <camera-model> and <output-image> "
<< "in order to proceed.\n\n"
<< usage << general_options );
if (vm.count("xoffset")){
opt.xoffset_forward = opt.xoffset;
opt.xoffset_reverse = opt.xoffset;
}else{
opt.xoffset_forward = default_xoffset_forward;
opt.xoffset_reverse = default_xoffset_reverse;
}
if (vm.count("yoffset")){
opt.yoffset_forward = opt.yoffset;
opt.yoffset_reverse = opt.yoffset;
}else{
opt.yoffset_forward = default_yoffset_forward;
opt.yoffset_reverse = default_yoffset_reverse;
}
}
template <class ImageT>
class WVCorrectView: public ImageViewBase< WVCorrectView<ImageT> >{
ImageT m_img;
double m_shift, m_period, m_xoffset, m_yoffset;
typedef typename ImageT::pixel_type PixelT;
public:
WVCorrectView( ImageT const& img,
double shift, double period, double xoffset, double yoffset):
m_img(img), m_shift(shift), m_period(period),
m_xoffset(xoffset), m_yoffset(yoffset){}
typedef PixelT pixel_type;
typedef PixelT result_type;
typedef ProceduralPixelAccessor<WVCorrectView> pixel_accessor;
inline int32 cols() const { return m_img.cols(); }
inline int32 rows() const { return m_img.rows(); }
inline int32 planes() const { return 1; }
inline pixel_accessor origin() const { return pixel_accessor( *this, 0, 0 ); }
inline pixel_type operator()( double/*i*/, double/*j*/, int32/*p*/ = 0 ) const {
vw_throw(NoImplErr() << "WVCorrectView::operator()(...) is not implemented");
return pixel_type();
}
typedef CropView<ImageView<pixel_type> > prerasterize_type;
inline prerasterize_type prerasterize(BBox2i const& bbox) const {
// Need to see a bit more of the input image for the purpose
// of interpolation.
int bias = (int)ceil(std::max(std::abs(m_xoffset), std::abs(m_yoffset)))
+ BilinearInterpolation::pixel_buffer + 1;
BBox2i biased_box = bbox;
biased_box.expand(bias);
biased_box.crop(bounding_box(m_img));
ImageView<result_type> cropped_img = crop(m_img, biased_box);
InterpolationView<EdgeExtensionView< ImageView<result_type>, ValueEdgeExtension<result_type> >, BilinearInterpolation> interp_img
= interpolate(cropped_img, BilinearInterpolation(),
ValueEdgeExtension<result_type>(result_type()));
ImageView<result_type> tile(bbox.width(), bbox.height());
for (int col = bbox.min().x(); col < bbox.max().x(); col++){
// The sign of CCD offsets alternates as one moves along the image
// columns. As such, at "even" blocks, the offsets accumulated so
// far cancel each other, so we need to correct the "odd" blocks
// only.
int block_index = (int)floor((col - m_shift)/m_period);
double valx = 0, valy = 0;
if (block_index % 2 ){
valx = -m_xoffset;
valy = -m_yoffset;
}
for (int row = bbox.min().y(); row < bbox.max().y(); row++){
tile(col - bbox.min().x(), row - bbox.min().y() )
= interp_img(col - biased_box.min().x() + valx,
row - biased_box.min().y() + valy);
}
}
return prerasterize_type(tile, -bbox.min().x(), -bbox.min().y(),
cols(), rows() );
}
template <class DestT>
inline void rasterize(DestT const& dest, BBox2i bbox) const {
vw::rasterize(prerasterize(bbox), dest, bbox);
}
};
template <class ImageT>
WVCorrectView<ImageT> wv_correct(ImageT const& img, double shift,
double period, double xoffset, double yoffset){
return WVCorrectView<ImageT>(img, shift, period, xoffset, yoffset);
}
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
GeometricXML geo;
AttitudeXML att;
EphemerisXML eph;
ImageXML img;
RPCXML rpc;
std::string scan_dir;
try{
XMLPlatformUtils::Initialize();
read_xml( opt.camera_model_file, geo, att, eph, img, rpc );
scan_dir = boost::to_lower_copy( img.scan_direction );
if (scan_dir != "forward" && scan_dir != "reverse"){
vw_throw( ArgumentErr() << "XML file \"" << opt.camera_model_file
<< "\" is lacking a valid image scan direction.\n" );
}
if (geo.detector_pixel_pitch <= 0.0){
vw_throw( ArgumentErr() << "XML file \"" << opt.camera_model_file
<< "\" has a non-positive pixel pitch.\n" );
}
}catch(...){
vw_throw( ArgumentErr() << "XML file \"" << opt.camera_model_file << "\" is invalid.\n" );
}
// The first CCD artifact is at column period + shift,
// then they repeat with given period.
double shift = -30.0;
double period = 5.64/geo.detector_pixel_pitch;
// The offsets at the first CCD artifact location.
// The offsets keep the same magnitude but their sign
// alternates as one moves along image columns.
double xoffset, yoffset;
if (scan_dir == "forward"){
xoffset = opt.xoffset_forward;
yoffset = opt.yoffset_forward;
}else{
xoffset = opt.xoffset_reverse;
yoffset = opt.yoffset_reverse;
}
vw_out() << "Using x offset: " << xoffset << std::endl;
vw_out() << "Using y offset: " << yoffset << std::endl;
// Internal sign adjustments
if (scan_dir == "forward"){
yoffset = -yoffset;
}else{
xoffset = -xoffset;
}
DiskImageView<float> input_img(opt.camera_image_file);
bool has_nodata = false;
double nodata = numeric_limits<double>::quiet_NaN();
boost::shared_ptr<DiskImageResource> img_rsrc
( new DiskImageResourceGDAL(opt.camera_image_file) );
if (img_rsrc->has_nodata_read()){
has_nodata = true;
nodata = img_rsrc->nodata_read();
}
vw_out() << "Writing: " << opt.output_image << std::endl;
if (has_nodata){
asp::block_write_gdal_image(opt.output_image,
apply_mask
(wv_correct(create_mask(input_img,
nodata),
shift, period, xoffset, yoffset),
nodata),
nodata, opt,
TerminalProgressCallback("asp", "\t-->: "));
}else{
asp::block_write_gdal_image(opt.output_image,
wv_correct(input_img, shift, period,
xoffset, yoffset),
opt,
TerminalProgressCallback("asp", "\t-->: "));
}
} ASP_STANDARD_CATCHES;
return 0;
}
|
Clarify that it is optional to provide offsets
|
wv_correct: Clarify that it is optional to provide offsets
|
C++
|
apache-2.0
|
oleg-alexandrov/StereoPipeline,ScottMcMichael/StereoPipeline,ScottMcMichael/StereoPipeline,njwilson23/StereoPipeline,DougFirErickson/StereoPipeline,njwilson23/StereoPipeline,njwilson23/StereoPipeline,DougFirErickson/StereoPipeline,ScottMcMichael/StereoPipeline,NeoGeographyToolkit/StereoPipeline,NeoGeographyToolkit/StereoPipeline,njwilson23/StereoPipeline,oleg-alexandrov/StereoPipeline,njwilson23/StereoPipeline,aaronknister/StereoPipeline,aaronknister/StereoPipeline,NeoGeographyToolkit/StereoPipeline,oleg-alexandrov/StereoPipeline,DougFirErickson/StereoPipeline,aaronknister/StereoPipeline,DougFirErickson/StereoPipeline,NeoGeographyToolkit/StereoPipeline,oleg-alexandrov/StereoPipeline,NeoGeographyToolkit/StereoPipeline,aaronknister/StereoPipeline,NeoGeographyToolkit/StereoPipeline,DougFirErickson/StereoPipeline,aaronknister/StereoPipeline,oleg-alexandrov/StereoPipeline,ScottMcMichael/StereoPipeline,njwilson23/StereoPipeline,oleg-alexandrov/StereoPipeline,ScottMcMichael/StereoPipeline,ScottMcMichael/StereoPipeline,DougFirErickson/StereoPipeline
|
669ac214234c51222ab3bd7435b7853bea5a096f
|
src-plugins/itkDataImage/interactors/medVtkViewItkDataImage4DInteractor.cpp
|
src-plugins/itkDataImage/interactors/medVtkViewItkDataImage4DInteractor.cpp
|
/*=========================================================================
medInria
Copyright (c) INRIA 2013 - 2014. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include "medVtkViewItkDataImage4DInteractor.h"
#include <vtkMetaDataSetSequence.h>
#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkImageActor.h>
#include <vtkImageProperty.h>
#include <medAbstractImageView.h>
#include <medVtkViewBackend.h>
#include <medViewFactory.h>
#include <medAbstractImageData.h>
#include <medDoubleParameter.h>
class medVtkViewItkDataImage4DInteractorPrivate
{
public:
typedef vtkSmartPointer <vtkActor> ActorSmartPointer;
typedef vtkSmartPointer <vtkProperty> PropertySmartPointer;
medAbstractImageView *view;
vtkImageView2D *view2d;
vtkImageView3D *view3d;
vtkRenderWindow *render;
vtkMetaDataSetSequence *sequence;
medAbstractImageData *imageData;
double currentTime;
};
template <typename TYPE>
bool AppendImageSequence(medAbstractData* data,medAbstractImageView* view,vtkMetaDataSetSequence* sequence, int& layer) {
if (itk::Image<TYPE,4>* image = dynamic_cast<itk::Image<TYPE,4>*>(static_cast<itk::Object*>(data->data()))) {
medVtkViewBackend* backend = static_cast<medVtkViewBackend*>(view->backend());
sequence->SetITKDataSet<TYPE>(image);
vtkMetaImageData* metaimage = vtkMetaImageData::SafeDownCast(sequence->GetMetaDataSet(0U));
vtkImageData* vtkimage = vtkImageData::SafeDownCast(sequence->GetDataSet());
backend->view2D->SetInput(vtkimage,metaimage->GetOrientationMatrix(), layer);
backend->view3D->SetInput(vtkimage,metaimage->GetOrientationMatrix(), layer);
layer = backend->view2D->GetNumberOfLayers()-1;
return true;
}
return false;
}
medVtkViewItkDataImage4DInteractor::medVtkViewItkDataImage4DInteractor(medAbstractView *parent):
medVtkViewItkDataImageInteractor(parent), d(new medVtkViewItkDataImage4DInteractorPrivate)
{
d->view = dynamic_cast<medAbstractImageView *>(parent);
medVtkViewBackend* backend = static_cast<medVtkViewBackend*>(parent->backend());
d->view2d = backend->view2D;
d->view3d = backend->view3D;
d->render = backend->renWin;
d->currentTime = 0.0;
}
medVtkViewItkDataImage4DInteractor::~medVtkViewItkDataImage4DInteractor()
{
}
QString medVtkViewItkDataImage4DInteractor::description() const
{
return tr("Interactor displaying 4D Meshes");
}
QString medVtkViewItkDataImage4DInteractor::identifier() const
{
return "medVtkViewItkDataImage4DInteractor";
}
QStringList medVtkViewItkDataImage4DInteractor::handled() const
{
return medVtkViewItkDataImage4DInteractor::dataHandled();
}
QStringList medVtkViewItkDataImage4DInteractor::dataHandled()
{
QStringList d = QStringList() << "itkDataImageChar4"
<< "itkDataImageUChar4"
<< "itkDataImageShort4"
<< "itkDataImageUShort4"
<< "itkDataImageInt4"
<< "itkDataImageLong4"
<< "itkDataImageULong4"
<< "itkDataImageFloat4"
<< "itkDataImageDouble4";
return d;
}
bool medVtkViewItkDataImage4DInteractor::registered()
{
medViewFactory *factory = medViewFactory::instance();
return factory->registerInteractor<medVtkViewItkDataImage4DInteractor>("medVtkViewItkDataImage4DInteractor",
QStringList () << "medVtkView" <<
medVtkViewItkDataImage4DInteractor::dataHandled());
}
void medVtkViewItkDataImage4DInteractor::setData(medAbstractData *data)
{
d->imageData = dynamic_cast<medAbstractImageData *>(data);
if(!d->imageData)
return;
if( data->identifier().contains("itkDataImage") && d->imageData->Dimension() == 4 ) {
d->sequence = vtkMetaDataSetSequence::New();
int layer = d->view->layer(data);
if ( AppendImageSequence<char>(data,d->view,d->sequence, layer) ||
AppendImageSequence<unsigned char>(data,d->view,d->sequence, layer) ||
AppendImageSequence<short>(data,d->view,d->sequence, layer) ||
AppendImageSequence<unsigned short>(data,d->view,d->sequence, layer) ||
AppendImageSequence<float>(data,d->view,d->sequence, layer) ||
AppendImageSequence<double>(data,d->view,d->sequence, layer))
{
d->imageData->addMetaData("SequenceDuration", QString::number(d->sequence->GetMaxTime()));
d->imageData->addMetaData("SequenceFrameRate", QString::number((double)d->sequence->GetNumberOfMetaDataSets() /
(double)d->sequence->GetMaxTime()));
qDebug() << "SequenceDuration" << d->sequence->GetMaxTime();
qDebug() << "SequenceFrameRate" <<(double)d->sequence->GetNumberOfMetaDataSets() / (double)d->sequence->GetMaxTime();
d->view2d->GetImageActor(d->view2d->GetCurrentLayer())->GetProperty()->SetInterpolationTypeToCubic();
initParameters(d->imageData);
if(d->view->layer(d->imageData) == 0)
{
switch(d->view2d->GetViewOrientation())
{
case vtkImageView2D::VIEW_ORIENTATION_AXIAL:
d->view->setOrientation(medImageView::VIEW_ORIENTATION_AXIAL);
break;
case vtkImageView2D::VIEW_ORIENTATION_SAGITTAL:
d->view->setOrientation(medImageView::VIEW_ORIENTATION_SAGITTAL);
break;
case vtkImageView2D::VIEW_ORIENTATION_CORONAL:
d->view->setOrientation(medImageView::VIEW_ORIENTATION_CORONAL);
break;
}
}
}
}
}
medAbstractData *medVtkViewItkDataImage4DInteractor::data() const
{
return d->imageData;
}
QWidget* medVtkViewItkDataImage4DInteractor::buildToolBoxWidget()
{
QWidget *toolBoxWidget = new QWidget;
QVBoxLayout *tbLayout = new QVBoxLayout(toolBoxWidget);
tbLayout->addWidget(medVtkViewItkDataImageInteractor::buildToolBoxWidget());
return toolBoxWidget;
}
QWidget* medVtkViewItkDataImage4DInteractor::buildToolBarWidget()
{
return medVtkViewItkDataImageInteractor::buildToolBarWidget();
}
QWidget* medVtkViewItkDataImage4DInteractor::buildLayerWidget()
{
return medVtkViewItkDataImageInteractor::buildLayerWidget();
}
QList<medAbstractParameter*> medVtkViewItkDataImage4DInteractor::linkableParameters()
{
QList<medAbstractParameter*> parameters;
parameters << medVtkViewItkDataImageInteractor::linkableParameters();
return parameters;
}
void medVtkViewItkDataImage4DInteractor::setCurrentTime(double time)
{
if(d->sequence->GetTime() == time)
return;
d->sequence->UpdateToTime(time);
}
void medVtkViewItkDataImage4DInteractor::updateWidgets()
{
medVtkViewItkDataImageInteractor::updateWidgets();
}
|
/*=========================================================================
medInria
Copyright (c) INRIA 2013 - 2014. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include "medVtkViewItkDataImage4DInteractor.h"
#include <vtkMetaDataSetSequence.h>
#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkImageActor.h>
#include <vtkImageProperty.h>
#include <medAbstractImageView.h>
#include <medVtkViewBackend.h>
#include <medViewFactory.h>
#include <medAbstractImageData.h>
#include <medDoubleParameter.h>
class medVtkViewItkDataImage4DInteractorPrivate
{
public:
typedef vtkSmartPointer <vtkActor> ActorSmartPointer;
typedef vtkSmartPointer <vtkProperty> PropertySmartPointer;
medAbstractImageView *view;
vtkImageView2D *view2d;
vtkImageView3D *view3d;
vtkRenderWindow *render;
vtkMetaDataSetSequence *sequence;
medAbstractImageData *imageData;
double currentTime;
};
template <typename TYPE>
bool AppendImageSequence(medAbstractData* data,medAbstractImageView* view,vtkMetaDataSetSequence* sequence, int& layer) {
if (itk::Image<TYPE,4>* image = dynamic_cast<itk::Image<TYPE,4>*>(static_cast<itk::Object*>(data->data()))) {
medVtkViewBackend* backend = static_cast<medVtkViewBackend*>(view->backend());
sequence->SetITKDataSet<TYPE>(image);
vtkMetaImageData* metaimage = vtkMetaImageData::SafeDownCast(sequence->GetMetaDataSet(0U));
vtkImageData* vtkimage = vtkImageData::SafeDownCast(sequence->GetDataSet());
backend->view2D->SetInput(vtkimage,metaimage->GetOrientationMatrix(), layer);
backend->view3D->SetInput(vtkimage,metaimage->GetOrientationMatrix(), layer);
layer = backend->view2D->GetNumberOfLayers()-1;
return true;
}
return false;
}
medVtkViewItkDataImage4DInteractor::medVtkViewItkDataImage4DInteractor(medAbstractView *parent):
medVtkViewItkDataImageInteractor(parent), d(new medVtkViewItkDataImage4DInteractorPrivate)
{
d->view = dynamic_cast<medAbstractImageView *>(parent);
medVtkViewBackend* backend = static_cast<medVtkViewBackend*>(parent->backend());
d->view2d = backend->view2D;
d->view3d = backend->view3D;
d->render = backend->renWin;
d->currentTime = 0.0;
}
medVtkViewItkDataImage4DInteractor::~medVtkViewItkDataImage4DInteractor()
{
}
QString medVtkViewItkDataImage4DInteractor::description() const
{
return tr("Interactor displaying 4D Meshes");
}
QString medVtkViewItkDataImage4DInteractor::identifier() const
{
return "medVtkViewItkDataImage4DInteractor";
}
QStringList medVtkViewItkDataImage4DInteractor::handled() const
{
return medVtkViewItkDataImage4DInteractor::dataHandled();
}
QStringList medVtkViewItkDataImage4DInteractor::dataHandled()
{
QStringList d = QStringList() << "itkDataImageChar4"
<< "itkDataImageUChar4"
<< "itkDataImageShort4"
<< "itkDataImageUShort4"
<< "itkDataImageInt4"
<< "itkDataImageLong4"
<< "itkDataImageULong4"
<< "itkDataImageFloat4"
<< "itkDataImageDouble4";
return d;
}
bool medVtkViewItkDataImage4DInteractor::registered()
{
medViewFactory *factory = medViewFactory::instance();
return factory->registerInteractor<medVtkViewItkDataImage4DInteractor>("medVtkViewItkDataImage4DInteractor",
QStringList () << "medVtkView" <<
medVtkViewItkDataImage4DInteractor::dataHandled());
}
void medVtkViewItkDataImage4DInteractor::setData(medAbstractData *data)
{
d->imageData = dynamic_cast<medAbstractImageData *>(data);
if(!d->imageData)
return;
if( data->identifier().contains("itkDataImage") && d->imageData->Dimension() == 4 ) {
d->sequence = vtkMetaDataSetSequence::New();
int layer = d->view->layer(data);
if ( AppendImageSequence<char>(data,d->view,d->sequence, layer) ||
AppendImageSequence<unsigned char>(data,d->view,d->sequence, layer) ||
AppendImageSequence<short>(data,d->view,d->sequence, layer) ||
AppendImageSequence<unsigned short>(data,d->view,d->sequence, layer) ||
AppendImageSequence<int>(data,d->view,d->sequence, layer) ||
AppendImageSequence<unsigned int>(data,d->view,d->sequence, layer) ||
AppendImageSequence<long>(data,d->view,d->sequence, layer) ||
AppendImageSequence<unsigned long>(data,d->view,d->sequence, layer) ||
AppendImageSequence<float>(data,d->view,d->sequence, layer) ||
AppendImageSequence<double>(data,d->view,d->sequence, layer))
{
d->imageData->addMetaData("SequenceDuration", QString::number(d->sequence->GetMaxTime()));
d->imageData->addMetaData("SequenceFrameRate", QString::number((double)d->sequence->GetNumberOfMetaDataSets() /
(double)d->sequence->GetMaxTime()));
qDebug() << "SequenceDuration" << d->sequence->GetMaxTime();
qDebug() << "SequenceFrameRate" <<(double)d->sequence->GetNumberOfMetaDataSets() / (double)d->sequence->GetMaxTime();
d->view2d->GetImageActor(d->view2d->GetCurrentLayer())->GetProperty()->SetInterpolationTypeToCubic();
initParameters(d->imageData);
if(d->view->layer(d->imageData) == 0)
{
switch(d->view2d->GetViewOrientation())
{
case vtkImageView2D::VIEW_ORIENTATION_AXIAL:
d->view->setOrientation(medImageView::VIEW_ORIENTATION_AXIAL);
break;
case vtkImageView2D::VIEW_ORIENTATION_SAGITTAL:
d->view->setOrientation(medImageView::VIEW_ORIENTATION_SAGITTAL);
break;
case vtkImageView2D::VIEW_ORIENTATION_CORONAL:
d->view->setOrientation(medImageView::VIEW_ORIENTATION_CORONAL);
break;
}
}
}
}
}
medAbstractData *medVtkViewItkDataImage4DInteractor::data() const
{
return d->imageData;
}
QWidget* medVtkViewItkDataImage4DInteractor::buildToolBoxWidget()
{
QWidget *toolBoxWidget = new QWidget;
QVBoxLayout *tbLayout = new QVBoxLayout(toolBoxWidget);
tbLayout->addWidget(medVtkViewItkDataImageInteractor::buildToolBoxWidget());
return toolBoxWidget;
}
QWidget* medVtkViewItkDataImage4DInteractor::buildToolBarWidget()
{
return medVtkViewItkDataImageInteractor::buildToolBarWidget();
}
QWidget* medVtkViewItkDataImage4DInteractor::buildLayerWidget()
{
return medVtkViewItkDataImageInteractor::buildLayerWidget();
}
QList<medAbstractParameter*> medVtkViewItkDataImage4DInteractor::linkableParameters()
{
QList<medAbstractParameter*> parameters;
parameters << medVtkViewItkDataImageInteractor::linkableParameters();
return parameters;
}
void medVtkViewItkDataImage4DInteractor::setCurrentTime(double time)
{
if(d->sequence->GetTime() == time)
return;
d->sequence->UpdateToTime(time);
}
void medVtkViewItkDataImage4DInteractor::updateWidgets()
{
medVtkViewItkDataImageInteractor::updateWidgets();
}
|
Add support for int and long pixel type of itkImageData4
|
Add support for int and long pixel type of itkImageData4
|
C++
|
bsd-3-clause
|
rdebroiz/medInria-public,aabadie/medInria-public,NicolasSchnitzler/medInria-public,NicolasSchnitzler/medInria-public,rdebroiz/medInria-public,aabadie/medInria-public,rdebroiz/medInria-public,NicolasSchnitzler/medInria-public,aabadie/medInria-public
|
3270289674655e945bfe3f47007a133b22fd5c8e
|
MMCore/Devices/DeviceInstance.cpp
|
MMCore/Devices/DeviceInstance.cpp
|
// PROJECT: Micro-Manager
// SUBSYSTEM: MMCore
//
// DESCRIPTION: Base class for wrapped device objects
//
// COPYRIGHT: University of California, San Francisco, 2014,
// All Rights reserved
//
// LICENSE: This file is distributed under the "Lesser GPL" (LGPL) license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR: Mark Tsuchida
#include "DeviceInstance.h"
#include "../../MMDevice/MMDevice.h"
#include "../CoreUtils.h"
#include "../Error.h"
#include "../LoadableModules/LoadedDeviceAdapter.h"
#include "../MMCore.h"
DeviceInstance::DeviceInstance(CMMCore* core,
boost::shared_ptr<LoadedDeviceAdapter> adapter,
const std::string& name,
MM::Device* pDevice,
DeleteDeviceFunction deleteFunction,
const std::string& label) :
core_(core),
adapter_(adapter),
label_(label),
deleteFunction_(deleteFunction),
pImpl_(pDevice)
{
const std::string actualName = GetName();
if (actualName != name)
{
deleteFunction_(pImpl_);
throw CMMError("Requested device " + ToQuotedString(name) +
" from device adapter " + ToQuotedString(adapter->GetName()) +
" but got an instance named " + ToQuotedString(actualName));
}
}
DeviceInstance::~DeviceInstance()
{
// TODO Should we call Shutdown here? Or check that we have done so?
deleteFunction_(pImpl_);
}
void
DeviceInstance::DeviceStringBuffer::ThrowBufferOverflowError() const
{
// TODO Log the error before crashing
std::string label(instance_ ? instance_->GetLabel() : "<unknown>");
throw CMMError("Buffer overflow in device " + ToQuotedString(label) +
" while calling " + funcName_ + "(); this is a bug in the device adapter");
}
std::vector<std::string>
DeviceInstance::GetPropertyNames() const
{
std::vector<std::string> result;
size_t nrProperties = GetNumberOfProperties();
result.reserve(nrProperties);
for (size_t i = 0; i < nrProperties; ++i)
result.push_back(GetPropertyName(i));
return result;
}
unsigned
DeviceInstance::GetNumberOfProperties() const
{ return pImpl_->GetNumberOfProperties(); }
int
DeviceInstance::GetProperty(const char* name, char* value) const
{ return pImpl_->GetProperty(name, value); }
int
DeviceInstance::SetProperty(const char* name, const char* value) const
{ return pImpl_->SetProperty(name, value); }
bool
DeviceInstance::HasProperty(const char* name) const
{ return pImpl_->HasProperty(name); }
std::string
DeviceInstance::GetPropertyName(size_t idx) const
{
DeviceStringBuffer nameBuf(this, "GetPropertyName");
bool ok = pImpl_->GetPropertyName(static_cast<unsigned>(idx), nameBuf.GetBuffer());
if (!ok)
throw CMMError("Cannot get property name at index " + ToString(idx));
return nameBuf.Get();
}
int
DeviceInstance::GetPropertyReadOnly(const char* name, bool& readOnly) const
{ return pImpl_->GetPropertyReadOnly(name, readOnly); }
int
DeviceInstance::GetPropertyInitStatus(const char* name, bool& preInit) const
{ return pImpl_->GetPropertyInitStatus(name, preInit); }
int
DeviceInstance::HasPropertyLimits(const char* name, bool& hasLimits) const
{ return pImpl_->HasPropertyLimits(name, hasLimits); }
int
DeviceInstance::GetPropertyLowerLimit(const char* name, double& lowLimit) const
{ return pImpl_->GetPropertyLowerLimit(name, lowLimit); }
int
DeviceInstance::GetPropertyUpperLimit(const char* name, double& hiLimit) const
{ return pImpl_->GetPropertyUpperLimit(name, hiLimit); }
int
DeviceInstance::GetPropertyType(const char* name, MM::PropertyType& pt) const
{ return pImpl_->GetPropertyType(name, pt); }
unsigned
DeviceInstance::GetNumberOfPropertyValues(const char* propertyName) const
{ return pImpl_->GetNumberOfPropertyValues(propertyName); }
bool
DeviceInstance::GetPropertyValueAt(const char* propertyName, unsigned index, char* value) const
{ return pImpl_->GetPropertyValueAt(propertyName, index, value); }
int
DeviceInstance::IsPropertySequenceable(const char* name, bool& isSequenceable) const
{ return pImpl_->IsPropertySequenceable(name, isSequenceable); }
int
DeviceInstance::GetPropertySequenceMaxLength(const char* propertyName, long& nrEvents) const
{ return pImpl_->GetPropertySequenceMaxLength(propertyName, nrEvents); }
int
DeviceInstance::StartPropertySequence(const char* propertyName)
{ return pImpl_->StartPropertySequence(propertyName); }
int
DeviceInstance::StopPropertySequence(const char* propertyName)
{ return pImpl_->StopPropertySequence(propertyName); }
int
DeviceInstance::ClearPropertySequence(const char* propertyName)
{ return pImpl_->ClearPropertySequence(propertyName); }
int
DeviceInstance::AddToPropertySequence(const char* propertyName, const char* value)
{ return pImpl_->AddToPropertySequence(propertyName, value); }
int
DeviceInstance::SendPropertySequence(const char* propertyName)
{ return pImpl_->SendPropertySequence(propertyName); }
bool
DeviceInstance::GetErrorText(int errorCode, char* errMessage) const
{ return pImpl_->GetErrorText(errorCode, errMessage); }
bool
DeviceInstance::Busy()
{ return pImpl_->Busy(); }
double
DeviceInstance::GetDelayMs() const
{ return pImpl_->GetDelayMs(); }
void
DeviceInstance::SetDelayMs(double delay)
{ return pImpl_->SetDelayMs(delay); }
bool
DeviceInstance::UsesDelay()
{ return pImpl_->UsesDelay(); }
int
DeviceInstance::Initialize()
{ return pImpl_->Initialize(); }
int
DeviceInstance::Shutdown()
{ return pImpl_->Shutdown(); }
MM::DeviceType
DeviceInstance::GetType() const
{ return pImpl_->GetType(); }
std::string
DeviceInstance::GetName() const
{
DeviceStringBuffer nameBuf(this, "GetName");
pImpl_->GetName(nameBuf.GetBuffer());
return nameBuf.Get();
}
void
DeviceInstance::SetCallback(MM::Core* callback)
{ return pImpl_->SetCallback(callback); }
int
DeviceInstance::AcqBefore()
{ return pImpl_->AcqBefore(); }
int
DeviceInstance::AcqAfter()
{ return pImpl_->AcqAfter(); }
int
DeviceInstance::AcqBeforeFrame()
{ return pImpl_->AcqBeforeFrame(); }
int
DeviceInstance::AcqAfterFrame()
{ return pImpl_->AcqAfterFrame(); }
int
DeviceInstance::AcqBeforeStack()
{ return pImpl_->AcqBeforeStack(); }
int
DeviceInstance::AcqAfterStack()
{ return pImpl_->AcqAfterStack(); }
MM::DeviceDetectionStatus
DeviceInstance::DetectDevice()
{ return pImpl_->DetectDevice(); }
void
DeviceInstance::SetParentID(const char* parentId)
{ return pImpl_->SetParentID(parentId); }
void
DeviceInstance::GetParentID(char* parentID) const
{ return pImpl_->GetParentID(parentID); }
|
// PROJECT: Micro-Manager
// SUBSYSTEM: MMCore
//
// DESCRIPTION: Base class for wrapped device objects
//
// COPYRIGHT: University of California, San Francisco, 2014,
// All Rights reserved
//
// LICENSE: This file is distributed under the "Lesser GPL" (LGPL) license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR: Mark Tsuchida
#include "DeviceInstance.h"
#include "../../MMDevice/MMDevice.h"
#include "../CoreUtils.h"
#include "../Error.h"
#include "../LoadableModules/LoadedDeviceAdapter.h"
#include "../MMCore.h"
DeviceInstance::DeviceInstance(CMMCore* core,
boost::shared_ptr<LoadedDeviceAdapter> adapter,
const std::string& name,
MM::Device* pDevice,
DeleteDeviceFunction deleteFunction,
const std::string& label) :
core_(core),
adapter_(adapter),
label_(label),
deleteFunction_(deleteFunction),
pImpl_(pDevice)
{
const std::string actualName = GetName();
if (actualName != name)
{
deleteFunction_(pImpl_);
throw CMMError("Requested device " + ToQuotedString(name) +
" from device adapter " + ToQuotedString(adapter->GetName()) +
" but got an instance named " + ToQuotedString(actualName));
}
pImpl_->SetLabel(label_.c_str());
}
DeviceInstance::~DeviceInstance()
{
// TODO Should we call Shutdown here? Or check that we have done so?
deleteFunction_(pImpl_);
}
void
DeviceInstance::DeviceStringBuffer::ThrowBufferOverflowError() const
{
// TODO Log the error before crashing
std::string label(instance_ ? instance_->GetLabel() : "<unknown>");
throw CMMError("Buffer overflow in device " + ToQuotedString(label) +
" while calling " + funcName_ + "(); this is a bug in the device adapter");
}
std::vector<std::string>
DeviceInstance::GetPropertyNames() const
{
std::vector<std::string> result;
size_t nrProperties = GetNumberOfProperties();
result.reserve(nrProperties);
for (size_t i = 0; i < nrProperties; ++i)
result.push_back(GetPropertyName(i));
return result;
}
unsigned
DeviceInstance::GetNumberOfProperties() const
{ return pImpl_->GetNumberOfProperties(); }
int
DeviceInstance::GetProperty(const char* name, char* value) const
{ return pImpl_->GetProperty(name, value); }
int
DeviceInstance::SetProperty(const char* name, const char* value) const
{ return pImpl_->SetProperty(name, value); }
bool
DeviceInstance::HasProperty(const char* name) const
{ return pImpl_->HasProperty(name); }
std::string
DeviceInstance::GetPropertyName(size_t idx) const
{
DeviceStringBuffer nameBuf(this, "GetPropertyName");
bool ok = pImpl_->GetPropertyName(static_cast<unsigned>(idx), nameBuf.GetBuffer());
if (!ok)
throw CMMError("Cannot get property name at index " + ToString(idx));
return nameBuf.Get();
}
int
DeviceInstance::GetPropertyReadOnly(const char* name, bool& readOnly) const
{ return pImpl_->GetPropertyReadOnly(name, readOnly); }
int
DeviceInstance::GetPropertyInitStatus(const char* name, bool& preInit) const
{ return pImpl_->GetPropertyInitStatus(name, preInit); }
int
DeviceInstance::HasPropertyLimits(const char* name, bool& hasLimits) const
{ return pImpl_->HasPropertyLimits(name, hasLimits); }
int
DeviceInstance::GetPropertyLowerLimit(const char* name, double& lowLimit) const
{ return pImpl_->GetPropertyLowerLimit(name, lowLimit); }
int
DeviceInstance::GetPropertyUpperLimit(const char* name, double& hiLimit) const
{ return pImpl_->GetPropertyUpperLimit(name, hiLimit); }
int
DeviceInstance::GetPropertyType(const char* name, MM::PropertyType& pt) const
{ return pImpl_->GetPropertyType(name, pt); }
unsigned
DeviceInstance::GetNumberOfPropertyValues(const char* propertyName) const
{ return pImpl_->GetNumberOfPropertyValues(propertyName); }
bool
DeviceInstance::GetPropertyValueAt(const char* propertyName, unsigned index, char* value) const
{ return pImpl_->GetPropertyValueAt(propertyName, index, value); }
int
DeviceInstance::IsPropertySequenceable(const char* name, bool& isSequenceable) const
{ return pImpl_->IsPropertySequenceable(name, isSequenceable); }
int
DeviceInstance::GetPropertySequenceMaxLength(const char* propertyName, long& nrEvents) const
{ return pImpl_->GetPropertySequenceMaxLength(propertyName, nrEvents); }
int
DeviceInstance::StartPropertySequence(const char* propertyName)
{ return pImpl_->StartPropertySequence(propertyName); }
int
DeviceInstance::StopPropertySequence(const char* propertyName)
{ return pImpl_->StopPropertySequence(propertyName); }
int
DeviceInstance::ClearPropertySequence(const char* propertyName)
{ return pImpl_->ClearPropertySequence(propertyName); }
int
DeviceInstance::AddToPropertySequence(const char* propertyName, const char* value)
{ return pImpl_->AddToPropertySequence(propertyName, value); }
int
DeviceInstance::SendPropertySequence(const char* propertyName)
{ return pImpl_->SendPropertySequence(propertyName); }
bool
DeviceInstance::GetErrorText(int errorCode, char* errMessage) const
{ return pImpl_->GetErrorText(errorCode, errMessage); }
bool
DeviceInstance::Busy()
{ return pImpl_->Busy(); }
double
DeviceInstance::GetDelayMs() const
{ return pImpl_->GetDelayMs(); }
void
DeviceInstance::SetDelayMs(double delay)
{ return pImpl_->SetDelayMs(delay); }
bool
DeviceInstance::UsesDelay()
{ return pImpl_->UsesDelay(); }
int
DeviceInstance::Initialize()
{ return pImpl_->Initialize(); }
int
DeviceInstance::Shutdown()
{ return pImpl_->Shutdown(); }
MM::DeviceType
DeviceInstance::GetType() const
{ return pImpl_->GetType(); }
std::string
DeviceInstance::GetName() const
{
DeviceStringBuffer nameBuf(this, "GetName");
pImpl_->GetName(nameBuf.GetBuffer());
return nameBuf.Get();
}
void
DeviceInstance::SetCallback(MM::Core* callback)
{ return pImpl_->SetCallback(callback); }
int
DeviceInstance::AcqBefore()
{ return pImpl_->AcqBefore(); }
int
DeviceInstance::AcqAfter()
{ return pImpl_->AcqAfter(); }
int
DeviceInstance::AcqBeforeFrame()
{ return pImpl_->AcqBeforeFrame(); }
int
DeviceInstance::AcqAfterFrame()
{ return pImpl_->AcqAfterFrame(); }
int
DeviceInstance::AcqBeforeStack()
{ return pImpl_->AcqBeforeStack(); }
int
DeviceInstance::AcqAfterStack()
{ return pImpl_->AcqAfterStack(); }
MM::DeviceDetectionStatus
DeviceInstance::DetectDevice()
{ return pImpl_->DetectDevice(); }
void
DeviceInstance::SetParentID(const char* parentId)
{ return pImpl_->SetParentID(parentId); }
void
DeviceInstance::GetParentID(char* parentID) const
{ return pImpl_->GetParentID(parentID); }
|
Set label in raw device instance.
|
Set label in raw device instance.
This is required because many devices depend on being able to get the
label using their own MM::Device::GetLabel() as implemented in
CDeviceBase. In particular, this fixes MultiCamera.
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@13487 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
|
C++
|
mit
|
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
|
f6c3e97b8907856ee671db1e598186fdb4697c89
|
test/ofp/hello_unittest.cpp
|
test/ofp/hello_unittest.cpp
|
#include "ofp/unittest.h"
#include "ofp/hello.h"
using namespace ofp;
TEST(hello, HelloBuilder1) {
HelloBuilder msg{ProtocolVersions{1, 2, 3, 4}};
MemoryChannel channel{99};
msg.send(&channel);
EXPECT_EQ(0x10, channel.size());
EXPECT_HEX("0400-0010-00000001 00010008-0000001E", channel.data(),
channel.size());
}
TEST(hello, HelloBuilder2) {
HelloBuilder msg{ProtocolVersions{1, 4}};
MemoryChannel channel{OFP_VERSION_1};
msg.send(&channel);
EXPECT_EQ(0x10, channel.size());
EXPECT_HEX("0400-0010-00000001 00010008-00000012", channel.data(),
channel.size());
}
TEST(hello, HelloBuilder3) {
HelloBuilder msg{ProtocolVersions{1}};
MemoryChannel channel{OFP_VERSION_4};
msg.send(&channel);
EXPECT_EQ(0x08, channel.size());
EXPECT_HEX("0100-0008-00000001", channel.data(), channel.size());
}
|
#include "ofp/unittest.h"
#include "ofp/hello.h"
using namespace ofp;
TEST(hello, HelloBuilder1) {
HelloBuilder msg{ProtocolVersions{1, 2, 3, 4}};
MemoryChannel channel{99};
msg.send(&channel);
EXPECT_EQ(0x10, channel.size());
EXPECT_HEX("0400-0010-00000001 00010008-0000001E", channel.data(),
channel.size());
}
TEST(hello, HelloBuilder2) {
HelloBuilder msg{ProtocolVersions{1, 4}};
MemoryChannel channel{OFP_VERSION_1};
msg.send(&channel);
EXPECT_EQ(0x10, channel.size());
EXPECT_HEX("0400-0010-00000001 00010008-00000012", channel.data(),
channel.size());
}
TEST(hello, HelloBuilder3) {
HelloBuilder msg{ProtocolVersions{1}};
MemoryChannel channel{OFP_VERSION_4};
msg.send(&channel);
EXPECT_EQ(0x08, channel.size());
EXPECT_HEX("0100-0008-00000001", channel.data(), channel.size());
}
TEST(hello, HelloBuilder4) {
HelloBuilder msg{OFP_VERSION_1};
MemoryChannel channel{0};
msg.send(&channel);
EXPECT_EQ(0x08, channel.size());
EXPECT_HEX("0100-0008-00000001", channel.data(), channel.size());
}
|
Add a HelloBuilder unit test.
|
Add a HelloBuilder unit test.
|
C++
|
mit
|
byllyfish/oftr,byllyfish/libofp,byllyfish/oftr,byllyfish/libofp,byllyfish/oftr,byllyfish/libofp,byllyfish/oftr,byllyfish/oftr
|
6c0c892bc33e83017651973b482073208ea9c4f6
|
src/Model.cpp
|
src/Model.cpp
|
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "Model.h"
#include "Mesh.h"
#include "Vertex.h"
using namespace eyesore;
using namespace glm;
using std::string;
using std::vector;
eyesore::Model::Model(const string &path)
{
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate);
for (int i = 0; i < scene->mNumMeshes; i++)
meshes.push_back(extractMesh(scene->mMeshes[i]));
}
void eyesore::Model::render() const
{
for (const Mesh &mesh : meshes)
mesh.render();
}
eyesore::Mesh eyesore::Model::extractMesh(const aiMesh *mesh)
{
vector<Vertex> vertices;
vector<GLuint> indices;
for (int i = 0; i < mesh->mNumVertices; i++) {
aiVector3D pos = mesh->mVertices[i];
aiVector3D uv = mesh->mTextureCoords[0][i];
if (mesh->HasNormals()) {
aiVector3D norm = mesh->mNormals[i];
vertices.push_back(Vertex(vec3(pos.x, pos.y, pos.z),
vec3(norm.x, norm.y, norm.z),
vec2(uv.x, uv.y)));
} else {
vertices.push_back(Vertex(vec3(pos.x, pos.y, pos.z), vec2(uv.x, uv.y)));
}
}
if (mesh->HasFaces())
for (int i = 0; i < mesh->mNumFaces; i++) {
aiFace face = mesh->mFaces[i];
for (int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
return Mesh(vertices, indices);
}
|
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "Model.h"
#include "Mesh.h"
#include "Vertex.h"
#include "Shader.h"
#include "ShaderProgram.h"
using namespace eyesore;
using namespace glm;
using std::string;
using std::vector;
eyesore::Model::Model(const string &path)
{
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate);
for (int i = 0; i < scene->mNumMeshes; i++)
meshes.push_back(extractMesh(scene->mMeshes[i]));
Shader vert("../shaders/vert.glsl", GL_VERTEX_SHADER);
Shader frag("../shaders/frag.glsl", GL_FRAGMENT_SHADER);
ShaderProgram shader;
shader.attach(vert);
shader.attach(frag);
for (Mesh &mesh : meshes)
mesh.setShader(shader);
}
void eyesore::Model::render() const
{
for (const Mesh &mesh : meshes)
mesh.render();
}
eyesore::Mesh eyesore::Model::extractMesh(const aiMesh *mesh)
{
vector<Vertex> vertices;
vector<GLuint> indices;
for (int i = 0; i < mesh->mNumVertices; i++) {
aiVector3D pos = mesh->mVertices[i];
aiVector3D uv = mesh->mTextureCoords[0][i];
if (mesh->HasNormals()) {
aiVector3D norm = mesh->mNormals[i];
vertices.push_back(Vertex(vec3(pos.x, pos.y, pos.z),
vec3(norm.x, norm.y, norm.z),
vec2(uv.x, uv.y)));
} else {
vertices.push_back(Vertex(vec3(pos.x, pos.y, pos.z), vec2(uv.x, uv.y)));
}
}
if (mesh->HasFaces())
for (int i = 0; i < mesh->mNumFaces; i++) {
aiFace face = mesh->mFaces[i];
for (int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
return Mesh(vertices, indices);
}
|
Use temporary shaders for testing
|
Use temporary shaders for testing
|
C++
|
mit
|
kartik-s/eyesore,kartik-s/eyesore
|
6e7239cfd23c32499134800b700140a5da26bcfe
|
src/mlpack/methods/ann/layer/dropout_layer.hpp
|
src/mlpack/methods/ann/layer/dropout_layer.hpp
|
/**
* @file dropout_layer.hpp
* @author Marcus Edel
*
* Definition of the DropoutLayer class, which implements a regularizer that
* randomly sets units to zero. Preventing units from co-adapting.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_DROPOUT_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_DROPOUT_LAYER_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* The dropout layer is a regularizer that randomly with probability ratio
* sets input values to zero and scales the remaining elements by factor 1 /
* (1 - ratio). If rescale is true the input is scaled with 1 / (1-p) when
* deterministic is false. In the deterministic mode (during testing), the layer
* just scales the output.
*
* Note: During training you should set deterministic to false and during
* testing you should set deterministic to true.
*
* For more information, see the following.
*
* @code
* @article{Hinton2012,
* author = {Geoffrey E. Hinton, Nitish Srivastava, Alex Krizhevsky,
* Ilya Sutskever, Ruslan Salakhutdinov},
* title = {Improving neural networks by preventing co-adaptation of feature
* detectors},
* journal = {CoRR},
* volume = {abs/1207.0580},
* year = {2012},
* }
* @endcode
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class DropoutLayer
{
public:
/**
* Create the BaseLayer object using the specified number of units.
*
* @param outSize The number of output units.
*/
DropoutLayer(const double ratio = 0.5,
const bool rescale = true) :
ratio(ratio),
rescale(rescale)
{
// Nothing to do here.
}
/**
* Ordinary feed forward pass of the dropout layer.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
// The dropout mask will not be multiplied in the deterministic mode
// (during testing).
if (deterministic)
{
output = input;
if (rescale)
output *= scale;
}
else
{
// Scale with input / (1 - ratio) and set values to zero with probability
// ratio.
scale = 1.0 / (1.0 - ratio);
mask = arma::randu<arma::Mat<eT> >(input.n_rows, input.n_cols);
mask.transform( [&](double val) { return (val > ratio); } );
output = input % mask * scale;
}
}
/**
* Ordinary feed forward pass of the dropout layer.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
// The dropout mask will not be multiplied in the deterministic mode
// (during testing).
if (deterministic)
{
output = input;
if (rescale)
output *= scale;
}
else
{
// Scale with input / (1 - ratio) and set values to zero with probability
// ratio.
scale = 1.0 / (1.0 - ratio);
mask = arma::randu<arma::Cube<eT> >(input.n_rows, input.n_cols,
input.n_slices);
mask.transform( [&](double val) { return (val > ratio); } );
output = input % mask * scale;
}
}
/**
* Ordinary feed backward pass of the dropout layer.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename DataType>
void Backward(const DataType& /* unused */,
const DataType& gy,
DataType& g)
{
g = gy % mask * scale;
}
//! Get the input parameter.
InputDataType& InputParameter() const {return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const {return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the detla.
OutputDataType& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! The value of the deterministic parameter.
bool Deterministic() const {return deterministic; }
//! Modify the value of the deterministic parameter.
bool& Deterministic() {return deterministic; }
//! The probability of setting a value to zero.
double Ratio() const {return ratio; }
//! Modify the probability of setting a value to zero.
double& Ratio() {return ratio; }
//! The value of the rescale parameter.
bool Rescale() const {return rescale; }
//! Modify the value of the rescale parameter.
bool& Rescale() {return rescale; }
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
//! Locally-stored mast object.
OutputDataType mask;
//! The probability of setting a value to zero.
double ratio;
//! The scale fraction.
double scale;
//! If true dropout and scaling is disabled, see notes above.
bool deterministic;
//! If true the input is rescaled when deterministic is False.
bool rescale;
}; // class DropoutLayer
//! Layer traits for the bias layer.
template <
typename InputDataType,
typename OutputDataType
>
class LayerTraits<DropoutLayer<InputDataType, OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = false;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
/**
* Standard Dropout-Layer2D.
*/
template <
typename InputDataType = arma::cube,
typename OutputDataType = arma::cube
>
using DropoutLayer2D = DropoutLayer<InputDataType, OutputDataType>;
}; // namespace ann
}; // namespace mlpack
#endif
|
/**
* @file dropout_layer.hpp
* @author Marcus Edel
*
* Definition of the DropoutLayer class, which implements a regularizer that
* randomly sets units to zero. Preventing units from co-adapting.
*/
#ifndef __MLPACK_METHODS_ANN_LAYER_DROPOUT_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_DROPOUT_LAYER_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* The dropout layer is a regularizer that randomly with probability ratio
* sets input values to zero and scales the remaining elements by factor 1 /
* (1 - ratio). If rescale is true the input is scaled with 1 / (1-p) when
* deterministic is false. In the deterministic mode (during testing), the layer
* just scales the output.
*
* Note: During training you should set deterministic to false and during
* testing you should set deterministic to true.
*
* For more information, see the following.
*
* @code
* @article{Hinton2012,
* author = {Geoffrey E. Hinton, Nitish Srivastava, Alex Krizhevsky,
* Ilya Sutskever, Ruslan Salakhutdinov},
* title = {Improving neural networks by preventing co-adaptation of feature
* detectors},
* journal = {CoRR},
* volume = {abs/1207.0580},
* year = {2012},
* }
* @endcode
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class DropoutLayer
{
public:
/**
* Create the BaseLayer object using the specified number of units.
*
* @param outSize The number of output units.
*/
DropoutLayer(const double ratio = 0.5,
const bool rescale = true) :
ratio(ratio),
rescale(rescale),
scale(1.0 / (1.0 - ratio))
{
// Nothing to do here.
}
/**
* Ordinary feed forward pass of the dropout layer.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
// The dropout mask will not be multiplied in the deterministic mode
// (during testing).
if (deterministic)
{
output = input;
if (rescale)
output *= scale;
}
else
{
// Scale with input / (1 - ratio) and set values to zero with probability
// ratio.
scale = 1.0 / (1.0 - ratio);
mask = arma::randu<arma::Mat<eT> >(input.n_rows, input.n_cols);
mask.transform( [&](double val) { return (val > ratio); } );
output = input % mask * scale;
}
}
/**
* Ordinary feed forward pass of the dropout layer.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename eT>
void Forward(const arma::Cube<eT>& input, arma::Cube<eT>& output)
{
// The dropout mask will not be multiplied in the deterministic mode
// (during testing).
if (deterministic)
{
output = input;
if (rescale)
output *= scale;
}
else
{
// Scale with input / (1 - ratio) and set values to zero with probability
// ratio.
scale = 1.0 / (1.0 - ratio);
mask = arma::randu<arma::Cube<eT> >(input.n_rows, input.n_cols,
input.n_slices);
mask.transform( [&](double val) { return (val > ratio); } );
output = input % mask * scale;
}
}
/**
* Ordinary feed backward pass of the dropout layer.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename DataType>
void Backward(const DataType& /* unused */,
const DataType& gy,
DataType& g)
{
g = gy % mask * scale;
}
//! Get the input parameter.
InputDataType& InputParameter() const {return inputParameter; }
//! Modify the input parameter.
InputDataType& InputParameter() { return inputParameter; }
//! Get the output parameter.
OutputDataType& OutputParameter() const {return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the detla.
OutputDataType& Delta() const { return delta; }
//! Modify the delta.
OutputDataType& Delta() { return delta; }
//! The value of the deterministic parameter.
bool Deterministic() const {return deterministic; }
//! Modify the value of the deterministic parameter.
bool& Deterministic() {return deterministic; }
//! The probability of setting a value to zero.
double Ratio() const {return ratio; }
//! Modify the probability of setting a value to zero.
double& Ratio() {return ratio; }
//! The value of the rescale parameter.
bool Rescale() const {return rescale; }
//! Modify the value of the rescale parameter.
bool& Rescale() {return rescale; }
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored input parameter object.
InputDataType inputParameter;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
//! Locally-stored mast object.
OutputDataType mask;
//! The probability of setting a value to zero.
double ratio;
//! The scale fraction.
double scale;
//! If true dropout and scaling is disabled, see notes above.
bool deterministic;
//! If true the input is rescaled when deterministic is False.
bool rescale;
}; // class DropoutLayer
//! Layer traits for the bias layer.
template <
typename InputDataType,
typename OutputDataType
>
class LayerTraits<DropoutLayer<InputDataType, OutputDataType> >
{
public:
static const bool IsBinary = false;
static const bool IsOutputLayer = false;
static const bool IsBiasLayer = false;
static const bool IsLSTMLayer = false;
static const bool IsConnection = true;
};
/**
* Standard Dropout-Layer2D.
*/
template <
typename InputDataType = arma::cube,
typename OutputDataType = arma::cube
>
using DropoutLayer2D = DropoutLayer<InputDataType, OutputDataType>;
}; // namespace ann
}; // namespace mlpack
#endif
|
fix bug--forgot to initialize parameter scale
|
fix bug--forgot to initialize parameter scale
|
C++
|
bsd-3-clause
|
stereomatchingkiss/mlpack,palashahuja/mlpack,stereomatchingkiss/mlpack,ranjan1990/mlpack,darcyliu/mlpack,ranjan1990/mlpack,darcyliu/mlpack,ajjl/mlpack,ajjl/mlpack,darcyliu/mlpack,ranjan1990/mlpack,theranger/mlpack,palashahuja/mlpack,palashahuja/mlpack,stereomatchingkiss/mlpack,theranger/mlpack,theranger/mlpack,ajjl/mlpack
|
bec9fc973ccf812c5226d425aca893ca62029897
|
OpenSim/Common/APDMDataReader.cpp
|
OpenSim/Common/APDMDataReader.cpp
|
#include <fstream>
#include "Simbody.h"
#include "Exception.h"
#include "FileAdapter.h"
#include "TimeSeriesTable.h"
#include "APDMDataReader.h"
namespace OpenSim {
const std::string APDMDataReader::Orientations{ "orientations" };
const std::string APDMDataReader::LinearAccelerations{ "linear_accelerations" };
const std::string APDMDataReader::MagneticHeading{ "magnetic_heading" };
const std::string APDMDataReader::AngularVelocity{ "angular_velocity" };
const std::vector<std::string> APDMDataReader::acceleration_labels{
"/Acceleration/X", "/Acceleration/Y", "/Acceleration/Z"
};
const std::vector<std::string> APDMDataReader::angular_velocity_labels{
"/Angular Velocity/X", "/Angular Velocity/Y","/Angular Velocity/Z"
};
const std::vector<std::string> APDMDataReader::magnetic_heading_labels{
"/Magnetic Field/X", "/Magnetic Field/Y","/Magnetic Field/Z"
};
const std::vector<std::string> APDMDataReader::orientation_labels{
"/Orientation/Scalar", "/Orientation/X", "/Orientation/Y","/Orientation/Z"
};
const std::string APDMDataReader::TimeLabel{ "Time" };
APDMDataReader* APDMDataReader::clone() const {
return new APDMDataReader{*this};
}
DataAdapter::OutputTables
APDMDataReader::readFile(const std::string& fileName) const {
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ifstream in_stream{ fileName };
OPENSIM_THROW_IF(!in_stream.good(),
FileDoesNotExist,
fileName);
OPENSIM_THROW_IF(in_stream.peek() == std::ifstream::traits_type::eof(),
FileIsEmpty,
fileName);
std::vector<std::string> labels;
// files specified by prefix + file name exist
double dataRate = SimTK::NaN;
std::vector<int> accIndex;
std::vector<int> gyroIndex;
std::vector<int> magIndex;
std::vector<int> orientationsIndex;
int n_imus = _settings.getProperty_ExperimentalSensors().size();
int last_size = 1024;
// Will read data into pre-allocated Matrices in-memory rather than appendRow
// on the fly to avoid the overhead of
SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus };
SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus };
SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus };
SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus };
std::vector<double> times;
times.resize(last_size);
// Format looks like this:
// Header Line 1: Test Name:, $String,,,,,..
// Header Line 2: Sample Rate:, $Value, Hz,,,,,
// Labels Line 3: Time {SensorName/Acceleration/X,SensorName/Acceleration/Y,SensorName/Acceleration/Z,....} repeated per sensor
// Units Line 4: s,{m/s^2,m/s^2,m/s^2....} repeated
int header_lines = 4;
std::string line;
// Line 1
std::getline(in_stream, line);
std::vector<std::string> tokens = FileAdapter::tokenize(line, ",");
std::string trialName = tokens[1]; // May contain spaces
// Line 2
std::getline(in_stream, line);
tokens = FileAdapter::tokenize(line, ",");
dataRate = std::stod(tokens[1]);
// Line 3, find columns for IMUs
std::getline(in_stream, line);
tokens = FileAdapter::tokenize(line, ",");
OPENSIM_THROW_IF((tokens[0] != TimeLabel), UnexpectedColumnLabel,
fileName,
TimeLabel,
tokens[0]);
for (int imu_index = 0; imu_index < n_imus; ++imu_index) {
std::string sensorName = _settings.get_ExperimentalSensors(imu_index).getName();
labels.push_back(_settings.get_ExperimentalSensors(imu_index).get_name_in_model());
find_start_column(tokens, APDMDataReader::acceleration_labels, sensorName, accIndex);
find_start_column(tokens, APDMDataReader::angular_velocity_labels, sensorName, gyroIndex);
find_start_column(tokens, APDMDataReader::magnetic_heading_labels, sensorName, magIndex);
find_start_column(tokens, APDMDataReader::orientation_labels, sensorName, orientationsIndex);
}
// Will create a table to map
// internally keep track of what data was found in input files
bool foundLinearAccelerationData = accIndex.size()>0;
bool foundMagneticHeadingData = magIndex.size()>0;
bool foundAngularVelocityData = gyroIndex.size()>0;
// If no Orientation data is available or dataRate can't be deduced we'll abort completely
OPENSIM_THROW_IF((orientationsIndex.size() == 0 || SimTK::isNaN(dataRate)),
TableMissingHeader);
// Line 4, Units unused
std::getline(in_stream, line);
// For all tables, will create row, stitch values from different sensors then append
bool done = false;
double time = 0.0;
double timeIncrement = 1 / dataRate;
int rowNumber = 0;
while (!done){
// Make vectors one per table
TimeSeriesTableQuaternion::RowVector
orientation_row_vector{ n_imus, SimTK::Quaternion() };
TimeSeriesTableVec3::RowVector
accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
TimeSeriesTableVec3::RowVector
magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
TimeSeriesTableVec3::RowVector
gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
std::vector<std::string> nextRow = FileAdapter::getNextLine(in_stream, ",");
if (nextRow.empty()) {
done = true;
break;
}
// Cycle through the imus collating values
for (int imu_index = 0; imu_index < n_imus; ++imu_index) {
// parse gyro info from in_stream
if (foundLinearAccelerationData)
accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex[imu_index]]),
std::stod(nextRow[accIndex[imu_index] + 1]), std::stod(nextRow[accIndex[imu_index] + 2]));
if (foundMagneticHeadingData)
magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex[imu_index]]),
std::stod(nextRow[magIndex[imu_index] + 1]), std::stod(nextRow[magIndex[imu_index] + 2]));
if (foundAngularVelocityData)
gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex[imu_index]]),
std::stod(nextRow[gyroIndex[imu_index] + 1]), std::stod(nextRow[gyroIndex[imu_index] + 2]));
// Create Quaternion from values in file, assume order in file W, X, Y, Z
orientation_row_vector[imu_index] =
SimTK::Quaternion(std::stod(nextRow[orientationsIndex[imu_index]]),
std::stod(nextRow[orientationsIndex[imu_index] + 1]),
std::stod(nextRow[orientationsIndex[imu_index] + 2]),
std::stod(nextRow[orientationsIndex[imu_index] + 3]));
}
if (done)
break;
// append to the tables
times[rowNumber] = time;
if (foundLinearAccelerationData)
linearAccelerationData[rowNumber] = accel_row_vector;
if (foundMagneticHeadingData)
magneticHeadingData[rowNumber] = magneto_row_vector;
if (foundAngularVelocityData)
angularVelocityData[rowNumber] = gyro_row_vector;
rotationsData[rowNumber] = orientation_row_vector;
// We could get some indication of time from file or generate time based on rate
// Here we use the latter mechanism.
time += timeIncrement;
rowNumber++;
if (std::remainder(rowNumber, last_size) == 0) {
// resize all Data/Matrices, double the size while keeping data
int newSize = last_size*2;
times.resize(newSize);
// Repeat for Data matrices in use
if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus);
if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus);
if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus);
rotationsData.resizeKeep(newSize, n_imus);
last_size = newSize;
}
}
// Trim Matrices in use to actual data and move into tables
times.resize(rowNumber);
// Repeat for Data matrices in use and create Tables from them or size 0 for empty
linearAccelerationData.resizeKeep(foundLinearAccelerationData? rowNumber : 0,
n_imus);
magneticHeadingData.resizeKeep(foundMagneticHeadingData? rowNumber : 0,
n_imus);
angularVelocityData.resizeKeep(foundAngularVelocityData? rowNumber :0,
n_imus);
rotationsData.resizeKeep(rowNumber, n_imus);
// Now create the tables from matrices
// Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading
// Tables could be empty if data is not present in file(s)
DataAdapter::OutputTables tables{};
auto orientationTable = std::make_shared<TimeSeriesTableQuaternion>(times, rotationsData, labels);
orientationTable->updTableMetaData()
.setValueForKey("DataRate", std::to_string(dataRate));
tables.emplace(Orientations, orientationTable);
std::vector<double> emptyTimes;
auto accelerationTable = (foundLinearAccelerationData ?
std::make_shared<TimeSeriesTableVec3>(times, linearAccelerationData, labels) :
std::make_shared<TimeSeriesTableVec3>(emptyTimes, linearAccelerationData, labels));
accelerationTable->updTableMetaData()
.setValueForKey("DataRate", std::to_string(dataRate));
tables.emplace(LinearAccelerations, accelerationTable);
auto magneticHeadingTable = (foundMagneticHeadingData ?
std::make_shared<TimeSeriesTableVec3>(times, magneticHeadingData, labels) :
std::make_shared<TimeSeriesTableVec3>(emptyTimes, magneticHeadingData, labels));
magneticHeadingTable->updTableMetaData()
.setValueForKey("DataRate", std::to_string(dataRate));
tables.emplace(MagneticHeading, magneticHeadingTable);
auto angularVelocityTable = (foundAngularVelocityData ?
std::make_shared<TimeSeriesTableVec3>(times, angularVelocityData, labels) :
std::make_shared<TimeSeriesTableVec3>(emptyTimes, angularVelocityData, labels));
angularVelocityTable->updTableMetaData()
.setValueForKey("DataRate", std::to_string(dataRate));
tables.emplace(AngularVelocity, angularVelocityTable);
return tables;
}
void APDMDataReader::find_start_column(std::vector<std::string> tokens,
std::vector<std::string> search_labels,
const std::string& sensorName,
std::vector<int>& indices) const {
// Search for "sensorName/{search_labels} in tokens, append result to indices if found"
std::string firstLabel = sensorName + search_labels[0];
// look for first label, when found check/confirm the rest. Out of order is not supported
int found_index = -1;
std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), firstLabel);
if (it != tokens.end()) {
found_index = static_cast<int>(std::distance(tokens.begin(), it));
// now check the following indices for match with remaining search_labels
bool match = true;
for (int remaining = 1; remaining < search_labels.size() && match; remaining++) {
match = tokens[found_index + remaining].
compare(sensorName + search_labels[remaining]) == 0;
}
if (match) {
indices.push_back(found_index);
return;
}
else { // first label found but the remaining didn't. Warn
return;
}
}
return; // not found
}
}
|
#include <fstream>
#include "Simbody.h"
#include "Exception.h"
#include "FileAdapter.h"
#include "TimeSeriesTable.h"
#include "APDMDataReader.h"
namespace OpenSim {
const std::string APDMDataReader::Orientations{ "orientations" };
const std::string APDMDataReader::LinearAccelerations{ "linear_accelerations" };
const std::string APDMDataReader::MagneticHeading{ "magnetic_heading" };
const std::string APDMDataReader::AngularVelocity{ "angular_velocity" };
const std::vector<std::string> APDMDataReader::acceleration_labels{
"/Acceleration/X", "/Acceleration/Y", "/Acceleration/Z"
};
const std::vector<std::string> APDMDataReader::angular_velocity_labels{
"/Angular Velocity/X", "/Angular Velocity/Y","/Angular Velocity/Z"
};
const std::vector<std::string> APDMDataReader::magnetic_heading_labels{
"/Magnetic Field/X", "/Magnetic Field/Y","/Magnetic Field/Z"
};
const std::vector<std::string> APDMDataReader::orientation_labels{
"/Orientation/Scalar", "/Orientation/X", "/Orientation/Y","/Orientation/Z"
};
const std::string APDMDataReader::TimeLabel{ "Time" };
APDMDataReader* APDMDataReader::clone() const {
return new APDMDataReader{*this};
}
DataAdapter::OutputTables
APDMDataReader::readFile(const std::string& fileName) const {
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ifstream in_stream{ fileName };
OPENSIM_THROW_IF(!in_stream.good(),
FileDoesNotExist,
fileName);
OPENSIM_THROW_IF(in_stream.peek() == std::ifstream::traits_type::eof(),
FileIsEmpty,
fileName);
std::vector<std::string> labels;
// files specified by prefix + file name exist
double dataRate = SimTK::NaN;
std::vector<int> accIndex;
std::vector<int> gyroIndex;
std::vector<int> magIndex;
std::vector<int> orientationsIndex;
int n_imus = _settings.getProperty_ExperimentalSensors().size();
int last_size = 1024;
// Will read data into pre-allocated Matrices in-memory rather than appendRow
// on the fly to avoid the overhead of
SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus };
SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus };
SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus };
SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus };
std::vector<double> times;
times.resize(last_size);
// Format looks like this:
// Header Line 1: Test Name:, $String,,,,,..
// Header Line 2: Sample Rate:, $Value, Hz,,,,,
// Labels Line 3: Time {SensorName/Acceleration/X,SensorName/Acceleration/Y,SensorName/Acceleration/Z,....} repeated per sensor
// Units Line 4: s,{m/s^2,m/s^2,m/s^2....} repeated
int header_lines = 4;
std::string line;
// Line 1
std::getline(in_stream, line);
std::vector<std::string> tokens = FileAdapter::tokenize(line, ",");
std::string trialName = tokens[1]; // May contain spaces
// Line 2
std::getline(in_stream, line);
tokens = FileAdapter::tokenize(line, ",");
dataRate = std::stod(tokens[1]);
// Line 3, find columns for IMUs
std::getline(in_stream, line);
tokens = FileAdapter::tokenize(line, ",");
OPENSIM_THROW_IF((tokens[0] != TimeLabel), UnexpectedColumnLabel,
fileName,
TimeLabel,
tokens[0]);
for (int imu_index = 0; imu_index < n_imus; ++imu_index) {
std::string sensorName = _settings.get_ExperimentalSensors(imu_index).getName();
labels.push_back(_settings.get_ExperimentalSensors(imu_index).get_name_in_model());
find_start_column(tokens, APDMDataReader::acceleration_labels, sensorName, accIndex);
find_start_column(tokens, APDMDataReader::angular_velocity_labels, sensorName, gyroIndex);
find_start_column(tokens, APDMDataReader::magnetic_heading_labels, sensorName, magIndex);
find_start_column(tokens, APDMDataReader::orientation_labels, sensorName, orientationsIndex);
}
// Will create a table to map
// internally keep track of what data was found in input files
bool foundLinearAccelerationData = accIndex.size()>0;
bool foundMagneticHeadingData = magIndex.size()>0;
bool foundAngularVelocityData = gyroIndex.size()>0;
// If no Orientation data is available or dataRate can't be deduced we'll abort completely
OPENSIM_THROW_IF((orientationsIndex.size() == 0 || SimTK::isNaN(dataRate)),
TableMissingHeader);
// Line 4, Units unused
std::getline(in_stream, line);
// For all tables, will create row, stitch values from different sensors then append
bool done = false;
double time = 0.0;
double timeIncrement = 1 / dataRate;
int rowNumber = 0;
while (!done){
// Make vectors one per table
TimeSeriesTableQuaternion::RowVector
orientation_row_vector{ n_imus, SimTK::Quaternion() };
TimeSeriesTableVec3::RowVector
accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
TimeSeriesTableVec3::RowVector
magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
TimeSeriesTableVec3::RowVector
gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) };
std::vector<std::string> nextRow = FileAdapter::getNextLine(in_stream, ",");
if (nextRow.empty()) {
done = true;
break;
}
// Cycle through the imus collating values
for (int imu_index = 0; imu_index < n_imus; ++imu_index) {
// parse gyro info from in_stream
if (foundLinearAccelerationData)
accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex[imu_index]]),
std::stod(nextRow[accIndex[imu_index] + 1]), std::stod(nextRow[accIndex[imu_index] + 2]));
if (foundMagneticHeadingData)
magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex[imu_index]]),
std::stod(nextRow[magIndex[imu_index] + 1]), std::stod(nextRow[magIndex[imu_index] + 2]));
if (foundAngularVelocityData)
gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex[imu_index]]),
std::stod(nextRow[gyroIndex[imu_index] + 1]), std::stod(nextRow[gyroIndex[imu_index] + 2]));
// Create Quaternion from values in file, assume order in file W, X, Y, Z
orientation_row_vector[imu_index] =
SimTK::Quaternion(std::stod(nextRow[orientationsIndex[imu_index]]),
std::stod(nextRow[orientationsIndex[imu_index] + 1]),
std::stod(nextRow[orientationsIndex[imu_index] + 2]),
std::stod(nextRow[orientationsIndex[imu_index] + 3]));
}
if (done)
break;
// append to the tables
times[rowNumber] = time;
if (foundLinearAccelerationData)
linearAccelerationData[rowNumber] = accel_row_vector;
if (foundMagneticHeadingData)
magneticHeadingData[rowNumber] = magneto_row_vector;
if (foundAngularVelocityData)
angularVelocityData[rowNumber] = gyro_row_vector;
rotationsData[rowNumber] = orientation_row_vector;
// We could get some indication of time from file or generate time based on rate
// Here we use the latter mechanism.
time += timeIncrement;
rowNumber++;
if (std::remainder(rowNumber, last_size) == 0) {
// resize all Data/Matrices, double the size while keeping data
int newSize = last_size*2;
times.resize(newSize);
// Repeat for Data matrices in use
if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus);
if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus);
if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus);
rotationsData.resizeKeep(newSize, n_imus);
last_size = newSize;
}
}
// Trim Matrices in use to actual data and move into tables
times.resize(rowNumber);
// Repeat for Data matrices in use and create Tables from them or size 0 for empty
linearAccelerationData.resizeKeep(foundLinearAccelerationData? rowNumber : 0,
n_imus);
magneticHeadingData.resizeKeep(foundMagneticHeadingData? rowNumber : 0,
n_imus);
angularVelocityData.resizeKeep(foundAngularVelocityData? rowNumber :0,
n_imus);
rotationsData.resizeKeep(rowNumber, n_imus);
// Now create the tables from matrices
// Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading
// Tables could be empty if data is not present in file(s)
DataAdapter::OutputTables tables{};
auto orientationTable = std::make_shared<TimeSeriesTableQuaternion>(times, rotationsData, labels);
orientationTable->updTableMetaData()
.setValueForKey("DataRate", std::to_string(dataRate));
tables.emplace(Orientations, orientationTable);
std::vector<double> emptyTimes;
auto accelerationTable = (foundLinearAccelerationData ?
std::make_shared<TimeSeriesTableVec3>(times, linearAccelerationData, labels) :
std::make_shared<TimeSeriesTableVec3>(emptyTimes, linearAccelerationData, labels));
accelerationTable->updTableMetaData()
.setValueForKey("DataRate", std::to_string(dataRate));
tables.emplace(LinearAccelerations, accelerationTable);
auto magneticHeadingTable = (foundMagneticHeadingData ?
std::make_shared<TimeSeriesTableVec3>(times, magneticHeadingData, labels) :
std::make_shared<TimeSeriesTableVec3>(emptyTimes, magneticHeadingData, labels));
magneticHeadingTable->updTableMetaData()
.setValueForKey("DataRate", std::to_string(dataRate));
tables.emplace(MagneticHeading, magneticHeadingTable);
auto angularVelocityTable = (foundAngularVelocityData ?
std::make_shared<TimeSeriesTableVec3>(times, angularVelocityData, labels) :
std::make_shared<TimeSeriesTableVec3>(emptyTimes, angularVelocityData, labels));
angularVelocityTable->updTableMetaData()
.setValueForKey("DataRate", std::to_string(dataRate));
tables.emplace(AngularVelocity, angularVelocityTable);
return tables;
}
void APDMDataReader::find_start_column(std::vector<std::string> tokens,
std::vector<std::string> search_labels,
const std::string& sensorName,
std::vector<int>& indices) const {
// Search for "sensorName/{search_labels} in tokens, append result to indices if found"
std::string firstLabel = sensorName + search_labels[0];
// look for first label, when found check/confirm the rest. Out of order is not supported
int found_index = -1;
std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), firstLabel);
if (it != tokens.end()) {
found_index = static_cast<int>(std::distance(tokens.begin(), it));
// now check the following indices for match with remaining search_labels
bool match = true;
for (int remaining = 1; remaining < search_labels.size() && match; remaining++) {
match = tokens[found_index + remaining].
compare(sensorName + search_labels[remaining]) == 0;
}
if (match) {
indices.push_back(found_index);
return;
}
else { // first label found but the remaining didn't. Throw
throw Exception{ "Expected labels for sensor " + sensorName +
" were not found. Aboring" };
}
}
return; // not found
}
}
|
Throw exception if label sequence was not found in csv file
|
Throw exception if label sequence was not found in csv file
|
C++
|
apache-2.0
|
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
|
4c922346622853cc527cb0a57a25279e05ba7b67
|
stdlib/toolchain/Compatibility50/Overrides.cpp
|
stdlib/toolchain/Compatibility50/Overrides.cpp
|
//===--- Overrides.cpp - Compat override table for Swift 5.0 runtime ------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file provides compatibility override hooks for Swift 5.0 runtimes.
//
//===----------------------------------------------------------------------===//
#include "Overrides.h"
#include "../../public/runtime/CompatibilityOverride.h"
#include <dlfcn.h>
using namespace swift;
struct OverrideSection {
uintptr_t version;
#define OVERRIDE(name, ret, attrs, ccAttrs, namespace, typedArgs, namedArgs) \
Override_ ## name name;
#include "../../public/runtime/CompatibilityOverride.def"
};
OverrideSection Overrides
__attribute__((used, section("__DATA,__swift_hooks"))) = {
.version = 0,
.conformsToProtocol = swift50override_conformsToProtocol,
};
// Allow this library to get force-loaded by autolinking
__attribute__((weak, visibility("hidden")))
extern "C"
char _swift_FORCE_LOAD_$_swiftCompatibility50 = 0;
// Put a getClass hook in front of the system Swift runtime's hook to prevent it
// from trying to interpret symbolic references. rdar://problem/55036306
// FIXME: delete this #if and dlsym once we don't
// need to build with older libobjc headers
#if !OBJC_GETCLASSHOOK_DEFINED
using objc_hook_getClass = BOOL(*)(const char * _Nonnull name,
Class _Nullable * _Nonnull outClass);
#endif
static objc_hook_getClass OldGetClassHook;
static BOOL
getObjCClassByMangledName_untrusted(const char * _Nonnull typeName,
Class _Nullable * _Nonnull outClass) {
// Scan the string for byte sequences that might be recognized as
// symbolic references, and reject them.
for (const char *c = typeName; *c != 0; ++c) {
if (*c >= 1 && *c < 0x20) {
*outClass = Nil;
return NO;
}
}
if (OldGetClassHook) {
return OldGetClassHook(typeName, outClass);
}
// In case the OS runtime for some reason didn't install a hook, fallback to
// NO.
return NO;
}
__attribute__((constructor))
static void installGetClassHook_untrusted() {
// FIXME: delete this #if and dlsym once we don't
// need to build with older libobjc headers
#if !OBJC_GETCLASSHOOK_DEFINED
using objc_hook_getClass = BOOL(*)(const char * _Nonnull name,
Class _Nullable * _Nonnull outClass);
auto objc_setHook_getClass =
(void(*)(objc_hook_getClass _Nonnull,
objc_hook_getClass _Nullable * _Nonnull))
dlsym(RTLD_DEFAULT, "objc_setHook_getClass");
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
if (objc_setHook_getClass) {
objc_setHook_getClass(getObjCClassByMangledName_untrusted,
&OldGetClassHook);
}
#pragma clang diagnostic pop
}
|
//===--- Overrides.cpp - Compat override table for Swift 5.0 runtime ------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file provides compatibility override hooks for Swift 5.0 runtimes.
//
//===----------------------------------------------------------------------===//
#include "Overrides.h"
#include "../../public/runtime/CompatibilityOverride.h"
#include <dlfcn.h>
#include <mach-o/dyld.h>
#include <mach-o/getsect.h>
using namespace swift;
struct OverrideSection {
uintptr_t version;
#define OVERRIDE(name, ret, attrs, ccAttrs, namespace, typedArgs, namedArgs) \
Override_ ## name name;
#include "../../public/runtime/CompatibilityOverride.def"
};
OverrideSection Overrides
__attribute__((used, section("__DATA,__swift_hooks"))) = {
.version = 0,
.conformsToProtocol = swift50override_conformsToProtocol,
};
// Allow this library to get force-loaded by autolinking
__attribute__((weak, visibility("hidden")))
extern "C"
char _swift_FORCE_LOAD_$_swiftCompatibility50 = 0;
// Put a getClass hook in front of the system Swift runtime's hook to prevent it
// from trying to interpret symbolic references. rdar://problem/55036306
// FIXME: delete this #if and dlsym once we don't
// need to build with older libobjc headers
#if !OBJC_GETCLASSHOOK_DEFINED
using objc_hook_getClass = BOOL(*)(const char * _Nonnull name,
Class _Nullable * _Nonnull outClass);
#endif
static objc_hook_getClass OldGetClassHook;
static BOOL
getObjCClassByMangledName_untrusted(const char * _Nonnull typeName,
Class _Nullable * _Nonnull outClass) {
// Scan the string for byte sequences that might be recognized as
// symbolic references, and reject them.
for (const char *c = typeName; *c != 0; ++c) {
if (*c >= 1 && *c < 0x20) {
*outClass = Nil;
return NO;
}
}
if (OldGetClassHook) {
return OldGetClassHook(typeName, outClass);
}
// In case the OS runtime for some reason didn't install a hook, fallback to
// NO.
return NO;
}
#if __POINTER_WIDTH__ == 64
using mach_header_platform = mach_header_64;
#else
using mach_header_platform = mach_header;
#endif
__attribute__((constructor))
static void installGetClassHook_untrusted() {
// swiftCompatibility* might be linked into multiple dynamic libraries because
// of build system reasons, but the copy in the main executable is the only
// one that should count. Bail early unless we're running out of the main
// executable.
//
// Newer versions of dyld add additional API that can determine this more
// efficiently, but we have to support back to OS X 10.9/iOS 7, so dladdr
// is the only API that reaches back that far.
Dl_info dlinfo;
if (dladdr((const void*)(uintptr_t)installGetClassHook_untrusted, &dlinfo) == 0)
return;
auto machHeader = (const mach_header_platform *)dlinfo.dli_fbase;
if (machHeader->filetype != MH_EXECUTE)
return;
// FIXME: delete this #if and dlsym once we don't
// need to build with older libobjc headers
#if !OBJC_GETCLASSHOOK_DEFINED
using objc_hook_getClass = BOOL(*)(const char * _Nonnull name,
Class _Nullable * _Nonnull outClass);
auto objc_setHook_getClass =
(void(*)(objc_hook_getClass _Nonnull,
objc_hook_getClass _Nullable * _Nonnull))
dlsym(RTLD_DEFAULT, "objc_setHook_getClass");
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
if (objc_setHook_getClass) {
objc_setHook_getClass(getObjCClassByMangledName_untrusted,
&OldGetClassHook);
}
#pragma clang diagnostic pop
}
|
Install objc_getClass hook only in main executable
|
Compatibility50: Install objc_getClass hook only in main executable
Xcode and other build systems currently link the compatibility libraries into every executable
or dynamic library, which can cause a chain of objc_getClass compatibility hacks to pile up if
a program loads a lot of dynamic libraries. In the static constructor that installs the
objc_getClass compatibility shim, check whether it's running on behalf of the main executable
before installing the shim.
|
C++
|
apache-2.0
|
stephentyrone/swift,roambotics/swift,aschwaighofer/swift,apple/swift,allevato/swift,stephentyrone/swift,allevato/swift,harlanhaskins/swift,glessard/swift,glessard/swift,harlanhaskins/swift,tkremenek/swift,harlanhaskins/swift,hooman/swift,rudkx/swift,hooman/swift,harlanhaskins/swift,benlangmuir/swift,gregomni/swift,CodaFi/swift,atrick/swift,jckarter/swift,gregomni/swift,glessard/swift,tkremenek/swift,airspeedswift/swift,xwu/swift,airspeedswift/swift,JGiola/swift,tkremenek/swift,jckarter/swift,harlanhaskins/swift,JGiola/swift,airspeedswift/swift,atrick/swift,harlanhaskins/swift,jckarter/swift,gregomni/swift,roambotics/swift,aschwaighofer/swift,rudkx/swift,glessard/swift,parkera/swift,glessard/swift,jckarter/swift,ahoppen/swift,allevato/swift,hooman/swift,rudkx/swift,airspeedswift/swift,aschwaighofer/swift,roambotics/swift,JGiola/swift,tkremenek/swift,benlangmuir/swift,ahoppen/swift,airspeedswift/swift,jckarter/swift,aschwaighofer/swift,stephentyrone/swift,apple/swift,apple/swift,atrick/swift,allevato/swift,nathawes/swift,JGiola/swift,xwu/swift,hooman/swift,parkera/swift,xwu/swift,gregomni/swift,atrick/swift,tkremenek/swift,stephentyrone/swift,ahoppen/swift,jmgc/swift,xwu/swift,harlanhaskins/swift,nathawes/swift,jmgc/swift,jckarter/swift,apple/swift,CodaFi/swift,apple/swift,hooman/swift,benlangmuir/swift,airspeedswift/swift,atrick/swift,jmgc/swift,jmgc/swift,stephentyrone/swift,parkera/swift,JGiola/swift,parkera/swift,tkremenek/swift,xwu/swift,airspeedswift/swift,atrick/swift,stephentyrone/swift,stephentyrone/swift,nathawes/swift,ahoppen/swift,CodaFi/swift,JGiola/swift,xwu/swift,tkremenek/swift,nathawes/swift,ahoppen/swift,rudkx/swift,aschwaighofer/swift,jmgc/swift,roambotics/swift,parkera/swift,roambotics/swift,jckarter/swift,rudkx/swift,gregomni/swift,parkera/swift,benlangmuir/swift,benlangmuir/swift,roambotics/swift,aschwaighofer/swift,parkera/swift,hooman/swift,benlangmuir/swift,jmgc/swift,apple/swift,CodaFi/swift,nathawes/swift,CodaFi/swift,jmgc/swift,ahoppen/swift,allevato/swift,CodaFi/swift,nathawes/swift,parkera/swift,nathawes/swift,allevato/swift,CodaFi/swift,gregomni/swift,hooman/swift,aschwaighofer/swift,xwu/swift,allevato/swift,glessard/swift,rudkx/swift
|
1bcafe2e349ae0747e2d70834bf02312f1fbe4ed
|
tomviz/FxiWorkflowWidget.cxx
|
tomviz/FxiWorkflowWidget.cxx
|
/* This source file is part of the Tomviz project, https://tomviz.org/.
It is released under the 3-Clause BSD License, see "LICENSE". */
#include "FxiWorkflowWidget.h"
#include "ui_FxiWorkflowWidget.h"
#include "ActiveObjects.h"
#include "ColorMap.h"
#include "DataSource.h"
#include "InternalPythonHelper.h"
#include "Utilities.h"
#include <cmath>
#include <pqApplicationCore.h>
#include <pqSettings.h>
#include <vtkCubeAxesActor.h>
#include <vtkColorTransferFunction.h>
#include <vtkImageData.h>
#include <vtkImageProperty.h>
#include <vtkImageSlice.h>
#include <vtkImageSliceMapper.h>
#include <vtkInteractorStyleRubberBand2D.h>
#include <vtkNew.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkScalarsToColors.h>
#include <QDebug>
#include <QKeyEvent>
#include <QMessageBox>
#include <algorithm>
namespace tomviz {
class FxiWorkflowWidget::Internal : public QObject
{
Q_OBJECT
public:
Ui::FxiWorkflowWidget ui;
QPointer<Operator> op;
vtkSmartPointer<vtkImageData> image;
vtkSmartPointer<vtkImageData> rotationImages;
QList<double> rotations;
vtkNew<vtkImageSlice> slice;
vtkNew<vtkImageSliceMapper> mapper;
vtkNew<vtkRenderer> renderer;
vtkNew<vtkCubeAxesActor> axesActor;
QString script;
InternalPythonHelper pythonHelper;
QPointer<FxiWorkflowWidget> parent;
QPointer<DataSource> dataSource;
int sliceNumber = 0;
Internal(Operator* o, vtkSmartPointer<vtkImageData> img, FxiWorkflowWidget* p)
: op(o), image(img)
{
// Must call setupUi() before using p in any way
ui.setupUi(p);
setParent(p);
parent = p;
readSettings();
// Keep the axes invisible until the data is displayed
axesActor->SetVisibility(false);
mapper->SetOrientation(0);
slice->SetMapper(mapper);
renderer->AddViewProp(slice);
ui.sliceView->renderWindow()->AddRenderer(renderer);
vtkNew<vtkInteractorStyleRubberBand2D> interatorStyle;
interatorStyle->SetRenderOnMouseMove(true);
ui.sliceView->interactor()->SetInteractorStyle(interatorStyle);
setRotationData(vtkImageData::New());
// Use a child data source if one is available so the color map will match
if (op->childDataSource()) {
dataSource = op->childDataSource();
} else if (op->dataSource()) {
dataSource = op->dataSource();
} else {
dataSource = ActiveObjects::instance().activeDataSource();
}
auto lut = vtkScalarsToColors::SafeDownCast(
dataSource->colorMap()->GetClientSideObject());
if (lut) {
// Make a deep copy so we can modify it
auto* newLut = lut->NewInstance();
newLut->DeepCopy(lut);
slice->GetProperty()->SetLookupTable(newLut);
// Decrement the reference count
newLut->FastDelete();
}
for (auto* w : inputWidgets()) {
w->installEventFilter(this);
}
auto* dims = image->GetDimensions();
ui.slice->setMaximum(dims[1] - 1);
ui.sliceStart->setMaximum(dims[1] - 1);
ui.sliceStop->setMaximum(dims[1]);
updateControls();
setupConnections();
}
void setupConnections()
{
connect(ui.testRotations, &QPushButton::pressed, this,
&Internal::generateTestImages);
connect(ui.imageViewSlider, &IntSliderWidget::valueEdited, this,
&Internal::sliderEdited);
}
void setupRenderer() { tomviz::setupRenderer(renderer, mapper, axesActor); }
void render() { ui.sliceView->renderWindow()->Render(); }
void readSettings()
{
readReconSettings();
readTestSettings();
}
void readReconSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("FxiWorkflowWidget");
settings->beginGroup("Recon");
setRotationCenter(settings->value("rotationCenter", 600).toDouble());
setSliceStart(settings->value("sliceStart", 0).toInt());
setSliceStop(settings->value("sliceStop", 1).toInt());
settings->endGroup();
settings->endGroup();
}
void readTestSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("FxiWorkflowWidget");
settings->beginGroup("TestSettings");
ui.start->setValue(settings->value("start", 550).toDouble());
ui.stop->setValue(settings->value("stop", 650).toDouble());
ui.steps->setValue(settings->value("steps", 26).toInt());
ui.slice->setValue(settings->value("sli", 0).toInt());
settings->endGroup();
settings->endGroup();
}
void writeSettings()
{
writeReconSettings();
writeTestSettings();
}
void writeReconSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("FxiWorkflowWidget");
settings->beginGroup("Recon");
settings->setValue("rotationCenter", rotationCenter());
settings->setValue("sliceStart", sliceStart());
settings->setValue("sliceStop", sliceStop());
settings->endGroup();
settings->endGroup();
}
void writeTestSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("FxiWorkflowWidget");
settings->beginGroup("TestSettings");
settings->setValue("start", ui.start->value());
settings->setValue("stop", ui.stop->value());
settings->setValue("steps", ui.steps->value());
settings->setValue("sli", ui.slice->value());
settings->endGroup();
settings->endGroup();
}
QList<QWidget*> inputWidgets()
{
return { ui.start, ui.stop, ui.steps, ui.slice,
ui.rotationCenter, ui.sliceStart, ui.sliceStop };
}
void generateTestImages()
{
rotations.clear();
{
Python python;
auto module = pythonHelper.loadModule(script);
if (!module.isValid()) {
QString msg = "Failed to load script";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
auto func = module.findFunction("test_rotations");
if (!func.isValid()) {
QString msg = "Failed to find function \"test_rotations\"";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
Python::Object data = Python::createDataset(image, *dataSource);
Python::Dict kwargs;
kwargs.set("dataset", data);
kwargs.set("start", ui.start->value());
kwargs.set("stop", ui.stop->value());
kwargs.set("steps", ui.steps->value());
kwargs.set("sli", ui.slice->value());
auto ret = func.call(kwargs);
auto result = ret.toDict();
if (!result.isValid()) {
QString msg = "Failed to execute test_rotations()";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
auto pyImages = result["images"];
auto* object = Python::VTK::convertToDataObject(pyImages);
if (!object) {
QString msg = "No image data was returned from test_rotations()";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
auto* imageData = vtkImageData::SafeDownCast(object);
if (!imageData) {
QString msg = "No image data was returned from test_rotations()";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
auto centers = result["centers"];
auto pyRotations = centers.toList();
if (!pyRotations.isValid() || pyRotations.length() <= 0) {
QString msg = "No rotations returned from test_rotations()";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
for (int i = 0; i < pyRotations.length(); ++i) {
rotations.append(pyRotations[i].toLong());
}
setRotationData(imageData);
}
// If we made it this far, it was a success
// Make the axes visible.
axesActor->SetVisibility(true);
// Save these settings in case the user wants to use them again...
writeTestSettings();
updateImageViewSlider();
render();
}
void setRotationData(vtkImageData* data)
{
rotationImages = data;
mapper->SetInputData(rotationImages);
mapper->SetSliceNumber(0);
mapper->Update();
rescaleColors();
setupRenderer();
}
void rescaleColors()
{
auto* lut = slice->GetProperty()->GetLookupTable();
if (!lut) {
return;
}
auto* tf = vtkColorTransferFunction::SafeDownCast(lut);
if (!tf) {
return;
}
auto* newRange = rotationImages->GetScalarRange();
rescaleLut(tf, newRange[0], newRange[1]);
}
void updateControls()
{
std::vector<QSignalBlocker> blockers;
for (auto w : inputWidgets()) {
blockers.emplace_back(w);
}
updateImageViewSlider();
// It would be nice if we could only write the settings when the
// widget is accepted, but I don't immediately see an easy way
// to do that.
writeSettings();
}
bool rotationDataValid()
{
if (!rotationImages.GetPointer()) {
return false;
}
if (rotations.isEmpty()) {
return false;
}
return true;
}
void updateImageViewSlider()
{
auto blocked = QSignalBlocker(ui.imageViewSlider);
bool enable = rotationDataValid();
ui.imageViewSlider->setVisible(enable);
ui.currentRotationLabel->setVisible(enable);
ui.currentRotation->setVisible(enable);
if (!enable) {
return;
}
auto* dims = rotationImages->GetDimensions();
ui.imageViewSlider->setMaximum(dims[0] - 1);
sliceNumber = 0;
ui.imageViewSlider->setValue(sliceNumber);
sliderEdited();
}
void sliderEdited()
{
sliceNumber = ui.imageViewSlider->value();
if (sliceNumber < rotations.size()) {
ui.currentRotation->setValue(rotations[sliceNumber]);
} else {
qCritical() << sliceNumber
<< "is greater than the rotations size:" << rotations.size();
}
mapper->SetSliceNumber(sliceNumber);
mapper->Update();
render();
}
bool eventFilter(QObject* o, QEvent* e) override
{
if (inputWidgets().contains(qobject_cast<QWidget*>(o))) {
if (e->type() == QEvent::KeyPress) {
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
if (keyEvent->key() == Qt::Key_Return ||
keyEvent->key() == Qt::Key_Enter) {
e->accept();
qobject_cast<QWidget*>(o)->clearFocus();
return true;
}
}
}
return QObject::eventFilter(o, e);
}
void setRotationCenter(double center) { ui.rotationCenter->setValue(center); }
double rotationCenter() const { return ui.rotationCenter->value(); }
void setSliceStart(int i) { ui.sliceStart->setValue(i); }
int sliceStart() const { return ui.sliceStart->value(); }
void setSliceStop(int i) { ui.sliceStop->setValue(i); }
int sliceStop() const { return ui.sliceStop->value(); }
};
#include "FxiWorkflowWidget.moc"
FxiWorkflowWidget::FxiWorkflowWidget(Operator* op,
vtkSmartPointer<vtkImageData> image,
QWidget* p)
: CustomPythonOperatorWidget(p)
{
m_internal.reset(new Internal(op, image, this));
}
FxiWorkflowWidget::~FxiWorkflowWidget() = default;
void FxiWorkflowWidget::getValues(QMap<QString, QVariant>& map)
{
map.insert("rotation_center", m_internal->rotationCenter());
map.insert("slice_start", m_internal->sliceStart());
map.insert("slice_stop", m_internal->sliceStop());
}
void FxiWorkflowWidget::setValues(const QMap<QString, QVariant>& map)
{
if (map.contains("rotation_center")) {
m_internal->setRotationCenter(map["rotation_center"].toDouble());
}
if (map.contains("slice_start")) {
m_internal->setSliceStart(map["slice_start"].toInt());
}
if (map.contains("slice_stop")) {
m_internal->setSliceStop(map["slice_stop"].toInt());
}
}
void FxiWorkflowWidget::setScript(const QString& script)
{
Superclass::setScript(script);
m_internal->script = script;
}
} // namespace tomviz
|
/* This source file is part of the Tomviz project, https://tomviz.org/.
It is released under the 3-Clause BSD License, see "LICENSE". */
#include "FxiWorkflowWidget.h"
#include "ui_FxiWorkflowWidget.h"
#include "ActiveObjects.h"
#include "ColorMap.h"
#include "DataSource.h"
#include "InternalPythonHelper.h"
#include "Utilities.h"
#include <cmath>
#include <pqApplicationCore.h>
#include <pqSettings.h>
#include <vtkCubeAxesActor.h>
#include <vtkColorTransferFunction.h>
#include <vtkImageData.h>
#include <vtkImageProperty.h>
#include <vtkImageSlice.h>
#include <vtkImageSliceMapper.h>
#include <vtkInteractorStyleRubberBand2D.h>
#include <vtkNew.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkScalarsToColors.h>
#include <QDebug>
#include <QFutureWatcher>
#include <QKeyEvent>
#include <QMessageBox>
#include <QProgressDialog>
#include <QtConcurrent>
#include <algorithm>
namespace tomviz {
class InternalProgressDialog : public QProgressDialog
{
public:
InternalProgressDialog(QWidget* parent = nullptr) : QProgressDialog(parent)
{
setWindowTitle("Tomviz");
setLabelText("Generating test images...");
setMinimum(0);
setMaximum(0);
setWindowModality(Qt::WindowModal);
// No cancel button
setCancelButton(nullptr);
// No close button in the corner
setWindowFlags((windowFlags() | Qt::CustomizeWindowHint) &
~Qt::WindowCloseButtonHint);
reset();
}
void keyPressEvent(QKeyEvent* e) override
{
// Do not let the user close the dialog by pressing escape
if (e->key() == Qt::Key_Escape) {
return;
}
QProgressDialog::keyPressEvent(e);
}
};
class FxiWorkflowWidget::Internal : public QObject
{
Q_OBJECT
public:
Ui::FxiWorkflowWidget ui;
QPointer<Operator> op;
vtkSmartPointer<vtkImageData> image;
vtkSmartPointer<vtkImageData> rotationImages;
QList<double> rotations;
vtkNew<vtkImageSlice> slice;
vtkNew<vtkImageSliceMapper> mapper;
vtkNew<vtkRenderer> renderer;
vtkNew<vtkCubeAxesActor> axesActor;
QString script;
InternalPythonHelper pythonHelper;
QPointer<FxiWorkflowWidget> parent;
QPointer<DataSource> dataSource;
int sliceNumber = 0;
QScopedPointer<InternalProgressDialog> progressDialog;
QFutureWatcher<void> futureWatcher;
Internal(Operator* o, vtkSmartPointer<vtkImageData> img, FxiWorkflowWidget* p)
: op(o), image(img)
{
// Must call setupUi() before using p in any way
ui.setupUi(p);
setParent(p);
parent = p;
readSettings();
// Keep the axes invisible until the data is displayed
axesActor->SetVisibility(false);
mapper->SetOrientation(0);
slice->SetMapper(mapper);
renderer->AddViewProp(slice);
ui.sliceView->renderWindow()->AddRenderer(renderer);
vtkNew<vtkInteractorStyleRubberBand2D> interatorStyle;
interatorStyle->SetRenderOnMouseMove(true);
ui.sliceView->interactor()->SetInteractorStyle(interatorStyle);
setRotationData(vtkImageData::New());
// Use a child data source if one is available so the color map will match
if (op->childDataSource()) {
dataSource = op->childDataSource();
} else if (op->dataSource()) {
dataSource = op->dataSource();
} else {
dataSource = ActiveObjects::instance().activeDataSource();
}
auto lut = vtkScalarsToColors::SafeDownCast(
dataSource->colorMap()->GetClientSideObject());
if (lut) {
// Make a deep copy so we can modify it
auto* newLut = lut->NewInstance();
newLut->DeepCopy(lut);
slice->GetProperty()->SetLookupTable(newLut);
// Decrement the reference count
newLut->FastDelete();
}
for (auto* w : inputWidgets()) {
w->installEventFilter(this);
}
auto* dims = image->GetDimensions();
ui.slice->setMaximum(dims[1] - 1);
ui.sliceStart->setMaximum(dims[1] - 1);
ui.sliceStop->setMaximum(dims[1]);
progressDialog.reset(new InternalProgressDialog(parent));
updateControls();
setupConnections();
}
void setupConnections()
{
connect(ui.testRotations, &QPushButton::pressed, this,
&Internal::startGeneratingTestImages);
connect(ui.imageViewSlider, &IntSliderWidget::valueEdited, this,
&Internal::sliderEdited);
connect(&futureWatcher, &QFutureWatcher<void>::finished, this,
&Internal::testImagesGenerated);
connect(&futureWatcher, &QFutureWatcher<void>::finished,
progressDialog.data(), &QProgressDialog::accept);
}
void setupRenderer() { tomviz::setupRenderer(renderer, mapper, axesActor); }
void render() { ui.sliceView->renderWindow()->Render(); }
void readSettings()
{
readReconSettings();
readTestSettings();
}
void readReconSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("FxiWorkflowWidget");
settings->beginGroup("Recon");
setRotationCenter(settings->value("rotationCenter", 600).toDouble());
setSliceStart(settings->value("sliceStart", 0).toInt());
setSliceStop(settings->value("sliceStop", 1).toInt());
settings->endGroup();
settings->endGroup();
}
void readTestSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("FxiWorkflowWidget");
settings->beginGroup("TestSettings");
ui.start->setValue(settings->value("start", 550).toDouble());
ui.stop->setValue(settings->value("stop", 650).toDouble());
ui.steps->setValue(settings->value("steps", 26).toInt());
ui.slice->setValue(settings->value("sli", 0).toInt());
settings->endGroup();
settings->endGroup();
}
void writeSettings()
{
writeReconSettings();
writeTestSettings();
}
void writeReconSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("FxiWorkflowWidget");
settings->beginGroup("Recon");
settings->setValue("rotationCenter", rotationCenter());
settings->setValue("sliceStart", sliceStart());
settings->setValue("sliceStop", sliceStop());
settings->endGroup();
settings->endGroup();
}
void writeTestSettings()
{
auto settings = pqApplicationCore::instance()->settings();
settings->beginGroup("FxiWorkflowWidget");
settings->beginGroup("TestSettings");
settings->setValue("start", ui.start->value());
settings->setValue("stop", ui.stop->value());
settings->setValue("steps", ui.steps->value());
settings->setValue("sli", ui.slice->value());
settings->endGroup();
settings->endGroup();
}
QList<QWidget*> inputWidgets()
{
return { ui.start, ui.stop, ui.steps, ui.slice,
ui.rotationCenter, ui.sliceStart, ui.sliceStop };
}
void startGeneratingTestImages()
{
progressDialog->show();
auto future = QtConcurrent::run(this, &Internal::generateTestImages);
futureWatcher.setFuture(future);
}
void testImagesGenerated()
{
updateImageViewSlider();
render();
}
void generateTestImages()
{
rotations.clear();
{
Python python;
auto module = pythonHelper.loadModule(script);
if (!module.isValid()) {
QString msg = "Failed to load script";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
auto func = module.findFunction("test_rotations");
if (!func.isValid()) {
QString msg = "Failed to find function \"test_rotations\"";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
Python::Object data = Python::createDataset(image, *dataSource);
Python::Dict kwargs;
kwargs.set("dataset", data);
kwargs.set("start", ui.start->value());
kwargs.set("stop", ui.stop->value());
kwargs.set("steps", ui.steps->value());
kwargs.set("sli", ui.slice->value());
auto ret = func.call(kwargs);
auto result = ret.toDict();
if (!result.isValid()) {
QString msg = "Failed to execute test_rotations()";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
auto pyImages = result["images"];
auto* object = Python::VTK::convertToDataObject(pyImages);
if (!object) {
QString msg = "No image data was returned from test_rotations()";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
auto* imageData = vtkImageData::SafeDownCast(object);
if (!imageData) {
QString msg = "No image data was returned from test_rotations()";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
auto centers = result["centers"];
auto pyRotations = centers.toList();
if (!pyRotations.isValid() || pyRotations.length() <= 0) {
QString msg = "No rotations returned from test_rotations()";
qCritical() << msg;
QMessageBox::critical(parent, "Tomviz", msg);
return;
}
for (int i = 0; i < pyRotations.length(); ++i) {
rotations.append(pyRotations[i].toLong());
}
setRotationData(imageData);
}
// If we made it this far, it was a success
// Make the axes visible.
axesActor->SetVisibility(true);
// Save these settings in case the user wants to use them again...
writeTestSettings();
}
void setRotationData(vtkImageData* data)
{
rotationImages = data;
mapper->SetInputData(rotationImages);
mapper->SetSliceNumber(0);
mapper->Update();
rescaleColors();
setupRenderer();
}
void rescaleColors()
{
auto* lut = slice->GetProperty()->GetLookupTable();
if (!lut) {
return;
}
auto* tf = vtkColorTransferFunction::SafeDownCast(lut);
if (!tf) {
return;
}
auto* newRange = rotationImages->GetScalarRange();
rescaleLut(tf, newRange[0], newRange[1]);
}
void updateControls()
{
std::vector<QSignalBlocker> blockers;
for (auto w : inputWidgets()) {
blockers.emplace_back(w);
}
updateImageViewSlider();
// It would be nice if we could only write the settings when the
// widget is accepted, but I don't immediately see an easy way
// to do that.
writeSettings();
}
bool rotationDataValid()
{
if (!rotationImages.GetPointer()) {
return false;
}
if (rotations.isEmpty()) {
return false;
}
return true;
}
void updateImageViewSlider()
{
auto blocked = QSignalBlocker(ui.imageViewSlider);
bool enable = rotationDataValid();
ui.imageViewSlider->setVisible(enable);
ui.currentRotationLabel->setVisible(enable);
ui.currentRotation->setVisible(enable);
if (!enable) {
return;
}
auto* dims = rotationImages->GetDimensions();
ui.imageViewSlider->setMaximum(dims[0] - 1);
sliceNumber = 0;
ui.imageViewSlider->setValue(sliceNumber);
sliderEdited();
}
void sliderEdited()
{
sliceNumber = ui.imageViewSlider->value();
if (sliceNumber < rotations.size()) {
ui.currentRotation->setValue(rotations[sliceNumber]);
} else {
qCritical() << sliceNumber
<< "is greater than the rotations size:" << rotations.size();
}
mapper->SetSliceNumber(sliceNumber);
mapper->Update();
render();
}
bool eventFilter(QObject* o, QEvent* e) override
{
if (inputWidgets().contains(qobject_cast<QWidget*>(o))) {
if (e->type() == QEvent::KeyPress) {
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
if (keyEvent->key() == Qt::Key_Return ||
keyEvent->key() == Qt::Key_Enter) {
e->accept();
qobject_cast<QWidget*>(o)->clearFocus();
return true;
}
}
}
return QObject::eventFilter(o, e);
}
void setRotationCenter(double center) { ui.rotationCenter->setValue(center); }
double rotationCenter() const { return ui.rotationCenter->value(); }
void setSliceStart(int i) { ui.sliceStart->setValue(i); }
int sliceStart() const { return ui.sliceStart->value(); }
void setSliceStop(int i) { ui.sliceStop->setValue(i); }
int sliceStop() const { return ui.sliceStop->value(); }
};
#include "FxiWorkflowWidget.moc"
FxiWorkflowWidget::FxiWorkflowWidget(Operator* op,
vtkSmartPointer<vtkImageData> image,
QWidget* p)
: CustomPythonOperatorWidget(p)
{
m_internal.reset(new Internal(op, image, this));
}
FxiWorkflowWidget::~FxiWorkflowWidget() = default;
void FxiWorkflowWidget::getValues(QMap<QString, QVariant>& map)
{
map.insert("rotation_center", m_internal->rotationCenter());
map.insert("slice_start", m_internal->sliceStart());
map.insert("slice_stop", m_internal->sliceStop());
}
void FxiWorkflowWidget::setValues(const QMap<QString, QVariant>& map)
{
if (map.contains("rotation_center")) {
m_internal->setRotationCenter(map["rotation_center"].toDouble());
}
if (map.contains("slice_start")) {
m_internal->setSliceStart(map["slice_start"].toInt());
}
if (map.contains("slice_stop")) {
m_internal->setSliceStop(map["slice_stop"].toInt());
}
}
void FxiWorkflowWidget::setScript(const QString& script)
{
Superclass::setScript(script);
m_internal->script = script;
}
} // namespace tomviz
|
Add progress bar for generating test images
|
Add progress bar for generating test images
This was relatively simple to add with QFutureWatcher and
QProgressDialog.
Signed-off-by: Patrick Avery <[email protected]>
|
C++
|
bsd-3-clause
|
OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz
|
4e11cce21bae397167ead6b0dd0627c337cff891
|
Lab-4/StudentTestScores.cpp
|
Lab-4/StudentTestScores.cpp
|
StudentTestScores::StudentTestScores(string name, int numScores){
studentName=name;
numTestScores=numScores;
}
StudentTestScores::StudentTestScores(const StudentTestScores &other){
studentName=other.studentName;
testScores=other.testScores;
numTestScores=other.numTestScores;
}
StudentTestScores::~StudentTestScores(){
delete [] testScores;
}
StudentTestScores::Display(){
cout << studentName << "\t" << numTestScores;
for(int i=0; i<numTestScores; i++){
cout << "\t" << testScores[i];
}
cout << endl;
}
/*StudentTestScores::operator=(const StudentTestScores &other){
studentName=other.studentName;
testScores=other.testScores;
numTestScores=other.numTestScores;
}*/
|
StudentTestScores::StudentTestScores(){
studentName="";
numTestScores=0;
}
StudentTestScores::StudentTestScores(string name){
studentName=name;
numTestScores=0;
}
StudentTestScores::StudentTestScores(const StudentTestScores &other){
studentName=other.studentName;
testScores=other.testScores;
numTestScores=other.numTestScores;
}
StudentTestScores::~StudentTestScores(){
delete [] testScores;
}
StudentTestScores::Display(){
cout << studentName << "\t" << numTestScores;
for(int i=0; i<numTestScores; i++){
cout << "\t" << testScores[i];
}
cout << endl;
}
/*StudentTestScores::operator=(const StudentTestScores &other){
studentName=other.studentName;
testScores=other.testScores;
numTestScores=other.numTestScores;
}*/
|
Update StudentTestScores.cpp
|
Update StudentTestScores.cpp
|
C++
|
mit
|
mercviper/CSLabs
|
2a82e24c11daa4fdb5da5231310de12ad62dcaf4
|
platform/android/Rhodes/jni/src/nativebar.cpp
|
platform/android/Rhodes/jni/src/nativebar.cpp
|
#include "JNIRhodes.h"
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "NativeBar"
RHO_GLOBAL void create_nativebar(int bar_type, int nparams, char** params)
{
JNIEnv *env = jnienv();
jclass clsVector = getJNIClass(RHODES_JAVA_CLASS_VECTOR);
if (!clsVector) return;
jclass clsNativeBar = getJNIClass(RHODES_JAVA_CLASS_NATIVEBAR);
if (!clsNativeBar) return;
jmethodID midConstructor = getJNIClassMethod(clsVector, "<init>", "(I)V");
if (!midConstructor) return;
jobject vectorObj = env->NewObject(clsVector, midConstructor, nparams);
if (!vectorObj) return;
jmethodID midAddElement = getJNIClassMethod(clsVector, "addElement", "(Ljava/lang/Object;)V");
if (!midAddElement) return;
jmethodID midCreate = getJNIClassStaticMethod(clsNativeBar, "create", "(ILjava/util/Vector;)V");
if (!midCreate) return;
for (int i = 0; i != nparams; ++i) {
jstring strObj = env->NewStringUTF(params[i] ? params[i] : "");
env->CallObjectMethod(vectorObj, midAddElement, strObj);
env->DeleteLocalRef(strObj);
}
env->CallStaticObjectMethod(clsNativeBar, midCreate, bar_type, vectorObj);
env->DeleteLocalRef(vectorObj);
}
RHO_GLOBAL void remove_nativebar()
{
jclass cls = getJNIClass(RHODES_JAVA_CLASS_NATIVEBAR);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(cls, "remove", "()V");
if (!mid) return;
jnienv()->CallStaticVoidMethod(cls, mid);
}
RHO_GLOBAL void nativebar_switch_tab(int index)
{
jclass cls = getJNIClass(RHODES_JAVA_CLASS_NATIVEBAR);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(cls, "switchTab", "(I)V");
if (!mid) return;
jnienv()->CallStaticVoidMethod(cls, mid, index);
}
|
#include "JNIRhodes.h"
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "NativeBar"
RHO_GLOBAL void create_nativebar(int bar_type, int nparams, char** params)
{
JNIEnv *env = jnienv();
jclass clsVector = getJNIClass(RHODES_JAVA_CLASS_VECTOR);
if (!clsVector) return;
jclass clsNativeBar = getJNIClass(RHODES_JAVA_CLASS_NATIVEBAR);
if (!clsNativeBar) return;
jmethodID midConstructor = getJNIClassMethod(clsVector, "<init>", "(I)V");
if (!midConstructor) return;
jobject vectorObj = env->NewObject(clsVector, midConstructor, nparams);
if (!vectorObj) return;
jmethodID midAddElement = getJNIClassMethod(clsVector, "addElement", "(Ljava/lang/Object;)V");
if (!midAddElement) return;
jmethodID midCreate = getJNIClassStaticMethod(clsNativeBar, "create", "(ILjava/util/Vector;)V");
if (!midCreate) return;
for (int i = 0; i != nparams; ++i) {
char const *s = params[i] ? params[i] : "";
jstring strObj = env->NewStringUTF(s);
env->CallVoidMethod(vectorObj, midAddElement, strObj);
env->DeleteLocalRef(strObj);
}
env->CallStaticVoidMethod(clsNativeBar, midCreate, bar_type, vectorObj);
env->DeleteLocalRef(vectorObj);
}
RHO_GLOBAL void remove_nativebar()
{
jclass cls = getJNIClass(RHODES_JAVA_CLASS_NATIVEBAR);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(cls, "remove", "()V");
if (!mid) return;
jnienv()->CallStaticVoidMethod(cls, mid);
}
RHO_GLOBAL void nativebar_switch_tab(int index)
{
jclass cls = getJNIClass(RHODES_JAVA_CLASS_NATIVEBAR);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(cls, "switchTab", "(I)V");
if (!mid) return;
jnienv()->CallStaticVoidMethod(cls, mid, index);
}
|
Fix android tab bar implementation
|
Fix android tab bar implementation
|
C++
|
mit
|
pslgoh/rhodes,tauplatform/tau,pslgoh/rhodes,tauplatform/tau,rhomobile/rhodes,watusi/rhodes,watusi/rhodes,rhomobile/rhodes,watusi/rhodes,rhomobile/rhodes,pslgoh/rhodes,rhomobile/rhodes,pslgoh/rhodes,rhomobile/rhodes,watusi/rhodes,pslgoh/rhodes,watusi/rhodes,watusi/rhodes,rhomobile/rhodes,pslgoh/rhodes,pslgoh/rhodes,watusi/rhodes,pslgoh/rhodes,tauplatform/tau,tauplatform/tau,tauplatform/tau,watusi/rhodes,rhomobile/rhodes,tauplatform/tau,rhomobile/rhodes,tauplatform/tau,watusi/rhodes,watusi/rhodes,pslgoh/rhodes,tauplatform/tau,tauplatform/tau,rhomobile/rhodes,pslgoh/rhodes,tauplatform/tau,rhomobile/rhodes
|
5dce3822698e83788d491bbbdae9d37861a75cc5
|
platform/android/Rhodes/jni/src/signature.cpp
|
platform/android/Rhodes/jni/src/signature.cpp
|
/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "rhodes/JNIRhodes.h"
#include "rhodes/JNIRhoRuby.h"
#include "rhodes/jni/com_rhomobile_rhodes_signature_Signature.h"
#include <common/rhoparams.h>
#include <common/RhodesApp.h>
#include <logging/RhoLog.h>
#include "ruby/ext/rho/rhoruby.h"
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "Signature"
RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_signature_Signature_callback
(JNIEnv *env, jclass, jstring callback, jstring filePath, jstring error, jboolean cancelled)
{
rho_rhodesapp_callSignatureCallback(rho_cast<std::string>(callback).c_str(),
rho_cast<std::string>(filePath).c_str(), rho_cast<std::string>(error).c_str(), cancelled);
}
RHO_GLOBAL void rho_signature_take(char* callback_url, rho_param* p)
{
JNIEnv *env = jnienv();
jclass cls = getJNIClass(RHODES_JAVA_CLASS_SIGNATURE);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(env, cls, "takeSignature", "(Ljava/lang/String;Ljava/lang/Object;)V");
if (!mid) return;
jhstring objCallback = rho_cast<jhstring>(callback_url);
/*
char* image_format = 0;
if (p)
{
rho_param* pFF = rho_param_hash_get(p, "imageFormat");
if ( pFF )
image_format = pFF->v.string;
}
if (!image_format)
image_format = "";
jhstring objFormat = rho_cast<jhstring>(image_format);
env->CallStaticVoidMethod(cls, mid, objCallback.get(), objFormat.get());
*/
jobject paramsObj = RhoValueConverter(env).createObject(p);
env->CallStaticVoidMethod(cls, mid, objCallback.get(), paramsObj);
env->DeleteLocalRef(paramsObj);
}
RHO_GLOBAL void rho_signature_visible(bool visible, rho_param* p)
{
// check for RhoElements :
if (!rho_is_rho_elements_extension_can_be_used()) {
RAWLOG_ERROR("Rho::SignatureCapture.visible() is unavailable without RhoElements ! For more information go to http://www.motorolasolutions.com/rhoelements");
return;
}
JNIEnv *env = jnienv();
jclass cls = getJNIClass(RHODES_JAVA_CLASS_SIGNATURE);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(env, cls, "inline_signature_visible", "(ILjava/lang/Object;)V");
if (!mid) return;
jobject paramsObj = RhoValueConverter(env).createObject(p);
env->CallStaticVoidMethod(cls, mid, visible, paramsObj);
env->DeleteLocalRef(paramsObj);
}
RHO_GLOBAL void rho_signature_capture(const char* callback_url)
{
// check for RhoElements :
if (!rho_is_rho_elements_extension_can_be_used()) {
RAWLOG_ERROR("Rho::SignatureCapture.capture() is unavailable without RhoElements ! For more information go to http://www.motorolasolutions.com/rhoelements");
return;
}
JNIEnv *env = jnienv();
jclass cls = getJNIClass(RHODES_JAVA_CLASS_SIGNATURE);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(env, cls, "inline_signature_capture", "(Ljava/lang/String;)V");
if (!mid) return;
jhstring objCallback = rho_cast<jhstring>(callback_url);
env->CallStaticVoidMethod(cls, mid, objCallback.get());
}
RHO_GLOBAL void rho_signature_clear()
{
// check for RhoElements :
if (!rho_is_rho_elements_extension_can_be_used()) {
RAWLOG_ERROR("Rho::SignatureCapture.clear() is unavailable without RhoElements ! For more information go to http://www.motorolasolutions.com/rhoelements");
return;
}
JNIEnv *env = jnienv();
jclass cls = getJNIClass(RHODES_JAVA_CLASS_SIGNATURE);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(env, cls, "inline_signature_clear", "()V");
if (!mid) return;
env->CallStaticVoidMethod(cls, mid);
}
|
/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "rhodes/JNIRhodes.h"
#include "rhodes/JNIRhoRuby.h"
#include "rhodes/jni/com_rhomobile_rhodes_signature_Signature.h"
#include <common/rhoparams.h>
#include <common/RhodesApp.h>
#include <logging/RhoLog.h>
#include "ruby/ext/rho/rhoruby.h"
#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "Signature"
RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_signature_Signature_callback
(JNIEnv *env, jclass, jstring callback, jstring filePath, jstring error, jboolean cancelled)
{
rho_rhodesapp_callSignatureCallback(rho_cast<std::string>(callback).c_str(),
rho_cast<std::string>(filePath).c_str(), rho_cast<std::string>(error).c_str(), cancelled);
}
RHO_GLOBAL void rho_signature_take(char* callback_url, rho_param* p)
{
JNIEnv *env = jnienv();
jclass cls = getJNIClass(RHODES_JAVA_CLASS_SIGNATURE);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(env, cls, "takeSignature", "(Ljava/lang/String;Ljava/lang/Object;)V");
if (!mid) return;
jhstring objCallback = rho_cast<jhstring>(callback_url);
/*
char* image_format = 0;
if (p)
{
rho_param* pFF = rho_param_hash_get(p, "imageFormat");
if ( pFF )
image_format = pFF->v.string;
}
if (!image_format)
image_format = "";
jhstring objFormat = rho_cast<jhstring>(image_format);
env->CallStaticVoidMethod(cls, mid, objCallback.get(), objFormat.get());
*/
jobject paramsObj = RhoValueConverter(env).createObject(p);
env->CallStaticVoidMethod(cls, mid, objCallback.get(), paramsObj);
env->DeleteLocalRef(paramsObj);
}
RHO_GLOBAL void rho_signature_visible(bool visible, rho_param* p)
{
// check for RhoElements :
#ifndef APP_BUILD_CAPABILITY_MOTOROLA
#ifndef APP_BUILD_CAPABILITY_MOTOROLA_BROWSER
if (!rho_is_rho_elements_extension_can_be_used()) {
RAWLOG_ERROR("Rho::SignatureCapture.visible() is unavailable without RhoElements ! For more information go to http://www.motorolasolutions.com/rhoelements");
return;
}
#endif
#endif
JNIEnv *env = jnienv();
jclass cls = getJNIClass(RHODES_JAVA_CLASS_SIGNATURE);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(env, cls, "inline_signature_visible", "(ILjava/lang/Object;)V");
if (!mid) return;
jobject paramsObj = RhoValueConverter(env).createObject(p);
env->CallStaticVoidMethod(cls, mid, visible, paramsObj);
env->DeleteLocalRef(paramsObj);
}
RHO_GLOBAL void rho_signature_capture(const char* callback_url)
{
// check for RhoElements :
#ifndef APP_BUILD_CAPABILITY_MOTOROLA
#ifndef APP_BUILD_CAPABILITY_MOTOROLA_BROWSER
if (!rho_is_rho_elements_extension_can_be_used()) {
RAWLOG_ERROR("Rho::SignatureCapture.capture() is unavailable without RhoElements ! For more information go to http://www.motorolasolutions.com/rhoelements");
return;
}
#endif
#endif
JNIEnv *env = jnienv();
jclass cls = getJNIClass(RHODES_JAVA_CLASS_SIGNATURE);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(env, cls, "inline_signature_capture", "(Ljava/lang/String;)V");
if (!mid) return;
jhstring objCallback = rho_cast<jhstring>(callback_url);
env->CallStaticVoidMethod(cls, mid, objCallback.get());
}
RHO_GLOBAL void rho_signature_clear()
{
// check for RhoElements :
#ifndef APP_BUILD_CAPABILITY_MOTOROLA
#ifndef APP_BUILD_CAPABILITY_MOTOROLA_BROWSER
if (!rho_is_rho_elements_extension_can_be_used()) {
RAWLOG_ERROR("Rho::SignatureCapture.clear() is unavailable without RhoElements ! For more information go to http://www.motorolasolutions.com/rhoelements");
return;
}
#endif
#endif
JNIEnv *env = jnienv();
jclass cls = getJNIClass(RHODES_JAVA_CLASS_SIGNATURE);
if (!cls) return;
jmethodID mid = getJNIClassStaticMethod(env, cls, "inline_signature_clear", "()V");
if (!mid) return;
env->CallStaticVoidMethod(cls, mid);
}
|
remove licence checking inside inline signature capture for motorola capability
|
remove licence checking inside inline signature capture for motorola capability
|
C++
|
mit
|
louisatome/rhodes,rhosilver/rhodes-1,rhosilver/rhodes-1,UIKit0/rhodes,louisatome/rhodes,louisatome/rhodes,louisatome/rhodes,UIKit0/rhodes,louisatome/rhodes,nosolosoftware/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,nosolosoftware/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,louisatome/rhodes,nosolosoftware/rhodes,UIKit0/rhodes,nosolosoftware/rhodes,rhosilver/rhodes-1,nosolosoftware/rhodes,rhosilver/rhodes-1,nosolosoftware/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,louisatome/rhodes,rhosilver/rhodes-1,nosolosoftware/rhodes,UIKit0/rhodes,rhosilver/rhodes-1,louisatome/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,nosolosoftware/rhodes,louisatome/rhodes
|
2384dbd193aca4d9b96485907fc58e1223ac7d50
|
MiniZincIDE/highlighter.cpp
|
MiniZincIDE/highlighter.cpp
|
/*
* Author:
* Guido Tack <[email protected]>
*
* Copyright:
* NICTA 2013
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <QDebug>
#include "highlighter.h"
Highlighter::Highlighter(QFont& font, bool dm, QTextDocument *parent)
: QSyntaxHighlighter(parent), keywordColor(Qt::darkGreen), functionColor(Qt::blue), stringColor(Qt::darkRed), commentColor(Qt::red)
{
Rule rule;
commentFormat.setForeground(commentColor);
QStringList patterns;
patterns << "\\bann\\b" << "\\bannotation\\b" << "\\bany\\b"
<< "\\barray\\b" << "\\bbool\\b" << "\\bcase\\b"
<< "\\bconstraint\\b" << "\\bdefault\\b" << "\\bdiv\\b"
<< "\\bdiff\\b" << "\\belse\\b" << "\\belseif\\b"
<< "\\bendif\\b" << "\\benum\\b" << "\\bfloat\\b"
<< "\\bfunction\\b" << "\\bif\\b" << "\\binclude\\b"
<< "\\bintersect\\b" << "\\bin\\b" << "\\bint\\b"
<< "\\blet\\b" << "\\bmaximize\\b" << "\\bminimize\\b"
<< "\\bmod\\b" << "\\bnot\\b" << "\\bof\\b" << "\\boutput\\b"
<< "\\bopt\\b" << "\\bpar\\b" << "\\bpredicate\\b"
<< "\\brecord\\b" << "\\bsatisfy\\b" << "\\bset\\b"
<< "\\bsolve\\b" << "\\bstring\\b" << "\\bsubset\\b"
<< "\\bsuperset\\b" << "\\bsymdiff\\b" << "\\btest\\b"
<< "\\bthen\\b" << "\\btuple\\b" << "\\btype\\b"
<< "\\bunion\\b" << "\\bvar\\b" << "\\bvariant_record\\b"
<< "\\bwhere\\b" << "\\bxor\\b";
QTextCharFormat format;
format.setForeground(functionColor);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\s*\\()");
rule.format = format;
rules.append(rule);
format = QTextCharFormat();
format.setFontWeight(QFont::Bold);
format.setForeground(keywordColor);
for (int i=0; i<patterns.size(); i++) {
rule.pattern = QRegExp(patterns[i]);
rule.format = format;
rules.append(rule);
}
setEditorFont(font);
commentStartExp = QRegExp("/\\*");
commentEndExp = QRegExp("\\*/");
setDarkMode(dm);
}
void Highlighter::setEditorFont(QFont& font)
{
quoteFormat.setFont(font);
commentFormat.setFont(font);
for (int i=0; i<rules.size(); i++) {
rules[i].format.setFont(font);
}
}
bool fg_contains(const FixedBg& a, const FixedBg& b) {
return (a.sl < b.sl || (a.sl == b.sl && a.sc <= b.sc))
&& (a.el > b.el || (a.el == b.el && a.ec >= b.ec));
}
void Highlighter::addFixedBg(
unsigned int sl, unsigned int sc, unsigned int el, unsigned ec,
QColor colour, QString tip) {
FixedBg ifb {sl, sc, el, ec};
for(BgMap::iterator it = fixedBg.begin();
it != fixedBg.end();) {
const FixedBg& fb = it.key();
if (fg_contains(fb, ifb)) {
it = fixedBg.erase(it);
} else {
++it;
}
}
fixedBg.insert(ifb, QPair<QColor, QString>(colour, tip));
}
void Highlighter::clearFixedBg() {
fixedBg.clear();
}
void Highlighter::highlightBlock(const QString &text)
{
QTextBlock block = currentBlock();
BracketData* bd = new BracketData;
if (currentBlockUserData()) {
bd->d = static_cast<BracketData*>(currentBlockUserData())->d;
}
if (block.previous().userData()) {
bd->highlightingState = static_cast<BracketData*>(block.previous().userData())->highlightingState;
}
QRegExp noneRegExp("\"|%|/\\*");
QRegExp stringRegExp("\"|\\\\\\(");
QRegExp commentRegexp("\\*/");
QRegExp interpolateRegexp("[)\"%(]|/\\*");
QTextCharFormat stringFormat;
stringFormat.setForeground(stringColor);
QTextCharFormat interpolateFormat;
interpolateFormat.setFontItalic(true);
// Stage 1: find strings (including interpolations) and comments
QVector<HighlightingState>& highlightingState = bd->highlightingState;
int curPosition = 0;
HighlightingState currentState;
while (curPosition >= 0) {
currentState = highlightingState.empty() ? HS_NONE : highlightingState.back();
switch (currentState) {
case HS_NONE:
{
int nxt = noneRegExp.indexIn(text, curPosition);
if (nxt==-1) {
curPosition = -1;
} else {
if (text[nxt]=='"') {
highlightingState.push_back(HS_STRING);
curPosition = nxt+1;
} else if (text[nxt]=='%') {
setFormat(nxt, text.size()-nxt, commentFormat);
curPosition = -1;
} else {
// /*
highlightingState.push_back(HS_COMMENT);
curPosition = nxt+1;
}
}
}
break;
case HS_STRING:
{
int nxt = stringRegExp.indexIn(text, curPosition);
int stringStartIdx = curPosition==0 ? 0 : curPosition-1;
if (nxt==-1) {
setFormat(stringStartIdx, text.size()-stringStartIdx, stringFormat);
highlightingState.clear(); // this is an error, reset to NONE state
curPosition = -1;
} else {
if (text[nxt]=='"') {
setFormat(stringStartIdx, nxt-stringStartIdx+1, stringFormat);
curPosition = nxt+1;
highlightingState.pop_back();
} else {
setFormat(stringStartIdx, nxt-stringStartIdx+2, stringFormat);
curPosition = nxt+2;
highlightingState.push_back(HS_INTERPOLATE);
}
}
}
break;
case HS_COMMENT:
{
int nxt = commentRegexp.indexIn(text, curPosition);
int commentStartIdx = curPosition==0 ? 0 : curPosition-1;
if (nxt==-1) {
// EOL -> stay in COMMENT state
setFormat(commentStartIdx, text.size()-commentStartIdx, commentFormat);
curPosition = -1;
} else {
// finish comment
setFormat(commentStartIdx, nxt-commentStartIdx+2, commentFormat);
curPosition = nxt+1;
highlightingState.pop_back();
}
}
break;
case HS_INTERPOLATE:
{
int nxt = interpolateRegexp.indexIn(text, curPosition);
if (nxt==-1) {
// EOL -> stay in INTERPOLATE state
setFormat(curPosition, text.size()-curPosition, interpolateFormat);
curPosition = -1;
} else {
setFormat(curPosition, nxt-curPosition+1, interpolateFormat);
if (text[nxt]==')') {
curPosition = nxt+1;
highlightingState.pop_back();
} else if (text[nxt]=='(') {
curPosition = nxt+1;
highlightingState.push_back(HS_INTERPOLATE);
} else if (text[nxt]=='%') {
setFormat(nxt, text.size()-nxt, commentFormat);
curPosition = -1;
} else if (text[nxt]=='"') {
curPosition = nxt+1;
highlightingState.push_back(HS_STRING);
} else {
// /*
highlightingState.push_back(HS_COMMENT);
curPosition = nxt+1;
}
}
}
break;
}
}
currentState = highlightingState.empty() ? HS_NONE : highlightingState.back();
setCurrentBlockState(currentState);
// Stage 2: find keywords and functions
for (int i=0; i<rules.size(); i++) {
const Rule& rule = rules[i];
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
if (format(index)!=quoteFormat && format(index)!=commentFormat) {
if (format(index)==interpolateFormat) {
QTextCharFormat interpolateRule = rule.format;
interpolateRule.setFontItalic(true);
setFormat(index, length, interpolateRule);
} else {
setFormat(index, length, rule.format);
}
}
index = expression.indexIn(text, index + length);
}
}
// Stage 3: update bracket data
QRegExp re("\\(|\\)|\\{|\\}|\\[|\\]");
int pos = text.indexOf(re);
while (pos != -1) {
if (format(pos)!=quoteFormat && format(pos)!=commentFormat) {
Bracket b;
b.b = text.at(pos);
b.pos = pos;
bd->brackets.append(b);
}
pos = text.indexOf(re, pos+1);
}
setCurrentBlockUserData(bd);
// Stage 4: apply highlighting
for(QMap<FixedBg, QPair<QColor, QString> >::iterator it = fixedBg.begin();
it != fixedBg.end(); ++it) {
const FixedBg& fb = it.key();
QPair<QColor, QString> val = it.value();
QColor colour = val.first;
QString tip = val.second;
unsigned int blockNumber = block.blockNumber() + 1;
if(fb.sl <= blockNumber && fb.el >= blockNumber) {
int index = 0;
int length = block.length();
if(fb.sl == blockNumber) {
index = fb.sc - 1;
if(fb.sl == fb.el) {
length = fb.ec - index;
}
} else if(fb.el == blockNumber) {
length = fb.ec;
}
int endpos = index + length;
foreach(const QTextLayout::FormatRange& fr, block.textFormats()) {
//if(index >= fr.start && index <= fr.start + length) {
int local_index = fr.start < index ? index : fr.start;
int fr_endpos = fr.start + fr.length;
int local_len = (fr_endpos < endpos ? fr_endpos : endpos) - local_index;
QTextCharFormat fmt = fr.format;
fmt.setBackground(colour);
fmt.setToolTip(tip);
setFormat(local_index, local_len, fmt);
//}
}
}
}
}
#include <QTextCursor>
#include <QTextDocumentFragment>
#include <QTextLayout>
#include <QTextEdit>
#include <QApplication>
#include <QClipboard>
#include <QMimeData>
class MyMimeDataExporter : public QTextEdit {
public:
QMimeData* md(void) const {
QMimeData* mymd = createMimeDataFromSelection();
mymd->removeFormat("text/plain");
return mymd;
}
};
void Highlighter::copyHighlightedToClipboard(QTextCursor cursor)
{
QTextDocument* tempDocument(new QTextDocument);
Q_ASSERT(tempDocument);
QTextCursor tempCursor(tempDocument);
tempCursor.insertFragment(cursor.selection());
tempCursor.select(QTextCursor::Document);
QTextCharFormat textfmt = cursor.charFormat();
textfmt.setFont(quoteFormat.font());
tempCursor.setCharFormat(textfmt);
QTextBlock start = document()->findBlock(cursor.selectionStart());
QTextBlock end = document()->findBlock(cursor.selectionEnd());
end = end.next();
const int selectionStart = cursor.selectionStart();
const int endOfDocument = tempDocument->characterCount() - 1;
for(QTextBlock current = start; current.isValid() && current != end; current = current.next()) {
const QTextLayout* layout(current.layout());
foreach(const QTextLayout::FormatRange &range, layout->formats()) {
const int start = current.position() + range.start - selectionStart;
const int end = start + range.length;
if(end <= 0 || start >= endOfDocument)
continue;
tempCursor.setPosition(qMax(start, 0));
tempCursor.setPosition(qMin(end, endOfDocument), QTextCursor::KeepAnchor);
tempCursor.setCharFormat(range.format);
}
}
for(QTextBlock block = tempDocument->begin(); block.isValid(); block = block.next())
block.setUserState(-1);
tempCursor.select(QTextCursor::Document);
QTextBlockFormat blockFormat = cursor.blockFormat();
blockFormat.setNonBreakableLines(true);
tempCursor.setBlockFormat(blockFormat);
MyMimeDataExporter te;
te.setDocument(tempDocument);
te.selectAll();
QMimeData* mimeData = te.md();
QApplication::clipboard()->setMimeData(mimeData);
delete tempDocument;
}
void Highlighter::setDarkMode(bool enable)
{
darkMode = enable;
if (darkMode) {
keywordColor = QColor(0xbb86fc);
functionColor = QColor(0x13C4F5);
stringColor = QColor(0xF29F05);
commentColor = QColor(0x52514C);
} else {
keywordColor = Qt::darkGreen;
functionColor = Qt::blue;
stringColor = Qt::darkRed;
commentColor = Qt::red;
}
commentFormat.setForeground(commentColor);
rules[0].format.setForeground(functionColor);
for (int i=1; i<rules.size(); i++) {
rules[i].format.setForeground(keywordColor);
}
}
|
/*
* Author:
* Guido Tack <[email protected]>
*
* Copyright:
* NICTA 2013
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <QDebug>
#include "highlighter.h"
Highlighter::Highlighter(QFont& font, bool dm, QTextDocument *parent)
: QSyntaxHighlighter(parent), keywordColor(Qt::darkGreen), functionColor(Qt::blue), stringColor(Qt::darkRed), commentColor(Qt::red)
{
Rule rule;
commentFormat.setForeground(commentColor);
QStringList patterns;
patterns << "\\bann\\b" << "\\bannotation\\b" << "\\bany\\b"
<< "\\barray\\b" << "\\bbool\\b" << "\\bcase\\b"
<< "\\bconstraint\\b" << "\\bdefault\\b" << "\\bdiv\\b"
<< "\\bdiff\\b" << "\\belse\\b" << "\\belseif\\b"
<< "\\bendif\\b" << "\\benum\\b" << "\\bfloat\\b"
<< "\\bfunction\\b" << "\\bif\\b" << "\\binclude\\b"
<< "\\bintersect\\b" << "\\bin\\b" << "\\bint\\b"
<< "\\blet\\b" << "\\bmaximize\\b" << "\\bminimize\\b"
<< "\\bmod\\b" << "\\bnot\\b" << "\\bof\\b" << "\\boutput\\b"
<< "\\bopt\\b" << "\\bpar\\b" << "\\bpredicate\\b"
<< "\\brecord\\b" << "\\bsatisfy\\b" << "\\bset\\b"
<< "\\bsolve\\b" << "\\bstring\\b" << "\\bsubset\\b"
<< "\\bsuperset\\b" << "\\bsymdiff\\b" << "\\btest\\b"
<< "\\bthen\\b" << "\\btuple\\b" << "\\btype\\b"
<< "\\bunion\\b" << "\\bvar\\b" << "\\bvariant_record\\b"
<< "\\bwhere\\b" << "\\bxor\\b";
QTextCharFormat format;
format.setForeground(functionColor);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\s*\\()");
rule.format = format;
rules.append(rule);
format = QTextCharFormat();
format.setFontWeight(QFont::Bold);
format.setForeground(keywordColor);
for (int i=0; i<patterns.size(); i++) {
rule.pattern = QRegExp(patterns[i]);
rule.format = format;
rules.append(rule);
}
setEditorFont(font);
commentStartExp = QRegExp("/\\*");
commentEndExp = QRegExp("\\*/");
setDarkMode(dm);
}
void Highlighter::setEditorFont(QFont& font)
{
quoteFormat.setFont(font);
commentFormat.setFont(font);
for (int i=0; i<rules.size(); i++) {
rules[i].format.setFont(font);
}
}
bool fg_contains(const FixedBg& a, const FixedBg& b) {
return (a.sl < b.sl || (a.sl == b.sl && a.sc <= b.sc))
&& (a.el > b.el || (a.el == b.el && a.ec >= b.ec));
}
void Highlighter::addFixedBg(
unsigned int sl, unsigned int sc, unsigned int el, unsigned ec,
QColor colour, QString tip) {
FixedBg ifb {sl, sc, el, ec};
for(BgMap::iterator it = fixedBg.begin();
it != fixedBg.end();) {
const FixedBg& fb = it.key();
if (fg_contains(fb, ifb)) {
it = fixedBg.erase(it);
} else {
++it;
}
}
fixedBg.insert(ifb, QPair<QColor, QString>(colour, tip));
}
void Highlighter::clearFixedBg() {
fixedBg.clear();
}
void Highlighter::highlightBlock(const QString &text)
{
QTextBlock block = currentBlock();
BracketData* bd = new BracketData;
if (currentBlockUserData()) {
bd->d = static_cast<BracketData*>(currentBlockUserData())->d;
}
if (block.previous().userData()) {
bd->highlightingState = static_cast<BracketData*>(block.previous().userData())->highlightingState;
}
QRegExp noneRegExp("\"|%|/\\*");
QRegExp stringRegExp("\"|\\\\\\(");
QRegExp commentRegexp("\\*/");
QRegExp interpolateRegexp("[)\"%(]|/\\*");
QTextCharFormat stringFormat;
stringFormat.setForeground(stringColor);
stringFormat.setFontItalic(true);
QTextCharFormat interpolateFormat;
interpolateFormat.setFontItalic(true);
// Stage 1: find strings (including interpolations) and comments
QVector<HighlightingState>& highlightingState = bd->highlightingState;
int curPosition = 0;
HighlightingState currentState;
while (curPosition >= 0) {
currentState = highlightingState.empty() ? HS_NONE : highlightingState.back();
switch (currentState) {
case HS_NONE:
{
int nxt = noneRegExp.indexIn(text, curPosition);
if (nxt==-1) {
curPosition = -1;
} else {
if (text[nxt]=='"') {
highlightingState.push_back(HS_STRING);
curPosition = nxt+1;
} else if (text[nxt]=='%') {
setFormat(nxt, text.size()-nxt, commentFormat);
curPosition = -1;
} else {
// /*
highlightingState.push_back(HS_COMMENT);
curPosition = nxt+1;
}
}
}
break;
case HS_STRING:
{
int nxt = stringRegExp.indexIn(text, curPosition);
int stringStartIdx = curPosition==0 ? 0 : curPosition-1;
if (nxt==-1) {
setFormat(stringStartIdx, text.size()-stringStartIdx, stringFormat);
highlightingState.clear(); // this is an error, reset to NONE state
curPosition = -1;
} else {
if (text[nxt]=='"') {
setFormat(stringStartIdx, nxt-stringStartIdx+1, stringFormat);
curPosition = nxt+1;
highlightingState.pop_back();
} else {
setFormat(stringStartIdx, nxt-stringStartIdx+2, stringFormat);
curPosition = nxt+2;
highlightingState.push_back(HS_INTERPOLATE);
}
}
}
break;
case HS_COMMENT:
{
int nxt = commentRegexp.indexIn(text, curPosition);
int commentStartIdx = curPosition==0 ? 0 : curPosition-1;
if (nxt==-1) {
// EOL -> stay in COMMENT state
setFormat(commentStartIdx, text.size()-commentStartIdx, commentFormat);
curPosition = -1;
} else {
// finish comment
setFormat(commentStartIdx, nxt-commentStartIdx+2, commentFormat);
curPosition = nxt+1;
highlightingState.pop_back();
}
}
break;
case HS_INTERPOLATE:
{
int nxt = interpolateRegexp.indexIn(text, curPosition);
if (nxt==-1) {
// EOL -> stay in INTERPOLATE state
setFormat(curPosition, text.size()-curPosition, interpolateFormat);
curPosition = -1;
} else {
setFormat(curPosition, nxt-curPosition+1, interpolateFormat);
if (text[nxt]==')') {
curPosition = nxt+1;
highlightingState.pop_back();
} else if (text[nxt]=='(') {
curPosition = nxt+1;
highlightingState.push_back(HS_INTERPOLATE);
} else if (text[nxt]=='%') {
setFormat(nxt, text.size()-nxt, commentFormat);
curPosition = -1;
} else if (text[nxt]=='"') {
curPosition = nxt+1;
highlightingState.push_back(HS_STRING);
} else {
// /*
highlightingState.push_back(HS_COMMENT);
curPosition = nxt+1;
}
}
}
break;
}
}
currentState = highlightingState.empty() ? HS_NONE : highlightingState.back();
setCurrentBlockState(currentState);
// Stage 2: find keywords and functions
for (int i=0; i<rules.size(); i++) {
const Rule& rule = rules[i];
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
if (format(index)!=quoteFormat && format(index)!=commentFormat) {
if (format(index)==interpolateFormat) {
QTextCharFormat interpolateRule = rule.format;
interpolateRule.setFontItalic(true);
setFormat(index, length, interpolateRule);
} else {
setFormat(index, length, rule.format);
}
}
index = expression.indexIn(text, index + length);
}
}
// Stage 3: update bracket data
QRegExp re("\\(|\\)|\\{|\\}|\\[|\\]");
int pos = text.indexOf(re);
while (pos != -1) {
if (format(pos)!=quoteFormat && format(pos)!=commentFormat) {
Bracket b;
b.b = text.at(pos);
b.pos = pos;
bd->brackets.append(b);
}
pos = text.indexOf(re, pos+1);
}
setCurrentBlockUserData(bd);
// Stage 4: apply highlighting
for(QMap<FixedBg, QPair<QColor, QString> >::iterator it = fixedBg.begin();
it != fixedBg.end(); ++it) {
const FixedBg& fb = it.key();
QPair<QColor, QString> val = it.value();
QColor colour = val.first;
QString tip = val.second;
unsigned int blockNumber = block.blockNumber() + 1;
if(fb.sl <= blockNumber && fb.el >= blockNumber) {
int index = 0;
int length = block.length();
if(fb.sl == blockNumber) {
index = fb.sc - 1;
if(fb.sl == fb.el) {
length = fb.ec - index;
}
} else if(fb.el == blockNumber) {
length = fb.ec;
}
int endpos = index + length;
foreach(const QTextLayout::FormatRange& fr, block.textFormats()) {
//if(index >= fr.start && index <= fr.start + length) {
int local_index = fr.start < index ? index : fr.start;
int fr_endpos = fr.start + fr.length;
int local_len = (fr_endpos < endpos ? fr_endpos : endpos) - local_index;
QTextCharFormat fmt = fr.format;
fmt.setBackground(colour);
fmt.setToolTip(tip);
setFormat(local_index, local_len, fmt);
//}
}
}
}
}
#include <QTextCursor>
#include <QTextDocumentFragment>
#include <QTextLayout>
#include <QTextEdit>
#include <QApplication>
#include <QClipboard>
#include <QMimeData>
class MyMimeDataExporter : public QTextEdit {
public:
QMimeData* md(void) const {
QMimeData* mymd = createMimeDataFromSelection();
mymd->removeFormat("text/plain");
return mymd;
}
};
void Highlighter::copyHighlightedToClipboard(QTextCursor cursor)
{
QTextDocument* tempDocument(new QTextDocument);
Q_ASSERT(tempDocument);
QTextCursor tempCursor(tempDocument);
tempCursor.insertFragment(cursor.selection());
tempCursor.select(QTextCursor::Document);
QTextCharFormat textfmt = cursor.charFormat();
textfmt.setFont(quoteFormat.font());
tempCursor.setCharFormat(textfmt);
QTextBlock start = document()->findBlock(cursor.selectionStart());
QTextBlock end = document()->findBlock(cursor.selectionEnd());
end = end.next();
const int selectionStart = cursor.selectionStart();
const int endOfDocument = tempDocument->characterCount() - 1;
for(QTextBlock current = start; current.isValid() && current != end; current = current.next()) {
const QTextLayout* layout(current.layout());
foreach(const QTextLayout::FormatRange &range, layout->formats()) {
const int start = current.position() + range.start - selectionStart;
const int end = start + range.length;
if(end <= 0 || start >= endOfDocument)
continue;
tempCursor.setPosition(qMax(start, 0));
tempCursor.setPosition(qMin(end, endOfDocument), QTextCursor::KeepAnchor);
tempCursor.setCharFormat(range.format);
}
}
for(QTextBlock block = tempDocument->begin(); block.isValid(); block = block.next())
block.setUserState(-1);
tempCursor.select(QTextCursor::Document);
QTextBlockFormat blockFormat = cursor.blockFormat();
blockFormat.setNonBreakableLines(true);
tempCursor.setBlockFormat(blockFormat);
MyMimeDataExporter te;
te.setDocument(tempDocument);
te.selectAll();
QMimeData* mimeData = te.md();
QApplication::clipboard()->setMimeData(mimeData);
delete tempDocument;
}
void Highlighter::setDarkMode(bool enable)
{
darkMode = enable;
if (darkMode) {
keywordColor = QColor(0xbb86fc);
functionColor = QColor(0x13C4F5);
stringColor = QColor(0xF29F05);
commentColor = QColor(0x52514C);
} else {
keywordColor = Qt::darkGreen;
functionColor = Qt::blue;
stringColor = Qt::darkRed;
commentColor = Qt::red;
}
commentFormat.setForeground(commentColor);
rules[0].format.setForeground(functionColor);
for (int i=1; i<rules.size(); i++) {
rules[i].format.setForeground(keywordColor);
}
}
|
Make strings italic (to match interpolated strings)
|
Make strings italic (to match interpolated strings)
|
C++
|
mpl-2.0
|
MiniZinc/MiniZincIDE,MiniZinc/MiniZincIDE,MiniZinc/MiniZincIDE,MiniZinc/MiniZincIDE
|
ffa9ef8d45c2423bf73aaad604f15bc9fd2e0383
|
projects/test_kernel/src/main_test_kernel.cpp
|
projects/test_kernel/src/main_test_kernel.cpp
|
/* * Copyright (c) 2015 Regents of the University of California. 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 names of its contributors may not 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.
*
* *********************************************************************************************** *
* CARLsim
* created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
* maintained by:
* (MA) Mike Avery <[email protected]>
* (MB) Michael Beyeler <[email protected]>,
* (KDC) Kristofor Carlson <[email protected]>
* (TSC) Ting-Shuo Chou <[email protected]>
*
* CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/
* Ver 5/22/2015
*/
// include CARLsim user interface
#include <carlsim.h>
#define N_EXC 800
#define N_INH 200
//class FixedSpikeGenerator : public SpikeGenerator {
//public:
// FixedSpikeGenerator() {}
//
// int nextSpikeTime(CARLsim* sim, int grpId, int nid, int currentTime, int lastScheduledSpikeTime, int endOfTimeSlice) {
// if (lastScheduledSpikeTime <= currentTime)
// return currentTime + nid + 100;
// else
// return endOfTimeSlice + 1;
// }
//};
int main() {
// create a network on GPU
int numCPUs = 2;
int randSeed = 42;
float pConn = 100.0f / (N_EXC + N_INH); // connection probability
CARLsim sim("test kernel", HYBRID_MODE, USER, 0, randSeed);
// configure the network
int gExc = sim.createGroup("exc", N_EXC, EXCITATORY_NEURON, 1, CPU_CORES);
sim.setNeuronParameters(gExc, 0.02f, 0.2f, -65.0f, 8.0f); // RS
int gExc2 = sim.createGroup("exc2", N_EXC, EXCITATORY_NEURON, 1, CPU_CORES);
sim.setNeuronParameters(gExc2, 0.02f, 0.2f, -65.0f, 8.0f);
int gInh = sim.createGroup("inh", N_INH, INHIBITORY_NEURON, 1, CPU_CORES);
sim.setNeuronParameters(gInh, 0.1f, 0.2f, -65.0f, 2.0f); // FS
int gInh2 = sim.createGroup("inh2", N_INH, INHIBITORY_NEURON, 1, CPU_CORES);
sim.setNeuronParameters(gInh2, 0.1f, 0.2f, -65.0f, 2.0f);
//int gExc2 = sim.createGroup("exc", N_EXC, EXCITATORY_NEURON);
//sim.setNeuronParameters(gExc2, 0.02f, 0.2f, -65.0f, 8.0f); // RS
int gInput = sim.createSpikeGeneratorGroup("input", N_EXC, EXCITATORY_NEURON, 1, CPU_CORES);
int gInput2 = sim.createSpikeGeneratorGroup("input2", N_EXC, EXCITATORY_NEURON, 1, CPU_CORES);
//FixedSpikeGenerator* f1 = new FixedSpikeGenerator();
//sim.setSpikeGenerator(gInput, f1);
//FixedSpikeGenerator* f2 = new FixedSpikeGenerator();
//sim.setSpikeGenerator(gInput2, f2);
sim.connect(gInput, gExc, "one-to-one", RangeWeight(30.0f), 1.0f, RangeDelay(1), RadiusRF(-1), SYN_FIXED);
sim.connect(gExc, gExc, "random", RangeWeight(6.0f), pConn, RangeDelay(1, 20), RadiusRF(-1), SYN_FIXED);
sim.connect(gExc, gInh, "random", RangeWeight(6.0f), pConn, RangeDelay(1, 20), RadiusRF(-1), SYN_FIXED);
sim.connect(gInh, gExc, "random", RangeWeight(5.0f), pConn * 1.25f, RangeDelay(1), RadiusRF(-1), SYN_FIXED);
sim.connect(gInput2, gExc2, "one-to-one", RangeWeight(30.0f), 1.0f, RangeDelay(1), RadiusRF(-1), SYN_FIXED);
sim.connect(gExc2, gExc2, "random", RangeWeight(6.0f), pConn, RangeDelay(1, 20), RadiusRF(-1), SYN_FIXED);
sim.connect(gExc2, gInh2, "random", RangeWeight(6.0f), pConn, RangeDelay(1, 20), RadiusRF(-1), SYN_FIXED);
sim.connect(gInh2, gExc2, "random", RangeWeight(5.0f), pConn * 1.25f, RangeDelay(1), RadiusRF(-1), SYN_FIXED);
sim.setConductances(false);
//sim.setESTDP(gExc, true, STANDARD, ExpCurve(0.1f/100, 20, -0.12f/100, 20));
// build the network
sim.setupNetwork();
// set some monitors
SpikeMonitor* smExc = sim.setSpikeMonitor(gExc, "NULL");
SpikeMonitor* smInh = sim.setSpikeMonitor(gInh, "NULL");
SpikeMonitor* smInput = sim.setSpikeMonitor(gInput, "NULL");
SpikeMonitor* smExc2 = sim.setSpikeMonitor(gExc2, "NULL");
SpikeMonitor* smInh2 = sim.setSpikeMonitor(gInh2, "NULL");
SpikeMonitor* smInput2 = sim.setSpikeMonitor(gInput2, "NULL");
//ConnectionMonitor* cmEE = sim.setConnectionMonitor(gExc, gInh, "DEFAULT");
//setup some baseline input
PoissonRate in(N_EXC);
in.setRates(1.0f);
sim.setSpikeRate(gInput, &in);
PoissonRate in2(N_EXC);
in2.setRates(1.0f);
sim.setSpikeRate(gInput2, &in2);
// run for a total of 10 seconds
// at the end of each runNetwork call, SpikeMonitor stats will be printed
//smInput->startRecording();
//smExc->startRecording();
//smInh->startRecording();
for (int t = 0; t < 10; t++) {
sim.runNetwork(1, 0, true);
}
//smInput->stopRecording();
//smExc->stopRecording();
//smInh->stopRecording();
//smExc->print(false);
//smInh->print(false);
//smInput->print(false);
return 0;
}
|
/* * Copyright (c) 2015 Regents of the University of California. 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 names of its contributors may not 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.
*
* *********************************************************************************************** *
* CARLsim
* created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
* maintained by:
* (MA) Mike Avery <[email protected]>
* (MB) Michael Beyeler <[email protected]>,
* (KDC) Kristofor Carlson <[email protected]>
* (TSC) Ting-Shuo Chou <[email protected]>
*
* CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/
* Ver 5/22/2015
*/
// include CARLsim user interface
#include <carlsim.h>
#define N_EXC 1
int main() {
// create a network on GPU
int randSeed = 42;
CARLsim sim("test kernel", GPU_MODE, USER, 0, randSeed);
// configure the network
int gExc = sim.createGroup("exc", N_EXC, EXCITATORY_NEURON, 0, GPU_CORES);
sim.setNeuronParameters(gExc, 0.02f, 0.2f, -65.0f, 8.0f); // RS
// set up a dummy (connection probability of 0) connection
int gInput = sim.createSpikeGeneratorGroup("input", N_EXC, EXCITATORY_NEURON, 0, GPU_CORES);
sim.connect(gInput, gExc, "one-to-one", RangeWeight(30.0f), 0.0f, RangeDelay(1), RadiusRF(-1), SYN_FIXED);
sim.setConductances(false);
// build the network
sim.setupNetwork();
// set some monitors
SpikeMonitor* smExc = sim.setSpikeMonitor(gExc, "NULL");
//SpikeMonitor* smInput = sim.setSpikeMonitor(gInput, "NULL");
//setup some baseline input
//PoissonRate in(N_EXC);
//in.setRates(1.0f);
//sim.setSpikeRate(gInput, &in);
//smInput->startRecording();
smExc->startRecording();
for (int t = 0; t < 1; t++) {
sim.runNetwork(0, 100, true);
sim.setExternalCurrent(gExc, 5);
sim.runNetwork(0, 900, true);
}
//smInput->stopRecording();
smExc->stopRecording();
smExc->print(true);
//Expected Spike Times: 108 196 293 390 487 584 681 778 875 972
//smInput->print(false);
return 0;
}
|
Set up feat/RK4 branch. Changed test_kernel to serve as a testing site for 4 & 9 parameter Izhikevich models.
|
Set up feat/RK4 branch. Changed test_kernel to serve as a testing site for 4 & 9 parameter Izhikevich models.
|
C++
|
mit
|
UCI-CARL/CARLsim4,UCI-CARL/CARLsim4,UCI-CARL/CARLsim4,UCI-CARL/CARLsim4,UCI-CARL/CARLsim4,UCI-CARL/CARLsim4
|
f07aa01a116d1f1c828ad4e08500b80e3f41d350
|
deal.II/source/lac/petsc_sparse_matrix.cc
|
deal.II/source/lac/petsc_sparse_matrix.cc
|
//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2004, 2005, 2006, 2008 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <lac/petsc_sparse_matrix.h>
#ifdef DEAL_II_USE_PETSC
# include <lac/petsc_vector.h>
# include <lac/sparsity_pattern.h>
# include <lac/compressed_sparsity_pattern.h>
# include <lac/compressed_simple_sparsity_pattern.h>
DEAL_II_NAMESPACE_OPEN
namespace PETScWrappers
{
SparseMatrix::SparseMatrix ()
{
const int m=0, n=0, n_nonzero_per_row=0;
const int ierr
= MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, n_nonzero_per_row,
0, &matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
SparseMatrix::SparseMatrix (const unsigned int m,
const unsigned int n,
const unsigned int n_nonzero_per_row,
const bool is_symmetric)
{
do_reinit (m, n, n_nonzero_per_row, is_symmetric);
}
SparseMatrix::SparseMatrix (const unsigned int m,
const unsigned int n,
const std::vector<unsigned int> &row_lengths,
const bool is_symmetric)
{
do_reinit (m, n, row_lengths, is_symmetric);
}
template <typename SparsityType>
SparseMatrix::
SparseMatrix (const SparsityType &sparsity_pattern,
const bool preset_nonzero_locations)
{
do_reinit (sparsity_pattern, preset_nonzero_locations);
}
SparseMatrix &
SparseMatrix::operator = (const double d)
{
MatrixBase::operator = (d);
return *this;
}
void
SparseMatrix::reinit (const unsigned int m,
const unsigned int n,
const unsigned int n_nonzero_per_row,
const bool is_symmetric)
{
// get rid of old matrix and generate a
// new one
const int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
do_reinit (m, n, n_nonzero_per_row, is_symmetric);
}
void
SparseMatrix::reinit (const unsigned int m,
const unsigned int n,
const std::vector<unsigned int> &row_lengths,
const bool is_symmetric)
{
// get rid of old matrix and generate a
// new one
const int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
do_reinit (m, n, row_lengths, is_symmetric);
}
template <typename SparsityType>
void
SparseMatrix::
reinit (const SparsityType &sparsity_pattern,
const bool preset_nonzero_locations)
{
// get rid of old matrix and generate a
// new one
const int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
do_reinit (sparsity_pattern, preset_nonzero_locations);
}
const MPI_Comm &
SparseMatrix::get_mpi_communicator () const
{
static const MPI_Comm communicator = MPI_COMM_SELF;
return communicator;
}
void
SparseMatrix::do_reinit (const unsigned int m,
const unsigned int n,
const unsigned int n_nonzero_per_row,
const bool is_symmetric)
{
// use the call sequence indicating only
// a maximal number of elements per row
// for all rows globally
const int ierr
= MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, n_nonzero_per_row,
0, &matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// set symmetric flag, if so requested
if (is_symmetric == true)
{
#if DEAL_II_PETSC_VERSION_LT(3,0,0)
const int ierr
= MatSetOption (matrix, MAT_SYMMETRIC);
#else
const int ierr
= MatSetOption (matrix, MAT_SYMMETRIC, PETSC_TRUE);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
}
void
SparseMatrix::do_reinit (const unsigned int m,
const unsigned int n,
const std::vector<unsigned int> &row_lengths,
const bool is_symmetric)
{
Assert (row_lengths.size() == m,
ExcDimensionMismatch (row_lengths.size(), m));
// use the call sequence indicating a
// maximal number of elements for each
// row individually. annoyingly, we
// always use unsigned ints for cases
// like this, while PETSc wants to see
// signed integers. so we have to
// convert, unless we want to play dirty
// tricks with conversions of pointers
#ifdef PETSC_USE_64BIT_INDICES
const std::vector<PetscInt>
#else
const std::vector<int>
#endif
int_row_lengths (row_lengths.begin(), row_lengths.end());
const int ierr
= MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, 0,
&int_row_lengths[0], &matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// set symmetric flag, if so requested
if (is_symmetric == true)
{
#if DEAL_II_PETSC_VERSION_LT(3,0,0)
const int ierr
= MatSetOption (matrix, MAT_SYMMETRIC);
#else
const int ierr
= MatSetOption (matrix, MAT_SYMMETRIC, PETSC_TRUE);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
}
template <typename SparsityType>
void
SparseMatrix::do_reinit (const SparsityType &sparsity_pattern,
const bool preset_nonzero_locations)
{
std::vector<unsigned int> row_lengths (sparsity_pattern.n_rows());
for (unsigned int i=0; i<sparsity_pattern.n_rows(); ++i)
row_lengths[i] = sparsity_pattern.row_length (i);
do_reinit (sparsity_pattern.n_rows(),
sparsity_pattern.n_cols(),
row_lengths, false);
// next preset the exact given matrix
// entries with zeros, if the user
// requested so. this doesn't avoid any
// memory allocations, but it at least
// avoids some searches later on. the
// key here is that we can use the
// matrix set routines that set an
// entire row at once, not a single
// entry at a time
//
// for the usefulness of this option
// read the documentation of this
// class.
if (preset_nonzero_locations == true)
{
#ifdef PETSC_USE_64BIT_INDICES
std::vector<PetscInt>
#else
std::vector<int>
#endif
row_entries;
std::vector<PetscScalar> row_values;
for (unsigned int i=0; i<sparsity_pattern.n_rows(); ++i)
{
row_entries.resize (row_lengths[i]);
row_values.resize (row_lengths[i], 0.0);
for (unsigned int j=0; j<row_lengths[i]; ++j)
row_entries[j] = sparsity_pattern.column_number (i,j);
#ifdef PETSC_USE_64BIT_INDICES
const PetscInt
#else
const int
#endif
int_row = i;
MatSetValues (matrix, 1, &int_row,
row_lengths[i], &row_entries[0],
&row_values[0], INSERT_VALUES);
}
compress ();
// Tell PETSc that we are not
// planning on adding new entries
// to the matrix. Generate errors
// in debugmode.
#if DEAL_II_PETSC_VERSION_LT(3,0,0)
int ierr;
#ifdef DEBUG
ierr = MatSetOption (matrix, MAT_NEW_NONZERO_LOCATION_ERR);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#else
ierr = MatSetOption (matrix, MAT_NO_NEW_NONZERO_LOCATIONS);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#endif
#else
int ierr;
#ifdef DEBUG
ierr = MatSetOption (matrix, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#else
ierr = MatSetOption (matrix, MAT_NEW_NONZERO_LOCATIONS, PETSC_FALSE);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#endif
#endif
}
}
// Explicit instantiations
//
template
SparseMatrix::SparseMatrix (const SparsityPattern &,
const bool);
template
SparseMatrix::SparseMatrix (const CompressedSparsityPattern &,
const bool);
template
SparseMatrix::SparseMatrix (const CompressedSimpleSparsityPattern &,
const bool);
template void
SparseMatrix::reinit (const SparsityPattern &,
const bool);
template void
SparseMatrix::reinit (const CompressedSparsityPattern &,
const bool);
template void
SparseMatrix::reinit (const CompressedSimpleSparsityPattern &,
const bool);
template void
SparseMatrix::do_reinit (const SparsityPattern &,
const bool);
template void
SparseMatrix::do_reinit (const CompressedSparsityPattern &,
const bool);
template void
SparseMatrix::do_reinit (const CompressedSimpleSparsityPattern &,
const bool);
}
DEAL_II_NAMESPACE_CLOSE
#endif // DEAL_II_USE_PETSC
|
//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2004, 2005, 2006, 2008 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <lac/petsc_sparse_matrix.h>
#ifdef DEAL_II_USE_PETSC
# include <lac/petsc_vector.h>
# include <lac/sparsity_pattern.h>
# include <lac/compressed_sparsity_pattern.h>
# include <lac/compressed_simple_sparsity_pattern.h>
DEAL_II_NAMESPACE_OPEN
namespace PETScWrappers
{
SparseMatrix::SparseMatrix ()
{
const int m=0, n=0, n_nonzero_per_row=0;
const int ierr
= MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, n_nonzero_per_row,
0, &matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
SparseMatrix::SparseMatrix (const unsigned int m,
const unsigned int n,
const unsigned int n_nonzero_per_row,
const bool is_symmetric)
{
do_reinit (m, n, n_nonzero_per_row, is_symmetric);
}
SparseMatrix::SparseMatrix (const unsigned int m,
const unsigned int n,
const std::vector<unsigned int> &row_lengths,
const bool is_symmetric)
{
do_reinit (m, n, row_lengths, is_symmetric);
}
template <typename SparsityType>
SparseMatrix::
SparseMatrix (const SparsityType &sparsity_pattern,
const bool preset_nonzero_locations)
{
do_reinit (sparsity_pattern, preset_nonzero_locations);
}
SparseMatrix &
SparseMatrix::operator = (const double d)
{
MatrixBase::operator = (d);
return *this;
}
void
SparseMatrix::reinit (const unsigned int m,
const unsigned int n,
const unsigned int n_nonzero_per_row,
const bool is_symmetric)
{
// get rid of old matrix and generate a
// new one
const int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
do_reinit (m, n, n_nonzero_per_row, is_symmetric);
}
void
SparseMatrix::reinit (const unsigned int m,
const unsigned int n,
const std::vector<unsigned int> &row_lengths,
const bool is_symmetric)
{
// get rid of old matrix and generate a
// new one
const int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
do_reinit (m, n, row_lengths, is_symmetric);
}
template <typename SparsityType>
void
SparseMatrix::
reinit (const SparsityType &sparsity_pattern,
const bool preset_nonzero_locations)
{
// get rid of old matrix and generate a
// new one
const int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
do_reinit (sparsity_pattern, preset_nonzero_locations);
}
const MPI_Comm &
SparseMatrix::get_mpi_communicator () const
{
static const MPI_Comm communicator = MPI_COMM_SELF;
return communicator;
}
void
SparseMatrix::do_reinit (const unsigned int m,
const unsigned int n,
const unsigned int n_nonzero_per_row,
const bool is_symmetric)
{
// use the call sequence indicating only
// a maximal number of elements per row
// for all rows globally
const int ierr
= MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, n_nonzero_per_row,
0, &matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// set symmetric flag, if so requested
if (is_symmetric == true)
{
#if DEAL_II_PETSC_VERSION_LT(3,0,0)
const int ierr
= MatSetOption (matrix, MAT_SYMMETRIC);
#else
const int ierr
= MatSetOption (matrix, MAT_SYMMETRIC, PETSC_TRUE);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
}
void
SparseMatrix::do_reinit (const unsigned int m,
const unsigned int n,
const std::vector<unsigned int> &row_lengths,
const bool is_symmetric)
{
Assert (row_lengths.size() == m,
ExcDimensionMismatch (row_lengths.size(), m));
// use the call sequence indicating a
// maximal number of elements for each
// row individually. annoyingly, we
// always use unsigned ints for cases
// like this, while PETSc wants to see
// signed integers. so we have to
// convert, unless we want to play dirty
// tricks with conversions of pointers
#ifdef PETSC_USE_64BIT_INDICES
const std::vector<PetscInt>
#else
const std::vector<int>
#endif
int_row_lengths (row_lengths.begin(), row_lengths.end());
const int ierr
= MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, 0,
&int_row_lengths[0], &matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// set symmetric flag, if so requested
if (is_symmetric == true)
{
#if DEAL_II_PETSC_VERSION_LT(3,0,0)
const int ierr
= MatSetOption (matrix, MAT_SYMMETRIC);
#else
const int ierr
= MatSetOption (matrix, MAT_SYMMETRIC, PETSC_TRUE);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
}
template <typename SparsityType>
void
SparseMatrix::do_reinit (const SparsityType &sparsity_pattern,
const bool preset_nonzero_locations)
{
std::vector<unsigned int> row_lengths (sparsity_pattern.n_rows());
for (unsigned int i=0; i<sparsity_pattern.n_rows(); ++i)
row_lengths[i] = sparsity_pattern.row_length (i);
do_reinit (sparsity_pattern.n_rows(),
sparsity_pattern.n_cols(),
row_lengths, false);
// next preset the exact given matrix
// entries with zeros, if the user
// requested so. this doesn't avoid any
// memory allocations, but it at least
// avoids some searches later on. the
// key here is that we can use the
// matrix set routines that set an
// entire row at once, not a single
// entry at a time
//
// for the usefulness of this option
// read the documentation of this
// class.
if (preset_nonzero_locations == true)
{
#ifdef PETSC_USE_64BIT_INDICES
std::vector<PetscInt>
#else
std::vector<int>
#endif
row_entries;
std::vector<PetscScalar> row_values;
for (unsigned int i=0; i<sparsity_pattern.n_rows(); ++i)
{
row_entries.resize (row_lengths[i]);
row_values.resize (row_lengths[i], 0.0);
for (unsigned int j=0; j<row_lengths[i]; ++j)
row_entries[j] = sparsity_pattern.column_number (i,j);
#ifdef PETSC_USE_64BIT_INDICES
const PetscInt
#else
const int
#endif
int_row = i;
MatSetValues (matrix, 1, &int_row,
row_lengths[i], &row_entries[0],
&row_values[0], INSERT_VALUES);
}
compress ();
// Tell PETSc that we are not
// planning on adding new entries
// to the matrix. Generate errors
// in debug mode.
int ierr;
#if DEAL_II_PETSC_VERSION_LT(3,0,0)
#ifdef DEBUG
ierr = MatSetOption (matrix, MAT_NEW_NONZERO_LOCATION_ERR);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#else
ierr = MatSetOption (matrix, MAT_NO_NEW_NONZERO_LOCATIONS);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#endif
#else
#ifdef DEBUG
ierr = MatSetOption (matrix, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#else
ierr = MatSetOption (matrix, MAT_NEW_NONZERO_LOCATIONS, PETSC_FALSE);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#endif
#endif
// Tell PETSc to keep the
// SparsityPattern entries even if
// we delete a row with
// clear_rows() which calls
// MatZeroRows(). Otherwise one can
// not write into that row
// afterwards.
#if DEAL_II_PETSC_VERSION_LT(3,1,0)
ierr = MatSetOption (matrix, MAT_KEEP_ZEROED_ROWS, PETSC_TRUE);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#else
ierr = MatSetOption (matrix, MAT_KEEP_NONZERO_PATTERN, PETSC_TRUE);
AssertThrow (ierr == 0, ExcPETScError(ierr));
#endif
}
}
// Explicit instantiations
//
template
SparseMatrix::SparseMatrix (const SparsityPattern &,
const bool);
template
SparseMatrix::SparseMatrix (const CompressedSparsityPattern &,
const bool);
template
SparseMatrix::SparseMatrix (const CompressedSimpleSparsityPattern &,
const bool);
template void
SparseMatrix::reinit (const SparsityPattern &,
const bool);
template void
SparseMatrix::reinit (const CompressedSparsityPattern &,
const bool);
template void
SparseMatrix::reinit (const CompressedSimpleSparsityPattern &,
const bool);
template void
SparseMatrix::do_reinit (const SparsityPattern &,
const bool);
template void
SparseMatrix::do_reinit (const CompressedSparsityPattern &,
const bool);
template void
SparseMatrix::do_reinit (const CompressedSimpleSparsityPattern &,
const bool);
}
DEAL_II_NAMESPACE_CLOSE
#endif // DEAL_II_USE_PETSC
|
Apply fix also for PETScWrappers::SparseMatrix in the same way it was done for MPI::SparseMatrix.
|
Apply fix also for PETScWrappers::SparseMatrix in the same way it was done for MPI::SparseMatrix.
git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@23424 0785d39b-7218-0410-832d-ea1e28bc413d
|
C++
|
lgpl-2.1
|
maieneuro/dealii,Arezou-gh/dealii,JaeryunYim/dealii,lpolster/dealii,adamkosik/dealii,kalj/dealii,flow123d/dealii,lpolster/dealii,ESeNonFossiIo/dealii,nicolacavallini/dealii,sairajat/dealii,danshapero/dealii,danshapero/dealii,rrgrove6/dealii,andreamola/dealii,mtezzele/dealii,pesser/dealii,mac-a/dealii,mtezzele/dealii,ESeNonFossiIo/dealii,pesser/dealii,andreamola/dealii,angelrca/dealii,nicolacavallini/dealii,gpitton/dealii,flow123d/dealii,Arezou-gh/dealii,ibkim11/dealii,naliboff/dealii,kalj/dealii,adamkosik/dealii,msteigemann/dealii,lpolster/dealii,kalj/dealii,mac-a/dealii,sriharisundar/dealii,nicolacavallini/dealii,flow123d/dealii,ibkim11/dealii,johntfoster/dealii,JaeryunYim/dealii,johntfoster/dealii,jperryhouts/dealii,angelrca/dealii,natashasharma/dealii,naliboff/dealii,Arezou-gh/dealii,natashasharma/dealii,ESeNonFossiIo/dealii,ibkim11/dealii,spco/dealii,sriharisundar/dealii,angelrca/dealii,msteigemann/dealii,rrgrove6/dealii,mac-a/dealii,lue/dealii,mac-a/dealii,nicolacavallini/dealii,johntfoster/dealii,andreamola/dealii,flow123d/dealii,naliboff/dealii,adamkosik/dealii,kalj/dealii,sairajat/dealii,ibkim11/dealii,adamkosik/dealii,EGP-CIG-REU/dealii,naliboff/dealii,pesser/dealii,ESeNonFossiIo/dealii,flow123d/dealii,nicolacavallini/dealii,kalj/dealii,sriharisundar/dealii,EGP-CIG-REU/dealii,EGP-CIG-REU/dealii,msteigemann/dealii,johntfoster/dealii,JaeryunYim/dealii,shakirbsm/dealii,mtezzele/dealii,ibkim11/dealii,mac-a/dealii,pesser/dealii,flow123d/dealii,shakirbsm/dealii,sairajat/dealii,lue/dealii,JaeryunYim/dealii,jperryhouts/dealii,EGP-CIG-REU/dealii,lpolster/dealii,lue/dealii,natashasharma/dealii,rrgrove6/dealii,natashasharma/dealii,mtezzele/dealii,ibkim11/dealii,sairajat/dealii,sairajat/dealii,maieneuro/dealii,gpitton/dealii,adamkosik/dealii,natashasharma/dealii,Arezou-gh/dealii,JaeryunYim/dealii,mtezzele/dealii,danshapero/dealii,maieneuro/dealii,spco/dealii,msteigemann/dealii,maieneuro/dealii,kalj/dealii,shakirbsm/dealii,danshapero/dealii,adamkosik/dealii,mac-a/dealii,rrgrove6/dealii,sriharisundar/dealii,sairajat/dealii,natashasharma/dealii,mac-a/dealii,spco/dealii,johntfoster/dealii,gpitton/dealii,gpitton/dealii,mtezzele/dealii,jperryhouts/dealii,YongYang86/dealii,mtezzele/dealii,danshapero/dealii,YongYang86/dealii,pesser/dealii,shakirbsm/dealii,jperryhouts/dealii,msteigemann/dealii,YongYang86/dealii,shakirbsm/dealii,sriharisundar/dealii,pesser/dealii,shakirbsm/dealii,Arezou-gh/dealii,kalj/dealii,angelrca/dealii,msteigemann/dealii,natashasharma/dealii,gpitton/dealii,andreamola/dealii,ESeNonFossiIo/dealii,maieneuro/dealii,sriharisundar/dealii,shakirbsm/dealii,jperryhouts/dealii,lue/dealii,lpolster/dealii,lue/dealii,ibkim11/dealii,andreamola/dealii,angelrca/dealii,maieneuro/dealii,adamkosik/dealii,gpitton/dealii,pesser/dealii,maieneuro/dealii,sairajat/dealii,spco/dealii,nicolacavallini/dealii,andreamola/dealii,Arezou-gh/dealii,rrgrove6/dealii,flow123d/dealii,spco/dealii,lpolster/dealii,johntfoster/dealii,EGP-CIG-REU/dealii,rrgrove6/dealii,lpolster/dealii,danshapero/dealii,Arezou-gh/dealii,angelrca/dealii,EGP-CIG-REU/dealii,JaeryunYim/dealii,JaeryunYim/dealii,lue/dealii,YongYang86/dealii,nicolacavallini/dealii,gpitton/dealii,YongYang86/dealii,lue/dealii,spco/dealii,angelrca/dealii,sriharisundar/dealii,johntfoster/dealii,EGP-CIG-REU/dealii,spco/dealii,danshapero/dealii,andreamola/dealii,rrgrove6/dealii,YongYang86/dealii,naliboff/dealii,msteigemann/dealii,naliboff/dealii,jperryhouts/dealii,naliboff/dealii,ESeNonFossiIo/dealii,jperryhouts/dealii,ESeNonFossiIo/dealii,YongYang86/dealii
|
28820c752c6e72323135fd7b2b66e21e4c7084b7
|
Base/Fonts/E_BitmapFont.cpp
|
Base/Fonts/E_BitmapFont.cpp
|
/*
This file is part of the E_GUI library.
Copyright (C) 2008-2012 Benjamin Eikel <[email protected]>
Copyright (C) 2008-2012 Claudius Jähn <[email protected]>
Copyright (C) 2008-2012 Ralf Petring <[email protected]>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_BitmapFont.h"
#include <EScript/EScript.h>
#include <E_Geometry/E_Rect.h>
#include <E_Geometry/E_Vec2.h>
#include <E_Util/E_FileName.h>
#include <E_Util/Graphics/E_Bitmap.h>
#include "../../Components/E_Image.h"
#include "../../ELibGUI.h"
using namespace EScript;
namespace E_GUI {
Type* E_BitmapFont::typeObject=nullptr;
//! [static] initMembers
void E_BitmapFont::init(EScript::Namespace & lib) {
// GUI.BitmapFont ---|> GUI.AbstractFont ---|> Object
typeObject = new EScript::Type(E_AbstractFont::typeObject);
declareConstant(&lib,getClassName(),typeObject);
using namespace GUI;
//! [ESF] BitmapFont new BitmapFont( FileName,Number size,String charMap)
ES_FUN(typeObject,"createFont",3,3, EScript::create(BitmapFont::createFont(parameter[0].to<Util::FileName>(rt),parameter[1].to<uint32_t>(rt),parameter[2].toString())))
//! [ESF] BitmapFont new BitmapFont( Image,lineHeight )
ES_CTOR(typeObject,2,2, EScript::create(new GUI::BitmapFont(parameter[0].to<Image*>(rt)->getImageData(),parameter[1].toInt())))
//! [ESMF] self BitmapFont.addGlyph( Number unicode, Number width, Number height, Geometry::Vec2 textureOffset,Geometry::Vec2 screenOffset,Number xAdvance )
ES_MFUNCTION(typeObject,E_BitmapFont,"addGlyph",6,6,{
thisObj->get()->addGlyph( parameter[0].to<uint32_t>(rt),
parameter[1].to<uint32_t>(rt),
parameter[2].to<uint32_t>(rt),
Geometry::Vec2i( parameter[3].to<Geometry::Vec2>(rt) ),
Geometry::Vec2i( parameter[4].to<Geometry::Vec2>(rt) ),
parameter[5].to<uint32_t>(rt));
return thisEObj;
})
//! [ESMF] Util.Bitmap BitmapFont.getBitmap( )
ES_MFUN(typeObject,BitmapFont,"getBitmap",0,0,
EScript::create( thisObj->getBitmap() ))
}
//---
//! (ctor)
E_BitmapFont::E_BitmapFont(GUI::BitmapFont * font,EScript::Type * type):
E_AbstractFont(font,type?type:typeObject) {
}
//! (dtor)
E_BitmapFont::~E_BitmapFont() {
}
}
|
/*
This file is part of the E_GUI library.
Copyright (C) 2008-2012 Benjamin Eikel <[email protected]>
Copyright (C) 2008-2012 Claudius Jähn <[email protected]>
Copyright (C) 2008-2012 Ralf Petring <[email protected]>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_BitmapFont.h"
#include <EScript/EScript.h>
#include <E_Geometry/E_Rect.h>
#include <E_Geometry/E_Vec2.h>
#include <E_Util/E_FileName.h>
#include <E_Util/Graphics/E_Bitmap.h>
#include "../../Components/E_Image.h"
#include "../../ELibGUI.h"
using namespace EScript;
namespace E_GUI {
Type* E_BitmapFont::typeObject=nullptr;
//! [static] initMembers
void E_BitmapFont::init(EScript::Namespace & lib) {
// GUI.BitmapFont ---|> GUI.AbstractFont ---|> Object
typeObject = new EScript::Type(E_AbstractFont::typeObject);
declareConstant(&lib,getClassName(),typeObject);
using namespace GUI;
//! [ESF] BitmapFont new BitmapFont( FileName,Number size,String charMap)
ES_FUN(typeObject,"createFont",3,3, EScript::create(BitmapFont::createFont(parameter[0].to<Util::FileName>(rt),parameter[1].to<uint32_t>(rt),parameter[2].toString())))
//! [ESF] BitmapFont new BitmapFont( Image,lineHeight )
ES_CTOR(typeObject,2,2, EScript::create(new GUI::BitmapFont(parameter[0].to<Image*>(rt)->getImageData(),parameter[1].toInt())))
//! [ESMF] self BitmapFont.addGlyph( Number unicode, Number width, Number height, Geometry::Vec2 textureOffset,Geometry::Vec2 screenOffset,Number xAdvance )
ES_MFUNCTION(typeObject,E_BitmapFont,"addGlyph",6,6,{
thisObj->get()->addGlyph( parameter[0].to<uint32_t>(rt),
parameter[1].to<uint32_t>(rt),
parameter[2].to<uint32_t>(rt),
Geometry::Vec2i( parameter[3].to<Geometry::Vec2>(rt) ),
Geometry::Vec2i( parameter[4].to<Geometry::Vec2>(rt) ),
parameter[5].to<uint32_t>(rt));
return thisEObj;
})
//! [ESMF] self BitmapFont.setKerning( Number unicode1,Number unicode2,Number kerning)
ES_MFUN(typeObject,BitmapFont,"setKerning",3,3,(thisObj->setKerning(parameter[0].to<uint32_t>(rt),parameter[1].to<uint32_t>(rt),parameter[2].to<int16_t>(rt)),thisObj))
//! [ESMF] Util.Bitmap BitmapFont.getBitmap( )
ES_MFUN(typeObject,BitmapFont,"getBitmap",0,0,
EScript::create( thisObj->getBitmap() ))
}
//---
//! (ctor)
E_BitmapFont::E_BitmapFont(GUI::BitmapFont * font,EScript::Type * type):
E_AbstractFont(font,type?type:typeObject) {
}
//! (dtor)
E_BitmapFont::~E_BitmapFont() {
}
}
|
add setKerning(...).
|
E_BitmapFont: add setKerning(...).
|
C++
|
mpl-2.0
|
PADrend/E_GUI
|
5624129604ed70b3d79ed650c2fa8baec2cc9792
|
backend/src/ir/profile.cpp
|
backend/src/ir/profile.cpp
|
/*
* Copyright © 2012 Intel Corporation
*
* 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 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, see <http://www.gnu.org/licenses/>.
*
* Author: Benjamin Segovia <[email protected]>
*/
/**
* \file profile.hpp
* \author Benjamin Segovia <[email protected]>
*/
#include "ir/profile.hpp"
#include "ir/function.hpp"
#include "sys/platform.hpp"
namespace gbe {
namespace ir {
namespace ocl
{
const char *specialRegMean[] = {
"local_id_0", "local_id_1", "local_id_2",
"group_id_0", "group_id_1", "group_id_2",
"num_groups_0", "num_groups_1", "num_groups_2",
"local_size_0", "local_size_1", "local_size_2",
"global_size_0", "global_size_1", "global_size_2",
"global_offset_0", "global_offset_1", "global_offset_2",
"stack_pointer",
"block_ip",
"barrier_id", "thread_number",
"const_curbe_offset",
};
#if GBE_DEBUG
#define DECL_NEW_REG(FAMILY, REG) \
r = fn.newRegister(FAMILY_DWORD); \
GBE_ASSERT(r == REG);
#else
#define DECL_NEW_REG(FAMILY, REG) \
fn.newRegister(FAMILY_DWORD);
#endif /* GBE_DEBUG */
static void init(Function &fn) {
IF_DEBUG(Register r);
DECL_NEW_REG(FAMILY_DWORD, lid0);
DECL_NEW_REG(FAMILY_DWORD, lid1);
DECL_NEW_REG(FAMILY_DWORD, lid2);
DECL_NEW_REG(FAMILY_DWORD, groupid0);
DECL_NEW_REG(FAMILY_DWORD, groupid1);
DECL_NEW_REG(FAMILY_DWORD, groupid2);
DECL_NEW_REG(FAMILY_DWORD, numgroup0);
DECL_NEW_REG(FAMILY_DWORD, numgroup1);
DECL_NEW_REG(FAMILY_DWORD, numgroup2);
DECL_NEW_REG(FAMILY_DWORD, lsize0);
DECL_NEW_REG(FAMILY_DWORD, lsize1);
DECL_NEW_REG(FAMILY_DWORD, lsize2);
DECL_NEW_REG(FAMILY_DWORD, gsize0);
DECL_NEW_REG(FAMILY_DWORD, gsize1);
DECL_NEW_REG(FAMILY_DWORD, gsize2);
DECL_NEW_REG(FAMILY_DWORD, goffset0);
DECL_NEW_REG(FAMILY_DWORD, goffset1);
DECL_NEW_REG(FAMILY_DWORD, goffset2);
DECL_NEW_REG(FAMILY_DWORD, stackptr);
DECL_NEW_REG(FAMILY_WORD, blockip);
DECL_NEW_REG(FAMILY_DWORD, barrierid);
DECL_NEW_REG(FAMILY_DWORD, threadn);
DECL_NEW_REG(FAMILY_DWORD, constoffst);
DECL_NEW_REG(FAMILY_DWORD, workdim);
}
#undef DECL_NEW_REG
} /* namespace ocl */
void initProfile(Function &fn) {
const Profile profile = fn.getProfile();
switch (profile) {
case PROFILE_C: GBE_ASSERTM(false, "Unsupported profile"); break;
case PROFILE_OCL: ocl::init(fn);
};
}
} /* namespace ir */
} /* namespace gbe */
|
/*
* Copyright © 2012 Intel Corporation
*
* 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 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, see <http://www.gnu.org/licenses/>.
*
* Author: Benjamin Segovia <[email protected]>
*/
/**
* \file profile.hpp
* \author Benjamin Segovia <[email protected]>
*/
#include "ir/profile.hpp"
#include "ir/function.hpp"
#include "sys/platform.hpp"
namespace gbe {
namespace ir {
namespace ocl
{
const char *specialRegMean[] = {
"local_id_0", "local_id_1", "local_id_2",
"group_id_0", "group_id_1", "group_id_2",
"num_groups_0", "num_groups_1", "num_groups_2",
"local_size_0", "local_size_1", "local_size_2",
"global_size_0", "global_size_1", "global_size_2",
"global_offset_0", "global_offset_1", "global_offset_2",
"stack_pointer",
"block_ip",
"barrier_id", "thread_number",
"const_curbe_offset",
"work_dimension",
};
#if GBE_DEBUG
#define DECL_NEW_REG(FAMILY, REG) \
r = fn.newRegister(FAMILY_DWORD); \
GBE_ASSERT(r == REG);
#else
#define DECL_NEW_REG(FAMILY, REG) \
fn.newRegister(FAMILY_DWORD);
#endif /* GBE_DEBUG */
static void init(Function &fn) {
IF_DEBUG(Register r);
DECL_NEW_REG(FAMILY_DWORD, lid0);
DECL_NEW_REG(FAMILY_DWORD, lid1);
DECL_NEW_REG(FAMILY_DWORD, lid2);
DECL_NEW_REG(FAMILY_DWORD, groupid0);
DECL_NEW_REG(FAMILY_DWORD, groupid1);
DECL_NEW_REG(FAMILY_DWORD, groupid2);
DECL_NEW_REG(FAMILY_DWORD, numgroup0);
DECL_NEW_REG(FAMILY_DWORD, numgroup1);
DECL_NEW_REG(FAMILY_DWORD, numgroup2);
DECL_NEW_REG(FAMILY_DWORD, lsize0);
DECL_NEW_REG(FAMILY_DWORD, lsize1);
DECL_NEW_REG(FAMILY_DWORD, lsize2);
DECL_NEW_REG(FAMILY_DWORD, gsize0);
DECL_NEW_REG(FAMILY_DWORD, gsize1);
DECL_NEW_REG(FAMILY_DWORD, gsize2);
DECL_NEW_REG(FAMILY_DWORD, goffset0);
DECL_NEW_REG(FAMILY_DWORD, goffset1);
DECL_NEW_REG(FAMILY_DWORD, goffset2);
DECL_NEW_REG(FAMILY_DWORD, stackptr);
DECL_NEW_REG(FAMILY_WORD, blockip);
DECL_NEW_REG(FAMILY_DWORD, barrierid);
DECL_NEW_REG(FAMILY_DWORD, threadn);
DECL_NEW_REG(FAMILY_DWORD, constoffst);
DECL_NEW_REG(FAMILY_DWORD, workdim);
}
#undef DECL_NEW_REG
} /* namespace ocl */
void initProfile(Function &fn) {
const Profile profile = fn.getProfile();
switch (profile) {
case PROFILE_C: GBE_ASSERTM(false, "Unsupported profile"); break;
case PROFILE_OCL: ocl::init(fn);
};
}
} /* namespace ir */
} /* namespace gbe */
|
add a lost special register name
|
add a lost special register name
Signed-off-by: Homer Hsing <[email protected]>
Reviewed-by: Zhigang Gong <[email protected]>
|
C++
|
lgpl-2.1
|
ignatenkobrain/beignet,wdv4758h/beignet,wdv4758h/beignet,wdv4758h/beignet,wdv4758h/beignet,ignatenkobrain/beignet,freedesktop-unofficial-mirror/beignet,ignatenkobrain/beignet,zhenyw/beignet,freedesktop-unofficial-mirror/beignet,zhenyw/beignet,ignatenkobrain/beignet,zhenyw/beignet,wdv4758h/beignet,ignatenkobrain/beignet,freedesktop-unofficial-mirror/beignet,freedesktop-unofficial-mirror/beignet,zhenyw/beignet,zhenyw/beignet
|
0358995ec1b1433184811024a779d9617bf30215
|
xcodec/xcodec_pipe_pair.cc
|
xcodec/xcodec_pipe_pair.cc
|
#include <common/buffer.h>
#include <common/endian.h>
#include <event/event_callback.h>
#include <io/pipe/pipe.h>
#include <io/pipe/pipe_pair.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_decoder.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_hash.h>
#include <xcodec/xcodec_pipe_pair.h>
/*
* XXX
* This is no longer up-to-date.
*
* And now for something completely different, a note on how end-of-stream
* indication works with the XCodec.
*
* When things are going along smoothly, the XCodec is a nice one-way stream
* compressor. All you need is state that you already have or state from
* earlier in the stream. However, it doesn't take much for things to go less
* smoothly. When you have two connections, a symbol may be defined in the
* first and referenced in the second, and the reference in the second stream
* may be decoded before the definition in the first one. In this case, we
* have <ASK> and <LEARN> in the stream to communicate bidirectionally
* to get the reference. If we're actually going to get the definition soon,
* that's a bit wasteful, and there are a lot of optimizations we can make,
* but the basic principle needs to be robust in case, say, the first
* connection goes down.
*
* Because of this, we can't just pass through end-of-stream indicators
* freely. When the encoder receives EOS from a StreamChannel, we could then
* send EOS out to the StreamChannel that connects us to the decoder on the
* other side of the network. But what if that decoder needs to <ASK> us
* about a symbol we sent a reference to just before EOS?
*
* So we send <EOS> rather than EOS, a message saying that the encoded stream
* has ended.
*
* When the decoder receives <EOS> it can send EOS on to the StreamChannel it
* is writing to, assuming it has processed all outstanding frame data. And
* when it has finished processing all outstanding frame data, it will send
* <EOS_ACK> on the encoder's output StreamChannel, to the remote decoder.
* When both sides have sent <EOS_ACK>, the encoder's StreamChannels may be
* shut down and no more communication will occur.
*/
/*
* Usage:
* <OP_HELLO> length[uint8_t] data[uint8_t x length]
*
* Effects:
* Must appear at the start of and only at the start of an encoded stream.
*
* Sife-effects:
* Possibly many.
*/
#define XCODEC_PIPE_OP_HELLO ((uint8_t)0xff)
/*
* Usage:
* <OP_LEARN> data[uint8_t x XCODEC_PIPE_SEGMENT_LENGTH]
*
* Effects:
* The `data' is hashed, the hash is associated with the data if possible.
*
* Side-effects:
* None.
*/
#define XCODEC_PIPE_OP_LEARN ((uint8_t)0xfe)
/*
* Usage:
* <OP_ASK> hash[uint64_t]
*
* Effects:
* An OP_LEARN will be sent in response with the data corresponding to the
* hash.
*
* If the hash is unknown, error will be indicated.
*
* Side-effects:
* None.
*/
#define XCODEC_PIPE_OP_ASK ((uint8_t)0xfd)
/*
* Usage:
* <OP_EOS>
*
* Effects:
* Alert the other party that we have no intention of sending more data.
*
* Side-effects:
* The other party will send <OP_EOS_ACK> when it has processed all of
* the data we have sent.
*/
#define XCODEC_PIPE_OP_EOS ((uint8_t)0xfc)
/*
* Usage:
* <OP_EOS_ACK>
*
* Effects:
* Alert the other party that we have no intention of reading more data.
*
* Side-effects:
* The connection will be torn down.
*/
#define XCODEC_PIPE_OP_EOS_ACK ((uint8_t)0xfb)
/*
* Usage:
* <FRAME> length[uint16_t] data[uint8_t x length]
*
* Effects:
* Frames an encoded chunk.
*
* Side-effects:
* None.
*/
#define XCODEC_PIPE_OP_FRAME ((uint8_t)0x00)
#define XCODEC_PIPE_MAX_FRAME (32768)
static void encode_frame(Buffer *, Buffer *);
void
XCodecPipePair::decoder_consume(Buffer *buf)
{
if (buf->empty()) {
if (!decoder_buffer_.empty())
ERROR(log_) << "Remote encoder closed connection with data outstanding.";
if (!decoder_frame_buffer_.empty())
ERROR(log_) << "Remote encoder closed connection with frame data outstanding.";
if (!decoder_sent_eos_) {
DEBUG(log_) << "Decoder received, sent EOS.";
decoder_sent_eos_ = true;
decoder_produce_eos();
} else {
DEBUG(log_) << "Decoder received EOS after sending EOS.";
}
return;
}
ASSERT(log_, !decoder_sent_eos_);
buf->moveout(&decoder_buffer_);
while (!decoder_buffer_.empty()) {
uint8_t op = decoder_buffer_.peek();
switch (op) {
case XCODEC_PIPE_OP_HELLO:
if (decoder_cache_ != NULL) {
ERROR(log_) << "Got <HELLO> twice.";
decoder_error();
return;
} else {
uint8_t len;
if (decoder_buffer_.length() < sizeof op + sizeof len)
return;
decoder_buffer_.extract(&len, sizeof op);
if (decoder_buffer_.length() < sizeof op + sizeof len + len)
return;
if (len != UUID_SIZE) {
ERROR(log_) << "Unsupported <HELLO> length: " << (unsigned)len;
decoder_error();
return;
}
Buffer uubuf;
decoder_buffer_.moveout(&uubuf, sizeof op + sizeof len, UUID_SIZE);
UUID uuid;
if (!uuid.decode(&uubuf)) {
ERROR(log_) << "Invalid UUID in <HELLO>.";
decoder_error();
return;
}
decoder_cache_ = XCodecCache::lookup(uuid);
if (decoder_cache_ == NULL) {
decoder_cache_ = new XCodecMemoryCache(uuid);
XCodecCache::enter(uuid, decoder_cache_);
}
ASSERT(log_, decoder_ == NULL);
decoder_ = new XCodecDecoder(decoder_cache_);
DEBUG(log_) << "Peer connected with UUID: " << uuid.string_;
}
break;
case XCODEC_PIPE_OP_ASK:
if (encoder_ == NULL) {
ERROR(log_) << "Got <ASK> before sending <HELLO>.";
decoder_error();
return;
} else {
uint64_t hash;
if (decoder_buffer_.length() < sizeof op + sizeof hash)
return;
decoder_buffer_.skip(sizeof op);
decoder_buffer_.extract(&hash);
decoder_buffer_.skip(sizeof hash);
hash = BigEndian::decode(hash);
BufferSegment *oseg = codec_->cache()->lookup(hash);
if (oseg == NULL) {
ERROR(log_) << "Unknown hash in <ASK>: " << hash;
decoder_error();
return;
}
DEBUG(log_) << "Responding to <ASK> with <LEARN>.";
Buffer learn;
learn.append(XCODEC_PIPE_OP_LEARN);
learn.append(oseg);
oseg->unref();
encoder_produce(&learn);
}
break;
case XCODEC_PIPE_OP_LEARN:
if (decoder_cache_ == NULL) {
ERROR(log_) << "Got <LEARN> before <HELLO>.";
decoder_error();
return;
} else {
if (decoder_buffer_.length() < sizeof op + XCODEC_SEGMENT_LENGTH)
return;
decoder_buffer_.skip(sizeof op);
BufferSegment *seg;
decoder_buffer_.copyout(&seg, XCODEC_SEGMENT_LENGTH);
decoder_buffer_.skip(XCODEC_SEGMENT_LENGTH);
uint64_t hash = XCodecHash::hash(seg->data());
if (decoder_unknown_hashes_.find(hash) == decoder_unknown_hashes_.end()) {
INFO(log_) << "Gratuitous <LEARN> without <ASK>.";
} else {
decoder_unknown_hashes_.erase(hash);
}
BufferSegment *oseg = decoder_cache_->lookup(hash);
if (oseg != NULL) {
if (!oseg->equal(seg)) {
oseg->unref();
ERROR(log_) << "Collision in <LEARN>.";
seg->unref();
decoder_error();
return;
}
oseg->unref();
DEBUG(log_) << "Redundant <LEARN>.";
} else {
DEBUG(log_) << "Successful <LEARN>.";
decoder_cache_->enter(hash, seg);
}
seg->unref();
}
break;
case XCODEC_PIPE_OP_EOS:
if (decoder_received_eos_) {
ERROR(log_) << "Duplicate <EOS>.";
decoder_error();
return;
}
decoder_buffer_.skip(1);
decoder_received_eos_ = true;
break;
case XCODEC_PIPE_OP_EOS_ACK:
if (!encoder_sent_eos_) {
ERROR(log_) << "Got <EOS_ACK> before sending <EOS>.";
decoder_error();
return;
}
if (decoder_received_eos_ack_) {
ERROR(log_) << "Duplicate <EOS_ACK>.";
decoder_error();
return;
}
decoder_buffer_.skip(1);
decoder_received_eos_ack_ = true;
break;
case XCODEC_PIPE_OP_FRAME:
if (decoder_ == NULL) {
ERROR(log_) << "Got frame data before decoder initialized.";
decoder_error();
return;
} else {
uint16_t len;
if (decoder_buffer_.length() < sizeof op + sizeof len)
return;
decoder_buffer_.extract(&len, sizeof op);
len = BigEndian::decode(len);
if (len == 0 || len > XCODEC_PIPE_MAX_FRAME) {
ERROR(log_) << "Invalid framed data length.";
decoder_error();
return;
}
if (decoder_buffer_.length() < sizeof op + sizeof len + len)
return;
decoder_buffer_.moveout(&decoder_frame_buffer_, sizeof op + sizeof len, len);
}
break;
default:
ERROR(log_) << "Unsupported operation in pipe stream.";
decoder_error();
return;
}
if (decoder_frame_buffer_.empty()) {
if (decoder_received_eos_ && !encoder_sent_eos_ack_) {
DEBUG(log_) << "Decoder finished, got <EOS>, sending <EOS_ACK>.";
Buffer eos_ack;
eos_ack.append(XCODEC_PIPE_OP_EOS_ACK);
encoder_produce(&eos_ack);
encoder_sent_eos_ack_ = true;
}
continue;
}
if (!decoder_unknown_hashes_.empty()) {
DEBUG(log_) << "Waiting for unknown hashes to continue processing data.";
continue;
}
Buffer output;
if (!decoder_->decode(&output, &decoder_frame_buffer_, decoder_unknown_hashes_)) {
ERROR(log_) << "Decoder exiting with error.";
decoder_error();
return;
}
if (!output.empty()) {
decoder_produce(&output);
} else {
/*
* We should only get no output from the decoder if
* we're waiting on the next frame or we need an
* unknown hash. It would be nice to make the
* encoder framing aware so that it would not end
* up with encoded data that straddles a frame
* boundary. (Fixing that would also allow us to
* simplify length checking within the decoder
* considerably.)
*/
ASSERT(log_, !decoder_frame_buffer_.empty() || !decoder_unknown_hashes_.empty());
}
Buffer ask;
std::set<uint64_t>::const_iterator it;
for (it = decoder_unknown_hashes_.begin(); it != decoder_unknown_hashes_.end(); ++it) {
uint64_t hash = *it;
hash = BigEndian::encode(hash);
ask.append(XCODEC_PIPE_OP_ASK);
ask.append(&hash);
}
if (!ask.empty()) {
DEBUG(log_) << "Sending <ASK>s.";
encoder_produce(&ask);
}
}
if (decoder_received_eos_ && !decoder_sent_eos_) {
DEBUG(log_) << "Decoder finished, got <EOS>, shutting down decoder output channel.";
decoder_produce_eos();
decoder_sent_eos_ = true;
}
if (encoder_sent_eos_ack_ && decoder_received_eos_ack_) {
ASSERT(log_, decoder_buffer_.empty());
ASSERT(log_, decoder_frame_buffer_.empty());
DEBUG(log_) << "Decoder finished, got <EOS_ACK>, shutting down encoder output channel.";
encoder_produce_eos();
}
}
void
XCodecPipePair::encoder_consume(Buffer *buf)
{
ASSERT(log_, !encoder_sent_eos_);
Buffer output;
if (encoder_ == NULL) {
Buffer extra;
if (!codec_->cache()->uuid_encode(&extra)) {
ERROR(log_) << "Could not encode UUID for <HELLO>.";
encoder_error();
return;
}
uint8_t len = extra.length();
ASSERT(log_, len == UUID_SIZE);
output.append(XCODEC_PIPE_OP_HELLO);
output.append(len);
output.append(extra);
ASSERT(log_, output.length() == 2 + UUID_SIZE);
encoder_ = new XCodecEncoder(codec_->cache());
}
if (!buf->empty()) {
Buffer encoded;
encoder_->encode(&encoded, buf);
ASSERT(log_, !encoded.empty());
encode_frame(&output, &encoded);
ASSERT(log_, !output.empty());
} else {
output.append(XCODEC_PIPE_OP_EOS);
encoder_sent_eos_ = true;
}
encoder_produce(&output);
}
static void
encode_frame(Buffer *out, Buffer *in)
{
while (!in->empty()) {
uint16_t framelen;
if (in->length() <= XCODEC_PIPE_MAX_FRAME)
framelen = in->length();
else
framelen = XCODEC_PIPE_MAX_FRAME;
Buffer frame;
in->moveout(&frame, framelen);
framelen = BigEndian::encode(framelen);
out->append(XCODEC_PIPE_OP_FRAME);
out->append(&framelen);
out->append(frame);
}
}
|
#include <common/buffer.h>
#include <common/endian.h>
#include <event/event_callback.h>
#include <io/pipe/pipe.h>
#include <io/pipe/pipe_pair.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_decoder.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_hash.h>
#include <xcodec/xcodec_pipe_pair.h>
/*
* XXX
* This is no longer up-to-date.
*
* And now for something completely different, a note on how end-of-stream
* indication works with the XCodec.
*
* When things are going along smoothly, the XCodec is a nice one-way stream
* compressor. All you need is state that you already have or state from
* earlier in the stream. However, it doesn't take much for things to go less
* smoothly. When you have two connections, a symbol may be defined in the
* first and referenced in the second, and the reference in the second stream
* may be decoded before the definition in the first one. In this case, we
* have <ASK> and <LEARN> in the stream to communicate bidirectionally
* to get the reference. If we're actually going to get the definition soon,
* that's a bit wasteful, and there are a lot of optimizations we can make,
* but the basic principle needs to be robust in case, say, the first
* connection goes down.
*
* Because of this, we can't just pass through end-of-stream indicators
* freely. When the encoder receives EOS from a StreamChannel, we could then
* send EOS out to the StreamChannel that connects us to the decoder on the
* other side of the network. But what if that decoder needs to <ASK> us
* about a symbol we sent a reference to just before EOS?
*
* So we send <EOS> rather than EOS, a message saying that the encoded stream
* has ended.
*
* When the decoder receives <EOS> it can send EOS on to the StreamChannel it
* is writing to, assuming it has processed all outstanding frame data. And
* when it has finished processing all outstanding frame data, it will send
* <EOS_ACK> on the encoder's output StreamChannel, to the remote decoder.
* When both sides have sent <EOS_ACK>, the encoder's StreamChannels may be
* shut down and no more communication will occur.
*/
/*
* Usage:
* <OP_HELLO> length[uint8_t] data[uint8_t x length]
*
* Effects:
* Must appear at the start of and only at the start of an encoded stream.
*
* Sife-effects:
* Possibly many.
*/
#define XCODEC_PIPE_OP_HELLO ((uint8_t)0xff)
/*
* Usage:
* <OP_LEARN> data[uint8_t x XCODEC_PIPE_SEGMENT_LENGTH]
*
* Effects:
* The `data' is hashed, the hash is associated with the data if possible.
*
* Side-effects:
* None.
*/
#define XCODEC_PIPE_OP_LEARN ((uint8_t)0xfe)
/*
* Usage:
* <OP_ASK> hash[uint64_t]
*
* Effects:
* An OP_LEARN will be sent in response with the data corresponding to the
* hash.
*
* If the hash is unknown, error will be indicated.
*
* Side-effects:
* None.
*/
#define XCODEC_PIPE_OP_ASK ((uint8_t)0xfd)
/*
* Usage:
* <OP_EOS>
*
* Effects:
* Alert the other party that we have no intention of sending more data.
*
* Side-effects:
* The other party will send <OP_EOS_ACK> when it has processed all of
* the data we have sent.
*/
#define XCODEC_PIPE_OP_EOS ((uint8_t)0xfc)
/*
* Usage:
* <OP_EOS_ACK>
*
* Effects:
* Alert the other party that we have no intention of reading more data.
*
* Side-effects:
* The connection will be torn down.
*/
#define XCODEC_PIPE_OP_EOS_ACK ((uint8_t)0xfb)
/*
* Usage:
* <FRAME> length[uint16_t] data[uint8_t x length]
*
* Effects:
* Frames an encoded chunk.
*
* Side-effects:
* None.
*/
#define XCODEC_PIPE_OP_FRAME ((uint8_t)0x00)
#define XCODEC_PIPE_MAX_FRAME (32768)
static void encode_frame(Buffer *, Buffer *);
void
XCodecPipePair::decoder_consume(Buffer *buf)
{
if (buf->empty()) {
if (!decoder_buffer_.empty())
ERROR(log_) << "Remote encoder closed connection with data outstanding.";
if (!decoder_frame_buffer_.empty())
ERROR(log_) << "Remote encoder closed connection with frame data outstanding.";
if (!decoder_sent_eos_) {
DEBUG(log_) << "Decoder received, sent EOS.";
decoder_sent_eos_ = true;
decoder_produce_eos();
} else {
DEBUG(log_) << "Decoder received EOS after sending EOS.";
}
return;
}
buf->moveout(&decoder_buffer_);
while (!decoder_buffer_.empty()) {
uint8_t op = decoder_buffer_.peek();
switch (op) {
case XCODEC_PIPE_OP_HELLO:
if (decoder_cache_ != NULL) {
ERROR(log_) << "Got <HELLO> twice.";
decoder_error();
return;
} else {
uint8_t len;
if (decoder_buffer_.length() < sizeof op + sizeof len)
return;
decoder_buffer_.extract(&len, sizeof op);
if (decoder_buffer_.length() < sizeof op + sizeof len + len)
return;
if (len != UUID_SIZE) {
ERROR(log_) << "Unsupported <HELLO> length: " << (unsigned)len;
decoder_error();
return;
}
Buffer uubuf;
decoder_buffer_.moveout(&uubuf, sizeof op + sizeof len, UUID_SIZE);
UUID uuid;
if (!uuid.decode(&uubuf)) {
ERROR(log_) << "Invalid UUID in <HELLO>.";
decoder_error();
return;
}
decoder_cache_ = XCodecCache::lookup(uuid);
if (decoder_cache_ == NULL) {
decoder_cache_ = new XCodecMemoryCache(uuid);
XCodecCache::enter(uuid, decoder_cache_);
}
ASSERT(log_, decoder_ == NULL);
decoder_ = new XCodecDecoder(decoder_cache_);
DEBUG(log_) << "Peer connected with UUID: " << uuid.string_;
}
break;
case XCODEC_PIPE_OP_ASK:
if (encoder_ == NULL) {
ERROR(log_) << "Got <ASK> before sending <HELLO>.";
decoder_error();
return;
} else {
uint64_t hash;
if (decoder_buffer_.length() < sizeof op + sizeof hash)
return;
decoder_buffer_.skip(sizeof op);
decoder_buffer_.extract(&hash);
decoder_buffer_.skip(sizeof hash);
hash = BigEndian::decode(hash);
BufferSegment *oseg = codec_->cache()->lookup(hash);
if (oseg == NULL) {
ERROR(log_) << "Unknown hash in <ASK>: " << hash;
decoder_error();
return;
}
DEBUG(log_) << "Responding to <ASK> with <LEARN>.";
Buffer learn;
learn.append(XCODEC_PIPE_OP_LEARN);
learn.append(oseg);
oseg->unref();
encoder_produce(&learn);
}
break;
case XCODEC_PIPE_OP_LEARN:
if (decoder_cache_ == NULL) {
ERROR(log_) << "Got <LEARN> before <HELLO>.";
decoder_error();
return;
} else {
if (decoder_buffer_.length() < sizeof op + XCODEC_SEGMENT_LENGTH)
return;
decoder_buffer_.skip(sizeof op);
BufferSegment *seg;
decoder_buffer_.copyout(&seg, XCODEC_SEGMENT_LENGTH);
decoder_buffer_.skip(XCODEC_SEGMENT_LENGTH);
uint64_t hash = XCodecHash::hash(seg->data());
if (decoder_unknown_hashes_.find(hash) == decoder_unknown_hashes_.end()) {
INFO(log_) << "Gratuitous <LEARN> without <ASK>.";
} else {
decoder_unknown_hashes_.erase(hash);
}
BufferSegment *oseg = decoder_cache_->lookup(hash);
if (oseg != NULL) {
if (!oseg->equal(seg)) {
oseg->unref();
ERROR(log_) << "Collision in <LEARN>.";
seg->unref();
decoder_error();
return;
}
oseg->unref();
DEBUG(log_) << "Redundant <LEARN>.";
} else {
DEBUG(log_) << "Successful <LEARN>.";
decoder_cache_->enter(hash, seg);
}
seg->unref();
}
break;
case XCODEC_PIPE_OP_EOS:
if (decoder_received_eos_) {
ERROR(log_) << "Duplicate <EOS>.";
decoder_error();
return;
}
decoder_buffer_.skip(1);
decoder_received_eos_ = true;
break;
case XCODEC_PIPE_OP_EOS_ACK:
if (!encoder_sent_eos_) {
ERROR(log_) << "Got <EOS_ACK> before sending <EOS>.";
decoder_error();
return;
}
if (decoder_received_eos_ack_) {
ERROR(log_) << "Duplicate <EOS_ACK>.";
decoder_error();
return;
}
decoder_buffer_.skip(1);
decoder_received_eos_ack_ = true;
break;
case XCODEC_PIPE_OP_FRAME:
if (decoder_ == NULL) {
ERROR(log_) << "Got frame data before decoder initialized.";
decoder_error();
return;
} else {
uint16_t len;
if (decoder_buffer_.length() < sizeof op + sizeof len)
return;
decoder_buffer_.extract(&len, sizeof op);
len = BigEndian::decode(len);
if (len == 0 || len > XCODEC_PIPE_MAX_FRAME) {
ERROR(log_) << "Invalid framed data length.";
decoder_error();
return;
}
if (decoder_buffer_.length() < sizeof op + sizeof len + len)
return;
decoder_buffer_.moveout(&decoder_frame_buffer_, sizeof op + sizeof len, len);
}
break;
default:
ERROR(log_) << "Unsupported operation in pipe stream.";
decoder_error();
return;
}
if (decoder_frame_buffer_.empty()) {
if (decoder_received_eos_ && !encoder_sent_eos_ack_) {
DEBUG(log_) << "Decoder finished, got <EOS>, sending <EOS_ACK>.";
Buffer eos_ack;
eos_ack.append(XCODEC_PIPE_OP_EOS_ACK);
encoder_produce(&eos_ack);
encoder_sent_eos_ack_ = true;
}
continue;
}
if (!decoder_unknown_hashes_.empty()) {
DEBUG(log_) << "Waiting for unknown hashes to continue processing data.";
continue;
}
Buffer output;
if (!decoder_->decode(&output, &decoder_frame_buffer_, decoder_unknown_hashes_)) {
ERROR(log_) << "Decoder exiting with error.";
decoder_error();
return;
}
if (!output.empty()) {
decoder_produce(&output);
} else {
/*
* We should only get no output from the decoder if
* we're waiting on the next frame or we need an
* unknown hash. It would be nice to make the
* encoder framing aware so that it would not end
* up with encoded data that straddles a frame
* boundary. (Fixing that would also allow us to
* simplify length checking within the decoder
* considerably.)
*/
ASSERT(log_, !decoder_frame_buffer_.empty() || !decoder_unknown_hashes_.empty());
}
Buffer ask;
std::set<uint64_t>::const_iterator it;
for (it = decoder_unknown_hashes_.begin(); it != decoder_unknown_hashes_.end(); ++it) {
uint64_t hash = *it;
hash = BigEndian::encode(hash);
ask.append(XCODEC_PIPE_OP_ASK);
ask.append(&hash);
}
if (!ask.empty()) {
DEBUG(log_) << "Sending <ASK>s.";
encoder_produce(&ask);
}
}
if (decoder_received_eos_ && !decoder_sent_eos_) {
DEBUG(log_) << "Decoder finished, got <EOS>, shutting down decoder output channel.";
decoder_produce_eos();
decoder_sent_eos_ = true;
}
if (encoder_sent_eos_ack_ && decoder_received_eos_ack_) {
ASSERT(log_, decoder_buffer_.empty());
ASSERT(log_, decoder_frame_buffer_.empty());
DEBUG(log_) << "Decoder finished, got <EOS_ACK>, shutting down encoder output channel.";
encoder_produce_eos();
}
}
void
XCodecPipePair::encoder_consume(Buffer *buf)
{
ASSERT(log_, !encoder_sent_eos_);
Buffer output;
if (encoder_ == NULL) {
Buffer extra;
if (!codec_->cache()->uuid_encode(&extra)) {
ERROR(log_) << "Could not encode UUID for <HELLO>.";
encoder_error();
return;
}
uint8_t len = extra.length();
ASSERT(log_, len == UUID_SIZE);
output.append(XCODEC_PIPE_OP_HELLO);
output.append(len);
output.append(extra);
ASSERT(log_, output.length() == 2 + UUID_SIZE);
encoder_ = new XCodecEncoder(codec_->cache());
}
if (!buf->empty()) {
Buffer encoded;
encoder_->encode(&encoded, buf);
ASSERT(log_, !encoded.empty());
encode_frame(&output, &encoded);
ASSERT(log_, !output.empty());
} else {
output.append(XCODEC_PIPE_OP_EOS);
encoder_sent_eos_ = true;
}
encoder_produce(&output);
}
static void
encode_frame(Buffer *out, Buffer *in)
{
while (!in->empty()) {
uint16_t framelen;
if (in->length() <= XCODEC_PIPE_MAX_FRAME)
framelen = in->length();
else
framelen = XCODEC_PIPE_MAX_FRAME;
Buffer frame;
in->moveout(&frame, framelen);
framelen = BigEndian::encode(framelen);
out->append(XCODEC_PIPE_OP_FRAME);
out->append(&framelen);
out->append(frame);
}
}
|
Remove misguided assertion.
|
Remove misguided assertion.
git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@921 4068ffdb-0463-0410-8185-8cc71e3bd399
|
C++
|
bsd-2-clause
|
diegows/wanproxy,splbio/wanproxy,diegows/wanproxy,splbio/wanproxy,splbio/wanproxy,diegows/wanproxy
|
2fbdf1259bad562ff9a1f2c9b2ed1d8bd403cf98
|
utils/util.hpp
|
utils/util.hpp
|
/*
* Vulkan Samples Kit
*
* Copyright (C) 2015 LunarG, Inc.
*
* 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 <iostream>
#include <string>
#include <sstream>
#include <vector>
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include <glm/gtc/matrix_transform.hpp>
#ifdef _WIN32
#pragma comment(linker, "/subsystem:console")
#include <windows.h>
#include <vulkan.h>
#include <vk_wsi_swapchain.h>
#include <vk_wsi_device_swapchain.h>
#include <vk_debug_report_lunarg.h>
#define APP_NAME_STR_LEN 80
#else // _WIN32
#include <xcb/xcb.h>
#include <vulkan/vulkan.h>
#include <vulkan/vk_wsi_swapchain.h>
#include <vulkan/vk_wsi_device_swapchain.h>
#include <vulkan/vk_debug_report_lunarg.h>
#endif // _WIN32
#define SAMPLE_BUFFER_COUNT 2
#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \
{ \
info.fp##entrypoint = (PFN_vk##entrypoint) vkGetInstanceProcAddr(inst, "vk"#entrypoint); \
if (info.fp##entrypoint == NULL) { \
std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \
exit(-1); \
} \
}
#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \
{ \
info.fp##entrypoint = (PFN_vk##entrypoint) vkGetDeviceProcAddr(dev, "vk"#entrypoint); \
if (info.fp##entrypoint == NULL) { \
std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \
exit(-1); \
} \
}
std::string get_base_data_dir();
std::string get_data_dir( std::string filename );
/*
* structure to track all objects related to a texture.
*/
struct texture_object {
VkSampler sampler;
VkImage image;
VkImageLayout imageLayout;
VkDeviceMemory mem;
VkImageView view;
int32_t tex_width, tex_height;
};
/*
* Keep each of our swap chain buffers' image, command buffer and view in one spot
*/
typedef struct _swap_chain_buffers {
VkImage image;
VkCmdBuffer cmd;
VkAttachmentView view;
} swap_chain_buffer;
/*
* A layer can expose extensions, keep track of those
* extensions here.
*/
typedef struct {
VkLayerProperties properties;
std::vector<VkExtensionProperties> extensions;
} layer_properties;
/*
* Structure for tracking information used / created / modified
* by utility functions.
*/
struct sample_info {
#ifdef _WIN32
#define APP_NAME_STR_LEN 80
HINSTANCE connection; // hInstance - Windows Instance
char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
HWND window; // hWnd - window handle
#else // _WIN32
xcb_connection_t *connection;
xcb_screen_t *screen;
xcb_window_t window;
xcb_intern_atom_reply_t *atom_wm_delete_window;
VkPlatformHandleXcbWSI platform_handle_xcb;
#endif // _WIN32
bool prepared;
bool use_staging_buffer;
std::vector<char *> instance_layer_names;
std::vector<char *> instance_extension_names;
std::vector<layer_properties> instance_layer_properties;
std::vector<VkExtensionProperties> instance_extension_properties;
VkInstance inst;
std::vector<char *> device_layer_names;
std::vector<char *> device_extension_names;
std::vector<layer_properties> device_layer_properties;
std::vector<VkExtensionProperties> device_extension_properties;
VkPhysicalDevice gpu;
VkDevice device;
VkQueue queue;
uint32_t graphics_queue_family_index;
VkPhysicalDeviceProperties gpu_props;
std::vector<VkPhysicalDeviceQueueProperties> queue_props;
VkPhysicalDeviceMemoryProperties memory_properties;
VkFramebuffer framebuffers[SAMPLE_BUFFER_COUNT];
int width, height;
VkFormat format;
PFN_vkGetPhysicalDeviceSurfaceSupportWSI fpGetPhysicalDeviceSurfaceSupportWSI;
PFN_vkGetSurfaceInfoWSI fpGetSurfaceInfoWSI;
PFN_vkCreateSwapChainWSI fpCreateSwapChainWSI;
PFN_vkDestroySwapChainWSI fpDestroySwapChainWSI;
PFN_vkGetSwapChainInfoWSI fpGetSwapChainInfoWSI;
PFN_vkAcquireNextImageWSI fpAcquireNextImageWSI;
PFN_vkQueuePresentWSI fpQueuePresentWSI;
VkSurfaceDescriptionWindowWSI surface_description;
size_t swapChainImageCount;
VkSwapChainWSI swap_chain;
std::vector<swap_chain_buffer> buffers;
VkCmdPool cmd_pool;
struct {
VkFormat format;
VkImage image;
VkDeviceMemory mem;
VkAttachmentView view;
} depth;
std::vector<struct texture_object> textures;
struct {
VkBuffer buf;
VkDeviceMemory mem;
VkBufferView view;
VkDescriptorInfo desc;
} uniform_data;
glm::mat4 Projection;
glm::mat4 View;
glm::mat4 Model;
glm::mat4 MVP;
VkCmdBuffer cmd; // Buffer for initialization commands
VkPipelineLayout pipeline_layout;
VkDescriptorSetLayout desc_layout;
VkPipelineCache pipelineCache;
VkRenderPass render_pass;
VkPipeline pipeline;
VkDynamicViewportState viewport;
VkDynamicRasterState raster;
VkDynamicColorBlendState color_blend;
VkDynamicDepthStencilState depth_stencil;
VkShaderModule vert_shader_module;
VkShaderModule frag_shader_module;
VkDescriptorPool desc_pool;
VkDescriptorSet desc_set;
PFN_vkDbgCreateMsgCallback dbgCreateMsgCallback;
PFN_vkDbgDestroyMsgCallback dbgDestroyMsgCallback;
PFN_vkDbgMsgCallback dbgBreakCallback;
std::vector<VkDbgMsgCallback> msg_callbacks;
uint32_t current_buffer;
uint32_t queue_count;
};
VkResult memory_type_from_properties(struct sample_info &info, uint32_t typeBits, VkFlags properties, uint32_t *typeIndex);
void set_image_layout(
struct sample_info &demo,
VkImage image,
VkImageAspect aspect,
VkImageLayout old_image_layout,
VkImageLayout new_image_layout);
bool read_ppm(char const*const filename, int *width, int *height, uint64_t rowPitch, char *dataPtr);
void extract_version(uint32_t version, uint32_t &major, uint32_t &minor, uint32_t &patch);
|
/*
* Vulkan Samples Kit
*
* Copyright (C) 2015 LunarG, Inc.
*
* 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 <iostream>
#include <string>
#include <sstream>
#include <vector>
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include <glm/gtc/matrix_transform.hpp>
#ifdef _WIN32
#pragma comment(linker, "/subsystem:console")
#include <windows.h>
#include <vulkan.h>
#include <vk_wsi_swapchain.h>
#include <vk_wsi_device_swapchain.h>
#include <vk_debug_report_lunarg.h>
#define APP_NAME_STR_LEN 80
#else // _WIN32
#include <xcb/xcb.h>
#include <vulkan/vulkan.h>
#include <vulkan/vk_wsi_swapchain.h>
#include <vulkan/vk_wsi_device_swapchain.h>
#include <vulkan/vk_debug_report_lunarg.h>
#endif // _WIN32
#define SAMPLE_BUFFER_COUNT 2
#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \
{ \
info.fp##entrypoint = (PFN_vk##entrypoint) vkGetInstanceProcAddr(inst, "vk"#entrypoint); \
if (info.fp##entrypoint == NULL) { \
std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \
exit(-1); \
} \
}
#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \
{ \
info.fp##entrypoint = (PFN_vk##entrypoint) vkGetDeviceProcAddr(dev, "vk"#entrypoint); \
if (info.fp##entrypoint == NULL) { \
std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \
exit(-1); \
} \
}
std::string get_base_data_dir();
std::string get_data_dir( std::string filename );
/*
* structure to track all objects related to a texture.
*/
struct texture_object {
VkSampler sampler;
VkImage image;
VkImageLayout imageLayout;
VkDeviceMemory mem;
VkImageView view;
int32_t tex_width, tex_height;
};
/*
* Keep each of our swap chain buffers' image, command buffer and view in one spot
*/
typedef struct _swap_chain_buffers {
VkImage image;
VkAttachmentView view;
} swap_chain_buffer;
/*
* A layer can expose extensions, keep track of those
* extensions here.
*/
typedef struct {
VkLayerProperties properties;
std::vector<VkExtensionProperties> extensions;
} layer_properties;
/*
* Structure for tracking information used / created / modified
* by utility functions.
*/
struct sample_info {
#ifdef _WIN32
#define APP_NAME_STR_LEN 80
HINSTANCE connection; // hInstance - Windows Instance
char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
HWND window; // hWnd - window handle
#else // _WIN32
xcb_connection_t *connection;
xcb_screen_t *screen;
xcb_window_t window;
xcb_intern_atom_reply_t *atom_wm_delete_window;
VkPlatformHandleXcbWSI platform_handle_xcb;
#endif // _WIN32
bool prepared;
bool use_staging_buffer;
std::vector<char *> instance_layer_names;
std::vector<char *> instance_extension_names;
std::vector<layer_properties> instance_layer_properties;
std::vector<VkExtensionProperties> instance_extension_properties;
VkInstance inst;
std::vector<char *> device_layer_names;
std::vector<char *> device_extension_names;
std::vector<layer_properties> device_layer_properties;
std::vector<VkExtensionProperties> device_extension_properties;
VkPhysicalDevice gpu;
VkDevice device;
VkQueue queue;
uint32_t graphics_queue_family_index;
VkPhysicalDeviceProperties gpu_props;
std::vector<VkPhysicalDeviceQueueProperties> queue_props;
VkPhysicalDeviceMemoryProperties memory_properties;
VkFramebuffer framebuffers[SAMPLE_BUFFER_COUNT];
int width, height;
VkFormat format;
PFN_vkGetPhysicalDeviceSurfaceSupportWSI fpGetPhysicalDeviceSurfaceSupportWSI;
PFN_vkGetSurfaceInfoWSI fpGetSurfaceInfoWSI;
PFN_vkCreateSwapChainWSI fpCreateSwapChainWSI;
PFN_vkDestroySwapChainWSI fpDestroySwapChainWSI;
PFN_vkGetSwapChainInfoWSI fpGetSwapChainInfoWSI;
PFN_vkAcquireNextImageWSI fpAcquireNextImageWSI;
PFN_vkQueuePresentWSI fpQueuePresentWSI;
VkSurfaceDescriptionWindowWSI surface_description;
size_t swapChainImageCount;
VkSwapChainWSI swap_chain;
std::vector<swap_chain_buffer> buffers;
VkCmdPool cmd_pool;
struct {
VkFormat format;
VkImage image;
VkDeviceMemory mem;
VkAttachmentView view;
} depth;
std::vector<struct texture_object> textures;
struct {
VkBuffer buf;
VkDeviceMemory mem;
VkBufferView view;
VkDescriptorInfo desc;
} uniform_data;
glm::mat4 Projection;
glm::mat4 View;
glm::mat4 Model;
glm::mat4 MVP;
VkCmdBuffer cmd; // Buffer for initialization commands
VkPipelineLayout pipeline_layout;
VkDescriptorSetLayout desc_layout;
VkPipelineCache pipelineCache;
VkRenderPass render_pass;
VkPipeline pipeline;
VkDynamicViewportState viewport;
VkDynamicRasterState raster;
VkDynamicColorBlendState color_blend;
VkDynamicDepthStencilState depth_stencil;
VkShaderModule vert_shader_module;
VkShaderModule frag_shader_module;
VkDescriptorPool desc_pool;
VkDescriptorSet desc_set;
PFN_vkDbgCreateMsgCallback dbgCreateMsgCallback;
PFN_vkDbgDestroyMsgCallback dbgDestroyMsgCallback;
PFN_vkDbgMsgCallback dbgBreakCallback;
std::vector<VkDbgMsgCallback> msg_callbacks;
uint32_t current_buffer;
uint32_t queue_count;
};
VkResult memory_type_from_properties(struct sample_info &info, uint32_t typeBits, VkFlags properties, uint32_t *typeIndex);
void set_image_layout(
struct sample_info &demo,
VkImage image,
VkImageAspect aspect,
VkImageLayout old_image_layout,
VkImageLayout new_image_layout);
bool read_ppm(char const*const filename, int *width, int *height, uint64_t rowPitch, char *dataPtr);
void extract_version(uint32_t version, uint32_t &major, uint32_t &minor, uint32_t &patch);
|
Remove unused field
|
Remove unused field
|
C++
|
apache-2.0
|
Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples
|
a00f21927961ed4a6e520cfd9c9f75b5fe062e5f
|
source/globjects/source/Framebuffer.cpp
|
source/globjects/source/Framebuffer.cpp
|
#include <globjects/Framebuffer.h>
#include <cassert>
#include <glbinding/gl/functions.h>
#include <glbinding/gl/enum.h>
#include <glbinding/Meta.h>
#include <glm/gtc/type_ptr.hpp>
#include <globjects/ObjectVisitor.h>
#include <globjects/AttachedTexture.h>
#include <globjects/FramebufferAttachment.h>
#include <globjects/AttachedRenderbuffer.h>
#include "pixelformat.h"
#include "registry/ImplementationRegistry.h"
#include "registry/ObjectRegistry.h"
#include "implementations/AbstractFramebufferImplementation.h"
#include "Resource.h"
using namespace gl;
namespace
{
const globjects::AbstractFramebufferImplementation & implementation()
{
return globjects::ImplementationRegistry::current().framebufferImplementation();
}
}
namespace globjects
{
void Framebuffer::hintBindlessImplementation(const BindlessImplementation impl)
{
ImplementationRegistry::current().initialize(impl);
}
Framebuffer::Framebuffer()
: Object(new FrameBufferObjectResource)
{
}
Framebuffer::Framebuffer(IDResource * resource)
: Object(resource)
{
}
Framebuffer * Framebuffer::fromId(const GLuint id)
{
return new Framebuffer(new ExternalResource(id));
}
Framebuffer * Framebuffer::defaultFBO()
{
return ObjectRegistry::current().defaultFBO();
}
Framebuffer::~Framebuffer()
{
}
void Framebuffer::accept(ObjectVisitor & visitor)
{
visitor.visitFrameBufferObject(this);
}
void Framebuffer::bind() const
{
glBindFramebuffer(GL_FRAMEBUFFER, id());
}
void Framebuffer::bind(const GLenum target) const
{
glBindFramebuffer(target, id());
}
void Framebuffer::unbind()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void Framebuffer::unbind(const GLenum target)
{
glBindFramebuffer(target, 0);
}
void Framebuffer::setParameter(const GLenum pname, const GLint param)
{
implementation().setParameter(this, pname, param);
}
GLint Framebuffer::getAttachmentParameter(const GLenum attachment, const GLenum pname) const
{
return implementation().getAttachmentParameter(this, attachment, pname);
}
void Framebuffer::attachTexture(const GLenum attachment, Texture * texture, const GLint level)
{
implementation().attachTexture(this, attachment, texture, level);
addAttachment(new AttachedTexture(this, attachment, texture, level));
}
void Framebuffer::attachTextureLayer(const GLenum attachment, Texture * texture, const GLint level, const GLint layer)
{
implementation().attachTextureLayer(this, attachment, texture, level, layer);
addAttachment(new AttachedTexture(this, attachment, texture, level, layer));
}
void Framebuffer::attachRenderBuffer(const GLenum attachment, Renderbuffer * renderBuffer)
{
implementation().attachRenderBuffer(this, attachment, renderBuffer);
addAttachment(new AttachedRenderbuffer(this, attachment, renderBuffer));
}
bool Framebuffer::detach(const GLenum attachment)
{
FramebufferAttachment * attachmentObject = getAttachment(attachment);
if (!attachmentObject)
return false;
if (attachmentObject->isTextureAttachment())
{
AttachedTexture * textureAttachment = attachmentObject->asTextureAttachment();
if (textureAttachment->hasLayer())
{
implementation().attachTextureLayer(this, attachment, nullptr, textureAttachment->level(), textureAttachment->layer());
}
else
{
implementation().attachTexture(this, attachment, nullptr, textureAttachment->level());
}
}
else if (attachmentObject->isRenderBufferAttachment())
{
implementation().attachRenderBuffer(this, attachment, nullptr);
}
m_attachments.erase(attachment);
return true;
}
void Framebuffer::setReadBuffer(const GLenum mode) const
{
implementation().setReadBuffer(this, mode);
}
void Framebuffer::setDrawBuffer(const GLenum mode) const
{
implementation().setDrawBuffer(this, mode);
}
void Framebuffer::setDrawBuffers(const GLsizei n, const GLenum * modes) const
{
assert(modes != nullptr || n == 0);
implementation().setDrawBuffers(this, n, modes);
}
void Framebuffer::setDrawBuffers(const std::vector<GLenum> & modes) const
{
setDrawBuffers(static_cast<int>(modes.size()), modes.data());
}
void Framebuffer::clear(const ClearBufferMask mask)
{
bind();
glClear(mask);
}
void Framebuffer::clearBufferiv(const GLenum buffer, const GLint drawBuffer, const GLint * value)
{
bind();
glClearBufferiv(buffer, drawBuffer, value);
}
void Framebuffer::clearBufferuiv(const GLenum buffer, const GLint drawBuffer, const GLuint * value)
{
bind();
glClearBufferuiv(buffer, drawBuffer, value);
}
void Framebuffer::clearBufferfv(const GLenum buffer, const GLint drawBuffer, const GLfloat * value)
{
bind();
glClearBufferfv(buffer, drawBuffer, value);
}
void Framebuffer::clearBufferfi(const GLenum buffer, const GLint drawBuffer, const GLfloat depth, const GLint stencil)
{
bind();
glClearBufferfi(buffer, drawBuffer, depth, stencil);
}
void Framebuffer::clearBuffer(const GLenum buffer, const GLint drawBuffer, const glm::ivec4 & value)
{
clearBufferiv(buffer, drawBuffer, glm::value_ptr(value));
}
void Framebuffer::clearBuffer(const GLenum buffer, const GLint drawBuffer, const glm::uvec4 & value)
{
clearBufferuiv(buffer, drawBuffer, glm::value_ptr(value));
}
void Framebuffer::clearBuffer(const GLenum buffer, const GLint drawBuffer, const glm::vec4 & value)
{
clearBufferfv(buffer, drawBuffer, glm::value_ptr(value));
}
void Framebuffer::colorMask(const GLboolean red, const GLboolean green, const GLboolean blue, const GLboolean alpha)
{
glColorMask(red, green, blue, alpha);
}
void Framebuffer::colorMask(const glm::bvec4 & mask)
{
colorMask(static_cast<GLboolean>(mask[0]), static_cast<GLboolean>(mask[1]), static_cast<GLboolean>(mask[2]), static_cast<GLboolean>(mask[3]));
}
void Framebuffer::colorMaski(const GLuint buffer, const GLboolean red, const GLboolean green, const GLboolean blue, const GLboolean alpha)
{
glColorMaski(buffer, red, green, blue, alpha);
}
void Framebuffer::colorMaski(const GLuint buffer, const glm::bvec4 & mask)
{
colorMaski(buffer, static_cast<GLboolean>(mask[0]), static_cast<GLboolean>(mask[1]), static_cast<GLboolean>(mask[2]), static_cast<GLboolean>(mask[3]));
}
void Framebuffer::clearColor(const GLfloat red, const GLfloat green, const GLfloat blue, const GLfloat alpha)
{
glClearColor(red, green, blue, alpha);
}
void Framebuffer::clearColor(const glm::vec4 & color)
{
clearColor(color.r, color.g, color.b, color.a);
}
void Framebuffer::clearDepth(const GLclampd depth)
{
glClearDepth(depth);
}
void Framebuffer::readPixels(const GLint x, const GLint y, const GLsizei width, const GLsizei height, const GLenum format, const GLenum type, GLvoid * data) const
{
bind(GL_READ_FRAMEBUFFER);
glReadPixels(x, y, width, height, format, type, data);
}
void Framebuffer::readPixels(const std::array<GLint, 4> & rect, const GLenum format, const GLenum type, GLvoid * data) const
{
readPixels(rect[0], rect[1], rect[2], rect[3], format, type, data);
}
void Framebuffer::readPixels(const GLenum readBuffer, const std::array<GLint, 4> & rect, const GLenum format, const GLenum type, GLvoid * data) const
{
setReadBuffer(readBuffer);
readPixels(rect, format, type, data);
}
std::vector<unsigned char> Framebuffer::readPixelsToByteArray(const std::array<GLint, 4> & rect, const GLenum format, const GLenum type) const
{
int size = imageSizeInBytes(rect[2], rect[3], 1, format, type);
std::vector<unsigned char> data(size);
readPixels(rect, format, type, data.data());
return data;
}
std::vector<unsigned char> Framebuffer::readPixelsToByteArray(GLenum readBuffer, const std::array<GLint, 4> & rect, GLenum format, GLenum type) const
{
setReadBuffer(readBuffer);
return readPixelsToByteArray(rect, format, type);
}
void Framebuffer::readPixelsToBuffer(const std::array<GLint, 4> & rect, GLenum format, GLenum type, Buffer * pbo) const
{
assert(pbo != nullptr);
pbo->bind(GL_PIXEL_PACK_BUFFER);
readPixels(rect, format, type, nullptr);
pbo->unbind(GL_PIXEL_PACK_BUFFER);
}
void Framebuffer::blit(GLenum readBuffer, const std::array<GLint, 4> & srcRect, Framebuffer * destFbo, GLenum drawBuffer, const std::array<GLint, 4> & destRect, ClearBufferMask mask, GLenum filter) const
{
blit(readBuffer, srcRect, destFbo, std::vector<GLenum>{ drawBuffer }, destRect, mask, filter);
}
void Framebuffer::blit(GLenum readBuffer, const std::array<GLint, 4> & srcRect, Framebuffer * destFbo, const std::vector<GLenum> & drawBuffers, const std::array<GLint, 4> & destRect, ClearBufferMask mask, GLenum filter) const
{
setReadBuffer(readBuffer);
destFbo->setDrawBuffers(drawBuffers);
bind(GL_READ_FRAMEBUFFER);
destFbo->bind(GL_DRAW_FRAMEBUFFER);
blit(srcRect, destRect, mask, filter);
}
void Framebuffer::blit(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint destX0, GLint destY0, GLint destX1, GLint destY1, ClearBufferMask mask, GLenum filter)
{
glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, destX0, destY0, destX1, destY1, mask, filter);
}
void Framebuffer::blit(const std::array<GLint, 4> & srcRect, const std::array<GLint, 4> & destRect, ClearBufferMask mask, GLenum filter)
{
blit(srcRect[0], srcRect[1], srcRect[2], srcRect[3], destRect[0], destRect[1], destRect[2], destRect[3], mask, filter);
}
GLenum Framebuffer::checkStatus() const
{
return implementation().checkStatus(this);
}
std::string Framebuffer::statusString() const
{
return glbinding::Meta::getString(checkStatus());
}
void Framebuffer::printStatus(bool onlyErrors) const
{
GLenum status = checkStatus();
if (onlyErrors && status == GL_FRAMEBUFFER_COMPLETE) return;
if (status == GL_FRAMEBUFFER_COMPLETE)
{
info() << glbinding::Meta::getString(GL_FRAMEBUFFER_COMPLETE);
}
else
{
std::stringstream ss;
ss.flags(std::ios::hex | std::ios::showbase);
ss << static_cast<unsigned int>(status);
critical() << glbinding::Meta::getString(status) << " (" << ss.str() << ")";
}
}
void Framebuffer::addAttachment(FramebufferAttachment * attachment)
{
assert(attachment != nullptr);
m_attachments[attachment->attachment()] = attachment;
}
FramebufferAttachment * Framebuffer::getAttachment(GLenum attachment)
{
return m_attachments[attachment];
}
std::vector<FramebufferAttachment*> Framebuffer::attachments()
{
std::vector<FramebufferAttachment*> attachments;
for (std::pair<GLenum, ref_ptr<FramebufferAttachment>> pair: m_attachments)
{
attachments.push_back(pair.second);
}
return attachments;
}
GLenum Framebuffer::objectType() const
{
return GL_FRAMEBUFFER;
}
} // namespace globjects
|
#include <globjects/Framebuffer.h>
#include <cassert>
#include <glbinding/gl/functions.h>
#include <glbinding/gl/enum.h>
#include <glbinding/Meta.h>
#include <glm/gtc/type_ptr.hpp>
#include <globjects/ObjectVisitor.h>
#include <globjects/AttachedTexture.h>
#include <globjects/FramebufferAttachment.h>
#include <globjects/AttachedRenderbuffer.h>
#include "pixelformat.h"
#include "registry/ImplementationRegistry.h"
#include "registry/ObjectRegistry.h"
#include "implementations/AbstractFramebufferImplementation.h"
#include "Resource.h"
using namespace gl;
namespace
{
const globjects::AbstractFramebufferImplementation & implementation()
{
return globjects::ImplementationRegistry::current().framebufferImplementation();
}
}
namespace globjects
{
void Framebuffer::hintBindlessImplementation(const BindlessImplementation impl)
{
ImplementationRegistry::current().initialize(impl);
}
Framebuffer::Framebuffer()
: Object(new FrameBufferObjectResource)
{
}
Framebuffer::Framebuffer(IDResource * resource)
: Object(resource)
{
}
Framebuffer * Framebuffer::fromId(const GLuint id)
{
return new Framebuffer(new ExternalResource(id));
}
Framebuffer * Framebuffer::defaultFBO()
{
return ObjectRegistry::current().defaultFBO();
}
Framebuffer::~Framebuffer()
{
}
void Framebuffer::accept(ObjectVisitor & visitor)
{
visitor.visitFrameBufferObject(this);
}
void Framebuffer::bind() const
{
glBindFramebuffer(GL_FRAMEBUFFER, id());
}
void Framebuffer::bind(const GLenum target) const
{
glBindFramebuffer(target, id());
}
void Framebuffer::unbind()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void Framebuffer::unbind(const GLenum target)
{
glBindFramebuffer(target, 0);
}
void Framebuffer::setParameter(const GLenum pname, const GLint param)
{
implementation().setParameter(this, pname, param);
}
GLint Framebuffer::getAttachmentParameter(const GLenum attachment, const GLenum pname) const
{
return implementation().getAttachmentParameter(this, attachment, pname);
}
void Framebuffer::attachTexture(const GLenum attachment, Texture * texture, const GLint level)
{
implementation().attachTexture(this, attachment, texture, level);
addAttachment(new AttachedTexture(this, attachment, texture, level));
}
void Framebuffer::attachTextureLayer(const GLenum attachment, Texture * texture, const GLint level, const GLint layer)
{
implementation().attachTextureLayer(this, attachment, texture, level, layer);
addAttachment(new AttachedTexture(this, attachment, texture, level, layer));
}
void Framebuffer::attachRenderBuffer(const GLenum attachment, Renderbuffer * renderBuffer)
{
implementation().attachRenderBuffer(this, attachment, renderBuffer);
addAttachment(new AttachedRenderbuffer(this, attachment, renderBuffer));
}
bool Framebuffer::detach(const GLenum attachment)
{
FramebufferAttachment * attachmentObject = getAttachment(attachment);
if (!attachmentObject)
return false;
if (attachmentObject->isTextureAttachment())
{
AttachedTexture * textureAttachment = attachmentObject->asTextureAttachment();
if (textureAttachment->hasLayer())
{
implementation().attachTextureLayer(this, attachment, nullptr, textureAttachment->level(), textureAttachment->layer());
}
else
{
implementation().attachTexture(this, attachment, nullptr, textureAttachment->level());
}
}
else if (attachmentObject->isRenderBufferAttachment())
{
implementation().attachRenderBuffer(this, attachment, nullptr);
}
m_attachments.erase(attachment);
return true;
}
void Framebuffer::setReadBuffer(const GLenum mode) const
{
implementation().setReadBuffer(this, mode);
}
void Framebuffer::setDrawBuffer(const GLenum mode) const
{
implementation().setDrawBuffer(this, mode);
}
void Framebuffer::setDrawBuffers(const GLsizei n, const GLenum * modes) const
{
assert(modes != nullptr || n == 0);
implementation().setDrawBuffers(this, n, modes);
}
void Framebuffer::setDrawBuffers(const std::vector<GLenum> & modes) const
{
setDrawBuffers(static_cast<int>(modes.size()), modes.data());
}
void Framebuffer::clear(const ClearBufferMask mask)
{
bind();
glClear(mask);
}
void Framebuffer::clearBufferiv(const GLenum buffer, const GLint drawBuffer, const GLint * value)
{
bind();
glClearBufferiv(buffer, drawBuffer, value);
}
void Framebuffer::clearBufferuiv(const GLenum buffer, const GLint drawBuffer, const GLuint * value)
{
bind();
glClearBufferuiv(buffer, drawBuffer, value);
}
void Framebuffer::clearBufferfv(const GLenum buffer, const GLint drawBuffer, const GLfloat * value)
{
bind();
glClearBufferfv(buffer, drawBuffer, value);
}
void Framebuffer::clearBufferfi(const GLenum buffer, const GLint drawBuffer, const GLfloat depth, const GLint stencil)
{
bind();
glClearBufferfi(buffer, drawBuffer, depth, stencil);
}
void Framebuffer::clearBuffer(const GLenum buffer, const GLint drawBuffer, const glm::ivec4 & value)
{
clearBufferiv(buffer, drawBuffer, glm::value_ptr(value));
}
void Framebuffer::clearBuffer(const GLenum buffer, const GLint drawBuffer, const glm::uvec4 & value)
{
clearBufferuiv(buffer, drawBuffer, glm::value_ptr(value));
}
void Framebuffer::clearBuffer(const GLenum buffer, const GLint drawBuffer, const glm::vec4 & value)
{
clearBufferfv(buffer, drawBuffer, glm::value_ptr(value));
}
void Framebuffer::colorMask(const GLboolean red, const GLboolean green, const GLboolean blue, const GLboolean alpha)
{
glColorMask(red, green, blue, alpha);
}
void Framebuffer::colorMask(const glm::bvec4 & mask)
{
colorMask(static_cast<GLboolean>(mask[0]), static_cast<GLboolean>(mask[1]), static_cast<GLboolean>(mask[2]), static_cast<GLboolean>(mask[3]));
}
void Framebuffer::colorMaski(const GLuint buffer, const GLboolean red, const GLboolean green, const GLboolean blue, const GLboolean alpha)
{
glColorMaski(buffer, red, green, blue, alpha);
}
void Framebuffer::colorMaski(const GLuint buffer, const glm::bvec4 & mask)
{
colorMaski(buffer, static_cast<GLboolean>(mask[0]), static_cast<GLboolean>(mask[1]), static_cast<GLboolean>(mask[2]), static_cast<GLboolean>(mask[3]));
}
void Framebuffer::clearColor(const GLfloat red, const GLfloat green, const GLfloat blue, const GLfloat alpha)
{
glClearColor(red, green, blue, alpha);
}
void Framebuffer::clearColor(const glm::vec4 & color)
{
clearColor(color.r, color.g, color.b, color.a);
}
void Framebuffer::clearDepth(const GLclampd depth)
{
glClearDepth(depth);
}
void Framebuffer::readPixels(const GLint x, const GLint y, const GLsizei width, const GLsizei height, const GLenum format, const GLenum type, GLvoid * data) const
{
bind(GL_READ_FRAMEBUFFER);
glReadPixels(x, y, width, height, format, type, data);
}
void Framebuffer::readPixels(const std::array<GLint, 4> & rect, const GLenum format, const GLenum type, GLvoid * data) const
{
readPixels(rect[0], rect[1], rect[2], rect[3], format, type, data);
}
void Framebuffer::readPixels(const GLenum readBuffer, const std::array<GLint, 4> & rect, const GLenum format, const GLenum type, GLvoid * data) const
{
setReadBuffer(readBuffer);
readPixels(rect, format, type, data);
}
std::vector<unsigned char> Framebuffer::readPixelsToByteArray(const std::array<GLint, 4> & rect, const GLenum format, const GLenum type) const
{
int size = imageSizeInBytes(rect[2], rect[3], 1, format, type);
std::vector<unsigned char> data(size);
readPixels(rect, format, type, data.data());
return data;
}
std::vector<unsigned char> Framebuffer::readPixelsToByteArray(GLenum readBuffer, const std::array<GLint, 4> & rect, GLenum format, GLenum type) const
{
setReadBuffer(readBuffer);
return readPixelsToByteArray(rect, format, type);
}
void Framebuffer::readPixelsToBuffer(const std::array<GLint, 4> & rect, GLenum format, GLenum type, Buffer * pbo) const
{
assert(pbo != nullptr);
pbo->bind(GL_PIXEL_PACK_BUFFER);
readPixels(rect, format, type, nullptr);
pbo->unbind(GL_PIXEL_PACK_BUFFER);
}
void Framebuffer::blit(GLenum readBuffer, const std::array<GLint, 4> & srcRect, Framebuffer * destFbo, GLenum drawBuffer, const std::array<GLint, 4> & destRect, ClearBufferMask mask, GLenum filter) const
{
blit(readBuffer, srcRect, destFbo, std::vector<GLenum>{ drawBuffer }, destRect, mask, filter);
}
void Framebuffer::blit(GLenum readBuffer, const std::array<GLint, 4> & srcRect, Framebuffer * destFbo, const std::vector<GLenum> & drawBuffers, const std::array<GLint, 4> & destRect, ClearBufferMask mask, GLenum filter) const
{
bind(GL_READ_FRAMEBUFFER);
destFbo->bind(GL_DRAW_FRAMEBUFFER);
setReadBuffer(readBuffer);
destFbo->setDrawBuffers(drawBuffers);
blit(srcRect, destRect, mask, filter);
}
void Framebuffer::blit(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint destX0, GLint destY0, GLint destX1, GLint destY1, ClearBufferMask mask, GLenum filter)
{
glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, destX0, destY0, destX1, destY1, mask, filter);
}
void Framebuffer::blit(const std::array<GLint, 4> & srcRect, const std::array<GLint, 4> & destRect, ClearBufferMask mask, GLenum filter)
{
blit(srcRect[0], srcRect[1], srcRect[2], srcRect[3], destRect[0], destRect[1], destRect[2], destRect[3], mask, filter);
}
GLenum Framebuffer::checkStatus() const
{
return implementation().checkStatus(this);
}
std::string Framebuffer::statusString() const
{
return glbinding::Meta::getString(checkStatus());
}
void Framebuffer::printStatus(bool onlyErrors) const
{
GLenum status = checkStatus();
if (onlyErrors && status == GL_FRAMEBUFFER_COMPLETE) return;
if (status == GL_FRAMEBUFFER_COMPLETE)
{
info() << glbinding::Meta::getString(GL_FRAMEBUFFER_COMPLETE);
}
else
{
std::stringstream ss;
ss.flags(std::ios::hex | std::ios::showbase);
ss << static_cast<unsigned int>(status);
critical() << glbinding::Meta::getString(status) << " (" << ss.str() << ")";
}
}
void Framebuffer::addAttachment(FramebufferAttachment * attachment)
{
assert(attachment != nullptr);
m_attachments[attachment->attachment()] = attachment;
}
FramebufferAttachment * Framebuffer::getAttachment(GLenum attachment)
{
return m_attachments[attachment];
}
std::vector<FramebufferAttachment*> Framebuffer::attachments()
{
std::vector<FramebufferAttachment*> attachments;
for (std::pair<GLenum, ref_ptr<FramebufferAttachment>> pair: m_attachments)
{
attachments.push_back(pair.second);
}
return attachments;
}
GLenum Framebuffer::objectType() const
{
return GL_FRAMEBUFFER;
}
} // namespace globjects
|
Fix Framebuffer blitting
|
Fix Framebuffer blitting
|
C++
|
mit
|
cginternals/globjects,j-o/globjects,j-o/globjects,j-o/globjects,cginternals/globjects,j-o/globjects
|
f3775ad5dbec6eb2479e01c70fa5610ee0fb5ebe
|
test/Thread/ThreadSchedulingPolicyTestCase.cpp
|
test/Thread/ThreadSchedulingPolicyTestCase.cpp
|
/**
* \file
* \brief ThreadSchedulingPolicyTestCase class implementation
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-17
*/
#include "ThreadSchedulingPolicyTestCase.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {192};
/// priority of test thread
constexpr uint8_t testThreadPriority {1};
/// number of test threads
constexpr size_t totalThreads {10};
/// number of loops in test thread
constexpr size_t loops {5};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
void thread(SequenceAsserter& sequenceAsserter, unsigned int sequencePoint, unsigned int sequenceStep);
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, thread,
std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>(), std::declval<unsigned int>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread.
*
* Marks the sequence point in SequenceAsserter and waits for context switch. This is repeated several times.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
* \param [in] sequenceStep is the step added to sequence point in each iteration of the loop
*/
void thread(SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint, const unsigned int sequenceStep)
{
for (size_t i = 0; i < loops; ++i)
{
sequenceAsserter.sequencePoint(sequencePoint + i * sequenceStep);
const auto contextSwitchCount = statistics::getContextSwitchCount();
while (contextSwitchCount == statistics::getContextSwitchCount());
}
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
* \param [in] sequenceStep is the step added to sequence point in each iteration of the loop
*
* \return constructed TestThread object
*/
TestThread makeTestThread(SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint,
const unsigned int sequenceStep)
{
return makeStaticThread<testThreadStackSize>(testThreadPriority, thread, std::ref(sequenceAsserter),
static_cast<unsigned int>(sequencePoint), static_cast<unsigned int>(sequenceStep));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool ThreadSchedulingPolicyTestCase::run_() const
{
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(sequenceAsserter, 0, totalThreads),
makeTestThread(sequenceAsserter, 1, totalThreads),
makeTestThread(sequenceAsserter, 2, totalThreads),
makeTestThread(sequenceAsserter, 3, totalThreads),
makeTestThread(sequenceAsserter, 4, totalThreads),
makeTestThread(sequenceAsserter, 5, totalThreads),
makeTestThread(sequenceAsserter, 6, totalThreads),
makeTestThread(sequenceAsserter, 7, totalThreads),
makeTestThread(sequenceAsserter, 8, totalThreads),
makeTestThread(sequenceAsserter, 9, totalThreads),
}};
volatile bool dummyThreadTerminate {};
// this thread is needed, because test threads need at least one other thread (which would preempt them) to
// exit their wait loop, so there is a problem with ending the very last iteration of the very last thread...
auto dummyThread = makeStaticThread<testThreadStackSize>(testThreadPriority,
[&dummyThreadTerminate]()
{
while (dummyThreadTerminate != true);
});
decltype(TickClock::now()) testStart;
{
architecture::InterruptMaskingLock interruptMaskingLock;
// wait for beginning of next tick - test threads should be started in the same tick
ThisThread::sleepFor({});
for (auto& thread : threads)
thread.start();
dummyThread.start();
testStart = TickClock::now();
}
for (auto& thread : threads)
thread.join();
const auto testDuration = TickClock::now() - testStart;
dummyThreadTerminate = true;
dummyThread.join();
if (sequenceAsserter.assertSequence(totalThreads * loops) == false)
return false;
// calculations need to take dummyThread into account - this is the "+ 1"
if (testDuration != scheduler::RoundRobinQuantum::getInitial() * (totalThreads + 1) * loops)
return false;
return true;
}
} // namespace test
} // namespace distortos
|
/**
* \file
* \brief ThreadSchedulingPolicyTestCase class implementation
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-17
*/
#include "ThreadSchedulingPolicyTestCase.hpp"
#include "SequenceAsserter.hpp"
#include "wasteTime.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// pair of sequence points
using SequencePoints = std::pair<unsigned int, unsigned int>;
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {192};
/// priority of test thread
constexpr uint8_t testThreadPriority {1};
/// number of test threads
constexpr size_t totalThreads {10};
/// duration of single test thread - significantly longer than single round-robin quantum
constexpr auto testThreadDuration = scheduler::RoundRobinQuantum::getInitial() * 2;
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
void thread(SequenceAsserter& sequenceAsserter, SequencePoints sequencePoints);
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, thread,
std::ref(std::declval<SequenceAsserter&>()), std::declval<SequencePoints>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread.
*
* Marks the first sequence point in SequenceAsserter, wastes some time and marks the second sequence point in
* SequenceAsserter.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoints is a pair of sequence points for this instance
*/
void thread(SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints)
{
sequenceAsserter.sequencePoint(sequencePoints.first);
wasteTime(testThreadDuration);
sequenceAsserter.sequencePoint(sequencePoints.second);
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoints is a pair of sequence points for this instance
*
* \return constructed TestThread object
*/
TestThread makeTestThread(SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints)
{
return makeStaticThread<testThreadStackSize>(testThreadPriority, thread, std::ref(sequenceAsserter),
static_cast<SequencePoints>(sequencePoints));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool ThreadSchedulingPolicyTestCase::run_() const
{
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(sequenceAsserter, {0, 0 + totalThreads}),
makeTestThread(sequenceAsserter, {1, 1 + totalThreads}),
makeTestThread(sequenceAsserter, {2, 2 + totalThreads}),
makeTestThread(sequenceAsserter, {3, 3 + totalThreads}),
makeTestThread(sequenceAsserter, {4, 4 + totalThreads}),
makeTestThread(sequenceAsserter, {5, 5 + totalThreads}),
makeTestThread(sequenceAsserter, {6, 6 + totalThreads}),
makeTestThread(sequenceAsserter, {7, 7 + totalThreads}),
makeTestThread(sequenceAsserter, {8, 8 + totalThreads}),
makeTestThread(sequenceAsserter, {9, 9 + totalThreads}),
}};
decltype(TickClock::now()) testStart;
{
architecture::InterruptMaskingLock interruptMaskingLock;
// wait for beginning of next tick - test threads should be started in the same tick
ThisThread::sleepFor({});
for (auto& thread : threads)
thread.start();
testStart = TickClock::now();
}
for (auto& thread : threads)
thread.join();
const auto testDuration = TickClock::now() - testStart;
if (sequenceAsserter.assertSequence(totalThreads * 2) == false)
return false;
// exact time cannot be calculated, because wasteTime() is not precise when context switches occur during it
if (testDuration < testThreadDuration * totalThreads)
return false;
return true;
}
} // namespace test
} // namespace distortos
|
simplify round-robin test in ThreadSchedulingPolicyTestCase to make it more generic
|
test: simplify round-robin test in ThreadSchedulingPolicyTestCase to
make it more generic
|
C++
|
mpl-2.0
|
jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,jasmin-j/distortos,DISTORTEC/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,jasmin-j/distortos,CezaryGapinski/distortos
|
278aed9144d10052b17260e7d6737bf7c66454d4
|
src/contract/superblock.cpp
|
src/contract/superblock.cpp
|
#include "superblock.h"
#include "uint256.h"
#include "util.h"
#include "main.h"
#include "compat/endian.h"
std::string ExtractValue(std::string data, std::string delimiter, int pos);
namespace
{
struct BinaryResearcher
{
std::array<unsigned char, 16> cpid;
int16_t magnitude;
};
// Ensure that the compiler does not add padding between the cpid and the
// magnitude. If it does it does it to align the data, at which point the
// pointer cast in UnpackBinarySuperblock will be illegal. In such a
// case we will have to resort to a slower unpack.
static_assert(offsetof(struct BinaryResearcher, magnitude) ==
sizeof(struct BinaryResearcher) - sizeof(int16_t),
"Unexpected padding in BinaryResearcher");
}
std::string UnpackBinarySuperblock(std::string sBlock)
{
// 12-21-2015: R HALFORD: If the block is not binary, return the legacy format for backward compatibility
std::string sBinary = ExtractXML(sBlock,"<BINARY>","</BINARY>");
if (sBinary.empty()) return sBlock;
std::ostringstream stream;
stream << "<AVERAGES>" << ExtractXML(sBlock,"<AVERAGES>","</AVERAGES>") << "</AVERAGES>"
<< "<QUOTES>" << ExtractXML(sBlock,"<QUOTES>","</QUOTES>") << "</QUOTES>"
<< "<MAGNITUDES>";
// Binary data support structure:
// Each CPID consumes 16 bytes and 2 bytes for magnitude: (Except CPIDs with zero magnitude - the count of those is stored in XML node <ZERO> to save space)
// 1234567890123456MM
// MM = Magnitude stored as 2 bytes
// No delimiter between CPIDs, Step Rate = 18.
// CPID and magnitude are stored in big endian.
for (unsigned int x = 0; x < sBinary.length(); x += 18)
{
if(sBinary.length() - x < 18)
break;
const BinaryResearcher* researcher = reinterpret_cast<const BinaryResearcher*>(sBinary.data() + x);
stream << HexStr(researcher->cpid.begin(), researcher->cpid.end()) << ","
<< be16toh(researcher->magnitude) << ";";
}
// Append zero magnitude researchers so the beacon count matches
int num_zero_mag = atoi(ExtractXML(sBlock,"<ZERO>","</ZERO>"));
const std::string zero_entry("0,15;");
for(int i=0; i<num_zero_mag; ++i)
stream << zero_entry;
stream << "</MAGNITUDES>";
return stream.str();
}
std::string PackBinarySuperblock(std::string sBlock)
{
std::string sMagnitudes = ExtractXML(sBlock,"<MAGNITUDES>","</MAGNITUDES>");
// For each CPID in the superblock, convert data to binary
std::stringstream stream;
int64_t num_zero_mag = 0;
for (auto& entry : split(sMagnitudes.c_str(), ";"))
{
if (entry.length() < 1)
continue;
const std::vector<unsigned char>& binary_cpid = ParseHex(entry);
if(binary_cpid.size() < 16)
{
++num_zero_mag;
continue;
}
BinaryResearcher researcher;
std::copy_n(binary_cpid.begin(), researcher.cpid.size(), researcher.cpid.begin());
// Ensure we do not blow out the binary space (technically we can handle 0-65535)
double magnitude_d = strtod(ExtractValue(entry, ",", 1).c_str(), NULL);
// Changed to 65535 for the new NN. This will still be able to be successfully unpacked by any node.
magnitude_d = std::max(0.0, std::min(magnitude_d, 65535.0));
researcher.magnitude = htobe16(roundint(magnitude_d));
stream.write((const char*) &researcher, sizeof(BinaryResearcher));
}
std::stringstream block_stream;
block_stream << "<ZERO>" << num_zero_mag << "</ZERO>"
"<BINARY>" << stream.rdbuf() << "</BINARY>"
"<AVERAGES>" << ExtractXML(sBlock,"<AVERAGES>","</AVERAGES>") << "</AVERAGES>"
"<QUOTES>" << ExtractXML(sBlock,"<QUOTES>","</QUOTES>") << "</QUOTES>";
return block_stream.str();
}
void Superblock::PopulateReducedMaps()
{
uint16_t iProject = 0;
for (auto const& entry : mScraperSBStats)
{
if (entry.first.objecttype == statsobjecttype::byProject)
{
mProjectRef[entry.first.objectID] = iProject;
mProjectStats[iProject] = std::make_pair((uint64_t) std::round(entry.second.statsvalue.dAvgRAC),
(uint64_t) std::round(entry.second.statsvalue.dRAC));
++iProject;
}
}
// Find the single network wide NN entry and put in string.
ScraperObjectStatsKey StatsKey;
StatsKey.objecttype = statsobjecttype::NetworkWide;
StatsKey.objectID = "";
const auto& iter = mScraperSBStats.find(StatsKey);
mProjectRef["Network"] = iProject;
mProjectStats[iProject] = std::make_pair((uint64_t) iter->second.statsvalue.dAvgRAC,
(uint64_t) iter->second.statsvalue.dRAC);
nNetworkMagnitude = (uint64_t) std::round(iter->second.statsvalue.dMag);
uint32_t iCPID = 0;
nZeroMagCPIDs = 0;
for (auto const& entry : mScraperSBStats)
{
if (entry.first.objecttype == statsobjecttype::byCPID)
{
// If the magnitude entry is zero suppress the CPID and increment the zero counter.
if (std::round(entry.second.statsvalue.dMag) > 0)
{
mCPIDRef[NN::Cpid::Parse(entry.first.objectID)] = iCPID;
mCPIDMagnitudes[iCPID] = (uint16_t) std::round(entry.second.statsvalue.dMag);
++iCPID;
}
else
{
nZeroMagCPIDs++;
}
}
}
for (auto const& entry : mScraperSBStats)
{
if (entry.first.objecttype == statsobjecttype::byCPIDbyProject)
{
std::vector<std::string> vObjectID = split(entry.first.objectID, ",");
const auto& iterProject = mProjectRef.find(vObjectID[0]);
const auto& iterCPID = mCPIDRef.find(NN::Cpid::Parse(vObjectID[1]));
mProjectCPIDStats[iterProject->second][iterCPID->second] = std::make_tuple((uint64_t) std::round(entry.second.statsvalue.dTC),
(uint64_t) std::round(entry.second.statsvalue.dRAC),
(uint16_t) std::round(entry.second.statsvalue.dMag));
}
}
fReducedMapsPopulated = true;
}
void Superblock::SerializeSuperblock(CDataStream& ss, int nType, int nVersion) const
{
WriteCompactSize(ss, mScraperSBStats.size());
for (const auto& entry : mScraperSBStats)
{
ss << (unsigned int) entry.first.objecttype;
ss << entry.first.objectID;
ss << entry.second.statsvalue.dTC;
ss << entry.second.statsvalue.dRAT;
ss << entry.second.statsvalue.dRAC;
ss << entry.second.statsvalue.dAvgRAC;
ss << entry.second.statsvalue.dMag;
}
ss << nTime;
ss << nSBVersion;
}
void Superblock::UnserializeSuperblock(CReaderStream& ss)
{
//ss >> mScraperConvergedStats;
int64_t nSize = ReadCompactSize(ss);
unsigned int iEntry = 0;
for (auto entry = ss.begin(); entry < ss.end(); ++entry)
{
if (iEntry == nSize) break;
ScraperObjectStats StatsEntry;
unsigned int nObjectType;
ss >> nObjectType;
StatsEntry.statskey.objecttype = (statsobjecttype) nObjectType;
ss >> StatsEntry.statskey.objectID;
ss >> StatsEntry.statsvalue.dTC;
ss >> StatsEntry.statsvalue.dRAT;
ss >> StatsEntry.statsvalue.dRAC;
ss >> StatsEntry.statsvalue.dAvgRAC;
ss >> StatsEntry.statsvalue.dMag;
mScraperSBStats[StatsEntry.statskey] = StatsEntry;
++iEntry;
}
ss >> nTime;
ss >> nSBVersion;
}
void Superblock::SerializeSuperblock2(CDataStream& ss, int nType, int nVersion) const
{
ss << mProjectRef;
ss << mCPIDRef;
ss << mProjectStats;
ss << mCPIDMagnitudes;
ss << mProjectCPIDStats;
ss << nNetworkMagnitude;
ss << nZeroMagCPIDs;
ss << nHeight;
ss << nTime;
ss << nSBVersion;
}
void Superblock::UnserializeSuperblock2(CReaderStream& ss)
{
ss >> mProjectRef;
ss >> mCPIDRef;
ss >> mProjectStats;
ss >> mCPIDMagnitudes;
ss >> mProjectCPIDStats;
ss >> nNetworkMagnitude;
ss >> nZeroMagCPIDs;
ss >> nHeight;
ss >> nTime;
ss >> nSBVersion;
}
|
#include "superblock.h"
#include "uint256.h"
#include "util.h"
#include "main.h"
#include "compat/endian.h"
std::string ExtractValue(std::string data, std::string delimiter, int pos);
namespace
{
struct BinaryResearcher
{
std::array<unsigned char, 16> cpid;
int16_t magnitude;
};
// Ensure that the compiler does not add padding between the cpid and the
// magnitude. If it does it does it to align the data, at which point the
// pointer cast in UnpackBinarySuperblock will be illegal. In such a
// case we will have to resort to a slower unpack.
static_assert(offsetof(struct BinaryResearcher, magnitude) ==
sizeof(struct BinaryResearcher) - sizeof(int16_t),
"Unexpected padding in BinaryResearcher");
}
std::string UnpackBinarySuperblock(std::string sBlock)
{
// 12-21-2015: R HALFORD: If the block is not binary, return the legacy format for backward compatibility
std::string sBinary = ExtractXML(sBlock,"<BINARY>","</BINARY>");
if (sBinary.empty()) return sBlock;
std::ostringstream stream;
stream << "<AVERAGES>" << ExtractXML(sBlock,"<AVERAGES>","</AVERAGES>") << "</AVERAGES>"
<< "<QUOTES>" << ExtractXML(sBlock,"<QUOTES>","</QUOTES>") << "</QUOTES>"
<< "<MAGNITUDES>";
// Binary data support structure:
// Each CPID consumes 16 bytes and 2 bytes for magnitude: (Except CPIDs with zero magnitude - the count of those is stored in XML node <ZERO> to save space)
// 1234567890123456MM
// MM = Magnitude stored as 2 bytes
// No delimiter between CPIDs, Step Rate = 18.
// CPID and magnitude are stored in big endian.
for (unsigned int x = 0; x < sBinary.length(); x += 18)
{
if(sBinary.length() - x < 18)
break;
const BinaryResearcher* researcher = reinterpret_cast<const BinaryResearcher*>(sBinary.data() + x);
stream << HexStr(researcher->cpid.begin(), researcher->cpid.end()) << ","
<< be16toh(researcher->magnitude) << ";";
}
// Append zero magnitude researchers so the beacon count matches
int num_zero_mag = atoi(ExtractXML(sBlock,"<ZERO>","</ZERO>"));
const std::string zero_entry("0,15;");
for(int i=0; i<num_zero_mag; ++i)
stream << zero_entry;
stream << "</MAGNITUDES>";
return stream.str();
}
std::string PackBinarySuperblock(std::string sBlock)
{
std::string sMagnitudes = ExtractXML(sBlock,"<MAGNITUDES>","</MAGNITUDES>");
// For each CPID in the superblock, convert data to binary
std::stringstream stream;
int64_t num_zero_mag = 0;
for (auto& entry : split(sMagnitudes.c_str(), ";"))
{
if (entry.length() < 1)
continue;
const std::vector<unsigned char>& binary_cpid = ParseHex(entry);
if(binary_cpid.size() < 16)
{
++num_zero_mag;
continue;
}
BinaryResearcher researcher;
std::copy_n(binary_cpid.begin(), researcher.cpid.size(), researcher.cpid.begin());
// Ensure we do not blow out the binary space (technically we can handle 0-65535)
double magnitude_d = strtod(ExtractValue(entry, ",", 1).c_str(), NULL);
// Changed to 65535 for the new NN. This will still be able to be successfully unpacked by any node.
magnitude_d = std::max(0.0, std::min(magnitude_d, 65535.0));
researcher.magnitude = htobe16(roundint(magnitude_d));
stream.write((const char*) &researcher, sizeof(BinaryResearcher));
}
std::stringstream block_stream;
block_stream << "<ZERO>" << num_zero_mag << "</ZERO>"
"<BINARY>" << stream.rdbuf() << "</BINARY>"
"<AVERAGES>" << ExtractXML(sBlock,"<AVERAGES>","</AVERAGES>") << "</AVERAGES>"
"<QUOTES>" << ExtractXML(sBlock,"<QUOTES>","</QUOTES>") << "</QUOTES>";
return block_stream.str();
}
void Superblock::PopulateReducedMaps()
{
uint16_t iProject = 0;
for (auto const& entry : mScraperSBStats)
{
if (entry.first.objecttype == statsobjecttype::byProject)
{
mProjectRef[entry.first.objectID] = iProject;
mProjectStats[iProject] = std::make_pair((uint64_t) std::round(entry.second.statsvalue.dAvgRAC),
(uint64_t) std::round(entry.second.statsvalue.dRAC));
++iProject;
}
}
// Find the single network wide NN entry and put in string.
ScraperObjectStatsKey StatsKey;
StatsKey.objecttype = statsobjecttype::NetworkWide;
StatsKey.objectID = "";
const auto& iter = mScraperSBStats.find(StatsKey);
mProjectRef["Network"] = iProject;
mProjectStats[iProject] = std::make_pair((uint64_t) iter->second.statsvalue.dAvgRAC,
(uint64_t) iter->second.statsvalue.dRAC);
nNetworkMagnitude = (uint64_t) std::round(iter->second.statsvalue.dMag);
uint32_t iCPID = 0;
nZeroMagCPIDs = 0;
for (auto const& entry : mScraperSBStats)
{
if (entry.first.objecttype == statsobjecttype::byCPID)
{
// If the magnitude entry is zero suppress the CPID and increment the zero counter.
if (std::round(entry.second.statsvalue.dMag) > 0)
{
mCPIDRef[NN::Cpid::Parse(entry.first.objectID)] = iCPID;
mCPIDMagnitudes[iCPID] = (uint16_t) std::round(entry.second.statsvalue.dMag);
++iCPID;
}
else
{
nZeroMagCPIDs++;
}
}
}
for (auto const& entry : mScraperSBStats)
{
if (entry.first.objecttype == statsobjecttype::byCPIDbyProject)
{
std::vector<std::string> vObjectID = split(entry.first.objectID, ",");
const auto& iterProject = mProjectRef.find(vObjectID[0]);
const auto& iterCPID = mCPIDRef.find(NN::Cpid::Parse(vObjectID[1]));
mProjectCPIDStats[iterProject->second][iterCPID->second] = std::make_tuple((uint64_t) std::round(entry.second.statsvalue.dTC),
(uint64_t) std::round(entry.second.statsvalue.dRAC),
(uint16_t) std::round(entry.second.statsvalue.dMag));
}
}
fReducedMapsPopulated = true;
}
void Superblock::SerializeSuperblock(CDataStream& ss, int nType, int nVersion) const
{
ss << mProjectRef;
ss << mCPIDRef;
ss << mProjectStats;
ss << mCPIDMagnitudes;
//ss << mProjectCPIDStats;
ss << nNetworkMagnitude;
ss << nZeroMagCPIDs;
ss << nHeight;
ss << nTime;
ss << nSBVersion;
}
void Superblock::UnserializeSuperblock(CReaderStream& ss)
{
ss >> mProjectRef;
ss >> mCPIDRef;
ss >> mProjectStats;
ss >> mCPIDMagnitudes;
//ss >> mProjectCPIDStats;
ss >> nNetworkMagnitude;
ss >> nZeroMagCPIDs;
ss >> nHeight;
ss >> nTime;
ss >> nSBVersion;
}
void Superblock::SerializeSuperblock2(CDataStream& ss, int nType, int nVersion) const
{
ss << mProjectRef;
ss << mCPIDRef;
ss << mProjectStats;
ss << mCPIDMagnitudes;
ss << mProjectCPIDStats;
ss << nNetworkMagnitude;
ss << nZeroMagCPIDs;
ss << nHeight;
ss << nTime;
ss << nSBVersion;
}
void Superblock::UnserializeSuperblock2(CReaderStream& ss)
{
ss >> mProjectRef;
ss >> mCPIDRef;
ss >> mProjectStats;
ss >> mCPIDMagnitudes;
ss >> mProjectCPIDStats;
ss >> nNetworkMagnitude;
ss >> nZeroMagCPIDs;
ss >> nHeight;
ss >> nTime;
ss >> nSBVersion;
}
|
Change (Un)SerializeSuperblock() for comparison purposes
|
Change (Un)SerializeSuperblock() for comparison purposes
|
C++
|
mit
|
gridcoin/Gridcoin-Research,caraka/gridcoinresearch,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,caraka/gridcoinresearch,theMarix/Gridcoin-Research,caraka/gridcoinresearch,theMarix/Gridcoin-Research,gridcoin/Gridcoin-Research,gridcoin/Gridcoin-Research,theMarix/Gridcoin-Research,Git-Jiro/Gridcoin-Research,gridcoin/Gridcoin-Research,theMarix/Gridcoin-Research,Git-Jiro/Gridcoin-Research,caraka/gridcoinresearch,caraka/gridcoinresearch,theMarix/Gridcoin-Research,Git-Jiro/Gridcoin-Research,Git-Jiro/Gridcoin-Research,theMarix/Gridcoin-Research,gridcoin/Gridcoin-Research,Git-Jiro/Gridcoin-Research
|
6ccc091b394f8246af40b79809269d31928602eb
|
src/database/YAMLEngine.cpp
|
src/database/YAMLEngine.cpp
|
#include "IDatabaseEngine.h"
#include "DBEngineFactory.h"
#include "util/Datagram.h"
#include "util/DatagramIterator.h"
#include "core/logger.h"
#include "core/global.h"
#include <fstream>
#include <list>
ConfigVariable<std::string> foldername("foldername", "yaml_db");
LogCategory fsdb_log("YAML-DB", "YAML Database Engine");
class YAMLEngine : public IDatabaseEngine
{
private:
unsigned int m_next_id;
std::list<unsigned int> m_free_ids;
std::string m_foldername;
public:
YAMLEngine(DBEngineConfig dbeconfig, unsigned int start_id) :
IDatabaseEngine(dbeconfig, start_id),
m_next_id(start_id),
m_free_ids()
m_foldername(foldername.get_rval(m_dbeconfig))
{
}
unsigned int get_next_id()
{
}
bool create_object(const DatabaseObject &dbo)
{
if(!m_free_ids.empty())
{
return *m_free_ids.begin();
}
return m_next_id;
}
bool get_object(DatabaseObject &dbo)
{
}
void delete_object(unsigned int do_id)
{
}
};
DBEngineCreator<FSDBEngine> yamlengine_creator("yaml");
|
#include "IDatabaseEngine.h"
#include "DBEngineFactory.h"
#include "util/Datagram.h"
#include "util/DatagramIterator.h"
#include "core/logger.h"
#include "core/global.h"
#include <yaml-cpp/yaml.h>
#include <fstream>
#include <list>
ConfigVariable<std::string> foldername("foldername", "yaml_db");
LogCategory fsdb_log("YAML-DB", "YAML Database Engine");
class YAMLEngine : public IDatabaseEngine
{
private:
unsigned int m_next_id;
std::list<unsigned int> m_free_ids;
std::string m_foldername;
// update_next_id writes replaces the "next" field of info.yaml
// with the current m_next_id value;
void update_next_id()
{
}
// update_free_ids replaces the "free" list of ids in info.yaml
// with the current list of free ids.
void update_free_ids()
{
}
public:
YAMLEngine(DBEngineConfig dbeconfig, unsigned int start_id) :
IDatabaseEngine(dbeconfig, start_id),
m_next_id(start_id),
m_free_ids()
m_foldername(foldername.get_rval(m_dbeconfig))
{
// Open database info file
std::ifstream info(m_foldername + "/info.yaml");
YAML::Parser parser(info);
YAML::Node document;
// Read existing database info if file exists
if(parser.GetNextDocument(document))
{
// Read next available id
if(auto next = document.FindValue("next"))
{
next >> m_next_id;
}
// Read available freed ids
if(auto freed = document.FindValue("free"))
{
for(unsigned int i = 0; i < freed.size(); i++)
{
unsigned int id;
freed[i] >> id;
m_free_ids.push_back(id);
}
}
}
// Close database info file
info.close();
};
unsigned int get_next_id()
{
// Get first free id from queue
if(!m_free_ids.empty())
{
return *m_free_ids.begin();
}
return m_next_id;
}
bool create_object(const DatabaseObject &dbo)
{
if(dbo.do_id != get_next_id())
{
return false;
}
if(!m_free_ids.empty())
{
m_free_ids.remove(dbo.do_id);
update_free_ids();
}
++m_next_id;
update_next_id();
}
bool get_object(DatabaseObject &dbo)
{
}
void delete_object(unsigned int do_id)
{
}
};
DBEngineCreator<FSDBEngine> yamlengine_creator("yaml");
|
Handle id management.
|
YAMLEngine: Handle id management.
|
C++
|
bsd-3-clause
|
pizcogirl/Astron,ketoo/Astron,pizcogirl/Astron,ketoo/Astron,blindsighttf2/Astron,blindsighttf2/Astron,ketoo/Astron,ketoo/Astron,pizcogirl/Astron,blindsighttf2/Astron,pizcogirl/Astron,blindsighttf2/Astron
|
6085e4f3359b335a0088bda0624a96575f00bb54
|
src/examples/duplicates.cpp
|
src/examples/duplicates.cpp
|
/*
Duplicates Example
Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QApplication>
#include <QTreeView>
#include <QDebug>
#include <QTextStream>
#include <persons-model.h>
#include <duplicatesfinder.h>
#include <qtest_kde.h>
PersonsModel model;
class ResultPrinter : public QObject
{
Q_OBJECT
public slots:
void print(KJob* j) {
QList<Match> res = ((DuplicatesFinder* ) j)->results();
qDebug() << "Results:";
foreach(const Match& c, res) {
QStringList roles;
foreach(int i, c.role)
roles += model.roleNames()[i];
QModelIndex idxA = model.index(c.rowA, 0), idxB = model.index(c.rowB, 0);
qDebug() << "\t-" << roles.join(", ") << ":" << c.rowA << c.rowB << "because: "
<< idxA.data(c.role.first()).toString() << idxB.data(c.role.first()).toString();
}
QCoreApplication::instance()->quit();
}
};
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
ResultPrinter r;
DuplicatesFinder* f = new DuplicatesFinder(&model);
QObject::connect(f, SIGNAL(finished(KJob*)), &r, SLOT(print(KJob*)));
f->start();
app.exec();
}
#include "duplicates.moc"
|
/*
Duplicates Example
Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QApplication>
#include <QTreeView>
#include <QDebug>
#include <QTextStream>
#include <persons-model.h>
#include <duplicatesfinder.h>
#include <qtest_kde.h>
PersonsModel model;
class ResultPrinter : public QObject
{
Q_OBJECT
public slots:
void print(KJob* j) {
QList<Match> res = ((DuplicatesFinder* ) j)->results();
qDebug() << "Results:";
foreach(const Match& c, res) {
QStringList roles;
QStringList r;
foreach(int i, c.role) {
roles += model.roleNames()[i];
QModelIndex idx = model.index(c.rowA, 0);
r += idx.data(c.role.first()).toString();
}
qDebug() << "\t-" << roles.join(", ") << ":" << c.rowA << c.rowB << "because: " << r.join(", ");
}
QCoreApplication::instance()->quit();
}
};
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
ResultPrinter r;
DuplicatesFinder* f = new DuplicatesFinder(&model);
QObject::connect(f, SIGNAL(finished(KJob*)), &r, SLOT(print(KJob*)));
f->start();
app.exec();
}
#include "duplicates.moc"
|
put all data that has matched
|
put all data that has matched
|
C++
|
lgpl-2.1
|
detrout/libkpeople-debian,detrout/libkpeople-debian,detrout/libkpeople-debian
|
2dde9473d5c976f09e168e21040ebeae3a5ee5ef
|
deps/ox/src/ox/std/error.hpp
|
deps/ox/src/ox/std/error.hpp
|
/*
* Copyright 2015 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "defines.hpp"
#include "strongint.hpp"
#include "typetraits.hpp"
#include "utility.hpp"
#define OxError(...) ox::Error(__FILE__, __LINE__, __VA_ARGS__)
namespace ox {
struct [[nodiscard]] Error {
const char *msg = nullptr;
const char *file = nullptr;
uint16_t line = 0;
uint64_t errCode = 0;
explicit constexpr Error(uint64_t ec = 0) noexcept: errCode(ec) {
}
explicit constexpr Error(const char *file, uint32_t line, uint64_t errCode, const char *msg = nullptr) noexcept {
this->file = file;
this->line = line;
this->msg = msg;
this->errCode = errCode;
}
constexpr Error(const Error &o) noexcept {
this->msg = o.msg;
this->file = o.file;
this->line = o.line;
this->errCode = o.errCode;
}
constexpr Error &operator=(const Error &o) noexcept {
this->msg = o.msg;
this->file = o.file;
this->line = o.line;
this->errCode = o.errCode;
return *this;
}
constexpr operator uint64_t() const noexcept {
return errCode;
}
};
template<typename T>
struct [[nodiscard]] Result {
using type = T;
T value;
Error error;
constexpr Result() noexcept: error(0) {
}
constexpr Result(Error error) noexcept: value(ox::move(value)), error(error) {
this->error = error;
}
constexpr Result(T value, Error error = OxError(0)) noexcept: value(ox::move(value)), error(error) {
}
explicit constexpr operator const T&() const noexcept {
return value;
}
explicit constexpr operator T&() noexcept {
return value;
}
[[nodiscard]] constexpr bool ok() const noexcept {
return error == 0;
}
constexpr Error get(T *val) noexcept {
*val = value;
return error;
}
constexpr Error moveTo(T *val) noexcept {
*val = ox::move(value);
return error;
}
};
namespace detail {
constexpr Error toError(Error e) noexcept {
return e;
}
template<typename T>
constexpr Error toError(const Result<T> &ve) noexcept {
return ve.error;
}
}
}
inline void oxIgnoreError(ox::Error) noexcept {}
#if __cplusplus >= 202002L
#define oxReturnError(x) if (const auto _ox_error = ox::detail::toError(x)) [[unlikely]] return _ox_error
#define oxThrowError(x) if (const auto _ox_error = ox::detail::toError(x)) [[unlikely]] throw _ox_error
#else
#define oxReturnError(x) if (const auto _ox_error = ox::detail::toError(x)) return _ox_error
#define oxThrowError(x) if (const auto _ox_error = ox::detail::toError(x)) throw _ox_error
#endif
#define oxConcatImpl(a, b) a##b
#define oxConcat(a, b) oxConcatImpl(a, b)
#define oxRequire(out, x) auto [out, oxConcat(oxRequire_err_, __LINE__)] = x; oxReturnError(oxConcat(oxRequire_err_, __LINE__))
#define oxRequireT(out, x) auto [out, oxConcat(oxRequire_err_, __LINE__)] = x; oxThrowError(oxConcat(oxRequire_err_, __LINE__))
|
/*
* Copyright 2015 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "defines.hpp"
#include "strongint.hpp"
#include "typetraits.hpp"
#include "utility.hpp"
#define OxError(...) ox::Error(__FILE__, __LINE__, __VA_ARGS__)
namespace ox {
using ErrorCode = uint16_t;
struct [[nodiscard]] Error {
ErrorCode errCode = 0;
const char *msg = nullptr;
const char *file = nullptr;
uint16_t line = 0;
explicit constexpr Error(ErrorCode ec = 0) noexcept: errCode(ec) {
}
explicit constexpr Error(const char *file, uint32_t line, ErrorCode errCode, const char *msg = nullptr) noexcept {
this->file = file;
this->line = line;
this->msg = msg;
this->errCode = errCode;
}
constexpr Error(const Error &o) noexcept {
this->msg = o.msg;
this->file = o.file;
this->line = o.line;
this->errCode = o.errCode;
}
constexpr Error &operator=(const Error &o) noexcept {
this->msg = o.msg;
this->file = o.file;
this->line = o.line;
this->errCode = o.errCode;
return *this;
}
constexpr operator uint64_t() const noexcept {
return errCode;
}
};
template<typename T>
struct [[nodiscard]] Result {
using type = T;
T value;
Error error;
constexpr Result() noexcept: error(0) {
}
constexpr Result(Error error) noexcept: error(error) {
}
constexpr Result(T value, Error error = OxError(0)) noexcept: value(ox::move(value)), error(error) {
}
explicit constexpr operator const T&() const noexcept {
return value;
}
explicit constexpr operator T&() noexcept {
return value;
}
[[nodiscard]] constexpr bool ok() const noexcept {
return error == 0;
}
constexpr Error get(T *val) noexcept {
*val = value;
return error;
}
constexpr Error moveTo(T *val) noexcept {
*val = ox::move(value);
return error;
}
};
namespace detail {
constexpr Error toError(const Error &e) noexcept {
return e;
}
template<typename T>
constexpr Error toError(const Result<T> &ve) noexcept {
return ve.error;
}
}
}
inline void oxIgnoreError(ox::Error) noexcept {}
#if __cplusplus >= 202002L
#define oxReturnError(x) if (const auto _ox_error = ox::detail::toError(x)) [[unlikely]] return _ox_error
#define oxThrowError(x) if (const auto _ox_error = ox::detail::toError(x)) [[unlikely]] throw _ox_error
#else
#define oxReturnError(x) if (const auto _ox_error = ox::detail::toError(x)) return _ox_error
#define oxThrowError(x) if (const auto _ox_error = ox::detail::toError(x)) throw _ox_error
#endif
#define oxConcatImpl(a, b) a##b
#define oxConcat(a, b) oxConcatImpl(a, b)
#define oxRequire(out, x) auto [out, oxConcat(oxRequire_err_, __LINE__)] = x; oxReturnError(oxConcat(oxRequire_err_, __LINE__))
#define oxRequireT(out, x) auto [out, oxConcat(oxRequire_err_, __LINE__)] = x; oxThrowError(oxConcat(oxRequire_err_, __LINE__))
|
Remove redundant copies from Result constructors
|
[ox/std] Remove redundant copies from Result constructors
|
C++
|
mpl-2.0
|
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
|
26098742a2c8e8e29ecea02ddc3d5243bcfbdb16
|
src/block.cpp
|
src/block.cpp
|
#include "block.h"
#include "main.h"
#include <cstdlib>
BlockFinder::BlockFinder()
: cache(nullptr)
{}
CBlockIndex* BlockFinder::FindByHeight(int height)
{
// If the height is at the bottom half of the chain, start searching from
// the start to the end, otherwise search backwards from the end.
CBlockIndex *index = height < nBestHeight / 2
? pindexGenesisBlock
: pindexBest;
if(index != nullptr)
{
// Use the cache if it's closer to the target than the current
// start block.
if (cache && abs(height - index->nHeight) > std::abs(height - cache->nHeight))
index = cache;
// Traverse towards the tail.
while (index && index->pprev && index->nHeight > height)
index = index->pprev;
// Traverse towards the head.
while (index && index->pnext && index->nHeight < height)
index = index->pnext;
}
cache = index;
return index;
}
CBlockIndex* BlockFinder::FindByMinTime(int64_t time)
{
CBlockIndex *index = abs(time - pindexBest->nTime) < abs(time - pindexGenesisBlock->nTime)
? pindexBest
: pindexGenesisBlock;
if(index != nullptr)
{
if(cache && abs(time - index->nTime) > abs(time - int64_t(cache->nTime)))
index = cache;
// Move back until the previous block is no longer younger than "time".
while(index && index->pprev && index->pprev->nTime > time)
index = index->pprev;
// Move forward until the current block is younger than "time".
while(index && index->pnext && index->nTime < time)
index = index->pnext;
}
cache = index;
return index;
}
void BlockFinder::Reset()
{
cache = nullptr;
}
|
#include "block.h"
#include "main.h"
#include <cstdlib>
BlockFinder::BlockFinder()
: cache(nullptr)
{}
CBlockIndex* BlockFinder::FindByHeight(int height)
{
// If the height is at the bottom half of the chain, start searching from
// the start to the end, otherwise search backwards from the end.
CBlockIndex *index = height < nBestHeight / 2
? pindexGenesisBlock
: pindexBest;
if(index != nullptr)
{
// Use the cache if it's closer to the target than the current
// start block.
if (cache && abs(height - index->nHeight) > std::abs(height - cache->nHeight))
index = cache;
// Traverse towards the tail.
while (index && index->pprev && index->nHeight > height)
index = index->pprev;
// Traverse towards the head.
while (index && index->pnext && index->nHeight < height)
index = index->pnext;
}
cache = index;
return index;
}
CBlockIndex* BlockFinder::FindByMinTime(int64_t time)
{
// Select starting point depending on time proximity. While this is not as
// accurate as in the FindByHeight case it will still give us a reasonable
// estimate.
CBlockIndex *index = abs(time - pindexBest->nTime) < abs(time - pindexGenesisBlock->nTime)
? pindexBest
: pindexGenesisBlock;
if(index != nullptr)
{
// If we have a cache that's closer to target than our current index,
// use it.
if(cache && abs(time - index->nTime) > abs(time - int64_t(cache->nTime)))
index = cache;
// Move back until the previous block is no longer younger than "time".
while(index && index->pprev && index->pprev->nTime > time)
index = index->pprev;
// Move forward until the current block is younger than "time".
while(index && index->pnext && index->nTime < time)
index = index->pnext;
}
cache = index;
return index;
}
void BlockFinder::Reset()
{
cache = nullptr;
}
|
Add additional comments.
|
Add additional comments.
|
C++
|
mit
|
caraka/gridcoinresearch,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,gridcoin/Gridcoin-Research,theMarix/Gridcoin-Research,theMarix/Gridcoin-Research,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,theMarix/Gridcoin-Research,theMarix/Gridcoin-Research,Git-Jiro/Gridcoin-Research,Git-Jiro/Gridcoin-Research,theMarix/Gridcoin-Research,gridcoin/Gridcoin-Research,Git-Jiro/Gridcoin-Research,Git-Jiro/Gridcoin-Research,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,caraka/gridcoinresearch,Git-Jiro/Gridcoin-Research,caraka/gridcoinresearch,theMarix/Gridcoin-Research,gridcoin/Gridcoin-Research
|
c9478191541e49351638db8a3efd262f19c700f4
|
src/buffer.cc
|
src/buffer.cc
|
#include "buffer.hh"
#include "buffer_manager.hh"
#include "window.hh"
#include "assert.hh"
#include "utils.hh"
#include "context.hh"
#include "utf8.hh"
#include <algorithm>
namespace Kakoune
{
Buffer::Buffer(String name, Type type,
String initial_content)
: m_name(std::move(name)), m_type(type),
m_history(1), m_history_cursor(m_history.begin()),
m_last_save_undo_index(0),
m_timestamp(0),
m_hook_manager(GlobalHookManager::instance()),
m_option_manager(GlobalOptionManager::instance())
{
BufferManager::instance().register_buffer(*this);
if (initial_content.back() != '\n')
initial_content += '\n';
do_insert(begin(), std::move(initial_content));
Editor editor_for_hooks(*this);
Context context(editor_for_hooks);
if (type == Type::NewFile)
m_hook_manager.run_hook("BufNew", m_name, context);
else if (type == Type::File)
m_hook_manager.run_hook("BufOpen", m_name, context);
m_hook_manager.run_hook("BufCreate", m_name, context);
reset_undo_data();
}
Buffer::~Buffer()
{
m_hook_manager.run_hook("BufClose", m_name, Context(Editor(*this)));
m_windows.clear();
BufferManager::instance().unregister_buffer(*this);
assert(m_change_listeners.empty());
}
BufferIterator Buffer::iterator_at(const BufferCoord& line_and_column,
bool avoid_eol) const
{
return BufferIterator(*this, clamp(line_and_column, avoid_eol));
}
BufferCoord Buffer::line_and_column_at(const BufferIterator& iterator) const
{
return iterator.m_coord;
}
ByteCount Buffer::line_length(LineCount line) const
{
assert(line < line_count());
ByteCount end = (line < line_count() - 1) ?
m_lines[line + 1].start : character_count();
return end - m_lines[line].start;
}
BufferCoord Buffer::clamp(const BufferCoord& line_and_column,
bool avoid_eol) const
{
if (m_lines.empty())
return BufferCoord();
BufferCoord result(line_and_column.line, line_and_column.column);
result.line = Kakoune::clamp(result.line, 0_line, line_count() - 1);
ByteCount max_col = std::max(0_byte, line_length(result.line) - (avoid_eol ? 2 : 1));
result.column = Kakoune::clamp(result.column, 0_byte, max_col);
return result;
}
BufferIterator Buffer::iterator_at_line_begin(const BufferIterator& iterator) const
{
return BufferIterator(*this, { iterator.line(), 0 });
}
BufferIterator Buffer::iterator_at_line_begin(LineCount line) const
{
return BufferIterator(*this, clamp({ line, 0 }));
}
BufferIterator Buffer::iterator_at_line_end(const BufferIterator& iterator) const
{
LineCount line = iterator.line();
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::iterator_at_line_end(LineCount line) const
{
line = std::min(line, line_count()-1);
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::begin() const
{
return BufferIterator(*this, { 0_line, 0 });
}
BufferIterator Buffer::end() const
{
if (m_lines.empty())
return BufferIterator(*this, { 0_line, 0 });
return BufferIterator(*this, { line_count()-1, m_lines.back().length() });
}
ByteCount Buffer::character_count() const
{
if (m_lines.empty())
return 0;
return m_lines.back().start + m_lines.back().length();
}
LineCount Buffer::line_count() const
{
return LineCount(m_lines.size());
}
String Buffer::string(const BufferIterator& begin, const BufferIterator& end) const
{
String res;
for (LineCount line = begin.line(); line <= end.line(); ++line)
{
ByteCount start = 0;
if (line == begin.line())
start = begin.column();
ByteCount count = -1;
if (line == end.line())
count = end.column() - start;
res += m_lines[line].content.substr(start, count);
}
return res;
}
void Buffer::begin_undo_group()
{
assert(m_current_undo_group.empty());
m_history.erase(m_history_cursor, m_history.end());
if (m_history.size() < m_last_save_undo_index)
m_last_save_undo_index = -1;
m_history_cursor = m_history.end();
}
void Buffer::end_undo_group()
{
if (m_current_undo_group.empty())
return;
m_history.push_back(std::move(m_current_undo_group));
m_history_cursor = m_history.end();
m_current_undo_group.clear();
}
// A Modification holds a single atomic modification to Buffer
struct Buffer::Modification
{
enum Type { Insert, Erase };
Type type;
BufferIterator position;
String content;
Modification(Type type, BufferIterator position, String content)
: type(type), position(position), content(std::move(content)) {}
Modification inverse() const
{
Type inverse_type;
switch (type)
{
case Insert: inverse_type = Erase; break;
case Erase: inverse_type = Insert; break;
default: assert(false);
}
return Modification(inverse_type, position, content);
}
};
bool Buffer::undo()
{
if (m_history_cursor == m_history.begin())
return false;
--m_history_cursor;
for (const Modification& modification : reversed(*m_history_cursor))
apply_modification(modification.inverse());
return true;
}
bool Buffer::redo()
{
if (m_history_cursor == m_history.end())
return false;
for (const Modification& modification : *m_history_cursor)
apply_modification(modification);
++m_history_cursor;
return true;
}
void Buffer::reset_undo_data()
{
m_history.clear();
m_history_cursor = m_history.end();
m_current_undo_group.clear();
}
void Buffer::check_invariant() const
{
ByteCount start = 0;
assert(not m_lines.empty());
for (auto& line : m_lines)
{
assert(line.start == start);
assert(line.length() > 0);
assert(line.content.back() == '\n');
start += line.length();
}
}
void Buffer::do_insert(const BufferIterator& pos, const String& content)
{
assert(pos.is_end() or utf8::is_character_start(pos));
++m_timestamp;
ByteCount offset = pos.offset();
// all following lines advanced by length
for (LineCount i = pos.line()+1; i < line_count(); ++i)
m_lines[i].start += content.length();
BufferIterator begin_it;
BufferIterator end_it;
// if we inserted at the end of the buffer, we may have created a new
// line without inserting a '\n'
if (pos == end() and (pos == begin() or *(pos-1) == '\n'))
{
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
m_lines.push_back({ offset + start, content.substr(start, i + 1 - start) });
start = i + 1;
}
}
if (start != content.length())
m_lines.push_back({ offset + start, content.substr(start) });
begin_it = pos;
end_it = end();
}
else
{
String prefix = m_lines[pos.line()].content.substr(0, pos.column());
String suffix = m_lines[pos.line()].content.substr(pos.column());
auto line_it = m_lines.begin() + (int)pos.line();
line_it = m_lines.erase(line_it);
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
String line_content = content.substr(start, i + 1 - start);
if (start == 0)
{
line_content = prefix + line_content;
line_it = m_lines.insert(line_it, { offset + start - prefix.length(),
std::move(line_content) });
}
else
line_it = m_lines.insert(line_it, { offset + start,
std::move(line_content) });
++line_it;
start = i + 1;
}
}
if (start == 0)
line_it = m_lines.insert(line_it, { offset + start - prefix.length(), prefix + content + suffix });
else if (start != content.length() or not suffix.empty())
line_it = m_lines.insert(line_it, { offset + start, content.substr(start) + suffix });
else
--line_it;
begin_it = pos;
end_it = BufferIterator(*this, { LineCount(line_it - m_lines.begin()),
line_it->length() - suffix.length() });
}
check_invariant();
for (auto listener : m_change_listeners)
listener->on_insert(begin_it, end_it);
}
void Buffer::do_erase(const BufferIterator& begin, const BufferIterator& end)
{
assert(utf8::is_character_start(begin) and
(end.is_end() or utf8::is_character_start(end)));
++m_timestamp;
const ByteCount length = end - begin;
String prefix = m_lines[begin.line()].content.substr(0, begin.column());
String suffix = m_lines[end.line()].content.substr(end.column());
Line new_line = { m_lines[begin.line()].start, prefix + suffix };
m_lines.erase(m_lines.begin() + (int)begin.line(), m_lines.begin() + (int)end.line() + 1);
if (new_line.length() != 0)
m_lines.insert(m_lines.begin() + (int)begin.line(), std::move(new_line));
for (LineCount i = begin.line()+1; i < line_count(); ++i)
m_lines[i].start -= length;
check_invariant();
for (auto listener : m_change_listeners)
listener->on_erase(begin, end);
}
void Buffer::apply_modification(const Modification& modification)
{
const String& content = modification.content;
const BufferIterator& pos = modification.position;
switch (modification.type)
{
case Modification::Insert:
{
do_insert(pos < end() ? pos : end(), content);
break;
}
case Modification::Erase:
{
ByteCount count = content.length();
BufferIterator end = pos + count;
assert(string(pos, end) == content);
do_erase(pos, end);
break;
}
default:
assert(false);
}
}
void Buffer::insert(BufferIterator pos, String content)
{
if (content.empty())
return;
if (pos.is_end() and content.back() != '\n')
content += '\n';
m_current_undo_group.emplace_back(Modification::Insert, pos,
std::move(content));
do_insert(pos, m_current_undo_group.back().content);
}
void Buffer::erase(BufferIterator begin, BufferIterator end)
{
if (end.is_end() and (begin.column() != 0 or begin.is_begin()))
--end;
if (begin == end)
return;
m_current_undo_group.emplace_back(Modification::Erase, begin,
string(begin, end));
do_erase(begin, end);
}
Window* Buffer::get_or_create_window()
{
if (m_windows.empty())
m_windows.push_front(std::unique_ptr<Window>(new Window(*this)));
return m_windows.front().get();
}
void Buffer::delete_window(Window* window)
{
assert(&window->buffer() == this);
auto window_it = std::find(m_windows.begin(), m_windows.end(), window);
assert(window_it != m_windows.end());
m_windows.erase(window_it);
}
bool Buffer::is_modified() const
{
size_t history_cursor_index = m_history_cursor - m_history.begin();
return m_last_save_undo_index != history_cursor_index
or not m_current_undo_group.empty();
}
void Buffer::notify_saved()
{
size_t history_cursor_index = m_history_cursor - m_history.begin();
m_last_save_undo_index = history_cursor_index;
}
void Buffer::add_change_listener(BufferChangeListener& listener)
{
assert(not contains(m_change_listeners, &listener));
m_change_listeners.push_back(&listener);
}
void Buffer::remove_change_listener(BufferChangeListener& listener)
{
auto it = std::find(m_change_listeners.begin(),
m_change_listeners.end(),
&listener);
assert(it != m_change_listeners.end());
m_change_listeners.erase(it);
}
}
|
#include "buffer.hh"
#include "buffer_manager.hh"
#include "window.hh"
#include "assert.hh"
#include "utils.hh"
#include "context.hh"
#include "utf8.hh"
#include <algorithm>
namespace Kakoune
{
Buffer::Buffer(String name, Type type,
String initial_content)
: m_name(std::move(name)), m_type(type),
m_history(1), m_history_cursor(m_history.begin()),
m_last_save_undo_index(0),
m_timestamp(0),
m_hook_manager(GlobalHookManager::instance()),
m_option_manager(GlobalOptionManager::instance())
{
BufferManager::instance().register_buffer(*this);
if (initial_content.back() != '\n')
initial_content += '\n';
do_insert(begin(), std::move(initial_content));
Editor editor_for_hooks(*this);
Context context(editor_for_hooks);
if (type == Type::NewFile)
m_hook_manager.run_hook("BufNew", m_name, context);
else if (type == Type::File)
m_hook_manager.run_hook("BufOpen", m_name, context);
m_hook_manager.run_hook("BufCreate", m_name, context);
reset_undo_data();
}
Buffer::~Buffer()
{
m_hook_manager.run_hook("BufClose", m_name, Context(Editor(*this)));
m_windows.clear();
BufferManager::instance().unregister_buffer(*this);
assert(m_change_listeners.empty());
}
BufferIterator Buffer::iterator_at(const BufferCoord& line_and_column,
bool avoid_eol) const
{
return BufferIterator(*this, clamp(line_and_column, avoid_eol));
}
BufferCoord Buffer::line_and_column_at(const BufferIterator& iterator) const
{
return iterator.m_coord;
}
ByteCount Buffer::line_length(LineCount line) const
{
assert(line < line_count());
ByteCount end = (line < line_count() - 1) ?
m_lines[line + 1].start : character_count();
return end - m_lines[line].start;
}
BufferCoord Buffer::clamp(const BufferCoord& line_and_column,
bool avoid_eol) const
{
if (m_lines.empty())
return BufferCoord();
BufferCoord result(line_and_column.line, line_and_column.column);
result.line = Kakoune::clamp(result.line, 0_line, line_count() - 1);
ByteCount max_col = std::max(0_byte, line_length(result.line) - (avoid_eol ? 2 : 1));
result.column = Kakoune::clamp(result.column, 0_byte, max_col);
return result;
}
BufferIterator Buffer::iterator_at_line_begin(const BufferIterator& iterator) const
{
return BufferIterator(*this, { iterator.line(), 0 });
}
BufferIterator Buffer::iterator_at_line_begin(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return BufferIterator(*this, { line, 0 });
}
BufferIterator Buffer::iterator_at_line_end(const BufferIterator& iterator) const
{
LineCount line = iterator.line();
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::iterator_at_line_end(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::begin() const
{
return BufferIterator(*this, { 0_line, 0 });
}
BufferIterator Buffer::end() const
{
if (m_lines.empty())
return BufferIterator(*this, { 0_line, 0 });
return BufferIterator(*this, { line_count()-1, m_lines.back().length() });
}
ByteCount Buffer::character_count() const
{
if (m_lines.empty())
return 0;
return m_lines.back().start + m_lines.back().length();
}
LineCount Buffer::line_count() const
{
return LineCount(m_lines.size());
}
String Buffer::string(const BufferIterator& begin, const BufferIterator& end) const
{
String res;
for (LineCount line = begin.line(); line <= end.line(); ++line)
{
ByteCount start = 0;
if (line == begin.line())
start = begin.column();
ByteCount count = -1;
if (line == end.line())
count = end.column() - start;
res += m_lines[line].content.substr(start, count);
}
return res;
}
void Buffer::begin_undo_group()
{
assert(m_current_undo_group.empty());
m_history.erase(m_history_cursor, m_history.end());
if (m_history.size() < m_last_save_undo_index)
m_last_save_undo_index = -1;
m_history_cursor = m_history.end();
}
void Buffer::end_undo_group()
{
if (m_current_undo_group.empty())
return;
m_history.push_back(std::move(m_current_undo_group));
m_history_cursor = m_history.end();
m_current_undo_group.clear();
}
// A Modification holds a single atomic modification to Buffer
struct Buffer::Modification
{
enum Type { Insert, Erase };
Type type;
BufferIterator position;
String content;
Modification(Type type, BufferIterator position, String content)
: type(type), position(position), content(std::move(content)) {}
Modification inverse() const
{
Type inverse_type;
switch (type)
{
case Insert: inverse_type = Erase; break;
case Erase: inverse_type = Insert; break;
default: assert(false);
}
return Modification(inverse_type, position, content);
}
};
bool Buffer::undo()
{
if (m_history_cursor == m_history.begin())
return false;
--m_history_cursor;
for (const Modification& modification : reversed(*m_history_cursor))
apply_modification(modification.inverse());
return true;
}
bool Buffer::redo()
{
if (m_history_cursor == m_history.end())
return false;
for (const Modification& modification : *m_history_cursor)
apply_modification(modification);
++m_history_cursor;
return true;
}
void Buffer::reset_undo_data()
{
m_history.clear();
m_history_cursor = m_history.end();
m_current_undo_group.clear();
}
void Buffer::check_invariant() const
{
ByteCount start = 0;
assert(not m_lines.empty());
for (auto& line : m_lines)
{
assert(line.start == start);
assert(line.length() > 0);
assert(line.content.back() == '\n');
start += line.length();
}
}
void Buffer::do_insert(const BufferIterator& pos, const String& content)
{
assert(pos.is_end() or utf8::is_character_start(pos));
++m_timestamp;
ByteCount offset = pos.offset();
// all following lines advanced by length
for (LineCount i = pos.line()+1; i < line_count(); ++i)
m_lines[i].start += content.length();
BufferIterator begin_it;
BufferIterator end_it;
// if we inserted at the end of the buffer, we may have created a new
// line without inserting a '\n'
if (pos == end() and (pos == begin() or *(pos-1) == '\n'))
{
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
m_lines.push_back({ offset + start, content.substr(start, i + 1 - start) });
start = i + 1;
}
}
if (start != content.length())
m_lines.push_back({ offset + start, content.substr(start) });
begin_it = pos;
end_it = end();
}
else
{
String prefix = m_lines[pos.line()].content.substr(0, pos.column());
String suffix = m_lines[pos.line()].content.substr(pos.column());
auto line_it = m_lines.begin() + (int)pos.line();
line_it = m_lines.erase(line_it);
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
String line_content = content.substr(start, i + 1 - start);
if (start == 0)
{
line_content = prefix + line_content;
line_it = m_lines.insert(line_it, { offset + start - prefix.length(),
std::move(line_content) });
}
else
line_it = m_lines.insert(line_it, { offset + start,
std::move(line_content) });
++line_it;
start = i + 1;
}
}
if (start == 0)
line_it = m_lines.insert(line_it, { offset + start - prefix.length(), prefix + content + suffix });
else if (start != content.length() or not suffix.empty())
line_it = m_lines.insert(line_it, { offset + start, content.substr(start) + suffix });
else
--line_it;
begin_it = pos;
end_it = BufferIterator(*this, { LineCount(line_it - m_lines.begin()),
line_it->length() - suffix.length() });
}
check_invariant();
for (auto listener : m_change_listeners)
listener->on_insert(begin_it, end_it);
}
void Buffer::do_erase(const BufferIterator& begin, const BufferIterator& end)
{
assert(utf8::is_character_start(begin) and
(end.is_end() or utf8::is_character_start(end)));
++m_timestamp;
const ByteCount length = end - begin;
String prefix = m_lines[begin.line()].content.substr(0, begin.column());
String suffix = m_lines[end.line()].content.substr(end.column());
Line new_line = { m_lines[begin.line()].start, prefix + suffix };
m_lines.erase(m_lines.begin() + (int)begin.line(), m_lines.begin() + (int)end.line() + 1);
if (new_line.length() != 0)
m_lines.insert(m_lines.begin() + (int)begin.line(), std::move(new_line));
for (LineCount i = begin.line()+1; i < line_count(); ++i)
m_lines[i].start -= length;
check_invariant();
for (auto listener : m_change_listeners)
listener->on_erase(begin, end);
}
void Buffer::apply_modification(const Modification& modification)
{
const String& content = modification.content;
const BufferIterator& pos = modification.position;
switch (modification.type)
{
case Modification::Insert:
{
do_insert(pos < end() ? pos : end(), content);
break;
}
case Modification::Erase:
{
ByteCount count = content.length();
BufferIterator end = pos + count;
assert(string(pos, end) == content);
do_erase(pos, end);
break;
}
default:
assert(false);
}
}
void Buffer::insert(BufferIterator pos, String content)
{
if (content.empty())
return;
if (pos.is_end() and content.back() != '\n')
content += '\n';
m_current_undo_group.emplace_back(Modification::Insert, pos,
std::move(content));
do_insert(pos, m_current_undo_group.back().content);
}
void Buffer::erase(BufferIterator begin, BufferIterator end)
{
if (end.is_end() and (begin.column() != 0 or begin.is_begin()))
--end;
if (begin == end)
return;
m_current_undo_group.emplace_back(Modification::Erase, begin,
string(begin, end));
do_erase(begin, end);
}
Window* Buffer::get_or_create_window()
{
if (m_windows.empty())
m_windows.push_front(std::unique_ptr<Window>(new Window(*this)));
return m_windows.front().get();
}
void Buffer::delete_window(Window* window)
{
assert(&window->buffer() == this);
auto window_it = std::find(m_windows.begin(), m_windows.end(), window);
assert(window_it != m_windows.end());
m_windows.erase(window_it);
}
bool Buffer::is_modified() const
{
size_t history_cursor_index = m_history_cursor - m_history.begin();
return m_last_save_undo_index != history_cursor_index
or not m_current_undo_group.empty();
}
void Buffer::notify_saved()
{
size_t history_cursor_index = m_history_cursor - m_history.begin();
m_last_save_undo_index = history_cursor_index;
}
void Buffer::add_change_listener(BufferChangeListener& listener)
{
assert(not contains(m_change_listeners, &listener));
m_change_listeners.push_back(&listener);
}
void Buffer::remove_change_listener(BufferChangeListener& listener)
{
auto it = std::find(m_change_listeners.begin(),
m_change_listeners.end(),
&listener);
assert(it != m_change_listeners.end());
m_change_listeners.erase(it);
}
}
|
Fix buffer iterator_at_line_{begin,end}(LineCount)
|
Fix buffer iterator_at_line_{begin,end}(LineCount)
|
C++
|
unlicense
|
casimir/kakoune,alpha123/kakoune,flavius/kakoune,jjthrash/kakoune,rstacruz/kakoune,Asenar/kakoune,danielma/kakoune,zakgreant/kakoune,mawww/kakoune,Asenar/kakoune,flavius/kakoune,jjthrash/kakoune,jkonecny12/kakoune,zakgreant/kakoune,rstacruz/kakoune,danr/kakoune,ekie/kakoune,alpha123/kakoune,flavius/kakoune,lenormf/kakoune,flavius/kakoune,alexherbo2/kakoune,elegios/kakoune,xificurC/kakoune,xificurC/kakoune,Somasis/kakoune,casimir/kakoune,jkonecny12/kakoune,jkonecny12/kakoune,casimir/kakoune,elegios/kakoune,occivink/kakoune,occivink/kakoune,zakgreant/kakoune,occivink/kakoune,danr/kakoune,elegios/kakoune,jjthrash/kakoune,zakgreant/kakoune,Somasis/kakoune,danr/kakoune,Asenar/kakoune,alpha123/kakoune,danielma/kakoune,lenormf/kakoune,lenormf/kakoune,mawww/kakoune,danr/kakoune,danielma/kakoune,jkonecny12/kakoune,occivink/kakoune,jjthrash/kakoune,mawww/kakoune,Asenar/kakoune,xificurC/kakoune,ekie/kakoune,lenormf/kakoune,xificurC/kakoune,rstacruz/kakoune,danielma/kakoune,mawww/kakoune,alexherbo2/kakoune,alpha123/kakoune,ekie/kakoune,ekie/kakoune,elegios/kakoune,Somasis/kakoune,alexherbo2/kakoune,Somasis/kakoune,alexherbo2/kakoune,casimir/kakoune,rstacruz/kakoune
|
71b8216dd074413421960b24098057b524330bf3
|
test/unit/XMLSchemaTest.cpp
|
test/unit/XMLSchemaTest.cpp
|
/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([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 name of Hobu, Inc. or Flaxen Geo Consulting 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 <boost/test/unit_test.hpp>
#include <boost/cstdint.hpp>
#include <boost/property_tree/ptree.hpp>
#include <libpc/XMLSchema.hpp>
#include <libpc/drivers/faux/Reader.hpp>
#include <libpc/drivers/faux/Writer.hpp>
#include <libpc/drivers/las/Reader.hpp>
#include <libpc/Iterator.hpp>
#include <libpc/Utils.hpp>
#include "Support.hpp"
#include "TestConfig.hpp"
#include <fstream>
using namespace libpc;
std::string ReadXML(std::string filename)
{
std::istream* infile = Utils::openFile(filename);
std::ifstream::pos_type size;
// char* data;
std::vector<char> data;
if (infile->good()){
infile->seekg(0, std::ios::end);
size = infile->tellg();
data.resize(static_cast<std::vector<char>::size_type>(size));
// data = new char [size];
infile->seekg (0, std::ios::beg);
infile->read (&data.front(), size);
// infile->close();
// delete[] data;
delete infile;
return std::string(&data[0], data.size());
// return data;
}
else
{
throw libpc_error("unable to open file!");
// return data;
}
}
BOOST_AUTO_TEST_SUITE(XMLSchemaTest)
BOOST_AUTO_TEST_CASE(test_schema_read)
{
// std::istream* xml_stream = Utils::openFile(TestConfig::g_data_path+"schemas/8-dimension-schema.xml");
// std::istream* xsd_stream = Utils::openFile(TestConfig::g_data_path+"/schemas/LAS.xsd");
std::string xml = ReadXML(TestConfig::g_data_path+"schemas/8-dimension-schema.xml");
std::string xsd = ReadXML(TestConfig::g_data_path+"/schemas/LAS.xsd");
libpc::schema::Reader reader(xml, xsd);
libpc::Schema schema = reader.getSchema();
libpc::schema::Writer writer(schema);
std::string xml_output = writer.write();
libpc::schema::Reader reader2(xml_output, xsd);
libpc::Schema schema2 = reader2.getSchema();
libpc::Schema::Dimensions const& dims1 = schema.getDimensions();
libpc::Schema::Dimensions const& dims2 = schema2.getDimensions();
BOOST_CHECK_EQUAL(dims1.size(), dims2.size());
for (boost::uint32_t i = 0; i < dims2.size(); ++i)
{
libpc::Dimension const& dim1 = schema.getDimension(i);
libpc::Dimension const& dim2 = schema2.getDimension(i);
BOOST_CHECK_EQUAL(dim1.getDataType(), dim2.getDataType());
BOOST_CHECK_EQUAL(dim1.getByteSize(), dim2.getByteSize());
BOOST_CHECK_EQUAL(dim1.getField(), dim2.getField());
BOOST_CHECK_EQUAL(dim1.getDescription(), dim2.getDescription());
}
}
BOOST_AUTO_TEST_SUITE_END()
|
/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([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 name of Hobu, Inc. or Flaxen Geo Consulting 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 <boost/test/unit_test.hpp>
#include <boost/cstdint.hpp>
#include <boost/property_tree/ptree.hpp>
#include <libpc/XMLSchema.hpp>
#include <libpc/drivers/faux/Reader.hpp>
#include <libpc/drivers/faux/Writer.hpp>
#include <libpc/drivers/las/Reader.hpp>
#include <libpc/Iterator.hpp>
#include <libpc/Utils.hpp>
#include "Support.hpp"
#include "TestConfig.hpp"
#include <fstream>
using namespace libpc;
std::string ReadXML(std::string filename)
{
std::istream* infile = Utils::openFile(filename);
std::ifstream::pos_type size;
// char* data;
std::vector<char> data;
if (infile->good()){
infile->seekg(0, std::ios::end);
size = infile->tellg();
data.resize(static_cast<std::vector<char>::size_type>(size));
// data = new char [size];
infile->seekg (0, std::ios::beg);
infile->read (&data.front(), size);
// infile->close();
// delete[] data;
delete infile;
return std::string(&data[0], data.size());
// return data;
}
else
{
throw libpc_error("unable to open file!");
// return data;
}
}
BOOST_AUTO_TEST_SUITE(XMLSchemaTest)
BOOST_AUTO_TEST_CASE(test_schema_read)
{
// std::istream* xml_stream = Utils::openFile(TestConfig::g_data_path+"schemas/8-dimension-schema.xml");
// std::istream* xsd_stream = Utils::openFile(TestConfig::g_data_path+"/schemas/LAS.xsd");
std::string xml = ReadXML(TestConfig::g_data_path+"schemas/8-dimension-schema.xml");
std::string xsd = ReadXML(TestConfig::g_data_path+"/schemas/LAS.xsd");
libpc::schema::Reader reader(xml, xsd);
libpc::Schema schema = reader.getSchema();
libpc::schema::Writer writer(schema);
std::string xml_output = writer.getXML();
libpc::schema::Reader reader2(xml_output, xsd);
libpc::Schema schema2 = reader2.getSchema();
libpc::Schema::Dimensions const& dims1 = schema.getDimensions();
libpc::Schema::Dimensions const& dims2 = schema2.getDimensions();
BOOST_CHECK_EQUAL(dims1.size(), dims2.size());
for (boost::uint32_t i = 0; i < dims2.size(); ++i)
{
libpc::Dimension const& dim1 = schema.getDimension(i);
libpc::Dimension const& dim2 = schema2.getDimension(i);
BOOST_CHECK_EQUAL(dim1.getDataType(), dim2.getDataType());
BOOST_CHECK_EQUAL(dim1.getByteSize(), dim2.getByteSize());
BOOST_CHECK_EQUAL(dim1.getField(), dim2.getField());
BOOST_CHECK_EQUAL(dim1.getDescription(), dim2.getDescription());
}
}
BOOST_AUTO_TEST_SUITE_END()
|
use new getXML() rename instead of write()
|
use new getXML() rename instead of write()
|
C++
|
bsd-3-clause
|
mpgerlek/PDAL-old,verma/PDAL,mtCarto/PDAL,boundlessgeo/PDAL,verma/PDAL,mtCarto/PDAL,radiantbluetechnologies/PDAL,lucadelu/PDAL,lucadelu/PDAL,mpgerlek/PDAL-old,Sciumo/PDAL,mtCarto/PDAL,boundlessgeo/PDAL,lucadelu/PDAL,radiantbluetechnologies/PDAL,DougFirErickson/PDAL,jwomeara/PDAL,lucadelu/PDAL,jwomeara/PDAL,mpgerlek/PDAL-old,mpgerlek/PDAL-old,jwomeara/PDAL,verma/PDAL,jwomeara/PDAL,boundlessgeo/PDAL,mtCarto/PDAL,boundlessgeo/PDAL,verma/PDAL,Sciumo/PDAL,DougFirErickson/PDAL,verma/PDAL,Sciumo/PDAL,DougFirErickson/PDAL,Sciumo/PDAL,verma/PDAL,radiantbluetechnologies/PDAL,DougFirErickson/PDAL,verma/PDAL,radiantbluetechnologies/PDAL
|
65456320e4feb8e6b5b6ae3e252ae8ff88f19bc3
|
C++/the-skyline-problem.cpp
|
C++/the-skyline-problem.cpp
|
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
vector<pair<int, int> > getSkyline(vector<vector<int> >& buildings) {
map<int, vector<int>> start_point_to_heights;
map<int, vector<int>> end_point_to_heights;
set<int> points;
for (int i = 0; i < buildings.size(); ++i) {
start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]);
end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]);
points.insert(buildings[i][0]);
points.insert(buildings[i][1]);
}
vector<pair<int, int>> res;
map<int, int> height_to_count;
int curr_max = 0;
// Enumerate each point in increasing order.
for (auto it = points.begin(); it != points.end(); ++it) {
vector<int> start_point_heights = start_point_to_heights[*it];
vector<int> end_point_heights = end_point_to_heights[*it];
for (int i = 0; i < start_point_heights.size(); ++i) {
++height_to_count[start_point_heights[i]];
}
for (int i = 0; i < end_point_heights.size(); ++i) {
--height_to_count[end_point_heights[i]];
if (height_to_count[end_point_heights[i]] == 0) {
height_to_count.erase(end_point_heights[i]);
}
}
if (height_to_count.empty()) {
curr_max = 0;
res.emplace_back(move(make_pair(*it, curr_max)));
} else if (curr_max != height_to_count.rbegin()->first) {
curr_max = height_to_count.rbegin()->first;
res.emplace_back(move(make_pair(*it, curr_max)));
}
}
return res;
}
};
|
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
vector<pair<int, int> > getSkyline(vector<vector<int> >& buildings) {
unordered_map<int, vector<int>> start_point_to_heights;
unordered_map<int, vector<int>> end_point_to_heights;
set<int> points;
for (int i = 0; i < buildings.size(); ++i) {
start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]);
end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]);
points.emplace(buildings[i][0]);
points.emplace(buildings[i][1]);
}
vector<pair<int, int>> res;
map<int, int> height_to_count;
int curr_max = 0;
// Enumerate each point in increasing order.
for (auto it = points.begin(); it != points.end(); ++it) {
vector<int> start_point_heights = start_point_to_heights[*it];
vector<int> end_point_heights = end_point_to_heights[*it];
for (int i = 0; i < start_point_heights.size(); ++i) {
++height_to_count[start_point_heights[i]];
}
for (int i = 0; i < end_point_heights.size(); ++i) {
--height_to_count[end_point_heights[i]];
if (height_to_count[end_point_heights[i]] == 0) {
height_to_count.erase(end_point_heights[i]);
}
}
if (height_to_count.empty()) {
curr_max = 0;
res.emplace_back(move(make_pair(*it, curr_max)));
} else if (curr_max != height_to_count.rbegin()->first) {
curr_max = height_to_count.rbegin()->first;
res.emplace_back(move(make_pair(*it, curr_max)));
}
}
return res;
}
};
|
Update the-skyline-problem.cpp
|
Update the-skyline-problem.cpp
|
C++
|
mit
|
tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,jaredkoontz/leetcode,githubutilities/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,jaredkoontz/leetcode,yiwen-luo/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode
|
93e031629ea3e278f32e9791cca0d4fa64063cf8
|
tutorial/lesson_21_auto_scheduler_generate.cpp
|
tutorial/lesson_21_auto_scheduler_generate.cpp
|
// Halide tutorial lesson 21: Auto-Scheduler
// This lesson demonstrates how to use the auto-scheduler to generate a
// copy-pastable CPU schedule that can be subsequently improved upon.
// On linux or os x, you can compile and run it like so:
// g++ lesson_21_auto_scheduler_generate.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_21_generate
// export LD_LIBRARY_PATH=../bin # For linux
// export DYLD_LIBRARY_PATH=../bin # For OS X
// ./lesson_21_generate -o . -f conv_layer target=host
// g++ lesson_21_auto_scheduler_run.cpp brighten_*.o -ldl -lpthread -o lesson_21_run
// ./lesson_21_run
// If you have the entire Halide source tree, you can also build it by
// running:
// make tutorial_lesson_21_auto_scheduler_run
// in a shell with the current directory at the top of the halide
// source tree.
#include "Halide.h"
#include <stdio.h>
using namespace Halide;
// We will define a generator to auto-schedule.
class AutoScheduled : public Halide::Generator<AutoScheduled> {
public:
GeneratorParam<bool> auto_schedule{"auto_schedule", false};
Input<Buffer<float>> input{"input", 4};
Input<Buffer<float>> filter{"filter", 4};
Input<Buffer<float>> bias{"bias", 1};
Input<float> min_value{"min_value"};
Output<Buffer<float>> output1{"output1", 4};
Output<Buffer<float>> output2{"output2", 4};
void generate() {
RDom r(filter.dim(0).min(), filter.dim(0).extent(),
filter.dim(1).min(), filter.dim(1).extent(),
filter.dim(2).min(), filter.dim(2).extent());
f(x, y, z, n) = bias(z);
f(x, y, z, n) += filter(r.x, r.y, r.z, z) * input(x + r.x, y + r.y, r.z, n);
output1(x, y, z, n) = max(0, f(x, y, z, n));
output2(x, y, z, n) = min(min_value, f(x, y, z, n));
}
void schedule() {
if (auto_schedule) {
// To use the auto-scheduler, we need to provide estimates on all
// the input/output sizes including estimates on all the parameter
// values; otherwise, the auto-scheduler will throw an assertion.
// First, provide estimates (min and extent values) for each dimension
// of the input images ('input', 'filter', and 'bias') using the
// set_bounds_estimate() method. set_bounds_estimate() takes in
// (min, extent) of the corresponding dimension as arguments.
input.dim(0).set_bounds_estimate(0, 131);
input.dim(1).set_bounds_estimate(0, 131);
input.dim(2).set_bounds_estimate(0, 64);
input.dim(3).set_bounds_estimate(0, 4);
filter.dim(0).set_bounds_estimate(0, 3);
filter.dim(1).set_bounds_estimate(0, 3);
filter.dim(2).set_bounds_estimate(0, 64);
filter.dim(3).set_bounds_estimate(0, 64);
bias.dim(0).set_bounds_estimate(0, 64);
// Next, provide estimates on the parameter values using the
// set_estimate() method.
min_value.set_estimate(2.0f);
// Last, provide estimates (min and extent values) for each dimension
// of pipeline outputs using the estimate() method. estimate() takes in
// (dim_name, min, extent) as arguments.
output1.estimate(x, 0, 128)
.estimate(y, 0, 128)
.estimate(z, 0, 64)
.estimate(n, 0, 4);
output2.estimate(x, 0, 128)
.estimate(y, 0, 128)
.estimate(z, 0, 64)
.estimate(n, 0, 4);
// Technically, the estimate values can be anything, but the closer
// they are to the actual use-case values, the better the generated
// schedule will be.
// Now, let's auto-schedule the pipeline by calling auto_schedule_outputs(),
// which takes in a MachineParams object as an argument. The machine_params
// argument is optional. If none is specified, the default machine parameters
// for a generic CPU architecture are going to be used by the auto-scheduler.
// Let's use some arbitrary but plausible values for the machine parameters.
MachineParams machine_params(32, 16 * 1024 * 1024, 40);
// The arguments to MachineParams are the maximum level of parallelism
// available, the size of the last-level cache (in KB), and the ratio
// between memory cost and arithmetic cost at the last level case, of
// the target architecture, in that order.
// Note that when using the auto-scheduler, no schedule should have
// been applied to the pipeline; otherwise, the auto-scheduler will
// throw an error. The current auto-scheduler does not work with
// partially-scheduled pipeline.
//
// Calling auto_schedule_outputs() will apply the generated schedule
// automatically to members of the pipeline in addition to returning
// a string representation of the schedule.
std::string schedule = auto_schedule_outputs(machine_params);
std::cout << "\nSchedule:\n\n" << schedule << "\n";
// The generated schedule that is dumped to std::cout is an actual
// Halide C++ source, which is readily copy-pastable back into
// this very same source file with little modifications. Programmers
// can use this as a starting schedule and iteratively improve the
// schedule. Note that the current auto-scheduler is only able to
// generate CPU schedule and only does tiling, simple vectorization
// and parallelization. It doesn't deal with line buffering, storage
// reordering, or factoring a reduction.
} else {
// This is where you would declare the schedule you have or
// paste the schedule generated by the auto-scheduler.
// This auto-scheduler will return the following schedule for the
// estimates and machine parameters declared above when run on
// this pipeline:
//
// Var x_vi("x_vi");
// Var x_vo("x_vo");
//
// Func f0 = pipeline.get_func(3);
// Func output1 = pipeline.get_func(4);
// Func output2 = pipeline.get_func(5);
//
// {
// Var x = f0.args()[0];
// Var y = f0.args()[1];
// Var z = f0.args()[2];
// Var n = f0.args()[3];
// RVar r$x(f0.update(0).get_schedule().rvars()[0].var);
// RVar r$y(f0.update(0).get_schedule().rvars()[1].var);
// RVar r$z(f0.update(0).get_schedule().rvars()[2].var);
// f0
// .compute_root()
// .split(x, x_vo, x_vi, 8)
// .vectorize(x_vi)
// .parallel(n)
// .parallel(z);
// f0.update(0)
// .split(x, x_vo, x_vi, 8)
// .vectorize(x_vi)
// .parallel(n)
// .parallel(z);
// }
// {
// Var x = output1.args()[0];
// Var y = output1.args()[1];
// Var z = output1.args()[2];
// Var n = output1.args()[3];
// output1
// .compute_root()
// .split(x, x_vo, x_vi, 8)
// .vectorize(x_vi)
// .parallel(n)
// .parallel(z);
// }
// {
// Var x = output2.args()[0];
// Var y = output2.args()[1];
// Var z = output2.args()[2];
// Var n = output2.args()[3];
// output2
// .compute_root()
// .split(x, x_vo, x_vi, 8)
// .vectorize(x_vi)
// .parallel(n)
// .parallel(z);
// }
}
}
private:
Var x{"x"}, y{"y"}, z{"z"}, n{"n"};
Func f;
};
// As in lesson 15, we register our generator and then compile this
// file along with tools/GenGen.cpp.
HALIDE_REGISTER_GENERATOR(AutoScheduled, auto_schedule_gen)
// After compiling this file, see how to use it in
// lesson_21_auto_scheduler_run.cpp
|
// Halide tutorial lesson 21: Auto-Scheduler
// This lesson demonstrates how to use the auto-scheduler to generate a
// copy-pastable CPU schedule that can be subsequently improved upon.
// On linux or os x, you can compile and run it like so:
// g++ lesson_21_auto_scheduler_generate.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_21_generate
// export LD_LIBRARY_PATH=../bin # For linux
// export DYLD_LIBRARY_PATH=../bin # For OS X
// ./lesson_21_generate -o . -f conv_layer target=host
// g++ lesson_21_auto_scheduler_run.cpp brighten_*.o -ldl -lpthread -o lesson_21_run
// ./lesson_21_run
// If you have the entire Halide source tree, you can also build it by
// running:
// make tutorial_lesson_21_auto_scheduler_run
// in a shell with the current directory at the top of the halide
// source tree.
#include "Halide.h"
#include <stdio.h>
using namespace Halide;
// We will define a generator to auto-schedule.
class AutoScheduled : public Halide::Generator<AutoScheduled> {
public:
GeneratorParam<bool> auto_schedule{"auto_schedule", false};
Input<Buffer<float>> input{"input", 4};
Input<Buffer<float>> filter{"filter", 4};
Input<Buffer<float>> bias{"bias", 1};
Input<float> min_value{"min_value"};
Output<Buffer<float>> output1{"output1", 4};
Output<Buffer<float>> output2{"output2", 4};
void generate() {
RDom r(filter.dim(0).min(), filter.dim(0).extent(),
filter.dim(1).min(), filter.dim(1).extent(),
filter.dim(2).min(), filter.dim(2).extent());
f(x, y, z, n) = bias(z);
f(x, y, z, n) += filter(r.x, r.y, r.z, z) * input(x + r.x, y + r.y, r.z, n);
output1(x, y, z, n) = max(0, f(x, y, z, n));
output2(x, y, z, n) = min(min_value, f(x, y, z, n));
}
void schedule() {
if (auto_schedule) {
// To use the auto-scheduler, we need to provide estimates on all
// the input/output sizes including estimates on all the parameter
// values; otherwise, the auto-scheduler will throw an assertion.
// To provide estimates (min and extent values) for each dimension
// of the input images ('input', 'filter', and 'bias'), we use the
// set_bounds_estimate() method. set_bounds_estimate() takes in
// (min, extent) of the corresponding dimension as arguments.
input.dim(0).set_bounds_estimate(0, 131);
input.dim(1).set_bounds_estimate(0, 131);
input.dim(2).set_bounds_estimate(0, 64);
input.dim(3).set_bounds_estimate(0, 4);
filter.dim(0).set_bounds_estimate(0, 3);
filter.dim(1).set_bounds_estimate(0, 3);
filter.dim(2).set_bounds_estimate(0, 64);
filter.dim(3).set_bounds_estimate(0, 64);
bias.dim(0).set_bounds_estimate(0, 64);
// To provide estimates on the parameter values, we use the
// set_estimate() method.
min_value.set_estimate(2.0f);
// To provide estimates (min and extent values) for each dimension
// of pipeline outputs, we use the estimate() method. estimate()
// takes in (dim_name, min, extent) as arguments.
output1.estimate(x, 0, 128)
.estimate(y, 0, 128)
.estimate(z, 0, 64)
.estimate(n, 0, 4);
output2.estimate(x, 0, 128)
.estimate(y, 0, 128)
.estimate(z, 0, 64)
.estimate(n, 0, 4);
// Technically, the estimate values can be anything, but the closer
// they are to the actual use-case values, the better the generated
// schedule will be.
// Now, let's auto-schedule the pipeline by calling auto_schedule_outputs(),
// which takes in a MachineParams object as an argument. The machine_params
// argument is optional. If none is specified, the default machine parameters
// for a generic CPU architecture are going to be used by the auto-scheduler.
// Let's use some arbitrary but plausible values for the machine parameters.
MachineParams machine_params(32, 16 * 1024 * 1024, 40);
// The arguments to MachineParams are the maximum level of parallelism
// available, the size of the last-level cache (in KB), and the ratio
// between memory cost and arithmetic cost at the last level case, of
// the target architecture, in that order.
// Note that when using the auto-scheduler, no schedule should have
// been applied to the pipeline; otherwise, the auto-scheduler will
// throw an error. The current auto-scheduler does not work with
// partially-scheduled pipeline.
//
// Calling auto_schedule_outputs() will apply the generated schedule
// automatically to members of the pipeline in addition to returning
// a string representation of the schedule.
std::string schedule = auto_schedule_outputs(machine_params);
std::cout << "\nSchedule:\n\n" << schedule << "\n";
// The generated schedule that is dumped to std::cout is an actual
// Halide C++ source, which is readily copy-pastable back into
// this very same source file with little modifications. Programmers
// can use this as a starting schedule and iteratively improve the
// schedule. Note that the current auto-scheduler is only able to
// generate CPU schedule and only does tiling, simple vectorization
// and parallelization. It doesn't deal with line buffering, storage
// reordering, or factoring a reduction.
} else {
// This is where you would declare the schedule you have or
// paste the schedule generated by the auto-scheduler.
// This auto-scheduler will return the following schedule for the
// estimates and machine parameters declared above when run on
// this pipeline:
//
// Var x_vi("x_vi");
// Var x_vo("x_vo");
//
// Func f0 = pipeline.get_func(3);
// Func output1 = pipeline.get_func(4);
// Func output2 = pipeline.get_func(5);
//
// {
// Var x = f0.args()[0];
// Var y = f0.args()[1];
// Var z = f0.args()[2];
// Var n = f0.args()[3];
// RVar r$x(f0.update(0).get_schedule().rvars()[0].var);
// RVar r$y(f0.update(0).get_schedule().rvars()[1].var);
// RVar r$z(f0.update(0).get_schedule().rvars()[2].var);
// f0
// .compute_root()
// .split(x, x_vo, x_vi, 8)
// .vectorize(x_vi)
// .parallel(n)
// .parallel(z);
// f0.update(0)
// .split(x, x_vo, x_vi, 8)
// .vectorize(x_vi)
// .parallel(n)
// .parallel(z);
// }
// {
// Var x = output1.args()[0];
// Var y = output1.args()[1];
// Var z = output1.args()[2];
// Var n = output1.args()[3];
// output1
// .compute_root()
// .split(x, x_vo, x_vi, 8)
// .vectorize(x_vi)
// .parallel(n)
// .parallel(z);
// }
// {
// Var x = output2.args()[0];
// Var y = output2.args()[1];
// Var z = output2.args()[2];
// Var n = output2.args()[3];
// output2
// .compute_root()
// .split(x, x_vo, x_vi, 8)
// .vectorize(x_vi)
// .parallel(n)
// .parallel(z);
// }
}
}
private:
Var x{"x"}, y{"y"}, z{"z"}, n{"n"};
Func f;
};
// As in lesson 15, we register our generator and then compile this
// file along with tools/GenGen.cpp.
HALIDE_REGISTER_GENERATOR(AutoScheduled, auto_schedule_gen)
// After compiling this file, see how to use it in
// lesson_21_auto_scheduler_run.cpp
|
Modify wording in lesson 21
|
Modify wording in lesson 21
|
C++
|
mit
|
psuriana/Halide,psuriana/Halide,psuriana/Halide,psuriana/Halide,psuriana/Halide,psuriana/Halide,psuriana/Halide
|
569f4204e57c1ce08df3be6dfe01330eb41ee91f
|
mathcore/src/Integrator.cxx
|
mathcore/src/Integrator.cxx
|
// @(#)root/mathmore:$Id: Integrator.cxx 19826 2007-09-19 19:56:11Z rdm $
// Authors: L. Moneta, M. Slawinska 10/2007
/**********************************************************************
* *
* Copyright (c) 2004 ROOT Foundation, CERN/PH-SFT *
* *
* *
**********************************************************************/
#include "Math/IFunction.h"
#include "Math/VirtualIntegrator.h"
#include "Math/Integrator.h"
#include "Math/IntegratorMultiDim.h"
#include "Math/AdaptiveIntegratorMultiDim.h"
#include "Math/OneDimFunctionAdapter.h"
#include "RConfigure.h"
#ifndef ROOTINCDIR
#define MATH_NO_PLUGIN_MANAGER
#endif
#ifndef MATH_NO_PLUGIN_MANAGER
#include "TROOT.h"
#include "TPluginManager.h"
#else // case no plugin manager is available
#ifdef R__HAS_MATHMORE
#include "Math/GSLIntegrator.h"
#include "Math/GSLMCIntegrator.h"
#endif
#endif
#include <cassert>
namespace ROOT {
namespace Math {
void IntegratorOneDim::SetFunction(const IMultiGenFunction &f, unsigned int icoord , const double * x ) {
// set function from a multi-dim function
// pass also x in case of multi-dim function express the other dimensions (which are fixed)
unsigned int ndim = f.NDim();
assert (icoord < ndim);
ROOT::Math::OneDimMultiFunctionAdapter<> adapter(f,ndim,icoord);
// case I pass a vector x which is needed (for example to compute I(y) = Integral( f(x,y) dx) ) need to setCX
if (x != 0) adapter.SetX(x, x+ ndim);
SetFunction(adapter,true); // need to copy this object
}
// methods to create integrators
VirtualIntegratorOneDim * IntegratorOneDim::CreateIntegrator(IntegrationOneDim::Type type , double absTol, double relTol, unsigned int size, int rule) {
// create the concrete class for one-dimensional integration. Use the plug-in manager if needed
VirtualIntegratorOneDim * ig = 0;
#ifdef MATH_NO_PLUGIN_MANAGER // no PM available
#ifdef R__HAS_MATHMORE
ig = new GSLIntegrator(type, absTol, relTol, size);
#else
MATH_ERROR_MSG("IntegratorOneDim::CreateIntegrator","Integrator type is not available in MathCore");
#endif
#else // case of using Plugin Manager
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::VirtualIntegrator", "GSLIntegrator"))) {
if (h->LoadPlugin() == -1) {
MATH_ERROR_MSG("IntegratorOneDim::CreateIntegrator","Error loading one dimensional GSL integrator");
return 0;
}
std::string typeName = "ADAPTIVE";
if (type == IntegrationOneDim::ADAPTIVESINGULAR)
typeName = "ADAPTIVESINGULAR";
if (type == IntegrationOneDim::NONADAPTIVE)
typeName = "NONADAPTIVE";
ig = reinterpret_cast<ROOT::Math::VirtualIntegratorOneDim *>( h->ExecPlugin(5,typeName.c_str(), rule, absTol, relTol, size ) );
assert(ig != 0);
#ifdef DEBUG
std::cout << "Loaded Integrator " << typeid(*ig).name() << std::endl;
#endif
}
#endif
return ig;
}
VirtualIntegratorMultiDim * IntegratorMultiDim::CreateIntegrator(IntegrationMultiDim::Type type , double absTol, double relTol, unsigned int ncall) {
// create concrete class for multidimensional integration
// no need for PM in the adaptive case using Genz method (class is in MathCore)
if (type == IntegrationMultiDim::ADAPTIVE)
return new AdaptiveIntegratorMultiDim(absTol, relTol, ncall);
VirtualIntegratorMultiDim * ig = 0;
#ifdef MATH_NO_PLUGIN_MANAGER // no PM available
#ifdef R__HAS_MATHMORE
ig = new GSLMCIntegrator(type, absTol, relTol, ncall);
#else
MATH_ERROR_MSG("IntegratorMultiDim::CreateIntegrator","Integrator type is not available in MathCore");
#endif
#else // use ROOT PM
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::VirtualIntegrator", "GSLMCIntegrator"))) {
if (h->LoadPlugin() == -1) {
MATH_ERROR_MSG("IntegratorMultiDim::CreateIntegrator","Error loading multidim integrator");
return 0;
}
std::string typeName = "VEGAS";
if (type == IntegrationMultiDim::MISER)
typeName = "MISER";
if (type == IntegrationMultiDim::PLAIN)
typeName = "PLAIN";
ig = reinterpret_cast<ROOT::Math::VirtualIntegratorMultiDim *>( h->ExecPlugin(4,typeName.c_str(), absTol, relTol, ncall ) );
assert(ig != 0);
#ifdef DEBUG
std::cout << "Loaded Integrator " << typeid(*ig).name() << std::endl;
#endif
}
#endif
return ig;
}
} // namespace Math
} // namespace ROOT
|
// @(#)root/mathmore:$Id: Integrator.cxx 19826 2007-09-19 19:56:11Z rdm $
// Authors: L. Moneta, M. Slawinska 10/2007
/**********************************************************************
* *
* Copyright (c) 2004 ROOT Foundation, CERN/PH-SFT *
* *
* *
**********************************************************************/
#include "Math/IFunction.h"
#include "Math/VirtualIntegrator.h"
#include "Math/Integrator.h"
#include "Math/IntegratorMultiDim.h"
#include "Math/AdaptiveIntegratorMultiDim.h"
#include "Math/OneDimFunctionAdapter.h"
#include "RConfigure.h"
// #ifndef ROOTINCDIR
// #define MATH_NO_PLUGIN_MANAGER
// #endif
#ifndef MATH_NO_PLUGIN_MANAGER
#include "TROOT.h"
#include "TPluginManager.h"
#else // case no plugin manager is available
#ifdef R__HAS_MATHMORE
#include "Math/GSLIntegrator.h"
#include "Math/GSLMCIntegrator.h"
#endif
#endif
#include <cassert>
namespace ROOT {
namespace Math {
void IntegratorOneDim::SetFunction(const IMultiGenFunction &f, unsigned int icoord , const double * x ) {
// set function from a multi-dim function
// pass also x in case of multi-dim function express the other dimensions (which are fixed)
unsigned int ndim = f.NDim();
assert (icoord < ndim);
ROOT::Math::OneDimMultiFunctionAdapter<> adapter(f,ndim,icoord);
// case I pass a vector x which is needed (for example to compute I(y) = Integral( f(x,y) dx) ) need to setCX
if (x != 0) adapter.SetX(x, x+ ndim);
SetFunction(adapter,true); // need to copy this object
}
// methods to create integrators
VirtualIntegratorOneDim * IntegratorOneDim::CreateIntegrator(IntegrationOneDim::Type type , double absTol, double relTol, unsigned int size, int rule) {
// create the concrete class for one-dimensional integration. Use the plug-in manager if needed
VirtualIntegratorOneDim * ig = 0;
#ifdef MATH_NO_PLUGIN_MANAGER // no PM available
#ifdef R__HAS_MATHMORE
ig = new GSLIntegrator(type, absTol, relTol, size);
#else
MATH_ERROR_MSG("IntegratorOneDim::CreateIntegrator","Integrator type is not available in MathCore");
#endif
#else // case of using Plugin Manager
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::VirtualIntegrator", "GSLIntegrator"))) {
if (h->LoadPlugin() == -1) {
MATH_ERROR_MSG("IntegratorOneDim::CreateIntegrator","Error loading one dimensional GSL integrator");
return 0;
}
std::string typeName = "ADAPTIVE";
if (type == IntegrationOneDim::ADAPTIVESINGULAR)
typeName = "ADAPTIVESINGULAR";
if (type == IntegrationOneDim::NONADAPTIVE)
typeName = "NONADAPTIVE";
ig = reinterpret_cast<ROOT::Math::VirtualIntegratorOneDim *>( h->ExecPlugin(5,typeName.c_str(), rule, absTol, relTol, size ) );
assert(ig != 0);
#ifdef DEBUG
std::cout << "Loaded Integrator " << typeid(*ig).name() << std::endl;
#endif
}
#endif
return ig;
}
VirtualIntegratorMultiDim * IntegratorMultiDim::CreateIntegrator(IntegrationMultiDim::Type type , double absTol, double relTol, unsigned int ncall) {
// create concrete class for multidimensional integration
// no need for PM in the adaptive case using Genz method (class is in MathCore)
if (type == IntegrationMultiDim::ADAPTIVE)
return new AdaptiveIntegratorMultiDim(absTol, relTol, ncall);
VirtualIntegratorMultiDim * ig = 0;
#ifdef MATH_NO_PLUGIN_MANAGER // no PM available
#ifdef R__HAS_MATHMORE
ig = new GSLMCIntegrator(type, absTol, relTol, ncall);
#else
MATH_ERROR_MSG("IntegratorMultiDim::CreateIntegrator","Integrator type is not available in MathCore");
#endif
#else // use ROOT PM
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::VirtualIntegrator", "GSLMCIntegrator"))) {
if (h->LoadPlugin() == -1) {
MATH_ERROR_MSG("IntegratorMultiDim::CreateIntegrator","Error loading multidim integrator");
return 0;
}
std::string typeName = "VEGAS";
if (type == IntegrationMultiDim::MISER)
typeName = "MISER";
if (type == IntegrationMultiDim::PLAIN)
typeName = "PLAIN";
ig = reinterpret_cast<ROOT::Math::VirtualIntegratorMultiDim *>( h->ExecPlugin(4,typeName.c_str(), absTol, relTol, ncall ) );
assert(ig != 0);
#ifdef DEBUG
std::cout << "Loaded Integrator " << typeid(*ig).name() << std::endl;
#endif
}
#endif
return ig;
}
} // namespace Math
} // namespace ROOT
|
fix a mistake with previous commit
|
fix a mistake with previous commit
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@21160 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
thomaskeck/root,beniz/root,georgtroska/root,BerserkerTroll/root,omazapa/root-old,gganis/root,karies/root,esakellari/root,mattkretz/root,sawenzel/root,omazapa/root,CristinaCristescu/root,krafczyk/root,agarciamontoro/root,satyarth934/root,bbockelm/root,lgiommi/root,ffurano/root5,thomaskeck/root,arch1tect0r/root,gbitzes/root,bbockelm/root,alexschlueter/cern-root,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,perovic/root,krafczyk/root,evgeny-boger/root,mkret2/root,omazapa/root-old,ffurano/root5,cxx-hep/root-cern,mkret2/root,beniz/root,perovic/root,esakellari/root,mkret2/root,Dr15Jones/root,strykejern/TTreeReader,evgeny-boger/root,CristinaCristescu/root,jrtomps/root,nilqed/root,simonpf/root,CristinaCristescu/root,buuck/root,veprbl/root,esakellari/my_root_for_test,thomaskeck/root,kirbyherm/root-r-tools,krafczyk/root,esakellari/root,Y--/root,jrtomps/root,perovic/root,cxx-hep/root-cern,vukasinmilosevic/root,gbitzes/root,smarinac/root,Y--/root,davidlt/root,alexschlueter/cern-root,arch1tect0r/root,krafczyk/root,perovic/root,kirbyherm/root-r-tools,satyarth934/root,davidlt/root,georgtroska/root,sirinath/root,nilqed/root,BerserkerTroll/root,vukasinmilosevic/root,buuck/root,esakellari/root,sirinath/root,mattkretz/root,sbinet/cxx-root,zzxuanyuan/root,alexschlueter/cern-root,pspe/root,Duraznos/root,0x0all/ROOT,mkret2/root,strykejern/TTreeReader,vukasinmilosevic/root,karies/root,sbinet/cxx-root,abhinavmoudgil95/root,krafczyk/root,jrtomps/root,lgiommi/root,sirinath/root,zzxuanyuan/root-compressor-dummy,Dr15Jones/root,mhuwiler/rootauto,mhuwiler/rootauto,gganis/root,nilqed/root,simonpf/root,vukasinmilosevic/root,lgiommi/root,omazapa/root,perovic/root,gbitzes/root,esakellari/my_root_for_test,krafczyk/root,sbinet/cxx-root,omazapa/root,gganis/root,satyarth934/root,smarinac/root,davidlt/root,mhuwiler/rootauto,mattkretz/root,vukasinmilosevic/root,smarinac/root,Duraznos/root,arch1tect0r/root,tc3t/qoot,jrtomps/root,BerserkerTroll/root,georgtroska/root,omazapa/root-old,Duraznos/root,mattkretz/root,Y--/root,esakellari/my_root_for_test,mhuwiler/rootauto,arch1tect0r/root,root-mirror/root,omazapa/root-old,CristinaCristescu/root,mhuwiler/rootauto,beniz/root,cxx-hep/root-cern,root-mirror/root,smarinac/root,bbockelm/root,zzxuanyuan/root-compressor-dummy,arch1tect0r/root,tc3t/qoot,gbitzes/root,satyarth934/root,nilqed/root,thomaskeck/root,simonpf/root,CristinaCristescu/root,omazapa/root,zzxuanyuan/root-compressor-dummy,karies/root,veprbl/root,veprbl/root,bbockelm/root,abhinavmoudgil95/root,bbockelm/root,arch1tect0r/root,georgtroska/root,thomaskeck/root,thomaskeck/root,zzxuanyuan/root,0x0all/ROOT,smarinac/root,abhinavmoudgil95/root,ffurano/root5,Dr15Jones/root,georgtroska/root,Duraznos/root,mkret2/root,cxx-hep/root-cern,karies/root,kirbyherm/root-r-tools,sirinath/root,beniz/root,omazapa/root-old,root-mirror/root,zzxuanyuan/root,tc3t/qoot,sawenzel/root,esakellari/root,mkret2/root,tc3t/qoot,sirinath/root,CristinaCristescu/root,buuck/root,veprbl/root,mattkretz/root,davidlt/root,pspe/root,buuck/root,sawenzel/root,satyarth934/root,nilqed/root,mkret2/root,Duraznos/root,lgiommi/root,beniz/root,karies/root,veprbl/root,0x0all/ROOT,abhinavmoudgil95/root,tc3t/qoot,cxx-hep/root-cern,dfunke/root,karies/root,nilqed/root,Duraznos/root,root-mirror/root,olifre/root,abhinavmoudgil95/root,CristinaCristescu/root,pspe/root,vukasinmilosevic/root,mattkretz/root,olifre/root,agarciamontoro/root,gganis/root,krafczyk/root,bbockelm/root,vukasinmilosevic/root,gbitzes/root,root-mirror/root,karies/root,esakellari/root,mkret2/root,dfunke/root,mattkretz/root,kirbyherm/root-r-tools,perovic/root,esakellari/root,pspe/root,arch1tect0r/root,gganis/root,buuck/root,beniz/root,olifre/root,lgiommi/root,mhuwiler/rootauto,zzxuanyuan/root,0x0all/ROOT,sbinet/cxx-root,gbitzes/root,mkret2/root,jrtomps/root,olifre/root,evgeny-boger/root,agarciamontoro/root,zzxuanyuan/root,arch1tect0r/root,dfunke/root,strykejern/TTreeReader,omazapa/root-old,mattkretz/root,jrtomps/root,beniz/root,olifre/root,sawenzel/root,Duraznos/root,olifre/root,mkret2/root,dfunke/root,dfunke/root,0x0all/ROOT,karies/root,BerserkerTroll/root,lgiommi/root,BerserkerTroll/root,jrtomps/root,veprbl/root,esakellari/my_root_for_test,nilqed/root,strykejern/TTreeReader,abhinavmoudgil95/root,zzxuanyuan/root,alexschlueter/cern-root,simonpf/root,evgeny-boger/root,CristinaCristescu/root,sawenzel/root,pspe/root,tc3t/qoot,gganis/root,georgtroska/root,georgtroska/root,jrtomps/root,gbitzes/root,esakellari/my_root_for_test,tc3t/qoot,root-mirror/root,simonpf/root,evgeny-boger/root,omazapa/root,dfunke/root,olifre/root,mattkretz/root,lgiommi/root,veprbl/root,esakellari/my_root_for_test,gganis/root,olifre/root,evgeny-boger/root,BerserkerTroll/root,nilqed/root,davidlt/root,CristinaCristescu/root,gganis/root,vukasinmilosevic/root,sirinath/root,davidlt/root,Dr15Jones/root,0x0all/ROOT,Duraznos/root,beniz/root,gbitzes/root,arch1tect0r/root,kirbyherm/root-r-tools,mattkretz/root,buuck/root,tc3t/qoot,esakellari/my_root_for_test,esakellari/root,evgeny-boger/root,abhinavmoudgil95/root,sawenzel/root,bbockelm/root,sawenzel/root,omazapa/root-old,bbockelm/root,arch1tect0r/root,bbockelm/root,esakellari/root,mkret2/root,vukasinmilosevic/root,vukasinmilosevic/root,BerserkerTroll/root,BerserkerTroll/root,thomaskeck/root,buuck/root,sirinath/root,omazapa/root,gganis/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,BerserkerTroll/root,gganis/root,Y--/root,esakellari/my_root_for_test,davidlt/root,root-mirror/root,agarciamontoro/root,CristinaCristescu/root,0x0all/ROOT,beniz/root,karies/root,beniz/root,Duraznos/root,simonpf/root,ffurano/root5,sbinet/cxx-root,dfunke/root,kirbyherm/root-r-tools,dfunke/root,pspe/root,bbockelm/root,zzxuanyuan/root,lgiommi/root,agarciamontoro/root,sbinet/cxx-root,zzxuanyuan/root,georgtroska/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,veprbl/root,krafczyk/root,agarciamontoro/root,omazapa/root-old,smarinac/root,zzxuanyuan/root-compressor-dummy,abhinavmoudgil95/root,pspe/root,satyarth934/root,perovic/root,pspe/root,smarinac/root,nilqed/root,cxx-hep/root-cern,buuck/root,zzxuanyuan/root-compressor-dummy,arch1tect0r/root,tc3t/qoot,perovic/root,ffurano/root5,Y--/root,Dr15Jones/root,esakellari/root,satyarth934/root,simonpf/root,olifre/root,olifre/root,0x0all/ROOT,omazapa/root-old,veprbl/root,Duraznos/root,karies/root,gganis/root,omazapa/root,gbitzes/root,sirinath/root,krafczyk/root,buuck/root,smarinac/root,omazapa/root,mhuwiler/rootauto,root-mirror/root,lgiommi/root,smarinac/root,simonpf/root,simonpf/root,pspe/root,sbinet/cxx-root,krafczyk/root,strykejern/TTreeReader,alexschlueter/cern-root,root-mirror/root,agarciamontoro/root,sawenzel/root,dfunke/root,olifre/root,mattkretz/root,strykejern/TTreeReader,davidlt/root,lgiommi/root,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,veprbl/root,BerserkerTroll/root,evgeny-boger/root,mhuwiler/rootauto,sirinath/root,georgtroska/root,thomaskeck/root,evgeny-boger/root,pspe/root,davidlt/root,Y--/root,sbinet/cxx-root,alexschlueter/cern-root,ffurano/root5,thomaskeck/root,nilqed/root,davidlt/root,mhuwiler/rootauto,omazapa/root,omazapa/root,CristinaCristescu/root,ffurano/root5,root-mirror/root,esakellari/root,alexschlueter/cern-root,strykejern/TTreeReader,zzxuanyuan/root-compressor-dummy,satyarth934/root,sirinath/root,perovic/root,cxx-hep/root-cern,cxx-hep/root-cern,jrtomps/root,smarinac/root,jrtomps/root,Y--/root,sirinath/root,bbockelm/root,Y--/root,krafczyk/root,lgiommi/root,kirbyherm/root-r-tools,Y--/root,zzxuanyuan/root,esakellari/my_root_for_test,BerserkerTroll/root,jrtomps/root,root-mirror/root,agarciamontoro/root,agarciamontoro/root,abhinavmoudgil95/root,mhuwiler/rootauto,0x0all/ROOT,esakellari/my_root_for_test,tc3t/qoot,sawenzel/root,thomaskeck/root,buuck/root,evgeny-boger/root,nilqed/root,dfunke/root,omazapa/root,georgtroska/root,perovic/root,davidlt/root,abhinavmoudgil95/root,zzxuanyuan/root,perovic/root,gbitzes/root,omazapa/root-old,Duraznos/root,satyarth934/root,karies/root,omazapa/root-old,Y--/root,agarciamontoro/root,sbinet/cxx-root,sbinet/cxx-root,simonpf/root,Dr15Jones/root,zzxuanyuan/root,agarciamontoro/root,satyarth934/root,beniz/root,buuck/root,pspe/root,Dr15Jones/root,sawenzel/root,gbitzes/root,simonpf/root,sbinet/cxx-root,abhinavmoudgil95/root,dfunke/root,zzxuanyuan/root,veprbl/root,mhuwiler/rootauto,sawenzel/root,satyarth934/root,Y--/root
|
7de2086f96da9faa12ef37e914dde669daab8243
|
source/gsgamelib/src/gs/System/FrameTimer.cpp
|
source/gsgamelib/src/gs/System/FrameTimer.cpp
|
#include "FrameTimer.h"
#include "System.h"
#include "gs/Math/MathEx.h"
#include <cassert>
FrameTimer::FrameTimer()
: m_isPaused(false)
, m_minFrameDeltaTime(NoLimit)
, m_maxFrameDeltaTime(NoLimit)
, m_firstTimeStamp(0.f)
, m_lastTimeStamp(0.f)
, m_simFrameDeltaTime(0.f)
, m_simElapsedTime(0.f)
, m_realElapsedTime(0.f)
, m_fps(0.f)
{
}
void FrameTimer::Update()
{
float64 currTimeStamp = System::GetElapsedSeconds();
if (m_firstTimeStamp == 0.f)
m_firstTimeStamp = currTimeStamp;
if (m_lastTimeStamp == 0.f)
m_lastTimeStamp = currTimeStamp;
float32 frameDeltaTime = static_cast<float32>(currTimeStamp - m_lastTimeStamp); //@TODO: lossless_cast<float32>(...)
while (frameDeltaTime < m_minFrameDeltaTime)
{
currTimeStamp = System::GetElapsedSeconds();
frameDeltaTime = static_cast<float32>(currTimeStamp - m_lastTimeStamp);
}
m_lastTimeStamp = currTimeStamp;
m_simFrameDeltaTime = m_isPaused? 0.f : frameDeltaTime;
m_simFrameDeltaTime = MathEx::Min(m_simFrameDeltaTime, m_maxFrameDeltaTime);
m_realElapsedTime += frameDeltaTime;
m_simElapsedTime += m_simFrameDeltaTime;
static float32 FACTOR = 0.1f;
const float32 instantFps = frameDeltaTime > 0.f? 1.0f / frameDeltaTime : 0.f;
m_fps = m_fps + FACTOR * (instantFps - m_fps);
}
|
#include "FrameTimer.h"
#include "System.h"
#include "gs/Math/MathEx.h"
#include <cassert>
FrameTimer::FrameTimer()
: m_isPaused(false)
, m_minFrameDeltaTime(0.f)
, m_maxFrameDeltaTime(0.f)
, m_firstTimeStamp(0.f)
, m_lastTimeStamp(0.f)
, m_simFrameDeltaTime(0.f)
, m_simElapsedTime(0.f)
, m_realElapsedTime(0.f)
, m_fps(0.f)
{
SetMinFPS(NoLimit);
SetMaxFPS(NoLimit);
}
void FrameTimer::Update()
{
float64 currTimeStamp = System::GetElapsedSeconds();
if (m_firstTimeStamp == 0.f)
m_firstTimeStamp = currTimeStamp;
if (m_lastTimeStamp == 0.f)
m_lastTimeStamp = currTimeStamp;
float32 frameDeltaTime = static_cast<float32>(currTimeStamp - m_lastTimeStamp); //@TODO: lossless_cast<float32>(...)
while (frameDeltaTime < m_minFrameDeltaTime)
{
currTimeStamp = System::GetElapsedSeconds();
frameDeltaTime = static_cast<float32>(currTimeStamp - m_lastTimeStamp);
}
m_lastTimeStamp = currTimeStamp;
m_simFrameDeltaTime = m_isPaused? 0.f : frameDeltaTime;
m_simFrameDeltaTime = MathEx::Min(m_simFrameDeltaTime, m_maxFrameDeltaTime);
m_realElapsedTime += frameDeltaTime;
m_simElapsedTime += m_simFrameDeltaTime;
static float32 FACTOR = 0.1f;
const float32 instantFps = frameDeltaTime > 0.f? 1.0f / frameDeltaTime : 0.f;
m_fps = m_fps + FACTOR * (instantFps - m_fps);
}
|
Fix FrameTimer min/max frame delta time not being initialized correctly
|
Fix FrameTimer min/max frame delta time not being initialized correctly
|
C++
|
mit
|
amaiorano/StarFox,amaiorano/StarFox
|
b8f7adab5a146bea04d598299c04570fe95caedc
|
tests/auto/qfontcombobox/tst_qfontcombobox.cpp
|
tests/auto/qfontcombobox/tst_qfontcombobox.cpp
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $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$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qfontcombobox.h>
class tst_QFontComboBox : public QObject
{
Q_OBJECT
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private slots:
void qfontcombobox_data();
void qfontcombobox();
void currentFont_data();
void currentFont();
void fontFilters_data();
void fontFilters();
void sizeHint();
void writingSystem_data();
void writingSystem();
void currentFontChanged();
};
// Subclass that exposes the protected functions.
class SubQFontComboBox : public QFontComboBox
{
public:
void call_currentFontChanged(QFont const& f)
{ return SubQFontComboBox::currentFontChanged(f); }
bool call_event(QEvent* e)
{ return SubQFontComboBox::event(e); }
};
// This will be called before the first test function is executed.
// It is only called once.
void tst_QFontComboBox::initTestCase()
{
}
// This will be called after the last test function is executed.
// It is only called once.
void tst_QFontComboBox::cleanupTestCase()
{
}
// This will be called before each test function is executed.
void tst_QFontComboBox::init()
{
}
// This will be called after every test function.
void tst_QFontComboBox::cleanup()
{
}
void tst_QFontComboBox::qfontcombobox_data()
{
}
void tst_QFontComboBox::qfontcombobox()
{
SubQFontComboBox box;
QCOMPARE(box.currentFont(), QFont());
QCOMPARE(box.fontFilters(), QFontComboBox::AllFonts);
box.setCurrentFont(QFont());
box.setFontFilters(QFontComboBox::AllFonts);
box.setWritingSystem(QFontDatabase::Any);
QVERIFY(box.sizeHint() != QSize());
QCOMPARE(box.writingSystem(), QFontDatabase::Any);
box.call_currentFontChanged(QFont());
QEvent event(QEvent::None);
QCOMPARE(box.call_event(&event), false);
}
void tst_QFontComboBox::currentFont_data()
{
QTest::addColumn<QFont>("currentFont");
// Normalize the names
QFont defaultFont;
QTest::newRow("default") << defaultFont;
defaultFont.setPointSize(defaultFont.pointSize() + 10);
QTest::newRow("default") << defaultFont;
QFontDatabase db;
QStringList list = db.families();
for (int i = 0; i < list.count(); ++i) {
QFont f = QFont(QFontInfo(QFont(list.at(i))).family());
QTest::newRow(qPrintable(list.at(i))) << f;
}
}
// public QFont currentFont() const
void tst_QFontComboBox::currentFont()
{
QFETCH(QFont, currentFont);
SubQFontComboBox box;
QSignalSpy spy0(&box, SIGNAL(currentFontChanged(QFont const&)));
QFont oldCurrentFont = box.currentFont();
box.setCurrentFont(currentFont);
QRegExp foundry(" \\[.*\\]");
if (!box.currentFont().family().contains(foundry)) {
QCOMPARE(box.currentFont(), currentFont);
}
QString boxFontFamily = QFontInfo(box.currentFont()).family();
if (!currentFont.family().contains(foundry))
boxFontFamily.remove(foundry);
QCOMPARE(boxFontFamily, currentFont.family());
if (oldCurrentFont != box.currentFont()) {
//the signal may be emit twice if there is a foundry into brackets
QCOMPARE(spy0.count(),1);
}
}
Q_DECLARE_METATYPE(QFontComboBox::FontFilters)
void tst_QFontComboBox::fontFilters_data()
{
QTest::addColumn<QFontComboBox::FontFilters>("fontFilters");
QTest::newRow("AllFonts")
<< QFontComboBox::FontFilters(QFontComboBox::AllFonts);
QTest::newRow("ScalableFonts")
<< QFontComboBox::FontFilters(QFontComboBox::ScalableFonts);
QTest::newRow("NonScalableFonts")
<< QFontComboBox::FontFilters(QFontComboBox::NonScalableFonts);
QTest::newRow("MonospacedFonts")
<< QFontComboBox::FontFilters(QFontComboBox::MonospacedFonts);
QTest::newRow("ProportionalFonts")
<< QFontComboBox::FontFilters(QFontComboBox::ProportionalFonts);
// combine two
QTest::newRow("ProportionalFonts | NonScalableFonts")
<< QFontComboBox::FontFilters(QFontComboBox::ProportionalFonts | QFontComboBox::NonScalableFonts);
// i.e. all
QTest::newRow("ScalableFonts | NonScalableFonts")
<< QFontComboBox::FontFilters(QFontComboBox::ScalableFonts | QFontComboBox::NonScalableFonts);
}
// public QFontComboBox::FontFilters fontFilters() const
void tst_QFontComboBox::fontFilters()
{
QFETCH(QFontComboBox::FontFilters, fontFilters);
SubQFontComboBox box;
QSignalSpy spy0(&box, SIGNAL(currentFontChanged(QFont const&)));
QFont currentFont = box.currentFont();
box.setFontFilters(fontFilters);
QCOMPARE(box.fontFilters(), fontFilters);
QFontDatabase db;
QStringList list = db.families();
int c = 0;
const int scalableMask = (QFontComboBox::ScalableFonts | QFontComboBox::NonScalableFonts);
const int spacingMask = (QFontComboBox::ProportionalFonts | QFontComboBox::MonospacedFonts);
if((fontFilters & scalableMask) == scalableMask)
fontFilters &= ~scalableMask;
if((fontFilters & spacingMask) == spacingMask)
fontFilters &= ~spacingMask;
for (int i = 0; i < list.count(); ++i) {
if (fontFilters & QFontComboBox::ScalableFonts) {
if (!db.isSmoothlyScalable(list[i]))
continue;
} else if (fontFilters & QFontComboBox::NonScalableFonts) {
if (db.isSmoothlyScalable(list[i]))
continue;
}
if (fontFilters & QFontComboBox::MonospacedFonts) {
if (!db.isFixedPitch(list[i]))
continue;
} else if (fontFilters & QFontComboBox::ProportionalFonts) {
if (db.isFixedPitch(list[i]))
continue;
}
c++;
}
QCOMPARE(box.model()->rowCount(), c);
if (c == 0)
QCOMPARE(box.currentFont(), QFont());
QCOMPARE(spy0.count(), (currentFont != box.currentFont()) ? 1 : 0);
}
// public QSize sizeHint() const
void tst_QFontComboBox::sizeHint()
{
SubQFontComboBox box;
QSize sizeHint = box.QComboBox::sizeHint();
QFontMetrics fm(box.font());
sizeHint.setWidth(qMax(sizeHint.width(), fm.width(QLatin1Char('m'))*14));
QCOMPARE(box.sizeHint(), sizeHint);
}
Q_DECLARE_METATYPE(QFontDatabase::WritingSystem)
void tst_QFontComboBox::writingSystem_data()
{
QTest::addColumn<QFontDatabase::WritingSystem>("writingSystem");
QTest::newRow("Any") << QFontDatabase::Any;
QTest::newRow("Latin") << QFontDatabase::Latin;
QTest::newRow("Lao") << QFontDatabase::Lao;
QTest::newRow("TraditionalChinese") << QFontDatabase::TraditionalChinese;
QTest::newRow("Ogham") << QFontDatabase::Ogham;
QTest::newRow("Runic") << QFontDatabase::Runic;
for (int i = 0; i < 31; ++i)
QTest::newRow("enum") << (QFontDatabase::WritingSystem)i;
}
// public QFontDatabase::WritingSystem writingSystem() const
void tst_QFontComboBox::writingSystem()
{
QFETCH(QFontDatabase::WritingSystem, writingSystem);
SubQFontComboBox box;
QSignalSpy spy0(&box, SIGNAL(currentFontChanged(QFont const&)));
QFont currentFont = box.currentFont();
box.setWritingSystem(writingSystem);
QCOMPARE(box.writingSystem(), writingSystem);
QFontDatabase db;
QStringList list = db.families(writingSystem);
QCOMPARE(box.model()->rowCount(), list.count());
if (list.count() == 0)
QCOMPARE(box.currentFont(), QFont());
QCOMPARE(spy0.count(), (currentFont != box.currentFont()) ? 1 : 0);
}
// protected void currentFontChanged(QFont const& f)
void tst_QFontComboBox::currentFontChanged()
{
SubQFontComboBox box;
QSignalSpy spy0(&box, SIGNAL(currentFontChanged(QFont const&)));
if (box.model()->rowCount() > 2) {
QTest::keyPress(&box, Qt::Key_Down);
QCOMPARE(spy0.count(), 1);
QFont f( "Sans Serif" );
box.setCurrentFont(f);
QCOMPARE(spy0.count(), 2);
} else
qWarning("Not enough fonts installed on test system. Consider adding some");
}
QTEST_MAIN(tst_QFontComboBox)
#include "tst_qfontcombobox.moc"
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the Qt Toolkit.
**
** $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$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qfontcombobox.h>
class tst_QFontComboBox : public QObject
{
Q_OBJECT
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
private slots:
void qfontcombobox_data();
void qfontcombobox();
void currentFont_data();
void currentFont();
void fontFilters_data();
void fontFilters();
void sizeHint();
void writingSystem_data();
void writingSystem();
void currentFontChanged();
};
// Subclass that exposes the protected functions.
class SubQFontComboBox : public QFontComboBox
{
public:
void call_currentFontChanged(QFont const& f)
{ return SubQFontComboBox::currentFontChanged(f); }
bool call_event(QEvent* e)
{ return SubQFontComboBox::event(e); }
};
// This will be called before the first test function is executed.
// It is only called once.
void tst_QFontComboBox::initTestCase()
{
}
// This will be called after the last test function is executed.
// It is only called once.
void tst_QFontComboBox::cleanupTestCase()
{
}
// This will be called before each test function is executed.
void tst_QFontComboBox::init()
{
}
// This will be called after every test function.
void tst_QFontComboBox::cleanup()
{
}
void tst_QFontComboBox::qfontcombobox_data()
{
}
void tst_QFontComboBox::qfontcombobox()
{
SubQFontComboBox box;
QCOMPARE(box.currentFont(), QFont());
QCOMPARE(box.fontFilters(), QFontComboBox::AllFonts);
box.setCurrentFont(QFont());
box.setFontFilters(QFontComboBox::AllFonts);
box.setWritingSystem(QFontDatabase::Any);
QVERIFY(box.sizeHint() != QSize());
QCOMPARE(box.writingSystem(), QFontDatabase::Any);
box.call_currentFontChanged(QFont());
QEvent event(QEvent::None);
QCOMPARE(box.call_event(&event), false);
}
void tst_QFontComboBox::currentFont_data()
{
QTest::addColumn<QFont>("currentFont");
// Normalize the names
QFont defaultFont;
QFontInfo fi(defaultFont);
defaultFont = QFont(fi.family()); // make sure we have a real font name and not something like 'Sans Serif'.
QTest::newRow("default") << defaultFont;
defaultFont.setPointSize(defaultFont.pointSize() + 10);
QTest::newRow("default2") << defaultFont;
QFontDatabase db;
QStringList list = db.families();
for (int i = 0; i < list.count(); ++i) {
QFont f = QFont(QFontInfo(QFont(list.at(i))).family());
QTest::newRow(qPrintable(list.at(i))) << f;
}
}
// public QFont currentFont() const
void tst_QFontComboBox::currentFont()
{
QFETCH(QFont, currentFont);
SubQFontComboBox box;
QSignalSpy spy0(&box, SIGNAL(currentFontChanged(QFont const&)));
QFont oldCurrentFont = box.currentFont();
box.setCurrentFont(currentFont);
QRegExp foundry(" \\[.*\\]");
if (!box.currentFont().family().contains(foundry)) {
QCOMPARE(box.currentFont(), currentFont);
}
QString boxFontFamily = QFontInfo(box.currentFont()).family();
if (!currentFont.family().contains(foundry))
boxFontFamily.remove(foundry);
QCOMPARE(boxFontFamily, currentFont.family());
if (oldCurrentFont != box.currentFont()) {
//the signal may be emit twice if there is a foundry into brackets
QCOMPARE(spy0.count(),1);
}
}
Q_DECLARE_METATYPE(QFontComboBox::FontFilters)
void tst_QFontComboBox::fontFilters_data()
{
QTest::addColumn<QFontComboBox::FontFilters>("fontFilters");
QTest::newRow("AllFonts")
<< QFontComboBox::FontFilters(QFontComboBox::AllFonts);
QTest::newRow("ScalableFonts")
<< QFontComboBox::FontFilters(QFontComboBox::ScalableFonts);
QTest::newRow("NonScalableFonts")
<< QFontComboBox::FontFilters(QFontComboBox::NonScalableFonts);
QTest::newRow("MonospacedFonts")
<< QFontComboBox::FontFilters(QFontComboBox::MonospacedFonts);
QTest::newRow("ProportionalFonts")
<< QFontComboBox::FontFilters(QFontComboBox::ProportionalFonts);
// combine two
QTest::newRow("ProportionalFonts | NonScalableFonts")
<< QFontComboBox::FontFilters(QFontComboBox::ProportionalFonts | QFontComboBox::NonScalableFonts);
// i.e. all
QTest::newRow("ScalableFonts | NonScalableFonts")
<< QFontComboBox::FontFilters(QFontComboBox::ScalableFonts | QFontComboBox::NonScalableFonts);
}
// public QFontComboBox::FontFilters fontFilters() const
void tst_QFontComboBox::fontFilters()
{
QFETCH(QFontComboBox::FontFilters, fontFilters);
SubQFontComboBox box;
QSignalSpy spy0(&box, SIGNAL(currentFontChanged(QFont const&)));
QFont currentFont = box.currentFont();
box.setFontFilters(fontFilters);
QCOMPARE(box.fontFilters(), fontFilters);
QFontDatabase db;
QStringList list = db.families();
int c = 0;
const int scalableMask = (QFontComboBox::ScalableFonts | QFontComboBox::NonScalableFonts);
const int spacingMask = (QFontComboBox::ProportionalFonts | QFontComboBox::MonospacedFonts);
if((fontFilters & scalableMask) == scalableMask)
fontFilters &= ~scalableMask;
if((fontFilters & spacingMask) == spacingMask)
fontFilters &= ~spacingMask;
for (int i = 0; i < list.count(); ++i) {
if (fontFilters & QFontComboBox::ScalableFonts) {
if (!db.isSmoothlyScalable(list[i]))
continue;
} else if (fontFilters & QFontComboBox::NonScalableFonts) {
if (db.isSmoothlyScalable(list[i]))
continue;
}
if (fontFilters & QFontComboBox::MonospacedFonts) {
if (!db.isFixedPitch(list[i]))
continue;
} else if (fontFilters & QFontComboBox::ProportionalFonts) {
if (db.isFixedPitch(list[i]))
continue;
}
c++;
}
QCOMPARE(box.model()->rowCount(), c);
if (c == 0)
QCOMPARE(box.currentFont(), QFont());
QCOMPARE(spy0.count(), (currentFont != box.currentFont()) ? 1 : 0);
}
// public QSize sizeHint() const
void tst_QFontComboBox::sizeHint()
{
SubQFontComboBox box;
QSize sizeHint = box.QComboBox::sizeHint();
QFontMetrics fm(box.font());
sizeHint.setWidth(qMax(sizeHint.width(), fm.width(QLatin1Char('m'))*14));
QCOMPARE(box.sizeHint(), sizeHint);
}
Q_DECLARE_METATYPE(QFontDatabase::WritingSystem)
void tst_QFontComboBox::writingSystem_data()
{
QTest::addColumn<QFontDatabase::WritingSystem>("writingSystem");
QTest::newRow("Any") << QFontDatabase::Any;
QTest::newRow("Latin") << QFontDatabase::Latin;
QTest::newRow("Lao") << QFontDatabase::Lao;
QTest::newRow("TraditionalChinese") << QFontDatabase::TraditionalChinese;
QTest::newRow("Ogham") << QFontDatabase::Ogham;
QTest::newRow("Runic") << QFontDatabase::Runic;
for (int i = 0; i < 31; ++i)
QTest::newRow("enum") << (QFontDatabase::WritingSystem)i;
}
// public QFontDatabase::WritingSystem writingSystem() const
void tst_QFontComboBox::writingSystem()
{
QFETCH(QFontDatabase::WritingSystem, writingSystem);
SubQFontComboBox box;
QSignalSpy spy0(&box, SIGNAL(currentFontChanged(QFont const&)));
QFont currentFont = box.currentFont();
box.setWritingSystem(writingSystem);
QCOMPARE(box.writingSystem(), writingSystem);
QFontDatabase db;
QStringList list = db.families(writingSystem);
QCOMPARE(box.model()->rowCount(), list.count());
if (list.count() == 0)
QCOMPARE(box.currentFont(), QFont());
QCOMPARE(spy0.count(), (currentFont != box.currentFont()) ? 1 : 0);
}
// protected void currentFontChanged(QFont const& f)
void tst_QFontComboBox::currentFontChanged()
{
SubQFontComboBox box;
QSignalSpy spy0(&box, SIGNAL(currentFontChanged(QFont const&)));
if (box.model()->rowCount() > 2) {
QTest::keyPress(&box, Qt::Key_Down);
QCOMPARE(spy0.count(), 1);
QFont f( "Sans Serif" );
box.setCurrentFont(f);
QCOMPARE(spy0.count(), 2);
} else
qWarning("Not enough fonts installed on test system. Consider adding some");
}
QTEST_MAIN(tst_QFontComboBox)
#include "tst_qfontcombobox.moc"
|
Make unit test more robust
|
Make unit test more robust
Make sure that on systems that have a default font of "Sans Serif" (or
another not really existing font name) the unit test doesn't fail.
Reviewed-By: Simon Hausmann
Reviewed-By: Olivier
|
C++
|
lgpl-2.1
|
pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk
|
0c0fcee493cd0c4ead376a79b875a87526a1c4ea
|
tests/auto/qmessagestore/tst_qmessagestore.cpp
|
tests/auto/qmessagestore/tst_qmessagestore.cpp
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the Qt Messaging Framework.
**
** $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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QObject>
#include <QTest>
#include <QDebug>
#include "qtmessaging.h"
#include "../support/support.h"
//TESTED_CLASS=
//TESTED_FILES=
/*
Unit test for QMessageStore class.
*/
class tst_QMessageStore : public QObject
{
Q_OBJECT
public:
tst_QMessageStore();
virtual ~tst_QMessageStore();
private slots:
void initTestCase();
void cleanup();
void cleanupTestCase();
void testAccount();
};
QTEST_MAIN(tst_QMessageStore)
#include "tst_qmessagestore.moc"
tst_QMessageStore::tst_QMessageStore()
{
}
tst_QMessageStore::~tst_QMessageStore()
{
}
void tst_QMessageStore::initTestCase()
{
Support::clearMessageStore();
}
void tst_QMessageStore::cleanup()
{
}
void tst_QMessageStore::cleanupTestCase()
{
}
void tst_QMessageStore::testAccount()
{
Support::Parameters p;
p.insert("name", "Test Account");
p.insert("fromAddress", "[email protected]");
Support::addAccount(p);
foreach (const QMessageAccount &account, QMessageStore::instance()->queryAccounts()) {
qDebug() << "Account:" << account.name();
}
}
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the Qt Messaging Framework.
**
** $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 either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QObject>
#include <QTest>
#include <QDebug>
#include "qtmessaging.h"
#include "../support/support.h"
//TESTED_CLASS=
//TESTED_FILES=
/*
Unit test for QMessageStore class.
*/
class tst_QMessageStore : public QObject
{
Q_OBJECT
public:
tst_QMessageStore();
virtual ~tst_QMessageStore();
private slots:
void initTestCase();
void cleanup();
void cleanupTestCase();
void testAccount_data();
void testAccount();
};
QTEST_MAIN(tst_QMessageStore)
#include "tst_qmessagestore.moc"
tst_QMessageStore::tst_QMessageStore()
{
}
tst_QMessageStore::~tst_QMessageStore()
{
}
void tst_QMessageStore::initTestCase()
{
Support::clearMessageStore();
}
void tst_QMessageStore::cleanup()
{
}
void tst_QMessageStore::cleanupTestCase()
{
}
void tst_QMessageStore::testAccount_data()
{
QTest::addColumn<QString>("name");
QTest::addColumn<QString>("fromAddress");
QTest::newRow("1") << "Test Account #1" << "[email protected]";
QTest::newRow("2") << "Test Account #2" << "[email protected]";
}
void tst_QMessageStore::testAccount()
{
QFETCH(QString, name);
QFETCH(QString, fromAddress);
Support::Parameters p;
p.insert("name", name);
p.insert("fromAddress", fromAddress);
QMessageAccountId accountId(Support::addAccount(p));
QVERIFY(!(accountId == QMessageAccountId()));
QMessageAccount account(accountId);
QCOMPARE(account.id(), accountId);
QCOMPARE(account.name(), name);
QCOMPARE(account.fromAddress().recipient(), fromAddress);
QCOMPARE(account.fromAddress().type(), QMessageAddress::Email);
QMessageAccountIdList accountIds(QMessageStore::instance()->queryAccounts());
QVERIFY(accountIds.contains(accountId));
}
|
Structure test correctly.
|
Structure test correctly.
|
C++
|
lgpl-2.1
|
qtproject/qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,KDE/android-qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,KDE/android-qt-mobility
|
756ef1f355d088cd093cd0d54cc4ee9ef51c4e3e
|
examples/benchmark/generate_benchmark.cpp
|
examples/benchmark/generate_benchmark.cpp
|
/*
* Copyright 2014 Google Inc. 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 <iostream>
#include <set>
#include <random>
#include <cassert>
#include <fstream>
#include <sstream>
#include <chrono>
using namespace std;
// This is a constant so that we always generate the same file (=> benchmark more repeatable).
unsigned seed = 42;
std::default_random_engine generator(seed);
string getHeaderName(int n) {
ostringstream stream;
stream << "X" << n << ".h";
return stream.str();
}
string getSourceName(int n) {
ostringstream stream;
stream << "X" << n << ".cpp";
return stream.str();
}
string getObjectName(int n) {
ostringstream stream;
stream << "X" << n << ".o";
return stream.str();
}
void add_node(int n, set<int> deps) {
std::string headerName = getHeaderName(n);
std::string sourceName = getSourceName(n);
ofstream headerFile(headerName);
headerFile << "#include <fruit/fruit.h>" << endl << endl;
headerFile << "#ifndef X" << n << "_H" << endl;
headerFile << "#define X" << n << "_H" << endl;
for (auto dep : deps) {
headerFile << "class X" << dep << ";" << endl;
}
headerFile << "struct X" << n << " { INJECT(X" << n << "(";
for (auto i = deps.begin(), i_end = deps.end(); i != i_end; ++i) {
if (i != deps.begin()) {
headerFile << ", ";
}
headerFile << "const X" << *i << "&";
}
headerFile << ")) {} };" << endl;
headerFile << "fruit::Component<X" << n << "> getX" << n << "Component();" << endl;
headerFile << "#endif // X" << n << "_H" << endl;
ofstream sourceFile(sourceName);
sourceFile << "#include \"" << headerName << "\"" << endl << endl;
for (auto dep : deps) {
sourceFile << "#include \"" << getHeaderName(dep) << "\"" << endl;
}
sourceFile << "fruit::Component<X" << n << "> getX" << n << "Component() {" << endl;
sourceFile << " return fruit::createComponent()" << endl;
for (auto dep : deps) {
sourceFile << " .install(getX" << dep << "Component())" << endl;
}
sourceFile << " ;" << endl;
sourceFile << "}" << endl;
}
set<int> get_random_set(set<int>& pool, size_t desired_size) {
assert(desired_size <= pool.size());
set<int> result;
while (result.size() != desired_size) {
std::uniform_int_distribution<int> distribution(0, pool.size() - 1);
int i = distribution(generator);
auto itr = pool.begin();
std::advance(itr, i);
result.insert(*itr);
pool.erase(itr);
}
return result;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cout << "Invalid invocation: " << argv[0];
for (int i = 1; i < argc; i++) {
cout << " " << argv[i];
}
cout << endl;
cout << "Usage: " << argv[0] << " /path/to/compiler path/to/fruit/sources/root" << endl;
return 1;
}
constexpr int num_types_with_no_deps = 91;
constexpr int num_types_with_deps = 10;
constexpr int num_deps = 9;
constexpr int num_loops = 20;
static_assert(num_types_with_no_deps >= num_types_with_deps * num_deps + 1, "Not enough types with no deps");
int num_used_ids = 0;
set<int> toplevel_types;
for (int i = 0; i < num_types_with_no_deps; i++) {
int id = num_used_ids++;
add_node(id, {});
toplevel_types.insert(id);
}
for (int i = 0; i < num_types_with_deps; i++) {
int current_dep_id = num_used_ids++;
auto deps = get_random_set(toplevel_types, num_deps);
toplevel_types.insert(current_dep_id);
add_node(current_dep_id, deps);
}
int toplevel_component = num_used_ids++;
add_node(toplevel_component, toplevel_types);
ofstream mainFile("main.cpp");
mainFile << "#include \"" << getHeaderName(toplevel_component) << "\"" << endl;
mainFile << "#include <ctime>" << endl;
mainFile << "#include <iostream>" << endl;
mainFile << "using namespace std;" << endl;
mainFile << "int main() {" << endl;
mainFile << "clock_t start_time = clock();" << endl;
mainFile << "for (int i = 0; i < " << num_loops << "; i++) {" << endl;
mainFile << "fruit::Injector<X" << toplevel_component << "> injector(getX" << toplevel_component << "Component());" << endl;
mainFile << "injector.get<X" << toplevel_component << "*>();" << endl;
mainFile << "}" << endl;
mainFile << "clock_t end_time = clock();" << endl;
mainFile << "cout << (end_time - start_time) / " << num_loops << " << endl;" << endl;
mainFile << "return 0;" << endl;
mainFile << "}" << endl;
const string compiler = string(argv[1]) + " -std=c++11 -O2 -g -W -Wall -Werror -DNDEBUG -ftemplate-depth=1000 -I" + argv[2] + "/include";
vector<string> fruit_srcs = {"component_storage", "demangle_type_name", "injector_storage"};
ofstream buildFile("build.sh");
buildFile << "#!/bin/bash" << endl;
for (int i = 0; i < num_used_ids; i++) {
buildFile << compiler << " -c " << getSourceName(i) << " -o " << getObjectName(i) << " &" << endl;
if (i % 20 == 0) {
// Avoids having too many parallel processes.
buildFile << "wait || exit 1" << endl;
}
}
buildFile << compiler << " -c main.cpp -o main.o &" << endl;
for (string s : fruit_srcs) {
buildFile << compiler << " -c " << argv[2] << "/src/" << s << ".cpp -o " << s << ".o &" << endl;
}
buildFile << "wait" << endl;
buildFile << compiler << " main.o ";
for (string s : fruit_srcs) {
buildFile << s << ".o ";
}
for (int i = 0; i < num_used_ids; i++) {
buildFile << getObjectName(i) << " ";
}
buildFile << " -o main" << endl;
return 0;
}
|
/*
* Copyright 2014 Google Inc. 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 <iostream>
#include <set>
#include <random>
#include <cassert>
#include <fstream>
#include <sstream>
#include <chrono>
using namespace std;
// This is a constant so that we always generate the same file (=> benchmark more repeatable).
unsigned seed = 42;
std::default_random_engine generator(seed);
string getHeaderName(int n) {
ostringstream stream;
stream << "interface" << n << ".h";
return stream.str();
}
string getSourceName(int n) {
ostringstream stream;
stream << "interface" << n << ".cpp";
return stream.str();
}
string getObjectName(int n) {
ostringstream stream;
stream << "interface" << n << ".o";
return stream.str();
}
void add_node(int n, set<int> deps) {
std::string headerName = getHeaderName(n);
std::string sourceName = getSourceName(n);
ofstream headerFile(headerName);
headerFile << "#include <fruit/fruit.h>" << endl << endl;
headerFile << "#ifndef INTERFACE" << n << "_H" << endl;
headerFile << "#define INTERFACE" << n << "_H" << endl;
headerFile << "struct Interface" << n << " {};" << endl;
headerFile << "fruit::Component<Interface" << n << "> getInterface" << n << "Component();" << endl;
headerFile << "#endif // INTERFACE" << n << "_H" << endl;
ofstream sourceFile(sourceName);
sourceFile << "#include \"" << headerName << "\"" << endl << endl;
for (auto dep : deps) {
sourceFile << "#include \"" << getHeaderName(dep) << "\"" << endl;
}
sourceFile << "struct X" << n << " : public Interface" << n << " { INJECT(X" << n << "(";
for (auto i = deps.begin(), i_end = deps.end(); i != i_end; ++i) {
if (i != deps.begin()) {
sourceFile << ", ";
}
sourceFile << "Interface" << *i << "*";
}
sourceFile << ")) {} };" << endl;
sourceFile << "fruit::Component<Interface" << n << "> getInterface" << n << "Component() {" << endl;
sourceFile << " return fruit::createComponent()" << endl;
for (auto dep : deps) {
sourceFile << " .install(getInterface" << dep << "Component())" << endl;
}
sourceFile << " .bind<Interface" << n << ", " << "X" << n << ">();" << endl;
sourceFile << "}" << endl;
}
set<int> get_random_set(set<int>& pool, size_t desired_size) {
assert(desired_size <= pool.size());
set<int> result;
while (result.size() != desired_size) {
std::uniform_int_distribution<int> distribution(0, pool.size() - 1);
int i = distribution(generator);
auto itr = pool.begin();
std::advance(itr, i);
result.insert(*itr);
pool.erase(itr);
}
return result;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cout << "Invalid invocation: " << argv[0];
for (int i = 1; i < argc; i++) {
cout << " " << argv[i];
}
cout << endl;
cout << "Usage: " << argv[0] << " /path/to/compiler path/to/fruit/sources/root" << endl;
return 1;
}
constexpr int num_types_with_no_deps = 91;
constexpr int num_types_with_deps = 10;
constexpr int num_deps = 9;
constexpr int num_loops = 20;
static_assert(num_types_with_no_deps >= num_types_with_deps * num_deps + 1, "Not enough types with no deps");
int num_used_ids = 0;
set<int> toplevel_types;
for (int i = 0; i < num_types_with_no_deps; i++) {
int id = num_used_ids++;
add_node(id, {});
toplevel_types.insert(id);
}
for (int i = 0; i < num_types_with_deps; i++) {
int current_dep_id = num_used_ids++;
auto deps = get_random_set(toplevel_types, num_deps);
toplevel_types.insert(current_dep_id);
add_node(current_dep_id, deps);
}
int toplevel_component = num_used_ids++;
add_node(toplevel_component, toplevel_types);
ofstream mainFile("main.cpp");
mainFile << "#include \"" << getHeaderName(toplevel_component) << "\"" << endl;
mainFile << "#include <ctime>" << endl;
mainFile << "#include <iostream>" << endl;
mainFile << "using namespace std;" << endl;
mainFile << "int main() {" << endl;
mainFile << "fruit::Component<Interface" << toplevel_component << "> component(getInterface" << toplevel_component << "Component());" << endl;
mainFile << "clock_t start_time = clock();" << endl;
mainFile << "for (int i = 0; i < " << num_loops << "; i++) {" << endl;
mainFile << "fruit::Injector<Interface" << toplevel_component << "> injector(component);" << endl;
mainFile << "injector.get<Interface" << toplevel_component << "*>();" << endl;
mainFile << "}" << endl;
mainFile << "clock_t end_time = clock();" << endl;
mainFile << "cout << (end_time - start_time) / " << num_loops << " << endl;" << endl;
mainFile << "return 0;" << endl;
mainFile << "}" << endl;
const string compiler = string(argv[1]) + " -std=c++11 -O2 -g -W -Wall -Werror -DNDEBUG -ftemplate-depth=1000 -I" + argv[2] + "/include";
vector<string> fruit_srcs = {"component_storage", "demangle_type_name", "injector_storage"};
ofstream buildFile("build.sh");
buildFile << "#!/bin/bash" << endl;
for (int i = 0; i < num_used_ids; i++) {
buildFile << compiler << " -c " << getSourceName(i) << " -o " << getObjectName(i) << " &" << endl;
if (i % 20 == 0) {
// Avoids having too many parallel processes.
buildFile << "wait || exit 1" << endl;
}
}
buildFile << compiler << " -c main.cpp -o main.o &" << endl;
for (string s : fruit_srcs) {
buildFile << compiler << " -c " << argv[2] << "/src/" << s << ".cpp -o " << s << ".o &" << endl;
}
buildFile << "wait" << endl;
buildFile << compiler << " main.o ";
for (string s : fruit_srcs) {
buildFile << s << ".o ";
}
for (int i = 0; i < num_used_ids; i++) {
buildFile << getObjectName(i) << " ";
}
buildFile << " -o main" << endl;
return 0;
}
|
Change the benchmark to use both registerConstructor and bind in each component.
|
Change the benchmark to use both registerConstructor and bind in each component.
|
C++
|
apache-2.0
|
google/fruit,d/fruit,d/fruit,google/fruit,google/fruit,d/fruit
|
d70b7c711955d7ef238575e6a4ad074f476695a5
|
mjolnir/potential/local/FlexibleLocalAnglePotential.hpp
|
mjolnir/potential/local/FlexibleLocalAnglePotential.hpp
|
#ifndef MJOLNIR_FLEXIBLE_LOCAL_ANGLE_POTENTIAL
#define MJOLNIR_FLEXIBLE_LOCAL_ANGLE_POTENTIAL
#include <array>
#include <algorithm>
#include <cassert>
#include <cmath>
namespace mjolnir
{
template<typename T> class System;
/*! @brief Default FLP angle *
* NOTE: It assumes that each theta value in histogram is same as default. */
template<typename traitsT>
class FlexibleLocalAnglePotential
{
public:
typedef traitsT traits_type;
typedef System<traits_type> system_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
constexpr static real_type max_force = 30.0;
constexpr static real_type min_force = -30.0;
public:
FlexibleLocalAnglePotential(const real_type k,
const std::array<real_type, 10>& term1,
const std::array<real_type, 10>& term2)
: min_theta(1.30900), max_theta(2.87979),
dtheta((max_theta - min_theta) / 9.0), inv_dtheta(1. / dtheta), k_(k),
thetas{{1.30900, 1.48353, 1.65806, 1.83260, 2.00713,
2.18166, 2.35619, 2.53073, 2.70526, 2.87979}},
term1_(term1), term2_(term2)
{
// from cafemol3/mloop_flexible_local.F90
real_type th = thetas[0];
const real_type center_th = (max_theta + min_theta) * 0.5;
min_theta_ene = min_energy = spline_interpolate(min_theta);
max_theta_ene = spline_interpolate(max_theta - 1e-4);
while(th < max_theta)
{
const real_type energy = spline_interpolate(th);
const real_type force = spline_derivative(th);
min_energy = std::min(min_energy, energy);
if(force < min_force)
{
min_theta = th;
min_theta_ene = energy;
}
if(max_force < force && center_th < th && max_theta == thetas[9])
{
max_theta = th;
max_theta_ene = energy;
}
th += 1e-4;
}
}
~FlexibleLocalAnglePotential() = default;
real_type potential(const real_type th) const noexcept
{
if(th < min_theta)
{
return ((min_force * th + min_theta_ene - min_force * min_theta) -
min_energy) * k_;
}
else if(th >= max_theta)
{
return ((max_force * th + max_theta_ene - max_force * max_theta) -
min_energy) * k_;
}
else
return k_ * (spline_interpolate(th) - min_energy);
}
real_type derivative(const real_type th) const noexcept
{
if(th < min_theta) return min_force;
else if(th >= max_theta) return max_force;
else return spline_derivative(th) * k_;
}
void update(const system_type&, const real_type) const noexcept {return;}
const char* name() const noexcept {return "FlexibleLocalAngle";}
private:
real_type spline_interpolate(const real_type th) const noexcept
{
const std::size_t n = std::floor((th - min_theta) * inv_dtheta);
assert(n < 9);
const real_type a = (thetas[n+1] - th) * inv_dtheta;
const real_type b = (th - thetas[n ]) * inv_dtheta;
const real_type e1 = a * term1_[n] + b * term1_[n+1];
const real_type e2 =
((a * a * a - a) * term2_[n] + (b * b * b - b) * term2_[n+1]) *
dtheta * dtheta / 6.;
return e1 + e2;
}
real_type spline_derivative(const real_type th) const noexcept
{
const std::size_t n = std::floor((th - min_theta) * inv_dtheta);
assert(n < 9);
const real_type a = (thetas[n+1] - th) * inv_dtheta;
const real_type b = (th - thetas[n ]) * inv_dtheta;
const real_type f1 = (term1_[n+1] - term1_[n]) * inv_dtheta;
const real_type f2 = (
(3. * b * b - 1.) * term2_[n+1] - (3. * a * a - 1.) * term2_[n]
) * dtheta / 6.;
return f1 + f2;
}
private:
real_type min_energy;
real_type min_theta_ene;
real_type max_theta_ene;
real_type min_theta;
real_type max_theta;
real_type dtheta;
real_type inv_dtheta;
real_type k_;
std::array<real_type, 10> thetas;
std::array<real_type, 10> term1_;
std::array<real_type, 10> term2_;
};
} // mjolnir
#endif // MJOLNIR_FLEXIBLE_LOCAL_ANGLE_POTENTIAL
|
#ifndef MJOLNIR_FLEXIBLE_LOCAL_ANGLE_POTENTIAL
#define MJOLNIR_FLEXIBLE_LOCAL_ANGLE_POTENTIAL
#include <array>
#include <algorithm>
#include <cassert>
#include <cmath>
namespace mjolnir
{
template<typename T> class System;
/*! @brief Default FLP angle *
* NOTE: It assumes that each theta value in histogram is same as default. */
template<typename traitsT>
class FlexibleLocalAnglePotential
{
public:
typedef traitsT traits_type;
typedef System<traits_type> system_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
constexpr static real_type max_force = 30.0;
constexpr static real_type min_force = -30.0;
public:
FlexibleLocalAnglePotential(const real_type k,
const std::array<real_type, 10>& term1,
const std::array<real_type, 10>& term2)
: min_theta(1.30900), max_theta(2.87979),
dtheta((max_theta - min_theta) / 9.0), inv_dtheta(1. / dtheta), k_(k),
thetas{{1.30900, 1.48353, 1.65806, 1.83260, 2.00713,
2.18166, 2.35619, 2.53073, 2.70526, 2.87979}},
term1_(term1), term2_(term2)
{
// from cafemol3/mloop_flexible_local.F90
real_type th = thetas[0];
const real_type center_th = (max_theta + min_theta) * 0.5;
min_theta_ene = min_energy = spline_interpolate(min_theta);
max_theta_ene = spline_interpolate(max_theta - 1e-4);
while(th < max_theta)
{
const real_type energy = spline_interpolate(th);
const real_type force = spline_derivative(th);
min_energy = std::min(min_energy, energy);
if(force < min_force)
{
min_theta = th;
min_theta_ene = energy;
}
if(max_force < force && center_th < th && max_theta == thetas[9])
{
max_theta = th;
max_theta_ene = energy;
}
th += 1e-4;
}
}
~FlexibleLocalAnglePotential() = default;
real_type potential(const real_type th) const noexcept
{
if(th < min_theta)
{
return ((min_force * th + min_theta_ene - min_force * min_theta) -
min_energy) * k_;
}
else if(th >= max_theta)
{
return ((max_force * th + max_theta_ene - max_force * max_theta) -
min_energy) * k_;
}
else
{
return k_ * (spline_interpolate(th) - min_energy);
}
}
real_type derivative(const real_type th) const noexcept
{
if(th < min_theta) {return min_force;}
else if(th >= max_theta) {return max_force;}
else {return spline_derivative(th) * k_;}
}
void update(const system_type&, const real_type) const noexcept {return;}
const char* name() const noexcept {return "FlexibleLocalAngle";}
private:
real_type spline_interpolate(const real_type th) const noexcept
{
const std::size_t n = std::floor((th - min_theta) * inv_dtheta);
assert(n < 9);
const real_type a = (thetas[n+1] - th) * inv_dtheta;
const real_type b = (th - thetas[n ]) * inv_dtheta;
const real_type e1 = a * term1_[n] + b * term1_[n+1];
const real_type e2 =
((a * a * a - a) * term2_[n] + (b * b * b - b) * term2_[n+1]) *
dtheta * dtheta / 6.;
return e1 + e2;
}
real_type spline_derivative(const real_type th) const noexcept
{
const std::size_t n = std::floor((th - min_theta) * inv_dtheta);
assert(n < 9);
const real_type a = (thetas[n+1] - th) * inv_dtheta;
const real_type b = (th - thetas[n ]) * inv_dtheta;
const real_type f1 = (term1_[n+1] - term1_[n]) * inv_dtheta;
const real_type f2 = (
(3. * b * b - 1.) * term2_[n+1] - (3. * a * a - 1.) * term2_[n]
) * dtheta / 6.;
return f1 + f2;
}
private:
real_type min_energy;
real_type min_theta_ene;
real_type max_theta_ene;
real_type min_theta;
real_type max_theta;
real_type dtheta;
real_type inv_dtheta;
real_type k_;
std::array<real_type, 10> thetas;
std::array<real_type, 10> term1_;
std::array<real_type, 10> term2_;
};
} // mjolnir
#endif // MJOLNIR_FLEXIBLE_LOCAL_ANGLE_POTENTIAL
|
write code block explicitly
|
nit: write code block explicitly
|
C++
|
mit
|
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
|
7949f6430f548e56f55972cc04ce5deb492006d3
|
match.hpp
|
match.hpp
|
/*
cpp-match-case - Code covered by the MIT License
Author: mutouyun (http://darkc.at)
*/
#pragma once
#include "capo/preprocessor.hpp"
#include <utility> // std::forward
#include <regex> // std::regex, std::regex_match
#include <string> // std::string
#include <tuple> // std::tuple
#include <type_traits> // std::add_pointer, std::remove_reference, ...
#include <cstddef> // size_t
namespace match {
// To remove reference and cv qualification from a type.
template <typename T>
struct underlying : std::remove_cv<typename std::remove_reference<T>::type> {};
// The helper meta-predicate capable of distinguishing all our patterns.
template <typename T>
struct is_pattern : std::false_type {};
template <typename T>
struct pattern_checker : is_pattern<typename underlying<T>::type> {};
/*
* Constant pattern
*/
template <typename T>
struct constant
{
const T& t_;
template <typename U>
bool operator()(U&& tar) const
{
return (std::forward<U>(tar) == t_);
}
};
template <typename T>
struct is_pattern<constant<T>> : std::true_type {};
/*
* Variable pattern
*/
template <typename T>
struct variable
{
T& t_;
template <typename U>
bool operator()(U&& tar) const
{
t_ = std::forward<U>(tar);
return (t_ == std::forward<U>(tar));
}
};
template <typename T>
struct is_pattern<variable<T>> : std::true_type {};
/*
* Wildcard pattern
*/
struct wildcard
{
template <typename U>
bool operator()(U&&) const
{
return true;
}
};
template <>
struct is_pattern<wildcard> : std::true_type{};
#if defined(_MSC_VER)
__pragma(warning(suppress:4100)) static wildcard _;
#elif defined(__GNUC__)
__attribute__((__unused__)) static wildcard _;
#else
static wildcard _;
#endif
/*
* Predicate pattern, for lambda-expressions or other callable objects.
*/
template <typename F>
struct predicate
{
F judge_;
template <typename U>
bool operator()(U&& tar) const
{
return !!(this->judge_(std::forward<U>(tar)));
}
};
template <typename T>
struct is_pattern<predicate<T>> : std::true_type {};
struct is_functor_checker_
{
template <typename T> static std::true_type check(decltype(&T::operator())*);
template <typename T> static std::false_type check(...);
};
template <typename T>
struct is_functor : decltype(is_functor_checker_::check<T>(nullptr)) {};
template <typename T, bool = std::is_function<typename std::remove_pointer<T>::type>::value ||
is_functor<T>::value>
struct is_closure_;
template <typename T> struct is_closure_<T, true> : std::true_type {};
template <typename T> struct is_closure_<T, false> : std::false_type {};
template <typename T>
struct is_closure : is_closure_<typename underlying<T>::type> {};
template <typename T>
inline auto converter(T&& arg)
-> typename std::enable_if<is_closure<T>::value, predicate<T&&>>::type
{
return { std::forward<T>(arg) };
}
/*
* Regular expression pattern
*/
struct regex
{
std::regex r_;
template <typename T>
regex(T&& r)
: r_(std::forward<T>(r))
{}
template <typename U>
bool operator()(U&& tar) const
{
return std::regex_match(std::forward<U>(tar), r_);
}
};
template <>
struct is_pattern<regex> : std::true_type{};
#define Regex(...) match::regex { __VA_ARGS__ }
/*
* Type pattern
*/
template <typename T> inline const T* addr(const T* t) { return t; }
template <typename T> inline T* addr( T* t) { return t; }
template <typename T> inline const T* addr(const T& t) { return std::addressof(t); }
template <typename T> inline T* addr( T& t) { return std::addressof(t); }
template <typename T, bool = std::is_polymorphic<typename underlying<T>::type>::value>
struct type;
template <>
struct type<wildcard, false>
{
template <typename U>
bool operator()(U&&) const
{
return true;
}
};
template <typename T>
struct type<T, false>
{
template <typename U>
bool operator()(const volatile U&) const
{
return std::is_same<typename underlying<T>::type, U>::value;
}
};
template <typename T>
struct type<T, true>
{
template <typename U>
bool operator()(U&& tar) const
{
using p_t = typename underlying<T>::type const volatile *;
return (dynamic_cast<p_t>(addr(tar)) != nullptr);
}
};
template <typename T, bool Cond>
struct is_pattern<type<T, Cond>> : std::true_type{};
#define Type(...) match::type<__VA_ARGS__> {}
/*
* Constructor pattern
*/
template <typename...>
struct model;
template <>
struct model<> {};
template <typename T1, typename... T>
struct model<T1, T...> : model<T...> { T1 m_; };
template <typename Tp, size_t N>
struct model_strip;
template <typename T1, typename... T, size_t N>
struct model_strip<model<T1, T...>, N> : model_strip<model<T...>, N - 1> {};
template <typename T1, typename... T>
struct model_strip<model<T1, T...>, 0> { using type = model<T1, T...>; };
template <typename Tp>
struct model_strip<Tp, 0> { using type = Tp; };
template <typename Tp>
struct model_length : std::integral_constant<size_t, 0> {};
template <typename... T>
struct model_length<model<T...>> : std::integral_constant<size_t, sizeof...(T)> {};
template <typename T, typename U>
struct model_append { using type = model<T, U>; };
template <typename... T, typename U>
struct model_append<model<T...>, U> { using type = model<T..., U>; };
template <typename Tp>
struct model_reverse { using type = Tp; };
template <typename T1, typename... T>
struct model_reverse<model<T1, T...>>
{
using head = typename model_reverse<model<T...>>::type;
using type = typename model_append<head, T1>::type;
};
template <typename... T>
struct layout
{
using model_t = typename model_reverse<model<T...>>::type;
template <typename U, typename V>
struct rep;
template <typename U, typename V>
struct rep<U&, V> { using type = V&; };
template <typename U, typename V>
struct rep<U&&, V> { using type = V&&; };
template <typename U, typename V>
struct rep<const U&, V> { using type = const V&; };
template <typename U, typename V>
struct rep<const U&&, V> { using type = const V&&; };
template <size_t N, typename U>
static auto & get(U&& tar)
{
decltype(auto) mm = reinterpret_cast<typename rep<U&&, model_t>::type>(tar);
return static_cast<typename model_strip<model_t, model_length<model_t>::value - N - 1>::type &>(mm).m_;
}
};
template <class Bind>
struct bindings_base
{
template <size_t N, typename T, typename U>
static auto apply(const T&, U&&)
-> typename std::enable_if<(std::tuple_size<T>::value <= N), bool>::type
{
return true;
}
template <size_t N, typename T, typename U>
static auto apply(const T& tp, U&& tar)
-> typename std::enable_if<(std::tuple_size<T>::value > N), bool>::type
{
using layout_t = typename Bind::layout_t;
if ( std::get<N>(tp)(layout_t::template get<N>(tar)) )
{
return apply<N + 1>(tp, std::forward<U>(tar));
}
return false;
}
template <typename T, typename U>
static auto apply(const T& tp, U&& tar)
-> typename std::enable_if<std::is_pointer<typename underlying<U>::type>::value, bool>::type
{
return apply<0>(tp, *std::forward<U>(tar));
}
template <typename T, typename U>
static auto apply(const T& tp, U&& tar)
-> typename std::enable_if<!std::is_pointer<typename underlying<U>::type>::value, bool>::type
{
return apply<0>(tp, std::forward<U>(tar));
}
};
template <class C>
struct bindings;
template <typename C, typename... T>
struct constructor : type<C>
{
std::tuple<T...> tp_;
template <typename... U>
constructor(U&&... args)
: tp_(std::forward<U>(args)...)
{}
template <typename U>
bool operator()(U&& tar) const
{
if ( type<C>::operator()(std::forward<U>(tar)) )
{
return bindings<typename underlying<U>::type>::apply(tp_, std::forward<U>(tar));
}
return false;
}
};
template <typename C, typename... T>
struct is_pattern<constructor<C, T...>> : std::true_type{};
#define MATCH_REGIST_TYPE(TYPE, ...) \
namespace match \
{ \
template <> struct bindings<TYPE> : bindings_base<bindings<TYPE>> \
{ \
using layout_t = layout<__VA_ARGS__>; \
}; \
template <> struct bindings<TYPE*> : bindings<TYPE> {}; \
}
/*
* Sequence pattern
*/
template <typename... T>
struct sequence
{
std::tuple<T...> tp_;
template <typename... U>
sequence(U&&... args)
: tp_(std::forward<U>(args)...)
{}
template <size_t N, typename U, typename It>
auto apply(U&&, It&&) const
-> typename std::enable_if<(sizeof...(T) <= N), bool>::type
{
return true;
}
template <size_t N, typename U, typename It>
auto apply(U&& tar, It&& it) const
-> typename std::enable_if<(sizeof...(T) > N), bool>::type
{
if ( it == tar.end() ) return false;
if ( std::get<N>(tp_)(*it) ) return apply<N + 1>(std::forward<U>(tar), ++it);
return false;
}
template <typename U>
bool operator()(U&& tar) const
{
return apply<0>(std::forward<U>(tar), tar.begin());
}
};
template <typename... T>
struct is_pattern<sequence<T...>> : std::true_type{};
/*
* "filter" is a common function used to provide convenience to the users by converting
* constant values into constant patterns and regular variables into variable patterns.
* If the users defined a suitable converter for a specific type, the filter would choose
* the custom converter for wrapping that variable of the type.
*/
void converter(...);
template <typename T>
inline auto filter(T&& arg)
-> typename std::enable_if<pattern_checker<T>::value, T&&>::type
{
return std::forward<T>(arg);
}
template <typename T>
inline auto filter(const T& arg)
-> typename std::enable_if<!pattern_checker<T>::value &&
std::is_same<decltype(converter(arg)), void>::value,
constant<T>>::type
{
return { arg };
}
template <typename T>
inline auto filter(T& arg)
-> typename std::enable_if<!pattern_checker<T>::value &&
std::is_same<decltype(converter(arg)), void>::value,
variable<T>>::type
{
return { arg };
}
template <typename T>
inline auto filter(T&& arg)
-> typename std::enable_if<!pattern_checker<T>::value &&
!std::is_same<decltype(converter(std::forward<T>(arg))), void>::value,
decltype(converter(std::forward<T>(arg)))>::type
{
return converter(std::forward<T>(arg));
}
/*
* Here is a part of the constructor & sequence pattern.
* I have to implement it here, because gcc needs the filter be declared before it.
*/
template <typename T = wildcard, typename... P>
inline auto C(P&&... args)
-> constructor<T, decltype(filter(std::forward<P>(args)))...>
{
return { filter(std::forward<P>(args))... };
}
template <typename... P>
inline auto S(P&&... args)
-> sequence<decltype(filter(std::forward<P>(args)))...>
{
return { filter(std::forward<P>(args))... };
}
} // namespace match
#define Match(...) \
{ \
auto target_ = std::forward_as_tuple(__VA_ARGS__); \
if (false)
#define MATCH_CASE_ARG_(N, ...) && ( match::filter( CAPO_PP_A_(N, __VA_ARGS__) )( std::get<N - 1>(target_) ) )
#define P(...) ( true CAPO_PP_REPEAT_(CAPO_PP_COUNT_(__VA_ARGS__), MATCH_CASE_ARG_, __VA_ARGS__) )
#define With(...) \
} else if (__VA_ARGS__) {
#define Case(...) With( P(__VA_ARGS__) )
#define Otherwise() \
} else {
#define EndMatch \
}
|
/*
cpp-match-case - Code covered by the MIT License
Author: mutouyun (http://darkc.at)
*/
#pragma once
#include "capo/preprocessor.hpp"
#include <utility> // std::forward
#include <regex> // std::regex, std::regex_match
#include <string> // std::string
#include <tuple> // std::tuple
#include <type_traits> // std::add_pointer, std::remove_reference, ...
#include <cstddef> // size_t
namespace match {
// To remove reference and cv qualification from a type.
template <typename T>
struct underlying : std::remove_cv<typename std::remove_reference<T>::type> {};
// The helper meta-predicate capable of distinguishing all our patterns.
template <typename T>
struct is_pattern : std::false_type {};
template <typename T>
struct pattern_checker : is_pattern<typename underlying<T>::type> {};
/*
* Constant pattern
*/
template <typename T>
struct constant
{
const T& t_;
template <typename U>
bool operator()(U&& tar) const
{
return (std::forward<U>(tar) == t_);
}
};
template <typename T>
struct is_pattern<constant<T>> : std::true_type {};
/*
* Variable pattern
*/
template <typename T>
struct variable
{
T& t_;
template <typename U>
bool operator()(U&& tar) const
{
t_ = std::forward<U>(tar);
return (t_ == std::forward<U>(tar));
}
};
template <typename T>
struct is_pattern<variable<T>> : std::true_type {};
/*
* Wildcard pattern
*/
struct wildcard
{
template <typename U>
bool operator()(U&&) const
{
return true;
}
};
constexpr wildcard _;
template <>
struct is_pattern<wildcard> : std::true_type{};
/*
* Predicate pattern, for lambda-expressions or other callable objects.
*/
template <typename F>
struct predicate
{
F judge_;
template <typename U>
bool operator()(U&& tar) const
{
return !!(this->judge_(std::forward<U>(tar)));
}
};
template <typename T>
struct is_pattern<predicate<T>> : std::true_type {};
struct is_functor_checker_
{
template <typename T> static std::true_type check(decltype(&T::operator())*);
template <typename T> static std::false_type check(...);
};
template <typename T>
struct is_functor : decltype(is_functor_checker_::check<T>(nullptr)) {};
template <typename T, bool = std::is_function<typename std::remove_pointer<T>::type>::value ||
is_functor<T>::value>
struct is_closure_;
template <typename T> struct is_closure_<T, true> : std::true_type {};
template <typename T> struct is_closure_<T, false> : std::false_type {};
template <typename T>
struct is_closure : is_closure_<typename underlying<T>::type> {};
template <typename T>
inline auto converter(T&& arg)
-> typename std::enable_if<is_closure<T>::value, predicate<T&&>>::type
{
return { std::forward<T>(arg) };
}
/*
* Regular expression pattern
*/
struct regex
{
std::regex r_;
template <typename T>
regex(T&& r)
: r_(std::forward<T>(r))
{}
template <typename U>
bool operator()(U&& tar) const
{
return std::regex_match(std::forward<U>(tar), r_);
}
};
template <>
struct is_pattern<regex> : std::true_type{};
#define Regex(...) match::regex { __VA_ARGS__ }
/*
* Type pattern
*/
template <typename T> inline const T* addr(const T* t) { return t; }
template <typename T> inline T* addr( T* t) { return t; }
template <typename T> inline const T* addr(const T& t) { return std::addressof(t); }
template <typename T> inline T* addr( T& t) { return std::addressof(t); }
template <typename T, bool = std::is_polymorphic<typename underlying<T>::type>::value>
struct type;
template <>
struct type<wildcard, false>
{
template <typename U>
bool operator()(U&&) const
{
return true;
}
};
template <typename T>
struct type<T, false>
{
template <typename U>
bool operator()(const volatile U&) const
{
return std::is_same<typename underlying<T>::type, U>::value;
}
};
template <typename T>
struct type<T, true>
{
template <typename U>
bool operator()(U&& tar) const
{
using p_t = typename underlying<T>::type const volatile *;
return (dynamic_cast<p_t>(addr(tar)) != nullptr);
}
};
template <typename T, bool Cond>
struct is_pattern<type<T, Cond>> : std::true_type{};
#define Type(...) match::type<__VA_ARGS__> {}
/*
* Constructor pattern
*/
template <typename...>
struct model;
template <>
struct model<> {};
template <typename T1, typename... T>
struct model<T1, T...> : model<T...> { T1 m_; };
template <typename Tp, size_t N>
struct model_strip;
template <typename T1, typename... T, size_t N>
struct model_strip<model<T1, T...>, N> : model_strip<model<T...>, N - 1> {};
template <typename T1, typename... T>
struct model_strip<model<T1, T...>, 0> { using type = model<T1, T...>; };
template <typename Tp>
struct model_strip<Tp, 0> { using type = Tp; };
template <typename Tp>
struct model_length : std::integral_constant<size_t, 0> {};
template <typename... T>
struct model_length<model<T...>> : std::integral_constant<size_t, sizeof...(T)> {};
template <typename T, typename U>
struct model_append { using type = model<T, U>; };
template <typename... T, typename U>
struct model_append<model<T...>, U> { using type = model<T..., U>; };
template <typename Tp>
struct model_reverse { using type = Tp; };
template <typename T1, typename... T>
struct model_reverse<model<T1, T...>>
{
using head = typename model_reverse<model<T...>>::type;
using type = typename model_append<head, T1>::type;
};
template <typename... T>
struct layout
{
using model_t = typename model_reverse<model<T...>>::type;
template <typename U, typename V>
struct rep;
template <typename U, typename V>
struct rep<U&, V> { using type = V&; };
template <typename U, typename V>
struct rep<U&&, V> { using type = V&&; };
template <typename U, typename V>
struct rep<const U&, V> { using type = const V&; };
template <typename U, typename V>
struct rep<const U&&, V> { using type = const V&&; };
template <size_t N, typename U>
static auto & get(U&& tar)
{
decltype(auto) mm = reinterpret_cast<typename rep<U&&, model_t>::type>(tar);
return static_cast<typename model_strip<model_t, model_length<model_t>::value - N - 1>::type &>(mm).m_;
}
};
template <class Bind>
struct bindings_base
{
template <size_t N, typename T, typename U>
static auto apply(const T&, U&&)
-> typename std::enable_if<(std::tuple_size<T>::value <= N), bool>::type
{
return true;
}
template <size_t N, typename T, typename U>
static auto apply(const T& tp, U&& tar)
-> typename std::enable_if<(std::tuple_size<T>::value > N), bool>::type
{
using layout_t = typename Bind::layout_t;
if ( std::get<N>(tp)(layout_t::template get<N>(tar)) )
{
return apply<N + 1>(tp, std::forward<U>(tar));
}
return false;
}
template <typename T, typename U>
static auto apply(const T& tp, U&& tar)
-> typename std::enable_if<std::is_pointer<typename underlying<U>::type>::value, bool>::type
{
return apply<0>(tp, *std::forward<U>(tar));
}
template <typename T, typename U>
static auto apply(const T& tp, U&& tar)
-> typename std::enable_if<!std::is_pointer<typename underlying<U>::type>::value, bool>::type
{
return apply<0>(tp, std::forward<U>(tar));
}
};
template <class C>
struct bindings;
template <typename C, typename... T>
struct constructor : type<C>
{
std::tuple<T...> tp_;
template <typename... U>
constructor(U&&... args)
: tp_(std::forward<U>(args)...)
{}
template <typename U>
bool operator()(U&& tar) const
{
if ( type<C>::operator()(std::forward<U>(tar)) )
{
return bindings<typename underlying<U>::type>::apply(tp_, std::forward<U>(tar));
}
return false;
}
};
template <typename C, typename... T>
struct is_pattern<constructor<C, T...>> : std::true_type{};
#define MATCH_REGIST_TYPE(TYPE, ...) \
namespace match \
{ \
template <> struct bindings<TYPE> : bindings_base<bindings<TYPE>> \
{ \
using layout_t = layout<__VA_ARGS__>; \
}; \
template <> struct bindings<TYPE*> : bindings<TYPE> {}; \
}
/*
* Sequence pattern
*/
template <typename... T>
struct sequence
{
std::tuple<T...> tp_;
template <typename... U>
sequence(U&&... args)
: tp_(std::forward<U>(args)...)
{}
template <size_t N, typename U, typename It>
auto apply(U&&, It&&) const
-> typename std::enable_if<(sizeof...(T) <= N), bool>::type
{
return true;
}
template <size_t N, typename U, typename It>
auto apply(U&& tar, It&& it) const
-> typename std::enable_if<(sizeof...(T) > N), bool>::type
{
if ( it == tar.end() ) return false;
if ( std::get<N>(tp_)(*it) ) return apply<N + 1>(std::forward<U>(tar), ++it);
return false;
}
template <typename U>
bool operator()(U&& tar) const
{
return apply<0>(std::forward<U>(tar), tar.begin());
}
};
template <typename... T>
struct is_pattern<sequence<T...>> : std::true_type{};
/*
* "filter" is a common function used to provide convenience to the users by converting
* constant values into constant patterns and regular variables into variable patterns.
* If the users defined a suitable converter for a specific type, the filter would choose
* the custom converter for wrapping that variable of the type.
*/
void converter(...);
template <typename T>
inline auto filter(T&& arg)
-> typename std::enable_if<pattern_checker<T>::value, T&&>::type
{
return std::forward<T>(arg);
}
template <typename T>
inline auto filter(const T& arg)
-> typename std::enable_if<!pattern_checker<T>::value &&
std::is_same<decltype(converter(arg)), void>::value,
constant<T>>::type
{
return { arg };
}
template <typename T>
inline auto filter(T& arg)
-> typename std::enable_if<!pattern_checker<T>::value &&
std::is_same<decltype(converter(arg)), void>::value,
variable<T>>::type
{
return { arg };
}
template <typename T>
inline auto filter(T&& arg)
-> typename std::enable_if<!pattern_checker<T>::value &&
!std::is_same<decltype(converter(std::forward<T>(arg))), void>::value,
decltype(converter(std::forward<T>(arg)))>::type
{
return converter(std::forward<T>(arg));
}
/*
* Here is a part of the constructor & sequence pattern.
* I have to implement it here, because gcc needs the filter be declared before it.
*/
template <typename T = wildcard, typename... P>
inline auto C(P&&... args)
-> constructor<T, decltype(filter(std::forward<P>(args)))...>
{
return { filter(std::forward<P>(args))... };
}
template <typename... P>
inline auto S(P&&... args)
-> sequence<decltype(filter(std::forward<P>(args)))...>
{
return { filter(std::forward<P>(args))... };
}
} // namespace match
#define Match(...) \
{ \
auto target_ = std::forward_as_tuple(__VA_ARGS__); \
if (false)
#define MATCH_CASE_ARG_(N, ...) && ( match::filter( CAPO_PP_A_(N, __VA_ARGS__) )( std::get<N - 1>(target_) ) )
#define P(...) ( true CAPO_PP_REPEAT_(CAPO_PP_COUNT_(__VA_ARGS__), MATCH_CASE_ARG_, __VA_ARGS__) )
#define With(...) \
} else if (__VA_ARGS__) {
#define Case(...) With( P(__VA_ARGS__) )
#define Otherwise() \
} else {
#define EndMatch \
}
|
Simplify source codes, remove some stupid stuff.
|
Simplify source codes, remove some stupid stuff.
|
C++
|
mit
|
mutouyun/cpp-pattern-matching
|
3f80377082334a1f8f7ee851322358f6dc43c098
|
dune/gdt/playground/mapper/block.hh
|
dune/gdt/playground/mapper/block.hh
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_MAPPER_BLOCK_HH
#define DUNE_GDT_MAPPER_BLOCK_HH
#include <type_traits>
#include <dune/stuff/common/exceptions.hh>
#if HAVE_DUNE_GRID_MULTISCALE
# include <dune/grid/multiscale/default.hh>
#endif
#include <dune/gdt/spaces/interface.hh>
#include "../../mapper/interface.hh"
namespace Dune {
namespace GDT {
namespace Mapper {
#if HAVE_DUNE_GRID_MULTISCALE
template< class LocalSpaceImp >
class Block;
namespace internal {
template< class LocalSpaceType >
class BlockTraits
{
static_assert(std::is_base_of< SpaceInterface< typename LocalSpaceType::Traits >, LocalSpaceType >::value,
"LocalSpaceType has to be derived from SpaceInterface!");
public:
typedef Block< LocalSpaceType > derived_type;
typedef typename LocalSpaceType::MapperType::BackendType BackendType;
}; // class BlockTraits
} // namespace internal
template< class LocalSpaceImp >
class Block
: public MapperInterface< internal::BlockTraits< LocalSpaceImp > >
{
typedef MapperInterface< internal::BlockTraits< LocalSpaceImp > > BaseType;
public:
typedef internal::BlockTraits< LocalSpaceImp > Traits;
typedef typename Traits::BackendType BackendType;
typedef LocalSpaceImp LocalSpaceType;
typedef grid::Multiscale::Default< typename LocalSpaceType::GridViewType::Grid > MsGridType;
private:
template< class L, class E >
class Compute
{
static_assert(AlwaysFalse< L >::value, "Not implemented for this kind of entity (only codim 0)!");
};
template< class L >
class Compute< L, typename MsGridType::EntityType >
{
typedef typename MsGridType::EntityType Comdim0EntityType;
public:
static size_t numDofs(const MsGridType& ms_grid,
const std::vector< std::shared_ptr< const L > >& local_spaces,
const Comdim0EntityType& entity)
{
const size_t block = find_block_of_(ms_grid, entity);
return local_spaces[block]->mapper().numDofs(entity);
}
static void globalIndices(const MsGridType& ms_grid,
const std::vector< std::shared_ptr< const L > >& local_spaces,
const std::vector< size_t >& global_start_indices,
const Comdim0EntityType& entity,
Dune::DynamicVector< size_t >& ret)
{
const size_t block = find_block_of_(ms_grid, entity);
local_spaces[block]->mapper().globalIndices(entity, ret);
const size_t num_dofs = local_spaces[block]->mapper().numDofs(entity);
assert(ret.size() >= num_dofs);
for (size_t ii = 0; ii < num_dofs; ++ii)
ret[ii] += global_start_indices[block];
}
static size_t mapToGlobal(const MsGridType& ms_grid,
const std::vector< std::shared_ptr< const L > >& local_spaces,
const std::vector< size_t >& global_start_indices,
const Comdim0EntityType& entity,
const size_t& localIndex)
{
const size_t block = find_block_of_(ms_grid, entity);
const size_t block_local_index = local_spaces[block]->mapper().mapToGlobal(entity, localIndex);
return global_start_indices[block] + block_local_index;
}
private:
static size_t find_block_of_(const MsGridType& ms_grid, const Comdim0EntityType& entity)
{
const auto global_entity_index = ms_grid.globalGridView()->indexSet().index(entity);
const auto result = ms_grid.entityToSubdomainMap()->find(global_entity_index);
#ifndef NDEBUG
if (result == ms_grid.entityToSubdomainMap()->end())
DUNE_THROW(Stuff::Exceptions::internal_error,
"Entity " << global_entity_index
<< " of the global grid view was not found in the multiscale grid!");
#endif // NDEBUG
const size_t subdomain = result->second;
#ifndef NDEBUG
if (subdomain >= ms_grid.size())
DUNE_THROW(Stuff::Exceptions::internal_error,
"The multiscale grid is corrupted!\nIt reports Entity " << global_entity_index
<< " to be in subdomain " << subdomain << " while only having "
<< ms_grid.size() << " subdomains!");
#endif // NDEBUG
return subdomain;
} // ... find_block_of_(...)
}; // class Compute< ..., EntityType >
public:
Block(const std::shared_ptr< const MsGridType > ms_grid,
const std::vector< std::shared_ptr< const LocalSpaceType > > local_spaces)
: ms_grid_(ms_grid)
, local_spaces_(local_spaces)
, num_blocks_(local_spaces_.size())
, size_(0)
, max_num_dofs_(0)
{
if (local_spaces_.size() != ms_grid_->size())
DUNE_THROW(Stuff::Exceptions::shapes_do_not_match,
"You have to provide a local space for each subdomain of the multiscale grid!\n"
<< " Size of the given multiscale grid: " << ms_grid_->size() << "\n"
<< " Number of local spaces given: " << local_spaces_.size());
for (size_t bb = 0; bb < num_blocks_; ++bb) {
max_num_dofs_ = std::max(max_num_dofs_, local_spaces_[bb]->mapper().maxNumDofs());
global_start_indices_.push_back(size_);
size_ += local_spaces_[bb]->mapper().size();
}
} // Block(...)
size_t numBlocks() const
{
return num_blocks_;
}
size_t localSize(const size_t block) const
{
assert(block < num_blocks_);
return local_spaces_[block]->mapper().size();
}
size_t mapToGlobal(const size_t block, const size_t localIndex) const
{
assert(block < num_blocks_);
return global_start_indices_[block] + localIndex;
}
const BackendType& backend() const
{
return local_spaces_[0]->mapper().backend();
}
size_t size() const
{
return size_;
}
size_t maxNumDofs() const
{
return max_num_dofs_;
}
template< class EntityType >
size_t numDofs(const EntityType& entity) const
{
return Compute< LocalSpaceType, EntityType >::numDofs(*ms_grid_, local_spaces_, entity);
}
template< class EntityType >
void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
{
Compute< LocalSpaceType, EntityType >::globalIndices(*ms_grid_, local_spaces_, global_start_indices_, entity, ret);
}
template< class EntityType >
size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
{
return Compute< LocalSpaceType, EntityType >::mapToGlobal(*ms_grid_,
local_spaces_,
global_start_indices_,
entity,
localIndex);
} // ... mapToGlobal(...)
private:
std::shared_ptr< const MsGridType > ms_grid_;
std::vector< std::shared_ptr< const LocalSpaceType > > local_spaces_;
size_t num_blocks_;
size_t size_;
size_t max_num_dofs_;
std::vector< size_t > global_start_indices_;
}; // class Block
#else // HAVE_DUNE_GRID_MULTISCALE
template< class LocalSpaceImp >
class Block
{
static_assert(AlwaysFalse< LocalSpaceImp >::value, "You are missing dune-grid-multiscale!");
};
#endif // HAVE_DUNE_GRID_MULTISCALE
} // namespace Mapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_MAPPER_BLOCK_HH
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_MAPPER_BLOCK_HH
#define DUNE_GDT_MAPPER_BLOCK_HH
#include <type_traits>
#include <dune/stuff/common/exceptions.hh>
#if HAVE_DUNE_GRID_MULTISCALE
# include <dune/grid/multiscale/default.hh>
#endif
#include <dune/gdt/spaces/interface.hh>
#include "../../mapper/interface.hh"
namespace Dune {
namespace GDT {
namespace Mapper {
#if HAVE_DUNE_GRID_MULTISCALE
template< class LocalSpaceImp >
class Block;
namespace internal {
template< class LocalSpaceType >
class BlockTraits
{
static_assert(std::is_base_of< SpaceInterface< typename LocalSpaceType::Traits >, LocalSpaceType >::value,
"LocalSpaceType has to be derived from SpaceInterface!");
public:
typedef Block< LocalSpaceType > derived_type;
typedef typename LocalSpaceType::EntityType EntityType;
typedef typename LocalSpaceType::MapperType::BackendType BackendType;
}; // class BlockTraits
} // namespace internal
template< class LocalSpaceImp >
class Block
: public MapperInterface< internal::BlockTraits< LocalSpaceImp > >
{
typedef MapperInterface< internal::BlockTraits< LocalSpaceImp > > BaseType;
public:
typedef internal::BlockTraits< LocalSpaceImp > Traits;
typedef typename Traits::BackendType BackendType;
typedef typename Traits::EntityType EntityType;
typedef LocalSpaceImp LocalSpaceType;
typedef grid::Multiscale::Default< typename LocalSpaceType::GridViewType::Grid > MsGridType;
private:
template< class L, class E >
class Compute
{
static_assert(AlwaysFalse< L >::value, "Not implemented for this kind of entity (only codim 0)!");
};
template< class L >
class Compute< L, typename MsGridType::EntityType >
{
typedef typename MsGridType::EntityType Comdim0EntityType;
public:
static size_t numDofs(const MsGridType& ms_grid,
const std::vector< std::shared_ptr< const L > >& local_spaces,
const Comdim0EntityType& entity)
{
const size_t block = find_block_of_(ms_grid, entity);
return local_spaces[block]->mapper().numDofs(entity);
}
static void globalIndices(const MsGridType& ms_grid,
const std::vector< std::shared_ptr< const L > >& local_spaces,
const std::vector< size_t >& global_start_indices,
const Comdim0EntityType& entity,
Dune::DynamicVector< size_t >& ret)
{
const size_t block = find_block_of_(ms_grid, entity);
local_spaces[block]->mapper().globalIndices(entity, ret);
const size_t num_dofs = local_spaces[block]->mapper().numDofs(entity);
assert(ret.size() >= num_dofs);
for (size_t ii = 0; ii < num_dofs; ++ii)
ret[ii] += global_start_indices[block];
}
static size_t mapToGlobal(const MsGridType& ms_grid,
const std::vector< std::shared_ptr< const L > >& local_spaces,
const std::vector< size_t >& global_start_indices,
const Comdim0EntityType& entity,
const size_t& localIndex)
{
const size_t block = find_block_of_(ms_grid, entity);
const size_t block_local_index = local_spaces[block]->mapper().mapToGlobal(entity, localIndex);
return global_start_indices[block] + block_local_index;
}
private:
static size_t find_block_of_(const MsGridType& ms_grid, const Comdim0EntityType& entity)
{
const auto global_entity_index = ms_grid.globalGridView()->indexSet().index(entity);
const auto result = ms_grid.entityToSubdomainMap()->find(global_entity_index);
#ifndef NDEBUG
if (result == ms_grid.entityToSubdomainMap()->end())
DUNE_THROW(Stuff::Exceptions::internal_error,
"Entity " << global_entity_index
<< " of the global grid view was not found in the multiscale grid!");
#endif // NDEBUG
const size_t subdomain = result->second;
#ifndef NDEBUG
if (subdomain >= ms_grid.size())
DUNE_THROW(Stuff::Exceptions::internal_error,
"The multiscale grid is corrupted!\nIt reports Entity " << global_entity_index
<< " to be in subdomain " << subdomain << " while only having "
<< ms_grid.size() << " subdomains!");
#endif // NDEBUG
return subdomain;
} // ... find_block_of_(...)
}; // class Compute< ..., EntityType >
public:
Block(const std::shared_ptr< const MsGridType > ms_grid,
const std::vector< std::shared_ptr< const LocalSpaceType > > local_spaces)
: ms_grid_(ms_grid)
, local_spaces_(local_spaces)
, num_blocks_(local_spaces_.size())
, size_(0)
, max_num_dofs_(0)
{
if (local_spaces_.size() != ms_grid_->size())
DUNE_THROW(Stuff::Exceptions::shapes_do_not_match,
"You have to provide a local space for each subdomain of the multiscale grid!\n"
<< " Size of the given multiscale grid: " << ms_grid_->size() << "\n"
<< " Number of local spaces given: " << local_spaces_.size());
for (size_t bb = 0; bb < num_blocks_; ++bb) {
max_num_dofs_ = std::max(max_num_dofs_, local_spaces_[bb]->mapper().maxNumDofs());
global_start_indices_.push_back(size_);
size_ += local_spaces_[bb]->mapper().size();
}
} // Block(...)
size_t numBlocks() const
{
return num_blocks_;
}
size_t localSize(const size_t block) const
{
assert(block < num_blocks_);
return local_spaces_[block]->mapper().size();
}
size_t mapToGlobal(const size_t block, const size_t localIndex) const
{
assert(block < num_blocks_);
return global_start_indices_[block] + localIndex;
}
const BackendType& backend() const
{
return local_spaces_[0]->mapper().backend();
}
size_t size() const
{
return size_;
}
size_t maxNumDofs() const
{
return max_num_dofs_;
}
size_t numDofs(const EntityType& entity) const
{
return Compute< LocalSpaceType, EntityType >::numDofs(*ms_grid_, local_spaces_, entity);
}
void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
{
Compute< LocalSpaceType, EntityType >::globalIndices(*ms_grid_, local_spaces_, global_start_indices_, entity, ret);
}
size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
{
return Compute< LocalSpaceType, EntityType >::mapToGlobal(*ms_grid_,
local_spaces_,
global_start_indices_,
entity,
localIndex);
} // ... mapToGlobal(...)
private:
std::shared_ptr< const MsGridType > ms_grid_;
std::vector< std::shared_ptr< const LocalSpaceType > > local_spaces_;
size_t num_blocks_;
size_t size_;
size_t max_num_dofs_;
std::vector< size_t > global_start_indices_;
}; // class Block
#else // HAVE_DUNE_GRID_MULTISCALE
template< class LocalSpaceImp >
class Block
{
static_assert(AlwaysFalse< LocalSpaceImp >::value, "You are missing dune-grid-multiscale!");
};
#endif // HAVE_DUNE_GRID_MULTISCALE
} // namespace Mapper
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_MAPPER_BLOCK_HH
|
remove EntityType as a template parameter
|
[mapper.block] remove EntityType as a template parameter
|
C++
|
bsd-2-clause
|
BarbaraV/dune-gdt,ftalbrecht/dune-gdt
|
843ccb24f7b092580c48cf659865def0758ed976
|
webkit/plugins/ppapi/ppb_video_decoder_impl.cc
|
webkit/plugins/ppapi/ppb_video_decoder_impl.cc
|
// Copyright (c) 2011 The Chromium 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 "webkit/plugins/ppapi/ppb_video_decoder_impl.h"
#include <string>
#include "base/logging.h"
#include "base/message_loop.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "media/video/picture.h"
#include "ppapi/c/dev/pp_video_dev.h"
#include "ppapi/c/dev/ppb_video_decoder_dev.h"
#include "ppapi/c/dev/ppp_video_decoder_dev.h"
#include "ppapi/c/pp_completion_callback.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/thunk/enter.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_buffer_impl.h"
#include "webkit/plugins/ppapi/ppb_context_3d_impl.h"
#include "webkit/plugins/ppapi/resource_tracker.h"
using ppapi::thunk::EnterResourceNoLock;
using ppapi::thunk::PPB_Buffer_API;
using ppapi::thunk::PPB_Context3D_API;
using ppapi::thunk::PPB_VideoDecoder_API;
namespace webkit {
namespace ppapi {
PPB_VideoDecoder_Impl::PPB_VideoDecoder_Impl(PluginInstance* instance)
: Resource(instance) {
ppp_videodecoder_ =
static_cast<const PPP_VideoDecoder_Dev*>(instance->module()->
GetPluginInterface(PPP_VIDEODECODER_DEV_INTERFACE));
}
PPB_VideoDecoder_Impl::~PPB_VideoDecoder_Impl() {
}
PPB_VideoDecoder_API* PPB_VideoDecoder_Impl::AsPPB_VideoDecoder_API() {
return this;
}
// static
PP_Resource PPB_VideoDecoder_Impl::Create(PluginInstance* instance,
PP_Resource context3d_id,
const PP_VideoConfigElement* config) {
if (!context3d_id)
return NULL;
EnterResourceNoLock<PPB_Context3D_API> enter_context(context3d_id, true);
if (enter_context.failed())
return NULL;
scoped_refptr<PPB_VideoDecoder_Impl> decoder(
new PPB_VideoDecoder_Impl(instance));
if (decoder->Init(context3d_id, enter_context.object(), config))
return decoder->GetReference();
return 0;
}
bool PPB_VideoDecoder_Impl::Init(PP_Resource context3d_id,
PPB_Context3D_API* context3d,
const PP_VideoConfigElement* config) {
if (!::ppapi::VideoDecoderImpl::Init(context3d_id, context3d, config))
return false;
std::vector<int32> copied;
if (!CopyConfigsToVector(config, &copied))
return false;
PPB_Context3D_Impl* context3d_impl =
static_cast<PPB_Context3D_Impl*>(context3d);
int command_buffer_route_id =
context3d_impl->platform_context()->GetCommandBufferRouteId();
if (command_buffer_route_id == 0)
return false;
platform_video_decoder_ = instance()->delegate()->CreateVideoDecoder(
this, command_buffer_route_id);
if (!platform_video_decoder_)
return false;
FlushCommandBuffer();
return platform_video_decoder_->Initialize(copied);
}
int32_t PPB_VideoDecoder_Impl::Decode(
const PP_VideoBitstreamBuffer_Dev* bitstream_buffer,
PP_CompletionCallback callback) {
if (!platform_video_decoder_)
return PP_ERROR_BADRESOURCE;
EnterResourceNoLock<PPB_Buffer_API> enter(bitstream_buffer->data, true);
if (enter.failed())
return PP_ERROR_FAILED;
PPB_Buffer_Impl* buffer = static_cast<PPB_Buffer_Impl*>(enter.object());
media::BitstreamBuffer decode_buffer(bitstream_buffer->id,
buffer->shared_memory()->handle(),
static_cast<size_t>(buffer->size()));
SetBitstreamBufferCallback(bitstream_buffer->id, callback);
FlushCommandBuffer();
platform_video_decoder_->Decode(decode_buffer);
return PP_OK_COMPLETIONPENDING;
}
void PPB_VideoDecoder_Impl::AssignPictureBuffers(
uint32_t no_of_buffers,
const PP_PictureBuffer_Dev* buffers) {
if (!platform_video_decoder_)
return;
std::vector<media::PictureBuffer> wrapped_buffers;
for (uint32 i = 0; i < no_of_buffers; i++) {
PP_PictureBuffer_Dev in_buf = buffers[i];
media::PictureBuffer buffer(
in_buf.id,
gfx::Size(in_buf.size.width, in_buf.size.height),
in_buf.texture_id);
wrapped_buffers.push_back(buffer);
}
FlushCommandBuffer();
platform_video_decoder_->AssignPictureBuffers(wrapped_buffers);
}
void PPB_VideoDecoder_Impl::ReusePictureBuffer(int32_t picture_buffer_id) {
if (!platform_video_decoder_)
return;
FlushCommandBuffer();
platform_video_decoder_->ReusePictureBuffer(picture_buffer_id);
}
int32_t PPB_VideoDecoder_Impl::Flush(PP_CompletionCallback callback) {
if (!platform_video_decoder_)
return PP_ERROR_BADRESOURCE;
SetFlushCallback(callback);
FlushCommandBuffer();
platform_video_decoder_->Flush();
return PP_OK_COMPLETIONPENDING;
}
int32_t PPB_VideoDecoder_Impl::Reset(PP_CompletionCallback callback) {
if (!platform_video_decoder_)
return PP_ERROR_BADRESOURCE;
SetResetCallback(callback);
FlushCommandBuffer();
platform_video_decoder_->Reset();
return PP_OK_COMPLETIONPENDING;
}
void PPB_VideoDecoder_Impl::Destroy() {
if (!platform_video_decoder_)
return;
FlushCommandBuffer();
platform_video_decoder_->Destroy();
::ppapi::VideoDecoderImpl::Destroy();
platform_video_decoder_ = NULL;
ppp_videodecoder_ = NULL;
}
void PPB_VideoDecoder_Impl::ProvidePictureBuffers(
uint32 requested_num_of_buffers, const gfx::Size& dimensions) {
if (!ppp_videodecoder_)
return;
PP_Size out_dim = PP_MakeSize(dimensions.width(), dimensions.height());
ScopedResourceId resource(this);
ppp_videodecoder_->ProvidePictureBuffers(
instance()->pp_instance(), resource.id, requested_num_of_buffers,
out_dim);
}
void PPB_VideoDecoder_Impl::PictureReady(const media::Picture& picture) {
if (!ppp_videodecoder_)
return;
PP_Picture_Dev output;
output.picture_buffer_id = picture.picture_buffer_id();
output.bitstream_buffer_id = picture.bitstream_buffer_id();
ScopedResourceId resource(this);
ppp_videodecoder_->PictureReady(
instance()->pp_instance(), resource.id, output);
}
void PPB_VideoDecoder_Impl::DismissPictureBuffer(int32 picture_buffer_id) {
if (!ppp_videodecoder_)
return;
ScopedResourceId resource(this);
ppp_videodecoder_->DismissPictureBuffer(
instance()->pp_instance(), resource.id, picture_buffer_id);
}
void PPB_VideoDecoder_Impl::NotifyEndOfStream() {
if (!ppp_videodecoder_)
return;
ScopedResourceId resource(this);
ppp_videodecoder_->EndOfStream(instance()->pp_instance(), resource.id);
}
void PPB_VideoDecoder_Impl::NotifyError(
media::VideoDecodeAccelerator::Error error) {
if (!ppp_videodecoder_)
return;
ScopedResourceId resource(this);
// TODO(vrk): This is assuming VideoDecodeAccelerator::Error and
// PP_VideoDecodeError_Dev have identical enum values. There is no compiler
// assert to guarantee this. We either need to add such asserts or
// merge these two enums.
ppp_videodecoder_->NotifyError(instance()->pp_instance(), resource.id,
static_cast<PP_VideoDecodeError_Dev>(error));
}
void PPB_VideoDecoder_Impl::NotifyResetDone() {
RunResetCallback(PP_OK);
}
void PPB_VideoDecoder_Impl::NotifyEndOfBitstreamBuffer(
int32 bitstream_buffer_id) {
RunBitstreamBufferCallback(bitstream_buffer_id, PP_OK);
}
void PPB_VideoDecoder_Impl::NotifyFlushDone() {
RunFlushCallback(PP_OK);
}
void PPB_VideoDecoder_Impl::NotifyInitializeDone() {
NOTREACHED() << "PlatformVideoDecoder::Initialize() is synchronous!";
}
void PPB_VideoDecoder_Impl::AddRefResource(PP_Resource resource) {
ResourceTracker::Get()->AddRefResource(resource);
}
void PPB_VideoDecoder_Impl::UnrefResource(PP_Resource resource) {
ResourceTracker::Get()->UnrefResource(resource);
}
} // namespace ppapi
} // namespace webkit
|
// Copyright (c) 2011 The Chromium 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 "webkit/plugins/ppapi/ppb_video_decoder_impl.h"
#include <string>
#include "base/logging.h"
#include "base/message_loop.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "media/video/picture.h"
#include "ppapi/c/dev/pp_video_dev.h"
#include "ppapi/c/dev/ppb_video_decoder_dev.h"
#include "ppapi/c/dev/ppp_video_decoder_dev.h"
#include "ppapi/c/pp_completion_callback.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/thunk/enter.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_buffer_impl.h"
#include "webkit/plugins/ppapi/ppb_context_3d_impl.h"
#include "webkit/plugins/ppapi/resource_tracker.h"
using ppapi::thunk::EnterResourceNoLock;
using ppapi::thunk::PPB_Buffer_API;
using ppapi::thunk::PPB_Context3D_API;
using ppapi::thunk::PPB_VideoDecoder_API;
namespace webkit {
namespace ppapi {
PPB_VideoDecoder_Impl::PPB_VideoDecoder_Impl(PluginInstance* instance)
: Resource(instance) {
ppp_videodecoder_ =
static_cast<const PPP_VideoDecoder_Dev*>(instance->module()->
GetPluginInterface(PPP_VIDEODECODER_DEV_INTERFACE));
}
PPB_VideoDecoder_Impl::~PPB_VideoDecoder_Impl() {
}
PPB_VideoDecoder_API* PPB_VideoDecoder_Impl::AsPPB_VideoDecoder_API() {
return this;
}
// static
PP_Resource PPB_VideoDecoder_Impl::Create(PluginInstance* instance,
PP_Resource context3d_id,
const PP_VideoConfigElement* config) {
if (!context3d_id)
return 0;
EnterResourceNoLock<PPB_Context3D_API> enter_context(context3d_id, true);
if (enter_context.failed())
return 0;
scoped_refptr<PPB_VideoDecoder_Impl> decoder(
new PPB_VideoDecoder_Impl(instance));
if (decoder->Init(context3d_id, enter_context.object(), config))
return decoder->GetReference();
return 0;
}
bool PPB_VideoDecoder_Impl::Init(PP_Resource context3d_id,
PPB_Context3D_API* context3d,
const PP_VideoConfigElement* config) {
if (!::ppapi::VideoDecoderImpl::Init(context3d_id, context3d, config))
return false;
std::vector<int32> copied;
if (!CopyConfigsToVector(config, &copied))
return false;
PPB_Context3D_Impl* context3d_impl =
static_cast<PPB_Context3D_Impl*>(context3d);
int command_buffer_route_id =
context3d_impl->platform_context()->GetCommandBufferRouteId();
if (command_buffer_route_id == 0)
return false;
platform_video_decoder_ = instance()->delegate()->CreateVideoDecoder(
this, command_buffer_route_id);
if (!platform_video_decoder_)
return false;
FlushCommandBuffer();
return platform_video_decoder_->Initialize(copied);
}
int32_t PPB_VideoDecoder_Impl::Decode(
const PP_VideoBitstreamBuffer_Dev* bitstream_buffer,
PP_CompletionCallback callback) {
if (!platform_video_decoder_)
return PP_ERROR_BADRESOURCE;
EnterResourceNoLock<PPB_Buffer_API> enter(bitstream_buffer->data, true);
if (enter.failed())
return PP_ERROR_FAILED;
PPB_Buffer_Impl* buffer = static_cast<PPB_Buffer_Impl*>(enter.object());
media::BitstreamBuffer decode_buffer(bitstream_buffer->id,
buffer->shared_memory()->handle(),
static_cast<size_t>(buffer->size()));
SetBitstreamBufferCallback(bitstream_buffer->id, callback);
FlushCommandBuffer();
platform_video_decoder_->Decode(decode_buffer);
return PP_OK_COMPLETIONPENDING;
}
void PPB_VideoDecoder_Impl::AssignPictureBuffers(
uint32_t no_of_buffers,
const PP_PictureBuffer_Dev* buffers) {
if (!platform_video_decoder_)
return;
std::vector<media::PictureBuffer> wrapped_buffers;
for (uint32 i = 0; i < no_of_buffers; i++) {
PP_PictureBuffer_Dev in_buf = buffers[i];
media::PictureBuffer buffer(
in_buf.id,
gfx::Size(in_buf.size.width, in_buf.size.height),
in_buf.texture_id);
wrapped_buffers.push_back(buffer);
}
FlushCommandBuffer();
platform_video_decoder_->AssignPictureBuffers(wrapped_buffers);
}
void PPB_VideoDecoder_Impl::ReusePictureBuffer(int32_t picture_buffer_id) {
if (!platform_video_decoder_)
return;
FlushCommandBuffer();
platform_video_decoder_->ReusePictureBuffer(picture_buffer_id);
}
int32_t PPB_VideoDecoder_Impl::Flush(PP_CompletionCallback callback) {
if (!platform_video_decoder_)
return PP_ERROR_BADRESOURCE;
SetFlushCallback(callback);
FlushCommandBuffer();
platform_video_decoder_->Flush();
return PP_OK_COMPLETIONPENDING;
}
int32_t PPB_VideoDecoder_Impl::Reset(PP_CompletionCallback callback) {
if (!platform_video_decoder_)
return PP_ERROR_BADRESOURCE;
SetResetCallback(callback);
FlushCommandBuffer();
platform_video_decoder_->Reset();
return PP_OK_COMPLETIONPENDING;
}
void PPB_VideoDecoder_Impl::Destroy() {
if (!platform_video_decoder_)
return;
FlushCommandBuffer();
platform_video_decoder_->Destroy();
::ppapi::VideoDecoderImpl::Destroy();
platform_video_decoder_ = NULL;
ppp_videodecoder_ = NULL;
}
void PPB_VideoDecoder_Impl::ProvidePictureBuffers(
uint32 requested_num_of_buffers, const gfx::Size& dimensions) {
if (!ppp_videodecoder_)
return;
PP_Size out_dim = PP_MakeSize(dimensions.width(), dimensions.height());
ScopedResourceId resource(this);
ppp_videodecoder_->ProvidePictureBuffers(
instance()->pp_instance(), resource.id, requested_num_of_buffers,
out_dim);
}
void PPB_VideoDecoder_Impl::PictureReady(const media::Picture& picture) {
if (!ppp_videodecoder_)
return;
PP_Picture_Dev output;
output.picture_buffer_id = picture.picture_buffer_id();
output.bitstream_buffer_id = picture.bitstream_buffer_id();
ScopedResourceId resource(this);
ppp_videodecoder_->PictureReady(
instance()->pp_instance(), resource.id, output);
}
void PPB_VideoDecoder_Impl::DismissPictureBuffer(int32 picture_buffer_id) {
if (!ppp_videodecoder_)
return;
ScopedResourceId resource(this);
ppp_videodecoder_->DismissPictureBuffer(
instance()->pp_instance(), resource.id, picture_buffer_id);
}
void PPB_VideoDecoder_Impl::NotifyEndOfStream() {
if (!ppp_videodecoder_)
return;
ScopedResourceId resource(this);
ppp_videodecoder_->EndOfStream(instance()->pp_instance(), resource.id);
}
void PPB_VideoDecoder_Impl::NotifyError(
media::VideoDecodeAccelerator::Error error) {
if (!ppp_videodecoder_)
return;
ScopedResourceId resource(this);
// TODO(vrk): This is assuming VideoDecodeAccelerator::Error and
// PP_VideoDecodeError_Dev have identical enum values. There is no compiler
// assert to guarantee this. We either need to add such asserts or
// merge these two enums.
ppp_videodecoder_->NotifyError(instance()->pp_instance(), resource.id,
static_cast<PP_VideoDecodeError_Dev>(error));
}
void PPB_VideoDecoder_Impl::NotifyResetDone() {
RunResetCallback(PP_OK);
}
void PPB_VideoDecoder_Impl::NotifyEndOfBitstreamBuffer(
int32 bitstream_buffer_id) {
RunBitstreamBufferCallback(bitstream_buffer_id, PP_OK);
}
void PPB_VideoDecoder_Impl::NotifyFlushDone() {
RunFlushCallback(PP_OK);
}
void PPB_VideoDecoder_Impl::NotifyInitializeDone() {
NOTREACHED() << "PlatformVideoDecoder::Initialize() is synchronous!";
}
void PPB_VideoDecoder_Impl::AddRefResource(PP_Resource resource) {
ResourceTracker::Get()->AddRefResource(resource);
}
void PPB_VideoDecoder_Impl::UnrefResource(PP_Resource resource) {
ResourceTracker::Get()->UnrefResource(resource);
}
} // namespace ppapi
} // namespace webkit
|
Fix ARM build bustage.
|
Fix ARM build bustage.
[email protected]
Review URL: http://codereview.chromium.org/7541061
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@95729 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
patrickm/chromium.src,patrickm/chromium.src,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,ltilve/chromium,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,jaruba/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,zcbenz/cefode-chromium,rogerwang/chromium,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,Just-D/chromium-1,dednal/chromium.src,dednal/chromium.src,jaruba/chromium.src,Chilledheart/chromium,keishi/chromium,Chilledheart/chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,Just-D/chromium-1,anirudhSK/chromium,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,timopulkkinen/BubbleFish,ondra-novak/chromium.src,markYoungH/chromium.src,rogerwang/chromium,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,keishi/chromium,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,rogerwang/chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,ltilve/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,keishi/chromium,bright-sparks/chromium-spacewalk,ltilve/chromium,markYoungH/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,hujiajie/pa-chromium,rogerwang/chromium,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,dednal/chromium.src,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,ltilve/chromium,ondra-novak/chromium.src,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,keishi/chromium,robclark/chromium,patrickm/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,robclark/chromium,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,anirudhSK/chromium,dednal/chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,robclark/chromium,anirudhSK/chromium,dednal/chromium.src,ltilve/chromium,ltilve/chromium,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,anirudhSK/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,rogerwang/chromium,hujiajie/pa-chromium,patrickm/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,keishi/chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,ondra-novak/chromium.src,dushu1203/chromium.src,keishi/chromium,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,robclark/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,keishi/chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,jaruba/chromium.src,keishi/chromium,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,robclark/chromium,M4sse/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,keishi/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,jaruba/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,rogerwang/chromium,robclark/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,nacl-webkit/chrome_deps,Jonekee/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,robclark/chromium,rogerwang/chromium,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium
|
ae65c26469b1f838ab0a6c7741572e1e2bc51148
|
atom/browser/api/atom_api_desktop_capturer.cc
|
atom/browser/api/atom_api_desktop_capturer.cc
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_desktop_capturer.h"
using base::PlatformThreadRef;
#include "atom/common/api/atom_api_native_image.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/media/desktop_media_list.h"
#include "native_mate/dictionary.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "content/public/browser/desktop_capture.h"
#include "atom/common/node_includes.h"
namespace mate {
template<>
struct Converter<DesktopMediaList::Source> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const DesktopMediaList::Source& source) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
content::DesktopMediaID id = source.id;
dict.Set("name", base::UTF16ToUTF8(source.name));
dict.Set("id", id.ToString());
dict.Set(
"thumbnail",
atom::api::NativeImage::Create(isolate, gfx::Image(source.thumbnail)));
return ConvertToV8(isolate, dict);
}
};
} // namespace mate
namespace atom {
namespace api {
DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {
Init(isolate);
}
DesktopCapturer::~DesktopCapturer() {
}
void DesktopCapturer::StartHandling(bool capture_window,
bool capture_screen,
const gfx::Size& thumbnail_size) {
webrtc::DesktopCaptureOptions options = content::CreateDesktopCaptureOptions();
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer(
capture_screen ? webrtc::DesktopCapturer::CreateScreenCapturer(options)
: nullptr);
std::unique_ptr<webrtc::DesktopCapturer> window_capturer(
capture_window ? webrtc::DesktopCapturer::CreateWindowCapturer(options)
: nullptr);
media_list_.reset(new NativeDesktopMediaList(
std::move(screen_capturer), std::move(window_capturer)));
media_list_->SetThumbnailSize(thumbnail_size);
media_list_->StartUpdating(this);
}
void DesktopCapturer::OnSourceAdded(int index) {
}
void DesktopCapturer::OnSourceRemoved(int index) {
}
void DesktopCapturer::OnSourceMoved(int old_index, int new_index) {
}
void DesktopCapturer::OnSourceNameChanged(int index) {
}
void DesktopCapturer::OnSourceThumbnailChanged(int index) {
}
bool DesktopCapturer::OnRefreshFinished() {
Emit("finished", media_list_->GetSources());
return false;
}
// static
mate::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new DesktopCapturer(isolate));
}
// static
void DesktopCapturer::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "DesktopCapturer"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("startHandling", &DesktopCapturer::StartHandling);
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("desktopCapturer", atom::api::DesktopCapturer::Create(isolate));
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_desktop_capturer, Initialize);
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_desktop_capturer.h"
using base::PlatformThreadRef;
#include "atom/common/api/atom_api_native_image.h"
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/media/desktop_media_list.h"
#include "content/public/browser/desktop_capture.h"
#include "native_mate/dictionary.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "atom/common/node_includes.h"
namespace mate {
template<>
struct Converter<DesktopMediaList::Source> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const DesktopMediaList::Source& source) {
mate::Dictionary dict(isolate, v8::Object::New(isolate));
content::DesktopMediaID id = source.id;
dict.Set("name", base::UTF16ToUTF8(source.name));
dict.Set("id", id.ToString());
dict.Set(
"thumbnail",
atom::api::NativeImage::Create(isolate, gfx::Image(source.thumbnail)));
return ConvertToV8(isolate, dict);
}
};
} // namespace mate
namespace atom {
namespace api {
DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {
Init(isolate);
}
DesktopCapturer::~DesktopCapturer() {
}
void DesktopCapturer::StartHandling(bool capture_window,
bool capture_screen,
const gfx::Size& thumbnail_size) {
webrtc::DesktopCaptureOptions options =
content::CreateDesktopCaptureOptions();
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer(
capture_screen ? webrtc::DesktopCapturer::CreateScreenCapturer(options)
: nullptr);
std::unique_ptr<webrtc::DesktopCapturer> window_capturer(
capture_window ? webrtc::DesktopCapturer::CreateWindowCapturer(options)
: nullptr);
media_list_.reset(new NativeDesktopMediaList(
std::move(screen_capturer), std::move(window_capturer)));
media_list_->SetThumbnailSize(thumbnail_size);
media_list_->StartUpdating(this);
}
void DesktopCapturer::OnSourceAdded(int index) {
}
void DesktopCapturer::OnSourceRemoved(int index) {
}
void DesktopCapturer::OnSourceMoved(int old_index, int new_index) {
}
void DesktopCapturer::OnSourceNameChanged(int index) {
}
void DesktopCapturer::OnSourceThumbnailChanged(int index) {
}
bool DesktopCapturer::OnRefreshFinished() {
Emit("finished", media_list_->GetSources());
return false;
}
// static
mate::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new DesktopCapturer(isolate));
}
// static
void DesktopCapturer::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "DesktopCapturer"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("startHandling", &DesktopCapturer::StartHandling);
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("desktopCapturer", atom::api::DesktopCapturer::Create(isolate));
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_desktop_capturer, Initialize);
|
fix lint
|
fix lint
|
C++
|
mit
|
gerhardberger/electron,seanchas116/electron,seanchas116/electron,bpasero/electron,electron/electron,seanchas116/electron,bpasero/electron,bpasero/electron,electron/electron,the-ress/electron,gerhardberger/electron,bpasero/electron,gerhardberger/electron,seanchas116/electron,the-ress/electron,the-ress/electron,gerhardberger/electron,the-ress/electron,gerhardberger/electron,shiftkey/electron,bpasero/electron,bpasero/electron,electron/electron,gerhardberger/electron,seanchas116/electron,shiftkey/electron,shiftkey/electron,electron/electron,electron/electron,shiftkey/electron,the-ress/electron,bpasero/electron,shiftkey/electron,the-ress/electron,shiftkey/electron,electron/electron,gerhardberger/electron,electron/electron,the-ress/electron,seanchas116/electron
|
11bea54fe1a144b8e5a75feab4ebb137fadc74fe
|
bbb/tmp/integer_sequence/integer_sequence.hpp
|
bbb/tmp/integer_sequence/integer_sequence.hpp
|
/* **** **** **** **** **** **** **** **** *
*
* _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
* _/ _/ _/ _/ _/ _/
* _/ _/ _/ _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
*
* bit by bit
* bbb/core/type/sequence/integer_sequence.hpp
*
* author: ISHII 2bit
* mail: [email protected]
*
* **** **** **** **** **** **** **** **** */
#pragma once
#include <bbb/core.hpp>
#include <bbb/tmp/utility.hpp>
namespace bbb {
namespace tmp {
namespace integer_sequences {
#if bbb_is_cpp14
template <typename type, type ... ns>
struct integer_sequence {
using value_type = type;
static constexpr std::size_t size() noexcept { return sizeof...(ns); }
};
namespace detail {
template <typename integer_type, integer_type n, integer_type ... ns>
struct make_integer_sequence {
using type = resolve_t<conditional_t<
n == 0,
defer<integer_sequence<integer_type, ns ...>>,
detail::make_integer_sequence<integer_type, n - 1, n - 1, ns ...>
>>;
};
};
template <typename type, type n>
using make_integer_sequence = detail::make_integer_sequence<type, n>;
template <std::size_t ... ns>
using index_sequence = integer_sequence<std::size_t, ns ...>;
template <std::size_t n>
using make_index_sequence = make_integer_sequence<std::size_t, n>;
template <typename... types>
using index_sequence_for = make_index_sequence<sizeof...(types)>;
template <typename type, type n>
#else
using std::integer_sequence;
using std::make_integer_sequence;
using std::index_sequence;
using std::make_index_sequence;
using std::index_sequence_for;
#endif
using make_integer_sequence_t = get_type<make_integer_sequence<type, n>>;
template <std::size_t n>
using make_index_sequence_t = get_type<make_index_sequence<n>>;
template <typename... types>
using index_sequence_for_t = get_type<index_sequence_for<types ...>>;
#if BBB_EXEC_UNIT_TEST
namespace integer_sequence_test {
using test1 = unit_test::assert<
make_index_sequence_t<4>,
index_sequence<0, 1, 2, 3>
>;
using test2 = unit_test::assert<
index_sequence_for_t<int, int>,
index_sequence<0, 1>
>;
};
#endif
};
using namespace integer_sequences;
};
};
|
/* **** **** **** **** **** **** **** **** *
*
* _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
* _/ _/ _/ _/ _/ _/
* _/ _/ _/ _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
*
* bit by bit
* bbb/core/type/sequence/integer_sequence.hpp
*
* author: ISHII 2bit
* mail: [email protected]
*
* **** **** **** **** **** **** **** **** */
#pragma once
#include <bbb/core.hpp>
#include <bbb/tmp/utility.hpp>
namespace bbb {
namespace tmp {
namespace integer_sequences {
#if bbb_is_cpp14
template <typename type, type ... ns>
struct integer_sequence {
using value_type = type;
static constexpr std::size_t size() noexcept { return sizeof...(ns); }
};
namespace detail {
template <typename integer_type, integer_type n, integer_type ... ns>
struct make_integer_sequence {
using type = resolve_t<conditional_t<
n == 0,
defer<integer_sequence<integer_type, ns ...>>,
detail::make_integer_sequence<integer_type, n - 1, n - 1, ns ...>
>>;
};
};
template <typename type, type n>
using make_integer_sequence = detail::make_integer_sequence<type, n>;
template <std::size_t ... ns>
using index_sequence = integer_sequence<std::size_t, ns ...>;
template <std::size_t n>
using make_index_sequence = make_integer_sequence<std::size_t, n>;
template <typename... types>
using index_sequence_for = make_index_sequence<sizeof...(types)>;
template <typename type, type n>
#else
using std::integer_sequence;
using std::make_integer_sequence;
using std::index_sequence;
using std::make_index_sequence;
using std::index_sequence_for;
#endif
using make_integer_sequence_t = get_type<make_integer_sequence<type, n>>;
template <std::size_t n>
using make_index_sequence_t = get_type<make_index_sequence<n>>;
template <typename... types>
using index_sequence_for_t = get_type<index_sequence_for<types ...>>;
#if BBB_EXEC_UNIT_TEST
namespace integer_sequence_test {
using test1 = unit_test::assert<
make_index_sequence_t<4>,
index_sequence<0, 1, 2, 3>
>;
using test2 = unit_test::assert<
index_sequence_for_t<int, int>,
index_sequence<0, 1>
>;
};
#endif
};
using namespace integer_sequences;
};
};
|
adjust indentation
|
adjust indentation
|
C++
|
mit
|
2bbb/bit_by_bit
|
1b5408401cd1f32a38904555c9e6d8c66364b2f3
|
life.cpp
|
life.cpp
|
#include <ncurses.h>
#include <fstream>
using std::ifstream;
#include <string>
using std::string; using std::getline;
#include <thread>
using std::this_thread::sleep_for;
#include <chrono>
using std::chrono::milliseconds;
#define TEST_FILE "init_samples/glider_gun.txt"
#define ALIVE '#'
#define DEAD '.'
/* To Do:
- create struct for game window that stores the grid size and number of turns
- add welcome screen
- add main menu with options:
- load state from file
- set state interactively
- quit
- add exceptions where noted
- make grid/buffer swap into own function
*/
// create 2D array to use as the grid
bool** createGridArray(int grid_width, int grid_height)
{
bool** grid_array_pointer = new bool*[grid_height];
for (int i = 0; i < grid_height; ++i) {
grid_array_pointer[i] = new bool[grid_width];
}
return grid_array_pointer;
}
// set initial state of the grid
// ADD AN EXCEPTION HERE FOR "FILE NOT FOUND"
void setInitialState(bool** grid, ifstream& init_file, int grid_width, int grid_height)
{
// get a line to represent each row and copy it into the grid
string row;
for (int y = 0; y < grid_height; ++y) {
getline(init_file,row);
for (int x = 0; x < grid_width; ++x) {
if (row[x] == ALIVE) {
grid[y][x] = true;
}
else if (row[x] == DEAD) {
grid[y][x] = false;
}
else {
// raise not_implemented_error;
}
}
}
}
// return the number of neighboring cells that are alive
int countNeighbors(bool** grid, int grid_width, int grid_height, int target_y, int target_x)
{
int live_neighbors = 0;
for (int y = target_y - 1; y <= target_y + 1; ++y) {
for (int x = target_x - 1; x <= target_x + 1; ++x) {
if (y == target_y && x == target_x) // ignore target itself
continue;
// add length of row/column to offset effect of negative integer in mod calculation
if (grid[(y + grid_height) % grid_height][(x + grid_width) % grid_width])
++live_neighbors;
}
}
return live_neighbors;
}
// determine if cells live or die
void step(bool** grid, bool** buffer, int grid_width, int grid_height)
{
int live_neighbors;
for (int y = 0; y < grid_height; ++y) {
for (int x = 0; x < grid_width; ++x) {
live_neighbors = countNeighbors(grid, grid_width, grid_height, y, x);
// live cell with fewer than two live neighbors dies (under-population)
if (grid[y][x] && live_neighbors < 2 )
buffer[y][x] = false;
// live cell with two or three live neighbors lives on to next generation
else if ((grid[y][x] && live_neighbors == 2) || (grid[y][x] && live_neighbors == 3))
buffer[y][x] = true;
// live cell with more than three neighbors dies (over-population)
else if (grid[y][x] && live_neighbors > 3)
buffer[y][x] = false;
// dead cell with exactly three live neighbors becomes a live cell (reproduction)
else if (!grid[y][x] && live_neighbors == 3)
buffer[y][x] = true;
}
}
// write buffer to grid and clear buffer
for (int i = 0; i < grid_height; ++i) {
for (int j = 0; j < grid_width; ++j) {
grid[i][j] = buffer[i][j];
buffer[i][j] = false;
}
}
}
void printFrame(WINDOW* win, bool** grid)
{
int h, w;
werase(win);
getmaxyx(win, h, w);
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
if (grid[i][j])
mvwaddch(win, i, j, ALIVE);
}
}
wrefresh(win);
}
WINDOW* createGameWindow(int height, int width, int starty, int startx)
{
WINDOW* win;
win = newwin(height, width, starty, startx);
wrefresh(win);
return win;
}
int main()
{
int turns, width, height;
initscr(); // start curses mode
noecho();
cbreak(); // disable line buffering
curs_set(0);
ifstream init_file;
init_file.open(TEST_FILE);
init_file >> turns >> width >> height;
init_file.seekg(1, init_file.cur);
bool** life_grid = createGridArray(width, height);
bool** buffer = createGridArray(width, height);
setInitialState(life_grid, init_file, width, height);
init_file.close();
int starty = (getmaxy(stdscr) - height) / 2;
int startx = (getmaxx(stdscr) - width) / 2;
WINDOW* game_window = createGameWindow(height, width, starty, startx);
wrefresh(game_window);
// main game loop
for (int t = 0; t < turns; ++t) {
printFrame(game_window, life_grid);
sleep_for(milliseconds(150));
step(life_grid, buffer, width, height);
}
delwin(game_window);
endwin(); // end curses mode
return 0;
}
|
#include <ncurses.h>
#include <fstream>
using std::ifstream;
#include <string>
using std::string; using std::getline;
#include <thread>
using std::this_thread::sleep_for;
#include <chrono>
using std::chrono::milliseconds;
#define TEST_FILE "init_samples/glider_gun.txt"
#define ALIVE '#'
#define DEAD '.'
/* To Do:
- create struct for game window that stores the grid size and number of turns
- add welcome screen
- add main menu with options:
- load state from file
- set state interactively
- quit
- add exceptions where noted
- make grid/buffer swap into own function
*/
// create 2D array to use as the grid
bool** createGridArray(int grid_width, int grid_height)
{
bool** grid_array_pointer = new bool*[grid_height];
for (int i = 0; i < grid_height; ++i) {
grid_array_pointer[i] = new bool[grid_width];
}
return grid_array_pointer;
}
// set initial state of the grid
// ADD AN EXCEPTION HERE FOR "FILE NOT FOUND"
void setInitialState(bool** grid, ifstream& init_file, int grid_width, int grid_height)
{
// get a line to represent each row and copy it into the grid
string row;
for (int y = 0; y < grid_height; ++y) {
getline(init_file,row);
for (int x = 0; x < grid_width; ++x) {
if (row[x] == ALIVE) {
grid[y][x] = true;
}
else if (row[x] == DEAD) {
grid[y][x] = false;
}
else {
// raise not_implemented_error;
}
}
}
}
// return the number of neighboring cells that are alive
int countNeighbors(bool** grid, int grid_width, int grid_height, int target_y, int target_x)
{
int live_neighbors = 0;
for (int y = target_y - 1; y <= target_y + 1; ++y) {
for (int x = target_x - 1; x <= target_x + 1; ++x) {
if (y == target_y && x == target_x) // ignore target itself
continue;
// add length of row/column to offset effect of negative integer in mod calculation
if (grid[(y + grid_height) % grid_height][(x + grid_width) % grid_width])
++live_neighbors;
}
}
return live_neighbors;
}
// write buffer to displayed grid, then clear it
void bufferSwap(bool** grid, bool** buffer, int grid_width, int grid_height)
{
for (int i = 0; i < grid_height; ++i) {
for (int j = 0; j < grid_width; ++j) {
grid[i][j] = buffer[i][j];
buffer[i][j] = false;
}
}
}
// determine if cells live or die
void step(bool** grid, bool** buffer, int grid_width, int grid_height)
{
int live_neighbors;
for (int y = 0; y < grid_height; ++y) {
for (int x = 0; x < grid_width; ++x) {
live_neighbors = countNeighbors(grid, grid_width, grid_height, y, x);
// live cell with fewer than two live neighbors dies (under-population)
if (grid[y][x] && live_neighbors < 2 )
buffer[y][x] = false;
// live cell with two or three live neighbors lives on to next generation
else if ((grid[y][x] && live_neighbors == 2) || (grid[y][x] && live_neighbors == 3))
buffer[y][x] = true;
// live cell with more than three neighbors dies (over-population)
else if (grid[y][x] && live_neighbors > 3)
buffer[y][x] = false;
// dead cell with exactly three live neighbors becomes a live cell (reproduction)
else if (!grid[y][x] && live_neighbors == 3)
buffer[y][x] = true;
}
}
bufferSwap(grid, buffer, grid_width, grid_height);
}
void printFrame(WINDOW* win, bool** grid)
{
int h, w;
werase(win);
getmaxyx(win, h, w);
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
if (grid[i][j])
mvwaddch(win, i, j, ALIVE);
}
}
wrefresh(win);
}
WINDOW* createGameWindow(int height, int width, int starty, int startx)
{
WINDOW* win;
win = newwin(height, width, starty, startx);
wrefresh(win);
return win;
}
int main()
{
int turns, width, height;
initscr(); // start curses mode
noecho();
cbreak(); // disable line buffering
curs_set(0);
ifstream init_file;
init_file.open(TEST_FILE);
init_file >> turns >> width >> height;
init_file.seekg(1, init_file.cur);
bool** life_grid = createGridArray(width, height);
bool** buffer = createGridArray(width, height);
setInitialState(life_grid, init_file, width, height);
init_file.close();
int starty = (getmaxy(stdscr) - height) / 2;
int startx = (getmaxx(stdscr) - width) / 2;
WINDOW* game_window = createGameWindow(height, width, starty, startx);
wrefresh(game_window);
// main game loop
for (int t = 0; t < turns; ++t) {
printFrame(game_window, life_grid);
sleep_for(milliseconds(150));
step(life_grid, buffer, width, height);
}
delwin(game_window);
endwin(); // end curses mode
return 0;
}
|
add bufferSwap function
|
add bufferSwap function
|
C++
|
mit
|
leftysolara/Game_of_Life
|
74380665db605dd8f3417648fb74b18c5c9c7006
|
main.cpp
|
main.cpp
|
#include "opencv2/core/utility.hpp"
#include "opencv2/core/ocl.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/xfeatures2d.hpp"
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <iostream>
#include <cctype>
#include "Camshift.hpp"
#include "SurfMatcher.hpp"
#include "TestFile.hpp"
#include "ColorBalance.hpp"
#include "BlurDectection.hpp"
using namespace std;
using namespace cv;
using namespace cv::xfeatures2d;
char scenePath[100] = "../scene/";
//char diagonal[1] = "/";
TestFile _TF;
int main(int argc, const char ** argv)
{
//匯入檔案
Mat imgObject = imread( argv[1], IMREAD_COLOR );//object.png
_TF.InitTestFile(argv[2], argv[3], argv[4]);//input,output,result
for(int index = 0; index < 15; index++)
{
strcpy(scenePath, "../scene/");
//讀取scene
//imgBuffer = new char[_TF.GetImgByIndex(index).length() + 1];
char imgBuffer[50];
strcpy(imgBuffer, _TF.GetImgByIndex(index).c_str());
strcat(scenePath, imgBuffer); //從檔案輸入scene圖片及加上路徑
cout << "scenePath = " << scenePath << endl;
Mat imgScene = imread(scenePath , IMREAD_COLOR ); //讀取場景圖片
//模糊偵測
//BlurDectect(imgScene);
//將圖片檔名稱去除副檔名
char imageBasePath[20] = "../imageOutput/";
int folderIndex = index + 1;
char folderIndexChar[5];
sprintf(folderIndexChar, "%d", folderIndex);
strcpy(folderIndexChar, _TF.FillDigit(folderIndexChar));
cout << "folderIndexChar = " << folderIndexChar << endl;
// waitKey(0);
// return EXIT_SUCCESS;
//先色彩平衡再灰階 失敗
//Mat imgSceneCB;
//Mat imgObjectCB;
//ColorBalance(imgScene,imgSceneCB,1);
//ColorBalance(imgObject,imgObjectCB,1);
//Mat imgSceneGary;
//Mat imgObjectGary;
//cvtColor(imgSceneCB, imgSceneGary, CV_BGR2GRAY);
//cvtColor(imgObjectCB, imgObjectGary, CV_BGR2GRAY);
//File測試
// for(int i = 0; i < _TF.GetImgVectorSize(); i++)
// {
// _TF.WriteToOutput(_TF.GetImgByIndex(i));
// }
// _TF.WriteDownOutput();
//
// _TF.Close();
//File測試結束
Mat imgID = SurfMatch(imgObject, imgScene);//切割出身份證樣本區域
//驗證樣本區域size是否大於size(800(寬),480(高))
resize(imgID, imgID, Size(800, 480));//大於的話就resize成較好辨識的大小;否則不辨識
imshow("resized", imgID);
//割出身份證字號樣本
Mat imgIdNumber = imgID(Rect(580, 400, 210, 70)).clone();
imshow("IdNumber", imgIdNumber);
char imgIdNumberName[] = "/IdNum.png";
char imgIdNumberPath[50];
strcpy(imgIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgIdNumberName));
cout << "imgIdNumberPath = " << imgIdNumberPath << endl;
imwrite(imgIdNumberPath, imgIdNumber);
//把身份證字號樣本放到較大的黑底圖上
Mat bigSizeMat(960, 1280, CV_8UC3, Scalar::all(0));
imgIdNumber.copyTo(bigSizeMat(Rect(100, 100, imgIdNumber.cols, imgIdNumber.rows)));
char imgBigSizeName[] = "/bigSizeMat.png";
char imgBigSizePath[50];
strcpy(imgBigSizePath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgBigSizeName));
imwrite(imgBigSizePath, bigSizeMat);
//割出字號上每個數字到subNumber
vector<Mat> subNumber;
for(int i = 0; i < 10; i++)
{
Mat subMat = imgIdNumber(Rect(i * 21, 0, 21, 70)).clone();
Mat bigSizeSubMat(960, 1280, CV_8UC3, Scalar::all(0));//用成大圖片 較好用OCR
subMat.copyTo(bigSizeSubMat(Rect(50, 50, subMat.cols, subMat.rows)));
subNumber.push_back(bigSizeSubMat);//切割成一個一個的數字
}
//顯示各個數字&儲存
char imgSubIdNumberPath[50];
for(int i = 0; i < 10; i++)
{
char charNum[1];
sprintf(charNum, "%d", i);
imshow(charNum, subNumber[i]);
char fileName[] = "/subNum";
strcat(fileName, charNum);
char type[] = ".png";
strcat(fileName, type);
strcpy(imgSubIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, fileName));
cout << "imgSubIdNumberPath = " << imgSubIdNumberPath << endl;
imwrite(imgSubIdNumberPath, subNumber[i]);
}
//灰階
char imgGrayIdNumberPath[50];
char imgGrayIdNumberName[] = "/imgIdNumber_gray.png";
cvtColor(imgIdNumber, imgIdNumber, CV_BGR2GRAY);
strcpy(imgGrayIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgGrayIdNumberName));
imwrite(imgGrayIdNumberPath, imgIdNumber);
//做等化統計圖
char imgEqualizeIdNumberPath[50];
char imgEqualizeIdNumberName[] = "/imgIdNumber_Equalize.png";
equalizeHist( imgIdNumber, imgIdNumber );
strcpy(imgEqualizeIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgEqualizeIdNumberName));
imwrite(imgEqualizeIdNumberPath, imgIdNumber);
//二值化
// Set threshold and maxValue
double thresh = 127;
double maxValue = 255;
Mat whiteWord;
Mat whiteLight;
char whiteWordPath[50];
char whiteWordName[20];
char whiteLightPath[50];
char whiteLightName[20];
int threshTemp;
for(int i = 0; i < 8; i++)
{
threshTemp = i * 32;
char s1[10];
sprintf(s1, "%d", threshTemp);
threshold(imgIdNumber,whiteWord,threshTemp, maxValue, THRESH_BINARY_INV);//字變白底變黑
strcpy(whiteWordName, "/1_whiteWord");
strcat(whiteWordName, s1);
strcat(whiteWordName, ".png");
strcpy(whiteWordPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, whiteWordName));
imwrite(whiteWordPath, whiteWord);
threshold(imgIdNumber,whiteLight, threshTemp, maxValue, THRESH_BINARY);//反光變白
strcpy(whiteLightName, "/2_whiteLight");
strcat(whiteLightName, s1);
strcat(whiteLightName, ".png");
strcpy(whiteLightPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, whiteLightName));
imwrite(whiteLightPath,whiteLight);
}
// Binary Threshold
char imgBiraryIdNumberPath[50];
char imgBinaryName[] = "/imgIdNumber_binary.png";
threshold(imgIdNumber,imgIdNumber, 32, maxValue, THRESH_BINARY_INV);//字變白底變黑
strcpy(imgBiraryIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgBigSizeName));
imwrite(imgBiraryIdNumberPath, imgIdNumber);
//閉合(先膨脹再侵蝕)
Mat element = getStructuringElement(MORPH_RECT, Size(2, 2));
Mat closeImg;
morphologyEx( imgIdNumber, imgIdNumber, MORPH_CLOSE, element);
//中值濾波
char imgMedianIdNumberPath[50];
char imgMedianName[] = "/imgIdNumber_medianBlur.png";
medianBlur(imgIdNumber, imgIdNumber, 3);
strcpy(imgMedianIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgMedianName));
imwrite(imgMedianIdNumberPath, imgIdNumber);
//OCR處理
//Mat imgTest =imread( "scenetext02.jpg", IMREAD_COLOR );
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
api -> Init("/home/tyson/tessdata/", "eng", tesseract::OEM_DEFAULT);
api -> SetPageSegMode(tesseract::PSM_SINGLE_BLOCK);
api -> SetImage((uchar*)imgIdNumber.data, imgIdNumber.size().width, imgIdNumber.size().height,
imgIdNumber.channels(), imgIdNumber.step1());
api -> Recognize(0);
const char* eng = api -> GetUTF8Text();
char outputString[15] = "";
strncpy(outputString, eng, 10);
cout << "String:" << outputString << endl;
api -> End();
//Mat img =imread( argv[1], IMREAD_COLOR );
//camshift(output);
//camshift2(output);
_TF.WriteToOutput(outputString);
}
_TF.WriteDownOutput();
_TF.MatchResult();
waitKey(0);
return EXIT_SUCCESS;
}
//./main ../template/object2.png ../test/inputTest.txt ../test/outputTest.txt ../test/testResult.txt
|
/*
* Copyright 2016 Tai-Yuan Chen
* 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 "opencv2/core/utility.hpp"
#include "opencv2/core/ocl.hpp"
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/xfeatures2d.hpp"
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include <iostream>
#include <cctype>
#include "Camshift.hpp"
#include "SurfMatcher.hpp"
#include "TestFile.hpp"
#include "ColorBalance.hpp"
#include "BlurDectection.hpp"
using namespace std;
using namespace cv;
using namespace cv::xfeatures2d;
char scenePath[100] = "../scene/";
//char diagonal[1] = "/";
TestFile _TF;
int main(int argc, const char ** argv)
{
//匯入檔案
Mat imgObject = imread( argv[1], IMREAD_COLOR );//object.png
_TF.InitTestFile(argv[2], argv[3], argv[4]);//input,output,result
for(int index = 0; index < 15; index++)
{
strcpy(scenePath, "../scene/");
//讀取scene
//imgBuffer = new char[_TF.GetImgByIndex(index).length() + 1];
char imgBuffer[50];
strcpy(imgBuffer, _TF.GetImgByIndex(index).c_str());
strcat(scenePath, imgBuffer); //從檔案輸入scene圖片及加上路徑
cout << "scenePath = " << scenePath << endl;
Mat imgScene = imread(scenePath , IMREAD_COLOR ); //讀取場景圖片
//模糊偵測
//BlurDectect(imgScene);
//將圖片檔名稱去除副檔名
char imageBasePath[20] = "../imageOutput/";
int folderIndex = index + 1;
char folderIndexChar[5];
sprintf(folderIndexChar, "%d", folderIndex);
strcpy(folderIndexChar, _TF.FillDigit(folderIndexChar));
cout << "folderIndexChar = " << folderIndexChar << endl;
// waitKey(0);
// return EXIT_SUCCESS;
//先色彩平衡再灰階 失敗
//Mat imgSceneCB;
//Mat imgObjectCB;
//ColorBalance(imgScene,imgSceneCB,1);
//ColorBalance(imgObject,imgObjectCB,1);
//Mat imgSceneGary;
//Mat imgObjectGary;
//cvtColor(imgSceneCB, imgSceneGary, CV_BGR2GRAY);
//cvtColor(imgObjectCB, imgObjectGary, CV_BGR2GRAY);
//File測試
// for(int i = 0; i < _TF.GetImgVectorSize(); i++)
// {
// _TF.WriteToOutput(_TF.GetImgByIndex(i));
// }
// _TF.WriteDownOutput();
//
// _TF.Close();
//File測試結束
Mat imgID = SurfMatch(imgObject, imgScene);//切割出身份證樣本區域
//驗證樣本區域size是否大於size(800(寬),480(高))
resize(imgID, imgID, Size(800, 480));//大於的話就resize成較好辨識的大小;否則不辨識
imshow("resized", imgID);
//割出身份證字號樣本
Mat imgIdNumber = imgID(Rect(580, 400, 210, 70)).clone();
imshow("IdNumber", imgIdNumber);
char imgIdNumberName[] = "/IdNum.png";
char imgIdNumberPath[50];
strcpy(imgIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgIdNumberName));
cout << "imgIdNumberPath = " << imgIdNumberPath << endl;
imwrite(imgIdNumberPath, imgIdNumber);
//把身份證字號樣本放到較大的黑底圖上
Mat bigSizeMat(960, 1280, CV_8UC3, Scalar::all(0));
imgIdNumber.copyTo(bigSizeMat(Rect(100, 100, imgIdNumber.cols, imgIdNumber.rows)));
char imgBigSizeName[] = "/bigSizeMat.png";
char imgBigSizePath[50];
strcpy(imgBigSizePath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgBigSizeName));
imwrite(imgBigSizePath, bigSizeMat);
//割出字號上每個數字到subNumber
vector<Mat> subNumber;
for(int i = 0; i < 10; i++)
{
Mat subMat = imgIdNumber(Rect(i * 21, 0, 21, 70)).clone();
Mat bigSizeSubMat(960, 1280, CV_8UC3, Scalar::all(0));//用成大圖片 較好用OCR
subMat.copyTo(bigSizeSubMat(Rect(50, 50, subMat.cols, subMat.rows)));
subNumber.push_back(bigSizeSubMat);//切割成一個一個的數字
}
//顯示各個數字&儲存
char imgSubIdNumberPath[50];
for(int i = 0; i < 10; i++)
{
char charNum[1];
sprintf(charNum, "%d", i);
imshow(charNum, subNumber[i]);
char fileName[] = "/subNum";
strcat(fileName, charNum);
char type[] = ".png";
strcat(fileName, type);
strcpy(imgSubIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, fileName));
cout << "imgSubIdNumberPath = " << imgSubIdNumberPath << endl;
imwrite(imgSubIdNumberPath, subNumber[i]);
}
//灰階
char imgGrayIdNumberPath[50];
char imgGrayIdNumberName[] = "/imgIdNumber_gray.png";
cvtColor(imgIdNumber, imgIdNumber, CV_BGR2GRAY);
strcpy(imgGrayIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgGrayIdNumberName));
imwrite(imgGrayIdNumberPath, imgIdNumber);
//做等化統計圖
char imgEqualizeIdNumberPath[50];
char imgEqualizeIdNumberName[] = "/imgIdNumber_Equalize.png";
equalizeHist( imgIdNumber, imgIdNumber );
strcpy(imgEqualizeIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgEqualizeIdNumberName));
imwrite(imgEqualizeIdNumberPath, imgIdNumber);
//二值化
// Set threshold and maxValue
double thresh = 127;
double maxValue = 255;
Mat whiteWord;
Mat whiteLight;
char whiteWordPath[50];
char whiteWordName[20];
char whiteLightPath[50];
char whiteLightName[20];
int threshTemp;
for(int i = 0; i < 8; i++)
{
threshTemp = i * 32;
char s1[10];
sprintf(s1, "%d", threshTemp);
threshold(imgIdNumber,whiteWord,threshTemp, maxValue, THRESH_BINARY_INV);//字變白底變黑
strcpy(whiteWordName, "/1_whiteWord");
strcat(whiteWordName, s1);
strcat(whiteWordName, ".png");
strcpy(whiteWordPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, whiteWordName));
imwrite(whiteWordPath, whiteWord);
threshold(imgIdNumber,whiteLight, threshTemp, maxValue, THRESH_BINARY);//反光變白
strcpy(whiteLightName, "/2_whiteLight");
strcat(whiteLightName, s1);
strcat(whiteLightName, ".png");
strcpy(whiteLightPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, whiteLightName));
imwrite(whiteLightPath,whiteLight);
}
// Binary Threshold
char imgBiraryIdNumberPath[50];
char imgBinaryName[] = "/imgIdNumber_binary.png";
threshold(imgIdNumber,imgIdNumber, 32, maxValue, THRESH_BINARY_INV);//字變白底變黑
strcpy(imgBiraryIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgBigSizeName));
imwrite(imgBiraryIdNumberPath, imgIdNumber);
//閉合(先膨脹再侵蝕)
Mat element = getStructuringElement(MORPH_RECT, Size(2, 2));
Mat closeImg;
morphologyEx( imgIdNumber, imgIdNumber, MORPH_CLOSE, element);
//中值濾波
char imgMedianIdNumberPath[50];
char imgMedianName[] = "/imgIdNumber_medianBlur.png";
medianBlur(imgIdNumber, imgIdNumber, 3);
strcpy(imgMedianIdNumberPath, _TF.ImageOutputPath(imageBasePath, folderIndexChar, imgMedianName));
imwrite(imgMedianIdNumberPath, imgIdNumber);
//OCR處理
//Mat imgTest =imread( "scenetext02.jpg", IMREAD_COLOR );
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
api -> Init("/home/tyson/tessdata/", "eng", tesseract::OEM_DEFAULT);
api -> SetPageSegMode(tesseract::PSM_SINGLE_BLOCK);
api -> SetImage((uchar*)imgIdNumber.data, imgIdNumber.size().width, imgIdNumber.size().height,
imgIdNumber.channels(), imgIdNumber.step1());
api -> Recognize(0);
const char* eng = api -> GetUTF8Text();
char outputString[15] = "";
strncpy(outputString, eng, 10);
cout << "String:" << outputString << endl;
api -> End();
//Mat img =imread( argv[1], IMREAD_COLOR );
//camshift(output);
//camshift2(output);
_TF.WriteToOutput(outputString);
}
_TF.WriteDownOutput();
_TF.MatchResult();
waitKey(0);
return EXIT_SUCCESS;
}
//./main ../template/object2.png ../test/inputTest.txt ../test/outputTest.txt ../test/testResult.txt
|
Update main.cpp
|
Update main.cpp
新增標頭版權宣言
|
C++
|
apache-2.0
|
tyson3822/IdentityCardNumberRecognition
|
57239a543f3802395f27f974c02b022b6bdc5d3b
|
main.cpp
|
main.cpp
|
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
cout << "Arguments:" << endl;
for (int i = 0; i < argc; i++) {
cout << " " << i << ": " << argv[i] << endl;
}
return 0;
}
|
#include <iostream>
using namespace std;
static void showLogo() {
cout << "\n"
"---------------------------\n"
" /\\ \n"
" \\/ Draupnir v0.0.1 \n"
" /\\ \n"
"---------------------------\n"
"\n";
}
int main(int argc, char *argv[]) {
showLogo();
cout << "Arguments:" << endl;
for (int i = 0; i < argc; i++) {
cout << " " << i << ": " << argv[i] << endl;
}
return 0;
}
|
Add draupnir logo
|
Add draupnir logo
|
C++
|
agpl-3.0
|
mariano-perez-rodriguez/draupnir
|
0c3d1eef074907927d023b162231ae2cfa575c7d
|
main.cpp
|
main.cpp
|
#include "imgui.h"
#include "imgui-sfml.h"
#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800,600),"ReIGen", sf::Style::Titlebar|
sf::Style::Close);
ImGui::SFML::Init(window);
sf::Clock deltaClock;
window.resetGLStates();
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
ImGui::SFML::ProcessEvent(event);
if (event.type == sf::Event::Closed)
window.close();
}
ImGui::SFML::Update(window, deltaClock.restart());
ImGui::SetNextWindowPos(ImVec2(600,0));
ImGui::SetNextWindowSize(ImVec2(200,600));
ImGui::Begin("Settings", false, ImGuiWindowFlags_NoTitleBar|
ImGuiWindowFlags_NoResize|
ImGuiWindowFlags_NoMove|
ImGuiWindowFlags_NoCollapse|
ImGuiWindowFlags_ShowBorders);
ImGui::End();
window.clear();
ImGui::Render();
window.display();
}
ImGui::SFML::Shutdown();
return 0;
}
|
#include "imgui.h"
#include "imgui-sfml.h"
#include <SFML/Graphics.hpp>
#include <SFML/System/Clock.hpp>
// TEMP
enum class Direction{
HORIZONTAL,
VERTICAL,
BOTH
};
void drawLine(sf::RenderWindow &window, sf::RectangleShape &line,
const sf::Color &color=sf::Color::White, const int step=10,
const Direction direction=Direction::BOTH, const int lineWidth=1)
{
if(direction == Direction::BOTH){
drawLine(window, line, color, step, Direction::HORIZONTAL);
drawLine(window, line, color, step, Direction::VERTICAL);
}
else{
sf::Vector2u winSize{window.getSize()};
int edge{0};
line.setFillColor(color);
switch(direction){
case Direction::HORIZONTAL:
edge = window.getSize().x;
line.setSize(sf::Vector2f(edge,lineWidth));
break;
case Direction::VERTICAL:
edge = window.getSize().y;
line.setSize(sf::Vector2f(lineWidth,edge));
break;
}
for(int i=0; i<edge; i+=step){
switch(direction){
case Direction::HORIZONTAL:
line.setPosition(0,i);
break;
case Direction::VERTICAL:
line.setPosition(i,0);
break;
}
window.draw(line);
}
}
}
void drawGrid(sf::RenderWindow &window)
{
sf::RectangleShape line;
int steps[]{12,24,96};
sf::Color colors[]{sf::Color {35,85,125},
sf::Color {40,90,130},
sf::Color {60,110,150}};
for(int i=0;i<3;++i)
drawLine(window,line,colors[i],steps[i]);
}
int main()
{
sf::RenderWindow window(sf::VideoMode(800,600),"ReIGen", sf::Style::Titlebar|
sf::Style::Close);
sf::Color bgColor(30,80,120);
ImGui::SFML::Init(window);
sf::Clock deltaClock;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
ImGui::SFML::ProcessEvent(event);
if (event.type == sf::Event::Closed)
window.close();
}
ImGui::SFML::Update(window, deltaClock.restart());
ImGui::SetNextWindowPos(ImVec2(600,0));
ImGui::SetNextWindowSize(ImVec2(200,600));
ImGui::Begin("Settings", false, ImGuiWindowFlags_NoTitleBar|
ImGuiWindowFlags_NoResize|
ImGuiWindowFlags_NoMove|
ImGuiWindowFlags_NoCollapse|
ImGuiWindowFlags_ShowBorders);
ImGui::End();
window.clear(bgColor);
drawGrid(window);
ImGui::Render();
window.display();
}
ImGui::SFML::Shutdown();
return 0;
}
|
add background grid drawing
|
add background grid drawing
|
C++
|
mit
|
testoo1/TEST_ReIGen
|
7a3b5c5d93a7eed228813ac7220e9029932807ae
|
main.cpp
|
main.cpp
|
#include "main.h"
void PrintSize(size_t size)
{
if (size < 1024)
{
std::cout << size << " B";
}
else if (size < 1024 * 1024)
{
std::cout << size / 1024.0 << " KB";
}
else
{
std::cout << size / 1024.0 / 1024.0 << " MB";
}
}
#ifdef _WIN32
int ProcessFile(const wchar_t *file_path)
{
char mbs[256] = { 0 };
WideCharToMultiByte(CP_ACP, 0, file_path, -1, mbs, sizeof(mbs), nullptr, nullptr);
std::cout << "Processing: " << mbs << std::endl;
#else
// written like this in order to be callback funtion of ftw()
int ProcessFile(const char file_path[], const struct stat *sb = nullptr, int typeflag = FTW_F)
{
if (typeflag != FTW_F)
{
return 0;
}
std::cout << "Processing: " << file_path << std::endl;
#endif // _WIN32
File input_file(file_path);
if (input_file.IsOK())
{
size_t original_size = input_file.GetSize();
size_t new_size = LeanifyFile(input_file.GetFilePionter(), original_size);
PrintSize(original_size);
std::cout << " -> ";
PrintSize(new_size);
std::cout << "\tLeanified: ";
PrintSize(original_size - new_size);
std::cout << " (" << 100 - 100.0 * new_size / original_size << "%)" << std::endl;
input_file.UnMapFile(new_size);
}
return 0;
}
void PauseIfNotTerminal()
{
// pause if Leanify is not started in terminal
// so that user can see the output instead of just a flash of a black box
#ifdef _WIN32
if (!getenv("PROMPT"))
{
system("pause");
}
#endif // _WIN32
}
void PrintInfo()
{
std::cerr << "Leanify\t" << VERSION << std::endl << std::endl;
std::cerr << "Usage: Leanify [options] paths" << std::endl;
std::cerr << " -i iteration\tMore iterations means slower but better result. Default: 15." << std::endl;
std::cerr << " -f\t\tFast mode, no recompression." << std::endl;
std::cerr << " -q\t\tQuiet mode, no output." << std::endl;
std::cerr << " -v\t\tVerbose output." << std::endl;
PauseIfNotTerminal();
}
#ifdef _WIN32
int main()
{
int argc;
wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
#else
int main(int argc, char const *argv[])
{
#endif // _WIN32
is_fast = false;
is_verbose = false;
iterations = 15;
level = 0;
int i;
for (i = 1; i < argc && argv[i][0] == L'-'; i++)
{
bool need_plus1 = false;
for (int j = 1; argv[i][j]; j++)
{
switch (argv[i][j])
{
case 'f':
case 'F':
is_fast = true;
break;
case 'i':
case 'I':
if (i < argc - 1)
{
#ifdef _WIN32
iterations = wcstol(argv[i + 1], nullptr, 10);
#else
iterations = strtol(argv[i + 1], nullptr, 10);
#endif // _WIN32
// strtol will return 0 on fail
if (iterations == 0)
{
std::cerr << "There should be a positive number after -i option." << std::endl;
PrintInfo();
return 1;
}
need_plus1 = true;
}
break;
case 'q':
case 'Q':
std::cout.setstate(std::ios::failbit);
is_verbose = false;
break;
case 'v':
case 'V':
std::cout.clear();
is_verbose = true;
break;
default:
PrintInfo();
return 1;
}
}
if (need_plus1)
{
i++;
}
}
if (i == argc)
{
std::cerr << "No file path provided." << std::endl;
PrintInfo();
return 1;
}
std::cout << std::fixed;
std::cout.precision(2);
// support multiple input file
do
{
if (IsDirectory(argv[i]))
{
// directory
TraverseDirectory(argv[i], ProcessFile);
}
else
{
// file
ProcessFile(argv[i]);
}
} while (++i < argc);
PauseIfNotTerminal();
return 0;
}
|
#include "main.h"
void PrintSize(size_t size)
{
if (size < 1024)
{
std::cout << size << " B";
}
else if (size < 1024 * 1024)
{
std::cout << size / 1024.0 << " KB";
}
else
{
std::cout << size / 1024.0 / 1024.0 << " MB";
}
}
#ifdef _WIN32
int ProcessFile(const wchar_t *file_path)
{
char mbs[256] = { 0 };
WideCharToMultiByte(CP_ACP, 0, file_path, -1, mbs, sizeof(mbs), nullptr, nullptr);
std::cout << "Processing: " << mbs << std::endl;
#else
// written like this in order to be callback funtion of ftw()
int ProcessFile(const char file_path[], const struct stat *sb = nullptr, int typeflag = FTW_F)
{
if (typeflag != FTW_F)
{
return 0;
}
std::cout << "Processing: " << file_path << std::endl;
#endif // _WIN32
File input_file(file_path);
if (input_file.IsOK())
{
size_t original_size = input_file.GetSize();
size_t new_size = LeanifyFile(input_file.GetFilePionter(), original_size);
PrintSize(original_size);
std::cout << " -> ";
PrintSize(new_size);
std::cout << "\tLeanified: ";
PrintSize(original_size - new_size);
std::cout << " (" << 100 - 100.0 * new_size / original_size << "%)" << std::endl;
input_file.UnMapFile(new_size);
}
return 0;
}
void PauseIfNotTerminal()
{
// pause if Leanify is not started in terminal
// so that user can see the output instead of just a flash of a black box
#ifdef _WIN32
if (!getenv("PROMPT"))
{
system("pause");
}
#endif // _WIN32
}
void PrintInfo()
{
std::cerr << "Leanify\t" << VERSION << std::endl << std::endl;
std::cerr << "Usage: Leanify [options] paths" << std::endl;
std::cerr << " -i iteration\tMore iterations means slower but better result. Default: 15." << std::endl;
std::cerr << " -f\t\tFast mode, no recompression." << std::endl;
std::cerr << " -q\t\tQuiet mode, no output." << std::endl;
std::cerr << " -v\t\tVerbose output." << std::endl;
PauseIfNotTerminal();
}
#ifdef _WIN32
int main()
{
int argc;
wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
#else
int main(int argc, char const *argv[])
{
#endif // _WIN32
is_fast = false;
is_verbose = false;
iterations = 15;
level = 0;
int i;
for (i = 1; i < argc && argv[i][0] == L'-'; i++)
{
bool need_plus1 = false;
for (int j = 1; argv[i][j]; j++)
{
switch (argv[i][j])
{
case 'f':
case 'F':
is_fast = true;
break;
case 'i':
case 'I':
if (i < argc - 1)
{
#ifdef _WIN32
iterations = wcstol(argv[i + 1], nullptr, 10);
#else
iterations = strtol(argv[i + 1], nullptr, 10);
#endif // _WIN32
// strtol will return 0 on fail
if (iterations == 0)
{
std::cerr << "There should be a positive number after -i option." << std::endl;
PrintInfo();
return 1;
}
need_plus1 = true;
}
break;
case 'q':
case 'Q':
std::cout.setstate(std::ios::failbit);
is_verbose = false;
break;
case 'v':
case 'V':
std::cout.clear();
is_verbose = true;
break;
default:
std::cerr << "Unknown option: " << (char)argv[i][j] << std::endl;
PrintInfo();
return 1;
}
}
if (need_plus1)
{
i++;
}
}
if (i == argc)
{
std::cerr << "No file path provided." << std::endl;
PrintInfo();
return 1;
}
std::cout << std::fixed;
std::cout.precision(2);
// support multiple input file
do
{
if (IsDirectory(argv[i]))
{
// directory
TraverseDirectory(argv[i], ProcessFile);
}
else
{
// file
ProcessFile(argv[i]);
}
} while (++i < argc);
PauseIfNotTerminal();
return 0;
}
|
print information about unknown option
|
print information about unknown option
|
C++
|
mit
|
JayXon/Leanify,yyjdelete/Leanify,JayXon/Leanify,yyjdelete/Leanify
|
16a92a84dd61d337e03dcedf6e5ffedd14e4b256
|
main.cpp
|
main.cpp
|
/*
* Copyright (C) 2016 - 2020 Judd Niemann - All Rights Reserved.
* You may use, distribute and modify this code under the
* terms of the GNU Lesser General Public License, version 2.1
*
* You should have received a copy of GNU Lesser General Public License v2.1
* with this file. If not, please refer to: https://github.com/jniemann66/ReSampler
*/
// main.cpp : defines main entry point
#include <iostream>
#include <string>
#if defined(__ANDROID__)
// define COMPILING_ON_ANDROID macro first before including any user headers
#define COMPILING_ON_ANDROID
#ifdef __aarch64__
#define COMPILING_ON_ANDROID64
#endif
#include <android/log.h>
// https://gist.github.com/dzhioev/6127982
class androidbuf : public std::streambuf {
public:
enum { bufsize = 1024 }; // ... or some other suitable buffer size
androidbuf(const int log_priority, const char * log_tag) :LOG_PRIORITY(log_priority), LOG_TAG(log_tag) { this->setp(buffer, buffer + bufsize - 1); };
private:
int overflow(int c) {
if (c == traits_type::eof()) {
*this->pptr() = traits_type::to_char_type(c);
this->sbumpc();
}
return this->sync() ? traits_type::eof() : traits_type::not_eof(c);
}
int sync() {
int rc = 0;
if (this->pbase() != this->pptr()) {
__android_log_print(LOG_PRIORITY, LOG_TAG, "%s", std::string(this->pbase(), this->pptr() - this->pbase()).c_str());
rc = 0;
this->setp(buffer, buffer + bufsize - 1);
}
return rc;
}
char buffer[bufsize];
const char * LOG_TAG;
const int LOG_PRIORITY;
};
void androidCleanup() {
delete std::cout.rdbuf(0);
delete std::cerr.rdbuf(0);
}
#endif // defined(__ANDROID__)
#include "ReSampler.h"
#include "mpxdecode.h"
#include "iqdemodulator.h"
int main(int argc, char * argv[])
{
#ifdef COMPILING_ON_ANDROID
std::cout.rdbuf(new androidbuf(ANDROID_LOG_INFO, "ReSampler"));
std::cerr.rdbuf(new androidbuf(ANDROID_LOG_ERROR, "ReSampler"));
#endif
int result = ReSampler::runCommand(argc, argv);
#ifdef COMPILING_ON_ANDROID
androidCleanup();
#endif
return result;
}
|
/*
* Copyright (C) 2016 - 2021 Judd Niemann - All Rights Reserved.
* You may use, distribute and modify this code under the
* terms of the GNU Lesser General Public License, version 2.1
*
* You should have received a copy of GNU Lesser General Public License v2.1
* with this file. If not, please refer to: https://github.com/jniemann66/ReSampler
*/
// main.cpp : defines main entry point
#include <iostream>
#include <string>
#if defined(__ANDROID__)
// define COMPILING_ON_ANDROID macro first before including any user headers
#define COMPILING_ON_ANDROID
#ifdef __aarch64__
#define COMPILING_ON_ANDROID64
#endif
#include <android/log.h>
// https://gist.github.com/dzhioev/6127982
class androidbuf : public std::streambuf {
public:
enum { bufsize = 1024 }; // ... or some other suitable buffer size
androidbuf(const int log_priority, const char * log_tag) :LOG_PRIORITY(log_priority), LOG_TAG(log_tag) { this->setp(buffer, buffer + bufsize - 1); };
private:
int overflow(int c) {
if (c == traits_type::eof()) {
*this->pptr() = traits_type::to_char_type(c);
this->sbumpc();
}
return this->sync() ? traits_type::eof() : traits_type::not_eof(c);
}
int sync() {
int rc = 0;
if (this->pbase() != this->pptr()) {
__android_log_print(LOG_PRIORITY, LOG_TAG, "%s", std::string(this->pbase(), this->pptr() - this->pbase()).c_str());
rc = 0;
this->setp(buffer, buffer + bufsize - 1);
}
return rc;
}
char buffer[bufsize];
const char * LOG_TAG;
const int LOG_PRIORITY;
};
void androidCleanup() {
delete std::cout.rdbuf(0);
delete std::cerr.rdbuf(0);
}
#endif // defined(__ANDROID__)
#include "ReSampler.h"
#include "mpxdecode.h"
#include "iqdemodulator.h"
int main(int argc, char * argv[])
{
#ifdef COMPILING_ON_ANDROID
std::cout.rdbuf(new androidbuf(ANDROID_LOG_INFO, "ReSampler"));
std::cerr.rdbuf(new androidbuf(ANDROID_LOG_ERROR, "ReSampler"));
#endif
int result = ReSampler::runCommand(argc, argv);
#ifdef COMPILING_ON_ANDROID
androidCleanup();
#endif
return result;
}
|
update copyright notice
|
update copyright notice
|
C++
|
lgpl-2.1
|
jniemann66/ReSampler,jniemann66/ReSampler,jniemann66/ReSampler,jniemann66/ReSampler,jniemann66/ReSampler,jniemann66/ReSampler,jniemann66/ReSampler,jniemann66/ReSampler
|
7fdfd8123dc072a6067067843fbfa28e68de6d37
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <array>
#include <SFML/Graphics.hpp>
#include "vector2.h"
#include "triangle.h"
#include "delaunay.h"
float RandomFloat(float a, float b) {
const float random = ((float) rand()) / (float) RAND_MAX;
const float diff = b - a;
const float r = random * diff;
return a + r;
}
int main()
{
srand (time(NULL));
float numberPoints = roundf(RandomFloat(4, 40));
std::cout << "Generating " << numberPoints << " random points" << std::endl;
std::vector<Vector2<float>> points;
for(int i = 0; i < numberPoints; i++) {
points.push_back(Vector2<float>(RandomFloat(0, 800), RandomFloat(0, 600)));
}
Delaunay<float> triangulation;
std::vector<Triangle<float>> triangles = triangulation.triangulate(points);
std::cout << triangles.size() << " triangles generated\n";
std::vector<Edge<float>> edges = triangulation.getEdges();
std::cout << " ========= ";
std::cout << "\nPoints : " << points.size() << std::endl;
for(auto &p : points)
std::cout << p << std::endl;
std::cout << "\nTriangles : " << triangles.size() << std::endl;
for(auto &t : triangles)
std::cout << t << std::endl;
std::cout << "\nEdges : " << edges.size() << std::endl;
for(auto &e : edges)
std::cout << e << std::endl;
// SFML window
sf::RenderWindow window(sf::VideoMode(800, 600), "Delaunay triangulation");
// Transform each points of each vector as a rectangle
std::vector<sf::RectangleShape*> squares;
for(auto p = begin(points); p != end(points); p++) {
sf::RectangleShape *c1 = new sf::RectangleShape(sf::Vector2f(4, 4));
c1->setPosition(p->x, p->y);
squares.push_back(c1);
}
// Make the lines
std::vector<std::array<sf::Vertex, 2> > lines;
for(auto e = begin(edges); e != end(edges); e++) {
lines.push_back({{
sf::Vertex(sf::Vector2f((*e).p1.x + 2, (*e).p1.y + 2)),
sf::Vertex(sf::Vector2f((*e).p2.x + 2, (*e).p2.y + 2))
}});
}
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
// Draw the squares
for(auto s = begin(squares); s != end(squares); s++) {
window.draw(**s);
}
// Draw the lines
for(auto l = begin(lines); l != end(lines); l++) {
window.draw((*l).data(), 2, sf::Lines);
}
window.display();
}
return 0;
}
|
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <array>
#include <SFML/Graphics.hpp>
#include "vector2.h"
#include "triangle.h"
#include "delaunay.h"
float RandomFloat(float a, float b) {
const float random = ((float) rand()) / (float) RAND_MAX;
const float diff = b - a;
const float r = random * diff;
return a + r;
}
int main(int argc, char * argv[])
{
int numberPoints = 40;
if (argc==1)
{
numberPoints = (int) roundf(RandomFloat(4, numberPoints));
}
else if (argc>1)
{
numberPoints = atoi(argv[1]);
}
srand (time(NULL));
std::cout << "Generating " << numberPoints << " random points" << std::endl;
std::vector<Vector2<float>> points;
for(int i = 0; i < numberPoints; i++) {
points.push_back(Vector2<float>(RandomFloat(0, 800), RandomFloat(0, 600)));
}
Delaunay<float> triangulation;
std::vector<Triangle<float>> triangles = triangulation.triangulate(points);
std::cout << triangles.size() << " triangles generated\n";
std::vector<Edge<float>> edges = triangulation.getEdges();
std::cout << " ========= ";
std::cout << "\nPoints : " << points.size() << std::endl;
for(auto &p : points)
std::cout << p << std::endl;
std::cout << "\nTriangles : " << triangles.size() << std::endl;
for(auto &t : triangles)
std::cout << t << std::endl;
std::cout << "\nEdges : " << edges.size() << std::endl;
for(auto &e : edges)
std::cout << e << std::endl;
// SFML window
sf::RenderWindow window(sf::VideoMode(800, 600), "Delaunay triangulation");
// Transform each points of each vector as a rectangle
std::vector<sf::RectangleShape*> squares;
for(auto p = begin(points); p != end(points); p++) {
sf::RectangleShape *c1 = new sf::RectangleShape(sf::Vector2f(4, 4));
c1->setPosition(p->x, p->y);
squares.push_back(c1);
}
// Make the lines
std::vector<std::array<sf::Vertex, 2> > lines;
for(auto e = begin(edges); e != end(edges); e++) {
lines.push_back({{
sf::Vertex(sf::Vector2f((*e).p1.x + 2, (*e).p1.y + 2)),
sf::Vertex(sf::Vector2f((*e).p2.x + 2, (*e).p2.y + 2))
}});
}
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
// Draw the squares
for(auto s = begin(squares); s != end(squares); s++) {
window.draw(**s);
}
// Draw the lines
for(auto l = begin(lines); l != end(lines); l++) {
window.draw((*l).data(), 2, sf::Lines);
}
window.display();
}
return 0;
}
|
Add the possibility to input number of points
|
Add the possibility to input number of points
|
C++
|
mit
|
Bl4ckb0ne/delaunay-triangulation
|
94d9d2de161ce5ab88a4587d7c29e66e894acc46
|
main.cpp
|
main.cpp
|
a4d8684f-2747-11e6-b93f-e0f84713e7b8
|
a4edc28f-2747-11e6-b293-e0f84713e7b8
|
Deal with it
|
Deal with it
|
C++
|
apache-2.0
|
jhelgglehj/rocket
|
5d962c1453d069fae1daaeb0e7f0b70bba037d2d
|
main.cpp
|
main.cpp
|
#include "AssassinWar.h"
#include <QtGui/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
AssassinWar w;
w.show();
return a.exec();
}
|
#include "AssassinWar.h"
#include <QtGui/QApplication>
int main(int argc, char *argv[])
{
QApplication AW_App(argc, argv);
AssassinWar AW;
AW.show();
return AW_App.exec();
}
|
change name
|
change name
change some name
|
C++
|
bsd-2-clause
|
TyrealGray/AssassinWar,TyrealGray/AssassinWar
|
ad9d5fb58fd29b678ed357258900b7fce4f8d540
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/function.hpp>
#include <sstream>
#include <string>
using namespace std;
void testVector();
void testLexicalCast();
void testFunction();
int main()
{
cout << "Hello, world!" << endl;
//testLexicalCast();
testFunction();
return 0;
}
void testVector()
{
std::vector<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
for (int i = 0; i < (int)numbers.size(); ++i)
cout << i << endl;
}
void testLexicalCast()
{
// 以下会抛出异常
//cout << boost::lexical_cast<int>(" 123 ") << endl;
//cout << boost::lexical_cast<int>("123 ") << endl;
//cout << boost::lexical_cast<int>("12 3") << endl;
//cout << boost::lexical_cast<int>("1 2 3") << endl;
// 空字符串会抛出异常
//cout << boost::lexical_cast<int>("") << endl;
// 不支持十六进制
//cout << boost::lexical_cast<int>("0x0362") << endl;
// 十六进制字符串转成整数 0x前缀可有可无
stringstream ss;
ss << hex << "0x0362f"; // 13871
int i;
ss >> i;
cout << i << endl;
// 十六进制字符串转成整数 C++11 中的 std::stoi <string>
cout << std::stoi("0x0362f", 0, 16) << endl;
cout << std::stoi("0362f", 0, 16) << endl;
//cout << std::stoi("", 0, 16) << endl; // 抛出异常
// 字符串转换为bool 只支持 0 和 1,不支持true或false或其他整数值
//cout << boost::lexical_cast<bool>("true") << endl;
//cout << boost::lexical_cast<bool>("false") << endl;
//cout << boost::lexical_cast<bool>("True") << endl;
//cout << boost::lexical_cast<bool>("-1") << endl;
//cout << boost::lexical_cast<bool>("2") << endl;
cout << boost::lexical_cast<bool>("1") << endl;
cout << boost::lexical_cast<bool>("0") << endl;
// test
}
void func(int i)
{
cout << i << endl;
}
class Test1
{
public:
void func()
{
cout << "Test1::func()" << endl;
}
void func2(int i)
{
cout << "Test1::func()" << i << endl;
}
};
void testFunction()
{
boost::function<void (int)> f1 = &func;
f1(12);
Test1 t1;
boost::function<void (Test1*)> f2 = &Test1::func;
f2(&t1);
boost::function<void (Test1*, int)> f3 = &Test1::func2;
f3(&t1, 100);
}
|
#include <iostream>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <sstream>
#include <string>
using namespace std;
void testVector();
void testLexicalCast();
void testFunction();
void testBind();
int main()
{
cout << "Hello, world!" << endl;
//testLexicalCast();
//testFunction();
testBind();
return 0;
}
void testVector()
{
std::vector<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
for (int i = 0; i < (int)numbers.size(); ++i)
cout << i << endl;
}
void testLexicalCast()
{
// 以下会抛出异常
//cout << boost::lexical_cast<int>(" 123 ") << endl;
//cout << boost::lexical_cast<int>("123 ") << endl;
//cout << boost::lexical_cast<int>("12 3") << endl;
//cout << boost::lexical_cast<int>("1 2 3") << endl;
// 空字符串会抛出异常
//cout << boost::lexical_cast<int>("") << endl;
// 不支持十六进制
//cout << boost::lexical_cast<int>("0x0362") << endl;
// 十六进制字符串转成整数 0x前缀可有可无
stringstream ss;
ss << hex << "0x0362f"; // 13871
int i;
ss >> i;
cout << i << endl;
// 十六进制字符串转成整数 C++11 中的 std::stoi <string>
cout << std::stoi("0x0362f", 0, 16) << endl;
cout << std::stoi("0362f", 0, 16) << endl;
//cout << std::stoi("", 0, 16) << endl; // 抛出异常
// 字符串转换为bool 只支持 0 和 1,不支持true或false或其他整数值
//cout << boost::lexical_cast<bool>("true") << endl;
//cout << boost::lexical_cast<bool>("false") << endl;
//cout << boost::lexical_cast<bool>("True") << endl;
//cout << boost::lexical_cast<bool>("-1") << endl;
//cout << boost::lexical_cast<bool>("2") << endl;
cout << boost::lexical_cast<bool>("1") << endl;
cout << boost::lexical_cast<bool>("0") << endl;
// test
}
void func(int i)
{
cout << i << endl;
}
class Test1
{
public:
void func()
{
cout << "Test1::func()" << endl;
}
void func2(int i)
{
cout << "Test1::func()" << i << endl;
}
};
void testFunction()
{
boost::function<void (int)> f1 = &func;
f1(12);
Test1 t1;
boost::function<void (Test1*)> f2 = &Test1::func;
f2(&t1);
boost::function<void (Test1*, int)> f3 = &Test1::func2;
f3(&t1, 100);
}
void testBind()
{
Test1 t1;
auto f1 = boost::bind(&Test1::func2, &t1, _1);
f1(100);
}
|
Test boost::bind
|
Test boost::bind
|
C++
|
mit
|
yjwx0017/test,yjwx0017/test,yjwx0017/test
|
fd5c7c1ad0d0366aa7026b64257b27b66084da17
|
main.cpp
|
main.cpp
|
#include "layouter.h"
#include "layouterSDL.h"
#define TXT_WIDTH 700
#define WIN_WIDTH 800
int main ()
{
textStyleSheet_c styleSheet;
// setze default sprache des textes
styleSheet.language="en-Engl";
// alle Fonts, die so genutzt werden: familie heißt sans, und dann der bold Font dazu
styleSheet.font("sans", "/usr/share/fonts/freefont/FreeSans.ttf");
styleSheet.font("sans", "/usr/share/fonts/freefont/FreeSansBold.ttf", "normal", "normal", "bold");
// CSS regeln, immer Selector, attribut, wert
styleSheet.addRule("body", "color", "#ffffff");
styleSheet.addRule("body", "font-family", "sans");
styleSheet.addRule("body", "font-style", "normal");
styleSheet.addRule("body", "font-size", "30px");
styleSheet.addRule("body", "font-variant", "normal");
styleSheet.addRule("body", "font-weight", "normal");
styleSheet.addRule("body", "text-align", "justify");
styleSheet.addRule(".BigFont", "font-size", "35px");
styleSheet.addRule(".BoldFont", "font-weight", "bold");
styleSheet.addRule("i", "color", "#ff0000");
styleSheet.addRule("h1", "font-weight", "bold");
styleSheet.addRule("h1", "font-size", "60px");
styleSheet.addRule("h1", "text-align", "center");
// der zu formatierende text
std::string text = u8"<html><body>"
"<h1>Überschrift</h1><p>Test <i>Text</i> more and some"
"<div class=\"BoldFont\">more text so</div> that the pa\u00ADra\u00ADgraph is at least "
"<div>long</div> enough to span some lines on the screen let us "
"also <i>i</i>nclude sm hebrew נייה, העגורן הוא and back to english</p>"
"<p>2nd Paragraph<div class=\"BigFont\"> with <div class=\"BoldFont\">a\ndivision</div>"
"</div>.</p>"
"<p>a b c andnowone<i>very</i>longwordthatdoesntfitononelineandmight d e f °C</p>"
"<ul><li>First long text in an ul list of html sdfsd fsd fs dfsd f gobble di gock and"
"even more</li><li>Second with just a bit</li></ul>"
"</body></html>";
// Vektor mit auszugebenden Text layouts, besteht immer aus einem layoute
// und dessen Position auf dem Bildschirm
std::vector<layoutInfo_c> l;
// grauer Hintergrund, damit ich sehen kann, ob der Text die korrekte Breite hat
// erzeuge ein künstliches Layout nur mit einem Rechteck drin... so etwas wird später
// nicht mehr benötigt, ist nur für den Test
textLayout_c la;
textLayout_c::commandData c;
c.command = textLayout_c::commandData::CMD_RECT;
c.x = c.y = 0;
c.w = TXT_WIDTH;
c.h = 600;
c.r = c.g = c.b = 50;
la.addCommand(c);
l.emplace_back(layoutInfo_c(la, (WIN_WIDTH-TXT_WIDTH)/2, 20));
// das eigentliche Layout
// layoutXHTML macht die Arbeit, übergeben wird der Text, das Stylesheet und eine Klasse,
// die die Form des Textes beinhaltet (für nicht rechteckiges Layout
l.emplace_back(layoutInfo_c(layoutXHTML(text, styleSheet, rectangleShape_c(TXT_WIDTH)),
(WIN_WIDTH-TXT_WIDTH)/2, 20));
// Ausgabe mittels SDL
showLayoutsSelf(WIN_WIDTH, 600, l);
}
|
#include "layouterXHTML.h"
#include "layouterSDL.h"
#define TXT_WIDTH 700
#define WIN_WIDTH 800
int main ()
{
textStyleSheet_c styleSheet;
// setze default sprache des textes
styleSheet.language="en-Engl";
// alle Fonts, die so genutzt werden: familie heißt sans, und dann der bold Font dazu
styleSheet.font("sans", "/usr/share/fonts/freefont/FreeSans.ttf");
styleSheet.font("sans", "/usr/share/fonts/freefont/FreeSansBold.ttf", "normal", "normal", "bold");
// CSS regeln, immer Selector, attribut, wert
styleSheet.addRule("body", "color", "#ffffff");
styleSheet.addRule("body", "font-family", "sans");
styleSheet.addRule("body", "font-style", "normal");
styleSheet.addRule("body", "font-size", "30px");
styleSheet.addRule("body", "font-variant", "normal");
styleSheet.addRule("body", "font-weight", "normal");
styleSheet.addRule("body", "text-align", "justify");
styleSheet.addRule(".BigFont", "font-size", "35px");
styleSheet.addRule(".BoldFont", "font-weight", "bold");
styleSheet.addRule("i", "color", "#ff0000");
styleSheet.addRule("h1", "font-weight", "bold");
styleSheet.addRule("h1", "font-size", "60px");
styleSheet.addRule("h1", "text-align", "center");
// der zu formatierende text
std::string text = u8"<html><body>"
"<h1>Überschrift</h1>"
"<p>Test <i>Text</i> more and some "
"<div class='BoldFont'>more text so</div> that the pa\u00ADra\u00ADgraph is at least "
"<div>long</div> enough to span some lines on the screen let us "
"also <i>i</i>nclude sm hebrew נייה, העגורן הוא and back to english</p>"
"<p>2nd Paragraph<div class='BigFont'> with <div class='BoldFont'>a\ndivision</div>"
"</div>.</p>"
"<p>a b c andnowone<i>very</i>longwordthatdoesntfitononelineandmight d e f °C</p>"
"<ul><li>First long text in an ul list of html sdfsd fsd fs dfsd f gobble di gock and"
"even more</li><li>Second with just a bit</li></ul>"
"<p>MargaretAreYouGrievingOverGoldengroveUnleavingLeavesLikeTheThingsOfManYouWithYourFreshThoughtsCareForCanYouAhAsTheHeartGrowsOlderItWillComeToSuchSightsColderByAndByNorSpareASighThoughWorldsOfWanwoodLeafmealLieAndYetYouWillWeepAndKnowWhyNowNoMatterChildTheNameSorrowsSpringsAreTheSameNorMouthHadNoNorMindExpressedWhatHeartHeardOfGhostGuessedItIsTheBlightManWasBornForItIsMargaretYouMournFor</p>"
"</body></html>";
// Vektor mit auszugebenden Text layouts, besteht immer aus einem layoute
// und dessen Position auf dem Bildschirm
std::vector<layoutInfo_c> l;
// grauer Hintergrund, damit ich sehen kann, ob der Text die korrekte Breite hat
// erzeuge ein künstliches Layout nur mit einem Rechteck drin... so etwas wird später
// nicht mehr benötigt, ist nur für den Test
textLayout_c la;
textLayout_c::commandData c;
c.command = textLayout_c::commandData::CMD_RECT;
c.x = c.y = 0;
c.w = TXT_WIDTH;
c.h = 600;
c.r = c.g = c.b = 50;
la.addCommand(c);
l.emplace_back(layoutInfo_c(la, (WIN_WIDTH-TXT_WIDTH)/2, 20));
// das eigentliche Layout
// layoutXHTML macht die Arbeit, übergeben wird der Text, das Stylesheet und eine Klasse,
// die die Form des Textes beinhaltet (für nicht rechteckiges Layout
l.emplace_back(layoutInfo_c(layoutXHTML(text, styleSheet, rectangleShape_c(TXT_WIDTH)),
(WIN_WIDTH-TXT_WIDTH)/2, 20));
// Ausgabe mittels SDL
showLayoutsSelf(WIN_WIDTH, 600, l);
}
|
update tester file
|
update tester file
Ignore-this: a7277c875f2f1c995b5408a3b0fc457c
darcs-hash:20140801135431-c09e1-f1ac8389dc1d1c14a40d818ca27f6855115f1a28
|
C++
|
lgpl-2.1
|
stll/STLL,stll/STLL,stll/STLL
|
84223345dc8286d733b08443d9a25d456e9a15ae
|
main.cpp
|
main.cpp
|
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the V4VM module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmljs_objects.h"
#include "qv4codegen_p.h"
#include "qv4isel_masm_p.h"
#include "qv4isel_moth_p.h"
#include "qv4vme_moth_p.h"
#include "qv4syntaxchecker_p.h"
#include "qv4ecmaobjects_p.h"
#include <QtCore>
#include <private/qqmljsengine_p.h>
#include <private/qqmljslexer_p.h>
#include <private/qqmljsparser_p.h>
#include <private/qqmljsast_p.h>
#include <sys/mman.h>
#include <iostream>
#ifndef QMLJS_NO_LLVM
# include "qv4isel_llvm_p.h"
# include <llvm/PassManager.h>
# include <llvm/Analysis/Passes.h>
# include <llvm/Transforms/Scalar.h>
# include <llvm/Transforms/IPO.h>
# include <llvm/Assembly/PrintModulePass.h>
# include <llvm/Support/raw_ostream.h>
# include <llvm/Support/FormattedStream.h>
# include <llvm/Support/Host.h>
# include <llvm/Support/TargetRegistry.h>
# include <llvm/Support/TargetSelect.h>
# include <llvm/Target/TargetMachine.h>
# include <llvm/Target/TargetData.h>
#endif
static inline bool protect(const void *addr, size_t size)
{
size_t pageSize = sysconf(_SC_PAGESIZE);
size_t iaddr = reinterpret_cast<size_t>(addr);
size_t roundAddr = iaddr & ~(pageSize - static_cast<size_t>(1));
int mode = PROT_READ | PROT_WRITE | PROT_EXEC;
return mprotect(reinterpret_cast<void*>(roundAddr), size + (iaddr - roundAddr), mode) == 0;
}
static void evaluate(QQmlJS::VM::Context *ctx, const QString &fileName, const QString &source,
QQmlJS::Codegen::Mode mode = QQmlJS::Codegen::GlobalCode);
namespace builtins {
using namespace QQmlJS::VM;
struct Print: FunctionObject
{
Print(Context *scope): FunctionObject(scope) {}
virtual void call(Context *ctx)
{
for (unsigned int i = 0; i < ctx->argumentCount; ++i) {
String *s = ctx->argument(i).toString(ctx);
if (i)
std::cout << ' ';
std::cout << qPrintable(s->toQString());
}
std::cout << std::endl;
}
};
struct Eval: FunctionObject
{
Eval(Context *scope): FunctionObject(scope) {}
virtual void call(Context *ctx)
{
const QString code = ctx->argument(0).toString(ctx)->toQString();
evaluate(ctx, QStringLiteral("eval code"), code, QQmlJS::Codegen::EvalCode);
}
};
} // builtins
#ifndef QMLJS_NO_LLVM
void compile(const QString &fileName, const QString &source)
{
using namespace QQmlJS;
IR::Module module;
QQmlJS::Engine ee, *engine = ⅇ
Lexer lexer(engine);
lexer.setCode(source, 1, false);
Parser parser(engine);
const bool parsed = parser.parseProgram();
foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
std::cerr << qPrintable(fileName) << ':' << m.loc.startLine << ':' << m.loc.startColumn
<< ": error: " << qPrintable(m.message) << std::endl;
}
if (parsed) {
using namespace AST;
Program *program = AST::cast<Program *>(parser.rootNode());
Codegen cg;
/*IR::Function *globalCode =*/ cg(program, &module);
LLVMInstructionSelection llvmIsel(llvm::getGlobalContext());
if (llvm::Module *llvmModule = llvmIsel.getLLVMModule(&module)) {
llvm::PassManager PM;
const std::string triple = llvm::sys::getDefaultTargetTriple();
LLVMInitializeX86TargetInfo();
LLVMInitializeX86Target();
LLVMInitializeX86AsmPrinter();
LLVMInitializeX86AsmParser();
LLVMInitializeX86Disassembler();
LLVMInitializeX86TargetMC();
std::string err;
const llvm::Target *target = llvm::TargetRegistry::lookupTarget(triple, err);
if (! err.empty()) {
std::cerr << err << ", triple: " << triple << std::endl;
assert(!"cannot create target for the host triple");
}
std::string cpu;
std::string features;
llvm::TargetOptions options;
llvm::TargetMachine *targetMachine = target->createTargetMachine(triple, cpu, features, options, llvm::Reloc::PIC_);
assert(targetMachine);
llvm::formatted_raw_ostream out(llvm::outs());
PM.add(llvm::createScalarReplAggregatesPass());
PM.add(llvm::createInstructionCombiningPass());
PM.add(llvm::createGlobalOptimizerPass());
PM.add(llvm::createFunctionInliningPass(25));
targetMachine->addPassesToEmitFile(PM, out, llvm::TargetMachine::CGFT_AssemblyFile);
PM.run(*llvmModule);
delete llvmModule;
}
}
}
int compileFiles(const QStringList &files)
{
foreach (const QString &fileName, files) {
QFile file(fileName);
if (file.open(QFile::ReadOnly)) {
QString source = QString::fromUtf8(file.readAll());
compile(fileName, source);
}
}
return 0;
}
int evaluateCompiledCode(const QStringList &files)
{
using namespace QQmlJS;
foreach (const QString &libName, files) {
QFileInfo libInfo(libName);
QLibrary lib(libInfo.absoluteFilePath());
lib.load();
QFunctionPointer ptr = lib.resolve("_25_entry");
void (*code)(VM::Context *) = (void (*)(VM::Context *)) ptr;
VM::ExecutionEngine vm;
VM::Context *ctx = vm.rootContext;
QQmlJS::VM::Object *globalObject = vm.globalObject.objectValue();
globalObject->setProperty(ctx, vm.identifier(QStringLiteral("print")),
QQmlJS::VM::Value::fromObject(new builtins::Print(ctx)));
code(ctx);
if (ctx->hasUncaughtException) {
if (VM::ErrorObject *e = ctx->result.asErrorObject())
std::cerr << "Uncaught exception: " << qPrintable(e->value.toString(ctx)->toQString()) << std::endl;
else
std::cerr << "Uncaught exception: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
}
}
return 0;
}
#endif
static void evaluate(QQmlJS::VM::Context *ctx, const QString &fileName, const QString &source,
QQmlJS::Codegen::Mode mode)
{
using namespace QQmlJS;
VM::ExecutionEngine *vm = ctx->engine;
IR::Module module;
IR::Function *globalCode = 0;
const size_t codeSize = 400 * getpagesize();
uchar *code = 0;
posix_memalign((void**)&code, 16, codeSize);
assert(code);
assert(! (size_t(code) & 15));
static bool useMoth = !qgetenv("USE_MOTH").isNull();
{
QQmlJS::Engine ee, *engine = ⅇ
Lexer lexer(engine);
lexer.setCode(source, 1, false);
Parser parser(engine);
const bool parsed = parser.parseProgram();
foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
std::cerr << qPrintable(fileName) << ':' << m.loc.startLine << ':' << m.loc.startColumn
<< ": error: " << qPrintable(m.message) << std::endl;
}
if (parsed) {
using namespace AST;
Program *program = AST::cast<Program *>(parser.rootNode());
Codegen cg;
globalCode = cg(program, &module, mode);
if (useMoth) {
Moth::InstructionSelection isel(vm, &module, code);
foreach (IR::Function *function, module.functions)
isel(function);
} else {
foreach (IR::Function *function, module.functions) {
MASM::InstructionSelection isel(vm, &module, code);
isel(function);
}
if (! protect(code, codeSize))
Q_UNREACHABLE();
}
}
if (! globalCode)
return;
}
ctx->hasUncaughtException = false;
if (! ctx->activation.isObject())
__qmljs_init_object(&ctx->activation, new QQmlJS::VM::Object());
foreach (const QString *local, globalCode->locals) {
ctx->activation.objectValue()->setProperty(ctx, *local, QQmlJS::VM::Value::undefinedValue());
}
if (useMoth) {
Moth::VME vme;
vme(ctx, code);
} else {
globalCode->code(ctx, globalCode->codeData);
}
if (ctx->hasUncaughtException) {
if (VM::ErrorObject *e = ctx->result.asErrorObject())
std::cerr << "Uncaught exception: " << qPrintable(e->value.toString(ctx)->toQString()) << std::endl;
else
std::cerr << "Uncaught exception: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
} else if (! ctx->result.isUndefined()) {
if (! qgetenv("SHOW_EXIT_VALUE").isNull())
std::cout << "exit value: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
}
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QStringList args = app.arguments();
args.removeFirst();
#ifndef QMLJS_NO_LLVM
if (args.isEmpty()) {
std::cerr << "Usage: v4 [--compile|--aot] file..." << std::endl;
return 0;
}
if (args.first() == QLatin1String("--compile")) {
args.removeFirst();
return compileFiles(args);
} else if (args.first() == QLatin1String("--aot")) {
args.removeFirst();
return evaluateCompiledCode(args);
}
#endif
QQmlJS::VM::ExecutionEngine vm;
QQmlJS::VM::Context *ctx = vm.rootContext;
QQmlJS::VM::Object *globalObject = vm.globalObject.objectValue();
globalObject->setProperty(ctx, vm.identifier(QStringLiteral("print")),
QQmlJS::VM::Value::fromObject(new builtins::Print(ctx)));
globalObject->setProperty(ctx, vm.identifier(QStringLiteral("eval")),
QQmlJS::VM::Value::fromObject(new builtins::Eval(ctx)));
foreach (const QString &fn, args) {
QFile file(fn);
if (file.open(QFile::ReadOnly)) {
const QString code = QString::fromUtf8(file.readAll());
file.close();
evaluate(vm.rootContext, fn, code);
}
}
}
|
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the V4VM module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QMLJS_NO_LLVM
// These includes have to come first, because WTF/Platform.h defines some macros
// with very unfriendly names that collide with class fields in LLVM.
# include <llvm/PassManager.h>
# include <llvm/Analysis/Passes.h>
# include <llvm/Transforms/Scalar.h>
# include <llvm/Transforms/IPO.h>
# include <llvm/Assembly/PrintModulePass.h>
# include <llvm/Support/raw_ostream.h>
# include <llvm/Support/FormattedStream.h>
# include <llvm/Support/Host.h>
# include <llvm/Support/TargetRegistry.h>
# include <llvm/Support/TargetSelect.h>
# include <llvm/Target/TargetMachine.h>
# include <llvm/Target/TargetData.h>
# include "qv4isel_llvm_p.h"
#endif
#include "qmljs_objects.h"
#include "qv4codegen_p.h"
#include "qv4isel_masm_p.h"
#include "qv4isel_moth_p.h"
#include "qv4vme_moth_p.h"
#include "qv4syntaxchecker_p.h"
#include "qv4ecmaobjects_p.h"
#include <QtCore>
#include <private/qqmljsengine_p.h>
#include <private/qqmljslexer_p.h>
#include <private/qqmljsparser_p.h>
#include <private/qqmljsast_p.h>
#include <sys/mman.h>
#include <iostream>
static inline bool protect(const void *addr, size_t size)
{
size_t pageSize = sysconf(_SC_PAGESIZE);
size_t iaddr = reinterpret_cast<size_t>(addr);
size_t roundAddr = iaddr & ~(pageSize - static_cast<size_t>(1));
int mode = PROT_READ | PROT_WRITE | PROT_EXEC;
return mprotect(reinterpret_cast<void*>(roundAddr), size + (iaddr - roundAddr), mode) == 0;
}
static void evaluate(QQmlJS::VM::Context *ctx, const QString &fileName, const QString &source,
QQmlJS::Codegen::Mode mode = QQmlJS::Codegen::GlobalCode);
namespace builtins {
using namespace QQmlJS::VM;
struct Print: FunctionObject
{
Print(Context *scope): FunctionObject(scope) {}
virtual void call(Context *ctx)
{
for (unsigned int i = 0; i < ctx->argumentCount; ++i) {
String *s = ctx->argument(i).toString(ctx);
if (i)
std::cout << ' ';
std::cout << qPrintable(s->toQString());
}
std::cout << std::endl;
}
};
struct Eval: FunctionObject
{
Eval(Context *scope): FunctionObject(scope) {}
virtual void call(Context *ctx)
{
const QString code = ctx->argument(0).toString(ctx)->toQString();
evaluate(ctx, QStringLiteral("eval code"), code, QQmlJS::Codegen::EvalCode);
}
};
} // builtins
#ifndef QMLJS_NO_LLVM
void compile(const QString &fileName, const QString &source)
{
using namespace QQmlJS;
IR::Module module;
QQmlJS::Engine ee, *engine = ⅇ
Lexer lexer(engine);
lexer.setCode(source, 1, false);
Parser parser(engine);
const bool parsed = parser.parseProgram();
foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
std::cerr << qPrintable(fileName) << ':' << m.loc.startLine << ':' << m.loc.startColumn
<< ": error: " << qPrintable(m.message) << std::endl;
}
if (parsed) {
using namespace AST;
Program *program = AST::cast<Program *>(parser.rootNode());
Codegen cg;
/*IR::Function *globalCode =*/ cg(program, &module);
LLVMInstructionSelection llvmIsel(llvm::getGlobalContext());
if (llvm::Module *llvmModule = llvmIsel.getLLVMModule(&module)) {
llvm::PassManager PM;
const std::string triple = llvm::sys::getDefaultTargetTriple();
LLVMInitializeX86TargetInfo();
LLVMInitializeX86Target();
LLVMInitializeX86AsmPrinter();
LLVMInitializeX86AsmParser();
LLVMInitializeX86Disassembler();
LLVMInitializeX86TargetMC();
std::string err;
const llvm::Target *target = llvm::TargetRegistry::lookupTarget(triple, err);
if (! err.empty()) {
std::cerr << err << ", triple: " << triple << std::endl;
assert(!"cannot create target for the host triple");
}
std::string cpu;
std::string features;
llvm::TargetOptions options;
llvm::TargetMachine *targetMachine = target->createTargetMachine(triple, cpu, features, options, llvm::Reloc::PIC_);
assert(targetMachine);
llvm::formatted_raw_ostream out(llvm::outs());
PM.add(llvm::createScalarReplAggregatesPass());
PM.add(llvm::createInstructionCombiningPass());
PM.add(llvm::createGlobalOptimizerPass());
PM.add(llvm::createFunctionInliningPass(25));
targetMachine->addPassesToEmitFile(PM, out, llvm::TargetMachine::CGFT_AssemblyFile);
PM.run(*llvmModule);
delete llvmModule;
}
}
}
int compileFiles(const QStringList &files)
{
foreach (const QString &fileName, files) {
QFile file(fileName);
if (file.open(QFile::ReadOnly)) {
QString source = QString::fromUtf8(file.readAll());
compile(fileName, source);
}
}
return 0;
}
int evaluateCompiledCode(const QStringList &files)
{
using namespace QQmlJS;
foreach (const QString &libName, files) {
QFileInfo libInfo(libName);
QLibrary lib(libInfo.absoluteFilePath());
lib.load();
QFunctionPointer ptr = lib.resolve("_25_entry");
void (*code)(VM::Context *) = (void (*)(VM::Context *)) ptr;
VM::ExecutionEngine vm;
VM::Context *ctx = vm.rootContext;
QQmlJS::VM::Object *globalObject = vm.globalObject.objectValue();
globalObject->setProperty(ctx, vm.identifier(QStringLiteral("print")),
QQmlJS::VM::Value::fromObject(new builtins::Print(ctx)));
code(ctx);
if (ctx->hasUncaughtException) {
if (VM::ErrorObject *e = ctx->result.asErrorObject())
std::cerr << "Uncaught exception: " << qPrintable(e->value.toString(ctx)->toQString()) << std::endl;
else
std::cerr << "Uncaught exception: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
}
}
return 0;
}
#endif
static void evaluate(QQmlJS::VM::Context *ctx, const QString &fileName, const QString &source,
QQmlJS::Codegen::Mode mode)
{
using namespace QQmlJS;
VM::ExecutionEngine *vm = ctx->engine;
IR::Module module;
IR::Function *globalCode = 0;
const size_t codeSize = 400 * getpagesize();
uchar *code = 0;
posix_memalign((void**)&code, 16, codeSize);
assert(code);
assert(! (size_t(code) & 15));
static bool useMoth = !qgetenv("USE_MOTH").isNull();
{
QQmlJS::Engine ee, *engine = ⅇ
Lexer lexer(engine);
lexer.setCode(source, 1, false);
Parser parser(engine);
const bool parsed = parser.parseProgram();
foreach (const DiagnosticMessage &m, parser.diagnosticMessages()) {
std::cerr << qPrintable(fileName) << ':' << m.loc.startLine << ':' << m.loc.startColumn
<< ": error: " << qPrintable(m.message) << std::endl;
}
if (parsed) {
using namespace AST;
Program *program = AST::cast<Program *>(parser.rootNode());
Codegen cg;
globalCode = cg(program, &module, mode);
if (useMoth) {
Moth::InstructionSelection isel(vm, &module, code);
foreach (IR::Function *function, module.functions)
isel(function);
} else {
foreach (IR::Function *function, module.functions) {
MASM::InstructionSelection isel(vm, &module, code);
isel(function);
}
if (! protect(code, codeSize))
Q_UNREACHABLE();
}
}
if (! globalCode)
return;
}
ctx->hasUncaughtException = false;
if (! ctx->activation.isObject())
__qmljs_init_object(&ctx->activation, new QQmlJS::VM::Object());
foreach (const QString *local, globalCode->locals) {
ctx->activation.objectValue()->setProperty(ctx, *local, QQmlJS::VM::Value::undefinedValue());
}
if (useMoth) {
Moth::VME vme;
vme(ctx, code);
} else {
globalCode->code(ctx, globalCode->codeData);
}
if (ctx->hasUncaughtException) {
if (VM::ErrorObject *e = ctx->result.asErrorObject())
std::cerr << "Uncaught exception: " << qPrintable(e->value.toString(ctx)->toQString()) << std::endl;
else
std::cerr << "Uncaught exception: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
} else if (! ctx->result.isUndefined()) {
if (! qgetenv("SHOW_EXIT_VALUE").isNull())
std::cout << "exit value: " << qPrintable(ctx->result.toString(ctx)->toQString()) << std::endl;
}
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QStringList args = app.arguments();
args.removeFirst();
#ifndef QMLJS_NO_LLVM
if (args.isEmpty()) {
std::cerr << "Usage: v4 [--compile|--aot] file..." << std::endl;
return 0;
}
if (args.first() == QLatin1String("--compile")) {
args.removeFirst();
return compileFiles(args);
} else if (args.first() == QLatin1String("--aot")) {
args.removeFirst();
return evaluateCompiledCode(args);
}
#endif
QQmlJS::VM::ExecutionEngine vm;
QQmlJS::VM::Context *ctx = vm.rootContext;
QQmlJS::VM::Object *globalObject = vm.globalObject.objectValue();
globalObject->setProperty(ctx, vm.identifier(QStringLiteral("print")),
QQmlJS::VM::Value::fromObject(new builtins::Print(ctx)));
globalObject->setProperty(ctx, vm.identifier(QStringLiteral("eval")),
QQmlJS::VM::Value::fromObject(new builtins::Eval(ctx)));
foreach (const QString &fn, args) {
QFile file(fn);
if (file.open(QFile::ReadOnly)) {
const QString code = QString::fromUtf8(file.readAll());
file.close();
evaluate(vm.rootContext, fn, code);
}
}
}
|
Fix LLVM build
|
Fix LLVM build
Change-Id: I7ae00a5e90087182d9f7d939db0a036c120e3b9b
Reviewed-by: Simon Hausmann <[email protected]>
|
C++
|
lgpl-2.1
|
qmlc/qtdeclarative,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,matthewvogt/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,qmlc/qtdeclarative
|
ba5eda9d033fa747a6e9f84f04507f39c1c40775
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <vector>
#include <utility>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
extern "C" {
#include <lightning.h>
}
enum Opcode {
OP_NOP,
OP_PUSH,
OP_ADD,
OP_SUB,
OP_MUL,
OP_DIV,
OP_CALL,
};
const char *trans_opcode(int op) {
switch (op) {
case OP_NOP:
return "NOP";
case OP_PUSH:
return "PUSH";
case OP_ADD:
return "ADD";
case OP_SUB:
return "SUB";
case OP_MUL:
return "MUL";
case OP_DIV:
return "DIV";
case OP_CALL:
return "CALL";
default:
return "unknown";
}
}
struct Instruction {
uint8_t op;
union {
int ival;
double dval;
struct {
uint32_t fidx;
uint32_t narg;
} callop;
};
Instruction(Opcode op) : op(op) {}
Instruction(Opcode op, int ival) : op(op), ival(ival) {}
Instruction(Opcode op, double dval) : op(op), dval(dval) {}
Instruction(Opcode op, uint32_t function_idx, uint32_t nargs)
: op(op) { callop.fidx = function_idx; callop.narg = nargs; }
};
void _JIT_stack_push(jit_state_t *_jit, int reg, int *sp) {
jit_stxi_d(*sp, JIT_FP, reg);
*sp += sizeof(double);
}
void _JIT_stack_pop(jit_state_t *_jit, int reg, int *sp) {
*sp -= sizeof(double);
jit_ldxi_d(reg, JIT_FP, *sp);
}
typedef std::pair<int, double> Result;
Result fixme_function(void *env, uint32_t nargs, const double *stack) {
return std::make_pair(0, stack[0] + stack[1]);
}
Result second_function(void *env, uint32_t nargs, const double *stack) {
int retcode;
double result;
if (nargs < 3) {
retcode = 1;
result = 0.0;
} else {
retcode = 0;
result = stack[0] != 0.0 ? stack[1] : stack[2];
}
return std::make_pair(retcode, result);
}
typedef Result (*Callback)(void *, uint32_t, const double*);
struct Translator {
virtual ~Translator() {}
virtual Callback lookup(uint32_t function_idx)=0;
};
struct DummyTranslator : public Translator {
virtual ~DummyTranslator() {}
Callback lookup(uint32_t function_idx) override {
switch (function_idx) {
case 1:
return fixme_function;
case 2:
return second_function;
default:
throw std::runtime_error("Unknown function index!");
}
}
};
typedef std::vector<Instruction> Program;
class JIT {
public:
JIT() : _jit(jit_new_state()), func_(nullptr) {}
~JIT() {
jit_destroy_state();
}
bool compile(const Program &program, Translator &trans, void *userdata) {
jit_node_t *fn = jit_note(NULL, 0);
jit_prolog();
const int stack_base_offset = jit_allocai(32 * sizeof(double));
int stack_top_idx = 0;
auto &&stackPush = [&](int reg) {
jit_stxi_d(stack_base_offset + stack_top_idx * sizeof(double), JIT_FP, reg);
++stack_top_idx;
};
auto &&stackPop = [&](int reg) {
--stack_top_idx;
jit_ldxi_d(reg, JIT_FP, stack_base_offset + stack_top_idx * sizeof(double));
return reg;
};
size_t pc = 0;
const size_t progsz = program.size();
while (pc < progsz) {
const Instruction &instr = program[pc];
switch (instr.op) {
case OP_NOP:
break;
case OP_PUSH:
stackPush(JIT_F0);
jit_movi_d(JIT_F0, instr.dval);
break;
case OP_ADD: {
const int reg = stackPop(JIT_F1);
jit_addr_d(JIT_F0, reg, JIT_F0);
}
break;
case OP_SUB: {
const int reg = stackPop(JIT_F1);
jit_subr_d(JIT_F0, reg, JIT_F0);
}
break;
case OP_MUL: {
const int reg = stackPop(JIT_F1);
jit_mulr_d(JIT_F0, reg, JIT_F0);
}
break;
case OP_DIV: {
const int reg = stackPop(JIT_F1);
jit_divr_d(JIT_F0, reg, JIT_F0);
}
break;
case OP_CALL: {
}
break;
}
++pc;
}
jit_retr_d(JIT_F0);
jit_epilog();
(void)jit_emit();
func_ = reinterpret_cast<JitFunction>(jit_address(fn));
return true;
}
bool run() {
result_ = func_();
return true;
}
double result() const noexcept {
return result_;
}
void disassemble() {
jit_disassemble();
}
const char *error() const {
return "TODO: implement";
}
private:
typedef double (*JitFunction)();
jit_state_t *_jit; // DO NOT CHANGE NAME. Satisfies req.s for GNU lightning macros
JitFunction func_;
double result_;
};
// TODO: implement
struct MyEnv {};
// jit_node_t *JIT_translate(jit_state_t *_jit, const struct instruction *restrict program, size_t progsz, void *env, translator_t trans) {
// const struct instruction *ip;
// size_t pc = 0;
// int sp;
// jit_node_t *fn;
// jit_node_t *ref;
// callback_t cb;
// fn = jit_note(NULL, 0);
// jit_prolog();
// sp = jit_allocai(6 * sizeof(double));
// while (pc < progsz) {
// ip = &program[pc];
// switch (ip->op) {
// case OP_NOP:
// break;
// case OP_PUSH:
// _JIT_stack_push(_jit, JIT_F0, &sp);
// jit_movi_d(JIT_F0, ip->dval);
// break;
// case OP_ADD:
// _JIT_stack_pop(_jit, JIT_F1, &sp);
// jit_addr_d(JIT_F0, JIT_F1, JIT_F0);
// break;
// case OP_SUB:
// _JIT_stack_pop(_jit, JIT_F1, &sp);
// jit_subr_d(JIT_F0, JIT_F1, JIT_F0);
// break;
// case OP_MUL:
// _JIT_stack_pop(_jit, JIT_F1, &sp);
// jit_mulr_d(JIT_F0, JIT_F1, JIT_F0);
// break;
// case OP_DIV:
// _JIT_stack_pop(_jit, JIT_F1, &sp);
// jit_divr_d(JIT_F0, JIT_F1, JIT_F0);
// break;
// case OP_CALL:
// jit_prepare();
// jit_pushargi((jit_word_t)env); // 1st argument is env pointer
// jit_pushargi(ip->callop.narg); // 2nd argument is number of arguments
// _JIT_stack_push(_jit, JIT_F0, &sp); // move top of stack to C stack
// jit_addi(JIT_R0, JIT_FP, sp - (ip->callop.narg * sizeof(double))); // 3rd argument is stack pointer
// jit_pushargr(JIT_R0);
// cb = trans(ip->callop.fidx);
// if (!cb) {
// printf("Failed to map function index: %d\n", ip->callop.fidx);
// abort();
// }
// jit_finishi((jit_pointer_t)cb);
// sp -= sizeof(double) * ip->callop.narg; // consume arguments on stack
// jit_retval_d(JIT_F0);
// jit_retval(JIT_R0);
// ref = jit_beqi(JIT_R0, 0);
// // return early because of bad retcode
// jit_movi_d(JIT_F0, -1.0);
// jit_retr_d(JIT_F0);
// jit_patch(ref);
// break;
// }
// ++pc;
// }
// jit_retr_d(JIT_F0);
// jit_epilog();
// return fn;
// }
int main(int argc, char **argv) {
Program program = {
{ OP_PUSH, 1234. },
{ OP_PUSH, 6666. },
{ OP_ADD },
{ OP_PUSH, 4444. },
{ OP_SUB },
{ OP_PUSH, 5555. },
{ OP_MUL },
};
init_jit(argv[0]); // TODO: move to static function
JIT jit;
DummyTranslator trans;
MyEnv env;
if (!jit.compile(program, trans, &env)) {
std::cerr << "Failed to compile program!" << std::endl;
return 1;
}
if (!jit.run()) {
std::cerr << "Error running program: " << jit.error() << std::endl;
return 1;
}
std::cout << "\n\nProgram: \n";
jit.disassemble();
std::cout << "Result: " << jit.result() << std::endl;
std::cout << "Expected: " << (((1234. + 6666.) - 4444.) * 5555.) << std::endl;
finish_jit();
return 0;
}
|
#include <iostream>
#include <vector>
#include <utility>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
extern "C" {
#include <lightning.h>
}
enum Opcode {
OP_NOP,
OP_PUSH,
OP_ADD,
OP_SUB,
OP_MUL,
OP_DIV,
OP_CALL,
};
const char *trans_opcode(int op) {
switch (op) {
case OP_NOP:
return "NOP";
case OP_PUSH:
return "PUSH";
case OP_ADD:
return "ADD";
case OP_SUB:
return "SUB";
case OP_MUL:
return "MUL";
case OP_DIV:
return "DIV";
case OP_CALL:
return "CALL";
default:
return "unknown";
}
}
struct Instruction {
uint8_t op;
union {
int ival;
double dval;
struct {
uint32_t fidx;
uint32_t nargs;
} callop;
};
Instruction(Opcode op) : op(op) {}
Instruction(Opcode op, int ival) : op(op), ival(ival) {}
Instruction(Opcode op, double dval) : op(op), dval(dval) {}
Instruction(Opcode op, uint32_t function_idx, uint32_t nargs)
: op(op) { callop.fidx = function_idx; callop.nargs = nargs; }
};
void _JIT_stack_push(jit_state_t *_jit, int reg, int *sp) {
jit_stxi_d(*sp, JIT_FP, reg);
*sp += sizeof(double);
}
void _JIT_stack_pop(jit_state_t *_jit, int reg, int *sp) {
*sp -= sizeof(double);
jit_ldxi_d(reg, JIT_FP, *sp);
}
typedef std::pair<int, double> Result;
Result fixme_function(void *env, uint32_t nargs, const double *stack) {
return std::make_pair(0, stack[0] + stack[1]);
}
Result second_function(void *env, uint32_t nargs, const double *stack) {
int retcode;
double result;
if (nargs < 3) {
retcode = 1;
result = 0.0;
} else {
retcode = 0;
result = stack[0] != 0.0 ? stack[1] : stack[2];
}
return std::make_pair(retcode, result);
}
typedef Result (*Callback)(void *, uint32_t, const double*);
struct Translator {
virtual ~Translator() {}
virtual Callback lookup(uint32_t function_idx)=0;
};
struct DummyTranslator : public Translator {
virtual ~DummyTranslator() {}
Callback lookup(uint32_t function_idx) override {
switch (function_idx) {
case 1:
return fixme_function;
case 2:
return second_function;
default:
throw std::runtime_error("Unknown function index!");
}
}
};
typedef std::vector<Instruction> Program;
class JIT {
public:
JIT() : _jit(jit_new_state()), func_(nullptr) {}
~JIT() {
jit_destroy_state();
}
bool compile(const Program &program, Translator &trans, void *userdata) {
jit_node_t *fn = jit_note(NULL, 0);
jit_prolog();
const int stack_base_offset = jit_allocai(32 * sizeof(double));
int stack_top_idx = 0;
auto &&stackPush = [&](int reg) {
jit_stxi_d(stack_base_offset + stack_top_idx * sizeof(double), JIT_FP, reg);
++stack_top_idx;
};
auto &&stackPop = [&](int reg) {
--stack_top_idx;
jit_ldxi_d(reg, JIT_FP, stack_base_offset + stack_top_idx * sizeof(double));
return reg;
};
size_t pc = 0;
const size_t progsz = program.size();
while (pc < progsz) {
const Instruction &instr = program[pc];
switch (instr.op) {
case OP_NOP:
break;
case OP_PUSH:
stackPush(JIT_F0);
jit_movi_d(JIT_F0, instr.dval);
break;
case OP_ADD: {
const int reg = stackPop(JIT_F1);
jit_addr_d(JIT_F0, reg, JIT_F0);
}
break;
case OP_SUB: {
const int reg = stackPop(JIT_F1);
jit_subr_d(JIT_F0, reg, JIT_F0);
}
break;
case OP_MUL: {
const int reg = stackPop(JIT_F1);
jit_mulr_d(JIT_F0, reg, JIT_F0);
}
break;
case OP_DIV: {
const int reg = stackPop(JIT_F1);
jit_divr_d(JIT_F0, reg, JIT_F0);
}
break;
case OP_CALL: {
stackPush(JIT_F0);
const int sp = stack_top_idx - (instr.callop.nargs);
jit_addi(JIT_R0, JIT_FP, stack_base_offset + sp * sizeof(double));
jit_prepare();
jit_pushargi((jit_word_t)userdata); // 1st arg: userdata
jit_pushargi(instr.callop.nargs); // 2nd arg: # of arguments
jit_pushargr(JIT_R0); // 3rd arg: pointer to args on stack
auto &&cb = trans.lookup(instr.callop.fidx);
jit_finishi(reinterpret_cast<jit_pointer_t>(cb));
stack_top_idx -= instr.callop.nargs; // consume arguments on stack
jit_retval_d(JIT_F0);
}
break;
}
++pc;
}
jit_retr_d(JIT_F0);
jit_epilog();
(void)jit_emit();
func_ = reinterpret_cast<JitFunction>(jit_address(fn));
return true;
}
bool run() {
result_ = func_();
return true;
}
double result() const noexcept {
return result_;
}
void disassemble() {
jit_disassemble();
}
const char *error() const {
return "TODO: implement";
}
private:
typedef double (*JitFunction)();
jit_state_t *_jit; // DO NOT CHANGE NAME. Satisfies req.s for GNU lightning macros
JitFunction func_;
double result_;
};
// TODO: implement
struct MyEnv {};
// jit_node_t *JIT_translate(jit_state_t *_jit, const struct instruction *restrict program, size_t progsz, void *env, translator_t trans) {
// const struct instruction *ip;
// size_t pc = 0;
// int sp;
// jit_node_t *fn;
// jit_node_t *ref;
// callback_t cb;
// fn = jit_note(NULL, 0);
// jit_prolog();
// sp = jit_allocai(6 * sizeof(double));
// while (pc < progsz) {
// ip = &program[pc];
// switch (ip->op) {
// case OP_NOP:
// break;
// case OP_PUSH:
// _JIT_stack_push(_jit, JIT_F0, &sp);
// jit_movi_d(JIT_F0, ip->dval);
// break;
// case OP_ADD:
// _JIT_stack_pop(_jit, JIT_F1, &sp);
// jit_addr_d(JIT_F0, JIT_F1, JIT_F0);
// break;
// case OP_SUB:
// _JIT_stack_pop(_jit, JIT_F1, &sp);
// jit_subr_d(JIT_F0, JIT_F1, JIT_F0);
// break;
// case OP_MUL:
// _JIT_stack_pop(_jit, JIT_F1, &sp);
// jit_mulr_d(JIT_F0, JIT_F1, JIT_F0);
// break;
// case OP_DIV:
// _JIT_stack_pop(_jit, JIT_F1, &sp);
// jit_divr_d(JIT_F0, JIT_F1, JIT_F0);
// break;
// case OP_CALL:
// jit_prepare();
// jit_pushargi((jit_word_t)env); // 1st argument is env pointer
// jit_pushargi(ip->callop.narg); // 2nd argument is number of arguments
// _JIT_stack_push(_jit, JIT_F0, &sp); // move top of stack to C stack
// jit_addi(JIT_R0, JIT_FP, sp - (ip->callop.narg * sizeof(double))); // 3rd argument is stack pointer
// jit_pushargr(JIT_R0);
// cb = trans(ip->callop.fidx);
// if (!cb) {
// printf("Failed to map function index: %d\n", ip->callop.fidx);
// abort();
// }
// jit_finishi((jit_pointer_t)cb);
// sp -= sizeof(double) * ip->callop.narg; // consume arguments on stack
// jit_retval_d(JIT_F0);
// jit_retval(JIT_R0);
// ref = jit_beqi(JIT_R0, 0);
// // return early because of bad retcode
// jit_movi_d(JIT_F0, -1.0);
// jit_retr_d(JIT_F0);
// jit_patch(ref);
// break;
// }
// ++pc;
// }
// jit_retr_d(JIT_F0);
// jit_epilog();
// return fn;
// }
int main(int argc, char **argv) {
Program program = {
{ OP_PUSH, 1234. },
{ OP_PUSH, 6666. },
//{ OP_ADD },
{ OP_CALL, 1, 2 }, // fixme_function
{ OP_PUSH, 4444. },
{ OP_SUB },
{ OP_PUSH, 5555. },
{ OP_MUL },
};
init_jit(argv[0]); // TODO: move to static function
JIT jit;
DummyTranslator trans;
MyEnv env;
if (!jit.compile(program, trans, &env)) {
std::cerr << "Failed to compile program!" << std::endl;
return 1;
}
if (!jit.run()) {
std::cerr << "Error running program: " << jit.error() << std::endl;
return 1;
}
std::cout << "\n\nProgram: \n";
jit.disassemble();
std::cout << "Result: " << jit.result() << std::endl;
std::cout << "Expected: " << (((1234. + 6666.) - 4444.) * 5555.) << std::endl;
finish_jit();
return 0;
}
|
Implement basic calling convention
|
Implement basic calling convention
|
C++
|
mit
|
selavy/stackvm,selavy/stackvm
|
eb1d0d7c0713db147d17f25c4b3bcfd796ff47c6
|
main.cpp
|
main.cpp
|
#include <sys/mman.h>
#include "asmtest.h"
#include "x86_64/Operand.h"
#include "x86_64/Assembler.h"
#include "CompiledCode.h"
#include "Linker.h"
#include "lib/IncrementalAlloc.h"
#include "Util.h"
#include <iostream>
using namespace std;
#define __ masm.
using namespace snot;
using namespace snot::x86_64;
void say_hello() {
printf("HELLO WORLD! %lx\n", (void*)say_hello);
}
CompiledCode define_function(const std::string& name) {
x86_64::Assembler masm;
__ define_symbol(name);
__ enter();
__ call("say_hello");
__ mov(Immediate(15), rax);
__ debug_break();
__ debug_break();
__ leave();
__ ret();
return masm.compile();
}
int main (int argc, char const *argv[])
{
SymbolTable table;
table["say_hello"] = (void*)say_hello;
CompiledCode code = define_function("hejsa");
Linker::register_symbols(code, table);
Linker::link(code, table);
code.make_executable();
print_mem(code.code(), &code.code()[code.size()]);
print_mem(simple_ret, simple_loop);
printf("code is at 0x%lx\n", code.code());
int(*func)() = (int(*)())code.code();
printf("add: %d\n", func());
char* br = NULL;
br[0] = '0';
return 0;
}
|
#include <sys/mman.h>
#include "asmtest.h"
#include "x86_64/Operand.h"
#include "x86_64/Assembler.h"
#include "CompiledCode.h"
#include "Linker.h"
#include "lib/IncrementalAlloc.h"
#include "Util.h"
#include <iostream>
using namespace std;
#include "lib/Runtime.h"
#include "lib/Object.h"
#define __ masm.
using namespace snot;
using namespace snot::x86_64;
void say_hello() {
printf("HELLO WORLD! %lx\n", (void*)say_hello);
}
CompiledCode define_function(const std::string& name) {
x86_64::Assembler masm;
__ define_symbol(name);
__ enter(16);
__ bin_xor(rdi, rdi); // NULL prototype
__ call("snot_create_object");
__ mov(rax, Address(rbp, -8));
__ mov(Address(rbp, -8), rdi);
__ clear(rax);
__ call("snot_call");
__ mov(rax, Address(rbp, -8));
__ mov(Address(rbp, -8), rdi);
__ mov("initialize", rsi);
__ mov(3, rdx);
__ clear(rax);
__ call("snot_send");
__ clear(rax);
__ add(56, rax);
__ debug_break();
__ leave();
__ ret();
return masm.compile();
}
int main (int argc, char const *argv[])
{
SymbolTable table;
table["say_hello"] = (void*)say_hello;
table["snot_create_object"] = (void*)snot::create_object;
table["snot_send"] = (void*)snot::send;
table["snot_call"] = (void*)snot::call;
CompiledCode code = define_function("hejsa");
Linker::register_symbols(code, table);
Linker::link(code, table);
code.make_executable();
print_mem(code.code(), &code.code()[code.size()]);
print_mem(simple_ret, simple_loop);
printf("code is at 0x%lx\n", code.code());
int(*func)() = (int(*)())code.code();
printf("add: %d\n", func());
return 0;
}
|
test runtime call
|
test runtime call
|
C++
|
isc
|
simonask/snow-deprecated,simonask/snow-deprecated,simonask/snow-deprecated
|
5cf691bf97105e82bf935c173cdafc5cb9ffe2a4
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <string>
#include <map>
#define True 1
#define False 0
using namespace std;
class AST {
private:
string script;
vector<string> words;
int exit_flag;
void hello();
void if_function();
void elif_function();
void else_function();
void while_function();
void comment_function();
void wide_comment_function();
void coding_style();
public:
AST() {
cout << "hello User" << endl;
exitFlag(True);
}
void init();
int exitFlag();
void exitFlag(int flag);
static void printWords(const string word);
void readLine();
void separator();
void commandDetect();
void printScript();
void script_loop();
};
void AST::hello(){
cout << "暁の水平線に勝利を刻みなさい!" << endl;
}
int AST::exitFlag(){
return this->exit_flag;
}
void AST::exitFlag(int flag){
this->exit_flag = flag;
}
static void AST::printWords(const string word){
cout << word << endl;
}
void AST::readLine(){
printf("curb > ");
getline(cin, script);
}
void AST::separator(){
int separator = 0;
int i = 0;
words.clear();
while (separator != string::npos) {
separator = script.find_first_of(' ');
if (separator == string::npos) {
break;
}
words.push_back("");
words[i].append(script, 0, separator);
script = script.substr(separator+1);
i++;
}
words.push_back("");
words[i].append(script);
}
void AST::commandDetect(){
if (words[0] == "exit") {
this->exitFlag(False);
}else if(words[0] == "hello"){
this->hello();
}else if(words[0] == "if"){
this->if_function();
}else if(words[0] == "elif"){
this->elif_function();
}else if(words[0] == "else"){
this->else_function();
}else if(words[0] == "while"){
this->while_function();
}
}
void AST::printScript(){
for_each(words.begin(), words.end(), printWords);
}
void AST::script_loop(){
while (this->exitFlag()) {
readLine();
separator();
commandDetect();
}
}
int main(){
AST ast;
ast.script_loop();
return 0;
}
|
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <string>
#include <map>
#define True 1
#define False 0
using namespace std;
class AST {
private:
string script;
vector<string> words;
int exit_flag;
void hello();
void if_function();
void elif_function();
void else_function();
void while_function();
void comment_function();
void wide_comment_function();
void coding_style();
void status();
public:
AST() {
cout << "hello User" << endl;
exitFlag(True);
}
void init();
int exitFlag();
void exitFlag(int flag);
static void printWords(const string word);
void readLine();
void separator();
void commandDetect();
void printScript();
void script_loop();
};
void AST::hello(){
cout << "暁の水平線に勝利を刻みなさい!" << endl;
}
int AST::exitFlag(){
return this->exit_flag;
}
void AST::exitFlag(int flag){
this->exit_flag = flag;
}
static void AST::printWords(const string word){
cout << word << endl;
}
void AST::readLine(){
printf("curb > ");
getline(cin, script);
}
void AST::separator(){
int separator = 0;
int i = 0;
words.clear();
while (separator != string::npos) {
separator = script.find_first_of(' ');
if (separator == string::npos) {
break;
}
words.push_back("");
words[i].append(script, 0, separator);
script = script.substr(separator+1);
i++;
}
words.push_back("");
words[i].append(script);
}
void AST::commandDetect(){
if (words[0] == "exit") {
this->exitFlag(False);
}else if(words[0] == "hello"){
this->hello();
}else if(words[0] == "if"){
this->if_function();
}else if(words[0] == "elif"){
this->elif_function();
}else if(words[0] == "else"){
this->else_function();
}else if(words[0] == "while"){
this->while_function();
}
}
void AST::printScript(){
for_each(words.begin(), words.end(), printWords);
}
void AST::script_loop(){
while (this->exitFlag()) {
readLine();
separator();
commandDetect();
}
}
int main(){
AST ast;
ast.script_loop();
return 0;
}
|
Add status.
|
Add status.
|
C++
|
mit
|
EnsekiTT/curb_script
|
c39213a24796b5fcabfb29dd2714721681ba99cc
|
mhash.cc
|
mhash.cc
|
#ifdef __APPLE__
#include <stdbool.h>
#endif
#include <v8.h>
#include <mhash.h>
#include <node.h>
#include <node_buffer.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace v8;
using namespace node;
void reverse_bytes(unsigned char * start, unsigned long len)
{
unsigned char *lo = start;
unsigned char *hi = start + len - 1;
unsigned char swap;
while(lo<hi)
{
swap = *lo;
*lo++ = *hi;
*hi-- = swap;
}
}
char * convert_to_hex(unsigned char * hash_data, unsigned long len)
{
char * converted;
unsigned long i;
converted = (char *)malloc((len*2)+1);
memset(converted, 0, (len*2)+1);
for(i=0;i<len;i++)
{
sprintf(converted+(i*2), "%02x", hash_data[i]);
}
return converted;
}
char * hash(hashid hashType, unsigned char * data, unsigned long len)
{
MHASH td;
unsigned char * hash_data;
char * converted=0;
unsigned long block_size;
if((td=mhash_init(hashType))==MHASH_FAILED)
return 0;
mhash(td, data, len);
if((hash_data=(unsigned char *)mhash_end(td)))
{
block_size = mhash_get_block_size(hashType);
if(hashType==MHASH_ADLER32) // Fixes #6
reverse_bytes(hash_data, block_size);
converted = convert_to_hex(hash_data, block_size);
mhash_free(hash_data);
}
return converted;
}
hashid get_hash_type_by_name(char * name)
{
if(strcasecmp(name, "crc32")==0)
return MHASH_CRC32;
else if(strcasecmp(name, "crc32b")==0)
return MHASH_CRC32B;
else if(strcasecmp(name, "md2")==0)
return MHASH_MD2;
else if(strcasecmp(name, "md4")==0)
return MHASH_MD4;
else if(strcasecmp(name, "md5")==0)
return MHASH_MD5;
else if(strcasecmp(name, "haval128")==0)
return MHASH_HAVAL128;
else if(strcasecmp(name, "haval160")==0)
return MHASH_HAVAL160;
else if(strcasecmp(name, "haval192")==0)
return MHASH_HAVAL192;
else if(strcasecmp(name, "haval224")==0)
return MHASH_HAVAL224;
else if(strcasecmp(name, "haval256")==0)
return MHASH_HAVAL256;
else if(strcasecmp(name, "sha1")==0)
return MHASH_SHA1;
else if(strcasecmp(name, "sha224")==0)
return MHASH_SHA224;
else if(strcasecmp(name, "sha256")==0)
return MHASH_SHA256;
else if(strcasecmp(name, "sha384")==0)
return MHASH_SHA384;
else if(strcasecmp(name, "sha512")==0)
return MHASH_SHA512;
else if(strcasecmp(name, "ripemd128")==0)
return MHASH_RIPEMD128;
else if(strcasecmp(name, "ripemd160")==0)
return MHASH_RIPEMD160;
else if(strcasecmp(name, "ripemd256")==0)
return MHASH_RIPEMD256;
else if(strcasecmp(name, "ripemd320")==0)
return MHASH_RIPEMD320;
else if(strcasecmp(name, "tiger128")==0)
return MHASH_TIGER128;
else if(strcasecmp(name, "tiger160")==0)
return MHASH_TIGER160;
else if(strcasecmp(name, "tiger192")==0)
return MHASH_TIGER192;
else if(strcasecmp(name, "gost")==0)
return MHASH_GOST;
else if(strcasecmp(name, "whirlpool")==0)
return MHASH_WHIRLPOOL;
else if(strcasecmp(name, "adler32")==0)
return MHASH_ADLER32;
else if(strcasecmp(name, "snefru128")==0)
return MHASH_SNEFRU128;
else if(strcasecmp(name, "snefru256")==0)
return MHASH_SNEFRU256;
return (hashid)-1;
}
Handle<Value> hash_binding(const Arguments& args)
{
HandleScope scope;
Local<String> ret;
char * hashed=0;
hashid type=(hashid)-1;
String::Utf8Value name(args[0]->ToString());
type = get_hash_type_by_name(*name);
if(type==(hashid)-1)
return Null();
if(args[1]->IsString())
{
String::Utf8Value data(args[1]->ToString());
hashed = hash(type, (unsigned char *)*data, data.length());
}
else if(Buffer::HasInstance(args[1]))
{
Handle<Object> data = args[1]->ToObject();
hashed = hash(type, (unsigned char *)Buffer::Data(data), Buffer::Length(data));
}
if(!hashed)
return Null();
ret = String::New(hashed);
free(hashed);
return scope.Close(ret);
}
extern "C" void init(Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("hash"), FunctionTemplate::New(hash_binding)->GetFunction());
}
#ifdef NODE_MODULE
NODE_MODULE(mhash, init)
#endif
|
#ifdef __APPLE__
#include <stdbool.h>
#endif
#include <v8.h>
#include <mhash.h>
#include <node.h>
#include <node_buffer.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace v8;
using namespace node;
void reverse_bytes(unsigned char * start, unsigned long len)
{
unsigned char *lo = start;
unsigned char *hi = start + len - 1;
unsigned char swap;
while(lo<hi)
{
swap = *lo;
*lo++ = *hi;
*hi-- = swap;
}
}
char * convert_to_hex(unsigned char * hash_data, unsigned long len)
{
char * converted;
unsigned long i;
converted = (char *)malloc((len*2)+1);
memset(converted, 0, (len*2)+1);
for(i=0;i<len;i++)
{
sprintf(converted+(i*2), "%02x", hash_data[i]);
}
return converted;
}
char * hash(hashid hashType, unsigned char * data, unsigned long len)
{
MHASH td;
unsigned char * hash_data;
char * converted=0;
unsigned long block_size;
if((td=mhash_init(hashType))==MHASH_FAILED)
return 0;
mhash(td, data, len);
if((hash_data=(unsigned char *)mhash_end(td)))
{
block_size = mhash_get_block_size(hashType);
if(hashType==MHASH_ADLER32) // Fixes #6
reverse_bytes(hash_data, block_size);
converted = convert_to_hex(hash_data, block_size);
mhash_free(hash_data);
}
return converted;
}
hashid get_hash_type_by_name(char * name)
{
if(strcasecmp(name, "crc32")==0)
return MHASH_CRC32;
else if(strcasecmp(name, "crc32b")==0)
return MHASH_CRC32B;
else if(strcasecmp(name, "md2")==0)
return MHASH_MD2;
else if(strcasecmp(name, "md4")==0)
return MHASH_MD4;
else if(strcasecmp(name, "md5")==0)
return MHASH_MD5;
else if(strcasecmp(name, "haval128")==0)
return MHASH_HAVAL128;
else if(strcasecmp(name, "haval160")==0)
return MHASH_HAVAL160;
else if(strcasecmp(name, "haval192")==0)
return MHASH_HAVAL192;
else if(strcasecmp(name, "haval224")==0)
return MHASH_HAVAL224;
else if(strcasecmp(name, "haval256")==0)
return MHASH_HAVAL256;
else if(strcasecmp(name, "sha1")==0)
return MHASH_SHA1;
else if(strcasecmp(name, "sha224")==0)
return MHASH_SHA224;
else if(strcasecmp(name, "sha256")==0)
return MHASH_SHA256;
else if(strcasecmp(name, "sha384")==0)
return MHASH_SHA384;
else if(strcasecmp(name, "sha512")==0)
return MHASH_SHA512;
else if(strcasecmp(name, "ripemd128")==0)
return MHASH_RIPEMD128;
else if(strcasecmp(name, "ripemd160")==0)
return MHASH_RIPEMD160;
else if(strcasecmp(name, "ripemd256")==0)
return MHASH_RIPEMD256;
else if(strcasecmp(name, "ripemd320")==0)
return MHASH_RIPEMD320;
else if(strcasecmp(name, "tiger128")==0)
return MHASH_TIGER128;
else if(strcasecmp(name, "tiger160")==0)
return MHASH_TIGER160;
else if(strcasecmp(name, "tiger192")==0)
return MHASH_TIGER192;
else if(strcasecmp(name, "gost")==0)
return MHASH_GOST;
else if(strcasecmp(name, "whirlpool")==0)
return MHASH_WHIRLPOOL;
else if(strcasecmp(name, "adler32")==0)
return MHASH_ADLER32;
else if(strcasecmp(name, "snefru128")==0)
return MHASH_SNEFRU128;
else if(strcasecmp(name, "snefru256")==0)
return MHASH_SNEFRU256;
return (hashid)-1;
}
Handle<Value> hash_binding(const Arguments& args)
{
HandleScope scope;
Local<String> ret;
char * hashed=0;
hashid type;
String::Utf8Value name(args[0]->ToString());
type = get_hash_type_by_name(*name);
if(type==(hashid)-1)
return Null();
if(args[1]->IsString())
{
String::Utf8Value data(args[1]->ToString());
hashed = hash(type, (unsigned char *)*data, data.length());
}
else if(Buffer::HasInstance(args[1]))
{
Handle<Object> data = args[1]->ToObject();
hashed = hash(type, (unsigned char *)Buffer::Data(data), Buffer::Length(data));
}
if(!hashed)
return Null();
ret = String::New(hashed);
free(hashed);
return scope.Close(ret);
}
extern "C" void init(Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("hash"), FunctionTemplate::New(hash_binding)->GetFunction());
}
#ifdef NODE_MODULE
NODE_MODULE(mhash, init)
#endif
|
Fix initialization before immediate reassignment
|
Fix initialization before immediate reassignment
|
C++
|
unlicense
|
Sembiance/mhash,Sembiance/mhash,Sembiance/mhash,Sembiance/mhash
|
d7aadd40c98b7344ab6849f653b3600f5ce73486
|
ch12/ex12_27.cpp
|
ch12/ex12_27.cpp
|
//
// ex12_27.cpp
// Exercise 12.27
//
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <cctype>
#include "ex12_27.h"
using namespace std;
TextQuery::TextQuery(ifstream &is):file(new vector<string>)
{
string text;
while(getline(is, text))
{
file->push_back(text);
int n=file->size()-1;
istringstream line(text);
string word;
while(line>>word)
{
//avoid read a word followed by punctuation(such as: word,)
remove_copy_if(word.begin(), word.end(), back_inserter(word), [](const char &ch) {return isalpha(ch);});
auto &lines=wm[word];
if(!lines)
lines.reset(new set<line_no>);
lines->insert(n);
}
}
}
QueryResult TextQuery::query(const string &sought) const
{
//use static just allocate once
static shared_ptr<set<line_no>> nodata(new set<line_no>);
auto loc=wm.find(sought);
if(loc==wm.end())
return QueryResult(sought, nodata, file);
else
return QueryResult(sought, loc->second, file);
}
ostream &print(ostream &os, const QueryResult &qr)
{
os<<qr.sought<<" occurs "<<qr.lines->size()<<(qr.lines->size()>1 ? " times" : " time")<<endl;
for(auto num : *qr.lines)
os<<"\t(line "<<num+1<<") "<<qr.file->at(num)<<endl;
return os;
}
|
//
// ex12_27.cpp
// Exercise 12.27
//
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <cctype>
#include "ex12_27.h"
using namespace std;
TextQuery::TextQuery(ifstream &is):file(new vector<string>)
{
string line;
while(getline(is, line))
{
file->push_back(line);
int n=file->size()-1;
istringstream in(line);
string text, word;
while(in>>text)
{
//avoid read a word followed by punctuation(such as: word,)
remove_copy_if(text.begin(), text.end(), back_inserter(word), [](const char &ch) {return ispunct(ch);});
auto &lines=wm[word];
if(!lines)
lines.reset(new set<line_no>);
lines->insert(n);
word.clear();
}
}
}
QueryResult TextQuery::query(const string &sought) const
{
//use static just allocate once
static shared_ptr<set<line_no>> nodata(new set<line_no>);
auto loc=wm.find(sought);
if(loc==wm.end())
return QueryResult(sought, nodata, file);
else
return QueryResult(sought, loc->second, file);
}
ostream &print(ostream &os, const QueryResult &qr)
{
os<<qr.sought<<" occurs "<<qr.lines->size()<<(qr.lines->size()>1 ? " times" : " time")<<endl;
for(auto num : *qr.lines)
os<<"\t(line "<<num+1<<") "<<qr.file->at(num)<<endl;
return os;
}
|
Update ex12_27.cpp
|
Update ex12_27.cpp
|
C++
|
cc0-1.0
|
zhangzhizhongz3/CppPrimer,zhangzhizhongz3/CppPrimer
|
393afe12f9f368bffedcaf4cb116361d7666371d
|
test/unittests/serviceRoutines/putIndividualContextEntityAttribute_test.cpp
|
test/unittests/serviceRoutines/putIndividualContextEntityAttribute_test.cpp
|
/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: TID Developer
*/
#include "logMsg/logMsg.h"
#include "serviceRoutines/putIndividualContextEntityAttribute.h"
#include "serviceRoutines/badRequest.h"
#include "rest/RestService.h"
#include "unittest.h"
/* ****************************************************************************
*
* rs -
*/
static RestService rs[] =
{
{ "PUT", IndividualContextEntityAttribute, 5, { "ngsi10", "contextEntities", "*", "attributes", "*" }, "", putIndividualContextEntityAttribute },
{ "*", InvalidRequest, 0, { "*", "*", "*", "*", "*", "*" }, "", badRequest },
{ "", InvalidRequest, 0, { }, "", NULL }
};
/* ****************************************************************************
*
* json -
*/
TEST(putIndividualContextEntityAttribute, xml)
{
ConnectionInfo ci("/ngsi10/contextEntities/entity11/attributes/temperature", "PUT", "1.1");
const char* infile = "ngsi10.updateContextAttributeRequest.putAttribute.valid.xml";
const char* outfile = "ngsi10.updateContextAttributeResponse.ok.valid.xml";
std::string out;
EXPECT_EQ("OK", testDataFromFile(testBuf, sizeof(testBuf), infile)) << "Error getting test data from '" << infile << "'";
EXPECT_EQ("OK", testDataFromFile(expectedBuf, sizeof(expectedBuf), outfile)) << "Error getting test data from '" << outfile << "'";
ci.outFormat = XML;
ci.inFormat = XML;
ci.payload = testBuf;
ci.payloadSize = strlen(testBuf);
out = restService(&ci, rs);
EXPECT_STREQ(expectedBuf, out.c_str());
utExit();
}
/* ****************************************************************************
*
* json -
*/
TEST(putIndividualContextEntityAttribute, json)
{
ConnectionInfo ci("/ngsi10/contextEntities/entity11/attributes/temperature", "PUT", "1.1");
const char* infile = "ngsi10.updateContextAttributeRequest.putAttribute.valid.json";
const char* outfile = "ngsi10.updateContextAttributeResponse.ok.invalid.json";
std::string out;
EXPECT_EQ("OK", testDataFromFile(testBuf, sizeof(testBuf), infile)) << "Error getting test data from '" << infile << "'";
EXPECT_EQ("OK", testDataFromFile(expectedBuf, sizeof(expectedBuf), outfile)) << "Error getting test data from '" << outfile << "'";
ci.outFormat = JSON;
ci.inFormat = JSON;
ci.payload = testBuf;
ci.payloadSize = strlen(testBuf);
out = restService(&ci, rs);
EXPECT_STREQ(expectedBuf, out.c_str());
utExit();
}
|
/*
*
* Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: TID Developer
*/
#include "logMsg/logMsg.h"
#include "serviceRoutines/putIndividualContextEntityAttribute.h"
#include "serviceRoutines/badRequest.h"
#include "rest/RestService.h"
#include "unittest.h"
/* ****************************************************************************
*
* rs -
*/
static RestService rs[] =
{
{ "PUT", IndividualContextEntityAttribute, 5, { "ngsi10", "contextEntities", "*", "attributes", "*" }, "", putIndividualContextEntityAttribute },
{ "*", InvalidRequest, 0, { "*", "*", "*", "*", "*", "*" }, "", badRequest },
{ "", InvalidRequest, 0, { }, "", NULL }
};
/* ****************************************************************************
*
* json -
*/
TEST(putIndividualContextEntityAttribute, xml)
{
ConnectionInfo ci("/ngsi10/contextEntities/entity11/attributes/temperature", "PUT", "1.1");
const char* infile = "ngsi10.updateContextAttributeRequest.putAttribute.valid.xml";
const char* outfile = "ngsi10.updateContextAttributeResponse.ok.valid.xml";
std::string out;
EXPECT_EQ("OK", testDataFromFile(testBuf, sizeof(testBuf), infile)) << "Error getting test data from '" << infile << "'";
EXPECT_EQ("OK", testDataFromFile(expectedBuf, sizeof(expectedBuf), outfile)) << "Error getting test data from '" << outfile << "'";
ci.outFormat = XML;
ci.inFormat = XML;
ci.payload = testBuf;
ci.payloadSize = strlen(testBuf);
out = restService(&ci, rs);
EXPECT_STREQ(expectedBuf, out.c_str());
utExit();
}
/* ****************************************************************************
*
* json -
*/
TEST(putIndividualContextEntityAttribute, json)
{
ConnectionInfo ci("/ngsi10/contextEntities/entity11/attributes/temperature", "PUT", "1.1");
const char* infile = "ngsi10.updateContextAttributeRequest.putAttribute.valid.json";
const char* outfile = "ngsi10.updateContextAttributeResponse.ok.invalid.json";
std::string out;
EXPECT_EQ("OK", testDataFromFile(testBuf, sizeof(testBuf), infile)) << "Error getting test data from '" << infile << "'";
EXPECT_EQ("OK", testDataFromFile(expectedBuf, sizeof(expectedBuf), outfile)) << "Error getting test data from '" << outfile << "'";
ci.outFormat = JSON;
ci.inFormat = JSON;
ci.payload = testBuf;
ci.payloadSize = strlen(testBuf);
out = restService(&ci, rs);
EXPECT_STREQ(expectedBuf, out.c_str());
utExit();
}
|
Change date of copyright notice
|
Change date of copyright notice
|
C++
|
agpl-3.0
|
pacificIT/fiware-orion,gavioto/fiware-orion,fortizc/fiware-orion,fortizc/fiware-orion,Fiware/data.Orion,jmcanterafonseca/fiware-orion,gavioto/fiware-orion,pacificIT/fiware-orion,j1fig/fiware-orion,Fiware/data.Orion,McMutton/fiware-orion,fiwareulpgcmirror/fiware-orion,fiwareulpgcmirror/fiware-orion,telefonicaid/fiware-orion,jmcanterafonseca/fiware-orion,Fiware/data.Orion,telefonicaid/fiware-orion,yalp/fiware-orion,Fiware/context.Orion,gavioto/fiware-orion,fortizc/fiware-orion,fiwareulpgcmirror/fiware-orion,guerrerocarlos/fiware-orion,Fiware/context.Orion,gavioto/fiware-orion,jmcanterafonseca/fiware-orion,pacificIT/fiware-orion,j1fig/fiware-orion,fortizc/fiware-orion,Fiware/context.Orion,guerrerocarlos/fiware-orion,yalp/fiware-orion,fortizc/fiware-orion,McMutton/fiware-orion,j1fig/fiware-orion,yalp/fiware-orion,fiwareulpgcmirror/fiware-orion,gavioto/fiware-orion,McMutton/fiware-orion,telefonicaid/fiware-orion,guerrerocarlos/fiware-orion,Fiware/context.Orion,pacificIT/fiware-orion,j1fig/fiware-orion,telefonicaid/fiware-orion,Fiware/context.Orion,guerrerocarlos/fiware-orion,Fiware/data.Orion,telefonicaid/fiware-orion,guerrerocarlos/fiware-orion,McMutton/fiware-orion,Fiware/data.Orion,jmcanterafonseca/fiware-orion,McMutton/fiware-orion,Fiware/data.Orion,yalp/fiware-orion,jmcanterafonseca/fiware-orion,McMutton/fiware-orion,jmcanterafonseca/fiware-orion,fiwareulpgcmirror/fiware-orion,yalp/fiware-orion,fortizc/fiware-orion,fiwareulpgcmirror/fiware-orion,Fiware/context.Orion,j1fig/fiware-orion,pacificIT/fiware-orion,McMutton/fiware-orion,telefonicaid/fiware-orion
|
d891d69cd50ece1cbfc736ffdbfb06c108103138
|
DacrsUI/SignAccountsDlg.cpp
|
DacrsUI/SignAccountsDlg.cpp
|
// SignAccountsDlg.cpp : ʵļ
//
#include "stdafx.h"
#include "DacrsUI.h"
#include "SignAccountsDlg.h"
#include "afxdialogex.h"
// CSignAccountsDlg Ի
IMPLEMENT_DYNAMIC(CSignAccountsDlg, CDialogEx)
CSignAccountsDlg::CSignAccountsDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CSignAccountsDlg::IDD, pParent)
{
m_pBmp = NULL ;
}
CSignAccountsDlg::~CSignAccountsDlg()
{
if( NULL != m_pBmp ) {
DeleteObject(m_pBmp) ;
m_pBmp = NULL ;
}
}
void CSignAccountsDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_BUTTON_CLOSE, m_rBtnClose);
DDX_Control(pDX, IDC_BUTTON_SEND, m_rBtnSend);
}
BEGIN_MESSAGE_MAP(CSignAccountsDlg, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON_SEND, &CSignAccountsDlg::OnBnClickedButtonSend)
ON_WM_CREATE()
ON_WM_ERASEBKGND()
ON_WM_CTLCOLOR()
ON_BN_CLICKED(IDC_BUTTON_CLOSE, &CSignAccountsDlg::OnBnClickedButtonClose)
ON_WM_LBUTTONDOWN()
ON_WM_NCHITTEST()
END_MESSAGE_MAP()
// CSignAccountsDlg Ϣ
void CSignAccountsDlg::SetBkBmpNid( UINT nBitmapIn )
{
if( NULL != m_pBmp ) {
::DeleteObject( m_pBmp ) ;
m_pBmp = NULL ;
}
m_pBmp = NULL ;
HINSTANCE hInstResource = NULL;
hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP);
if( NULL != hInstResource ) {
m_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0);
}
}
void CSignAccountsDlg::OnBnClickedButtonSend()
{
// TODO: ڴӿؼ֪ͨ
CString address;
GetDlgItem(IDC_EDIT_ADDRESS)->GetWindowText(address);
if ( _T("") != address ) {
CString strCommand , strShowData,strFee ;
strCommand.Format(_T("%s %s %lld"),_T("getaccountinfo") ,address);
CSoyPayHelp::getInstance()->SendRpc(strCommand,strShowData);
if (strShowData == _T(""))
{
::MessageBox( this->GetSafeHwnd() ,_T("ûзӦ") , _T("ʾ") , MB_ICONINFORMATION ) ;
}
Json::Reader reader;
Json::Value root;
if (!reader.parse(strShowData.GetString(), root))
return ;
GetDlgItem(IDC_EDIT_FEE)->GetWindowText(strFee);
strCommand.Format(_T("%s %s %lld"),_T("registaccounttx") ,address , (INT64)REAL_MONEY(atof(strFee)) );
CSoyPayHelp::getInstance()->SendRpc(strCommand,strShowData);
if (strShowData == _T(""))
{
::MessageBox( this->GetSafeHwnd() ,_T("ûзӦ") , _T("ʾ") , MB_ICONINFORMATION ) ;
}
if (!reader.parse(strShowData.GetString(), root))
return ;
CString strData;
int pos = strShowData.Find("hash");
if ( pos >=0 ) {
//뵽ݿ
CString strHash , strHash1;
strHash1.Format(_T("%s") , root["hash"].asCString() );
// theApp.cs_SqlData.Lock();
int nItem = theApp.m_SqliteDeal.FindDB(_T("revtransaction") , strHash1 ,_T("hash") ) ;
// theApp.cs_SqlData.Unlock();
strHash.Format(_T("'%s'") , root["hash"].asCString() );
if ( 0 == nItem ) {
CPostMsg postmsg(MSG_USER_GET_UPDATABASE,WM_REVTRANSACTION);
postmsg.SetData(strHash);
theApp.m_MsgQueue.push(postmsg);
}
}
if ( pos >=0 ) {
strData.Format( _T("ͳɹȴ1-2ȷϼ\n%s") , root["hash"].asCString() ) ;
}else{
strData.Format( _T("˻ʧ!") ) ;
}
if ( IDYES == ::MessageBox( this->GetSafeHwnd() ,strData , _T("ʾ") , MB_YESNO|MB_ICONINFORMATION ) ){
EndDialog(IDOK);
}
}
}
void CSignAccountsDlg::SetShowAddr(CString addr)
{
((CComboBox*)GetDlgItem(IDC_COMBO2))->SetCurSel(0);
GetDlgItem(IDC_EDIT_ADDRESS)->SetWindowText(addr);
}
int CSignAccountsDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialogEx::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: ڴרõĴ
return 0;
}
BOOL CSignAccountsDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: ڴӶijʼ
m_rBtnClose.SetBitmaps( IDB_BITMAP_CLOSE , RGB(255, 255, 0) , IDB_BITMAP_CLOSE2 , RGB(255, 255, 255) );
m_rBtnClose.SetAlign(CButtonST::ST_ALIGN_OVERLAP);
m_rBtnClose.SetWindowText("") ;
m_rBtnClose.SetFontEx(20 , _T("ź"));
m_rBtnClose.SetColor(CButtonST::BTNST_COLOR_FG_OUT , RGB(0, 0, 0));
m_rBtnClose.SetColor(CButtonST::BTNST_COLOR_FG_IN , RGB(200, 75, 60));
m_rBtnClose.SetColor(CButtonST::BTNST_COLOR_FG_FOCUS, RGB(0, 0, 0));
m_rBtnClose.SetColor(CButtonST::BTNST_COLOR_BK_IN, RGB(0, 0, 0));
m_rBtnClose.SizeToContent();
m_rBtnClose.SetWindowPos(NULL ,476-26 , 0 , 0 , 0 , SWP_NOSIZE);
m_rBtnSend.SetBitmaps( IDB_BITMAP_BUTTON , RGB(255, 255, 0) , IDB_BITMAP_BUTTON , RGB(255, 255, 255) );
m_rBtnSend.SetAlign(CButtonST::ST_ALIGN_OVERLAP);
m_rBtnSend.SetWindowText(" ") ;
m_rBtnSend.SetFontEx(20 , _T("ź"));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_OUT , RGB(0, 0, 0));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_IN , RGB(200, 75, 60));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_FOCUS, RGB(0, 0, 0));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_BK_IN, RGB(0, 0, 0));
m_rBtnSend.SizeToContent();
SetShowAddr( theApp.m_strAddress);
SetBkBmpNid( IDB_BITMAP_DLG_BALCK ) ;
m_fontGrid.CreatePointFont(100,_T(""));
GetDlgItem(IDC_EDIT_FEE)->SetWindowTextA("0.0001");
return TRUE; // return TRUE unless you set the focus to a control
// 쳣: OCX ҳӦ FALSE
}
BOOL CSignAccountsDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: ڴϢ/Ĭֵ
CRect rect;
GetClientRect(&rect);
if(m_pBmp != NULL) {
BITMAP bm;
CDC dcMem;
::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm);
dcMem.CreateCompatibleDC(NULL);
HBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp);
pDC->StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY);
dcMem.SelectObject(pOldBitmap);
dcMem.DeleteDC();
} else
CWnd::OnEraseBkgnd(pDC);
return TRUE;
}
HBRUSH CSignAccountsDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: ڴ˸ DC κ
if (nCtlColor == CTLCOLOR_STATIC)
{
pDC->SetBkMode(TRANSPARENT);
pDC->SelectObject(&m_fontGrid);
hbr = (HBRUSH)CreateSolidBrush(RGB(249,249,249));
}
// TODO: ĬϵIJ軭ʣһ
return hbr;
}
void CSignAccountsDlg::OnBnClickedButtonClose()
{
// TODO: ڴӿؼ֪ͨ
EndDialog(IDOK);
}
void CSignAccountsDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: ڴϢ/Ĭֵ
SendMessage(WM_SYSCOMMAND, SC_MOVE, 0);//һƶϢ
CDialogEx::OnLButtonDown(nFlags, point);
}
LRESULT CSignAccountsDlg::OnNcHitTest(CPoint point)
{
// TODO: ڴϢ/Ĭֵ
UINT nResult = CDialog::OnNcHitTest(point);
return nResult == HTCLIENT ? HTCAPTION : nResult;//ڿͻôڵĻͰɱ
return CDialogEx::OnNcHitTest(point);
}
|
// SignAccountsDlg.cpp : ʵļ
//
#include "stdafx.h"
#include "DacrsUI.h"
#include "SignAccountsDlg.h"
#include "afxdialogex.h"
// CSignAccountsDlg Ի
IMPLEMENT_DYNAMIC(CSignAccountsDlg, CDialogEx)
CSignAccountsDlg::CSignAccountsDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CSignAccountsDlg::IDD, pParent)
{
m_pBmp = NULL ;
}
CSignAccountsDlg::~CSignAccountsDlg()
{
if( NULL != m_pBmp ) {
DeleteObject(m_pBmp) ;
m_pBmp = NULL ;
}
}
void CSignAccountsDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_BUTTON_CLOSE, m_rBtnClose);
DDX_Control(pDX, IDC_BUTTON_SEND, m_rBtnSend);
}
BEGIN_MESSAGE_MAP(CSignAccountsDlg, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON_SEND, &CSignAccountsDlg::OnBnClickedButtonSend)
ON_WM_CREATE()
ON_WM_ERASEBKGND()
ON_WM_CTLCOLOR()
ON_BN_CLICKED(IDC_BUTTON_CLOSE, &CSignAccountsDlg::OnBnClickedButtonClose)
ON_WM_LBUTTONDOWN()
ON_WM_NCHITTEST()
END_MESSAGE_MAP()
// CSignAccountsDlg Ϣ
void CSignAccountsDlg::SetBkBmpNid( UINT nBitmapIn )
{
if( NULL != m_pBmp ) {
::DeleteObject( m_pBmp ) ;
m_pBmp = NULL ;
}
m_pBmp = NULL ;
HINSTANCE hInstResource = NULL;
hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nBitmapIn), RT_BITMAP);
if( NULL != hInstResource ) {
m_pBmp = (HBITMAP)::LoadImage(hInstResource, MAKEINTRESOURCE(nBitmapIn), IMAGE_BITMAP, 0, 0, 0);
}
}
void CSignAccountsDlg::OnBnClickedButtonSend()
{
// TODO: ڴӿؼ֪ͨ
CString address;
GetDlgItem(IDC_EDIT_ADDRESS)->GetWindowText(address);
if ( _T("") != address ) {
CString strCommand , strShowData,strFee ;
strCommand.Format(_T("%s %s %lld"),_T("getaccountinfo") ,address);
CSoyPayHelp::getInstance()->SendRpc(strCommand,strShowData);
if (strShowData == _T(""))
{
::MessageBox( this->GetSafeHwnd() ,_T("ûзӦ") , _T("ʾ") , MB_ICONINFORMATION ) ;
}
Json::Reader reader;
Json::Value root;
if (!reader.parse(strShowData.GetString(), root))
return ;
GetDlgItem(IDC_EDIT_FEE)->GetWindowText(strFee);
strCommand.Format(_T("%s %s %lld"),_T("registaccounttx") ,address , (INT64)REAL_MONEY(atof(strFee)) );
CSoyPayHelp::getInstance()->SendRpc(strCommand,strShowData);
if (strShowData == _T(""))
{
::MessageBox( this->GetSafeHwnd() ,_T("ûзӦ") , _T("ʾ") , MB_ICONINFORMATION ) ;
}
if (!reader.parse(strShowData.GetString(), root))
return ;
CString strData;
int pos = strShowData.Find("hash");
if ( pos >=0 ) {
//뵽ݿ
CString strHash , strHash1;
strHash1.Format(_T("%s") , root["hash"].asCString() );
// theApp.cs_SqlData.Lock();
int nItem = theApp.m_SqliteDeal.FindDB(_T("revtransaction") , strHash1 ,_T("hash") ) ;
// theApp.cs_SqlData.Unlock();
strHash.Format(_T("'%s'") , root["hash"].asCString() );
if ( 0 == nItem ) {
CPostMsg postmsg(MSG_USER_GET_UPDATABASE,WM_REVTRANSACTION);
postmsg.SetData(strHash);
theApp.m_MsgQueue.push(postmsg);
}
}
if ( pos >=0 ) {
strData.Format( _T("ͳɹȴ1-2ȷϼ\n%s") , root["hash"].asCString() ) ;
}else{
strData.Format( _T("˻ʧ!") ) ;
}
if ( IDYES == ::MessageBox( this->GetSafeHwnd() ,strData , _T("ʾ") , MB_YESNO|MB_ICONINFORMATION ) ){
EndDialog(IDOK);
}
}
}
void CSignAccountsDlg::SetShowAddr(CString addr)
{
((CComboBox*)GetDlgItem(IDC_COMBO2))->SetCurSel(0);
GetDlgItem(IDC_EDIT_ADDRESS)->SetWindowText(addr);
}
int CSignAccountsDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialogEx::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: ڴרõĴ
return 0;
}
BOOL CSignAccountsDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: ڴӶijʼ
m_rBtnClose.SetBitmaps( IDB_BITMAP_CLOSE , RGB(255, 255, 0) , IDB_BITMAP_CLOSE2 , RGB(255, 255, 255) );
m_rBtnClose.SetAlign(CButtonST::ST_ALIGN_OVERLAP);
m_rBtnClose.SetWindowText("") ;
m_rBtnClose.SetFontEx(20 , _T("ź"));
m_rBtnClose.SetColor(CButtonST::BTNST_COLOR_FG_OUT , RGB(0, 0, 0));
m_rBtnClose.SetColor(CButtonST::BTNST_COLOR_FG_IN , RGB(200, 75, 60));
m_rBtnClose.SetColor(CButtonST::BTNST_COLOR_FG_FOCUS, RGB(0, 0, 0));
m_rBtnClose.SetColor(CButtonST::BTNST_COLOR_BK_IN, RGB(0, 0, 0));
m_rBtnClose.SizeToContent();
m_rBtnClose.SetWindowPos(NULL ,476-26 , 0 , 0 , 0 , SWP_NOSIZE);
m_rBtnSend.SetBitmaps( IDB_BITMAP_BUTTON , RGB(255, 255, 0) , IDB_BITMAP_BUTTON , RGB(255, 255, 255) );
m_rBtnSend.SetAlign(CButtonST::ST_ALIGN_OVERLAP);
m_rBtnSend.SetWindowText(" ") ;
m_rBtnSend.SetFontEx(20 , _T("ź"));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_OUT , RGB(0, 0, 0));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_IN , RGB(200, 75, 60));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_FG_FOCUS, RGB(0, 0, 0));
m_rBtnSend.SetColor(CButtonST::BTNST_COLOR_BK_IN, RGB(0, 0, 0));
m_rBtnSend.SizeToContent();
SetShowAddr( theApp.m_strAddress);
SetBkBmpNid( IDB_BITMAP_DLG_BALCK ) ;
m_fontGrid.CreatePointFont(100,_T(""));
GetDlgItem(IDC_EDIT_FEE)->SetWindowTextA("0.0001");
return TRUE; // return TRUE unless you set the focus to a control
// 쳣: OCX ҳӦ FALSE
}
BOOL CSignAccountsDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: ڴϢ/Ĭֵ
CRect rect;
GetClientRect(&rect);
if(m_pBmp != NULL) {
BITMAP bm;
CDC dcMem;
::GetObject(m_pBmp,sizeof(BITMAP), (LPVOID)&bm);
dcMem.CreateCompatibleDC(NULL);
HBITMAP pOldBitmap =(HBITMAP ) dcMem.SelectObject(m_pBmp);
pDC->StretchBlt(rect.left,rect.top-1,rect.Width(),rect.Height(), &dcMem, 0, 0,bm.bmWidth-1,bm.bmHeight-1, SRCCOPY);
dcMem.SelectObject(pOldBitmap);
dcMem.DeleteDC();
} else
CWnd::OnEraseBkgnd(pDC);
return TRUE;
}
HBRUSH CSignAccountsDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: ڴ˸ DC κ
if (nCtlColor == CTLCOLOR_STATIC)
{
pDC->SetBkMode(TRANSPARENT);
pDC->SelectObject(&m_fontGrid);
hbr = (HBRUSH)CreateSolidBrush(RGB(249,249,249));
}
// TODO: ĬϵIJ軭ʣһ
return hbr;
}
void CSignAccountsDlg::OnBnClickedButtonClose()
{
// TODO: ڴӿؼ֪ͨ
EndDialog(IDOK);
}
void CSignAccountsDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: ڴϢ/Ĭֵ
SendMessage(WM_SYSCOMMAND, SC_MOVE, 0);//һƶϢ
CDialogEx::OnLButtonDown(nFlags, point);
}
LRESULT CSignAccountsDlg::OnNcHitTest(CPoint point)
{
// TODO: ڴϢ/Ĭֵ
UINT nResult = CDialog::OnNcHitTest(point);
return nResult == HTCLIENT ? HTCAPTION : nResult;//ڿͻôڵĻͰɱ
return CDialogEx::OnNcHitTest(point);
}
|
modify regaccount btn text
|
modify regaccount btn text
Former-commit-id: 28e926c7cd3a5ee0043835d6551941113487bb2f
|
C++
|
mit
|
SoyPay/DacrsUI,SoyPay/DacrsUI
|
ac86e4cecfbef915a9aeea3e44f8d2c541577476
|
test/DebouncedGPIO.t.cpp
|
test/DebouncedGPIO.t.cpp
|
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "../DebouncedGPIO.h"
class CapturingLightSwitch : public LightSwitch
{
public:
int state = 0;
CapturingLightSwitch() { };
void externalOn()
{
state=1;
};
void externalOff()
{
state=2;
};
void externalToggle()
{
state=4;
};
};
TEST_CASE("Debouncing high low from a gpio", "[DebouncedGPIO]" ) {
CapturingLightSwitch cls{};
AbstractButton * debounced = new DebouncedGPIO{cls};
debounced->low();
SECTION("Low to High results in TOGGLE") {
debounced->high();
REQUIRE( cls.state == 0);
debounced->loop();
REQUIRE( cls.state == 4);
}
SECTION("Low to High quickly results in no change, NEED TO INTRODUCE CONCEPT OF TIME") {
int preState = cls.state;
debounced->high();
REQUIRE( cls.state == preState);
debounced->loop();
REQUIRE( cls.state == preState);
}
}
|
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "../DebouncedGPIO.h"
class CapturingLightSwitch : public LightSwitch
{
public:
int state = 0;
CapturingLightSwitch() { };
void externalOn()
{
state=1;
};
void externalOff()
{
state=2;
};
void externalToggle()
{
state=4;
};
};
TEST_CASE("Debouncing high low from a gpio", "[DebouncedGPIO]" ) {
CapturingLightSwitch cls{};
AbstractButton * debounced = new DebouncedGPIO{cls};
debounced->low();
SECTION("Low to High results in TOGGLE") {
debounced->high(1);
REQUIRE( cls.state == 0);
debounced->loop(200);
REQUIRE( cls.state == 4);
}
SECTION("Low to High quickly results in no change, NEED TO INTRODUCE CONCEPT OF TIME") {
int preState = cls.state;
debounced->high(1);
REQUIRE( cls.state == preState);
debounced->loop(90);
REQUIRE( cls.state == preState);
}
}
|
Change the interfaces for button, nothing compiles
|
Change the interfaces for button, nothing compiles
|
C++
|
mit
|
rossbeazley/SonoffBoilerplate,rossbeazley/SonoffBoilerplate,rossbeazley/SonoffBoilerplate,rossbeazley/SonoffBoilerplate,rossbeazley/SonoffBoilerplate
|
aadc2db22cb5c7226700f4b9c463d27a15a11703
|
test/Prompt/Regression.C
|
test/Prompt/Regression.C
|
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -I%p | FileCheck %s
// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here
// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char *) "Root"]
// End PR #98146
|
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -I%p | FileCheck %s
// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here
// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char *) "Root"]
gCling->declare("typedef enum {k1,k2} enumName");
// CHECK:
// End PR #98146
|
Add test for unnamed decls for cling.
|
Add test for unnamed decls for cling.
|
C++
|
lgpl-2.1
|
marsupial/cling,karies/cling,karies/cling,karies/cling,perovic/cling,marsupial/cling,root-mirror/cling,marsupial/cling,marsupial/cling,marsupial/cling,marsupial/cling,root-mirror/cling,perovic/cling,perovic/cling,perovic/cling,root-mirror/cling,root-mirror/cling,karies/cling,perovic/cling,karies/cling,root-mirror/cling,karies/cling,root-mirror/cling
|
4322000f0b077b1f8415cdea5cc15dbea7738c88
|
test/aggregates_test.cpp
|
test/aggregates_test.cpp
|
#include <archie/utils/fused/holder.h>
#include <archie/utils/fused/tuple.h>
#include <archie/utils/fused/tuple_view.h>
#include <string>
#include <memory>
#include <archie/utils/test.h>
namespace detail {
struct PackedStruct {
struct Id : archie::utils::fused::holder<unsigned> {
using holder::holder;
};
struct Name : archie::utils::fused::holder<std::string> {
using holder::holder;
};
struct Value : archie::utils::fused::holder<int> {
using holder::holder;
};
struct Amount : archie::utils::fused::holder<unsigned> {
using holder::holder;
};
using type = archie::utils::fused::tuple<Id, Name, Value, Amount>;
};
}
struct PackedStruct : detail::PackedStruct::type {
using Id = detail::PackedStruct::Id;
using Name = detail::PackedStruct::Name;
using Value = detail::PackedStruct::Value;
using Amount = detail::PackedStruct::Amount;
using BaseType = detail::PackedStruct::type;
using BaseType::BaseType;
};
namespace fused = archie::utils::fused;
void canCreate() {
auto pack = std::make_unique<PackedStruct>(1, "Aqq", -20, 10);
EXPECT_EQ(1u, fused::get<PackedStruct::Id>(*pack));
EXPECT_EQ("Aqq", fused::get<PackedStruct::Name>(*pack));
EXPECT_EQ(-20, fused::get<PackedStruct::Value>(*pack));
pack.reset();
}
void canSelect() {
auto pack = std::make_unique<PackedStruct>(1, "Aqq", -20, 10);
auto select = fused::select<PackedStruct::Id, PackedStruct::Value>(*pack);
EXPECT_EQ(1u, fused::get<PackedStruct::Id>(select));
EXPECT_EQ(-20, fused::get<PackedStruct::Value>(select));
}
int main() {
canCreate();
canSelect();
return 0;
}
|
#include <archie/utils/fused/holder.h>
#include <archie/utils/fused/tuple.h>
#include <archie/utils/fused/tuple_view.h>
#include <string>
#include <archie/utils/test.h>
namespace detail {
struct PackedStruct {
struct Id : archie::utils::fused::holder<unsigned> {
using holder::holder;
};
struct Name : archie::utils::fused::holder<std::string> {
using holder::holder;
};
struct Value : archie::utils::fused::holder<int> {
using holder::holder;
};
struct Amount : archie::utils::fused::holder<unsigned> {
using holder::holder;
};
using type = archie::utils::fused::tuple<Id, Name, Value, Amount>;
};
}
struct PackedStruct : detail::PackedStruct::type {
using Id = detail::PackedStruct::Id;
using Name = detail::PackedStruct::Name;
using Value = detail::PackedStruct::Value;
using Amount = detail::PackedStruct::Amount;
using BaseType = detail::PackedStruct::type;
using BaseType::BaseType;
};
namespace fused = archie::utils::fused;
void canCreate() {
PackedStruct pack{1, "Aqq", -20, 10};
EXPECT_EQ(1u, fused::get<PackedStruct::Id>(pack));
EXPECT_EQ("Aqq", fused::get<PackedStruct::Name>(pack));
EXPECT_EQ(-20, fused::get<PackedStruct::Value>(pack));
}
void canSelect() {
PackedStruct pack{1, "Aqq", -20, 10};
auto select = fused::select<PackedStruct::Id, PackedStruct::Value>(pack);
EXPECT_EQ(1u, fused::get<PackedStruct::Id>(select));
EXPECT_EQ(-20, fused::get<PackedStruct::Value>(select));
}
int main() {
canCreate();
canSelect();
return 0;
}
|
remove smart ptr
|
remove smart ptr
|
C++
|
mit
|
attugit/archie,attugit/archie,attugit/archie,attugit/archie
|
2fb4178f7c145d33a8caa986e6a957c0d4fa9f3d
|
modules/core/src/kmeans.cpp
|
modules/core/src/kmeans.cpp
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
////////////////////////////////////////// kmeans ////////////////////////////////////////////
namespace cv
{
static void generateRandomCenter(const std::vector<Vec2f>& box, float* center, RNG& rng)
{
size_t j, dims = box.size();
float margin = 1.f/dims;
for( j = 0; j < dims; j++ )
center[j] = ((float)rng*(1.f+margin*2.f)-margin)*(box[j][1] - box[j][0]) + box[j][0];
}
class KMeansPPDistanceComputer : public ParallelLoopBody
{
public:
KMeansPPDistanceComputer( float *_tdist2,
const float *_data,
const float *_dist,
int _dims,
size_t _step,
size_t _stepci )
: tdist2(_tdist2),
data(_data),
dist(_dist),
dims(_dims),
step(_step),
stepci(_stepci) { }
void operator()( const cv::Range& range ) const
{
const int begin = range.start;
const int end = range.end;
for ( int i = begin; i<end; i++ )
{
tdist2[i] = std::min(normL2Sqr_(data + step*i, data + stepci, dims), dist[i]);
}
}
private:
KMeansPPDistanceComputer& operator=(const KMeansPPDistanceComputer&); // to quiet MSVC
float *tdist2;
const float *data;
const float *dist;
const int dims;
const size_t step;
const size_t stepci;
};
/*
k-means center initialization using the following algorithm:
Arthur & Vassilvitskii (2007) k-means++: The Advantages of Careful Seeding
*/
static void generateCentersPP(const Mat& _data, Mat& _out_centers,
int K, RNG& rng, int trials)
{
int i, j, k, dims = _data.cols, N = _data.rows;
const float* data = _data.ptr<float>(0);
size_t step = _data.step/sizeof(data[0]);
std::vector<int> _centers(K);
int* centers = &_centers[0];
std::vector<float> _dist(N*3);
float* dist = &_dist[0], *tdist = dist + N, *tdist2 = tdist + N;
double sum0 = 0;
centers[0] = (unsigned)rng % N;
for( i = 0; i < N; i++ )
{
dist[i] = normL2Sqr_(data + step*i, data + step*centers[0], dims);
sum0 += dist[i];
}
for( k = 1; k < K; k++ )
{
double bestSum = DBL_MAX;
int bestCenter = -1;
for( j = 0; j < trials; j++ )
{
double p = (double)rng*sum0, s = 0;
for( i = 0; i < N-1; i++ )
if( (p -= dist[i]) <= 0 )
break;
int ci = i;
parallel_for_(Range(0, N),
KMeansPPDistanceComputer(tdist2, data, dist, dims, step, step*ci));
for( i = 0; i < N; i++ )
{
s += tdist2[i];
}
if( s < bestSum )
{
bestSum = s;
bestCenter = ci;
std::swap(tdist, tdist2);
}
}
centers[k] = bestCenter;
sum0 = bestSum;
std::swap(dist, tdist);
}
for( k = 0; k < K; k++ )
{
const float* src = data + step*centers[k];
float* dst = _out_centers.ptr<float>(k);
for( j = 0; j < dims; j++ )
dst[j] = src[j];
}
}
class KMeansDistanceComputer : public ParallelLoopBody
{
public:
KMeansDistanceComputer( double *_distances,
int *_labels,
const Mat& _data,
const Mat& _centers )
: distances(_distances),
labels(_labels),
data(_data),
centers(_centers)
{
}
void operator()( const Range& range ) const
{
const int begin = range.start;
const int end = range.end;
const int K = centers.rows;
const int dims = centers.cols;
const float *sample;
for( int i = begin; i<end; ++i)
{
sample = data.ptr<float>(i);
int k_best = 0;
double min_dist = DBL_MAX;
for( int k = 0; k < K; k++ )
{
const float* center = centers.ptr<float>(k);
const double dist = normL2Sqr_(sample, center, dims);
if( min_dist > dist )
{
min_dist = dist;
k_best = k;
}
}
distances[i] = min_dist;
labels[i] = k_best;
}
}
private:
KMeansDistanceComputer& operator=(const KMeansDistanceComputer&); // to quiet MSVC
double *distances;
int *labels;
const Mat& data;
const Mat& centers;
};
}
double cv::kmeans( InputArray _data, int K,
InputOutputArray _bestLabels,
TermCriteria criteria, int attempts,
int flags, OutputArray _centers )
{
const int SPP_TRIALS = 3;
Mat data0 = _data.getMat();
bool isrow = data0.rows == 1 && data0.channels() > 1;
int N = !isrow ? data0.rows : data0.cols;
int dims = (!isrow ? data0.cols : 1)*data0.channels();
int type = data0.depth();
attempts = std::max(attempts, 1);
CV_Assert( data0.dims <= 2 && type == CV_32F && K > 0 );
CV_Assert( N >= K );
Mat data(N, dims, CV_32F, data0.ptr(), isrow ? dims * sizeof(float) : static_cast<size_t>(data0.step));
_bestLabels.create(N, 1, CV_32S, -1, true);
Mat _labels, best_labels = _bestLabels.getMat();
if( flags & CV_KMEANS_USE_INITIAL_LABELS )
{
CV_Assert( (best_labels.cols == 1 || best_labels.rows == 1) &&
best_labels.cols*best_labels.rows == N &&
best_labels.type() == CV_32S &&
best_labels.isContinuous());
best_labels.copyTo(_labels);
}
else
{
if( !((best_labels.cols == 1 || best_labels.rows == 1) &&
best_labels.cols*best_labels.rows == N &&
best_labels.type() == CV_32S &&
best_labels.isContinuous()))
best_labels.create(N, 1, CV_32S);
_labels.create(best_labels.size(), best_labels.type());
}
int* labels = _labels.ptr<int>();
Mat centers(K, dims, type), old_centers(K, dims, type), temp(1, dims, type);
std::vector<int> counters(K);
std::vector<Vec2f> _box(dims);
Vec2f* box = &_box[0];
double best_compactness = DBL_MAX, compactness = 0;
RNG& rng = theRNG();
int a, iter, i, j, k;
if( criteria.type & TermCriteria::EPS )
criteria.epsilon = std::max(criteria.epsilon, 0.);
else
criteria.epsilon = FLT_EPSILON;
criteria.epsilon *= criteria.epsilon;
if( criteria.type & TermCriteria::COUNT )
criteria.maxCount = std::min(std::max(criteria.maxCount, 2), 100);
else
criteria.maxCount = 100;
if( K == 1 )
{
attempts = 1;
criteria.maxCount = 2;
}
const float* sample = data.ptr<float>(0);
for( j = 0; j < dims; j++ )
box[j] = Vec2f(sample[j], sample[j]);
for( i = 1; i < N; i++ )
{
sample = data.ptr<float>(i);
for( j = 0; j < dims; j++ )
{
float v = sample[j];
box[j][0] = std::min(box[j][0], v);
box[j][1] = std::max(box[j][1], v);
}
}
for( a = 0; a < attempts; a++ )
{
double max_center_shift = DBL_MAX;
for( iter = 0;; )
{
swap(centers, old_centers);
if( iter == 0 && (a > 0 || !(flags & KMEANS_USE_INITIAL_LABELS)) )
{
if( flags & KMEANS_PP_CENTERS )
generateCentersPP(data, centers, K, rng, SPP_TRIALS);
else
{
for( k = 0; k < K; k++ )
generateRandomCenter(_box, centers.ptr<float>(k), rng);
}
}
else
{
if( iter == 0 && a == 0 && (flags & KMEANS_USE_INITIAL_LABELS) )
{
for( i = 0; i < N; i++ )
CV_Assert( (unsigned)labels[i] < (unsigned)K );
}
// compute centers
centers = Scalar(0);
for( k = 0; k < K; k++ )
counters[k] = 0;
for( i = 0; i < N; i++ )
{
sample = data.ptr<float>(i);
k = labels[i];
float* center = centers.ptr<float>(k);
j=0;
#if CV_ENABLE_UNROLLED
for(; j <= dims - 4; j += 4 )
{
float t0 = center[j] + sample[j];
float t1 = center[j+1] + sample[j+1];
center[j] = t0;
center[j+1] = t1;
t0 = center[j+2] + sample[j+2];
t1 = center[j+3] + sample[j+3];
center[j+2] = t0;
center[j+3] = t1;
}
#endif
for( ; j < dims; j++ )
center[j] += sample[j];
counters[k]++;
}
if( iter > 0 )
max_center_shift = 0;
for( k = 0; k < K; k++ )
{
if( counters[k] != 0 )
continue;
// if some cluster appeared to be empty then:
// 1. find the biggest cluster
// 2. find the farthest from the center point in the biggest cluster
// 3. exclude the farthest point from the biggest cluster and form a new 1-point cluster.
int max_k = 0;
for( int k1 = 1; k1 < K; k1++ )
{
if( counters[max_k] < counters[k1] )
max_k = k1;
}
double max_dist = 0;
int farthest_i = -1;
float* new_center = centers.ptr<float>(k);
float* old_center = centers.ptr<float>(max_k);
float* _old_center = temp.ptr<float>(); // normalized
float scale = 1.f/counters[max_k];
for( j = 0; j < dims; j++ )
_old_center[j] = old_center[j]*scale;
for( i = 0; i < N; i++ )
{
if( labels[i] != max_k )
continue;
sample = data.ptr<float>(i);
double dist = normL2Sqr_(sample, _old_center, dims);
if( max_dist <= dist )
{
max_dist = dist;
farthest_i = i;
}
}
counters[max_k]--;
counters[k]++;
labels[farthest_i] = k;
sample = data.ptr<float>(farthest_i);
for( j = 0; j < dims; j++ )
{
old_center[j] -= sample[j];
new_center[j] += sample[j];
}
}
for( k = 0; k < K; k++ )
{
float* center = centers.ptr<float>(k);
CV_Assert( counters[k] != 0 );
float scale = 1.f/counters[k];
for( j = 0; j < dims; j++ )
center[j] *= scale;
if( iter > 0 )
{
double dist = 0;
const float* old_center = old_centers.ptr<float>(k);
for( j = 0; j < dims; j++ )
{
double t = center[j] - old_center[j];
dist += t*t;
}
max_center_shift = std::max(max_center_shift, dist);
}
}
}
if( ++iter == MAX(criteria.maxCount, 2) || max_center_shift <= criteria.epsilon )
break;
// assign labels
Mat dists(1, N, CV_64F);
double* dist = dists.ptr<double>(0);
parallel_for_(Range(0, N),
KMeansDistanceComputer(dist, labels, data, centers));
compactness = 0;
for( i = 0; i < N; i++ )
{
compactness += dist[i];
}
}
if( compactness < best_compactness )
{
best_compactness = compactness;
if( _centers.needed() )
centers.copyTo(_centers);
_labels.copyTo(best_labels);
}
}
return best_compactness;
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
////////////////////////////////////////// kmeans ////////////////////////////////////////////
namespace cv
{
static void generateRandomCenter(const std::vector<Vec2f>& box, float* center, RNG& rng)
{
size_t j, dims = box.size();
float margin = 1.f/dims;
for( j = 0; j < dims; j++ )
center[j] = ((float)rng*(1.f+margin*2.f)-margin)*(box[j][1] - box[j][0]) + box[j][0];
}
class KMeansPPDistanceComputer : public ParallelLoopBody
{
public:
KMeansPPDistanceComputer( float *_tdist2,
const float *_data,
const float *_dist,
int _dims,
size_t _step,
size_t _stepci )
: tdist2(_tdist2),
data(_data),
dist(_dist),
dims(_dims),
step(_step),
stepci(_stepci) { }
void operator()( const cv::Range& range ) const
{
const int begin = range.start;
const int end = range.end;
for ( int i = begin; i<end; i++ )
{
tdist2[i] = std::min(normL2Sqr_(data + step*i, data + stepci, dims), dist[i]);
}
}
private:
KMeansPPDistanceComputer& operator=(const KMeansPPDistanceComputer&); // to quiet MSVC
float *tdist2;
const float *data;
const float *dist;
const int dims;
const size_t step;
const size_t stepci;
};
/*
k-means center initialization using the following algorithm:
Arthur & Vassilvitskii (2007) k-means++: The Advantages of Careful Seeding
*/
static void generateCentersPP(const Mat& _data, Mat& _out_centers,
int K, RNG& rng, int trials)
{
int i, j, k, dims = _data.cols, N = _data.rows;
const float* data = _data.ptr<float>(0);
size_t step = _data.step/sizeof(data[0]);
std::vector<int> _centers(K);
int* centers = &_centers[0];
std::vector<float> _dist(N*3);
float* dist = &_dist[0], *tdist = dist + N, *tdist2 = tdist + N;
double sum0 = 0;
centers[0] = (unsigned)rng % N;
for( i = 0; i < N; i++ )
{
dist[i] = normL2Sqr_(data + step*i, data + step*centers[0], dims);
sum0 += dist[i];
}
for( k = 1; k < K; k++ )
{
double bestSum = DBL_MAX;
int bestCenter = -1;
for( j = 0; j < trials; j++ )
{
double p = (double)rng*sum0, s = 0;
for( i = 0; i < N-1; i++ )
if( (p -= dist[i]) <= 0 )
break;
int ci = i;
parallel_for_(Range(0, N),
KMeansPPDistanceComputer(tdist2, data, dist, dims, step, step*ci));
for( i = 0; i < N; i++ )
{
s += tdist2[i];
}
if( s < bestSum )
{
bestSum = s;
bestCenter = ci;
std::swap(tdist, tdist2);
}
}
centers[k] = bestCenter;
sum0 = bestSum;
std::swap(dist, tdist);
}
for( k = 0; k < K; k++ )
{
const float* src = data + step*centers[k];
float* dst = _out_centers.ptr<float>(k);
for( j = 0; j < dims; j++ )
dst[j] = src[j];
}
}
class KMeansDistanceComputer : public ParallelLoopBody
{
public:
KMeansDistanceComputer( double *_distances,
int *_labels,
const Mat& _data,
const Mat& _centers )
: distances(_distances),
labels(_labels),
data(_data),
centers(_centers)
{
}
void operator()( const Range& range ) const
{
const int begin = range.start;
const int end = range.end;
const int K = centers.rows;
const int dims = centers.cols;
for( int i = begin; i<end; ++i)
{
const float *sample = data.ptr<float>(i);
int k_best = 0;
double min_dist = DBL_MAX;
for( int k = 0; k < K; k++ )
{
const float* center = centers.ptr<float>(k);
const double dist = normL2Sqr_(sample, center, dims);
if( min_dist > dist )
{
min_dist = dist;
k_best = k;
}
}
distances[i] = min_dist;
labels[i] = k_best;
}
}
private:
KMeansDistanceComputer& operator=(const KMeansDistanceComputer&); // to quiet MSVC
double *distances;
int *labels;
const Mat& data;
const Mat& centers;
};
}
double cv::kmeans( InputArray _data, int K,
InputOutputArray _bestLabels,
TermCriteria criteria, int attempts,
int flags, OutputArray _centers )
{
const int SPP_TRIALS = 3;
Mat data0 = _data.getMat();
bool isrow = data0.rows == 1 && data0.channels() > 1;
int N = !isrow ? data0.rows : data0.cols;
int dims = (!isrow ? data0.cols : 1)*data0.channels();
int type = data0.depth();
attempts = std::max(attempts, 1);
CV_Assert( data0.dims <= 2 && type == CV_32F && K > 0 );
CV_Assert( N >= K );
Mat data(N, dims, CV_32F, data0.ptr(), isrow ? dims * sizeof(float) : static_cast<size_t>(data0.step));
_bestLabels.create(N, 1, CV_32S, -1, true);
Mat _labels, best_labels = _bestLabels.getMat();
if( flags & CV_KMEANS_USE_INITIAL_LABELS )
{
CV_Assert( (best_labels.cols == 1 || best_labels.rows == 1) &&
best_labels.cols*best_labels.rows == N &&
best_labels.type() == CV_32S &&
best_labels.isContinuous());
best_labels.copyTo(_labels);
}
else
{
if( !((best_labels.cols == 1 || best_labels.rows == 1) &&
best_labels.cols*best_labels.rows == N &&
best_labels.type() == CV_32S &&
best_labels.isContinuous()))
best_labels.create(N, 1, CV_32S);
_labels.create(best_labels.size(), best_labels.type());
}
int* labels = _labels.ptr<int>();
Mat centers(K, dims, type), old_centers(K, dims, type), temp(1, dims, type);
std::vector<int> counters(K);
std::vector<Vec2f> _box(dims);
Vec2f* box = &_box[0];
double best_compactness = DBL_MAX, compactness = 0;
RNG& rng = theRNG();
int a, iter, i, j, k;
if( criteria.type & TermCriteria::EPS )
criteria.epsilon = std::max(criteria.epsilon, 0.);
else
criteria.epsilon = FLT_EPSILON;
criteria.epsilon *= criteria.epsilon;
if( criteria.type & TermCriteria::COUNT )
criteria.maxCount = std::min(std::max(criteria.maxCount, 2), 100);
else
criteria.maxCount = 100;
if( K == 1 )
{
attempts = 1;
criteria.maxCount = 2;
}
const float* sample = data.ptr<float>(0);
for( j = 0; j < dims; j++ )
box[j] = Vec2f(sample[j], sample[j]);
for( i = 1; i < N; i++ )
{
sample = data.ptr<float>(i);
for( j = 0; j < dims; j++ )
{
float v = sample[j];
box[j][0] = std::min(box[j][0], v);
box[j][1] = std::max(box[j][1], v);
}
}
for( a = 0; a < attempts; a++ )
{
double max_center_shift = DBL_MAX;
for( iter = 0;; )
{
swap(centers, old_centers);
if( iter == 0 && (a > 0 || !(flags & KMEANS_USE_INITIAL_LABELS)) )
{
if( flags & KMEANS_PP_CENTERS )
generateCentersPP(data, centers, K, rng, SPP_TRIALS);
else
{
for( k = 0; k < K; k++ )
generateRandomCenter(_box, centers.ptr<float>(k), rng);
}
}
else
{
if( iter == 0 && a == 0 && (flags & KMEANS_USE_INITIAL_LABELS) )
{
for( i = 0; i < N; i++ )
CV_Assert( (unsigned)labels[i] < (unsigned)K );
}
// compute centers
centers = Scalar(0);
for( k = 0; k < K; k++ )
counters[k] = 0;
for( i = 0; i < N; i++ )
{
sample = data.ptr<float>(i);
k = labels[i];
float* center = centers.ptr<float>(k);
j=0;
#if CV_ENABLE_UNROLLED
for(; j <= dims - 4; j += 4 )
{
float t0 = center[j] + sample[j];
float t1 = center[j+1] + sample[j+1];
center[j] = t0;
center[j+1] = t1;
t0 = center[j+2] + sample[j+2];
t1 = center[j+3] + sample[j+3];
center[j+2] = t0;
center[j+3] = t1;
}
#endif
for( ; j < dims; j++ )
center[j] += sample[j];
counters[k]++;
}
if( iter > 0 )
max_center_shift = 0;
for( k = 0; k < K; k++ )
{
if( counters[k] != 0 )
continue;
// if some cluster appeared to be empty then:
// 1. find the biggest cluster
// 2. find the farthest from the center point in the biggest cluster
// 3. exclude the farthest point from the biggest cluster and form a new 1-point cluster.
int max_k = 0;
for( int k1 = 1; k1 < K; k1++ )
{
if( counters[max_k] < counters[k1] )
max_k = k1;
}
double max_dist = 0;
int farthest_i = -1;
float* new_center = centers.ptr<float>(k);
float* old_center = centers.ptr<float>(max_k);
float* _old_center = temp.ptr<float>(); // normalized
float scale = 1.f/counters[max_k];
for( j = 0; j < dims; j++ )
_old_center[j] = old_center[j]*scale;
for( i = 0; i < N; i++ )
{
if( labels[i] != max_k )
continue;
sample = data.ptr<float>(i);
double dist = normL2Sqr_(sample, _old_center, dims);
if( max_dist <= dist )
{
max_dist = dist;
farthest_i = i;
}
}
counters[max_k]--;
counters[k]++;
labels[farthest_i] = k;
sample = data.ptr<float>(farthest_i);
for( j = 0; j < dims; j++ )
{
old_center[j] -= sample[j];
new_center[j] += sample[j];
}
}
for( k = 0; k < K; k++ )
{
float* center = centers.ptr<float>(k);
CV_Assert( counters[k] != 0 );
float scale = 1.f/counters[k];
for( j = 0; j < dims; j++ )
center[j] *= scale;
if( iter > 0 )
{
double dist = 0;
const float* old_center = old_centers.ptr<float>(k);
for( j = 0; j < dims; j++ )
{
double t = center[j] - old_center[j];
dist += t*t;
}
max_center_shift = std::max(max_center_shift, dist);
}
}
}
if( ++iter == MAX(criteria.maxCount, 2) || max_center_shift <= criteria.epsilon )
break;
// assign labels
Mat dists(1, N, CV_64F);
double* dist = dists.ptr<double>(0);
parallel_for_(Range(0, N),
KMeansDistanceComputer(dist, labels, data, centers));
compactness = 0;
for( i = 0; i < N; i++ )
{
compactness += dist[i];
}
}
if( compactness < best_compactness )
{
best_compactness = compactness;
if( _centers.needed() )
centers.copyTo(_centers);
_labels.copyTo(best_labels);
}
}
return best_compactness;
}
|
Reduce variable scope
|
Reduce variable scope
|
C++
|
apache-2.0
|
opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv
|
6cad032375fcf3b4a23d5036b4f4f6b39b5714ed
|
somfyRts/CCodecSomfyRTS.cpp
|
somfyRts/CCodecSomfyRTS.cpp
|
/**
** Class RTS Somfy
**
** @authors nand 17/11/2016
** _ _
** /\ /\___ _ __ ___ ___ /\ /\___ _ __ | |_ _ __ ___ | |
** / /_/ / _ \| '_ ` _ \ / _ \ / //_/ _ \| '_ \| __| '__/ _ \| |
** / __ / (_) | | | | | | __/ / __ \ (_) | | | | |_| | | (_) | |
** \/ /_/ \___/|_| |_| |_|\___| \/ \/\___/|_| |_|\__|_| \___/|_|
**
**/
#include "somfyRTS.h"
using namespace std;
void log(const char *a) {
/** @foo logs */
cout << a << endl;
}
void scheduler_realtime() {
struct sched_param p;
p.__sched_priority = sched_get_priority_max(SCHED_RR);
if (sched_setscheduler(0, SCHED_RR, &p) == -1) {
perror("Failed to switch to realtime scheduler.");
}
}
void scheduler_standard() {
struct sched_param p;
p.__sched_priority = 0;
if (sched_setscheduler(0, SCHED_OTHER, &p) == -1) {
perror("Failed to switch to normal scheduler.");
}
}
int getRollingCode() {
int rcode = 0;
string line;
ifstream rc ("rc.txt");
if (rc.is_open())
{
getline(rc, line);
cout << line << endl;
rcode = stoi(line);
rc.close();
} else {
log("Unable to open file");
}
return (rcode);
}
void storeRollingCode(int rcode) {
string line = to_string(rcode);
ofstream rc ("rc.txt");
if (rc.is_open())
{
rc << line;
rc.close();
} else {
log("Unable to open file");
}
}
/** constructor */
CCodecSomfyRTS::CCodecSomfyRTS()
: _status(k_waiting_synchro)
, _cpt_synchro_hw(0)
, _cpt_bits(0)
, _previous_bit(0)
, _waiting_half_symbol(false) {
for (int i = 0; i < 7; ++i) _payload[i] = 0;
}
/** transmit function that follow RTS */
bool CCodecSomfyRTS::transmit(int8_t cmd, unsigned long rolling_code, int8_t first) {
/** Construction de la trame claire */
int8_t data[7];
data[0] = (int8_t) 0xA7;
data[1] = cmd << 4;
data[2] = (int8_t) ((rolling_code & 0xFF00) >> 8);
data[3] = (int8_t) (rolling_code & 0x00FF);
/** Mettre ici l'adresse de votre TC ou de la TC simulée */
data[4] = (int8_t) 0xAB;
data[5] = (int8_t) 0xCD;
data[6] = (int8_t) 0xEF;
/** Calcul du checksum */
int8_t cksum = 0;
for (int i = 0; i < 7; ++i) cksum = (int8_t) (cksum ^ (data[i] & 0xF) ^ (data[i] >> 4));
data[1] = data[1] | (cksum);
/** Obsufscation */
int8_t datax[7];
datax[0] = data[0];
for (int i = 1; i < 7; ++i) datax[i] = datax[i - 1] ^ data[i];
/** Emission wakeup, synchro hardware et software */
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_wakeup_pulse);
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_wakeup_silence);
for (int i = 0; i < first; ++i) {
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_synchro_hw);
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_synchro_hw);
}
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_synchro_sw);
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_half_symbol);
/** Emission des donnees */
for (int i = 0; i < 56; ++i) {
int8_t bit_to_transmit = (int8_t) (datax[i / 8] >> (7 - i % 8) & 0x01);
if (bit_to_transmit == 0) {
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_half_symbol);
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_half_symbol);
} else {
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_half_symbol);
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_half_symbol);
}
}
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_inter_frame_gap);
}
|
/**
** Class RTS Somfy
**
** @authors nand 17/11/2016
** _ _
** /\ /\___ _ __ ___ ___ /\ /\___ _ __ | |_ _ __ ___ | |
** / /_/ / _ \| '_ ` _ \ / _ \ / //_/ _ \| '_ \| __| '__/ _ \| |
** / __ / (_) | | | | | | __/ / __ \ (_) | | | | |_| | | (_) | |
** \/ /_/ \___/|_| |_| |_|\___| \/ \/\___/|_| |_|\__|_| \___/|_|
**
**/
#include "somfyRTS.h"
using namespace std;
void log(const char *a) {
/** @foo logs */
cout << a << endl;
}
void scheduler_realtime() {
struct sched_param p;
p.__sched_priority = sched_get_priority_max(SCHED_RR);
if (sched_setscheduler(0, SCHED_RR, &p) == -1) {
perror("Failed to switch to realtime scheduler.");
}
}
void scheduler_standard() {
struct sched_param p;
p.__sched_priority = 0;
if (sched_setscheduler(0, SCHED_OTHER, &p) == -1) {
perror("Failed to switch to normal scheduler.");
}
}
int getRollingCode() {
int rcode = 0;
string line;
ifstream rc ("rc.txt");
if (rc.is_open())
{
getline(rc, line);
cout << line << endl;
rcode = std::stoi(line);
rc.close();
} else {
log("Unable to open file");
}
return (rcode);
}
void storeRollingCode(int rcode) {
string line = std::to_string(rcode);
ofstream rc ("rc.txt");
if (rc.is_open())
{
rc << line;
rc.close();
} else {
log("Unable to open file");
}
}
/** constructor */
CCodecSomfyRTS::CCodecSomfyRTS()
: _status(k_waiting_synchro)
, _cpt_synchro_hw(0)
, _cpt_bits(0)
, _previous_bit(0)
, _waiting_half_symbol(false) {
for (int i = 0; i < 7; ++i) _payload[i] = 0;
}
/** transmit function that follow RTS */
bool CCodecSomfyRTS::transmit(int8_t cmd, unsigned long rolling_code, int8_t first) {
/** Construction de la trame claire */
int8_t data[7];
data[0] = (int8_t) 0xA7;
data[1] = cmd << 4;
data[2] = (int8_t) ((rolling_code & 0xFF00) >> 8);
data[3] = (int8_t) (rolling_code & 0x00FF);
/** Mettre ici l'adresse de votre TC ou de la TC simulée */
data[4] = (int8_t) 0xAB;
data[5] = (int8_t) 0xCD;
data[6] = (int8_t) 0xEF;
/** Calcul du checksum */
int8_t cksum = 0;
for (int i = 0; i < 7; ++i) cksum = (int8_t) (cksum ^ (data[i] & 0xF) ^ (data[i] >> 4));
data[1] = data[1] | (cksum);
/** Obsufscation */
int8_t datax[7];
datax[0] = data[0];
for (int i = 1; i < 7; ++i) datax[i] = datax[i - 1] ^ data[i];
/** Emission wakeup, synchro hardware et software */
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_wakeup_pulse);
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_wakeup_silence);
for (int i = 0; i < first; ++i) {
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_synchro_hw);
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_synchro_hw);
}
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_synchro_sw);
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_half_symbol);
/** Emission des donnees */
for (int i = 0; i < 56; ++i) {
int8_t bit_to_transmit = (int8_t) (datax[i / 8] >> (7 - i % 8) & 0x01);
if (bit_to_transmit == 0) {
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_half_symbol);
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_half_symbol);
} else {
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_half_symbol);
digitalWrite(GPIO_SOMFY, 1);
delayMicroseconds(k_tempo_half_symbol);
}
}
digitalWrite(GPIO_SOMFY, 0);
delayMicroseconds(k_tempo_inter_frame_gap);
}
|
debug for raspberry pi
|
debug for raspberry pi
|
C++
|
mit
|
Nandotk/home.kontrol
|
0b7ab7cb2f71b6b7b8ea8fb77886bc9e780cda7e
|
source/crisscross/llist.cpp
|
source/crisscross/llist.cpp
|
/*
* CrissCross
* A multi-purpose cross-platform library.
*
* A product of Uplink Laboratories.
*
* (c) 2006-2010 Steven Noonan.
* Licensed under the New BSD License.
*
*/
#ifndef __included_cc_llist_h
#error "This file shouldn't be compiled directly."
#endif
#include <crisscross/llist.h>
namespace CrissCross
{
namespace Data
{
template <class T> LListNode <T>::LListNode()
{
m_next = NULL;
m_previous = NULL;
}
template <class T> LList <T>::LList()
{
m_first = NULL;
m_last = NULL;
m_numItems = 0;
m_previous = NULL;
m_previousIndex = (size_t)-1;
}
template <class T> LList <T>::~LList()
{
empty();
}
template <class T> LList <T>::LList(const LList <T> &source) : m_first(NULL),
m_last(NULL),
m_previous(NULL),
m_previousIndex(-1),
m_numItems(0)
{
for (size_t i = 0; i < source.size(); i++) {
insert_back(source.GetData(i));
}
}
template <class T>
LList <T> &LList <T>::operator =(const LList <T> &source)
{
empty();
for (size_t i = 0; i < source.size(); i++) {
insert_back(source.getData(i));
}
return *this;
}
template <class T> void LList <T>::change(const T &_rec, size_t _index)
{
LListNode <T> *li = getItem(_index);
li->m_data = _rec;
}
template <class T> void LList <T>::insert(const T & newdata)
{
insert_back(newdata);
}
template <class T> void LList <T>::insert_back(const T & newdata)
{
LListNode <T> *li = new LListNode <T> ();
li->m_data = newdata;
li->m_next = NULL;
li->m_previous = m_last;
++m_numItems;
if (m_last == NULL) {
m_first = li;
m_last = li;
m_previous = li;
m_previousIndex = 0;
} else {
m_last->m_next = li;
m_last = li;
}
}
template <class T> void LList <T>::insert_front(const T & newdata)
{
LListNode <T> *li = new LListNode <T> ();
li->m_data = newdata;
li->m_previous = NULL;
++m_numItems;
if (m_last == NULL) {
li->m_next = NULL;
m_first = li;
m_last = li;
m_previous = li;
m_previousIndex = 0;
} else {
m_first->m_previous = li;
li->m_next = m_first;
m_first = li;
m_previousIndex++;
}
}
template <class T>
void LList <T>::insert_at(const T & newdata, size_t index)
{
if (index == 0) {
insert_front(newdata);
} else if (index == m_numItems) {
insert_back(newdata);
} else {
LListNode <T> *current = m_first;
for (size_t i = 0; i < index - 1; ++i) {
if (!current) {
return;
}
current = current->m_next;
}
if (!current) {
return;
}
LListNode <T> *li = new LListNode <T> ();
li->m_data = newdata;
li->m_previous = current;
li->m_next = current->m_next;
if (current->m_next)
current->m_next->m_previous = li;
current->m_next = li;
++m_numItems;
m_previousIndex = 0;
m_previous = m_first;
}
}
template <class T> size_t LList <T>::size() const
{
return m_numItems;
}
template <class T> T const & LList <T>::get(size_t index, T const &_default) const
{
LListNode <T> const *item = getItem(index);
if (item) {
T const &ret = item->m_data;
return ret;
}
return _default;
}
template <class T> T * LList <T>::getPointer(size_t index) const
{
LListNode <T> *item = getItem(index);
if (item) {
T *ret = &item->m_data;
return ret;
}
return NULL;
}
template <class T> LListNode <T> *LList <T>::getItem(size_t index) const
{
if (!valid(index)) {
return NULL;
}
/* */
/* Choose a place for which to start walking the list */
/* Best place to start is either; m_first, m_previous or m_last */
/* */
/* m_first m_previous m_last */
/* |----------:-----------|---------------------:--------------------| */
/* mid-point 1 mid-point 2 */
/* */
/* If index is less than mid-point 1, then m_first is nearest. */
/* If index is greater than mid-point 2, then m_last is nearest. */
/* Otherwise m_previous is nearest. */
/* The two if statements below test for these conditions. */
if (index <= (m_previousIndex >> 1)) {
m_previous = m_first;
m_previousIndex = 0;
} else if ((size_t)abs((long)index - (long)m_previousIndex) > (m_numItems - index)) {
m_previous = m_last;
m_previousIndex = m_numItems - 1;
}
if (!m_previous) {
m_previous = m_first;
m_previousIndex = 0;
}
while (index > m_previousIndex) {
m_previous = m_previous->m_next;
m_previousIndex++;
}
while (index < m_previousIndex) {
m_previous = m_previous->m_previous;
m_previousIndex--;
}
LListNode<T> *temp = m_previous;
return temp;
}
template <class T> bool LList <T>::valid(size_t index) const
{
return (index < m_numItems);
}
template <class T> void LList <T>::empty()
{
LListNode <T> *current = m_first;
while (current) {
LListNode <T> *m_next = current->m_next;
delete current;
current = m_next;
}
m_first = NULL;
m_last = NULL;
m_numItems = 0;
m_previous = NULL;
m_previousIndex = (size_t)-1;
}
template <class T> void LList <T>::remove(size_t index)
{
LListNode <T> *current = getItem(index);
if (current == NULL) {
return;
}
if (current->m_previous == NULL)
m_first = current->m_next;
else
current->m_previous->m_next = current->m_next;
if (current->m_next == NULL)
m_last = current->m_previous;
else
current->m_next->m_previous = current->m_previous;
if (index == m_previousIndex) {
if (m_numItems == 1) {
m_previousIndex = (size_t)-1;
m_previous = NULL;
} else if (index > 0) {
m_previousIndex--;
m_previous = current->m_previous;
} else {
m_previous = current->m_next;
}
} else if (index < m_previousIndex) {
m_previousIndex--;
}
delete current;
--m_numItems;
}
template <class T>
size_t LList<T>::mem_usage() const
{
LListNode<T> *node = m_first;
size_t ret = sizeof(*this);
while (node) {
ret += sizeof(*node);
node = node->m_next;
}
return ret;
}
template <class T> void LList <T>::sort(CrissCross::Data::Sorter<T> &_sortMethod)
{
sort(&_sortMethod);
}
template <class T> void LList <T>::sort(CrissCross::Data::Sorter<T> *_sortMethod)
{
/*
* The theory here is that doing LList node relinking is both
* painful and costly, as the relinking may be done more than
* one relink on any one node because of the way certain sorts
* work. So it simplifies things by serializing the LList as a
* DArray temporarily and then rebuilding the LList.
*
* Unfortunately this method is still very costly, so if someone
* is doing a LList::sort, they might as well be using a DArray.
*
*/
size_t llistSize = size();
DArray <T> sortArray;
sortArray.setSize(llistSize);
for (size_t i = 0; i < llistSize; i++) {
sortArray.insert(get(i));
}
empty();
sortArray.sort(_sortMethod);
for (size_t i = 0; i < llistSize; i++) {
insert(sortArray.get(i));
}
}
template <class T> T const & LList <T>::operator [](size_t index) const
{
LListNode<T> *item = getItem(index);
return item->m_data;
}
template <class T> T & LList <T>::operator [](size_t index)
{
LListNode<T> *item = getItem(index);
return item->m_data;
}
template <class T> size_t LList <T>::find(const T & data)
{
size_t const lsize = this->size();
if (Compare(get(m_previousIndex), data) == 0)
return m_previousIndex;
for (size_t i = 0; i < lsize; ++i) {
if (Compare(get(i), data) == 0) {
return i;
}
}
return -1;
}
}
}
|
/*
* CrissCross
* A multi-purpose cross-platform library.
*
* A product of Uplink Laboratories.
*
* (c) 2006-2010 Steven Noonan.
* Licensed under the New BSD License.
*
*/
#ifndef __included_cc_llist_h
#error "This file shouldn't be compiled directly."
#endif
#include <crisscross/llist.h>
namespace CrissCross
{
namespace Data
{
template <class T> LListNode <T>::LListNode()
{
m_next = NULL;
m_previous = NULL;
}
template <class T> LList <T>::LList()
{
m_first = NULL;
m_last = NULL;
m_numItems = 0;
m_previous = NULL;
m_previousIndex = (size_t)-1;
}
template <class T> LList <T>::~LList()
{
empty();
}
template <class T> LList <T>::LList(const LList <T> &source) : m_first(NULL),
m_last(NULL),
m_previous(NULL),
m_previousIndex(-1),
m_numItems(0)
{
for (size_t i = 0; i < source.size(); i++) {
insert_back(source.get(i));
}
}
template <class T>
LList <T> &LList <T>::operator =(const LList <T> &source)
{
empty();
for (size_t i = 0; i < source.size(); i++) {
insert_back(source.get(i));
}
return *this;
}
template <class T> void LList <T>::change(const T &_rec, size_t _index)
{
LListNode <T> *li = getItem(_index);
li->m_data = _rec;
}
template <class T> void LList <T>::insert(const T & newdata)
{
insert_back(newdata);
}
template <class T> void LList <T>::insert_back(const T & newdata)
{
LListNode <T> *li = new LListNode <T> ();
li->m_data = newdata;
li->m_next = NULL;
li->m_previous = m_last;
++m_numItems;
if (m_last == NULL) {
m_first = li;
m_last = li;
m_previous = li;
m_previousIndex = 0;
} else {
m_last->m_next = li;
m_last = li;
}
}
template <class T> void LList <T>::insert_front(const T & newdata)
{
LListNode <T> *li = new LListNode <T> ();
li->m_data = newdata;
li->m_previous = NULL;
++m_numItems;
if (m_last == NULL) {
li->m_next = NULL;
m_first = li;
m_last = li;
m_previous = li;
m_previousIndex = 0;
} else {
m_first->m_previous = li;
li->m_next = m_first;
m_first = li;
m_previousIndex++;
}
}
template <class T>
void LList <T>::insert_at(const T & newdata, size_t index)
{
if (index == 0) {
insert_front(newdata);
} else if (index == m_numItems) {
insert_back(newdata);
} else {
LListNode <T> *current = m_first;
for (size_t i = 0; i < index - 1; ++i) {
if (!current) {
return;
}
current = current->m_next;
}
if (!current) {
return;
}
LListNode <T> *li = new LListNode <T> ();
li->m_data = newdata;
li->m_previous = current;
li->m_next = current->m_next;
if (current->m_next)
current->m_next->m_previous = li;
current->m_next = li;
++m_numItems;
m_previousIndex = 0;
m_previous = m_first;
}
}
template <class T> size_t LList <T>::size() const
{
return m_numItems;
}
template <class T> T const & LList <T>::get(size_t index, T const &_default) const
{
LListNode <T> const *item = getItem(index);
if (item) {
T const &ret = item->m_data;
return ret;
}
return _default;
}
template <class T> T * LList <T>::getPointer(size_t index) const
{
LListNode <T> *item = getItem(index);
if (item) {
T *ret = &item->m_data;
return ret;
}
return NULL;
}
template <class T> LListNode <T> *LList <T>::getItem(size_t index) const
{
if (!valid(index)) {
return NULL;
}
/* */
/* Choose a place for which to start walking the list */
/* Best place to start is either; m_first, m_previous or m_last */
/* */
/* m_first m_previous m_last */
/* |----------:-----------|---------------------:--------------------| */
/* mid-point 1 mid-point 2 */
/* */
/* If index is less than mid-point 1, then m_first is nearest. */
/* If index is greater than mid-point 2, then m_last is nearest. */
/* Otherwise m_previous is nearest. */
/* The two if statements below test for these conditions. */
if (index <= (m_previousIndex >> 1)) {
m_previous = m_first;
m_previousIndex = 0;
} else if ((size_t)abs((long)index - (long)m_previousIndex) > (m_numItems - index)) {
m_previous = m_last;
m_previousIndex = m_numItems - 1;
}
if (!m_previous) {
m_previous = m_first;
m_previousIndex = 0;
}
while (index > m_previousIndex) {
m_previous = m_previous->m_next;
m_previousIndex++;
}
while (index < m_previousIndex) {
m_previous = m_previous->m_previous;
m_previousIndex--;
}
LListNode<T> *temp = m_previous;
return temp;
}
template <class T> bool LList <T>::valid(size_t index) const
{
return (index < m_numItems);
}
template <class T> void LList <T>::empty()
{
LListNode <T> *current = m_first;
while (current) {
LListNode <T> *m_next = current->m_next;
delete current;
current = m_next;
}
m_first = NULL;
m_last = NULL;
m_numItems = 0;
m_previous = NULL;
m_previousIndex = (size_t)-1;
}
template <class T> void LList <T>::remove(size_t index)
{
LListNode <T> *current = getItem(index);
if (current == NULL) {
return;
}
if (current->m_previous == NULL)
m_first = current->m_next;
else
current->m_previous->m_next = current->m_next;
if (current->m_next == NULL)
m_last = current->m_previous;
else
current->m_next->m_previous = current->m_previous;
if (index == m_previousIndex) {
if (m_numItems == 1) {
m_previousIndex = (size_t)-1;
m_previous = NULL;
} else if (index > 0) {
m_previousIndex--;
m_previous = current->m_previous;
} else {
m_previous = current->m_next;
}
} else if (index < m_previousIndex) {
m_previousIndex--;
}
delete current;
--m_numItems;
}
template <class T>
size_t LList<T>::mem_usage() const
{
LListNode<T> *node = m_first;
size_t ret = sizeof(*this);
while (node) {
ret += sizeof(*node);
node = node->m_next;
}
return ret;
}
template <class T> void LList <T>::sort(CrissCross::Data::Sorter<T> &_sortMethod)
{
sort(&_sortMethod);
}
template <class T> void LList <T>::sort(CrissCross::Data::Sorter<T> *_sortMethod)
{
/*
* The theory here is that doing LList node relinking is both
* painful and costly, as the relinking may be done more than
* one relink on any one node because of the way certain sorts
* work. So it simplifies things by serializing the LList as a
* DArray temporarily and then rebuilding the LList.
*
* Unfortunately this method is still very costly, so if someone
* is doing a LList::sort, they might as well be using a DArray.
*
*/
size_t llistSize = size();
DArray <T> sortArray;
sortArray.setSize(llistSize);
for (size_t i = 0; i < llistSize; i++) {
sortArray.insert(get(i));
}
empty();
sortArray.sort(_sortMethod);
for (size_t i = 0; i < llistSize; i++) {
insert(sortArray.get(i));
}
}
template <class T> T const & LList <T>::operator [](size_t index) const
{
LListNode<T> *item = getItem(index);
return item->m_data;
}
template <class T> T & LList <T>::operator [](size_t index)
{
LListNode<T> *item = getItem(index);
return item->m_data;
}
template <class T> size_t LList <T>::find(const T & data)
{
size_t const lsize = this->size();
if (Compare(get(m_previousIndex), data) == 0)
return m_previousIndex;
for (size_t i = 0; i < lsize; ++i) {
if (Compare(get(i), data) == 0) {
return i;
}
}
return -1;
}
}
}
|
fix llist copy constructor and assignment operator usage of get()
|
llist.cpp: fix llist copy constructor and assignment operator usage of get()
Signed-off-by: Steven Noonan <[email protected]>
|
C++
|
bsd-3-clause
|
tycho/crisscross,tycho/crisscross,tycho/crisscross
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.