text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "StdAfx.h"
#include <windows.h>
#include <iostream>
#include <osg/MatrixTransform>
#include <osgFX/Scribe>
#include "jrOSGHighlightVisitor.h"
jrOSGHighlightVisitor::jrOSGHighlightVisitor(void) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {
}
jrOSGHighlightVisitor::~jrOSGHighlightVisitor(void) {
}
void jrOSGHighlightVisitor::apply(osg::Node &node) {
if (node.getName().find("ForeArm.Flat") != std::string::npos) {
//std::cout << "highlighting: " << node.getName() << std::endl;
//osgFX::Scribe* scribe = new osgFX::Scribe();
//osg::Group* parent = node.getParent(0);
//
//scribe->setName("highlighted");
//scribe->setWireframeColor(osg::Vec4(0,1,0,0.5));
//scribe->addChild(&node);
//
//parent->replaceChild(&node, scribe);
osg::Group* parent = node.getParent(0);
osg::MatrixTransform* transform = new osg::MatrixTransform;
const double angle = 0.1;
const osg::Vec3d axis(0, 0, 1);
transform->setMatrix(osg::Matrix::rotate(angle, axis));
transform->setName("trans");
transform->addChild(&node);
parent->replaceChild(&node, transform);
}
else if (node.getName().find("highlighted") != std::string::npos) {
std::cout << "removing highlight on: " << node.getName() << std::endl;
osg::Group* parent = node.getParent(0);
osgFX::Scribe* scribe = dynamic_cast<osgFX::Scribe*>(&node);
parent->replaceChild(&node, scribe->getChild(0));
return;
}
traverse(node);
}
<commit_msg>More work on the highlight visitor.<commit_after>#include "StdAfx.h"
#include <windows.h>
#include <iostream>
#include <osg/MatrixTransform>
#include <osgFX/Scribe>
#include "jrOSGHighlightVisitor.h"
jrOSGHighlightVisitor::jrOSGHighlightVisitor(void) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {
}
jrOSGHighlightVisitor::~jrOSGHighlightVisitor(void) {
}
void jrOSGHighlightVisitor::apply(osg::Node &node) {
if (node.getName().find("ForeArm.Flat") != std::string::npos) {
std::cout << "highlighting: " << node.getName() << std::endl;
osgFX::Scribe* scribe = new osgFX::Scribe();
osg::Group* parent = node.getParent(0);
scribe->setName("highlighted");
scribe->setWireframeColor(osg::Vec4(0,1,0,0.5));
scribe->addChild(&node);
parent->replaceChild(&node, scribe);
parent = node.getParent(0);
osg::MatrixTransform* transform = new osg::MatrixTransform;
const double angle = 0.1;
const osg::Vec3d axis(0, 0, 1);
transform->setMatrix(osg::Matrix::rotate(angle, axis));
transform->setName("trans");
transform->addChild(&node);
parent->replaceChild(&node, transform);
}
else if (node.getName().find("highlighted") != std::string::npos) {
std::cout << "removing highlight on: " << node.getName() << std::endl;
osg::Group* parent = node.getParent(0);
osgFX::Scribe* scribe = dynamic_cast<osgFX::Scribe*>(&node);
parent->replaceChild(&node, scribe->getChild(0));
return;
}
traverse(node);
}
<|endoftext|>
|
<commit_before>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @GFile g_file.cpp
* @version
* @brief
* @author duye
* @date 2013-06-20
* @note
*
* 1. 2013-06-20 duye Created this GFile
*
*/
#include <stdarg.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <g_file.h>
namespace gsys {
// default create GFile permissions
static const GUint32 G_FILE_MASK = 0x775;
GResult FileUtil::createFile(const GInt8* filePath)
{
return createFile(filePath, 0);
}
GResult FileUtil::createFile(const GInt8* filePath, const GUint64& initSize)
{
GInt32 fd = ::creat(filePath, G_FILE_MASK);
if (fd == -1)
{
return G_NO;
}
if (ftruncate(fd, initSize) == -1)
{
::close(fd);
return G_NO;
}
::close(fd);
return G_YES;
}
bool FileUtil::isExist(const GInt8* filePath)
{
if (filePath == nullptr)
{
return false;
}
if (access(filePath, 0) < 0)
{
return false;
}
return true;
}
GResult FileUtil::removeFile(const GInt8* filePath)
{
if (filePath == nullptr)
{
return G_NO;
}
GInt8 cmd[128] = {0};
sprintf(cmd, "rm %s -f", filePath);
return System::shell(cmd);
}
File::File() : m_fd(-1), m_flags(0), m_pathLen(0)
{
m_error[0] = 0;
m_path[0] = 0;
}
File::File(const GInt8* filePath) : m_fd(-1), m_flags(0), m_pathLen(0)
{
GUint32 len = strlen(filePath);
if (len < G_PATH_MAX)
{
memcpy(m_path, filePath, len);
m_path[len] = 0;
m_pathLen = len;
}
m_error[0] = 0;
}
File::~File()
{
close();
}
GResult File::open(const FileOpenFlags fileOpenFlags)
{
return open(fileOpenFlags, G_FILE_MASK);
}
GResult File::open(const FileOpenFlags fileOpenFlags, const GInt32 mode)
{
GInt32 openFlags = 0;
if (fileOpenFlags | G_OPEN_READ)
{
openFlags = O_RDONLY;
}
else if (fileOpenFlags | G_OPEN_WRITE)
{
openFlags = O_WRONLY | O_CREAT;
}
else if (fileOpenFlags | G_OPEN_RDWR)
{
openFlags = O_RDWR | O_CREAT;
}
else if (fileOpenFlags | G_OPEN_APPEND)
{
if (openFlags == 0)
{
return G_NO;
}
openFlags |= O_APPEND;
}
if (openFlags == 0)
{
setError("input open mode error");
return G_NO;
}
return orgOpen(openFlags, mode);
}
GResult File::close()
{
if (m_fd < 0)
{
setError("file don't open");
return G_NO;
}
GResult ret = (::close(m_fd) != -1 ? G_YES : G_NO);
m_fd = -1;
m_path[0] = 0;
m_flags = 0;
return ret;
}
GInt64 File::getSize()
{
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
struct stat fileStat;
fstat(m_fd, &fileStat);
return (GInt64)(fileStat.st_size);
}
GInt64 File::seek(const GInt64 offset, const FileSeekFlags& flags)
{
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
GInt32 sysFlags = -1;
switch(flags)
{
case G_SEEK_BEG:
sysFlags = SEEK_SET;
break;
case G_SEEK_CUR:
sysFlags = SEEK_CUR;
break;
case G_SEEK_END:
sysFlags = SEEK_END;
break;
default:
return G_NO;
break;
}
return ::lseek(m_fd, offset, sysFlags);
}
GInt64 File::tell()
{
return seek(0, G_SEEK_CUR);
}
GInt64 File::read(GInt8* buffer, const GUint64 size)
{
if (buffer == NULL || size <= 0)
{
setError("input parameter is error");
return G_NO;
}
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
return ::read(m_fd, buffer, size);
}
GInt64 File::write(const GInt8* data, const GUint64 length)
{
if (data == NULL || length <= 0)
{
setError("input parameter is error");
return G_NO;
}
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
return ::write(m_fd, data, length);
}
GInt8* File::getError()
{
return m_error;
}
GResult File::orgOpen(const GInt32 flags, const GUint32 mode)
{
if (m_fd > 0)
{
setError("file had opened");
return G_NO;
}
if (m_pathLen == 0)
{
setError("hasn't set file path");
return G_NO;
}
m_fd = ::open(m_path, flags, mode);
if (m_fd > 0)
{
m_flags = flags;
}
else
{
setError("open file failed, check whether exist this file path");
}
return (m_fd != -1 ? true : false);
}
void File::setError(const GInt8* args, ...)
{
System::pformat(m_error, G_ERROR_BUF_SIZE, args);
}
<commit_msg>Update g_file.cpp<commit_after>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @GFile g_file.cpp
* @version
* @brief
* @author duye
* @date 2013-06-20
* @note
*
* 1. 2013-06-20 duye Created this GFile
*
*/
#include <stdarg.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <g_file.h>
namespace gsys {
// default create GFile permissions
static const GUint32 G_FILE_MASK = 0x775;
GResult FileUtil::createFile(const GInt8* filePath)
{
return createFile(filePath, 0);
}
GResult FileUtil::createFile(const GInt8* filePath, const GUint64& initSize)
{
GInt32 fd = ::creat(filePath, G_FILE_MASK);
if (fd == -1)
{
return G_NO;
}
if (ftruncate(fd, initSize) == -1)
{
::close(fd);
return G_NO;
}
::close(fd);
return G_YES;
}
bool FileUtil::isExist(const GInt8* filePath)
{
if (filePath == nullptr)
{
return false;
}
if (access(filePath, 0) < 0)
{
return false;
}
return true;
}
GResult FileUtil::removeFile(const GInt8* filePath)
{
if (filePath == nullptr)
{
return G_NO;
}
GInt8 cmd[128] = {0};
sprintf(cmd, "rm %s -f", filePath);
return System::shell(cmd);
}
File::File() : m_fd(-1), m_flags(0), m_pathLen(0)
{
m_error[0] = 0;
m_path[0] = 0;
}
File::File(const GInt8* filePath) : m_fd(-1), m_flags(0), m_pathLen(0)
{
GUint32 len = strlen(filePath);
if (len < G_PATH_MAX)
{
memcpy(m_path, filePath, len);
m_path[len] = 0;
m_pathLen = len;
}
m_error[0] = 0;
}
File::~File()
{
close();
}
GResult File::open(const FileOpenFlags fileOpenFlags)
{
return open(fileOpenFlags, G_FILE_MASK);
}
GResult File::open(const FileOpenFlags fileOpenFlags, const GInt32 mode)
{
GInt32 openFlags = 0;
if (fileOpenFlags | G_OPEN_READ)
{
openFlags = O_RDONLY;
}
else if (fileOpenFlags | G_OPEN_WRITE)
{
openFlags = O_WRONLY | O_CREAT;
}
else if (fileOpenFlags | G_OPEN_RDWR)
{
openFlags = O_RDWR | O_CREAT;
}
else if (fileOpenFlags | G_OPEN_APPEND)
{
if (openFlags == 0)
{
return G_NO;
}
openFlags |= O_APPEND;
}
if (openFlags == 0)
{
setError("input open mode error");
return G_NO;
}
return orgOpen(openFlags, mode);
}
GResult File::close()
{
if (m_fd < 0)
{
setError("file don't open");
return G_NO;
}
GResult ret = (::close(m_fd) != -1 ? G_YES : G_NO);
m_fd = -1;
m_path[0] = 0;
m_flags = 0;
return ret;
}
GInt64 File::getSize()
{
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
struct stat fileStat;
fstat(m_fd, &fileStat);
return (GInt64)(fileStat.st_size);
}
GInt64 File::seek(const GInt64 offset, const FileSeekFlags& flags)
{
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
GInt32 sysFlags = -1;
switch(flags)
{
case G_SEEK_BEG:
sysFlags = SEEK_SET;
break;
case G_SEEK_CUR:
sysFlags = SEEK_CUR;
break;
case G_SEEK_END:
sysFlags = SEEK_END;
break;
default:
return G_NO;
break;
}
return ::lseek(m_fd, offset, sysFlags);
}
GInt64 File::tell()
{
return seek(0, G_SEEK_CUR);
}
GInt64 File::read(GInt8* buffer, const GUint64 size)
{
if (buffer == NULL || size <= 0)
{
setError("input parameter is error");
return G_NO;
}
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
return ::read(m_fd, buffer, size);
}
GInt64 File::write(const GInt8* data, const GUint64 length)
{
if (data == NULL || length <= 0)
{
setError("input parameter is error");
return G_NO;
}
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
return ::write(m_fd, data, length);
}
GInt8* File::getError()
{
return m_error;
}
GResult File::orgOpen(const GInt32 flags, const GUint32 mode)
{
if (m_fd > 0)
{
setError("file had opened");
return G_NO;
}
if (m_pathLen == 0)
{
setError("hasn't set file path");
return G_NO;
}
m_fd = ::open(m_path, flags, mode);
if (m_fd > 0)
{
m_flags = flags;
}
else
{
setError("open file failed, check whether exist this file path");
}
return (m_fd != -1 ? true : false);
}
void File::setError(const GInt8* args, ...)
{
System::pformat(m_error, G_ERROR_BUF_SIZE, args);
}
}
<|endoftext|>
|
<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "TError.h"
#include <TClass.h>
#include <TFileMerger.h>
#include <TCanvas.h>
#include <TH1.h>
#include <TGraph.h>
#include <TObjArray.h>
#include <TObjString.h>
#include <TPython.h>
#include <TString.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TStyle.h>
#include "qaRec/AliTRDrecoTask.h"
#endif
#include "run.h"
Char_t *libs[] = {"libProofPlayer.so", "libANALYSIS.so", "libTRDqaRec.so", "libPyROOT"};
void makeResults(Char_t *tasks = "ALL", Char_t* dir=0x0)
{
// Load Libraries in interactive mode
Int_t nlibs = static_cast<Int_t>(sizeof(libs)/sizeof(Char_t *));
for(Int_t ilib=0; ilib<nlibs; ilib++){
if(gSystem->Load(libs[ilib]) >= 0) continue;
printf("Failed to load %s.\n", libs[ilib]);
return;
}
gStyle->SetOptStat(0);
Bool_t mc = kTRUE;
Bool_t friends = kTRUE;
// select tasks to process; we should move it to an
// individual function and move the task identifiers
// outside the const space
TObjArray *tasksArray = TString(tasks).Tokenize(" ");
Int_t fSteerTask = 0;
for(Int_t isel = 0; isel < tasksArray->GetEntriesFast(); isel++){
TString s = (dynamic_cast<TObjString *>(tasksArray->UncheckedAt(isel)))->String();
if(s.CompareTo("ALL") == 0){
for(Int_t itask = 1; itask < fknTasks; itask++) SETBIT(fSteerTask, itask);
continue;
} else if(s.CompareTo("NOFR") == 0){
friends = kFALSE;
} else if(s.CompareTo("NOMC") == 0){
mc = kFALSE;
} else {
Bool_t foundOpt = kFALSE;
for(Int_t itask = 1; itask < fknTasks; itask++){
if(s.CompareTo(fTaskOpt[itask]) != 0) continue;
SETBIT(fSteerTask, itask);
foundOpt = kTRUE;
break;
}
if(!foundOpt) Info("makeResults.C", Form("Task %s not implemented (yet).", s.Data()));
}
}
// catch the list of files using the ROOT Python Interface
TPython *pyshell = new TPython();
pyshell->Exec("import commands");
// file merger object
TFileMerger *fFM = new TFileMerger();
TClass *ctask = 0x0;
TObject *o = 0x0;
TObjArray *fContainer = 0x0;
AliTRDrecoTask *task = 0x0;
if(gSystem->AccessPathName(Form("%s/merge", gSystem->ExpandPathName("$PWD")))) gSystem->Exec(Form("mkdir -v %s/merge", gSystem->ExpandPathName("$PWD")));
printf("\n\tPROCESSING DATA FOR TASKS [%b]:\n", fSteerTask);
for(Int_t itask = 1; itask <fknTasks; itask++){
if(!TESTBIT(fSteerTask, itask)) continue;
ctask = new TClass(fTaskClass[itask]);
task = (AliTRDrecoTask*)ctask->New();
task->SetDebugLevel(0);
task->SetMCdata(mc);
task->SetFriends(friends);
printf("\t%s [%s]\n", task->GetTitle(), task->GetName());
// setup filelist
TString pathname = gSystem->ExpandPathName( dir ? dir : "$PWD");
TString filestring((const Char_t*) pyshell->Eval(Form("commands.getstatusoutput(\"find %s | grep TRD.Task%s.root\")[1]", pathname.Data(), task->GetName())));
TObjArray *filenames = filestring.Tokenize("\n");
Int_t nFiles = filenames->GetEntriesFast();
if(!nFiles){
printf("No Files found for Task %s\n", task->GetName());
delete task;
delete ctask;
continue;
}
if(nFiles>1){
fFM = new(fFM) TFileMerger(kTRUE);
fFM->OutputFile(Form("%s/merge/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName()));
for(Int_t ifile = 0; ifile < nFiles; ifile++){
TString filename = (dynamic_cast<TObjString *>(filenames->UncheckedAt(ifile)))->String();
if(filename.Contains("merge")) continue;
//printf("\tProcessing %s ...\n", filename.Data());
fFM->AddFile(filename.Data());
}
fFM->Merge();
fFM->~TFileMerger();
task->Load(Form("%s/merge/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName()));
} else task->Load((dynamic_cast<TObjString *>(filenames->UncheckedAt(0)))->String().Data());
if(!(fContainer = task->Container())) {
delete task;
delete ctask;
continue;
}
task->PostProcess();
for(Int_t ipic=0; ipic<task->GetNRefFigures(); ipic++){
TCanvas *c = new TCanvas("c", "", 500, 500);
Int_t ifirst, ilast; Option_t *opt;
TH1 *h = 0x0; TGraph *g = 0x0;
task->GetRefFigure(ipic, ifirst, ilast, opt);
if(!(o = fContainer->At(ifirst))) continue;
if(o->InheritsFrom("TH1")){
h = dynamic_cast<TH1*>(o);
h->Draw(opt);
} else if(o->InheritsFrom("TGraph")){
g = dynamic_cast<TGraph*>(o);
g->Draw(opt);
} else{
printf("No idea how to plot object of type %s.\n", o->IsA()->GetName());
printf("Please teach me.\n");
continue;
}
for(Int_t ig=ifirst+1; ig<ilast; ig++){
if(!(o = fContainer->At(ig))) continue;
if(o->InheritsFrom("TH1")){
h = dynamic_cast<TH1*>(o);
h->Draw(Form("%ssame", opt));
} else if(o->InheritsFrom("TGraph")){
g = dynamic_cast<TGraph*>(o);
g->Draw(opt);
}
}
c->SaveAs(Form("%s_fig%d.gif", task->GetName(), ipic));
delete c;
}
delete task;
delete ctask;
}
delete pyshell;
}
<commit_msg>small fix for drawing superimposed graphs<commit_after>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "TError.h"
#include <TClass.h>
#include <TFileMerger.h>
#include <TCanvas.h>
#include <TH1.h>
#include <TGraph.h>
#include <TObjArray.h>
#include <TObjString.h>
#include <TPython.h>
#include <TString.h>
#include <TROOT.h>
#include <TSystem.h>
#include <TStyle.h>
#include "qaRec/AliTRDrecoTask.h"
#endif
#include "run.h"
Char_t *libs[] = {"libProofPlayer.so", "libANALYSIS.so", "libTRDqaRec.so", "libPyROOT"};
void makeResults(Char_t *tasks = "ALL", Char_t* dir=0x0)
{
// Load Libraries in interactive mode
Int_t nlibs = static_cast<Int_t>(sizeof(libs)/sizeof(Char_t *));
for(Int_t ilib=0; ilib<nlibs; ilib++){
if(gSystem->Load(libs[ilib]) >= 0) continue;
printf("Failed to load %s.\n", libs[ilib]);
return;
}
gStyle->SetOptStat(0);
Bool_t mc = kTRUE;
Bool_t friends = kTRUE;
// select tasks to process; we should move it to an
// individual function and move the task identifiers
// outside the const space
TObjArray *tasksArray = TString(tasks).Tokenize(" ");
Int_t fSteerTask = 0;
for(Int_t isel = 0; isel < tasksArray->GetEntriesFast(); isel++){
TString s = (dynamic_cast<TObjString *>(tasksArray->UncheckedAt(isel)))->String();
if(s.CompareTo("ALL") == 0){
for(Int_t itask = 1; itask < fknTasks; itask++) SETBIT(fSteerTask, itask);
continue;
} else if(s.CompareTo("NOFR") == 0){
friends = kFALSE;
} else if(s.CompareTo("NOMC") == 0){
mc = kFALSE;
} else {
Bool_t foundOpt = kFALSE;
for(Int_t itask = 1; itask < fknTasks; itask++){
if(s.CompareTo(fTaskOpt[itask]) != 0) continue;
SETBIT(fSteerTask, itask);
foundOpt = kTRUE;
break;
}
if(!foundOpt) Info("makeResults.C", Form("Task %s not implemented (yet).", s.Data()));
}
}
// catch the list of files using the ROOT Python Interface
TPython *pyshell = new TPython();
pyshell->Exec("import commands");
// file merger object
TFileMerger *fFM = new TFileMerger();
TClass *ctask = 0x0;
TObject *o = 0x0;
TObjArray *fContainer = 0x0;
AliTRDrecoTask *task = 0x0;
if(gSystem->AccessPathName(Form("%s/merge", gSystem->ExpandPathName("$PWD")))) gSystem->Exec(Form("mkdir -v %s/merge", gSystem->ExpandPathName("$PWD")));
printf("\n\tPROCESSING DATA FOR TASKS [%b]:\n", fSteerTask);
for(Int_t itask = 1; itask <fknTasks; itask++){
if(!TESTBIT(fSteerTask, itask)) continue;
ctask = new TClass(fTaskClass[itask]);
task = (AliTRDrecoTask*)ctask->New();
task->SetDebugLevel(0);
task->SetMCdata(mc);
task->SetFriends(friends);
printf("\t%s [%s]\n", task->GetTitle(), task->GetName());
// setup filelist
TString pathname = gSystem->ExpandPathName( dir ? dir : "$PWD");
TString filestring((const Char_t*) pyshell->Eval(Form("commands.getstatusoutput(\"find %s | grep TRD.Task%s.root\")[1]", pathname.Data(), task->GetName())));
TObjArray *filenames = filestring.Tokenize("\n");
Int_t nFiles = filenames->GetEntriesFast();
if(!nFiles){
printf("No Files found for Task %s\n", task->GetName());
delete task;
delete ctask;
continue;
}
if(nFiles>1){
fFM = new(fFM) TFileMerger(kTRUE);
fFM->OutputFile(Form("%s/merge/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName()));
for(Int_t ifile = 0; ifile < nFiles; ifile++){
TString filename = (dynamic_cast<TObjString *>(filenames->UncheckedAt(ifile)))->String();
if(filename.Contains("merge")) continue;
//printf("\tProcessing %s ...\n", filename.Data());
fFM->AddFile(filename.Data());
}
fFM->Merge();
fFM->~TFileMerger();
task->Load(Form("%s/merge/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName()));
} else task->Load((dynamic_cast<TObjString *>(filenames->UncheckedAt(0)))->String().Data());
if(!(fContainer = task->Container())) {
delete task;
delete ctask;
continue;
}
task->PostProcess();
for(Int_t ipic=0; ipic<task->GetNRefFigures(); ipic++){
TCanvas *c = new TCanvas("c", "", 500, 500);
Int_t ifirst, ilast; Option_t *opt;
TH1 *h = 0x0; TGraph *g = 0x0;
task->GetRefFigure(ipic, ifirst, ilast, opt);
if(!(o = fContainer->At(ifirst))) continue;
if(o->InheritsFrom("TH1")){
h = dynamic_cast<TH1*>(o);
h->Draw(opt);
} else if(o->InheritsFrom("TGraph")){
g = dynamic_cast<TGraph*>(o);
g->Draw(Form("a%s", opt));
} else{
printf("No idea how to plot object of type %s.\n", o->IsA()->GetName());
printf("Please teach me.\n");
continue;
}
for(Int_t ig=ifirst+1; ig<ilast; ig++){
if(!(o = fContainer->At(ig))) continue;
if(o->InheritsFrom("TH1")){
h = dynamic_cast<TH1*>(o);
h->Draw(Form("%ssame", opt));
} else if(o->InheritsFrom("TGraph")){
g = dynamic_cast<TGraph*>(o);
g->Draw(opt);
}
}
c->SaveAs(Form("%s_fig%d.gif", task->GetName(), ipic));
delete c;
}
delete task;
delete ctask;
}
delete pyshell;
}
<|endoftext|>
|
<commit_before>/**
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 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.
*/
/**
* @file tgHillyGround.cpp
* @brief Contains the implementation of class tgHillyGround
* @author Steven Lessard
* $Id$
*/
//This Module
#include "tgHillyGround.h"
//Bullet Physics
#include "BulletCollision/CollisionShapes/btBoxShape.h"
#include "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h"
#include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "LinearMath/btDefaultMotionState.h"
#include "LinearMath/btTransform.h"
// The C++ Standard Library
#include <cassert>
#include <iostream> //For debugging
tgHillyGround::Config::Config(btVector3 eulerAngles,
btScalar friction,
btScalar restitution,
btVector3 size,
btVector3 origin,
size_t nx,
size_t ny,
double margin,
double triangleSize,
double waveHeight,
double offset) :
m_eulerAngles(eulerAngles),
m_friction(friction),
m_restitution(restitution),
m_size(size),
m_origin(origin),
m_nx(nx),
m_ny(ny),
m_margin(margin),
m_triangleSize(triangleSize),
m_waveHeight(waveHeight),
m_offset(offset)
{
assert((m_friction >= 0.0) && (m_friction <= 1.0));
assert((m_restitution >= 0.0) && (m_restitution <= 1.0));
assert((m_size[0] >= 0.0) && (m_size[1] >= 0.0) && (m_size[2] >= 0.0));
assert(m_nx > 0);
assert(m_ny > 0);
assert(m_margin >= 0.0);
assert(m_triangleSize >= 0.0);
assert(m_waveHeight >= 0.0);
assert(m_offset >= 0.0);
}
tgHillyGround::tgHillyGround() :
m_config(Config())
{
// @todo make constructor aux to avoid repeated code
pGroundShape = hillyCollisionShape();
}
tgHillyGround::tgHillyGround(const tgHillyGround::Config& config) :
m_config(config)
{
pGroundShape = hillyCollisionShape();
}
btRigidBody* tgHillyGround::getGroundRigidBody() const
{
const btScalar mass = 0.0;
btTransform groundTransform;
groundTransform.setIdentity();
groundTransform.setOrigin(m_config.m_origin);
btQuaternion orientation;
orientation.setEuler(m_config.m_eulerAngles[0], // Yaw
m_config.m_eulerAngles[1], // Pitch
m_config.m_eulerAngles[2]); // Roll
groundTransform.setRotation(orientation);
// Using motionstate is recommended
// It provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* const pMotionState =
new btDefaultMotionState(groundTransform);
const btVector3 localInertia(0, 0, 0);
btRigidBody::btRigidBodyConstructionInfo const rbInfo(mass, pMotionState, pGroundShape, localInertia);
btRigidBody* const pGroundBody = new btRigidBody(rbInfo);
assert(pGroundBody);
return pGroundBody;
}
btCollisionShape* tgHillyGround::hillyCollisionShape() {
btCollisionShape * pShape = 0;
// The number of vertices in the mesh
// Hill Paramenters: Subject to Change
const size_t vertexCount = m_config.m_nx * m_config.m_ny;
std::cout << "vertexCount: " << vertexCount << std::endl;
std::cout << "In hillyCollisionShape()" << std::endl;
if (vertexCount > 0) {
// The number of triangles in the mesh
const size_t triangleCount = 2 * (m_config.m_nx - 1) * (m_config.m_ny - 1);
std::cout << "triangleCount: " << triangleCount << std::endl;
// A flattened array of all vertices in the mesh
btVector3 * const vertices = new btVector3[vertexCount];
// Supplied by the derived class
setVertices(vertices);
// A flattened array of indices for each corner of each triangle
int *indices = new int[triangleCount * 3];
// Supplied by the derived class
setIndices(indices);
// Create the mesh object
btTriangleIndexVertexArray* const pMesh =
createMesh(triangleCount, indices, vertexCount, vertices);
// Create the shape object
pShape = createShape(pMesh);
// Set the margin
pShape->setMargin(m_config.m_margin);
// DO NOT deallocate vertices, indices or pMesh! The shape owns them.
}
assert(pShape);
return pShape;
}
btTriangleIndexVertexArray *tgHillyGround::createMesh(size_t triangleCount, int indices[], size_t vertexCount, btVector3 vertices[]) {
const int vertexStride = sizeof(btVector3);
const int indexStride = 3 * sizeof(int);
btTriangleIndexVertexArray* const pMesh =
new btTriangleIndexVertexArray(triangleCount,
indices,
indexStride,
vertexCount,
(btScalar*) &vertices[0].x(),
vertexStride);
return pMesh;
}
btCollisionShape *tgHillyGround::createShape(btTriangleIndexVertexArray *pMesh) {
const bool useQuantizedAabbCompression = true;
btCollisionShape *const pShape =
new btBvhTriangleMeshShape(pMesh, useQuantizedAabbCompression);
return pShape;
}
void tgHillyGround::setVertices(btVector3 vertices[]) {
for (size_t i = 0; i < m_config.m_nx; i++)
{
for (size_t j = 0; j < m_config.m_ny; j++)
{
const btScalar x = (i - (m_config.m_nx * 0.5)) * m_config.m_triangleSize;
const btScalar y = (m_config.m_waveHeight * sinf((float)i) * cosf((float)j) +
m_config.m_offset);
const btScalar z = (j - (m_config.m_ny * 0.5)) * m_config.m_triangleSize;
vertices[i + (j * m_config.m_nx)].setValue(x, y, z);
}
}
}
void tgHillyGround::setIndices(int indices[]) {
int index = 0;
for (int i = 0; i < m_config.m_nx - 1; i++)
{
for (int j = 0; j < m_config.m_ny - 1; j++)
{
indices[index++] = (j * m_config.m_nx) + i;
indices[index++] = (j * m_config.m_nx) + i + 1;
indices[index++] = ((j + 1) * m_config.m_nx) + i + 1;
indices[index++] = (j * m_config.m_nx) + i;
indices[index++] = ((j + 1) * m_config.m_nx) + i + 1;
indices[index++] = ((j + 1) * m_config.m_nx) + i;
}
}
}
<commit_msg>Removed debugging print statements<commit_after>/**
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 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.
*/
/**
* @file tgHillyGround.cpp
* @brief Contains the implementation of class tgHillyGround
* @author Steven Lessard
* $Id$
*/
//This Module
#include "tgHillyGround.h"
//Bullet Physics
#include "BulletCollision/CollisionShapes/btBoxShape.h"
#include "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h"
#include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "LinearMath/btDefaultMotionState.h"
#include "LinearMath/btTransform.h"
// The C++ Standard Library
#include <cassert>
tgHillyGround::Config::Config(btVector3 eulerAngles,
btScalar friction,
btScalar restitution,
btVector3 size,
btVector3 origin,
size_t nx,
size_t ny,
double margin,
double triangleSize,
double waveHeight,
double offset) :
m_eulerAngles(eulerAngles),
m_friction(friction),
m_restitution(restitution),
m_size(size),
m_origin(origin),
m_nx(nx),
m_ny(ny),
m_margin(margin),
m_triangleSize(triangleSize),
m_waveHeight(waveHeight),
m_offset(offset)
{
assert((m_friction >= 0.0) && (m_friction <= 1.0));
assert((m_restitution >= 0.0) && (m_restitution <= 1.0));
assert((m_size[0] >= 0.0) && (m_size[1] >= 0.0) && (m_size[2] >= 0.0));
assert(m_nx > 0);
assert(m_ny > 0);
assert(m_margin >= 0.0);
assert(m_triangleSize >= 0.0);
assert(m_waveHeight >= 0.0);
assert(m_offset >= 0.0);
}
tgHillyGround::tgHillyGround() :
m_config(Config())
{
// @todo make constructor aux to avoid repeated code
pGroundShape = hillyCollisionShape();
}
tgHillyGround::tgHillyGround(const tgHillyGround::Config& config) :
m_config(config)
{
pGroundShape = hillyCollisionShape();
}
btRigidBody* tgHillyGround::getGroundRigidBody() const
{
const btScalar mass = 0.0;
btTransform groundTransform;
groundTransform.setIdentity();
groundTransform.setOrigin(m_config.m_origin);
btQuaternion orientation;
orientation.setEuler(m_config.m_eulerAngles[0], // Yaw
m_config.m_eulerAngles[1], // Pitch
m_config.m_eulerAngles[2]); // Roll
groundTransform.setRotation(orientation);
// Using motionstate is recommended
// It provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* const pMotionState =
new btDefaultMotionState(groundTransform);
const btVector3 localInertia(0, 0, 0);
btRigidBody::btRigidBodyConstructionInfo const rbInfo(mass, pMotionState, pGroundShape, localInertia);
btRigidBody* const pGroundBody = new btRigidBody(rbInfo);
assert(pGroundBody);
return pGroundBody;
}
btCollisionShape* tgHillyGround::hillyCollisionShape() {
btCollisionShape * pShape = 0;
// The number of vertices in the mesh
// Hill Paramenters: Subject to Change
const size_t vertexCount = m_config.m_nx * m_config.m_ny;
if (vertexCount > 0) {
// The number of triangles in the mesh
const size_t triangleCount = 2 * (m_config.m_nx - 1) * (m_config.m_ny - 1);
// A flattened array of all vertices in the mesh
btVector3 * const vertices = new btVector3[vertexCount];
// Supplied by the derived class
setVertices(vertices);
// A flattened array of indices for each corner of each triangle
int *indices = new int[triangleCount * 3];
// Supplied by the derived class
setIndices(indices);
// Create the mesh object
btTriangleIndexVertexArray* const pMesh =
createMesh(triangleCount, indices, vertexCount, vertices);
// Create the shape object
pShape = createShape(pMesh);
// Set the margin
pShape->setMargin(m_config.m_margin);
// DO NOT deallocate vertices, indices or pMesh! The shape owns them.
}
assert(pShape);
return pShape;
}
btTriangleIndexVertexArray *tgHillyGround::createMesh(size_t triangleCount, int indices[], size_t vertexCount, btVector3 vertices[]) {
const int vertexStride = sizeof(btVector3);
const int indexStride = 3 * sizeof(int);
btTriangleIndexVertexArray* const pMesh =
new btTriangleIndexVertexArray(triangleCount,
indices,
indexStride,
vertexCount,
(btScalar*) &vertices[0].x(),
vertexStride);
return pMesh;
}
btCollisionShape *tgHillyGround::createShape(btTriangleIndexVertexArray *pMesh) {
const bool useQuantizedAabbCompression = true;
btCollisionShape *const pShape =
new btBvhTriangleMeshShape(pMesh, useQuantizedAabbCompression);
return pShape;
}
void tgHillyGround::setVertices(btVector3 vertices[]) {
for (size_t i = 0; i < m_config.m_nx; i++)
{
for (size_t j = 0; j < m_config.m_ny; j++)
{
const btScalar x = (i - (m_config.m_nx * 0.5)) * m_config.m_triangleSize;
const btScalar y = (m_config.m_waveHeight * sinf((float)i) * cosf((float)j) +
m_config.m_offset);
const btScalar z = (j - (m_config.m_ny * 0.5)) * m_config.m_triangleSize;
vertices[i + (j * m_config.m_nx)].setValue(x, y, z);
}
}
}
void tgHillyGround::setIndices(int indices[]) {
int index = 0;
for (int i = 0; i < m_config.m_nx - 1; i++)
{
for (int j = 0; j < m_config.m_ny - 1; j++)
{
indices[index++] = (j * m_config.m_nx) + i;
indices[index++] = (j * m_config.m_nx) + i + 1;
indices[index++] = ((j + 1) * m_config.m_nx) + i + 1;
indices[index++] = (j * m_config.m_nx) + i;
indices[index++] = ((j + 1) * m_config.m_nx) + i + 1;
indices[index++] = ((j + 1) * m_config.m_nx) + i;
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>these 9 scripts are in icu >= 4.8, but not in 4.6.1<commit_after><|endoftext|>
|
<commit_before>//
// Electron.cpp
// Clock Signal
//
// Created by Thomas Harte on 03/01/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "Electron.hpp"
#include <algorithm>
using namespace Electron;
Machine::Machine()
{
setup6502();
}
Machine::~Machine()
{
}
unsigned int Machine::perform_bus_operation(CPU6502::BusOperation operation, uint16_t address, uint8_t *value)
{
printf("%04x\n", address);
if(address < 32768)
{
if(isReadOperation(operation))
{
*value = ram[address];
}
else
{
ram[address] = *value;
}
}
else
{
if(address > 49152)
{
if(isReadOperation(operation)) *value = os[address - 49152];
}
else
{
if(isReadOperation(operation)) *value = basic[address - 32768];
}
}
return 1;
}
void Machine::set_rom(ROMSlot slot, size_t length, const uint8_t *data)
{
uint8_t *target = nullptr;
switch(slot)
{
case ROMTypeBASIC: target = basic; break;
case ROMTypeOS: target = os; break;
}
memcpy(target, data, std::min((size_t)16384, length));
}
<commit_msg>This is the bare minimum to prove that the ROM is trying properly to boot.<commit_after>//
// Electron.cpp
// Clock Signal
//
// Created by Thomas Harte on 03/01/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "Electron.hpp"
#include <algorithm>
using namespace Electron;
Machine::Machine()
{
setup6502();
}
Machine::~Machine()
{
}
unsigned int Machine::perform_bus_operation(CPU6502::BusOperation operation, uint16_t address, uint8_t *value)
{
if(address < 32768)
{
if(isReadOperation(operation))
{
*value = ram[address];
}
else
{
ram[address] = *value;
}
}
else
{
if(address > 49152)
{
if((address & 0xff00) == 0xfe00)
{
printf("%c: %02x: ", isReadOperation(operation) ? 'r' : 'w', *value);
switch(address&0xf)
{
case 0x0:
printf("Interrupt status or control\n");
break;
case 0x1:
break;
case 0x2:
case 0x3:
printf("Screen start address\n");
break;
case 0x4:
printf("Cassette\n");
break;
case 0x5:
printf("Interrupt clear and paging\n");
break;
case 0x6:
printf("Counter\n");
break;
case 0x7:
printf("Misc. control\n");
break;
default:
printf("Palette\n");
break;
}
}
else
{
if(isReadOperation(operation))
*value = os[address - 49152];
}
}
else
{
if(isReadOperation(operation)) *value = basic[address - 32768];
}
}
return 1;
}
void Machine::set_rom(ROMSlot slot, size_t length, const uint8_t *data)
{
uint8_t *target = nullptr;
switch(slot)
{
case ROMTypeBASIC: target = basic; break;
case ROMTypeOS: target = os; break;
}
memcpy(target, data, std::min((size_t)16384, length));
}
<|endoftext|>
|
<commit_before>/********************************************************************
* Copyright © 2016 Computational Molecular Biology Group, *
* Freie Universität Berlin (GER) *
* *
* This file is part of ReaDDy. *
* *
* ReaDDy is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General *
* Public License along with this program. If not, see *
* <http://www.gnu.org/licenses/>. *
********************************************************************/
/**
* << detailed description >>
*
* @file ParticleTypeRegistry.cpp
* @brief << brief description >>
* @author clonker
* @date 29.03.17
* @copyright GNU Lesser General Public License v3.0
*/
#include <readdy/model/ParticleTypeRegistry.h>
#include <readdy/model/Utils.h>
namespace readdy {
namespace model {
ParticleTypeInfo::ParticleTypeInfo(const std::string &name, const scalar diffusionConstant,
const particle_flavor flavor, const Particle::type_type typeId)
: name(name), diffusionConstant(diffusionConstant), flavor(flavor), typeId(typeId) {}
void ParticleTypeRegistry::add(const std::string &name, const scalar diffusionConst, const particle_flavor flavor) {
util::validateTypeName(name);
{
if(diffusionConst < 0) {
throw std::invalid_argument("The diffusion constant must not be negative");
}
// check if name already exists
for(const auto &e : particle_info_) {
if(e.second.name == name) {
throw std::invalid_argument(fmt::format("A particle type with name {} already exists.", name));
}
}
}
particle_type_type t_id = type_counter_++;
type_mapping_.emplace(name, t_id);
particle_info_.emplace(std::make_pair(t_id, ParticleTypeInfo{name, diffusionConst, flavor, t_id}));
n_types_++;
}
std::string ParticleTypeRegistry::describe() const {
namespace rus = readdy::util::str;
std::string description;
description += fmt::format(" - particle types:{}", rus::newline);
auto flavorName = [](auto flavor) -> std::string {
switch (flavor) {
case particleflavor::NORMAL: {
return "";
}
case particleflavor::TOPOLOGY: {
return "Topology";
}
case particleflavor::MEMBRANE: {
return "Membrane";
}
default: {
throw std::logic_error("encountered a particle flavor that was neither of NORMAL, TOPOLOGY, MEMBRANE.");
}
}
};
for (const auto &entry : particle_info_) {
description += fmt::format(" * {} particle type \"{}\" with D={}{}", entry.second.name,
flavorName(entry.second.flavor), entry.second.diffusionConstant, rus::newline);
}
return description;
}
}
}
<commit_msg>prettified particle type registry output<commit_after>/********************************************************************
* Copyright © 2016 Computational Molecular Biology Group, *
* Freie Universität Berlin (GER) *
* *
* This file is part of ReaDDy. *
* *
* ReaDDy is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General *
* Public License along with this program. If not, see *
* <http://www.gnu.org/licenses/>. *
********************************************************************/
/**
* << detailed description >>
*
* @file ParticleTypeRegistry.cpp
* @brief << brief description >>
* @author clonker
* @date 29.03.17
* @copyright GNU Lesser General Public License v3.0
*/
#include <readdy/model/ParticleTypeRegistry.h>
#include <readdy/model/Utils.h>
namespace readdy {
namespace model {
ParticleTypeInfo::ParticleTypeInfo(const std::string &name, const scalar diffusionConstant,
const particle_flavor flavor, const Particle::type_type typeId)
: name(name), diffusionConstant(diffusionConstant), flavor(flavor), typeId(typeId) {}
void ParticleTypeRegistry::add(const std::string &name, const scalar diffusionConst, const particle_flavor flavor) {
util::validateTypeName(name);
{
if(diffusionConst < 0) {
throw std::invalid_argument("The diffusion constant must not be negative");
}
// check if name already exists
for(const auto &e : particle_info_) {
if(e.second.name == name) {
throw std::invalid_argument(fmt::format("A particle type with name {} already exists.", name));
}
}
}
particle_type_type t_id = type_counter_++;
type_mapping_.emplace(name, t_id);
particle_info_.emplace(std::make_pair(t_id, ParticleTypeInfo{name, diffusionConst, flavor, t_id}));
n_types_++;
}
std::string ParticleTypeRegistry::describe() const {
namespace rus = readdy::util::str;
std::string description;
description += fmt::format(" - particle types:{}", rus::newline);
auto flavorName = [](auto flavor) -> std::string {
switch (flavor) {
case particleflavor::NORMAL: {
return "";
}
case particleflavor::TOPOLOGY: {
return "Topology";
}
case particleflavor::MEMBRANE: {
return "Membrane";
}
default: {
throw std::logic_error("encountered a particle flavor that was neither of NORMAL, TOPOLOGY, MEMBRANE.");
}
}
};
for (const auto &entry : particle_info_) {
description += fmt::format(" * {} particle type \"{}\" with D={}{}", flavorName(entry.second.flavor),
entry.second.name, entry.second.diffusionConstant, rus::newline);
}
return description;
}
}
}
<|endoftext|>
|
<commit_before>#include <Cosa/Alarm.hh>
#include <Cosa/IOBuffer.hh>
#include <Cosa/RTT.hh>
#include <Cosa/Trace.hh>
#include <Cosa/UART.hh>
#include <Cosa/Soft/UART.hh>
#include <Cosa/Watchdog.hh>
#include <stdint-gcc.h>
#include "initializer_list"
static const uint16_t WATCHDOG_PERIOD = 16;
static const uint32_t SEND_PERIOD_SECS = 60;
static const uint32_t CAM_REPLY_TIMEOUT_SECS = 2;
static const size_t CAM_RX_BUFFER_MAX = 64;
static const size_t CAM_TX_BUFFER_MAX = 16;
static const size_t CAM_RECV_BUFFER_SIZE = 16;
static const size_t CAM_PICT_BUFFER_SIZE = 32;
static const Board::DigitalPin CAM_TX_PIN = Board::D2;
static const Board::InterruptPin CAM_RX_PIN = Board::PCI3;
static uint8_t HI(uint16_t in)
{
return (in >> 8);
}
static uint8_t LO(uint16_t in)
{
return (in & 0xFF);
}
static uint16_t SWAP(uint16_t in)
{
return (LO(in) << 8) | HI(in);
}
class Camera
{
public:
enum class Resolution
{
RES_640x480,
RES_320x240,
RES_160x120,
};
enum class BaudRate
{
BAUD_9600,
BAUD_19200,
BAUD_38400,
BAUD_57600,
BAUD_115200
};
Camera(IOStream& cam, uint32_t timeout)
:_timeout(timeout * 1000), _cam(cam)
{
delay(3000);
_trace(true);
}
void reset()
{
// trace << "reset" << endl;
_send({0x56, 0x00, 0x26, 0x00});
_receive({0x76, 0x00, 0x26, 0x00, 0x00});
//FIXME reset generates the power on init string: we should wait until it is received then!
delay(3000);
// _trace(true);
}
//TODO method to take picture and notify callback for content
template<typename CB>
void take_picture(CB& callback)
{
take_picture();
int32_t size = picture_size();
uint16_t address = 0;
while (size > 0)
{
//TODO buffer should be an argument to the function (more customizable)
uint8_t buffer[CAM_PICT_BUFFER_SIZE];
picture_content(address, CAM_PICT_BUFFER_SIZE, buffer);
address += CAM_PICT_BUFFER_SIZE;
size -= CAM_PICT_BUFFER_SIZE;
callback(buffer, CAM_PICT_BUFFER_SIZE, (size > 0));
}
stop_picture();
}
void take_picture()
{
// trace << "take_picture" << endl;
_send({0x56, 0x00, 0x36, 0x01, 0x00});
_receive({0x76, 0x00, 0x36, 0x00, 0x00});
}
void stop_picture()
{
// trace << "stop_picture" << endl;
_send({0x56, 0x00, 0x36, 0x01, 0x03});
_receive({0x76, 0x00, 0x36, 0x00, 0x00});
}
uint16_t picture_size()
{
// trace << "get picture_size" << endl;
_send({0x56, 0x00, 0x34, 0x01, 0x00});
uint16_t size;
if ( _receive({0x76, 0x00, 0x34, 0x00, 0x04, 0x00, 0x00})
&& _receive((uint8_t*)(&size), sizeof(size)))
return SWAP(size);
return 0;
}
void picture_content(uint16_t address, uint16_t size, uint8_t* buffer)
{
_send({
0x56, 0x00, 0x32, 0x0C, 0x00, 0x0A,
0x00, 0x00, HI(address), LO(address),
0x00, 0x00, HI(size), LO(size),
0x00, 0x0A});
_receive({0x76, 0x00, 0x32, 0x00, 0x00}) &&
_receive(buffer, size) &&
_receive({0x76, 0x00, 0x32, 0x00, 0x00});
}
void compression(uint8_t ratio)
{
_send({0x56, 0x00, 0x31, 0x05, 0x01, 0x01, 0x12, 0x04, ratio});
_receive({0x76, 0x00, 0x31, 0x00, 0x00});
}
void picture_resolution(Resolution resolution)
{
uint8_t code;
switch (resolution)
{
case Resolution::RES_160x120: code = 0x22; break;
case Resolution::RES_320x240: code = 0x11; break;
case Resolution::RES_640x480: code = 0x00; break;
}
_send({0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, code});
_receive({0x76, 0x00, 0x31, 0x00, 0x00});
}
void enter_power_save()
{
// trace << "enter_power_save" << endl;
_send({0x56, 0x00, 0x3E, 0x03, 0x00, 0x01, 0x01});
_receive({0x76, 0x00, 0x3E, 0x00, 0x00});
}
void exit_power_save()
{
// trace << "exit_power_save" << endl;
_send({0x56, 0x00, 0x3E, 0x03, 0x00, 0x01, 0x00});
_receive({0x76, 0x00, 0x3E, 0x00, 0x00});
}
void baud_rate(BaudRate baud)
{
uint16_t code;
switch (baud)
{
case BaudRate::BAUD_9600: code = 0xAEC8; break;
case BaudRate::BAUD_19200: code = 0x56E4; break;
case BaudRate::BAUD_38400: code = 0x2AF2; break;
case BaudRate::BAUD_57600: code = 0x1C4C; break;
case BaudRate::BAUD_115200: code = 0x0DA6; break;
}
_send({
0x56, 0x00, 0x24, 0x03, 0x01,
HI(code), LO(code)});
_receive({0x76, 0x00, 0x24, 0x00, 0x00});
}
private:
void _send(std::initializer_list<uint8_t> content)
{
for (auto i : content)
_cam.device()->putchar(i);
_cam.device()->flush();
}
bool _receive(std::initializer_list<uint8_t> expected)
{
uint8_t content[CAM_RECV_BUFFER_SIZE];
if (_receive(content, expected.size()))
{
uint8_t* compare = content;
for (auto i : expected)
{
if (*compare != i)
{
trace << "expected " << hex << i << ", actual " << *compare << endl;
return false;
}
++compare;
}
return true;
}
return false;
}
bool _receive(uint8_t* content, uint8_t size)
{
// Wait until timeout or expected received
uint32_t now = RTT::millis();
uint8_t count = 0;
do
{
while (_cam.device()->available())
{
*content++ = _cam.device()->getchar();
if (++count == size)
return true;
}
delay(1);
}
while (RTT::since(now) < _timeout);
trace << "receive timeout. Expected size " << size << ", actual " << count << endl;
return false;
}
void _trace(bool ascii_response = false)
{
trace << "<< ";
while (_cam.device()->available())
{
int c = _cam.device()->getchar();
if (ascii_response)
trace << (char) c;
else
trace << hex << c << ' ';
}
trace << endl;
}
const uint32_t _timeout;
IOStream& _cam;
};
class CamHandler: public Alarm
{
public:
CamHandler(Camera& cam, ::Clock* clock, uint32_t period)
:Alarm(clock, period), _cam(cam), _led(Board::LED, 0)
{
cam.reset();
cam.compression(0x36);
cam.picture_resolution(Camera::Resolution::RES_640x480);
cam.reset();
}
virtual void run()
{
_led.toggle();
_cam.exit_power_save();
_cam.take_picture();
int32_t size = _cam.picture_size();
trace << "picture size = " << size << endl;
uint16_t address = 0;
while (size > 0)
{
uint8_t buffer[CAM_PICT_BUFFER_SIZE];
_cam.picture_content(address, CAM_PICT_BUFFER_SIZE, buffer);
address += CAM_PICT_BUFFER_SIZE;
size -= CAM_PICT_BUFFER_SIZE;
}
_cam.stop_picture();
_cam.enter_power_save();
// This delay seems necessary to avoid garbage sent to trace... (1ms is not long enough)
delay(5);
}
private:
Camera& _cam;
OutputPin _led;
};
int main()
{
// Disable analog comparator
ACSR = _BV(ACD);
// Disable all modules but ADC (required for bandgap reading)
Power::all_disable();
Power::adc_enable();
// Allow interrupts from here
sei();
// Start watchdog and alarms
Watchdog::begin(WATCHDOG_PERIOD);
// Power::set(SLEEP_MODE_PWR_DOWN); // 5uA
// Start using RTT
RTT::begin();
uart.begin(115200);
trace.begin(&uart, PSTR("CamCheck: started"));
IOBuffer<CAM_RX_BUFFER_MAX> ibuf;
Soft::UART uartCam{CAM_TX_PIN, CAM_RX_PIN, &ibuf};
uartCam.begin(38400);
IOStream streamCam{&uartCam};
Camera camera{streamCam, CAM_REPLY_TIMEOUT_SECS};
//TODO improve baud rate here
// camera.baud_rate(Camera::BaudRate::BAUD_115200);
// uartCam.end();
// uartCam.begin(115200);
// Needed for Alarms to work properly
Watchdog::Clock clock;
CamHandler handler(camera, &clock, SEND_PERIOD_SECS);
// Stop using RTT and restore Watchdog
RTT::end();
::delay = Watchdog::delay;
handler.start();
while (true)
{
Watchdog::await();
// If there is at least one event to be dispatched, then change sleep mode, start RTT and NRF
if (Event::queue.available())
{
// Only this mode works when using serial output and full-time RTC
Power::set(SLEEP_MODE_IDLE); // 15mA
// Start using RTT
RTT::begin();
Event event;
while (Event::queue.dequeue(&event))
event.dispatch();
// Stop using RTT and restore Watchdog
RTT::end();
::delay = Watchdog::delay;
// Lowest consumption mode
Power::set(SLEEP_MODE_PWR_DOWN); // 5uA
}
}
}
<commit_msg>Improve project prototype for LinkSprite Camera.<commit_after>#include <Cosa/Alarm.hh>
#include <Cosa/IOBuffer.hh>
#include <Cosa/RTT.hh>
#include <Cosa/Trace.hh>
#include <Cosa/UART.hh>
#include <Cosa/Soft/UART.hh>
#include <Cosa/Watchdog.hh>
#include <stdint-gcc.h>
#include "initializer_list"
static const uint16_t WATCHDOG_PERIOD = 16;
static const uint32_t SEND_PERIOD_SECS = 60;
static const uint32_t CAM_REPLY_TIMEOUT_SECS = 2;
static const size_t CAM_RX_BUFFER_MAX = 64;
static const size_t CAM_TX_BUFFER_MAX = 16;
static const size_t CAM_RECV_BUFFER_SIZE = 16;
static const size_t CAM_PICT_BUFFER_SIZE = 64;
//static const size_t CAM_PICT_BUFFER_SIZE = 32;
static const Board::DigitalPin CAM_TX_PIN = Board::D2;
static const Board::InterruptPin CAM_RX_PIN = Board::PCI3;
static uint8_t HI(uint16_t in)
{
return (in >> 8);
}
static uint8_t LO(uint16_t in)
{
return (in & 0xFF);
}
static uint16_t SWAP(uint16_t in)
{
return (LO(in) << 8) | HI(in);
}
class Camera
{
public:
enum class Resolution
{
RES_640x480,
RES_320x240,
RES_160x120
};
enum class BaudRate
{
BAUD_9600,
BAUD_19200,
BAUD_38400,
BAUD_57600,
BAUD_115200
};
Camera(IOStream& cam, uint32_t timeout)
:_timeout(timeout * 1000), _cam(cam)
{
reset();
}
void reset()
{
trace << "reset" << endl;
_send({0x56, 0x00, 0x26, 0x00});
_receive({0x76, 0x00, 0x26, 0x00, 0x00});
// Reset generates the power on init string: wait until it is received
// _wait_init();
delay(3000);
_cam.device()->empty();
// _trace(true);
}
//TODO method to take picture and notify callback for content
template<typename CB>
void take_picture(CB& callback)
{
take_picture();
int32_t size = picture_size();
uint16_t address = 0;
while (size > 0)
{
//TODO buffer should be an argument to the function (more customizable)
uint8_t buffer[CAM_PICT_BUFFER_SIZE];
picture_content(address, CAM_PICT_BUFFER_SIZE, buffer);
address += CAM_PICT_BUFFER_SIZE;
size -= CAM_PICT_BUFFER_SIZE;
callback(buffer, CAM_PICT_BUFFER_SIZE, (size > 0));
}
stop_picture();
}
void take_picture()
{
// trace << "take_picture" << endl;
_send({0x56, 0x00, 0x36, 0x01, 0x00});
_receive({0x76, 0x00, 0x36, 0x00, 0x00});
}
void stop_picture()
{
// trace << "stop_picture" << endl;
_send({0x56, 0x00, 0x36, 0x01, 0x03});
_receive({0x76, 0x00, 0x36, 0x00, 0x00});
}
uint16_t picture_size()
{
// trace << "get picture_size" << endl;
_send({0x56, 0x00, 0x34, 0x01, 0x00});
uint16_t size;
if ( _receive({0x76, 0x00, 0x34, 0x00, 0x04, 0x00, 0x00})
&& _receive((uint8_t*)(&size), sizeof(size)))
return SWAP(size);
return 0;
}
void picture_content(uint16_t address, uint16_t size, uint8_t* buffer)
{
_send({
0x56, 0x00, 0x32, 0x0C, 0x00, 0x0A,
0x00, 0x00, HI(address), LO(address),
0x00, 0x00, HI(size), LO(size),
0x00, 0x0A});
_receive({0x76, 0x00, 0x32, 0x00, 0x00}) &&
_receive(buffer, size) &&
_receive({0x76, 0x00, 0x32, 0x00, 0x00});
}
void compression(uint8_t ratio)
{
// trace << "compression" << endl;
_send({0x56, 0x00, 0x31, 0x05, 0x01, 0x01, 0x12, 0x04, ratio});
_receive({0x76, 0x00, 0x31, 0x00, 0x00});
}
void picture_resolution(Resolution resolution)
{
// trace << "picture_resolution" << endl;
uint8_t code;
switch (resolution)
{
case Resolution::RES_160x120: code = 0x22; break;
case Resolution::RES_320x240: code = 0x11; break;
case Resolution::RES_640x480: code = 0x00; break;
}
_send({0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, code});
_receive({0x76, 0x00, 0x31, 0x00, 0x00});
}
void enter_power_save()
{
// trace << "enter_power_save" << endl;
_send({0x56, 0x00, 0x3E, 0x03, 0x00, 0x01, 0x01});
_receive({0x76, 0x00, 0x3E, 0x00, 0x00});
}
void exit_power_save()
{
// trace << "exit_power_save" << endl;
_send({0x56, 0x00, 0x3E, 0x03, 0x00, 0x01, 0x00});
_receive({0x76, 0x00, 0x3E, 0x00, 0x00});
}
void baud_rate(BaudRate baud)
{
// trace << "baud_rate" << endl;
uint16_t code;
switch (baud)
{
case BaudRate::BAUD_9600: code = 0xAEC8; break;
case BaudRate::BAUD_19200: code = 0x56E4; break;
case BaudRate::BAUD_38400: code = 0x2AF2; break;
case BaudRate::BAUD_57600: code = 0x1C4C; break;
case BaudRate::BAUD_115200: code = 0x0DA6; break;
}
_send({
0x56, 0x00, 0x24, 0x03, 0x01,
HI(code), LO(code)});
_receive({0x76, 0x00, 0x24, 0x00, 0x00});
}
private:
bool _wait_init()
{
// Wait until timeout or expected received
uint32_t now = RTT::millis();
do
{
char buffer[80];
if ( _cam.readline(buffer, sizeof(buffer), false)
&& strstr(buffer, "Init end"))
{
_cam.device()->empty();
return true;
}
delay(1);
}
while (RTT::since(now) < 3000);
trace << "wait init timeout." << endl;
_cam.device()->empty();
return false;
}
void _send(std::initializer_list<uint8_t> content)
{
for (auto i : content)
_cam.device()->putchar(i);
_cam.device()->flush();
}
bool _receive(std::initializer_list<uint8_t> expected)
{
uint8_t content[CAM_RECV_BUFFER_SIZE];
if (_receive(content, expected.size()))
{
uint8_t* compare = content;
for (auto i : expected)
{
if (*compare != i)
{
trace << "expected " << hex << i << ", actual " << hex << *compare << endl;
return false;
}
++compare;
}
return true;
}
return false;
}
bool _receive(uint8_t* content, uint8_t size)
{
// Wait until timeout or expected received
uint32_t now = RTT::millis();
uint8_t count = 0;
do
{
while (_cam.device()->available())
{
*content++ = _cam.device()->getchar();
if (++count == size)
return true;
}
delay(1);
}
while (RTT::since(now) < _timeout);
trace << "receive timeout. Expected size " << size << ", actual " << count << endl;
return false;
}
void _trace(bool ascii_response = false)
{
trace << "<< ";
while (_cam.device()->available())
{
int c = _cam.device()->getchar();
if (ascii_response)
trace << (char) c;
else
trace << hex << c << ' ';
}
trace << endl;
}
const uint32_t _timeout;
IOStream& _cam;
};
class CamHandler: public Alarm
{
public:
CamHandler(Camera& cam, ::Clock* clock, uint32_t period)
:Alarm(clock, period), _cam(cam), _led(Board::LED, 0)
{
cam.compression(0x36);
cam.picture_resolution(Camera::Resolution::RES_640x480);
cam.reset();
}
virtual void run()
{
_led.toggle();
_cam.exit_power_save();
_cam.take_picture();
int32_t size = _cam.picture_size();
// trace << "picture size = " << size << endl;
uint16_t address = 0;
while (size > 0)
{
uint8_t buffer[CAM_PICT_BUFFER_SIZE];
_cam.picture_content(address, CAM_PICT_BUFFER_SIZE, buffer);
address += CAM_PICT_BUFFER_SIZE;
size -= CAM_PICT_BUFFER_SIZE;
trace.device()->write(buffer, CAM_PICT_BUFFER_SIZE);
}
_cam.stop_picture();
_cam.enter_power_save();
// This delay seems necessary to avoid garbage sent to trace... (1ms is not long enough)
delay(5);
}
private:
Camera& _cam;
OutputPin _led;
};
int main()
{
// Disable analog comparator
ACSR = _BV(ACD);
// Disable all modules but ADC (required for bandgap reading)
Power::all_disable();
Power::adc_enable();
// Allow interrupts from here
sei();
// Start watchdog and alarms
Watchdog::begin(WATCHDOG_PERIOD);
// Power::set(SLEEP_MODE_PWR_DOWN); // 5uA
// Start using RTT
RTT::begin();
uart.begin(115200);
trace.begin(&uart, PSTR("CamCheck: started"));
IOBuffer<CAM_RX_BUFFER_MAX> ibuf;
Soft::UART uartCam{CAM_TX_PIN, CAM_RX_PIN, &ibuf};
uartCam.begin(38400);
IOStream streamCam{&uartCam};
Camera camera{streamCam, CAM_REPLY_TIMEOUT_SECS};
//TODO improve baud rate here
// camera.baud_rate(Camera::BaudRate::BAUD_115200);
// uartCam.end();
// uartCam.begin(115200);
// Needed for Alarms to work properly
Watchdog::Clock clock;
CamHandler handler(camera, &clock, SEND_PERIOD_SECS);
// Stop using RTT and restore Watchdog
RTT::end();
::delay = Watchdog::delay;
handler.start();
while (true)
{
Watchdog::await();
// If there is at least one event to be dispatched, then change sleep mode, start RTT and NRF
if (Event::queue.available())
{
// Only this mode works when using serial output and full-time RTC
Power::set(SLEEP_MODE_IDLE); // 15mA
// Start using RTT
RTT::begin();
Event event;
while (Event::queue.dequeue(&event))
event.dispatch();
// Stop using RTT and restore Watchdog
RTT::end();
::delay = Watchdog::delay;
// Lowest consumption mode
Power::set(SLEEP_MODE_PWR_DOWN); // 5uA
}
}
}
<|endoftext|>
|
<commit_before>/*
* The main source of the Beng proxy server.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "direct.hxx"
#include "lb_instance.hxx"
#include "lb_check.hxx"
#include "lb_setup.hxx"
#include "lb_connection.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "stock/MapStock.hxx"
#include "failure.hxx"
#include "bulldog.hxx"
#include "balancer.hxx"
#include "pipe_stock.hxx"
#include "log_glue.hxx"
#include "lb_config.hxx"
#include "ssl/ssl_init.hxx"
#include "pool.hxx"
#include "thread_pool.hxx"
#include "fb_pool.hxx"
#include "capabilities.hxx"
#include "system/Isolate.hxx"
#include "system/SetupProcess.hxx"
#include "util/PrintException.hxx"
#include "util/Macros.hxx"
#include <daemon/log.h>
#include <systemd/sd-daemon.h>
#include <postgresql/libpq-fe.h>
#include <assert.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#ifdef __linux
#include <sys/prctl.h>
#ifndef PR_SET_NO_NEW_PRIVS
#define PR_SET_NO_NEW_PRIVS 38
#endif
#endif
static constexpr cap_value_t cap_keep_list[1] = {
/* keep the NET_RAW capability to be able to to use the socket
option IP_TRANSPARENT */
CAP_NET_RAW,
};
void
LbInstance::ShutdownCallback()
{
if (should_exit)
return;
should_exit = true;
deinit_signals(this);
thread_pool_stop();
avahi_client.Close();
compress_event.Cancel();
deinit_all_controls(this);
DisconnectCertCaches();
while (!connections.empty())
lb_connection_close(&connections.front());
assert(n_tcp_connections == 0);
deinit_all_listeners(this);
thread_pool_join();
monitors.Clear();
pool_commit();
if (tcp_balancer != nullptr)
tcp_balancer_free(tcp_balancer);
delete tcp_stock;
if (balancer != nullptr)
balancer_free(balancer);
if (pipe_stock != nullptr)
pipe_stock_free(pipe_stock);
pool_commit();
}
void
LbInstance::ReloadEventCallback(int)
{
unsigned n_ssl_sessions = FlushSSLSessionCache(LONG_MAX);
daemon_log(3, "flushed %u SSL sessions\n", n_ssl_sessions);
Compress();
}
void
init_signals(LbInstance *instance)
{
instance->shutdown_listener.Enable();
instance->sighup_event.Enable();
}
void
deinit_signals(LbInstance *instance)
{
instance->shutdown_listener.Disable();
instance->sighup_event.Disable();
}
int main(int argc, char **argv)
{
const ScopeFbPoolInit fb_pool_init;
LbInstance instance;
/* configuration */
LbConfig config;
ParseCommandLine(instance.cmdline, config, argc, argv);
try {
LoadConfigFile(config,
instance.cmdline.config_path);
} catch (const std::exception &e) {
PrintException(e);
return EXIT_FAILURE;
}
instance.config = &config;
if (instance.cmdline.check) {
int status = EXIT_SUCCESS;
const ScopeSslGlobalInit ssl_init;
try {
lb_check(instance.event_loop, *instance.config);
} catch (const std::exception &e) {
PrintException(e);
status = EXIT_FAILURE;
}
return status;
}
/* initialize */
SetupProcess();
const ScopeSslGlobalInit ssl_init;
/* prevent libpq from initializing libssl & libcrypto again */
PQinitOpenSSL(0, 0);
direct_global_init();
init_signals(&instance);
try {
init_all_controls(&instance);
init_all_listeners(instance);
} catch (const std::exception &e) {
fprintf(stderr, "%s\n", e.what());
return EXIT_FAILURE;
}
instance.balancer = balancer_new(instance.event_loop);
instance.tcp_stock = tcp_stock_new(instance.event_loop,
instance.cmdline.tcp_stock_limit);
instance.tcp_balancer = tcp_balancer_new(*instance.tcp_stock,
*instance.balancer);
instance.pipe_stock = pipe_stock_new(instance.event_loop);
failure_init();
bulldog_init(instance.cmdline.bulldog_path);
/* launch the access logger */
log_global_init(config.access_logger.c_str(),
&instance.cmdline.logger_user);
/* daemonize II */
if (!instance.cmdline.user.IsEmpty())
capabilities_pre_setuid();
instance.cmdline.user.Apply();
for (const auto &path : config.lua_files)
instance.RunLuaFile(path.c_str());
/* can't change to new (empty) rootfs if we may need to reconnect
to PostgreSQL eventually */
// TODO: bind-mount the PostgreSQL socket into the new rootfs
if (!instance.config->HasCertDatabase())
isolate_from_filesystem(instance.config->HasZeroConf());
if (!instance.cmdline.user.IsEmpty())
capabilities_post_setuid(cap_keep_list, ARRAY_SIZE(cap_keep_list));
#ifdef __linux
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
#endif
/* main loop */
instance.InitWorker();
/* tell systemd we're ready */
sd_notify(0, "READY=1");
instance.event_loop.Dispatch();
/* cleanup */
log_global_deinit();
bulldog_deinit();
failure_deinit();
deinit_all_listeners(&instance);
deinit_all_controls(&instance);
thread_pool_deinit();
}
<commit_msg>lb_main: global exception handler<commit_after>/*
* The main source of the Beng proxy server.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "direct.hxx"
#include "lb_instance.hxx"
#include "lb_check.hxx"
#include "lb_setup.hxx"
#include "lb_connection.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "stock/MapStock.hxx"
#include "failure.hxx"
#include "bulldog.hxx"
#include "balancer.hxx"
#include "pipe_stock.hxx"
#include "log_glue.hxx"
#include "lb_config.hxx"
#include "ssl/ssl_init.hxx"
#include "pool.hxx"
#include "thread_pool.hxx"
#include "fb_pool.hxx"
#include "capabilities.hxx"
#include "system/Isolate.hxx"
#include "system/SetupProcess.hxx"
#include "util/PrintException.hxx"
#include "util/Macros.hxx"
#include <daemon/log.h>
#include <systemd/sd-daemon.h>
#include <postgresql/libpq-fe.h>
#include <assert.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#ifdef __linux
#include <sys/prctl.h>
#ifndef PR_SET_NO_NEW_PRIVS
#define PR_SET_NO_NEW_PRIVS 38
#endif
#endif
static constexpr cap_value_t cap_keep_list[1] = {
/* keep the NET_RAW capability to be able to to use the socket
option IP_TRANSPARENT */
CAP_NET_RAW,
};
void
LbInstance::ShutdownCallback()
{
if (should_exit)
return;
should_exit = true;
deinit_signals(this);
thread_pool_stop();
avahi_client.Close();
compress_event.Cancel();
deinit_all_controls(this);
DisconnectCertCaches();
while (!connections.empty())
lb_connection_close(&connections.front());
assert(n_tcp_connections == 0);
deinit_all_listeners(this);
thread_pool_join();
monitors.Clear();
pool_commit();
if (tcp_balancer != nullptr)
tcp_balancer_free(tcp_balancer);
delete tcp_stock;
if (balancer != nullptr)
balancer_free(balancer);
if (pipe_stock != nullptr)
pipe_stock_free(pipe_stock);
pool_commit();
}
void
LbInstance::ReloadEventCallback(int)
{
unsigned n_ssl_sessions = FlushSSLSessionCache(LONG_MAX);
daemon_log(3, "flushed %u SSL sessions\n", n_ssl_sessions);
Compress();
}
void
init_signals(LbInstance *instance)
{
instance->shutdown_listener.Enable();
instance->sighup_event.Enable();
}
void
deinit_signals(LbInstance *instance)
{
instance->shutdown_listener.Disable();
instance->sighup_event.Disable();
}
int main(int argc, char **argv)
try {
const ScopeFbPoolInit fb_pool_init;
LbInstance instance;
/* configuration */
LbConfig config;
ParseCommandLine(instance.cmdline, config, argc, argv);
LoadConfigFile(config, instance.cmdline.config_path);
instance.config = &config;
if (instance.cmdline.check) {
const ScopeSslGlobalInit ssl_init;
lb_check(instance.event_loop, *instance.config);
return EXIT_SUCCESS;
}
/* initialize */
SetupProcess();
const ScopeSslGlobalInit ssl_init;
/* prevent libpq from initializing libssl & libcrypto again */
PQinitOpenSSL(0, 0);
direct_global_init();
init_signals(&instance);
init_all_controls(&instance);
init_all_listeners(instance);
instance.balancer = balancer_new(instance.event_loop);
instance.tcp_stock = tcp_stock_new(instance.event_loop,
instance.cmdline.tcp_stock_limit);
instance.tcp_balancer = tcp_balancer_new(*instance.tcp_stock,
*instance.balancer);
instance.pipe_stock = pipe_stock_new(instance.event_loop);
failure_init();
bulldog_init(instance.cmdline.bulldog_path);
/* launch the access logger */
log_global_init(config.access_logger.c_str(),
&instance.cmdline.logger_user);
/* daemonize II */
if (!instance.cmdline.user.IsEmpty())
capabilities_pre_setuid();
instance.cmdline.user.Apply();
for (const auto &path : config.lua_files)
instance.RunLuaFile(path.c_str());
/* can't change to new (empty) rootfs if we may need to reconnect
to PostgreSQL eventually */
// TODO: bind-mount the PostgreSQL socket into the new rootfs
if (!instance.config->HasCertDatabase())
isolate_from_filesystem(instance.config->HasZeroConf());
if (!instance.cmdline.user.IsEmpty())
capabilities_post_setuid(cap_keep_list, ARRAY_SIZE(cap_keep_list));
#ifdef __linux
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
#endif
/* main loop */
instance.InitWorker();
/* tell systemd we're ready */
sd_notify(0, "READY=1");
instance.event_loop.Dispatch();
/* cleanup */
log_global_deinit();
bulldog_deinit();
failure_deinit();
deinit_all_listeners(&instance);
deinit_all_controls(&instance);
thread_pool_deinit();
} catch (const std::exception &e) {
PrintException(e);
return EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>#include "modinclude.h"
#include "bot_admin.h"
class DieCommand : public AdminHook {
public:
int botAPIversion();
bool onLoadComplete();
void onRehash();
std::string getDesc();
std::vector<std::string> supports();
std::vector<std::vector<std::string> > adminCommands();
void onAdminCommand(std::string server, std::string nick, std::string command, std::string message, dccSender* dccMod, bool master);
};
int DieCommand::botAPIversion() {
return 1002;
}
bool DieCommand::onLoadComplete() {
std::multimap<std::string, std::string> modAbilities = getModAbilities();
std::multimap<std::string, std::string>::iterator botAdminAbility = modAbilities.find("BOT_ADMIN");
if (botAdminAbility == modAbilities.end()) { // BOT_ADMIN not provided but required for this module
std::cout << "A module providing BOT_ADMIN is required for " << moduleName << ". Unloading." << std::endl;
unloadModule(moduleName);
return false;
}
if (config["masteronly"] != "") {
if (config["masteronly"][0] == 'n')
config["masteronly"] = "no";
else
config["masteronly"] = "yes";
} else
config["masteronly"] = "yes";
return true;
}
void DieCommand::onRehash() {
std::multimap<std::string, std::string> modAbilities = getModAbilities();
std::multimap<std::string, std::string>::iterator botAdminAbility = modAbilities.find("BOT_ADMIN");
if (botAdminAbility == modAbilities.end()) { // BOT_ADMIN not provided but required for this module
std::cout << "A module providing BOT_ADMIN is required for " << moduleName << ". Unloading." << std::endl;
unloadModule(moduleName);
}
if (config["masteronly"] != "") {
if (config["masteronly"][0] == 'n')
config["masteronly"] = "no";
else
config["masteronly"] = "yes";
} else
config["masteronly"] = "yes";
}
std::string DieCommand::getDesc() {
return "Allows the bot master to shut the bot down from IRC.";
}
std::vector<std::string> DieCommand::supports() {
std::vector<std::string> supporting;
supporting.push_back("BOT_ADMIN");
return supporting;
}
std::vector<std::vector<std::string> > DieCommand::adminCommands() {
std::vector<std::vector<std::string> > theCommands;
std::vector<std::string> dieCommand;
dieCommand.push_back("die");
dieCommand.push_back("Makes the bot shut down.");
dieCommand.push_back("Syntax: die [reason]");
dieCommand.push_back("This command causes the bot to shut down. If a reason is given, it will be used as the quit reason on all servers.");
if (config["masteronly"] == "yes")
dieCommand.push_back("This command is available only to bot admins.");
theCommands.push_back(dieCommand);
return theCommands;
}
void DieCommand::onAdminCommand(std::string server, std::string nick, std::string command, std::string message, dccSender* dccMod, bool master) {
if (config["masteronly"] == "yes" && !master) {
if (dccMod == NULL)
sendPrivMsg(server, nick, "The die command is available only to bot masters.");
else
dccMod->dccSend(server + "/" + nick, "The die command is available only to bot masters.");
return;
}
std::list<std::string> connectedServers = getServers();
for (std::list<std::string>::iterator servIter = connectedServers.begin(); servIter != connectedServers.end(); ++servIter)
quitServer(*servIter, message);
if (dccMod != NULL) {
std::vector<std::string> connectedDCC = dccMod->getConnections();
for (unsigned int i = 0; i < connectedDCC.size(); i++)
dccMod->closeDCCConnection(connectedDCC[i]);
}
std::cout << "Shutting down by admin command: die" << std::endl;
std::exit(0);
}
extern "C" Module* spawn() {
return new DieCommand;
}<commit_msg>Add some sleep to m_admin_die so the bot doesn't exist before the send queues can flush.<commit_after>#include "modinclude.h"
#include "bot_admin.h"
class DieCommand : public AdminHook {
public:
int botAPIversion();
bool onLoadComplete();
void onRehash();
std::string getDesc();
std::vector<std::string> supports();
std::vector<std::vector<std::string> > adminCommands();
void onAdminCommand(std::string server, std::string nick, std::string command, std::string message, dccSender* dccMod, bool master);
};
int DieCommand::botAPIversion() {
return 1002;
}
bool DieCommand::onLoadComplete() {
std::multimap<std::string, std::string> modAbilities = getModAbilities();
std::multimap<std::string, std::string>::iterator botAdminAbility = modAbilities.find("BOT_ADMIN");
if (botAdminAbility == modAbilities.end()) { // BOT_ADMIN not provided but required for this module
std::cout << "A module providing BOT_ADMIN is required for " << moduleName << ". Unloading." << std::endl;
unloadModule(moduleName);
return false;
}
if (config["masteronly"] != "") {
if (config["masteronly"][0] == 'n')
config["masteronly"] = "no";
else
config["masteronly"] = "yes";
} else
config["masteronly"] = "yes";
return true;
}
void DieCommand::onRehash() {
std::multimap<std::string, std::string> modAbilities = getModAbilities();
std::multimap<std::string, std::string>::iterator botAdminAbility = modAbilities.find("BOT_ADMIN");
if (botAdminAbility == modAbilities.end()) { // BOT_ADMIN not provided but required for this module
std::cout << "A module providing BOT_ADMIN is required for " << moduleName << ". Unloading." << std::endl;
unloadModule(moduleName);
}
if (config["masteronly"] != "") {
if (config["masteronly"][0] == 'n')
config["masteronly"] = "no";
else
config["masteronly"] = "yes";
} else
config["masteronly"] = "yes";
}
std::string DieCommand::getDesc() {
return "Allows the bot master to shut the bot down from IRC.";
}
std::vector<std::string> DieCommand::supports() {
std::vector<std::string> supporting;
supporting.push_back("BOT_ADMIN");
return supporting;
}
std::vector<std::vector<std::string> > DieCommand::adminCommands() {
std::vector<std::vector<std::string> > theCommands;
std::vector<std::string> dieCommand;
dieCommand.push_back("die");
dieCommand.push_back("Makes the bot shut down.");
dieCommand.push_back("Syntax: die [reason]");
dieCommand.push_back("This command causes the bot to shut down. If a reason is given, it will be used as the quit reason on all servers.");
if (config["masteronly"] == "yes")
dieCommand.push_back("This command is available only to bot admins.");
theCommands.push_back(dieCommand);
return theCommands;
}
void DieCommand::onAdminCommand(std::string server, std::string nick, std::string command, std::string message, dccSender* dccMod, bool master) {
if (config["masteronly"] == "yes" && !master) {
if (dccMod == NULL)
sendPrivMsg(server, nick, "The die command is available only to bot masters.");
else
dccMod->dccSend(server + "/" + nick, "The die command is available only to bot masters.");
return;
}
std::list<std::string> connectedServers = getServers();
for (std::list<std::string>::iterator servIter = connectedServers.begin(); servIter != connectedServers.end(); ++servIter)
quitServer(*servIter, message);
if (dccMod != NULL) {
std::vector<std::string> connectedDCC = dccMod->getConnections();
for (unsigned int i = 0; i < connectedDCC.size(); i++)
dccMod->closeDCCConnection(connectedDCC[i]);
}
std::cout << "Shutting down by admin command: die" << std::endl;
sleep(1);
std::exit(0);
}
extern "C" Module* spawn() {
return new DieCommand;
}<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <qobject.h>
#endif
#include "Workbench.h"
#include <Gui/MenuManager.h>
#include <Gui/ToolBarManager.h>
using namespace PartGui;
#if 0 // needed for Qt's lupdate utility
qApp->translate("Workbench", "&Part");
qApp->translate("Workbench", "&Simple");
qApp->translate("Workbench", "&Parametric");
qApp->translate("Workbench", "Solids");
qApp->translate("Workbench", "Part tools");
qApp->translate("Workbench", "Boolean");
#endif
/// @namespace PartGui @class Workbench
TYPESYSTEM_SOURCE(PartGui::Workbench, Gui::StdWorkbench)
Workbench::Workbench()
{
}
Workbench::~Workbench()
{
}
Gui::MenuItem* Workbench::setupMenuBar() const
{
Gui::MenuItem* root = StdWorkbench::setupMenuBar();
Gui::MenuItem* item = root->findItem("&Windows");
Gui::MenuItem* prim = new Gui::MenuItem;
prim->setCommand("Primitives");
*prim << "Part_Box" << "Part_Cylinder" << "Part_Sphere"
<< "Part_Cone" << "Part_Torus";
Gui::MenuItem* bop = new Gui::MenuItem;
bop->setCommand("Boolean");
*bop << "Part_Boolean" << "Part_Cut" << "Part_Fuse" << "Part_Common";
Gui::MenuItem* join = new Gui::MenuItem;
join->setCommand("Join");
*join << "Part_JoinConnect" << "Part_JoinEmbed" << "Part_JoinCutout";
Gui::MenuItem* split = new Gui::MenuItem;
split->setCommand("Split");
*split << "Part_BooleanFragments" << "Part_Slice" << "Part_XOR";
Gui::MenuItem* compound = new Gui::MenuItem;
compound->setCommand("Compound");
*compound << "Part_Compound" << "Part_CompoundFilter";
Gui::MenuItem* part = new Gui::MenuItem;
root->insertItem(item, part);
part->setCommand("&Part");
*part << "Part_Import" << "Part_Export" << "Separator";
*part << prim << "Part_Primitives" << "Part_Builder" << "Separator"
<< "Part_ShapeFromMesh" << "Part_MakeSolid" << "Part_ReverseShape"
<< "Part_SimpleCopy" << "Part_RefineShape" << "Part_CheckGeometry"
<< "Separator" << bop << join << split << compound << "Separator"
<< "Part_CrossSections" << "Part_MakeFace" << "Part_Extrude"
<< "Part_Revolve" << "Part_Mirror" << "Part_Fillet" << "Part_Chamfer"
<< "Part_RuledSurface" << "Part_Loft" << "Part_Sweep"
<< "Part_Offset" << "Part_Offset2D" << "Part_Thickness" << "Separator" << "Part_EditAttachment";
Gui::MenuItem* measure = new Gui::MenuItem;
root->insertItem(item,measure);
measure->setCommand("Measure");
*measure << "Part_Measure_Linear" << "Part_Measure_Angular" << "Separator" << "Part_Measure_Clear_All" << "Part_Measure_Toggle_All" <<
"Part_Measure_Toggle_3d" << "Part_Measure_Toggle_Delta";
// leave this for 0.14 until #0000477 is fixed
#if 0
Gui::MenuItem* view = root->findItem("&View");
if (view) {
Gui::MenuItem* appr = view->findItem("Std_RandomColor");
appr = view->afterItem(appr);
Gui::MenuItem* face = new Gui::MenuItem();
face->setCommand("Part_ColorPerFace");
view->insertItem(appr, face);
}
#endif
return root;
}
Gui::ToolBarItem* Workbench::setupToolBars() const
{
Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
Gui::ToolBarItem* solids = new Gui::ToolBarItem(root);
solids->setCommand("Solids");
*solids << "Part_Box" << "Part_Cylinder" << "Part_Sphere" << "Part_Cone"
<< "Part_Torus" << "Part_Primitives" << "Part_Builder";
Gui::ToolBarItem* tool = new Gui::ToolBarItem(root);
tool->setCommand("Part tools");
*tool << "Part_Extrude" << "Part_Revolve" << "Part_Mirror" << "Part_Fillet"
<< "Part_Chamfer" << "Part_RuledSurface" << "Part_Loft" << "Part_Sweep"
<< "Part_CompOffset" << "Part_Thickness";
Gui::ToolBarItem* boolop = new Gui::ToolBarItem(root);
boolop->setCommand("Boolean");
*boolop << "Part_Boolean" << "Part_Cut" << "Part_Fuse" << "Part_Common"
<< "Part_CompJoinFeatures" << "Part_CompSplitFeatures" << "Part_CheckGeometry" << "Part_Section"
<< "Part_CrossSections";
Gui::ToolBarItem* measure = new Gui::ToolBarItem(root);
measure->setCommand("Measure");
*measure << "Part_Measure_Linear" << "Part_Measure_Angular" << "Separator" << "Part_Measure_Clear_All" << "Part_Measure_Toggle_All"
<< "Part_Measure_Toggle_3d" << "Part_Measure_Toggle_Delta";
return root;
}
Gui::ToolBarItem* Workbench::setupCommandBars() const
{
// Part tools
Gui::ToolBarItem* root = new Gui::ToolBarItem;
return root;
}
<commit_msg>fixes #0001955: Part Section not available in the Part menu<commit_after>/***************************************************************************
* Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <qobject.h>
#endif
#include "Workbench.h"
#include <Gui/MenuManager.h>
#include <Gui/ToolBarManager.h>
using namespace PartGui;
#if 0 // needed for Qt's lupdate utility
qApp->translate("Workbench", "&Part");
qApp->translate("Workbench", "&Simple");
qApp->translate("Workbench", "&Parametric");
qApp->translate("Workbench", "Solids");
qApp->translate("Workbench", "Part tools");
qApp->translate("Workbench", "Boolean");
#endif
/// @namespace PartGui @class Workbench
TYPESYSTEM_SOURCE(PartGui::Workbench, Gui::StdWorkbench)
Workbench::Workbench()
{
}
Workbench::~Workbench()
{
}
Gui::MenuItem* Workbench::setupMenuBar() const
{
Gui::MenuItem* root = StdWorkbench::setupMenuBar();
Gui::MenuItem* item = root->findItem("&Windows");
Gui::MenuItem* prim = new Gui::MenuItem;
prim->setCommand("Primitives");
*prim << "Part_Box"
<< "Part_Cylinder"
<< "Part_Sphere"
<< "Part_Cone"
<< "Part_Torus";
Gui::MenuItem* bop = new Gui::MenuItem;
bop->setCommand("Boolean");
*bop << "Part_Boolean"
<< "Part_Cut"
<< "Part_Fuse"
<< "Part_Common";
Gui::MenuItem* join = new Gui::MenuItem;
join->setCommand("Join");
*join << "Part_JoinConnect"
<< "Part_JoinEmbed"
<< "Part_JoinCutout";
Gui::MenuItem* split = new Gui::MenuItem;
split->setCommand("Split");
*split << "Part_BooleanFragments"
<< "Part_Slice"
<< "Part_XOR";
Gui::MenuItem* compound = new Gui::MenuItem;
compound->setCommand("Compound");
*compound << "Part_Compound"
<< "Part_CompoundFilter";
Gui::MenuItem* part = new Gui::MenuItem;
root->insertItem(item, part);
part->setCommand("&Part");
*part << "Part_Import"
<< "Part_Export"
<< "Separator";
*part << prim
<< "Part_Primitives"
<< "Part_Builder"
<< "Separator"
<< "Part_ShapeFromMesh"
<< "Part_MakeSolid"
<< "Part_ReverseShape"
<< "Part_SimpleCopy"
<< "Part_RefineShape"
<< "Part_CheckGeometry"
<< "Separator"
<< bop << join << split << compound
<< "Separator"
<< "Part_Section"
<< "Part_CrossSections"
<< "Part_MakeFace"
<< "Part_Extrude"
<< "Part_Revolve"
<< "Part_Mirror"
<< "Part_Fillet"
<< "Part_Chamfer"
<< "Part_RuledSurface"
<< "Part_Loft"
<< "Part_Sweep"
<< "Part_Offset"
<< "Part_Offset2D"
<< "Part_Thickness"
<< "Separator"
<< "Part_EditAttachment";
Gui::MenuItem* measure = new Gui::MenuItem;
root->insertItem(item,measure);
measure->setCommand("Measure");
*measure << "Part_Measure_Linear"
<< "Part_Measure_Angular"
<< "Separator"
<< "Part_Measure_Clear_All"
<< "Part_Measure_Toggle_All"
<< "Part_Measure_Toggle_3d"
<< "Part_Measure_Toggle_Delta";
// leave this for 0.14 until #0000477 is fixed
#if 0
Gui::MenuItem* view = root->findItem("&View");
if (view) {
Gui::MenuItem* appr = view->findItem("Std_RandomColor");
appr = view->afterItem(appr);
Gui::MenuItem* face = new Gui::MenuItem();
face->setCommand("Part_ColorPerFace");
view->insertItem(appr, face);
}
#endif
return root;
}
Gui::ToolBarItem* Workbench::setupToolBars() const
{
Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
Gui::ToolBarItem* solids = new Gui::ToolBarItem(root);
solids->setCommand("Solids");
*solids << "Part_Box"
<< "Part_Cylinder"
<< "Part_Sphere"
<< "Part_Cone"
<< "Part_Torus"
<< "Part_Primitives"
<< "Part_Builder";
Gui::ToolBarItem* tool = new Gui::ToolBarItem(root);
tool->setCommand("Part tools");
*tool << "Part_Extrude"
<< "Part_Revolve"
<< "Part_Mirror"
<< "Part_Fillet"
<< "Part_Chamfer"
<< "Part_RuledSurface"
<< "Part_Loft"
<< "Part_Sweep"
<< "Part_CompOffset"
<< "Part_Thickness";
Gui::ToolBarItem* boolop = new Gui::ToolBarItem(root);
boolop->setCommand("Boolean");
*boolop << "Part_Boolean"
<< "Part_Cut"
<< "Part_Fuse"
<< "Part_Common"
<< "Part_CompJoinFeatures"
<< "Part_CompSplitFeatures"
<< "Part_CheckGeometry"
<< "Part_Section"
<< "Part_CrossSections";
Gui::ToolBarItem* measure = new Gui::ToolBarItem(root);
measure->setCommand("Measure");
*measure << "Part_Measure_Linear"
<< "Part_Measure_Angular"
<< "Separator"
<< "Part_Measure_Clear_All"
<< "Part_Measure_Toggle_All"
<< "Part_Measure_Toggle_3d"
<< "Part_Measure_Toggle_Delta";
return root;
}
Gui::ToolBarItem* Workbench::setupCommandBars() const
{
// Part tools
Gui::ToolBarItem* root = new Gui::ToolBarItem;
return root;
}
<|endoftext|>
|
<commit_before>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Razer 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.
// Internal Includes
#include "FindDriver.h"
// Library/third-party includes
#include <boost/iostreams/stream.hpp>
#include <boost/process.hpp>
#include <json/reader.h>
#include <json/value.h>
#include <osvr/Util/Finally.h>
#include <osvr/Util/PlatformConfig.h>
// Standard includes
#include <iostream>
#include <limits.h>
#include <vector>
#if _MSC_VER >= 1800
#include <filesystem>
#else
#include <boost/filesystem.hpp>
#endif
#if defined(OSVR_WINDOWS)
#include <shlobj.h>
#endif
#undef VIVELOADER_VERBOSE
using osvr::util::finally;
namespace osvr {
namespace vive {
#if defined(OSVR_WINDOWS)
static const auto PLATFORM_DIRNAME_BASE = "win";
static const auto DRIVER_EXTENSION = ".dll";
static const auto TOOL_EXTENSION = ".exe";
static const auto PATH_SEP = "\\";
#elif defined(OSVR_MACOSX)
/// @todo Note that there are no 64-bit steamvr runtimes or drivers on OS X
static const auto PLATFORM_DIRNAME_BASE = "osx";
static const auto DRIVER_EXTENSION = ".dylib";
static const auto TOOL_EXTENSION = "";
static const auto PATH_SEP = "/";
#elif defined(OSVR_LINUX)
static const auto PLATFORM_DIRNAME_BASE = "linux";
static const auto DRIVER_EXTENSION = ".so";
static const auto TOOL_EXTENSION = "";
static const auto PATH_SEP = "/";
#else
#error "Sorry, Valve does not produce a SteamVR runtime for your platform."
#endif
#if defined(OSVR_USING_FILESYSTEM_TR2)
using std::tr2::sys::path;
using std::tr2::sys::wpath;
using std::tr2::sys::exists;
#elif defined(OSVR_USING_BOOST_FILESYSTEM)
using boost::filesystem::path;
using boost::filesystem::exists;
#endif
inline std::string getPlatformDirname() {
return PLATFORM_DIRNAME_BASE +
std::to_string(sizeof(void *) * CHAR_BIT);
inline void parsePathConfigFile(std::istream &is, Json::Value &ret) {
Json::Reader reader;
if (!reader.parse(is, ret)) {
std::cerr << "Error parsing file containing path configuration - "
"have you run SteamVR yet?"
<< std::endl;
std::cerr << reader.getFormattedErrorMessages() << std::endl;
}
}
#if defined(OSVR_WINDOWS)
inline Json::Value getPathConfig() {
PWSTR outString = nullptr;
Json::Value ret;
// It's OK to use Vista+ stuff here, since openvr_api.dll uses Vista+
// stuff too.
auto hr =
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &outString);
if (!SUCCEEDED(hr)) {
std::cerr << "Could not get local app data directory!" << std::endl;
return ret;
}
// Free the string returned when we're all done.
auto freeString = [&] { CoTaskMemFree(outString); };
// Build the path to the file.
auto vrPaths =
wpath(outString) / wpath(L"openvr") / wpath(L"openvrpaths.vrpath");
std::ifstream is(vrPaths.string());
if (!is) {
std::wcerr << L"Could not open file containing path configuration "
L"- have you run SteamVR yet? "
<< vrPaths << L"\n";
return ret;
}
parsePathConfigFile(is, ret);
return ret;
}
#elif defined(OSVR_MACOSX)
inline Json::Value getPathConfig() {
#error "implementation not complete"
}
#elif defined(OSVR_LINUX)
inline Json::Value getPathConfig() {
#error "implementation not complete"
}
#endif
#if 0
#if defined(OSVR_WINDOWS)
inline std::vector<std::string> getSteamVRRoots() {
/// @todo make this better - there's Windows API for that.
return std::vector<std::string>{
std::string{"C:\\Program Files\\Steam\\steamapps\\common\\SteamVR"},
std::string{
"C:\\Program Files (x86)\\Steam\\steamapps\\common\\SteamVR"}};
}
#elif defined(OSVR_MACOSX)
inline std::vector<std::string> getSteamVRRoots() {
#error "implementation not complete"
}
#elif defined(OSVR_LINUX)
inline std::vector<std::string> getSteamVRRoots() {
#error "implementation not complete"
}
#endif
#endif
inline std::vector<std::string> getSteamVRRoots(Json::Value const &json) {
std::vector<std::string> ret;
auto &runtimes = json["runtime"];
if (!runtimes.isArray()) {
return ret;
}
for (auto &runtime : runtimes) {
ret.emplace_back(runtime.asString());
}
return ret;
}
inline std::vector<std::string> getSteamVRRoots() {
return getSteamVRRoots(getPathConfig());
}
inline void computeDriverRootAndFilePath(DriverLocationInfo &info,
std::string const &driver) {
auto p = path{info.steamVrRoot};
p /= "drivers";
p /= driver;
p /= "bin";
p /= getPlatformDirname();
info.driverRoot = p.string();
p /= ("driver_" + driver + DRIVER_EXTENSION);
info.driverFile = p.string();
}
DriverLocationInfo findDriver(std::string const &driver) {
DriverLocationInfo info;
for (auto &root : getSteamVRRoots()) {
info.steamVrRoot = root;
info.driverName = driver;
computeDriverRootAndFilePath(info, driver);
#ifdef VIVELOADER_VERBOSE
std::cout << "Will try to load driver from:\n"
<< info.driverFile << std::endl;
if (exists(path{info.driverRoot})) {
std::cout << "Driver root exists" << std::endl;
}
if (exists(path{info.driverFile})) {
std::cout << "Driver file exists" << std::endl;
}
#endif
if (exists(path{info.driverRoot}) &&
exists(path{info.driverFile})) {
info.found = true;
return info;
}
}
info = DriverLocationInfo{};
return info;
}
std::string getToolLocation(std::string const &toolName,
std::string const &steamVrRoot) {
std::vector<std::string> searchPath;
if (!steamVrRoot.empty()) {
searchPath = {steamVrRoot};
} else {
searchPath = getSteamVRRoots();
}
for (auto &root : searchPath) {
auto p = path{root};
p /= "bin";
p /= getPlatformDirname();
p /= (toolName + TOOL_EXTENSION);
if (exists(p)) {
return p.string();
}
}
return std::string{};
}
ConfigDirs findConfigDirs(std::string const & /*steamVrRoot*/,
std::string const &driver) {
ConfigDirs ret;
auto json = getPathConfig();
auto const &configLocations = json["config"];
if (!configLocations.isArray()) {
return ret;
}
for (auto &configDir : configLocations) {
auto configPath = path{configDir.asString()};
if (!exists(configPath)) {
continue;
}
ret.rootConfigDir = configPath.string();
ret.driverConfigDir = (configPath / path{driver}).string();
ret.valid = true;
return ret;
}
ret = ConfigDirs{};
return ret;
}
#if 0
ConfigDirs findConfigDirs(std::string const &steamVrRoot,
std::string const &driver) {
static const auto LINE_PREFIX = "Config path = ";
ConfigDirs ret;
bool foundLine = false;
auto vrpathregFile =
osvr::vive::getToolLocation("vrpathreg", steamVrRoot);
if (vrpathregFile.empty()) {
return ret;
}
std::string pathLine;
{
using namespace boost::process;
using namespace boost::process::initializers;
using namespace boost::iostreams;
auto p = create_pipe();
file_descriptor_sink sink(p.sink, close_handle);
auto c = execute(run_exe(vrpathregFile),
#ifdef _WIN32
show_window(SW_HIDE),
#endif
bind_stdout(sink), bind_stderr(sink));
file_descriptor_source source(p.source, close_handle);
stream<file_descriptor_source> is(source);
for (int i = 0; i < 4; ++i) {
std::getline(is, pathLine);
if (pathLine.find(LINE_PREFIX) != std::string::npos) {
foundLine = true;
break;
}
}
wait_for_exit(c);
}
if (!foundLine) {
return ret;
}
while (!pathLine.empty() &&
(pathLine.back() == '\r' || pathLine.back() == '\n')) {
pathLine.pop_back();
}
#ifdef VIVELOADER_VERBOSE
std::cout << "Path line is: " << pathLine << std::endl;
#endif
auto prefixLoc = pathLine.find(LINE_PREFIX);
auto sub = pathLine.substr(std::string(LINE_PREFIX).size() + prefixLoc);
#ifdef VIVELOADER_VERBOSE
std::cout << "substring is: " << sub << std::endl;
#endif
ret.rootConfigDir = sub;
ret.driverConfigDir = sub + PATH_SEP + driver;
if (exists(path{ret.rootConfigDir})) {
#ifdef VIVELOADER_VERBOSE
std::cout << "root config dir exists" << std::endl;
#endif
ret.valid = true;
}
return ret;
}
#endif
} // namespace vive
} // namespace osvr
<commit_msg>Remove boost::process-using code from FindDriver<commit_after>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Razer 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.
// Internal Includes
#include "FindDriver.h"
// Library/third-party includes
#include <boost/iostreams/stream.hpp>
#include <json/reader.h>
#include <json/value.h>
#include <osvr/Util/Finally.h>
#include <osvr/Util/PlatformConfig.h>
// Standard includes
#include <iostream>
#include <limits.h>
#include <vector>
#if _MSC_VER >= 1800
#include <filesystem>
#else
#include <boost/filesystem.hpp>
#endif
#if defined(OSVR_WINDOWS)
#include <shlobj.h>
#endif
#undef VIVELOADER_VERBOSE
using osvr::util::finally;
namespace osvr {
namespace vive {
#if defined(OSVR_WINDOWS)
static const auto PLATFORM_DIRNAME_BASE = "win";
static const auto DRIVER_EXTENSION = ".dll";
static const auto TOOL_EXTENSION = ".exe";
static const auto PATH_SEP = "\\";
#elif defined(OSVR_MACOSX)
/// @todo Note that there are no 64-bit steamvr runtimes or drivers on OS X
static const auto PLATFORM_DIRNAME_BASE = "osx";
static const auto DRIVER_EXTENSION = ".dylib";
static const auto TOOL_EXTENSION = "";
static const auto PATH_SEP = "/";
#elif defined(OSVR_LINUX)
static const auto PLATFORM_DIRNAME_BASE = "linux";
static const auto DRIVER_EXTENSION = ".so";
static const auto TOOL_EXTENSION = "";
static const auto PATH_SEP = "/";
#else
#error "Sorry, Valve does not produce a SteamVR runtime for your platform."
#endif
#if defined(OSVR_USING_FILESYSTEM_TR2)
using std::tr2::sys::path;
using std::tr2::sys::wpath;
using std::tr2::sys::exists;
#elif defined(OSVR_USING_BOOST_FILESYSTEM)
using boost::filesystem::path;
using boost::filesystem::exists;
#endif
#ifdef OSVR_MACOSX
inline std::string getPlatformBitSuffix() {
// they use universal binaries but stick them in "32"
return "32";
}
#else
inline std::string getPlatformBitSuffix() {
return std::to_string(sizeof(void *) * CHAR_BIT);
}
#endif
inline std::string getPlatformDirname() {
return PLATFORM_DIRNAME_BASE + getPlatformBitSuffix();
}
inline void parsePathConfigFile(std::istream &is, Json::Value &ret) {
Json::Reader reader;
if (!reader.parse(is, ret)) {
std::cerr << "Error parsing file containing path configuration - "
"have you run SteamVR yet?"
<< std::endl;
std::cerr << reader.getFormattedErrorMessages() << std::endl;
}
}
#if defined(OSVR_WINDOWS)
inline Json::Value getPathConfig() {
PWSTR outString = nullptr;
Json::Value ret;
// It's OK to use Vista+ stuff here, since openvr_api.dll uses Vista+
// stuff too.
auto hr =
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &outString);
if (!SUCCEEDED(hr)) {
std::cerr << "Could not get local app data directory!" << std::endl;
return ret;
}
// Free the string returned when we're all done.
auto freeString = [&] { CoTaskMemFree(outString); };
// Build the path to the file.
auto vrPaths =
wpath(outString) / wpath(L"openvr") / wpath(L"openvrpaths.vrpath");
std::ifstream is(vrPaths.string());
if (!is) {
std::wcerr << L"Could not open file containing path configuration "
L"- have you run SteamVR yet? "
<< vrPaths << L"\n";
return ret;
}
parsePathConfigFile(is, ret);
return ret;
}
#elif defined(OSVR_MACOSX)
inline Json::Value getPathConfig() {
#error "implementation not complete"
}
#elif defined(OSVR_LINUX)
inline Json::Value getPathConfig() {
#error "implementation not complete"
}
#endif
#if 0
#if defined(OSVR_WINDOWS)
inline std::vector<std::string> getSteamVRRoots() {
/// @todo make this better - there's Windows API for that.
return std::vector<std::string>{
std::string{"C:\\Program Files\\Steam\\steamapps\\common\\SteamVR"},
std::string{
"C:\\Program Files (x86)\\Steam\\steamapps\\common\\SteamVR"}};
}
#elif defined(OSVR_MACOSX)
inline std::vector<std::string> getSteamVRRoots() {
#error "implementation not complete"
}
#elif defined(OSVR_LINUX)
inline std::vector<std::string> getSteamVRRoots() {
#error "implementation not complete"
}
#endif
#endif
inline std::vector<std::string> getSteamVRRoots(Json::Value const &json) {
std::vector<std::string> ret;
auto &runtimes = json["runtime"];
if (!runtimes.isArray()) {
return ret;
}
for (auto &runtime : runtimes) {
ret.emplace_back(runtime.asString());
}
return ret;
}
inline std::vector<std::string> getSteamVRRoots() {
return getSteamVRRoots(getPathConfig());
}
inline void computeDriverRootAndFilePath(DriverLocationInfo &info,
std::string const &driver) {
auto p = path{info.steamVrRoot};
p /= "drivers";
p /= driver;
p /= "bin";
p /= getPlatformDirname();
info.driverRoot = p.string();
p /= ("driver_" + driver + DRIVER_EXTENSION);
info.driverFile = p.string();
}
DriverLocationInfo findDriver(std::string const &driver) {
DriverLocationInfo info;
for (auto &root : getSteamVRRoots()) {
info.steamVrRoot = root;
info.driverName = driver;
computeDriverRootAndFilePath(info, driver);
#ifdef VIVELOADER_VERBOSE
std::cout << "Will try to load driver from:\n"
<< info.driverFile << std::endl;
if (exists(path{info.driverRoot})) {
std::cout << "Driver root exists" << std::endl;
}
if (exists(path{info.driverFile})) {
std::cout << "Driver file exists" << std::endl;
}
#endif
if (exists(path{info.driverRoot}) &&
exists(path{info.driverFile})) {
info.found = true;
return info;
}
}
info = DriverLocationInfo{};
return info;
}
std::string getToolLocation(std::string const &toolName,
std::string const &steamVrRoot) {
std::vector<std::string> searchPath;
if (!steamVrRoot.empty()) {
searchPath = {steamVrRoot};
} else {
searchPath = getSteamVRRoots();
}
for (auto &root : searchPath) {
auto p = path{root};
p /= "bin";
p /= getPlatformDirname();
p /= (toolName + TOOL_EXTENSION);
if (exists(p)) {
return p.string();
}
}
return std::string{};
}
ConfigDirs findConfigDirs(std::string const & /*steamVrRoot*/,
std::string const &driver) {
ConfigDirs ret;
auto json = getPathConfig();
auto const &configLocations = json["config"];
if (!configLocations.isArray()) {
return ret;
}
for (auto &configDir : configLocations) {
auto configPath = path{configDir.asString()};
if (!exists(configPath)) {
continue;
}
ret.rootConfigDir = configPath.string();
ret.driverConfigDir = (configPath / path{driver}).string();
ret.valid = true;
return ret;
}
ret = ConfigDirs{};
return ret;
}
} // namespace vive
} // namespace osvr
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU 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. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/io/ImagePNG.h>
#include <sofa/helper/system/FileRepository.h>
#include <gtest/gtest.h>
namespace sofa {
class ImagePNG_test : public ::testing::Test
{
protected:
ImagePNG_test() {}
void SetUp()
{
sofa::helper::system::DataRepository.addFirstPath(FRAMEWORK_TEST_RESOURCES_DIR);
}
void TearDown()
{
sofa::helper::system::DataRepository.removePath(FRAMEWORK_TEST_RESOURCES_DIR);
}
struct ImagePNGTestData
{
std::string filename;
unsigned int width;
unsigned int height;
const unsigned char* data;
ImagePNGTestData(const std::string& filename, unsigned int width, unsigned int height
, unsigned int bpp, const unsigned char* data)
: filename(filename), width(width), height(height), data(data)
{
}
void testBench()
{
sofa::helper::io::ImagePNG img;
EXPECT_TRUE(img.load(filename));
EXPECT_EQ(width, img.getWidth());
EXPECT_EQ(height, img.getHeight());
EXPECT_EQ(width*height, img.getPixelCount());
const unsigned char* testdata = img.getPixels();
EXPECT_TRUE(0 == std::memcmp(data, testdata, sizeof(data)));
}
};
};
TEST_F(ImagePNG_test, ImagePNG_NoFile)
{
sofa::helper::io::ImagePNG imgNoFile;
EXPECT_FALSE(imgNoFile.load("image/randomnamewhichdoesnotexist.png"));
}
TEST_F(ImagePNG_test, ImagePNG_NoImg)
{
sofa::helper::io::ImagePNG imgNoImage;
EXPECT_FALSE(imgNoImage.load("image/imagetest_noimage.png"));
}
TEST_F(ImagePNG_test, ImagePNG_BlackWhite)
{
unsigned int width = 800;
unsigned int height = 600;
unsigned int bpp = 3;
unsigned int totalsize = width*height*bpp;
unsigned char* imgdata = new unsigned char[totalsize];
//half image (800x300) is black the other one is white
std::fill(imgdata, imgdata + (800*300*3), 0);
std::fill(imgdata + (800 * 300 * 3), imgdata + (800 * 600 * 3), 255);
ImagePNGTestData imgBW("image/imagetest_blackwhite.png", width, height, bpp, imgdata);
imgBW.testBench();
}
}// namespace sofa
<commit_msg>[SofaKernel] Framework_test: fixing ImagePNG_test<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU 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. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/io/ImagePNG.h>
#include <sofa/helper/system/FileRepository.h>
#include <cstring>
#include <gtest/gtest.h>
namespace sofa {
class ImagePNG_test : public ::testing::Test
{
protected:
ImagePNG_test() {}
void SetUp()
{
sofa::helper::system::DataRepository.addFirstPath(FRAMEWORK_TEST_RESOURCES_DIR);
}
void TearDown()
{
sofa::helper::system::DataRepository.removePath(FRAMEWORK_TEST_RESOURCES_DIR);
}
struct ImagePNGTestData
{
std::string filename;
unsigned int width;
unsigned int height;
unsigned int bpp;
const unsigned char* data;
ImagePNGTestData(const std::string& filename, unsigned int width, unsigned int height
, unsigned int bpp, const unsigned char* data)
: filename(filename), width(width), height(height), bpp(bpp), data(data)
{
}
void testBench()
{
sofa::helper::io::ImagePNG img;
EXPECT_TRUE(img.load(filename));
EXPECT_EQ(width, img.getWidth());
EXPECT_EQ(height, img.getHeight());
EXPECT_EQ(width*height, img.getPixelCount());
EXPECT_EQ(bpp, img.getBytesPerPixel());
const unsigned char* testdata = img.getPixels();
EXPECT_TRUE(0 == std::memcmp(data, testdata, width*height*bpp));
}
};
};
TEST_F(ImagePNG_test, ImagePNG_NoFile)
{
sofa::helper::io::ImagePNG imgNoFile;
EXPECT_FALSE(imgNoFile.load("image/randomnamewhichdoesnotexist.png"));
}
TEST_F(ImagePNG_test, ImagePNG_NoImg)
{
sofa::helper::io::ImagePNG imgNoImage;
EXPECT_FALSE(imgNoImage.load("image/imagetest_noimage.png"));
}
TEST_F(ImagePNG_test, ImagePNG_BlackWhite)
{
unsigned int width = 800;
unsigned int height = 600;
unsigned int bpp = 3;
unsigned int totalsize = width*height*bpp;
unsigned char* imgdata = new unsigned char[totalsize];
//half image (800x300) is black the other one is white
std::fill(imgdata, imgdata + (800*300*3), 0);
std::fill(imgdata + (800 * 300 * 3), imgdata + (800 * 600 * 3), 255);
ImagePNGTestData imgBW("image/imagetest_blackwhite.png", width, height, bpp, imgdata);
imgBW.testBench();
}
}// namespace sofa
<|endoftext|>
|
<commit_before>/*****************************************************************************/
/**
* @file NormalizedDeviceCoordinate.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id$
*/
/*****************************************************************************/
#include "NormalizedDeviceCoordinate.h"
#include "WindowCoordinate.h"
#include "CameraCoordinate.h"
#include <kvs/Camera>
namespace kvs
{
/*===========================================================================*/
/**
* @brief Constructs a new NormalizedDeviceCoordinate class.
* @param position [in] position in normalized device coordinates
*/
/*===========================================================================*/
NormalizedDeviceCoordinate::NormalizedDeviceCoordinate( const kvs::Vec3& position ):
m_position( position )
{
}
/*===========================================================================*/
/**
* @brief Transforms normalized device coordinates to world coordinates.
* @param x [in] x coordinate value of left corner of the viewport
* @param y [in] y coordinate value of left corner of the viewport
* @param width [in] width of the viewport
* @param height [in] height of the viewport
* @return world coordinates
*/
/*===========================================================================*/
const WindowCoordinate NormalizedDeviceCoordinate::toWindowCoordinate(
const int x,
const int y,
const size_t width,
const size_t height ) const
{
const float px = ( m_position[0] + 1.0f ) * width * 0.5f + x;
const float py = ( m_position[1] + 1.0f ) * height * 0.5f + y;
const float pz = WindowCoordinate::CalculateDepth( ( m_position[2] + 1.0f ) / 2.0f );
const kvs::Vec3 position( px, py, pz );
return WindowCoordinate( position, x, y, width, height );
}
/*===========================================================================*/
/**
* @brief Transforms normalized device coordinates to camera coordinates.
* @param camera [in] pointer to a camera defines camera coordinates
* @return camera coordinates
*/
/*===========================================================================*/
const CameraCoordinate NormalizedDeviceCoordinate::toCameraCoordinate( const kvs::Camera* camera ) const
{
const kvs::Xform xform( camera->projectionMatrix() * camera->viewingMatrix() );
const kvs::Vec3 position = xform.inverse().project( m_position );
return CameraCoordinate( position, camera );
}
} // end of namespace kvs
<commit_msg>Fixed a problem.<commit_after>/*****************************************************************************/
/**
* @file NormalizedDeviceCoordinate.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id$
*/
/*****************************************************************************/
#include "NormalizedDeviceCoordinate.h"
#include "WindowCoordinate.h"
#include "CameraCoordinate.h"
#include <kvs/Camera>
namespace kvs
{
/*===========================================================================*/
/**
* @brief Constructs a new NormalizedDeviceCoordinate class.
* @param position [in] position in normalized device coordinates
*/
/*===========================================================================*/
NormalizedDeviceCoordinate::NormalizedDeviceCoordinate( const kvs::Vec3& position ):
m_position( position )
{
}
/*===========================================================================*/
/**
* @brief Transforms normalized device coordinates to world coordinates.
* @param x [in] x coordinate value of left corner of the viewport
* @param y [in] y coordinate value of left corner of the viewport
* @param width [in] width of the viewport
* @param height [in] height of the viewport
* @return world coordinates
*/
/*===========================================================================*/
const WindowCoordinate NormalizedDeviceCoordinate::toWindowCoordinate(
const int x,
const int y,
const size_t width,
const size_t height ) const
{
const float px = ( m_position[0] + 1.0f ) * width * 0.5f + x;
const float py = ( m_position[1] + 1.0f ) * height * 0.5f + y;
const float pz = WindowCoordinate::CalculateDepth( ( m_position[2] + 1.0f ) / 2.0f );
const kvs::Vec3 position( px, py, pz );
return WindowCoordinate( position, x, y, width, height );
}
/*===========================================================================*/
/**
* @brief Transforms normalized device coordinates to camera coordinates.
* @param camera [in] pointer to a camera defines camera coordinates
* @return camera coordinates
*/
/*===========================================================================*/
const CameraCoordinate NormalizedDeviceCoordinate::toCameraCoordinate( const kvs::Camera* camera ) const
{
const kvs::Xform xform( camera->projectionMatrix() );
const kvs::Vec3 position = xform.inverse().project( m_position );
return CameraCoordinate( position, camera );
}
} // end of namespace kvs
<|endoftext|>
|
<commit_before>#include <catch.hpp>
#include <lua.hpp>
#include <luwra.hpp>
#include <cstring>
#include <string>
#include <utility>
#include <type_traits>
template <typename I>
struct NumericTest {
static
void test(lua_State* state) {
const I max_value = std::numeric_limits<I>::max();
const I min_value = std::numeric_limits<I>::lowest();
const I avg_value = (max_value + min_value) / 2;
// Largest value
CHECK(luwra::push(state, max_value) == 1);
CHECK(luwra::read<I>(state, -1) == max_value);
// Lowest value
CHECK(luwra::push(state, min_value) == 1);
CHECK(luwra::read<I>(state, -1) == min_value);
// Average value
CHECK(luwra::push(state, avg_value) == 1);
CHECK(luwra::read<I>(state, -1) == avg_value);
}
};
struct TautologyTest {
static
void test(lua_State*) {}
};
template <typename B, typename I>
using SelectNumericTest =
typename std::conditional<
luwra::internal::NumericContainedValueBase<I, B>::qualifies,
NumericTest<I>,
TautologyTest
>::type;
TEST_CASE("types_numeric") {
lua_State* state = luaL_newstate();
// Integer-based types
SelectNumericTest<lua_Integer, signed char>::test(state);
SelectNumericTest<lua_Integer, unsigned char>::test(state);
SelectNumericTest<lua_Integer, signed short>::test(state);
SelectNumericTest<lua_Integer, unsigned short>::test(state);
SelectNumericTest<lua_Integer, signed int>::test(state);
SelectNumericTest<lua_Integer, unsigned int>::test(state);
SelectNumericTest<lua_Integer, signed long int>::test(state);
SelectNumericTest<lua_Integer, unsigned long int>::test(state);
SelectNumericTest<lua_Integer, signed long long int>::test(state);
SelectNumericTest<lua_Integer, unsigned long long int>::test(state);
// Number-based types
SelectNumericTest<lua_Number, float>::test(state);
SelectNumericTest<lua_Number, double>::test(state);
SelectNumericTest<lua_Number, long double>::test(state);
lua_close(state);
}
TEST_CASE("types_string") {
lua_State* state = luaL_newstate();
const char* test_cstr = "Luwra Test String";
std::string test_str(test_cstr);
// Safety first
REQUIRE(test_str == test_cstr);
// Push both strings
REQUIRE(luwra::push(state, test_cstr) == 1);
REQUIRE(luwra::push(state, test_str) == 1);
// They must be equal to Lua
REQUIRE(luwra::equal(state, -1, -2));
// Extraction as C string must not change the string's value
const char* l_cstr1 = luwra::read<const char*>(state, -1);
const char* l_cstr2 = luwra::read<const char*>(state, -2);
REQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);
REQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);
REQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);
REQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);
REQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);
// Extraction as C++ string must not change the string's value
std::string l_str1 = luwra::read<std::string>(state, -1);
std::string l_str2 = luwra::read<std::string>(state, -2);
REQUIRE(l_str1 == test_cstr);
REQUIRE(l_str2 == test_cstr);
REQUIRE(test_str == l_str1);
REQUIRE(test_str == l_str2);
REQUIRE(l_str1 == l_str2);
lua_close(state);
}
TEST_CASE("types_tuple") {
lua_State* state = luaL_newstate();
int a = 13;
std::string b("Hello");
float c = 0.37;
// Push normal tuple
auto tuple = std::make_tuple(a, b, c);
REQUIRE(luwra::push(state, tuple) == 3);
// Push nested tuple
auto tuple_nested = std::make_tuple(a, b, c, tuple);
REQUIRE(luwra::push(state, tuple_nested) == 6);
lua_close(state);
}
TEST_CASE("types_bool") {
lua_State* state = luaL_newstate();
bool value = true;
REQUIRE(luwra::push(state, value) == 1);
REQUIRE(luwra::read<bool>(state, -1) == value);
lua_close(state);
}
<commit_msg>What are parentheses?<commit_after>#include <catch.hpp>
#include <lua.hpp>
#include <luwra.hpp>
#include <cstring>
#include <string>
#include <utility>
#include <type_traits>
template <typename I>
struct NumericTest {
static
void test(lua_State* state) {
const I max_value = std::numeric_limits<I>::max();
const I min_value = std::numeric_limits<I>::lowest();
const I avg_value = (max_value + min_value) / 2;
// Largest value
CHECK((luwra::push(state, max_value) == 1));
CHECK((luwra::read<I>(state, -1) == max_value));
// Lowest value
CHECK((luwra::push(state, min_value) == 1));
CHECK((luwra::read<I>(state, -1) == min_value));
// Average value
CHECK((luwra::push(state, avg_value) == 1));
CHECK((luwra::read<I>(state, -1) == avg_value));
}
};
struct TautologyTest {
static
void test(lua_State*) {}
};
template <typename B, typename I>
using SelectNumericTest =
typename std::conditional<
luwra::internal::NumericContainedValueBase<I, B>::qualifies,
NumericTest<I>,
TautologyTest
>::type;
TEST_CASE("types_numeric") {
lua_State* state = luaL_newstate();
// Integer-based types
SelectNumericTest<lua_Integer, signed char>::test(state);
SelectNumericTest<lua_Integer, unsigned char>::test(state);
SelectNumericTest<lua_Integer, signed short>::test(state);
SelectNumericTest<lua_Integer, unsigned short>::test(state);
SelectNumericTest<lua_Integer, signed int>::test(state);
SelectNumericTest<lua_Integer, unsigned int>::test(state);
SelectNumericTest<lua_Integer, signed long int>::test(state);
SelectNumericTest<lua_Integer, unsigned long int>::test(state);
SelectNumericTest<lua_Integer, signed long long int>::test(state);
SelectNumericTest<lua_Integer, unsigned long long int>::test(state);
// Number-based types
SelectNumericTest<lua_Number, float>::test(state);
SelectNumericTest<lua_Number, double>::test(state);
SelectNumericTest<lua_Number, long double>::test(state);
lua_close(state);
}
TEST_CASE("types_string") {
lua_State* state = luaL_newstate();
const char* test_cstr = "Luwra Test String";
std::string test_str(test_cstr);
// Safety first
REQUIRE(test_str == test_cstr);
// Push both strings
REQUIRE(luwra::push(state, test_cstr) == 1);
REQUIRE(luwra::push(state, test_str) == 1);
// They must be equal to Lua
REQUIRE(luwra::equal(state, -1, -2));
// Extraction as C string must not change the string's value
const char* l_cstr1 = luwra::read<const char*>(state, -1);
const char* l_cstr2 = luwra::read<const char*>(state, -2);
REQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);
REQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);
REQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);
REQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);
REQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);
// Extraction as C++ string must not change the string's value
std::string l_str1 = luwra::read<std::string>(state, -1);
std::string l_str2 = luwra::read<std::string>(state, -2);
REQUIRE(l_str1 == test_cstr);
REQUIRE(l_str2 == test_cstr);
REQUIRE(test_str == l_str1);
REQUIRE(test_str == l_str2);
REQUIRE(l_str1 == l_str2);
lua_close(state);
}
TEST_CASE("types_tuple") {
lua_State* state = luaL_newstate();
int a = 13;
std::string b("Hello");
float c = 0.37;
// Push normal tuple
auto tuple = std::make_tuple(a, b, c);
REQUIRE(luwra::push(state, tuple) == 3);
// Push nested tuple
auto tuple_nested = std::make_tuple(a, b, c, tuple);
REQUIRE(luwra::push(state, tuple_nested) == 6);
lua_close(state);
}
TEST_CASE("types_bool") {
lua_State* state = luaL_newstate();
bool value = true;
REQUIRE(luwra::push(state, value) == 1);
REQUIRE(luwra::read<bool>(state, -1) == value);
lua_close(state);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 Mohammad Mehdi Saboorian
*
* This is part of moor, a wrapper for libarchive
*
* 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 "archive_writer.hpp"
#include "memory_writer_callback.hpp"
#include <archive.h>
#include <archive_entry.h>
#include <fstream>
#include <stdexcept>
#include <system_error>
#include <sys/types.h>
#include <sys/stat.h>
using namespace moor;
namespace
{
class ScopedReadDisk
{
private:
archive* m_archive;
public:
ScopedReadDisk()
: m_archive(archive_read_disk_new())
{
if (!m_archive)
{
throw std::bad_alloc();
}
}
~ScopedReadDisk()
{
archive_read_close(m_archive);
archive_read_free(m_archive);
}
operator archive*()
{
return m_archive;
}
operator const archive*() const
{
return m_archive;
}
};
}
void ArchiveWriter::checkError(const int err_code,
const bool close_before_throw)
{
int archiveErrno = 0;
const char* errStr = nullptr;
if (err_code == ARCHIVE_FATAL)
{
archiveErrno = archive_errno(m_archive);
errStr = archive_error_string(m_archive);
if (close_before_throw)
{
close();
}
}
if (err_code != ARCHIVE_OK && err_code != ARCHIVE_WARN)
{
throw std::system_error(archiveErrno,
std::generic_category(),
errStr ? errStr : "");
}
}
ArchiveWriter::ArchiveWriter(const std::string& archive_file_name_,
const Format& format_,
const Filter& filter_)
: Archive(archive_write_new(), archive_file_name_),
m_entry(archive_entry_new()),
m_format(format_),
m_filter(filter_),
m_open(true)
{
// Set archive format
checkError(archive_write_set_format(m_archive, (int) m_format), true);
// Set archive compression
checkError(archive_write_add_filter(m_archive, (int) m_filter), true);
checkError(archive_write_open_filename(m_archive, cfilename()), true);
}
ArchiveWriter::ArchiveWriter(std::vector<unsigned char>& out_buffer_,
const Format& format_,
const Filter& filter_)
: Archive(archive_write_new()),
m_entry(archive_entry_new()),
m_format(format_),
m_filter(filter_),
m_open(true)
{
// Set archive format
checkError(archive_write_set_format(m_archive, static_cast<int>(m_format)), true);
// Set archive filter
checkError(archive_write_add_filter(m_archive, static_cast<int>(m_filter)), true);
checkError(write_open_memory(m_archive, &out_buffer_), true);
}
ArchiveWriter::ArchiveWriter(unsigned char* out_buffer_,
size_t* size_,
const Format& format_,
const Filter& filter_)
: Archive(archive_write_new()),
m_entry(archive_entry_new()),
m_format(format_),
m_filter(filter_),
m_open(true)
{
// Set archive format
checkError(archive_write_set_format(m_archive, static_cast<int>(m_format)), true);
// Set archive filter
checkError(archive_write_add_filter(m_archive, static_cast<int>(m_filter)), true);
checkError(archive_write_open_memory(m_archive, out_buffer_, *size_, size_), true);
}
ArchiveWriter::~ArchiveWriter()
{
close();
}
void ArchiveWriter::addHeader(const std::string& entry_name_,
const FileType entry_type_,
const long long size_,
const int permission_)
{
m_entry = archive_entry_clear(m_entry);
archive_entry_set_pathname(m_entry, entry_name_.c_str());
archive_entry_set_perm(m_entry, permission_);
archive_entry_set_filetype(m_entry, static_cast<int>(entry_type_));
archive_entry_set_size(m_entry, size_);
checkError(archive_write_header(m_archive, m_entry));
}
void ArchiveWriter::addHeader(const std::string& filePath, const struct stat* statBuf)
{
ScopedReadDisk a;
m_entry = archive_entry_clear(m_entry);
archive_entry_set_pathname(m_entry, filePath.c_str());
checkError(archive_read_disk_entry_from_file(a, m_entry, -1, statBuf));
checkError(archive_write_header(m_archive, m_entry));
}
void ArchiveWriter::addContent(const char b)
{
archive_write_data(m_archive, &b, 1);
}
void ArchiveWriter::addContent(const void* data, const unsigned long long size)
{
archive_write_data(m_archive, data, size);
}
void ArchiveWriter::addFinish()
{
archive_write_finish_entry(m_archive);
}
void ArchiveWriter::addFile(const std::string& file_path)
{
struct stat file_stat;
if (stat(file_path.c_str(), &file_stat) < 0)
{
throw std::system_error(std::error_code(errno, std::generic_category()));
}
addHeader(file_path, &file_stat);
if (!S_ISREG(file_stat.st_mode))
{
throw std::system_error(std::make_error_code(std::errc::not_supported));
}
std::fstream entry_file(file_path, std::ios::in);
char buf[8192];
while (entry_file.good())
{
entry_file.read(buf, sizeof(buf));
archive_write_data(m_archive, buf, static_cast<size_t>(entry_file.gcount()));
}
entry_file.close();
addFinish();
}
void ArchiveWriter::addFile(const std::string& entry_name,
const void* data,
unsigned long long size)
{
addHeader(entry_name, FileType::Regular, size);
addContent(data, size);
addFinish();
}
void ArchiveWriter::addDirectory(const std::string& directory_name)
{
addHeader(directory_name, FileType::Directory, 0777);
addFinish();
}
void ArchiveWriter::close()
{
if (m_open)
{
m_open = false;
if (m_archive)
{
archive_write_close(m_archive);
archive_write_free(m_archive);
}
if (m_entry)
{
archive_entry_free(m_entry);
}
}
}
<commit_msg>Less C-style casts<commit_after>/*
* Copyright (c) 2013 Mohammad Mehdi Saboorian
*
* This is part of moor, a wrapper for libarchive
*
* 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 "archive_writer.hpp"
#include "memory_writer_callback.hpp"
#include <archive.h>
#include <archive_entry.h>
#include <fstream>
#include <stdexcept>
#include <system_error>
#include <sys/types.h>
#include <sys/stat.h>
using namespace moor;
namespace
{
class ScopedReadDisk
{
private:
archive* m_archive;
public:
ScopedReadDisk()
: m_archive(archive_read_disk_new())
{
if (!m_archive)
{
throw std::bad_alloc();
}
}
~ScopedReadDisk()
{
archive_read_close(m_archive);
archive_read_free(m_archive);
}
operator archive*()
{
return m_archive;
}
operator const archive*() const
{
return m_archive;
}
};
}
void ArchiveWriter::checkError(const int err_code,
const bool close_before_throw)
{
int archiveErrno = 0;
const char* errStr = nullptr;
if (err_code == ARCHIVE_FATAL)
{
archiveErrno = archive_errno(m_archive);
errStr = archive_error_string(m_archive);
if (close_before_throw)
{
close();
}
}
if (err_code != ARCHIVE_OK && err_code != ARCHIVE_WARN)
{
throw std::system_error(archiveErrno,
std::generic_category(),
errStr ? errStr : "");
}
}
ArchiveWriter::ArchiveWriter(const std::string& archive_file_name_,
const Format& format_,
const Filter& filter_)
: Archive(archive_write_new(), archive_file_name_),
m_entry(archive_entry_new()),
m_format(format_),
m_filter(filter_),
m_open(true)
{
// Set archive format
checkError(archive_write_set_format(m_archive, static_cast<int>(m_format)), true);
// Set archive compression
checkError(archive_write_add_filter(m_archive, static_cast<int>(m_filter)), true);
checkError(archive_write_open_filename(m_archive, cfilename()), true);
}
ArchiveWriter::ArchiveWriter(std::vector<unsigned char>& out_buffer_,
const Format& format_,
const Filter& filter_)
: Archive(archive_write_new()),
m_entry(archive_entry_new()),
m_format(format_),
m_filter(filter_),
m_open(true)
{
// Set archive format
checkError(archive_write_set_format(m_archive, static_cast<int>(m_format)), true);
// Set archive filter
checkError(archive_write_add_filter(m_archive, static_cast<int>(m_filter)), true);
checkError(write_open_memory(m_archive, &out_buffer_), true);
}
ArchiveWriter::ArchiveWriter(unsigned char* out_buffer_,
size_t* size_,
const Format& format_,
const Filter& filter_)
: Archive(archive_write_new()),
m_entry(archive_entry_new()),
m_format(format_),
m_filter(filter_),
m_open(true)
{
// Set archive format
checkError(archive_write_set_format(m_archive, static_cast<int>(m_format)), true);
// Set archive filter
checkError(archive_write_add_filter(m_archive, static_cast<int>(m_filter)), true);
checkError(archive_write_open_memory(m_archive, out_buffer_, *size_, size_), true);
}
ArchiveWriter::~ArchiveWriter()
{
close();
}
void ArchiveWriter::addHeader(const std::string& entry_name_,
const FileType entry_type_,
const long long size_,
const int permission_)
{
m_entry = archive_entry_clear(m_entry);
archive_entry_set_pathname(m_entry, entry_name_.c_str());
archive_entry_set_perm(m_entry, permission_);
archive_entry_set_filetype(m_entry, static_cast<int>(entry_type_));
archive_entry_set_size(m_entry, size_);
checkError(archive_write_header(m_archive, m_entry));
}
void ArchiveWriter::addHeader(const std::string& filePath, const struct stat* statBuf)
{
ScopedReadDisk a;
m_entry = archive_entry_clear(m_entry);
archive_entry_set_pathname(m_entry, filePath.c_str());
checkError(archive_read_disk_entry_from_file(a, m_entry, -1, statBuf));
checkError(archive_write_header(m_archive, m_entry));
}
void ArchiveWriter::addContent(const char b)
{
archive_write_data(m_archive, &b, 1);
}
void ArchiveWriter::addContent(const void* data, const unsigned long long size)
{
archive_write_data(m_archive, data, size);
}
void ArchiveWriter::addFinish()
{
archive_write_finish_entry(m_archive);
}
void ArchiveWriter::addFile(const std::string& file_path)
{
struct stat file_stat;
if (stat(file_path.c_str(), &file_stat) < 0)
{
throw std::system_error(std::error_code(errno, std::generic_category()));
}
addHeader(file_path, &file_stat);
if (!S_ISREG(file_stat.st_mode))
{
throw std::system_error(std::make_error_code(std::errc::not_supported));
}
std::fstream entry_file(file_path, std::ios::in);
char buf[8192];
while (entry_file.good())
{
entry_file.read(buf, sizeof(buf));
archive_write_data(m_archive, buf, static_cast<size_t>(entry_file.gcount()));
}
entry_file.close();
addFinish();
}
void ArchiveWriter::addFile(const std::string& entry_name,
const void* data,
unsigned long long size)
{
addHeader(entry_name, FileType::Regular, size);
addContent(data, size);
addFinish();
}
void ArchiveWriter::addDirectory(const std::string& directory_name)
{
addHeader(directory_name, FileType::Directory, 0777);
addFinish();
}
void ArchiveWriter::close()
{
if (m_open)
{
m_open = false;
if (m_archive)
{
archive_write_close(m_archive);
archive_write_free(m_archive);
}
if (m_entry)
{
archive_entry_free(m_entry);
}
}
}
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include <lua.hpp>
#include <luwra.hpp>
#include <cstring>
#include <string>
#include <utility>
#include <type_traits>
template <typename I>
struct NumericTest {
static
void test(lua_State* state) {
const I max_value = std::numeric_limits<I>::max();
const I min_value = std::numeric_limits<I>::lowest();
const I avg_value = (max_value + min_value) / 2;
// Largest value
REQUIRE(luwra::Value<I>::push(state, max_value) == 1);
REQUIRE(luwra::Value<I>::read(state, -1) == max_value);
lua_pop(state, 1);
// Lowest value
REQUIRE(luwra::Value<I>::push(state, min_value) == 1);
REQUIRE(luwra::Value<I>::read(state, -1) == min_value);
lua_pop(state, 1);
// Average value
REQUIRE(luwra::Value<I>::push(state, avg_value) == 1);
REQUIRE(luwra::Value<I>::read(state, -1) == avg_value);
lua_pop(state, 1);
}
};
struct TautologyTest {
static
void test(lua_State*) {}
};
template <typename B, typename I>
using SelectNumericTest =
typename std::conditional<
luwra::internal::NumericContainedValueBase<I, B>::qualifies,
NumericTest<I>,
TautologyTest
>::type;
TEST_CASE("Test Value specialization for numeric C types", "types_numeric") {
lua_State* state = luaL_newstate();
// Integer-based types
SelectNumericTest<lua_Integer, signed short>::test(state);
SelectNumericTest<lua_Integer, unsigned short>::test(state);
SelectNumericTest<lua_Integer, signed int>::test(state);
SelectNumericTest<lua_Integer, unsigned int>::test(state);
SelectNumericTest<lua_Integer, signed long int>::test(state);
SelectNumericTest<lua_Integer, unsigned long int>::test(state);
SelectNumericTest<lua_Integer, signed long long int>::test(state);
SelectNumericTest<lua_Integer, unsigned long long int>::test(state);
// Number-based types
SelectNumericTest<lua_Number, float>::test(state);
SelectNumericTest<lua_Number, double>::test(state);
SelectNumericTest<lua_Number, long double>::test(state);
lua_close(state);
}
TEST_CASE("Test Value specialization for string types", "types_string") {
lua_State* state = luaL_newstate();
const char* test_cstr = "Luwra Test String";
std::string test_str(test_cstr);
// Safety first
REQUIRE(test_str == test_cstr);
// Push both strings
REQUIRE(luwra::Value<const char*>::push(state, test_cstr) == 1);
REQUIRE(luwra::Value<std::string>::push(state, test_str) == 1);
// They must be equal to Lua
REQUIRE(lua_compare(state, -1, -2, LUA_OPEQ));
// Extraction as C string must not change the string's value
const char* l_cstr1 = luwra::Value<const char*>::read(state, -1);
const char* l_cstr2 = luwra::Value<const char*>::read(state, -2);
REQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);
REQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);
REQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);
REQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);
REQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);
// Extraction as C++ string must not change the string's value
std::string l_str1 = luwra::Value<std::string>::read(state, -1);
std::string l_str2 = luwra::Value<std::string>::read(state, -2);
REQUIRE(l_str1 == test_cstr);
REQUIRE(l_str2 == test_cstr);
REQUIRE(test_str == l_str1);
REQUIRE(test_str == l_str2);
REQUIRE(l_str1 == l_str2);
lua_pop(state, 2);
lua_close(state);
}
<commit_msg>Add tuple test<commit_after>#include "catch.hpp"
#include <lua.hpp>
#include <luwra.hpp>
#include <cstring>
#include <string>
#include <utility>
#include <type_traits>
template <typename I>
struct NumericTest {
static
void test(lua_State* state) {
const I max_value = std::numeric_limits<I>::max();
const I min_value = std::numeric_limits<I>::lowest();
const I avg_value = (max_value + min_value) / 2;
// Largest value
REQUIRE(luwra::Value<I>::push(state, max_value) == 1);
REQUIRE(luwra::Value<I>::read(state, -1) == max_value);
// Lowest value
REQUIRE(luwra::Value<I>::push(state, min_value) == 1);
REQUIRE(luwra::Value<I>::read(state, -1) == min_value);
// Average value
REQUIRE(luwra::Value<I>::push(state, avg_value) == 1);
REQUIRE(luwra::Value<I>::read(state, -1) == avg_value);
}
};
struct TautologyTest {
static
void test(lua_State*) {}
};
template <typename B, typename I>
using SelectNumericTest =
typename std::conditional<
luwra::internal::NumericContainedValueBase<I, B>::qualifies,
NumericTest<I>,
TautologyTest
>::type;
TEST_CASE("Test Value specialization for numeric C types", "types_numeric") {
lua_State* state = luaL_newstate();
// Integer-based types
SelectNumericTest<lua_Integer, signed short>::test(state);
SelectNumericTest<lua_Integer, unsigned short>::test(state);
SelectNumericTest<lua_Integer, signed int>::test(state);
SelectNumericTest<lua_Integer, unsigned int>::test(state);
SelectNumericTest<lua_Integer, signed long int>::test(state);
SelectNumericTest<lua_Integer, unsigned long int>::test(state);
SelectNumericTest<lua_Integer, signed long long int>::test(state);
SelectNumericTest<lua_Integer, unsigned long long int>::test(state);
// Number-based types
SelectNumericTest<lua_Number, float>::test(state);
SelectNumericTest<lua_Number, double>::test(state);
SelectNumericTest<lua_Number, long double>::test(state);
lua_close(state);
}
TEST_CASE("Test Value specialization for string types", "types_string") {
lua_State* state = luaL_newstate();
const char* test_cstr = "Luwra Test String";
std::string test_str(test_cstr);
// Safety first
REQUIRE(test_str == test_cstr);
// Push both strings
REQUIRE(luwra::Value<const char*>::push(state, test_cstr) == 1);
REQUIRE(luwra::Value<std::string>::push(state, test_str) == 1);
// They must be equal to Lua
REQUIRE(lua_compare(state, -1, -2, LUA_OPEQ));
// Extraction as C string must not change the string's value
const char* l_cstr1 = luwra::Value<const char*>::read(state, -1);
const char* l_cstr2 = luwra::Value<const char*>::read(state, -2);
REQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);
REQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);
REQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);
REQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);
REQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);
// Extraction as C++ string must not change the string's value
std::string l_str1 = luwra::Value<std::string>::read(state, -1);
std::string l_str2 = luwra::Value<std::string>::read(state, -2);
REQUIRE(l_str1 == test_cstr);
REQUIRE(l_str2 == test_cstr);
REQUIRE(test_str == l_str1);
REQUIRE(test_str == l_str2);
REQUIRE(l_str1 == l_str2);
lua_close(state);
}
TEST_CASE("Test Value specialization for tuples", "types_tuple") {
lua_State* state = luaL_newstate();
int a = 13;
std::string b("Hello");
float c = 0.37;
// Push normal tuple
auto tuple = std::make_tuple(a, b, c);
REQUIRE(luwra::Value<decltype(tuple)>::push(state, tuple) == 3);
// Push nested tuple
auto tuple_nested = std::make_tuple(a, b, c, tuple);
REQUIRE(luwra::Value<decltype(tuple_nested)>::push(state, tuple_nested) == 6);
lua_close(state);
}
<|endoftext|>
|
<commit_before>#ifndef ALPINOCORPUS_EITHER_HH
#define ALPINOCORPUS_EITHER_HH
namespace alpinocorpus {
/**
* Either is an option type that resembles the Either type in Haskell.
* It's used to indicate that computation results in two possible type:
* the left type or the right type (which could have the same type).
*
* Unfortunately, we do not have algebraic data types in C++, so both
* posibilities are encoded in the same type. The isLeft() and isRight()
* methods can be used to probe whether we have a left or right value.
*
* In error handling the convention is that <tt>Left L</tt> is an error,
* and information about the error is encoded using the type <tt>L</tt>.
* <tt>Right R</tt> is a succesful computation with a result of the type
* <tt>R</tt>.
*/
template <typename L, typename R>
class Either {
public:
static Either left(L left);
static Either right(R right);
bool isLeft();
bool isRight();
L left();
R right();
private:
enum Result { LEFT, RIGHT };
Either(Result result, L left, R right) :
d_result(result), d_left(left), d_right(right) {}
Result d_result;
L d_left;
R d_right;
};
template <typename L, typename R>
inline Either<L, R> Either<L, R>::left(L left)
{
return Either(LEFT, left, R());
}
template <typename L, typename R>
inline Either<L, R> Either<L, R>::right(R right)
{
return Either(RIGHT, L(), right);
}
template <typename L, typename R>
inline bool Either<L, R>::isLeft()
{
return d_result == LEFT;
}
template <typename L, typename R>
inline bool Either<L, R>::isRight()
{
return d_result == RIGHT;
}
template <typename L, typename R>
inline L Either<L, R>::left()
{
return d_left;
}
template <typename L, typename R>
inline R Either<L, R>::right()
{
return d_right;
}
struct Empty {};
}
#endif // ALPINOCORPUS_EITHER_HH
<commit_msg>Either: Add a note about boost::variant.<commit_after>#ifndef ALPINOCORPUS_EITHER_HH
#define ALPINOCORPUS_EITHER_HH
namespace alpinocorpus {
/**
* Either is an option type that resembles the Either type in Haskell.
* It's used to indicate that computation results in two possible type:
* the left type or the right type (which could have the same type).
*
* Unfortunately, we do not have algebraic data types in C++, so both
* posibilities are encoded in the same type. The isLeft() and isRight()
* methods can be used to probe whether we have a left or right value.
*
* In error handling the convention is that <tt>Left L</tt> is an error,
* and information about the error is encoded using the type <tt>L</tt>.
* <tt>Right R</tt> is a succesful computation with a result of the type
* <tt>R</tt>.
*
* Note: we could have used boost::variant, but I think it is kinda
* heavyweight. It does more, but also has a more complex API.
*/
template <typename L, typename R>
class Either {
public:
static Either left(L left);
static Either right(R right);
bool isLeft();
bool isRight();
L left();
R right();
private:
enum Result { LEFT, RIGHT };
Either(Result result, L left, R right) :
d_result(result), d_left(left), d_right(right) {}
Result d_result;
L d_left;
R d_right;
};
template <typename L, typename R>
inline Either<L, R> Either<L, R>::left(L left)
{
return Either(LEFT, left, R());
}
template <typename L, typename R>
inline Either<L, R> Either<L, R>::right(R right)
{
return Either(RIGHT, L(), right);
}
template <typename L, typename R>
inline bool Either<L, R>::isLeft()
{
return d_result == LEFT;
}
template <typename L, typename R>
inline bool Either<L, R>::isRight()
{
return d_result == RIGHT;
}
template <typename L, typename R>
inline L Either<L, R>::left()
{
return d_left;
}
template <typename L, typename R>
inline R Either<L, R>::right()
{
return d_right;
}
struct Empty {};
}
#endif // ALPINOCORPUS_EITHER_HH
<|endoftext|>
|
<commit_before>#ifndef ALEPH_GEOMETRY_COVER_TREE_HH__
#define ALEPH_GEOMETRY_COVER_TREE_HH__
#include <algorithm>
#include <iterator>
#include <limits>
#include <memory>
#include <ostream>
#include <queue>
#include <stack>
#include <stdexcept>
#include <vector>
// FIXME: remove after debugging
#include <iostream>
#include <cassert>
#include <cmath>
namespace aleph
{
namespace geometry
{
/**
@class CoverTree
@brief Generic cover tree data structure
This class models a cover tree data structure, as described in the
paper "Cover trees for nearest neighbor" by Beygelzimer et al.; an
implementation is given at:
http://hunch.net/~jl/projects/cover_tree/cover_tree.html
This implementation attempts to be as generic as possible. It uses
the simplified description of the cover tree, as given by Izbicki,
Shelton in "Faster Cover Trees".
*/
template <class Point, class Metric> class CoverTree
{
public:
/**
Covering constant of the cover tree. It might make sense to change
this later on in order to improve performance. Some papers set the
constant to `1.3`.
*/
constexpr static const double coveringConstant = 2.0;
class Node
{
public:
/** Creates a new node that stores a point */
Node( const Point& point, long level )
: _point( point )
, _level( level )
{
}
/** Calculates current covering distance of the node */
double coveringDistance() const noexcept
{
return std::pow( coveringConstant, static_cast<double>( _level ) );
}
/** @returns true if the node is a leaf node */
bool isLeaf() const noexcept
{
return _children.empty();
}
void insert( const Point& p )
{
auto d = Metric()( _point, p );
std::cerr << __PRETTY_FUNCTION__ << ": Covering distance = " << this->coveringDistance() << "\n";
std::cerr << __PRETTY_FUNCTION__ << ": Distance from point to root = " << d << "\n";
if( d > this->coveringDistance() )
{
while( d > 2 * this->coveringDistance() )
{
std::cerr << __PRETTY_FUNCTION__ << ": Distance is bigger than covering distance; need to raise level of tree\n";
// -----------------------------------------------------------
//
// Find a leaf node that can become the new root node with
// a raised level.
std::stack<Node*> nodes;
nodes.push( this );
Node* leaf = nullptr;
Node* parent = nullptr;
while( !nodes.empty() )
{
auto&& node = nodes.top();
for( auto&& child : parent->_children )
{
if( child->isLeaf() )
{
leaf = child.get();
parent = node;
break;
}
}
nodes.pop();
}
// There is no leaf, so there is nothing to do and we just
// skip to the bottom where we add the current node as the
// new root of the tree.
if( !leaf )
break;
assert( leaf );
assert( parent );
// Remove leaf from subtree ----------------------------------
//
// The previous tree does not contain the leaf node any more,
// and it can be added as the new root node.
std::unique_ptr<Node> leaf_ptr( nullptr );
parent->_children.erase(
std::remove_if(
parent->_children.begin(), parent->_children.end(),
[&leaf, &leaf_ptr] ( std::unique_ptr<Node>& child )
{
if( child.get() == leaf )
{
leaf_ptr = std::move( child );
return true;
}
return false;
}
),
parent->_children.end()
);
// Make leaf node the new root node --------------------------
//
// Notice that this does increase the level of the current
// root. This has to be adjusted for.
auto oldRoot
= std::unique_ptr<Node>( new Node( this->_point, this->_level ) );
for( auto&& child : _children )
oldRoot->_children.push_back( std::move( child ) );
_point = leaf->_point;
_level = _level + 1;
_children.clear();
_children.push_back( std::move( oldRoot ) );
}
// Make current point the new root -----------------------------
auto oldRoot
= std::unique_ptr<Node>( new Node( this->_point, this->_level ) );
for( auto&& child : _children )
oldRoot->_children.push_back( std::move( child ) );
_point = p;
_level = _level + 1;
_children.clear();
_children.push_back( std::move( oldRoot ) );
return;
}
return insert_( p );
}
/**
Auxiliary function for performing the recursive insertion of a new
node into the tree.
*/
void insert_( const Point& p )
{
for( auto&& child : _children )
{
auto d = Metric()( child->_point, p );
if( d <= child->coveringDistance() )
{
std::cerr << __PRETTY_FUNCTION__ << ": Recursive enumeration of the tree\n";
// We found a node in which the new point can be inserted
// *without* violating the covering invariant.
child->insert_( p );
return;
}
}
// Add the new point as a child of the current root node. Note the
// level adjustment.
_children.push_back( std::unique_ptr<Node>( new Node( p, _level - 1 ) ) );
}
Point _point; //< The point stored in the node
long _level; //< The level of the node
/**
All children of the node. Their order depends on the insertion
order into the data set.
*/
std::vector< std::unique_ptr<Node> > _children;
};
/**
Inserts a new point into the cover tree. If the tree is empty,
the new point will become the root of the tree. Else, it shall
be inserted according to the covering invariant.
*/
void insert( const Point& p )
{
if( !_root )
_root = std::unique_ptr<Node>( new Node(p,1) );
else
_root->insert( p );
}
// Pretty-printing function for the tree; this is only meant for
// debugging purposes and could conceivably be implemented using
// `std::ostream`.
void print( std::ostream& o )
{
std::queue<const Node*> nodes;
nodes.push( _root.get() );
while( !nodes.empty() )
{
{
auto n = nodes.size();
for( decltype(n) i = 0; i < n; i++ )
{
auto&& node = nodes.front();
if( i == 0 )
o << node->_level << ": ";
else
o << " ";
o << node->_point;
for( auto&& child : node->_children )
nodes.push( child.get() );
nodes.pop();
}
o << "\n";
}
}
}
private:
/** Root pointer of the tree */
std::unique_ptr<Node> _root;
};
} // namespace geometry
} // namespace aleph
#endif
<commit_msg>Documented tree creation<commit_after>#ifndef ALEPH_GEOMETRY_COVER_TREE_HH__
#define ALEPH_GEOMETRY_COVER_TREE_HH__
#include <algorithm>
#include <iterator>
#include <limits>
#include <memory>
#include <ostream>
#include <queue>
#include <stack>
#include <stdexcept>
#include <vector>
// FIXME: remove after debugging
#include <iostream>
#include <cassert>
#include <cmath>
namespace aleph
{
namespace geometry
{
/**
@class CoverTree
@brief Generic cover tree data structure
This class models a cover tree data structure, as described in the
paper "Cover trees for nearest neighbor" by Beygelzimer et al.; an
implementation is given at:
http://hunch.net/~jl/projects/cover_tree/cover_tree.html
This implementation attempts to be as generic as possible. It uses
the simplified description of the cover tree, as given by Izbicki,
Shelton in "Faster Cover Trees".
*/
template <class Point, class Metric> class CoverTree
{
public:
/**
Covering constant of the cover tree. It might make sense to change
this later on in order to improve performance. Some papers set the
constant to `1.3`.
*/
constexpr static const double coveringConstant = 2.0;
class Node
{
public:
/** Creates a new node that stores a point */
Node( const Point& point, long level )
: _point( point )
, _level( level )
{
}
/** Calculates current covering distance of the node */
double coveringDistance() const noexcept
{
return std::pow( coveringConstant, static_cast<double>( _level ) );
}
/** @returns true if the node is a leaf node */
bool isLeaf() const noexcept
{
return _children.empty();
}
void insert( const Point& p )
{
auto d = Metric()( _point, p );
std::cerr << __PRETTY_FUNCTION__ << ": Covering distance = " << this->coveringDistance() << "\n";
std::cerr << __PRETTY_FUNCTION__ << ": Distance from point to root = " << d << "\n";
if( d > this->coveringDistance() )
{
while( d > 2 * this->coveringDistance() )
{
std::cerr << __PRETTY_FUNCTION__ << ": Distance is bigger than covering distance; need to raise level of tree\n";
// -----------------------------------------------------------
//
// Find a leaf node that can become the new root node with
// a raised level.
std::stack<Node*> nodes;
nodes.push( this );
Node* leaf = nullptr;
Node* parent = nullptr;
while( !nodes.empty() )
{
auto&& node = nodes.top();
for( auto&& child : parent->_children )
{
if( child->isLeaf() )
{
leaf = child.get();
parent = node;
break;
}
}
nodes.pop();
}
// There is no leaf, so there is nothing to do and we just
// skip to the bottom where we add the current node as the
// new root of the tree.
if( !leaf )
break;
assert( leaf );
assert( parent );
// Remove leaf from subtree ----------------------------------
//
// The previous tree does not contain the leaf node any more,
// and it can be added as the new root node.
std::unique_ptr<Node> leaf_ptr( nullptr );
parent->_children.erase(
std::remove_if(
parent->_children.begin(), parent->_children.end(),
[&leaf, &leaf_ptr] ( std::unique_ptr<Node>& child )
{
if( child.get() == leaf )
{
leaf_ptr = std::move( child );
return true;
}
return false;
}
),
parent->_children.end()
);
// Make leaf node the new root node --------------------------
//
// Notice that this does increase the level of the current
// root. This has to be adjusted for.
auto oldRoot
= std::unique_ptr<Node>( new Node( this->_point, this->_level ) );
for( auto&& child : _children )
oldRoot->_children.push_back( std::move( child ) );
_point = leaf->_point;
_level = _level + 1;
_children.clear();
_children.push_back( std::move( oldRoot ) );
}
// Make current point the new root -----------------------------
//
// So far, the new point has not yet been inserted into the
// tree. This needs to be done now while the cover is valid
// again.
auto oldRoot
= std::unique_ptr<Node>( new Node( this->_point, this->_level ) );
for( auto&& child : _children )
oldRoot->_children.push_back( std::move( child ) );
_point = p;
_level = _level + 1;
_children.clear();
_children.push_back( std::move( oldRoot ) );
return;
}
return insert_( p );
}
/**
Auxiliary function for performing the recursive insertion of a new
node into the tree.
*/
void insert_( const Point& p )
{
for( auto&& child : _children )
{
auto d = Metric()( child->_point, p );
if( d <= child->coveringDistance() )
{
std::cerr << __PRETTY_FUNCTION__ << ": Recursive enumeration of the tree\n";
// We found a node in which the new point can be inserted
// *without* violating the covering invariant.
child->insert_( p );
return;
}
}
// Add the new point as a child of the current root node. Note the
// level adjustment.
_children.push_back( std::unique_ptr<Node>( new Node( p, _level - 1 ) ) );
}
Point _point; //< The point stored in the node
long _level; //< The level of the node
/**
All children of the node. Their order depends on the insertion
order into the data set.
*/
std::vector< std::unique_ptr<Node> > _children;
};
/**
Inserts a new point into the cover tree. If the tree is empty,
the new point will become the root of the tree. Else, it shall
be inserted according to the covering invariant.
*/
void insert( const Point& p )
{
if( !_root )
_root = std::unique_ptr<Node>( new Node(p,1) );
else
_root->insert( p );
}
// Pretty-printing function for the tree; this is only meant for
// debugging purposes and could conceivably be implemented using
// `std::ostream`.
void print( std::ostream& o )
{
std::queue<const Node*> nodes;
nodes.push( _root.get() );
while( !nodes.empty() )
{
{
auto n = nodes.size();
for( decltype(n) i = 0; i < n; i++ )
{
auto&& node = nodes.front();
if( i == 0 )
o << node->_level << ": ";
else
o << " ";
o << node->_point;
for( auto&& child : node->_children )
nodes.push( child.get() );
nodes.pop();
}
o << "\n";
}
}
}
private:
/** Root pointer of the tree */
std::unique_ptr<Node> _root;
};
} // namespace geometry
} // namespace aleph
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include <memory>
#include <anyode/anyode.hpp>
#include <anyode/anyode_blas_lapack.hpp> // dgemv, dgesvd
#include <anyode/anyode_matrix.hpp> // DenseMatrix
#include <anyode/anyode_buffer.hpp> // make_unique
#include <anyode/anyode_decomposition.hpp> // SVD
namespace AnyODE {
template <typename Real_t=double, typename JacMat_t=DenseMatrix<Real_t>, typename Decomp_t=SVD<Real_t>>
struct OdeSysIterativeBase : public OdeSysBase<Real_t> {
int m_njacvec_dot=0, m_nprec_setup=0, m_nprec_solve=0;
std::unique_ptr<JacMat_t> m_jac_cache {nullptr};
std::unique_ptr<JacMat_t> m_prec_cache {nullptr};
bool m_update_prec_cache = false;
Real_t m_old_gamma;
virtual Status jac_times_vec(const Real_t * const __restrict__ vec,
Real_t * const __restrict__ out,
Real_t t,
const Real_t * const __restrict__ y,
const Real_t * const __restrict__ fy
) override
{
// See "Jacobian information (matrix-vector product)"
// (4.6.8 in cvs_guide.pdf for sundials 2.7.0)
auto status = AnyODE::Status::success;
const int ny = this->get_ny();
if (m_jac_cache == nullptr){
m_jac_cache = make_unique<JacMat_t>(nullptr, ny, ny, ny, true);
status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);
}
m_jac_cache->dot_vec(vec, out);
m_njacvec_dot++;
return status;
}
virtual Status prec_setup(Real_t t,
const Real_t * const __restrict__ y,
const Real_t * const __restrict__ fy,
bool jac_ok,
bool& jac_recomputed,
Real_t gamma) override
{
const int ny = this->get_ny();
auto status = AnyODE::Status::success;
ignore(gamma);
// See "Preconditioning (Jacobian data)" in cvs_guide.pdf (4.6.10 for 2.7.0)
if (m_jac_cache == nullptr)
m_jac_cache = make_unique<JacMat_t>(nullptr, ny, ny, ny, true);
if (jac_ok){
jac_recomputed = false;
} else {
status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);
m_update_prec_cache = true;
jac_recomputed = true;
}
m_nprec_setup++;
return status;
}
virtual Status prec_solve_left(const Real_t t,
const Real_t * const __restrict__ y,
const Real_t * const __restrict__ fy,
const Real_t * const __restrict__ r,
Real_t * const __restrict__ z,
Real_t gamma,
Real_t delta,
const Real_t * const __restrict__ ewt
) override
{
// See 4.6.9 on page 75 in cvs_guide.pdf (Sundials 2.6.2)
// Solves P*z = r, where P ~= I - gamma*J
ignore(delta);
const int ny = this->get_ny();
if (ewt)
throw std::runtime_error("Not implemented.");
m_nprec_solve++;
ignore(t); ignore(fy); ignore(y);
bool recompute = false;
if (m_prec_cache == nullptr){
m_prec_cache = make_unique<JacMat_t>(nullptr, ny, ny, ny, true);
recompute = true;
} else {
if (m_update_prec_cache or (m_old_gamma != gamma))
recompute = true;
}
if (recompute){
m_old_gamma = gamma;
m_prec_cache->set_to_eye_plus_scaled_mtx(-gamma, *m_jac_cache);
}
int info;
auto decomp = Decomp_t((JacMat_t*)(m_prec_cache.get()));
info = decomp.solve(r, z);
if (info == 0)
return AnyODE::Status::success;
return AnyODE::Status::recoverable_error;
}
};
}
<commit_msg>Recompute jacobian for CVSpilsJacTimesVecFn<commit_after>#pragma once
#include <memory>
#include <anyode/anyode.hpp>
#include <anyode/anyode_blas_lapack.hpp> // dgemv, dgesvd
#include <anyode/anyode_matrix.hpp> // DenseMatrix
#include <anyode/anyode_buffer.hpp> // make_unique
#include <anyode/anyode_decomposition.hpp> // SVD
namespace AnyODE {
template <typename Real_t=double, typename JacMat_t=DenseMatrix<Real_t>, typename Decomp_t=SVD<Real_t>>
struct OdeSysIterativeBase : public OdeSysBase<Real_t> {
int m_njacvec_dot=0, m_nprec_setup=0, m_nprec_solve=0;
std::unique_ptr<JacMat_t> m_jac_cache {nullptr};
std::unique_ptr<JacMat_t> m_prec_cache {nullptr};
bool m_update_prec_cache = false;
Real_t m_old_gamma;
virtual Status jac_times_vec(const Real_t * const __restrict__ vec,
Real_t * const __restrict__ out,
Real_t t,
const Real_t * const __restrict__ y,
const Real_t * const __restrict__ fy
) override
{
// See "Jacobian information (matrix-vector product)"
// (4.6.8 in cvs_guide.pdf for sundials 2.7.0)
auto status = AnyODE::Status::success;
const int ny = this->get_ny();
if (m_jac_cache == nullptr){
m_jac_cache = make_unique<JacMat_t>(nullptr, ny, ny, ny, true);
}
status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);
m_jac_cache->dot_vec(vec, out);
m_njacvec_dot++;
return status;
}
virtual Status prec_setup(Real_t t,
const Real_t * const __restrict__ y,
const Real_t * const __restrict__ fy,
bool jac_ok,
bool& jac_recomputed,
Real_t gamma) override
{
const int ny = this->get_ny();
auto status = AnyODE::Status::success;
ignore(gamma);
// See "Preconditioning (Jacobian data)" in cvs_guide.pdf (4.6.10 for 2.7.0)
if (m_jac_cache == nullptr)
m_jac_cache = make_unique<JacMat_t>(nullptr, ny, ny, ny, true);
if (jac_ok){
jac_recomputed = false;
} else {
status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);
m_update_prec_cache = true;
jac_recomputed = true;
}
m_nprec_setup++;
return status;
}
virtual Status prec_solve_left(const Real_t t,
const Real_t * const __restrict__ y,
const Real_t * const __restrict__ fy,
const Real_t * const __restrict__ r,
Real_t * const __restrict__ z,
Real_t gamma,
Real_t delta,
const Real_t * const __restrict__ ewt
) override
{
// See 4.6.9 on page 75 in cvs_guide.pdf (Sundials 2.6.2)
// Solves P*z = r, where P ~= I - gamma*J
ignore(delta);
const int ny = this->get_ny();
if (ewt)
throw std::runtime_error("Not implemented.");
m_nprec_solve++;
ignore(t); ignore(fy); ignore(y);
bool recompute = false;
if (m_prec_cache == nullptr){
m_prec_cache = make_unique<JacMat_t>(nullptr, ny, ny, ny, true);
recompute = true;
} else {
if (m_update_prec_cache or (m_old_gamma != gamma))
recompute = true;
}
if (recompute){
m_old_gamma = gamma;
m_prec_cache->set_to_eye_plus_scaled_mtx(-gamma, *m_jac_cache);
}
int info;
auto decomp = Decomp_t((JacMat_t*)(m_prec_cache.get()));
info = decomp.solve(r, z);
if (info == 0)
return AnyODE::Status::success;
return AnyODE::Status::recoverable_error;
}
};
}
<|endoftext|>
|
<commit_before>namespace gen {
/** \brief The Population template.
*
* Requires a `Candidate` class derived from ICandidate and implementing a
* default constructor. */
template<class Candidate>
class Population : private std::vector<Candidate> {
bool sorted = false;
std::mutex mtx{};
static_assert(std::is_default_constructible<Candidate>::value,
"The Candidate type needs to provide a default constructor.");
typedef decltype(internal::detectFT<Candidate>(nullptr)) _FitnessType;
static_assert(internal::hasFT<Candidate>(nullptr) &&
std::is_base_of<ICandidate<_FitnessType>, Candidate>::value,
"The Candidate type needs to be derived from ICandidate.");
public:
/** \brief Creates an empty population. */
Population() = default;
/** \brief Creates an empty population but preallocate space for count
* candidates. */
Population(size_t count) {
this->reserve(count);
}
/** \brief Creates a population of size `count` whose candidates are results
* of calls to the source function `src`.
*
* For discussion about the latter parameter see add(size_t, Source).
*
* \see add(size_t, Source) */
template<class Source>
Population(size_t count, Source src) {
add(count, src);
}
/* The Big Four: trivial but we need them because the mutex can't be
* default copied or moved */
/** \brief The copy constructor. */
Population(const Population& _p): std::vector<Candidate>(_p), sorted(_p.sorted) { }
/** \brief The move constructor. */
Population(Population&& _p): std::vector<Candidate>(std::move(_p)), sorted(_p.sorted) { }
/** \brief Copy assignment operator. */
Population& operator=(const Population& _p) {
std::lock_guard<std::mutex> lock(mtx);
std::vector<Candidate>::operator=(_p);
sorted = _p.sorted;
return *this;
}
/** \brief Move assignment operator. */
Population& operator=(Population&& _p) {
std::lock_guard<std::mutex> lock(mtx);
std::vector<Candidate>::operator=(std::move(_p));
sorted = _p.sorted;
return *this;
}
/** \brief Adds a new candidate. */
void add(const Candidate& c) {
std::lock_guard<std::mutex> lock(mtx);
this->push_back(c);
sorted = false;
}
/** \brief Pushes back a new candidate using the move semantics. */
void add(Candidate&& c) {
std::lock_guard<std::mutex> lock(mtx);
this->push_back(std::forward<Candidate>(c));
sorted = false;
}
/** \brief Draws `count` candidates from a source function `src`.
*
* Source can be:
* - `std::function<(const) Candidate>`: returning by copy,
* - `std::function<(const) Candidate&>`: returning by reference,
* - a pointer to function returning `Candidate` or `Candidate&`,
* - a lambda function returning either.
*
* The template allows for optimizations (inlining) in the latter case. */
template<class Source>
void NOINLINE add(size_t count, Source src) {
std::lock_guard<std::mutex> lock(mtx);
this->reserve(size() + count);
for(size_t j = 0; j < count; j++)
this->push_back(src());
sorted = false;
}
/** \brief Copies all candidates from a vector of `Candidate`s. */
void NOINLINE add(const std::vector<Candidate>& vec) {
add(vec.begin(), vec.end());
}
/** \brief Copies an iterator range from a container of `Candidate`s. */
template<class InputIt>
void add(InputIt first, InputIt last) {
std::lock_guard<std::mutex> lock(mtx);
this->reserve(size() + std::distance(first, last));
this->insert(end(), first, last);
sorted = false;
}
/** \brief Moves all candidates from a vector of `Candidate`s. */
void NOINLINE add(std::vector<Candidate>&& vec) {
std::lock_guard<std::mutex> lock(mtx);
this->reserve(size() + vec.size());
this->insert(end(), std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end()));
vec.clear();
sorted = false;
}
/** \brief Copies all candidates from another Population. */
void add(const Population<Candidate>& pop) {
return merge(static_cast<const std::vector<Candidate>&>(pop));
}
/** \brief Moves all candidates from another Population. */
void add(Population<Candidate>&& pop) {
return add(static_cast<std::vector<Candidate>&&>(pop));
}
using std::vector<Candidate>::begin;
using std::vector<Candidate>::end;
using std::vector<Candidate>::size;
using std::vector<Candidate>::clear;
using std::vector<Candidate>::operator[];
/** \brief Retrieves a candidate randomly chosen by rank-based selection.
*
* This method accepts as a template parameter a name of a function
* `double(double)` that will receive arguments linearly spaced between
* `1/size * bias` and `bias` for candidates ranked `1` through `size` and
* its return value will be interpreted as inverse probability, and as such,
* is expected to be positive and strictly increasing in its argument. This
* function will be built in at compile time, eliminating a function pointer
* lookup. The default value is `std::exp`, for which an equivalent fast
* replacement algorithm is provided.
*
* Applicable only if the fitness type of `Candidate` allows total ordering
* using `operator<`. This method generates an error at compile time in
* specializations for which this condition is not satisfied.
*
* \param bias > 0 determines how much low-fitness solutions are preferred.
* Zero would mean no account on fitness in the selection process
* whatsoever. The bigger the value the more candidates with low fitness are
* likely to be selected.
* \param rng the random number generator, or gen::rng by default.
*
* \returns a constant reference to a randomly chosen `Candidate`. */
template<double (*fun)(double) = std::exp, class Rng = decltype(rng)>
const Candidate& NOINLINE rankSelect(float bias, Rng& rng = rng) {
if(internal::is_exp<fun>::value)
return rankSelect_exp(bias, rng);
else
return rankSelect<
static_cast<double(*)(double, double)>(&internal::eval_in_product<fun>)
> (bias);
}
/** \brief Retrieves a candidate randomly chosen by rank-based selection.
*
* This method accepts as a template parameter a name of a function
* `double(double, double)` that will receive its first argument linearly
* spaced between `1/size` and `1` for candidates ranked `1` through `size`
* and second argument equal to `bias` and its return value will be
* interpreted as inverse probability. As such, is expected to be positive
* and strictly increasing in its argument. This function will be built in
* at compile time, eliminating a function pointer lookup. A usual choice
* for `fun` is `std::pow`.
*
* Applicable only if the fitness type of `Candidate` allows total ordering
* using `operator<`. This method generates an error at compile time in
* specializations for which this condition is not satisfied.
*
* \param bias > 0 determines how much low-fitness solutions are preferred.
* Zero would mean no account on fitness in the selection process
* whatsoever. The bigger the value the more candidates with low fitness are
* likely to be selected.
* \param rng the random number generator, or gen::rng by default.
*
* \returns a constant reference to a randomly chosen `Candidate`. */
template<double (*fun)(double, double), class Rng = decltype(rng)>
const Candidate& NOINLINE rankSelect(double bias, Rng& rng = rng) {
static thread_local std::discrete_distribution<size_t> iDist{};
static thread_local size_t last_sz = 0;
static thread_local std::vector<double> probs{};
size_t sz = size();
if(sz != last_sz) {
probs.clear();
probs.reserve(sz);
for(size_t i = 0; i < sz; i++)
probs.push_back(1 / fun((double)(i+1) / sz, bias));
iDist = std::discrete_distribution<size_t>(probs.begin(), probs.end());
last_sz = sz;
}
ensureSorted();
return (*this)[iDist(rng)];
}
private:
template<class Rng>
const Candidate& rankSelect_exp(double bias, Rng& rng = rng) {
static thread_local std::uniform_real_distribution<double> rDist(0, 1);
ensureSorted();
double x = rDist(rng);
if(x == 1)
return this->back();
else
return (*this)[(int)(-log(1 - x + x*exp(-bias))/bias*size())];
}
public:
/** \brief Returns the best candidate of population.
*
* If more candidates have equal best fitness the returned reference may be
* any of them.
*
* Applicable only if the fitness type of `Candidate` allows total ordering
* using `operator<`. This method generates an error at compile time in
* specializations for which this condition is not satisfied. */
const Candidate& best() {
ensureSorted();
return this->front();
}
/** \brief Reduces the population to a maximum size given by the argument,
* dropping the worst part of the sample.
*
* Applicable only if the fitness type of `Candidate` allows total ordering
* using `operator<`. This method generates an error at compile time in
* specializations for which this condition is not satisfied. */
Population<Candidate>& trim(size_t newSize) {
ensureSorted();
std::lock_guard<std::mutex> lock(mtx);
if(size() > newSize)
this->resize(newSize);
return *this;
}
/** \brief The return type of stat(). */
struct Stat {
double mean; ///< The mean fitness of the Population.
double stdev; ///< The standard deviation of fitness in the Population.
};
/** \brief Returns the mean fitness of the population and the standard
* deviation.
*
* Applicable only to candidate classes whose fitness is a simple floating
* point type or allows an implicit convertion to one. This method
* generates an error at compile time in specializations for which this
* condition is not satisfied. */
Stat stat() {
static_assert(std::is_convertible<_FitnessType, double>::value,
"This method requires the fitness type to be convertible to double.");
double f, sf = 0, sf2 = 0;
for(Candidate &c : *this) {
f = c.fitness();
sf += f;
sf2 += f*f;
}
size_t sz = size();
double dev2 = sf2/sz - sf/sz*sf/sz;
return Stat{sf/sz, dev2 >= 0 ? sqrt(dev2) : 0};
}
private:
void ensureSorted() {
static_assert(internal::comparable<_FitnessType>(0),
"This method requires the fitness type to implement an operator<.");
std::lock_guard<std::mutex> lock(mtx);
if(!sorted) {
std::sort(begin(), end());
sorted = true;
}
}
}; // class Population
} // namespace gen
<commit_msg>Fix old call to merge()<commit_after>namespace gen {
/** \brief The Population template.
*
* Requires a `Candidate` class derived from ICandidate and implementing a
* default constructor. */
template<class Candidate>
class Population : private std::vector<Candidate> {
bool sorted = false;
std::mutex mtx{};
static_assert(std::is_default_constructible<Candidate>::value,
"The Candidate type needs to provide a default constructor.");
typedef decltype(internal::detectFT<Candidate>(nullptr)) _FitnessType;
static_assert(internal::hasFT<Candidate>(nullptr) &&
std::is_base_of<ICandidate<_FitnessType>, Candidate>::value,
"The Candidate type needs to be derived from ICandidate.");
public:
/** \brief Creates an empty population. */
Population() = default;
/** \brief Creates an empty population but preallocate space for count
* candidates. */
Population(size_t count) {
this->reserve(count);
}
/** \brief Creates a population of size `count` whose candidates are results
* of calls to the source function `src`.
*
* For discussion about the latter parameter see add(size_t, Source).
*
* \see add(size_t, Source) */
template<class Source>
Population(size_t count, Source src) {
add(count, src);
}
/* The Big Four: trivial but we need them because the mutex can't be
* default copied or moved */
/** \brief The copy constructor. */
Population(const Population& _p): std::vector<Candidate>(_p), sorted(_p.sorted) { }
/** \brief The move constructor. */
Population(Population&& _p): std::vector<Candidate>(std::move(_p)), sorted(_p.sorted) { }
/** \brief Copy assignment operator. */
Population& operator=(const Population& _p) {
std::lock_guard<std::mutex> lock(mtx);
std::vector<Candidate>::operator=(_p);
sorted = _p.sorted;
return *this;
}
/** \brief Move assignment operator. */
Population& operator=(Population&& _p) {
std::lock_guard<std::mutex> lock(mtx);
std::vector<Candidate>::operator=(std::move(_p));
sorted = _p.sorted;
return *this;
}
/** \brief Adds a new candidate. */
void add(const Candidate& c) {
std::lock_guard<std::mutex> lock(mtx);
this->push_back(c);
sorted = false;
}
/** \brief Pushes back a new candidate using the move semantics. */
void add(Candidate&& c) {
std::lock_guard<std::mutex> lock(mtx);
this->push_back(std::forward<Candidate>(c));
sorted = false;
}
/** \brief Draws `count` candidates from a source function `src`.
*
* Source can be:
* - `std::function<(const) Candidate>`: returning by copy,
* - `std::function<(const) Candidate&>`: returning by reference,
* - a pointer to function returning `Candidate` or `Candidate&`,
* - a lambda function returning either.
*
* The template allows for optimizations (inlining) in the latter case. */
template<class Source>
void NOINLINE add(size_t count, Source src) {
std::lock_guard<std::mutex> lock(mtx);
this->reserve(size() + count);
for(size_t j = 0; j < count; j++)
this->push_back(src());
sorted = false;
}
/** \brief Copies all candidates from a vector of `Candidate`s. */
void NOINLINE add(const std::vector<Candidate>& vec) {
add(vec.begin(), vec.end());
}
/** \brief Copies an iterator range from a container of `Candidate`s. */
template<class InputIt>
void add(InputIt first, InputIt last) {
std::lock_guard<std::mutex> lock(mtx);
this->reserve(size() + std::distance(first, last));
this->insert(end(), first, last);
sorted = false;
}
/** \brief Moves all candidates from a vector of `Candidate`s. */
void NOINLINE add(std::vector<Candidate>&& vec) {
std::lock_guard<std::mutex> lock(mtx);
this->reserve(size() + vec.size());
this->insert(end(), std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end()));
vec.clear();
sorted = false;
}
/** \brief Copies all candidates from another Population. */
void add(const Population<Candidate>& pop) {
return add(static_cast<const std::vector<Candidate>&>(pop));
}
/** \brief Moves all candidates from another Population. */
void add(Population<Candidate>&& pop) {
return add(static_cast<std::vector<Candidate>&&>(pop));
}
using std::vector<Candidate>::begin;
using std::vector<Candidate>::end;
using std::vector<Candidate>::size;
using std::vector<Candidate>::clear;
using std::vector<Candidate>::operator[];
/** \brief Retrieves a candidate randomly chosen by rank-based selection.
*
* This method accepts as a template parameter a name of a function
* `double(double)` that will receive arguments linearly spaced between
* `1/size * bias` and `bias` for candidates ranked `1` through `size` and
* its return value will be interpreted as inverse probability, and as such,
* is expected to be positive and strictly increasing in its argument. This
* function will be built in at compile time, eliminating a function pointer
* lookup. The default value is `std::exp`, for which an equivalent fast
* replacement algorithm is provided.
*
* Applicable only if the fitness type of `Candidate` allows total ordering
* using `operator<`. This method generates an error at compile time in
* specializations for which this condition is not satisfied.
*
* \param bias > 0 determines how much low-fitness solutions are preferred.
* Zero would mean no account on fitness in the selection process
* whatsoever. The bigger the value the more candidates with low fitness are
* likely to be selected.
* \param rng the random number generator, or gen::rng by default.
*
* \returns a constant reference to a randomly chosen `Candidate`. */
template<double (*fun)(double) = std::exp, class Rng = decltype(rng)>
const Candidate& NOINLINE rankSelect(float bias, Rng& rng = rng) {
if(internal::is_exp<fun>::value)
return rankSelect_exp(bias, rng);
else
return rankSelect<
static_cast<double(*)(double, double)>(&internal::eval_in_product<fun>)
> (bias);
}
/** \brief Retrieves a candidate randomly chosen by rank-based selection.
*
* This method accepts as a template parameter a name of a function
* `double(double, double)` that will receive its first argument linearly
* spaced between `1/size` and `1` for candidates ranked `1` through `size`
* and second argument equal to `bias` and its return value will be
* interpreted as inverse probability. As such, is expected to be positive
* and strictly increasing in its argument. This function will be built in
* at compile time, eliminating a function pointer lookup. A usual choice
* for `fun` is `std::pow`.
*
* Applicable only if the fitness type of `Candidate` allows total ordering
* using `operator<`. This method generates an error at compile time in
* specializations for which this condition is not satisfied.
*
* \param bias > 0 determines how much low-fitness solutions are preferred.
* Zero would mean no account on fitness in the selection process
* whatsoever. The bigger the value the more candidates with low fitness are
* likely to be selected.
* \param rng the random number generator, or gen::rng by default.
*
* \returns a constant reference to a randomly chosen `Candidate`. */
template<double (*fun)(double, double), class Rng = decltype(rng)>
const Candidate& NOINLINE rankSelect(double bias, Rng& rng = rng) {
static thread_local std::discrete_distribution<size_t> iDist{};
static thread_local size_t last_sz = 0;
static thread_local std::vector<double> probs{};
size_t sz = size();
if(sz != last_sz) {
probs.clear();
probs.reserve(sz);
for(size_t i = 0; i < sz; i++)
probs.push_back(1 / fun((double)(i+1) / sz, bias));
iDist = std::discrete_distribution<size_t>(probs.begin(), probs.end());
last_sz = sz;
}
ensureSorted();
return (*this)[iDist(rng)];
}
private:
template<class Rng>
const Candidate& rankSelect_exp(double bias, Rng& rng = rng) {
static thread_local std::uniform_real_distribution<double> rDist(0, 1);
ensureSorted();
double x = rDist(rng);
if(x == 1)
return this->back();
else
return (*this)[(int)(-log(1 - x + x*exp(-bias))/bias*size())];
}
public:
/** \brief Returns the best candidate of population.
*
* If more candidates have equal best fitness the returned reference may be
* any of them.
*
* Applicable only if the fitness type of `Candidate` allows total ordering
* using `operator<`. This method generates an error at compile time in
* specializations for which this condition is not satisfied. */
const Candidate& best() {
ensureSorted();
return this->front();
}
/** \brief Reduces the population to a maximum size given by the argument,
* dropping the worst part of the sample.
*
* Applicable only if the fitness type of `Candidate` allows total ordering
* using `operator<`. This method generates an error at compile time in
* specializations for which this condition is not satisfied. */
Population<Candidate>& trim(size_t newSize) {
ensureSorted();
std::lock_guard<std::mutex> lock(mtx);
if(size() > newSize)
this->resize(newSize);
return *this;
}
/** \brief The return type of stat(). */
struct Stat {
double mean; ///< The mean fitness of the Population.
double stdev; ///< The standard deviation of fitness in the Population.
};
/** \brief Returns the mean fitness of the population and the standard
* deviation.
*
* Applicable only to candidate classes whose fitness is a simple floating
* point type or allows an implicit convertion to one. This method
* generates an error at compile time in specializations for which this
* condition is not satisfied. */
Stat stat() {
static_assert(std::is_convertible<_FitnessType, double>::value,
"This method requires the fitness type to be convertible to double.");
double f, sf = 0, sf2 = 0;
for(Candidate &c : *this) {
f = c.fitness();
sf += f;
sf2 += f*f;
}
size_t sz = size();
double dev2 = sf2/sz - sf/sz*sf/sz;
return Stat{sf/sz, dev2 >= 0 ? sqrt(dev2) : 0};
}
private:
void ensureSorted() {
static_assert(internal::comparable<_FitnessType>(0),
"This method requires the fitness type to implement an operator<.");
std::lock_guard<std::mutex> lock(mtx);
if(!sorted) {
std::sort(begin(), end());
sorted = true;
}
}
}; // class Population
} // namespace gen
<|endoftext|>
|
<commit_before>/*
* StoichiometryView.hpp
*
* Copyright (C) 2012 Marc Kirchner
*
*/
#ifndef __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__
#define __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__
namespace ipaca {
template<typename T>
struct StoichiometryTraits
{
typedef typename T::iterator iterator_type;
typedef typename T::const_iterator const_iterator_type;
typedef typename T::value_type value_type;
};
template<typename T>
struct StoichiometryValueTraits
{
// must be specified by the user
};
/** A generic view on stoichiometries.
* This class declares the interface that \c libipaca expects from a
* stoichiometry. The client is required to specify stoichiometry
* propertie (iterator types, value types and accessor functors in the
* respective trait classes \c StoichiometryTraits and
* \c StoichiometryValueTraits.
*/
template<typename T>
class StoichiometryView
{
public:
typedef typename StoichiometryTraits<T>::iterator_type iterator;
typedef typename StoichiometryTraits<T>::const_iterator_type
const_iterator;
StoichiometryView(T&);
StoichiometryView(const StoichiometryView<T>& rhs);
const_iterator begin() const;
const_iterator end() const;
// TODO: figure out if we REALLY need the non-const iterator. Eliminate if possible.
iterator begin();
iterator end();
const T& ref() const;
bool isNonNegative() const;
private:
T& stoi_;
};
}
//
// template implementation
//
template<typename T>
ipaca::StoichiometryView<T>::StoichiometryView(T& stoi) :
stoi_(stoi)
{
}
template<typename T>
ipaca::StoichiometryView<T>::StoichiometryView(const StoichiometryView<T>& rhs) :
stoi_(rhs.stoi_)
{
}
template<typename T>
typename ipaca::StoichiometryView<T>::const_iterator ipaca::StoichiometryView<
T>::begin() const
{
return stoi_.begin();
}
template<typename T>
typename ipaca::StoichiometryView<T>::const_iterator ipaca::StoichiometryView<
T>::end() const
{
return stoi_.end();
}
template<typename T>
typename ipaca::StoichiometryView<T>::iterator ipaca::StoichiometryView<T>::begin()
{
return stoi_.begin();
}
template<typename T>
typename ipaca::StoichiometryView<T>::iterator ipaca::StoichiometryView<T>::end()
{
return stoi_.end();
}
template<typename T>
const T& ipaca::StoichiometryView<T>::ref() const
{
return stoi_;
}
#endif /* __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__ */
<commit_msg>adding typeinfo for the viewed type<commit_after>/*
* StoichiometryView.hpp
*
* Copyright (C) 2012 Marc Kirchner
*
*/
#ifndef __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__
#define __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__
namespace ipaca {
template<typename T>
struct StoichiometryTraits
{
typedef typename T::iterator iterator_type;
typedef typename T::const_iterator const_iterator_type;
typedef typename T::value_type value_type;
};
template<typename T>
struct StoichiometryValueTraits
{
// must be specified by the user
};
/** A generic view on stoichiometries.
* This class declares the interface that \c libipaca expects from a
* stoichiometry. The client is required to specify stoichiometry
* propertie (iterator types, value types and accessor functors in the
* respective trait classes \c StoichiometryTraits and
* \c StoichiometryValueTraits.
*/
template<typename T>
class StoichiometryView
{
public:
typedef T viewed_type;
typedef typename StoichiometryTraits<T>::iterator_type iterator;
typedef typename StoichiometryTraits<T>::const_iterator_type
const_iterator;
StoichiometryView(T&);
StoichiometryView(const StoichiometryView<T>& rhs);
const_iterator begin() const;
const_iterator end() const;
// TODO: figure out if we REALLY need the non-const iterator. Eliminate if possible.
iterator begin();
iterator end();
const T& ref() const;
bool isNonNegative() const;
private:
T& stoi_;
};
}
//
// template implementation
//
template<typename T>
ipaca::StoichiometryView<T>::StoichiometryView(T& stoi) :
stoi_(stoi)
{
}
template<typename T>
ipaca::StoichiometryView<T>::StoichiometryView(const StoichiometryView<T>& rhs) :
stoi_(rhs.stoi_)
{
}
template<typename T>
typename ipaca::StoichiometryView<T>::const_iterator ipaca::StoichiometryView<
T>::begin() const
{
return stoi_.begin();
}
template<typename T>
typename ipaca::StoichiometryView<T>::const_iterator ipaca::StoichiometryView<
T>::end() const
{
return stoi_.end();
}
template<typename T>
typename ipaca::StoichiometryView<T>::iterator ipaca::StoichiometryView<T>::begin()
{
return stoi_.begin();
}
template<typename T>
typename ipaca::StoichiometryView<T>::iterator ipaca::StoichiometryView<T>::end()
{
return stoi_.end();
}
template<typename T>
const T& ipaca::StoichiometryView<T>::ref() const
{
return stoi_;
}
#endif /* __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__ */
<|endoftext|>
|
<commit_before>#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/phoenix/bind/bind_member_function.hpp>
#include <string>
#include <vector>
#include <functional>
#include <map>
/**
Parser and executer of my primitive (not Turing complete) assembly-like language
Example:
create function_name(param1, param2,...) {
create x
create y
setval x 5
setval y 10
add y y
mul x y
sub y x
div x y
setvar param1 x
setvar param2 y
print x
}
*/
#define BIND_VALUE(member_method, bind_point) phoenix::bind(&member_method, &bind_point, qi::_1)
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
namespace L
{
class Function {
private:
struct Command {
std::string commandName;
std::string param1;
std::string param2;
Command(const std::string& cmdName)
: commandName(cmdName) {}
};
bool isValid = true;
std::string name;
std::vector<std::string> param;
std::vector<Command> commands;
public:
Function() = default;
void SetName(const std::string& n) {
//std::cout << "setting name " << n << std::endl;
name = n;
}
void AddFunctionParameter(const std::string& p) {
//std::cout << "adding function parameter " << p << std::endl;
param.push_back(p);
}
void AddCommand(const std::string& c) {
//std::cout << "adding command " << c << std::endl;
commands.emplace_back(c);
}
void AddCommandParameter(const std::string& p) {
//std::cout << "adding command parameter " << p << std::endl;
if (!commands.empty()) {
auto& b = commands.back();
if (b.param1.empty()) {
b.param1 = p;
}
else if (b.param2.empty()) {
b.param2 = p;
}
else {
isValid = false;
}
}
}
bool CheckValidity() {
if (name.empty()) {
isValid = false;
}
return isValid;
}
};
template<typename It>
class FunctionParser : public qi::grammar<It, std::string(), ascii::space_type>
{
private:
qi::rule<It, std::string(), ascii::space_type> startRule;
qi::rule<It, std::string(), ascii::space_type> paramRule;
qi::rule<It, std::string(), ascii::space_type> bodyRule;
Function func;
public:
FunctionParser() : FunctionParser::base_type(startRule)
{
startRule =
qi::lit("create")
>> qi::as_string[+(qi::alnum - qi::char_('('))][BIND_VALUE(Function::SetName, func)]
>> '('
>> *paramRule
>> qi::char_(')')
>> qi::char_('{')
>> -bodyRule
>> qi::char_('}');
paramRule =
qi::as_string[+(qi::alnum)][BIND_VALUE(Function::AddFunctionParameter, func)]
>> -qi::char_(',');
bodyRule =
qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommand, func)]
>> -qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommandParameter, func)]
>> -qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommandParameter, func)]
>> -(qi::char_(',') >> bodyRule);
}
Function& GetParsedFunction() {
return func;
}
};
}
template<typename It>
void ParseAndRun(It first, It end)
{
L::FunctionParser<It> parser;
bool succ = qi::phrase_parse(first, end, parser, ascii::space, std::string());
auto& func = parser.GetParsedFunction();
// TODO check first iterator
// TODO replace first iterator with begin
if (succ && func.CheckValidity()) {
std::cout << "Parsing successful" << std::endl;
}
else {
std::cout << "Parsing failed" << std::endl;
}
}
int main() {
std::string line;
do {
std::getline(std::cin, line);
ParseAndRun(line.cbegin(), line.cend());
} while (!line.empty());
return 0;
}
<commit_msg>qi::char_ update<commit_after>#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/phoenix/bind/bind_member_function.hpp>
#include <string>
#include <vector>
#include <functional>
#include <map>
/**
Parser and executer of my primitive (not Turing complete) assembly-like language
Example:
create function_name(param1, param2,...) {
create x
create y
setval x 5
setval y 10
add y y
mul x y
sub y x
div x y
setvar param1 x
setvar param2 y
print x
}
*/
#define BIND_VALUE(member_method, bind_point) phoenix::bind(&member_method, &bind_point, qi::_1)
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
namespace L
{
class Function {
private:
struct Command {
std::string commandName;
std::string param1;
std::string param2;
Command(const std::string& cmdName)
: commandName(cmdName) {}
};
bool isValid = true;
std::string name;
std::vector<std::string> param;
std::vector<Command> commands;
public:
Function() = default;
void SetName(const std::string& n) {
//std::cout << "setting name " << n << std::endl;
name = n;
}
void AddFunctionParameter(const std::string& p) {
//std::cout << "adding function parameter " << p << std::endl;
param.push_back(p);
}
void AddCommand(const std::string& c) {
//std::cout << "adding command " << c << std::endl;
commands.emplace_back(c);
}
void AddCommandParameter(const std::string& p) {
//std::cout << "adding command parameter " << p << std::endl;
if (!commands.empty()) {
auto& b = commands.back();
if (b.param1.empty()) {
b.param1 = p;
}
else if (b.param2.empty()) {
b.param2 = p;
}
else {
isValid = false;
}
}
}
bool CheckValidity() {
if (name.empty()) {
isValid = false;
}
return isValid;
}
};
template<typename It>
class FunctionParser : public qi::grammar<It, std::string(), ascii::space_type>
{
private:
qi::rule<It, std::string(), ascii::space_type> startRule;
qi::rule<It, std::string(), ascii::space_type> paramRule;
qi::rule<It, std::string(), ascii::space_type> bodyRule;
Function func;
public:
FunctionParser() : FunctionParser::base_type(startRule)
{
startRule =
qi::lit("create")
>> qi::as_string[+(qi::alnum - qi::char_('('))][BIND_VALUE(Function::SetName, func)]
>> qi::char_('(')
>> *paramRule
>> qi::char_(')')
>> qi::char_('{')
>> -bodyRule
>> qi::char_('}');
paramRule =
qi::as_string[+(qi::alnum)][BIND_VALUE(Function::AddFunctionParameter, func)]
>> -qi::char_(',');
bodyRule =
qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommand, func)]
>> -qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommandParameter, func)]
>> -qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommandParameter, func)]
>> -(qi::char_(',') >> bodyRule);
}
Function& GetParsedFunction() {
return func;
}
};
}
template<typename It>
void ParseAndRun(It first, It end)
{
L::FunctionParser<It> parser;
bool succ = qi::phrase_parse(first, end, parser, ascii::space, std::string());
auto& func = parser.GetParsedFunction();
// TODO check first iterator
// TODO replace first iterator with begin
if (succ && func.CheckValidity()) {
std::cout << "Parsing successful" << std::endl;
}
else {
std::cout << "Parsing failed" << std::endl;
}
}
int main() {
std::string line;
do {
std::getline(std::cin, line);
ParseAndRun(line.cbegin(), line.cend());
} while (!line.empty());
return 0;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2016 3D Repo Ltd
*
* This program 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.
*
* 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 Affero 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, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/core/model/bson/repo_node_transformation.h>
#include <repo/core/model/bson/repo_bson_builder.h>
#include "../../../../repo_test_utils.h"
using namespace repo::core::model;
std::vector<float> identity =
{ 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
std::vector<float> notId =
{ 1, 2, 3, 4,
5, 6, 7, 8,
9, 0.3f, 10, 11,
5342, 31, 0.6f, 12 };
std::vector<float> idInBoundary =
{ 1, 0, 0, 0,
0, 1, 0, (float)1e-6,
0, 0, 1, 0,
0, (float)1e-6, (float)1e-6, 1 };
std::vector<float> notIdInBoundary = { 1, 0, 0, 0,
0, 1, 0, (float)2e-5,
0, 0, 2, 0,
0, (float)2e-5, (float)2e-5, 1 };
TransformationNode makeTransformationNode(
const std::vector<float> &matrix)
{
RepoBSONBuilder bsonBuilder;
RepoBSONBuilder rows;
for (uint32_t i = 0; i < 4; ++i)
{
RepoBSONBuilder columns;
for (uint32_t j = 0; j < 4; ++j){
columns << std::to_string(j) << matrix[i * 4 + j];
}
rows.appendArray(std::to_string(i), columns.obj());
}
bsonBuilder.appendArray(REPO_NODE_LABEL_MATRIX, rows.obj());
return bsonBuilder.obj();
}
TEST(RepoTransformationNodeTest, Constructor)
{
auto empty = TransformationNode();
EXPECT_TRUE(empty.isEmpty());
EXPECT_EQ(NodeType::TRANSFORMATION, empty.getTypeAsEnum());
auto repoBson = RepoBSON(BSON("test" << "blah" << "test2" << 2));
auto fromRepoBSON = TransformationNode(repoBson);
EXPECT_EQ(NodeType::TRANSFORMATION, fromRepoBSON.getTypeAsEnum());
EXPECT_EQ(fromRepoBSON.nFields(), repoBson.nFields());
EXPECT_EQ(0, fromRepoBSON.getFileList().size());
}
TEST(RepoTransformationNodeTest, IdentityTest)
{
auto empty = TransformationNode();
EXPECT_TRUE(empty.isIdentity());
EXPECT_TRUE(makeTransformationNode(identity).isIdentity());
EXPECT_TRUE(makeTransformationNode(idInBoundary).isIdentity());
EXPECT_FALSE(makeTransformationNode(notId).isIdentity());
EXPECT_FALSE(makeTransformationNode(notIdInBoundary).isIdentity());
}
TEST(RepoTransformationNodeTest, IdentityTest2)
{
auto identity = TransformationNode::identityMat();
ASSERT_EQ(4, identity.size());
for (int i = 0; i < 4; ++i)
{
ASSERT_EQ(4, identity[i].size());
for (int j = 0; j < 4; ++j)
{
float expectedOutcome = i % 4 == j ? 1 : 0;
EXPECT_EQ(expectedOutcome, identity[i][j]);
}
}
}
TEST(RepoTransformationNodeTest, TypeTest)
{
TransformationNode node = TransformationNode();
EXPECT_EQ(REPO_NODE_TYPE_TRANSFORMATION, node.getType());
EXPECT_EQ(NodeType::TRANSFORMATION, node.getTypeAsEnum());
}
TEST(RepoTransformationNodeTest, PositionDependantTest)
{
TransformationNode node = TransformationNode();
//transformation node should always be position dependant
EXPECT_TRUE(node.positionDependant());
}
TEST(RepoTransformationNodeTest, SEqualTest)
{
auto empty1 = TransformationNode();
auto empty2 = TransformationNode();
auto notEmpty1 = makeTransformationNode(notId);
auto notEmpty2 = makeTransformationNode(notId);
auto notEmpty3 = makeTransformationNode(identity);
EXPECT_TRUE(empty1.sEqual(empty2));
EXPECT_TRUE(empty2.sEqual(empty1));
EXPECT_TRUE(empty1.sEqual(empty1));
EXPECT_TRUE(notEmpty1.sEqual(notEmpty2));
EXPECT_TRUE(notEmpty2.sEqual(notEmpty1));
EXPECT_FALSE(notEmpty1.sEqual(empty2));
EXPECT_TRUE(notEmpty3.sEqual(notEmpty3));
EXPECT_FALSE(notEmpty3.sEqual(notEmpty2));
EXPECT_FALSE(empty1.sEqual(notEmpty2));
}
TEST(RepoTransformationNodeTest, CloneAndApplyTransformationTest)
{
auto empty = TransformationNode();
TransformationNode modifiedEmpty = empty.cloneAndApplyTransformation(notId);
EXPECT_EQ(empty.getTransMatrix(false), identity);
EXPECT_EQ(modifiedEmpty.getTransMatrix(false), notId);
auto filled = makeTransformationNode(notId);
TransformationNode modifiedFilled = filled.cloneAndApplyTransformation(std::vector<float>());
EXPECT_EQ(modifiedFilled.getTransMatrix(false).getData(), notId);
}
TEST(RepoTransformationNodeTest, GetTransMatrixTest)
{
TransformationNode empty = TransformationNode();
EXPECT_EQ(identity, empty.getTransMatrix(false));
TransformationNode notEmpty = makeTransformationNode(notId);
EXPECT_EQ(notId, notEmpty.getTransMatrix(false));
//check transpose is done correctly
auto notIdTransposed = notEmpty.getTransMatrix(true);
auto notIdTransData = notIdTransposed.getData();
ASSERT_EQ(notId.size(), notIdTransData.size());
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
int index = i * 4 + j;
int transIndex = j * 4 + i;
EXPECT_EQ(notId[index], notIdTransData[transIndex]);
}
}
}<commit_msg>#48 small commit<commit_after>/**
* Copyright (C) 2016 3D Repo Ltd
*
* This program 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.
*
* 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 Affero 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, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/core/model/bson/repo_node_transformation.h>
#include <repo/core/model/bson/repo_bson_builder.h>
#include "../../../../repo_test_utils.h"
using namespace repo::core::model;
std::vector<float> identity =
{ 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
std::vector<float> notId =
{ 1, 2, 3, 4,
5, 6, 7, 8,
9, 0.3f, 10, 11,
5342, 31, 0.6f, 12 };
std::vector<float> idInBoundary =
{ 1, 0, 0, 0,
0, 1, 0, (float)1e-6,
0, 0, 1, 0,
0, (float)1e-6, (float)1e-6, 1 };
std::vector<float> notIdInBoundary = { 1, 0, 0, 0,
0, 1, 0, (float)2e-5,
0, 0, 2, 0,
0, (float)2e-5, (float)2e-5, 1 };
TransformationNode makeTransformationNode(
const std::vector<float> &matrix)
{
RepoBSONBuilder bsonBuilder;
RepoBSONBuilder rows;
for (uint32_t i = 0; i < 4; ++i)
{
RepoBSONBuilder columns;
for (uint32_t j = 0; j < 4; ++j){
columns << std::to_string(j) << matrix[i * 4 + j];
}
rows.appendArray(std::to_string(i), columns.obj());
}
bsonBuilder.appendArray(REPO_NODE_LABEL_MATRIX, rows.obj());
return bsonBuilder.obj();
}
TEST(RepoTransformationNodeTest, Constructor)
{
auto empty = TransformationNode();
EXPECT_TRUE(empty.isEmpty());
EXPECT_EQ(NodeType::TRANSFORMATION, empty.getTypeAsEnum());
auto repoBson = RepoBSON(BSON("test" << "blah" << "test2" << 2));
auto fromRepoBSON = TransformationNode(repoBson);
EXPECT_EQ(NodeType::TRANSFORMATION, fromRepoBSON.getTypeAsEnum());
EXPECT_EQ(fromRepoBSON.nFields(), repoBson.nFields());
EXPECT_EQ(0, fromRepoBSON.getFileList().size());
}
TEST(RepoTransformationNodeTest, IdentityTest)
{
auto empty = TransformationNode();
EXPECT_TRUE(empty.isIdentity());
EXPECT_TRUE(makeTransformationNode(identity).isIdentity());
EXPECT_TRUE(makeTransformationNode(idInBoundary).isIdentity());
EXPECT_FALSE(makeTransformationNode(notId).isIdentity());
EXPECT_FALSE(makeTransformationNode(notIdInBoundary).isIdentity());
}
TEST(RepoTransformationNodeTest, IdentityTest2)
{
auto identity = TransformationNode::identityMat();
ASSERT_EQ(4, identity.size());
for (int i = 0; i < 4; ++i)
{
ASSERT_EQ(4, identity[i].size());
for (int j = 0; j < 4; ++j)
{
float expectedOutcome = i % 4 == j ? 1 : 0;
EXPECT_EQ(expectedOutcome, identity[i][j]);
}
}
}
TEST(RepoTransformationNodeTest, TypeTest)
{
TransformationNode node = TransformationNode();
EXPECT_EQ(REPO_NODE_TYPE_TRANSFORMATION, node.getType());
EXPECT_EQ(NodeType::TRANSFORMATION, node.getTypeAsEnum());
}
TEST(RepoTransformationNodeTest, PositionDependantTest)
{
TransformationNode node = TransformationNode();
//transformation node should always be position dependant
EXPECT_TRUE(node.positionDependant());
}
TEST(RepoTransformationNodeTest, SEqualTest)
{
auto empty1 = TransformationNode();
auto empty2 = TransformationNode();
auto notEmpty1 = makeTransformationNode(notId);
auto notEmpty2 = makeTransformationNode(notId);
auto notEmpty3 = makeTransformationNode(identity);
EXPECT_TRUE(empty1.sEqual(empty2));
EXPECT_TRUE(empty2.sEqual(empty1));
EXPECT_TRUE(empty1.sEqual(empty1));
EXPECT_TRUE(notEmpty1.sEqual(notEmpty2));
EXPECT_TRUE(notEmpty2.sEqual(notEmpty1));
EXPECT_FALSE(notEmpty1.sEqual(empty2));
EXPECT_TRUE(notEmpty3.sEqual(notEmpty3));
EXPECT_FALSE(notEmpty3.sEqual(notEmpty2));
EXPECT_FALSE(empty1.sEqual(notEmpty2));
}
TEST(RepoTransformationNodeTest, CloneAndApplyTransformationTest)
{
auto empty = TransformationNode();
TransformationNode modifiedEmpty = empty.cloneAndApplyTransformation(notId);
EXPECT_EQ(empty.getTransMatrix(false), identity);
EXPECT_EQ(modifiedEmpty.getTransMatrix(false), notId);
auto filled = makeTransformationNode(notId);
TransformationNode modifiedFilled = filled.cloneAndApplyTransformation(std::vector<float>());
EXPECT_EQ(modifiedFilled.getTransMatrix(false), notId);
}
TEST(RepoTransformationNodeTest, GetTransMatrixTest)
{
TransformationNode empty = TransformationNode();
EXPECT_EQ(identity, empty.getTransMatrix(false));
TransformationNode notEmpty = makeTransformationNode(notId);
EXPECT_EQ(notId, notEmpty.getTransMatrix(false));
//check transpose is done correctly
auto notIdTransposed = notEmpty.getTransMatrix(true);
auto notIdTransData = notIdTransposed.getData();
ASSERT_EQ(notId.size(), notIdTransData.size());
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
int index = i * 4 + j;
int transIndex = j * 4 + i;
EXPECT_EQ(notId[index], notIdTransData[transIndex]);
}
}
}<|endoftext|>
|
<commit_before>// $Id: Sentence.cpp 1465 2007-09-27 14:16:28Z hieuhoang1972 $
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
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 "XmlOption.h"
#include <vector>
#include <string>
#include <iostream>
#include "Util.h"
#include "StaticData.h"
namespace {
std::string ParseXmlTagAttribute(const std::string& tag,const std::string& attributeName){
/*TODO deal with unescaping \"*/
string tagOpen = attributeName + "=\"";
size_t contentsStart = tag.find(tagOpen);
if (contentsStart == std::string::npos) return "";
contentsStart += tagOpen.size();
size_t contentsEnd = tag.find_first_of('"',contentsStart+1);
if (contentsEnd == std::string::npos) {
TRACE_ERR("Malformed XML attribute: "<< tag);
return "";
}
size_t possibleEnd;
while (tag.at(contentsEnd-1) == '\\' && (possibleEnd = tag.find_first_of('"',contentsEnd+1)) != std::string::npos) {
contentsEnd = possibleEnd;
}
return tag.substr(contentsStart,contentsEnd-contentsStart);
}
std::string TrimXml(const std::string& str) {
if (str.size() < 2) return str;
if (str[0] == '<' && str[str.size() - 1] == '>') {
return str.substr(1, str.size() - 2);
} else { return str; }
}
bool isXmlTag(const std::string& tag)
{
return tag[0] == '<';
}
inline std::vector<std::string> TokenizeXml(const std::string& str)
{
std::string lbrack = "<";
std::string rbrack = ">";
std::vector<std::string> tokens;
// Find first "non-delimiter".
std::string::size_type cpos = 0;
std::string::size_type lpos = 0;
std::string::size_type rpos = 0;
while (cpos != str.size()) {
lpos = str.find_first_of(lbrack, cpos);
if (lpos != std::string::npos) {
rpos = str.find_first_of(rbrack, lpos);
if (rpos == std::string::npos) {
TRACE_ERR("ERROR: malformed XML: " << str << endl);
return tokens;
}
} else {
tokens.push_back(str.substr(cpos));
break;
}
if (lpos - cpos > 0)
tokens.push_back(str.substr(cpos, lpos - cpos));
tokens.push_back(str.substr(lpos, rpos-lpos+1));
cpos = rpos + 1;
}
return tokens;
}
}
std::vector<XmlOption> ProcessAndStripXMLTags(std::string& line) {
//parse XML markup in translation line
std::vector<XmlOption> res;
std::string rstr;
if (line.find_first_of('<') == std::string::npos) { return res; }
std::vector<std::string> xmlTokens = TokenizeXml(line);
std::string tagName = "";
std::string tagContents = "";
std::vector<std::string> altTexts;
std::vector<std::string> altProbs;
size_t tagStart=0;
size_t tagEnd=0;
size_t curWord=0;
int numUnary = 0;
bool doClose = false;
for (size_t xmlTokenPos = 0 ; xmlTokenPos < xmlTokens.size() ; xmlTokenPos++)
{
if(!isXmlTag(xmlTokens[xmlTokenPos]))
{
//phrase, not tag
rstr += xmlTokens[xmlTokenPos];
curWord = Tokenize(rstr).size();
}
else
{
//tag data
std::string tag = Trim(TrimXml(xmlTokens[xmlTokenPos]));
VERBOSE(3,"XML TAG IS: " << tag << std::endl);
std::string::size_type endOfName = tag.find_first_of(' ');
std::string nextTagName = tag;
bool isUnary = tag[tag.size() - 1] == '/';
bool isOpen = tag[1] != '/';
if (endOfName != std::string::npos) {
nextTagName = tag.substr(0,endOfName);
tagContents = tag.substr(endOfName+1);
}
if (isOpen)
{
//this is an open tag
tagName = nextTagName;
altTexts = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContents,"english"), "||");
altProbs = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContents,"prob"), "||");
std::string span = ParseXmlTagAttribute(tagContents,"span");
tagStart = curWord;
if (isUnary) {
numUnary++;
if (span.empty()) {
TRACE_ERR("ERROR: unary tags must have a span attribute: " << line << endl);
return res;
}
std::vector<std::string> ij = Tokenize(span, ",");
if (ij.size() != 2) {
TRACE_ERR("ERROR: span tag must be of the form \"i,j\": " << line << endl);
return res;
}
tagStart = atoi(ij[0].c_str());
tagEnd = atoi(ij[1].c_str());
if (tagEnd < tagStart) {
TRACE_ERR("ERROR: span tag " << span << " invalid" << endl);
return res;
}
doClose = true;
VERBOSE(3,"XML TAG IS UNARY" << endl);
}
VERBOSE(3,"XML TAG NAME IS: '" << tagName << "'" << endl);
VERBOSE(3,"XML TAG ENGLISH IS: '" << altTexts[0] << "'" << endl);
VERBOSE(3,"XML TAG PROB IS: '" << altProbs[0] << "'" << endl);
VERBOSE(3,"XML TAG STARTS AT WORD: " << tagStart << endl);
if (altTexts.size() != altProbs.size()) {
TRACE_ERR("ERROR: Unequal number of probabilities and translation alternatives: " << line << endl);
return res;
}
}
else if ((nextTagName.size() == 0) || (nextTagName.at(0) != '/') || (nextTagName.substr(1) != tagName))
{
//mismatched tag, abort!
TRACE_ERR("ERROR: tried to parse malformed XML with xml-input enabled: " << line << endl);
return res;
}
else {
doClose = true;
tagEnd = curWord-1; //size is inclusive
}
if (doClose) {
VERBOSE(3,"XML END TAG IS: " << nextTagName.substr(1) << endl);
VERBOSE(3,"XML TAG ENDS AT WORD: " << tagEnd << endl);
//store translation options into members
//TODO: deal with multiple XML options here
if (StaticData::Instance().GetXmlInputType() != XmlIgnore) {
for (size_t i=0; i<altTexts.size(); ++i) {
//only store options if we aren't ignoring them
//set default probability
float probValue = 1;
if (altProbs[i] != "") probValue = Scan<float>(altProbs[i]);
//Convert from prob to log-prob
float scoreValue = FloorScore(TransformScore(probValue));
XmlOption option(tagStart,tagEnd,altTexts[i],scoreValue);
res.push_back(option);
}
}
tagName= "";
tagContents = "";
altTexts.clear();
altProbs.clear();
doClose = false;
}
}
}
line = rstr;
return res;
}
<commit_msg>fixed bug with XML markup<commit_after>// $Id: Sentence.cpp 1465 2007-09-27 14:16:28Z hieuhoang1972 $
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
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 "XmlOption.h"
#include <vector>
#include <string>
#include <iostream>
#include "Util.h"
#include "StaticData.h"
namespace {
std::string ParseXmlTagAttribute(const std::string& tag,const std::string& attributeName){
/*TODO deal with unescaping \"*/
string tagOpen = attributeName + "=\"";
size_t contentsStart = tag.find(tagOpen);
if (contentsStart == std::string::npos) return "";
contentsStart += tagOpen.size();
size_t contentsEnd = tag.find_first_of('"',contentsStart+1);
if (contentsEnd == std::string::npos) {
TRACE_ERR("Malformed XML attribute: "<< tag);
return "";
}
size_t possibleEnd;
while (tag.at(contentsEnd-1) == '\\' && (possibleEnd = tag.find_first_of('"',contentsEnd+1)) != std::string::npos) {
contentsEnd = possibleEnd;
}
return tag.substr(contentsStart,contentsEnd-contentsStart);
}
std::string TrimXml(const std::string& str) {
if (str.size() < 2) return str;
if (str[0] == '<' && str[str.size() - 1] == '>') {
return str.substr(1, str.size() - 2);
} else { return str; }
}
bool isXmlTag(const std::string& tag)
{
return tag[0] == '<';
}
inline std::vector<std::string> TokenizeXml(const std::string& str)
{
std::string lbrack = "<";
std::string rbrack = ">";
std::vector<std::string> tokens;
// Find first "non-delimiter".
std::string::size_type cpos = 0;
std::string::size_type lpos = 0;
std::string::size_type rpos = 0;
while (cpos != str.size()) {
lpos = str.find_first_of(lbrack, cpos);
if (lpos != std::string::npos) {
rpos = str.find_first_of(rbrack, lpos);
if (rpos == std::string::npos) {
TRACE_ERR("ERROR: malformed XML: " << str << endl);
return tokens;
}
} else {
tokens.push_back(str.substr(cpos));
break;
}
if (lpos - cpos > 0)
tokens.push_back(str.substr(cpos, lpos - cpos));
tokens.push_back(str.substr(lpos, rpos-lpos+1));
cpos = rpos + 1;
}
return tokens;
}
}
std::vector<XmlOption> ProcessAndStripXMLTags(std::string& line) {
//parse XML markup in translation line
std::vector<XmlOption> res;
std::string rstr;
if (line.find_first_of('<') == std::string::npos) { return res; }
std::vector<std::string> xmlTokens = TokenizeXml(line);
std::string tagName = "";
std::string tagContents = "";
std::vector<std::string> altTexts;
std::vector<std::string> altProbs;
size_t tagStart=0;
size_t tagEnd=0;
size_t curWord=0;
int numUnary = 0;
bool doClose = false;
for (size_t xmlTokenPos = 0 ; xmlTokenPos < xmlTokens.size() ; xmlTokenPos++)
{
if(!isXmlTag(xmlTokens[xmlTokenPos]))
{
//phrase, not tag
rstr += xmlTokens[xmlTokenPos];
curWord = Tokenize(rstr).size();
}
else
{
//tag data
std::string tag = Trim(TrimXml(xmlTokens[xmlTokenPos]));
VERBOSE(3,"XML TAG IS: " << tag << std::endl);
std::string::size_type endOfName = tag.find_first_of(' ');
std::string nextTagName = tag;
bool isUnary = tag[tag.size() - 1] == '/';
bool isOpen = tag[0] != '/';
if (endOfName != std::string::npos) {
nextTagName = tag.substr(0,endOfName);
tagContents = tag.substr(endOfName+1);
}
if (isOpen)
{
//this is an open tag
tagName = nextTagName;
altTexts = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContents,"english"), "||");
altProbs = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContents,"prob"), "||");
std::string span = ParseXmlTagAttribute(tagContents,"span");
tagStart = curWord;
if (isUnary) {
numUnary++;
if (span.empty()) {
TRACE_ERR("ERROR: unary tags must have a span attribute: " << line << endl);
return res;
}
std::vector<std::string> ij = Tokenize(span, ",");
if (ij.size() != 2) {
TRACE_ERR("ERROR: span tag must be of the form \"i,j\": " << line << endl);
return res;
}
tagStart = atoi(ij[0].c_str());
tagEnd = atoi(ij[1].c_str());
if (tagEnd < tagStart) {
TRACE_ERR("ERROR: span tag " << span << " invalid" << endl);
return res;
}
doClose = true;
VERBOSE(3,"XML TAG IS UNARY" << endl);
}
VERBOSE(3,"XML TAG NAME IS: '" << tagName << "'" << endl);
VERBOSE(3,"XML TAG ENGLISH IS: '" << altTexts[0] << "'" << endl);
VERBOSE(3,"XML TAG PROB IS: '" << altProbs[0] << "'" << endl);
VERBOSE(3,"XML TAG STARTS AT WORD: " << tagStart << endl);
if (altTexts.size() != altProbs.size()) {
TRACE_ERR("ERROR: Unequal number of probabilities and translation alternatives: " << line << endl);
return res;
}
}
else if ((nextTagName.size() == 0) || (nextTagName.at(0) != '/') || (nextTagName.substr(1) != tagName))
{
//mismatched tag, abort!
TRACE_ERR("ERROR: tried to parse malformed XML with xml-input enabled: " << line << endl);
return res;
}
else {
doClose = true;
tagEnd = curWord-1; //size is inclusive
}
if (doClose) {
VERBOSE(3,"XML END TAG IS: " << nextTagName.substr(1) << endl);
VERBOSE(3,"XML TAG ENDS AT WORD: " << tagEnd << endl);
//store translation options into members
//TODO: deal with multiple XML options here
if (StaticData::Instance().GetXmlInputType() != XmlIgnore) {
for (size_t i=0; i<altTexts.size(); ++i) {
//only store options if we aren't ignoring them
//set default probability
float probValue = 1;
if (altProbs[i] != "") probValue = Scan<float>(altProbs[i]);
//Convert from prob to log-prob
float scoreValue = FloorScore(TransformScore(probValue));
XmlOption option(tagStart,tagEnd,altTexts[i],scoreValue);
res.push_back(option);
}
}
tagName= "";
tagContents = "";
altTexts.clear();
altProbs.clear();
doClose = false;
}
}
}
line = rstr;
return res;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/lib/stdio.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* COPYRIGHT International Business Machines Corp. 2011,2014 */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <stdint.h>
#include <stdio.h>
#include <util/sprintf.H>
class SprintfBuffer : public Util::ConsoleBufferInterface
{
public:
int putc(int c)
{
if ('\b' == c)
{
iv_pos--;
}
else if (iv_pos < iv_size)
{
iv_buffer[iv_pos++] = c;
}
else
{
iv_pos++;
}
return c;
}
explicit SprintfBuffer(char* buf, size_t size = UINT64_MAX) :
iv_pos(0), iv_size(size), iv_buffer(buf) {};
size_t operator()(int c) { return putc(c); }
private:
size_t iv_pos;
size_t iv_size;
char * iv_buffer;
};
int sprintf(char *str, const char * format, ...)
{
using Util::vasprintf;
va_list args;
va_start(args, format);
SprintfBuffer console(str);
size_t count = vasprintf(console, format, args);
va_end(args);
console.putc('\0');
return count;
}
int snprintf(char *str, size_t size, const char * format, ...)
{
using Util::vasprintf;
va_list args;
va_start(args, format);
SprintfBuffer console(str, size);
size_t count = vasprintf(console, format, args);
va_end(args);
console.putc('\0');
return count;
}
int vsprintf(char *str, const char * format, va_list args)
{
using Util::vasprintf;
SprintfBuffer console(str);
size_t count = vasprintf(console, format, args);
console.putc('\0');
return count;
}
int vsnprintf(char *str, size_t size, const char * format, va_list args)
{
SprintfBuffer console(str, size);
size_t count = vasprintf(console, format, args);
console.putc('\0');
return count;
}
<commit_msg>Make snprintf always terminate the output buffer<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/lib/stdio.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2011,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <stdint.h>
#include <stdio.h>
#include <util/sprintf.H>
class SprintfBuffer : public Util::ConsoleBufferInterface
{
public:
int putc(int c)
{
if ('\b' == c)
{
if (iv_pos > 0)
{
iv_pos--;
}
}
else if (iv_pos < iv_size)
{
iv_buffer[iv_pos++] = c;
}
else
{
iv_pos++;
}
return c;
}
void nullTerminate()
{
if (iv_size > 0)
{
if (iv_pos >= iv_size)
{
iv_pos = iv_size - 1;
}
putc('\0');
}
}
explicit SprintfBuffer(char* buf, size_t size = UINT64_MAX) :
iv_pos(0), iv_size(size), iv_buffer(buf) {};
size_t operator()(int c) { return putc(c); }
private:
size_t iv_pos;
size_t iv_size;
char * iv_buffer;
};
int sprintf(char *str, const char * format, ...)
{
using Util::vasprintf;
va_list args;
va_start(args, format);
SprintfBuffer console(str);
size_t count = vasprintf(console, format, args);
va_end(args);
console.nullTerminate();
return count;
}
int snprintf(char *str, size_t size, const char * format, ...)
{
using Util::vasprintf;
va_list args;
va_start(args, format);
SprintfBuffer console(str, size);
size_t count = vasprintf(console, format, args);
va_end(args);
console.nullTerminate();
return count;
}
int vsprintf(char *str, const char * format, va_list args)
{
using Util::vasprintf;
SprintfBuffer console(str);
size_t count = vasprintf(console, format, args);
console.nullTerminate();
return count;
}
int vsnprintf(char *str, size_t size, const char * format, va_list args)
{
SprintfBuffer console(str, size);
size_t count = vasprintf(console, format, args);
console.nullTerminate();
return count;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(DART_HOST_OS_MACOS)
#include "bin/platform.h"
#include "bin/platform_macos.h"
#include <CoreFoundation/CoreFoundation.h>
#if !DART_HOST_OS_IOS
#include <crt_externs.h> // NOLINT
#endif // !DART_HOST_OS_IOS
#include <errno.h> // NOLINT
#include <mach-o/dyld.h>
#include <signal.h> // NOLINT
#include <sys/resource.h> // NOLINT
#include <sys/sysctl.h> // NOLINT
#include <sys/types.h> // NOLINT
#include <sys/utsname.h> // NOLINT
#include <unistd.h> // NOLINT
#include <string>
#include "bin/console.h"
#include "bin/file.h"
#include "bin/platform_macos_cocoa.h"
namespace dart {
namespace bin {
const char* Platform::executable_name_ = NULL;
int Platform::script_index_ = 1;
char** Platform::argv_ = NULL;
static void segv_handler(int signal, siginfo_t* siginfo, void* context) {
Syslog::PrintErr(
"\n===== CRASH =====\n"
"si_signo=%s(%d), si_code=%d, si_addr=%p\n",
strsignal(siginfo->si_signo), siginfo->si_signo, siginfo->si_code,
siginfo->si_addr);
Dart_DumpNativeStackTrace(context);
Dart_PrepareToAbort();
abort();
}
bool Platform::Initialize() {
// Turn off the signal handler for SIGPIPE as it causes the process
// to terminate on writing to a closed pipe. Without the signal
// handler error EPIPE is set instead.
struct sigaction act = {};
act.sa_handler = SIG_IGN;
if (sigaction(SIGPIPE, &act, 0) != 0) {
perror("Setting signal handler failed");
return false;
}
// tcsetattr raises SIGTTOU if we try to set console attributes when
// backgrounded, which suspends the process. Ignoring the signal prevents
// us from being suspended and lets us fail gracefully instead.
sigset_t signal_mask;
sigemptyset(&signal_mask);
sigaddset(&signal_mask, SIGTTOU);
if (sigprocmask(SIG_BLOCK, &signal_mask, NULL) < 0) {
perror("Setting signal handler failed");
return false;
}
act.sa_flags = SA_SIGINFO;
act.sa_sigaction = &segv_handler;
if (sigemptyset(&act.sa_mask) != 0) {
perror("sigemptyset() failed.");
return false;
}
if (sigaddset(&act.sa_mask, SIGPROF) != 0) {
perror("sigaddset() failed");
return false;
}
if (sigaction(SIGSEGV, &act, NULL) != 0) {
perror("sigaction() failed.");
return false;
}
if (sigaction(SIGBUS, &act, NULL) != 0) {
perror("sigaction() failed.");
return false;
}
if (sigaction(SIGTRAP, &act, NULL) != 0) {
perror("sigaction() failed.");
return false;
}
if (sigaction(SIGILL, &act, NULL) != 0) {
perror("sigaction() failed.");
return false;
}
return true;
}
int Platform::NumberOfProcessors() {
int32_t cpus = -1;
size_t cpus_length = sizeof(cpus);
if (sysctlbyname("hw.logicalcpu", &cpus, &cpus_length, NULL, 0) == 0) {
return cpus;
} else {
// Failed, fallback to using sysconf.
return sysconf(_SC_NPROCESSORS_ONLN);
}
}
const char* Platform::OperatingSystem() {
#if DART_HOST_OS_IOS
return "ios";
#else
return "macos";
#endif
}
const char* Platform::OperatingSystemVersion() {
std::string version(NSProcessInfoOperatingSystemVersionString());
return DartUtils::ScopedCopyCString(version.c_str());
}
const char* Platform::LibraryPrefix() {
return "lib";
}
const char* Platform::LibraryExtension() {
return "dylib";
}
static const char* GetLocaleName() {
CFLocaleRef locale = CFLocaleCopyCurrent();
CFStringRef locale_string = CFLocaleGetIdentifier(locale);
CFIndex len = CFStringGetLength(locale_string);
CFIndex max_len =
CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;
char* result = reinterpret_cast<char*>(Dart_ScopeAllocate(max_len));
ASSERT(result != NULL);
bool success =
CFStringGetCString(locale_string, result, max_len, kCFStringEncodingUTF8);
CFRelease(locale);
if (!success) {
return NULL;
}
return result;
}
static const char* GetPreferredLanguageName() {
CFArrayRef languages = CFLocaleCopyPreferredLanguages();
CFIndex languages_length = CFArrayGetCount(languages);
if (languages_length < 1) {
CFRelease(languages);
return NULL;
}
CFTypeRef item =
reinterpret_cast<CFTypeRef>(CFArrayGetValueAtIndex(languages, 0));
CFTypeID item_type = CFGetTypeID(item);
ASSERT(item_type == CFStringGetTypeID());
CFStringRef language = reinterpret_cast<CFStringRef>(item);
CFIndex len = CFStringGetLength(language);
CFIndex max_len =
CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;
char* result = reinterpret_cast<char*>(Dart_ScopeAllocate(max_len));
ASSERT(result != NULL);
bool success =
CFStringGetCString(language, result, max_len, kCFStringEncodingUTF8);
CFRelease(languages);
if (!success) {
return NULL;
}
return result;
}
const char* Platform::LocaleName() {
// First see if there is a preferred language. If not, return the
// current locale name.
const char* preferred_language = GetPreferredLanguageName();
return (preferred_language != NULL) ? preferred_language : GetLocaleName();
}
bool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {
return gethostname(buffer, buffer_length) == 0;
}
char** Platform::Environment(intptr_t* count) {
#if DART_HOST_OS_IOS
// TODO(zra,chinmaygarde): On iOS, environment variables are seldom used. Wire
// this up if someone needs it. In the meantime, we return an empty array.
char** result;
result = reinterpret_cast<char**>(Dart_ScopeAllocate(1 * sizeof(*result)));
if (result == NULL) {
return NULL;
}
result[0] = NULL;
*count = 0;
return result;
#else
// Using environ directly is only safe as long as we do not
// provide access to modifying environment variables.
// On MacOS you have to do a bit of magic to get to the
// environment strings.
char** environ = *(_NSGetEnviron());
intptr_t i = 0;
char** tmp = environ;
while (*(tmp++) != NULL) {
i++;
}
*count = i;
char** result;
result = reinterpret_cast<char**>(Dart_ScopeAllocate(i * sizeof(*result)));
for (intptr_t current = 0; current < i; current++) {
result[current] = environ[current];
}
return result;
#endif
}
const char* Platform::GetExecutableName() {
return executable_name_;
}
const char* Platform::ResolveExecutablePath() {
// Get the required length of the buffer.
uint32_t path_size = 0;
if (_NSGetExecutablePath(NULL, &path_size) == 0) {
return NULL;
}
// Allocate buffer and get executable path.
char* path = DartUtils::ScopedCString(path_size);
if (_NSGetExecutablePath(path, &path_size) != 0) {
return NULL;
}
// Return the canonical path as the returned path might contain symlinks.
const char* canon_path = File::GetCanonicalPath(NULL, path);
return canon_path;
}
intptr_t Platform::ResolveExecutablePathInto(char* result, size_t result_size) {
// Get the required length of the buffer.
uint32_t path_size = 0;
if (_NSGetExecutablePath(nullptr, &path_size) == 0) {
return -1;
}
if (path_size > result_size) {
return -1;
}
if (_NSGetExecutablePath(result, &path_size) != 0) {
return -1;
}
return path_size;
}
void Platform::SetProcessName(const char* name) {}
void Platform::Exit(int exit_code) {
Console::RestoreConfig();
Dart_PrepareToAbort();
exit(exit_code);
}
void Platform::SetCoreDumpResourceLimit(int value) {
rlimit limit = {static_cast<rlim_t>(value), static_cast<rlim_t>(value)};
setrlimit(RLIMIT_CORE, &limit);
}
} // namespace bin
} // namespace dart
#endif // defined(DART_HOST_OS_MACOS)
<commit_msg>[standalone, mac] Set the process title based on the main script.<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(DART_HOST_OS_MACOS)
#include "bin/platform.h"
#include "bin/platform_macos.h"
#include <CoreFoundation/CoreFoundation.h>
#if !DART_HOST_OS_IOS
#include <crt_externs.h> // NOLINT
#endif // !DART_HOST_OS_IOS
#include <dlfcn.h> // NOLINT
#include <errno.h> // NOLINT
#include <mach-o/dyld.h>
#include <signal.h> // NOLINT
#include <sys/resource.h> // NOLINT
#include <sys/sysctl.h> // NOLINT
#include <sys/types.h> // NOLINT
#include <sys/utsname.h> // NOLINT
#include <unistd.h> // NOLINT
#include <string>
#include "bin/console.h"
#include "bin/file.h"
#include "bin/platform_macos_cocoa.h"
namespace dart {
namespace bin {
const char* Platform::executable_name_ = NULL;
int Platform::script_index_ = 1;
char** Platform::argv_ = NULL;
static void segv_handler(int signal, siginfo_t* siginfo, void* context) {
Syslog::PrintErr(
"\n===== CRASH =====\n"
"si_signo=%s(%d), si_code=%d, si_addr=%p\n",
strsignal(siginfo->si_signo), siginfo->si_signo, siginfo->si_code,
siginfo->si_addr);
Dart_DumpNativeStackTrace(context);
Dart_PrepareToAbort();
abort();
}
bool Platform::Initialize() {
// Turn off the signal handler for SIGPIPE as it causes the process
// to terminate on writing to a closed pipe. Without the signal
// handler error EPIPE is set instead.
struct sigaction act = {};
act.sa_handler = SIG_IGN;
if (sigaction(SIGPIPE, &act, 0) != 0) {
perror("Setting signal handler failed");
return false;
}
// tcsetattr raises SIGTTOU if we try to set console attributes when
// backgrounded, which suspends the process. Ignoring the signal prevents
// us from being suspended and lets us fail gracefully instead.
sigset_t signal_mask;
sigemptyset(&signal_mask);
sigaddset(&signal_mask, SIGTTOU);
if (sigprocmask(SIG_BLOCK, &signal_mask, NULL) < 0) {
perror("Setting signal handler failed");
return false;
}
act.sa_flags = SA_SIGINFO;
act.sa_sigaction = &segv_handler;
if (sigemptyset(&act.sa_mask) != 0) {
perror("sigemptyset() failed.");
return false;
}
if (sigaddset(&act.sa_mask, SIGPROF) != 0) {
perror("sigaddset() failed");
return false;
}
if (sigaction(SIGSEGV, &act, NULL) != 0) {
perror("sigaction() failed.");
return false;
}
if (sigaction(SIGBUS, &act, NULL) != 0) {
perror("sigaction() failed.");
return false;
}
if (sigaction(SIGTRAP, &act, NULL) != 0) {
perror("sigaction() failed.");
return false;
}
if (sigaction(SIGILL, &act, NULL) != 0) {
perror("sigaction() failed.");
return false;
}
return true;
}
int Platform::NumberOfProcessors() {
int32_t cpus = -1;
size_t cpus_length = sizeof(cpus);
if (sysctlbyname("hw.logicalcpu", &cpus, &cpus_length, NULL, 0) == 0) {
return cpus;
} else {
// Failed, fallback to using sysconf.
return sysconf(_SC_NPROCESSORS_ONLN);
}
}
const char* Platform::OperatingSystem() {
#if DART_HOST_OS_IOS
return "ios";
#else
return "macos";
#endif
}
const char* Platform::OperatingSystemVersion() {
std::string version(NSProcessInfoOperatingSystemVersionString());
return DartUtils::ScopedCopyCString(version.c_str());
}
const char* Platform::LibraryPrefix() {
return "lib";
}
const char* Platform::LibraryExtension() {
return "dylib";
}
static const char* GetLocaleName() {
CFLocaleRef locale = CFLocaleCopyCurrent();
CFStringRef locale_string = CFLocaleGetIdentifier(locale);
CFIndex len = CFStringGetLength(locale_string);
CFIndex max_len =
CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;
char* result = reinterpret_cast<char*>(Dart_ScopeAllocate(max_len));
ASSERT(result != NULL);
bool success =
CFStringGetCString(locale_string, result, max_len, kCFStringEncodingUTF8);
CFRelease(locale);
if (!success) {
return NULL;
}
return result;
}
static const char* GetPreferredLanguageName() {
CFArrayRef languages = CFLocaleCopyPreferredLanguages();
CFIndex languages_length = CFArrayGetCount(languages);
if (languages_length < 1) {
CFRelease(languages);
return NULL;
}
CFTypeRef item =
reinterpret_cast<CFTypeRef>(CFArrayGetValueAtIndex(languages, 0));
CFTypeID item_type = CFGetTypeID(item);
ASSERT(item_type == CFStringGetTypeID());
CFStringRef language = reinterpret_cast<CFStringRef>(item);
CFIndex len = CFStringGetLength(language);
CFIndex max_len =
CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;
char* result = reinterpret_cast<char*>(Dart_ScopeAllocate(max_len));
ASSERT(result != NULL);
bool success =
CFStringGetCString(language, result, max_len, kCFStringEncodingUTF8);
CFRelease(languages);
if (!success) {
return NULL;
}
return result;
}
const char* Platform::LocaleName() {
// First see if there is a preferred language. If not, return the
// current locale name.
const char* preferred_language = GetPreferredLanguageName();
return (preferred_language != NULL) ? preferred_language : GetLocaleName();
}
bool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {
return gethostname(buffer, buffer_length) == 0;
}
char** Platform::Environment(intptr_t* count) {
#if DART_HOST_OS_IOS
// TODO(zra,chinmaygarde): On iOS, environment variables are seldom used. Wire
// this up if someone needs it. In the meantime, we return an empty array.
char** result;
result = reinterpret_cast<char**>(Dart_ScopeAllocate(1 * sizeof(*result)));
if (result == NULL) {
return NULL;
}
result[0] = NULL;
*count = 0;
return result;
#else
// Using environ directly is only safe as long as we do not
// provide access to modifying environment variables.
// On MacOS you have to do a bit of magic to get to the
// environment strings.
char** environ = *(_NSGetEnviron());
intptr_t i = 0;
char** tmp = environ;
while (*(tmp++) != NULL) {
i++;
}
*count = i;
char** result;
result = reinterpret_cast<char**>(Dart_ScopeAllocate(i * sizeof(*result)));
for (intptr_t current = 0; current < i; current++) {
result[current] = environ[current];
}
return result;
#endif
}
const char* Platform::GetExecutableName() {
return executable_name_;
}
const char* Platform::ResolveExecutablePath() {
// Get the required length of the buffer.
uint32_t path_size = 0;
if (_NSGetExecutablePath(NULL, &path_size) == 0) {
return NULL;
}
// Allocate buffer and get executable path.
char* path = DartUtils::ScopedCString(path_size);
if (_NSGetExecutablePath(path, &path_size) != 0) {
return NULL;
}
// Return the canonical path as the returned path might contain symlinks.
const char* canon_path = File::GetCanonicalPath(NULL, path);
return canon_path;
}
intptr_t Platform::ResolveExecutablePathInto(char* result, size_t result_size) {
// Get the required length of the buffer.
uint32_t path_size = 0;
if (_NSGetExecutablePath(nullptr, &path_size) == 0) {
return -1;
}
if (path_size > result_size) {
return -1;
}
if (_NSGetExecutablePath(result, &path_size) != 0) {
return -1;
}
return path_size;
}
void Platform::SetProcessName(const char* name) {
pthread_setname_np(name);
#if !defined(DART_HOST_OS_IOS) && !defined(DART_PRECOMPILED_RUNTIME)
// Attempt to set the name displayed in ActivityMonitor.
// https://codereview.chromium.org/659007/
class ScopedDLHandle : public ValueObject {
public:
explicit ScopedDLHandle(void* handle) : handle_(handle) {}
~ScopedDLHandle() {
if (handle_ != NULL) dlclose(handle_);
}
void* get() const { return handle_; }
private:
void* handle_;
DISALLOW_COPY_AND_ASSIGN(ScopedDLHandle);
};
class ScopedCFStringRef : public ValueObject {
public:
explicit ScopedCFStringRef(const char* s)
: ref_(CFStringCreateWithCString(NULL, (s), kCFStringEncodingUTF8)) {}
~ScopedCFStringRef() {
if (ref_ != NULL) CFRelease(ref_);
}
CFStringRef get() const { return ref_; }
private:
CFStringRef ref_;
DISALLOW_COPY_AND_ASSIGN(ScopedCFStringRef);
};
ScopedDLHandle application_services_handle(
dlopen("/System/Library/Frameworks/ApplicationServices.framework/"
"Versions/A/ApplicationServices",
RTLD_LAZY | RTLD_LOCAL));
if (application_services_handle.get() == NULL) return;
ScopedCFStringRef launch_services_bundle_name("com.apple.LaunchServices");
CFBundleRef launch_services_bundle =
CFBundleGetBundleWithIdentifier(launch_services_bundle_name.get());
if (launch_services_bundle == NULL) return;
#define GET_FUNC(name, cstr) \
ScopedCFStringRef name##_id(cstr); \
*reinterpret_cast<void**>(&name) = CFBundleGetFunctionPointerForName( \
launch_services_bundle, name##_id.get()); \
if (name == NULL) return;
#define GET_DATA(name, cstr) \
ScopedCFStringRef name##_id(cstr); \
*reinterpret_cast<void**>(&name) = \
CFBundleGetDataPointerForName(launch_services_bundle, name##_id.get()); \
if (name == NULL) return;
CFTypeRef (*_LSGetCurrentApplicationASN)(void);
GET_FUNC(_LSGetCurrentApplicationASN, "_LSGetCurrentApplicationASN");
OSStatus (*_LSSetApplicationInformationItem)(int, CFTypeRef, CFStringRef,
CFStringRef, CFDictionaryRef*);
GET_FUNC(_LSSetApplicationInformationItem,
"_LSSetApplicationInformationItem");
CFDictionaryRef (*_LSApplicationCheckIn)(int, CFDictionaryRef);
GET_FUNC(_LSApplicationCheckIn, "_LSApplicationCheckIn");
void (*_LSSetApplicationLaunchServicesServerConnectionStatus)(uint64_t,
void*);
GET_FUNC(_LSSetApplicationLaunchServicesServerConnectionStatus,
"_LSSetApplicationLaunchServicesServerConnectionStatus");
CFStringRef* _kLSDisplayNameKey;
GET_DATA(_kLSDisplayNameKey, "_kLSDisplayNameKey");
if (*_kLSDisplayNameKey == NULL) return;
_LSSetApplicationLaunchServicesServerConnectionStatus(0, NULL);
_LSApplicationCheckIn(-2, CFBundleGetInfoDictionary(CFBundleGetMainBundle()));
CFTypeRef asn;
asn = _LSGetCurrentApplicationASN();
if (asn == NULL) return;
ScopedCFStringRef cf_name(name);
_LSSetApplicationInformationItem(-2, asn, *_kLSDisplayNameKey, cf_name.get(),
NULL);
#undef GET_DATA
#undef GET_FUNC
#endif // !defined(DART_HOST_OS_IOS)
}
void Platform::Exit(int exit_code) {
Console::RestoreConfig();
Dart_PrepareToAbort();
exit(exit_code);
}
void Platform::SetCoreDumpResourceLimit(int value) {
rlimit limit = {static_cast<rlim_t>(value), static_cast<rlim_t>(value)};
setrlimit(RLIMIT_CORE, &limit);
}
} // namespace bin
} // namespace dart
#endif // defined(DART_HOST_OS_MACOS)
<|endoftext|>
|
<commit_before>
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef RASTER_COLORIZER_HPP
#define RASTER_COLORIZER_HPP
#include <mapnik/config.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/color.hpp>
#include <mapnik/feature.hpp>
#include <vector>
using mapnik::color;
using std::vector;
namespace mapnik
{
struct MAPNIK_DECL color_band
{
float value_;
color color_;
unsigned midpoints_;
bool is_interpolated_;
color_band(float value, color c)
: value_(value),
color_(c),
midpoints_(0),
is_interpolated_(false) {}
const bool is_interpolated() const
{
return is_interpolated_;
}
const unsigned get_midpoints() const
{
return midpoints_;
}
const float get_value() const
{
return value_;
}
const color& get_color() const
{
return color_;
}
bool operator==(color_band const& other) const
{
return value_ == other.value_ && color_ == other.color_;
}
std::string to_string() const
{
std::stringstream ss;
ss << color_.to_string() << " " << value_;
return ss.str();
}
};
typedef vector<color_band> color_bands;
struct MAPNIK_DECL raster_colorizer
{
explicit raster_colorizer()
: colors_() {}
raster_colorizer(const raster_colorizer &ps)
: colors_(ps.colors_) {}
raster_colorizer(color_bands &colors)
: colors_(colors) {}
const color_bands& get_color_bands() const
{
return colors_;
}
void append_band (color_band band)
{
if (colors_.size() > 0 && colors_.back().value_ > band.value_) {
#ifdef MAPNIK_DEBUG
std::clog << "prev.v=" << colors_.back().value_ << ". band.v=" << band.value_ << "\n";
#endif
throw config_error(
"Bands must be appended in ascending value order"
);
}
colors_.push_back(band);
}
void append_band (color_band band, unsigned midpoints)
{
band.midpoints_ = midpoints;
if (colors_.size() > 0 && midpoints > 0) {
color_band lo = colors_.back();
color_band const &hi = band;
int steps = midpoints+1;
float dv = (hi.value_ - lo.value_)/steps;
float da = (float(hi.color_.alpha()) - lo.color_.alpha())/steps;
float dr = (float(hi.color_.red()) - lo.color_.red())/steps;
float dg = (float(hi.color_.green()) - lo.color_.green())/steps;
float db = (float(hi.color_.blue()) - lo.color_.blue())/steps;
#ifdef MAPNIK_DEBUG
std::clog << "lo.v=" << lo.value_ << ", hi.v=" << hi.value_ << ", dv="<<dv<<"\n";
#endif
// interpolate intermediate values and colors
int j;
for (j=1; j<steps; j++) {
color_band b(
lo.get_value() + dv*j,
color(int(float(lo.color_.red()) + dr*j),
int(float(lo.color_.green()) + dg*j),
int(float(lo.color_.blue()) + db*j),
int(float(lo.color_.alpha()) + da*j)
)
);
b.is_interpolated_ = true;
append_band(b);
}
}
append_band(band);
}
void append_band (float value, color c)
{
append_band(color_band(value, c));
}
void append_band (float value, color c, unsigned midpoints)
{
append_band(color_band(value, c), midpoints);
}
/* rgba =
* if cs[pos].value <= value < cs[pos+1].value: cs[pos].color
* otherwise: transparent
* where 0 <= pos < length(bands)-1
* Last band is special, its value represents the upper bound and its
* color will only be used if the value matches its value exactly.
*/
color get_color(float value) const {
int pos=-1, last=(int)colors_.size()-1, lo=0, hi=last;
while (lo<=hi) {
pos = (lo+hi)/2;
if (colors_[pos].value_<value) {
lo = pos+1;
} else if (colors_[pos].value_>value) {
hi = pos-1;
} else {
lo = pos+1;
break;
}
}
lo--;
if ((0 <= lo && lo < last) ||
(lo==last && colors_[last].value_==value))
return colors_[lo].color_;
else
return color(0,0,0,0);
}
void colorize(mapnik::raster_ptr const& raster) const {
float *rasterData = (float*)raster->data_.getBytes();
unsigned *imageData = raster->data_.getData();
unsigned i;
for (i=0; i<raster->data_.width()*raster->data_.height(); i++)
imageData[i] = get_color(rasterData[i]).rgba();
}
private:
color_bands colors_;
};
typedef boost::shared_ptr<mapnik::raster_colorizer> raster_colorizer_ptr;
}
#endif //RASTER_COLORIZER_HPP
<commit_msg>+ remove mapnik:: classification from inside namespace mapnik {} + use c++ style casts!<commit_after>
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef RASTER_COLORIZER_HPP
#define RASTER_COLORIZER_HPP
#include <mapnik/config.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/color.hpp>
#include <mapnik/feature.hpp>
#include <vector>
namespace mapnik
{
struct MAPNIK_DECL color_band
{
float value_;
color color_;
unsigned midpoints_;
bool is_interpolated_;
color_band(float value, color c)
: value_(value),
color_(c),
midpoints_(0),
is_interpolated_(false) {}
const bool is_interpolated() const
{
return is_interpolated_;
}
const unsigned get_midpoints() const
{
return midpoints_;
}
const float get_value() const
{
return value_;
}
const color& get_color() const
{
return color_;
}
bool operator==(color_band const& other) const
{
return value_ == other.value_ && color_ == other.color_;
}
std::string to_string() const
{
std::stringstream ss;
ss << color_.to_string() << " " << value_;
return ss.str();
}
};
typedef std::vector<color_band> color_bands;
struct MAPNIK_DECL raster_colorizer
{
explicit raster_colorizer()
: colors_() {}
raster_colorizer(const raster_colorizer &ps)
: colors_(ps.colors_) {}
raster_colorizer(color_bands &colors)
: colors_(colors) {}
const color_bands& get_color_bands() const
{
return colors_;
}
void append_band (color_band band)
{
if (colors_.size() > 0 && colors_.back().value_ > band.value_) {
#ifdef MAPNIK_DEBUG
std::clog << "prev.v=" << colors_.back().value_ << ". band.v=" << band.value_ << "\n";
#endif
throw config_error(
"Bands must be appended in ascending value order"
);
}
colors_.push_back(band);
}
void append_band (color_band band, unsigned midpoints)
{
band.midpoints_ = midpoints;
if (colors_.size() > 0 && midpoints > 0) {
color_band lo = colors_.back();
color_band const &hi = band;
int steps = midpoints+1;
float dv = (hi.value_ - lo.value_)/steps;
float da = (float(hi.color_.alpha()) - lo.color_.alpha())/steps;
float dr = (float(hi.color_.red()) - lo.color_.red())/steps;
float dg = (float(hi.color_.green()) - lo.color_.green())/steps;
float db = (float(hi.color_.blue()) - lo.color_.blue())/steps;
#ifdef MAPNIK_DEBUG
std::clog << "lo.v=" << lo.value_ << ", hi.v=" << hi.value_ << ", dv="<<dv<<"\n";
#endif
// interpolate intermediate values and colors
int j;
for (j=1; j<steps; j++) {
color_band b(
lo.get_value() + dv*j,
color(int(float(lo.color_.red()) + dr*j),
int(float(lo.color_.green()) + dg*j),
int(float(lo.color_.blue()) + db*j),
int(float(lo.color_.alpha()) + da*j)
)
);
b.is_interpolated_ = true;
append_band(b);
}
}
append_band(band);
}
void append_band (float value, color c)
{
append_band(color_band(value, c));
}
void append_band (float value, color c, unsigned midpoints)
{
append_band(color_band(value, c), midpoints);
}
/* rgba =
* if cs[pos].value <= value < cs[pos+1].value: cs[pos].color
* otherwise: transparent
* where 0 <= pos < length(bands)-1
* Last band is special, its value represents the upper bound and its
* color will only be used if the value matches its value exactly.
*/
color get_color(float value) const {
int pos=-1, last=(int)colors_.size()-1, lo=0, hi=last;
while (lo<=hi) {
pos = (lo+hi)/2;
if (colors_[pos].value_<value) {
lo = pos+1;
} else if (colors_[pos].value_>value) {
hi = pos-1;
} else {
lo = pos+1;
break;
}
}
lo--;
if ((0 <= lo && lo < last) ||
(lo==last && colors_[last].value_==value))
return colors_[lo].color_;
else
return color(0,0,0,0);
}
void colorize(raster_ptr const& raster) const
{
float *rasterData = reinterpret_cast<float*>(raster->data_.getBytes());
unsigned *imageData = raster->data_.getData();
unsigned i;
for (i=0; i<raster->data_.width()*raster->data_.height(); i++)
{
imageData[i] = get_color(rasterData[i]).rgba();
}
}
private:
color_bands colors_;
};
typedef boost::shared_ptr<raster_colorizer> raster_colorizer_ptr;
} // mapnik namespace
#endif //RASTER_COLORIZER_HPP
<|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include <unordered_map>
#include <glm/glm.hpp>
#include "nova_renderer/rhi_enums.hpp"
#include "device_memory_resource.hpp"
#include "shaderpack_data.hpp"
namespace nova::renderer::rhi {
#pragma region Structs
struct BufferCreateInfo {
uint64_t size = 0;
BufferUsage buffer_usage{};
};
struct DeviceMemory {};
/*!
* \brief A resource
*
* Resources may by dynamic of static. Dynamic resources are updated after they are created, possibly by a shader,
* while static resources are loaded once and that's that
*/
struct Resource {
ResourceType type = {};
bool is_dynamic = true;
};
struct Sampler {};
struct Image : Resource {
bool is_depth_tex = false;
};
struct Buffer : Resource {
uint32_t size = 0;
};
struct Framebuffer {
glm::uvec2 size;
uint32_t num_attachments;
};
struct Renderpass {};
struct ResourceBindingDescription {
/*!
* \brief Descriptor set that his binding belongs to
*/
uint32_t set;
/*!
* \brief Binding of this resource binding
*/
uint32_t binding;
/*!
* \brief Number of bindings. Useful if you have an array of descriptors
*
* If this is a unbounded array, this count is the upper limit on the size of the array
*/
uint32_t count;
/*!
* \brief If true, this binding is an unbounded array
*
* Unbounded descriptors must be the final binding in their descriptor set
*/
bool is_unbounded;
/*!
* \brief The type of object that will be bound
*/
DescriptorType type;
/*!
* \brief The shader stages that need access to this binding
*/
ShaderStageFlags stages;
bool operator==(const ResourceBindingDescription& other);
bool operator!=(const ResourceBindingDescription& other);
};
/*!
* \brief The interface for a pipeline. Includes both inputs (descriptors) and outputs (framebuffers)
*/
struct PipelineInterface {
std::unordered_map<std::string, ResourceBindingDescription> bindings;
};
struct Pipeline {};
struct Semaphore {};
struct PresentSemaphore {};
struct Fence {};
struct DescriptorPool {};
struct DescriptorSet {};
// TODO: This struct actually maps pretty directly to a Vulkan barrier, so it doesn't map well to a D3D12 barrier. Figure out how to
// make it D3D12-friendly
struct ResourceBarrier {
Resource* resource_to_barrier;
/*!
* \brief The resource access that much finish before this barrier executed
*/
AccessFlags access_before_barrier;
/*!
* \brief The resource access that must wait for this battier to finish executing
*/
AccessFlags access_after_barrier;
/*!
* \brief How you're going to access this resource just before this barrier
*
* Will a shader read from it before the barrier? Will the fragment depth by copied to a depth buffer before
* this barrier? Will the resource be used as a indirect draw command buffer right before this barrier?
*/
ResourceState old_state;
/*!
* \brief How you're going to access this resource after this barrier
*
* Will a shader read from it after the barrier? Will the fragment depth by copied to a depth buffer after
* this barrier? Will the resource be used as a indirect draw command buffer right after this barrier?
*/
ResourceState new_state;
QueueType source_queue;
QueueType destination_queue;
union {
struct {
ImageAspectFlags aspect;
} image_memory_barrier;
struct {
uint64_t offset;
uint64_t size;
} buffer_memory_barrier;
};
};
struct DescriptorImageUpdate {
const Image* image;
shaderpack::TextureFormat format;
Sampler* sampler;
};
struct DescriptorBufferWrite {
const Buffer* buffer;
};
struct DescriptorSetWrite {
/*!
* \brief Pointer to the descriptor set to write to
*/
DescriptorSet* set;
/*!
* \brief The specific binding in the set that you want to write to
*/
uint32_t binding;
/*!
* \brief The type of descriptor you're writing to
*/
DescriptorType type;
union {
/*!
* \brief Information to update an image descriptor
*/
DescriptorImageUpdate image_info;
/*!
* \brief Information to update a buffer descriptor
*/
DescriptorBufferWrite buffer_info;
};
};
#pragma endregion
ShaderStageFlags operator|=(ShaderStageFlags lhs, ShaderStageFlags rhs);
} // namespace nova::renderer::rhi
<commit_msg>[rhi] Support for updating descriptors as arrays of resources<commit_after>#pragma once
#include <string>
#include <unordered_map>
#include <glm/glm.hpp>
#include "nova_renderer/rhi_enums.hpp"
#include "device_memory_resource.hpp"
#include "shaderpack_data.hpp"
namespace nova::renderer::rhi {
#pragma region Structs
struct BufferCreateInfo {
uint64_t size = 0;
BufferUsage buffer_usage{};
};
struct DeviceMemory {};
/*!
* \brief A resource
*
* Resources may by dynamic of static. Dynamic resources are updated after they are created, possibly by a shader,
* while static resources are loaded once and that's that
*/
struct Resource {
ResourceType type = {};
bool is_dynamic = true;
};
struct Sampler {};
struct Image : Resource {
bool is_depth_tex = false;
};
struct Buffer : Resource {
uint32_t size = 0;
};
struct Framebuffer {
glm::uvec2 size;
uint32_t num_attachments;
};
struct Renderpass {};
struct ResourceBindingDescription {
/*!
* \brief Descriptor set that his binding belongs to
*/
uint32_t set;
/*!
* \brief Binding of this resource binding
*/
uint32_t binding;
/*!
* \brief Number of bindings. Useful if you have an array of descriptors
*
* If this is a unbounded array, this count is the upper limit on the size of the array
*/
uint32_t count;
/*!
* \brief If true, this binding is an unbounded array
*
* Unbounded descriptors must be the final binding in their descriptor set
*/
bool is_unbounded;
/*!
* \brief The type of object that will be bound
*/
DescriptorType type;
/*!
* \brief The shader stages that need access to this binding
*/
ShaderStageFlags stages;
bool operator==(const ResourceBindingDescription& other);
bool operator!=(const ResourceBindingDescription& other);
};
/*!
* \brief The interface for a pipeline. Includes both inputs (descriptors) and outputs (framebuffers)
*/
struct PipelineInterface {
std::unordered_map<std::string, ResourceBindingDescription> bindings;
};
struct Pipeline {};
struct Semaphore {};
struct PresentSemaphore {};
struct Fence {};
struct DescriptorPool {};
struct DescriptorSet {};
// TODO: This struct actually maps pretty directly to a Vulkan barrier, so it doesn't map well to a D3D12 barrier. Figure out how to
// make it D3D12-friendly
struct ResourceBarrier {
Resource* resource_to_barrier;
/*!
* \brief The resource access that much finish before this barrier executed
*/
AccessFlags access_before_barrier;
/*!
* \brief The resource access that must wait for this battier to finish executing
*/
AccessFlags access_after_barrier;
/*!
* \brief How you're going to access this resource just before this barrier
*
* Will a shader read from it before the barrier? Will the fragment depth by copied to a depth buffer before
* this barrier? Will the resource be used as a indirect draw command buffer right before this barrier?
*/
ResourceState old_state;
/*!
* \brief How you're going to access this resource after this barrier
*
* Will a shader read from it after the barrier? Will the fragment depth by copied to a depth buffer after
* this barrier? Will the resource be used as a indirect draw command buffer right after this barrier?
*/
ResourceState new_state;
QueueType source_queue;
QueueType destination_queue;
union {
struct {
ImageAspectFlags aspect;
} image_memory_barrier;
struct {
uint64_t offset;
uint64_t size;
} buffer_memory_barrier;
};
};
struct DescriptorImageInfo {
const Image* image;
shaderpack::TextureFormat format;
Sampler* sampler;
};
struct DescriptorBufferInfo {
const Buffer* buffer;
};
union DescriptorResourceInfo {
/*!
* \brief Information to update an image descriptor
*/
DescriptorImageInfo image_info;
/*!
* \brief Information to update a buffer descriptor
*/
DescriptorBufferInfo buffer_info;
};
struct DescriptorSetWrite {
/*!
* \brief Pointer to the descriptor set to write to
*/
DescriptorSet* set;
/*!
* \brief The specific binding in the set that you want to write to
*/
uint32_t first_binding;
/*!
* \brief The type of descriptor you're writing to
*/
DescriptorType type;
/*!
* \brief Information about th
*/
std::vector<DescriptorResourceInfo> bindings;
};
#pragma endregion
ShaderStageFlags operator|=(ShaderStageFlags lhs, ShaderStageFlags rhs);
} // namespace nova::renderer::rhi
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_clear_firs.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_xbus_clear_firs.C
/// @brief Clears I/O Firs
///-----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HWP Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team : IO
/// *HWP Level : 2
/// *HWP Consumed by : FSP:HB
///-----------------------------------------------------------------------------
///
/// @verbatim
/// High-level procedure flow:
///
/// Clears I/O Xbus FIRs on the PHY Rx/Tx.
///
/// Clocks must be running.
///
/// @endverbatim
///----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#include <p9_io_xbus_clear_firs.H>
#include <p9_io_gcr.H>
#include <p9_io_regs.H>
//-----------------------------------------------------------------------------
// Definitions
//-----------------------------------------------------------------------------
fapi2::ReturnCode io_rx_fir_reset(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group);
fapi2::ReturnCode io_tx_fir_reset(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group);
/**
* @brief A HWP that runs on every instance of the XBUS(EDI+)
* @param[in] i_target FAPI2 Target
* @param[in] i_clock_group Clock Group
* @retval ReturnCode
*/
fapi2::ReturnCode p9_io_xbus_clear_firs(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group)
{
FAPI_IMP("I/O Start Xbus Clear FIRs");
FAPI_TRY(io_tx_fir_reset(i_target, i_clock_group), "Tx Reset Failed");
FAPI_TRY(io_rx_fir_reset(i_target, i_clock_group), "Rx Reset Failed");
fapi_try_exit:
FAPI_IMP("I/O End Xbus Clear FIRs");
return fapi2::current_err;
}
/**
* @brief This function resets the Rx Firs on a EDI+ Xbus
* @param[in] i_target FAPI2 Target
* @param[in] i_clock_group Clock Group
* @retval ReturnCode
*/
fapi2::ReturnCode io_rx_fir_reset(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group)
{
Register < EDIP_RX_GLBSM_CNTLX1_EO_PG > rx_fir_reg;
FAPI_TRY(rx_fir_reg.read(i_target, i_clock_group),
"Reading Rx Fir Reg Failed");
rx_fir_reg.set<EDIP_RX_FIR_RESET>(0);
FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
"Writing Rx Fir Reg Failed");
rx_fir_reg.set<EDIP_RX_FIR_RESET>(1);
FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
"Writing rx Fir Reg Failed");
rx_fir_reg.set<EDIP_RX_FIR_RESET>(0);
FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),
"Writing Rx Fir Reg Failed");
fapi_try_exit:
return fapi2::current_err;
}
/**
* @brief This function resets the Tx Firs on a EDI+ Xbus
* @param[in] i_target FAPI2 Target
* @param[in] i_clock_group Clock Group
* @retval ReturnCode
*/
fapi2::ReturnCode io_tx_fir_reset(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group)
{
Register < EDIP_TX_FIR_RESET_PG > tx_fir_reg;
FAPI_TRY(tx_fir_reg.read(i_target, i_clock_group),
"Reading Tx Fir Reg Failed");
tx_fir_reg.set<EDIP_TX_FIR_RESET>(0);
FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
"Writing Tx Fir Reg Failed");
tx_fir_reg.set<EDIP_TX_FIR_RESET>(1);
FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
"Writing Tx Fir Reg Failed");
tx_fir_reg.set<EDIP_TX_FIR_RESET>(0);
FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),
"Writing Tx Fir Reg Failed");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>io scom access conversion<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_clear_firs.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_xbus_clear_firs.C
/// @brief Clears I/O Firs
///-----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HWP Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team : IO
/// *HWP Level : 2
/// *HWP Consumed by : FSP:HB
///-----------------------------------------------------------------------------
///
/// @verbatim
/// High-level procedure flow:
///
/// Clears I/O Xbus FIRs on the PHY Rx/Tx.
///
/// Clocks must be running.
///
/// @endverbatim
///----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#include <p9_io_xbus_clear_firs.H>
#include <p9_io_scom.H>
#include <p9_io_regs.H>
//-----------------------------------------------------------------------------
// Definitions
//-----------------------------------------------------------------------------
fapi2::ReturnCode io_rx_fir_reset(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group );
fapi2::ReturnCode io_tx_fir_reset(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group );
/**
* @brief Clears PHY Rx/Tx FIRs on the XBUS(EDI+) specified target. The FIRs
* are cleared by toggling a rx & tx fir reset bit.
* @param[in] i_target FAPI2 Target
* @param[in] i_clock_group Clock Group
* @retval ReturnCode
*/
fapi2::ReturnCode p9_io_xbus_clear_firs(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group )
{
FAPI_IMP( "I/O Start Xbus Clear FIRs" );
FAPI_TRY( io_tx_fir_reset( i_target, i_clock_group ), "Tx Reset Failed" );
FAPI_TRY( io_rx_fir_reset( i_target, i_clock_group ), "Rx Reset Failed" );
fapi_try_exit:
FAPI_IMP( "I/O End Xbus Clear FIRs" );
return fapi2::current_err;
}
/**
* @brief This function resets the Rx Firs on a EDI+ Xbus
* @param[in] i_target FAPI2 Target
* @param[in] i_clock_group Clock Group
* @retval ReturnCode
*/
fapi2::ReturnCode io_rx_fir_reset(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group)
{
const uint8_t LANE_00 = 0;
uint64_t l_data = 0;
FAPI_TRY( io::read( EDIP_RX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),
"Reading Rx Fir Reg Failed");
io::set (EDIP_RX_FIR_RESET, 0, l_data);
FAPI_TRY(io::write( EDIP_RX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),
"Writing Rx Fir Reg Failed");
io::set (EDIP_RX_FIR_RESET, 1, l_data);
FAPI_TRY(io::write( EDIP_RX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),
"Writing Rx Fir Reg Failed");
io::set (EDIP_RX_FIR_RESET, 0, l_data);
FAPI_TRY(io::write( EDIP_RX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),
"Writing Rx Fir Reg Failed");
fapi_try_exit:
return fapi2::current_err;
}
/**
* @brief This function resets the Tx Firs on a EDI+ Xbus
* @param[in] i_target FAPI2 Target
* @param[in] i_clock_group Clock Group
* @retval ReturnCode
*/
fapi2::ReturnCode io_tx_fir_reset(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,
const uint8_t& i_clock_group)
{
const uint8_t LANE_00 = 0;
uint64_t l_data = 0;
FAPI_TRY( io::read( EDIP_TX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),
"Reading Tx Fir Reg Failed");
io::set (EDIP_TX_FIR_RESET, 0, l_data);
FAPI_TRY(io::write( EDIP_TX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),
"Writing Tx Fir Reg Failed");
io::set (EDIP_TX_FIR_RESET, 1, l_data);
FAPI_TRY(io::write( EDIP_TX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),
"Writing Tx Fir Reg Failed");
io::set (EDIP_TX_FIR_RESET, 0, l_data);
FAPI_TRY(io::write( EDIP_TX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),
"Writing Tx Fir Reg Failed");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.
//
#pragma once
#include "include/aclTypes.h"
#include "platform/context.hpp"
#include "platform/object.hpp"
#include "platform/memory.hpp"
#include "devwavelimiter.hpp"
#include "comgrctx.hpp"
#if defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)
#ifndef USE_COMGR_LIBRARY
#include "driver/AmdCompiler.h"
#endif
//#include "llvm/Support/AMDGPUMetadata.h"
namespace llvm {
namespace AMDGPU {
namespace HSAMD {
struct Metadata;
namespace Kernel {
struct Metadata;
}}}}
#define LC_METADATA 1
typedef llvm::AMDGPU::HSAMD::Metadata CodeObjectMD;
typedef llvm::AMDGPU::HSAMD::Kernel::Metadata KernelMD;
//typedef llvm::AMDGPU::HSAMD::Kernel::Arg::Metadata KernelArgMD;
#endif // defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)
#ifndef LC_METADATA
typedef char CodeObjectMD;
#endif
namespace amd {
namespace hsa {
namespace loader {
class Symbol;
} // loader
namespace code {
namespace Kernel {
class Metadata;
} // Kernel
} // code
} // hsa
} // amd
namespace amd {
class Device;
class Program;
namespace option {
class Options;
} // option
}
namespace device {
class ClBinary;
class Kernel;
//! A program object for a specific device.
class Program : public amd::HeapObject {
public:
typedef std::pair<const void*, size_t> binary_t;
typedef std::unordered_map<std::string, Kernel*> kernels_t;
// type of the program
typedef enum {
TYPE_NONE = 0, // uncompiled
TYPE_COMPILED, // compiled
TYPE_LIBRARY, // linked library
TYPE_EXECUTABLE, // linked executable
TYPE_INTERMEDIATE // intermediate
} type_t;
private:
//! The device target for this binary.
amd::SharedReference<amd::Device> device_;
kernels_t kernels_; //!< The kernel entry points this binary.
type_t type_; //!< type of this program
protected:
union {
struct {
uint32_t isNull_ : 1; //!< Null program no memory allocations
uint32_t internal_ : 1; //!< Internal blit program
uint32_t isLC_ : 1; //!< LC was used for the program compilation
uint32_t hasGlobalStores_ : 1; //!< Program has writable program scope variables
uint32_t xnackEnabled_ : 1; //!< Xnack was enabled during compilation
uint32_t sramEccEnabled_ : 1; //!< SRAM ECC was enabled during compilation
};
uint32_t flags_; //!< Program flags
};
ClBinary* clBinary_; //!< The CL program binary file
std::string llvmBinary_; //!< LLVM IR binary code
amd::OclElf::oclElfSections elfSectionType_; //!< LLVM IR binary code is in SPIR format
std::string compileOptions_; //!< compile/build options.
std::string linkOptions_; //!< link options.
//!< the option arg passed in to clCompileProgram(), clLinkProgram(),
//! or clBuildProgram(), whichever is called last
aclBinaryOptions binOpts_; //!< Binary options to create aclBinary
aclBinary* binaryElf_; //!< Binary for the new compiler library
std::string lastBuildOptionsArg_;
mutable std::string buildLog_; //!< build log.
cl_int buildStatus_; //!< build status.
cl_int buildError_; //!< build error
const char* machineTarget_; //!< Machine target for this program
aclTargetInfo info_; //!< The info target for this binary.
size_t globalVariableTotalSize_;
amd::option::Options* programOptions_;
#if defined(USE_COMGR_LIBRARY)
amd_comgr_metadata_node_t* metadata_; //!< COMgr metadata
std::map<std::string,amd_comgr_metadata_node_t> kernelMetadataMap_; //!< Map of kernel metadata
#else
CodeObjectMD* metadata_; //!< Runtime metadata
#endif
public:
//! Construct a section.
Program(amd::Device& device);
//! Destroy this binary image.
virtual ~Program();
//! Destroy all the kernels
void clear();
//! Return the compiler options passed to build this program
amd::option::Options* getCompilerOptions() const { return programOptions_; }
//! Compile the device program.
cl_int compile(const std::string& sourceCode, const std::vector<const std::string*>& headers,
const char** headerIncludeNames, const char* origOptions,
amd::option::Options* options);
//! Builds the device program.
cl_int link(const std::vector<Program*>& inputPrograms, const char* origOptions,
amd::option::Options* options);
//! Builds the device program.
cl_int build(const std::string& sourceCode, const char* origOptions,
amd::option::Options* options);
//! Returns the device object, associated with this program.
const amd::Device& device() const { return device_(); }
//! Return the compiler options used to build the program.
const std::string& compileOptions() const { return compileOptions_; }
//! Return the option arg passed in to clCompileProgram(), clLinkProgram(),
//! or clBuildProgram(), whichever is called last
const std::string lastBuildOptionsArg() const { return lastBuildOptionsArg_; }
//! Return the build log.
const std::string& buildLog() const { return buildLog_; }
//! Return the build status.
cl_build_status buildStatus() const { return buildStatus_; }
//! Return the build error.
cl_int buildError() const { return buildError_; }
//! Return the symbols vector.
const kernels_t& kernels() const { return kernels_; }
kernels_t& kernels() { return kernels_; }
//! Return the binary image.
inline const binary_t binary() const;
inline binary_t binary();
//! Returns the CL program binary file
ClBinary* clBinary() { return clBinary_; }
const ClBinary* clBinary() const { return clBinary_; }
bool setBinary(const char* binaryIn, size_t size);
type_t type() const { return type_; }
void setGlobalVariableTotalSize(size_t size) { globalVariableTotalSize_ = size; }
size_t globalVariableTotalSize() const { return globalVariableTotalSize_; }
//! Returns the aclBinary associated with the program
aclBinary* binaryElf() const { return static_cast<aclBinary*>(binaryElf_); }
//! Returns TRUE if the program just compiled
bool isNull() const { return isNull_; }
//! Returns TRUE if the program used internally by runtime
bool isInternal() const { return internal_; }
//! Returns TRUE if Lightning compiler was used for this program
bool isLC() const { return isLC_; }
//! Global variables are a part of the code segment
bool hasGlobalStores() const { return hasGlobalStores_; }
#if defined(USE_COMGR_LIBRARY)
const amd_comgr_metadata_node_t* metadata() const { return metadata_; }
//! Get the kernel metadata
const amd_comgr_metadata_node_t* getKernelMetadata(const std::string name) const {
auto it = kernelMetadataMap_.find(name);
return (it == kernelMetadataMap_.end()) ? nullptr : &(it->second);
}
#else
const CodeObjectMD* metadata() const { return metadata_; }
#endif
//! Get the machine target for the program
const char* machineTarget() const { return machineTarget_; }
//! Check if xnack is enable
const bool xnackEnable() const { return (xnackEnabled_ == 1); }
//! Check if SRAM ECC is enable
const bool sramEccEnable() const { return (sramEccEnabled_ == 1); }
virtual bool findGlobalSymbols(void** dptr, size_t* bytes, const char* globalName) const {
ShouldNotReachHere();
}
protected:
//! pre-compile setup
bool initBuild(amd::option::Options* options);
//! post-compile cleanup
bool finiBuild(bool isBuildGood);
/*! \brief Compiles GPU CL program to LLVM binary (compiler frontend)
*
* \return True if we successefully compiled a GPU program
*/
virtual bool compileImpl(
const std::string& sourceCode, //!< the program's source code
const std::vector<const std::string*>& headers,
const char** headerIncludeNames,
amd::option::Options* options //!< compile options's object
);
//! Link the device program.
virtual bool linkImpl(amd::option::Options* options);
//! Link the device programs.
virtual bool linkImpl(const std::vector<Program*>& inputPrograms, amd::option::Options* options,
bool createLibrary);
virtual bool createBinary(amd::option::Options* options) = 0;
//! Initialize Binary (used only for clCreateProgramWithBinary()).
bool initClBinary(const char* binaryIn, size_t size);
//! Initialize Binary
virtual bool initClBinary();
virtual bool saveBinaryAndSetType(type_t type) = 0;
//! Release the Binary
void releaseClBinary();
//! return target info
virtual const aclTargetInfo& info(const char* str = "") = 0;
virtual bool setKernels(
amd::option::Options* options, void* binary, size_t binSize) { return true; }
//! Returns all the options to be appended while passing to the compiler library
std::string ProcessOptions(amd::option::Options* options);
//! At linking time, get the set of compile options to be used from
//! the set of input program, warn if they have inconsisten compile options.
bool getCompileOptionsAtLinking(const std::vector<Program*>& inputPrograms,
const amd::option::Options* linkOptions);
void setType(type_t newType) { type_ = newType; }
#if defined(WITH_LIGHTNING_COMPILER) && !defined(USE_COMGR_LIBRARY)
//! Return a new transient compiler instance.
static std::unique_ptr<amd::opencl_driver::Compiler> newCompilerInstance();
#endif // defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)
/* \brief Returns the next stage to compile from, based on sections in binary,
* also returns completeStages in a vector, which contains at least ACL_TYPE_DEFAULT,
* sets needOptionsCheck to true if options check is needed to decide whether or not to recompile
*/
aclType getCompilationStagesFromBinary(
std::vector<aclType>& completeStages,
bool& needOptionsCheck);
/* \brief Returns the next stage to compile from, based on sections and options in binary
*/
aclType getNextCompilationStageFromBinary(amd::option::Options* options);
//! Finds the total size of all global variables in the program
bool FindGlobalVarSize(void* binary, size_t binSize);
bool isElf(const char* bin) const { return amd::isElfMagic(bin); }
private:
//! Compile the device program with LC path
bool compileImplLC(const std::string& sourceCode,
const std::vector<const std::string*>& headers,
const char** headerIncludeNames, amd::option::Options* options);
//! Compile the device program with HSAIL path
bool compileImplHSAIL(const std::string& sourceCode,
const std::vector<const std::string*>& headers,
const char** headerIncludeNames, amd::option::Options* options);
//! Link the device programs with LC path
bool linkImplLC(const std::vector<Program*>& inputPrograms,
amd::option::Options* options, bool createLibrary);
//! Link the device programs with HSAIL path
bool linkImplHSAIL(const std::vector<Program*>& inputPrograms,
amd::option::Options* options, bool createLibrary);
//! Link the device program with LC path
bool linkImplLC(amd::option::Options* options);
//! Link the device program with HSAIL path
bool linkImplHSAIL(amd::option::Options* options);
#if defined(USE_COMGR_LIBRARY)
//! Dump the log data object to the build log, if both are present
amd_comgr_status_t extractBuildLog(const char* buildLog,
amd_comgr_data_set_t dataSet);
//! Dump the code object data
amd_comgr_status_t extractByteCodeBinary(const amd_comgr_data_set_t inDataSet,
const amd_comgr_data_kind_t dataKind, const std::string& outFileName,
char* outBinary[] = nullptr, size_t* outSize = nullptr);
//! Set the OCL language and target triples with feature
void setLangAndTargetStr(const char* clStd, amd_comgr_language_t* oclver,
std::string& targetIdent);
//! Create code object and add it into the data set
amd_comgr_status_t addCodeObjData(const char *source,
const size_t size, const amd_comgr_data_kind_t type,
const char* name, amd_comgr_data_set_t* dataSet);
//! Create action for the specified language, target and options
amd_comgr_status_t createAction(const amd_comgr_language_t oclvar,
const std::string& targetIdent, const std::string& options,
amd_comgr_action_info_t* action, bool* hasAction);
//! Create the bitcode of the linked input dataset
bool linkLLVMBitcode(const amd_comgr_data_set_t inputs,
const std::string& options, const bool requiredDump,
amd::option::Options* amdOptions, amd_comgr_data_set_t* output,
char* binary[] = nullptr, size_t* binarySize = nullptr);
//! Create the bitcode of the compiled input dataset
bool compileToLLVMBitcode(const amd_comgr_data_set_t inputs,
const std::string& options, amd::option::Options* amdOptions,
char* binary[], size_t* binarySize);
//! Compile and create the excutable of the input dataset
bool compileAndLinkExecutable(const amd_comgr_data_set_t inputs,
const std::string& options, amd::option::Options* amdOptions,
char* executable[], size_t* executableSize);
//! Create the map for the kernel name and its metadata for fast access
bool createKernelMetadataMap();
#endif
//! Disable default copy constructor
Program(const Program&);
//! Disable operator=
Program& operator=(const Program&);
};
} // namespace device
<commit_msg>P4 to Git Change 1757956 by kjayapra@1_HIPWS_SL_IPC on 2019/03/18 18:47:13<commit_after>//
// Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.
//
#pragma once
#include "include/aclTypes.h"
#include "platform/context.hpp"
#include "platform/object.hpp"
#include "platform/memory.hpp"
#include "devwavelimiter.hpp"
#include "comgrctx.hpp"
#if defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)
#ifndef USE_COMGR_LIBRARY
#include "driver/AmdCompiler.h"
#endif
//#include "llvm/Support/AMDGPUMetadata.h"
namespace llvm {
namespace AMDGPU {
namespace HSAMD {
struct Metadata;
namespace Kernel {
struct Metadata;
}}}}
#define LC_METADATA 1
typedef llvm::AMDGPU::HSAMD::Metadata CodeObjectMD;
typedef llvm::AMDGPU::HSAMD::Kernel::Metadata KernelMD;
//typedef llvm::AMDGPU::HSAMD::Kernel::Arg::Metadata KernelArgMD;
#endif // defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)
#ifndef LC_METADATA
typedef char CodeObjectMD;
#endif
namespace amd {
namespace hsa {
namespace loader {
class Symbol;
} // loader
namespace code {
namespace Kernel {
class Metadata;
} // Kernel
} // code
} // hsa
} // amd
namespace amd {
class Device;
class Program;
namespace option {
class Options;
} // option
}
namespace device {
class ClBinary;
class Kernel;
//! A program object for a specific device.
class Program : public amd::HeapObject {
public:
typedef std::pair<const void*, size_t> binary_t;
typedef std::unordered_map<std::string, Kernel*> kernels_t;
// type of the program
typedef enum {
TYPE_NONE = 0, // uncompiled
TYPE_COMPILED, // compiled
TYPE_LIBRARY, // linked library
TYPE_EXECUTABLE, // linked executable
TYPE_INTERMEDIATE // intermediate
} type_t;
private:
//! The device target for this binary.
amd::SharedReference<amd::Device> device_;
kernels_t kernels_; //!< The kernel entry points this binary.
type_t type_; //!< type of this program
protected:
union {
struct {
uint32_t isNull_ : 1; //!< Null program no memory allocations
uint32_t internal_ : 1; //!< Internal blit program
uint32_t isLC_ : 1; //!< LC was used for the program compilation
uint32_t hasGlobalStores_ : 1; //!< Program has writable program scope variables
uint32_t xnackEnabled_ : 1; //!< Xnack was enabled during compilation
uint32_t sramEccEnabled_ : 1; //!< SRAM ECC was enabled during compilation
};
uint32_t flags_; //!< Program flags
};
ClBinary* clBinary_; //!< The CL program binary file
std::string llvmBinary_; //!< LLVM IR binary code
amd::OclElf::oclElfSections elfSectionType_; //!< LLVM IR binary code is in SPIR format
std::string compileOptions_; //!< compile/build options.
std::string linkOptions_; //!< link options.
//!< the option arg passed in to clCompileProgram(), clLinkProgram(),
//! or clBuildProgram(), whichever is called last
aclBinaryOptions binOpts_; //!< Binary options to create aclBinary
aclBinary* binaryElf_; //!< Binary for the new compiler library
std::string lastBuildOptionsArg_;
mutable std::string buildLog_; //!< build log.
cl_int buildStatus_; //!< build status.
cl_int buildError_; //!< build error
const char* machineTarget_; //!< Machine target for this program
aclTargetInfo info_; //!< The info target for this binary.
size_t globalVariableTotalSize_;
amd::option::Options* programOptions_;
#if defined(USE_COMGR_LIBRARY)
amd_comgr_metadata_node_t* metadata_; //!< COMgr metadata
std::map<std::string,amd_comgr_metadata_node_t> kernelMetadataMap_; //!< Map of kernel metadata
#else
CodeObjectMD* metadata_; //!< Runtime metadata
#endif
public:
//! Construct a section.
Program(amd::Device& device);
//! Destroy this binary image.
virtual ~Program();
//! Destroy all the kernels
void clear();
//! Return the compiler options passed to build this program
amd::option::Options* getCompilerOptions() const { return programOptions_; }
//! Compile the device program.
cl_int compile(const std::string& sourceCode, const std::vector<const std::string*>& headers,
const char** headerIncludeNames, const char* origOptions,
amd::option::Options* options);
//! Builds the device program.
cl_int link(const std::vector<Program*>& inputPrograms, const char* origOptions,
amd::option::Options* options);
//! Builds the device program.
cl_int build(const std::string& sourceCode, const char* origOptions,
amd::option::Options* options);
//! Returns the device object, associated with this program.
const amd::Device& device() const { return device_(); }
//! Return the compiler options used to build the program.
const std::string& compileOptions() const { return compileOptions_; }
//! Return the option arg passed in to clCompileProgram(), clLinkProgram(),
//! or clBuildProgram(), whichever is called last
const std::string lastBuildOptionsArg() const { return lastBuildOptionsArg_; }
//! Return the build log.
const std::string& buildLog() const { return buildLog_; }
//! Return the build status.
cl_build_status buildStatus() const { return buildStatus_; }
//! Return the build error.
cl_int buildError() const { return buildError_; }
//! Return the symbols vector.
const kernels_t& kernels() const { return kernels_; }
kernels_t& kernels() { return kernels_; }
//! Return the binary image.
inline const binary_t binary() const;
inline binary_t binary();
//! Returns the CL program binary file
ClBinary* clBinary() { return clBinary_; }
const ClBinary* clBinary() const { return clBinary_; }
bool setBinary(const char* binaryIn, size_t size);
type_t type() const { return type_; }
void setGlobalVariableTotalSize(size_t size) { globalVariableTotalSize_ = size; }
size_t globalVariableTotalSize() const { return globalVariableTotalSize_; }
//! Returns the aclBinary associated with the program
aclBinary* binaryElf() const { return static_cast<aclBinary*>(binaryElf_); }
//! Returns TRUE if the program just compiled
bool isNull() const { return isNull_; }
//! Returns TRUE if the program used internally by runtime
bool isInternal() const { return internal_; }
//! Returns TRUE if Lightning compiler was used for this program
bool isLC() const { return isLC_; }
//! Global variables are a part of the code segment
bool hasGlobalStores() const { return hasGlobalStores_; }
#if defined(USE_COMGR_LIBRARY)
const amd_comgr_metadata_node_t* metadata() const { return metadata_; }
//! Get the kernel metadata
const amd_comgr_metadata_node_t* getKernelMetadata(const std::string name) const {
auto it = kernelMetadataMap_.find(name);
return (it == kernelMetadataMap_.end()) ? nullptr : &(it->second);
}
#else
const CodeObjectMD* metadata() const { return metadata_; }
#endif
//! Get the machine target for the program
const char* machineTarget() const { return machineTarget_; }
//! Check if xnack is enable
const bool xnackEnable() const { return (xnackEnabled_ == 1); }
//! Check if SRAM ECC is enable
const bool sramEccEnable() const { return (sramEccEnabled_ == 1); }
virtual bool findGlobalSymbols(void** dptr, size_t* bytes, const char* globalName) const {
ShouldNotReachHere();
return false;
}
protected:
//! pre-compile setup
bool initBuild(amd::option::Options* options);
//! post-compile cleanup
bool finiBuild(bool isBuildGood);
/*! \brief Compiles GPU CL program to LLVM binary (compiler frontend)
*
* \return True if we successefully compiled a GPU program
*/
virtual bool compileImpl(
const std::string& sourceCode, //!< the program's source code
const std::vector<const std::string*>& headers,
const char** headerIncludeNames,
amd::option::Options* options //!< compile options's object
);
//! Link the device program.
virtual bool linkImpl(amd::option::Options* options);
//! Link the device programs.
virtual bool linkImpl(const std::vector<Program*>& inputPrograms, amd::option::Options* options,
bool createLibrary);
virtual bool createBinary(amd::option::Options* options) = 0;
//! Initialize Binary (used only for clCreateProgramWithBinary()).
bool initClBinary(const char* binaryIn, size_t size);
//! Initialize Binary
virtual bool initClBinary();
virtual bool saveBinaryAndSetType(type_t type) = 0;
//! Release the Binary
void releaseClBinary();
//! return target info
virtual const aclTargetInfo& info(const char* str = "") = 0;
virtual bool setKernels(
amd::option::Options* options, void* binary, size_t binSize) { return true; }
//! Returns all the options to be appended while passing to the compiler library
std::string ProcessOptions(amd::option::Options* options);
//! At linking time, get the set of compile options to be used from
//! the set of input program, warn if they have inconsisten compile options.
bool getCompileOptionsAtLinking(const std::vector<Program*>& inputPrograms,
const amd::option::Options* linkOptions);
void setType(type_t newType) { type_ = newType; }
#if defined(WITH_LIGHTNING_COMPILER) && !defined(USE_COMGR_LIBRARY)
//! Return a new transient compiler instance.
static std::unique_ptr<amd::opencl_driver::Compiler> newCompilerInstance();
#endif // defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)
/* \brief Returns the next stage to compile from, based on sections in binary,
* also returns completeStages in a vector, which contains at least ACL_TYPE_DEFAULT,
* sets needOptionsCheck to true if options check is needed to decide whether or not to recompile
*/
aclType getCompilationStagesFromBinary(
std::vector<aclType>& completeStages,
bool& needOptionsCheck);
/* \brief Returns the next stage to compile from, based on sections and options in binary
*/
aclType getNextCompilationStageFromBinary(amd::option::Options* options);
//! Finds the total size of all global variables in the program
bool FindGlobalVarSize(void* binary, size_t binSize);
bool isElf(const char* bin) const { return amd::isElfMagic(bin); }
private:
//! Compile the device program with LC path
bool compileImplLC(const std::string& sourceCode,
const std::vector<const std::string*>& headers,
const char** headerIncludeNames, amd::option::Options* options);
//! Compile the device program with HSAIL path
bool compileImplHSAIL(const std::string& sourceCode,
const std::vector<const std::string*>& headers,
const char** headerIncludeNames, amd::option::Options* options);
//! Link the device programs with LC path
bool linkImplLC(const std::vector<Program*>& inputPrograms,
amd::option::Options* options, bool createLibrary);
//! Link the device programs with HSAIL path
bool linkImplHSAIL(const std::vector<Program*>& inputPrograms,
amd::option::Options* options, bool createLibrary);
//! Link the device program with LC path
bool linkImplLC(amd::option::Options* options);
//! Link the device program with HSAIL path
bool linkImplHSAIL(amd::option::Options* options);
#if defined(USE_COMGR_LIBRARY)
//! Dump the log data object to the build log, if both are present
amd_comgr_status_t extractBuildLog(const char* buildLog,
amd_comgr_data_set_t dataSet);
//! Dump the code object data
amd_comgr_status_t extractByteCodeBinary(const amd_comgr_data_set_t inDataSet,
const amd_comgr_data_kind_t dataKind, const std::string& outFileName,
char* outBinary[] = nullptr, size_t* outSize = nullptr);
//! Set the OCL language and target triples with feature
void setLangAndTargetStr(const char* clStd, amd_comgr_language_t* oclver,
std::string& targetIdent);
//! Create code object and add it into the data set
amd_comgr_status_t addCodeObjData(const char *source,
const size_t size, const amd_comgr_data_kind_t type,
const char* name, amd_comgr_data_set_t* dataSet);
//! Create action for the specified language, target and options
amd_comgr_status_t createAction(const amd_comgr_language_t oclvar,
const std::string& targetIdent, const std::string& options,
amd_comgr_action_info_t* action, bool* hasAction);
//! Create the bitcode of the linked input dataset
bool linkLLVMBitcode(const amd_comgr_data_set_t inputs,
const std::string& options, const bool requiredDump,
amd::option::Options* amdOptions, amd_comgr_data_set_t* output,
char* binary[] = nullptr, size_t* binarySize = nullptr);
//! Create the bitcode of the compiled input dataset
bool compileToLLVMBitcode(const amd_comgr_data_set_t inputs,
const std::string& options, amd::option::Options* amdOptions,
char* binary[], size_t* binarySize);
//! Compile and create the excutable of the input dataset
bool compileAndLinkExecutable(const amd_comgr_data_set_t inputs,
const std::string& options, amd::option::Options* amdOptions,
char* executable[], size_t* executableSize);
//! Create the map for the kernel name and its metadata for fast access
bool createKernelMetadataMap();
#endif
//! Disable default copy constructor
Program(const Program&);
//! Disable operator=
Program& operator=(const Program&);
};
} // namespace device
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: VKey.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: oj $ $Date: 2002-11-12 09:17:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_KEY_HXX_
#include "connectivity/sdbcx/VKey.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OKey::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)
{
if(isNew())
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VKeyDescription");
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VKey");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OKey::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
if(isNew())
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.KeyDescription");
else
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Key");
return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OKey::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
// -------------------------------------------------------------------------
OKey::OKey(sal_Bool _bCase) : ODescriptor_BASE(m_aMutex)
, ODescriptor(ODescriptor_BASE::rBHelper,_bCase,sal_True)
, m_pColumns(NULL)
{
}
// -------------------------------------------------------------------------
OKey::OKey( const ::rtl::OUString& _Name,
const ::rtl::OUString& _ReferencedTable,
sal_Int32 _Type,
sal_Int32 _UpdateRule,
sal_Int32 _DeleteRule,
sal_Bool _bCase) : ODescriptor_BASE(m_aMutex)
,ODescriptor(ODescriptor_BASE::rBHelper,_bCase)
,m_pColumns(NULL)
,m_ReferencedTable(_ReferencedTable)
,m_Type(_Type)
,m_UpdateRule(_UpdateRule)
,m_DeleteRule(_DeleteRule)
{
m_Name = _Name;
}
// -------------------------------------------------------------------------
OKey::~OKey( )
{
delete m_pColumns;
}
// -------------------------------------------------------------------------
Any SAL_CALL OKey::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = ODescriptor::queryInterface( rType);
if(!aRet.hasValue())
{
if(!isNew())
aRet = OKey_BASE::queryInterface(rType);
if(!aRet.hasValue())
aRet = ODescriptor_BASE::queryInterface( rType);
}
return aRet;
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OKey::getTypes( ) throw(RuntimeException)
{
if(isNew())
return ::comphelper::concatSequences(ODescriptor::getTypes(),ODescriptor_BASE::getTypes());
return ::comphelper::concatSequences(ODescriptor::getTypes(),ODescriptor_BASE::getTypes(),OKey_BASE::getTypes());
}
// -------------------------------------------------------------------------
void OKey::construct()
{
ODescriptor::construct();
sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REFERENCEDTABLE), PROPERTY_ID_REFERENCEDTABLE, nAttrib,&m_ReferencedTable, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE), PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_UPDATERULE), PROPERTY_ID_UPDATERULE, nAttrib,&m_UpdateRule, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DELETERULE), PROPERTY_ID_DELETERULE, nAttrib,&m_DeleteRule, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
}
// -------------------------------------------------------------------------
void SAL_CALL OKey::disposing()
{
OPropertySetHelper::disposing();
::osl::MutexGuard aGuard(m_aMutex);
if(m_pColumns)
m_pColumns->disposing();
ODescriptor_BASE::disposing();
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OKey::createArrayHelper(sal_Int32 _nId ) const
{
Sequence< Property > aProps;
describeProperties(aProps);
changePropertyAttributte(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & OKey::getInfoHelper()
{
return *const_cast<OKey*>(this)->getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OKey::getColumns( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(ODescriptor_BASE::rBHelper.bDisposed);
try
{
if ( !m_pColumns )
refreshColumns();
}
catch( const RuntimeException& )
{
// allowed to leave this method
throw;
}
catch( const Exception& )
{
// allowed
}
return const_cast<OKey*>(this)->m_pColumns;
}
// -------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OKey::createDataDescriptor( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(ODescriptor_BASE::rBHelper.bDisposed);
return this;
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OKey::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)
{
return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OKey::getName( ) throw(::com::sun::star::uno::RuntimeException)
{
return m_Name;
}
// -----------------------------------------------------------------------------
void SAL_CALL OKey::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)
{
}
// -----------------------------------------------------------------------------
// XInterface
void SAL_CALL OKey::acquire() throw()
{
ODescriptor_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OKey::release() throw()
{
ODescriptor_BASE::release();
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.13.320); FILE MERGED 2005/09/05 17:25:55 rt 1.13.320.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VKey.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: rt $ $Date: 2005-09-08 07:44:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_SDBCX_KEY_HXX_
#include "connectivity/sdbcx/VKey.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
// -------------------------------------------------------------------------
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OKey::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)
{
if(isNew())
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VKeyDescription");
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VKey");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OKey::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
if(isNew())
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.KeyDescription");
else
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Key");
return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OKey::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
// -------------------------------------------------------------------------
OKey::OKey(sal_Bool _bCase) : ODescriptor_BASE(m_aMutex)
, ODescriptor(ODescriptor_BASE::rBHelper,_bCase,sal_True)
, m_pColumns(NULL)
{
}
// -------------------------------------------------------------------------
OKey::OKey( const ::rtl::OUString& _Name,
const ::rtl::OUString& _ReferencedTable,
sal_Int32 _Type,
sal_Int32 _UpdateRule,
sal_Int32 _DeleteRule,
sal_Bool _bCase) : ODescriptor_BASE(m_aMutex)
,ODescriptor(ODescriptor_BASE::rBHelper,_bCase)
,m_pColumns(NULL)
,m_ReferencedTable(_ReferencedTable)
,m_Type(_Type)
,m_UpdateRule(_UpdateRule)
,m_DeleteRule(_DeleteRule)
{
m_Name = _Name;
}
// -------------------------------------------------------------------------
OKey::~OKey( )
{
delete m_pColumns;
}
// -------------------------------------------------------------------------
Any SAL_CALL OKey::queryInterface( const Type & rType ) throw(RuntimeException)
{
Any aRet = ODescriptor::queryInterface( rType);
if(!aRet.hasValue())
{
if(!isNew())
aRet = OKey_BASE::queryInterface(rType);
if(!aRet.hasValue())
aRet = ODescriptor_BASE::queryInterface( rType);
}
return aRet;
}
// -------------------------------------------------------------------------
Sequence< Type > SAL_CALL OKey::getTypes( ) throw(RuntimeException)
{
if(isNew())
return ::comphelper::concatSequences(ODescriptor::getTypes(),ODescriptor_BASE::getTypes());
return ::comphelper::concatSequences(ODescriptor::getTypes(),ODescriptor_BASE::getTypes(),OKey_BASE::getTypes());
}
// -------------------------------------------------------------------------
void OKey::construct()
{
ODescriptor::construct();
sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REFERENCEDTABLE), PROPERTY_ID_REFERENCEDTABLE, nAttrib,&m_ReferencedTable, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE), PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_UPDATERULE), PROPERTY_ID_UPDATERULE, nAttrib,&m_UpdateRule, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DELETERULE), PROPERTY_ID_DELETERULE, nAttrib,&m_DeleteRule, ::getCppuType(reinterpret_cast<sal_Int32*>(NULL)));
}
// -------------------------------------------------------------------------
void SAL_CALL OKey::disposing()
{
OPropertySetHelper::disposing();
::osl::MutexGuard aGuard(m_aMutex);
if(m_pColumns)
m_pColumns->disposing();
ODescriptor_BASE::disposing();
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OKey::createArrayHelper(sal_Int32 _nId ) const
{
Sequence< Property > aProps;
describeProperties(aProps);
changePropertyAttributte(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & OKey::getInfoHelper()
{
return *const_cast<OKey*>(this)->getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OKey::getColumns( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(ODescriptor_BASE::rBHelper.bDisposed);
try
{
if ( !m_pColumns )
refreshColumns();
}
catch( const RuntimeException& )
{
// allowed to leave this method
throw;
}
catch( const Exception& )
{
// allowed
}
return const_cast<OKey*>(this)->m_pColumns;
}
// -------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OKey::createDataDescriptor( ) throw(RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(ODescriptor_BASE::rBHelper.bDisposed);
return this;
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OKey::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)
{
return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OKey::getName( ) throw(::com::sun::star::uno::RuntimeException)
{
return m_Name;
}
// -----------------------------------------------------------------------------
void SAL_CALL OKey::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)
{
}
// -----------------------------------------------------------------------------
// XInterface
void SAL_CALL OKey::acquire() throw()
{
ODescriptor_BASE::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OKey::release() throw()
{
ODescriptor_BASE::release();
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/**
* @file : p9_cpu_special_wakeup.C
* @brief : HWP to perform special wakeup of core, EQ or EX.
* @HWP HW Owner : Greg Still <stillgs@us.ibm.com>
* @HWP FW Owner : Prem S Jha <premjha2@in.ibm.com>
* @HWP Team : PM
* @HWP Level : L1
* @HWP Consumed by : OCC, FSP, HOST
*/
// ---------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------
#include <p9_cpu_special_wakeup.H>
fapi2::ReturnCode
p9_cpu_special_wakeup( CONST_FAPI2_WAKEUP_CHIPLET& i_chipletTarget,
PROC_SPCWKUP_OPS i_operation,
PROC_SPCWKUP_ENTITY i_entity )
{
FAPI_IMP("Entering... ");
FAPI_IMP("Exit..." );
return fapi2::FAPI2_RC_SUCCESS;
}
<commit_msg>PM: Added make file for special wakeup HWP and fixed prolog.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file : p9_cpu_special_wakeup.C
/// @brief : HWP to perform special wakeup of core, EQ or EX.
// *HWP HW Owner : Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner : Prem S Jha <premjha2@in.ibm.com>
// *HWP Team : PM
// *HWP Level : 1
// *HWP Consumed by : OCC:FSP:HOST
// ---------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------
#include <p9_cpu_special_wakeup.H>
using namespace p9specialWakeup;
enum
{
NUM_SPCWKUP_ENTITIES = 4,
NUM_SPCWKUP_OPS = 3,
};
fapi2::ReturnCode
p9_cpu_special_wakeup( const FAPI2_WAKEUP_CHIPLET& i_chipletTarget,
const PROC_SPCWKUP_OPS i_operation,
const PROC_SPCWKUP_ENTITY i_entity )
{
FAPI_DBG("Entering p9_cpu_special_wakeup");
FAPI_DBG("Exit p9_cpu_special_wakeup" );
return fapi2::FAPI2_RC_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkStatisticsImageFilter.h"
#include "itkInvertIntensityImageFilter.h"
/** This program inverts the intensity of an image:
* new = max - old,
* where max is the maximum of an image.
*/
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run( function, type, dim ) \
if ( ComponentTypeIn == #type && Dimension == dim ) \
{ \
typedef itk::Image< type, dim > InputImageType; \
function< InputImageType >( inputFileName, outputFileName ); \
supported = true; \
}
//-------------------------------------------------------------------------------------
/** Declare InvertIntensity. */
template< class InputImageType >
void InvertIntensity(
const std::string & inputFileName,
const std::string & outputFileName );
/** Declare PrintHelp. */
void PrintHelp( void );
//-------------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
/** Check arguments for help. */
if ( argc < 3 )
{
PrintHelp();
return 1;
}
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
/** Get arguments. */
std::string inputFileName = "";
bool retin = parser->GetCommandLineArgument( "-in", inputFileName );
if ( !retin )
{
std::cerr << "ERROR: You should specify \"-in\"." << std::endl;
return 1;
}
std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( "." ) );
outputFileName += "INVERTED.mhd";
parser->GetCommandLineArgument( "-out", outputFileName );
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int Dimension = 2;
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( Dimension, 0 );
int retgip = GetImageProperties(
inputFileName,
PixelType,
ComponentTypeIn,
Dimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 )
{
return 1;
}
/** Check for vector images. */
if ( NumberOfComponents > 1 )
{
std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl;
std::cerr << "Vector images are not supported." << std::endl;
return 1;
}
/** Get rid of the possible "_" in ComponentType. */
ReplaceUnderscoreWithSpace( ComponentTypeIn );
/** Run the program. */
bool supported = false;
try
{
/** 2D. */
run( InvertIntensity, char, 2 );
run( InvertIntensity, unsigned char, 2 );
run( InvertIntensity, short, 2 );
run( InvertIntensity, unsigned short, 2 );
run( InvertIntensity, float, 2 );
run( InvertIntensity, double, 2 );
/** 3D. */
run( InvertIntensity, char, 3 );
run( InvertIntensity, unsigned char, 3 );
run( InvertIntensity, short, 3 );
run( InvertIntensity, unsigned short, 3 );
run( InvertIntensity, float, 3 );
run( InvertIntensity, double, 3 );
} // end run
catch ( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
if ( !supported )
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr
<< "pixel (component) type = " << ComponentTypeIn
<< " ; dimension = " << Dimension
<< std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* InvertIntensity *******************
*
* The resize function templated over the input pixel type.
*/
template< class InputImageType >
void InvertIntensity( const std::string & inputFileName,
const std::string & outputFileName )
{
/** Some typedef's. */
typedef typename InputImageType::PixelType InputPixelType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< InputImageType > WriterType;
typedef itk::StatisticsImageFilter< InputImageType > StatisticsFilterType;
typedef typename StatisticsFilterType::RealType RealType;
typedef itk::InvertIntensityImageFilter< InputImageType > InvertIntensityFilterType;
/** Create reader. */
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputFileName.c_str() );
/** Create statistics filter. */
typename StatisticsFilterType::Pointer statistics = StatisticsFilterType::New();
statistics->SetInput( reader->GetOutput() );
statistics->Update();
/** Get all the output stuff. */
InputPixelType max = statistics->GetMaximum();
/** Create invert filter. */
typename InvertIntensityFilterType::Pointer invertFilter = InvertIntensityFilterType::New();
invertFilter->SetInput( reader->GetOutput() );
invertFilter->SetMaximum( max );
/** Create writer. */
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFileName.c_str() );
writer->SetInput( invertFilter->GetOutput() );
writer->Update();
} // end InvertIntensity()
/**
* ******************* PrintHelp *******************
*/
void PrintHelp( void )
{
std::cout << "This program inverts the intensities of an image." << std::endl;
std::cout << "Usage:" << std::endl << "pxinvertintensityimagefilter" << std::endl;
std::cout << " -in inputFilename" << std::endl;
std::cout << " [-out] outputFilename; default: in + INVERTED.mhd" << std::endl;
std::cout << "Supported: 2D, 3D, (unsigned) char, (unsigned) short, float, double." << std::endl;
} // end PrintHelp()
<commit_msg>New style arguments for invertintensityimagefilter<commit_after>#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkStatisticsImageFilter.h"
#include "itkInvertIntensityImageFilter.h"
/** This program inverts the intensity of an image:
* new = max - old,
* where max is the maximum of an image.
*/
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run( function, type, dim ) \
if ( ComponentTypeIn == #type && Dimension == dim ) \
{ \
typedef itk::Image< type, dim > InputImageType; \
function< InputImageType >( inputFileName, outputFileName ); \
supported = true; \
}
//-------------------------------------------------------------------------------------
/** Declare InvertIntensity. */
template< class InputImageType >
void InvertIntensity(
const std::string & inputFileName,
const std::string & outputFileName );
/** Declare PrintHelp. */
std::string PrintHelp( void );
//-------------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText(PrintHelp());
parser->MarkArgumentAsRequired( "-in", "The input filename." );
bool validateArguments = parser->CheckForRequiredArguments();
if(!validateArguments)
{
return EXIT_FAILURE;
}
/** Get arguments. */
std::string inputFileName = "";
parser->GetCommandLineArgument( "-in", inputFileName );
std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( "." ) );
outputFileName += "INVERTED.mhd";
parser->GetCommandLineArgument( "-out", outputFileName );
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int Dimension = 2;
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( Dimension, 0 );
int retgip = GetImageProperties(
inputFileName,
PixelType,
ComponentTypeIn,
Dimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 )
{
return 1;
}
/** Check for vector images. */
if ( NumberOfComponents > 1 )
{
std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl;
std::cerr << "Vector images are not supported." << std::endl;
return 1;
}
/** Get rid of the possible "_" in ComponentType. */
ReplaceUnderscoreWithSpace( ComponentTypeIn );
/** Run the program. */
bool supported = false;
try
{
/** 2D. */
run( InvertIntensity, char, 2 );
run( InvertIntensity, unsigned char, 2 );
run( InvertIntensity, short, 2 );
run( InvertIntensity, unsigned short, 2 );
run( InvertIntensity, float, 2 );
run( InvertIntensity, double, 2 );
/** 3D. */
run( InvertIntensity, char, 3 );
run( InvertIntensity, unsigned char, 3 );
run( InvertIntensity, short, 3 );
run( InvertIntensity, unsigned short, 3 );
run( InvertIntensity, float, 3 );
run( InvertIntensity, double, 3 );
} // end run
catch ( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
if ( !supported )
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr
<< "pixel (component) type = " << ComponentTypeIn
<< " ; dimension = " << Dimension
<< std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* InvertIntensity *******************
*
* The resize function templated over the input pixel type.
*/
template< class InputImageType >
void InvertIntensity( const std::string & inputFileName,
const std::string & outputFileName )
{
/** Some typedef's. */
typedef typename InputImageType::PixelType InputPixelType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< InputImageType > WriterType;
typedef itk::StatisticsImageFilter< InputImageType > StatisticsFilterType;
typedef typename StatisticsFilterType::RealType RealType;
typedef itk::InvertIntensityImageFilter< InputImageType > InvertIntensityFilterType;
/** Create reader. */
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputFileName.c_str() );
/** Create statistics filter. */
typename StatisticsFilterType::Pointer statistics = StatisticsFilterType::New();
statistics->SetInput( reader->GetOutput() );
statistics->Update();
/** Get all the output stuff. */
InputPixelType max = statistics->GetMaximum();
/** Create invert filter. */
typename InvertIntensityFilterType::Pointer invertFilter = InvertIntensityFilterType::New();
invertFilter->SetInput( reader->GetOutput() );
invertFilter->SetMaximum( max );
/** Create writer. */
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFileName.c_str() );
writer->SetInput( invertFilter->GetOutput() );
writer->Update();
} // end InvertIntensity()
/**
* ******************* PrintHelp *******************
*/
std::string PrintHelp( void )
{
std::string helpText = "This program inverts the intensities of an image. \
Usage:\
pxinvertintensityimagefilter \
-in inputFilename \
[-out] outputFilename; default: in + INVERTED.mhd \
Supported: 2D, 3D, (unsigned) char, (unsigned) short, float, double.";
return helpText;
} // end PrintHelp()
<|endoftext|>
|
<commit_before>#include <iostream>
#include "demoloop.h"
#include "graphics/2d_primitives.h"
#include "hsl.h"
using namespace std;
using namespace demoloop;
float t = 0;
const float CYCLE_LENGTH = 10;
class Loop5 : public Demoloop {
public:
Loop5() : Demoloop(150, 150, 150) {
glDisable(GL_DEPTH_TEST);
}
void Update(float dt) {
t += dt;
const float RADIUS = height / 3;
float cycle = fmod(t, CYCLE_LENGTH);
float cycle_ratio = cycle / CYCLE_LENGTH;
int ox = width / 2, oy = height / 2;
const int num_vertices = 5;
const float interval = (DEMOLOOP_M_PI * 2) / num_vertices;
float xCoords[num_vertices];
float yCoords[num_vertices];
for (int i = 0; i < num_vertices; ++i) {
float t = i;
xCoords[i] = cos(interval * t - DEMOLOOP_M_PI / 10) * RADIUS + ox;
yCoords[i] = sin(interval * t - DEMOLOOP_M_PI / 10) * RADIUS + oy;
}
auto color = hsl2rgb(cycle_ratio, 1, 0.5);
setColor(color);
polygon(gl, xCoords, yCoords, num_vertices);
const int dot_count = 20;
for (int v = 0; v < num_vertices; ++v) {
const float angularOffset = interval * v;
for (int t = 0; t < dot_count; ++t) {
float i = t;
const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);
const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
setColor(0, 0, 0, 255 * interval_cycle_ratio);
circle(gl, x1 + ox, y1 + oy, 3);
if (t == 0) {
const int n = (v + 1) % num_vertices;
const float x2 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
const float y2 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
const float x3 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;
const float y3 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;
setColor(0, 0, 0);
line(gl, x2 + ox, y2 + oy, xCoords[v], yCoords[v]);
line(gl, x2 + ox, y2 + oy, x3 + ox, y3 + oy);
}
}
}
for (float i = 0; i < dot_count; ++i) {
const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);
const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2) * RADIUS;
const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2) * RADIUS;
setColor(0, 0, 0);
circle(gl, x1 + ox, y1 + oy, 3);
}
}
private:
};
int main(int, char**){
Loop5 loop;
loop.Run();
return 0;
}
<commit_msg>greatly increase loop 5 rendering speed<commit_after>#include <iostream>
#include "demoloop.h"
#include "graphics/2d_primitives.h"
using namespace std;
using namespace demoloop;
float t = 0;
const float CYCLE_LENGTH = 10;
const int num_circle_verts = 10;
const int num_vertices = 5;
const int dot_count = 20;
class Loop5 : public Demoloop {
public:
Loop5() : Demoloop(150, 150, 150) {
glDisable(GL_DEPTH_TEST);
}
void Update(float dt) {
t += dt;
const float RADIUS = height / 3;
float cycle = fmod(t, CYCLE_LENGTH);
float cycle_ratio = cycle / CYCLE_LENGTH;
int ox = width / 2, oy = height / 2;
const float interval = (DEMOLOOP_M_PI * 2) / num_vertices;
float xCoords[num_vertices];
float yCoords[num_vertices];
for (int i = 0; i < num_vertices; ++i) {
float t = i;
xCoords[i] = cos(interval * t - DEMOLOOP_M_PI / 10) * RADIUS + ox;
yCoords[i] = sin(interval * t - DEMOLOOP_M_PI / 10) * RADIUS + oy;
}
auto color = hsl2rgb(cycle_ratio, 1, 0.5);
setColor(color);
polygon(gl, xCoords, yCoords, num_vertices);
int count = 0;
const RGB black = {0, 0, 0};
setColor(black);
for (int v = 0; v < num_vertices; ++v) {
const float angularOffset = interval * v;
for (int t = 0; t < dot_count; ++t) {
const float interval_cycle_ratio = fmod(static_cast<float>(t) / dot_count + cycle_ratio, 1);
const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
Matrix4 m;
m.translate(x1 + ox, y1 + oy);
for (uint32_t i = 0; i < num_circle_verts - 1; ++i) {
circleVerts[count].x = cosf(0) * 3;
circleVerts[count].y = sinf(0) * 3;
circleVerts[count].z = 1;
circleVerts[count].a = 255 * interval_cycle_ratio;
applyColor(circleVerts[count], black);
applyMatrix(circleVerts[count], m);
count++;
circleVerts[count].x = cosf(interval * i) * 3;
circleVerts[count].y = sinf(interval * i) * 3;
circleVerts[count].z = 1;
circleVerts[count].a = 255 * interval_cycle_ratio;
applyColor(circleVerts[count], black);
applyMatrix(circleVerts[count], m);
count++;
circleVerts[count].x = cosf(interval * (i + 1)) * 3;
circleVerts[count].y = sinf(interval * (i + 1)) * 3;
circleVerts[count].z = 1;
circleVerts[count].a = 255 * interval_cycle_ratio;
applyColor(circleVerts[count], black);
applyMatrix(circleVerts[count], m);
count++;
}
if (t == 0) {
const int n = (v + 1) % num_vertices;
const float x2 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
const float y2 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + angularOffset) * interval_cycle_ratio * RADIUS;
const float x3 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;
const float y3 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2 + (interval * n)) * interval_cycle_ratio * RADIUS;
line(gl, x2 + ox, y2 + oy, xCoords[v], yCoords[v]);
line(gl, x2 + ox, y2 + oy, x3 + ox, y3 + oy);
}
}
}
for (float i = 0; i < dot_count; ++i) {
const float interval_cycle_ratio = fmod(i / dot_count + cycle_ratio, 1);
const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2) * RADIUS;
const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI / 2) * RADIUS;
Matrix4 m;
m.translate(x1 + ox, y1 + oy);
for (uint32_t i = 0; i < num_circle_verts - 1; ++i) {
circleVerts[count].x = cosf(0) * 3;
circleVerts[count].y = sinf(0) * 3;
circleVerts[count].z = 1;
applyColor(circleVerts[count], black);
applyMatrix(circleVerts[count], m);
count++;
circleVerts[count].x = cosf(interval * i) * 3;
circleVerts[count].y = sinf(interval * i) * 3;
circleVerts[count].z = 1;
applyColor(circleVerts[count], black);
applyMatrix(circleVerts[count], m);
count++;
circleVerts[count].x = cosf(interval * (i + 1)) * 3;
circleVerts[count].y = sinf(interval * (i + 1)) * 3;
circleVerts[count].z = 1;
applyColor(circleVerts[count], black);
applyMatrix(circleVerts[count], m);
count++;
}
}
gl.triangles(circleVerts, count);
}
private:
Vertex circleVerts[(num_circle_verts - 1) * 3 * dot_count * (num_vertices + 1)];
};
int main(int, char**){
Loop5 loop;
loop.Run();
return 0;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
nucBedMain.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
aaronquinlan@gmail.com
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "nucBed.h"
#include "version.h"
using namespace std;
// define our program name
#define PROGRAM_NAME "bedtools nuc"
// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)
// function declarations
void nuc_help(void);
int nuc_main(int argc, char* argv[]) {
// our configuration variables
bool showHelp = false;
// input files
string fastaDbFile;
string bedFile;
string pattern;
// checks for existence of parameters
bool haveFastaDb = false;
bool haveBed = false;
bool printSeq = false;
bool hasPattern = false;
bool forceStrand = false;
bool ignoreCase = false;
bool useFullHeader = false;
// check to see if we should print out some help
if(argc <= 1) showHelp = true;
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if((PARAMETER_CHECK("-h", 2, parameterLength)) ||
(PARAMETER_CHECK("--help", 5, parameterLength))) {
showHelp = true;
}
}
if(showHelp) nuc_help();
// do some parsing (all of these parameters require 2 strings)
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if(PARAMETER_CHECK("-fi", 3, parameterLength)) {
if ((i+1) < argc) {
haveFastaDb = true;
fastaDbFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-bed", 4, parameterLength)) {
if ((i+1) < argc) {
haveBed = true;
bedFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-seq", 4, parameterLength)) {
printSeq = true;
}
else if(PARAMETER_CHECK("-s", 2, parameterLength)) {
forceStrand = true;
}
else if(PARAMETER_CHECK("-C", 2, parameterLength)) {
ignoreCase = true;
}
else if(PARAMETER_CHECK("-pattern", 8, parameterLength)) {
if ((i+1) < argc) {
hasPattern = true;
pattern = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-useFullHeader", 11, parameterLength)) {
useFullHeader = true;
}
else {
cerr << "*****ERROR: Unrecognized parameter: " << argv[i] << " *****" << endl << endl;
showHelp = true;
}
}
if (!haveFastaDb || !haveBed) {
showHelp = true;
}
if (!showHelp) {
NucBed *nuc = new NucBed(fastaDbFile, bedFile, printSeq,
hasPattern, pattern, forceStrand, ignoreCase,
useFullHeader);
delete nuc;
}
else {
nuc_help();
}
return 0;
}
void nuc_help(void) {
cerr << "\nTool: bedtools nuc (aka nucBed)" << endl;
cerr << "Version: " << VERSION << "\n";
cerr << "Summary: Profiles the nucleotide content of intervals in a fasta file." << endl << endl;
cerr << "Usage: " << PROGRAM_NAME << " [OPTIONS] -fi <fasta> -bed <bed/gff/vcf>" << endl << endl;
cerr << "Options: " << endl;
cerr << "\t-fi\tInput FASTA file" << endl << endl;
cerr << "\t-bed\tBED/GFF/VCF file of ranges to extract from -fi" << endl << endl;
cerr << "\t-s\tProfile the sequence according to strand." << endl << endl;
cerr << "\t-seq\tPrint the extracted sequence" << endl << endl;
cerr << "\t-pattern\tReport the number of times a user-defined sequence" << endl;
cerr << "\t\t\tis observed (case-sensitive)." << endl << endl;
cerr << "\t-C\tIgnore case when matching -pattern. By defaulty, case matters." << endl << endl;
cerr << "\t-fullHeader\tUse full fasta header." << endl;
cerr << "\t\t- By default, only the word before the first space or tab "
<< "is used." << endl << endl;
cerr << "Output format: " << endl;
cerr << "\tThe following information will be reported after each BED entry:" << endl;
cerr << "\t 1) %AT content" << endl;
cerr << "\t 2) %GC content" << endl;
cerr << "\t 3) Number of As observed" << endl;
cerr << "\t 4) Number of Cs observed" << endl;
cerr << "\t 5) Number of Gs observed" << endl;
cerr << "\t 6) Number of Ts observed" << endl;
cerr << "\t 7) Number of Ns observed" << endl;
cerr << "\t 8) Number of other bases observed" << endl;
cerr << "\t 9) The length of the explored sequence/interval." << endl;
cerr << "\t 10) The seq. extracted from the FASTA file. (opt., if -seq is used)" << endl;
cerr << "\t 11) The number of times a user's pattern was observed." << endl;
cerr << "\t (opt., if -pattern is used.)" << endl << endl;
// end the program here
exit(1);
}
<commit_msg>typo on option -useFullHeader<commit_after>/*****************************************************************************
nucBedMain.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
aaronquinlan@gmail.com
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "nucBed.h"
#include "version.h"
using namespace std;
// define our program name
#define PROGRAM_NAME "bedtools nuc"
// define our parameter checking macro
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)
// function declarations
void nuc_help(void);
int nuc_main(int argc, char* argv[]) {
// our configuration variables
bool showHelp = false;
// input files
string fastaDbFile;
string bedFile;
string pattern;
// checks for existence of parameters
bool haveFastaDb = false;
bool haveBed = false;
bool printSeq = false;
bool hasPattern = false;
bool forceStrand = false;
bool ignoreCase = false;
bool useFullHeader = false;
// check to see if we should print out some help
if(argc <= 1) showHelp = true;
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if((PARAMETER_CHECK("-h", 2, parameterLength)) ||
(PARAMETER_CHECK("--help", 5, parameterLength))) {
showHelp = true;
}
}
if(showHelp) nuc_help();
// do some parsing (all of these parameters require 2 strings)
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if(PARAMETER_CHECK("-fi", 3, parameterLength)) {
if ((i+1) < argc) {
haveFastaDb = true;
fastaDbFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-bed", 4, parameterLength)) {
if ((i+1) < argc) {
haveBed = true;
bedFile = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-seq", 4, parameterLength)) {
printSeq = true;
}
else if(PARAMETER_CHECK("-s", 2, parameterLength)) {
forceStrand = true;
}
else if(PARAMETER_CHECK("-C", 2, parameterLength)) {
ignoreCase = true;
}
else if(PARAMETER_CHECK("-pattern", 8, parameterLength)) {
if ((i+1) < argc) {
hasPattern = true;
pattern = argv[i + 1];
i++;
}
}
else if(PARAMETER_CHECK("-fullHeader", 11, parameterLength)) {
useFullHeader = true;
}
else {
cerr << "*****ERROR: Unrecognized parameter: " << argv[i] << " *****" << endl << endl;
showHelp = true;
}
}
if (!haveFastaDb || !haveBed) {
showHelp = true;
}
if (!showHelp) {
NucBed *nuc = new NucBed(fastaDbFile, bedFile, printSeq,
hasPattern, pattern, forceStrand, ignoreCase,
useFullHeader);
delete nuc;
}
else {
nuc_help();
}
return 0;
}
void nuc_help(void) {
cerr << "\nTool: bedtools nuc (aka nucBed)" << endl;
cerr << "Version: " << VERSION << "\n";
cerr << "Summary: Profiles the nucleotide content of intervals in a fasta file." << endl << endl;
cerr << "Usage: " << PROGRAM_NAME << " [OPTIONS] -fi <fasta> -bed <bed/gff/vcf>" << endl << endl;
cerr << "Options: " << endl;
cerr << "\t-fi\tInput FASTA file" << endl << endl;
cerr << "\t-bed\tBED/GFF/VCF file of ranges to extract from -fi" << endl << endl;
cerr << "\t-s\tProfile the sequence according to strand." << endl << endl;
cerr << "\t-seq\tPrint the extracted sequence" << endl << endl;
cerr << "\t-pattern\tReport the number of times a user-defined sequence" << endl;
cerr << "\t\t\tis observed (case-sensitive)." << endl << endl;
cerr << "\t-C\tIgnore case when matching -pattern. By defaulty, case matters." << endl << endl;
cerr << "\t-fullHeader\tUse full fasta header." << endl;
cerr << "\t\t- By default, only the word before the first space or tab "
<< "is used." << endl << endl;
cerr << "Output format: " << endl;
cerr << "\tThe following information will be reported after each BED entry:" << endl;
cerr << "\t 1) %AT content" << endl;
cerr << "\t 2) %GC content" << endl;
cerr << "\t 3) Number of As observed" << endl;
cerr << "\t 4) Number of Cs observed" << endl;
cerr << "\t 5) Number of Gs observed" << endl;
cerr << "\t 6) Number of Ts observed" << endl;
cerr << "\t 7) Number of Ns observed" << endl;
cerr << "\t 8) Number of other bases observed" << endl;
cerr << "\t 9) The length of the explored sequence/interval." << endl;
cerr << "\t 10) The seq. extracted from the FASTA file. (opt., if -seq is used)" << endl;
cerr << "\t 11) The number of times a user's pattern was observed." << endl;
cerr << "\t (opt., if -pattern is used.)" << endl << endl;
// end the program here
exit(1);
}
<|endoftext|>
|
<commit_before>#include <QtSerialPort/QSerialPortInfo>
#include <QtCore/QDebug>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QWidget>
#include <cstdlib>
#include <iostream>
#include "GlowneOkno.hpp"
#include "WyborPortu.hpp"
#include "KodyWyjsciowe.hpp"
const char* bledy[14]=
{
"Brak błędu",
"Nie znaleziono urządzenia",
"Brak uprawnień (być może port jest używany przez inny program)",
"Port jest już otwarty",
"Błąd parzystości",
"Błąd ramki",
"Błąd stanu przerwy (rodzaj błędu ramki)",
"Ogólny błąd wysyłania",
"Ogólny błąd odczytu",
"Błąd zasobów (np. port został odłączony w czasie pracy programu)",
"Niedozwolona operacja",
"Nieznany błąd",
"Upłynął limit czasu oczekiwania",
"Port nie został prawidłowo otwarty"
};
GlowneOkno::GlowneOkno(QWidget* parent):QMainWindow(parent)
{
setupRS();
setupOkno();
setupRozklad();
setupWyslij();
setupReset();
setupTemperatura();
setupWykres();
okno_->show();
}
GlowneOkno::~GlowneOkno()
{
zadanaTemperatura_->setValue(0);
ustawTemperature();
rs232_->close();
delete rs232_;
delete zadanaTemperatura_;
delete wyslij_;
delete reset_;
delete wykres_;
//delete danePomiaroweWykres_;
czas_.clear();
temperatura_.clear();
delete okno_;
}
void GlowneOkno::setupOkno(void)
{
okno_=new QWidget();
okno_->resize(800,600);
okno_->setWindowTitle("Kontroler temperatury");
}
void GlowneOkno::setupRozklad(void)
{
glownyRozmieszczacz_=new QVBoxLayout(okno_);
okno_->setLayout(glownyRozmieszczacz_);
}
void GlowneOkno::setupRS(void)
{
rs232_=new QSerialPort(this);
QStringList itemList;
int wybor=QMessageBox::Retry;
do
{
itemList.clear();
Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts())
{
itemList<<port.portName();
qDebug() << port.portName() << port.vendorIdentifier() << port.productIdentifier() << port.hasProductIdentifier() << port.hasVendorIdentifier() << port.isBusy();
}
if(itemList.isEmpty())
{
QMessageBox pytanie(QMessageBox::Warning, "Brak portu szeregowego!", "Nie wykryto żadnego portu szeregowego! \nSprawdź czy port jest dostępny i podejmij ponowną próbę konfiguracji lub zakończ program.", QMessageBox::Ignore|QMessageBox::Abort|QMessageBox::Retry);
wybor=pytanie.exec();
if(wybor==QMessageBox::Abort)
{
QMessageBox(QMessageBox::Critical, "Brak portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
exit(BRAK_PORTU);
}
}
}
while(itemList.isEmpty()&&wybor!=QMessageBox::Ignore);
WyborPortu dialog(itemList);
int wynik;
do
{
wynik=dialog.exec();
rs232_->setPortName(dialog.poleKombi()->currentText());
if(wynik==QDialog::Rejected)
{
QMessageBox(QMessageBox::Critical, "Nie wybrano portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
exit(2);
}
}
while(wynik != QDialog::Accepted);
rs232_->open (QIODevice::ReadWrite);
rs232_->setBaudRate (QSerialPort::Baud57600);
rs232_->setDataBits (QSerialPort::Data8);
rs232_->setStopBits (QSerialPort::OneStop);
rs232_->setParity (QSerialPort::NoParity);
rs232_->setFlowControl (QSerialPort::NoFlowControl);
rs232_->clear();
std::cerr<<rs232_->error()<<std::endl;
QObject::connect(rs232_, SIGNAL(readyRead()),this, SLOT(odbierzDane()));
}
void GlowneOkno::setupTemperatura(void)
{
zadanaTemperatura_=new QSpinBox;
glownyRozmieszczacz_->addWidget(zadanaTemperatura_);
zadanaTemperatura_->setRange(0, 999);
zadanaTemperatura_->setSingleStep(1);
zadanaTemperatura_->setSuffix(" ℃");
}
void GlowneOkno::setupWyslij(void)
{
wyslij_=new QPushButton("Ustaw");
wyslij_->setFixedSize(100,20);
glownyRozmieszczacz_->addWidget(wyslij_);
QObject::connect(wyslij_, SIGNAL(clicked(bool)),this, SLOT(ustawTemperature()));
}
void GlowneOkno::setupZatrzymajGrzanie(void)
{
zatrzymajGrzanie_=new QPushButton("ZatrzymajGrzanie");
zatrzymajGrzanie_->setFixedSize(100,20);
glownyRozmieszczacz_->addWidget(zatrzymajGrzanie_);
}
void GlowneOkno::setupReset(void)
{
reset_=new QPushButton("Reset");
reset_->setFixedSize(100,20);
glownyRozmieszczacz_->addWidget(reset_);
QObject::connect(reset_, SIGNAL(clicked(bool)),this, SLOT(zrestartujUrzadenie()));
}
void GlowneOkno::setupWykres(void)
{
wykres_=new QwtPlot;
glownyRozmieszczacz_->addWidget(wykres_);
wykres_->setTitle ("Bieżąca temperatura próbki");
wykres_->setAxisTitle (QwtPlot::xBottom, "Czas /s");
wykres_->setAxisTitle (QwtPlot::yLeft, "Temperatura /℃");
wykres_->setCanvasBackground(QBrush (Qt::white));
wykres_->setAxisScale (QwtPlot::xBottom, 0, 120);
wykres_->setAxisScale (QwtPlot::yLeft, 0, 800);
danePomiaroweWykres_=new QwtPlotCurve;
danePomiaroweWykres_->setTitle("Temperatura");
danePomiaroweWykres_->setPen(QPen(Qt::blue, 3) ),
danePomiaroweWykres_->setRenderHint(QwtPlotItem::RenderAntialiased, true);
}
bool GlowneOkno::wyslijRozkaz(const char* rozkaz)
{
QSerialPort::SerialPortError error;
bool stan=true;
do
{
error=rs232_->error();
if(error!=QSerialPort::NoError)
{
stan=obsluzBladRS(error);
}
else
{
stan=false;
}
}
while(stan);
if(error==QSerialPort::NoError)
{
rs232_->write(rozkaz);
return OK;
}
return BLAD_PORTU;
}
void GlowneOkno::ustawTemperature(void)
{
char tmp[4];
int t=zadanaTemperatura_->value();
sprintf(tmp,"T%03i",t);
if(wyslijRozkaz(tmp)==OK)
std::cerr<<tmp<<std::endl;
}
void GlowneOkno::odbierzDane(void)
{
char tmpTekst[1024];
char tmp[256];
uint32_t tmpCzas=0;
uint32_t tmpTemperatura=0;
rs232_->readLine(tmpTekst,1023);
rs232_->clear();
sscanf(tmpTekst,"%u,%u,%s",&(tmpCzas),&(tmpTemperatura),tmp);
czas_.push_back((double)tmpCzas);
temperatura_.push_back((double)tmpTemperatura);
danePomiaroweWykres_->setSamples(czas_,temperatura_);
danePomiaroweWykres_->attach(wykres_);
if(czas_.last()>120)
wykres_->setAxisScale (QwtPlot::xBottom, czas_.last()-120, czas_.last());
else
wykres_->setAxisScale (QwtPlot::xBottom, 0, 120);
wykres_->replot();
std::cout<<tmpCzas<<" "<<tmpTemperatura<<std::endl;
}
bool GlowneOkno::obsluzBladRS(QSerialPort::SerialPortError kod_bledu)
{
char opis_bledu[128];
sprintf(opis_bledu,"Błąd portu szeregowego %i:\n%s.",kod_bledu,bledy[kod_bledu]);
QMessageBox pytanie(QMessageBox::Warning, "Brak portu szeregowego!", opis_bledu, QMessageBox::Ignore|QMessageBox::Abort|QMessageBox::Retry);
std::cerr<<opis_bledu<<std::endl;
int wynik=pytanie.exec();
if(wynik==QMessageBox::Abort)
{
QMessageBox(QMessageBox::Critical, "Błąd portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
exit(BLAD_PORTU);
return false;
}
if(wynik==QMessageBox::Retry)
{
return true;
}
//jeśli ani abort ani retry, to ignore
return false;
}
void GlowneOkno::zrestartujUrzadenie(void)
{
if(wyslijRozkaz("R")==OK)
{
czas_.clear();
temperatura_.clear();
}
}
#include "GlowneOkno.moc"
<commit_msg>Przy odbiorze komunikatów z układu program będzie sprawdzał, czy wysyłana wiadomość jest wynikiem pomiaru. Ponieważ wyniki pomiarów mają stałą długość (liczby są uzupełniane zerami), to można kontrolować zgodność przez sprawdzenie, czy przecinki rozdzielające wartości występują w konkretnych punktach łańcucha znaków.<commit_after>#include <QtSerialPort/QSerialPortInfo>
#include <QtCore/QDebug>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QWidget>
#include <cstdlib>
#include <iostream>
#include "GlowneOkno.hpp"
#include "WyborPortu.hpp"
#include "KodyWyjsciowe.hpp"
const char* bledy[14]=
{
"Brak błędu",
"Nie znaleziono urządzenia",
"Brak uprawnień (być może port jest używany przez inny program)",
"Port jest już otwarty",
"Błąd parzystości",
"Błąd ramki",
"Błąd stanu przerwy (rodzaj błędu ramki)",
"Ogólny błąd wysyłania",
"Ogólny błąd odczytu",
"Błąd zasobów (np. port został odłączony w czasie pracy programu)",
"Niedozwolona operacja",
"Nieznany błąd",
"Upłynął limit czasu oczekiwania",
"Port nie został prawidłowo otwarty"
};
GlowneOkno::GlowneOkno(QWidget* parent):QMainWindow(parent)
{
setupRS();
setupOkno();
setupRozklad();
setupWyslij();
setupReset();
setupTemperatura();
setupWykres();
okno_->show();
}
GlowneOkno::~GlowneOkno()
{
zadanaTemperatura_->setValue(0);
ustawTemperature();
rs232_->close();
delete rs232_;
delete zadanaTemperatura_;
delete wyslij_;
delete reset_;
delete wykres_;
//delete danePomiaroweWykres_;
czas_.clear();
temperatura_.clear();
delete okno_;
}
void GlowneOkno::setupOkno(void)
{
okno_=new QWidget();
okno_->resize(800,600);
okno_->setWindowTitle("Kontroler temperatury");
}
void GlowneOkno::setupRozklad(void)
{
glownyRozmieszczacz_=new QVBoxLayout(okno_);
okno_->setLayout(glownyRozmieszczacz_);
}
void GlowneOkno::setupRS(void)
{
rs232_=new QSerialPort(this);
QStringList itemList;
int wybor=QMessageBox::Retry;
do
{
itemList.clear();
Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts())
{
itemList<<port.portName();
qDebug() << port.portName() << port.vendorIdentifier() << port.productIdentifier() << port.hasProductIdentifier() << port.hasVendorIdentifier() << port.isBusy();
}
if(itemList.isEmpty())
{
QMessageBox pytanie(QMessageBox::Warning, "Brak portu szeregowego!", "Nie wykryto żadnego portu szeregowego! \nSprawdź czy port jest dostępny i podejmij ponowną próbę konfiguracji lub zakończ program.", QMessageBox::Ignore|QMessageBox::Abort|QMessageBox::Retry);
wybor=pytanie.exec();
if(wybor==QMessageBox::Abort)
{
QMessageBox(QMessageBox::Critical, "Brak portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
exit(BRAK_PORTU);
}
}
}
while(itemList.isEmpty()&&wybor!=QMessageBox::Ignore);
WyborPortu dialog(itemList);
int wynik;
do
{
wynik=dialog.exec();
rs232_->setPortName(dialog.poleKombi()->currentText());
if(wynik==QDialog::Rejected)
{
QMessageBox(QMessageBox::Critical, "Nie wybrano portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
exit(2);
}
}
while(wynik != QDialog::Accepted);
rs232_->open (QIODevice::ReadWrite);
rs232_->setBaudRate (QSerialPort::Baud57600);
rs232_->setDataBits (QSerialPort::Data8);
rs232_->setStopBits (QSerialPort::OneStop);
rs232_->setParity (QSerialPort::NoParity);
rs232_->setFlowControl (QSerialPort::NoFlowControl);
rs232_->clear();
std::cerr<<rs232_->error()<<std::endl;
QObject::connect(rs232_, SIGNAL(readyRead()),this, SLOT(odbierzDane()));
}
void GlowneOkno::setupTemperatura(void)
{
zadanaTemperatura_=new QSpinBox;
glownyRozmieszczacz_->addWidget(zadanaTemperatura_);
zadanaTemperatura_->setRange(0, 999);
zadanaTemperatura_->setSingleStep(1);
zadanaTemperatura_->setSuffix(" ℃");
}
void GlowneOkno::setupWyslij(void)
{
wyslij_=new QPushButton("Ustaw");
wyslij_->setFixedSize(100,20);
glownyRozmieszczacz_->addWidget(wyslij_);
QObject::connect(wyslij_, SIGNAL(clicked(bool)),this, SLOT(ustawTemperature()));
}
void GlowneOkno::setupZatrzymajGrzanie(void)
{
zatrzymajGrzanie_=new QPushButton("ZatrzymajGrzanie");
zatrzymajGrzanie_->setFixedSize(100,20);
glownyRozmieszczacz_->addWidget(zatrzymajGrzanie_);
}
void GlowneOkno::setupReset(void)
{
reset_=new QPushButton("Reset");
reset_->setFixedSize(100,20);
glownyRozmieszczacz_->addWidget(reset_);
QObject::connect(reset_, SIGNAL(clicked(bool)),this, SLOT(zrestartujUrzadenie()));
}
void GlowneOkno::setupWykres(void)
{
wykres_=new QwtPlot;
glownyRozmieszczacz_->addWidget(wykres_);
wykres_->setTitle ("Bieżąca temperatura próbki");
wykres_->setAxisTitle (QwtPlot::xBottom, "Czas /s");
wykres_->setAxisTitle (QwtPlot::yLeft, "Temperatura /℃");
wykres_->setCanvasBackground(QBrush (Qt::white));
wykres_->setAxisScale (QwtPlot::xBottom, 0, 120);
wykres_->setAxisScale (QwtPlot::yLeft, 0, 800);
danePomiaroweWykres_=new QwtPlotCurve;
danePomiaroweWykres_->setTitle("Temperatura");
danePomiaroweWykres_->setPen(QPen(Qt::blue, 3) ),
danePomiaroweWykres_->setRenderHint(QwtPlotItem::RenderAntialiased, true);
}
bool GlowneOkno::wyslijRozkaz(const char* rozkaz)
{
QSerialPort::SerialPortError error;
bool stan=true;
do
{
error=rs232_->error();
if(error!=QSerialPort::NoError)
{
stan=obsluzBladRS(error);
}
else
{
stan=false;
}
}
while(stan);
if(error==QSerialPort::NoError)
{
rs232_->write(rozkaz);
return OK;
}
return BLAD_PORTU;
}
void GlowneOkno::ustawTemperature(void)
{
char tmp[4];
int t=zadanaTemperatura_->value();
sprintf(tmp,"T%03i",t);
if(wyslijRozkaz(tmp)==OK)
std::cerr<<tmp<<std::endl;
}
void GlowneOkno::odbierzDane(void)
{
char tmpTekst[1024];
char tmp[256];
uint32_t tmpCzas=0;
uint32_t tmpTemperatura=0;
rs232_->readLine(tmpTekst,1023);
rs232_->clear();
if((tmpTekst[10]==',')&&(tmpTekst[17]==','))
{
sscanf(tmpTekst,"%u,%u,%s",&(tmpCzas),&(tmpTemperatura),tmp);
czas_.push_back((double)tmpCzas);
temperatura_.push_back((double)tmpTemperatura);
danePomiaroweWykres_->setSamples(czas_,temperatura_);
danePomiaroweWykres_->attach(wykres_);
if(czas_.last()>120)
wykres_->setAxisScale (QwtPlot::xBottom, czas_.last()-120, czas_.last());
else
wykres_->setAxisScale (QwtPlot::xBottom, 0, 120);
wykres_->replot();
std::cout<<tmpCzas<<" "<<tmpTemperatura<<std::endl;
}
else
{
std::cout<<tmpTekst;
}
}
bool GlowneOkno::obsluzBladRS(QSerialPort::SerialPortError kod_bledu)
{
char opis_bledu[128];
sprintf(opis_bledu,"Błąd portu szeregowego %i:\n%s.",kod_bledu,bledy[kod_bledu]);
QMessageBox pytanie(QMessageBox::Warning, "Brak portu szeregowego!", opis_bledu, QMessageBox::Ignore|QMessageBox::Abort|QMessageBox::Retry);
std::cerr<<opis_bledu<<std::endl;
int wynik=pytanie.exec();
if(wynik==QMessageBox::Abort)
{
QMessageBox(QMessageBox::Critical, "Błąd portu szeregowego!", "Koniec programu.", QMessageBox::Ok).exec();
exit(BLAD_PORTU);
return false;
}
if(wynik==QMessageBox::Retry)
{
return true;
}
//jeśli ani abort ani retry, to ignore
return false;
}
void GlowneOkno::zrestartujUrzadenie(void)
{
if(wyslijRozkaz("R")==OK)
{
czas_.clear();
temperatura_.clear();
}
}
#include "GlowneOkno.moc"
<|endoftext|>
|
<commit_before>#include "seatest.h"
#include <stdlib.h>
#include "picture.h"
//////////////////////////////////////////////////////////////////////////
// EXTERNAL FUNCTIONS
unsigned get_block_sad(picture *pic, picture *ref,
int pic_x, int pic_y, int ref_x, int ref_y,
int block_width, int block_height);
//////////////////////////////////////////////////////////////////////////
// DEFINES
#define TEST_SAD(X, Y) get_block_sad(g_pic, g_ref, 0, 0, (X), (Y), 8, 8)
//////////////////////////////////////////////////////////////////////////
// GLOBALS
const uint8_t ref_data[64] = {
1,2,2,2,2,2,2,3,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
7,8,8,8,8,8,8,9
};
const uint8_t pic_data[64] = {
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1
};
picture *g_pic = 0;
picture *g_ref = 0;
//////////////////////////////////////////////////////////////////////////
// SETUP, TEARDOWN AND HELPER FUNCTIONS
void sad_setup(void)
{
unsigned i;
g_pic = picture_init(8, 8, 1, 1);
for (i = 0; i < 64; ++i) {
g_pic->y_data[i] = pic_data[i] + 48;
}
g_ref = picture_init(8, 8, 1, 1);
for (i = 0; i < 64; ++i) {
g_ref->y_data[i] = ref_data[i] + 48;
}
}
void sad_teardown(void)
{
free(g_pic); g_pic = 0;
free(g_ref); g_ref = 0;
}
//////////////////////////////////////////////////////////////////////////
// TESTS
void test_topleft(void)
{
assert_ulong_equal(
1*(4*4) + (2+4)*(4*4) + 5*(4*4) - 64,
TEST_SAD(-3, -3));
}
void test_top(void)
{
assert_ulong_equal(
(1+3)*4 + 2*(6*4) + (4+6)*4 + 5*(6*4) - 64,
TEST_SAD(0, -3));
}
void test_topright(void)
{
assert_ulong_equal(
3*(4*4) + (2+6)*(4*4) + 5*(4*4) - 64,
TEST_SAD(3, -3));
}
void test_left(void)
{
assert_ulong_equal(
(1+7)*4 + 4*(6*4) + (2+8)*4 + 5*(6*4) - 64,
TEST_SAD(-3, 0));
}
void test_no_offset(void)
{
assert_ulong_equal(
(1+3+7+9) + (2+4+6+8)*6 + 5*(6*6) - 64,
TEST_SAD(0, 0));
}
void test_right(void)
{
assert_ulong_equal(
(3+9)*4 + 6*(4*6) + (2+8)*4 + 5*(6*4) - 64,
TEST_SAD(3, 0));
}
void test_bottomleft(void)
{
assert_ulong_equal(
7*(4*4) + (4+8)*(4*4) + 5*(4*4) - 64,
TEST_SAD(-3, 3));
}
void test_bottom(void)
{
assert_ulong_equal(
(7+9)*4 + 8*(6*4) + (4+6)*4 + 5*(6*4) - 64,
TEST_SAD(0, 3));
}
void test_bottomright(void)
{
assert_ulong_equal(
9*(4*4) + (6+8)*(4*4) + 5*(4*4) - 64,
TEST_SAD(3, 3));
}
//////////////////////////////////////////////////////////////////////////
// TEST FIXTURES
void sad_tests(void)
{
test_fixture_start();
fixture_setup(sad_setup);
run_test(test_topleft);
run_test(test_top);
run_test(test_topright);
run_test(test_left);
run_test(test_no_offset);
run_test(test_right);
run_test(test_bottomleft);
run_test(test_bottom);
run_test(test_bottomright);
fixture_teardown(sad_teardown);
test_fixture_end();
}
<commit_msg>Add tests for movement vectors that are completely out of frame.<commit_after>#include "seatest.h"
#include <stdlib.h>
#include "picture.h"
//////////////////////////////////////////////////////////////////////////
// EXTERNAL FUNCTIONS
unsigned get_block_sad(picture *pic, picture *ref,
int pic_x, int pic_y, int ref_x, int ref_y,
int block_width, int block_height);
//////////////////////////////////////////////////////////////////////////
// DEFINES
#define TEST_SAD(X, Y) get_block_sad(g_pic, g_ref, 0, 0, (X), (Y), 8, 8)
//////////////////////////////////////////////////////////////////////////
// GLOBALS
const uint8_t ref_data[64] = {
1,2,2,2,2,2,2,3,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
4,5,5,5,5,5,5,6,
7,8,8,8,8,8,8,9
};
const uint8_t pic_data[64] = {
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1
};
picture *g_pic = 0;
picture *g_ref = 0;
//////////////////////////////////////////////////////////////////////////
// SETUP, TEARDOWN AND HELPER FUNCTIONS
void sad_setup(void)
{
unsigned i;
g_pic = picture_init(8, 8, 1, 1);
for (i = 0; i < 64; ++i) {
g_pic->y_data[i] = pic_data[i] + 48;
}
g_ref = picture_init(8, 8, 1, 1);
for (i = 0; i < 64; ++i) {
g_ref->y_data[i] = ref_data[i] + 48;
}
}
void sad_teardown(void)
{
free(g_pic); g_pic = 0;
free(g_ref); g_ref = 0;
}
//////////////////////////////////////////////////////////////////////////
// OVERLAPPING BOUNDARY TESTS
void test_topleft(void)
{
assert_ulong_equal(
1*(4*4) + (2+4)*(4*4) + 5*(4*4) - 64,
TEST_SAD(-3, -3));
}
void test_top(void)
{
assert_ulong_equal(
(1+3)*4 + 2*(6*4) + (4+6)*4 + 5*(6*4) - 64,
TEST_SAD(0, -3));
}
void test_topright(void)
{
assert_ulong_equal(
3*(4*4) + (2+6)*(4*4) + 5*(4*4) - 64,
TEST_SAD(3, -3));
}
void test_left(void)
{
assert_ulong_equal(
(1+7)*4 + 4*(6*4) + (2+8)*4 + 5*(6*4) - 64,
TEST_SAD(-3, 0));
}
void test_no_offset(void)
{
assert_ulong_equal(
(1+3+7+9) + (2+4+6+8)*6 + 5*(6*6) - 64,
TEST_SAD(0, 0));
}
void test_right(void)
{
assert_ulong_equal(
(3+9)*4 + 6*(4*6) + (2+8)*4 + 5*(6*4) - 64,
TEST_SAD(3, 0));
}
void test_bottomleft(void)
{
assert_ulong_equal(
7*(4*4) + (4+8)*(4*4) + 5*(4*4) - 64,
TEST_SAD(-3, 3));
}
void test_bottom(void)
{
assert_ulong_equal(
(7+9)*4 + 8*(6*4) + (4+6)*4 + 5*(6*4) - 64,
TEST_SAD(0, 3));
}
void test_bottomright(void)
{
assert_ulong_equal(
9*(4*4) + (6+8)*(4*4) + 5*(4*4) - 64,
TEST_SAD(3, 3));
}
//////////////////////////////////////////////////////////////////////////
// OUT OF FRAME TESTS
void test_topleft_out(void)
{
assert_ulong_equal(
1*(8*8) - 64,
TEST_SAD(-8, -8));
}
void test_top_out(void)
{
assert_ulong_equal(
(1+3)*8 + 2*(6*8) - 64,
TEST_SAD(0, -8));
}
void test_topright_out(void)
{
assert_ulong_equal(
3*(8*8) - 64,
TEST_SAD(8, -8));
}
void test_left_out(void)
{
assert_ulong_equal(
(1+7)*8 + 4*(6*8) - 64,
TEST_SAD(-8, 0));
}
void test_right_out(void)
{
assert_ulong_equal(
(3+9)*8 + 6*(6*8) - 64,
TEST_SAD(8, 0));
}
void test_bottomleft_out(void)
{
assert_ulong_equal(
7*(8*8) - 64,
TEST_SAD(-8, 8));
}
void test_bottom_out(void)
{
assert_ulong_equal(
(7+9)*8 + 8*(6*8) - 64,
TEST_SAD(0, 8));
}
void test_bottomright_out(void)
{
assert_ulong_equal(
9*(8*8) - 64,
TEST_SAD(8, 8));
}
//////////////////////////////////////////////////////////////////////////
// TEST FIXTURES
void sad_tests(void)
{
test_fixture_start();
fixture_setup(sad_setup);
// Tests for movement vectors that overlap frame.
run_test(test_topleft);
run_test(test_top);
run_test(test_topright);
run_test(test_left);
run_test(test_no_offset);
run_test(test_right);
run_test(test_bottomleft);
run_test(test_bottom);
run_test(test_bottomright);
// Tests for movement vectors that are outside the frame.
run_test(test_topleft_out);
run_test(test_top_out);
run_test(test_topright_out);
run_test(test_left_out);
run_test(test_right_out);
run_test(test_bottomleft_out);
run_test(test_bottom_out);
run_test(test_bottomright_out);
fixture_teardown(sad_teardown);
test_fixture_end();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
using namespace std;
int main(int argc, char* argv[]) {
string line;
int linenumber = 0;
int category =0;
double value = 0.0;
int errors = 0;
if(argc < 2) {
cerr << "provide at least one argument" << endl;
return 1;
}
cout << "* trying to open and read: " << argv[1] << endl;
ifstream f (argv[1]);
double absValOne = 0.0;
double aV1_1 = 0.0;
double aV1_2 = 0.0;
double absValTwo = 0.0;
double aV2_1 = 0.0;
double aV2_2 = 0.0;
int wB1 = 0;
int wB2 = 0;
int cntOne = 0;
int cntTwo = 0;
int track = 0;
while(getline(f, line)) {
size_t posr;
track++;
if((posr = line.find("#")) == 0){
//std::cout << "ignoring line" << std::endl;
continue;
}
if(line[0] == '\n'){
//std::cout << "ignoring line" << std::endl;
continue;
}
std::string s = line;
std::string delimiter = ";";
int cat = 0;
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
if(cat==0){
try{
linenumber = std::stoi(token);
}catch(...){
errors++;
//std::cout << "linenumber" << std::endl;
//std::cout << track << std::endl;
break;
}
cat=1;
s.erase(0, pos + delimiter.length());
}
else if(cat==1){
try{
category = std::stoi(token);
}catch(...){
errors++;
//std::cout << "cat" << std::endl;
// std::cout << track << std::endl;
break;
}
s.erase(0, pos + delimiter.length());
try{
value = std::stod(s);
//Checking if value is a proper double format
if(!(value < 0.0 || value >= 0.0)){
errors++;
break;
}
if(value<=0){
//std::cout << "errsth0" << std::endl;
break;
}
}catch(...){
errors++;
//std::cout << "val" << std::endl;
//std::cout << track << std::endl;
break;
}
if(category==1){
cntOne++;
absValOne+= log(value);
}
else if(category==2){
cntTwo++;
absValTwo += log(value);
}
else break;
cat=0;
}
}
/*if(linenumber%100000==0){
std::cout << linenumber << std::endl;
std::cout << "Category One" << std::endl;
std::cout << aV1_1 << std::endl;
std::cout << aV1_2 << std::endl;
std::cout << cntOne << std::endl;
std::cout << absValOne/cntOne << std::endl;
std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;
std::cout << "Category Two" << std::endl;
std::cout << aV2_1 << std::endl;
std::cout << aV2_2 << std::endl;
std::cout << cntTwo << std::endl;
std::cout << absValTwo/cntTwo << std::endl;
std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;
std::cout << "Errors occured" << std::endl;
std::cout << errors << std::endl;
std::cout << "\n" << std::endl;
}*/
}
f.close();
std::cout << "Results:" << std::endl;
std::cout << "Category One" << std::endl;
std::cout << "Valid lines: ";
std::cout << cntOne << std::endl;
std::cout << "Geo Mean: ";
//std::cout << exp(aV1_1/cntOne + aV1_2/cntOne) << std::endl;
std::cout << exp(absValOne/cntOne) << std::endl;
std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;
std::cout << "Category Two" << std::endl;
std::cout << "Valid lines: ";
std::cout << cntTwo << std::endl;
std::cout << "Geo Mean: ";
//std::cout << exp(aV2_1/cntOne + aV2_2/cntOne) << std::endl;
std::cout << exp(absValTwo/cntTwo) << std::endl;
std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl;
std::cout << "Errors occured" << std::endl;
std::cout << errors << std::endl;
return 0;
}
<commit_msg>Delete ass01_01.cpp<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
//
// ------------------------------------------------
// Extrapolation Miniapp: PDE-based extrapolation
// ------------------------------------------------
//
// Compile with: make extrapolate
//
// Sample runs:
// mpirun -np 4 extrapolate -o 3
// mpirun -np 4 extrapolate -rs 3 -dt 0.002 -o 2 -p 1
#include <fstream>
#include <iostream>
#include "../common/mfem-common.hpp"
#include "marking.hpp"
using namespace std;
using namespace mfem;
int problem = 0;
double domainLS(const Vector &coord)
{
// Map from [0,1] to [-1,1].
const int dim = coord.Size();
const double x = coord(0)*2.0 - 1.0,
y = coord(1)*2.0 - 1.0,
z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;
switch(problem)
{
case 0:
{
// 2d circle.
return 0.75 - sqrt(x*x + y*y + 1e-12);
}
case 1:
{
// 2d star.
return 0.60 - sqrt(x*x + y*y + 1e-12) +
0.25 * (y*y*y*y*y + 5.0*x*x*x*x*y - 10.0*x*x*y*y*y) /
pow(x*x + y*y + 1e-12, 2.5);
}
default: MFEM_ABORT("Bad option for --problem!"); return 0.0;
}
}
double solution0(const Vector &coord)
{
// Map from [0,1] to [-1,1].
const int dim = coord.Size();
const double x = coord(0)*2.0 - 1.0,
y = coord(1)*2.0 - 1.0,
z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;
if (domainLS(coord) > 0.0)
{
return std::cos(M_PI * x) * std::sin(M_PI * y);
}
else { return 0.0; }
}
class LevelSetNormalGradCoeff : public VectorCoefficient
{
private:
const ParGridFunction &ls_gf;
public:
LevelSetNormalGradCoeff(const ParGridFunction &ls) :
VectorCoefficient(ls.ParFESpace()->GetMesh()->Dimension()), ls_gf(ls) { }
virtual void Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
Vector grad_ls(vdim), n(vdim);
ls_gf.GetGradient(T, grad_ls);
const double norm_grad = grad_ls.Norml2();
V = grad_ls;
if (norm_grad > 0.0) { V /= norm_grad; }
// Since positive level set values correspond to the known region, we
// transport into the opposite direction of the gradient.
V *= -1;
}
};
class NormalGradCoeff : public Coefficient
{
private:
const ParGridFunction &u_gf;
LevelSetNormalGradCoeff &n_coeff;
public:
NormalGradCoeff(const ParGridFunction &u, LevelSetNormalGradCoeff &n) :
u_gf(u), n_coeff(n) { }
virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
{
const int dim = T.GetDimension();
Vector n(dim), grad_u(dim);
n_coeff.Eval(n, T, ip);
u_gf.GetGradient(T, grad_u);
return n * grad_u;
}
};
class Extrapolator : public TimeDependentOperator
{
private:
Array<bool> &active_zones;
ParBilinearForm &M, &K;
const Vector &b;
Solver *M_prec;
CGSolver M_solver;
public:
Extrapolator(Array<bool> &zones,
ParBilinearForm &Mbf, ParBilinearForm &Kbf, const Vector &rhs)
: TimeDependentOperator(Mbf.Size()),
active_zones(zones),
M(Mbf), K(Kbf),
b(rhs), M_prec(NULL), M_solver(M.ParFESpace()->GetComm()) { }
virtual void Mult(const Vector &x, Vector &dx) const
{
K.BilinearForm::operator=(0.0);
K.Assemble();
ParFiniteElementSpace &pfes = *M.ParFESpace();
const int NE = pfes.GetNE();
const int nd = pfes.GetFE(0)->GetDof();
Vector rhs(x.Size());
HypreParMatrix *K_mat = K.ParallelAssemble(&K.SpMat());
K_mat->Mult(x, rhs);
rhs += b;
Array<int> dofs(nd);
DenseMatrix M_loc(nd);
DenseMatrixInverse M_loc_inv(&M_loc);
Vector rhs_loc(nd), dx_loc(nd);
for (int k = 0; k < NE; k++)
{
pfes.GetElementDofs(k, dofs);
if (active_zones[k] == false)
{
dx.SetSubVector(dofs, 0.0);
continue;
}
rhs.GetSubVector(dofs, rhs_loc);
M.SpMat().GetSubMatrix(dofs, dofs, M_loc);
M_loc_inv.Factor();
M_loc_inv.Mult(rhs_loc, dx_loc);
dx.SetSubVector(dofs, dx_loc);
}
}
};
int main(int argc, char *argv[])
{
// Initialize MPI.
MPI_Session mpi;
int myid = mpi.WorldRank();
// Parse command-line options.
const char *mesh_file = "../../data/inline-quad.mesh";
int rs_levels = 2;
int order = 2;
int ode_solver_type = 2;
double dt = 0.005;
bool visualization = true;
int vis_steps = 5;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&rs_levels, "-rs", "--refine-serial",
"Number of times to refine the mesh uniformly in serial.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&ode_solver_type, "-s", "--ode-solver",
"ODE solver: 1 - Forward Euler,\n\t"
" 2 - RK2 SSP,\n\t"
" 3 - RK3 SSP");
args.AddOption(&problem, "-p", "--problem",
"0 - 2D circle,\n\t"
"1 - 2D star");
args.AddOption(&dt, "-dt", "--time-step", "Time step.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&vis_steps, "-vs", "--visualization-steps",
"Visualize every n-th timestep.");
args.Parse();
if (!args.Good())
{
if (myid == 0) { args.PrintUsage(cout); }
return 1;
}
if (myid == 0) { args.PrintOptions(cout); }
char vishost[] = "localhost";
int visport = 19916, wsize = 500;
socketstream sock_grad_u_n, sock_u;
// Refine the mesh.
Mesh mesh(mesh_file, 1, 1);
for (int lev = 0; lev < rs_levels; lev++) { mesh.UniformRefinement(); }
// MPI distribution.
ParMesh pmesh(MPI_COMM_WORLD, mesh);
mesh.Clear();
const int dim = pmesh.Dimension(), NE = pmesh.GetNE();
FunctionCoefficient ls_coeff(domainLS), u0_coeff(solution0);
L2_FECollection fec_L2(order, dim, BasisType::GaussLobatto);
ParFiniteElementSpace pfes_L2(&pmesh, &fec_L2);
ParGridFunction u(&pfes_L2);
u.ProjectCoefficient(u0_coeff);
// Initialize the level set.
H1_FECollection fec(order, dim);
ParFiniteElementSpace pfes_H1(&pmesh, &fec);
ParGridFunction level_set(&pfes_H1);
level_set.ProjectCoefficient(ls_coeff);
if (visualization)
{
socketstream sol_sock_w;
common::VisualizeField(sol_sock_w, vishost, visport, level_set,
"Domain level set", 0, 0, wsize, wsize,
"rRjmm********A");
MPI_Barrier(pmesh.GetComm());
}
// Setup a VectorCoefficient for n = - grad_ls / |grad_ls|.
// The sign makes it point out of the known region.
LevelSetNormalGradCoeff ls_n_coeff(level_set);
// Mark elements.
Array<int> elem_marker, dofs;
ShiftedFaceMarker marker(pmesh, pfes_L2, false);
level_set.ExchangeFaceNbrData();
marker.MarkElements(level_set, elem_marker);
// Trim to the known values (only elements inside the known region).
ParGridFunction u_known(u);
for (int k = 0; k < NE; k++)
{
pfes_L2.GetElementDofs(k, dofs);
if (elem_marker[k] != ShiftedFaceMarker::INSIDE)
{ u_known.SetSubVector(dofs, 0.0); }
}
if (visualization)
{
socketstream sol_socks;
common::VisualizeField(sol_socks, vishost, visport, u_known,
"Fixed (known) u values", wsize, 0, wsize, wsize,
"rRjmm********A");
}
u = u_known;
// Normal derivative function.
ParGridFunction grad_u_n(&pfes_L2);
NormalGradCoeff grad_u_n_coeff(u, ls_n_coeff);
grad_u_n.ProjectCoefficient(grad_u_n_coeff);
if (visualization)
{
socketstream sol_sock;
common::VisualizeField(sol_sock, vishost, visport, grad_u_n,
"grad_u n", 2*wsize, 0, wsize, wsize,
"rRjmm********A");
}
// The active zones are where we extrapolate (where the PDE is solved).
Array<bool> active_zones(NE);
for (int k = 0; k < NE; k++)
{
// Extrapolation is done in zones that are CUT or OUTSIDE.
active_zones[k] = (elem_marker[k] == ShiftedFaceMarker::INSIDE) ? false : true;
}
ParBilinearForm lhs_bf(&pfes_L2), rhs_bf(&pfes_L2);
lhs_bf.AddDomainIntegrator(new MassIntegrator);
const double alpha = -1.0;
rhs_bf.AddDomainIntegrator(new ConvectionIntegrator(ls_n_coeff, alpha));
auto trace_i = new NonconservativeDGTraceIntegrator(ls_n_coeff, alpha);
rhs_bf.AddInteriorFaceIntegrator(trace_i);
rhs_bf.KeepNbrBlock(true);
lhs_bf.Assemble();
lhs_bf.Finalize();
rhs_bf.Assemble(0);
rhs_bf.Finalize(0);
Vector rhs(pfes_L2.GetVSize());
rhs = 0.0;
// Time loop
double t = 0.0;
ODESolver *ode_solver = NULL;
switch (ode_solver_type)
{
case 1: ode_solver = new ForwardEulerSolver; break;
case 2: ode_solver = new RK2Solver(1.0); break;
case 3: ode_solver = new RK3SSPSolver; break;
default:
{
if (myid == 0)
{ cout << "Unknown ODE solver type: " << ode_solver_type << '\n'; }
return 3;
}
}
Extrapolator ext(active_zones, lhs_bf, rhs_bf, rhs);
ode_solver->Init(ext);
bool done = false;
const double t_final = 0.4;
for (int ti = 0; !done;)
{
double dt_real = min(dt, t_final - t);
ode_solver->Step(grad_u_n, t, dt_real);
ti++;
done = (t >= t_final - 1e-8*dt);
if (done || ti % vis_steps == 0)
{
if (myid == 0)
{
cout << "time step: " << ti << ", time: " << t << endl;
}
if (visualization)
{
common::VisualizeField(sock_grad_u_n, vishost, visport, grad_u_n,
"Solution", 2*wsize, 570, wsize, wsize,
"rRjmm********A");
MPI_Barrier(pmesh.GetComm());
}
}
}
lhs_bf.Mult(grad_u_n, rhs);
done = false;
t = 0.0;
for (int ti = 0; !done;)
{
double dt_real = min(dt, t_final - t);
ode_solver->Step(u, t, dt_real);
ti++;
done = (t >= t_final - 1e-8*dt);
if (done || ti % vis_steps == 0)
{
if (myid == 0)
{
cout << "time step: " << ti << ", time: " << t << endl;
}
if (visualization)
{
common::VisualizeField(sock_u, vishost, visport, u,
"Solution", wsize, 570, wsize, wsize,
"rRjmm********A");
MPI_Barrier(pmesh.GetComm());
}
}
}
// ParaView output.
ParaViewDataCollection dacol("ParaViewExtrapolate", &pmesh);
dacol.SetLevelsOfDetail(order);
dacol.RegisterField("filtered_level_set", &level_set);
dacol.SetTime(1.0);
dacol.SetCycle(1);
dacol.Save();
return 0;
}
<commit_msg>Automatic dt calculation.<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
//
// ------------------------------------------------
// Extrapolation Miniapp: PDE-based extrapolation
// ------------------------------------------------
//
// Compile with: make extrapolate
//
// Sample runs:
// mpirun -np 4 extrapolate -o 3
// mpirun -np 4 extrapolate -rs 3 -o 2 -p 1
#include <fstream>
#include <iostream>
#include "../common/mfem-common.hpp"
#include "marking.hpp"
using namespace std;
using namespace mfem;
int problem = 0;
double domainLS(const Vector &coord)
{
// Map from [0,1] to [-1,1].
const int dim = coord.Size();
const double x = coord(0)*2.0 - 1.0,
y = coord(1)*2.0 - 1.0,
z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;
switch(problem)
{
case 0:
{
// 2d circle.
return 0.75 - sqrt(x*x + y*y + 1e-12);
}
case 1:
{
// 2d star.
return 0.60 - sqrt(x*x + y*y + 1e-12) +
0.25 * (y*y*y*y*y + 5.0*x*x*x*x*y - 10.0*x*x*y*y*y) /
pow(x*x + y*y + 1e-12, 2.5);
}
default: MFEM_ABORT("Bad option for --problem!"); return 0.0;
}
}
double solution0(const Vector &coord)
{
// Map from [0,1] to [-1,1].
const int dim = coord.Size();
const double x = coord(0)*2.0 - 1.0,
y = coord(1)*2.0 - 1.0,
z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;
if (domainLS(coord) > 0.0)
{
return std::cos(M_PI * x) * std::sin(M_PI * y);
}
else { return 0.0; }
}
class LevelSetNormalGradCoeff : public VectorCoefficient
{
private:
const ParGridFunction &ls_gf;
public:
LevelSetNormalGradCoeff(const ParGridFunction &ls) :
VectorCoefficient(ls.ParFESpace()->GetMesh()->Dimension()), ls_gf(ls) { }
virtual void Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
Vector grad_ls(vdim), n(vdim);
ls_gf.GetGradient(T, grad_ls);
const double norm_grad = grad_ls.Norml2();
V = grad_ls;
if (norm_grad > 0.0) { V /= norm_grad; }
// Since positive level set values correspond to the known region, we
// transport into the opposite direction of the gradient.
V *= -1;
}
};
class NormalGradCoeff : public Coefficient
{
private:
const ParGridFunction &u_gf;
LevelSetNormalGradCoeff &n_coeff;
public:
NormalGradCoeff(const ParGridFunction &u, LevelSetNormalGradCoeff &n) :
u_gf(u), n_coeff(n) { }
virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
{
const int dim = T.GetDimension();
Vector n(dim), grad_u(dim);
n_coeff.Eval(n, T, ip);
u_gf.GetGradient(T, grad_u);
return n * grad_u;
}
};
class Extrapolator : public TimeDependentOperator
{
private:
Array<bool> &active_zones;
ParBilinearForm &M, &K;
const Vector &b;
Solver *M_prec;
CGSolver M_solver;
public:
Extrapolator(Array<bool> &zones,
ParBilinearForm &Mbf, ParBilinearForm &Kbf, const Vector &rhs)
: TimeDependentOperator(Mbf.Size()),
active_zones(zones),
M(Mbf), K(Kbf),
b(rhs), M_prec(NULL), M_solver(M.ParFESpace()->GetComm()) { }
virtual void Mult(const Vector &x, Vector &dx) const
{
K.BilinearForm::operator=(0.0);
K.Assemble();
ParFiniteElementSpace &pfes = *M.ParFESpace();
const int NE = pfes.GetNE();
const int nd = pfes.GetFE(0)->GetDof();
Vector rhs(x.Size());
HypreParMatrix *K_mat = K.ParallelAssemble(&K.SpMat());
K_mat->Mult(x, rhs);
rhs += b;
Array<int> dofs(nd);
DenseMatrix M_loc(nd);
DenseMatrixInverse M_loc_inv(&M_loc);
Vector rhs_loc(nd), dx_loc(nd);
for (int k = 0; k < NE; k++)
{
pfes.GetElementDofs(k, dofs);
if (active_zones[k] == false)
{
dx.SetSubVector(dofs, 0.0);
continue;
}
rhs.GetSubVector(dofs, rhs_loc);
M.SpMat().GetSubMatrix(dofs, dofs, M_loc);
M_loc_inv.Factor();
M_loc_inv.Mult(rhs_loc, dx_loc);
dx.SetSubVector(dofs, dx_loc);
}
}
};
int main(int argc, char *argv[])
{
// Initialize MPI.
MPI_Session mpi;
int myid = mpi.WorldRank();
// Parse command-line options.
const char *mesh_file = "../../data/inline-quad.mesh";
int rs_levels = 2;
int order = 2;
int ode_solver_type = 2;
bool visualization = true;
int vis_steps = 5;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&rs_levels, "-rs", "--refine-serial",
"Number of times to refine the mesh uniformly in serial.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&ode_solver_type, "-s", "--ode-solver",
"ODE solver: 1 - Forward Euler,\n\t"
" 2 - RK2 SSP,\n\t"
" 3 - RK3 SSP");
args.AddOption(&problem, "-p", "--problem",
"0 - 2D circle,\n\t"
"1 - 2D star");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&vis_steps, "-vs", "--visualization-steps",
"Visualize every n-th timestep.");
args.Parse();
if (!args.Good())
{
if (myid == 0) { args.PrintUsage(cout); }
return 1;
}
if (myid == 0) { args.PrintOptions(cout); }
char vishost[] = "localhost";
int visport = 19916, wsize = 500;
socketstream sock_grad_u_n, sock_u;
// Refine the mesh.
Mesh mesh(mesh_file, 1, 1);
for (int lev = 0; lev < rs_levels; lev++) { mesh.UniformRefinement(); }
// MPI distribution.
ParMesh pmesh(MPI_COMM_WORLD, mesh);
mesh.Clear();
const int dim = pmesh.Dimension(), NE = pmesh.GetNE();
FunctionCoefficient ls_coeff(domainLS), u0_coeff(solution0);
L2_FECollection fec_L2(order, dim, BasisType::GaussLobatto);
ParFiniteElementSpace pfes_L2(&pmesh, &fec_L2);
ParGridFunction u(&pfes_L2);
u.ProjectCoefficient(u0_coeff);
// Initialize the level set.
H1_FECollection fec(order, dim);
ParFiniteElementSpace pfes_H1(&pmesh, &fec);
ParGridFunction level_set(&pfes_H1);
level_set.ProjectCoefficient(ls_coeff);
if (visualization)
{
socketstream sol_sock_w;
common::VisualizeField(sol_sock_w, vishost, visport, level_set,
"Domain level set", 0, 0, wsize, wsize,
"rRjmm********A");
MPI_Barrier(pmesh.GetComm());
}
// Setup a VectorCoefficient for n = - grad_ls / |grad_ls|.
// The sign makes it point out of the known region.
LevelSetNormalGradCoeff ls_n_coeff(level_set);
// Mark elements.
Array<int> elem_marker, dofs;
ShiftedFaceMarker marker(pmesh, pfes_L2, false);
level_set.ExchangeFaceNbrData();
marker.MarkElements(level_set, elem_marker);
// Trim to the known values (only elements inside the known region).
ParGridFunction u_known(u);
for (int k = 0; k < NE; k++)
{
pfes_L2.GetElementDofs(k, dofs);
if (elem_marker[k] != ShiftedFaceMarker::INSIDE)
{ u_known.SetSubVector(dofs, 0.0); }
}
if (visualization)
{
socketstream sol_socks;
common::VisualizeField(sol_socks, vishost, visport, u_known,
"Fixed (known) u values", wsize, 0, wsize, wsize,
"rRjmm********A");
}
u = u_known;
// Normal derivative function.
ParGridFunction grad_u_n(&pfes_L2);
NormalGradCoeff grad_u_n_coeff(u, ls_n_coeff);
grad_u_n.ProjectCoefficient(grad_u_n_coeff);
if (visualization)
{
socketstream sol_sock;
common::VisualizeField(sol_sock, vishost, visport, grad_u_n,
"grad_u n", 2*wsize, 0, wsize, wsize,
"rRjmm********A");
}
// The active zones are where we extrapolate (where the PDE is solved).
Array<bool> active_zones(NE);
for (int k = 0; k < NE; k++)
{
// Extrapolation is done in zones that are CUT or OUTSIDE.
active_zones[k] = (elem_marker[k] == ShiftedFaceMarker::INSIDE) ? false : true;
}
ParBilinearForm lhs_bf(&pfes_L2), rhs_bf(&pfes_L2);
lhs_bf.AddDomainIntegrator(new MassIntegrator);
const double alpha = -1.0;
rhs_bf.AddDomainIntegrator(new ConvectionIntegrator(ls_n_coeff, alpha));
auto trace_i = new NonconservativeDGTraceIntegrator(ls_n_coeff, alpha);
rhs_bf.AddInteriorFaceIntegrator(trace_i);
rhs_bf.KeepNbrBlock(true);
lhs_bf.Assemble();
lhs_bf.Finalize();
rhs_bf.Assemble(0);
rhs_bf.Finalize(0);
Vector rhs(pfes_L2.GetVSize());
rhs = 0.0;
// Compute a CFL time step.
double h_min = std::numeric_limits<double>::infinity();
for (int k = 0; k < NE; k++)
{
h_min = std::min(h_min, pmesh.GetElementSize(k));
}
MPI_Allreduce(MPI_IN_PLACE, &h_min, 1, MPI_DOUBLE, MPI_MIN,
pfes_L2.GetComm());
h_min /= order;
// The propagation speed is 1.
double dt = 0.25 * h_min / 1.0;
// Time loop
double t = 0.0;
ODESolver *ode_solver = NULL;
switch (ode_solver_type)
{
case 1: ode_solver = new ForwardEulerSolver; break;
case 2: ode_solver = new RK2Solver(1.0); break;
case 3: ode_solver = new RK3SSPSolver; break;
default:
{
if (myid == 0)
{ cout << "Unknown ODE solver type: " << ode_solver_type << '\n'; }
return 3;
}
}
Extrapolator ext(active_zones, lhs_bf, rhs_bf, rhs);
ode_solver->Init(ext);
bool done = false;
const double t_final = 0.4;
for (int ti = 0; !done;)
{
double dt_real = min(dt, t_final - t);
ode_solver->Step(grad_u_n, t, dt_real);
ti++;
done = (t >= t_final - 1e-8*dt);
if (done || ti % vis_steps == 0)
{
if (myid == 0)
{
cout << "time step: " << ti << ", time: " << t << endl;
}
if (visualization)
{
common::VisualizeField(sock_grad_u_n, vishost, visport, grad_u_n,
"Solution", 2*wsize, 570, wsize, wsize,
"rRjmm********A");
MPI_Barrier(pmesh.GetComm());
}
}
}
lhs_bf.Mult(grad_u_n, rhs);
done = false;
t = 0.0;
for (int ti = 0; !done;)
{
double dt_real = min(dt, t_final - t);
ode_solver->Step(u, t, dt_real);
ti++;
done = (t >= t_final - 1e-8*dt);
if (done || ti % vis_steps == 0)
{
if (myid == 0)
{
cout << "time step: " << ti << ", time: " << t << endl;
}
if (visualization)
{
common::VisualizeField(sock_u, vishost, visport, u,
"Solution", wsize, 570, wsize, wsize,
"rRjmm********A");
MPI_Barrier(pmesh.GetComm());
}
}
}
// ParaView output.
ParaViewDataCollection dacol("ParaViewExtrapolate", &pmesh);
dacol.SetLevelsOfDetail(order);
dacol.RegisterField("filtered_level_set", &level_set);
dacol.SetTime(1.0);
dacol.SetCycle(1);
dacol.Save();
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <list>
#include <vector>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include "player.h"
using namespace std;
void init(vector<string> &nums, vector<string> &teams, vector<string> &input, vector<string> &roster);
//use is ./program.exe file.csv rosters.txt
int main(int argc, char* argv[])
{
ifstream statsin(argv[1]); // input player stats .csv file
ifstream playersin(argv[2]); // input team rosters
string x;
vector<string> input; // vector of player stats
vector<string> players; //
vector<string> roster; // vector of team roster
vector<Player> obs; // vector of player objects
vector<string> nums; // vecotr of available numbers
vector<string> teams; //
init(nums, teams, input, roster); // initialize player numbers and NFL teams
for(int i=0; i<input.size(); ++i)
{
for(int j=0; j<10; ++j)
{
if(input[i][0]==nums[j][0]&& input[i][0+1]=='-'||input[i][0]==nums[j][0]&& input[i][0+2]=='-')
{
string name;
int count =0;
players.push_back(input[i]);
}
}
}
for(int i=0; i<players.size(); ++i)
{
string pnum="";
if(players[i][1]=='-')
{
pnum+= players[i][0];
}
else
{
pnum+= players[i][0];
pnum+= players[i][1];
}
for(int j=0; j<roster.size(); ++j)
{
if(pnum[0] == roster[j][0])
{
if (players[i][2]== roster[j+2][0]||players[i][3]== roster[j+2][0])
{
Player nextone= Player(roster[j+2], roster[j+1], roster[j+3], "ATL",roster[j]);
bool flag = false;
for(int q=0; q<obs.size(); ++q)
{
if(obs[q].get_fname()==roster[j+2] && obs[q].get_lname()==roster[j+1])
{
flag=true;
}
}
if(!flag)
{
obs.push_back(nextone);
}
}
}
}
}
cout<<obs.size()<<endl;
for(int i=0; i<10; ++i)
{
string name = obs[i].get_fname()+" "+obs[i].get_lname();
string num = obs[i].get_num();
for (int z= 0; z<name.size(); ++z)
{
if (ispunct(name[z]))
{
name.erase(z--, 1);
}
}
for (int z= 0; z<num.size(); ++z)
{
if (ispunct(num[z]))
{
num.erase(z--, 1);
}
}
cout<<"{"<<endl;
cout<<"\t'name':'"+name+"',"<<endl;
cout<<"\t'POS':'"+obs[i].get_pos()+"',"<<endl;
cout<<"\t'team':'"+obs[i].get_team()+"',"<<endl;
cout<<"\t'num':'"+num+"',"<<endl;
cout<<"\t'gp':"<<obs[i].get_gp()<<","<<endl;
cout<<"\t'att':"<<obs[i].get_att()<<","<<endl;
cout<<"\t'rushyards':"<<obs[i].get_rushyards()<<","<<endl;
cout<<"\t'rushtuddies':"<<obs[i].get_rushtds()<<","<<endl;
cout<<"\t'recs':"<<obs[i].get_recs()<<","<<endl;
cout<<"\t'tars':"<<obs[i].get_tars()<<","<<endl;
cout<<"\t'recyards':"<<obs[i].get_recyards()<<","<<endl;
cout<<"\t'rectuddies':"<<obs[i].get_rectds()<<","<<endl;
cout<<"\t'comp':"<<obs[i].get_comp()<<","<<endl;
cout<<"\t'passatt':"<<obs[i].get_patts()<<","<<endl;
cout<<"\t'pyards':"<<obs[i].get_pyards()<<","<<endl;
cout<<"\t'ptds':"<<obs[i].get_ptds()<<","<<endl;
cout<<"\t'ints':"<<obs[i].get_interceptions()<<","<<endl;
cout<<"\t'fum':"<<obs[i].get_fum()<<","<<endl;
cout<<"\t'fumlost':"<<obs[i].get_fumlost()<<","<<endl;
cout<<"},"<<endl;
}
}
void init(vector<string> &nums, vector<string> &teams, vector<string> &input, vector<string> &roster){
nums.push_back("1");
nums.push_back("2");
nums.push_back("3");
nums.push_back("4");
nums.push_back("5");
nums.push_back("6");
nums.push_back("7");
nums.push_back("8");
nums.push_back("9");
nums.push_back("0");
teams.push_back("ARI");
teams.push_back("ATL");
teams.push_back("BAL");
teams.push_back("BUF");
teams.push_back("CAR");
teams.push_back("CHI");
teams.push_back("CIN");
teams.push_back("CLE");
teams.push_back("DAL");
teams.push_back("DEN");
teams.push_back("DET");
teams.push_back("GB");
teams.push_back("HOU");
teams.push_back("IND");
teams.push_back("JAX");
teams.push_back("KC");
teams.push_back("MIA");
teams.push_back("MIN");
teams.push_back("NE");
teams.push_back("NO");
teams.push_back("NYG");
teams.push_back("NYJ")
teams.push_back("OAK");
teams.push_back("PHI");
teams.push_back("PIT");
teams.push_back("SD");
teams.push_back("SEA");
teams.push_back("SF");
teams.push_back("STL");
teams.push_back("TB");
teams.push_back("TEN");
teams.push_back("WAS");
while(statsin >> x) // pushback player stats to a vector
{
input.push_back(x);
}
while(playersin >> x) // pushback player names to a vector
{
roster.push_back(x);
}
}
<commit_msg>Minor fix<commit_after>#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <list>
#include <vector>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include "player.h"
using namespace std;
void init(vector<string> &nums, vector<string> &teams, vector<string> &input, vector<string> &roster, ifstream &statsin, ifstream &playersin);
//use is ./program.exe file.csv rosters.txt
int main(int argc, char* argv[])
{
ifstream statsin(argv[1]); // input player stats .csv file
ifstream playersin(argv[2]); // input team rosters
vector<string> input; // vector of player stats
vector<string> players; //
vector<string> roster; // vector of team roster
vector<Player> obs; // vector of player objects
vector<string> nums; // vecotr of available numbers
vector<string> teams; //
init(nums, teams, input, roster,statsin,playersin); // initialize player numbers and NFL teams
for(int i=0; i<input.size(); ++i)
{
for(int j=0; j<10; ++j)
{
if(input[i][0]==nums[j][0]&& input[i][0+1]=='-'||input[i][0]==nums[j][0]&& input[i][0+2]=='-')
{
string name;
int count =0;
players.push_back(input[i]);
}
}
}
for(int i=0; i<players.size(); ++i)
{
string pnum="";
if(players[i][1]=='-')
{
pnum+= players[i][0];
}
else
{
pnum+= players[i][0];
pnum+= players[i][1];
}
for(int j=0; j<roster.size(); ++j)
{
if(pnum[0] == roster[j][0])
{
if (players[i][2]== roster[j+2][0]||players[i][3]== roster[j+2][0])
{
Player nextone= Player(roster[j+2], roster[j+1], roster[j+3], "ATL",roster[j]);
bool flag = false;
for(int q=0; q<obs.size(); ++q)
{
if(obs[q].get_fname()==roster[j+2] && obs[q].get_lname()==roster[j+1])
{
flag=true;
}
}
if(!flag)
{
obs.push_back(nextone);
}
}
}
}
}
cout<<obs.size()<<endl;
for(int i=0; i<10; ++i)
{
string name = obs[i].get_fname()+" "+obs[i].get_lname();
string num = obs[i].get_num();
//remove punctuation from name and num
for (int z= 0; z<name.size(); ++z)
{
if (ispunct(name[z]))
{
name.erase(z--, 1);
}
}
for (int z= 0; z<num.size(); ++z)
{
if (ispunct(num[z]))
{
num.erase(z--, 1);
}
}
cout<<"{"<<endl;
cout<<"\t'name':'"+name+"',"<<endl;
cout<<"\t'POS':'"+obs[i].get_pos()+"',"<<endl;
cout<<"\t'team':'"+obs[i].get_team()+"',"<<endl;
cout<<"\t'num':'"+num+"',"<<endl;
cout<<"\t'gp':"<<obs[i].get_gp()<<","<<endl;
cout<<"\t'att':"<<obs[i].get_att()<<","<<endl;
cout<<"\t'rushyards':"<<obs[i].get_rushyards()<<","<<endl;
cout<<"\t'rushtuddies':"<<obs[i].get_rushtds()<<","<<endl;
cout<<"\t'recs':"<<obs[i].get_recs()<<","<<endl;
cout<<"\t'tars':"<<obs[i].get_tars()<<","<<endl;
cout<<"\t'recyards':"<<obs[i].get_recyards()<<","<<endl;
cout<<"\t'rectuddies':"<<obs[i].get_rectds()<<","<<endl;
cout<<"\t'comp':"<<obs[i].get_comp()<<","<<endl;
cout<<"\t'passatt':"<<obs[i].get_patts()<<","<<endl;
cout<<"\t'pyards':"<<obs[i].get_pyards()<<","<<endl;
cout<<"\t'ptds':"<<obs[i].get_ptds()<<","<<endl;
cout<<"\t'ints':"<<obs[i].get_interceptions()<<","<<endl;
cout<<"\t'fum':"<<obs[i].get_fum()<<","<<endl;
cout<<"\t'fumlost':"<<obs[i].get_fumlost()<<","<<endl;
cout<<"},"<<endl;
}
}
void init(vector<string> &nums, vector<string> &teams, vector<string> &input, vector<string> &roster, ifstream &statsin, ifstream &playersin)
{
string x;
nums.push_back("1");
nums.push_back("2");
nums.push_back("3");
nums.push_back("4");
nums.push_back("5");
nums.push_back("6");
nums.push_back("7");
nums.push_back("8");
nums.push_back("9");
nums.push_back("0");
teams.push_back("ARI");
teams.push_back("ATL");
teams.push_back("BAL");
teams.push_back("BUF");
teams.push_back("CAR");
teams.push_back("CHI");
teams.push_back("CIN");
teams.push_back("CLE");
teams.push_back("DAL");
teams.push_back("DEN");
teams.push_back("DET");
teams.push_back("GB");
teams.push_back("HOU");
teams.push_back("IND");
teams.push_back("JAX");
teams.push_back("KC");
teams.push_back("MIA");
teams.push_back("MIN");
teams.push_back("NE");
teams.push_back("NO");
teams.push_back("NYG");
teams.push_back("NYJ");
teams.push_back("OAK");
teams.push_back("PHI");
teams.push_back("PIT");
teams.push_back("SD");
teams.push_back("SEA");
teams.push_back("SF");
teams.push_back("STL");
teams.push_back("TB");
teams.push_back("TEN");
teams.push_back("WAS");
while(statsin >> x) // pushback player stats to a vector
{
input.push_back(x);
}
while(playersin >> x) // pushback player names to a vector
{
roster.push_back(x);
}
}
<|endoftext|>
|
<commit_before>#include "material.h"
#include <math.h>
#include "comp_math.h"
#include "context.h"
#include "decayer.h"
#include "error.h"
#include "logger.h"
namespace cyclus {
const ResourceType Material::kType = "Material";
Material::~Material() {}
Material::Ptr Material::Create(Agent* creator, double quantity,
Composition::Ptr c) {
Material::Ptr m(new Material(creator->context(), quantity, c));
m->tracker_.Create(creator);
return m;
}
Material::Ptr Material::CreateUntracked(double quantity,
Composition::Ptr c) {
Material::Ptr m(new Material(NULL, quantity, c));
return m;
}
int Material::qual_id() const {
return comp_->id();
}
const ResourceType Material::type() const {
return Material::kType;
}
Resource::Ptr Material::Clone() const {
Material* m = new Material(*this);
Resource::Ptr c(m);
m->tracker_.DontTrack();
return c;
}
void Material::Record(Context* ctx) const {
// Note that no time field is needed because the resource ID changes
// every time the resource changes - state_id by itself is already unique.
ctx_->NewDatum("MaterialInfo")
->AddVal("ResourceId", state_id())
->AddVal("PrevDecayTime", prev_decay_time_)
->Record();
comp_->Record(ctx);
}
std::string Material::units() const {
return "kg";
}
double Material::quantity() const {
return qty_;
}
Resource::Ptr Material::ExtractRes(double qty) {
return boost::static_pointer_cast<Resource>(ExtractQty(qty));
}
Material::Ptr Material::ExtractQty(double qty) {
return ExtractComp(qty, comp_);
}
Material::Ptr Material::ExtractComp(double qty, Composition::Ptr c,
double threshold) {
if (qty_ < qty) {
throw ValueError("mass extraction causes negative quantity");
}
if (comp_ != c) {
CompMap v(comp_->mass());
compmath::Normalize(&v, qty_);
CompMap otherv(c->mass());
compmath::Normalize(&otherv, qty);
CompMap newv = compmath::Sub(v, otherv);
compmath::ApplyThreshold(&newv, threshold);
comp_ = Composition::CreateFromMass(newv);
}
qty_ -= qty;
Material::Ptr other(new Material(ctx_, qty, c));
tracker_.Extract(&other->tracker_);
return other;
}
void Material::Absorb(Material::Ptr mat) {
if (comp_ != mat->comp()) {
CompMap v(comp_->mass());
compmath::Normalize(&v, qty_);
CompMap otherv(mat->comp()->mass());
compmath::Normalize(&otherv, mat->quantity());
comp_ = Composition::CreateFromMass(compmath::Add(v, otherv));
}
qty_ += mat->qty_;
mat->qty_ = 0;
tracker_.Absorb(&mat->tracker_);
}
void Material::Transmute(Composition::Ptr c) {
comp_ = c;
tracker_.Modify();
}
void Material::Decay(int curr_time) {
int dt = curr_time - prev_decay_time_;
double eps = 1e-3;
bool decay = false;
const CompMap c = comp_->atom();
if (c.size() > 100) {
decay = true;
} else {
CompMap::const_iterator it;
for (it = c.end(); it != c.begin(); --it) {
int nuc = it->first;
// 2419200 == secs / month
double lambda_months = pyne::decay_const(nuc) * 2419200;
if (eps <= 1 - std::exp(-lambda_months * dt)) {
decay = true;
break;
}
}
}
if (decay) {
prev_decay_time_ = curr_time;
if (dt > 0) {
Transmute(comp_->Decay(dt));
}
}
}
Composition::Ptr Material::comp() const {
return comp_;
}
Material::Material(Context* ctx, double quantity, Composition::Ptr c)
: qty_(quantity),
comp_(c),
tracker_(ctx, this),
ctx_(ctx),
prev_decay_time_(0) {
if (ctx != NULL) {
prev_decay_time_ = ctx->time();
} else {
tracker_.DontTrack();
}
}
Material::Ptr NewBlankMaterial(double quantity) {
Composition::Ptr comp = Composition::CreateFromMass(CompMap());
return Material::CreateUntracked(quantity, comp);
}
} // namespace cyclus
<commit_msg>only decay if decayallowed is true<commit_after>#include "material.h"
#include <math.h>
#include "comp_math.h"
#include "context.h"
#include "decayer.h"
#include "error.h"
#include "logger.h"
namespace cyclus {
const ResourceType Material::kType = "Material";
Material::~Material() {}
Material::Ptr Material::Create(Agent* creator, double quantity,
Composition::Ptr c) {
Material::Ptr m(new Material(creator->context(), quantity, c));
m->tracker_.Create(creator);
return m;
}
Material::Ptr Material::CreateUntracked(double quantity,
Composition::Ptr c) {
Material::Ptr m(new Material(NULL, quantity, c));
return m;
}
int Material::qual_id() const {
return comp_->id();
}
const ResourceType Material::type() const {
return Material::kType;
}
Resource::Ptr Material::Clone() const {
Material* m = new Material(*this);
Resource::Ptr c(m);
m->tracker_.DontTrack();
return c;
}
void Material::Record(Context* ctx) const {
// Note that no time field is needed because the resource ID changes
// every time the resource changes - state_id by itself is already unique.
ctx_->NewDatum("MaterialInfo")
->AddVal("ResourceId", state_id())
->AddVal("PrevDecayTime", prev_decay_time_)
->Record();
comp_->Record(ctx);
}
std::string Material::units() const {
return "kg";
}
double Material::quantity() const {
return qty_;
}
Resource::Ptr Material::ExtractRes(double qty) {
return boost::static_pointer_cast<Resource>(ExtractQty(qty));
}
Material::Ptr Material::ExtractQty(double qty) {
return ExtractComp(qty, comp_);
}
Material::Ptr Material::ExtractComp(double qty, Composition::Ptr c,
double threshold) {
if (qty_ < qty) {
throw ValueError("mass extraction causes negative quantity");
}
if (comp_ != c) {
CompMap v(comp_->mass());
compmath::Normalize(&v, qty_);
CompMap otherv(c->mass());
compmath::Normalize(&otherv, qty);
CompMap newv = compmath::Sub(v, otherv);
compmath::ApplyThreshold(&newv, threshold);
comp_ = Composition::CreateFromMass(newv);
}
qty_ -= qty;
Material::Ptr other(new Material(ctx_, qty, c));
tracker_.Extract(&other->tracker_);
return other;
}
void Material::Absorb(Material::Ptr mat) {
if (comp_ != mat->comp()) {
CompMap v(comp_->mass());
compmath::Normalize(&v, qty_);
CompMap otherv(mat->comp()->mass());
compmath::Normalize(&otherv, mat->quantity());
comp_ = Composition::CreateFromMass(compmath::Add(v, otherv));
}
qty_ += mat->qty_;
mat->qty_ = 0;
tracker_.Absorb(&mat->tracker_);
}
void Material::Transmute(Composition::Ptr c) {
comp_ = c;
tracker_.Modify();
}
void Material::Decay(int curr_time) {
if (context()->decay() == true) {
int dt = curr_time - prev_decay_time_;
double eps = 1e-3;
bool decay = false;
const CompMap c = comp_->atom();
if (c.size() > 100) {
decay = true;
} else {
CompMap::const_iterator it;
for (it = c.end(); it != c.begin(); --it) {
int nuc = it->first;
// 2419200 == secs / month
double lambda_months = pyne::decay_const(nuc) * 2419200;
if (eps <= 1 - std::exp(-lambda_months * dt)) {
decay = true;
break;
}
}
}
if (decay) {
prev_decay_time_ = curr_time;
if (dt > 0) {
Transmute(comp_->Decay(dt));
}
}
}
}
Composition::Ptr Material::comp() const {
return comp_;
}
Material::Material(Context* ctx, double quantity, Composition::Ptr c)
: qty_(quantity),
comp_(c),
tracker_(ctx, this),
ctx_(ctx),
prev_decay_time_(0) {
if (ctx != NULL) {
prev_decay_time_ = ctx->time();
} else {
tracker_.DontTrack();
}
}
Material::Ptr NewBlankMaterial(double quantity) {
Composition::Ptr comp = Composition::CreateFromMass(CompMap());
return Material::CreateUntracked(quantity, comp);
}
} // namespace cyclus
<|endoftext|>
|
<commit_before>#include "ff_source_syntax.h"
#include <sstream>
#include <stack>
#include "sentence_metadata.h"
#include "array2d.h"
#include "filelib.h"
using namespace std;
// implements the source side syntax features described in Blunsom et al. (EMNLP 2008)
// source trees must be represented in Penn Treebank format, e.g.
// (S (NP John) (VP (V left)))
// log transform to make long spans cluster together
// but preserve differences
inline int SpanSizeTransform(unsigned span_size) {
if (!span_size) return 0;
return static_cast<int>(log(span_size+1) / log(1.39)) - 1;
}
struct SourceSyntaxFeaturesImpl {
SourceSyntaxFeaturesImpl() {}
void InitializeGrids(const string& tree, unsigned src_len) {
assert(tree.size() > 0);
//fids_cat.clear();
fids_ef.clear();
src_tree.clear();
//fids_cat.resize(src_len, src_len + 1);
fids_ef.resize(src_len, src_len + 1);
src_tree.resize(src_len, src_len + 1, TD::Convert("XX"));
ParseTreeString(tree, src_len);
}
void ParseTreeString(const string& tree, unsigned src_len) {
stack<pair<int, WordID> > stk; // first = i, second = category
pair<int, WordID> cur_cat; cur_cat.first = -1;
unsigned i = 0;
unsigned p = 0;
while(p < tree.size()) {
const char cur = tree[p];
if (cur == '(') {
stk.push(cur_cat);
++p;
unsigned k = p + 1;
while (k < tree.size() && tree[k] != ' ') { ++k; }
cur_cat.first = i;
cur_cat.second = TD::Convert(tree.substr(p, k - p));
// cerr << "NT: '" << tree.substr(p, k-p) << "' (i=" << i << ")\n";
p = k + 1;
} else if (cur == ')') {
unsigned k = p;
while (k < tree.size() && tree[k] == ')') { ++k; }
const unsigned num_closes = k - p;
for (unsigned ci = 0; ci < num_closes; ++ci) {
// cur_cat.second spans from cur_cat.first to i
// cerr << TD::Convert(cur_cat.second) << " from " << cur_cat.first << " to " << i << endl;
// NOTE: unary rule chains end up being labeled with the top-most category
src_tree(cur_cat.first, i) = cur_cat.second;
cur_cat = stk.top();
stk.pop();
}
p = k;
while (p < tree.size() && (tree[p] == ' ' || tree[p] == '\t')) { ++p; }
} else if (cur == ' ' || cur == '\t') {
cerr << "Unexpected whitespace in: " << tree << endl;
abort();
} else { // terminal symbol
unsigned k = p + 1;
do {
while (k < tree.size() && tree[k] != ')' && tree[k] != ' ') { ++k; }
// cerr << "TERM: '" << tree.substr(p, k-p) << "' (i=" << i << ")\n";
++i;
assert(i <= src_len);
while (k < tree.size() && tree[k] == ' ') { ++k; }
p = k;
} while (p < tree.size() && tree[p] != ')');
}
}
// cerr << "i=" << i << " src_len=" << src_len << endl;
assert(i == src_len); // make sure tree specified in src_tree is
// the same length as the source sentence
}
WordID FireFeatures(const TRule& rule, const int i, const int j, const WordID* ants, SparseVector<double>* feats) {
//cerr << "fire features: " << rule.AsString() << " for " << i << "," << j << endl;
const WordID lhs = src_tree(i,j);
//int& fid_cat = fids_cat(i,j);
int& fid_ef = fids_ef(i,j)[&rule];
if (fid_ef <= 0) {
ostringstream os;
//ostringstream os2;
os << "SYN:" << TD::Convert(lhs);
//os2 << "SYN:" << TD::Convert(lhs) << '_' << SpanSizeTransform(j - i);
//fid_cat = FD::Convert(os2.str());
os << ':';
unsigned ntc = 0;
for (unsigned k = 0; k < rule.f_.size(); ++k) {
if (k > 0) os << '_';
int fj = rule.f_[k];
if (fj <= 0) {
os << '[' << TD::Convert(ants[ntc++]) << ']';
} else {
os << TD::Convert(fj);
}
}
os << ':';
for (unsigned k = 0; k < rule.e_.size(); ++k) {
const int ei = rule.e_[k];
if (k > 0) os << '_';
if (ei <= 0)
os << '[' << (1-ei) << ']';
else
os << TD::Convert(ei);
}
fid_ef = FD::Convert(os.str());
}
//if (fid_cat > 0)
// feats->set_value(fid_cat, 1.0);
if (fid_ef > 0)
feats->set_value(fid_ef, 1.0);
return lhs;
}
Array2D<WordID> src_tree; // src_tree(i,j) NT = type
// mutable Array2D<int> fids_cat; // this tends to overfit baddly
mutable Array2D<map<const TRule*, int> > fids_ef; // fires for fully lexicalized
};
SourceSyntaxFeatures::SourceSyntaxFeatures(const string& param) :
FeatureFunction(sizeof(WordID)) {
impl = new SourceSyntaxFeaturesImpl;
}
SourceSyntaxFeatures::~SourceSyntaxFeatures() {
delete impl;
impl = NULL;
}
void SourceSyntaxFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,
const Hypergraph::Edge& edge,
const vector<const void*>& ant_contexts,
SparseVector<double>* features,
SparseVector<double>* estimated_features,
void* context) const {
WordID ants[8];
for (unsigned i = 0; i < ant_contexts.size(); ++i)
ants[i] = *static_cast<const WordID*>(ant_contexts[i]);
*static_cast<WordID*>(context) =
impl->FireFeatures(*edge.rule_, edge.i_, edge.j_, ants, features);
}
void SourceSyntaxFeatures::PrepareForInput(const SentenceMetadata& smeta) {
impl->InitializeGrids(smeta.GetSGMLValue("src_tree"), smeta.GetSourceLength());
}
struct SourceSpanSizeFeaturesImpl {
SourceSpanSizeFeaturesImpl() {}
void InitializeGrids(unsigned src_len) {
fids.clear();
fids.resize(src_len, src_len + 1);
}
int FireFeatures(const TRule& rule, const int i, const int j, const WordID* ants, SparseVector<double>* feats) {
if (rule.Arity() > 0) {
int& fid = fids(i,j)[&rule];
if (fid <= 0) {
ostringstream os;
os << "SSS:";
unsigned ntc = 0;
for (unsigned k = 0; k < rule.f_.size(); ++k) {
if (k > 0) os << '_';
int fj = rule.f_[k];
if (fj <= 0) {
os << '[' << TD::Convert(-fj) << ants[ntc++] << ']';
} else {
os << TD::Convert(fj);
}
}
fid = FD::Convert(os.str());
}
if (fid > 0)
feats->set_value(fid, 1.0);
}
return SpanSizeTransform(j - i);
}
mutable Array2D<map<const TRule*, int> > fids;
};
SourceSpanSizeFeatures::SourceSpanSizeFeatures(const string& param) :
FeatureFunction(sizeof(char)) {
impl = new SourceSpanSizeFeaturesImpl;
}
SourceSpanSizeFeatures::~SourceSpanSizeFeatures() {
delete impl;
impl = NULL;
}
void SourceSpanSizeFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,
const Hypergraph::Edge& edge,
const vector<const void*>& ant_contexts,
SparseVector<double>* features,
SparseVector<double>* estimated_features,
void* context) const {
int ants[8];
for (unsigned i = 0; i < ant_contexts.size(); ++i)
ants[i] = *static_cast<const char*>(ant_contexts[i]);
*static_cast<char*>(context) =
impl->FireFeatures(*edge.rule_, edge.i_, edge.j_, ants, features);
}
void SourceSpanSizeFeatures::PrepareForInput(const SentenceMetadata& smeta) {
impl->InitializeGrids(smeta.GetSourceLength());
}
<commit_msg>add target side for sss features<commit_after>#include "ff_source_syntax.h"
#include <sstream>
#include <stack>
#include "sentence_metadata.h"
#include "array2d.h"
#include "filelib.h"
using namespace std;
// implements the source side syntax features described in Blunsom et al. (EMNLP 2008)
// source trees must be represented in Penn Treebank format, e.g.
// (S (NP John) (VP (V left)))
// log transform to make long spans cluster together
// but preserve differences
inline int SpanSizeTransform(unsigned span_size) {
if (!span_size) return 0;
return static_cast<int>(log(span_size+1) / log(1.39)) - 1;
}
struct SourceSyntaxFeaturesImpl {
SourceSyntaxFeaturesImpl() {}
void InitializeGrids(const string& tree, unsigned src_len) {
assert(tree.size() > 0);
//fids_cat.clear();
fids_ef.clear();
src_tree.clear();
//fids_cat.resize(src_len, src_len + 1);
fids_ef.resize(src_len, src_len + 1);
src_tree.resize(src_len, src_len + 1, TD::Convert("XX"));
ParseTreeString(tree, src_len);
}
void ParseTreeString(const string& tree, unsigned src_len) {
stack<pair<int, WordID> > stk; // first = i, second = category
pair<int, WordID> cur_cat; cur_cat.first = -1;
unsigned i = 0;
unsigned p = 0;
while(p < tree.size()) {
const char cur = tree[p];
if (cur == '(') {
stk.push(cur_cat);
++p;
unsigned k = p + 1;
while (k < tree.size() && tree[k] != ' ') { ++k; }
cur_cat.first = i;
cur_cat.second = TD::Convert(tree.substr(p, k - p));
// cerr << "NT: '" << tree.substr(p, k-p) << "' (i=" << i << ")\n";
p = k + 1;
} else if (cur == ')') {
unsigned k = p;
while (k < tree.size() && tree[k] == ')') { ++k; }
const unsigned num_closes = k - p;
for (unsigned ci = 0; ci < num_closes; ++ci) {
// cur_cat.second spans from cur_cat.first to i
// cerr << TD::Convert(cur_cat.second) << " from " << cur_cat.first << " to " << i << endl;
// NOTE: unary rule chains end up being labeled with the top-most category
src_tree(cur_cat.first, i) = cur_cat.second;
cur_cat = stk.top();
stk.pop();
}
p = k;
while (p < tree.size() && (tree[p] == ' ' || tree[p] == '\t')) { ++p; }
} else if (cur == ' ' || cur == '\t') {
cerr << "Unexpected whitespace in: " << tree << endl;
abort();
} else { // terminal symbol
unsigned k = p + 1;
do {
while (k < tree.size() && tree[k] != ')' && tree[k] != ' ') { ++k; }
// cerr << "TERM: '" << tree.substr(p, k-p) << "' (i=" << i << ")\n";
++i;
assert(i <= src_len);
while (k < tree.size() && tree[k] == ' ') { ++k; }
p = k;
} while (p < tree.size() && tree[p] != ')');
}
}
// cerr << "i=" << i << " src_len=" << src_len << endl;
assert(i == src_len); // make sure tree specified in src_tree is
// the same length as the source sentence
}
WordID FireFeatures(const TRule& rule, const int i, const int j, const WordID* ants, SparseVector<double>* feats) {
//cerr << "fire features: " << rule.AsString() << " for " << i << "," << j << endl;
const WordID lhs = src_tree(i,j);
//int& fid_cat = fids_cat(i,j);
int& fid_ef = fids_ef(i,j)[&rule];
if (fid_ef <= 0) {
ostringstream os;
//ostringstream os2;
os << "SYN:" << TD::Convert(lhs);
//os2 << "SYN:" << TD::Convert(lhs) << '_' << SpanSizeTransform(j - i);
//fid_cat = FD::Convert(os2.str());
os << ':';
unsigned ntc = 0;
for (unsigned k = 0; k < rule.f_.size(); ++k) {
if (k > 0) os << '_';
int fj = rule.f_[k];
if (fj <= 0) {
os << '[' << TD::Convert(ants[ntc++]) << ']';
} else {
os << TD::Convert(fj);
}
}
os << ':';
for (unsigned k = 0; k < rule.e_.size(); ++k) {
const int ei = rule.e_[k];
if (k > 0) os << '_';
if (ei <= 0)
os << '[' << (1-ei) << ']';
else
os << TD::Convert(ei);
}
fid_ef = FD::Convert(os.str());
}
//if (fid_cat > 0)
// feats->set_value(fid_cat, 1.0);
if (fid_ef > 0)
feats->set_value(fid_ef, 1.0);
return lhs;
}
Array2D<WordID> src_tree; // src_tree(i,j) NT = type
// mutable Array2D<int> fids_cat; // this tends to overfit baddly
mutable Array2D<map<const TRule*, int> > fids_ef; // fires for fully lexicalized
};
SourceSyntaxFeatures::SourceSyntaxFeatures(const string& param) :
FeatureFunction(sizeof(WordID)) {
impl = new SourceSyntaxFeaturesImpl;
}
SourceSyntaxFeatures::~SourceSyntaxFeatures() {
delete impl;
impl = NULL;
}
void SourceSyntaxFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,
const Hypergraph::Edge& edge,
const vector<const void*>& ant_contexts,
SparseVector<double>* features,
SparseVector<double>* estimated_features,
void* context) const {
WordID ants[8];
for (unsigned i = 0; i < ant_contexts.size(); ++i)
ants[i] = *static_cast<const WordID*>(ant_contexts[i]);
*static_cast<WordID*>(context) =
impl->FireFeatures(*edge.rule_, edge.i_, edge.j_, ants, features);
}
void SourceSyntaxFeatures::PrepareForInput(const SentenceMetadata& smeta) {
impl->InitializeGrids(smeta.GetSGMLValue("src_tree"), smeta.GetSourceLength());
}
struct SourceSpanSizeFeaturesImpl {
SourceSpanSizeFeaturesImpl() {}
void InitializeGrids(unsigned src_len) {
fids.clear();
fids.resize(src_len, src_len + 1);
}
int FireFeatures(const TRule& rule, const int i, const int j, const WordID* ants, SparseVector<double>* feats) {
if (rule.Arity() > 0) {
int& fid = fids(i,j)[&rule];
if (fid <= 0) {
ostringstream os;
os << "SSS:";
unsigned ntc = 0;
for (unsigned k = 0; k < rule.f_.size(); ++k) {
if (k > 0) os << '_';
int fj = rule.f_[k];
if (fj <= 0) {
os << '[' << TD::Convert(-fj) << ants[ntc++] << ']';
} else {
os << TD::Convert(fj);
}
}
os << ':';
for (unsigned k = 0; k < rule.e_.size(); ++k) {
const int ei = rule.e_[k];
if (k > 0) os << '_';
if (ei <= 0)
os << '[' << (1-ei) << ']';
else
os << TD::Convert(ei);
}
fid = FD::Convert(os.str());
}
if (fid > 0)
feats->set_value(fid, 1.0);
}
return SpanSizeTransform(j - i);
}
mutable Array2D<map<const TRule*, int> > fids;
};
SourceSpanSizeFeatures::SourceSpanSizeFeatures(const string& param) :
FeatureFunction(sizeof(char)) {
impl = new SourceSpanSizeFeaturesImpl;
}
SourceSpanSizeFeatures::~SourceSpanSizeFeatures() {
delete impl;
impl = NULL;
}
void SourceSpanSizeFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,
const Hypergraph::Edge& edge,
const vector<const void*>& ant_contexts,
SparseVector<double>* features,
SparseVector<double>* estimated_features,
void* context) const {
int ants[8];
for (unsigned i = 0; i < ant_contexts.size(); ++i)
ants[i] = *static_cast<const char*>(ant_contexts[i]);
*static_cast<char*>(context) =
impl->FireFeatures(*edge.rule_, edge.i_, edge.j_, ants, features);
}
void SourceSpanSizeFeatures::PrepareForInput(const SentenceMetadata& smeta) {
impl->InitializeGrids(smeta.GetSourceLength());
}
<|endoftext|>
|
<commit_before>#include "message.hpp"
#include "server.hpp"
#include "Cereal.hpp"
#include <vector>
#include <iostream>
using namespace std;
MqttFixedHeader::MqttFixedHeader():
type(), dup(), qos(), retain(), remaining() {
}
MqttFixedHeader::MqttFixedHeader(MqttType t, bool d, ubyte q, bool rt, uint re):
type(t), dup(d), qos(q), retain(rt), remaining(re) {
}
void MqttFixedHeader::cerealise(Cereal& cereal) {
cereal.grainBits(type, 4);
cereal.grainBits(dup, 1);
cereal.grainBits(qos, 2);
cereal.grainBits(retain, 1);
switch(cereal.getType()) {
case Cereal::Type::Write:
setRemainingSize(cereal);
break;
case Cereal::Type::Read:
remaining = getRemainingSize(cereal);
break;
}
}
uint MqttFixedHeader::getRemainingSize(Cereal& cereal) {
//algorithm straight from the MQTT spec
int multiplier = 1;
uint value = 0;
ubyte digit;
do {
cereal.grain(digit);
value += (digit & 127) * multiplier;
multiplier *= 128;
} while((digit & 128) != 0);
return value;
}
void MqttFixedHeader::setRemainingSize(Cereal& cereal) const {
//algorithm straight from the MQTT spec
vector<ubyte> digits;
uint x = remaining;
do {
ubyte digit = x % 128;
x /= 128;
if(x > 0) {
digit = digit | 0x80;
}
digits.push_back(digit);
} while(x > 0);
for(auto b: digits) cereal.grain(b);
}
class MqttConnect: public MqttMessage {
public:
MqttConnect(MqttFixedHeader h):header(h) { }
void cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(protoName);
cereal.grain(protoVersion);
cereal.grainBits(hasUserName, 1);
cereal.grainBits(hasPassword, 1);
cereal.grainBits(hasWillRetain, 1);
cereal.grainBits(willQos, 2);
cereal.grainBits(hasWill, 1);
cereal.grainBits(hasClear, 1);
cereal.grainBits(reserved, 1);
cereal.grain(keepAlive);
cereal.grain(clientId);
if(hasWill) cereal.grain(willTopic);
if(hasWill) cereal.grain(willMessage);
if(hasUserName) cereal.grain(userName);
if(hasPassword) cereal.grain(password);
}
bool isBadClientId() const { return clientId.length() < 1 || clientId.length() > 23; }
MqttFixedHeader header;
string protoName;
ubyte protoVersion;
bool hasUserName; //1
bool hasPassword; //1
bool hasWillRetain; //1
ubyte willQos; //2
bool hasWill; //1
bool hasClear; //1
bool reserved; //1
ushort keepAlive;
string clientId;
string willTopic;
string willMessage;
string userName;
string password;
};
class MqttConnack: public MqttMessage {
public:
enum class Code {
ACCEPTED = 0,
BAD_VERSION = 1,
BAD_ID = 2,
SERVER_UNAVAILABLE = 3,
BAD_USER_OR_PWD = 4,
NO_AUTH = 5,
};
MqttConnack():
header(MqttType::CONNACK, false, 0, false, 2) {
}
MqttConnack(Code c):
MqttConnack() {
code = c;
}
void cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(reserved);
cereal.grainBits(code, 8);
}
MqttFixedHeader header;
ubyte reserved;
Code code;
};
class MqttPublish: public MqttMessage {
public:
MqttPublish(MqttFixedHeader h):header(h) {
}
MqttPublish(string topic, std::vector<ubyte> payload, ushort msgId = 0):
MqttPublish(false, 0, false, topic, payload, msgId) {
}
MqttPublish(bool dup, ubyte qos, bool retain, string t, std::vector<ubyte> p, ushort mid = 0) {
const auto topicLen = t.length() + 2; //2 for length
auto remaining = qos ? topicLen + 2 /*msgId*/ : topicLen;
remaining += p.size();
header = MqttFixedHeader(MqttType::PUBLISH, dup, qos, retain, remaining);
topic = t;
payload = std::move(p);
msgId = mid;
}
void cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(topic);
auto payloadLen = header.remaining - (topic.length() + MqttFixedHeader::SIZE);
if(header.qos) {
if(header.remaining < 7 && cereal.getType() == Cereal::Type::Read) {
cerr << "Error: PUBLISH message with QOS but no message ID" << endl;
} else {
cereal.grain(msgId);
payloadLen -= 2;
}
}
if(cereal.getType() == Cereal::Type::Read) payload.resize(payloadLen);
for(auto& b: payload) cereal.grain(b);
}
void handle(MqttServer& server, MqttConnection& connection) const override {
(void)connection;
server.publish(topic, payload);
}
MqttFixedHeader header;
string topic;
std::vector<ubyte> payload;
ushort msgId;
};
MqttSubscribe::MqttSubscribe(MqttFixedHeader h):header(h) {
}
void MqttSubscribe::handle(MqttServer& server, MqttConnection& connection) const {
server.subscribe(connection, msgId, topics);
}
void MqttSubscribe::Topic::cerealise(Cereal& cereal) {
cereal.grain(topic);
cereal.grain(qos);
}
void MqttSubscribe::cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(msgId);
ushort size;
cereal.grain(size);
if(topics.size() != size) topics.resize(size);
for(auto& t: topics) cereal.grain(t);
}
// class MqttSuback: MqttMessage {
// public:
// this(MqttFixedHeader header) {
// this.header = header;
// }
// this(in ushort msgId, in std::vector<ubyte> qos) {
// this.header = MqttFixedHeader(MqttType.SUBACK, false, 0, false, cast(uint)qos.length + 2);
// this.msgId = msgId;
// this.qos = qos.dup;
// }
// MqttFixedHeader header;
// ushort msgId;
// @RawArray std::vector<ubyte> qos;
// }
// class MqttUnsubscribe: MqttMessage {
// this(MqttFixedHeader header) {
// this.header = header;
// }
// override void handle(MqttServer server, MqttConnection connection) const {
// server.unsubscribe(connection, msgId, topics);
// }
// MqttFixedHeader header;
// ushort msgId;
// @RawArray string[] topics;
// }
// class MqttUnsuback: MqttMessage {
// this(in ushort msgId) {
// this.header = MqttFixedHeader(MqttType.UNSUBACK, false, 0, false, 2);
// this.msgId = msgId;
// }
// this(MqttFixedHeader header) {
// this.header = header;
// }
// MqttFixedHeader header;
// ushort msgId;
// }
// class MqttDisconnect: MqttMessage {
// override void handle(MqttServer server, MqttConnection connection) const {
// server.unsubscribe(connection);
// connection.disconnect();
// }
// }
// class MqttPingReq: MqttMessage {
// override void handle(MqttServer server, MqttConnection connection) const {
// server.ping(connection);
// }
// }
// class MqttPingResp: MqttMessage {
// const(std::vector<ubyte>) encode() const {
// return [0xd0, 0x00];
// }
// }
<commit_msg>Uncommented MqttSuback<commit_after>#include "message.hpp"
#include "server.hpp"
#include "Cereal.hpp"
#include <vector>
#include <iostream>
using namespace std;
MqttFixedHeader::MqttFixedHeader():
type(), dup(), qos(), retain(), remaining() {
}
MqttFixedHeader::MqttFixedHeader(MqttType t, bool d, ubyte q, bool rt, uint re):
type(t), dup(d), qos(q), retain(rt), remaining(re) {
}
void MqttFixedHeader::cerealise(Cereal& cereal) {
cereal.grainBits(type, 4);
cereal.grainBits(dup, 1);
cereal.grainBits(qos, 2);
cereal.grainBits(retain, 1);
switch(cereal.getType()) {
case Cereal::Type::Write:
setRemainingSize(cereal);
break;
case Cereal::Type::Read:
remaining = getRemainingSize(cereal);
break;
}
}
uint MqttFixedHeader::getRemainingSize(Cereal& cereal) {
//algorithm straight from the MQTT spec
int multiplier = 1;
uint value = 0;
ubyte digit;
do {
cereal.grain(digit);
value += (digit & 127) * multiplier;
multiplier *= 128;
} while((digit & 128) != 0);
return value;
}
void MqttFixedHeader::setRemainingSize(Cereal& cereal) const {
//algorithm straight from the MQTT spec
vector<ubyte> digits;
uint x = remaining;
do {
ubyte digit = x % 128;
x /= 128;
if(x > 0) {
digit = digit | 0x80;
}
digits.push_back(digit);
} while(x > 0);
for(auto b: digits) cereal.grain(b);
}
class MqttConnect: public MqttMessage {
public:
MqttConnect(MqttFixedHeader h):header(h) { }
void cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(protoName);
cereal.grain(protoVersion);
cereal.grainBits(hasUserName, 1);
cereal.grainBits(hasPassword, 1);
cereal.grainBits(hasWillRetain, 1);
cereal.grainBits(willQos, 2);
cereal.grainBits(hasWill, 1);
cereal.grainBits(hasClear, 1);
cereal.grainBits(reserved, 1);
cereal.grain(keepAlive);
cereal.grain(clientId);
if(hasWill) cereal.grain(willTopic);
if(hasWill) cereal.grain(willMessage);
if(hasUserName) cereal.grain(userName);
if(hasPassword) cereal.grain(password);
}
bool isBadClientId() const { return clientId.length() < 1 || clientId.length() > 23; }
MqttFixedHeader header;
string protoName;
ubyte protoVersion;
bool hasUserName; //1
bool hasPassword; //1
bool hasWillRetain; //1
ubyte willQos; //2
bool hasWill; //1
bool hasClear; //1
bool reserved; //1
ushort keepAlive;
string clientId;
string willTopic;
string willMessage;
string userName;
string password;
};
class MqttConnack: public MqttMessage {
public:
enum class Code {
ACCEPTED = 0,
BAD_VERSION = 1,
BAD_ID = 2,
SERVER_UNAVAILABLE = 3,
BAD_USER_OR_PWD = 4,
NO_AUTH = 5,
};
MqttConnack():
header(MqttType::CONNACK, false, 0, false, 2) {
}
MqttConnack(Code c):
MqttConnack() {
code = c;
}
void cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(reserved);
cereal.grainBits(code, 8);
}
MqttFixedHeader header;
ubyte reserved;
Code code;
};
class MqttPublish: public MqttMessage {
public:
MqttPublish(MqttFixedHeader h):header(h) {
}
MqttPublish(string topic, std::vector<ubyte> payload, ushort msgId = 0):
MqttPublish(false, 0, false, topic, payload, msgId) {
}
MqttPublish(bool dup, ubyte qos, bool retain, string t, std::vector<ubyte> p, ushort mid = 0) {
const auto topicLen = t.length() + 2; //2 for length
auto remaining = qos ? topicLen + 2 /*msgId*/ : topicLen;
remaining += p.size();
header = MqttFixedHeader(MqttType::PUBLISH, dup, qos, retain, remaining);
topic = t;
payload = std::move(p);
msgId = mid;
}
void cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(topic);
auto payloadLen = header.remaining - (topic.length() + MqttFixedHeader::SIZE);
if(header.qos) {
if(header.remaining < 7 && cereal.getType() == Cereal::Type::Read) {
cerr << "Error: PUBLISH message with QOS but no message ID" << endl;
} else {
cereal.grain(msgId);
payloadLen -= 2;
}
}
if(cereal.getType() == Cereal::Type::Read) payload.resize(payloadLen);
for(auto& b: payload) cereal.grain(b);
}
void handle(MqttServer& server, MqttConnection& connection) const override {
(void)connection;
server.publish(topic, payload);
}
MqttFixedHeader header;
string topic;
std::vector<ubyte> payload;
ushort msgId;
};
MqttSubscribe::MqttSubscribe(MqttFixedHeader h):header(h) {
}
void MqttSubscribe::handle(MqttServer& server, MqttConnection& connection) const {
server.subscribe(connection, msgId, topics);
}
void MqttSubscribe::Topic::cerealise(Cereal& cereal) {
cereal.grain(topic);
cereal.grain(qos);
}
void MqttSubscribe::cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(msgId);
ushort size;
cereal.grain(size);
if(topics.size() != size) topics.resize(size);
for(auto& t: topics) cereal.grain(t);
}
class MqttSuback: MqttMessage {
public:
MqttSuback(MqttFixedHeader h):header(h) {
}
MqttSuback(ushort m, std::vector<ubyte> q):
header(MqttType::SUBACK, false, 0, false, qos.size() + 2),
msgId(m),
qos(std::move(q)) {
}
void cerealise(Cereal& cereal) {
cereal.grain(header);
cereal.grain(msgId);
ushort size;
cereal.grain(size);
if(qos.size() != size) qos.resize(size);
for(auto& q: qos) cereal.grain(q);
}
MqttFixedHeader header;
ushort msgId;
std::vector<ubyte> qos;
};
// class MqttUnsubscribe: MqttMessage {
// this(MqttFixedHeader header) {
// this.header = header;
// }
// override void handle(MqttServer server, MqttConnection connection) const {
// server.unsubscribe(connection, msgId, topics);
// }
// MqttFixedHeader header;
// ushort msgId;
// @RawArray string[] topics;
// }
// class MqttUnsuback: MqttMessage {
// this(in ushort msgId) {
// this.header = MqttFixedHeader(MqttType.UNSUBACK, false, 0, false, 2);
// this.msgId = msgId;
// }
// this(MqttFixedHeader header) {
// this.header = header;
// }
// MqttFixedHeader header;
// ushort msgId;
// }
// class MqttDisconnect: MqttMessage {
// override void handle(MqttServer server, MqttConnection connection) const {
// server.unsubscribe(connection);
// connection.disconnect();
// }
// }
// class MqttPingReq: MqttMessage {
// override void handle(MqttServer server, MqttConnection connection) const {
// server.ping(connection);
// }
// }
// class MqttPingResp: MqttMessage {
// const(std::vector<ubyte>) encode() const {
// return [0xd0, 0x00];
// }
// }
<|endoftext|>
|
<commit_before>#include "core/tz.hpp"
#include "core/window.hpp"
#include "core/profiling/zone.hpp"
#include "core/matrix_transform.hpp"
#include "core/time.hpp"
#include "gl/device.hpp"
#include "gl/renderer.hpp"
#include "gl/resource.hpp"
#include "gl/imported_shaders.hpp"
#include ImportedShaderHeader(tz_terrain_demo, vertex)
#include ImportedShaderHeader(tz_terrain_demo, tesscon)
#include ImportedShaderHeader(tz_terrain_demo, tesseval)
#include ImportedShaderHeader(tz_terrain_demo, fragment)
int main()
{
tz::initialise
({
.name = "tz_terrain_demo",
});
{
struct BufferData
{
tz::Mat4 model = tz::model({0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f});
tz::Mat4 view = tz::Mat4::identity();
tz::Mat4 projection = tz::Mat4::identity();
};
tz::gl::Device dev;
tz::gl::BufferResource buf = tz::gl::BufferResource::from_one(BufferData{}, tz::gl::ResourceAccess::DynamicFixed);
tz::gl::RendererInfo rinfo;
tz::gl::ResourceHandle bufh = rinfo.add_resource(buf);
rinfo.shader().set_shader(tz::gl::ShaderStage::Vertex, ImportedShaderSource(tz_terrain_demo, vertex));
rinfo.shader().set_shader(tz::gl::ShaderStage::TessellationControl, ImportedShaderSource(tz_terrain_demo, tesscon));
rinfo.shader().set_shader(tz::gl::ShaderStage::TessellationEvaluation, ImportedShaderSource(tz_terrain_demo, tesseval));
rinfo.shader().set_shader(tz::gl::ShaderStage::Fragment, ImportedShaderSource(tz_terrain_demo, fragment));
rinfo.set_clear_colour({0.0f, 0.765f, 1.0f, 1.0f});
tz::gl::Renderer renderer = dev.create_renderer(rinfo);
tz::Vec3 camera_position{0.0f, 2.0f, 1.0f};
tz::Vec3 cam_rot{0.0f, 0.0f, 0.0f};
bool wireframe_mode = false;
using namespace tz::literals;
tz::Delay fixed_update{25_ms};
constexpr float multiplier = 1.5f;
while(!tz::window().is_close_requested())
{
TZ_FRAME_BEGIN;
tz::window().update();
renderer.render(2);
TZ_FRAME_END;
// Every 25ms, we do a fixed-update.
if(fixed_update.done())
{
fixed_update.reset();
// If Q is pressed, toggle wireframe mode via renderer edit.
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::Q))
{
renderer.edit
({
.render_state_edit = tz::gl::RendererStateEditRequest
{
.wireframe_mode = wireframe_mode
}
});
wireframe_mode = !wireframe_mode;
}
// Retrieve the dynamic buffer resource data.
BufferData& bufd = renderer.get_resource(bufh)->data_as<BufferData>().front();
// Dragging the mouse influences the camera rotation.
static tz::Vec2i mouse_position;
auto mpi = static_cast<tz::Vec2i>(tz::window().get_mouse_position_state().get_mouse_position());
if(tz::window().get_mouse_button_state().is_mouse_button_down(tz::MouseButton::Left))
{
// Get mouse delta since last frame.
tz::Vec2i mouse_delta = mpi - mouse_position;
constexpr float rot_multiplier = 0.003f;
cam_rot[1] -= mouse_delta[0] * rot_multiplier;
cam_rot[0] -= mouse_delta[1] * rot_multiplier;
}
mouse_position = mpi;
bufd.view = tz::view(camera_position, cam_rot);
// Recalculate projection every fixed update. This is a massive waste of time but easily guarantees no distortion if the window is ever resized.
const float aspect_ratio = static_cast<float>(tz::window().get_width()) / tz::window().get_height();
bufd.projection = tz::perspective(1.6f, aspect_ratio, 0.1f, 1000.0f);
// WASD move the camera position around. Space and LeftShift move camera directly up or down.
tz::Vec4 cam_forward4 = bufd.view * tz::Vec4{0.0f, 0.0f, -1.0f, 0.0f};
tz::Vec4 cam_right4 = bufd.view * tz::Vec4{-1.0f, 0.0f, 0.0f, 0.0f};
tz::Vec3 cam_forward = cam_forward4.swizzle<0, 1, 2>();
tz::Vec3 cam_right = cam_right4.swizzle<0, 1, 2>();
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::W))
{
camera_position += cam_forward * multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::S))
{
camera_position -= cam_forward * multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::Space))
{
camera_position[1] += multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::LeftShift))
{
camera_position[1] -= multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::A))
{
camera_position += cam_right * multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::D))
{
camera_position -= cam_right * multiplier;
}
}
}
}
tz::terminate();
}
<commit_msg>* tz_terrain_demo - Camera now spawns slightly above terrain as previously you could be clipping inside the terrain<commit_after>#include "core/tz.hpp"
#include "core/window.hpp"
#include "core/profiling/zone.hpp"
#include "core/matrix_transform.hpp"
#include "core/time.hpp"
#include "gl/device.hpp"
#include "gl/renderer.hpp"
#include "gl/resource.hpp"
#include "gl/imported_shaders.hpp"
#include ImportedShaderHeader(tz_terrain_demo, vertex)
#include ImportedShaderHeader(tz_terrain_demo, tesscon)
#include ImportedShaderHeader(tz_terrain_demo, tesseval)
#include ImportedShaderHeader(tz_terrain_demo, fragment)
int main()
{
tz::initialise
({
.name = "tz_terrain_demo",
});
{
struct BufferData
{
tz::Mat4 model = tz::model({0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f});
tz::Mat4 view = tz::Mat4::identity();
tz::Mat4 projection = tz::Mat4::identity();
};
tz::gl::Device dev;
tz::gl::BufferResource buf = tz::gl::BufferResource::from_one(BufferData{}, tz::gl::ResourceAccess::DynamicFixed);
tz::gl::RendererInfo rinfo;
tz::gl::ResourceHandle bufh = rinfo.add_resource(buf);
rinfo.shader().set_shader(tz::gl::ShaderStage::Vertex, ImportedShaderSource(tz_terrain_demo, vertex));
rinfo.shader().set_shader(tz::gl::ShaderStage::TessellationControl, ImportedShaderSource(tz_terrain_demo, tesscon));
rinfo.shader().set_shader(tz::gl::ShaderStage::TessellationEvaluation, ImportedShaderSource(tz_terrain_demo, tesseval));
rinfo.shader().set_shader(tz::gl::ShaderStage::Fragment, ImportedShaderSource(tz_terrain_demo, fragment));
rinfo.set_clear_colour({0.0f, 0.765f, 1.0f, 1.0f});
tz::gl::Renderer renderer = dev.create_renderer(rinfo);
tz::Vec3 camera_position{0.0f, 50.0f, 1.0f};
tz::Vec3 cam_rot{0.0f, 0.0f, 0.0f};
bool wireframe_mode = false;
using namespace tz::literals;
tz::Delay fixed_update{25_ms};
constexpr float multiplier = 1.5f;
while(!tz::window().is_close_requested())
{
TZ_FRAME_BEGIN;
tz::window().update();
renderer.render(2);
TZ_FRAME_END;
// Every 25ms, we do a fixed-update.
if(fixed_update.done())
{
fixed_update.reset();
// If Q is pressed, toggle wireframe mode via renderer edit.
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::Q))
{
renderer.edit
({
.render_state_edit = tz::gl::RendererStateEditRequest
{
.wireframe_mode = wireframe_mode
}
});
wireframe_mode = !wireframe_mode;
}
// Retrieve the dynamic buffer resource data.
BufferData& bufd = renderer.get_resource(bufh)->data_as<BufferData>().front();
// Dragging the mouse influences the camera rotation.
static tz::Vec2i mouse_position;
auto mpi = static_cast<tz::Vec2i>(tz::window().get_mouse_position_state().get_mouse_position());
if(tz::window().get_mouse_button_state().is_mouse_button_down(tz::MouseButton::Left))
{
// Get mouse delta since last frame.
tz::Vec2i mouse_delta = mpi - mouse_position;
constexpr float rot_multiplier = 0.003f;
cam_rot[1] -= mouse_delta[0] * rot_multiplier;
cam_rot[0] -= mouse_delta[1] * rot_multiplier;
}
mouse_position = mpi;
bufd.view = tz::view(camera_position, cam_rot);
// Recalculate projection every fixed update. This is a massive waste of time but easily guarantees no distortion if the window is ever resized.
const float aspect_ratio = static_cast<float>(tz::window().get_width()) / tz::window().get_height();
bufd.projection = tz::perspective(1.6f, aspect_ratio, 0.1f, 1000.0f);
// WASD move the camera position around. Space and LeftShift move camera directly up or down.
tz::Vec4 cam_forward4 = bufd.view * tz::Vec4{0.0f, 0.0f, -1.0f, 0.0f};
tz::Vec4 cam_right4 = bufd.view * tz::Vec4{-1.0f, 0.0f, 0.0f, 0.0f};
tz::Vec3 cam_forward = cam_forward4.swizzle<0, 1, 2>();
tz::Vec3 cam_right = cam_right4.swizzle<0, 1, 2>();
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::W))
{
camera_position += cam_forward * multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::S))
{
camera_position -= cam_forward * multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::Space))
{
camera_position[1] += multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::LeftShift))
{
camera_position[1] -= multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::A))
{
camera_position += cam_right * multiplier;
}
if(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::D))
{
camera_position -= cam_right * multiplier;
}
}
}
}
tz::terminate();
}
<|endoftext|>
|
<commit_before>import java.util.Scanner;
public class MergeSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int day = Integer.parseInt(scanner.nextLine());
int month = Integer.parseInt(scanner.nextLine());
switch(month) {
case 2:
if (day + 5 > 28) {
month++;
day = day + 5 - 28;
}
else {
day += 5;
}
break;
case 4:
case 6:
case 9:
case 11:
if (day + 5 > 30) {
month++;
day = day + 5 - 30;
}
else {
day += 5;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
if (day + 5 > 31) {
month++;
day = day + 5 - 31;
}
else {
day += 5;
}
break;
case 12:
if (day + 5 > 31) {
month = 1;
day = day + 5 - 31;
}
else {
day += 5;
}
break;
default:
break;
}
System.out.print(day + ".");
if (month < 10) {
System.out.print("0");
}
System.out.print(month);
}
}
<commit_msg>Update 05.DateAfter5Days.cpp<commit_after>import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int day = Integer.parseInt(scanner.nextLine());
int month = Integer.parseInt(scanner.nextLine());
switch(month) {
case 2:
if (day + 5 > 28) {
month++;
day = day + 5 - 28;
}
else {
day += 5;
}
break;
case 4:
case 6:
case 9:
case 11:
if (day + 5 > 30) {
month++;
day = day + 5 - 30;
}
else {
day += 5;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
if (day + 5 > 31) {
month++;
day = day + 5 - 31;
}
else {
day += 5;
}
break;
case 12:
if (day + 5 > 31) {
month = 1;
day = day + 5 - 31;
}
else {
day += 5;
}
break;
default:
break;
}
System.out.print(day + ".");
if (month < 10) {
System.out.print("0");
}
System.out.print(month);
}
}
<|endoftext|>
|
<commit_before>#include "paintarea.h"
#define STARTING_X 10
//Padding from the right side of the window
#define RIGHT_SIDE_PADDING 50
#define STARTING_Y 10
PaintArea::PaintArea(QWidget *parent) :
QWidget(parent)
{
currentX = STARTING_X;
currentY = STARTING_Y;
totalWidth = 0;
webpage = new Document;
positionSet = false;
currentCharacter = new QString;
nextWordChecked = false;
}
void PaintArea::setDocument(Document *documentToSet)
{
webpage = documentToSet;
}
void PaintArea::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
if (webpage->getFirstNode() != NULL)
{
QPainter qPainter(this);
paintNodesVector = webpage->getFirstNode()->getPaintNodes();
drawDocument(&qPainter, paintNodesVector);
//Prevents document from moving around while being redrawn.
positionSet = true;
//This is necessary to show the entire paint area in the scroll area.
setMinimumHeight(currentY);
}
}
void PaintArea::drawDocument(QPainter *qPainter,
std::vector<PaintNode*> *paintNodes)
{
std::vector<PaintNode*>::iterator i = paintNodes->begin();
for (; i != paintNodes->end(); i++)
{
paintCurrentNode(*i, qPainter, paintNodes);
}
}
void PaintArea::insertLineBreak()
{
QFont font = currentFont;
QFontMetrics fm(font);
currentX = STARTING_X;
currentY += 2 * fm.height();
totalWidth = 0;
}
void PaintArea::paintCurrentNode(PaintNode *currentPaintNode,
QPainter *qPainter,
std::vector<PaintNode*> *paintNodes)
{
if (currentPaintNode->getTypeOfPaintNode() == "char")
{
//Draw the text contained within each paragraph node. New lines are
//only added after each paragraph node--not any other element.
if (positionSet)
{
updateCurrentPosition();
}
char *character = currentPaintNode->getCharacter();
*currentCharacter = QString(*character);
currentFont = qPainter->font();
if (currentPaintNode->getWeight() == QFont::Bold)
{
currentFont.setBold(true);
}
else
{
currentFont.setBold(false);
}
QFontMetrics fm(currentFont);
if (!nextWordChecked)
{
if (totalWidth >= this->width() - 200)
{
int currentLineWidth = totalWidth;
currentLineWidth += getNextWordWidth(paintNodes, qPainter);
if (currentLineWidth + STARTING_X >= this->width() - RIGHT_SIDE_PADDING)
{
totalWidth = 0;
currentY += fm.height();
currentX = STARTING_X;
}
nextWordChecked = true;
}
}
QRect box(QPoint(currentX, currentY), QSize(fm.width(*character),
fm.height()));
qPainter->setFont(currentFont);
qPainter->drawText(box, Qt::AlignCenter, QString(*character));
if (isspace(*character))
{
nextWordChecked = false;
}
updateCurrentPosition();
}
else if (currentPaintNode->getTypeOfPaintNode() == "node")
{
//Call the function again on each of the PaintNode's child paint nodes.
//This ensures that all of the child nodes of the overall parent node
//are drawn.
std::vector<PaintNode*> *childPaintNodes = currentPaintNode->
returnNode()->getPaintNodes();
drawDocument(qPainter, childPaintNodes);
if (currentPaintNode->returnNode()->getTypeOfRenderNode() == "p")
{
insertLineBreak();
}
}
}
//This adjusts the location where the next character will be drawn, including
//changing lines when the total length exceeds the width of the window.
void PaintArea::updateCurrentPosition()
{
//positionSet is only true when the entire text has been drawn.
//If it is false, then it is safe to set the character to the spot
//after the current character.
if (!positionSet)
{
QFontMetrics fm(currentFont);
totalWidth += fm.width(*currentCharacter);
currentX += fm.width(*currentCharacter);
if (totalWidth + STARTING_X >= this->width())
{
setMinimumWidth(totalWidth + STARTING_X);
}
}
//However, if positionSet is true, then it is time to draw the entire
//document again, so we reset the current position to the initial state.
else
{
currentX = STARTING_X;
currentY = STARTING_Y;
totalWidth = 0;
positionSet = false;
}
}
int PaintArea::getNextWordWidth(std::vector<PaintNode*> *paintNodes, QPainter *qPainter)
{
int wordWidth = 0;
bool wordEndReached = false;
std::vector<PaintNode*>::iterator currentNode = paintNodes->begin();
for (; !wordEndReached; currentNode++)
{
if (currentNode == paintNodes->end())
{
wordEndReached = true;
}
else if ((*currentNode)->getTypeOfPaintNode() == "char")
{
if (!isspace(*(*currentNode)->getCharacter()))
{
QFont font = qPainter->font();
QFontMetrics fm(font);
wordWidth += fm.width((*currentNode)->getCharacter());
}
else
{
wordEndReached = true;
}
}
else if ((*currentNode)->getTypeOfPaintNode() == "node")
{
wordWidth += getNextWordWidth(paintNodes, qPainter);
}
}
return wordWidth;
}
<commit_msg>Fix bug with text not shrinking to match resized window.<commit_after>#include "paintarea.h"
#define STARTING_X 10
//Padding from the right side of the window
#define RIGHT_SIDE_PADDING 50
#define STARTING_Y 10
PaintArea::PaintArea(QWidget *parent) :
QWidget(parent)
{
currentX = STARTING_X;
currentY = STARTING_Y;
totalWidth = 0;
webpage = new Document;
positionSet = false;
currentCharacter = new QString;
nextWordChecked = false;
}
void PaintArea::setDocument(Document *documentToSet)
{
webpage = documentToSet;
}
void PaintArea::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
if (webpage->getFirstNode() != NULL)
{
QPainter qPainter(this);
paintNodesVector = webpage->getFirstNode()->getPaintNodes();
drawDocument(&qPainter, paintNodesVector);
//Prevents document from moving around while being redrawn.
positionSet = true;
//This is necessary to show the entire paint area in the scroll area.
setMinimumHeight(currentY);
}
}
void PaintArea::drawDocument(QPainter *qPainter,
std::vector<PaintNode*> *paintNodes)
{
std::vector<PaintNode*>::iterator i = paintNodes->begin();
for (; i != paintNodes->end(); i++)
{
paintCurrentNode(*i, qPainter, paintNodes);
}
}
void PaintArea::insertLineBreak()
{
QFont font = currentFont;
QFontMetrics fm(font);
currentX = STARTING_X;
currentY += 2 * fm.height();
totalWidth = 0;
}
void PaintArea::paintCurrentNode(PaintNode *currentPaintNode,
QPainter *qPainter,
std::vector<PaintNode*> *paintNodes)
{
if (currentPaintNode->getTypeOfPaintNode() == "char")
{
//Draw the text contained within each paragraph node. New lines are
//only added after each paragraph node--not any other element.
if (positionSet)
{
updateCurrentPosition();
}
char *character = currentPaintNode->getCharacter();
*currentCharacter = QString(*character);
currentFont = qPainter->font();
if (currentPaintNode->getWeight() == QFont::Bold)
{
currentFont.setBold(true);
}
else
{
currentFont.setBold(false);
}
QFontMetrics fm(currentFont);
if (!nextWordChecked)
{
if (totalWidth >= this->width() - 200)
{
int currentLineWidth = totalWidth;
currentLineWidth += getNextWordWidth(paintNodes, qPainter);
if (currentLineWidth + STARTING_X >= this->width() - RIGHT_SIDE_PADDING)
{
totalWidth = 0;
currentY += fm.height();
currentX = STARTING_X;
}
nextWordChecked = true;
}
}
QRect box(QPoint(currentX, currentY), QSize(fm.width(*character),
fm.height()));
qPainter->setFont(currentFont);
qPainter->drawText(box, Qt::AlignCenter, QString(*character));
if (isspace(*character))
{
nextWordChecked = false;
}
updateCurrentPosition();
}
else if (currentPaintNode->getTypeOfPaintNode() == "node")
{
//Call the function again on each of the PaintNode's child paint nodes.
//This ensures that all of the child nodes of the overall parent node
//are drawn.
std::vector<PaintNode*> *childPaintNodes = currentPaintNode->
returnNode()->getPaintNodes();
drawDocument(qPainter, childPaintNodes);
if (currentPaintNode->returnNode()->getTypeOfRenderNode() == "p")
{
insertLineBreak();
}
}
}
//This adjusts the location where the next character will be drawn, including
//changing lines when the total length exceeds the width of the window.
void PaintArea::updateCurrentPosition()
{
//positionSet is only true when the entire text has been drawn.
//If it is false, then it is safe to set the character to the spot
//after the current character.
if (!positionSet)
{
QFontMetrics fm(currentFont);
totalWidth += fm.width(*currentCharacter);
currentX += fm.width(*currentCharacter);
}
//However, if positionSet is true, then it is time to draw the entire
//document again, so we reset the current position to the initial state.
else
{
currentX = STARTING_X;
currentY = STARTING_Y;
totalWidth = 0;
positionSet = false;
}
}
int PaintArea::getNextWordWidth(std::vector<PaintNode*> *paintNodes, QPainter *qPainter)
{
int wordWidth = 0;
bool wordEndReached = false;
std::vector<PaintNode*>::iterator currentNode = paintNodes->begin();
for (; !wordEndReached; currentNode++)
{
if (currentNode == paintNodes->end())
{
wordEndReached = true;
}
else if ((*currentNode)->getTypeOfPaintNode() == "char")
{
if (!isspace(*(*currentNode)->getCharacter()))
{
QFont font = qPainter->font();
QFontMetrics fm(font);
wordWidth += fm.width((*currentNode)->getCharacter());
}
else
{
wordEndReached = true;
}
}
else if ((*currentNode)->getTypeOfPaintNode() == "node")
{
wordWidth += getNextWordWidth(paintNodes, qPainter);
}
}
return wordWidth;
}
<|endoftext|>
|
<commit_before>/**
* Copyright 2014, Planet Labs, 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 <algorithm>
#include "compositor.h"
/************************************************************************/
/* PercentileQuality */
/************************************************************************/
class PercentileQuality : public QualityMethodBase
{
PLCInput *input;
std::vector<float> targetQuality;
double percentileRatio;
public:
PercentileQuality() : QualityMethodBase("percentile") {}
~PercentileQuality() {}
/********************************************************************/
QualityMethodBase *create(PLCContext* context, WJElement node) {
PercentileQuality *obj = new PercentileQuality();
if( node == NULL )
{
CPLString default_percentile;
if( EQUAL(context->getStratParam("compositor", "quality"),
"median") )
default_percentile = "50";
else
default_percentile = "100";
// 50 is true median, 100 is best quality, 0 is worst quality.
obj->percentileRatio = atof(
context->getStratParam("quality_percentile",
default_percentile)) / 100.0;
// median_ratio is here for backwards compatability, quality_percentile
// Eventually it should be removed.
if( context->getStratParam("median_ratio", NULL) != NULL )
obj->percentileRatio = atof(context->getStratParam("median_ratio", NULL));
CPLDebug("PLC", "Percentile quality in effect, ratio=%.3f",
obj->percentileRatio);
}
else
{
obj->percentileRatio = WJEDouble(node, "quality_percentile",
WJE_GET, 50.0) / 100.0;
}
return obj;
}
/********************************************************************/
void mergeQuality(PLCInput *input, PLCLine *line) {
float *quality = line->getQuality();
float *newQuality = line->getNewQuality();
// In this case we copy the new quality over the old since it already incorporates
// the old.
for(int i=0; i < line->getWidth(); i++)
{
quality[i] = newQuality[i];
newQuality[i] = 1.0;
}
}
/********************************************************************/
int computeQuality(PLCInput *input, PLCLine *lineObj) {
float *newQuality = lineObj->getNewQuality();
float *oldQuality = lineObj->getQuality();
for(int i=lineObj->getWidth()-1; i >= 0; i--)
{
if( oldQuality[i] <= 0 )
newQuality[i] = -1;
else
newQuality[i] = 1.0 - fabs(oldQuality[i] - targetQuality[i]); // rescale?
}
return TRUE;
}
/********************************************************************/
int computeStackQuality(PLCContext *context, std::vector<PLCLine*>& lines) {
unsigned int i;
std::vector<float*> inputQualities;
targetQuality.resize(context->width);
for(i = 0; i < context->inputFiles.size(); i++ )
inputQualities.push_back(lines[i]->getQuality());
std::vector<float> pixelQualities;
pixelQualities.resize(context->width);
for(int iPixel=0; iPixel < context->width; iPixel++)
{
int activeCandidates = 0;
for(i=0; i < inputQualities.size(); i++)
{
if( inputQualities[i][iPixel] > 0.0 )
pixelQualities[activeCandidates++] = inputQualities[i][iPixel];
}
if( activeCandidates > 1 )
{
std::sort(pixelQualities.begin(),
pixelQualities.begin()+activeCandidates);
int bestCandidate =
MAX(0,MIN(activeCandidates-1,
((int) floor(activeCandidates*percentileRatio))));
targetQuality[iPixel] = pixelQualities[bestCandidate];
}
else if( activeCandidates == 1 )
targetQuality[iPixel] = pixelQualities[0];
else
targetQuality[iPixel] = -1.0;
}
return QualityMethodBase::computeStackQuality(context, lines);
}
};
static PercentileQuality percentileQualityTemplateInstance;
<commit_msg>debug output for percentile value added<commit_after>/**
* Copyright 2014, Planet Labs, 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 <algorithm>
#include "compositor.h"
/************************************************************************/
/* PercentileQuality */
/************************************************************************/
class PercentileQuality : public QualityMethodBase
{
PLCInput *input;
std::vector<float> targetQuality;
double percentileRatio;
public:
PercentileQuality() : QualityMethodBase("percentile") {}
~PercentileQuality() {}
/********************************************************************/
QualityMethodBase *create(PLCContext* context, WJElement node) {
PercentileQuality *obj = new PercentileQuality();
if( node == NULL )
{
CPLString default_percentile;
if( EQUAL(context->getStratParam("compositor", "quality"),
"median") )
default_percentile = "50";
else
default_percentile = "100";
// 50 is true median, 100 is best quality, 0 is worst quality.
obj->percentileRatio = atof(
context->getStratParam("quality_percentile",
default_percentile)) / 100.0;
// median_ratio is here for backwards compatability, quality_percentile
// Eventually it should be removed.
if( context->getStratParam("median_ratio", NULL) != NULL )
obj->percentileRatio = atof(context->getStratParam("median_ratio", NULL));
CPLDebug("PLC", "Percentile quality in effect, ratio=%.3f",
obj->percentileRatio);
}
else
{
obj->percentileRatio = WJEDouble(node, "quality_percentile",
WJE_GET, 50.0) / 100.0;
CPLDebug("PLC", "Percentile Quality: %.2f.", obj->percentileRatio);
}
return obj;
}
/********************************************************************/
void mergeQuality(PLCInput *input, PLCLine *line) {
float *quality = line->getQuality();
float *newQuality = line->getNewQuality();
// In this case we copy the new quality over the old since it already incorporates
// the old.
for(int i=0; i < line->getWidth(); i++)
{
quality[i] = newQuality[i];
newQuality[i] = 1.0;
}
}
/********************************************************************/
int computeQuality(PLCInput *input, PLCLine *lineObj) {
float *newQuality = lineObj->getNewQuality();
float *oldQuality = lineObj->getQuality();
for(int i=lineObj->getWidth()-1; i >= 0; i--)
{
if( oldQuality[i] <= 0 )
newQuality[i] = -1;
else
newQuality[i] = 1.0 - fabs(oldQuality[i] - targetQuality[i]); // rescale?
}
return TRUE;
}
/********************************************************************/
int computeStackQuality(PLCContext *context, std::vector<PLCLine*>& lines) {
unsigned int i;
std::vector<float*> inputQualities;
targetQuality.resize(context->width);
for(i = 0; i < context->inputFiles.size(); i++ )
inputQualities.push_back(lines[i]->getQuality());
std::vector<float> pixelQualities;
pixelQualities.resize(context->width);
for(int iPixel=0; iPixel < context->width; iPixel++)
{
int activeCandidates = 0;
for(i=0; i < inputQualities.size(); i++)
{
if( inputQualities[i][iPixel] > 0.0 )
pixelQualities[activeCandidates++] = inputQualities[i][iPixel];
}
if( activeCandidates > 1 )
{
std::sort(pixelQualities.begin(),
pixelQualities.begin()+activeCandidates);
int bestCandidate =
MAX(0,MIN(activeCandidates-1,
((int) floor(activeCandidates*percentileRatio))));
targetQuality[iPixel] = pixelQualities[bestCandidate];
}
else if( activeCandidates == 1 )
targetQuality[iPixel] = pixelQualities[0];
else
targetQuality[iPixel] = -1.0;
}
return QualityMethodBase::computeStackQuality(context, lines);
}
};
static PercentileQuality percentileQualityTemplateInstance;
<|endoftext|>
|
<commit_before>/* <x0/plugins/accesslog.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpResponse.h>
#include <x0/http/HttpHeader.h>
#include <x0/strutils.h>
#include <x0/Types.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cerrno>
/**
* \ingroup plugins
* \brief implements an accesslog log facility - in spirit of "combined" mode of apache's accesslog logs.
*/
class accesslog_plugin :
public x0::HttpPlugin
{
private:
x0::HttpServer::RequestPostHook::Connection c;
struct context : public x0::ScopeValue
{
std::string filename_;
int fd_;
context() :
filename_(),
fd_(-1)
{
}
~context()
{
close();
}
std::error_code open(const std::string& filename)
{
if (fd_ >= 0)
::close(fd_);
fd_ = ::open(filename.c_str(), O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644);
if (fd_ < 0)
return std::make_error_code(static_cast<std::errc>(errno));
filename_ = filename;
return std::error_code();
}
void write(const std::string message)
{
if (fd_ < 0)
return;
int rv = ::write(fd_, message.c_str(), message.size());
if (rv < 0)
DEBUG("Couldn't write to accesslog(%s): %s", filename_.c_str(), strerror(errno));
}
void close()
{
if (fd_ >= 0)
{
::close(fd_);
fd_ = -1;
}
}
void reopen()
{
close();
open(filename_);
}
virtual void merge(const x0::ScopeValue *value)
{
if (auto cx = dynamic_cast<const context *>(value))
{
if (filename_.empty())
{
filename_ = cx->filename_;
reopen();
}
}
}
};
public:
accesslog_plugin(x0::HttpServer& srv, const std::string& name) :
x0::HttpPlugin(srv, name)
{
using namespace std::placeholders;
c = srv.onRequestDone.connect<accesslog_plugin, &accesslog_plugin::request_done>(this);
declareCVar("AccessLog", x0::HttpContext::server | x0::HttpContext::host, &accesslog_plugin::setup_log);
}
~accesslog_plugin()
{
server_.onRequestDone.disconnect(c);
}
private:
std::error_code setup_log(const x0::SettingsValue& cvar, x0::Scope& s)
{
std::string filename;
std::error_code ec = cvar.load(filename);
if (ec)
return ec;
auto cx = s.acquire<context>(this);
ec = cx->open(filename);
return std::error_code();
}
void request_done(x0::HttpRequest *in, x0::HttpResponse *out)
{
if (auto stream = server().resolveHost(in->hostid())->get<context>(this))
{
std::stringstream sstr;
sstr << hostname(in);
sstr << " - "; // identity as of identd
sstr << username(in) << ' ';
sstr << server_.now().htlog_str().c_str() << " \"";
sstr << request_line(in) << "\" ";
sstr << out->status << ' ';
sstr << out->headers["Content-Length"] << ' ';
sstr << '"' << getheader(in, "Referer") << "\" ";
sstr << '"' << getheader(in, "User-Agent") << '"';
sstr << std::endl;
stream->write(sstr.str());
}
}
inline context *getlogstream(x0::HttpRequest *in)
{
return server_.resolveHost(in->hostid())->get<context>(this);
}
inline std::string hostname(x0::HttpRequest *in)
{
std::string name = in->connection.remote_ip();
return !name.empty() ? name : "-";
}
inline std::string username(x0::HttpRequest *in)
{
return !in->username.empty() ? in->username.str() : "-";
}
inline std::string request_line(x0::HttpRequest *in)
{
std::stringstream str;
str << in->method.str() << ' ' << in->uri.str()
<< " HTTP/" << in->http_version_major << '.' << in->http_version_minor;
return str.str();
}
inline std::string getheader(const x0::HttpRequest *in, const std::string& name)
{
x0::BufferRef value(in->header(name));
return !value.empty() ? value.str() : "-";
}
};
X0_EXPORT_PLUGIN(accesslog);
<commit_msg>[plugins] accesslog: fixes status code logging<commit_after>/* <x0/plugins/accesslog.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpResponse.h>
#include <x0/http/HttpHeader.h>
#include <x0/strutils.h>
#include <x0/Types.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cerrno>
/**
* \ingroup plugins
* \brief implements an accesslog log facility - in spirit of "combined" mode of apache's accesslog logs.
*/
class accesslog_plugin :
public x0::HttpPlugin
{
private:
x0::HttpServer::RequestPostHook::Connection c;
struct context : public x0::ScopeValue
{
std::string filename_;
int fd_;
context() :
filename_(),
fd_(-1)
{
}
~context()
{
close();
}
std::error_code open(const std::string& filename)
{
if (fd_ >= 0)
::close(fd_);
fd_ = ::open(filename.c_str(), O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644);
if (fd_ < 0)
return std::make_error_code(static_cast<std::errc>(errno));
filename_ = filename;
return std::error_code();
}
void write(const std::string message)
{
if (fd_ < 0)
return;
int rv = ::write(fd_, message.c_str(), message.size());
if (rv < 0)
DEBUG("Couldn't write to accesslog(%s): %s", filename_.c_str(), strerror(errno));
}
void close()
{
if (fd_ >= 0)
{
::close(fd_);
fd_ = -1;
}
}
void reopen()
{
close();
open(filename_);
}
virtual void merge(const x0::ScopeValue *value)
{
if (auto cx = dynamic_cast<const context *>(value))
{
if (filename_.empty())
{
filename_ = cx->filename_;
reopen();
}
}
}
};
public:
accesslog_plugin(x0::HttpServer& srv, const std::string& name) :
x0::HttpPlugin(srv, name)
{
using namespace std::placeholders;
c = srv.onRequestDone.connect<accesslog_plugin, &accesslog_plugin::request_done>(this);
declareCVar("AccessLog", x0::HttpContext::server | x0::HttpContext::host, &accesslog_plugin::setup_log);
}
~accesslog_plugin()
{
server_.onRequestDone.disconnect(c);
}
private:
std::error_code setup_log(const x0::SettingsValue& cvar, x0::Scope& s)
{
std::string filename;
std::error_code ec = cvar.load(filename);
if (ec)
return ec;
auto cx = s.acquire<context>(this);
ec = cx->open(filename);
return std::error_code();
}
void request_done(x0::HttpRequest *in, x0::HttpResponse *out)
{
if (auto stream = server().resolveHost(in->hostid())->get<context>(this))
{
std::stringstream sstr;
sstr << hostname(in);
sstr << " - "; // identity as of identd
sstr << username(in) << ' ';
sstr << server_.now().htlog_str().c_str() << " \"";
sstr << request_line(in) << "\" ";
sstr << static_cast<int>(out->status) << ' ';
sstr << out->headers["Content-Length"] << ' ';
sstr << '"' << getheader(in, "Referer") << "\" ";
sstr << '"' << getheader(in, "User-Agent") << '"';
sstr << std::endl;
stream->write(sstr.str());
}
}
inline context *getlogstream(x0::HttpRequest *in)
{
return server_.resolveHost(in->hostid())->get<context>(this);
}
inline std::string hostname(x0::HttpRequest *in)
{
std::string name = in->connection.remote_ip();
return !name.empty() ? name : "-";
}
inline std::string username(x0::HttpRequest *in)
{
return !in->username.empty() ? in->username.str() : "-";
}
inline std::string request_line(x0::HttpRequest *in)
{
std::stringstream str;
str << in->method.str() << ' ' << in->uri.str()
<< " HTTP/" << in->http_version_major << '.' << in->http_version_minor;
return str.str();
}
inline std::string getheader(const x0::HttpRequest *in, const std::string& name)
{
x0::BufferRef value(in->header(name));
return !value.empty() ? value.str() : "-";
}
};
X0_EXPORT_PLUGIN(accesslog);
<|endoftext|>
|
<commit_before>#include "command.hh"
#include "common-args.hh"
#include "shared.hh"
#include "store-api.hh"
#include "eval.hh"
#include "json.hh"
#include "value-to-json.hh"
using namespace nix;
struct CmdEval : MixJSON, InstallableCommand
{
bool raw = false;
CmdEval()
{
mkFlag(0, "raw", "print strings unquoted", &raw);
}
std::string name() override
{
return "eval";
}
std::string description() override
{
return "evaluate a Nix expression";
}
Examples examples() override
{
return {
Example{
"To evaluate a Nix expression given on the command line:",
"nix eval '(1 + 2)'"
},
Example{
"To evaluate a Nix expression from a file or URI:",
"nix eval -f channel:nixos-17.09 hello.name"
},
Example{
"To get the current version of Nixpkgs:",
"nix eval --raw nixpkgs.lib.nixpkgsVersion"
},
Example{
"To print the store path of the Hello package:",
"nix eval --raw nixpkgs.hello"
},
};
}
void run(ref<Store> store) override
{
if (raw && json)
throw UsageError("--raw and --json are mutually exclusive");
auto state = getEvalState();
auto v = installable->toValue(*state);
PathSet context;
if (raw) {
std::cout << state->coerceToString(noPos, *v, context);
} else if (json) {
JSONPlaceholder jsonOut(std::cout);
printValueAsJSON(*state, true, *v, jsonOut, context);
} else {
state->forceValueDeep(*v);
std::cout << *v << "\n";
}
}
};
static RegisterCommand r1(make_ref<CmdEval>());
<commit_msg>nix eval: Stop progress bar before printing the result<commit_after>#include "command.hh"
#include "common-args.hh"
#include "shared.hh"
#include "store-api.hh"
#include "eval.hh"
#include "json.hh"
#include "value-to-json.hh"
#include "progress-bar.hh"
using namespace nix;
struct CmdEval : MixJSON, InstallableCommand
{
bool raw = false;
CmdEval()
{
mkFlag(0, "raw", "print strings unquoted", &raw);
}
std::string name() override
{
return "eval";
}
std::string description() override
{
return "evaluate a Nix expression";
}
Examples examples() override
{
return {
Example{
"To evaluate a Nix expression given on the command line:",
"nix eval '(1 + 2)'"
},
Example{
"To evaluate a Nix expression from a file or URI:",
"nix eval -f channel:nixos-17.09 hello.name"
},
Example{
"To get the current version of Nixpkgs:",
"nix eval --raw nixpkgs.lib.nixpkgsVersion"
},
Example{
"To print the store path of the Hello package:",
"nix eval --raw nixpkgs.hello"
},
};
}
void run(ref<Store> store) override
{
if (raw && json)
throw UsageError("--raw and --json are mutually exclusive");
auto state = getEvalState();
auto v = installable->toValue(*state);
PathSet context;
stopProgressBar();
if (raw) {
std::cout << state->coerceToString(noPos, *v, context);
} else if (json) {
JSONPlaceholder jsonOut(std::cout);
printValueAsJSON(*state, true, *v, jsonOut, context);
} else {
state->forceValueDeep(*v);
std::cout << *v << "\n";
}
}
};
static RegisterCommand r1(make_ref<CmdEval>());
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP
#define MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/is_finite.hpp>
#include <limits>
#include <memory>
//
// Dynamic variable is a (non-) physical parameter in a system that has
// (virtual) mass, velocity and force and updated by integrator.
//
namespace mjolnir
{
template<typename realT>
struct DynamicVariableBase
{
using real_type = realT;
real_type x, v, f;
real_type m, gamma;
real_type lower, upper;
DynamicVariableBase(real_type x_, real_type v_, real_type f_,
real_type m_, real_type gamma_,
real_type lower_, real_type upper_)
: x(x_), v(v_), f(f_), m(m_), gamma(gamma_), lower(lower_), upper(upper_)
{}
virtual ~DynamicVariableBase() = default;
virtual void update(real_type x, real_type v, real_type f) noexcept = 0;
virtual DynamicVariableBase<real_type>* clone() const = 0;
};
// It makes `DynamicVariable`s copyable and easier to handle.
template<typename realT>
struct DynamicVariable
{
using real_type = typename DynamicVariableBase<realT>::real_type;
template<typename DynVar>
explicit DynamicVariable(DynVar&& dynvar)
: resource_(make_unique<DynamicVariableBase<real_type>>(std::forward<DynVar>(dynvar)))
{
static_assert(std::is_base_of<DynamicVariableBase<realT>, DynVar>::value, "");
}
DynamicVariable(const DynamicVariable& other)
: resource_(other.resource_->clone())
{}
DynamicVariable& operator=(const DynamicVariable& other)
{
this->resource_.reset(other.resource_->clone());
return *this;
}
DynamicVariable(DynamicVariable&&) = default;
DynamicVariable& operator=(DynamicVariable&&) = default;
~DynamicVariable() = default;
real_type x() const noexcept {return resource_->x;}
real_type v() const noexcept {return resource_->v;}
real_type f() const noexcept {return resource_->f;}
real_type m() const noexcept {return resource_->m;}
real_type gamma() const noexcept {return resource_->gamma;}
void update(real_type x, real_type v, real_type f) const noexcept
{
resource_->update(x, v, f);
}
private:
std::unique_ptr<DynamicVariableBase<realT>> resource_;
};
template<typename realT>
struct DefaultDynamicVariable : public DynamicVariableBase<realT>
{
using base_type = DynamicVariableBase<realT>;
using real_type = typename base_type::real_type;
DefaultDynamicVariable(const real_type x, const real_type v, const real_type f,
const real_type m, const real_type gamma)
: base_type{x, v, f, m, gamma,
-std::numeric_limits<real_type>::infinity(),
std::numeric_limits<real_type>::infinity()}
{}
~DefaultDynamicVariable() override = default;
void update(real_type x, real_type v, real_type f) noexcept override
{
this->x = x;
this->v = v;
this->f = f;
return;
}
DynamicVariableBase<real_type>* clone() const override
{
return new DefaultDynamicVariable(*this);
}
};
template<typename realT>
struct PeriodicDynamicVariable : public DynamicVariableBase<realT>
{
using base_type = DynamicVariableBase<realT>;
using real_type = typename base_type::real_type;
PeriodicDynamicVariable(const real_type x, const real_type v, const real_type f,
const real_type m, const real_type gamma,
const real_type lower, const real_type upper)
: base_type(x, v, f, m, gamma, lower, upper)
{}
~PeriodicDynamicVariable() override = default;
void update(real_type x, real_type v, real_type f) noexcept override
{
this->x = x;
if (this->x < this->lower) {this->x += (this->upper - this->lower);}
else if (this->upper <= this->x) {this->x -= (this->upper - this->lower);}
this->v = v;
this->f = f;
return;
}
DynamicVariableBase<real_type>* clone() const override
{
return new PeriodicDynamicVariable(*this);
}
};
template<typename realT>
struct RepulsiveDynamicVariable : public DynamicVariableBase<realT>
{
using base_type = DynamicVariableBase<realT>;
using real_type = typename base_type::real_type;
RepulsiveDynamicVariable(const real_type x, const real_type v, const real_type f,
const real_type m, const real_type gamma,
const real_type lower, const real_type upper)
: base_type(x, v, f, m, gamma, lower, upper)
{}
~RepulsiveDynamicVariable() override = default;
void update(real_type x, real_type v, real_type f) noexcept override
{
if(x < this->lower)
{
this->x = 2 * this->lower - x; // lower + (lower - x)
this->v = -v;
}
else if (this->upper < x)
{
this->x = 2 * this->upper - x; // upper - (x - upper)
this->v = -v;
}
else
{
this->x = x;
this->v = v;
}
this->f = f;
return;
}
DynamicVariableBase<real_type>* clone() const override
{
return new RepulsiveDynamicVariable(*this);
}
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class DynamicVariableBase<double>;
extern template class DynamicVariableBase<float >;
extern template class DynamicVariable<double>;
extern template class DynamicVariable<float >;
extern template class DefaultDynamicVariable<double>;
extern template class DefaultDynamicVariable<float >;
extern template class PeriodicDynamicVariable<double>;
extern template class PeriodicDynamicVariable<float >;
extern template class RepulsiveDynamicVariable<double>;
extern template class RepulsiveDynamicVariable<float >;
#endif
} // mjolnir
#endif// MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP
<commit_msg>feat: add default ctor to dynvar<commit_after>#ifndef MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP
#define MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/is_finite.hpp>
#include <limits>
#include <memory>
//
// Dynamic variable is a (non-) physical parameter in a system that has
// (virtual) mass, velocity and force and updated by integrator.
//
namespace mjolnir
{
template<typename realT>
struct DynamicVariableBase
{
using real_type = realT;
real_type x, v, f;
real_type m, gamma;
real_type lower, upper;
DynamicVariableBase(real_type x_, real_type v_, real_type f_,
real_type m_, real_type gamma_,
real_type lower_, real_type upper_)
: x(x_), v(v_), f(f_), m(m_), gamma(gamma_), lower(lower_), upper(upper_)
{}
virtual ~DynamicVariableBase() = default;
virtual void update(real_type x, real_type v, real_type f) noexcept = 0;
virtual DynamicVariableBase<real_type>* clone() const = 0;
};
// It makes `DynamicVariable`s copyable and easier to handle.
template<typename realT>
struct DynamicVariable
{
using real_type = typename DynamicVariableBase<realT>::real_type;
template<typename DynVar>
explicit DynamicVariable(DynVar&& dynvar)
: resource_(make_unique<DynamicVariableBase<real_type>>(std::forward<DynVar>(dynvar)))
{
static_assert(std::is_base_of<DynamicVariableBase<realT>, DynVar>::value, "");
}
DynamicVariable(): resource_(nullptr) {}
DynamicVariable(const DynamicVariable& other)
: resource_(other.resource_->clone())
{}
DynamicVariable& operator=(const DynamicVariable& other)
{
this->resource_.reset(other.resource_->clone());
return *this;
}
DynamicVariable(DynamicVariable&&) = default;
DynamicVariable& operator=(DynamicVariable&&) = default;
~DynamicVariable() = default;
real_type x() const noexcept {return resource_->x;}
real_type v() const noexcept {return resource_->v;}
real_type f() const noexcept {return resource_->f;}
real_type m() const noexcept {return resource_->m;}
real_type gamma() const noexcept {return resource_->gamma;}
void update(real_type x, real_type v, real_type f) const noexcept
{
resource_->update(x, v, f);
}
private:
std::unique_ptr<DynamicVariableBase<realT>> resource_;
};
template<typename realT>
struct DefaultDynamicVariable : public DynamicVariableBase<realT>
{
using base_type = DynamicVariableBase<realT>;
using real_type = typename base_type::real_type;
DefaultDynamicVariable(const real_type x, const real_type v, const real_type f,
const real_type m, const real_type gamma)
: base_type{x, v, f, m, gamma,
-std::numeric_limits<real_type>::infinity(),
std::numeric_limits<real_type>::infinity()}
{}
~DefaultDynamicVariable() override = default;
void update(real_type x, real_type v, real_type f) noexcept override
{
this->x = x;
this->v = v;
this->f = f;
return;
}
DynamicVariableBase<real_type>* clone() const override
{
return new DefaultDynamicVariable(*this);
}
};
template<typename realT>
struct PeriodicDynamicVariable : public DynamicVariableBase<realT>
{
using base_type = DynamicVariableBase<realT>;
using real_type = typename base_type::real_type;
PeriodicDynamicVariable(const real_type x, const real_type v, const real_type f,
const real_type m, const real_type gamma,
const real_type lower, const real_type upper)
: base_type(x, v, f, m, gamma, lower, upper)
{}
~PeriodicDynamicVariable() override = default;
void update(real_type x, real_type v, real_type f) noexcept override
{
this->x = x;
if (this->x < this->lower) {this->x += (this->upper - this->lower);}
else if (this->upper <= this->x) {this->x -= (this->upper - this->lower);}
this->v = v;
this->f = f;
return;
}
DynamicVariableBase<real_type>* clone() const override
{
return new PeriodicDynamicVariable(*this);
}
};
template<typename realT>
struct RepulsiveDynamicVariable : public DynamicVariableBase<realT>
{
using base_type = DynamicVariableBase<realT>;
using real_type = typename base_type::real_type;
RepulsiveDynamicVariable(const real_type x, const real_type v, const real_type f,
const real_type m, const real_type gamma,
const real_type lower, const real_type upper)
: base_type(x, v, f, m, gamma, lower, upper)
{}
~RepulsiveDynamicVariable() override = default;
void update(real_type x, real_type v, real_type f) noexcept override
{
if(x < this->lower)
{
this->x = 2 * this->lower - x; // lower + (lower - x)
this->v = -v;
}
else if (this->upper < x)
{
this->x = 2 * this->upper - x; // upper - (x - upper)
this->v = -v;
}
else
{
this->x = x;
this->v = v;
}
this->f = f;
return;
}
DynamicVariableBase<real_type>* clone() const override
{
return new RepulsiveDynamicVariable(*this);
}
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class DynamicVariableBase<double>;
extern template class DynamicVariableBase<float >;
extern template class DynamicVariable<double>;
extern template class DynamicVariable<float >;
extern template class DefaultDynamicVariable<double>;
extern template class DefaultDynamicVariable<float >;
extern template class PeriodicDynamicVariable<double>;
extern template class PeriodicDynamicVariable<float >;
extern template class RepulsiveDynamicVariable<double>;
extern template class RepulsiveDynamicVariable<float >;
#endif
} // mjolnir
#endif// MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "os.h"
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <cxxabi.h>
#include <dirent.h>
#include <execinfo.h>
#include <fnmatch.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1 // for dladdr()
#endif
#include <dlfcn.h>
const char os::kDirSepChar = '/';
std::string os::GetModulePath(void *address, std::size_t maxLength) {
std::vector<char> name(maxLength + 1);
if (address != 0) {
Dl_info info;
dladdr(address, &info);
strncpy(name.data(), info.dli_fname, maxLength);
}
return std::string(name.data());
}
// The crash handler - it is set via SetCrashHandler()
static void (*crashHandler)() = 0;
// Previous SIGSEGV handler
static void (*previousSIGSEGVHandler)(int);
static void HandleSIGSEGV(int sig)
{
if (::crashHandler != 0) {
::crashHandler();
}
signal(sig, SIG_DFL);
}
void os::SetCrashHandler(void (*handler)()) {
::crashHandler = handler;
if (handler != 0) {
::previousSIGSEGVHandler = signal(SIGSEGV, HandleSIGSEGV);
} else {
signal(SIGSEGV, ::previousSIGSEGVHandler);
}
}
// The interrupt (Ctrl+C) handler - set via SetInterruptHandler
static void (*interruptHandler)();
// Previous SIGINT handler
static void (*previousSIGINTHandler)(int);
// Out SIGINT handler
static void HandleSIGINT(int sig) {
if (::interruptHandler != 0) {
::interruptHandler();
}
signal(sig, ::previousSIGINTHandler);
raise(sig);
}
void os::SetInterruptHandler(void (*handler)()) {
::interruptHandler = handler;
::previousSIGINTHandler = signal(SIGINT, HandleSIGINT);
}
std::string os::GetSymbolName(void *address, std::size_t maxLength) {
char **symbols = backtrace_symbols(&address, 1);
std::string symbol(symbols[0]);
std::free(symbols);
std::string::size_type lp = symbol.find('(');
std::string::size_type rp = symbol.find_first_of(")+-");
std::string name;
if (lp != std::string::npos && rp != std::string::npos) {
name.assign(symbol.begin() + lp + 1, symbol.begin() + rp);
}
if (!name.empty()) {
char *demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, 0);
if (demangled_name != 0) {
name.assign(demangled_name);
}
}
return name;
}
void os::ListDirectoryFiles(const std::string &directory, const std::string &pattern,
bool (*callback)(const char *, void *), void *userData)
{
DIR *dp;
if ((dp = opendir(directory.c_str())) != 0) {
struct dirent *dirp;
while ((dirp = readdir(dp)) != 0) {
if (!fnmatch(pattern.c_str(), dirp->d_name, FNM_CASEFOLD | FNM_NOESCAPE | FNM_PERIOD)) {
callback(dirp->d_name, userData);
}
}
closedir(dp);
}
}
<commit_msg>os-unix: Make GetSymbolName() strip type information from C++ names<commit_after>// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "os.h"
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <cxxabi.h>
#include <dirent.h>
#include <execinfo.h>
#include <fnmatch.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1 // for dladdr()
#endif
#include <dlfcn.h>
const char os::kDirSepChar = '/';
std::string os::GetModulePath(void *address, std::size_t maxLength) {
std::vector<char> name(maxLength + 1);
if (address != 0) {
Dl_info info;
dladdr(address, &info);
strncpy(name.data(), info.dli_fname, maxLength);
}
return std::string(name.data());
}
// The crash handler - it is set via SetCrashHandler()
static void (*crashHandler)() = 0;
// Previous SIGSEGV handler
static void (*previousSIGSEGVHandler)(int);
static void HandleSIGSEGV(int sig)
{
if (::crashHandler != 0) {
::crashHandler();
}
signal(sig, SIG_DFL);
}
void os::SetCrashHandler(void (*handler)()) {
::crashHandler = handler;
if (handler != 0) {
::previousSIGSEGVHandler = signal(SIGSEGV, HandleSIGSEGV);
} else {
signal(SIGSEGV, ::previousSIGSEGVHandler);
}
}
// The interrupt (Ctrl+C) handler - set via SetInterruptHandler
static void (*interruptHandler)();
// Previous SIGINT handler
static void (*previousSIGINTHandler)(int);
// Out SIGINT handler
static void HandleSIGINT(int sig) {
if (::interruptHandler != 0) {
::interruptHandler();
}
signal(sig, ::previousSIGINTHandler);
raise(sig);
}
void os::SetInterruptHandler(void (*handler)()) {
::interruptHandler = handler;
::previousSIGINTHandler = signal(SIGINT, HandleSIGINT);
}
std::string os::GetSymbolName(void *address, std::size_t maxLength) {
char **symbols = backtrace_symbols(&address, 1);
std::string symbol(symbols[0]);
std::free(symbols);
std::string::size_type lp = symbol.find('(');
std::string::size_type rp = symbol.find_first_of(")+-");
std::string name;
if (lp != std::string::npos && rp != std::string::npos) {
name.assign(symbol.begin() + lp + 1, symbol.begin() + rp);
}
if (!name.empty()) {
char *demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, 0);
if (demangled_name != 0) {
name.assign(demangled_name);
// Cut argment type information e.g. (int*, char*, void*).
std::string::size_type end = name.find('(');
if (end != std::string::npos) {
name.erase(end);
}
}
}
return name;
}
void os::ListDirectoryFiles(const std::string &directory, const std::string &pattern,
bool (*callback)(const char *, void *), void *userData)
{
DIR *dp;
if ((dp = opendir(directory.c_str())) != 0) {
struct dirent *dirp;
while ((dirp = readdir(dp)) != 0) {
if (!fnmatch(pattern.c_str(), dirp->d_name, FNM_CASEFOLD | FNM_NOESCAPE | FNM_PERIOD)) {
callback(dirp->d_name, userData);
}
}
closedir(dp);
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
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.
*/
#include "TelegramServerConfig.hpp"
#include "TelegramServerUser.hpp"
#include "DcConfiguration.hpp"
#include "LocalCluster.hpp"
#include "Session.hpp"
#include "Utils.hpp"
#include <QCoreApplication>
#include <QDebug>
#include <QStandardPaths>
using namespace Telegram::Server;
#ifdef USE_DBUS_NOTIFIER
#include <QDBusConnection>
#include <QDBusMessage>
#include "DefaultAuthorizationProvider.hpp"
class DBusCodeAuthProvider : public Authorization::DefaultProvider
{
protected:
Authorization::Code generateCode(Session *session, const QString &identifier) override;
};
Authorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier)
{
Authorization::Code code = DefaultProvider::generateCode(session, identifier);
QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("Notify"));
message.setArguments({
QCoreApplication::applicationName(),
QVariant::fromValue(0u),
QString(),
QStringLiteral("New auth code request"),
QStringLiteral("Auth code for account %1 is %2. Peer IP: %3").arg(identifier, code.code, session->ip),
QStringList(),
QVariantMap(),
3000
});
// QString app_name, uint replaces_id, QString app_icon, QString summary,
// QString body, QStringList actions, QVariantMap hints, int timeout
QDBusConnection::sessionBus().send(message);
return code;
}
#endif // USE_DBUS_NOTIFIER
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
a.setOrganizationName(QStringLiteral("TelegramQt"));
a.setApplicationName(QStringLiteral("TelegramQt Server"));
Telegram::initialize();
Config config;
if (!config.load()) {
// create "default" config file to ease editing
config.save();
}
const Telegram::RsaKey key = Telegram::RsaKey::fromFile(config.privateKeyFile());
if (!key.isValid()) {
qCritical() << "Unable to read RSA key. Please read README.md for more information.";
return -1;
}
LocalCluster cluster;
cluster.setServerPrivateRsaKey(key);
cluster.setServerConfiguration(config.serverConfiguration());
#ifdef USE_DBUS_NOTIFIER
DBusCodeAuthProvider authProvider;
cluster.setAuthorizationProvider(&authProvider);
qInfo() << "DBus auth code provider enabled";
#endif
cluster.start();
return a.exec();
}
<commit_msg>Server: add command line option to specify config location<commit_after>/*
Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
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.
*/
#include "TelegramServerConfig.hpp"
#include "TelegramServerUser.hpp"
#include "DcConfiguration.hpp"
#include "LocalCluster.hpp"
#include "Session.hpp"
#include "Utils.hpp"
#include <QCoreApplication>
#include <QDebug>
#include <QStandardPaths>
#include <QCommandLineParser>
using namespace Telegram::Server;
#ifdef USE_DBUS_NOTIFIER
#include <QDBusConnection>
#include <QDBusMessage>
#include "DefaultAuthorizationProvider.hpp"
class DBusCodeAuthProvider : public Authorization::DefaultProvider
{
protected:
Authorization::Code generateCode(Session *session, const QString &identifier) override;
};
Authorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier)
{
Authorization::Code code = DefaultProvider::generateCode(session, identifier);
QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("/org/freedesktop/Notifications"),
QStringLiteral("org.freedesktop.Notifications"),
QStringLiteral("Notify"));
message.setArguments({
QCoreApplication::applicationName(),
QVariant::fromValue(0u),
QString(),
QStringLiteral("New auth code request"),
QStringLiteral("Auth code for account %1 is %2. Peer IP: %3").arg(identifier, code.code, session->ip),
QStringList(),
QVariantMap(),
3000
});
// QString app_name, uint replaces_id, QString app_icon, QString summary,
// QString body, QStringList actions, QVariantMap hints, int timeout
QDBusConnection::sessionBus().send(message);
return code;
}
#endif // USE_DBUS_NOTIFIER
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
a.setOrganizationName(QStringLiteral("TelegramQt"));
a.setApplicationName(QStringLiteral("TelegramQt Server"));
Telegram::initialize();
QCommandLineParser parser;
parser.addHelpOption();
QCommandLineOption configFileOption(QStringList{ QStringLiteral("c"), QStringLiteral("config") });
configFileOption.setDescription(QStringLiteral("Path to config file"));
configFileOption.setValueName(QStringLiteral("configFilePath"));
parser.addOption(configFileOption);
parser.process(a);
// where to load config file from?
QString configFilePath;
if (parser.isSet(configFileOption)) {
configFilePath = parser.value(configFileOption);
}
// Load config
Config config(configFilePath);
if (!config.load()) {
// create "default" config file to ease editing
config.save();
}
const Telegram::RsaKey key = Telegram::RsaKey::fromFile(config.privateKeyFile());
if (!key.isValid()) {
qCritical() << "Unable to read RSA key. Please read README.md for more information.";
return -1;
}
LocalCluster cluster;
cluster.setServerPrivateRsaKey(key);
cluster.setServerConfiguration(config.serverConfiguration());
#ifdef USE_DBUS_NOTIFIER
DBusCodeAuthProvider authProvider;
cluster.setAuthorizationProvider(&authProvider);
qInfo() << "DBus auth code provider enabled";
#endif
cluster.start();
return a.exec();
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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 <config_folders.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "liblibreoffice.h"
#include <tools/errinf.hxx>
#include <osl/file.hxx>
#include <osl/process.h>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/ucb/XContentProvider.hpp>
#include <com/sun/star/ucb/XUniversalContentBroker.hpp>
#include <vcl/svapp.hxx>
#include <tools/resmgr.hxx>
#include <vcl/graphicfilter.hxx>
#include <unotools/syslocaleoptions.hxx>
using namespace ::com::sun::star;
class LibLODocument_Impl;
class LibLibreOffice_Impl;
static LibLibreOffice_Impl *gImpl = NULL;
typedef struct {
const char *extn;
const char *filterName;
} ExtensionMap;
static const ExtensionMap
aWriterExtensionMap[] = {
{ "doc", "MS Word 97" },
{ "docx", "MS Word 2007 XML" },
{ "fodt", "OpenDocument Text Flat XML" },
{ "html", "HTML (StarWriter)" },
{ "odt", "writer8" },
{ "ott", "writer8_template" },
{ "pdf", "writer_pdf_Export" },
{ "txt", "Text" },
{ "xhtml", "XHTML Writer File" },
{ NULL, NULL }
};
static const ExtensionMap
aCalcExtensionMap[] = {
{ "csv", "Text - txt - csv (StarCalc)" },
{ "fods", "OpenDocument Spreadsheet Flat XML" },
{ "html", "HTML (StarCalc)" },
{ "ods", "calc8" },
{ "ots", "calc8_template" },
{ "pdf", "calc_pdf_Export" },
{ "xhtml", "XHTML Calc File" },
{ "xls", "MS Excel 97" },
{ "xlsx", "Calc MS Excel 2007 XML" },
{ NULL, NULL }
};
static const ExtensionMap
aImpressExtensionMap[] = {
{ "fodp", "OpenDocument Presentation Flat XML" },
{ "html", "impress_html_Export" },
{ "odg", "impress8_draw" },
{ "odp", "impress8" },
{ "otp", "impress8_template" },
{ "pdf", "impress_pdf_Export" },
{ "potm", "Impress MS PowerPoint 2007 XML Template" },
{ "pot", "MS PowerPoint 97 Vorlage" },
{ "pptx", "Impress MS PowerPoint 2007 XML" },
{ "pps", "MS PowerPoint 97 Autoplay" },
{ "ppt", "MS PowerPoint 97" },
{ "svg", "impress_svg_Export" },
{ "swf", "impress_flash_Export" },
{ "xhtml", "XHTML Impress File" },
{ NULL, NULL }
};
extern "C" {
SAL_DLLPUBLIC_EXPORT LibreOffice *liblibreoffice_hook(void);
static void doc_destroy( LibreOfficeDocument *pThis );
static int doc_saveAs( LibreOfficeDocument *pThis, const char *pUrl, const char *pFormat );
struct LibLODocument_Impl : public _LibreOfficeDocument
{
uno::Reference < css::lang::XComponent > mxComponent;
LibLODocument_Impl( const uno::Reference < css::lang::XComponent > &xComponent )
: mxComponent( xComponent )
{
nSize = sizeof( LibreOffice );
destroy = doc_destroy;
saveAs = doc_saveAs;
}
};
static void doc_destroy( LibreOfficeDocument *pThis )
{
LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );
delete pDocument;
}
static void lo_destroy (LibreOffice *pThis);
static int lo_initialize (LibreOffice *pThis,
const char *pInstallPath);
static LibreOfficeDocument *lo_documentLoad (LibreOffice *pThis,
const char *pURL);
static char * lo_getError (LibreOffice *pThis);
struct LibLibreOffice_Impl : public _LibreOffice
{
rtl::OUString maLastExceptionMsg;
LibLibreOffice_Impl()
{
nSize = sizeof( LibreOfficeDocument );
destroy = lo_destroy;
initialize = lo_initialize;
documentLoad = lo_documentLoad;
getError = lo_getError;
}
};
// Wonder global state ...
static uno::Reference<css::uno::XComponentContext> xContext;
static uno::Reference<css::lang::XMultiServiceFactory> xSFactory;
static uno::Reference<css::lang::XMultiComponentFactory> xFactory;
static OUString getUString( const char *str )
{
if( !str )
return OUString( "" );
return OStringToOUString( OString( str, strlen (str) ),
RTL_TEXTENCODING_UTF8 );
}
// Try to convert a relative URL to an absolute one
static OUString getAbsoluteURL( const char *pURL )
{
OUString aURL( getUString( pURL ) );
OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl;
// FIXME: this would appear to kill non-file URLs.
osl_getProcessWorkingDir(&sWorkingDir.pData);
osl::FileBase::getFileURLFromSystemPath( aURL, sDocPathUrl );
osl::FileBase::getAbsoluteFileURL(sWorkingDir, sDocPathUrl, sAbsoluteDocUrl);
return sAbsoluteDocUrl;
}
static LibreOfficeDocument *
lo_documentLoad( LibreOffice *pThis, const char *pURL )
{
LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
OUString aURL = getAbsoluteURL( pURL );
uno::Reference < css::frame::XDesktop2 > xComponentLoader =
css::frame::Desktop::create(xContext);
pLib->maLastExceptionMsg = "";
try {
uno::Reference < css::lang::XComponent > xComponent =
xComponentLoader->loadComponentFromURL(
aURL, OUString("_blank"), 0,
uno::Sequence < css::beans::PropertyValue >());
if( xComponentLoader.is() )
return new LibLODocument_Impl( xComponent );
else
pLib->maLastExceptionMsg = "unknown load failure";
} catch (const uno::Exception &ex) {
pLib->maLastExceptionMsg = ex.Message;
}
return NULL;
}
static int
doc_saveAs( LibreOfficeDocument *pThis,
const char *url, const char *format )
{
LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );
OUString sFormat = getUString( format );
OUString aURL = getAbsoluteURL( url );
try {
uno::Reference< frame::XModel > xDocument( pDocument->mxComponent,
uno::UNO_QUERY_THROW );
uno::Sequence< beans::PropertyValue > aSeq = xDocument->getArgs();
OUString aDocumentService;
for( sal_Int32 i = 0; i < aSeq.getLength(); ++i )
{
if( aSeq[i].Name == "DocumentService" )
aSeq[i].Value >>= aDocumentService;
OUString aValue;
aSeq[i].Value >>= aValue;
}
if( aDocumentService == "")
{
gImpl->maLastExceptionMsg = "Unknown document type";
return false;
}
const ExtensionMap *pMap;
if( aDocumentService == "com.sun.star.sheet.SpreadsheetDocument" )
pMap = (const ExtensionMap *)aCalcExtensionMap;
else if( aDocumentService == "com.sun.star.presentation.PresentationDocument" )
pMap = (const ExtensionMap *)aImpressExtensionMap;
else // for the sake of argument only writer documents ...
pMap = (const ExtensionMap *)aWriterExtensionMap;
if( ! format )
{
// sniff from the extension
sal_Int32 idx = aURL.lastIndexOf( "." );
if( idx > 0 )
{
sFormat = aURL.copy( idx + 1 );
}
else
{
gImpl->maLastExceptionMsg = "input filename without a suffix";
return false;
}
}
OUString aFilterName;
for( sal_Int32 i = 0; pMap[i].extn; i++ )
{
if( sFormat.equalsIgnoreAsciiCaseAscii( pMap[i].extn ) )
{
aFilterName = getUString( pMap[i].filterName );
break;
}
}
if( ! aFilterName.getLength() )
{
gImpl->maLastExceptionMsg = "no output filter found for provided suffix";
return false;
}
aSeq.realloc(2);
aSeq[0].Name = "Overwrite";
aSeq[0].Value <<= sal_True;
aSeq[1].Name = "FilterName";
aSeq[1].Value <<= aFilterName;
uno::Reference< frame::XStorable > xStorable( pDocument->mxComponent,
uno::UNO_QUERY_THROW );
xStorable->storeToURL( aURL, aSeq );
return true;
} catch (const uno::Exception &ex) {
gImpl->maLastExceptionMsg = "exception " + ex.Message;
return false;
}
}
static char *
lo_getError (LibreOffice *pThis)
{
LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
OString aStr = rtl::OUStringToOString( pLib->maLastExceptionMsg, RTL_TEXTENCODING_UTF8 );
char *pMem = (char *) malloc (aStr.getLength() + 1);
strcpy( pMem, aStr.getStr() );
return pMem;
}
static void
force_c_locale( void )
{
// force locale (and resource files loaded) to en-US
OUString aLangISO( "en-US" );
LanguageTag aLocale( aLangISO );
ResMgr::SetDefaultLocale( aLocale );
SvtSysLocaleOptions aLocalOptions;
aLocalOptions.SetLocaleConfigString( aLangISO );
aLocalOptions.SetUILocaleConfigString( aLangISO );
}
static void
aBasicErrorFunc( const OUString &rErr, const OUString &rAction )
{
OStringBuffer aErr( "Unexpected dialog: " );
aErr.append( OUStringToOString( rAction, RTL_TEXTENCODING_ASCII_US ) );
aErr.append( " Error: " );
aErr.append( OUStringToOString( rErr, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "Unexpected basic error dialog '%s'\n", aErr.getStr() );
}
static void
initialize_uno( const OUString &aAppURL )
{
rtl::Bootstrap::setIniFilename( aAppURL + "/fundamentalrc" );
rtl::Bootstrap::set( "CONFIGURATION_LAYERS",
"xcsxcu:${BRAND_BASE_DIR}/" LIBO_SHARE_FOLDER "/registry "
"res:${BRAND_BASE_DIR}/" LIBO_SHARE_FOLDER "/registry "
// "bundledext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:BUNDLED_EXTENSIONS_USER}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini " );
// "sharedext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:SHARED_EXTENSIONS_USER}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini "
// "userext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:UNO_USER_PACKAGES_CACHE}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini "
// "user:${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/bootstraprc:UserInstallation}/user/registrymodifications.xcu"
);
xContext = cppu::defaultBootstrap_InitialComponentContext();
fprintf( stderr, "Uno initialized %d\n", xContext.is() );
xFactory = xContext->getServiceManager();
xSFactory = uno::Reference<lang::XMultiServiceFactory>(xFactory, uno::UNO_QUERY_THROW);
comphelper::setProcessServiceFactory(xSFactory);
// set UserInstallation to user profile dir in test/user-template
// rtl::Bootstrap aDefaultVars;
// aDefaultVars.set(OUString("UserInstallation"), aAppURL + "../registry" );
// configmgr setup ?
}
static int
lo_initialize( LibreOffice *pThis, const char *app_path )
{
(void) pThis;
static bool bInitialized = false;
if( bInitialized )
return 1;
if( !app_path )
return 0;
OUString aAppPath( app_path, strlen( app_path ), RTL_TEXTENCODING_UTF8 );
OUString aAppURL;
if( osl::FileBase::getFileURLFromSystemPath( aAppPath, aAppURL ) !=
osl::FileBase::E_None )
return 0;
try {
initialize_uno( aAppURL );
force_c_locale();
// Force headless
rtl::Bootstrap::set( "SAL_USE_VCLPLUGIN", "svp" );
InitVCL();
Application::EnableHeadlessMode(true);
ErrorHandler::RegisterDisplay( aBasicErrorFunc );
fprintf( stderr, "initialized\n" );
bInitialized = true;
} catch (css::uno::Exception & e) {
fprintf( stderr, "bootstrapping exception '%s'\n",
OUStringToOString( e.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
}
return bInitialized;
}
LibreOffice *liblibreoffice_hook(void)
{
if( !gImpl )
{
fprintf( stderr, "create libreoffice object\n" );
gImpl = new LibLibreOffice_Impl();
}
return static_cast< LibreOffice *>( gImpl );
}
static void lo_destroy (LibreOffice *pThis)
{
LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
delete pLib;
gImpl = NULL;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>-Werror,-Wmismatched-tags<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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 <config_folders.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "liblibreoffice.h"
#include <tools/errinf.hxx>
#include <osl/file.hxx>
#include <osl/process.h>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/ucb/XContentProvider.hpp>
#include <com/sun/star/ucb/XUniversalContentBroker.hpp>
#include <vcl/svapp.hxx>
#include <tools/resmgr.hxx>
#include <vcl/graphicfilter.hxx>
#include <unotools/syslocaleoptions.hxx>
using namespace ::com::sun::star;
struct LibLODocument_Impl;
struct LibLibreOffice_Impl;
static LibLibreOffice_Impl *gImpl = NULL;
typedef struct {
const char *extn;
const char *filterName;
} ExtensionMap;
static const ExtensionMap
aWriterExtensionMap[] = {
{ "doc", "MS Word 97" },
{ "docx", "MS Word 2007 XML" },
{ "fodt", "OpenDocument Text Flat XML" },
{ "html", "HTML (StarWriter)" },
{ "odt", "writer8" },
{ "ott", "writer8_template" },
{ "pdf", "writer_pdf_Export" },
{ "txt", "Text" },
{ "xhtml", "XHTML Writer File" },
{ NULL, NULL }
};
static const ExtensionMap
aCalcExtensionMap[] = {
{ "csv", "Text - txt - csv (StarCalc)" },
{ "fods", "OpenDocument Spreadsheet Flat XML" },
{ "html", "HTML (StarCalc)" },
{ "ods", "calc8" },
{ "ots", "calc8_template" },
{ "pdf", "calc_pdf_Export" },
{ "xhtml", "XHTML Calc File" },
{ "xls", "MS Excel 97" },
{ "xlsx", "Calc MS Excel 2007 XML" },
{ NULL, NULL }
};
static const ExtensionMap
aImpressExtensionMap[] = {
{ "fodp", "OpenDocument Presentation Flat XML" },
{ "html", "impress_html_Export" },
{ "odg", "impress8_draw" },
{ "odp", "impress8" },
{ "otp", "impress8_template" },
{ "pdf", "impress_pdf_Export" },
{ "potm", "Impress MS PowerPoint 2007 XML Template" },
{ "pot", "MS PowerPoint 97 Vorlage" },
{ "pptx", "Impress MS PowerPoint 2007 XML" },
{ "pps", "MS PowerPoint 97 Autoplay" },
{ "ppt", "MS PowerPoint 97" },
{ "svg", "impress_svg_Export" },
{ "swf", "impress_flash_Export" },
{ "xhtml", "XHTML Impress File" },
{ NULL, NULL }
};
extern "C" {
SAL_DLLPUBLIC_EXPORT LibreOffice *liblibreoffice_hook(void);
static void doc_destroy( LibreOfficeDocument *pThis );
static int doc_saveAs( LibreOfficeDocument *pThis, const char *pUrl, const char *pFormat );
struct LibLODocument_Impl : public _LibreOfficeDocument
{
uno::Reference < css::lang::XComponent > mxComponent;
LibLODocument_Impl( const uno::Reference < css::lang::XComponent > &xComponent )
: mxComponent( xComponent )
{
nSize = sizeof( LibreOffice );
destroy = doc_destroy;
saveAs = doc_saveAs;
}
};
static void doc_destroy( LibreOfficeDocument *pThis )
{
LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );
delete pDocument;
}
static void lo_destroy (LibreOffice *pThis);
static int lo_initialize (LibreOffice *pThis,
const char *pInstallPath);
static LibreOfficeDocument *lo_documentLoad (LibreOffice *pThis,
const char *pURL);
static char * lo_getError (LibreOffice *pThis);
struct LibLibreOffice_Impl : public _LibreOffice
{
rtl::OUString maLastExceptionMsg;
LibLibreOffice_Impl()
{
nSize = sizeof( LibreOfficeDocument );
destroy = lo_destroy;
initialize = lo_initialize;
documentLoad = lo_documentLoad;
getError = lo_getError;
}
};
// Wonder global state ...
static uno::Reference<css::uno::XComponentContext> xContext;
static uno::Reference<css::lang::XMultiServiceFactory> xSFactory;
static uno::Reference<css::lang::XMultiComponentFactory> xFactory;
static OUString getUString( const char *str )
{
if( !str )
return OUString( "" );
return OStringToOUString( OString( str, strlen (str) ),
RTL_TEXTENCODING_UTF8 );
}
// Try to convert a relative URL to an absolute one
static OUString getAbsoluteURL( const char *pURL )
{
OUString aURL( getUString( pURL ) );
OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl;
// FIXME: this would appear to kill non-file URLs.
osl_getProcessWorkingDir(&sWorkingDir.pData);
osl::FileBase::getFileURLFromSystemPath( aURL, sDocPathUrl );
osl::FileBase::getAbsoluteFileURL(sWorkingDir, sDocPathUrl, sAbsoluteDocUrl);
return sAbsoluteDocUrl;
}
static LibreOfficeDocument *
lo_documentLoad( LibreOffice *pThis, const char *pURL )
{
LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
OUString aURL = getAbsoluteURL( pURL );
uno::Reference < css::frame::XDesktop2 > xComponentLoader =
css::frame::Desktop::create(xContext);
pLib->maLastExceptionMsg = "";
try {
uno::Reference < css::lang::XComponent > xComponent =
xComponentLoader->loadComponentFromURL(
aURL, OUString("_blank"), 0,
uno::Sequence < css::beans::PropertyValue >());
if( xComponentLoader.is() )
return new LibLODocument_Impl( xComponent );
else
pLib->maLastExceptionMsg = "unknown load failure";
} catch (const uno::Exception &ex) {
pLib->maLastExceptionMsg = ex.Message;
}
return NULL;
}
static int
doc_saveAs( LibreOfficeDocument *pThis,
const char *url, const char *format )
{
LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );
OUString sFormat = getUString( format );
OUString aURL = getAbsoluteURL( url );
try {
uno::Reference< frame::XModel > xDocument( pDocument->mxComponent,
uno::UNO_QUERY_THROW );
uno::Sequence< beans::PropertyValue > aSeq = xDocument->getArgs();
OUString aDocumentService;
for( sal_Int32 i = 0; i < aSeq.getLength(); ++i )
{
if( aSeq[i].Name == "DocumentService" )
aSeq[i].Value >>= aDocumentService;
OUString aValue;
aSeq[i].Value >>= aValue;
}
if( aDocumentService == "")
{
gImpl->maLastExceptionMsg = "Unknown document type";
return false;
}
const ExtensionMap *pMap;
if( aDocumentService == "com.sun.star.sheet.SpreadsheetDocument" )
pMap = (const ExtensionMap *)aCalcExtensionMap;
else if( aDocumentService == "com.sun.star.presentation.PresentationDocument" )
pMap = (const ExtensionMap *)aImpressExtensionMap;
else // for the sake of argument only writer documents ...
pMap = (const ExtensionMap *)aWriterExtensionMap;
if( ! format )
{
// sniff from the extension
sal_Int32 idx = aURL.lastIndexOf( "." );
if( idx > 0 )
{
sFormat = aURL.copy( idx + 1 );
}
else
{
gImpl->maLastExceptionMsg = "input filename without a suffix";
return false;
}
}
OUString aFilterName;
for( sal_Int32 i = 0; pMap[i].extn; i++ )
{
if( sFormat.equalsIgnoreAsciiCaseAscii( pMap[i].extn ) )
{
aFilterName = getUString( pMap[i].filterName );
break;
}
}
if( ! aFilterName.getLength() )
{
gImpl->maLastExceptionMsg = "no output filter found for provided suffix";
return false;
}
aSeq.realloc(2);
aSeq[0].Name = "Overwrite";
aSeq[0].Value <<= sal_True;
aSeq[1].Name = "FilterName";
aSeq[1].Value <<= aFilterName;
uno::Reference< frame::XStorable > xStorable( pDocument->mxComponent,
uno::UNO_QUERY_THROW );
xStorable->storeToURL( aURL, aSeq );
return true;
} catch (const uno::Exception &ex) {
gImpl->maLastExceptionMsg = "exception " + ex.Message;
return false;
}
}
static char *
lo_getError (LibreOffice *pThis)
{
LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
OString aStr = rtl::OUStringToOString( pLib->maLastExceptionMsg, RTL_TEXTENCODING_UTF8 );
char *pMem = (char *) malloc (aStr.getLength() + 1);
strcpy( pMem, aStr.getStr() );
return pMem;
}
static void
force_c_locale( void )
{
// force locale (and resource files loaded) to en-US
OUString aLangISO( "en-US" );
LanguageTag aLocale( aLangISO );
ResMgr::SetDefaultLocale( aLocale );
SvtSysLocaleOptions aLocalOptions;
aLocalOptions.SetLocaleConfigString( aLangISO );
aLocalOptions.SetUILocaleConfigString( aLangISO );
}
static void
aBasicErrorFunc( const OUString &rErr, const OUString &rAction )
{
OStringBuffer aErr( "Unexpected dialog: " );
aErr.append( OUStringToOString( rAction, RTL_TEXTENCODING_ASCII_US ) );
aErr.append( " Error: " );
aErr.append( OUStringToOString( rErr, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "Unexpected basic error dialog '%s'\n", aErr.getStr() );
}
static void
initialize_uno( const OUString &aAppURL )
{
rtl::Bootstrap::setIniFilename( aAppURL + "/fundamentalrc" );
rtl::Bootstrap::set( "CONFIGURATION_LAYERS",
"xcsxcu:${BRAND_BASE_DIR}/" LIBO_SHARE_FOLDER "/registry "
"res:${BRAND_BASE_DIR}/" LIBO_SHARE_FOLDER "/registry "
// "bundledext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:BUNDLED_EXTENSIONS_USER}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini " );
// "sharedext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:SHARED_EXTENSIONS_USER}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini "
// "userext:${${BRAND_BASE_DIR}/" LIBO_ETC_FOLDER "/unorc:UNO_USER_PACKAGES_CACHE}/registry/com.sun.star.comp.deployment.configuration.PackageRegistryBackend/configmgr.ini "
// "user:${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/bootstraprc:UserInstallation}/user/registrymodifications.xcu"
);
xContext = cppu::defaultBootstrap_InitialComponentContext();
fprintf( stderr, "Uno initialized %d\n", xContext.is() );
xFactory = xContext->getServiceManager();
xSFactory = uno::Reference<lang::XMultiServiceFactory>(xFactory, uno::UNO_QUERY_THROW);
comphelper::setProcessServiceFactory(xSFactory);
// set UserInstallation to user profile dir in test/user-template
// rtl::Bootstrap aDefaultVars;
// aDefaultVars.set(OUString("UserInstallation"), aAppURL + "../registry" );
// configmgr setup ?
}
static int
lo_initialize( LibreOffice *pThis, const char *app_path )
{
(void) pThis;
static bool bInitialized = false;
if( bInitialized )
return 1;
if( !app_path )
return 0;
OUString aAppPath( app_path, strlen( app_path ), RTL_TEXTENCODING_UTF8 );
OUString aAppURL;
if( osl::FileBase::getFileURLFromSystemPath( aAppPath, aAppURL ) !=
osl::FileBase::E_None )
return 0;
try {
initialize_uno( aAppURL );
force_c_locale();
// Force headless
rtl::Bootstrap::set( "SAL_USE_VCLPLUGIN", "svp" );
InitVCL();
Application::EnableHeadlessMode(true);
ErrorHandler::RegisterDisplay( aBasicErrorFunc );
fprintf( stderr, "initialized\n" );
bInitialized = true;
} catch (css::uno::Exception & e) {
fprintf( stderr, "bootstrapping exception '%s'\n",
OUStringToOString( e.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
}
return bInitialized;
}
LibreOffice *liblibreoffice_hook(void)
{
if( !gImpl )
{
fprintf( stderr, "create libreoffice object\n" );
gImpl = new LibLibreOffice_Impl();
}
return static_cast< LibreOffice *>( gImpl );
}
static void lo_destroy (LibreOffice *pThis)
{
LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );
delete pLib;
gImpl = NULL;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include "musicmarqueewidget.h"
#include <QtGui>
MusicMarqueeWidget::MusicMarqueeWidget(QWidget *parent)
: QWidget(parent)
{
m_offset = 0;
m_myTimerId = 0;
}
void MusicMarqueeWidget::setText(const QString &newText)
{
m_myText = newText.leftJustified(50, ' ');
update();
updateGeometry();
}
QSize MusicMarqueeWidget::sizeHint() const
{
return fontMetrics().size(0, text());
}
void MusicMarqueeWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
int textWidth = fontMetrics().width(text());
if(textWidth < 1)
{
return;
}
int x = -m_offset;
while(x < width())
{
painter.drawText(x, 0, textWidth, height(),
Qt::AlignLeft | Qt::AlignVCenter, text());
x += textWidth;
}
painter.end();
}
void MusicMarqueeWidget::showEvent(QShowEvent *)
{
m_myTimerId = startTimer(30);
}
void MusicMarqueeWidget::timerEvent(QTimerEvent *event)
{
if(event->timerId() == m_myTimerId)
{
++m_offset;
if (m_offset >= fontMetrics().width(text()))
{
m_offset = 0;
}
scroll(-1, 0);
}
else
{
QWidget::timerEvent(event);
}
}
void MusicMarqueeWidget::hideEvent(QHideEvent *)
{
killTimer(m_myTimerId);
m_myTimerId = 0;
}
<commit_msg>optimized marquee widgte size[320187]<commit_after>#include "musicmarqueewidget.h"
#include <QtGui>
MusicMarqueeWidget::MusicMarqueeWidget(QWidget *parent)
: QWidget(parent)
{
m_offset = 0;
m_myTimerId = 0;
}
void MusicMarqueeWidget::setText(const QString &newText)
{
m_myText = newText.leftJustified(fontMetrics().width(newText) >= width()
? 45 : 25, ' ');
update();
updateGeometry();
}
QSize MusicMarqueeWidget::sizeHint() const
{
return fontMetrics().size(0, text());
}
void MusicMarqueeWidget::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
QPainter painter(this);
int textWidth = fontMetrics().width(text());
if(textWidth < 1)
{
return;
}
int x = -m_offset;
while(x < width())
{
painter.drawText(x, 0, textWidth, height(),
Qt::AlignLeft | Qt::AlignVCenter, text());
x += textWidth;
}
painter.end();
}
void MusicMarqueeWidget::showEvent(QShowEvent *event)
{
QWidget::showEvent(event);
m_myTimerId = startTimer(30);
}
void MusicMarqueeWidget::timerEvent(QTimerEvent *event)
{
if(event->timerId() == m_myTimerId)
{
++m_offset;
if (m_offset >= fontMetrics().width(text()))
{
m_offset = 0;
}
scroll(-1, 0);
}
else
{
QWidget::timerEvent(event);
}
}
void MusicMarqueeWidget::hideEvent(QHideEvent *event)
{
QWidget::hideEvent(event);
killTimer(m_myTimerId);
m_myTimerId = 0;
}
<|endoftext|>
|
<commit_before>#pragma once
// https://infektor.net/posts/2017-03-31-range-based-enumerate.html
#include <iterator>
#include <utility>
// ----------------------------------------------------------------------
namespace acmacs
{
namespace _enumerate_internal
{
template <typename Iterator, typename index_type> struct enumerate_iterator
{
using iterator = Iterator;
//using index_type = typename std::iterator_traits<iterator>::difference_type;
using reference = typename std::iterator_traits<iterator>::reference;
inline enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
inline enumerate_iterator& operator++() { ++index; ++iter; return *this; }
inline bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
inline std::pair<index_type, reference> operator*() { return {index, *iter}; }
private:
index_type index;
iterator iter;
};
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> struct enumerate_range
{
// using index_type = typename std::iterator_traits<Iterator>::difference_type;
using iterator = enumerate_iterator<Iterator, index_type>;
inline enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
inline iterator begin() const { return iterator(initial, first); }
inline iterator end() const { return iterator(0, last); }
private:
Iterator first;
Iterator last;
index_type initial;
};
} // namespace _enumerate_internal
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)
{
return _enumerate_internal::enumerate_range<Iterator, index_type>(first, last, initial);
}
template <typename Container> inline auto enumerate(Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
}
template <typename Container> inline auto enumerate(const Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
}
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>minor fix<commit_after>#pragma once
// https://infektor.net/posts/2017-03-31-range-based-enumerate.html
#include <iterator>
#include <utility>
// ----------------------------------------------------------------------
namespace acmacs
{
namespace _enumerate_internal
{
template <typename Iterator, typename index_type> struct enumerate_iterator
{
using iterator = Iterator;
//using index_type = typename std::iterator_traits<iterator>::difference_type;
using reference = typename std::iterator_traits<iterator>::reference;
enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
enumerate_iterator& operator++() { ++index; ++iter; return *this; }
bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
std::pair<index_type, reference> operator*() { return {index, *iter}; }
private:
index_type index;
iterator iter;
};
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> struct enumerate_range
{
// using index_type = typename std::iterator_traits<Iterator>::difference_type;
using iterator = enumerate_iterator<Iterator, index_type>;
enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
iterator begin() const { return iterator(initial, first); }
iterator end() const { return iterator(0, last); }
private:
Iterator first;
Iterator last;
index_type initial;
};
} // namespace _enumerate_internal
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)
{
return _enumerate_internal::enumerate_range<Iterator, index_type>(first, last, initial);
}
template <typename Container> inline auto enumerate(Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
}
template <typename Container> inline auto enumerate(const Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
}
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>// @(#)root/base:$Id$
// Author: Christian Bormann 13/10/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TSystemDirectory //
// //
// Describes an Operating System directory for the browser. //
// //
// Author: Christian Bormann 30/09/97 //
// http://www.ikf.physik.uni-frankfurt.de/~bormann/ //
// //
//////////////////////////////////////////////////////////////////////////
#include "TSystemDirectory.h"
#include "TSystem.h"
#include "TBrowser.h"
#include "TOrdCollection.h"
#include "TList.h"
ClassImp(TSystemDirectory);
////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.
TSystemDirectory::TSystemDirectory()
{
fDirsInBrowser = 0;
fFilesInBrowser = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.
TSystemDirectory::TSystemDirectory(const char *dirname, const char *path) :
TSystemFile(dirname, path)
{
fDirsInBrowser = 0;
fFilesInBrowser = 0;
}
////////////////////////////////////////////////////////////////////////////////
///copy constructor
TSystemDirectory::TSystemDirectory(const TSystemDirectory& sd) :
TSystemFile(sd),
fDirsInBrowser(sd.fDirsInBrowser),
fFilesInBrowser(sd.fFilesInBrowser)
{
}
////////////////////////////////////////////////////////////////////////////////
///assignment operator
TSystemDirectory& TSystemDirectory::operator=(const TSystemDirectory& sd)
{
if(this!=&sd) {
TSystemFile::operator=(sd);
fDirsInBrowser=sd.fDirsInBrowser;
fFilesInBrowser=sd.fFilesInBrowser;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Delete system directory object.
TSystemDirectory::~TSystemDirectory()
{
delete fDirsInBrowser;
delete fFilesInBrowser;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns a TList of TSystemFile objects representing the contents
/// of the directory. It's the responsibility of the user to delete
/// the list (the list owns the contained objects).
/// Returns 0 in case of errors.
TList *TSystemDirectory::GetListOfFiles() const
{
void *dir = gSystem->OpenDirectory(GetTitle());
if (!dir) return 0;
const char *file = 0;
TList *contents = new TList;
contents->SetOwner();
while ((file = gSystem->GetDirEntry(dir))) {
if (IsItDirectory(file)) {
TString sdirpath;
if (file[0] == '.' && file[1] == '\0')
sdirpath = GetTitle();
else if (file[0] == '.' && file[1] == '.' && file[2] == '.')
sdirpath = gSystem->DirName(GetTitle());
else {
sdirpath = GetTitle();
if (!sdirpath.EndsWith("/"))
sdirpath += "/";
sdirpath += file;
}
contents->Add(new TSystemDirectory(file, sdirpath.Data()));
} else
contents->Add(new TSystemFile(file, GetTitle()));
}
gSystem->FreeDirectory(dir);
return contents;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.
void TSystemDirectory::SetDirectory(const char *name)
{
SetName(name);
SetTitle(name);
}
////////////////////////////////////////////////////////////////////////////////
/// Check if name is a directory.
Bool_t TSystemDirectory::IsItDirectory(const char *name) const
{
Long64_t size;
Long_t id, flags, modtime;
const char *dirfile = GetTitle();
TString savDir = gSystem->WorkingDirectory();
gSystem->ChangeDirectory(dirfile);
flags = id = size = modtime = 0;
gSystem->GetPathInfo(name, &id, &size, &flags, &modtime);
Int_t isdir = (Int_t)flags & 2;
gSystem->ChangeDirectory(savDir);
return isdir ? kTRUE : kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Browse OS system directories.
void TSystemDirectory::Browse(TBrowser *b)
{
// Collections to keep track of all browser objects that have been
// generated. It's main goal is to prevent the contineous
// allocations of new objects with the same names during browsing.
if (!fDirsInBrowser) fDirsInBrowser = new TOrdCollection;
if (!fFilesInBrowser) fFilesInBrowser = new TOrdCollection(10);
const char *name = GetTitle();
TSystemFile *sfile;
TSystemDirectory *sdir;
const char *file;
gSystem->ChangeDirectory(name);
if (GetName()[0] == '.' && GetName()[1] == '.')
SetName(gSystem->BaseName(name));
void *dir = gSystem->OpenDirectory(name);
if (!dir)
return;
while ((file = gSystem->GetDirEntry(dir))) {
if (b->TestBit(TBrowser::kNoHidden) && file[0] == '.' && file[1] != '.' )
continue;
if (IsItDirectory(file)) {
TString sdirpath;
if (!strcmp(file, "."))
sdirpath = name;
else if (!strcmp(file, ".."))
sdirpath = gSystem->DirName(name);
else {
sdirpath = name;
if (!sdirpath.EndsWith("/"))
sdirpath += "/";
sdirpath += file;
}
if (!(sdir = FindDirObj(sdirpath.Data()))) {
sdir = new TSystemDirectory(file, sdirpath.Data());
fDirsInBrowser->Add(sdir);
}
b->Add(sdir, file);
} else {
if (!(sfile = FindFileObj(file, gSystem->WorkingDirectory()))) {
sfile = new TSystemFile(file, gSystem->WorkingDirectory());
fFilesInBrowser->Add(sfile);
}
b->Add(sfile, file);
}
}
gSystem->FreeDirectory(dir);
}
////////////////////////////////////////////////////////////////////////////////
/// Method that returns system directory object if it
/// exists in list, 0 otherwise.
TSystemDirectory *TSystemDirectory::FindDirObj(const char *name)
{
int size = fDirsInBrowser->GetSize();
for (int i = 0; i < size; i++) {
TSystemDirectory *obj = (TSystemDirectory *) fDirsInBrowser->At(i);
if (!strcmp(name, obj->GetTitle()))
return obj;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Method that returns system file object if it exists in
/// list, 0 otherwise.
TSystemFile *TSystemDirectory::FindFileObj(const char *name, const char *dir)
{
int size = fFilesInBrowser->GetSize();
for (int i = 0; i < size; i++) {
TSystemFile *obj = (TSystemFile *) fFilesInBrowser->At(i);
if (!strcmp(name, obj->GetName()) && !strcmp(dir, obj->GetTitle()))
return obj;
}
return 0;
}
<commit_msg>Doxygen<commit_after>// @(#)root/base:$Id$
// Author: Christian Bormann 13/10/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////////////////
/** \class TSystemDirectory
Describes an Operating System directory for the browser.
*/
#include "TSystemDirectory.h"
#include "TSystem.h"
#include "TBrowser.h"
#include "TOrdCollection.h"
#include "TList.h"
ClassImp(TSystemDirectory);
////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.
TSystemDirectory::TSystemDirectory()
{
fDirsInBrowser = 0;
fFilesInBrowser = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.
TSystemDirectory::TSystemDirectory(const char *dirname, const char *path) :
TSystemFile(dirname, path)
{
fDirsInBrowser = 0;
fFilesInBrowser = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Copy constructor
TSystemDirectory::TSystemDirectory(const TSystemDirectory& sd) :
TSystemFile(sd),
fDirsInBrowser(sd.fDirsInBrowser),
fFilesInBrowser(sd.fFilesInBrowser)
{
}
////////////////////////////////////////////////////////////////////////////////
/// Assignment operator
TSystemDirectory& TSystemDirectory::operator=(const TSystemDirectory& sd)
{
if(this!=&sd) {
TSystemFile::operator=(sd);
fDirsInBrowser=sd.fDirsInBrowser;
fFilesInBrowser=sd.fFilesInBrowser;
}
return *this;
}
////////////////////////////////////////////////////////////////////////////////
/// Delete system directory object.
TSystemDirectory::~TSystemDirectory()
{
delete fDirsInBrowser;
delete fFilesInBrowser;
}
////////////////////////////////////////////////////////////////////////////////
/// Returns a TList of TSystemFile objects representing the contents
/// of the directory. It's the responsibility of the user to delete
/// the list (the list owns the contained objects).
/// Returns 0 in case of errors.
TList *TSystemDirectory::GetListOfFiles() const
{
void *dir = gSystem->OpenDirectory(GetTitle());
if (!dir) return 0;
const char *file = 0;
TList *contents = new TList;
contents->SetOwner();
while ((file = gSystem->GetDirEntry(dir))) {
if (IsItDirectory(file)) {
TString sdirpath;
if (file[0] == '.' && file[1] == '\0')
sdirpath = GetTitle();
else if (file[0] == '.' && file[1] == '.' && file[2] == '.')
sdirpath = gSystem->DirName(GetTitle());
else {
sdirpath = GetTitle();
if (!sdirpath.EndsWith("/"))
sdirpath += "/";
sdirpath += file;
}
contents->Add(new TSystemDirectory(file, sdirpath.Data()));
} else
contents->Add(new TSystemFile(file, GetTitle()));
}
gSystem->FreeDirectory(dir);
return contents;
}
////////////////////////////////////////////////////////////////////////////////
/// Create a system directory object.
void TSystemDirectory::SetDirectory(const char *name)
{
SetName(name);
SetTitle(name);
}
////////////////////////////////////////////////////////////////////////////////
/// Check if name is a directory.
Bool_t TSystemDirectory::IsItDirectory(const char *name) const
{
Long64_t size;
Long_t id, flags, modtime;
const char *dirfile = GetTitle();
TString savDir = gSystem->WorkingDirectory();
gSystem->ChangeDirectory(dirfile);
flags = id = size = modtime = 0;
gSystem->GetPathInfo(name, &id, &size, &flags, &modtime);
Int_t isdir = (Int_t)flags & 2;
gSystem->ChangeDirectory(savDir);
return isdir ? kTRUE : kFALSE;
}
////////////////////////////////////////////////////////////////////////////////
/// Browse OS system directories.
void TSystemDirectory::Browse(TBrowser *b)
{
// Collections to keep track of all browser objects that have been
// generated. It's main goal is to prevent the continuous
// allocations of new objects with the same names during browsing.
if (!fDirsInBrowser) fDirsInBrowser = new TOrdCollection;
if (!fFilesInBrowser) fFilesInBrowser = new TOrdCollection(10);
const char *name = GetTitle();
TSystemFile *sfile;
TSystemDirectory *sdir;
const char *file;
gSystem->ChangeDirectory(name);
if (GetName()[0] == '.' && GetName()[1] == '.')
SetName(gSystem->BaseName(name));
void *dir = gSystem->OpenDirectory(name);
if (!dir)
return;
while ((file = gSystem->GetDirEntry(dir))) {
if (b->TestBit(TBrowser::kNoHidden) && file[0] == '.' && file[1] != '.' )
continue;
if (IsItDirectory(file)) {
TString sdirpath;
if (!strcmp(file, "."))
sdirpath = name;
else if (!strcmp(file, ".."))
sdirpath = gSystem->DirName(name);
else {
sdirpath = name;
if (!sdirpath.EndsWith("/"))
sdirpath += "/";
sdirpath += file;
}
if (!(sdir = FindDirObj(sdirpath.Data()))) {
sdir = new TSystemDirectory(file, sdirpath.Data());
fDirsInBrowser->Add(sdir);
}
b->Add(sdir, file);
} else {
if (!(sfile = FindFileObj(file, gSystem->WorkingDirectory()))) {
sfile = new TSystemFile(file, gSystem->WorkingDirectory());
fFilesInBrowser->Add(sfile);
}
b->Add(sfile, file);
}
}
gSystem->FreeDirectory(dir);
}
////////////////////////////////////////////////////////////////////////////////
/// Method that returns system directory object if it
/// exists in list, 0 otherwise.
TSystemDirectory *TSystemDirectory::FindDirObj(const char *name)
{
int size = fDirsInBrowser->GetSize();
for (int i = 0; i < size; i++) {
TSystemDirectory *obj = (TSystemDirectory *) fDirsInBrowser->At(i);
if (!strcmp(name, obj->GetTitle()))
return obj;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Method that returns system file object if it exists in
/// list, 0 otherwise.
TSystemFile *TSystemDirectory::FindFileObj(const char *name, const char *dir)
{
int size = fFilesInBrowser->GetSize();
for (int i = 0; i < size; i++) {
TSystemFile *obj = (TSystemFile *) fFilesInBrowser->At(i);
if (!strcmp(name, obj->GetName()) && !strcmp(dir, obj->GetTitle()))
return obj;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "pbfParser.h"
#include "platform.h"
#include "tileID.h"
#include <sstream>
#include <fstream>
#include "protobuffSrc.h"
MapboxProtoBuffSrc::MapboxProtoBuffSrc() {
m_urlTemplate = "http://vector.mapzen.com/osm/all/[z]/[x]/[y].mapbox";
}
std::shared_ptr<TileData> MapboxProtoBuffSrc::parse(const MapTile& _tile, std::stringstream& _in) {
std::shared_ptr<TileData> tileData = std::make_shared<TileData>();
std::string buffer(std::istreambuf_iterator<char>(_in.rdbuf()), (std::istreambuf_iterator<char>()));
protobuf::message item(buffer.data(), buffer.size());
while(item.next()) {
if(item.tag == 3) {
protobuf::message layerMsg = item.getMessage();
protobuf::message layerItr = layerMsg;
while (layerItr.next()) {
if (layerItr.tag == 1) {
auto layerName = layerItr.string();
tileData->layers.emplace_back(layerName);
PbfParser::extractLayer(layerMsg, tileData->layers.back(), _tile);
} else {
layerItr.skip();
}
}
} else {
item.skip();
}
}
return tileData;
}
<commit_msg>renamed header inclusion<commit_after>#include "pbfParser.h"
#include "platform.h"
#include "tileID.h"
#include <sstream>
#include <fstream>
#include "protobufSrc.h"
MapboxProtoBuffSrc::MapboxProtoBuffSrc() {
m_urlTemplate = "http://vector.mapzen.com/osm/all/[z]/[x]/[y].mapbox";
}
std::shared_ptr<TileData> MapboxProtoBuffSrc::parse(const MapTile& _tile, std::stringstream& _in) {
std::shared_ptr<TileData> tileData = std::make_shared<TileData>();
std::string buffer(std::istreambuf_iterator<char>(_in.rdbuf()), (std::istreambuf_iterator<char>()));
protobuf::message item(buffer.data(), buffer.size());
while(item.next()) {
if(item.tag == 3) {
protobuf::message layerMsg = item.getMessage();
protobuf::message layerItr = layerMsg;
while (layerItr.next()) {
if (layerItr.tag == 1) {
auto layerName = layerItr.string();
tileData->layers.emplace_back(layerName);
PbfParser::extractLayer(layerMsg, tileData->layers.back(), _tile);
} else {
layerItr.skip();
}
}
} else {
item.skip();
}
}
return tileData;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <HgScene2.h>
#include <HgEngine.h>
namespace Engine {
std::unordered_map<std::string, factoryCallback> HgScene::m_entityFactories;
HgScene::HgScene()
{
auto vBuffer = std::make_shared<HgVectorBuffer<Instancing::GPUTransformationMatrix>>();
std::unique_ptr<IGLBufferUse> action = std::make_unique<MatrixVertexAttribute>("ModelMatrix");
vBuffer->setUseClass(action);
m_vBuffer = vBuffer;
}
HgEntity* HgScene::create_entity(const char* type_str)
{
auto factory = m_entityFactories.find(type_str);
if (factory == m_entityFactories.end()) {
fprintf(stderr, "Unable to find entity type \"%s\"\n", type_str);
return nullptr;
}
factoryCallback clbk = factory->second;
HgEntity* entity = clbk(this);
return entity;
}
void HgScene::RegisterEntityFactory(const char* str, Engine::factoryCallback clbk)
{
m_entityFactories[str] = clbk;
}
void HgScene::update(HgTime dtime)
{
for (auto& i : m_collections) {
i->update(dtime);
}
RemoveInvalidEntities();
}
void HgScene::RemoveInvalidEntities()
{
m_tmpEntities.clear();
if (m_tmpEntities.capacity() < m_entities.size())
{
m_tmpEntities.reserve(m_entities.size());
}
for (auto id : m_entities)
{
if (EntityIdTable::Manager.exists(id))
{
m_tmpEntities.push_back(id);
}
}
std::swap(m_entities, m_tmpEntities);
}
struct {
bool operator()(const EntityRDPair& a, const EntityRDPair& b) const
{
//sort to ascending entity id
if (a.ptr == b.ptr)
{
return a.entity < b.entity;
}
return a.ptr < b.ptr;
}
} orderByRenderData;
struct RdDrawOrder
{
RdDrawOrder()
:drawOrder(0)
{}
EntityRDPair rdPair;
int8_t drawOrder;
inline bool isSameGroup(const RdDrawOrder& rhs)
{
return (drawOrder == rhs.drawOrder)
&& (rdPair.ptr == rhs.rdPair.ptr);
}
};
struct {
bool operator()(const RdDrawOrder& a, const RdDrawOrder& b) const
{
if (a.drawOrder == b.drawOrder)
{
//sort to ascending entity id
if (a.rdPair.ptr == b.rdPair.ptr)
{
return a.rdPair.entity < b.rdPair.entity;
}
return a.rdPair.ptr < b.rdPair.ptr;
}
return a.drawOrder < b.drawOrder;
}
} orderEntitesForDraw;
void HgScene::EnqueueForRender(RenderQueue* queue, HgTime dt) {
for (auto& i : m_collections) {
i->EnqueueForRender(queue, dt);
}
if (m_entities.empty()) return;
auto renderDatas = RenderDataTable::Manager.getRenderDataForEntities(m_entities.data(), m_entities.size());
std::vector<RdDrawOrder> list;
list.reserve(renderDatas.size());
for (auto& rdp : renderDatas)
{
RdDrawOrder t;
t.rdPair = rdp;
t.drawOrder = EntityTable::Singleton.getPtr(rdp.entity)->getDrawOrder();
list.push_back(t);
}
if (m_modelMatrices.capacity() < list.size())
{
m_modelMatrices.resize(list.size());
}
std::vector< Instancing::InstancingMetaData > instances;
m_vBuffer->setDataSource(m_modelMatrices);
m_vBuffer->setNeedsLoadToGPU(true); //entire vector contents needs to be sent to the GPU
//sort by draworder, renderdata, entityID
std::sort(list.begin(), list.end(), orderEntitesForDraw);
//group by draworder, renderdata
RdDrawOrder lastRDO;
Instancing::InstancingMetaData imd;
uint32_t matrixOffset = 0;
for (const auto& t : list)
{
if (!lastRDO.isSameGroup(t))
{
if (imd.instanceCount > 0)
{
instances.push_back(imd);
}
imd = Instancing::InstancingMetaData();
imd.byteOffset = sizeof(Instancing::GPUTransformationMatrix) * matrixOffset;
imd.renderData = t.rdPair.ptr;
imd.instanceData = m_vBuffer;
}
lastRDO = t;
auto entity = EntityTable::Singleton.getPtr(t.rdPair.entity);
const auto m = entity->computeWorldSpaceMatrix();
m.store(m_modelMatrices[matrixOffset].matrix);
imd.instanceCount++;
matrixOffset++;
}
if (imd.instanceCount > 0)
{
instances.push_back(imd);
}
for (const auto& i : instances)
{
queue->Enqueue(i);
}
}
} //Engine<commit_msg>rewrite sort for better performance<commit_after>#pragma once
#include <HgScene2.h>
#include <HgEngine.h>
namespace Engine {
std::unordered_map<std::string, factoryCallback> HgScene::m_entityFactories;
HgScene::HgScene()
{
auto vBuffer = std::make_shared<HgVectorBuffer<Instancing::GPUTransformationMatrix>>();
std::unique_ptr<IGLBufferUse> action = std::make_unique<MatrixVertexAttribute>("ModelMatrix");
vBuffer->setUseClass(action);
m_vBuffer = vBuffer;
}
HgEntity* HgScene::create_entity(const char* type_str)
{
auto factory = m_entityFactories.find(type_str);
if (factory == m_entityFactories.end()) {
fprintf(stderr, "Unable to find entity type \"%s\"\n", type_str);
return nullptr;
}
factoryCallback clbk = factory->second;
HgEntity* entity = clbk(this);
return entity;
}
void HgScene::RegisterEntityFactory(const char* str, Engine::factoryCallback clbk)
{
m_entityFactories[str] = clbk;
}
void HgScene::update(HgTime dtime)
{
for (auto& i : m_collections) {
i->update(dtime);
}
RemoveInvalidEntities();
}
void HgScene::RemoveInvalidEntities()
{
m_tmpEntities.clear();
if (m_tmpEntities.capacity() < m_entities.size())
{
m_tmpEntities.reserve(m_entities.size());
}
for (auto id : m_entities)
{
if (EntityIdTable::Manager.exists(id))
{
m_tmpEntities.push_back(id);
}
}
std::swap(m_entities, m_tmpEntities);
}
struct {
bool operator()(const EntityRDPair& a, const EntityRDPair& b) const
{
//sort to ascending entity id
if (a.ptr == b.ptr)
{
return a.entity < b.entity;
}
return a.ptr < b.ptr;
}
} orderByRenderData;
struct RdDrawOrder
{
RdDrawOrder()
:drawOrder(0)
{}
EntityRDPair rdPair;
int8_t drawOrder;
inline bool isSameGroup(const RdDrawOrder& rhs)
{
return (drawOrder == rhs.drawOrder)
&& (rdPair.ptr == rhs.rdPair.ptr);
}
};
struct {
bool operator()(const RdDrawOrder& a, const RdDrawOrder& b) const
{
return (a.drawOrder < b.drawOrder) ||
((a.drawOrder == b.drawOrder) && (a.rdPair.ptr < b.rdPair.ptr)) ||
((a.drawOrder == b.drawOrder) && (a.rdPair.ptr == b.rdPair.ptr) && (a.rdPair.ptr < b.rdPair.ptr));
//if (a.drawOrder == b.drawOrder)
// {
// //sort to ascending entity id
// if (a.rdPair.ptr == b.rdPair.ptr)
// {
// return a.rdPair.entity < b.rdPair.entity;
// }
// return a.rdPair.ptr < b.rdPair.ptr;
// }
// return a.drawOrder < b.drawOrder;
}
} orderEntitesForDraw;
void HgScene::EnqueueForRender(RenderQueue* queue, HgTime dt) {
for (auto& i : m_collections) {
i->EnqueueForRender(queue, dt);
}
if (m_entities.empty()) return;
auto renderDatas = RenderDataTable::Manager.getRenderDataForEntities(m_entities.data(), m_entities.size());
std::vector<RdDrawOrder> list;
list.reserve(renderDatas.size());
for (auto& rdp : renderDatas)
{
RdDrawOrder t;
t.rdPair = rdp;
t.drawOrder = EntityTable::Singleton.getPtr(rdp.entity)->getDrawOrder();
list.push_back(t);
}
if (m_modelMatrices.capacity() < list.size())
{
m_modelMatrices.resize(list.size());
}
std::vector< Instancing::InstancingMetaData > instances;
m_vBuffer->setDataSource(m_modelMatrices);
m_vBuffer->setNeedsLoadToGPU(true); //entire vector contents needs to be sent to the GPU
//sort by draworder, renderdata, entityID
std::sort(list.begin(), list.end(), orderEntitesForDraw);
//group by draworder, renderdata
RdDrawOrder lastRDO;
Instancing::InstancingMetaData imd;
uint32_t matrixOffset = 0;
for (const auto& t : list)
{
if (!lastRDO.isSameGroup(t))
{
if (imd.instanceCount > 0)
{
instances.push_back(imd);
}
imd = Instancing::InstancingMetaData();
imd.byteOffset = sizeof(Instancing::GPUTransformationMatrix) * matrixOffset;
imd.renderData = t.rdPair.ptr;
imd.instanceData = m_vBuffer;
lastRDO = t;
}
auto entity = EntityTable::Singleton.getPtr(t.rdPair.entity);
const auto m = entity->computeWorldSpaceMatrix();
m.store(m_modelMatrices[matrixOffset].matrix);
imd.instanceCount++;
matrixOffset++;
}
if (imd.instanceCount > 0)
{
instances.push_back(imd);
}
for (const auto& i : instances)
{
queue->Enqueue(i);
}
}
} //Engine<|endoftext|>
|
<commit_before>/*
* Harversine.c
* Haversine
*
* Created by Jaime Rios on 2/16/08.
*
*/
#include "Harversine.h"
#include <math.h> // For PI
/*
Haversine Formula
R = earth’s radius (mean radius = 6,371km)
Δlat = lat2− lat1
Δlong = long2− long1
a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
c = 2.atan2(√a, √(1−a))
d = R.c
JavaScript Example from http://www.movable-type.co.uk/scripts/latlong.html
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
lat1 = lat1.toRad(), lat2 = lat2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
*/
auto CalculateDistance( Angle latitude1, Angle longtitude1, Angle latitude2, Angle longtitude2 ) -> Angle
{
auto radius = Kilometers{ 6371 }; // Earth's radius
// Get the difference between our two points then convert the difference into radians
auto latDelta = Convert(latitude2 - latitude1);
auto lonDelta = Convert(longtitude2 - longtitude1);
latitude1 = Convert(latitude1);
latitude2 = Convert(latitude2);
auto a = pow ( sin(latDelta/2), 2 ) +
cos(latitude1) * cos(latitude2) *
pow ( sin(lonDelta/2), 2 );
auto c = 2 * atan2( sqrt(a), sqrt( 1 - a ));
auto d = radius * c;
return d;
}
// Convert our passed value to Radians
auto Convert( const Angle angle ) -> Radians
{
return angle * (M_PI/180);
}<commit_msg>Spaces versus tabs again :|<commit_after>/*
* Harversine.c
* Haversine
*
* Created by Jaime Rios on 2/16/08.
*
*/
#include "Harversine.h"
#include <math.h> // For PI
/*
Haversine Formula
R = earth’s radius (mean radius = 6,371km)
Δlat = lat2− lat1
Δlong = long2− long1
a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
c = 2.atan2(√a, √(1−a))
d = R.c
JavaScript Example from http://www.movable-type.co.uk/scripts/latlong.html
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
lat1 = lat1.toRad(), lat2 = lat2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
*/
auto CalculateDistance( Angle latitude1, Angle longtitude1, Angle latitude2, Angle longtitude2 ) -> Angle
{
auto radius = Kilometers{ 6371 }; // Earth's radius
// Get the difference between our two points then convert the difference into radians
auto latDelta = Convert(latitude2 - latitude1);
auto lonDelta = Convert(longtitude2 - longtitude1);
latitude1 = Convert(latitude1);
latitude2 = Convert(latitude2);
auto a = pow ( sin(latDelta/2), 2 ) +
cos(latitude1) * cos(latitude2) *
pow ( sin(lonDelta/2), 2 );
auto c = 2 * atan2( sqrt(a), sqrt( 1 - a ));
auto d = radius * c;
return d;
}
// Convert our passed value to Radians
auto Convert( const Angle angle ) -> Radians
{
return angle * (M_PI/180);
}<|endoftext|>
|
<commit_before>#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <stack>
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define ll long long
using namespace std;
class Solver {
vector <int> current_set;
int N, count_set;
vector<vector<int>> edges;
vector<int> L;
map <int, int> R;
vector<int> viz;
set<vector<int>> unique_sets;
public:
Solver(int _N) {
//
N = _N;
count_set = 0;
edges.assign(N, vector<int>());
L.assign(N,0);
viz.assign(N, 0);
}
bool intersect(int mask1, int mask2) {
return (mask1 & mask2);
}
void to_set(int mask) {
cout << "{";
vector<int> Ans;
for (int i = 0; i < N; ++i) {
if (mask & (1 << i)) {
Ans.push_back(i + 1);
}
}
for (int i = 0; i < Ans.size() - 1; ++i) {
cout << Ans[i] << ",";
}
if (Ans.size() > 0) {
cout << Ans[Ans.size() - 1];
}
cout << "}";
}
bool pairup(int node) {
if (viz[node]) {
return 0;
}
viz[node] = 1;
for (auto vec: edges[node]) {
if (R.find(vec) == R.end()) {
L[node] = vec;
R[vec] = node;
return 1;
}
}
for (auto vec: edges[node]) {
if (pairup(R[vec])) {
L[node] = vec;
R[vec] = node;
return 1;
}
}
return 0;
}
void debug_set(const vector<int>& v) {
cout << "**********\n";
for (int i = 0; i < v.size(); ++i) {
to_set(v[i]);
cout << "\n";
}
}
bool do_matching(const vector<int>&to_check) {
//debug_set(to_check);
//
int ret = prime_condition(to_check);
if (ret == 0) {
return 0;
}
for (int i = 0; i < N; ++i) {
edges[i].clear();
viz[i] = 0;
L[i] = -1;
R.clear();
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (to_check[j] & (1 << i)) {
edges[i].push_back(j);
}
}
}
for (int i = 0; i < N; ++i) {
if (edges[i].size() == 0) {
return 0;
}
}
int change = 1;
while(change) {
change = 0;
for (int i = 0; i < N; ++i) {
viz[i] = 0;
}
for (int i = 0; i < N; ++i) {
if (L[i] == -1) {
change |= pairup(i);
}
}
}
for (int i = 0; i < N; ++i) {
if (L[i] == -1) {
cout << "FAIL ON\n";
cout << "is prime condition? " << ret << "\n";
write_set(L, to_check);
cout << "graph: \n";
for (int k = 0; k < N; ++k) {
cerr << k + 1 << " -> " ;
for (auto vec: edges[k]) {
to_set(to_check[vec]);
}
cerr << "\n";
}
return 0;
}
}
/*
cout << "set: " << count_set << "\n";
write_set(L, to_check);
*/
//cerr << "MATCHING DONE?\n";
/*
vector<int> tmp(to_check);
sort(tmp.begin(), tmp.end());
unique_sets.insert(tmp);
*/
return 1;
}
void generate_all_sets(int k) {
if (k == N) {
count_set += do_matching(current_set);
} else {
int start = 0;
if (k != 0) {
start = current_set[k - 1];
}
for (int mask = start + 1; mask < (1 << N); ++mask) {
bool flag = false;
for (int i = 0; i < k; ++i) {
if (!intersect(mask, current_set[i])) {
flag = true;
break;
}
}
if (flag) {
continue;
}
current_set.push_back(mask);
generate_all_sets(k + 1);
current_set.pop_back();
}
}
}
bool prime_condition(const vector<int>&to_check) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (i == j) {
continue;
}
bool can_go = false;
for (int k = 0; k < N; ++k) {
if (intersect(to_check[k], 1<<i) && !intersect(to_check[k], 1<<j)) {
can_go = true;
break;
}
}
if (!can_go) {
//cerr << "pair: " << i + 1 << " " << j + 1 << "\n";
return 0;
}
}
}
return 1;
}
void write_set(vector<int>& L, const vector<int>&v) {
for (int i = 0; i < N; ++i) {
if (L[i] == -1) {
cout << "?";
} else {
cout << i + 1;
}
cout << " -> ";
if (L[i] != -1) {
to_set(v[L[i]]);
}
cout << "\n";
}
}
void checker() {
generate_all_sets(0);
cout << "Found " << count_set << " matchings\n";
cout << "Found " << unique_sets.size() << " unique sets\n";
}
};
int main() {
ifstream cin("test.in");
int N; cin >> N;
N = 4;
Solver G(N);
G.checker();
//int res = G.do_matching({127,191,223,239,247,251,253,254,22019,10764,3376,12736,341,405,16808});
//cout << res << "\n";
//cout << G.prime_condition({7,6,5});
return 0;
}
<commit_msg>last chance<commit_after>#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <omp.h>
#include <stack>
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define ll long long
using namespace std;
class Graph {
public:
Graph(int _N) {
N = _N;
viz.assign(N, 0);
L.assign(N, -1);
R.assign(N, -1);
edges.assign(N, vector<int>());
edge_mask.assign(N, 0);
}
void addEdge(int x, int y) {
edges[x].push_back(y);
edge_mask[y] |= (1 << x);
}
bool pairup(int node) {
if (viz[node]) {
return 0;
}
viz[node] = 1;
for (auto vec: edges[node]) {
if (R[vec] == -1) {
L[node] = vec;
R[vec] = node;
return 1;
}
}
for (auto vec: edges[node]) {
if (pairup(R[vec])) {
L[node] = vec;
R[vec] = node;
return 1;
}
}
return 0;
}
bool maxMatch() {
int change = 1;
while(change) {
change = 0;
for (int i = 0; i < N; ++i) {
viz[i] = 0;
}
for (int i = 0; i < N; ++i) {
if (L[i] == -1) {
change |= pairup(i);
}
}
}
for (int i = 0; i < N; ++i) {
if (L[i] == -1) {
return 0;
}
}
return 1;
}
void write() {
for (int i = 0; i < N; ++i) {
vector<int> row;
for (int j = 0; j < N; ++j) {
if ( edge_mask[i] & (1 << j) ) {
row.push_back(j);
}
}
if (R[i] != -1) {
cerr << R[i] << " -> ";
} else {
cerr << "?" << " -> ";
}
cerr << "{";
for (int j = 0; j < row.size() - 1; ++j) {
cerr << row[j] << ",";
}
cerr << *row.rbegin() << "}\n";
}
}
int N;
vector<int> viz, L, R, edge_mask;
vector<vector<int>> edges;
};
class Solver {
vector <int> current_set;
int N, count_set;
set<vector<int>> unique_sets;
public:
Solver(int _N) {
N = _N;
count_set = 0;
}
bool intersect(int mask1, int mask2) {
return (mask1 & mask2);
}
bool do_matching(const vector<int>& to_check) {
//debug_set(to_check);
//
int ret = prime_condition(to_check);
if (ret == 0) {
return 0;
}
Graph G(N);
// prob cache misses?
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (to_check[j] & (1 << i)) {
G.addEdge(i, j);
}
}
}
for (int i = 0; i < N; ++i) {
if (G.edges[i].size() == 0) {
return 0;
}
}
if (!G.maxMatch()) {
cout << "FAIL ON\n";
cout << "is prime condition? " << ret << "\n";
G.write();
return 0;
}
//cout << "set: " << count_set << "\n";
//cerr << "MATCHING DONE?\n";
/*
vector<int> tmp(to_check);
sort(tmp.begin(), tmp.end());
unique_sets.insert(tmp);
*/
return 1;
}
void generate_all_sets(int k, vector<int>& current_set) {
if (k == N) {
count += do_matching(current_set);
} else {
int start = 0;
if (k != 0) {
start = current_set[k - 1];
}
#pragma omp parallel for
for (int mask = start + 1; mask < (1 << N); ++mask) {
bool flag = false;
for (int i = 0; i < k; ++i) {
if (!intersect(mask, current_set[i])) {
flag = true;
break;
}
}
if (!flag) {
vector<int> next_set(current_set);
next_set.push_back(mask);
generate_all_sets(k + 1, next_set);
}
}
}
}
bool prime_condition(const vector<int>&to_check) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (i == j) {
continue;
}
bool can_go = false;
for (int k = 0; k < N; ++k) {
if (intersect(to_check[k], 1<<i) && !intersect(to_check[k], 1<<j)) {
can_go = true;
// cerr << "fails with " << i << " " << j << "\n";
break;
}
}
if (!can_go) {
// cerr << "pair: " << i + 1 << " " << j + 1 << "\n";
return 0;
}
}
}
return 1;
}
void debug_(vector<int>& edges) {
for (int i = 0; i < edges.size(); ++i) {
for (int j = 0; j < N; ++j) {
if (edges[i] & (1 << j)) {
cout << j + 1 << " " ;
}
}
cout << "\n";
}
cout << "\n";
}
void checker() {
vector<int> empty_vector;
generate_all_sets(0, empty_vector);
cout << "Found " << count_set << " matchings\n";
cout << "Found " << unique_sets.size() << " unique sets\n";
/*
for (auto edges: unique_sets) {
debug_(edges);
}
*/
}
};
int main() {
ifstream cin("test.in");
int N; cin >> N;
Solver G(N);
G.checker();
// int res = G.do_matching({35,77,161,53,19,13,102,122});
// cout << res << "\n";
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/utils:$Id$
// Author: Axel Naumann, 2014-04-07
/*************************************************************************
* Copyright (C) 1995-2014, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// Provides bindings to TCling (compiled with rtti) from rootcling (compiled
// without rtti).
#include "TCling.h"
#include "TROOT.h"
#include "TFile.h"
#include "TClass.h"
#include "TStreamerInfo.h"
#include <iostream>
#include "TProtoClass.h"
std::string gPCMFilename;
std::vector<std::string> gClassesToStore;
std::vector<std::string> gTypedefsToStore;
std::vector<std::string> gAncestorPCMsNames;
extern "C"
const char*** TROOT__GetExtraInterpreterArgs() {
return &TROOT::GetExtraInterpreterArgs();
}
extern "C"
cling::Interpreter* TCling__GetInterpreter()
{
static bool sInitialized = false;
gROOT; // trigger initialization
if (!sInitialized) {
gCling->SetClassAutoloading(false);
sInitialized = true;
}
return ((TCling*)gCling)->GetInterpreter();
}
extern "C"
void InitializeStreamerInfoROOTFile(const char* filename)
{
gPCMFilename = filename;
}
extern "C"
void AddStreamerInfoToROOTFile(const char* normName)
{
gClassesToStore.emplace_back(normName);
}
extern "C"
void AddTypedefToROOTFile(const char* tdname)
{
gTypedefsToStore.push_back(tdname);
}
extern "C"
void AddAncestorPCMROOTFile(const char* pcmName)
{
gAncestorPCMsNames.emplace_back(pcmName);
}
extern "C"
bool CloseStreamerInfoROOTFile()
{
// Write all persistent TClasses.
// Avoid plugins.
TVirtualStreamerInfo::SetFactory(new TStreamerInfo());
TObjArray protoClasses;
for (const auto normName: gClassesToStore) {
TClass* cl = TClass::GetClass(normName.c_str(), kTRUE /*load*/);
if (!cl) {
std::cerr << "ERROR in CloseStreamerInfoROOTFile(): cannot find class "
<< normName << '\n';
return false;
}
// If the class is not persistent we return success.
if (cl->GetClassVersion() == 0)
continue;
// If this is a proxied collection then offsets are not needed.
if (cl->GetCollectionProxy())
continue;
cl->Property(); // Force initialization of the bits and property fields.
protoClasses.AddLast(new TProtoClass(cl));
}
TObjArray typedefs;
for (const auto dtname: gTypedefsToStore) {
TDataType* dt = (TDataType*)gROOT->GetListOfTypes()->FindObject(dtname.c_str());
if (!dt) {
std::cerr << "ERROR in CloseStreamerInfoROOTFile(): cannot find class "
<< dtname << '\n';
return false;
}
if (dt->GetType() == -1) {
dt->Property(); // Force initialization of the bits and property fields.
dt->GetTypeName(); // Force caching of type name.
typedefs.AddLast(dt);
}
}
// Don't use TFile::Open(); we don't need plugins.
TFile dictFile(gPCMFilename.c_str(), "RECREATE");
if (dictFile.IsZombie())
return false;
// Instead of plugins:
protoClasses.Write("__ProtoClasses", TObject::kSingleKey);
protoClasses.Delete();
typedefs.Write("__Typedefs", TObject::kSingleKey);
dictFile.WriteObjectAny(&gAncestorPCMsNames, "std::vector<std::string>", "__AncestorPCMsNames");
return true;
}
<commit_msg>Make sure that the list of bases is complete.<commit_after>// @(#)root/utils:$Id$
// Author: Axel Naumann, 2014-04-07
/*************************************************************************
* Copyright (C) 1995-2014, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// Provides bindings to TCling (compiled with rtti) from rootcling (compiled
// without rtti).
#include "TCling.h"
#include "TROOT.h"
#include "TFile.h"
#include "TClass.h"
#include "TStreamerInfo.h"
#include <iostream>
#include "TProtoClass.h"
std::string gPCMFilename;
std::vector<std::string> gClassesToStore;
std::vector<std::string> gTypedefsToStore;
std::vector<std::string> gAncestorPCMsNames;
extern "C"
const char*** TROOT__GetExtraInterpreterArgs() {
return &TROOT::GetExtraInterpreterArgs();
}
extern "C"
cling::Interpreter* TCling__GetInterpreter()
{
static bool sInitialized = false;
gROOT; // trigger initialization
if (!sInitialized) {
gCling->SetClassAutoloading(false);
sInitialized = true;
}
return ((TCling*)gCling)->GetInterpreter();
}
extern "C"
void InitializeStreamerInfoROOTFile(const char* filename)
{
gPCMFilename = filename;
}
extern "C"
void AddStreamerInfoToROOTFile(const char* normName)
{
gClassesToStore.emplace_back(normName);
}
extern "C"
void AddTypedefToROOTFile(const char* tdname)
{
gTypedefsToStore.push_back(tdname);
}
extern "C"
void AddAncestorPCMROOTFile(const char* pcmName)
{
gAncestorPCMsNames.emplace_back(pcmName);
}
extern "C"
bool CloseStreamerInfoROOTFile()
{
// Write all persistent TClasses.
// Avoid plugins.
TVirtualStreamerInfo::SetFactory(new TStreamerInfo());
TObjArray protoClasses;
for (const auto normName: gClassesToStore) {
TClass* cl = TClass::GetClass(normName.c_str(), kTRUE /*load*/);
if (!cl) {
std::cerr << "ERROR in CloseStreamerInfoROOTFile(): cannot find class "
<< normName << '\n';
return false;
}
// If the class is not persistent we return success.
if (cl->GetClassVersion() == 0)
continue;
// If this is a proxied collection then offsets are not needed.
if (cl->GetCollectionProxy())
continue;
cl->Property(); // Force initialization of the bits and property fields.
cl->GetListOfBases();
protoClasses.AddLast(new TProtoClass(cl));
}
TObjArray typedefs;
for (const auto dtname: gTypedefsToStore) {
TDataType* dt = (TDataType*)gROOT->GetListOfTypes()->FindObject(dtname.c_str());
if (!dt) {
std::cerr << "ERROR in CloseStreamerInfoROOTFile(): cannot find class "
<< dtname << '\n';
return false;
}
if (dt->GetType() == -1) {
dt->Property(); // Force initialization of the bits and property fields.
dt->GetTypeName(); // Force caching of type name.
typedefs.AddLast(dt);
}
}
// Don't use TFile::Open(); we don't need plugins.
TFile dictFile(gPCMFilename.c_str(), "RECREATE");
if (dictFile.IsZombie())
return false;
// Instead of plugins:
protoClasses.Write("__ProtoClasses", TObject::kSingleKey);
protoClasses.Delete();
typedefs.Write("__Typedefs", TObject::kSingleKey);
dictFile.WriteObjectAny(&gAncestorPCMsNames, "std::vector<std::string>", "__AncestorPCMsNames");
return true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef DATABASE_HH_
#define DATABASE_HH_
#include "core/sstring.hh"
#include "core/shared_ptr.hh"
#include "net/byteorder.hh"
#include "utils/UUID.hh"
#include "db_clock.hh"
#include "gc_clock.hh"
#include <functional>
#include <boost/any.hpp>
#include <cstdint>
#include <boost/variant.hpp>
#include <unordered_map>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <boost/functional/hash.hpp>
#include <experimental/optional>
#include <string.h>
#include "types.hh"
#include "tuple.hh"
#include "core/future.hh"
#include "cql3/column_specification.hh"
#include <limits>
#include <cstddef>
#include "schema.hh"
using partition_key_type = tuple_type<>;
using clustering_key_type = tuple_type<>;
using clustering_prefix_type = tuple_prefix;
using partition_key = bytes;
using clustering_key = bytes;
using clustering_prefix = clustering_prefix_type::value_type;
namespace api {
using timestamp_type = int64_t;
timestamp_type constexpr missing_timestamp = std::numeric_limits<timestamp_type>::min();
timestamp_type constexpr min_timestamp = std::numeric_limits<timestamp_type>::min() + 1;
timestamp_type constexpr max_timestamp = std::numeric_limits<timestamp_type>::max();
}
/**
* Represents deletion operation. Can be commuted with other tombstones via apply() method.
* Can be empty.
*
*/
struct tombstone final {
api::timestamp_type timestamp;
gc_clock::time_point ttl;
tombstone(api::timestamp_type timestamp, gc_clock::time_point ttl)
: timestamp(timestamp)
, ttl(ttl)
{ }
tombstone()
: tombstone(api::missing_timestamp, {})
{ }
int compare(const tombstone& t) const {
if (timestamp < t.timestamp) {
return -1;
} else if (timestamp > t.timestamp) {
return 1;
} else if (ttl < t.ttl) {
return -1;
} else if (ttl > t.ttl) {
return 1;
} else {
return 0;
}
}
bool operator<(const tombstone& t) const {
return compare(t) < 0;
}
bool operator==(const tombstone& t) const {
return compare(t) == 0;
}
operator bool() const {
return timestamp != api::missing_timestamp;
}
void apply(const tombstone& t) {
if (*this < t) {
*this = t;
}
}
};
using ttl_opt = std::experimental::optional<gc_clock::time_point>;
struct atomic_cell final {
struct dead {
gc_clock::time_point ttl;
};
struct live {
ttl_opt ttl;
bytes value;
};
api::timestamp_type timestamp;
boost::variant<dead, live> value;
bool is_live() const { return value.which() == 1; }
// Call only when is_live() == true
const live& as_live() const { return boost::get<live>(value); }
// Call only when is_live() == false
const dead& as_dead() const { return boost::get<dead>(value); }
};
using row = std::map<column_id, boost::any>;
struct deletable_row final {
tombstone t;
row cells;
};
using row_tombstone_set = std::map<bytes, tombstone, serialized_compare>;
class mutation_partition final {
private:
tombstone _tombstone;
row _static_row;
std::map<clustering_key, deletable_row, key_compare> _rows;
row_tombstone_set _row_tombstones;
public:
mutation_partition(schema_ptr s)
: _rows(key_compare(s->clustering_key_type))
, _row_tombstones(serialized_compare(s->clustering_key_prefix_type))
{ }
void apply(tombstone t) {
_tombstone.apply(t);
}
void apply_delete(schema_ptr schema, const clustering_prefix& prefix, tombstone t) {
if (prefix.empty()) {
apply(t);
} else if (prefix.size() == schema->clustering_key.size()) {
_rows[serialize_value(*schema->clustering_key_type, prefix)].t.apply(t);
} else {
apply_row_tombstone(schema, {serialize_value(*schema->clustering_key_prefix_type, prefix), t});
}
}
void apply_row_tombstone(schema_ptr schema, bytes prefix, tombstone t) {
apply_row_tombstone(schema, {std::move(prefix), std::move(t)});
}
void apply_row_tombstone(schema_ptr schema, std::pair<bytes, tombstone> row_tombstone) {
auto& prefix = row_tombstone.first;
auto i = _row_tombstones.lower_bound(prefix);
if (i == _row_tombstones.end() || !schema->clustering_key_prefix_type->equal(prefix, i->first)
|| row_tombstone.second > i->second) {
_row_tombstones.insert(i, std::move(row_tombstone));
}
}
void apply(schema_ptr schema, mutation_partition&& p);
row& static_row() {
return _static_row;
}
row& clustered_row(const clustering_key& key) {
return _rows[key].cells;
}
row& clustered_row(clustering_key&& key) {
return _rows[std::move(key)].cells;
}
row* find_row(const clustering_key& key) {
auto i = _rows.find(key);
if (i == _rows.end()) {
return nullptr;
}
return &i->second.cells;
}
};
class mutation final {
public:
schema_ptr schema;
partition_key key;
mutation_partition p;
public:
mutation(partition_key key_, schema_ptr schema_)
: schema(std::move(schema_))
, key(std::move(key_))
, p(schema)
{ }
mutation(mutation&&) = default;
mutation(const mutation&) = delete;
void set_static_cell(const column_definition& def, boost::any value) {
p.static_row()[def.id] = std::move(value);
}
void set_clustered_cell(const clustering_prefix& prefix, const column_definition& def, boost::any value) {
auto& row = p.clustered_row(serialize_value(*schema->clustering_key_type, prefix));
row[def.id] = std::move(value);
}
void set_clustered_cell(const clustering_key& key, const column_definition& def, boost::any value) {
auto& row = p.clustered_row(key);
row[def.id] = std::move(value);
}
};
struct column_family {
column_family(schema_ptr schema);
mutation_partition& find_or_create_partition(const bytes& key);
row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key);
mutation_partition* find_partition(const bytes& key);
row* find_row(const bytes& partition_key, const bytes& clustering_key);
schema_ptr _schema;
// partition key -> partition
std::map<bytes, mutation_partition, key_compare> partitions;
void apply(mutation&& m);
};
class keyspace {
public:
std::unordered_map<sstring, column_family> column_families;
static future<keyspace> populate(sstring datadir);
schema_ptr find_schema(sstring cf_name);
column_family* find_column_family(sstring cf_name);
};
class database {
public:
std::unordered_map<sstring, keyspace> keyspaces;
static future<database> populate(sstring datadir);
keyspace* find_keyspace(sstring name);
};
#endif /* DATABASE_HH_ */
<commit_msg>db: Define the rest of comparison operators in tombstone<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef DATABASE_HH_
#define DATABASE_HH_
#include "core/sstring.hh"
#include "core/shared_ptr.hh"
#include "net/byteorder.hh"
#include "utils/UUID.hh"
#include "db_clock.hh"
#include "gc_clock.hh"
#include <functional>
#include <boost/any.hpp>
#include <cstdint>
#include <boost/variant.hpp>
#include <unordered_map>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <boost/functional/hash.hpp>
#include <experimental/optional>
#include <string.h>
#include "types.hh"
#include "tuple.hh"
#include "core/future.hh"
#include "cql3/column_specification.hh"
#include <limits>
#include <cstddef>
#include "schema.hh"
using partition_key_type = tuple_type<>;
using clustering_key_type = tuple_type<>;
using clustering_prefix_type = tuple_prefix;
using partition_key = bytes;
using clustering_key = bytes;
using clustering_prefix = clustering_prefix_type::value_type;
namespace api {
using timestamp_type = int64_t;
timestamp_type constexpr missing_timestamp = std::numeric_limits<timestamp_type>::min();
timestamp_type constexpr min_timestamp = std::numeric_limits<timestamp_type>::min() + 1;
timestamp_type constexpr max_timestamp = std::numeric_limits<timestamp_type>::max();
}
/**
* Represents deletion operation. Can be commuted with other tombstones via apply() method.
* Can be empty.
*
*/
struct tombstone final {
api::timestamp_type timestamp;
gc_clock::time_point ttl;
tombstone(api::timestamp_type timestamp, gc_clock::time_point ttl)
: timestamp(timestamp)
, ttl(ttl)
{ }
tombstone()
: tombstone(api::missing_timestamp, {})
{ }
int compare(const tombstone& t) const {
if (timestamp < t.timestamp) {
return -1;
} else if (timestamp > t.timestamp) {
return 1;
} else if (ttl < t.ttl) {
return -1;
} else if (ttl > t.ttl) {
return 1;
} else {
return 0;
}
}
bool operator<(const tombstone& t) const {
return compare(t) < 0;
}
bool operator<=(const tombstone& t) const {
return compare(t) <= 0;
}
bool operator>(const tombstone& t) const {
return compare(t) > 0;
}
bool operator>=(const tombstone& t) const {
return compare(t) >= 0;
}
bool operator==(const tombstone& t) const {
return compare(t) == 0;
}
bool operator!=(const tombstone& t) const {
return compare(t) != 0;
}
operator bool() const {
return timestamp != api::missing_timestamp;
}
void apply(const tombstone& t) {
if (*this < t) {
*this = t;
}
}
};
using ttl_opt = std::experimental::optional<gc_clock::time_point>;
struct atomic_cell final {
struct dead {
gc_clock::time_point ttl;
};
struct live {
ttl_opt ttl;
bytes value;
};
api::timestamp_type timestamp;
boost::variant<dead, live> value;
bool is_live() const { return value.which() == 1; }
// Call only when is_live() == true
const live& as_live() const { return boost::get<live>(value); }
// Call only when is_live() == false
const dead& as_dead() const { return boost::get<dead>(value); }
};
using row = std::map<column_id, boost::any>;
struct deletable_row final {
tombstone t;
row cells;
};
using row_tombstone_set = std::map<bytes, tombstone, serialized_compare>;
class mutation_partition final {
private:
tombstone _tombstone;
row _static_row;
std::map<clustering_key, deletable_row, key_compare> _rows;
row_tombstone_set _row_tombstones;
public:
mutation_partition(schema_ptr s)
: _rows(key_compare(s->clustering_key_type))
, _row_tombstones(serialized_compare(s->clustering_key_prefix_type))
{ }
void apply(tombstone t) {
_tombstone.apply(t);
}
void apply_delete(schema_ptr schema, const clustering_prefix& prefix, tombstone t) {
if (prefix.empty()) {
apply(t);
} else if (prefix.size() == schema->clustering_key.size()) {
_rows[serialize_value(*schema->clustering_key_type, prefix)].t.apply(t);
} else {
apply_row_tombstone(schema, {serialize_value(*schema->clustering_key_prefix_type, prefix), t});
}
}
void apply_row_tombstone(schema_ptr schema, bytes prefix, tombstone t) {
apply_row_tombstone(schema, {std::move(prefix), std::move(t)});
}
void apply_row_tombstone(schema_ptr schema, std::pair<bytes, tombstone> row_tombstone) {
auto& prefix = row_tombstone.first;
auto i = _row_tombstones.lower_bound(prefix);
if (i == _row_tombstones.end() || !schema->clustering_key_prefix_type->equal(prefix, i->first)
|| row_tombstone.second > i->second) {
_row_tombstones.insert(i, std::move(row_tombstone));
}
}
void apply(schema_ptr schema, mutation_partition&& p);
row& static_row() {
return _static_row;
}
row& clustered_row(const clustering_key& key) {
return _rows[key].cells;
}
row& clustered_row(clustering_key&& key) {
return _rows[std::move(key)].cells;
}
row* find_row(const clustering_key& key) {
auto i = _rows.find(key);
if (i == _rows.end()) {
return nullptr;
}
return &i->second.cells;
}
};
class mutation final {
public:
schema_ptr schema;
partition_key key;
mutation_partition p;
public:
mutation(partition_key key_, schema_ptr schema_)
: schema(std::move(schema_))
, key(std::move(key_))
, p(schema)
{ }
mutation(mutation&&) = default;
mutation(const mutation&) = delete;
void set_static_cell(const column_definition& def, boost::any value) {
p.static_row()[def.id] = std::move(value);
}
void set_clustered_cell(const clustering_prefix& prefix, const column_definition& def, boost::any value) {
auto& row = p.clustered_row(serialize_value(*schema->clustering_key_type, prefix));
row[def.id] = std::move(value);
}
void set_clustered_cell(const clustering_key& key, const column_definition& def, boost::any value) {
auto& row = p.clustered_row(key);
row[def.id] = std::move(value);
}
};
struct column_family {
column_family(schema_ptr schema);
mutation_partition& find_or_create_partition(const bytes& key);
row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key);
mutation_partition* find_partition(const bytes& key);
row* find_row(const bytes& partition_key, const bytes& clustering_key);
schema_ptr _schema;
// partition key -> partition
std::map<bytes, mutation_partition, key_compare> partitions;
void apply(mutation&& m);
};
class keyspace {
public:
std::unordered_map<sstring, column_family> column_families;
static future<keyspace> populate(sstring datadir);
schema_ptr find_schema(sstring cf_name);
column_family* find_column_family(sstring cf_name);
};
class database {
public:
std::unordered_map<sstring, keyspace> keyspaces;
static future<database> populate(sstring datadir);
keyspace* find_keyspace(sstring name);
};
#endif /* DATABASE_HH_ */
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <sys/time.h>
#include <inttypes.h>
#include <time.h>
#include "TTimestamp.h"
namespace tyr { namespace basic {
static_assert(sizeof(Timestamp) == sizeof(int64_t), "Timestamp is same size as int64_t");
std::string Timestamp::to_string(void) const {
char buf[32] = {0};
int64_t sec = epoch_msec_ / kMicroSecondsPerSecond;
int64_t msec = epoch_msec_ % kMicroSecondsPerSecond;
snprintf(buf, sizeof(buf) - 1, "%" PRId64 ".%06" PRId64 "", sec, msec);
return buf;
}
std::string Timestamp::to_formatted_string(bool show_msec) const {
char buf[32] = {0};
time_t sec = static_cast<time_t>(epoch_msec_ / kMicroSecondsPerSecond);
struct tm tm_time;
gmtime_r(&sec, &tm_time);
if (show_msec) {
int msec = static_cast<int>(epoch_msec_ % kMicroSecondsPerSecond);
snprintf(buf,
sizeof(buf),
"%04d%02d%02d %02d:%02d:%02d.%06d",
tm_time.tm_year + 1900,
tm_time.tm_mon + 1,
tm_time.tm_mday,
tm_time.tm_hour,
tm_time.tm_min,
tm_time.tm_sec,
msec);
}
else {
snprintf(buf,
sizeof(buf),
"%04d%02d%02d %02d:%02d:%02d",
tm_time.tm_year + 1900,
tm_time.tm_mon + 1,
tm_time.tm_mday,
tm_time.tm_hour,
tm_time.tm_min,
tm_time.tm_sec);
}
return buf;
}
Timestamp Timestamp::now(void) {
struct timeval tv;
gettimeofday(&tv, nullptr);
int64_t sec = tv.tv_sec;
return Timestamp(sec * kMicroSecondsPerSecond + tv.tv_usec);
}
Timestamp Timestamp::invalid(void) {
return Timestamp();
}
Timestamp Timestamp::from_unix_time(time_t t) {
return from_unix_time(t, 0);
}
Timestamp Timestamp::from_unix_time(time_t t, int msec) {
return Timestamp(static_cast<int64_t>(t) * kMicroSecondsPerSecond + msec);
}
}}
<commit_msg>chore(timestamp): updated the implementation of timestamp<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <inttypes.h>
#include <time.h>
#include "TPlatform.h"
#include "TTimestamp.h"
namespace tyr { namespace basic {
static_assert(sizeof(Timestamp) == sizeof(int64_t), "Timestamp is same size as int64_t");
std::string Timestamp::to_string(void) const {
char buf[32] = {0};
int64_t sec = epoch_msec_ / kMicroSecondsPerSecond;
int64_t msec = epoch_msec_ % kMicroSecondsPerSecond;
snprintf(buf, sizeof(buf) - 1, "%" PRId64 ".%06" PRId64 "", sec, msec);
return buf;
}
std::string Timestamp::to_formatted_string(bool show_msec) const {
char buf[32] = {0};
time_t time = static_cast<time_t>(epoch_msec_ / kMicroSecondsPerSecond);
struct tm result;
gmtime_r(&time, &result);
if (show_msec) {
int msec = static_cast<int>(epoch_msec_ % kMicroSecondsPerSecond);
snprintf(buf,
sizeof(buf),
"%04d%02d%02d %02d:%02d:%02d.%06d",
result.tm_year + 1900,
result.tm_mon + 1,
result.tm_mday,
result.tm_hour,
result.tm_min,
result.tm_sec,
msec);
}
else {
snprintf(buf,
sizeof(buf),
"%04d%02d%02d %02d:%02d:%02d",
result.tm_year + 1900,
result.tm_mon + 1,
result.tm_mday,
result.tm_hour,
result.tm_min,
result.tm_sec);
}
return buf;
}
Timestamp Timestamp::now(void) {
struct timeval tv;
gettimeofday(&tv, nullptr);
int64_t sec = tv.tv_sec;
return Timestamp(sec * kMicroSecondsPerSecond + tv.tv_usec);
}
Timestamp Timestamp::invalid(void) {
return Timestamp();
}
Timestamp Timestamp::from_unix_time(time_t t) {
return from_unix_time(t, 0);
}
Timestamp Timestamp::from_unix_time(time_t t, int msec) {
return Timestamp(static_cast<int64_t>(t) * kMicroSecondsPerSecond + msec);
}
}}
<|endoftext|>
|
<commit_before>// 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.
#include "arrow/util/tdigest.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
#include <tuple>
#include <vector>
#include "arrow/status.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace arrow {
namespace internal {
namespace {
// a numerically stable lerp is unbelievably complex
// but we are *approximating* the quantile, so let's keep it simple
double Lerp(double a, double b, double t) { return a + t * (b - a); }
// histogram bin
struct Centroid {
double mean;
double weight; // # data points in this bin
// merge with another centroid
void Merge(const Centroid& centroid) {
weight += centroid.weight;
mean += (centroid.mean - mean) * centroid.weight / weight;
}
};
// scale function K0: linear function, as baseline
struct ScalerK0 {
explicit ScalerK0(uint32_t delta) : delta_norm(delta / 2.0) {}
double K(double q) const { return delta_norm * q; }
double Q(double k) const { return k / delta_norm; }
const double delta_norm;
};
// scale function K1
struct ScalerK1 {
explicit ScalerK1(uint32_t delta) : delta_norm(delta / (2.0 * M_PI)) {}
double K(double q) const { return delta_norm * std::asin(2 * q - 1); }
double Q(double k) const { return (std::sin(k / delta_norm) + 1) / 2; }
const double delta_norm;
};
// implements t-digest merging algorithm
template <class T = ScalerK1>
class TDigestMerger : private T {
public:
explicit TDigestMerger(uint32_t delta) : T(delta) { Reset(0, nullptr); }
void Reset(double total_weight, std::vector<Centroid>* tdigest) {
total_weight_ = total_weight;
tdigest_ = tdigest;
if (tdigest_) {
tdigest_->resize(0);
}
weight_so_far_ = 0;
weight_limit_ = -1; // trigger first centroid merge
}
// merge one centroid from a sorted centroid stream
void Add(const Centroid& centroid) {
auto& td = *tdigest_;
const double weight = weight_so_far_ + centroid.weight;
if (weight <= weight_limit_) {
td.back().Merge(centroid);
} else {
const double quantile = weight_so_far_ / total_weight_;
const double next_weight_limit = total_weight_ * this->Q(this->K(quantile) + 1);
// weight limit should be strictly increasing, until the last centroid
if (next_weight_limit <= weight_limit_) {
weight_limit_ = total_weight_;
} else {
weight_limit_ = next_weight_limit;
}
td.push_back(centroid); // should never exceed capacity and trigger reallocation
}
weight_so_far_ = weight;
}
// validate k-size of a tdigest
Status Validate(const std::vector<Centroid>& tdigest, double total_weight) const {
double q_prev = 0, k_prev = this->K(0);
for (size_t i = 0; i < tdigest.size(); ++i) {
const double q = q_prev + tdigest[i].weight / total_weight;
const double k = this->K(q);
if (tdigest[i].weight != 1 && (k - k_prev) > 1.001) {
return Status::Invalid("oversized centroid: ", k - k_prev);
}
k_prev = k;
q_prev = q;
}
return Status::OK();
}
private:
double total_weight_; // total weight of this tdigest
double weight_so_far_; // accumulated weight till current bin
double weight_limit_; // max accumulated weight to move to next bin
std::vector<Centroid>* tdigest_;
};
} // namespace
class TDigest::TDigestImpl {
public:
explicit TDigestImpl(uint32_t delta)
: delta_(delta > 10 ? delta : 10), merger_(delta_) {
tdigests_[0].reserve(delta_);
tdigests_[1].reserve(delta_);
Reset();
}
void Reset() {
tdigests_[0].resize(0);
tdigests_[1].resize(0);
current_ = 0;
total_weight_ = 0;
min_ = std::numeric_limits<double>::max();
max_ = std::numeric_limits<double>::lowest();
merger_.Reset(0, nullptr);
}
Status Validate() const {
// check weight, centroid order
double total_weight = 0, prev_mean = std::numeric_limits<double>::lowest();
for (const auto& centroid : tdigests_[current_]) {
if (std::isnan(centroid.mean) || std::isnan(centroid.weight)) {
return Status::Invalid("NAN found in tdigest");
}
if (centroid.mean < prev_mean) {
return Status::Invalid("centroid mean decreases");
}
if (centroid.weight < 1) {
return Status::Invalid("invalid centroid weight");
}
prev_mean = centroid.mean;
total_weight += centroid.weight;
}
if (total_weight != total_weight_) {
return Status::Invalid("tdigest total weight mismatch");
}
// check if buffer expanded
if (tdigests_[0].capacity() > delta_ || tdigests_[1].capacity() > delta_) {
return Status::Invalid("oversized tdigest buffer");
}
// check k-size
return merger_.Validate(tdigests_[current_], total_weight_);
}
void Dump() const {
const auto& td = tdigests_[current_];
for (size_t i = 0; i < td.size(); ++i) {
std::cerr << i << ": mean = " << td[i].mean << ", weight = " << td[i].weight
<< std::endl;
}
std::cerr << "min = " << min_ << ", max = " << max_ << std::endl;
}
// merge with other tdigests
void Merge(const std::vector<const TDigestImpl*>& tdigest_impls) {
// current and end iterator
using CentroidIter = std::vector<Centroid>::const_iterator;
using CentroidIterPair = std::pair<CentroidIter, CentroidIter>;
// use a min-heap to find next minimal centroid from all tdigests
auto centroid_gt = [](const CentroidIterPair& lhs, const CentroidIterPair& rhs) {
return lhs.first->mean > rhs.first->mean;
};
using CentroidQueue =
std::priority_queue<CentroidIterPair, std::vector<CentroidIterPair>,
decltype(centroid_gt)>;
// trivial dynamic memory allocated at runtime
std::vector<CentroidIterPair> queue_buffer;
queue_buffer.reserve(tdigest_impls.size() + 1);
CentroidQueue queue(std::move(centroid_gt), std::move(queue_buffer));
const auto& this_tdigest = tdigests_[current_];
if (this_tdigest.size() > 0) {
queue.emplace(this_tdigest.cbegin(), this_tdigest.cend());
}
for (const TDigestImpl* td : tdigest_impls) {
const auto& other_tdigest = td->tdigests_[td->current_];
if (other_tdigest.size() > 0) {
queue.emplace(other_tdigest.cbegin(), other_tdigest.cend());
total_weight_ += td->total_weight_;
min_ = std::min(min_, td->min_);
max_ = std::max(max_, td->max_);
}
}
merger_.Reset(total_weight_, &tdigests_[1 - current_]);
CentroidIter current_iter, end_iter;
// do k-way merge till one buffer left
while (queue.size() > 1) {
std::tie(current_iter, end_iter) = queue.top();
merger_.Add(*current_iter);
queue.pop();
if (++current_iter != end_iter) {
queue.emplace(current_iter, end_iter);
}
}
// merge last buffer
if (!queue.empty()) {
std::tie(current_iter, end_iter) = queue.top();
while (current_iter != end_iter) {
merger_.Add(*current_iter++);
}
}
merger_.Reset(0, nullptr);
current_ = 1 - current_;
}
// merge input data with current tdigest
void MergeInput(std::vector<double>& input) {
total_weight_ += input.size();
std::sort(input.begin(), input.end());
min_ = std::min(min_, input.front());
max_ = std::max(max_, input.back());
// pick next minimal centroid from input and tdigest, feed to merger
merger_.Reset(total_weight_, &tdigests_[1 - current_]);
const auto& td = tdigests_[current_];
uint32_t tdigest_index = 0, input_index = 0;
while (tdigest_index < td.size() && input_index < input.size()) {
if (td[tdigest_index].mean < input[input_index]) {
merger_.Add(td[tdigest_index++]);
} else {
merger_.Add(Centroid{input[input_index++], 1});
}
}
while (tdigest_index < td.size()) {
merger_.Add(td[tdigest_index++]);
}
while (input_index < input.size()) {
merger_.Add(Centroid{input[input_index++], 1});
}
merger_.Reset(0, nullptr);
input.resize(0);
current_ = 1 - current_;
}
double Quantile(double q) const {
const auto& td = tdigests_[current_];
if (q < 0 || q > 1 || td.size() == 0) {
return NAN;
}
const double index = q * total_weight_;
if (index <= 1) {
return min_;
} else if (index >= total_weight_ - 1) {
return max_;
}
// find centroid contains the index
uint32_t ci = 0;
double weight_sum = 0;
for (; ci < td.size(); ++ci) {
weight_sum += td[ci].weight;
if (index <= weight_sum) {
break;
}
}
DCHECK_LT(ci, td.size());
// deviation of index from the centroid center
double diff = index + td[ci].weight / 2 - weight_sum;
// index happen to be in a unit weight centroid
if (td[ci].weight == 1 && std::abs(diff) < 0.5) {
return td[ci].mean;
}
// find adjacent centroids for interpolation
uint32_t ci_left = ci, ci_right = ci;
if (diff > 0) {
if (ci_right == td.size() - 1) {
// index larger than center of last bin
DCHECK_EQ(weight_sum, total_weight_);
const Centroid* c = &td[ci_right];
DCHECK_GE(c->weight, 2);
return Lerp(c->mean, max_, diff / (c->weight / 2));
}
++ci_right;
} else {
if (ci_left == 0) {
// index smaller than center of first bin
const Centroid* c = &td[0];
DCHECK_GE(c->weight, 2);
return Lerp(min_, c->mean, index / (c->weight / 2));
}
--ci_left;
diff += td[ci_left].weight / 2 + td[ci_right].weight / 2;
}
// interpolate from adjacent centroids
diff /= (td[ci_left].weight / 2 + td[ci_right].weight / 2);
return Lerp(td[ci_left].mean, td[ci_right].mean, diff);
}
double Mean() const {
double sum = 0;
for (const auto& centroid : tdigests_[current_]) {
sum += centroid.mean * centroid.weight;
}
return total_weight_ == 0 ? NAN : sum / total_weight_;
}
double total_weight() const { return total_weight_; }
private:
// must be delcared before merger_, see constructor initialization list
const uint32_t delta_;
TDigestMerger<> merger_;
double total_weight_;
double min_, max_;
// ping-pong buffer holds two tdigests, size = 2 * delta * sizeof(Centroid)
std::vector<Centroid> tdigests_[2];
// index of active tdigest buffer, 0 or 1
int current_;
};
TDigest::TDigest(uint32_t delta, uint32_t buffer_size) : impl_(new TDigestImpl(delta)) {
input_.reserve(buffer_size);
Reset();
}
TDigest::~TDigest() = default;
TDigest::TDigest(TDigest&&) = default;
TDigest& TDigest::operator=(TDigest&&) = default;
void TDigest::Reset() {
input_.resize(0);
impl_->Reset();
}
Status TDigest::Validate() {
MergeInput();
return impl_->Validate();
}
void TDigest::Dump() {
MergeInput();
impl_->Dump();
}
void TDigest::Merge(std::vector<TDigest>* tdigests) {
MergeInput();
std::vector<const TDigestImpl*> tdigest_impls;
tdigest_impls.reserve(tdigests->size());
for (auto& td : *tdigests) {
td.MergeInput();
tdigest_impls.push_back(td.impl_.get());
}
impl_->Merge(tdigest_impls);
}
double TDigest::Quantile(double q) {
MergeInput();
return impl_->Quantile(q);
}
double TDigest::Mean() {
MergeInput();
return impl_->Mean();
}
bool TDigest::is_empty() const {
return input_.size() == 0 && impl_->total_weight() == 0;
}
void TDigest::MergeInput() {
if (input_.size() > 0) {
impl_->MergeInput(input_); // will mutate input_
}
}
} // namespace internal
} // namespace arrow
<commit_msg>ARROW-13290: [C++] Add missing include<commit_after>// 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.
#include "arrow/util/tdigest.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <queue>
#include <tuple>
#include <vector>
#include "arrow/status.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace arrow {
namespace internal {
namespace {
// a numerically stable lerp is unbelievably complex
// but we are *approximating* the quantile, so let's keep it simple
double Lerp(double a, double b, double t) { return a + t * (b - a); }
// histogram bin
struct Centroid {
double mean;
double weight; // # data points in this bin
// merge with another centroid
void Merge(const Centroid& centroid) {
weight += centroid.weight;
mean += (centroid.mean - mean) * centroid.weight / weight;
}
};
// scale function K0: linear function, as baseline
struct ScalerK0 {
explicit ScalerK0(uint32_t delta) : delta_norm(delta / 2.0) {}
double K(double q) const { return delta_norm * q; }
double Q(double k) const { return k / delta_norm; }
const double delta_norm;
};
// scale function K1
struct ScalerK1 {
explicit ScalerK1(uint32_t delta) : delta_norm(delta / (2.0 * M_PI)) {}
double K(double q) const { return delta_norm * std::asin(2 * q - 1); }
double Q(double k) const { return (std::sin(k / delta_norm) + 1) / 2; }
const double delta_norm;
};
// implements t-digest merging algorithm
template <class T = ScalerK1>
class TDigestMerger : private T {
public:
explicit TDigestMerger(uint32_t delta) : T(delta) { Reset(0, nullptr); }
void Reset(double total_weight, std::vector<Centroid>* tdigest) {
total_weight_ = total_weight;
tdigest_ = tdigest;
if (tdigest_) {
tdigest_->resize(0);
}
weight_so_far_ = 0;
weight_limit_ = -1; // trigger first centroid merge
}
// merge one centroid from a sorted centroid stream
void Add(const Centroid& centroid) {
auto& td = *tdigest_;
const double weight = weight_so_far_ + centroid.weight;
if (weight <= weight_limit_) {
td.back().Merge(centroid);
} else {
const double quantile = weight_so_far_ / total_weight_;
const double next_weight_limit = total_weight_ * this->Q(this->K(quantile) + 1);
// weight limit should be strictly increasing, until the last centroid
if (next_weight_limit <= weight_limit_) {
weight_limit_ = total_weight_;
} else {
weight_limit_ = next_weight_limit;
}
td.push_back(centroid); // should never exceed capacity and trigger reallocation
}
weight_so_far_ = weight;
}
// validate k-size of a tdigest
Status Validate(const std::vector<Centroid>& tdigest, double total_weight) const {
double q_prev = 0, k_prev = this->K(0);
for (size_t i = 0; i < tdigest.size(); ++i) {
const double q = q_prev + tdigest[i].weight / total_weight;
const double k = this->K(q);
if (tdigest[i].weight != 1 && (k - k_prev) > 1.001) {
return Status::Invalid("oversized centroid: ", k - k_prev);
}
k_prev = k;
q_prev = q;
}
return Status::OK();
}
private:
double total_weight_; // total weight of this tdigest
double weight_so_far_; // accumulated weight till current bin
double weight_limit_; // max accumulated weight to move to next bin
std::vector<Centroid>* tdigest_;
};
} // namespace
class TDigest::TDigestImpl {
public:
explicit TDigestImpl(uint32_t delta)
: delta_(delta > 10 ? delta : 10), merger_(delta_) {
tdigests_[0].reserve(delta_);
tdigests_[1].reserve(delta_);
Reset();
}
void Reset() {
tdigests_[0].resize(0);
tdigests_[1].resize(0);
current_ = 0;
total_weight_ = 0;
min_ = std::numeric_limits<double>::max();
max_ = std::numeric_limits<double>::lowest();
merger_.Reset(0, nullptr);
}
Status Validate() const {
// check weight, centroid order
double total_weight = 0, prev_mean = std::numeric_limits<double>::lowest();
for (const auto& centroid : tdigests_[current_]) {
if (std::isnan(centroid.mean) || std::isnan(centroid.weight)) {
return Status::Invalid("NAN found in tdigest");
}
if (centroid.mean < prev_mean) {
return Status::Invalid("centroid mean decreases");
}
if (centroid.weight < 1) {
return Status::Invalid("invalid centroid weight");
}
prev_mean = centroid.mean;
total_weight += centroid.weight;
}
if (total_weight != total_weight_) {
return Status::Invalid("tdigest total weight mismatch");
}
// check if buffer expanded
if (tdigests_[0].capacity() > delta_ || tdigests_[1].capacity() > delta_) {
return Status::Invalid("oversized tdigest buffer");
}
// check k-size
return merger_.Validate(tdigests_[current_], total_weight_);
}
void Dump() const {
const auto& td = tdigests_[current_];
for (size_t i = 0; i < td.size(); ++i) {
std::cerr << i << ": mean = " << td[i].mean << ", weight = " << td[i].weight
<< std::endl;
}
std::cerr << "min = " << min_ << ", max = " << max_ << std::endl;
}
// merge with other tdigests
void Merge(const std::vector<const TDigestImpl*>& tdigest_impls) {
// current and end iterator
using CentroidIter = std::vector<Centroid>::const_iterator;
using CentroidIterPair = std::pair<CentroidIter, CentroidIter>;
// use a min-heap to find next minimal centroid from all tdigests
auto centroid_gt = [](const CentroidIterPair& lhs, const CentroidIterPair& rhs) {
return lhs.first->mean > rhs.first->mean;
};
using CentroidQueue =
std::priority_queue<CentroidIterPair, std::vector<CentroidIterPair>,
decltype(centroid_gt)>;
// trivial dynamic memory allocated at runtime
std::vector<CentroidIterPair> queue_buffer;
queue_buffer.reserve(tdigest_impls.size() + 1);
CentroidQueue queue(std::move(centroid_gt), std::move(queue_buffer));
const auto& this_tdigest = tdigests_[current_];
if (this_tdigest.size() > 0) {
queue.emplace(this_tdigest.cbegin(), this_tdigest.cend());
}
for (const TDigestImpl* td : tdigest_impls) {
const auto& other_tdigest = td->tdigests_[td->current_];
if (other_tdigest.size() > 0) {
queue.emplace(other_tdigest.cbegin(), other_tdigest.cend());
total_weight_ += td->total_weight_;
min_ = std::min(min_, td->min_);
max_ = std::max(max_, td->max_);
}
}
merger_.Reset(total_weight_, &tdigests_[1 - current_]);
CentroidIter current_iter, end_iter;
// do k-way merge till one buffer left
while (queue.size() > 1) {
std::tie(current_iter, end_iter) = queue.top();
merger_.Add(*current_iter);
queue.pop();
if (++current_iter != end_iter) {
queue.emplace(current_iter, end_iter);
}
}
// merge last buffer
if (!queue.empty()) {
std::tie(current_iter, end_iter) = queue.top();
while (current_iter != end_iter) {
merger_.Add(*current_iter++);
}
}
merger_.Reset(0, nullptr);
current_ = 1 - current_;
}
// merge input data with current tdigest
void MergeInput(std::vector<double>& input) {
total_weight_ += input.size();
std::sort(input.begin(), input.end());
min_ = std::min(min_, input.front());
max_ = std::max(max_, input.back());
// pick next minimal centroid from input and tdigest, feed to merger
merger_.Reset(total_weight_, &tdigests_[1 - current_]);
const auto& td = tdigests_[current_];
uint32_t tdigest_index = 0, input_index = 0;
while (tdigest_index < td.size() && input_index < input.size()) {
if (td[tdigest_index].mean < input[input_index]) {
merger_.Add(td[tdigest_index++]);
} else {
merger_.Add(Centroid{input[input_index++], 1});
}
}
while (tdigest_index < td.size()) {
merger_.Add(td[tdigest_index++]);
}
while (input_index < input.size()) {
merger_.Add(Centroid{input[input_index++], 1});
}
merger_.Reset(0, nullptr);
input.resize(0);
current_ = 1 - current_;
}
double Quantile(double q) const {
const auto& td = tdigests_[current_];
if (q < 0 || q > 1 || td.size() == 0) {
return NAN;
}
const double index = q * total_weight_;
if (index <= 1) {
return min_;
} else if (index >= total_weight_ - 1) {
return max_;
}
// find centroid contains the index
uint32_t ci = 0;
double weight_sum = 0;
for (; ci < td.size(); ++ci) {
weight_sum += td[ci].weight;
if (index <= weight_sum) {
break;
}
}
DCHECK_LT(ci, td.size());
// deviation of index from the centroid center
double diff = index + td[ci].weight / 2 - weight_sum;
// index happen to be in a unit weight centroid
if (td[ci].weight == 1 && std::abs(diff) < 0.5) {
return td[ci].mean;
}
// find adjacent centroids for interpolation
uint32_t ci_left = ci, ci_right = ci;
if (diff > 0) {
if (ci_right == td.size() - 1) {
// index larger than center of last bin
DCHECK_EQ(weight_sum, total_weight_);
const Centroid* c = &td[ci_right];
DCHECK_GE(c->weight, 2);
return Lerp(c->mean, max_, diff / (c->weight / 2));
}
++ci_right;
} else {
if (ci_left == 0) {
// index smaller than center of first bin
const Centroid* c = &td[0];
DCHECK_GE(c->weight, 2);
return Lerp(min_, c->mean, index / (c->weight / 2));
}
--ci_left;
diff += td[ci_left].weight / 2 + td[ci_right].weight / 2;
}
// interpolate from adjacent centroids
diff /= (td[ci_left].weight / 2 + td[ci_right].weight / 2);
return Lerp(td[ci_left].mean, td[ci_right].mean, diff);
}
double Mean() const {
double sum = 0;
for (const auto& centroid : tdigests_[current_]) {
sum += centroid.mean * centroid.weight;
}
return total_weight_ == 0 ? NAN : sum / total_weight_;
}
double total_weight() const { return total_weight_; }
private:
// must be delcared before merger_, see constructor initialization list
const uint32_t delta_;
TDigestMerger<> merger_;
double total_weight_;
double min_, max_;
// ping-pong buffer holds two tdigests, size = 2 * delta * sizeof(Centroid)
std::vector<Centroid> tdigests_[2];
// index of active tdigest buffer, 0 or 1
int current_;
};
TDigest::TDigest(uint32_t delta, uint32_t buffer_size) : impl_(new TDigestImpl(delta)) {
input_.reserve(buffer_size);
Reset();
}
TDigest::~TDigest() = default;
TDigest::TDigest(TDigest&&) = default;
TDigest& TDigest::operator=(TDigest&&) = default;
void TDigest::Reset() {
input_.resize(0);
impl_->Reset();
}
Status TDigest::Validate() {
MergeInput();
return impl_->Validate();
}
void TDigest::Dump() {
MergeInput();
impl_->Dump();
}
void TDigest::Merge(std::vector<TDigest>* tdigests) {
MergeInput();
std::vector<const TDigestImpl*> tdigest_impls;
tdigest_impls.reserve(tdigests->size());
for (auto& td : *tdigests) {
td.MergeInput();
tdigest_impls.push_back(td.impl_.get());
}
impl_->Merge(tdigest_impls);
}
double TDigest::Quantile(double q) {
MergeInput();
return impl_->Quantile(q);
}
double TDigest::Mean() {
MergeInput();
return impl_->Mean();
}
bool TDigest::is_empty() const {
return input_.size() == 0 && impl_->total_weight() == 0;
}
void TDigest::MergeInput() {
if (input_.size() > 0) {
impl_->MergeInput(input_); // will mutate input_
}
}
} // namespace internal
} // namespace arrow
<|endoftext|>
|
<commit_before>#include "ImagePanel.h"
#include <set>
using namespace std;
wxBitmapPtr ToBitmap( const LinearImage& image )
{
vector< unsigned char > color, alpha;
image.GetSrgb( color, alpha );
return wxBitmapPtr( new wxBitmap(
alpha.empty()
? wxImage( image.GetWidth(), image.GetHeight(), &color[0], true )
: wxImage( image.GetWidth(), image.GetHeight(), &color[0], &alpha[0], true )
) );
}
vector< wxRect > GetCoverage( const wxRect& viewport, const wxRect& canvas, const wxSize& gridSize )
{
const wxRect clippedViewport( canvas.Intersect( viewport ) );
vector< wxRect > coverage;
const int top = clippedViewport.GetTop() / gridSize.y;
const int bottom = clippedViewport.GetBottom() / gridSize.y;
const int left = clippedViewport.GetLeft() / gridSize.x;
const int right = clippedViewport.GetRight() / gridSize.x;
for( int y = top; y <= bottom; ++y )
{
for( int x = left; x <= right; ++x )
{
const wxRect candidate( x * gridSize.x, y * gridSize.y, gridSize.x, gridSize.y );
const wxRect clipped( canvas.Intersect( candidate ) );
coverage.push_back( clipped );
}
}
return coverage;
}
template< typename T >
T clamp( const T& val, const T& minVal, const T& maxVal )
{
if( val < minVal ) return minVal;
if( val > maxVal ) return maxVal;
return val;
}
wxPoint ClampPosition( const wxRect& viewport, const wxRect& extent )
{
const wxSize delta( viewport.GetSize() - extent.GetSize() );
wxPoint newTopLeft( viewport.GetPosition() );
if( delta.x < 0 )
{
// viewport smaller than extent
int minX = extent.GetPosition().x;
int maxX = ( extent.GetPosition().x + extent.GetSize().x ) - viewport.GetSize().x;
newTopLeft.x = clamp( newTopLeft.x, minX, maxX );
}
else
{
// viewport larger than extent
newTopLeft.x = extent.GetPosition().x - ( delta.x / 2 );
}
if( delta.y < 0 )
{
// viewport smaller than extent
int minY = extent.GetPosition().y;
int maxY = ( extent.GetPosition().y + extent.GetSize().y ) - viewport.GetSize().y;
newTopLeft.y = clamp( newTopLeft.y, minY, maxY );
}
else
{
// viewport larger than extent
newTopLeft.y = extent.GetPosition().y - ( delta.y / 2 );
}
return newTopLeft;
}
wxBitmapPtr GetScaledSubrect( const LinearImage& src, auto_ptr< Resampler > resamplers[ 4 ], const wxRect& rect )
{
LinearImage dst( rect.GetWidth(), rect.GetHeight(), src.GetNumChannels() == 4 ? true : false, NULL );
for( size_t c = 0; c < src.GetNumChannels(); ++c )
{
resamplers[ c ]->StartResample
(
rect.x, rect.y,
rect.GetWidth(), rect.GetHeight()
);
}
size_t dstY = 0;
for( size_t y = 0; y < src.GetHeight(); ++y )
{
for( size_t c = 0; c < src.GetNumChannels(); ++c )
{
resamplers[ c ]->PutLine( src.GetRow( c, y ) );
}
while( true )
{
bool missedLine = false;
for( size_t c = 0; c < src.GetNumChannels(); ++c )
{
const float* line = resamplers[ c ]->GetLine();
if( NULL == line )
{
missedLine = true;
break;
}
copy( line, line + dst.GetWidth(), dst.GetRow( c, dstY ) );
}
if( missedLine )
{
break;
}
dstY++;
}
}
return ToBitmap( dst );
}
wxImagePanel::wxImagePanel( wxWindow* parent )
: wxWindow( parent, wxID_ANY )
, mPosition( 0, 0 )
, mScale( 1.0 )
{
// for wxAutoBufferedPaintDC
SetBackgroundStyle( wxBG_STYLE_PAINT );
SetBackgroundColour( *wxBLACK );
Bind( wxEVT_SIZE , &wxImagePanel::OnSize , this );
Bind( wxEVT_PAINT , &wxImagePanel::OnPaint , this );
Bind( wxEVT_KEY_DOWN , &wxImagePanel::OnKeyDown , this );
Bind( wxEVT_KEY_UP , &wxImagePanel::OnKeyUp , this );
Bind( wxEVT_LEFT_DOWN , &wxImagePanel::OnButtonDown , this );
Bind( wxEVT_RIGHT_DOWN , &wxImagePanel::OnButtonDown , this );
Bind( wxEVT_MIDDLE_DOWN , &wxImagePanel::OnButtonDown , this );
Bind( wxEVT_MOTION , &wxImagePanel::OnMotion , this );
}
void wxImagePanel::OnSize( wxSizeEvent& event )
{
mPosition = ClampPosition( mPosition );
// invalidate entire panel since we need to redraw everything
Refresh( true );
// skip the event so sizers can do their thing
event.Skip();
}
void wxImagePanel::OnButtonDown( wxMouseEvent& event )
{
if( event.LeftDown() )
{
mLeftPositionStart = mPosition;
mLeftMouseStart = event.GetPosition();
}
}
void wxImagePanel::OnMotion( wxMouseEvent& event )
{
if( event.LeftIsDown() && event.Dragging() )
{
wxPoint newPos( mLeftPositionStart - ( event.GetPosition() - mLeftMouseStart ) );
if( newPos != mPosition )
{
ScrollToPosition( newPos );
}
}
}
void wxImagePanel::OnIdle( wxIdleEvent& event )
{
wxPoint newPos( mPosition );
const int step = 1;
if( wxGetKeyState( WXK_LEFT ) ) newPos += step * wxPoint( -1, 0 );
if( wxGetKeyState( WXK_RIGHT ) ) newPos += step * wxPoint( 1, 0 );
if( wxGetKeyState( WXK_UP ) ) newPos += step * wxPoint( 0, -1 );
if( wxGetKeyState( WXK_DOWN ) ) newPos += step * wxPoint( 0, 1 );
if( newPos == mPosition )
{
Unbind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );
return;
}
ScrollToPosition( newPos );
//event.RequestMore( true );
//wxMilliSleep( 1 );
}
void wxImagePanel::OnKeyDown( wxKeyEvent& event )
{
switch( event.GetKeyCode() )
{
case WXK_LEFT:
case WXK_RIGHT:
case WXK_UP:
case WXK_DOWN:
Bind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );
break;
default:
break;
}
}
wxPoint wxImagePanel::ClampPosition( const wxPoint& newPos )
{
if( NULL == mImage )
{
return newPos;
}
const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );
return ::ClampPosition
(
wxRect( newPos, GetSize() ),
wxRect( wxPoint(0,0), scaledSize )
);
}
void wxImagePanel::OnKeyUp( wxKeyEvent& event )
{
switch( event.GetKeyCode() )
{
case WXK_ADD:
case WXK_NUMPAD_ADD:
SetScale( mScale * 1.1 );
break;
case WXK_SUBTRACT:
case WXK_NUMPAD_SUBTRACT:
SetScale( mScale / 1.1 );
break;
default:
break;
}
}
void wxImagePanel::ScrollToPosition( const wxPoint& newPos )
{
const wxPoint clamped = ClampPosition( newPos );
wxPoint delta( clamped - mPosition );
ScrollWindow( -delta.x, -delta.y );
mPosition = clamped;
}
void wxImagePanel::OnPaint( wxPaintEvent& event )
{
wxPaintDC dc(this);
//wxAutoBufferedPaintDC dc( this );
dc.SetDeviceOrigin( -mPosition.x, -mPosition.y );
dc.Clear();
if( NULL == mImage )
{
return;
}
const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );
const wxRect scaledRect( wxPoint( 0, 0 ), scaledSize );
const wxSize gridSize( TILE_SIZE, TILE_SIZE );
// get the set of tiles we need to draw
set< wxRect, wxRectCmp > covered;
for( wxRegionIterator upd( GetUpdateRegion() ); upd.HaveRects(); ++upd )
{
wxRect rect( upd.GetRect() );
rect.SetPosition( rect.GetPosition() + mPosition );
const vector< wxRect > ret = GetCoverage( rect, scaledRect, gridSize );
covered.insert( ret.begin(), ret.end() );
}
for( const wxRect& rect : covered )
{
map< wxRect, wxBitmapPtr >::iterator it = mBitmapCache.find( rect );
if( mBitmapCache.end() == it )
{
it = mBitmapCache.insert( make_pair( rect, GetScaledSubrect( *mImage, mResamplers, rect ) ) ).first;
}
dc.DrawBitmap( *(it->second), rect.GetPosition() );
}
}
void wxImagePanel::SetImage( const LinearImage* newImage )
{
mImage = newImage;
SetScale( mScale );
mPosition = ClampPosition( mPosition );
}
void wxImagePanel::SetScale( const double newScale )
{
mScale = newScale;
mBitmapCache.clear();
mPosition = ClampPosition( mPosition );
// invalidate entire panel since we need to redraw everything
Refresh( true );
if( NULL == mImage )
{
return;
}
// regenerate resamplers
mContribLists.reset( new Resampler::ContribLists
(
mImage->GetWidth(), mImage->GetHeight(),
mImage->GetWidth() * mScale, mImage->GetHeight() * mScale
) );
for( size_t i = 0; i < 4; ++i )
{
mResamplers[ i ].reset( new Resampler( *mContribLists ) );
}
}<commit_msg>Add fit-to-window and reset zoom controls<commit_after>#include "ImagePanel.h"
#include <set>
using namespace std;
wxBitmapPtr ToBitmap( const LinearImage& image )
{
vector< unsigned char > color, alpha;
image.GetSrgb( color, alpha );
return wxBitmapPtr( new wxBitmap(
alpha.empty()
? wxImage( image.GetWidth(), image.GetHeight(), &color[0], true )
: wxImage( image.GetWidth(), image.GetHeight(), &color[0], &alpha[0], true )
) );
}
vector< wxRect > GetCoverage( const wxRect& viewport, const wxRect& canvas, const wxSize& gridSize )
{
const wxRect clippedViewport( canvas.Intersect( viewport ) );
vector< wxRect > coverage;
const int top = clippedViewport.GetTop() / gridSize.y;
const int bottom = clippedViewport.GetBottom() / gridSize.y;
const int left = clippedViewport.GetLeft() / gridSize.x;
const int right = clippedViewport.GetRight() / gridSize.x;
for( int y = top; y <= bottom; ++y )
{
for( int x = left; x <= right; ++x )
{
const wxRect candidate( x * gridSize.x, y * gridSize.y, gridSize.x, gridSize.y );
const wxRect clipped( canvas.Intersect( candidate ) );
coverage.push_back( clipped );
}
}
return coverage;
}
template< typename T >
T clamp( const T& val, const T& minVal, const T& maxVal )
{
if( val < minVal ) return minVal;
if( val > maxVal ) return maxVal;
return val;
}
wxPoint ClampPosition( const wxRect& viewport, const wxRect& extent )
{
const wxSize delta( viewport.GetSize() - extent.GetSize() );
wxPoint newTopLeft( viewport.GetPosition() );
if( delta.x < 0 )
{
// viewport smaller than extent
int minX = extent.GetPosition().x;
int maxX = ( extent.GetPosition().x + extent.GetSize().x ) - viewport.GetSize().x;
newTopLeft.x = clamp( newTopLeft.x, minX, maxX );
}
else
{
// viewport larger than extent
newTopLeft.x = extent.GetPosition().x - ( delta.x / 2 );
}
if( delta.y < 0 )
{
// viewport smaller than extent
int minY = extent.GetPosition().y;
int maxY = ( extent.GetPosition().y + extent.GetSize().y ) - viewport.GetSize().y;
newTopLeft.y = clamp( newTopLeft.y, minY, maxY );
}
else
{
// viewport larger than extent
newTopLeft.y = extent.GetPosition().y - ( delta.y / 2 );
}
return newTopLeft;
}
wxBitmapPtr GetScaledSubrect( const LinearImage& src, auto_ptr< Resampler > resamplers[ 4 ], const wxRect& rect )
{
LinearImage dst( rect.GetWidth(), rect.GetHeight(), src.GetNumChannels() == 4 ? true : false, NULL );
for( size_t c = 0; c < src.GetNumChannels(); ++c )
{
resamplers[ c ]->StartResample
(
rect.x, rect.y,
rect.GetWidth(), rect.GetHeight()
);
}
size_t dstY = 0;
for( size_t y = 0; y < src.GetHeight(); ++y )
{
for( size_t c = 0; c < src.GetNumChannels(); ++c )
{
resamplers[ c ]->PutLine( src.GetRow( c, y ) );
}
while( true )
{
bool missedLine = false;
for( size_t c = 0; c < src.GetNumChannels(); ++c )
{
const float* line = resamplers[ c ]->GetLine();
if( NULL == line )
{
missedLine = true;
break;
}
copy( line, line + dst.GetWidth(), dst.GetRow( c, dstY ) );
}
if( missedLine )
{
break;
}
dstY++;
}
}
return ToBitmap( dst );
}
wxImagePanel::wxImagePanel( wxWindow* parent )
: wxWindow( parent, wxID_ANY )
, mPosition( 0, 0 )
, mScale( 1.0 )
{
// for wxAutoBufferedPaintDC
SetBackgroundStyle( wxBG_STYLE_PAINT );
SetBackgroundColour( *wxBLACK );
Bind( wxEVT_SIZE , &wxImagePanel::OnSize , this );
Bind( wxEVT_PAINT , &wxImagePanel::OnPaint , this );
Bind( wxEVT_KEY_DOWN , &wxImagePanel::OnKeyDown , this );
Bind( wxEVT_KEY_UP , &wxImagePanel::OnKeyUp , this );
Bind( wxEVT_LEFT_DOWN , &wxImagePanel::OnButtonDown , this );
Bind( wxEVT_RIGHT_DOWN , &wxImagePanel::OnButtonDown , this );
Bind( wxEVT_MIDDLE_DOWN , &wxImagePanel::OnButtonDown , this );
Bind( wxEVT_MOTION , &wxImagePanel::OnMotion , this );
}
void wxImagePanel::OnSize( wxSizeEvent& event )
{
mPosition = ClampPosition( mPosition );
// invalidate entire panel since we need to redraw everything
Refresh( true );
// skip the event so sizers can do their thing
event.Skip();
}
void wxImagePanel::OnButtonDown( wxMouseEvent& event )
{
if( event.LeftDown() )
{
mLeftPositionStart = mPosition;
mLeftMouseStart = event.GetPosition();
}
}
void wxImagePanel::OnMotion( wxMouseEvent& event )
{
if( event.LeftIsDown() && event.Dragging() )
{
wxPoint newPos( mLeftPositionStart - ( event.GetPosition() - mLeftMouseStart ) );
if( newPos != mPosition )
{
ScrollToPosition( newPos );
}
}
}
void wxImagePanel::OnIdle( wxIdleEvent& event )
{
wxPoint newPos( mPosition );
const int step = 1;
if( wxGetKeyState( WXK_LEFT ) ) newPos += step * wxPoint( -1, 0 );
if( wxGetKeyState( WXK_RIGHT ) ) newPos += step * wxPoint( 1, 0 );
if( wxGetKeyState( WXK_UP ) ) newPos += step * wxPoint( 0, -1 );
if( wxGetKeyState( WXK_DOWN ) ) newPos += step * wxPoint( 0, 1 );
if( newPos == mPosition )
{
Unbind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );
return;
}
ScrollToPosition( newPos );
//event.RequestMore( true );
//wxMilliSleep( 1 );
}
void wxImagePanel::OnKeyDown( wxKeyEvent& event )
{
switch( event.GetKeyCode() )
{
case WXK_LEFT:
case WXK_RIGHT:
case WXK_UP:
case WXK_DOWN:
Bind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );
break;
default:
break;
}
}
wxPoint wxImagePanel::ClampPosition( const wxPoint& newPos )
{
if( NULL == mImage )
{
return newPos;
}
const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );
return ::ClampPosition
(
wxRect( newPos, GetSize() ),
wxRect( wxPoint(0,0), scaledSize )
);
}
void wxImagePanel::OnKeyUp( wxKeyEvent& event )
{
if( NULL == mImage )
{
return;
}
switch( event.GetKeyCode() )
{
case WXK_ADD:
case WXK_NUMPAD_ADD:
SetScale( mScale * 1.1 );
break;
case WXK_SUBTRACT:
case WXK_NUMPAD_SUBTRACT:
SetScale( mScale / 1.1 );
break;
case WXK_NUMPAD_MULTIPLY:
{
const int iMax = max( mImage->GetWidth(), mImage->GetHeight() );
const int wMin = min( GetSize().x, GetSize().y );
SetScale( wMin / (double)iMax );
}
break;
case WXK_NUMPAD_DIVIDE:
SetScale( 1.0 );
break;
default:
break;
}
}
void wxImagePanel::ScrollToPosition( const wxPoint& newPos )
{
const wxPoint clamped = ClampPosition( newPos );
wxPoint delta( clamped - mPosition );
ScrollWindow( -delta.x, -delta.y );
mPosition = clamped;
}
void wxImagePanel::OnPaint( wxPaintEvent& event )
{
wxPaintDC dc(this);
//wxAutoBufferedPaintDC dc( this );
dc.SetDeviceOrigin( -mPosition.x, -mPosition.y );
dc.Clear();
if( NULL == mImage )
{
return;
}
const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );
const wxRect scaledRect( wxPoint( 0, 0 ), scaledSize );
const wxSize gridSize( TILE_SIZE, TILE_SIZE );
// get the set of tiles we need to draw
set< wxRect, wxRectCmp > covered;
for( wxRegionIterator upd( GetUpdateRegion() ); upd.HaveRects(); ++upd )
{
wxRect rect( upd.GetRect() );
rect.SetPosition( rect.GetPosition() + mPosition );
const vector< wxRect > ret = GetCoverage( rect, scaledRect, gridSize );
covered.insert( ret.begin(), ret.end() );
}
for( const wxRect& rect : covered )
{
map< wxRect, wxBitmapPtr >::iterator it = mBitmapCache.find( rect );
if( mBitmapCache.end() == it )
{
it = mBitmapCache.insert( make_pair( rect, GetScaledSubrect( *mImage, mResamplers, rect ) ) ).first;
}
dc.DrawBitmap( *(it->second), rect.GetPosition() );
}
}
void wxImagePanel::SetImage( const LinearImage* newImage )
{
mImage = newImage;
SetScale( mScale );
mPosition = ClampPosition( mPosition );
}
void wxImagePanel::SetScale( const double newScale )
{
mScale = newScale;
mBitmapCache.clear();
mPosition = ClampPosition( mPosition );
// invalidate entire panel since we need to redraw everything
Refresh( true );
if( NULL == mImage )
{
return;
}
// regenerate resamplers
mContribLists.reset( new Resampler::ContribLists
(
mImage->GetWidth(), mImage->GetHeight(),
mImage->GetWidth() * mScale, mImage->GetHeight() * mScale
) );
for( size_t i = 0; i < 4; ++i )
{
mResamplers[ i ].reset( new Resampler( *mContribLists ) );
}
}<|endoftext|>
|
<commit_before>#ifndef __GLYPH_HPP_INCLUDED
#define __GLYPH_HPP_INCLUDED
#include "species_or_glyph.hpp"
#include "text3D.hpp"
#include "vector_font.hpp"
#include "render_templates.hpp"
#include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include standard headers
#include <queue> // std::queue
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
namespace model
{
class Object;
class Glyph
{
public:
// constructor.
Glyph(GlyphStruct glyph_struct);
// destructor.
// glyphs should be destroyed only by destroying the entire `VectorFont`.
~Glyph();
// this method sets a object pointer.
void set_object_pointer(uint32_t childID, void* parent_pointer);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
uint32_t get_objectID();
glm::vec3 light_position; // light position.
// The rest fields are created in the constructor.
uint32_t image_width;
uint32_t image_height;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<uint32_t> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
model::VectorFont* parent_pointer; // pointer to `VectorFont`.
friend class Object;
template<class T1>
friend void render_children(std::vector<void*> &child_pointer_vector);
template<class T1>
friend void hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<void*> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue);
template<class T1>
friend void render_species_or_glyph(T1 species_or_glyph_pointer);
private:
void bind_to_parent();
// this method renders all objects of this species.
void render();
uint32_t childID; // glyph ID, returned by `model::VectorFont->get_glyphID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
std::string* glyph_name_pointer;
std::vector<void*> object_pointer_vector;
std::queue<uint32_t> free_objectID_queue;
};
}
#endif
<commit_msg>`class Glyph`: new variables and one new `#include`.<commit_after>#ifndef __GLYPH_HPP_INCLUDED
#define __GLYPH_HPP_INCLUDED
#include "species_or_glyph.hpp"
#include "text3D.hpp"
#include "vector_font.hpp"
#include "render_templates.hpp"
#include "cpp/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <queue> // std::queue
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
namespace model
{
class Object;
class Glyph
{
public:
// constructor.
Glyph(GlyphStruct glyph_struct);
// destructor.
// glyphs should be destroyed only by destroying the entire `VectorFont`.
~Glyph();
// this method sets a object pointer.
void set_object_pointer(uint32_t childID, void* parent_pointer);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
uint32_t get_objectID();
glm::vec3 light_position; // light position.
// The rest fields are created in the constructor.
uint32_t image_width;
uint32_t image_height;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<uint32_t> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
model::VectorFont* parent_pointer; // pointer to `VectorFont`.
friend class Object;
template<class T1>
friend void render_children(std::vector<void*> &child_pointer_vector);
template<class T1>
friend void hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<void*> &child_pointer_vector, std::queue<uint32_t> &free_childID_queue);
template<class T1>
friend void render_species_or_glyph(T1 species_or_glyph_pointer);
private:
void bind_to_parent();
// this method renders all objects of this species.
void render();
uint32_t childID; // glyph ID, returned by `model::VectorFont->get_glyphID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
std::vector<std::vector<glm::vec2>>* glyph_vertex_data;
std::string* glyph_name_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
std::string* unicode_string_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
std::vector<void*> object_pointer_vector;
std::queue<uint32_t> free_objectID_queue;
};
}
#endif
<|endoftext|>
|
<commit_before>#include "simplesp.h"
#include "spex/spgl.h"
using namespace sp;
class ModelTrackGUI : public BaseWindow {
// camera
CamParam m_cam;
// image
Mem2<Col3> m_img;
// map
Mem2<VecPN3> m_map;
// model
Mem1<Mesh3> m_model;
// pose
Pose m_pose;
// pose model
Mem1<PoseModel> m_pmodels;
// mode
int m_mode;
private:
void help() {
printf("'r' key : render\n");
printf("'c' key : track 2d\n");
printf("'v' key : track 3d\n");
printf("'ESC' key : exit\n");
printf("\n");
}
virtual void init() {
help();
m_mode = 0;
m_cam = getCamParam(640, 480);
if (loadBunny(m_model, SP_DATA_DIR "/stanford/bun_zipper.ply") == false) {
// if could not find stanford bunny, load dummy model
loadGeodesicDorm(m_model, 100.0, 1);
}
const double distance = getModelDistance(m_model, m_cam);
printf("please wait...\n");
const int level = 2;
m_pmodels = getPoseModel(m_model, distance, level);
m_pose = getPose(getVec(0.0, 0.0, distance));
}
virtual void keyFun(int key, int scancode, int action, int mods) {
if (m_keyAction[GLFW_KEY_R] == 1) {
m_map.zero();
renderVecPN(m_map, m_cam, m_pose, m_model);
cnvNormalToImg(m_img, m_map);
}
if (m_keyAction[GLFW_KEY_C] > 0) {
if (m_img.size() == 0) return;
m_mode = 0;
Mem2<Byte> gry;
cnvImg(gry, m_img);
track2D(m_pose, gry, m_cam, m_pmodels, 50, 1);
}
if (m_keyAction[GLFW_KEY_V] > 0) {
if (m_map.size() == 0) return;
m_mode = 1;
track3D(m_pose, m_map, m_cam, m_pmodels, 1);
}
}
virtual void display() {
// render image
{
glLoadView2D(m_cam, m_viewPos, m_viewScale);
glRenderImg(m_img);
}
// render model
{
glLoadView3D(m_cam, m_viewPos, m_viewScale);
glClear(GL_DEPTH_BUFFER_BIT);
{
glLoadMatrix(m_pose);
glRenderOutline(m_model);
// render points
glPointSize(5.f);
glBegin(GL_POINTS);
glColor3f(0.2f, 0.7f, 0.2f);
const int id = findPoseModel(m_pmodels, m_pose);
if (m_mode == 0) {
for (int i = 0; i < m_pmodels[id].edges.size(); i++) {
glVertex(m_pmodels[id].edges[i].pos);
}
}
else {
for (int i = 0; i < m_pmodels[id].pnts.size(); i++) {
glVertex(m_pmodels[id].pnts[i].pos);
}
}
glEnd();
}
renderAxis();
}
}
void renderAxis() {
glLoadMatrix(m_pose);
glLineWidth(2.f);
glBegin(GL_LINES);
glAxis(100.0);
glEnd();
}
virtual void mousePos(double x, double y) {
controlPose(m_pose, m_mouse, m_wcam, m_viewScale);
}
virtual void mouseScroll(double x, double y) {
controlPose(m_pose, m_mouse, m_wcam, m_viewScale);
}
};
int main(){
ModelTrackGUI win;
win.execute("modeltrack", 800, 600);
return 0;
}<commit_msg>modify gl render<commit_after>#include "simplesp.h"
#include "spex/spgl.h"
using namespace sp;
class ModelTrackGUI : public BaseWindow {
// camera
CamParam m_cam;
// image
Mem2<Col3> m_img;
// map
Mem2<VecPN3> m_map;
// model
Mem1<Mesh3> m_model;
// pose
Pose m_pose;
// pose model
Mem1<PoseModel> m_pmodels;
// mode
int m_mode;
private:
void help() {
printf("'r' key : render\n");
printf("'c' key : track 2d\n");
printf("'v' key : track 3d\n");
printf("'ESC' key : exit\n");
printf("\n");
}
virtual void init() {
help();
m_mode = 0;
m_cam = getCamParam(640, 480);
if (loadBunny(m_model, SP_DATA_DIR "/stanford/bun_zipper.ply") == false) {
// if could not find stanford bunny, load dummy model
loadGeodesicDorm(m_model, 100.0, 1);
}
const double distance = getModelDistance(m_model, m_cam);
printf("please wait...\n");
const int level = 2;
m_pmodels = getPoseModel(m_model, distance, level);
m_pose = getPose(getVec(0.0, 0.0, distance));
}
virtual void keyFun(int key, int scancode, int action, int mods) {
if (m_keyAction[GLFW_KEY_R] == 1) {
m_map.zero();
renderVecPN(m_map, m_cam, m_pose, m_model);
cnvNormalToImg(m_img, m_map);
}
if (m_keyAction[GLFW_KEY_C] > 0) {
if (m_img.size() == 0) return;
m_mode = 0;
Mem2<Byte> gry;
cnvImg(gry, m_img);
track2D(m_pose, gry, m_cam, m_pmodels, 50, 1);
}
if (m_keyAction[GLFW_KEY_V] > 0) {
if (m_map.size() == 0) return;
m_mode = 1;
track3D(m_pose, m_map, m_cam, m_pmodels, 1);
}
}
virtual void display() {
// render image
{
glLoadView2D(m_cam, m_viewPos, m_viewScale);
glRenderImg(m_img);
}
// render model
{
glLoadView3D(m_cam, m_viewPos, m_viewScale);
glLoadMatrix(m_pose);
glClear(GL_DEPTH_BUFFER_BIT);
{
glRenderOutline(m_model);
}
glClear(GL_DEPTH_BUFFER_BIT);
{
// render points
glPointSize(5.f);
glBegin(GL_POINTS);
glColor3f(0.2f, 0.7f, 0.2f);
const int id = findPoseModel(m_pmodels, m_pose);
if (m_mode == 0) {
for (int i = 0; i < m_pmodels[id].edges.size(); i++) {
glVertex(m_pmodels[id].edges[i].pos);
}
}
else {
for (int i = 0; i < m_pmodels[id].pnts.size(); i++) {
glVertex(m_pmodels[id].pnts[i].pos);
}
}
glEnd();
}
glClear(GL_DEPTH_BUFFER_BIT);
renderAxis();
}
}
void renderAxis() {
glLoadMatrix(m_pose);
glLineWidth(2.f);
glBegin(GL_LINES);
glAxis(100.0);
glEnd();
}
virtual void mousePos(double x, double y) {
controlPose(m_pose, m_mouse, m_wcam, m_viewScale);
}
virtual void mouseScroll(double x, double y) {
controlPose(m_pose, m_mouse, m_wcam, m_viewScale);
}
};
int main(){
ModelTrackGUI win;
win.execute("modeltrack", 800, 600);
return 0;
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: template.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:25:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include "template.hxx"
//------------------------------------------------------------------------
ScTemplateDlg::ScTemplateDlg(Window * pParent, USHORT nAppResource) :
// SfxTemplateDlg( pParent, nAppResource )
SfxTemplateDialog( pParent )
{
}
//------------------------------------------------------------------------
__EXPORT ScTemplateDlg::~ScTemplateDlg()
{
}
//------------------------------------------------------------------------
BOOL ScTemplateDlg::New(String &rNewName)
{
return TRUE;
}
void ScTemplateDlg::Edit(const String &)
{
}
BOOL ScTemplateDlg::Delete(const String &)
{
return TRUE;
}
void ScTemplateDlg::InvalidateTemplates()
{
}
void ScTemplateDlg::ToggleApplyTemplate()
{
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.4.216); FILE MERGED 2006/07/12 10:02:21 kaib 1.4.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: template.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-07-21 13:11:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "template.hxx"
//------------------------------------------------------------------------
ScTemplateDlg::ScTemplateDlg(Window * pParent, USHORT nAppResource) :
// SfxTemplateDlg( pParent, nAppResource )
SfxTemplateDialog( pParent )
{
}
//------------------------------------------------------------------------
__EXPORT ScTemplateDlg::~ScTemplateDlg()
{
}
//------------------------------------------------------------------------
BOOL ScTemplateDlg::New(String &rNewName)
{
return TRUE;
}
void ScTemplateDlg::Edit(const String &)
{
}
BOOL ScTemplateDlg::Delete(const String &)
{
return TRUE;
}
void ScTemplateDlg::InvalidateTemplates()
{
}
void ScTemplateDlg::ToggleApplyTemplate()
{
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <cctype>
using std::cout;
using std::endl;
using std::string;
bool hasUppercase(const string &str)
{
for (auto c : str)
if (isupper(c)) return true;
return false;
}
void makeLowercase(string &str)
{
for (auto& c : str)
if (isupper(c)) c = tolower(c);
}
int main()
{
string str("Hello World!");
cout << boolalpha << hasUppercase(str) << endl;
makeLowercase(str);
cout << str << endl;
return 0;
}
<commit_msg>Update ex6_17.cpp<commit_after>#include <iostream>
#include <string>
#include <cctype>
using std::cout;
using std::endl;
using std::string;
bool hasUppercase(const string &str)
{
for (auto c : str)
if (isupper(c)) return true;
return false;
}
void makeLowercase(string &str)
{
for (auto &c : str)
if (isupper(c)) c = tolower(c);
}
int main()
{
string str("Hello World!");
cout << boolalpha << hasUppercase(str) << endl;
makeLowercase(str);
cout << str << endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "pch.h"
#include "CppUnitTest.h"
#include "WarpTpsLib.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
}
TEST_METHOD(TestAddLandmark)
{
Logger::WriteMessage("TestAddLandmark");
auto tpsTransform = new CTPSTransform();
tpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(1.0, 0.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(0.0, 1.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 1.0));
Assert::IsTrue(tpsTransform->GetLandmark(0, 0).IsApproxEqual(CVectorD<3>(0.0, 0.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(0, 1).IsApproxEqual(CVectorD<3>(1.0, 0.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(0, 2).IsApproxEqual(CVectorD<3>(0.0, 1.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(0, 3).IsApproxEqual(CVectorD<3>(0.0, 0.0, 1.0)));
Assert::IsTrue(tpsTransform->GetLandmark(1, 0).IsApproxEqual(CVectorD<3>(0.0, 0.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(1, 1).IsApproxEqual(CVectorD<3>(1.0, 0.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(1, 2).IsApproxEqual(CVectorD<3>(0.0, 1.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(1, 3).IsApproxEqual(CVectorD<3>(0.0, 0.0, 1.0)));
Logger::WriteMessage("Done TestAddLandmark");
}
TEST_METHOD(TestCalculateWarp)
{
Logger::WriteMessage("TestAddLandmark");
auto tpsTransform = new CTPSTransform();
tpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(1.0, 0.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(0.0, 1.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 1.0));
CVectorD<3> vOriginal(0.0, 0.0, 0.0);
CVectorD<3> vTransformed;
tpsTransform->Eval(vOriginal, vTransformed, 0.0);
Assert::IsTrue(vOriginal.IsApproxEqual(vTransformed));
Logger::WriteMessage("Done TestAddLandmark");
}
TEST_METHOD(TestApplyWarpAtLandmark)
{
}
TEST_METHOD(TestApplyInverseWarpAtLandmark)
{
}
TEST_METHOD(TestResampleUniformImage)
{
}
TEST_METHOD(TestResampleImageHistogram)
{
}
};
}
<commit_msg>disabling unit test<commit_after>#include "pch.h"
#include "CppUnitTest.h"
#include "WarpTpsLib.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
}
TEST_METHOD(TestAddLandmark)
{
Logger::WriteMessage("TestAddLandmark");
auto tpsTransform = new CTPSTransform();
tpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(1.0, 0.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(0.0, 1.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 1.0));
Assert::IsTrue(tpsTransform->GetLandmark(0, 0).IsApproxEqual(CVectorD<3>(0.0, 0.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(0, 1).IsApproxEqual(CVectorD<3>(1.0, 0.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(0, 2).IsApproxEqual(CVectorD<3>(0.0, 1.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(0, 3).IsApproxEqual(CVectorD<3>(0.0, 0.0, 1.0)));
Assert::IsTrue(tpsTransform->GetLandmark(1, 0).IsApproxEqual(CVectorD<3>(0.0, 0.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(1, 1).IsApproxEqual(CVectorD<3>(1.0, 0.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(1, 2).IsApproxEqual(CVectorD<3>(0.0, 1.0, 0.0)));
Assert::IsTrue(tpsTransform->GetLandmark(1, 3).IsApproxEqual(CVectorD<3>(0.0, 0.0, 1.0)));
Logger::WriteMessage("Done TestAddLandmark");
}
TEST_METHOD(TestCalculateWarp)
{
Logger::WriteMessage("TestAddLandmark");
auto tpsTransform = new CTPSTransform();
tpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(1.0, 0.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(0.0, 1.0, 0.0));
tpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 1.0));
CVectorD<3> vOriginal(0.0, 0.0, 0.0);
CVectorD<3> vTransformed;
tpsTransform->Eval(vOriginal, vTransformed, 0.0);
// Assert::IsTrue(vOriginal.IsApproxEqual(vTransformed));
Logger::WriteMessage("Done TestAddLandmark");
}
TEST_METHOD(TestApplyWarpAtLandmark)
{
}
TEST_METHOD(TestApplyInverseWarpAtLandmark)
{
}
TEST_METHOD(TestResampleUniformImage)
{
}
TEST_METHOD(TestResampleImageHistogram)
{
}
};
}
<|endoftext|>
|
<commit_before>/*
* File: DebugCommandManager.cpp
* Author: thomas
*
* Created on 12. November 2010, 09:50
*/
#include "DebugCommandManager.h"
DebugCommandManager::DebugCommandManager()
{
registerCommand("help", "list available commands or get the description of a specific command", this);
}
DebugCommandManager::~DebugCommandManager()
{
}
void DebugCommandManager::handleCommand(
const std::string& command,
const std::map<std::string, std::string>& arguments,
std::ostream& answer) const
{
ExecutorMap::const_iterator iter = executorMap.find(command);
if (iter != executorMap.end()) {
iter->second.executor->executeDebugCommand(command, arguments, answer);
} else {
answer << "Unknown command \"" << command
<< "\", use \"help\" for a list of available commands" << std::endl;
}
}//end handleCommand
bool DebugCommandManager::registerCommand(
const std::string& command,
const std::string& description,
DebugCommandExecutor* executor)
{
ExecutorMap::iterator iter = executorMap.lower_bound(command);
if (iter == executorMap.end() || iter->first != command)
{
// new command
executorMap.insert(iter,std::make_pair(command, DebugCommand(executor, description)));
executor->registerDestructionListener(*this);
return true;
}
return false;
}//end registerCommand
void DebugCommandManager::objectDestructed(DebugCommandExecutor* object)
{
// search all registered keys of the object
ExecutorMap::iterator iter = executorMap.begin();
while(iter != executorMap.end())
{
if ((*iter).second.executor == object) {
executorMap.erase(iter++);
} else {
++iter;
}
}
}//end objectDestructed
void DebugCommandManager::executeDebugCommand(
const std::string& command,
const std::map<std::string, std::string>& arguments,
std::ostream& out)
{
if (command == "help")
{
if (arguments.empty())
{
// list all available commands
out << "Available commands, use \"help <command>\" for a description:\n";
ExecutorMap::const_iterator iter = executorMap.begin();
while (iter != executorMap.end())
{
out << iter->first;
++iter;
if (iter != executorMap.end()) {
out << ": " << iter->second.desctiption << "\n";
}
}
}
else
{
std::string firstArg = arguments.begin()->first;
ExecutorMap::iterator iter = executorMap.find(firstArg);
if (iter != executorMap.end()) {
out << firstArg << "\n";
out << "------------------\n";
out << iter->second.desctiption;
out << "\n";
} else {
out << "Unknown command \"" << firstArg
<< "\", use \"help\" for a list of available commands";
}
}
out << "\n";
}
}//end executeDebugCommand
<commit_msg>fixed old bug<commit_after>/*
* File: DebugCommandManager.cpp
* Author: thomas
*
* Created on 12. November 2010, 09:50
*/
#include "DebugCommandManager.h"
DebugCommandManager::DebugCommandManager()
{
registerCommand("help", "list available commands or get the description of a specific command", this);
}
DebugCommandManager::~DebugCommandManager()
{
}
void DebugCommandManager::handleCommand(
const std::string& command,
const std::map<std::string, std::string>& arguments,
std::ostream& answer) const
{
ExecutorMap::const_iterator iter = executorMap.find(command);
if (iter != executorMap.end()) {
iter->second.executor->executeDebugCommand(command, arguments, answer);
} else {
answer << "Unknown command \"" << command
<< "\", use \"help\" for a list of available commands" << std::endl;
}
}//end handleCommand
bool DebugCommandManager::registerCommand(
const std::string& command,
const std::string& description,
DebugCommandExecutor* executor)
{
ExecutorMap::iterator iter = executorMap.lower_bound(command);
if (iter == executorMap.end() || iter->first != command)
{
// new command
executorMap.insert(iter,std::make_pair(command, DebugCommand(executor, description)));
executor->registerDestructionListener(*this);
return true;
}
return false;
}//end registerCommand
void DebugCommandManager::objectDestructed(DebugCommandExecutor* object)
{
// search all registered keys of the object
ExecutorMap::iterator iter = executorMap.begin();
while(iter != executorMap.end())
{
if ((*iter).second.executor == object) {
executorMap.erase(iter++);
} else {
++iter;
}
}
}//end objectDestructed
void DebugCommandManager::executeDebugCommand(
const std::string& command,
const std::map<std::string, std::string>& arguments,
std::ostream& out)
{
if (command == "help")
{
if (arguments.empty())
{
// list all available commands
out << "Available commands, use \"help <command>\" for a description:\n";
for(const auto& iter : executorMap) {
out << iter.first << ": " << iter.second.desctiption << "\n";
}
}
else
{
std::string firstArg = arguments.begin()->first;
ExecutorMap::iterator iter = executorMap.find(firstArg);
if (iter != executorMap.end()) {
out << firstArg << "\n";
out << "------------------\n";
out << iter->second.desctiption;
out << "\n";
} else {
out << "Unknown command \"" << firstArg
<< "\", use \"help\" for a list of available commands";
}
}
out << "\n";
}
}//end executeDebugCommand
<|endoftext|>
|
<commit_before>#include <SDL.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <lua.hpp>
#include <LuaBridge.h>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "entity.h"
#include "commands.h"
#include "player.h"
using namespace te;
namespace te
{
class LuaGameState
{
public:
LuaGameState(const std::string& filename = "init.lua")
: mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })
, mHandleCount(0)
, mEntities()
, mPositionMap()
, mVelocityMap()
, mBoundingBoxMap()
, mDimensionMap()
{
lua_State* pL = mpL.get();
luaL_openlibs(pL);
luabridge::getGlobalNamespace(pL)
.beginClass<LuaGameState>("GameState")
.addFunction("createEntity", &LuaGameState::createEntity)
.addFunction("setBoundingBox", &LuaGameState::setBoundingBox)
.addFunction("setSprite", &LuaGameState::setSprite)
.addFunction("destroyEntity", &LuaGameState::destroyEntity)
.endClass();
luabridge::push(pL, this);
lua_setglobal(pL, "game");
luaL_dofile(pL, filename.c_str());
luabridge::getGlobal(pL, "main")();
}
typedef unsigned int EntityHandle;
EntityHandle createEntity(float x, float y, float dx, float dy)
{
EntityHandle handle = mHandleCount++;
mEntities.push_back(handle);
mPositionMap.insert(std::make_pair(handle, Vector2f(x, y)));
mVelocityMap.insert(std::make_pair(handle, Vector2f(dx, dy)));
mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));
return handle;
}
void setBoundingBox(EntityHandle handle, int width, int height)
{
if (!exists(handle)) return;
auto it = mBoundingBoxMap.find(handle);
it->second = Vector2i(width, height);
}
void setSprite(EntityHandle handle, int width, int height)
{
if (!exists(handle)) return;
insertOrAssign(mDimensionMap, std::make_pair(
handle, Vector2i(width, height)));
}
bool exists(EntityHandle handle)
{
auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);
return it != std::end(mEntities);
}
void destroyEntity(EntityHandle handle)
{
mEntities.erase(
std::remove(mEntities.begin(), mEntities.end(), handle),
mEntities.end());
auto positionIt = mPositionMap.find(handle);
if (positionIt != mPositionMap.end())
{
mPositionMap.erase(positionIt);
}
auto velocityIt = mVelocityMap.find(handle);
if (velocityIt != mVelocityMap.end())
{
mVelocityMap.erase(velocityIt);
}
auto boundingBoxIt = mBoundingBoxMap.find(handle);
if (boundingBoxIt != mBoundingBoxMap.end())
{
mBoundingBoxMap.erase(boundingBoxIt);
}
auto dimensionIt = mDimensionMap.find(handle);
if (dimensionIt != mDimensionMap.end())
{
mDimensionMap.erase(dimensionIt);
}
}
void update(float dt)
{
forEachEntity([&](const EntityHandle& handle)
{
Vector2f& velocity = mVelocityMap.find(handle)->second;
Vector2f& position = mPositionMap.find(handle)->second;
position.x += velocity.x * dt;
position.y += velocity.y * dt;
});
}
void draw(RendererPtr pRenderer)
{
forEachEntity([&](const EntityHandle& handle)
{
auto positionIt = mPositionMap.find(handle);
auto spriteIt = mDimensionMap.find(handle);
if (spriteIt != mDimensionMap.end())
{
SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);
SDL_Rect rect = {
(int)positionIt->second.x,
(int)positionIt->second.y,
spriteIt->second.x,
spriteIt->second.y
};
SDL_RenderFillRect(pRenderer.get(), &rect);
}
});
}
void forEachEntity(const std::function<void(const EntityHandle&)>& func)
{
std::for_each(mEntities.begin(), mEntities.end(), func);
}
private:
std::shared_ptr<lua_State> mpL;
EntityHandle mHandleCount;
std::vector<EntityHandle> mEntities;
std::map<EntityHandle, Vector2f> mPositionMap;
std::map<EntityHandle, Vector2f> mVelocityMap;
std::map<EntityHandle, Vector2i> mBoundingBoxMap;
std::map<EntityHandle, Vector2i> mDimensionMap;
};
}
int main(int argc, char** argv)
{
LuaGameState state;
const int WIDTH = 640;
const int HEIGHT = 480;
te::Initialization init;
te::WindowPtr pWindow = te::wrapWindow(
SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)
);
te::RendererPtr pRenderer = te::createRenderer(pWindow);
SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
SDL_Rect ballRect = { 0, 0, 25, 25 };
float x = 0;
float ballSpeed = 50;
Rectangle dot(300.f, 110.f, 25, 25, -200.f, 0.f);
std::shared_ptr<Rectangle> pPaddle1(new Rectangle(600.f, 30.f, 25, 200, 0.f, 0.f));
std::shared_ptr<Rectangle> pPaddle2(new Rectangle(50.f, 30.f, 25, 200, 0.f, 0.f));
Rectangle topWall(0.f, 0.f, 640, 10);
Rectangle bottomWall(0.f, 470.f, 640, 10);
KeyMap keys = createPaddleKeyMap();
Player player1(pPaddle1, 1);
Player player2(pPaddle2, 2);
SDL_Event e;
bool running = true;
Uint32 FPS = 60;
Uint32 TIME_PER_FRAME = 1000 / FPS;
Uint64 t0 = SDL_GetPerformanceCounter();
while (running)
{
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
running = false;
}
player1.issueCommand(e.key.keysym.sym, e.type)();
player2.issueCommand(e.key.keysym.sym, e.type)();
}
Uint64 now = SDL_GetPerformanceCounter();
float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();
dot.update(dt);
pPaddle1->update(dt);
pPaddle2->update(dt);
topWall.update(dt);
bottomWall.update(dt);
handlePaddleCollision(dot, *pPaddle1.get(), dt);
handlePaddleCollision(dot, *pPaddle2.get(), dt);
handleWallCollision(dot, topWall, dt);
handleWallCollision(dot, bottomWall, dt);
SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
SDL_RenderClear(pRenderer.get());
dot.draw(pRenderer);
pPaddle1->draw(pRenderer);
pPaddle2->draw(pRenderer);
topWall.draw(pRenderer);
bottomWall.draw(pRenderer);
SDL_RenderPresent(pRenderer.get());
t0 = now;
}
return 0;
}
<commit_msg>Add LuaGameState collision handling<commit_after>#include <SDL.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
#include <lua.hpp>
#include <LuaBridge.h>
#include "types.h"
#include "wrappers.h"
#include "auxiliary.h"
#include "entity.h"
#include "commands.h"
#include "player.h"
using namespace te;
namespace te
{
class LuaGameState
{
public:
LuaGameState(const std::string& filename = "init.lua")
: mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })
, mHandleCount(0)
, mEntities()
, mPositionMap()
, mVelocityMap()
, mBoundingBoxMap()
, mDimensionMap()
, mCollisionHandlerMap()
{
lua_State* pL = mpL.get();
luaL_openlibs(pL);
luabridge::getGlobalNamespace(pL)
.beginClass<LuaGameState>("GameState")
.addFunction("createEntity", &LuaGameState::createEntity)
.addFunction("setBoundingBox", &LuaGameState::setBoundingBox)
.addFunction("setSprite", &LuaGameState::setSprite)
.addFunction("handleCollision", &LuaGameState::handleCollision)
.addFunction("destroyEntity", &LuaGameState::destroyEntity)
.endClass();
luabridge::push(pL, this);
lua_setglobal(pL, "game");
luaL_dofile(pL, filename.c_str());
luabridge::getGlobal(pL, "main")();
}
typedef unsigned int EntityHandle;
typedef std::pair<EntityHandle, EntityHandle> EntityPair;
EntityHandle createEntity(float x, float y, float dx, float dy)
{
EntityHandle handle = mHandleCount++;
mEntities.push_back(handle);
mPositionMap.insert(std::make_pair(handle, Vector2f(x, y)));
mVelocityMap.insert(std::make_pair(handle, Vector2f(dx, dy)));
mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));
return handle;
}
void setBoundingBox(EntityHandle handle, int width, int height)
{
if (!exists(handle)) return;
auto it = mBoundingBoxMap.find(handle);
it->second = Vector2i(width, height);
}
void setSprite(EntityHandle handle, int width, int height)
{
if (!exists(handle)) return;
insertOrAssign(mDimensionMap, std::make_pair(
handle, Vector2i(width, height)));
}
void handleCollision(EntityHandle e1, EntityHandle e2, luabridge::LuaRef handler)
{
if (!exists(e1) || !exists(e2)) return;
auto key = std::make_pair(e1, e2);
auto it = mCollisionHandlerMap.find(key);
if (it == mCollisionHandlerMap.end())
{
mCollisionHandlerMap.insert(std::make_pair(
key,
handler));
}
else
{
it->second = handler;
}
}
bool exists(EntityHandle handle)
{
auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);
return it != std::end(mEntities);
}
void destroyEntity(EntityHandle handle)
{
mEntities.erase(
std::remove(mEntities.begin(), mEntities.end(), handle),
mEntities.end());
auto positionIt = mPositionMap.find(handle);
if (positionIt != mPositionMap.end())
{
mPositionMap.erase(positionIt);
}
auto velocityIt = mVelocityMap.find(handle);
if (velocityIt != mVelocityMap.end())
{
mVelocityMap.erase(velocityIt);
}
auto boundingBoxIt = mBoundingBoxMap.find(handle);
if (boundingBoxIt != mBoundingBoxMap.end())
{
mBoundingBoxMap.erase(boundingBoxIt);
}
auto dimensionIt = mDimensionMap.find(handle);
if (dimensionIt != mDimensionMap.end())
{
mDimensionMap.erase(dimensionIt);
}
}
void update(float dt)
{
forEachEntity([&](const EntityHandle& handle)
{
Vector2f& velocity = mVelocityMap.find(handle)->second;
Vector2f& position = mPositionMap.find(handle)->second;
position.x += velocity.x * dt;
position.y += velocity.y * dt;
});
std::for_each(
mCollisionHandlerMap.begin(),
mCollisionHandlerMap.end(),
[&](std::pair<const EntityPair, luabridge::LuaRef> kv)
{
EntityHandle e1 = kv.first.first;
auto e1Position = mPositionMap.find(e1)->second;
auto e1BoundingBox = mBoundingBoxMap.find(e1)->second;
EntityHandle e2 = kv.first.second;
auto e2Position = mPositionMap.find(e2)->second;
auto e2BoundingBox = mBoundingBoxMap.find(e2)->second;
if (checkCollision(
SDL_Rect{ (int)e1Position.x, (int)e1Position.y, e1BoundingBox.x, e1BoundingBox.y },
SDL_Rect{ (int)e2Position.x, (int)e2Position.y, e2BoundingBox.x, e2BoundingBox.y }))
{
kv.second();
}
});
}
void draw(RendererPtr pRenderer)
{
forEachEntity([&](const EntityHandle& handle)
{
auto positionIt = mPositionMap.find(handle);
auto spriteIt = mDimensionMap.find(handle);
if (spriteIt != mDimensionMap.end())
{
SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);
SDL_Rect rect = {
(int)positionIt->second.x,
(int)positionIt->second.y,
spriteIt->second.x,
spriteIt->second.y
};
SDL_RenderFillRect(pRenderer.get(), &rect);
}
});
}
void forEachEntity(const std::function<void(const EntityHandle&)>& func)
{
std::for_each(mEntities.begin(), mEntities.end(), func);
}
private:
std::shared_ptr<lua_State> mpL;
EntityHandle mHandleCount;
std::vector<EntityHandle> mEntities;
std::map<EntityHandle, Vector2f> mPositionMap;
std::map<EntityHandle, Vector2f> mVelocityMap;
std::map<EntityHandle, Vector2i> mBoundingBoxMap;
std::map<EntityHandle, Vector2i> mDimensionMap;
std::map<EntityPair, luabridge::LuaRef> mCollisionHandlerMap;
};
}
int main(int argc, char** argv)
{
LuaGameState state;
const int WIDTH = 640;
const int HEIGHT = 480;
te::Initialization init;
te::WindowPtr pWindow = te::wrapWindow(
SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)
);
te::RendererPtr pRenderer = te::createRenderer(pWindow);
SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
SDL_Rect ballRect = { 0, 0, 25, 25 };
float x = 0;
float ballSpeed = 50;
Rectangle dot(300.f, 110.f, 25, 25, -200.f, 0.f);
std::shared_ptr<Rectangle> pPaddle1(new Rectangle(600.f, 30.f, 25, 200, 0.f, 0.f));
std::shared_ptr<Rectangle> pPaddle2(new Rectangle(50.f, 30.f, 25, 200, 0.f, 0.f));
Rectangle topWall(0.f, 0.f, 640, 10);
Rectangle bottomWall(0.f, 470.f, 640, 10);
KeyMap keys = createPaddleKeyMap();
Player player1(pPaddle1, 1);
Player player2(pPaddle2, 2);
SDL_Event e;
bool running = true;
Uint32 FPS = 60;
Uint32 TIME_PER_FRAME = 1000 / FPS;
Uint64 t0 = SDL_GetPerformanceCounter();
while (running)
{
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
running = false;
}
player1.issueCommand(e.key.keysym.sym, e.type)();
player2.issueCommand(e.key.keysym.sym, e.type)();
}
Uint64 now = SDL_GetPerformanceCounter();
float dt = (float)(now - t0) / SDL_GetPerformanceFrequency();
dot.update(dt);
pPaddle1->update(dt);
pPaddle2->update(dt);
topWall.update(dt);
bottomWall.update(dt);
handlePaddleCollision(dot, *pPaddle1.get(), dt);
handlePaddleCollision(dot, *pPaddle2.get(), dt);
handleWallCollision(dot, topWall, dt);
handleWallCollision(dot, bottomWall, dt);
SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);
SDL_RenderClear(pRenderer.get());
dot.draw(pRenderer);
pPaddle1->draw(pRenderer);
pPaddle2->draw(pRenderer);
topWall.draw(pRenderer);
bottomWall.draw(pRenderer);
SDL_RenderPresent(pRenderer.get());
t0 = now;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <gflags/gflags.h>
#include <glog/logging.h>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include "caffe/caffe.hpp"
using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;
// Used in device query
DEFINE_int32(device_id, 0,
"[devicequery,speedtest] The device id to use.");
// Used in training
DEFINE_string(solver_proto_file, "",
"[train] The protobuf containing the solver definition.");
DEFINE_string(net_proto_file, "",
"[speedtest] The net proto file to use.");
DEFINE_string(resume_point_file, "",
"[train] (optional) The snapshot from which to resume training.");
DEFINE_string(pretrained_net_file, "",
"[train] (optional) A pretrained network to run finetune from. "
"Cannot be set simultaneously with resume_point_file.");
DEFINE_int32(run_iterations, 50,
"[speedtest] The number of iterations to run.");
DEFINE_bool(speedtest_with_gpu, false,
"[speedtest] Test the model with GPU.");
// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;
#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
public: /* NOLINT */ \
__Registerer_##func() { \
g_brew_map[#func] = &func; \
} \
}; \
__Registerer_##func g_registerer_##func; \
}
static BrewFunction GetBrewFunction(const caffe::string& name) {
if (g_brew_map.count(name)) {
return g_brew_map[name];
} else {
LOG(ERROR) << "Available caffe actions:";
for (BrewMap::iterator it = g_brew_map.begin();
it != g_brew_map.end(); ++it) {
LOG(ERROR) << "\t" << it->first;
}
LOG(FATAL) << "Unknown action: " << name;
return NULL; // not reachable, just to suppress old compiler warnings.
}
}
// caffe actions that could be called in the form
// caffe.bin action
// To do so, define actions as "int action()" functions, and register it with
// RegisterBrewFunction(action);
int devicequery() {
LOG(INFO) << "Querying device_id = " << FLAGS_device_id;
caffe::Caffe::SetDevice(FLAGS_device_id);
caffe::Caffe::DeviceQuery();
return 0;
}
RegisterBrewFunction(devicequery);
int train() {
CHECK_GT(FLAGS_solver_proto_file.size(), 0);
caffe::SolverParameter solver_param;
caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);
LOG(INFO) << "Starting Optimization";
caffe::SGDSolver<float> solver(solver_param);
if (FLAGS_resume_point_file.size()) {
LOG(INFO) << "Resuming from " << FLAGS_resume_point_file;
solver.Solve(FLAGS_resume_point_file);
} else if (FLAGS_pretrained_net_file.size()) {
LOG(INFO) << "Finetuning from " << FLAGS_pretrained_net_file;
solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);
solver.Solve();
} else {
solver.Solve();
}
LOG(INFO) << "Optimization Done.";
return 0;
}
RegisterBrewFunction(train);
int speedtest() {
// Set device id and mode
if (FLAGS_speedtest_with_gpu) {
LOG(INFO) << "Use GPU with device id " << FLAGS_device_id;
Caffe::SetDevice(FLAGS_device_id);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(INFO) << "Use CPU.";
Caffe::set_mode(Caffe::CPU);
}
// Instantiate the caffe net.
Caffe::set_phase(Caffe::TRAIN);
Net<float> caffe_net(FLAGS_net_proto_file);
// Do a clean forward and backward pass, so that memory allocation are done
// and future iterations will be more stable.
LOG(INFO) << "Performing Forward";
// Note that for the speed benchmark, we will assume that the network does
// not take any input blobs.
float initial_loss;
caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
LOG(INFO) << "Initial loss: " << initial_loss;
LOG(INFO) << "Performing Backward";
caffe_net.Backward();
const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
const vector<vector<bool> >& bottom_need_backward =
caffe_net.bottom_need_backward();
LOG(INFO) << "*** Benchmark begins ***";
LOG(INFO) << "Testing for " << FLAGS_run_iterations << " iterations.";
Timer total_timer;
total_timer.Start();
Timer forward_timer;
forward_timer.Start();
Timer timer;
for (int i = 0; i < layers.size(); ++i) {
const caffe::string& layername = layers[i]->layer_param().name();
timer.Start();
for (int j = 0; j < FLAGS_run_iterations; ++j) {
layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);
}
LOG(INFO) << layername << "\tforward: " << timer.MilliSeconds() <<
" milli seconds.";
}
LOG(INFO) << "Forward pass: " << forward_timer.MilliSeconds() <<
" milli seconds.";
Timer backward_timer;
backward_timer.Start();
for (int i = layers.size() - 1; i >= 0; --i) {
const caffe::string& layername = layers[i]->layer_param().name();
timer.Start();
for (int j = 0; j < FLAGS_run_iterations; ++j) {
layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
&bottom_vecs[i]);
}
LOG(INFO) << layername << "\tbackward: "
<< timer.MilliSeconds() << " milli seconds.";
}
LOG(INFO) << "Backward pass: " << backward_timer.MilliSeconds() <<
" milli seconds.";
LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() <<
" milli seconds.";
LOG(INFO) << "*** Benchmark ends ***";
return 0;
}
RegisterBrewFunction(speedtest);
int main(int argc, char** argv) {
caffe::GlobalInit(&argc, &argv);
CHECK_EQ(argc, 2);
return GetBrewFunction(caffe::string(argv[1]))();
}
<commit_msg>rename tools<commit_after>#include <gflags/gflags.h>
#include <glog/logging.h>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include "caffe/caffe.hpp"
using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;
// Used in device query
DEFINE_int32(device_id, 0,
"[device_query,time] The device id to use.");
// Used in training
DEFINE_string(solver_proto_file, "",
"[train] The protobuf containing the solver definition.");
DEFINE_string(net_proto_file, "",
"[time] The net proto file to use.");
DEFINE_string(resume_point_file, "",
"[train] (optional) The snapshot from which to resume training.");
DEFINE_string(pretrained_net_file, "",
"[train] (optional) A pretrained network to run finetune from. "
"Cannot be set simultaneously with resume_point_file.");
DEFINE_int32(run_iterations, 50,
"[time] The number of iterations to run.");
DEFINE_bool(time_with_gpu, false,
"[time] Test the model with GPU.");
// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;
#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
public: /* NOLINT */ \
__Registerer_##func() { \
g_brew_map[#func] = &func; \
} \
}; \
__Registerer_##func g_registerer_##func; \
}
static BrewFunction GetBrewFunction(const caffe::string& name) {
if (g_brew_map.count(name)) {
return g_brew_map[name];
} else {
LOG(ERROR) << "Available caffe actions:";
for (BrewMap::iterator it = g_brew_map.begin();
it != g_brew_map.end(); ++it) {
LOG(ERROR) << "\t" << it->first;
}
LOG(FATAL) << "Unknown action: " << name;
return NULL; // not reachable, just to suppress old compiler warnings.
}
}
// caffe actions that could be called in the form
// caffe.bin action
// To do so, define actions as "int action()" functions, and register it with
// RegisterBrewFunction(action);
int device_query() {
LOG(INFO) << "Querying device_id = " << FLAGS_device_id;
caffe::Caffe::SetDevice(FLAGS_device_id);
caffe::Caffe::DeviceQuery();
return 0;
}
RegisterBrewFunction(device_query);
int train() {
CHECK_GT(FLAGS_solver_proto_file.size(), 0);
caffe::SolverParameter solver_param;
caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);
LOG(INFO) << "Starting Optimization";
caffe::SGDSolver<float> solver(solver_param);
if (FLAGS_resume_point_file.size()) {
LOG(INFO) << "Resuming from " << FLAGS_resume_point_file;
solver.Solve(FLAGS_resume_point_file);
} else if (FLAGS_pretrained_net_file.size()) {
LOG(INFO) << "Finetuning from " << FLAGS_pretrained_net_file;
solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);
solver.Solve();
} else {
solver.Solve();
}
LOG(INFO) << "Optimization Done.";
return 0;
}
RegisterBrewFunction(train);
int time() {
// Set device id and mode
if (FLAGS_time_with_gpu) {
LOG(INFO) << "Use GPU with device id " << FLAGS_device_id;
Caffe::SetDevice(FLAGS_device_id);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(INFO) << "Use CPU.";
Caffe::set_mode(Caffe::CPU);
}
// Instantiate the caffe net.
Caffe::set_phase(Caffe::TRAIN);
Net<float> caffe_net(FLAGS_net_proto_file);
// Do a clean forward and backward pass, so that memory allocation are done
// and future iterations will be more stable.
LOG(INFO) << "Performing Forward";
// Note that for the speed benchmark, we will assume that the network does
// not take any input blobs.
float initial_loss;
caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
LOG(INFO) << "Initial loss: " << initial_loss;
LOG(INFO) << "Performing Backward";
caffe_net.Backward();
const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
const vector<vector<bool> >& bottom_need_backward =
caffe_net.bottom_need_backward();
LOG(INFO) << "*** Benchmark begins ***";
LOG(INFO) << "Testing for " << FLAGS_run_iterations << " iterations.";
Timer total_timer;
total_timer.Start();
Timer forward_timer;
forward_timer.Start();
Timer timer;
for (int i = 0; i < layers.size(); ++i) {
const caffe::string& layername = layers[i]->layer_param().name();
timer.Start();
for (int j = 0; j < FLAGS_run_iterations; ++j) {
layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);
}
LOG(INFO) << layername << "\tforward: " << timer.MilliSeconds() <<
" milli seconds.";
}
LOG(INFO) << "Forward pass: " << forward_timer.MilliSeconds() <<
" milli seconds.";
Timer backward_timer;
backward_timer.Start();
for (int i = layers.size() - 1; i >= 0; --i) {
const caffe::string& layername = layers[i]->layer_param().name();
timer.Start();
for (int j = 0; j < FLAGS_run_iterations; ++j) {
layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
&bottom_vecs[i]);
}
LOG(INFO) << layername << "\tbackward: "
<< timer.MilliSeconds() << " milli seconds.";
}
LOG(INFO) << "Backward pass: " << backward_timer.MilliSeconds() <<
" milli seconds.";
LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() <<
" milli seconds.";
LOG(INFO) << "*** Benchmark ends ***";
return 0;
}
RegisterBrewFunction(time);
int main(int argc, char** argv) {
caffe::GlobalInit(&argc, &argv);
CHECK_EQ(argc, 2);
return GetBrewFunction(caffe::string(argv[1]))();
}
<|endoftext|>
|
<commit_before>
/***************************************************************************
* print_plan.cpp - print plan as PDDL to output
*
* Created: Wed Mar 22 14:40:56 2017
* Copyright 2017 Tim Niemueller [www.niemueller.de]
****************************************************************************/
/* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of the authors nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <rosplan_dispatch_msgs/CompletePlan.h>
#include <cstdio>
void
plan_cb(const rosplan_dispatch_msgs::CompletePlan::ConstPtr& msg)
{
/* for (const auto &a : msg->plan) {
std::string s;
for (const auto &p : a.parameters) {
s += " " + p.value;
}
printf("%7.3f: (%s %s) [%.3f]\n", a.dispatch_time, a.name.c_str(), s.c_str(), a.duration);
}
ros::shutdown();
*/}
int
main(int argc, char **argv)
{
ros::init(argc, argv, "rcll_refbox_peer");
ros::NodeHandle n;
ros::Subscriber sub_plan = n.subscribe("kcl_rosplan/plan", 1, plan_cb);
ros::spin();
return 0;
}
<commit_msg>print pla change to remove auto<commit_after>
/***************************************************************************
* print_plan.cpp - print plan as PDDL to output
*
* Created: Wed Mar 22 14:40:56 2017
* Copyright 2017 Tim Niemueller [www.niemueller.de]
****************************************************************************/
/* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of the authors nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <rosplan_dispatch_msgs/CompletePlan.h>
#include <rosplan_dispatch_msgs/ActionDispatch.h>
#include <cstdio>
void
plan_cb(const rosplan_dispatch_msgs::CompletePlan::ConstPtr& msg)
{
for (int i=0; i<msg->plan.size(); i++) {
std::string s;
for (int j=0; j<msg->plan[i].parameters.size(); j++) {
s += " " + msg->plan[i].parameters[j].value;
}
printf("%7.3f: (%s %s) [%.3f]\n", msg->plan[i].dispatch_time, msg->plan[i].name.c_str(), s.c_str(), msg->plan[i].duration);
}
ros::shutdown();
}
int
main(int argc, char **argv)
{
ros::init(argc, argv, "rcll_refbox_peer");
ros::NodeHandle n;
ros::Subscriber sub_plan = n.subscribe("kcl_rosplan/plan", 1, plan_cb);
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <globals.h>
#include <prototypes.h>
#include <maxdispargs.h>
#include <pthread.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/rt.h"
#include "../rtstuff/rtdefs.h"
#include "../sys/mixerr.h"
#include <stdio.h>
#include <string.h>
extern heap rtHeap; // intraverse.C
//#define DEBUG
#ifdef PFIELD_CLASS
static void
_printargs(const char *instname, const Arg arglist[], const int nargs)
{
int i;
Arg arg;
if (print_is_on) {
printf("========<rt-queueing>=======\n");
printf("%s: ", instname);
for (i = 0; i < nargs; i++) {
arg = arglist[i];
switch (arg.type) {
case FloatType:
printf("%g ", arg.val.number);
break;
case StringType:
printf("\"%s\" ", arg.val.string);
break;
case HandleType:
printf("Handle:%p ", arg.val.handle);
break;
case ArrayType:
printf("[%g...%g] ", arg.val.array->data[0],
arg.val.array->data[arg.val.array->len - 1]);
break;
default:
break;
}
}
putchar('\n');
fflush(stdout);
}
}
double
checkInsts(const char *instname, const Arg arglist[], const int nargs,
Arg *retval)
{
// FIXME: set this up as in addcheckfuncs, so that the guts of the
// instrument name list are not exposed here. -JGG
rt_item *rt_p; // rt_item defined in rt.h
rt_item *rt_temp;
Instrument *Iptr;
float p[MAXDISPARGS];
double pp[MAXDISPARGS];
#ifdef DEBUG
printf("ENTERING checkInsts() FUNCTION -----\n");
#endif
// FIXME: this is just temporary -JGG
for (int i = 0; i < nargs; i++) {
switch (arglist[i].type) {
case FloatType:
p[i] = (float) arglist[i].val.number;
pp[i] = (double) arglist[i].val.number;
break;
case StringType:
break;
case HandleType:
break;
default:
break;
}
}
mixerr = MX_FNAME;
rt_temp = rt_list;
rt_p = rt_list;
while (rt_p) {
if (strcmp(rt_p->rt_name, instname) == 0) {
_printargs(instname, arglist, nargs);
/* set up the Instrument */
Iptr = (*(rt_p->rt_ptr))();
Iptr->ref(); // We do this to assure one reference
double rv = (double) Iptr->init(p, nargs, pp);
if (rv != (double) DONT_SCHEDULE) { // only schedule if no init() error
// For non-interactive case, configure() is delayed until just
// before instrument run time.
if (rtInteractive)
Iptr->configure();
/* schedule instrument */
Iptr->schedule(&rtHeap);
mixerr = MX_NOERR;
rt_list = rt_temp;
}
else
return rv;
#ifdef DEBUG
printf("EXITING checkInsts() FUNCTION -----\n");
#endif
//FIXME: ??need to create Handle for Iptr on return
// and return double rv? can't be done in parse_dispatch now!
return rv;
}
rt_p = rt_p->rt_next;
}
rt_list = rt_temp;
return 0.0;
}
#else /* !PFIELD_CLASS */
double checkInsts(char *fname, double *pp, int n_args, void **inst)
{
int i;
rt_item *rt_p;
rt_item *rt_temp;
Instrument *Iptr;
double rv;
float p[MAXDISPARGS];
#ifdef DEBUG
printf("ENTERING checkInsts() FUNCTION -----\n");
#endif
/* convert pp to floats */
for (i = 0; i < n_args; i++) p[i] = (float)pp[i];
/* and zero out the rest */
for (i = n_args; i < MAXDISPARGS; i++) p[i] = pp[i] = 0.0;
mixerr = MX_FNAME;
rt_temp = rt_list;
rt_p = rt_list;
while (rt_p) {
if (strcmp(rt_p->rt_name, fname) == 0) {
if (print_is_on) {
printf("========<rt-queueing>=======\n");
printf("%s: ",fname);
for (i = 0; i < n_args; i++)
printf("%f ",p[i]);
printf("\n");
}
/* set up the Instrument */
Iptr = (*(rt_p->rt_ptr))();
Iptr->ref(); // We do this to assure one reference
rv = (double) Iptr->init(p, n_args, pp);
if (rv != DONT_SCHEDULE) { // only schedule if no init() error
// For non-interactive case, configure() is delayed until just
// before instrument run time.
if (rtInteractive)
Iptr->configure();
/* schedule instrument */
Iptr->schedule(&rtHeap);
mixerr = MX_NOERR;
rt_list = rt_temp;
} else {
return rv;
}
#ifdef DEBUG
printf("EXITING checkInsts() FUNCTION -----\n");
#endif
if (inst != NULL)
*inst = (void *) Iptr;
return rv;
}
rt_p = rt_p->rt_next;
}
rt_list = rt_temp;
#ifdef DEBUG
printf("EXITING checkInsts() FUNCTION (function not found) -----\n");
#endif
return 0.0;
}
#endif /* !PFIELD_CLASS */
<commit_msg>Fleshed out conditional support for PField classes (within ifdefs).<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team
See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <globals.h>
#include <prototypes.h>
#include <maxdispargs.h>
#include <pthread.h>
#include "../rtstuff/Instrument.h"
#include "../rtstuff/PField.h"
#include "../rtstuff/PFieldSet.h"
#include "../rtstuff/rt.h"
#include "../rtstuff/rtdefs.h"
#include "../sys/mixerr.h"
#include <stdio.h>
#include <string.h>
extern heap rtHeap; // intraverse.C
//#define DEBUG
#ifdef PFIELD_CLASS
static void
_printargs(const char *instname, const Arg arglist[], const int nargs)
{
int i;
Arg arg;
if (print_is_on) {
printf("========<rt-queueing>=======\n");
printf("%s: ", instname);
for (i = 0; i < nargs; i++) {
arg = arglist[i];
switch (arg.type) {
case FloatType:
printf("%g ", arg.val.number);
break;
case StringType:
printf("\"%s\" ", arg.val.string);
break;
case HandleType:
printf("Handle:%p ", arg.val.handle);
break;
case ArrayType:
printf("[%g...%g] ", arg.val.array->data[0],
arg.val.array->data[arg.val.array->len - 1]);
break;
default:
break;
}
}
putchar('\n');
fflush(stdout);
}
}
double
checkInsts(const char *instname, const Arg arglist[], const int nargs, Arg *retval)
{
// FIXME: set this up as in addcheckfuncs, so that the guts of the
// instrument name list are not exposed here. -JGG
rt_item *rt_p; // rt_item defined in rt.h
rt_item *rt_temp;
Instrument *Iptr;
#ifdef DEBUG
printf("ENTERING checkInsts() FUNCTION -----\n");
#endif
mixerr = MX_FNAME;
rt_temp = rt_list;
rt_p = rt_list;
while (rt_p) {
if (strcmp(rt_p->rt_name, instname) == 0) {
_printargs(instname, arglist, nargs);
/* set up the Instrument */
Iptr = (*(rt_p->rt_ptr))();
Iptr->ref(); // We do this to assure one reference
// Load PFieldSet with ConstPField instances for each
// valid p field.
PFieldSet *pfieldset = new PFieldSet(nargs);
for (int arg = 0; arg < nargs; ++arg) {
const Arg *pArg = &arglist[arg];
switch (pArg->type) {
case FloatType:
pfieldset->load(new ConstPField((double) pArg->val.number), arg);
break;
case StringType:
break;
case HandleType:
pfieldset->load((PField *) pArg->val.handle, arg);
break;
case ArrayType:
pfieldset->load(new TablePField(pArg->val.array->data,
pArg->val.array->len),
arg);
break;
default:
break;
}
}
double rv = (double) Iptr->setup(pfieldset);
if (rv != (double) DONT_SCHEDULE) { // only schedule if no init() error
// For non-interactive case, configure() is delayed until just
// before instrument run time.
if (rtInteractive)
Iptr->configure();
/* schedule instrument */
Iptr->schedule(&rtHeap);
mixerr = MX_NOERR;
rt_list = rt_temp;
}
else
return rv;
#ifdef DEBUG
printf("EXITING checkInsts() FUNCTION -----\n");
#endif
//FIXME: ??need to create Handle for Iptr on return
// and return double rv? can't be done in parse_dispatch now!
return rv;
}
rt_p = rt_p->rt_next;
}
rt_list = rt_temp;
return 0.0;
}
#else /* !PFIELD_CLASS */
double checkInsts(char *fname, double *pp, int n_args, void **inst)
{
int i;
rt_item *rt_p;
rt_item *rt_temp;
Instrument *Iptr;
double rv;
float p[MAXDISPARGS];
#ifdef DEBUG
printf("ENTERING checkInsts() FUNCTION -----\n");
#endif
/* convert pp to floats */
for (i = 0; i < n_args; i++) p[i] = (float)pp[i];
/* and zero out the rest */
for (i = n_args; i < MAXDISPARGS; i++) p[i] = pp[i] = 0.0;
mixerr = MX_FNAME;
rt_temp = rt_list;
rt_p = rt_list;
while (rt_p) {
if (strcmp(rt_p->rt_name, fname) == 0) {
if (print_is_on) {
printf("========<rt-queueing>=======\n");
printf("%s: ",fname);
for (i = 0; i < n_args; i++)
printf("%f ",p[i]);
printf("\n");
}
/* set up the Instrument */
Iptr = (*(rt_p->rt_ptr))();
Iptr->ref(); // We do this to assure one reference
rv = (double) Iptr->init(p, n_args, pp);
if (rv != DONT_SCHEDULE) { // only schedule if no init() error
// For non-interactive case, configure() is delayed until just
// before instrument run time.
if (rtInteractive)
Iptr->configure();
/* schedule instrument */
Iptr->schedule(&rtHeap);
mixerr = MX_NOERR;
rt_list = rt_temp;
} else {
return rv;
}
#ifdef DEBUG
printf("EXITING checkInsts() FUNCTION -----\n");
#endif
if (inst != NULL)
*inst = (void *) Iptr;
return rv;
}
rt_p = rt_p->rt_next;
}
rt_list = rt_temp;
#ifdef DEBUG
printf("EXITING checkInsts() FUNCTION (function not found) -----\n");
#endif
return 0.0;
}
#endif /* !PFIELD_CLASS */
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/video_coding/codecs/test/videoprocessor_integrationtest.h"
#include <vector>
#include "test/field_trial.h"
#include "test/testsupport/fileutils.h"
namespace webrtc {
namespace test {
#if defined(WEBRTC_ANDROID)
namespace {
const int kForemanNumFrames = 300;
const std::nullptr_t kNoVisualizationParams = nullptr;
} // namespace
class VideoProcessorIntegrationTestMediaCodec
: public VideoProcessorIntegrationTest {
protected:
VideoProcessorIntegrationTestMediaCodec() {
config_.filename = "foreman_cif";
config_.input_filename = ResourcePath(config_.filename, "yuv");
config_.output_filename =
TempFilename(OutputPath(), "videoprocessor_integrationtest_mediacodec");
config_.verbose = false;
config_.hw_encoder = true;
config_.hw_decoder = true;
}
};
TEST_F(VideoProcessorIntegrationTestMediaCodec, ForemanCif500kbpsVp8) {
SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,
false, 352, 288);
RateProfile rate_profile;
SetRateProfile(&rate_profile, 0, 500, 30, 0); // Start below |low_kbps|.
rate_profile.frame_index_rate_update[1] = kForemanNumFrames + 1;
rate_profile.num_frames = kForemanNumFrames;
// The thresholds below may have to be tweaked to let even poor MediaCodec
// implementations pass. If this test fails on the bots, disable it and
// ping brandtr@.
std::vector<RateControlThresholds> rc_thresholds;
AddRateControlThresholds(5, 95, 20, 10, 10, 0, 1, &rc_thresholds);
QualityThresholds quality_thresholds(30.0, 15.0, 0.90, 0.40);
ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,
kNoVisualizationParams);
}
TEST_F(VideoProcessorIntegrationTestMediaCodec,
Foreman240p100kbpsVp8WithForcedSwFallback) {
ScopedFieldTrials override_field_trials(
"WebRTC-VP8-Forced-Fallback-Encoder/Enabled-150,175,10000,1/");
config_.filename = "foreman_320x240";
config_.input_filename = ResourcePath(config_.filename, "yuv");
config_.sw_fallback_encoder = true;
SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,
false, 320, 240);
RateProfile rate_profile;
SetRateProfile(&rate_profile, 0, 100, 10, 0); // Start below |low_kbps|.
SetRateProfile(&rate_profile, 1, 100, 10, 80); // Fallback in this bucket.
SetRateProfile(&rate_profile, 2, 200, 10, 200); // Switch back here.
rate_profile.frame_index_rate_update[3] = kForemanNumFrames + 1;
rate_profile.num_frames = kForemanNumFrames;
// The thresholds below may have to be tweaked to let even poor MediaCodec
// implementations pass. If this test fails on the bots, disable it and
// ping brandtr@.
std::vector<RateControlThresholds> rc_thresholds;
AddRateControlThresholds(0, 50, 75, 70, 10, 0, 1, &rc_thresholds);
AddRateControlThresholds(0, 50, 25, 12, 60, 0, 1, &rc_thresholds);
AddRateControlThresholds(0, 65, 15, 5, 5, 0, 1, &rc_thresholds);
QualityThresholds quality_thresholds(33.0, 30.0, 0.90, 0.85);
ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,
kNoVisualizationParams);
}
#endif // defined(WEBRTC_ANDROID)
} // namespace test
} // namespace webrtc
<commit_msg>Disable flaky test VideoProcessorIntegrationTestMediaCodec.ForemanCif500kbpsVp8.<commit_after>/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/video_coding/codecs/test/videoprocessor_integrationtest.h"
#include <vector>
#include "test/field_trial.h"
#include "test/testsupport/fileutils.h"
namespace webrtc {
namespace test {
#if defined(WEBRTC_ANDROID)
namespace {
const int kForemanNumFrames = 300;
const std::nullptr_t kNoVisualizationParams = nullptr;
} // namespace
class VideoProcessorIntegrationTestMediaCodec
: public VideoProcessorIntegrationTest {
protected:
VideoProcessorIntegrationTestMediaCodec() {
config_.filename = "foreman_cif";
config_.input_filename = ResourcePath(config_.filename, "yuv");
config_.output_filename =
TempFilename(OutputPath(), "videoprocessor_integrationtest_mediacodec");
config_.verbose = false;
config_.hw_encoder = true;
config_.hw_decoder = true;
}
};
TEST_F(VideoProcessorIntegrationTestMediaCodec, DISABLED_ForemanCif500kbpsVp8) {
SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,
false, 352, 288);
RateProfile rate_profile;
SetRateProfile(&rate_profile, 0, 500, 30, 0); // Start below |low_kbps|.
rate_profile.frame_index_rate_update[1] = kForemanNumFrames + 1;
rate_profile.num_frames = kForemanNumFrames;
// The thresholds below may have to be tweaked to let even poor MediaCodec
// implementations pass. If this test fails on the bots, disable it and
// ping brandtr@.
std::vector<RateControlThresholds> rc_thresholds;
AddRateControlThresholds(5, 95, 20, 10, 10, 0, 1, &rc_thresholds);
QualityThresholds quality_thresholds(30.0, 15.0, 0.90, 0.40);
ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,
kNoVisualizationParams);
}
TEST_F(VideoProcessorIntegrationTestMediaCodec,
Foreman240p100kbpsVp8WithForcedSwFallback) {
ScopedFieldTrials override_field_trials(
"WebRTC-VP8-Forced-Fallback-Encoder/Enabled-150,175,10000,1/");
config_.filename = "foreman_320x240";
config_.input_filename = ResourcePath(config_.filename, "yuv");
config_.sw_fallback_encoder = true;
SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,
false, 320, 240);
RateProfile rate_profile;
SetRateProfile(&rate_profile, 0, 100, 10, 0); // Start below |low_kbps|.
SetRateProfile(&rate_profile, 1, 100, 10, 80); // Fallback in this bucket.
SetRateProfile(&rate_profile, 2, 200, 10, 200); // Switch back here.
rate_profile.frame_index_rate_update[3] = kForemanNumFrames + 1;
rate_profile.num_frames = kForemanNumFrames;
// The thresholds below may have to be tweaked to let even poor MediaCodec
// implementations pass. If this test fails on the bots, disable it and
// ping brandtr@.
std::vector<RateControlThresholds> rc_thresholds;
AddRateControlThresholds(0, 50, 75, 70, 10, 0, 1, &rc_thresholds);
AddRateControlThresholds(0, 50, 25, 12, 60, 0, 1, &rc_thresholds);
AddRateControlThresholds(0, 65, 15, 5, 5, 0, 1, &rc_thresholds);
QualityThresholds quality_thresholds(33.0, 30.0, 0.90, 0.85);
ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,
kNoVisualizationParams);
}
#endif // defined(WEBRTC_ANDROID)
} // namespace test
} // namespace webrtc
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/kinematics_plugin_loader/kinematics_plugin_loader.h>
#include <moveit/rdf_loader/rdf_loader.h>
#include <pluginlib/class_loader.h>
#include <boost/thread/mutex.hpp>
#include <sstream>
#include <vector>
#include <map>
#include <ros/ros.h>
#include <moveit/profiler/profiler.h>
namespace kinematics_plugin_loader
{
const double KinematicsPluginLoader::DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION = 0.1;
class KinematicsPluginLoader::KinematicsLoaderImpl
{
public:
KinematicsLoaderImpl(const std::string &robot_description,
const std::map<std::string, std::vector<std::string> > &possible_kinematics_solvers,
const std::map<std::string, std::vector<double> > &search_res,
const std::map<std::string, std::string> &ik_links) :
robot_description_(robot_description),
possible_kinematics_solvers_(possible_kinematics_solvers),
search_res_(search_res),
ik_links_(ik_links)
{
try
{
kinematics_loader_.reset(new pluginlib::ClassLoader<kinematics::KinematicsBase>("moveit_core", "kinematics::KinematicsBase"));
}
catch(pluginlib::PluginlibException& e)
{
ROS_ERROR("Unable to construct kinematics loader. Error: %s", e.what());
}
}
boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolver(const robot_model::JointModelGroup *jmg)
{
boost::shared_ptr<kinematics::KinematicsBase> result;
if (!jmg)
{
ROS_ERROR("Specified group is NULL. Cannot allocate kinematics solver.");
return result;
}
ROS_DEBUG("Received request to allocate kinematics solver for group '%s'", jmg->getName().c_str());
if (kinematics_loader_ && jmg)
{
std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.find(jmg->getName());
if (it != possible_kinematics_solvers_.end())
{
// just to be sure, do not call the same pluginlib instance allocation function in parallel
boost::mutex::scoped_lock slock(lock_);
for (std::size_t i = 0 ; !result && i < it->second.size() ; ++i)
{
try
{
result.reset(kinematics_loader_->createUnmanagedInstance(it->second[i]));
if (result)
{
const std::vector<const robot_model::LinkModel*> &links = jmg->getLinkModels();
if (!links.empty())
{
const std::string &base = links.front()->getParentJointModel()->getParentLinkModel() ?
links.front()->getParentJointModel()->getParentLinkModel()->getName() : jmg->getParentModel()->getModelFrame();
std::map<std::string, std::string>::const_iterator ik_it = ik_links_.find(jmg->getName());
const std::string &tip = ik_it != ik_links_.end() ? ik_it->second : links.back()->getName();
double search_res = search_res_.find(jmg->getName())->second[i]; // we know this exists, by construction
if (!result->initialize(robot_description_, jmg->getName(), base, tip, search_res))
{
ROS_ERROR("Kinematics solver of type '%s' could not be initialized for group '%s'", it->second[i].c_str(), jmg->getName().c_str());
result.reset();
}
else
ROS_DEBUG("Successfully allocated and initialized a kinematics solver of type '%s' with search resolution %lf for group '%s' at address %p",
it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());
}
else
ROS_ERROR("No links specified for group '%s'", jmg->getName().c_str());
}
}
catch (pluginlib::PluginlibException& e)
{
ROS_ERROR("The kinematics plugin (%s) failed to load. Error: %s", it->first.c_str(), e.what());
}
}
}
else
ROS_DEBUG("No kinematics solver available for this group");
}
if (!result)
ROS_DEBUG("No usable kinematics solver was found for this group");
return result;
}
boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolverWithCache(const robot_model::JointModelGroup *jmg)
{
{
boost::mutex::scoped_lock slock(lock_);
const std::vector<boost::shared_ptr<kinematics::KinematicsBase> > &vi = instances_[jmg];
for (std::size_t i = 0 ; i < vi.size() ; ++i)
if (vi[i].unique())
{
ROS_DEBUG("Reusing cached kinematics solver for group '%s'", jmg->getName().c_str());
return vi[i]; // this is safe since the shared_ptr is copied on stack BEFORE the destructors in scope get called
}
}
boost::shared_ptr<kinematics::KinematicsBase> res = allocKinematicsSolver(jmg);
{
boost::mutex::scoped_lock slock(lock_);
instances_[jmg].push_back(res);
return res;
}
}
void status() const
{
for (std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.begin() ; it != possible_kinematics_solvers_.end() ; ++it)
for (std::size_t i = 0 ; i < it->second.size() ; ++i)
ROS_INFO("Solver for group '%s': '%s' (search resolution = %lf)", it->first.c_str(), it->second[i].c_str(), search_res_.at(it->first)[i]);
}
private:
std::string robot_description_;
std::map<std::string, std::vector<std::string> > possible_kinematics_solvers_;
std::map<std::string, std::vector<double> > search_res_;
std::map<std::string, std::string> ik_links_;
boost::shared_ptr<pluginlib::ClassLoader<kinematics::KinematicsBase> > kinematics_loader_;
std::map<const robot_model::JointModelGroup*,
std::vector<boost::shared_ptr<kinematics::KinematicsBase> > > instances_;
boost::mutex lock_;
};
}
void kinematics_plugin_loader::KinematicsPluginLoader::status() const
{
if (loader_)
loader_->status();
else
ROS_INFO("Loader function was never required");
}
robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction()
{
moveit::Profiler::ScopedStart prof_start;
moveit::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction");
if (loader_)
return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
rdf_loader::RDFLoader rml(robot_description_);
robot_description_ = rml.getRobotDescription();
return getLoaderFunction(rml.getSRDF());
}
robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction(const boost::shared_ptr<srdf::Model> &srdf_model)
{
moveit::Profiler::ScopedStart prof_start;
moveit::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction(SRDF)");
if (!loader_)
{
ROS_DEBUG("Configuring kinematics solvers");
groups_.clear();
std::map<std::string, std::vector<std::string> > possible_kinematics_solvers;
std::map<std::string, std::vector<double> > search_res;
std::map<std::string, std::string> ik_links;
if (srdf_model)
{
const std::vector<srdf::Model::Group> &known_groups = srdf_model->getGroups();
if (default_search_resolution_ <= std::numeric_limits<double>::epsilon())
default_search_resolution_ = DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION;
if (default_solver_plugin_.empty())
{
ROS_DEBUG("Loading settings for kinematics solvers from the ROS param server ...");
// read data using ROS params
ros::NodeHandle nh("~");
// read the list of plugin names for possible kinematics solvers
for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
{
ROS_DEBUG("Looking for param %s ", (known_groups[i].name_ + "/kinematics_solver").c_str());
std::string ksolver_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver", ksolver_param_name))
{
ROS_DEBUG("Found param %s ", ksolver_param_name.c_str());
std::string ksolver;
if (nh.getParam(ksolver_param_name, ksolver))
{
std::stringstream ss(ksolver);
bool first = true;
while (ss.good() && !ss.eof())
{
if (first)
{
first = false;
groups_.push_back(known_groups[i].name_);
}
std::string solver; ss >> solver >> std::ws;
possible_kinematics_solvers[known_groups[i].name_].push_back(solver);
ROS_DEBUG("Using kinematics solver '%s' for group '%s'.", solver.c_str(), known_groups[i].name_.c_str());
}
}
}
std::string ksolver_timeout_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_timeout", ksolver_timeout_param_name))
{
double ksolver_timeout;
if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout))
ik_timeout_[known_groups[i].name_] = ksolver_timeout;
else
{// just in case this is an int
int ksolver_timeout_i;
if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout_i))
ik_timeout_[known_groups[i].name_] = ksolver_timeout_i;
}
}
std::string ksolver_attempts_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_attempts", ksolver_attempts_param_name))
{
int ksolver_attempts;
if (nh.getParam(ksolver_attempts_param_name, ksolver_attempts))
ik_attempts_[known_groups[i].name_] = ksolver_attempts;
}
std::string ksolver_res_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_search_resolution", ksolver_res_param_name))
{
std::string ksolver_res;
if (nh.getParam(ksolver_res_param_name, ksolver_res))
{
std::stringstream ss(ksolver_res);
while (ss.good() && !ss.eof())
{
double res; ss >> res >> std::ws;
search_res[known_groups[i].name_].push_back(res);
}
}
else
{ // handle the case this param is just one value and parsed as a double
double res;
if (nh.getParam(ksolver_res_param_name, res))
search_res[known_groups[i].name_].push_back(res);
else
{
int res_i;
if (nh.getParam(ksolver_res_param_name, res_i))
search_res[known_groups[i].name_].push_back(res_i);
}
}
}
std::string ksolver_ik_link_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_ik_link", ksolver_ik_link_param_name))
{
std::string ksolver_ik_link;
if (nh.getParam(ksolver_ik_link_param_name, ksolver_ik_link))
ik_links[known_groups[i].name_] = ksolver_ik_link;
}
// make sure there is a default resolution at least specified for every solver (in case it was not specified on the param server)
while (search_res[known_groups[i].name_].size() < possible_kinematics_solvers[known_groups[i].name_].size())
search_res[known_groups[i].name_].push_back(default_search_resolution_);
}
}
else
{
ROS_DEBUG("Using specified default settings for kinematics solvers ...");
for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
{
possible_kinematics_solvers[known_groups[i].name_].resize(1, default_solver_plugin_);
search_res[known_groups[i].name_].resize(1, default_search_resolution_);
ik_timeout_[known_groups[i].name_] = default_solver_timeout_;
ik_attempts_[known_groups[i].name_] = default_ik_attempts_;
groups_.push_back(known_groups[i].name_);
}
}
}
loader_.reset(new KinematicsLoaderImpl(robot_description_, possible_kinematics_solvers, search_res, ik_links));
}
return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
}
<commit_msg>Added debug info to remind user to load kinematics.yaml<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/kinematics_plugin_loader/kinematics_plugin_loader.h>
#include <moveit/rdf_loader/rdf_loader.h>
#include <pluginlib/class_loader.h>
#include <boost/thread/mutex.hpp>
#include <sstream>
#include <vector>
#include <map>
#include <ros/ros.h>
#include <moveit/profiler/profiler.h>
namespace kinematics_plugin_loader
{
const double KinematicsPluginLoader::DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION = 0.1;
class KinematicsPluginLoader::KinematicsLoaderImpl
{
public:
KinematicsLoaderImpl(const std::string &robot_description,
const std::map<std::string, std::vector<std::string> > &possible_kinematics_solvers,
const std::map<std::string, std::vector<double> > &search_res,
const std::map<std::string, std::string> &ik_links) :
robot_description_(robot_description),
possible_kinematics_solvers_(possible_kinematics_solvers),
search_res_(search_res),
ik_links_(ik_links)
{
try
{
kinematics_loader_.reset(new pluginlib::ClassLoader<kinematics::KinematicsBase>("moveit_core", "kinematics::KinematicsBase"));
}
catch(pluginlib::PluginlibException& e)
{
ROS_ERROR("Unable to construct kinematics loader. Error: %s", e.what());
}
}
boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolver(const robot_model::JointModelGroup *jmg)
{
boost::shared_ptr<kinematics::KinematicsBase> result;
if (!jmg)
{
ROS_ERROR("Specified group is NULL. Cannot allocate kinematics solver.");
return result;
}
ROS_DEBUG("Received request to allocate kinematics solver for group '%s'", jmg->getName().c_str());
if (kinematics_loader_ && jmg)
{
std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.find(jmg->getName());
if (it != possible_kinematics_solvers_.end())
{
// just to be sure, do not call the same pluginlib instance allocation function in parallel
boost::mutex::scoped_lock slock(lock_);
for (std::size_t i = 0 ; !result && i < it->second.size() ; ++i)
{
try
{
result.reset(kinematics_loader_->createUnmanagedInstance(it->second[i]));
if (result)
{
const std::vector<const robot_model::LinkModel*> &links = jmg->getLinkModels();
if (!links.empty())
{
const std::string &base = links.front()->getParentJointModel()->getParentLinkModel() ?
links.front()->getParentJointModel()->getParentLinkModel()->getName() : jmg->getParentModel()->getModelFrame();
std::map<std::string, std::string>::const_iterator ik_it = ik_links_.find(jmg->getName());
const std::string &tip = ik_it != ik_links_.end() ? ik_it->second : links.back()->getName();
double search_res = search_res_.find(jmg->getName())->second[i]; // we know this exists, by construction
if (!result->initialize(robot_description_, jmg->getName(), base, tip, search_res))
{
ROS_ERROR("Kinematics solver of type '%s' could not be initialized for group '%s'", it->second[i].c_str(), jmg->getName().c_str());
result.reset();
}
else
ROS_DEBUG("Successfully allocated and initialized a kinematics solver of type '%s' with search resolution %lf for group '%s' at address %p",
it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());
}
else
ROS_ERROR("No links specified for group '%s'", jmg->getName().c_str());
}
}
catch (pluginlib::PluginlibException& e)
{
ROS_ERROR("The kinematics plugin (%s) failed to load. Error: %s", it->first.c_str(), e.what());
}
}
}
else
ROS_DEBUG("No kinematics solver available for this group");
}
if (!result)
{
ROS_DEBUG("No usable kinematics solver was found for this group.");
ROS_DEBUG("Did you load kinematics.yaml into your node's namespace?");
}
return result;
}
boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolverWithCache(const robot_model::JointModelGroup *jmg)
{
{
boost::mutex::scoped_lock slock(lock_);
const std::vector<boost::shared_ptr<kinematics::KinematicsBase> > &vi = instances_[jmg];
for (std::size_t i = 0 ; i < vi.size() ; ++i)
if (vi[i].unique())
{
ROS_DEBUG("Reusing cached kinematics solver for group '%s'", jmg->getName().c_str());
return vi[i]; // this is safe since the shared_ptr is copied on stack BEFORE the destructors in scope get called
}
}
boost::shared_ptr<kinematics::KinematicsBase> res = allocKinematicsSolver(jmg);
{
boost::mutex::scoped_lock slock(lock_);
instances_[jmg].push_back(res);
return res;
}
}
void status() const
{
for (std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.begin() ; it != possible_kinematics_solvers_.end() ; ++it)
for (std::size_t i = 0 ; i < it->second.size() ; ++i)
ROS_INFO("Solver for group '%s': '%s' (search resolution = %lf)", it->first.c_str(), it->second[i].c_str(), search_res_.at(it->first)[i]);
}
private:
std::string robot_description_;
std::map<std::string, std::vector<std::string> > possible_kinematics_solvers_;
std::map<std::string, std::vector<double> > search_res_;
std::map<std::string, std::string> ik_links_;
boost::shared_ptr<pluginlib::ClassLoader<kinematics::KinematicsBase> > kinematics_loader_;
std::map<const robot_model::JointModelGroup*,
std::vector<boost::shared_ptr<kinematics::KinematicsBase> > > instances_;
boost::mutex lock_;
};
}
void kinematics_plugin_loader::KinematicsPluginLoader::status() const
{
if (loader_)
loader_->status();
else
ROS_INFO("Loader function was never required");
}
robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction()
{
moveit::Profiler::ScopedStart prof_start;
moveit::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction");
if (loader_)
return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
rdf_loader::RDFLoader rml(robot_description_);
robot_description_ = rml.getRobotDescription();
return getLoaderFunction(rml.getSRDF());
}
robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction(const boost::shared_ptr<srdf::Model> &srdf_model)
{
moveit::Profiler::ScopedStart prof_start;
moveit::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction(SRDF)");
if (!loader_)
{
ROS_DEBUG("Configuring kinematics solvers");
groups_.clear();
std::map<std::string, std::vector<std::string> > possible_kinematics_solvers;
std::map<std::string, std::vector<double> > search_res;
std::map<std::string, std::string> ik_links;
if (srdf_model)
{
const std::vector<srdf::Model::Group> &known_groups = srdf_model->getGroups();
if (default_search_resolution_ <= std::numeric_limits<double>::epsilon())
default_search_resolution_ = DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION;
if (default_solver_plugin_.empty())
{
ROS_DEBUG("Loading settings for kinematics solvers from the ROS param server ...");
// read data using ROS params
ros::NodeHandle nh("~");
// read the list of plugin names for possible kinematics solvers
for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
{
ROS_DEBUG("Looking for param %s ", (known_groups[i].name_ + "/kinematics_solver").c_str());
std::string ksolver_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver", ksolver_param_name))
{
ROS_DEBUG("Found param %s ", ksolver_param_name.c_str());
std::string ksolver;
if (nh.getParam(ksolver_param_name, ksolver))
{
std::stringstream ss(ksolver);
bool first = true;
while (ss.good() && !ss.eof())
{
if (first)
{
first = false;
groups_.push_back(known_groups[i].name_);
}
std::string solver; ss >> solver >> std::ws;
possible_kinematics_solvers[known_groups[i].name_].push_back(solver);
ROS_DEBUG("Using kinematics solver '%s' for group '%s'.", solver.c_str(), known_groups[i].name_.c_str());
}
}
}
std::string ksolver_timeout_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_timeout", ksolver_timeout_param_name))
{
double ksolver_timeout;
if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout))
ik_timeout_[known_groups[i].name_] = ksolver_timeout;
else
{// just in case this is an int
int ksolver_timeout_i;
if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout_i))
ik_timeout_[known_groups[i].name_] = ksolver_timeout_i;
}
}
std::string ksolver_attempts_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_attempts", ksolver_attempts_param_name))
{
int ksolver_attempts;
if (nh.getParam(ksolver_attempts_param_name, ksolver_attempts))
ik_attempts_[known_groups[i].name_] = ksolver_attempts;
}
std::string ksolver_res_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_search_resolution", ksolver_res_param_name))
{
std::string ksolver_res;
if (nh.getParam(ksolver_res_param_name, ksolver_res))
{
std::stringstream ss(ksolver_res);
while (ss.good() && !ss.eof())
{
double res; ss >> res >> std::ws;
search_res[known_groups[i].name_].push_back(res);
}
}
else
{ // handle the case this param is just one value and parsed as a double
double res;
if (nh.getParam(ksolver_res_param_name, res))
search_res[known_groups[i].name_].push_back(res);
else
{
int res_i;
if (nh.getParam(ksolver_res_param_name, res_i))
search_res[known_groups[i].name_].push_back(res_i);
}
}
}
std::string ksolver_ik_link_param_name;
if (nh.searchParam(known_groups[i].name_ + "/kinematics_solver_ik_link", ksolver_ik_link_param_name))
{
std::string ksolver_ik_link;
if (nh.getParam(ksolver_ik_link_param_name, ksolver_ik_link))
ik_links[known_groups[i].name_] = ksolver_ik_link;
}
// make sure there is a default resolution at least specified for every solver (in case it was not specified on the param server)
while (search_res[known_groups[i].name_].size() < possible_kinematics_solvers[known_groups[i].name_].size())
search_res[known_groups[i].name_].push_back(default_search_resolution_);
}
}
else
{
ROS_DEBUG("Using specified default settings for kinematics solvers ...");
for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
{
possible_kinematics_solvers[known_groups[i].name_].resize(1, default_solver_plugin_);
search_res[known_groups[i].name_].resize(1, default_search_resolution_);
ik_timeout_[known_groups[i].name_] = default_solver_timeout_;
ik_attempts_[known_groups[i].name_] = default_ik_attempts_;
groups_.push_back(known_groups[i].name_);
}
}
}
loader_.reset(new KinematicsLoaderImpl(robot_description_, possible_kinematics_solvers, search_res, ik_links));
}
return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* 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 "Directory.h"
#include "utils/Charsets.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/Directory.h"
#include "medialibrary/filesystem/IFileSystemFactory.h"
#include "File.h"
#include "logging/Logger.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <cassert>
#include <windows.h>
#include <winapifamily.h>
namespace medialibrary
{
namespace fs
{
Directory::Directory( const std::string& mrl , fs::IFileSystemFactory& fsFactory )
: CommonDirectory( fsFactory )
{
m_path = utils::file::toFolderPath(
utils::fs::toAbsolute( utils::file::toLocalPath( mrl ) ) );
assert( *m_path.crbegin() == '/' || *m_path.crbegin() == '\\' );
m_mrl = utils::file::toMrl( m_path );
}
const std::string& Directory::mrl() const
{
return m_mrl;
}
void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
WIN32_FIND_DATA f;
auto pattern = m_path + '*';
auto wpattern = charset::ToWide( pattern.c_str() );
auto h = FindFirstFile( wpattern.get(), &f );
if ( h == INVALID_HANDLE_VALUE )
{
LOG_ERROR( "Failed to browse ", m_path );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
}
do
{
auto file = charset::FromWide( f.cFileName );
if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
continue;
auto fullpath = m_path + file.get();
try
{
if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
m_dirs.emplace_back( m_fsFactory.createDirectory(
m_mrl + utils::url::encode( file.get() ) ) );
else
m_files.emplace_back( std::make_shared<File>( fullpath ) );
}
catch ( const std::system_error& ex )
{
LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
". Ignoring this entry." );
}
} while ( FindNextFile( h, &f ) != 0 );
FindClose( h );
#else
// We must remove the trailing /
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
// «Do not use a trailing backslash (\), which indicates the root directory of a drive»
auto tmpPath = path.substr( 0, m_path.length() - 1 );
auto wpath = charset::ToWide( tmpPath.c_str() );
CREATEFILE2_EXTENDED_PARAMETERS params{};
params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms );
if ( handle == INVALID_HANDLE_VALUE )
{
LOG_ERROR( "Failed to open directory ", m_path );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
}
std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );
// Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
[](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
if ( dirInfo == nullptr )
throw std::bad_alloc();
while ( true )
{
auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
if ( h == 0 )
{
auto error = GetLastError();
if ( error == ERROR_FILE_NOT_FOUND )
break;
else if ( error == ERROR_MORE_DATA )
{
buffSize *= 2;
dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
if ( dirInfo == nullptr )
throw std::bad_alloc();
continue;
}
LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
}
auto file = charset::FromWide( dirInfo->FileName );
if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
continue;
try
{
if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) );
else
m_files.emplace_back( std::make_shared<File>( m_path + file.get()) );
}
catch ( const std::system_error& ex )
{
LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
". Ignoring this entry." );
}
}
#endif
}
}
}
<commit_msg>fix typo when compiling for Windows Store<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* 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 "Directory.h"
#include "utils/Charsets.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/Directory.h"
#include "medialibrary/filesystem/IFileSystemFactory.h"
#include "File.h"
#include "logging/Logger.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <cassert>
#include <windows.h>
#include <winapifamily.h>
namespace medialibrary
{
namespace fs
{
Directory::Directory( const std::string& mrl , fs::IFileSystemFactory& fsFactory )
: CommonDirectory( fsFactory )
{
m_path = utils::file::toFolderPath(
utils::fs::toAbsolute( utils::file::toLocalPath( mrl ) ) );
assert( *m_path.crbegin() == '/' || *m_path.crbegin() == '\\' );
m_mrl = utils::file::toMrl( m_path );
}
const std::string& Directory::mrl() const
{
return m_mrl;
}
void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
WIN32_FIND_DATA f;
auto pattern = m_path + '*';
auto wpattern = charset::ToWide( pattern.c_str() );
auto h = FindFirstFile( wpattern.get(), &f );
if ( h == INVALID_HANDLE_VALUE )
{
LOG_ERROR( "Failed to browse ", m_path );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
}
do
{
auto file = charset::FromWide( f.cFileName );
if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
continue;
auto fullpath = m_path + file.get();
try
{
if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
m_dirs.emplace_back( m_fsFactory.createDirectory(
m_mrl + utils::url::encode( file.get() ) ) );
else
m_files.emplace_back( std::make_shared<File>( fullpath ) );
}
catch ( const std::system_error& ex )
{
LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
". Ignoring this entry." );
}
} while ( FindNextFile( h, &f ) != 0 );
FindClose( h );
#else
// We must remove the trailing /
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
// «Do not use a trailing backslash (\), which indicates the root directory of a drive»
auto tmpPath = m_path.substr( 0, m_path.length() - 1 );
auto wpath = charset::ToWide( tmpPath.c_str() );
CREATEFILE2_EXTENDED_PARAMETERS params{};
params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms );
if ( handle == INVALID_HANDLE_VALUE )
{
LOG_ERROR( "Failed to open directory ", m_path );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
}
std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );
// Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
[](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
if ( dirInfo == nullptr )
throw std::bad_alloc();
while ( true )
{
auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
if ( h == 0 )
{
auto error = GetLastError();
if ( error == ERROR_FILE_NOT_FOUND )
break;
else if ( error == ERROR_MORE_DATA )
{
buffSize *= 2;
dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
if ( dirInfo == nullptr )
throw std::bad_alloc();
continue;
}
LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
}
auto file = charset::FromWide( dirInfo->FileName );
if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
continue;
try
{
if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) );
else
m_files.emplace_back( std::make_shared<File>( m_path + file.get()) );
}
catch ( const std::system_error& ex )
{
LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
". Ignoring this entry." );
}
}
#endif
}
}
}
<|endoftext|>
|
<commit_before>/************************************************************
COSC 501
Elliott Plack
19 NOV 2013 Due 25 NOV 2013
Problem: Create a 1-dimensional array with n elements; get
the size of the array as user input (validate!), max size
should be 10 (declared as class constant). Perform a
variety of functions with the array.
Algorithm: Get array size from user, validate, get values,
perform functions.
************************************************************/
#include <iostream>
using namespace std;
// various array handling functions
float average(float numbers[]);
void even(float numbers[]);
void odd(float numbers[]);
float evenSum(float numbers[]);
float oddSum(float numbers[]);
int main()
{
// redo with arrays
// copy back in commit c864814b032eff90c493701556f869aff79629d4
//https://github.com/talllguy/Lab12/blob/c864814b032eff90c493701556f869aff79629d4/Lab12array.cpp
int arraySize = 0; // size of the array
const int maxArraySize = 10; // max size of the array
float averageNum(0), evenSumNum(0), oddSumNum(0); // variables that returns will be stored in
cout << "This program does a number of calculations on an array.\n"
<< "Enter the size of the array up to 10.\n";
while (!(cin >> arraySize) || arraySize < 1 || arraySize > maxArraySize) // validate
{
cin.clear(); // Clear the error flags
cin.ignore(100, '\n'); // Remove unwanted characters from buffer
cout << "\aEnter a positive integer, less than 10: "; // Re-issue the prompt
}
// test:
cout << arraySize;
float *numbers;
numbers = new float[arraySize]; // declare numbers array with 'elements' (n) positions
for (int i = 0; i < arraySize; i++) // loop to fill array
{
cout << "Position " << (i + 1) << ": "; // display the iterator + 1 since it begins as 0
while ((!(cin >> numbers[i]))) //detects errors in input
{
cin.clear(); // Clear the error flags
cin.ignore(100, '\n'); // Remove unwanted characters from buffer
cout << "\aInput Error. Please enter a number only.\n" // if error, sound the alarm
<< "Position " << (i + 1) << ": ";
}
}
cout << "\nExcellent. Your inputs are:\n";
cout << "| "; // first separator for clarity
for (int i = 0; i < arraySize; i++) // test loop to output variables in positions
{
cout << numbers[i] << " | "; // put formatted separator in
}
return 0;
}<commit_msg>removed test<commit_after>/************************************************************
COSC 501
Elliott Plack
19 NOV 2013 Due 25 NOV 2013
Problem: Create a 1-dimensional array with n elements; get
the size of the array as user input (validate!), max size
should be 10 (declared as class constant). Perform a
variety of functions with the array.
Algorithm: Get array size from user, validate, get values,
perform functions.
************************************************************/
#include <iostream>
using namespace std;
// various array handling functions
float average(float numbers[]);
void even(float numbers[]);
void odd(float numbers[]);
float evenSum(float numbers[]);
float oddSum(float numbers[]);
int main()
{
// redo with arrays
// copy back in commit c864814b032eff90c493701556f869aff79629d4
//https://github.com/talllguy/Lab12/blob/c864814b032eff90c493701556f869aff79629d4/Lab12array.cpp
int arraySize = 0; // size of the array
const int maxArraySize = 10; // max size of the array
float averageNum(0), evenSumNum(0), oddSumNum(0); // variables that returns will be stored in
cout << "This program does a number of calculations on an array.\n"
<< "Enter the size of the array up to 10.\n";
while (!(cin >> arraySize) || arraySize < 1 || arraySize > maxArraySize) // validate
{
cin.clear(); // Clear the error flags
cin.ignore(100, '\n'); // Remove unwanted characters from buffer
cout << "\aEnter a positive integer, less than 10: "; // Re-issue the prompt
}
float *numbers;
numbers = new float[arraySize]; // declare numbers array with 'elements' (n) positions
for (int i = 0; i < arraySize; i++) // loop to fill array
{
cout << "Position " << (i + 1) << ": "; // display the iterator + 1 since it begins as 0
while ((!(cin >> numbers[i]))) //detects errors in input
{
cin.clear(); // Clear the error flags
cin.ignore(100, '\n'); // Remove unwanted characters from buffer
cout << "\aInput Error. Please enter a number only.\n" // if error, sound the alarm
<< "Position " << (i + 1) << ": ";
}
}
cout << "\nExcellent. Your inputs are:\n";
cout << "| "; // first separator for clarity
for (int i = 0; i < arraySize; i++) // test loop to output variables in positions
{
cout << numbers[i] << " | "; // put formatted separator in
}
return 0;
}<|endoftext|>
|
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file opt_constant_variable.cpp
*
* Marks variables assigned a single constant value over the course
* of the program as constant.
*
* The goal here is to trigger further constant folding and then dead
* code elimination. This is common with vector/matrix constructors
* and calls to builtin functions.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"
namespace {
struct assignment_entry {
exec_node link;
int assignment_count;
ir_variable *var;
ir_constant *constval;
bool our_scope;
};
class ir_constant_variable_visitor : public ir_hierarchical_visitor {
public:
virtual ir_visitor_status visit_enter(ir_dereference_variable *);
virtual ir_visitor_status visit(ir_variable *);
virtual ir_visitor_status visit_enter(ir_assignment *);
virtual ir_visitor_status visit_enter(ir_call *);
exec_list list;
};
} /* unnamed namespace */
static struct assignment_entry *
get_assignment_entry(ir_variable *var, exec_list *list)
{
struct assignment_entry *entry;
foreach_list_typed(struct assignment_entry, entry, link, list) {
if (entry->var == var)
return entry;
}
entry = (struct assignment_entry *)calloc(1, sizeof(*entry));
entry->var = var;
list->push_head(&entry->link);
return entry;
}
ir_visitor_status
ir_constant_variable_visitor::visit(ir_variable *ir)
{
struct assignment_entry *entry = get_assignment_entry(ir, &this->list);
entry->our_scope = true;
return visit_continue;
}
/* Skip derefs of variables so that we can detect declarations. */
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_dereference_variable *ir)
{
(void)ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_assignment *ir)
{
ir_constant *constval;
struct assignment_entry *entry;
entry = get_assignment_entry(ir->lhs->variable_referenced(), &this->list);
assert(entry);
entry->assignment_count++;
/* If it's already constant, don't do the work. */
if (entry->var->constant_value)
return visit_continue;
/* OK, now find if we actually have all the right conditions for
* this to be a constant value assigned to the var.
*/
if (ir->condition)
return visit_continue;
ir_variable *var = ir->whole_variable_written();
if (!var)
return visit_continue;
constval = ir->rhs->constant_expression_value();
if (!constval)
return visit_continue;
/* Mark this entry as having a constant assignment (if the
* assignment count doesn't go >1). do_constant_variable will fix
* up the variable with the constant value later.
*/
entry->constval = constval;
return visit_continue;
}
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_call *ir)
{
/* Mark any out parameters as assigned to */
exec_list_iterator sig_iter = ir->callee->parameters.iterator();
foreach_iter(exec_list_iterator, iter, *ir) {
ir_rvalue *param_rval = (ir_rvalue *)iter.get();
ir_variable *param = (ir_variable *)sig_iter.get();
if (param->mode == ir_var_out ||
param->mode == ir_var_inout) {
ir_variable *var = param_rval->variable_referenced();
struct assignment_entry *entry;
assert(var);
entry = get_assignment_entry(var, &this->list);
entry->assignment_count++;
}
sig_iter.next();
}
/* Mark the return storage as having been assigned to */
if (ir->return_deref != NULL) {
ir_variable *var = ir->return_deref->variable_referenced();
struct assignment_entry *entry;
assert(var);
entry = get_assignment_entry(var, &this->list);
entry->assignment_count++;
}
return visit_continue;
}
/**
* Does a copy propagation pass on the code present in the instruction stream.
*/
bool
do_constant_variable(exec_list *instructions)
{
bool progress = false;
ir_constant_variable_visitor v;
v.run(instructions);
while (!v.list.is_empty()) {
struct assignment_entry *entry;
entry = exec_node_data(struct assignment_entry, v.list.head, link);
if (entry->assignment_count == 1 && entry->constval && entry->our_scope) {
entry->var->constant_value = entry->constval;
progress = true;
}
entry->link.remove();
free(entry);
}
return progress;
}
bool
do_constant_variable_unlinked(exec_list *instructions)
{
bool progress = false;
foreach_iter(exec_list_iterator, iter, *instructions) {
ir_instruction *ir = (ir_instruction *)iter.get();
ir_function *f = ir->as_function();
if (f) {
foreach_iter(exec_list_iterator, sigiter, *f) {
ir_function_signature *sig =
(ir_function_signature *) sigiter.get();
if (do_constant_variable(&sig->body))
progress = true;
}
}
}
return progress;
}
<commit_msg>fix too eager constant variable optimization v2; mark function input parameters as being assigned to<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file opt_constant_variable.cpp
*
* Marks variables assigned a single constant value over the course
* of the program as constant.
*
* The goal here is to trigger further constant folding and then dead
* code elimination. This is common with vector/matrix constructors
* and calls to builtin functions.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_optimization.h"
#include "glsl_types.h"
namespace {
struct assignment_entry {
exec_node link;
int assignment_count;
ir_variable *var;
ir_constant *constval;
bool our_scope;
};
class ir_constant_variable_visitor : public ir_hierarchical_visitor {
public:
virtual ir_visitor_status visit_enter(ir_dereference_variable *);
virtual ir_visitor_status visit(ir_variable *);
virtual ir_visitor_status visit_enter(ir_assignment *);
virtual ir_visitor_status visit_enter(ir_call *);
virtual ir_visitor_status visit_enter(ir_function_signature *);
exec_list list;
};
} /* unnamed namespace */
static struct assignment_entry *
get_assignment_entry(ir_variable *var, exec_list *list)
{
struct assignment_entry *entry;
foreach_list_typed(struct assignment_entry, entry, link, list) {
if (entry->var == var)
return entry;
}
entry = (struct assignment_entry *)calloc(1, sizeof(*entry));
entry->var = var;
list->push_head(&entry->link);
return entry;
}
ir_visitor_status
ir_constant_variable_visitor::visit(ir_variable *ir)
{
struct assignment_entry *entry = get_assignment_entry(ir, &this->list);
entry->our_scope = true;
return visit_continue;
}
/* Skip derefs of variables so that we can detect declarations. */
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_dereference_variable *ir)
{
(void)ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_assignment *ir)
{
ir_constant *constval;
struct assignment_entry *entry;
entry = get_assignment_entry(ir->lhs->variable_referenced(), &this->list);
assert(entry);
entry->assignment_count++;
/* If it's already constant, don't do the work. */
if (entry->var->constant_value)
return visit_continue;
/* OK, now find if we actually have all the right conditions for
* this to be a constant value assigned to the var.
*/
if (ir->condition)
return visit_continue;
ir_variable *var = ir->whole_variable_written();
if (!var)
return visit_continue;
constval = ir->rhs->constant_expression_value();
if (!constval)
return visit_continue;
/* Mark this entry as having a constant assignment (if the
* assignment count doesn't go >1). do_constant_variable will fix
* up the variable with the constant value later.
*/
entry->constval = constval;
return visit_continue;
}
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_call *ir)
{
/* Mark any out parameters as assigned to */
exec_list_iterator sig_iter = ir->callee->parameters.iterator();
foreach_iter(exec_list_iterator, iter, *ir) {
ir_rvalue *param_rval = (ir_rvalue *)iter.get();
ir_variable *param = (ir_variable *)sig_iter.get();
if (param->mode == ir_var_out ||
param->mode == ir_var_inout) {
ir_variable *var = param_rval->variable_referenced();
struct assignment_entry *entry;
assert(var);
entry = get_assignment_entry(var, &this->list);
entry->assignment_count++;
}
sig_iter.next();
}
/* Mark the return storage as having been assigned to */
if (ir->return_deref != NULL) {
ir_variable *var = ir->return_deref->variable_referenced();
struct assignment_entry *entry;
assert(var);
entry = get_assignment_entry(var, &this->list);
entry->assignment_count++;
}
return visit_continue;
}
ir_visitor_status
ir_constant_variable_visitor::visit_enter(ir_function_signature *ir)
{
/* Mark any in parameters as assigned to */
foreach_iter(exec_list_iterator, iter, ir->parameters) {
ir_variable *var = (ir_variable *)iter.get();
if (var->mode == ir_var_in || var->mode == ir_var_const_in || var->mode == ir_var_inout) {
struct assignment_entry *entry;
entry = get_assignment_entry(var, &this->list);
entry->assignment_count++;
}
}
visit_list_elements(this, &ir->body);
return visit_continue_with_parent;
}
/**
* Does a copy propagation pass on the code present in the instruction stream.
*/
bool
do_constant_variable(exec_list *instructions)
{
bool progress = false;
ir_constant_variable_visitor v;
v.run(instructions);
while (!v.list.is_empty()) {
struct assignment_entry *entry;
entry = exec_node_data(struct assignment_entry, v.list.head, link);
if (entry->assignment_count == 1 && entry->constval && entry->our_scope) {
entry->var->constant_value = entry->constval;
progress = true;
}
entry->link.remove();
free(entry);
}
return progress;
}
bool
do_constant_variable_unlinked(exec_list *instructions)
{
bool progress = false;
foreach_iter(exec_list_iterator, iter, *instructions) {
ir_instruction *ir = (ir_instruction *)iter.get();
ir_function *f = ir->as_function();
if (f) {
foreach_iter(exec_list_iterator, sigiter, *f) {
ir_function_signature *sig =
(ir_function_signature *) sigiter.get();
if (do_constant_variable(&sig->body))
progress = true;
}
}
}
return progress;
}
<|endoftext|>
|
<commit_before>/* conduitConfigDialog.cc KPilot
**
** Copyright (C) 2004 by Dan Pilone
** Written 2004 by Reinhold Kainhofer
**
** This file defines a .ui-based configuration dialog for conduits.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
static const char *conduitconfigdialog_id =
"$Id$";
//#include "options.h"
#include <qpushbutton.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfigskeleton.h>
#include "kpilotConfig.h"
#include "options.h"
#include "kpilotConfigWizard_base1.h"
#include "kpilotConfigWizard_base2.h"
#include "kpilotConfigWizard_base3.h"
#include "kpilotConfigWizard.moc"
#include "kpilotProbeDialog.h"
ConfigWizard::ConfigWizard(QWidget *parent, const char *n) :
KWizard(parent, n)
{
page1=new ConfigWizard_base1(this);
addPage( page1, i18n("Select connection type") );
page2=new ConfigWizard_base2(this);
addPage( page2, i18n("Pilot info") );
page3=new ConfigWizard_base3(this);
addPage( page3, i18n("Application to sync with") );
setFinishEnabled( page3, true );
connect( page2->fProbeButton, SIGNAL( pressed() ),
this, SLOT( probeHandheld() ) );
KPilotSettings::self()->readConfig();
page2->fUserName->setText( KPilotSettings::userName() );
page2->fDeviceName->setText( KPilotSettings::pilotDevice() );
page2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() );
}
ConfigWizard::~ConfigWizard()
{
}
void ConfigWizard::accept()
{
FUNCTIONSETUP;
QString username( page2->fUserName->text() );
QString devicename( page2->fDeviceName->text() );
// int devicetype( page1->fConnectionType->selectedId() );
enum eSyncApp {
eAppKDE=0,
eAppKontact,
eAppEvolution
} app;
app=(eSyncApp)( page3->fAppType->selectedId() );
bool keepPermanently( page2->fPilotRunningPermanently->isChecked() );
#ifdef DEBUG
DEBUGCONDUIT<<fname<<"Keep permanently: "<<keepPermanently<<endl;
#endif
KPilotSettings::setPilotDevice( devicename );
KPilotSettings::setUserName(username);
KPilotSettings::setEncoding("iso 8859-15");
KPilotSettings::setDockDaemon( true );
KPilotSettings::setKillDaemonAtExit( !keepPermanently);
KPilotSettings::setQuitAfterSync( !keepPermanently );
KPilotSettings::setStartDaemonAtLogin( keepPermanently );
KPilotSettings::setSyncType(0);
KPilotSettings::setFullSyncOnPCChange( true );
KPilotSettings::setConflictResolution(0);
QStringList conduits = KPilotSettings::installedConduits();
// TODO: enable the right conduits
#define APPEND_CONDUIT(a) if (!conduits.contains(a)) conduits.append(a)
QString applicationName(i18n("general KDE-PIM"));
APPEND_CONDUIT("internal_fileinstall");
APPEND_CONDUIT("todo-conduit");
APPEND_CONDUIT("vcal-conduit");
switch (app) {
case eAppEvolution:
applicationName=i18n("Gnome's PIM suite", "Evolution");
conduits.remove("knotes-conduit");
// TODO: Once the Evolution abook resource is finished, enable it...
conduits.remove("abbrowser_conduit");
// TODO: settings for conduits
KMessageBox::information(this, i18n("KPilot cannot yet synchronize the addressbook with Evolution, so the addressbook conduit was disabled.\nWhen syncing the calendar or todo list using KPilot, please quit Evolution before the sync, otherwise you will loose data."), i18n("Restrictions with Evolution"));
break;
case eAppKontact:
applicationName=i18n("KDE's PIM suite", "Kontact");
case eAppKDE:
default:
APPEND_CONDUIT("knotes-conduit");
APPEND_CONDUIT("abbrowser_conduit");
// TODO: settings for conduits
break;
}
KPilotSettings::setInstalledConduits( conduits );
#undef APPEND_CONDUIT
KMessageBox::information(this, i18n("KPilot is now configured to sync with %1.\n"
"The remaining options in the config dialog are advanced options and can "
"be used to fine-tune KPilot.").arg(applicationName), i18n("Automatic configuration finished"));
KPilotSettings::self()->writeConfig();
QDialog::accept();
}
// Devices to probe:
// Linux: /dev/pilot (symlink), /dev/ttyS* (serial + irda), /dev/tts/[012345...] (with devfs),
// /dev/ttyUSB*, /dev/usb/tts/[012345...]
// *BSD: /dev/pilot, /dev/cuaa[01] (serial), /dev/ucom* (usb)
void ConfigWizard::probeHandheld()
{
ProbeDialog *probeDialog = new ProbeDialog( this );
if ( probeDialog->exec() && probeDialog->detected() ) {
page2->fUserName->setText( probeDialog->userName() );
page2->fDeviceName->setText( probeDialog->device() );
}
KPILOT_DELETE(probeDialog);
}
<commit_msg><commit_after>/* conduitConfigDialog.cc KPilot
**
** Copyright (C) 2004 by Dan Pilone
** Written 2004 by Reinhold Kainhofer
**
** This file defines a .ui-based configuration dialog for conduits.
*/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
static const char *conduitconfigdialog_id =
"$Id$";
//#include "options.h"
#include <qpushbutton.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfigskeleton.h>
#include "kpilotConfig.h"
#include "options.h"
#include "kpilotConfigWizard_base1.h"
#include "kpilotConfigWizard_base2.h"
#include "kpilotConfigWizard_base3.h"
#include "kpilotConfigWizard.moc"
#include "kpilotProbeDialog.h"
ConfigWizard::ConfigWizard(QWidget *parent, const char *n) :
KWizard(parent, n)
{
page1=new ConfigWizard_base1(this);
addPage( page1, i18n("Select connection type") );
page2=new ConfigWizard_base2(this);
addPage( page2, i18n("Pilot info") );
page3=new ConfigWizard_base3(this);
addPage( page3, i18n("Application to sync with") );
setFinishEnabled( page3, true );
connect( page2->fProbeButton, SIGNAL( pressed() ),
this, SLOT( probeHandheld() ) );
KPilotSettings::self()->readConfig();
page2->fUserName->setText( KPilotSettings::userName() );
page2->fDeviceName->setText( KPilotSettings::pilotDevice() );
page2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() );
}
ConfigWizard::~ConfigWizard()
{
}
void ConfigWizard::accept()
{
FUNCTIONSETUP;
QString username( page2->fUserName->text() );
QString devicename( page2->fDeviceName->text() );
// int devicetype( page1->fConnectionType->selectedId() );
enum eSyncApp {
eAppKDE=0,
eAppKontact,
eAppEvolution
} app;
app=(eSyncApp)( page3->fAppType->selectedId() );
bool keepPermanently( page2->fPilotRunningPermanently->isChecked() );
#ifdef DEBUG
DEBUGCONDUIT<<fname<<"Keep permanently: "<<keepPermanently<<endl;
#endif
KPilotSettings::setPilotDevice( devicename );
KPilotSettings::setUserName(username);
KPilotSettings::setEncoding("iso 8859-15");
KPilotSettings::setDockDaemon( true );
KPilotSettings::setKillDaemonAtExit( !keepPermanently);
KPilotSettings::setQuitAfterSync( !keepPermanently );
KPilotSettings::setStartDaemonAtLogin( keepPermanently );
KPilotSettings::setSyncType(0);
KPilotSettings::setFullSyncOnPCChange( true );
KPilotSettings::setConflictResolution(0);
QStringList conduits = KPilotSettings::installedConduits();
// TODO: enable the right conduits
#define APPEND_CONDUIT(a) if (!conduits.contains(a)) conduits.append(a)
QString applicationName(i18n("general KDE-PIM"));
APPEND_CONDUIT("internal_fileinstall");
APPEND_CONDUIT("todo-conduit");
APPEND_CONDUIT("vcal-conduit");
switch (app) {
case eAppEvolution:
applicationName=i18n("Gnome's PIM suite", "Evolution");
conduits.remove("knotes-conduit");
// TODO: Once the Evolution abook resource is finished, enable it...
conduits.remove("abbrowser_conduit");
// TODO: settings for conduits
KMessageBox::information(this, i18n("KPilot cannot yet synchronize the addressbook with Evolution, so the addressbook conduit was disabled.\nWhen syncing the calendar or todo list using KPilot please quit Evolution before the sync, otherwise you will lose data."), i18n("Restrictions with Evolution"));
break;
case eAppKontact:
applicationName=i18n("KDE's PIM suite", "Kontact");
case eAppKDE:
default:
APPEND_CONDUIT("knotes-conduit");
APPEND_CONDUIT("abbrowser_conduit");
// TODO: settings for conduits
break;
}
KPilotSettings::setInstalledConduits( conduits );
#undef APPEND_CONDUIT
KMessageBox::information(this, i18n("KPilot is now configured to sync with %1.\n"
"The remaining options in the config dialog are advanced options and can "
"be used to fine-tune KPilot.").arg(applicationName), i18n("Automatic configuration finished"));
KPilotSettings::self()->writeConfig();
QDialog::accept();
}
// Devices to probe:
// Linux: /dev/pilot (symlink), /dev/ttyS* (serial + irda), /dev/tts/[012345...] (with devfs),
// /dev/ttyUSB*, /dev/usb/tts/[012345...]
// *BSD: /dev/pilot, /dev/cuaa[01] (serial), /dev/ucom* (usb)
void ConfigWizard::probeHandheld()
{
ProbeDialog *probeDialog = new ProbeDialog( this );
if ( probeDialog->exec() && probeDialog->detected() ) {
page2->fUserName->setText( probeDialog->userName() );
page2->fDeviceName->setText( probeDialog->device() );
}
KPILOT_DELETE(probeDialog);
}
<|endoftext|>
|
<commit_before>/* libwpd
* Copyright (C) 2004 Marc Maurer (uwog@uwog.net)
* Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include "WP3FileStructure.h"
#include "WP3VariableLengthGroup.h"
#include "WP3UnsupportedVariableLengthGroup.h"
#include "WP3EndOfLinePageGroup.h"
#include "WP3MiscellaneousGroup.h"
#include "WP3PageFormatGroup.h"
#include "WP3FontGroup.h"
#include "WP3DefinitionGroup.h"
#include "WP3DisplayGroup.h"
#include "WP3HeaderFooterGroup.h"
#include "WP3FootnoteEndnoteGroup.h"
#include "WP3TablesGroup.h"
#include "libwpd_internal.h"
WP3VariableLengthGroup::WP3VariableLengthGroup()
{
}
WP3VariableLengthGroup * WP3VariableLengthGroup::constructVariableLengthGroup(WPXInputStream *input, uint8_t group)
{
switch (group)
{
case WP3_PAGE_FORMAT_GROUP:
return new WP3PageFormatGroup(input);
case WP3_END_OF_LINE_PAGE_GROUP:
return new WP3EndOfLinePageGroup(input);
case WP3_MISCELLANEOUS_GROUP:
return new WP3MiscellaneousGroup(input);
case WP3_TABLES_GROUP:
return new WP3TablesGroup(input);
case WP3_FONT_GROUP:
return new WP3FontGroup(input);
case WP3_DEFINITION_GROUP:
return new WP3DefinitionGroup(input);
case WP3_HEADER_FOOTER_GROUP:
return new WP3HeaderFooterGroup(input);
case WP3_FOOTNOTE_ENDNOTE_GROUP:
return new WP3FootnoteEndnoteGroup(input);
case WP3_DISPLAY_GROUP:
return new WP3DisplayGroup(input);
default:
// this is an unhandled group, just skip it
return new WP3UnsupportedVariableLengthGroup(input);
}
}
bool WP3VariableLengthGroup::isGroupConsistent(WPXInputStream *input, const uint8_t group)
{
uint32_t startPosition = input->tell();
try
{
uint8_t subGroup = readU8(input);
uint16_t size = readU16(input, true);
if (input->seek((startPosition + size - 1 - input->tell()), WPX_SEEK_CUR) || input->atEOS())
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
if (size != readU16(input, true))
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
if (subGroup != readU8(input))
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
if (group != readU8(input))
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
input->seek(startPosition, WPX_SEEK_SET);
return true;
}
catch(...)
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
}
void WP3VariableLengthGroup::_read(WPXInputStream *input)
{
uint32_t startPosition = input->tell();
WPD_DEBUG_MSG(("WordPerfect: handling a variable length group\n"));
m_subGroup = readU8(input);
m_size = readU16(input, true) + 4; // the length is the number of data bytes minus 4 (ie. the function codes)
WPD_DEBUG_MSG(("WordPerfect: Read variable group header (start_position: %i, sub_group: 0x%x, size: %i)\n", startPosition, m_subGroup, m_size));
_readContents(input);
input->seek((startPosition + m_size - 5 - input->tell()), WPX_SEEK_CUR);
if (m_size != (readU16(input, true) + 4))
{
WPD_DEBUG_MSG(("WordPerfect: Possible corruption detected. Bailing out!\n"));
throw FileException();
}
if (m_subGroup != readU8(input))
{
WPD_DEBUG_MSG(("WordPerfect: Possible corruption detected. Bailing out!\n"));
throw FileException();
}
input->seek((startPosition + m_size - 1 - input->tell()), WPX_SEEK_CUR);
}
<commit_msg>Adding a missing const<commit_after>/* libwpd
* Copyright (C) 2004 Marc Maurer (uwog@uwog.net)
* Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include "WP3FileStructure.h"
#include "WP3VariableLengthGroup.h"
#include "WP3UnsupportedVariableLengthGroup.h"
#include "WP3EndOfLinePageGroup.h"
#include "WP3MiscellaneousGroup.h"
#include "WP3PageFormatGroup.h"
#include "WP3FontGroup.h"
#include "WP3DefinitionGroup.h"
#include "WP3DisplayGroup.h"
#include "WP3HeaderFooterGroup.h"
#include "WP3FootnoteEndnoteGroup.h"
#include "WP3TablesGroup.h"
#include "libwpd_internal.h"
WP3VariableLengthGroup::WP3VariableLengthGroup()
{
}
WP3VariableLengthGroup * WP3VariableLengthGroup::constructVariableLengthGroup(WPXInputStream *input, const uint8_t group)
{
switch (group)
{
case WP3_PAGE_FORMAT_GROUP:
return new WP3PageFormatGroup(input);
case WP3_END_OF_LINE_PAGE_GROUP:
return new WP3EndOfLinePageGroup(input);
case WP3_MISCELLANEOUS_GROUP:
return new WP3MiscellaneousGroup(input);
case WP3_TABLES_GROUP:
return new WP3TablesGroup(input);
case WP3_FONT_GROUP:
return new WP3FontGroup(input);
case WP3_DEFINITION_GROUP:
return new WP3DefinitionGroup(input);
case WP3_HEADER_FOOTER_GROUP:
return new WP3HeaderFooterGroup(input);
case WP3_FOOTNOTE_ENDNOTE_GROUP:
return new WP3FootnoteEndnoteGroup(input);
case WP3_DISPLAY_GROUP:
return new WP3DisplayGroup(input);
default:
// this is an unhandled group, just skip it
return new WP3UnsupportedVariableLengthGroup(input);
}
}
bool WP3VariableLengthGroup::isGroupConsistent(WPXInputStream *input, const uint8_t group)
{
uint32_t startPosition = input->tell();
try
{
uint8_t subGroup = readU8(input);
uint16_t size = readU16(input, true);
if (input->seek((startPosition + size - 1 - input->tell()), WPX_SEEK_CUR) || input->atEOS())
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
if (size != readU16(input, true))
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
if (subGroup != readU8(input))
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
if (group != readU8(input))
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
input->seek(startPosition, WPX_SEEK_SET);
return true;
}
catch(...)
{
input->seek(startPosition, WPX_SEEK_SET);
return false;
}
}
void WP3VariableLengthGroup::_read(WPXInputStream *input)
{
uint32_t startPosition = input->tell();
WPD_DEBUG_MSG(("WordPerfect: handling a variable length group\n"));
m_subGroup = readU8(input);
m_size = readU16(input, true) + 4; // the length is the number of data bytes minus 4 (ie. the function codes)
WPD_DEBUG_MSG(("WordPerfect: Read variable group header (start_position: %i, sub_group: 0x%x, size: %i)\n", startPosition, m_subGroup, m_size));
_readContents(input);
input->seek((startPosition + m_size - 5 - input->tell()), WPX_SEEK_CUR);
if (m_size != (readU16(input, true) + 4))
{
WPD_DEBUG_MSG(("WordPerfect: Possible corruption detected. Bailing out!\n"));
throw FileException();
}
if (m_subGroup != readU8(input))
{
WPD_DEBUG_MSG(("WordPerfect: Possible corruption detected. Bailing out!\n"));
throw FileException();
}
input->seek((startPosition + m_size - 1 - input->tell()), WPX_SEEK_CUR);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org)
*
* 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 <vector>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <votca/tools/getline.h>
#include "pdbreader.h"
namespace votca { namespace csg {
using namespace boost;
using namespace std;
bool PDBReader::ReadTopology(string file, Topology &top)
{
_topology = true;
top.Cleanup();
_fl.open(file.c_str());
if(!_fl.is_open())
throw std::ios_base::failure("Error on open topology file: " + file);
NextFrame(top);
_fl.close();
return true;
}
bool PDBReader::Open(const string &file)
{
_fl.open(file.c_str());
if(!_fl.is_open())
throw std::ios_base::failure("Error on open trajectory file: " + file);
return true;
}
void PDBReader::Close()
{
_fl.close();
}
bool PDBReader::FirstFrame(Topology &top)
{
_topology = false;
NextFrame(top);
return true;
}
bool PDBReader::NextFrame(Topology &top)
{
string line;
int i = 0 ;
while ( std::getline(_fl, line) ){
if( wildcmp("CRYST1*",line.c_str())){
string a, b, c, alpha, beta, gamma;
try {
//1 - 6 Record name "CRYST1"
a=string(line,(7-1),9); //7 - 15 Real(9.3) a (Angstroms)
b=string(line,(16-1),9); //16 - 24 Real(9.3) b (Angstroms)
c=string(line,(25-1),9); //25 - 33 Real(9.3) c (Angstroms)
alpha=string(line,(34-1),7); //34 - 40 Real(7.2) alpha (degrees)
beta=string(line,(41-1),7); //41 - 47 Real(7.2) beta (degrees)
gamma=string(line,(48-1),7); //48 - 54 Real(7.2) gamma (degrees)
//56 - 66 LString Space group
//67 - 70 Integer Z value
} catch (std::out_of_range& err) {
throw std::runtime_error("Misformated pdb file in CRYST1 line");
}
boost::algorithm::trim(a);
boost::algorithm::trim(b);
boost::algorithm::trim(c);
boost::algorithm::trim(alpha);
boost::algorithm::trim(beta);
boost::algorithm::trim(gamma);
if ((!wildcmp("90*",alpha.c_str()))||(!wildcmp("90*",alpha.c_str()))||(!wildcmp("90*",alpha.c_str()))){
throw std::runtime_error("Non cubical box in pdb file not implemented, yet!");
}
top.setBox(matrix(vec(boost::lexical_cast<double>(a), 0, 0),
vec(0, boost::lexical_cast<double>(b), 0),
vec(0, 0, boost::lexical_cast<double>(c))));
}
if( wildcmp("ATOM*",line.c_str()) || wildcmp("HETATM*",line.c_str())){
// according to PDB format
string x,y,z, resNum, resName, atName;
try {
/* Some pdb don't include all this, read only what we realy need*/
/* leave this here in case we need more later*/
//string recType (line,( 1-1),6); // str, "ATOM", "HETATM"
//string atNum (line,( 7-1),6); // int, Atom serial number
atName=string(line,(13-1),4); // str, Atom name
//string atAltLoc (line,(17-1),1); // char, Alternate location indicator
resName=string(line,(18-1),3); // str, Residue name
//string chainID (line,(22-1),1); // char, Chain identifier
resNum=string(line,(23-1),4); // int, Residue sequence number
//string atICode (line,(27-1),1); // char, Code for insertion of res
x=string(line,(31-1),8); // float 8.3 ,x
y=string(line,(39-1),8); // float 8.3 ,y
z=string(line,(47-1),8); // float 8.3 ,z
//string atOccup (line,(55-1),6); // float 6.2, Occupancy
//string atTFactor (line,(61-1),6); // float 6.2, Temperature factor
//string segID (line,(73-1),4); // str, Segment identifier
//string atElement (line,(77-1),2); // str, Element symbol
//string atCharge (line,(79-1),2); // str, Charge on the atom
} catch (std::out_of_range& err) {
throw std::runtime_error("Misformated pdb file in atom line # "+ boost::lexical_cast<string>(i));
}
boost::algorithm::trim(atName);
boost::algorithm::trim(resName);
boost::algorithm::trim(resNum);
boost::algorithm::trim(x);
boost::algorithm::trim(y);
boost::algorithm::trim(z);
i++;
if(!_topology && i > top.BeadCount())
throw std::runtime_error("number of beads in topology and trajectory differ");
Bead *b;
if(_topology){
int resnr;
try {
resnr = boost::lexical_cast<int>(resNum);
} catch(bad_lexical_cast &) {
throw std::runtime_error("Cannot convert resNum='"+ resNum+"' to int, that usallly means: misformated pdb file");
}
if (resnr < 1)
throw std::runtime_error("Misformated pdb file, resnr has to be > 0");
//TODO: fix the case that resnr is not in ascending order
if(resnr > top.ResidueCount()) {
while ((resnr-1)>top.ResidueCount()){ //pdb resnr should start with 1 but accept sloppy files
top.CreateResidue("DUMMY"); // create dummy residue, hopefully it will never show
cout << "Warning: residue numbers not continous, create DUMMY residue with nr " << top.ResidueCount() << endl;
}
top.CreateResidue(resName);
}
//this is not correct, but still better than no type at all!
BeadType *type = top.GetOrCreateBeadType(atName);
// res -1 as internal number starts with 0
b = top.CreateBead(1, atName, type, resnr-1, 1., 0.);
} else {
b = top.getBead(i-1);
}
// convert to nm from A
b->setPos(vec(
boost::lexical_cast<double>(x)/10.0,
boost::lexical_cast<double>(y)/10.0,
boost::lexical_cast<double>(z)/10.0
));
}
if (( line == "ENDMDL" ) || ( line == "END" ) || ( _fl.eof())){
break;
}
}
if(!_topology && (i>0) && i != top.BeadCount())
throw std::runtime_error("number of beads in topology and trajectory differ");
if (_topology)
cout << "WARNING: topology created from .pdb file, charges and masses are wrong!\n";
return !_fl.eof();
}
}}
<commit_msg>pdbreader: box needs to be scaled as well (A -> nm)<commit_after>/*
* Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org)
*
* 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 <vector>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <votca/tools/getline.h>
#include "pdbreader.h"
namespace votca { namespace csg {
using namespace boost;
using namespace std;
bool PDBReader::ReadTopology(string file, Topology &top)
{
_topology = true;
top.Cleanup();
_fl.open(file.c_str());
if(!_fl.is_open())
throw std::ios_base::failure("Error on open topology file: " + file);
NextFrame(top);
_fl.close();
return true;
}
bool PDBReader::Open(const string &file)
{
_fl.open(file.c_str());
if(!_fl.is_open())
throw std::ios_base::failure("Error on open trajectory file: " + file);
return true;
}
void PDBReader::Close()
{
_fl.close();
}
bool PDBReader::FirstFrame(Topology &top)
{
_topology = false;
NextFrame(top);
return true;
}
bool PDBReader::NextFrame(Topology &top)
{
string line;
int i = 0 ;
while ( std::getline(_fl, line) ){
if( wildcmp("CRYST1*",line.c_str())){
string a, b, c, alpha, beta, gamma;
try {
//1 - 6 Record name "CRYST1"
a=string(line,(7-1),9); //7 - 15 Real(9.3) a (Angstroms)
b=string(line,(16-1),9); //16 - 24 Real(9.3) b (Angstroms)
c=string(line,(25-1),9); //25 - 33 Real(9.3) c (Angstroms)
alpha=string(line,(34-1),7); //34 - 40 Real(7.2) alpha (degrees)
beta=string(line,(41-1),7); //41 - 47 Real(7.2) beta (degrees)
gamma=string(line,(48-1),7); //48 - 54 Real(7.2) gamma (degrees)
//56 - 66 LString Space group
//67 - 70 Integer Z value
} catch (std::out_of_range& err) {
throw std::runtime_error("Misformated pdb file in CRYST1 line");
}
boost::algorithm::trim(a);
boost::algorithm::trim(b);
boost::algorithm::trim(c);
boost::algorithm::trim(alpha);
boost::algorithm::trim(beta);
boost::algorithm::trim(gamma);
if ((!wildcmp("90*",alpha.c_str()))||(!wildcmp("90*",alpha.c_str()))||(!wildcmp("90*",alpha.c_str()))){
throw std::runtime_error("Non cubical box in pdb file not implemented, yet!");
}
top.setBox(matrix(vec(boost::lexical_cast<double>(a)/10.0, 0, 0),
vec(0, boost::lexical_cast<double>(b)/10.0, 0),
vec(0, 0, boost::lexical_cast<double>(c)/10.0)));
}
if( wildcmp("ATOM*",line.c_str()) || wildcmp("HETATM*",line.c_str())){
// according to PDB format
string x,y,z, resNum, resName, atName;
try {
/* Some pdb don't include all this, read only what we realy need*/
/* leave this here in case we need more later*/
//string recType (line,( 1-1),6); // str, "ATOM", "HETATM"
//string atNum (line,( 7-1),6); // int, Atom serial number
atName=string(line,(13-1),4); // str, Atom name
//string atAltLoc (line,(17-1),1); // char, Alternate location indicator
resName=string(line,(18-1),3); // str, Residue name
//string chainID (line,(22-1),1); // char, Chain identifier
resNum=string(line,(23-1),4); // int, Residue sequence number
//string atICode (line,(27-1),1); // char, Code for insertion of res
x=string(line,(31-1),8); // float 8.3 ,x
y=string(line,(39-1),8); // float 8.3 ,y
z=string(line,(47-1),8); // float 8.3 ,z
//string atOccup (line,(55-1),6); // float 6.2, Occupancy
//string atTFactor (line,(61-1),6); // float 6.2, Temperature factor
//string segID (line,(73-1),4); // str, Segment identifier
//string atElement (line,(77-1),2); // str, Element symbol
//string atCharge (line,(79-1),2); // str, Charge on the atom
} catch (std::out_of_range& err) {
throw std::runtime_error("Misformated pdb file in atom line # "+ boost::lexical_cast<string>(i));
}
boost::algorithm::trim(atName);
boost::algorithm::trim(resName);
boost::algorithm::trim(resNum);
boost::algorithm::trim(x);
boost::algorithm::trim(y);
boost::algorithm::trim(z);
i++;
if(!_topology && i > top.BeadCount())
throw std::runtime_error("number of beads in topology and trajectory differ");
Bead *b;
if(_topology){
int resnr;
try {
resnr = boost::lexical_cast<int>(resNum);
} catch(bad_lexical_cast &) {
throw std::runtime_error("Cannot convert resNum='"+ resNum+"' to int, that usallly means: misformated pdb file");
}
if (resnr < 1)
throw std::runtime_error("Misformated pdb file, resnr has to be > 0");
//TODO: fix the case that resnr is not in ascending order
if(resnr > top.ResidueCount()) {
while ((resnr-1)>top.ResidueCount()){ //pdb resnr should start with 1 but accept sloppy files
top.CreateResidue("DUMMY"); // create dummy residue, hopefully it will never show
cout << "Warning: residue numbers not continous, create DUMMY residue with nr " << top.ResidueCount() << endl;
}
top.CreateResidue(resName);
}
//this is not correct, but still better than no type at all!
BeadType *type = top.GetOrCreateBeadType(atName);
// res -1 as internal number starts with 0
b = top.CreateBead(1, atName, type, resnr-1, 1., 0.);
} else {
b = top.getBead(i-1);
}
// convert to nm from A
b->setPos(vec(
boost::lexical_cast<double>(x)/10.0,
boost::lexical_cast<double>(y)/10.0,
boost::lexical_cast<double>(z)/10.0
));
}
if (( line == "ENDMDL" ) || ( line == "END" ) || ( _fl.eof())){
break;
}
}
if(!_topology && (i>0) && i != top.BeadCount())
throw std::runtime_error("number of beads in topology and trajectory differ");
if (_topology)
cout << "WARNING: topology created from .pdb file, charges and masses are wrong!\n";
return !_fl.eof();
}
}}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: morphdlg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2003-11-24 17:10:12 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "strings.hrc"
#include "sdresid.hxx"
#include "sdmod.hxx"
#include "sdiocmpt.hxx"
#include "morphdlg.hxx"
#include "morphdlg.hrc"
#ifndef _SV_CONFIG_HXX //autogen
#include <vcl/config.hxx>
#endif
#ifndef SVX_XFILLIT0_HXX //autogen
#include <svx/xfillit0.hxx>
#endif
#ifndef _SVX_XLINEIT0_HXX //autogen
#include <svx/xlineit0.hxx>
#endif
#ifndef _XENUM_HXX //autogen
#include <svx/xenum.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
/******************************************************************************/
#define FADE_STEP "FadeSteps"
#define FADE_ATTRIB "FadeAttributes"
#define FADE_ORIENT "FadeOrientation"
#define FADE_TRUE "true"
#define FADE_FALSE "false"
/******************************************************************************/
/******************************************************************************
|*
|*
|*
\******************************************************************************/
SdMorphDlg::SdMorphDlg( Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2 ) :
ModalDialog ( pParent, SdResId( DLG_MORPH ) ),
aBtnOK ( this, SdResId( BTN_OK ) ),
aBtnCancel ( this, SdResId( BTN_CANCEL ) ),
aBtnHelp ( this, SdResId( BTN_HELP ) ),
aGrpPreset ( this, SdResId( GRP_PRESET ) ),
aFtSteps ( this, SdResId( FT_STEPS ) ),
aMtfSteps ( this, SdResId( MTF_STEPS ) ),
aCbxAttributes ( this, SdResId( CBX_ATTRIBUTES ) ),
aCbxOrientation ( this, SdResId( CBX_ORIENTATION ) )
{
FreeResource();
LoadSettings();
SfxItemPool* pPool = (SfxItemPool*) pObj1->GetItemPool();
SfxItemSet aSet1( *pPool );
SfxItemSet aSet2( *pPool );
aSet1.Put(pObj1->GetMergedItemSet());
aSet2.Put(pObj2->GetMergedItemSet());
const XLineStyle eLineStyle1 = ( (const XLineStyleItem&) aSet1.Get( XATTR_LINESTYLE ) ).GetValue();
const XLineStyle eLineStyle2 = ( (const XLineStyleItem&) aSet2.Get( XATTR_LINESTYLE ) ).GetValue();
const XFillStyle eFillStyle1 = ( (const XFillStyleItem&) aSet1.Get( XATTR_FILLSTYLE ) ).GetValue();
const XFillStyle eFillStyle2 = ( (const XFillStyleItem&) aSet2.Get( XATTR_FILLSTYLE ) ).GetValue();
if ( ( ( eLineStyle1 == XLINE_NONE ) || ( eLineStyle2 == XLINE_NONE ) ) &&
( ( eFillStyle1 != XFILL_SOLID ) || ( eFillStyle2 != XFILL_SOLID ) ) )
{
aCbxAttributes.Disable();
}
}
/******************************************************************************
|*
|*
|*
\******************************************************************************/
SdMorphDlg::~SdMorphDlg()
{
}
/******************************************************************************
|*
|*
|*
\******************************************************************************/
void SdMorphDlg::LoadSettings()
{
SvStorageStreamRef xIStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(
RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),
SD_OPTION_LOAD ) );
UINT16 nSteps;
BOOL bOrient, bAttrib;
if( xIStm.Is() )
{
SdIOCompat aCompat( *xIStm, STREAM_READ );
*xIStm >> nSteps >> bOrient >> bAttrib;
}
else
{
nSteps = 16;
bOrient = bAttrib = TRUE;
}
aMtfSteps.SetValue( nSteps );
aCbxOrientation.Check( bOrient );
aCbxAttributes.Check( bAttrib );
}
// -----------------------------------------------------------------------------
void SdMorphDlg::SaveSettings() const
{
SvStorageStreamRef xOStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(
RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),
SD_OPTION_STORE ) );
if( xOStm.Is() )
{
SdIOCompat aCompat( *xOStm, STREAM_WRITE, 1 );
*xOStm << (UINT16) aMtfSteps.GetValue()
<< aCbxOrientation.IsChecked()
<< aCbxAttributes.IsChecked();
}
}
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.5.8); FILE MERGED 2003/12/11 09:17:26 mt 1.5.8.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/*************************************************************************
*
* $RCSfile: morphdlg.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2004-01-06 18:44:12 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "strings.hrc"
#include "sdresid.hxx"
#include "sdmod.hxx"
#include "sdiocmpt.hxx"
#include "morphdlg.hxx"
#include "morphdlg.hrc"
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef SVX_XFILLIT0_HXX //autogen
#include <svx/xfillit0.hxx>
#endif
#ifndef _SVX_XLINEIT0_HXX //autogen
#include <svx/xlineit0.hxx>
#endif
#ifndef _XENUM_HXX //autogen
#include <svx/xenum.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
/******************************************************************************/
#define FADE_STEP "FadeSteps"
#define FADE_ATTRIB "FadeAttributes"
#define FADE_ORIENT "FadeOrientation"
#define FADE_TRUE "true"
#define FADE_FALSE "false"
/******************************************************************************/
/******************************************************************************
|*
|*
|*
\******************************************************************************/
SdMorphDlg::SdMorphDlg( Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2 ) :
ModalDialog ( pParent, SdResId( DLG_MORPH ) ),
aBtnOK ( this, SdResId( BTN_OK ) ),
aBtnCancel ( this, SdResId( BTN_CANCEL ) ),
aBtnHelp ( this, SdResId( BTN_HELP ) ),
aGrpPreset ( this, SdResId( GRP_PRESET ) ),
aFtSteps ( this, SdResId( FT_STEPS ) ),
aMtfSteps ( this, SdResId( MTF_STEPS ) ),
aCbxAttributes ( this, SdResId( CBX_ATTRIBUTES ) ),
aCbxOrientation ( this, SdResId( CBX_ORIENTATION ) )
{
FreeResource();
LoadSettings();
SfxItemPool* pPool = (SfxItemPool*) pObj1->GetItemPool();
SfxItemSet aSet1( *pPool );
SfxItemSet aSet2( *pPool );
aSet1.Put(pObj1->GetMergedItemSet());
aSet2.Put(pObj2->GetMergedItemSet());
const XLineStyle eLineStyle1 = ( (const XLineStyleItem&) aSet1.Get( XATTR_LINESTYLE ) ).GetValue();
const XLineStyle eLineStyle2 = ( (const XLineStyleItem&) aSet2.Get( XATTR_LINESTYLE ) ).GetValue();
const XFillStyle eFillStyle1 = ( (const XFillStyleItem&) aSet1.Get( XATTR_FILLSTYLE ) ).GetValue();
const XFillStyle eFillStyle2 = ( (const XFillStyleItem&) aSet2.Get( XATTR_FILLSTYLE ) ).GetValue();
if ( ( ( eLineStyle1 == XLINE_NONE ) || ( eLineStyle2 == XLINE_NONE ) ) &&
( ( eFillStyle1 != XFILL_SOLID ) || ( eFillStyle2 != XFILL_SOLID ) ) )
{
aCbxAttributes.Disable();
}
}
/******************************************************************************
|*
|*
|*
\******************************************************************************/
SdMorphDlg::~SdMorphDlg()
{
}
/******************************************************************************
|*
|*
|*
\******************************************************************************/
void SdMorphDlg::LoadSettings()
{
SvStorageStreamRef xIStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(
RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),
SD_OPTION_LOAD ) );
UINT16 nSteps;
BOOL bOrient, bAttrib;
if( xIStm.Is() )
{
SdIOCompat aCompat( *xIStm, STREAM_READ );
*xIStm >> nSteps >> bOrient >> bAttrib;
}
else
{
nSteps = 16;
bOrient = bAttrib = TRUE;
}
aMtfSteps.SetValue( nSteps );
aCbxOrientation.Check( bOrient );
aCbxAttributes.Check( bAttrib );
}
// -----------------------------------------------------------------------------
void SdMorphDlg::SaveSettings() const
{
SvStorageStreamRef xOStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(
RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),
SD_OPTION_STORE ) );
if( xOStm.Is() )
{
SdIOCompat aCompat( *xOStm, STREAM_WRITE, 1 );
*xOStm << (UINT16) aMtfSteps.GetValue()
<< aCbxOrientation.IsChecked()
<< aCbxAttributes.IsChecked();
}
}
<|endoftext|>
|
<commit_before>#include "archive.hh"
#include "binary-cache-store.hh"
#include "compression.hh"
#include "derivations.hh"
#include "fs-accessor.hh"
#include "globals.hh"
#include "nar-info.hh"
#include "sync.hh"
#include "remote-fs-accessor.hh"
#include "nar-info-disk-cache.hh"
#include "nar-accessor.hh"
#include "json.hh"
#include <chrono>
#include <future>
namespace nix {
BinaryCacheStore::BinaryCacheStore(const Params & params)
: Store(params)
{
if (secretKeyFile != "")
secretKey = std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));
StringSink sink;
sink << narVersionMagic1;
narMagic = *sink.s;
}
void BinaryCacheStore::init()
{
std::string cacheInfoFile = "nix-cache-info";
auto cacheInfo = getFile(cacheInfoFile);
if (!cacheInfo) {
upsertFile(cacheInfoFile, "StoreDir: " + storeDir + "\n", "text/x-nix-cache-info");
} else {
for (auto & line : tokenizeString<Strings>(*cacheInfo, "\n")) {
size_t colon = line.find(':');
if (colon == std::string::npos) continue;
auto name = line.substr(0, colon);
auto value = trim(line.substr(colon + 1, std::string::npos));
if (name == "StoreDir") {
if (value != storeDir)
throw Error(format("binary cache '%s' is for Nix stores with prefix '%s', not '%s'")
% getUri() % value % storeDir);
} else if (name == "WantMassQuery") {
wantMassQuery_ = value == "1";
} else if (name == "Priority") {
string2Int(value, priority);
}
}
}
}
void BinaryCacheStore::getFile(const std::string & path,
Callback<std::shared_ptr<std::string>> callback)
{
try {
callback(getFile(path));
} catch (...) { callback.rethrow(); }
}
void BinaryCacheStore::getFile(const std::string & path, Sink & sink)
{
std::promise<std::shared_ptr<std::string>> promise;
getFile(path,
{[&](std::future<std::shared_ptr<std::string>> result) {
try {
promise.set_value(result.get());
} catch (...) {
promise.set_exception(std::current_exception());
}
}});
auto data = promise.get_future().get();
sink((unsigned char *) data->data(), data->size());
}
std::shared_ptr<std::string> BinaryCacheStore::getFile(const std::string & path)
{
StringSink sink;
try {
getFile(path, sink);
} catch (NoSuchBinaryCacheFile &) {
return nullptr;
}
return sink.s;
}
Path BinaryCacheStore::narInfoFileFor(const Path & storePath)
{
assertStorePath(storePath);
return storePathToHash(storePath) + ".narinfo";
}
void BinaryCacheStore::writeNarInfo(ref<NarInfo> narInfo)
{
auto narInfoFile = narInfoFileFor(narInfo->path);
upsertFile(narInfoFile, narInfo->to_string(), "text/x-nix-narinfo");
auto hashPart = storePathToHash(narInfo->path);
{
auto state_(state.lock());
state_->pathInfoCache.upsert(hashPart, std::shared_ptr<NarInfo>(narInfo));
}
if (diskCache)
diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr<NarInfo>(narInfo));
}
void BinaryCacheStore::addToStore(const ValidPathInfo & info, const ref<std::string> & nar,
RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr<FSAccessor> accessor)
{
if (!repair && isValidPath(info.path)) return;
/* Verify that all references are valid. This may do some .narinfo
reads, but typically they'll already be cached. */
for (auto & ref : info.references)
try {
if (ref != info.path)
queryPathInfo(ref);
} catch (InvalidPath &) {
throw Error(format("cannot add '%s' to the binary cache because the reference '%s' is not valid")
% info.path % ref);
}
assert(nar->compare(0, narMagic.size(), narMagic) == 0);
auto narInfo = make_ref<NarInfo>(info);
narInfo->narSize = nar->size();
narInfo->narHash = hashString(htSHA256, *nar);
if (info.narHash && info.narHash != narInfo->narHash)
throw Error(format("refusing to copy corrupted path '%1%' to binary cache") % info.path);
auto accessor_ = std::dynamic_pointer_cast<RemoteFSAccessor>(accessor);
/* Optionally write a JSON file containing a listing of the
contents of the NAR. */
if (writeNARListing) {
std::ostringstream jsonOut;
{
JSONObject jsonRoot(jsonOut);
jsonRoot.attr("version", 1);
auto narAccessor = makeNarAccessor(nar);
if (accessor_)
accessor_->addToCache(info.path, *nar, narAccessor);
{
auto res = jsonRoot.placeholder("root");
listNar(res, narAccessor, "", true);
}
}
upsertFile(storePathToHash(info.path) + ".ls", jsonOut.str(), "application/json");
}
else {
if (accessor_)
accessor_->addToCache(info.path, *nar, makeNarAccessor(nar));
}
/* Compress the NAR. */
narInfo->compression = compression;
auto now1 = std::chrono::steady_clock::now();
auto narCompressed = compress(compression, *nar, parallelCompression);
auto now2 = std::chrono::steady_clock::now();
narInfo->fileHash = hashString(htSHA256, *narCompressed);
narInfo->fileSize = narCompressed->size();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count();
printMsg(lvlTalkative, format("copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache")
% narInfo->path % narInfo->narSize
% ((1.0 - (double) narCompressed->size() / nar->size()) * 100.0)
% duration);
/* Atomically write the NAR file. */
narInfo->url = "nar/" + narInfo->fileHash.to_string(Base32, false) + ".nar"
+ (compression == "xz" ? ".xz" :
compression == "bzip2" ? ".bz2" :
compression == "br" ? ".br" :
"");
if (repair || !fileExists(narInfo->url)) {
stats.narWrite++;
upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar");
} else
stats.narWriteAverted++;
stats.narWriteBytes += nar->size();
stats.narWriteCompressedBytes += narCompressed->size();
stats.narWriteCompressionTimeMs += duration;
/* Atomically write the NAR info file.*/
if (secretKey) narInfo->sign(*secretKey);
writeNarInfo(narInfo);
stats.narInfoWrite++;
}
bool BinaryCacheStore::isValidPathUncached(const Path & storePath)
{
// FIXME: this only checks whether a .narinfo with a matching hash
// part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even
// though they shouldn't. Not easily fixed.
return fileExists(narInfoFileFor(storePath));
}
void BinaryCacheStore::narFromPath(const Path & storePath, Sink & sink)
{
auto info = queryPathInfo(storePath).cast<const NarInfo>();
uint64_t narSize = 0;
LambdaSink wrapperSink([&](const unsigned char * data, size_t len) {
sink(data, len);
narSize += len;
});
auto decompressor = makeDecompressionSink(info->compression, wrapperSink);
try {
getFile(info->url, *decompressor);
} catch (NoSuchBinaryCacheFile & e) {
throw SubstituteGone(e.what());
}
decompressor->flush();
stats.narRead++;
//stats.narReadCompressedBytes += nar->size(); // FIXME
stats.narReadBytes += narSize;
}
void BinaryCacheStore::queryPathInfoUncached(const Path & storePath,
Callback<std::shared_ptr<ValidPathInfo>> callback)
{
auto uri = getUri();
auto act = std::make_shared<Activity>(*logger, lvlTalkative, actQueryPathInfo,
fmt("querying info about '%s' on '%s'", storePath, uri), Logger::Fields{storePath, uri});
PushActivity pact(act->id);
auto narInfoFile = narInfoFileFor(storePath);
getFile(narInfoFile,
{[=](std::future<std::shared_ptr<std::string>> fut) {
try {
auto data = fut.get();
if (!data) return callback(nullptr);
stats.narInfoRead++;
callback((std::shared_ptr<ValidPathInfo>)
std::make_shared<NarInfo>(*this, *data, narInfoFile));
(void) act; // force Activity into this lambda to ensure it stays alive
} catch (...) {
callback.rethrow();
}
}});
}
Path BinaryCacheStore::addToStore(const string & name, const Path & srcPath,
bool recursive, HashType hashAlgo, PathFilter & filter, RepairFlag repair)
{
// FIXME: some cut&paste from LocalStore::addToStore().
/* Read the whole path into memory. This is not a very scalable
method for very large paths, but `copyPath' is mainly used for
small files. */
StringSink sink;
Hash h;
if (recursive) {
dumpPath(srcPath, sink, filter);
h = hashString(hashAlgo, *sink.s);
} else {
auto s = readFile(srcPath);
dumpString(s, sink);
h = hashString(hashAlgo, s);
}
ValidPathInfo info;
info.path = makeFixedOutputPath(recursive, h, name);
addToStore(info, sink.s, repair, CheckSigs, nullptr);
return info.path;
}
Path BinaryCacheStore::addTextToStore(const string & name, const string & s,
const PathSet & references, RepairFlag repair)
{
ValidPathInfo info;
info.path = computeStorePathForText(name, s, references);
info.references = references;
if (repair || !isValidPath(info.path)) {
StringSink sink;
dumpString(s, sink);
addToStore(info, sink.s, repair, CheckSigs, nullptr);
}
return info.path;
}
ref<FSAccessor> BinaryCacheStore::getFSAccessor()
{
return make_ref<RemoteFSAccessor>(ref<Store>(shared_from_this()), localNarCache);
}
void BinaryCacheStore::addSignatures(const Path & storePath, const StringSet & sigs)
{
/* Note: this is inherently racy since there is no locking on
binary caches. In particular, with S3 this unreliable, even
when addSignatures() is called sequentially on a path, because
S3 might return an outdated cached version. */
auto narInfo = make_ref<NarInfo>((NarInfo &) *queryPathInfo(storePath));
narInfo->sigs.insert(sigs.begin(), sigs.end());
auto narInfoFile = narInfoFileFor(narInfo->path);
writeNarInfo(narInfo);
}
std::shared_ptr<std::string> BinaryCacheStore::getBuildLog(const Path & path)
{
Path drvPath;
if (isDerivation(path))
drvPath = path;
else {
try {
auto info = queryPathInfo(path);
// FIXME: add a "Log" field to .narinfo
if (info->deriver == "") return nullptr;
drvPath = info->deriver;
} catch (InvalidPath &) {
return nullptr;
}
}
auto logPath = "log/" + baseNameOf(drvPath);
debug("fetching build log from binary cache '%s/%s'", getUri(), logPath);
return getFile(logPath);
}
}
<commit_msg>Fix another 'coroutine has finished' during decompression<commit_after>#include "archive.hh"
#include "binary-cache-store.hh"
#include "compression.hh"
#include "derivations.hh"
#include "fs-accessor.hh"
#include "globals.hh"
#include "nar-info.hh"
#include "sync.hh"
#include "remote-fs-accessor.hh"
#include "nar-info-disk-cache.hh"
#include "nar-accessor.hh"
#include "json.hh"
#include <chrono>
#include <future>
namespace nix {
BinaryCacheStore::BinaryCacheStore(const Params & params)
: Store(params)
{
if (secretKeyFile != "")
secretKey = std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));
StringSink sink;
sink << narVersionMagic1;
narMagic = *sink.s;
}
void BinaryCacheStore::init()
{
std::string cacheInfoFile = "nix-cache-info";
auto cacheInfo = getFile(cacheInfoFile);
if (!cacheInfo) {
upsertFile(cacheInfoFile, "StoreDir: " + storeDir + "\n", "text/x-nix-cache-info");
} else {
for (auto & line : tokenizeString<Strings>(*cacheInfo, "\n")) {
size_t colon = line.find(':');
if (colon == std::string::npos) continue;
auto name = line.substr(0, colon);
auto value = trim(line.substr(colon + 1, std::string::npos));
if (name == "StoreDir") {
if (value != storeDir)
throw Error(format("binary cache '%s' is for Nix stores with prefix '%s', not '%s'")
% getUri() % value % storeDir);
} else if (name == "WantMassQuery") {
wantMassQuery_ = value == "1";
} else if (name == "Priority") {
string2Int(value, priority);
}
}
}
}
void BinaryCacheStore::getFile(const std::string & path,
Callback<std::shared_ptr<std::string>> callback)
{
try {
callback(getFile(path));
} catch (...) { callback.rethrow(); }
}
void BinaryCacheStore::getFile(const std::string & path, Sink & sink)
{
std::promise<std::shared_ptr<std::string>> promise;
getFile(path,
{[&](std::future<std::shared_ptr<std::string>> result) {
try {
promise.set_value(result.get());
} catch (...) {
promise.set_exception(std::current_exception());
}
}});
auto data = promise.get_future().get();
sink((unsigned char *) data->data(), data->size());
}
std::shared_ptr<std::string> BinaryCacheStore::getFile(const std::string & path)
{
StringSink sink;
try {
getFile(path, sink);
} catch (NoSuchBinaryCacheFile &) {
return nullptr;
}
return sink.s;
}
Path BinaryCacheStore::narInfoFileFor(const Path & storePath)
{
assertStorePath(storePath);
return storePathToHash(storePath) + ".narinfo";
}
void BinaryCacheStore::writeNarInfo(ref<NarInfo> narInfo)
{
auto narInfoFile = narInfoFileFor(narInfo->path);
upsertFile(narInfoFile, narInfo->to_string(), "text/x-nix-narinfo");
auto hashPart = storePathToHash(narInfo->path);
{
auto state_(state.lock());
state_->pathInfoCache.upsert(hashPart, std::shared_ptr<NarInfo>(narInfo));
}
if (diskCache)
diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr<NarInfo>(narInfo));
}
void BinaryCacheStore::addToStore(const ValidPathInfo & info, const ref<std::string> & nar,
RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr<FSAccessor> accessor)
{
if (!repair && isValidPath(info.path)) return;
/* Verify that all references are valid. This may do some .narinfo
reads, but typically they'll already be cached. */
for (auto & ref : info.references)
try {
if (ref != info.path)
queryPathInfo(ref);
} catch (InvalidPath &) {
throw Error(format("cannot add '%s' to the binary cache because the reference '%s' is not valid")
% info.path % ref);
}
assert(nar->compare(0, narMagic.size(), narMagic) == 0);
auto narInfo = make_ref<NarInfo>(info);
narInfo->narSize = nar->size();
narInfo->narHash = hashString(htSHA256, *nar);
if (info.narHash && info.narHash != narInfo->narHash)
throw Error(format("refusing to copy corrupted path '%1%' to binary cache") % info.path);
auto accessor_ = std::dynamic_pointer_cast<RemoteFSAccessor>(accessor);
/* Optionally write a JSON file containing a listing of the
contents of the NAR. */
if (writeNARListing) {
std::ostringstream jsonOut;
{
JSONObject jsonRoot(jsonOut);
jsonRoot.attr("version", 1);
auto narAccessor = makeNarAccessor(nar);
if (accessor_)
accessor_->addToCache(info.path, *nar, narAccessor);
{
auto res = jsonRoot.placeholder("root");
listNar(res, narAccessor, "", true);
}
}
upsertFile(storePathToHash(info.path) + ".ls", jsonOut.str(), "application/json");
}
else {
if (accessor_)
accessor_->addToCache(info.path, *nar, makeNarAccessor(nar));
}
/* Compress the NAR. */
narInfo->compression = compression;
auto now1 = std::chrono::steady_clock::now();
auto narCompressed = compress(compression, *nar, parallelCompression);
auto now2 = std::chrono::steady_clock::now();
narInfo->fileHash = hashString(htSHA256, *narCompressed);
narInfo->fileSize = narCompressed->size();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count();
printMsg(lvlTalkative, format("copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache")
% narInfo->path % narInfo->narSize
% ((1.0 - (double) narCompressed->size() / nar->size()) * 100.0)
% duration);
/* Atomically write the NAR file. */
narInfo->url = "nar/" + narInfo->fileHash.to_string(Base32, false) + ".nar"
+ (compression == "xz" ? ".xz" :
compression == "bzip2" ? ".bz2" :
compression == "br" ? ".br" :
"");
if (repair || !fileExists(narInfo->url)) {
stats.narWrite++;
upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar");
} else
stats.narWriteAverted++;
stats.narWriteBytes += nar->size();
stats.narWriteCompressedBytes += narCompressed->size();
stats.narWriteCompressionTimeMs += duration;
/* Atomically write the NAR info file.*/
if (secretKey) narInfo->sign(*secretKey);
writeNarInfo(narInfo);
stats.narInfoWrite++;
}
bool BinaryCacheStore::isValidPathUncached(const Path & storePath)
{
// FIXME: this only checks whether a .narinfo with a matching hash
// part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even
// though they shouldn't. Not easily fixed.
return fileExists(narInfoFileFor(storePath));
}
void BinaryCacheStore::narFromPath(const Path & storePath, Sink & sink)
{
auto info = queryPathInfo(storePath).cast<const NarInfo>();
uint64_t narSize = 0;
LambdaSink wrapperSink([&](const unsigned char * data, size_t len) {
sink(data, len);
narSize += len;
});
auto decompressor = makeDecompressionSink(info->compression, wrapperSink);
try {
getFile(info->url, *decompressor);
} catch (NoSuchBinaryCacheFile & e) {
throw SubstituteGone(e.what());
}
decompressor->finish();
stats.narRead++;
//stats.narReadCompressedBytes += nar->size(); // FIXME
stats.narReadBytes += narSize;
}
void BinaryCacheStore::queryPathInfoUncached(const Path & storePath,
Callback<std::shared_ptr<ValidPathInfo>> callback)
{
auto uri = getUri();
auto act = std::make_shared<Activity>(*logger, lvlTalkative, actQueryPathInfo,
fmt("querying info about '%s' on '%s'", storePath, uri), Logger::Fields{storePath, uri});
PushActivity pact(act->id);
auto narInfoFile = narInfoFileFor(storePath);
getFile(narInfoFile,
{[=](std::future<std::shared_ptr<std::string>> fut) {
try {
auto data = fut.get();
if (!data) return callback(nullptr);
stats.narInfoRead++;
callback((std::shared_ptr<ValidPathInfo>)
std::make_shared<NarInfo>(*this, *data, narInfoFile));
(void) act; // force Activity into this lambda to ensure it stays alive
} catch (...) {
callback.rethrow();
}
}});
}
Path BinaryCacheStore::addToStore(const string & name, const Path & srcPath,
bool recursive, HashType hashAlgo, PathFilter & filter, RepairFlag repair)
{
// FIXME: some cut&paste from LocalStore::addToStore().
/* Read the whole path into memory. This is not a very scalable
method for very large paths, but `copyPath' is mainly used for
small files. */
StringSink sink;
Hash h;
if (recursive) {
dumpPath(srcPath, sink, filter);
h = hashString(hashAlgo, *sink.s);
} else {
auto s = readFile(srcPath);
dumpString(s, sink);
h = hashString(hashAlgo, s);
}
ValidPathInfo info;
info.path = makeFixedOutputPath(recursive, h, name);
addToStore(info, sink.s, repair, CheckSigs, nullptr);
return info.path;
}
Path BinaryCacheStore::addTextToStore(const string & name, const string & s,
const PathSet & references, RepairFlag repair)
{
ValidPathInfo info;
info.path = computeStorePathForText(name, s, references);
info.references = references;
if (repair || !isValidPath(info.path)) {
StringSink sink;
dumpString(s, sink);
addToStore(info, sink.s, repair, CheckSigs, nullptr);
}
return info.path;
}
ref<FSAccessor> BinaryCacheStore::getFSAccessor()
{
return make_ref<RemoteFSAccessor>(ref<Store>(shared_from_this()), localNarCache);
}
void BinaryCacheStore::addSignatures(const Path & storePath, const StringSet & sigs)
{
/* Note: this is inherently racy since there is no locking on
binary caches. In particular, with S3 this unreliable, even
when addSignatures() is called sequentially on a path, because
S3 might return an outdated cached version. */
auto narInfo = make_ref<NarInfo>((NarInfo &) *queryPathInfo(storePath));
narInfo->sigs.insert(sigs.begin(), sigs.end());
auto narInfoFile = narInfoFileFor(narInfo->path);
writeNarInfo(narInfo);
}
std::shared_ptr<std::string> BinaryCacheStore::getBuildLog(const Path & path)
{
Path drvPath;
if (isDerivation(path))
drvPath = path;
else {
try {
auto info = queryPathInfo(path);
// FIXME: add a "Log" field to .narinfo
if (info->deriver == "") return nullptr;
drvPath = info->deriver;
} catch (InvalidPath &) {
return nullptr;
}
}
auto logPath = "log/" + baseNameOf(drvPath);
debug("fetching build log from binary cache '%s/%s'", getUri(), logPath);
return getFile(logPath);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: unmovss.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ka $ $Date: 2001-10-22 13:36:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "unmovss.hxx"
#include "docshell.hxx"
#include "drawdoc.hxx"
#include "stlsheet.hxx"
TYPEINIT1(SdMoveStyleSheetsUndoAction, SdUndoAction);
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
SdMoveStyleSheetsUndoAction::SdMoveStyleSheetsUndoAction(
SdDrawDocument* pTheDoc,
List* pTheStyles,
BOOL bInserted):
SdUndoAction(pTheDoc)
{
DBG_ASSERT(pTheStyles, "keine Liste gesetzt!");
pStyles = pTheStyles;
bMySheets = !bInserted;
pListOfChildLists = new List;
// Liste mit den Listen der StyleSheet-Kinder erstellen
for (SdStyleSheet* pSheet = (SdStyleSheet*)pStyles->First();
pSheet;
pSheet = (SdStyleSheet*)pStyles->Next())
{
List* pChildList = pSheet->CreateChildList();
pListOfChildLists->Insert(pChildList, LIST_APPEND);
}
}
/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/
void SdMoveStyleSheetsUndoAction::Undo()
{
SfxStyleSheetBasePool* pPool = pDoc->GetStyleSheetPool();
SdStyleSheet* pSheet = NULL;
/********************************************************************
|* die StyleSheets sollen wieder in den Pool eingefuegt werden
\*******************************************************************/
if (bMySheets)
{
/****************************************************************
|* erst alle StyleSheets wieder in den Pool einfuegen
\***************************************************************/
for (pSheet = (SdStyleSheet*)pStyles->First();
pSheet;
pSheet = (SdStyleSheet*)pStyles->Next())
{
pPool->Insert(pSheet);
}
/****************************************************************
|* jetzt die ehemaligen Kinder wieder zu Kindern machen
\***************************************************************/
List* pChildList = (List*)pListOfChildLists->First();
for (pSheet = (SdStyleSheet*)pStyles->First();
pSheet;
pSheet = (SdStyleSheet*)pStyles->Next())
{
String aParent(pSheet->GetName());
for (SfxStyleSheet* pChild = (SfxStyleSheet*)pChildList->First();
pChild;
pChild = (SfxStyleSheet*)pChildList->Next())
{
pChild->SetParent(aParent);
}
pChildList = (List*)pListOfChildLists->Next();
}
}
/********************************************************************
|* die StyleSheets sollen wieder aus dem, Pool entfernt werden
\*******************************************************************/
else
{
for (pSheet = (SdStyleSheet*)pStyles->First();
pSheet;
pSheet = (SdStyleSheet*)pStyles->Next())
{
pPool->Remove(pSheet);
}
}
bMySheets = !bMySheets;
}
/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/
void SdMoveStyleSheetsUndoAction::Redo()
{
Undo();
}
/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/
void SdMoveStyleSheetsUndoAction::Repeat()
{
DBG_ASSERT(FALSE, "SdMoveStyleSheetsUndoAction::Repeat: nicht implementiert");
}
/*************************************************************************
|*
|* Destruktor, Liste loeschen; ggfs. die enthaltenen StyleSheets loeschen
|*
\************************************************************************/
SdMoveStyleSheetsUndoAction::~SdMoveStyleSheetsUndoAction()
{
if (bMySheets)
{
// die Liste rueckwaerts aufdroeseln; wenn Gliederungsvorlagen ent-
// halten sind gewaehrleistet dies den geringsten Broadcasting-Aufwand
SfxStyleSheet* pSheet = (SfxStyleSheet*)pStyles->Last();
while (pSheet)
{
delete pSheet;
pSheet = (SfxStyleSheet*)pStyles->Prev();
}
}
delete pStyles;
for (List* pChildList = (List*)pListOfChildLists->First();
pChildList;
pChildList = (List*)pListOfChildLists->Next())
{
delete pChildList;
}
delete pListOfChildLists;
}
/*************************************************************************
|*
|* Kommentar liefern
|*
\************************************************************************/
String SdMoveStyleSheetsUndoAction::GetComment() const
{
return String();
}
<commit_msg>INTEGRATION: CWS impress1 (1.2.238); FILE MERGED 2003/09/17 09:06:20 af 1.2.238.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
*
* $RCSfile: unmovss.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-01-20 11:25:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "unmovss.hxx"
#include "DrawDocShell.hxx"
#include "drawdoc.hxx"
#include "stlsheet.hxx"
TYPEINIT1(SdMoveStyleSheetsUndoAction, SdUndoAction);
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
SdMoveStyleSheetsUndoAction::SdMoveStyleSheetsUndoAction(
SdDrawDocument* pTheDoc,
List* pTheStyles,
BOOL bInserted):
SdUndoAction(pTheDoc)
{
DBG_ASSERT(pTheStyles, "keine Liste gesetzt!");
pStyles = pTheStyles;
bMySheets = !bInserted;
pListOfChildLists = new List;
// Liste mit den Listen der StyleSheet-Kinder erstellen
for (SdStyleSheet* pSheet = (SdStyleSheet*)pStyles->First();
pSheet;
pSheet = (SdStyleSheet*)pStyles->Next())
{
List* pChildList = pSheet->CreateChildList();
pListOfChildLists->Insert(pChildList, LIST_APPEND);
}
}
/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/
void SdMoveStyleSheetsUndoAction::Undo()
{
SfxStyleSheetBasePool* pPool = pDoc->GetStyleSheetPool();
SdStyleSheet* pSheet = NULL;
/********************************************************************
|* die StyleSheets sollen wieder in den Pool eingefuegt werden
\*******************************************************************/
if (bMySheets)
{
/****************************************************************
|* erst alle StyleSheets wieder in den Pool einfuegen
\***************************************************************/
for (pSheet = (SdStyleSheet*)pStyles->First();
pSheet;
pSheet = (SdStyleSheet*)pStyles->Next())
{
pPool->Insert(pSheet);
}
/****************************************************************
|* jetzt die ehemaligen Kinder wieder zu Kindern machen
\***************************************************************/
List* pChildList = (List*)pListOfChildLists->First();
for (pSheet = (SdStyleSheet*)pStyles->First();
pSheet;
pSheet = (SdStyleSheet*)pStyles->Next())
{
String aParent(pSheet->GetName());
for (SfxStyleSheet* pChild = (SfxStyleSheet*)pChildList->First();
pChild;
pChild = (SfxStyleSheet*)pChildList->Next())
{
pChild->SetParent(aParent);
}
pChildList = (List*)pListOfChildLists->Next();
}
}
/********************************************************************
|* die StyleSheets sollen wieder aus dem, Pool entfernt werden
\*******************************************************************/
else
{
for (pSheet = (SdStyleSheet*)pStyles->First();
pSheet;
pSheet = (SdStyleSheet*)pStyles->Next())
{
pPool->Remove(pSheet);
}
}
bMySheets = !bMySheets;
}
/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/
void SdMoveStyleSheetsUndoAction::Redo()
{
Undo();
}
/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/
void SdMoveStyleSheetsUndoAction::Repeat()
{
DBG_ASSERT(FALSE, "SdMoveStyleSheetsUndoAction::Repeat: nicht implementiert");
}
/*************************************************************************
|*
|* Destruktor, Liste loeschen; ggfs. die enthaltenen StyleSheets loeschen
|*
\************************************************************************/
SdMoveStyleSheetsUndoAction::~SdMoveStyleSheetsUndoAction()
{
if (bMySheets)
{
// die Liste rueckwaerts aufdroeseln; wenn Gliederungsvorlagen ent-
// halten sind gewaehrleistet dies den geringsten Broadcasting-Aufwand
SfxStyleSheet* pSheet = (SfxStyleSheet*)pStyles->Last();
while (pSheet)
{
delete pSheet;
pSheet = (SfxStyleSheet*)pStyles->Prev();
}
}
delete pStyles;
for (List* pChildList = (List*)pListOfChildLists->First();
pChildList;
pChildList = (List*)pListOfChildLists->Next())
{
delete pChildList;
}
delete pListOfChildLists;
}
/*************************************************************************
|*
|* Kommentar liefern
|*
\************************************************************************/
String SdMoveStyleSheetsUndoAction::GetComment() const
{
return String();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: unmodpg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ka $ $Date: 2001-10-22 13:36:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVDLAYER
#include <svx/svdlayer.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#pragma hdrstop
#include "strings.hrc"
#include "glob.hrc" // STR_BCKGRND, STR_BCKGRNDOBJ
#include "app.hrc" // SID_SWITCHPAGE
#include "unmodpg.hxx"
#include "sdpage.hxx"
#include "sdresid.hxx"
#include "drawdoc.hxx"
TYPEINIT1(ModifyPageUndoAction, SdUndoAction);
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
ModifyPageUndoAction::ModifyPageUndoAction(
SfxUndoManager* pTheManager, // #67720#
SdDrawDocument* pTheDoc,
SdPage* pThePage,
String aTheNewName,
AutoLayout eTheNewAutoLayout,
BOOL bTheNewBckgrndVisible,
BOOL bTheNewBckgrndObjsVisible)
: SdUndoAction(pTheDoc),
mpManager(pTheManager)
{
DBG_ASSERT(pThePage, "Undo ohne Seite ???");
pPage = pThePage;
aNewName = aTheNewName;
eNewAutoLayout = eTheNewAutoLayout;
bNewBckgrndVisible = bTheNewBckgrndVisible;
bNewBckgrndObjsVisible = bTheNewBckgrndObjsVisible;
eOldAutoLayout = pPage->GetAutoLayout();
if (!pPage->IsMasterPage())
{
aOldName = pPage->GetName();
SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();
BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
USHORT nPos = 0;
SetOfByte aVisibleLayers = pPage->GetMasterPageVisibleLayers(nPos);
bOldBckgrndVisible = aVisibleLayers.IsSet(aBckgrnd);
bOldBckgrndObjsVisible = aVisibleLayers.IsSet(aBckgrndObj);
}
aComment = String(SdResId(STR_UNDO_MODIFY_PAGE));
}
/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/
void ModifyPageUndoAction::Undo()
{
pPage->SetAutoLayout(eOldAutoLayout, TRUE);
if (!pPage->IsMasterPage())
{
if (pPage->GetName() != aOldName)
{
pPage->SetName(aOldName);
if (pPage->GetPageKind() == PK_STANDARD)
{
SdPage* pNotesPage = (SdPage*)pDoc->GetPage(pPage->GetPageNum() + 1);
pNotesPage->SetName(aOldName);
}
}
SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();
BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
USHORT nPos = 0;
SetOfByte aVisibleLayers;
aVisibleLayers.Set(aBckgrnd, bOldBckgrndVisible);
aVisibleLayers.Set(aBckgrndObj, bOldBckgrndObjsVisible);
nPos = 0;
pPage->SetMasterPageVisibleLayers(aVisibleLayers, nPos);
}
// Redisplay
SfxViewFrame::Current()->GetDispatcher()->Execute(
SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );
// #67720# clear undo manager
if(mpManager)
{
// BEWARE: Do this as LAST action here since this will delete
// all actions which are added, inclusive to this one (!)
mpManager->Clear();
}
}
/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/
void ModifyPageUndoAction::Redo()
{
pPage->SetAutoLayout(eNewAutoLayout, TRUE);
if (!pPage->IsMasterPage())
{
if (pPage->GetName() != aNewName)
{
pPage->SetName(aNewName);
if (pPage->GetPageKind() == PK_STANDARD)
{
SdPage* pNotesPage = (SdPage*)pDoc->GetPage(pPage->GetPageNum() + 1);
pNotesPage->SetName(aNewName);
}
}
SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();
BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
USHORT nPos = 0;
SetOfByte aVisibleLayers;
aVisibleLayers.Set(aBckgrnd, bNewBckgrndVisible);
aVisibleLayers.Set(aBckgrndObj, bNewBckgrndObjsVisible);
nPos = 0;
pPage->SetMasterPageVisibleLayers(aVisibleLayers, nPos);
}
// Redisplay
SfxViewFrame::Current()->GetDispatcher()->Execute(
SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );
// #67720# clear undo manager
if(mpManager)
{
// BEWARE: Do this as LAST action here since this will delete
// all actions which are added, inclusive to this one (!)
mpManager->Clear();
}
}
/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/
void ModifyPageUndoAction::Repeat()
{
DBG_ASSERT(FALSE, "ModifyPageUndoAction::Repeat: nicht implementiert");
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
ModifyPageUndoAction::~ModifyPageUndoAction()
{
}
/*************************************************************************
|*
|* Kommentar liefern
|*
\************************************************************************/
String ModifyPageUndoAction::GetComment() const
{
return aComment;
}
<commit_msg>#94637# invalidate Selection, there could be objects deleted in tis UNDO which are no longer allowed to be selected then.<commit_after>/*************************************************************************
*
* $RCSfile: unmodpg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: aw $ $Date: 2001-11-13 18:11:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVDLAYER
#include <svx/svdlayer.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#pragma hdrstop
#include "strings.hrc"
#include "glob.hrc" // STR_BCKGRND, STR_BCKGRNDOBJ
#include "app.hrc" // SID_SWITCHPAGE
#include "unmodpg.hxx"
#include "sdpage.hxx"
#include "sdresid.hxx"
#include "drawdoc.hxx"
TYPEINIT1(ModifyPageUndoAction, SdUndoAction);
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
ModifyPageUndoAction::ModifyPageUndoAction(
SfxUndoManager* pTheManager, // #67720#
SdDrawDocument* pTheDoc,
SdPage* pThePage,
String aTheNewName,
AutoLayout eTheNewAutoLayout,
BOOL bTheNewBckgrndVisible,
BOOL bTheNewBckgrndObjsVisible)
: SdUndoAction(pTheDoc),
mpManager(pTheManager)
{
DBG_ASSERT(pThePage, "Undo ohne Seite ???");
pPage = pThePage;
aNewName = aTheNewName;
eNewAutoLayout = eTheNewAutoLayout;
bNewBckgrndVisible = bTheNewBckgrndVisible;
bNewBckgrndObjsVisible = bTheNewBckgrndObjsVisible;
eOldAutoLayout = pPage->GetAutoLayout();
if (!pPage->IsMasterPage())
{
aOldName = pPage->GetName();
SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();
BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
USHORT nPos = 0;
SetOfByte aVisibleLayers = pPage->GetMasterPageVisibleLayers(nPos);
bOldBckgrndVisible = aVisibleLayers.IsSet(aBckgrnd);
bOldBckgrndObjsVisible = aVisibleLayers.IsSet(aBckgrndObj);
}
aComment = String(SdResId(STR_UNDO_MODIFY_PAGE));
}
/*************************************************************************
|*
|* Undo()
|*
\************************************************************************/
#ifndef _SVDVITER_HXX
#include <svx/svdviter.hxx>
#endif
#ifndef _SVDVIEW_HXX
#include <svx/svdview.hxx>
#endif
void ModifyPageUndoAction::Undo()
{
// #94637# invalidate Selection, there could be objects deleted in tis UNDO
// which are no longer allowed to be selected then.
SdrViewIter aIter(pPage);
SdrView* pView = aIter.FirstView();
while(pView)
{
if(pView->HasMarked())
pView->UnmarkAll();
pView = aIter.NextView();
}
pPage->SetAutoLayout(eOldAutoLayout, TRUE);
if (!pPage->IsMasterPage())
{
if (pPage->GetName() != aOldName)
{
pPage->SetName(aOldName);
if (pPage->GetPageKind() == PK_STANDARD)
{
SdPage* pNotesPage = (SdPage*)pDoc->GetPage(pPage->GetPageNum() + 1);
pNotesPage->SetName(aOldName);
}
}
SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();
BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
USHORT nPos = 0;
SetOfByte aVisibleLayers;
aVisibleLayers.Set(aBckgrnd, bOldBckgrndVisible);
aVisibleLayers.Set(aBckgrndObj, bOldBckgrndObjsVisible);
nPos = 0;
pPage->SetMasterPageVisibleLayers(aVisibleLayers, nPos);
}
// Redisplay
SfxViewFrame::Current()->GetDispatcher()->Execute(
SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );
// #67720# clear undo manager
if(mpManager)
{
// BEWARE: Do this as LAST action here since this will delete
// all actions which are added, inclusive to this one (!)
mpManager->Clear();
}
}
/*************************************************************************
|*
|* Redo()
|*
\************************************************************************/
void ModifyPageUndoAction::Redo()
{
// #94637# invalidate Selection, there could be objects deleted in tis UNDO
// which are no longer allowed to be selected then.
SdrViewIter aIter(pPage);
SdrView* pView = aIter.FirstView();
while(pView)
{
if(pView->HasMarked())
pView->UnmarkAll();
pView = aIter.NextView();
}
pPage->SetAutoLayout(eNewAutoLayout, TRUE);
if (!pPage->IsMasterPage())
{
if (pPage->GetName() != aNewName)
{
pPage->SetName(aNewName);
if (pPage->GetPageKind() == PK_STANDARD)
{
SdPage* pNotesPage = (SdPage*)pDoc->GetPage(pPage->GetPageNum() + 1);
pNotesPage->SetName(aNewName);
}
}
SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();
BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);
BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);
USHORT nPos = 0;
SetOfByte aVisibleLayers;
aVisibleLayers.Set(aBckgrnd, bNewBckgrndVisible);
aVisibleLayers.Set(aBckgrndObj, bNewBckgrndObjsVisible);
nPos = 0;
pPage->SetMasterPageVisibleLayers(aVisibleLayers, nPos);
}
// Redisplay
SfxViewFrame::Current()->GetDispatcher()->Execute(
SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );
// #67720# clear undo manager
if(mpManager)
{
// BEWARE: Do this as LAST action here since this will delete
// all actions which are added, inclusive to this one (!)
mpManager->Clear();
}
}
/*************************************************************************
|*
|* Repeat()
|*
\************************************************************************/
void ModifyPageUndoAction::Repeat()
{
DBG_ASSERT(FALSE, "ModifyPageUndoAction::Repeat: nicht implementiert");
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
ModifyPageUndoAction::~ModifyPageUndoAction()
{
}
/*************************************************************************
|*
|* Kommentar liefern
|*
\************************************************************************/
String ModifyPageUndoAction::GetComment() const
{
return aComment;
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "PositionTracker.h"
/* implementation system headers */
#include <iostream>
#include <string>
/* implementation common headers */
#include "MathUtils.h"
/* private */
/* protected */
/* public: */
PositionTracker::PositionTracker()
{
return;
}
PositionTracker::PositionTracker(const PositionTracker& tracker)
: _trackedItem(tracker._trackedItem),
_waypointDistance(tracker._waypointDistance)
{
return;
}
PositionTracker::~PositionTracker()
{
// clear out all the tracked items vectors
for (std::map<std::string, TrackedItemVector>::iterator jano = _trackedItem.begin(); jano != _trackedItem.end(); jano++) {
TrackedItemVector& trackSet = (*jano).second;
for (unsigned int i = 0; i != trackSet.size(); i++) {
/* sanity clear */
trackSet[i]->id = UNSET_ID;
trackSet[i]->intID = 0;
trackSet[i]->strID = std::string("");
trackSet[i]->lastUpdate = TimeKeeper::getNullTime();
trackSet[i]->position[0] = trackSet[i]->position[1] = trackSet[i]->position[2] = 0.0;
trackSet[i]->forgotten = true;
delete trackSet[i];
}
}
_trackedItem.clear();
// clear out any waypoints
_waypointDistance.clear();
return;
}
/* Linear O(n) time to track a new item since the entire vector is
* searched. if the item is not found, an item is created and added.
*/
unsigned short PositionTracker::track(const std::string id, std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
for (unsigned int i = 0; i != trackSet.size(); i++) {
switch (trackSet[i]->id) {
case STR_ID:
if (id == trackSet[i]->strID) {
return i;
}
break;
case INT_ID:
case UNSET_ID:
break;
default:
std::cerr << "Unknown tracker ID type (id == " << trackSet[i]->id << ")" << std::endl;
break;
}
}
// the item was not found, so create it
item_t *newTracking = new item_t;
newTracking->id = STR_ID;
newTracking->intID = 0;
newTracking->strID = id;
newTracking->lastUpdate = TimeKeeper::getNullTime();
newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0;
newTracking->forgotten = false;
// and add it
trackSet.push_back(newTracking);
// nothing is deleted so should be last index
return trackSet.size() - 1;
}
/* alternative track() passing our own id */
unsigned short PositionTracker::track(long int id, std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
for (unsigned int i = 0; i != trackSet.size(); i++) {
switch (trackSet[i]->id) {
case INT_ID:
if (id == trackSet[i]->intID) {
return i;
}
break;
case STR_ID:
case UNSET_ID:
break;
default:
std::cerr << "Unknown tracker ID type (id == " << trackSet[i]->id << ")" << std::endl;
break;
}
}
// the item was not found, so create it
item_t *newTracking = new item_t;
newTracking->id = INT_ID;
newTracking->intID = id;
newTracking->strID = std::string("");
newTracking->lastUpdate = TimeKeeper::getNullTime();
newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0;
newTracking->forgotten = false;
// and add it
trackSet.push_back(newTracking);
// nothing is deleted so should be last index
return trackSet.size() - 1;
}
bool PositionTracker::update(unsigned short int token, const std::string id, const double position[3], std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
if ((token >= trackSet.size()) ||
(trackSet[token]->id != STR_ID) ||
(trackSet[token]->strID != id) ||
(trackSet[token]->forgotten)) {
return false;
}
trackSet[token]->position[0] = position[0];
trackSet[token]->position[1] = position[1];
trackSet[token]->position[2] = position[2];
trackSet[token]->lastUpdate = TimeKeeper::getCurrent();
return true;
}
bool PositionTracker::update(unsigned short int token, const std::string id, const float position[3], std::string group)
{
double pos[3];
pos[0] = (double)position[0];
pos[1] = (double)position[1];
pos[2] = (double)position[2];
return update(token, id, pos, group);
}
bool PositionTracker::update(unsigned short int token, long int id, const double position[3], std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
if ((token >= trackSet.size()) ||
(trackSet[token]->id != INT_ID) ||
(trackSet[token]->intID != id) ||
(trackSet[token]->forgotten)) {
return false;
}
trackSet[token]->position[0] = position[0];
trackSet[token]->position[1] = position[1];
trackSet[token]->position[2] = position[2];
trackSet[token]->lastUpdate = TimeKeeper::getCurrent();
return true;
}
bool PositionTracker::update(unsigned short int token, long int id, const float position[3], std::string group)
{
double pos[3];
pos[0] = (double)position[0];
pos[1] = (double)position[1];
pos[2] = (double)position[2];
return update(token, id, pos, group);
}
bool PositionTracker::addWaypoint(const double from[3], const double to[3], double distance)
{
unsigned short int fromToken, toToken;
bool updated;
bool foundPoint;
TrackedItemVector& waypointSet = _trackedItem[std::string("__waypoint__")];
// see if the first point already exists
foundPoint = false;
for (unsigned int i = 0; i != waypointSet.size(); i++) {
if ((waypointSet[i]->position[0] = from[0]) &&
(waypointSet[i]->position[1] = from[1]) &&
(waypointSet[i]->position[2] = from[2])) {
foundPoint = true;
fromToken = waypointSet[i]->intID;
}
}
if (!foundPoint) {
// add the first point
unsigned short int nextID = waypointSet.size();
fromToken = track((long int)nextID, std::string("__waypoint__"));
updated = update(fromToken, nextID, from, std::string("__waypoint__"));
if (!updated) {
std::cerr << "Unable to add waypoint?!" << std::endl;
return false;
}
}
// see if the second point already exists
foundPoint = false;
for (unsigned int i = 0; i != waypointSet.size(); i++) {
if ((waypointSet[i]->position[0] = to[0]) &&
(waypointSet[i]->position[1] = to[1]) &&
(waypointSet[i]->position[2] = to[2])) {
foundPoint = true;
toToken = waypointSet[i]->intID;
}
}
if (!foundPoint) {
// add the second point
unsigned short int nextID = waypointSet.size();
toToken = track((long int)nextID, std::string("__waypoint__"));
updated = update(toToken, nextID, to, std::string("__waypoint__"));
if (!updated) {
std::cerr << "Unable to add waypoint?!" << std::endl;
return false;
}
}
// compute and use real distance if distance passed was negative
if (distance < 0.0) {
distance = distanceBetween(fromToken, toToken, std::string("__waypoint__"), std::string("__waypoint__"));
}
std::pair<unsigned short int, unsigned short int> waypoint = std::make_pair(fromToken, toToken);
// see if the waypoint pair have already been added
/*
std::map<std::pair<unsigned short int, unsigned short int>, double>::iterator jano = _waypointDistance.find(waypoint);
if (jano != _waypointDistance.end()) {
// waypoint already added, but set distance anyways (might be an update)
(*jano).second = distance;
}
*/
_waypointDistance[waypoint] = distance;
return true;
}
bool PositionTracker::addWaypoint(const float from[3], const float to[3], double distance)
{
double fromPos[3], toPos[3];
fromPos[0] = from[0];
fromPos[1] = from[1];
fromPos[2] = from[2];
toPos[0] = to[0];
toPos[1] = to[1];
toPos[2] = to[2];
return addWaypoint(fromPos, toPos, distance);
}
bool PositionTracker::forget(unsigned short int token, const std::string id, std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
if ((token >= trackSet.size()) ||
(trackSet[token]->id != STR_ID) ||
(trackSet[token]->strID != id) ||
(trackSet[token]->forgotten)) {
return false;
}
trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0;
trackSet[token]->forgotten = true;
return true;
}
bool PositionTracker::forget(unsigned short int token, long int id, std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
if ((token >= trackSet.size()) ||
(trackSet[token]->id != INT_ID) ||
(trackSet[token]->intID != id) ||
(trackSet[token]->forgotten)) {
return false;
}
trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0;
trackSet[token]->forgotten = true;
return true;
}
double PositionTracker::distanceBetween(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const
{
// this indirection nastiness is needed to maintain constness
std::map <std::string, TrackedItemVector>::const_iterator fromIterator = _trackedItem.find(fromGroup);
std::map <std::string, TrackedItemVector>::const_iterator toIterator = _trackedItem.find(toGroup);
const TrackedItemVector& fromSet = (*fromIterator).second;
const TrackedItemVector& toSet = (*toIterator).second;
if ((fromToken > fromSet.size()) ||
(toToken > toSet.size()) ||
(fromToken == toToken)) {
return 0.0;
}
// basic Cartesian 3-space formula for distance between two points
double distanceSquared = (((fromSet[fromToken]->position[0] - toSet[toToken]->position[0]) *
(fromSet[fromToken]->position[0] - toSet[toToken]->position[0])) +
((fromSet[fromToken]->position[1] - toSet[toToken]->position[1]) *
(fromSet[fromToken]->position[1] - toSet[toToken]->position[1])) +
((fromSet[fromToken]->position[2] - toSet[toToken]->position[2]) *
(fromSet[fromToken]->position[2] - toSet[toToken]->position[2])));
return math_util::fastsqrt((float)distanceSquared);
}
double PositionTracker::waypointDistance(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const
{
double separationDistance = distanceBetween(fromToken, toToken, fromGroup, toGroup);
double shortestDistance = separationDistance;
// horrible linear search
std::map<std::pair<unsigned short int, unsigned short int>, double>::const_iterator waypointIterator;
for (waypointIterator = _waypointDistance.begin(); waypointIterator != _waypointDistance.end(); waypointIterator++) {
double fromDist, toDist, waypointDist;
fromDist = distanceBetween(fromToken, (*waypointIterator).first.first, fromGroup, std::string("__waypoint__"));
toDist = distanceBetween((*waypointIterator).first.second, toToken, std::string("__waypoint__"), toGroup);
waypointDist = fromDist + (*waypointIterator).second + toDist;
if (waypointDist < shortestDistance) {
shortestDistance = waypointDist;
}
}
return shortestDistance;
}
unsigned short int PositionTracker::trackedCount(std::string group) const
{
std::map <std::string, TrackedItemVector>::const_iterator i = _trackedItem.find(group);
const TrackedItemVector& trackSet = (*i).second;
return trackSet.size();
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>the redefinition of i strikes again<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "PositionTracker.h"
/* implementation system headers */
#include <iostream>
#include <string>
/* implementation common headers */
#include "MathUtils.h"
/* private */
/* protected */
/* public: */
PositionTracker::PositionTracker()
{
return;
}
PositionTracker::PositionTracker(const PositionTracker& tracker)
: _trackedItem(tracker._trackedItem),
_waypointDistance(tracker._waypointDistance)
{
return;
}
PositionTracker::~PositionTracker()
{
// clear out all the tracked items vectors
for (std::map<std::string, TrackedItemVector>::iterator jano = _trackedItem.begin(); jano != _trackedItem.end(); jano++) {
TrackedItemVector& trackSet = (*jano).second;
for (unsigned int i = 0; i != trackSet.size(); i++) {
/* sanity clear */
trackSet[i]->id = UNSET_ID;
trackSet[i]->intID = 0;
trackSet[i]->strID = std::string("");
trackSet[i]->lastUpdate = TimeKeeper::getNullTime();
trackSet[i]->position[0] = trackSet[i]->position[1] = trackSet[i]->position[2] = 0.0;
trackSet[i]->forgotten = true;
delete trackSet[i];
}
}
_trackedItem.clear();
// clear out any waypoints
_waypointDistance.clear();
return;
}
/* Linear O(n) time to track a new item since the entire vector is
* searched. if the item is not found, an item is created and added.
*/
unsigned short PositionTracker::track(const std::string id, std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
for (unsigned int i = 0; i != trackSet.size(); i++) {
switch (trackSet[i]->id) {
case STR_ID:
if (id == trackSet[i]->strID) {
return i;
}
break;
case INT_ID:
case UNSET_ID:
break;
default:
std::cerr << "Unknown tracker ID type (id == " << trackSet[i]->id << ")" << std::endl;
break;
}
}
// the item was not found, so create it
item_t *newTracking = new item_t;
newTracking->id = STR_ID;
newTracking->intID = 0;
newTracking->strID = id;
newTracking->lastUpdate = TimeKeeper::getNullTime();
newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0;
newTracking->forgotten = false;
// and add it
trackSet.push_back(newTracking);
// nothing is deleted so should be last index
return trackSet.size() - 1;
}
/* alternative track() passing our own id */
unsigned short PositionTracker::track(long int id, std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
for (unsigned int i = 0; i != trackSet.size(); i++) {
switch (trackSet[i]->id) {
case INT_ID:
if (id == trackSet[i]->intID) {
return i;
}
break;
case STR_ID:
case UNSET_ID:
break;
default:
std::cerr << "Unknown tracker ID type (id == " << trackSet[i]->id << ")" << std::endl;
break;
}
}
// the item was not found, so create it
item_t *newTracking = new item_t;
newTracking->id = INT_ID;
newTracking->intID = id;
newTracking->strID = std::string("");
newTracking->lastUpdate = TimeKeeper::getNullTime();
newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0;
newTracking->forgotten = false;
// and add it
trackSet.push_back(newTracking);
// nothing is deleted so should be last index
return trackSet.size() - 1;
}
bool PositionTracker::update(unsigned short int token, const std::string id, const double position[3], std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
if ((token >= trackSet.size()) ||
(trackSet[token]->id != STR_ID) ||
(trackSet[token]->strID != id) ||
(trackSet[token]->forgotten)) {
return false;
}
trackSet[token]->position[0] = position[0];
trackSet[token]->position[1] = position[1];
trackSet[token]->position[2] = position[2];
trackSet[token]->lastUpdate = TimeKeeper::getCurrent();
return true;
}
bool PositionTracker::update(unsigned short int token, const std::string id, const float position[3], std::string group)
{
double pos[3];
pos[0] = (double)position[0];
pos[1] = (double)position[1];
pos[2] = (double)position[2];
return update(token, id, pos, group);
}
bool PositionTracker::update(unsigned short int token, long int id, const double position[3], std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
if ((token >= trackSet.size()) ||
(trackSet[token]->id != INT_ID) ||
(trackSet[token]->intID != id) ||
(trackSet[token]->forgotten)) {
return false;
}
trackSet[token]->position[0] = position[0];
trackSet[token]->position[1] = position[1];
trackSet[token]->position[2] = position[2];
trackSet[token]->lastUpdate = TimeKeeper::getCurrent();
return true;
}
bool PositionTracker::update(unsigned short int token, long int id, const float position[3], std::string group)
{
double pos[3];
pos[0] = (double)position[0];
pos[1] = (double)position[1];
pos[2] = (double)position[2];
return update(token, id, pos, group);
}
bool PositionTracker::addWaypoint(const double from[3], const double to[3], double distance)
{
unsigned short int fromToken, toToken;
bool updated;
bool foundPoint;
unsigned int i;
TrackedItemVector& waypointSet = _trackedItem[std::string("__waypoint__")];
// see if the first point already exists
foundPoint = false;
for (i = 0; i != waypointSet.size(); i++) {
if ((waypointSet[i]->position[0] = from[0]) &&
(waypointSet[i]->position[1] = from[1]) &&
(waypointSet[i]->position[2] = from[2])) {
foundPoint = true;
fromToken = waypointSet[i]->intID;
}
}
if (!foundPoint) {
// add the first point
unsigned short int nextID = waypointSet.size();
fromToken = track((long int)nextID, std::string("__waypoint__"));
updated = update(fromToken, nextID, from, std::string("__waypoint__"));
if (!updated) {
std::cerr << "Unable to add waypoint?!" << std::endl;
return false;
}
}
// see if the second point already exists
foundPoint = false;
for (i = 0; i != waypointSet.size(); i++) {
if ((waypointSet[i]->position[0] = to[0]) &&
(waypointSet[i]->position[1] = to[1]) &&
(waypointSet[i]->position[2] = to[2])) {
foundPoint = true;
toToken = waypointSet[i]->intID;
}
}
if (!foundPoint) {
// add the second point
unsigned short int nextID = waypointSet.size();
toToken = track((long int)nextID, std::string("__waypoint__"));
updated = update(toToken, nextID, to, std::string("__waypoint__"));
if (!updated) {
std::cerr << "Unable to add waypoint?!" << std::endl;
return false;
}
}
// compute and use real distance if distance passed was negative
if (distance < 0.0) {
distance = distanceBetween(fromToken, toToken, std::string("__waypoint__"), std::string("__waypoint__"));
}
std::pair<unsigned short int, unsigned short int> waypoint = std::make_pair(fromToken, toToken);
// see if the waypoint pair have already been added
/*
std::map<std::pair<unsigned short int, unsigned short int>, double>::iterator jano = _waypointDistance.find(waypoint);
if (jano != _waypointDistance.end()) {
// waypoint already added, but set distance anyways (might be an update)
(*jano).second = distance;
}
*/
_waypointDistance[waypoint] = distance;
return true;
}
bool PositionTracker::addWaypoint(const float from[3], const float to[3], double distance)
{
double fromPos[3], toPos[3];
fromPos[0] = from[0];
fromPos[1] = from[1];
fromPos[2] = from[2];
toPos[0] = to[0];
toPos[1] = to[1];
toPos[2] = to[2];
return addWaypoint(fromPos, toPos, distance);
}
bool PositionTracker::forget(unsigned short int token, const std::string id, std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
if ((token >= trackSet.size()) ||
(trackSet[token]->id != STR_ID) ||
(trackSet[token]->strID != id) ||
(trackSet[token]->forgotten)) {
return false;
}
trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0;
trackSet[token]->forgotten = true;
return true;
}
bool PositionTracker::forget(unsigned short int token, long int id, std::string group)
{
TrackedItemVector& trackSet = _trackedItem[group];
if ((token >= trackSet.size()) ||
(trackSet[token]->id != INT_ID) ||
(trackSet[token]->intID != id) ||
(trackSet[token]->forgotten)) {
return false;
}
trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0;
trackSet[token]->forgotten = true;
return true;
}
double PositionTracker::distanceBetween(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const
{
// this indirection nastiness is needed to maintain constness
std::map <std::string, TrackedItemVector>::const_iterator fromIterator = _trackedItem.find(fromGroup);
std::map <std::string, TrackedItemVector>::const_iterator toIterator = _trackedItem.find(toGroup);
const TrackedItemVector& fromSet = (*fromIterator).second;
const TrackedItemVector& toSet = (*toIterator).second;
if ((fromToken > fromSet.size()) ||
(toToken > toSet.size()) ||
(fromToken == toToken)) {
return 0.0;
}
// basic Cartesian 3-space formula for distance between two points
double distanceSquared = (((fromSet[fromToken]->position[0] - toSet[toToken]->position[0]) *
(fromSet[fromToken]->position[0] - toSet[toToken]->position[0])) +
((fromSet[fromToken]->position[1] - toSet[toToken]->position[1]) *
(fromSet[fromToken]->position[1] - toSet[toToken]->position[1])) +
((fromSet[fromToken]->position[2] - toSet[toToken]->position[2]) *
(fromSet[fromToken]->position[2] - toSet[toToken]->position[2])));
return math_util::fastsqrt((float)distanceSquared);
}
double PositionTracker::waypointDistance(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const
{
double separationDistance = distanceBetween(fromToken, toToken, fromGroup, toGroup);
double shortestDistance = separationDistance;
// horrible linear search
std::map<std::pair<unsigned short int, unsigned short int>, double>::const_iterator waypointIterator;
for (waypointIterator = _waypointDistance.begin(); waypointIterator != _waypointDistance.end(); waypointIterator++) {
double fromDist, toDist, waypointDist;
fromDist = distanceBetween(fromToken, (*waypointIterator).first.first, fromGroup, std::string("__waypoint__"));
toDist = distanceBetween((*waypointIterator).first.second, toToken, std::string("__waypoint__"), toGroup);
waypointDist = fromDist + (*waypointIterator).second + toDist;
if (waypointDist < shortestDistance) {
shortestDistance = waypointDist;
}
}
return shortestDistance;
}
unsigned short int PositionTracker::trackedCount(std::string group) const
{
std::map <std::string, TrackedItemVector>::const_iterator i = _trackedItem.find(group);
const TrackedItemVector& trackSet = (*i).second;
return trackSet.size();
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2016 gRPC authors.
*
* 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 <map>
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
#include "src/compiler/node_generator_helpers.h"
using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using std::map;
namespace grpc_node_generator {
namespace {
// Returns the alias we assign to the module of the given .proto filename
// when importing. Copied entirely from
// github:google/protobuf/src/google/protobuf/compiler/js/js_generator.cc#L154
grpc::string ModuleAlias(const grpc::string filename) {
// This scheme could technically cause problems if a file includes any 2 of:
// foo/bar_baz.proto
// foo_bar_baz.proto
// foo_bar/baz.proto
//
// We'll worry about this problem if/when we actually see it. This name isn't
// exposed to users so we can change it later if we need to.
grpc::string basename = grpc_generator::StripProto(filename);
basename = grpc_generator::StringReplace(basename, "-", "$");
basename = grpc_generator::StringReplace(basename, "/", "_");
basename = grpc_generator::StringReplace(basename, ".", "_");
return basename + "_pb";
}
// Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript
// message file foo/bar/baz.js
grpc::string GetJSMessageFilename(const grpc::string& filename) {
grpc::string name = filename;
return grpc_generator::StripProto(name) + "_pb.js";
}
// Given a filename like foo/bar/baz.proto, returns the root directory
// path ../../
grpc::string GetRootPath(const grpc::string& from_filename,
const grpc::string& to_filename) {
if (to_filename.find("google/protobuf") == 0) {
// Well-known types (.proto files in the google/protobuf directory) are
// assumed to come from the 'google-protobuf' npm package. We may want to
// generalize this exception later by letting others put generated code in
// their own npm packages.
return "google-protobuf/";
}
size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/');
if (slashes == 0) {
return "./";
}
grpc::string result = "";
for (size_t i = 0; i < slashes; i++) {
result += "../";
}
return result;
}
// Return the relative path to load to_file from the directory containing
// from_file, assuming that both paths are relative to the same directory
grpc::string GetRelativePath(const grpc::string& from_file,
const grpc::string& to_file) {
return GetRootPath(from_file, to_file) + to_file;
}
/* Finds all message types used in all services in the file, and returns them
* as a map of fully qualified message type name to message descriptor */
map<grpc::string, const Descriptor*> GetAllMessages(
const FileDescriptor* file) {
map<grpc::string, const Descriptor*> message_types;
for (int service_num = 0; service_num < file->service_count();
service_num++) {
const ServiceDescriptor* service = file->service(service_num);
for (int method_num = 0; method_num < service->method_count();
method_num++) {
const MethodDescriptor* method = service->method(method_num);
const Descriptor* input_type = method->input_type();
const Descriptor* output_type = method->output_type();
message_types[input_type->full_name()] = input_type;
message_types[output_type->full_name()] = output_type;
}
}
return message_types;
}
grpc::string MessageIdentifierName(const grpc::string& name) {
return grpc_generator::StringReplace(name, ".", "_");
}
grpc::string NodeObjectPath(const Descriptor* descriptor) {
grpc::string module_alias = ModuleAlias(descriptor->file()->name());
grpc::string name = descriptor->full_name();
grpc_generator::StripPrefix(&name, descriptor->file()->package() + ".");
return module_alias + "." + name;
}
// Prints out the message serializer and deserializer functions
void PrintMessageTransformer(const Descriptor* descriptor, Printer* out) {
map<grpc::string, grpc::string> template_vars;
grpc::string full_name = descriptor->full_name();
template_vars["identifier_name"] = MessageIdentifierName(full_name);
template_vars["name"] = full_name;
template_vars["node_name"] = NodeObjectPath(descriptor);
// Print the serializer
out->Print(template_vars, "function serialize_$identifier_name$(arg) {\n");
out->Indent();
out->Print(template_vars, "if (!(arg instanceof $node_name$)) {\n");
out->Indent();
out->Print(template_vars,
"throw new Error('Expected argument of type $name$');\n");
out->Outdent();
out->Print("}\n");
out->Print("return new Buffer(arg.serializeBinary());\n");
out->Outdent();
out->Print("}\n\n");
// Print the deserializer
out->Print(template_vars,
"function deserialize_$identifier_name$(buffer_arg) {\n");
out->Indent();
out->Print(
template_vars,
"return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\n");
out->Outdent();
out->Print("}\n\n");
}
void PrintMethod(const MethodDescriptor* method, Printer* out) {
const Descriptor* input_type = method->input_type();
const Descriptor* output_type = method->output_type();
map<grpc::string, grpc::string> vars;
vars["service_name"] = method->service()->full_name();
vars["name"] = method->name();
vars["input_type"] = NodeObjectPath(input_type);
vars["input_type_id"] = MessageIdentifierName(input_type->full_name());
vars["output_type"] = NodeObjectPath(output_type);
vars["output_type_id"] = MessageIdentifierName(output_type->full_name());
vars["client_stream"] = method->client_streaming() ? "true" : "false";
vars["server_stream"] = method->server_streaming() ? "true" : "false";
out->Print("{\n");
out->Indent();
out->Print(vars, "path: '/$service_name$/$name$',\n");
out->Print(vars, "requestStream: $client_stream$,\n");
out->Print(vars, "responseStream: $server_stream$,\n");
out->Print(vars, "requestType: $input_type$,\n");
out->Print(vars, "responseType: $output_type$,\n");
out->Print(vars, "requestSerialize: serialize_$input_type_id$,\n");
out->Print(vars, "requestDeserialize: deserialize_$input_type_id$,\n");
out->Print(vars, "responseSerialize: serialize_$output_type_id$,\n");
out->Print(vars, "responseDeserialize: deserialize_$output_type_id$,\n");
out->Outdent();
out->Print("}");
}
// Prints out the service descriptor object
void PrintService(const ServiceDescriptor* service, Printer* out) {
map<grpc::string, grpc::string> template_vars;
out->Print(GetNodeComments(service, true).c_str());
template_vars["name"] = service->name();
out->Print(template_vars, "var $name$Service = exports.$name$Service = {\n");
out->Indent();
for (int i = 0; i < service->method_count(); i++) {
grpc::string method_name =
grpc_generator::LowercaseFirstLetter(service->method(i)->name());
out->Print(GetNodeComments(service->method(i), true).c_str());
out->Print("$method_name$: ", "method_name", method_name);
PrintMethod(service->method(i), out);
out->Print(",\n");
out->Print(GetNodeComments(service->method(i), false).c_str());
}
out->Outdent();
out->Print("};\n\n");
out->Print(template_vars,
"exports.$name$Client = "
"grpc.makeGenericClientConstructor($name$Service);\n");
out->Print(GetNodeComments(service, false).c_str());
}
void PrintImports(const FileDescriptor* file, Printer* out) {
out->Print("var grpc = require('grpc');\n");
if (file->message_type_count() > 0) {
grpc::string file_path =
GetRelativePath(file->name(), GetJSMessageFilename(file->name()));
out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
ModuleAlias(file->name()), "file_path", file_path);
}
for (int i = 0; i < file->dependency_count(); i++) {
grpc::string file_path = GetRelativePath(
file->name(), GetJSMessageFilename(file->dependency(i)->name()));
out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
ModuleAlias(file->dependency(i)->name()), "file_path",
file_path);
}
out->Print("\n");
}
void PrintTransformers(const FileDescriptor* file, Printer* out) {
map<grpc::string, const Descriptor*> messages = GetAllMessages(file);
for (std::map<grpc::string, const Descriptor*>::iterator it =
messages.begin();
it != messages.end(); it++) {
PrintMessageTransformer(it->second, out);
}
out->Print("\n");
}
void PrintServices(const FileDescriptor* file, Printer* out) {
for (int i = 0; i < file->service_count(); i++) {
PrintService(file->service(i), out);
}
}
} // namespace
grpc::string GenerateFile(const FileDescriptor* file) {
grpc::string output;
{
StringOutputStream output_stream(&output);
Printer out(&output_stream, '$');
if (file->service_count() == 0) {
return output;
}
out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
grpc::string leading_comments = GetNodeComments(file, true);
if (!leading_comments.empty()) {
out.Print("// Original file comments:\n");
out.PrintRaw(leading_comments.c_str());
}
out.Print("'use strict';\n");
PrintImports(file, &out);
PrintTransformers(file, &out);
PrintServices(file, &out);
out.Print(GetNodeComments(file, false).c_str());
}
return output;
}
} // namespace grpc_node_generator
<commit_msg>Switch to Buffer.from to avoid using deprecated constructor<commit_after>/*
*
* Copyright 2016 gRPC authors.
*
* 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 <map>
#include "src/compiler/config.h"
#include "src/compiler/generator_helpers.h"
#include "src/compiler/node_generator_helpers.h"
using grpc::protobuf::Descriptor;
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using std::map;
namespace grpc_node_generator {
namespace {
// Returns the alias we assign to the module of the given .proto filename
// when importing. Copied entirely from
// github:google/protobuf/src/google/protobuf/compiler/js/js_generator.cc#L154
grpc::string ModuleAlias(const grpc::string filename) {
// This scheme could technically cause problems if a file includes any 2 of:
// foo/bar_baz.proto
// foo_bar_baz.proto
// foo_bar/baz.proto
//
// We'll worry about this problem if/when we actually see it. This name isn't
// exposed to users so we can change it later if we need to.
grpc::string basename = grpc_generator::StripProto(filename);
basename = grpc_generator::StringReplace(basename, "-", "$");
basename = grpc_generator::StringReplace(basename, "/", "_");
basename = grpc_generator::StringReplace(basename, ".", "_");
return basename + "_pb";
}
// Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript
// message file foo/bar/baz.js
grpc::string GetJSMessageFilename(const grpc::string& filename) {
grpc::string name = filename;
return grpc_generator::StripProto(name) + "_pb.js";
}
// Given a filename like foo/bar/baz.proto, returns the root directory
// path ../../
grpc::string GetRootPath(const grpc::string& from_filename,
const grpc::string& to_filename) {
if (to_filename.find("google/protobuf") == 0) {
// Well-known types (.proto files in the google/protobuf directory) are
// assumed to come from the 'google-protobuf' npm package. We may want to
// generalize this exception later by letting others put generated code in
// their own npm packages.
return "google-protobuf/";
}
size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/');
if (slashes == 0) {
return "./";
}
grpc::string result = "";
for (size_t i = 0; i < slashes; i++) {
result += "../";
}
return result;
}
// Return the relative path to load to_file from the directory containing
// from_file, assuming that both paths are relative to the same directory
grpc::string GetRelativePath(const grpc::string& from_file,
const grpc::string& to_file) {
return GetRootPath(from_file, to_file) + to_file;
}
/* Finds all message types used in all services in the file, and returns them
* as a map of fully qualified message type name to message descriptor */
map<grpc::string, const Descriptor*> GetAllMessages(
const FileDescriptor* file) {
map<grpc::string, const Descriptor*> message_types;
for (int service_num = 0; service_num < file->service_count();
service_num++) {
const ServiceDescriptor* service = file->service(service_num);
for (int method_num = 0; method_num < service->method_count();
method_num++) {
const MethodDescriptor* method = service->method(method_num);
const Descriptor* input_type = method->input_type();
const Descriptor* output_type = method->output_type();
message_types[input_type->full_name()] = input_type;
message_types[output_type->full_name()] = output_type;
}
}
return message_types;
}
grpc::string MessageIdentifierName(const grpc::string& name) {
return grpc_generator::StringReplace(name, ".", "_");
}
grpc::string NodeObjectPath(const Descriptor* descriptor) {
grpc::string module_alias = ModuleAlias(descriptor->file()->name());
grpc::string name = descriptor->full_name();
grpc_generator::StripPrefix(&name, descriptor->file()->package() + ".");
return module_alias + "." + name;
}
// Prints out the message serializer and deserializer functions
void PrintMessageTransformer(const Descriptor* descriptor, Printer* out) {
map<grpc::string, grpc::string> template_vars;
grpc::string full_name = descriptor->full_name();
template_vars["identifier_name"] = MessageIdentifierName(full_name);
template_vars["name"] = full_name;
template_vars["node_name"] = NodeObjectPath(descriptor);
// Print the serializer
out->Print(template_vars, "function serialize_$identifier_name$(arg) {\n");
out->Indent();
out->Print(template_vars, "if (!(arg instanceof $node_name$)) {\n");
out->Indent();
out->Print(template_vars,
"throw new Error('Expected argument of type $name$');\n");
out->Outdent();
out->Print("}\n");
out->Print("return Buffer.from(arg.serializeBinary());\n");
out->Outdent();
out->Print("}\n\n");
// Print the deserializer
out->Print(template_vars,
"function deserialize_$identifier_name$(buffer_arg) {\n");
out->Indent();
out->Print(
template_vars,
"return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\n");
out->Outdent();
out->Print("}\n\n");
}
void PrintMethod(const MethodDescriptor* method, Printer* out) {
const Descriptor* input_type = method->input_type();
const Descriptor* output_type = method->output_type();
map<grpc::string, grpc::string> vars;
vars["service_name"] = method->service()->full_name();
vars["name"] = method->name();
vars["input_type"] = NodeObjectPath(input_type);
vars["input_type_id"] = MessageIdentifierName(input_type->full_name());
vars["output_type"] = NodeObjectPath(output_type);
vars["output_type_id"] = MessageIdentifierName(output_type->full_name());
vars["client_stream"] = method->client_streaming() ? "true" : "false";
vars["server_stream"] = method->server_streaming() ? "true" : "false";
out->Print("{\n");
out->Indent();
out->Print(vars, "path: '/$service_name$/$name$',\n");
out->Print(vars, "requestStream: $client_stream$,\n");
out->Print(vars, "responseStream: $server_stream$,\n");
out->Print(vars, "requestType: $input_type$,\n");
out->Print(vars, "responseType: $output_type$,\n");
out->Print(vars, "requestSerialize: serialize_$input_type_id$,\n");
out->Print(vars, "requestDeserialize: deserialize_$input_type_id$,\n");
out->Print(vars, "responseSerialize: serialize_$output_type_id$,\n");
out->Print(vars, "responseDeserialize: deserialize_$output_type_id$,\n");
out->Outdent();
out->Print("}");
}
// Prints out the service descriptor object
void PrintService(const ServiceDescriptor* service, Printer* out) {
map<grpc::string, grpc::string> template_vars;
out->Print(GetNodeComments(service, true).c_str());
template_vars["name"] = service->name();
out->Print(template_vars, "var $name$Service = exports.$name$Service = {\n");
out->Indent();
for (int i = 0; i < service->method_count(); i++) {
grpc::string method_name =
grpc_generator::LowercaseFirstLetter(service->method(i)->name());
out->Print(GetNodeComments(service->method(i), true).c_str());
out->Print("$method_name$: ", "method_name", method_name);
PrintMethod(service->method(i), out);
out->Print(",\n");
out->Print(GetNodeComments(service->method(i), false).c_str());
}
out->Outdent();
out->Print("};\n\n");
out->Print(template_vars,
"exports.$name$Client = "
"grpc.makeGenericClientConstructor($name$Service);\n");
out->Print(GetNodeComments(service, false).c_str());
}
void PrintImports(const FileDescriptor* file, Printer* out) {
out->Print("var grpc = require('grpc');\n");
if (file->message_type_count() > 0) {
grpc::string file_path =
GetRelativePath(file->name(), GetJSMessageFilename(file->name()));
out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
ModuleAlias(file->name()), "file_path", file_path);
}
for (int i = 0; i < file->dependency_count(); i++) {
grpc::string file_path = GetRelativePath(
file->name(), GetJSMessageFilename(file->dependency(i)->name()));
out->Print("var $module_alias$ = require('$file_path$');\n", "module_alias",
ModuleAlias(file->dependency(i)->name()), "file_path",
file_path);
}
out->Print("\n");
}
void PrintTransformers(const FileDescriptor* file, Printer* out) {
map<grpc::string, const Descriptor*> messages = GetAllMessages(file);
for (std::map<grpc::string, const Descriptor*>::iterator it =
messages.begin();
it != messages.end(); it++) {
PrintMessageTransformer(it->second, out);
}
out->Print("\n");
}
void PrintServices(const FileDescriptor* file, Printer* out) {
for (int i = 0; i < file->service_count(); i++) {
PrintService(file->service(i), out);
}
}
} // namespace
grpc::string GenerateFile(const FileDescriptor* file) {
grpc::string output;
{
StringOutputStream output_stream(&output);
Printer out(&output_stream, '$');
if (file->service_count() == 0) {
return output;
}
out.Print("// GENERATED CODE -- DO NOT EDIT!\n\n");
grpc::string leading_comments = GetNodeComments(file, true);
if (!leading_comments.empty()) {
out.Print("// Original file comments:\n");
out.PrintRaw(leading_comments.c_str());
}
out.Print("'use strict';\n");
PrintImports(file, &out);
PrintTransformers(file, &out);
PrintServices(file, &out);
out.Print(GetNodeComments(file, false).c_str());
}
return output;
}
} // namespace grpc_node_generator
<|endoftext|>
|
<commit_before>#include "components/BulletMover.h"
#include <bullet/btBulletCollisionCommon.h>
#include <bullet/btBulletDynamicsCommon.h>
namespace Sigma {
BulletMover::BulletMover(const int entityID) : IBulletShape(entityID), transform(nullptr) {}
BulletMover::~BulletMover() {}
void BulletMover::ApplyForces(const double delta) {
if (this->transform) {
glm::vec3 deltavec(delta);
glm::vec3 totalForce;
glm::vec3 targetrvel;
for (auto rotitr = this->rotationForces.begin(); rotitr != this->rotationForces.end(); ++rotitr) {
this->transform->Rotate((*rotitr) * deltavec);
}
// Inertial rotation
targetrvel = _rotationtarget * deltavec;
if(fabs(targetrvel.x) > 0.0001f || fabs(targetrvel.y) > 0.0001f || fabs(targetrvel.z) > 0.0001f) {
targetrvel = this->transform->Restrict(targetrvel);
this->transform->Rotate(targetrvel);
_rotationtarget -= targetrvel;
}
targetrvel = this->transform->Restrict(targetrvel);
this->rotationForces.clear();
for (auto forceitr = this->forces.begin(); forceitr != this->forces.end(); ++forceitr) {
totalForce += *forceitr;
}
glm::vec3 finalForce = (totalForce.z * this->transform->GetForward()) +
(totalForce.y * this->transform->GetUp()) +
(totalForce.x * this->transform->GetRight());
body->setActivationState(DISABLE_DEACTIVATION);
this->body->setLinearVelocity(btVector3(finalForce.x, this->body->getLinearVelocity().y() + 0.000000001f, finalForce.z));
}
}
void BulletMover::UpdateTransform() {
if (this->transform) {
btTransform trans;
this->body->getMotionState()->getWorldTransform(trans);
this->transform->TranslateTo(trans.getOrigin().x(),trans.getOrigin().y(), trans.getOrigin().z());
}
}
void BulletMover::InitializeRigidBody(float x, float y, float z, float rx, float ry, float rz) {
this->shape = new btCapsuleShape(0.3f, 1.3f);
btScalar mass = 1;
btVector3 fallInertia(0,0,0);
this->motionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(x, y, z)));
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, motionState, shape,fallInertia);
this->shape->calculateLocalInertia(mass,fallInertia);
this->body = new btRigidBody(fallRigidBodyCI);
}
void BulletMover::InitializeRigidBody() {
if(this->transform) {
this->InitializeRigidBody(
this->transform->GetPosition().x,
this->transform->GetPosition().y,
this->transform->GetPosition().z,
this->transform->GetPitch(),
this->transform->GetYaw(),
this->transform->GetRoll()
);
}
else {
this->InitializeRigidBody(0,1.5f,0,0,0,0);
}
}
// immediate mode rotation (for mouse motion)
void BulletMover::RotateNow(float x, float y, float z) {
if (this->transform) {
this->transform->Rotate(x,y,z);
}
}
void BulletMover::RotateTarget(float x, float y, float z) {
if (this->transform) {
this->_rotationtarget += glm::vec3(x,y,z);
}
}
}
<commit_msg>Fix entity id type of BulletMover<commit_after>#include "components/BulletMover.h"
#include <bullet/btBulletCollisionCommon.h>
#include <bullet/btBulletDynamicsCommon.h>
namespace Sigma {
BulletMover::BulletMover(const id_t entityID) : IBulletShape(entityID), transform(nullptr) {}
BulletMover::~BulletMover() {}
void BulletMover::ApplyForces(const double delta) {
if (this->transform) {
glm::vec3 deltavec(delta);
glm::vec3 totalForce;
glm::vec3 targetrvel;
for (auto rotitr = this->rotationForces.begin(); rotitr != this->rotationForces.end(); ++rotitr) {
this->transform->Rotate((*rotitr) * deltavec);
}
// Inertial rotation
targetrvel = _rotationtarget * deltavec;
if(fabs(targetrvel.x) > 0.0001f || fabs(targetrvel.y) > 0.0001f || fabs(targetrvel.z) > 0.0001f) {
targetrvel = this->transform->Restrict(targetrvel);
this->transform->Rotate(targetrvel);
_rotationtarget -= targetrvel;
}
targetrvel = this->transform->Restrict(targetrvel);
this->rotationForces.clear();
for (auto forceitr = this->forces.begin(); forceitr != this->forces.end(); ++forceitr) {
totalForce += *forceitr;
}
glm::vec3 finalForce = (totalForce.z * this->transform->GetForward()) +
(totalForce.y * this->transform->GetUp()) +
(totalForce.x * this->transform->GetRight());
body->setActivationState(DISABLE_DEACTIVATION);
this->body->setLinearVelocity(btVector3(finalForce.x, this->body->getLinearVelocity().y() + 0.000000001f, finalForce.z));
}
}
void BulletMover::UpdateTransform() {
if (this->transform) {
btTransform trans;
this->body->getMotionState()->getWorldTransform(trans);
this->transform->TranslateTo(trans.getOrigin().x(),trans.getOrigin().y(), trans.getOrigin().z());
}
}
void BulletMover::InitializeRigidBody(float x, float y, float z, float rx, float ry, float rz) {
this->shape = new btCapsuleShape(0.3f, 1.3f);
btScalar mass = 1;
btVector3 fallInertia(0,0,0);
this->motionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(x, y, z)));
btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, motionState, shape,fallInertia);
this->shape->calculateLocalInertia(mass,fallInertia);
this->body = new btRigidBody(fallRigidBodyCI);
}
void BulletMover::InitializeRigidBody() {
if(this->transform) {
this->InitializeRigidBody(
this->transform->GetPosition().x,
this->transform->GetPosition().y,
this->transform->GetPosition().z,
this->transform->GetPitch(),
this->transform->GetYaw(),
this->transform->GetRoll()
);
}
else {
this->InitializeRigidBody(0,1.5f,0,0,0,0);
}
}
// immediate mode rotation (for mouse motion)
void BulletMover::RotateNow(float x, float y, float z) {
if (this->transform) {
this->transform->Rotate(x,y,z);
}
}
void BulletMover::RotateTarget(float x, float y, float z) {
if (this->transform) {
this->_rotationtarget += glm::vec3(x,y,z);
}
}
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "selector.h"
void display_fd_set( char *msg, fd_set *set, int max );
int Selector::_fd_select_size = -1;
fd_set *Selector::cached_read_fds = NULL;
fd_set *Selector::cached_write_fds = NULL;
fd_set *Selector::cached_except_fds = NULL;
fd_set *Selector::cached_save_read_fds = NULL;
fd_set *Selector::cached_save_write_fds = NULL;
fd_set *Selector::cached_save_except_fds = NULL;
Selector::Selector()
{
#if defined(WIN32)
// On Windows, we can't treat fd_set as an open-ended bit array.
// fd_set can take up to FD_SETSIZE sockets (not any socket whose
// fd is <= FD_SETSIZE) and that's it. Currently, we set
// FD_SETSIZE to 1024. I'm not sure what we can do if we ever
// have more than 1024 sockets to select on.
fd_set_size = 1;
#else
int nfdbits = 8 * sizeof(fd_set);
fd_set_size = ( fd_select_size() + (nfdbits - 1) ) / nfdbits;
#endif
if ( cached_read_fds ) {
read_fds = cached_read_fds;
write_fds = cached_write_fds;
except_fds = cached_except_fds;
save_read_fds = cached_save_read_fds;
save_write_fds = cached_save_write_fds;
save_except_fds = cached_save_except_fds;
cached_read_fds = NULL;
cached_write_fds = NULL;
cached_except_fds = NULL;
cached_save_read_fds = NULL;
cached_save_write_fds = NULL;
cached_save_except_fds = NULL;
} else {
read_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
write_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
except_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
save_read_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
save_write_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
save_except_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
}
reset();
}
Selector::~Selector()
{
if ( cached_read_fds == NULL ) {
cached_read_fds = read_fds;
cached_write_fds = write_fds;
cached_except_fds = except_fds;
cached_save_read_fds = save_read_fds;
cached_save_write_fds = save_write_fds;
cached_save_except_fds = save_except_fds;
} else {
free( read_fds );
free( write_fds );
free( except_fds );
free( save_read_fds );
free( save_write_fds );
free( save_except_fds );
}
}
void
Selector::reset()
{
_select_retval = -2;
state = VIRGIN;
timeout_wanted = FALSE;
max_fd = -1;
#if defined(WIN32)
FD_ZERO( save_read_fds );
FD_ZERO( save_write_fds );
FD_ZERO( save_except_fds );
#else
memset( save_read_fds, 0, fd_set_size * sizeof(fd_set) );
memset( save_write_fds, 0, fd_set_size * sizeof(fd_set) );
memset( save_except_fds, 0, fd_set_size * sizeof(fd_set) );
#endif
}
int
Selector::fd_select_size()
{
if ( _fd_select_size < 0 ) {
#if defined(WIN32)
// On Windows, fd_set is not a bit-array, but a structure that can
// hold up to 1024 different file descriptors (not just file
// descriptors whose value is less than 1024). We set max_fd to
// 1024 (FD_SETSIZE) as a reasonable approximation.
_fd_select_size = FD_SETSIZE;
#elif defined(Solaris)
// Solaris's select() can't handle fds greater than FD_SETSIZE.
int max_fds = getdtablesize();
if ( max_fds < FD_SETSIZE ) {
_fd_select_size = max_fds;
} else {
_fd_select_size = FD_SETSIZE;
}
#else
_fd_select_size = getdtablesize();
#endif
}
return _fd_select_size;
}
void
Selector::add_fd( int fd, IO_FUNC interest )
{
// update max_fd (the highest valid index in fd_set's array) and also
// make sure we're not overflowing our fd_set
//
#if defined(WIN32)
max_fd++;
if (max_fd > fd_select_size() - 1) {
EXCEPT("Selector::add_fd(): fd_set is full");
}
#else
if( fd > max_fd ) {
max_fd = fd;
}
if ( fd < 0 || fd >= fd_select_size() ) {
EXCEPT( "Selector::add_fd(): fd %d outside valid range 0-%d",
fd, _fd_select_size-1 );
}
#endif
switch( interest ) {
case IO_READ:
FD_SET( fd, save_read_fds );
break;
case IO_WRITE:
FD_SET( fd, save_write_fds );
break;
case IO_EXCEPT:
FD_SET( fd, save_except_fds );
break;
}
}
void
Selector::delete_fd( int fd, IO_FUNC interest )
{
// on Windows, we need to update max_fd since it keeps track of
// how many sockets are in our fd_set. in UNIX, just do a sanity
// check based on the value of fd
//
#if defined(WIN32)
max_fd--;
#else
if ( fd < 0 || fd > fd_select_size() ) {
EXCEPT( "Selector::delete_fd(): fd %d outside valid range 0-%d",
fd, _fd_select_size-1 );
}
#endif
switch( interest ) {
case IO_READ:
FD_CLR( fd, save_read_fds );
break;
case IO_WRITE:
FD_CLR( fd, save_write_fds );
break;
case IO_EXCEPT:
FD_CLR( fd, save_except_fds );
break;
}
}
void
Selector::set_timeout( time_t sec, long usec )
{
timeout_wanted = TRUE;
timeout.tv_sec = sec;
timeout.tv_usec = usec;
}
void
Selector::set_timeout( timeval tv )
{
timeout_wanted = TRUE;
timeout = tv;
}
void
Selector::unset_timeout()
{
timeout_wanted = FALSE;
}
void
Selector::execute()
{
int nfds;
struct timeval *tp;
memcpy( read_fds, save_read_fds, fd_set_size * sizeof(fd_set) );
memcpy( write_fds, save_write_fds, fd_set_size * sizeof(fd_set) );
memcpy( except_fds, save_except_fds, fd_set_size * sizeof(fd_set) );
if( timeout_wanted ) {
tp = &timeout;
} else {
tp = NULL;
}
nfds = select( max_fd + 1,
(SELECT_FDSET_PTR) read_fds,
(SELECT_FDSET_PTR) write_fds,
(SELECT_FDSET_PTR) except_fds,
tp );
_select_retval = nfds;
if( nfds < 0 ) {
#if !defined(WIN32)
if( errno == EINTR ) {
state = SIGNALLED;
return;
}
#endif
state = FAILED;
return;
}
if( nfds == 0 ) {
state = TIMED_OUT;
} else {
state = FDS_READY;
}
return;
}
int
Selector::select_retval()
{
return _select_retval;
}
BOOLEAN
Selector::fd_ready( int fd, IO_FUNC interest )
{
if( state != FDS_READY && state != TIMED_OUT ) {
EXCEPT(
"Selector::fd_ready() called, but selector not in FDS_READY state"
);
}
#if !defined(WIN32)
// on UNIX, make sure the value of fd makes sense
//
if ( fd < 0 || fd > fd_select_size() ) {
return FALSE;
}
#endif
switch( interest ) {
case IO_READ:
return FD_ISSET( fd, read_fds );
break;
case IO_WRITE:
return FD_ISSET( fd, write_fds );
break;
case IO_EXCEPT:
return FD_ISSET( fd, except_fds );
break;
}
// Can never get here
return FALSE;
}
BOOLEAN
Selector::timed_out()
{
return state == TIMED_OUT;
}
BOOLEAN
Selector::signalled()
{
return state == SIGNALLED;
}
BOOLEAN
Selector::failed()
{
return state == FAILED;
}
BOOLEAN
Selector::has_ready()
{
return state == FDS_READY;
}
void
Selector::display()
{
switch( state ) {
case VIRGIN:
dprintf( D_ALWAYS, "State = VIRGIN\n" );
break;
case FDS_READY:
dprintf( D_ALWAYS, "State = FDS_READY\n" );
break;
case TIMED_OUT:
dprintf( D_ALWAYS, "State = TIMED_OUT\n" );
break;
case SIGNALLED:
dprintf( D_ALWAYS, "State = SIGNALLED\n" );
break;
case FAILED:
dprintf( D_ALWAYS, "State = FAILED\n" );
break;
}
dprintf( D_ALWAYS, "max_fd = %d\n", max_fd );
dprintf( D_ALWAYS, "Selection FD's\n" );
display_fd_set( "\tRead", save_read_fds, max_fd );
display_fd_set( "\tWrite", save_write_fds, max_fd );
display_fd_set( "\tExcept", save_except_fds, max_fd );
if( state == FDS_READY ) {
dprintf( D_ALWAYS, "Ready FD's\n" );
display_fd_set( "\tRead", read_fds, max_fd );
display_fd_set( "\tWrite", write_fds, max_fd );
display_fd_set( "\tExcept", except_fds, max_fd );
}
if( timeout_wanted ) {
dprintf( D_ALWAYS,
"Timeout = %ld.%06ld seconds\n", (long) timeout.tv_sec,
(long) timeout.tv_usec
);
} else {
dprintf( D_ALWAYS, "Timeout not wanted\n" );
}
}
void
display_fd_set( char *msg, fd_set *set, int max )
{
int i;
dprintf( D_ALWAYS, "%s {", msg );
for( i=0; i<=max; i++ ) {
if( FD_ISSET(i,set) ) {
dprintf( D_ALWAYS | D_NOHEADER, "%d ", i );
}
}
dprintf( D_ALWAYS | D_NOHEADER, "}\n" );
}
<commit_msg>Fix some minor problems in Selector, our wrapper for select(). We have not seen these bite running code yet, so no version history entry. * On Windows, the check for a full fd_set in add_fd() was wrong. * The display functions didn't work correctly on Windows. * Off-by-one errors in checking for out-of-range fds.<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "selector.h"
void display_fd_set( char *msg, fd_set *set, int max );
int Selector::_fd_select_size = -1;
fd_set *Selector::cached_read_fds = NULL;
fd_set *Selector::cached_write_fds = NULL;
fd_set *Selector::cached_except_fds = NULL;
fd_set *Selector::cached_save_read_fds = NULL;
fd_set *Selector::cached_save_write_fds = NULL;
fd_set *Selector::cached_save_except_fds = NULL;
Selector::Selector()
{
#if defined(WIN32)
// On Windows, we can't treat fd_set as an open-ended bit array.
// fd_set can take up to FD_SETSIZE sockets (not any socket whose
// fd is <= FD_SETSIZE) and that's it. Currently, we set
// FD_SETSIZE to 1024. I'm not sure what we can do if we ever
// have more than 1024 sockets to select on.
fd_set_size = 1;
#else
int nfdbits = 8 * sizeof(fd_set);
fd_set_size = ( fd_select_size() + (nfdbits - 1) ) / nfdbits;
#endif
if ( cached_read_fds ) {
read_fds = cached_read_fds;
write_fds = cached_write_fds;
except_fds = cached_except_fds;
save_read_fds = cached_save_read_fds;
save_write_fds = cached_save_write_fds;
save_except_fds = cached_save_except_fds;
cached_read_fds = NULL;
cached_write_fds = NULL;
cached_except_fds = NULL;
cached_save_read_fds = NULL;
cached_save_write_fds = NULL;
cached_save_except_fds = NULL;
} else {
read_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
write_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
except_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
save_read_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
save_write_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
save_except_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );
}
reset();
}
Selector::~Selector()
{
if ( cached_read_fds == NULL ) {
cached_read_fds = read_fds;
cached_write_fds = write_fds;
cached_except_fds = except_fds;
cached_save_read_fds = save_read_fds;
cached_save_write_fds = save_write_fds;
cached_save_except_fds = save_except_fds;
} else {
free( read_fds );
free( write_fds );
free( except_fds );
free( save_read_fds );
free( save_write_fds );
free( save_except_fds );
}
}
void
Selector::reset()
{
_select_retval = -2;
state = VIRGIN;
timeout_wanted = FALSE;
max_fd = -1;
#if defined(WIN32)
FD_ZERO( save_read_fds );
FD_ZERO( save_write_fds );
FD_ZERO( save_except_fds );
#else
memset( save_read_fds, 0, fd_set_size * sizeof(fd_set) );
memset( save_write_fds, 0, fd_set_size * sizeof(fd_set) );
memset( save_except_fds, 0, fd_set_size * sizeof(fd_set) );
#endif
}
int
Selector::fd_select_size()
{
if ( _fd_select_size < 0 ) {
#if defined(WIN32)
// On Windows, fd_set is not a bit-array, but a structure that can
// hold up to 1024 different file descriptors (not just file
// descriptors whose value is less than 1024). We set max_fds to
// 1024 (FD_SETSIZE) as a reasonable approximation.
_fd_select_size = FD_SETSIZE;
#elif defined(Solaris)
// Solaris's select() can't handle fds greater than FD_SETSIZE.
int max_fds = getdtablesize();
if ( max_fds < FD_SETSIZE ) {
_fd_select_size = max_fds;
} else {
_fd_select_size = FD_SETSIZE;
}
#else
_fd_select_size = getdtablesize();
#endif
}
return _fd_select_size;
}
void
Selector::add_fd( int fd, IO_FUNC interest )
{
// update max_fd (the highest valid index in fd_set's array) and also
// make sure we're not overflowing our fd_set
// On Windows, we have to check the individual fd_set to see if it's
// full.
if( fd > max_fd ) {
max_fd = fd;
}
#if !defined(WIN32)
if ( fd < 0 || fd >= fd_select_size() ) {
EXCEPT( "Selector::add_fd(): fd %d outside valid range 0-%d",
fd, _fd_select_size-1 );
}
#endif
switch( interest ) {
case IO_READ:
#if defined(WIN32)
if ( save_read_fds->fd_count >= fd_select_size() ) {
EXCEPT( "Selector::add_fd(): read fd_set is full" );
}
#endif
FD_SET( fd, save_read_fds );
break;
case IO_WRITE:
#if defined(WIN32)
if ( save_write_fds->fd_count >= fd_select_size() ) {
EXCEPT( "Selector::add_fd(): write fd_set is full" );
}
#endif
FD_SET( fd, save_write_fds );
break;
case IO_EXCEPT:
#if defined(WIN32)
if ( save_except_fds->fd_count >= fd_select_size() ) {
EXCEPT( "Selector::add_fd(): except fd_set is full" );
}
#endif
FD_SET( fd, save_except_fds );
break;
}
}
void
Selector::delete_fd( int fd, IO_FUNC interest )
{
#if !defined(WIN32)
if ( fd < 0 || fd >= fd_select_size() ) {
EXCEPT( "Selector::delete_fd(): fd %d outside valid range 0-%d",
fd, _fd_select_size-1 );
}
#endif
switch( interest ) {
case IO_READ:
FD_CLR( fd, save_read_fds );
break;
case IO_WRITE:
FD_CLR( fd, save_write_fds );
break;
case IO_EXCEPT:
FD_CLR( fd, save_except_fds );
break;
}
}
void
Selector::set_timeout( time_t sec, long usec )
{
timeout_wanted = TRUE;
timeout.tv_sec = sec;
timeout.tv_usec = usec;
}
void
Selector::set_timeout( timeval tv )
{
timeout_wanted = TRUE;
timeout = tv;
}
void
Selector::unset_timeout()
{
timeout_wanted = FALSE;
}
void
Selector::execute()
{
int nfds;
struct timeval *tp;
memcpy( read_fds, save_read_fds, fd_set_size * sizeof(fd_set) );
memcpy( write_fds, save_write_fds, fd_set_size * sizeof(fd_set) );
memcpy( except_fds, save_except_fds, fd_set_size * sizeof(fd_set) );
if( timeout_wanted ) {
tp = &timeout;
} else {
tp = NULL;
}
// select() ignores its first argument on Windows. We still track
// max_fd for the display() functions.
nfds = select( max_fd + 1,
(SELECT_FDSET_PTR) read_fds,
(SELECT_FDSET_PTR) write_fds,
(SELECT_FDSET_PTR) except_fds,
tp );
_select_retval = nfds;
if( nfds < 0 ) {
#if !defined(WIN32)
if( errno == EINTR ) {
state = SIGNALLED;
return;
}
#endif
state = FAILED;
return;
}
if( nfds == 0 ) {
state = TIMED_OUT;
} else {
state = FDS_READY;
}
return;
}
int
Selector::select_retval()
{
return _select_retval;
}
BOOLEAN
Selector::fd_ready( int fd, IO_FUNC interest )
{
if( state != FDS_READY && state != TIMED_OUT ) {
EXCEPT(
"Selector::fd_ready() called, but selector not in FDS_READY state"
);
}
#if !defined(WIN32)
// on UNIX, make sure the value of fd makes sense
//
if ( fd < 0 || fd >= fd_select_size() ) {
return FALSE;
}
#endif
switch( interest ) {
case IO_READ:
return FD_ISSET( fd, read_fds );
break;
case IO_WRITE:
return FD_ISSET( fd, write_fds );
break;
case IO_EXCEPT:
return FD_ISSET( fd, except_fds );
break;
}
// Can never get here
return FALSE;
}
BOOLEAN
Selector::timed_out()
{
return state == TIMED_OUT;
}
BOOLEAN
Selector::signalled()
{
return state == SIGNALLED;
}
BOOLEAN
Selector::failed()
{
return state == FAILED;
}
BOOLEAN
Selector::has_ready()
{
return state == FDS_READY;
}
void
Selector::display()
{
switch( state ) {
case VIRGIN:
dprintf( D_ALWAYS, "State = VIRGIN\n" );
break;
case FDS_READY:
dprintf( D_ALWAYS, "State = FDS_READY\n" );
break;
case TIMED_OUT:
dprintf( D_ALWAYS, "State = TIMED_OUT\n" );
break;
case SIGNALLED:
dprintf( D_ALWAYS, "State = SIGNALLED\n" );
break;
case FAILED:
dprintf( D_ALWAYS, "State = FAILED\n" );
break;
}
dprintf( D_ALWAYS, "max_fd = %d\n", max_fd );
dprintf( D_ALWAYS, "Selection FD's\n" );
display_fd_set( "\tRead", save_read_fds, max_fd );
display_fd_set( "\tWrite", save_write_fds, max_fd );
display_fd_set( "\tExcept", save_except_fds, max_fd );
if( state == FDS_READY ) {
dprintf( D_ALWAYS, "Ready FD's\n" );
display_fd_set( "\tRead", read_fds, max_fd );
display_fd_set( "\tWrite", write_fds, max_fd );
display_fd_set( "\tExcept", except_fds, max_fd );
}
if( timeout_wanted ) {
dprintf( D_ALWAYS,
"Timeout = %ld.%06ld seconds\n", (long) timeout.tv_sec,
(long) timeout.tv_usec
);
} else {
dprintf( D_ALWAYS, "Timeout not wanted\n" );
}
}
void
display_fd_set( char *msg, fd_set *set, int max )
{
int i;
dprintf( D_ALWAYS, "%s {", msg );
for( i=0; i<=max; i++ ) {
if( FD_ISSET(i,set) ) {
dprintf( D_ALWAYS | D_NOHEADER, "%d ", i );
}
}
dprintf( D_ALWAYS | D_NOHEADER, "}\n" );
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_classad.h"
#include "condor_version.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "daemon.h"
#include "dc_collector.h"
#include "reli_sock.h"
#include "command_strings.h"
#include "condor_distribution.h"
int handleHistoryDir(ReliSock *);
void
usage( char *cmd )
{
fprintf(stderr,"Usage: %s [options] <machine-name> <subsystem>[.ext]\n",cmd);
fprintf(stderr,"Where options are:\n");
fprintf(stderr," -help Display options\n");
fprintf(stderr," -version Display Condor version\n");
fprintf(stderr," -pool <hostname> Use this central manager\n");
fprintf(stderr," -debug Show extra debugging info\n");
fprintf(stderr,"To select a particular daemon to talk to (does NOT select log file), use:\n");
fprintf(stderr," -master\n");
fprintf(stderr," -schedd\n");
fprintf(stderr," -startd\n");
fprintf(stderr," -collector\n");
fprintf(stderr," -negotiator\n");
fprintf(stderr," -kbdd\n");
fprintf(stderr," -view_collector\n");
fprintf(stderr,"The subsystem name plus optional extension specifies the log file.\n");
fprintf(stderr,"Possible subsystem names (anything with an entry XXX_LOG in remote config file):\n");
fprintf(stderr," MASTER\n");
fprintf(stderr," COLLECTOR\n");
fprintf(stderr," NEGOTIATOR\n");
fprintf(stderr," NEGOTIATOR_MATCH\n");
fprintf(stderr," SCHEDD\n");
fprintf(stderr," SHADOW\n");
fprintf(stderr," STARTD\n");
fprintf(stderr," STARTER\n");
fprintf(stderr," KBDD\n");
fprintf(stderr," HISTORY\n");
fprintf(stderr," STARTD_HISTORY\n");
fprintf(stderr,"\nExample 1: %s -debug coral STARTD\n",cmd);
fprintf(stderr,"\nExample 2: %s -debug coral STARTER.slot2\n\n",cmd);
}
void
version()
{
printf( "%s\n%s\n", CondorVersion(), CondorPlatform() );
}
int main( int argc, char *argv[] )
{
char *machine_name = 0;
char *log_name = 0;
char *pool=0;
int i;
daemon_t type = DT_MASTER;
myDistro->Init( argc, argv );
config();
for( i=1; i<argc; i++ ) {
if(!strcmp(argv[i],"-help")) {
usage(argv[0]);
exit(0);
} else if(!strcmp(argv[i],"-pool")) {
i++;
if(!argv[i]) {
fprintf(stderr,"-pool requires an argument.\n\n");
usage(argv[0]);
exit(1);
}
pool = argv[i];
} else if(!strcmp(argv[i],"-version")) {
version();
exit(0);
} else if(!strcmp(argv[i],"-debug")) {
dprintf_set_tool_debug("TOOL", 0);
} else if(argv[i][0]=='-') {
type = stringToDaemonType(&argv[i][1]);
if( type == DT_NONE || type == DT_DAGMAN) {
usage(argv[0]);
exit(1);
}
} else if(argv[i][0]!='-') {
if(!machine_name) {
machine_name = argv[i];
} else if(!log_name) {
log_name = argv[i];
} else {
fprintf(stderr,"Extra argument: %s\n\n",argv[i]);
usage(argv[0]);
exit(1);
}
} else {
usage(argv[0]);
exit(1);
}
}
if( !machine_name || !log_name ) {
usage(argv[0]);
exit(1);
}
Daemon *daemon;
ReliSock *sock;
if (pool) {
DCCollector col( pool );
if( ! col.addr() ) {
fprintf( stderr, "Error: %s\n", col.error() );
exit(1);
}
daemon = new Daemon( type, machine_name, col.addr() );
} else {
daemon = new Daemon( type, machine_name );
}
dprintf(D_FULLDEBUG,"Locating daemon process on %s...\n",machine_name);
if(!daemon->locate()) {
fprintf(stderr,"Couldn't locate daemon on %s: %s\n",machine_name,daemon->error());
exit(1);
}
dprintf(D_FULLDEBUG,"Daemon %s is %s\n",daemon->hostname(),daemon->addr());
sock = (ReliSock*)daemon->startCommand( DC_FETCH_LOG, Sock::reli_sock, 1200);
if(!sock) {
fprintf(stderr,"couldn't connect to daemon %s at %s\n",daemon->hostname(),daemon->addr());
return 1;
}
int commandType = DC_FETCH_LOG_TYPE_PLAIN;
if ((strcmp(log_name, "HISTORY") == 0) || (strcmp(log_name, "STARTD_HISTORY") == 0)) {
commandType = DC_FETCH_LOG_TYPE_HISTORY;
}
if ((strcmp(log_name, "STARTD.PER_JOB_HISTORY_DIR") == 0) || (strcmp(log_name, "STARTD.PER_JOB_HISTORY_DIR") == 0)) {
commandType = DC_FETCH_LOG_TYPE_HISTORY_DIR;
}
sock->put( commandType );
sock->put( log_name );
sock->end_of_message();
if (commandType == DC_FETCH_LOG_TYPE_HISTORY_DIR) {
return handleHistoryDir(sock);
}
int result = -1;
int exitcode = 1;
const char *reason=NULL;
filesize_t filesize;
sock->decode();
sock->code(result);
switch(result) {
case -1:
reason = "permission denied";
break;
case DC_FETCH_LOG_RESULT_SUCCESS:
result = sock->get_file(&filesize,1,0);
if(result>=0) {
exitcode = 0;
} else {
reason = "connection lost";
}
while (!sock->get_file(&filesize, 1, 0)) ;
break;
case DC_FETCH_LOG_RESULT_NO_NAME:
reason = "no log file by that name";
break;
case DC_FETCH_LOG_RESULT_CANT_OPEN:
reason = "server was unable to access it";
break;
case DC_FETCH_LOG_RESULT_BAD_TYPE:
reason = "server can't provide that type of log";
break;
default:
reason = "unknown error";
break;
}
if(exitcode!=0) {
fprintf(stderr,"Couldn't fetch log: %s.\n",reason);
}
return exitcode;
}
int handleHistoryDir(ReliSock *sock) {
int result = -1;
filesize_t filesize;
char *filename = 0;
sock->decode();
sock->code(result);
while (result == 1) {
int fd = -1;
filename = NULL;
sock->code(filename);
fd = safe_open_wrapper_follow(filename, O_CREAT | O_WRONLY);
if (fd < 0) {
printf("Can't open local file %s for writing\n", filename);
exit(1);
}
result = sock->get_file(&filesize,fd,0);
close(fd);
sock->code(result);
free(filename);
}
return 0;
}
<commit_msg>Check return code from sock->code() #6345<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_classad.h"
#include "condor_version.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "daemon.h"
#include "dc_collector.h"
#include "reli_sock.h"
#include "command_strings.h"
#include "condor_distribution.h"
int handleHistoryDir(ReliSock *);
void
usage( char *cmd )
{
fprintf(stderr,"Usage: %s [options] <machine-name> <subsystem>[.ext]\n",cmd);
fprintf(stderr,"Where options are:\n");
fprintf(stderr," -help Display options\n");
fprintf(stderr," -version Display Condor version\n");
fprintf(stderr," -pool <hostname> Use this central manager\n");
fprintf(stderr," -debug Show extra debugging info\n");
fprintf(stderr,"To select a particular daemon to talk to (does NOT select log file), use:\n");
fprintf(stderr," -master\n");
fprintf(stderr," -schedd\n");
fprintf(stderr," -startd\n");
fprintf(stderr," -collector\n");
fprintf(stderr," -negotiator\n");
fprintf(stderr," -kbdd\n");
fprintf(stderr," -view_collector\n");
fprintf(stderr,"The subsystem name plus optional extension specifies the log file.\n");
fprintf(stderr,"Possible subsystem names (anything with an entry XXX_LOG in remote config file):\n");
fprintf(stderr," MASTER\n");
fprintf(stderr," COLLECTOR\n");
fprintf(stderr," NEGOTIATOR\n");
fprintf(stderr," NEGOTIATOR_MATCH\n");
fprintf(stderr," SCHEDD\n");
fprintf(stderr," SHADOW\n");
fprintf(stderr," STARTD\n");
fprintf(stderr," STARTER\n");
fprintf(stderr," KBDD\n");
fprintf(stderr," HISTORY\n");
fprintf(stderr," STARTD_HISTORY\n");
fprintf(stderr,"\nExample 1: %s -debug coral STARTD\n",cmd);
fprintf(stderr,"\nExample 2: %s -debug coral STARTER.slot2\n\n",cmd);
}
void
version()
{
printf( "%s\n%s\n", CondorVersion(), CondorPlatform() );
}
int main( int argc, char *argv[] )
{
char *machine_name = 0;
char *log_name = 0;
char *pool=0;
int i;
daemon_t type = DT_MASTER;
myDistro->Init( argc, argv );
config();
for( i=1; i<argc; i++ ) {
if(!strcmp(argv[i],"-help")) {
usage(argv[0]);
exit(0);
} else if(!strcmp(argv[i],"-pool")) {
i++;
if(!argv[i]) {
fprintf(stderr,"-pool requires an argument.\n\n");
usage(argv[0]);
exit(1);
}
pool = argv[i];
} else if(!strcmp(argv[i],"-version")) {
version();
exit(0);
} else if(!strcmp(argv[i],"-debug")) {
dprintf_set_tool_debug("TOOL", 0);
} else if(argv[i][0]=='-') {
type = stringToDaemonType(&argv[i][1]);
if( type == DT_NONE || type == DT_DAGMAN) {
usage(argv[0]);
exit(1);
}
} else if(argv[i][0]!='-') {
if(!machine_name) {
machine_name = argv[i];
} else if(!log_name) {
log_name = argv[i];
} else {
fprintf(stderr,"Extra argument: %s\n\n",argv[i]);
usage(argv[0]);
exit(1);
}
} else {
usage(argv[0]);
exit(1);
}
}
if( !machine_name || !log_name ) {
usage(argv[0]);
exit(1);
}
Daemon *daemon;
ReliSock *sock;
if (pool) {
DCCollector col( pool );
if( ! col.addr() ) {
fprintf( stderr, "Error: %s\n", col.error() );
exit(1);
}
daemon = new Daemon( type, machine_name, col.addr() );
} else {
daemon = new Daemon( type, machine_name );
}
dprintf(D_FULLDEBUG,"Locating daemon process on %s...\n",machine_name);
if(!daemon->locate()) {
fprintf(stderr,"Couldn't locate daemon on %s: %s\n",machine_name,daemon->error());
exit(1);
}
dprintf(D_FULLDEBUG,"Daemon %s is %s\n",daemon->hostname(),daemon->addr());
sock = (ReliSock*)daemon->startCommand( DC_FETCH_LOG, Sock::reli_sock, 1200);
if(!sock) {
fprintf(stderr,"couldn't connect to daemon %s at %s\n",daemon->hostname(),daemon->addr());
return 1;
}
int commandType = DC_FETCH_LOG_TYPE_PLAIN;
if ((strcmp(log_name, "HISTORY") == 0) || (strcmp(log_name, "STARTD_HISTORY") == 0)) {
commandType = DC_FETCH_LOG_TYPE_HISTORY;
}
if ((strcmp(log_name, "STARTD.PER_JOB_HISTORY_DIR") == 0) || (strcmp(log_name, "STARTD.PER_JOB_HISTORY_DIR") == 0)) {
commandType = DC_FETCH_LOG_TYPE_HISTORY_DIR;
}
sock->put( commandType );
sock->put( log_name );
sock->end_of_message();
if (commandType == DC_FETCH_LOG_TYPE_HISTORY_DIR) {
return handleHistoryDir(sock);
}
int result = -1;
int exitcode = 1;
const char *reason=NULL;
filesize_t filesize;
sock->decode();
if (!sock->code(result)) {
fprintf(stderr,"Couldn't fetch log: server did not reply\n");
return -1;
}
switch(result) {
case -1:
reason = "permission denied";
break;
case DC_FETCH_LOG_RESULT_SUCCESS:
result = sock->get_file(&filesize,1,0);
if(result>=0) {
exitcode = 0;
} else {
reason = "connection lost";
}
while (!sock->get_file(&filesize, 1, 0)) ;
break;
case DC_FETCH_LOG_RESULT_NO_NAME:
reason = "no log file by that name";
break;
case DC_FETCH_LOG_RESULT_CANT_OPEN:
reason = "server was unable to access it";
break;
case DC_FETCH_LOG_RESULT_BAD_TYPE:
reason = "server can't provide that type of log";
break;
default:
reason = "unknown error";
break;
}
if(exitcode!=0) {
fprintf(stderr,"Couldn't fetch log: %s.\n",reason);
}
return exitcode;
}
int handleHistoryDir(ReliSock *sock) {
int result = -1;
filesize_t filesize;
char *filename = 0;
sock->decode();
if (!sock->code(result)) {
printf("Can't connect to server\n");
exit(1);
}
while (result == 1) {
int fd = -1;
filename = NULL;
if (!sock->code(filename)) {
printf("Can't get filename from server\n");
exit(1);
}
fd = safe_open_wrapper_follow(filename, O_CREAT | O_WRONLY);
if (fd < 0) {
printf("Can't open local file %s for writing\n", filename);
exit(1);
}
result = sock->get_file(&filesize,fd,0);
close(fd);
if (!sock->code(result)) {
printf("Cannot get result status from server\n");
result = -1;
}
free(filename);
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Aldebaran
*
* 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 "memory_list.hpp"
namespace alros {
namespace converter {
MemoryListConverter::MemoryListConverter(const std::vector<std::string>& key_list, const std::string &name, const float &frequency, const qi::SessionPtr &session):
BaseConverter(name, frequency, session),
p_memory_(session->service("ALMemory")),
_key_list(key_list)
{}
void MemoryListConverter::reset(){
}
void MemoryListConverter::callAll(const std::vector<message_actions::MessageAction> &actions){
// Get inertial data
AL::ALValue memData = p_memory_.call<AL::ALValue>("getListData", _key_list);
// Reset message
_msg = naoqi_msgs::MemoryList();
for(int i=0; i<memData.getSize(); i++){
if(memData[i].isFloat())
{
naoqi_msgs::MemoryPairFloat tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.floats.push_back(tmp_msg);
}
else if(memData[i].isString())
{
naoqi_msgs::MemoryPairString tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i].toString();
_msg.strings.push_back(tmp_msg);
}
else if(memData[i].isInt())
{
naoqi_msgs::MemoryPairInt tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.ints.push_back(tmp_msg);
}
}
for_each( message_actions::MessageAction action, actions )
{
callbacks_[action]( _msg);
}
}
void MemoryListConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
callbacks_[action] = cb;
}
}
}
<commit_msg>Accept bool ALValue (convert them in Int)<commit_after>/*
* Copyright 2015 Aldebaran
*
* 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 "memory_list.hpp"
namespace alros {
namespace converter {
MemoryListConverter::MemoryListConverter(const std::vector<std::string>& key_list, const std::string &name, const float &frequency, const qi::SessionPtr &session):
BaseConverter(name, frequency, session),
p_memory_(session->service("ALMemory")),
_key_list(key_list)
{}
void MemoryListConverter::reset(){
}
void MemoryListConverter::callAll(const std::vector<message_actions::MessageAction> &actions){
// Get inertial data
AL::ALValue memData = p_memory_.call<AL::ALValue>("getListData", _key_list);
// Reset message
_msg = naoqi_msgs::MemoryList();
for(int i=0; i<memData.getSize(); i++){
if(memData[i].isFloat())
{
naoqi_msgs::MemoryPairFloat tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.floats.push_back(tmp_msg);
}
else if(memData[i].isString())
{
naoqi_msgs::MemoryPairString tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i].toString();
_msg.strings.push_back(tmp_msg);
}
else if(memData[i].isInt())
{
naoqi_msgs::MemoryPairInt tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.ints.push_back(tmp_msg);
}
else if(memData[i].isBool())
{
naoqi_msgs::MemoryPairInt tmp_msg;
tmp_msg.memoryKey = _key_list[i];
bool value = memData[i];
tmp_msg.data = (int) value;
_msg.ints.push_back(tmp_msg);
}
}
for_each( message_actions::MessageAction action, actions )
{
callbacks_[action]( _msg);
}
}
void MemoryListConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
callbacks_[action] = cb;
}
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of the kblog library.
Copyright (c) 2006-2007 Christian Weilbach <christian_weilbach@web.de>
Copyright (c) 2007 Mike Arthur <mike@mikearthur.co.uk>
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 "blogposting.h"
#include "blogposting_p.h"
#include "blog.h"
#include <KDateTime>
#include <KUrl>
#include <kcal/journal.h>
#include <QStringList>
namespace KBlog {
BlogPosting::BlogPosting( const KBlog::BlogPosting& posting ):
d_ptr( new BlogPostingPrivate )
{
d_ptr->q_ptr=this;
d_ptr->mPrivate=posting.isPrivate();
d_ptr->mPostingId=posting.postingId();
d_ptr->mTitle=posting.title();
d_ptr->mContent=posting.content();
d_ptr->mCategories=posting.categories();
d_ptr->mError=posting.error();
d_ptr->mJournalId=posting.journalId();
d_ptr->mStatus=posting.status();
d_ptr->mCreationDateTime=posting.creationDateTime();
d_ptr->mModificationDateTime=posting.modificationDateTime();
}
BlogPosting::BlogPosting( const QString &postingId ) :
d_ptr( new BlogPostingPrivate )
{
d_ptr->q_ptr = this;
d_ptr->mPrivate = false;
d_ptr->mPostingId = postingId;
d_ptr->mStatus = New;
}
BlogPosting::BlogPosting( const KCal::Journal &journal ) :
d_ptr( new BlogPostingPrivate )
{
d_ptr->q_ptr = this;
d_ptr->mPrivate = false;
d_ptr->mPostingId = journal.customProperty( "KBLOG", "ID" );
d_ptr->mJournalId = journal.uid();
d_ptr->mStatus = New;
d_ptr->mTitle = journal.summary();
d_ptr->mContent = journal.description();
d_ptr->mCategories = journal.categories();
d_ptr->mCreationDateTime = journal.dtStart();
}
// BlogPosting::BlogPosting( const KCal::Journal &journal, BlogPostingPrivate &dd )
// : d_ptr( &dd )
// {
// d_ptr->q_ptr = this;
// d_ptr->mPrivate = false;
// d_ptr->mPostingId = journal.customProperty( "KBLOG", "ID" );
// d_ptr->mJournalId = journal.uid();
// d_ptr->mStatus = New;
// d_ptr->mTitle = journal.summary();
// d_ptr->mContent = journal.description();
// d_ptr->mCategories = journal.categories();
// d_ptr->mCreationDateTime = journal.dtStart();
// }
BlogPosting::~BlogPosting()
{
delete d_ptr;
}
KCal::Journal* BlogPosting::journal( const Blog &blog ) const
{
QString url = blog.url().url();
QString username = blog.username();
QString blogId = blog.blogId();
// Generate unique ID. Should be unique enough...
QString id = "kblog-" + url + '-' + blogId + '-' + username +
'-' + d_ptr->mPostingId;
KCal::Journal *journal = new KCal::Journal();
journal->setUid( id );
journal->setSummary( d_ptr->mTitle );
journal->setCategories( d_ptr->mCategories );
//journal->setDescription( d_ptr->mContent, true );
journal->setDtStart( d_ptr->mCreationDateTime );
journal->setCustomProperty( "KBLOG", "URL", url );
journal->setCustomProperty( "KBLOG", "USER", blog.username() );
journal->setCustomProperty( "KBLOG", "BLOG", blogId );
journal->setCustomProperty( "KBLOG", "ID", d_ptr->mPostingId );
return journal;
}
QString BlogPosting::journalId() const
{
return d_ptr->mJournalId;
}
bool BlogPosting::isPrivate() const
{
return d_ptr->mPrivate;
}
void BlogPosting::setPrivate( bool privatePosting )
{
d_ptr->mPrivate = privatePosting;
}
QString BlogPosting::postingId() const
{
return d_ptr->mPostingId;
}
void BlogPosting::setPostingId( const QString &postingId )
{
d_ptr->mPostingId = postingId;
}
QString BlogPosting::title() const
{
return d_ptr->mTitle;
}
void BlogPosting::setTitle( const QString &title )
{
d_ptr->mTitle = title;
}
QString BlogPosting::content() const
{
return d_ptr->mContent;
}
void BlogPosting::setContent( const QString &content )
{
d_ptr->mContent = content;
}
// QString BlogPosting::abbreviatedContent() const
// {
// //TODO
// return 0;
// }
//
// void BlogPosting::setAbbreviatedContent( const QString &abbreviatedContent )
// {
// Q_UNUSED( abbreviatedContent );
// //TODO
// }
KUrl BlogPosting::link() const
{
return d_ptr->mLink;
}
void BlogPosting::setLink( const KUrl &link ) const
{
d_ptr->mLink = link;
}
KUrl BlogPosting::permaLink() const
{
return d_ptr->mPermaLink;
}
void BlogPosting::setPermaLink( const KUrl &permalink ) const
{
d_ptr->mPermaLink = permalink;
}
bool BlogPosting::isCommentAllowed() const
{
return d_ptr->mCommentAllowed;
}
void BlogPosting::setCommentAllowed( bool commentAllowed )
{
d_ptr->mCommentAllowed = commentAllowed;
}
bool BlogPosting::isTrackBackAllowed() const
{
return d_ptr->mCommentAllowed;
}
void BlogPosting::setTrackBackAllowed ( bool allowTrackBacks )
{
d_ptr->mTrackBackAllowed = allowTrackBacks;
}
QString BlogPosting::summary() const
{
return d_ptr->mSummary;
}
void BlogPosting::setSummary( const QString &summary )
{
d_ptr->mSummary = summary;
}
QStringList BlogPosting::tags() const
{
return d_ptr->mTags;
}
void BlogPosting::setTags( const QStringList &tags )
{
d_ptr->mTags = tags;
}
// QList<KUrl> BlogPosting::trackBackUrls() const
// {
// //TODO
// return QList<KUrl>();
// }
//
// void BlogPosting::setTrackBackUrls( const QList<KUrl> &trackBackUrls )
// {
// Q_UNUSED( trackBackUrls );
// //TODO
// }
QString BlogPosting::mood() const
{
//TODO
return QString();
}
void BlogPosting::setMood( const QString &mood )
{
Q_UNUSED( mood );
//TODO
}
QString BlogPosting::music() const
{
//TODO
return QString();
}
void BlogPosting::setMusic( const QString &music )
{
Q_UNUSED( music );
//TODO
}
QStringList BlogPosting::categories() const
{
return d_ptr->mCategories;
}
void BlogPosting::setCategories( const QStringList &categories )
{
d_ptr->mCategories = categories;
}
KDateTime BlogPosting::creationDateTime() const
{
return d_ptr->mCreationDateTime;
}
void BlogPosting::setCreationDateTime( const KDateTime &datetime )
{
d_ptr->mCreationDateTime = datetime;
}
KDateTime BlogPosting::modificationDateTime() const
{
return d_ptr->mModificationDateTime;
}
void BlogPosting::setModificationDateTime( const KDateTime &datetime )
{
d_ptr->mModificationDateTime = datetime;
}
BlogPosting::Status BlogPosting::status() const
{
return d_ptr->mStatus;
}
void BlogPosting::setStatus( BlogPosting::Status status )
{
d_ptr->mStatus = status;
// emit statusChanged( status );
}
QString BlogPosting::error() const
{
return d_ptr->mError;
}
void BlogPosting::setError( const QString &error )
{
d_ptr->mError = error;
}
BlogPosting& BlogPosting::operator=(const BlogPosting &posting)
{
*this = BlogPosting ( posting );
return *this;
}
} // namespace KBlog
<commit_msg>I apologize, i didn't want to comment this line<commit_after>/*
This file is part of the kblog library.
Copyright (c) 2006-2007 Christian Weilbach <christian_weilbach@web.de>
Copyright (c) 2007 Mike Arthur <mike@mikearthur.co.uk>
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 "blogposting.h"
#include "blogposting_p.h"
#include "blog.h"
#include <KDateTime>
#include <KUrl>
#include <kcal/journal.h>
#include <QStringList>
namespace KBlog {
BlogPosting::BlogPosting( const KBlog::BlogPosting& posting ):
d_ptr( new BlogPostingPrivate )
{
d_ptr->q_ptr=this;
d_ptr->mPrivate=posting.isPrivate();
d_ptr->mPostingId=posting.postingId();
d_ptr->mTitle=posting.title();
d_ptr->mContent=posting.content();
d_ptr->mCategories=posting.categories();
d_ptr->mError=posting.error();
d_ptr->mJournalId=posting.journalId();
d_ptr->mStatus=posting.status();
d_ptr->mCreationDateTime=posting.creationDateTime();
d_ptr->mModificationDateTime=posting.modificationDateTime();
}
BlogPosting::BlogPosting( const QString &postingId ) :
d_ptr( new BlogPostingPrivate )
{
d_ptr->q_ptr = this;
d_ptr->mPrivate = false;
d_ptr->mPostingId = postingId;
d_ptr->mStatus = New;
}
BlogPosting::BlogPosting( const KCal::Journal &journal ) :
d_ptr( new BlogPostingPrivate )
{
d_ptr->q_ptr = this;
d_ptr->mPrivate = false;
d_ptr->mPostingId = journal.customProperty( "KBLOG", "ID" );
d_ptr->mJournalId = journal.uid();
d_ptr->mStatus = New;
d_ptr->mTitle = journal.summary();
d_ptr->mContent = journal.description();
d_ptr->mCategories = journal.categories();
d_ptr->mCreationDateTime = journal.dtStart();
}
// BlogPosting::BlogPosting( const KCal::Journal &journal, BlogPostingPrivate &dd )
// : d_ptr( &dd )
// {
// d_ptr->q_ptr = this;
// d_ptr->mPrivate = false;
// d_ptr->mPostingId = journal.customProperty( "KBLOG", "ID" );
// d_ptr->mJournalId = journal.uid();
// d_ptr->mStatus = New;
// d_ptr->mTitle = journal.summary();
// d_ptr->mContent = journal.description();
// d_ptr->mCategories = journal.categories();
// d_ptr->mCreationDateTime = journal.dtStart();
// }
BlogPosting::~BlogPosting()
{
delete d_ptr;
}
KCal::Journal* BlogPosting::journal( const Blog &blog ) const
{
QString url = blog.url().url();
QString username = blog.username();
QString blogId = blog.blogId();
// Generate unique ID. Should be unique enough...
QString id = "kblog-" + url + '-' + blogId + '-' + username +
'-' + d_ptr->mPostingId;
KCal::Journal *journal = new KCal::Journal();
journal->setUid( id );
journal->setSummary( d_ptr->mTitle );
journal->setCategories( d_ptr->mCategories );
journal->setDescription( d_ptr->mContent, true );
journal->setDtStart( d_ptr->mCreationDateTime );
journal->setCustomProperty( "KBLOG", "URL", url );
journal->setCustomProperty( "KBLOG", "USER", blog.username() );
journal->setCustomProperty( "KBLOG", "BLOG", blogId );
journal->setCustomProperty( "KBLOG", "ID", d_ptr->mPostingId );
return journal;
}
QString BlogPosting::journalId() const
{
return d_ptr->mJournalId;
}
bool BlogPosting::isPrivate() const
{
return d_ptr->mPrivate;
}
void BlogPosting::setPrivate( bool privatePosting )
{
d_ptr->mPrivate = privatePosting;
}
QString BlogPosting::postingId() const
{
return d_ptr->mPostingId;
}
void BlogPosting::setPostingId( const QString &postingId )
{
d_ptr->mPostingId = postingId;
}
QString BlogPosting::title() const
{
return d_ptr->mTitle;
}
void BlogPosting::setTitle( const QString &title )
{
d_ptr->mTitle = title;
}
QString BlogPosting::content() const
{
return d_ptr->mContent;
}
void BlogPosting::setContent( const QString &content )
{
d_ptr->mContent = content;
}
// QString BlogPosting::abbreviatedContent() const
// {
// //TODO
// return 0;
// }
//
// void BlogPosting::setAbbreviatedContent( const QString &abbreviatedContent )
// {
// Q_UNUSED( abbreviatedContent );
// //TODO
// }
KUrl BlogPosting::link() const
{
return d_ptr->mLink;
}
void BlogPosting::setLink( const KUrl &link ) const
{
d_ptr->mLink = link;
}
KUrl BlogPosting::permaLink() const
{
return d_ptr->mPermaLink;
}
void BlogPosting::setPermaLink( const KUrl &permalink ) const
{
d_ptr->mPermaLink = permalink;
}
bool BlogPosting::isCommentAllowed() const
{
return d_ptr->mCommentAllowed;
}
void BlogPosting::setCommentAllowed( bool commentAllowed )
{
d_ptr->mCommentAllowed = commentAllowed;
}
bool BlogPosting::isTrackBackAllowed() const
{
return d_ptr->mCommentAllowed;
}
void BlogPosting::setTrackBackAllowed ( bool allowTrackBacks )
{
d_ptr->mTrackBackAllowed = allowTrackBacks;
}
QString BlogPosting::summary() const
{
return d_ptr->mSummary;
}
void BlogPosting::setSummary( const QString &summary )
{
d_ptr->mSummary = summary;
}
QStringList BlogPosting::tags() const
{
return d_ptr->mTags;
}
void BlogPosting::setTags( const QStringList &tags )
{
d_ptr->mTags = tags;
}
// QList<KUrl> BlogPosting::trackBackUrls() const
// {
// //TODO
// return QList<KUrl>();
// }
//
// void BlogPosting::setTrackBackUrls( const QList<KUrl> &trackBackUrls )
// {
// Q_UNUSED( trackBackUrls );
// //TODO
// }
QString BlogPosting::mood() const
{
//TODO
return QString();
}
void BlogPosting::setMood( const QString &mood )
{
Q_UNUSED( mood );
//TODO
}
QString BlogPosting::music() const
{
//TODO
return QString();
}
void BlogPosting::setMusic( const QString &music )
{
Q_UNUSED( music );
//TODO
}
QStringList BlogPosting::categories() const
{
return d_ptr->mCategories;
}
void BlogPosting::setCategories( const QStringList &categories )
{
d_ptr->mCategories = categories;
}
KDateTime BlogPosting::creationDateTime() const
{
return d_ptr->mCreationDateTime;
}
void BlogPosting::setCreationDateTime( const KDateTime &datetime )
{
d_ptr->mCreationDateTime = datetime;
}
KDateTime BlogPosting::modificationDateTime() const
{
return d_ptr->mModificationDateTime;
}
void BlogPosting::setModificationDateTime( const KDateTime &datetime )
{
d_ptr->mModificationDateTime = datetime;
}
BlogPosting::Status BlogPosting::status() const
{
return d_ptr->mStatus;
}
void BlogPosting::setStatus( BlogPosting::Status status )
{
d_ptr->mStatus = status;
// emit statusChanged( status );
}
QString BlogPosting::error() const
{
return d_ptr->mError;
}
void BlogPosting::setError( const QString &error )
{
d_ptr->mError = error;
}
BlogPosting& BlogPosting::operator=(const BlogPosting &posting)
{
*this = BlogPosting ( posting );
return *this;
}
} // namespace KBlog
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015 gRPC authors.
*
* 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 <grpc/support/port_platform.h>
#if defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC)
#include <errno.h>
#include <time.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
#include "src/core/lib/profiling/timers.h"
#ifdef GPR_LOW_LEVEL_COUNTERS
gpr_atm gpr_mu_locks = 0;
gpr_atm gpr_counter_atm_cas = 0;
gpr_atm gpr_counter_atm_add = 0;
#endif
void gpr_mu_init(gpr_mu* mu) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_init(&mu->mutex, nullptr) == 0);
mu->leak_checker = static_cast<int*>(malloc(sizeof(*mu->leak_checker)));
GPR_ASSERT(mu->leak_checker != nullptr);
#else
GPR_ASSERT(pthread_mutex_init(mu, nullptr) == 0);
#endif
}
void gpr_mu_destroy(gpr_mu* mu) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_destroy(&mu->mutex) == 0);
free(mu->leak_checker);
#else
GPR_ASSERT(pthread_mutex_destroy(mu) == 0);
#endif
}
void gpr_mu_lock(gpr_mu* mu) {
#ifdef GPR_LOW_LEVEL_COUNTERS
GPR_ATM_INC_COUNTER(gpr_mu_locks);
#endif
GPR_TIMER_SCOPE("gpr_mu_lock", 0);
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_lock(&mu->mutex) == 0);
#else
GPR_ASSERT(pthread_mutex_lock(mu) == 0);
#endif
}
void gpr_mu_unlock(gpr_mu* mu) {
GPR_TIMER_SCOPE("gpr_mu_unlock", 0);
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_unlock(&mu->mutex) == 0);
#else
GPR_ASSERT(pthread_mutex_unlock(mu) == 0);
#endif
}
int gpr_mu_trylock(gpr_mu* mu) {
GPR_TIMER_SCOPE("gpr_mu_trylock", 0);
int err = 0;
#ifdef GRPC_ASAN_ENABLED
err = pthread_mutex_trylock(&mu->mutex);
#else
err = pthread_mutex_trylock(mu);
#endif
GPR_ASSERT(err == 0 || err == EBUSY);
return err == 0;
}
/*----------------------------------------*/
void gpr_cv_init(gpr_cv* cv) {
pthread_condattr_t attr;
GPR_ASSERT(pthread_condattr_init(&attr) == 0);
#if GPR_LINUX
GPR_ASSERT(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0);
#endif // GPR_LINUX
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_init(&cv->cond_var, &attr) == 0);
cv->leak_checker = static_cast<int*>(malloc(sizeof(*cv->leak_checker)));
GPR_ASSERT(cv->leak_checker != nullptr);
#else
GPR_ASSERT(pthread_cond_init(cv, &attr) == 0);
#endif
}
void gpr_cv_destroy(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_destroy(&cv->cond_var) == 0);
free(cv->leak_checker);
#else
GPR_ASSERT(pthread_cond_destroy(cv) == 0);
#endif
}
int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
int err = 0;
if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
0) {
#ifdef GRPC_ASAN_ENABLED
err = pthread_cond_wait(&cv->cond_var, &mu->mutex);
#else
err = pthread_cond_wait(cv, mu);
#endif
} else {
struct timespec abs_deadline_ts;
#if GPR_LINUX
abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_MONOTONIC);
#else
abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
#endif // GPR_LINUX
abs_deadline_ts.tv_sec = static_cast<time_t>(abs_deadline.tv_sec);
abs_deadline_ts.tv_nsec = abs_deadline.tv_nsec;
#ifdef GRPC_ASAN_ENABLED
err = pthread_cond_timedwait(&cv->cond_var, &mu->mutex, &abs_deadline_ts);
#else
err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts);
#endif
}
GPR_ASSERT(err == 0 || err == ETIMEDOUT || err == EAGAIN);
return err == ETIMEDOUT;
}
void gpr_cv_signal(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_signal(&cv->cond_var) == 0);
#else
GPR_ASSERT(pthread_cond_signal(cv) == 0);
#endif
}
void gpr_cv_broadcast(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_broadcast(&cv->cond_var) == 0);
#else
GPR_ASSERT(pthread_cond_broadcast(cv) == 0);
#endif
}
/*----------------------------------------*/
void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
GPR_ASSERT(pthread_once(once, init_function) == 0);
}
#endif /* defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC) */
<commit_msg>Look at now before sleeping (#28996)<commit_after>/*
*
* Copyright 2015 gRPC authors.
*
* 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 <grpc/support/port_platform.h>
#if defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC)
#include <errno.h>
#include <time.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
#include "src/core/lib/profiling/timers.h"
#ifdef GPR_LOW_LEVEL_COUNTERS
gpr_atm gpr_mu_locks = 0;
gpr_atm gpr_counter_atm_cas = 0;
gpr_atm gpr_counter_atm_add = 0;
#endif
void gpr_mu_init(gpr_mu* mu) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_init(&mu->mutex, nullptr) == 0);
mu->leak_checker = static_cast<int*>(malloc(sizeof(*mu->leak_checker)));
GPR_ASSERT(mu->leak_checker != nullptr);
#else
GPR_ASSERT(pthread_mutex_init(mu, nullptr) == 0);
#endif
}
void gpr_mu_destroy(gpr_mu* mu) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_destroy(&mu->mutex) == 0);
free(mu->leak_checker);
#else
GPR_ASSERT(pthread_mutex_destroy(mu) == 0);
#endif
}
void gpr_mu_lock(gpr_mu* mu) {
#ifdef GPR_LOW_LEVEL_COUNTERS
GPR_ATM_INC_COUNTER(gpr_mu_locks);
#endif
GPR_TIMER_SCOPE("gpr_mu_lock", 0);
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_lock(&mu->mutex) == 0);
#else
GPR_ASSERT(pthread_mutex_lock(mu) == 0);
#endif
}
void gpr_mu_unlock(gpr_mu* mu) {
GPR_TIMER_SCOPE("gpr_mu_unlock", 0);
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_mutex_unlock(&mu->mutex) == 0);
#else
GPR_ASSERT(pthread_mutex_unlock(mu) == 0);
#endif
}
int gpr_mu_trylock(gpr_mu* mu) {
GPR_TIMER_SCOPE("gpr_mu_trylock", 0);
int err = 0;
#ifdef GRPC_ASAN_ENABLED
err = pthread_mutex_trylock(&mu->mutex);
#else
err = pthread_mutex_trylock(mu);
#endif
GPR_ASSERT(err == 0 || err == EBUSY);
return err == 0;
}
/*----------------------------------------*/
void gpr_cv_init(gpr_cv* cv) {
pthread_condattr_t attr;
GPR_ASSERT(pthread_condattr_init(&attr) == 0);
#if GPR_LINUX
GPR_ASSERT(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0);
#endif // GPR_LINUX
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_init(&cv->cond_var, &attr) == 0);
cv->leak_checker = static_cast<int*>(malloc(sizeof(*cv->leak_checker)));
GPR_ASSERT(cv->leak_checker != nullptr);
#else
GPR_ASSERT(pthread_cond_init(cv, &attr) == 0);
#endif
}
void gpr_cv_destroy(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_destroy(&cv->cond_var) == 0);
free(cv->leak_checker);
#else
GPR_ASSERT(pthread_cond_destroy(cv) == 0);
#endif
}
int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
int err = 0;
if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
0) {
#ifdef GRPC_ASAN_ENABLED
err = pthread_cond_wait(&cv->cond_var, &mu->mutex);
#else
err = pthread_cond_wait(cv, mu);
#endif
} else {
struct timespec abs_deadline_ts;
#if GPR_LINUX
abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_MONOTONIC);
#else
abs_deadline = gpr_time_max(abs_deadline, gpr_now(abs_deadline.clock_type));
abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
#endif // GPR_LINUX
abs_deadline_ts.tv_sec = static_cast<time_t>(abs_deadline.tv_sec);
abs_deadline_ts.tv_nsec = abs_deadline.tv_nsec;
#ifdef GRPC_ASAN_ENABLED
err = pthread_cond_timedwait(&cv->cond_var, &mu->mutex, &abs_deadline_ts);
#else
err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts);
#endif
}
GPR_ASSERT(err == 0 || err == ETIMEDOUT || err == EAGAIN);
return err == ETIMEDOUT;
}
void gpr_cv_signal(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_signal(&cv->cond_var) == 0);
#else
GPR_ASSERT(pthread_cond_signal(cv) == 0);
#endif
}
void gpr_cv_broadcast(gpr_cv* cv) {
#ifdef GRPC_ASAN_ENABLED
GPR_ASSERT(pthread_cond_broadcast(&cv->cond_var) == 0);
#else
GPR_ASSERT(pthread_cond_broadcast(cv) == 0);
#endif
}
/*----------------------------------------*/
void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
GPR_ASSERT(pthread_once(once, init_function) == 0);
}
#endif /* defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \
!defined(GPR_CUSTOM_SYNC) */
<|endoftext|>
|
<commit_before>/*
* This file is part of crash-reporter
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Ville Ilvonen <ville.p.ilvonen@nokia.com>
* Author: Riku Halonen <riku.halonen@nokia.com>
*
* Copyright (C) 2013 Jolla Ltd.
* Contact: Jakub Adam <jakub.adam@jollamobile.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This 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 St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// User includes.
#include "creporterdaemon.h"
#include "creporterdaemon_p.h"
#include "creporterdaemonadaptor.h"
#include "creporterdaemonmonitor.h"
#include "creporternwsessionmgr.h"
#include "creportersavedstate.h"
#include "creportercoreregistry.h"
#include "creporterutils.h"
#include "creportersettingsobserver.h"
#include "creporternamespace.h"
#include "creporterprivacysettingsmodel.h"
#include "creporternotification.h"
#ifndef CREPORTER_UNIT_TEST
#include "creportersavedstate.h"
#endif
// ======== MEMBER FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterDaemon::CReporterDaemon
// ----------------------------------------------------------------------------
CReporterDaemon::CReporterDaemon() :
d_ptr(new CReporterDaemonPrivate())
{
Q_D(CReporterDaemon);
d->monitor = 0;
d->timerId = 0;
// Create registry instance preserving core locations.
d->registry = new CReporterCoreRegistry();
Q_CHECK_PTR(d->registry);
// Adaptor class is deleted automatically, when the class, it is
// attached to is deleted.
new CReporterDaemonAdaptor(this);
}
// ----------------------------------------------------------------------------
// CReporterDaemon::~CReporterDaemon
// ----------------------------------------------------------------------------
CReporterDaemon::~CReporterDaemon()
{
Q_D(CReporterDaemon);
qDebug() << __PRETTY_FUNCTION__ << "Daemon destroyed.";
if (d->monitor) {
// Delete monitor instance and stop core monitoring.
delete d->monitor;
d->monitor = 0;
}
delete d->registry;
d->registry = 0;
CReporterPrivacySettingsModel::instance()->freeSingleton();
CReporterSavedState::freeSingleton();
delete d_ptr;
d_ptr = 0;
}
// ----------------------------------------------------------------------------
// CReporterDaemon::setDelayedStartup
// ----------------------------------------------------------------------------
void CReporterDaemon::setDelayedStartup(int timeout)
{
Q_D(CReporterDaemon);
qDebug() << __PRETTY_FUNCTION__ << "Delaying startup for" << timeout / 1000 << "seconds.";
if (timeout > 0) {
d->timerId = startTimer(timeout);
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::initiateDaemon
// ----------------------------------------------------------------------------
bool CReporterDaemon::initiateDaemon()
{
qDebug() << __PRETTY_FUNCTION__ << "Starting daemon...";
if (!CReporterPrivacySettingsModel::instance()->isValid())
{
qWarning() << __PRETTY_FUNCTION__ << "Invalid settings";
// Exit, if settings are missing.
return false;
}
QString filename = CReporterPrivacySettingsModel::instance()->settingsFile();
if (!startService())
{
return false;
}
if (CReporterPrivacySettingsModel::instance()->notificationsEnabled()
|| CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())
{
// Read from settings file, if monitor should be started.
startCoreMonitoring();
}
// Create observer to monitor changes in settings.
CReporterSettingsObserver *settingsObserver =
new CReporterSettingsObserver(filename, this);
settingsObserver->addWatcher(Settings::ValueNotifications);
settingsObserver->addWatcher(Settings::ValueAutomaticSending);
settingsObserver->addWatcher(Settings::ValueAutoDeleteDuplicates);
connect(settingsObserver, SIGNAL(valueChanged(QString,QVariant)),
this, SLOT(settingValueChanged(QString,QVariant)));
#ifndef CREPORTER_UNIT_TEST
// Each time daemon is started, we count successful core uploads from zero.
CReporterSavedState *state = CReporterSavedState::instance();
state->setUploadSuccessCount(0);
state->writeSettings();
#endif
if (CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())
{
QStringList files = collectAllCoreFiles();
if (!files.isEmpty() &&
CReporterNwSessionMgr::unpaidConnectionAvailable() &&
!CReporterUtils::notifyAutoUploader(files))
{
qDebug() << __PRETTY_FUNCTION__ << "Failed to add files to the queue.";
}
}
else if (CReporterPrivacySettingsModel::instance()->notificationsEnabled())
{
QStringList files = collectAllCoreFiles();
if (!files.isEmpty()) {
CReporterNotification *notification = new CReporterNotification(
CReporter::ApplicationNotificationEventType,
//% "This system has stored crash reports."
qtTrId("crash_reporter-notify-has_stored_cores"),
QString(), this);
connect(notification, &CReporterNotification::timeouted,
notification, &CReporterNotification::deleteLater);
}
}
return true;
}
// ----------------------------------------------------------------------------
// CReporterDaemon::startCoreMonitoring
// ----------------------------------------------------------------------------
void CReporterDaemon::startCoreMonitoring(const bool fromDBus)
{
Q_D(CReporterDaemon);
qDebug() << __PRETTY_FUNCTION__ << "Core monitoring requested. Called from DBus ="
<< fromDBus;
if (!d->monitor) {
// Create monitor instance and start monitoring cores.
d->monitor = new CReporterDaemonMonitor(d->registry);
Q_CHECK_PTR(d->monitor);
connect(d->monitor, SIGNAL(richCoreNotify(QString)), SLOT(newCoreDump(QString)));
qDebug() << __PRETTY_FUNCTION__ << "Core monitoring started.";
if (fromDBus) {
CReporterPrivacySettingsModel::instance()->setNotificationsEnabled(true);
CReporterPrivacySettingsModel::instance()->writeSettings();
}
d->monitor->setAutoDelete(CReporterPrivacySettingsModel::instance()->autoDeleteDuplicates());
d->monitor->setAutoDeleteMaxSimilarCores(
CReporterPrivacySettingsModel::instance()->autoDeleteMaxSimilarCores());
d->monitor->setAutoUpload(CReporterPrivacySettingsModel::instance()->automaticSendingEnabled());
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::stopCoreMonitoring
// ----------------------------------------------------------------------------
void CReporterDaemon::stopCoreMonitoring(const bool fromDBus)
{
Q_D(CReporterDaemon);
if (d->monitor) {
// Delete monitor instance and stop core monitoring.
delete d->monitor;
d->monitor = 0;
qDebug() << __PRETTY_FUNCTION__ << "Core monitoring stopped.";
if (fromDBus) {
CReporterPrivacySettingsModel::instance()->setNotificationsEnabled(false);
CReporterPrivacySettingsModel::instance()->writeSettings();
}
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::collectAllCoreFiles
// ----------------------------------------------------------------------------
QStringList CReporterDaemon::collectAllCoreFiles()
{
Q_D(CReporterDaemon);
return d->registry->collectAllCoreFiles();
}
// ======== LOCAL FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterDaemon::settingValueChanged
// ----------------------------------------------------------------------------
void CReporterDaemon::settingValueChanged(const QString &key, const QVariant &value)
{
qDebug() << __PRETTY_FUNCTION__ << "Setting:" << key << "has changed; value:" << value;
if (key == Settings::ValueNotifications || key == Settings::ValueAutomaticSending)
{
if (value.toBool())
{
startCoreMonitoring();
}
else if (!CReporterPrivacySettingsModel::instance()->notificationsEnabled()
&& !CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())
{
if (key == Settings::ValueAutomaticSending)
{
if (d_ptr->monitor)
{
d_ptr->monitor->setAutoUpload(value.toBool());
}
}
stopCoreMonitoring();
}
}
else if (key == Settings::ValueAutoDeleteDuplicates)
{
if (d_ptr->monitor)
{
d_ptr->monitor->setAutoDelete(value.toBool());
}
}
if (key == Settings::ValueAutomaticSending)
{
if (d_ptr->monitor)
{
d_ptr->monitor->setAutoUpload(value.toBool());
}
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::timerEvent
// ----------------------------------------------------------------------------
void CReporterDaemon::timerEvent(QTimerEvent *event)
{
Q_D(CReporterDaemon);
qDebug() << __PRETTY_FUNCTION__ << "Startup timer elapsed -> start now.";
if (event->timerId() != d->timerId) return;
// Kill timer and initiate daemon.
killTimer(d->timerId);
d->timerId = 0;
if (!initiateDaemon()) {
// If D-Bus registration fails, quit application.
qApp->quit();
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::startService
// ----------------------------------------------------------------------------
bool CReporterDaemon::startService()
{
qDebug() << __PRETTY_FUNCTION__ << "Starting D-Bus service...";
if (!QDBusConnection::sessionBus().isConnected()) {
qWarning() << __PRETTY_FUNCTION__ << "D-Bus not running?";
return false;
}
if (!QDBusConnection::sessionBus().registerService(CReporter::DaemonServiceName)) {
qWarning() << __PRETTY_FUNCTION__
<< "Failed to register service, daemon already running?";
return false;
}
qDebug() << __PRETTY_FUNCTION__ << "Service:"
<< CReporter::DaemonServiceName << "registered.";
QDBusConnection::sessionBus().registerObject(CReporter::DaemonObjectPath, this);
qDebug() << __PRETTY_FUNCTION__ << "Object:"
<< CReporter::DaemonObjectPath << "registered.";
// Good to go.
qDebug() << __PRETTY_FUNCTION__ << "D-Bus service started.";
return true;
}
// ----------------------------------------------------------------------------
// CReporterDaemon::stopService
// ----------------------------------------------------------------------------
void CReporterDaemon::stopService()
{
qDebug() << __PRETTY_FUNCTION__ << "Stopping D-Bus service...";
QDBusConnection::sessionBus().unregisterObject(CReporter::DaemonObjectPath);
QDBusConnection::sessionBus().unregisterService(CReporter::DaemonServiceName);
}
// End of file
<commit_msg>[daemon] removed superfluous QObject::connect()<commit_after>/*
* This file is part of crash-reporter
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Ville Ilvonen <ville.p.ilvonen@nokia.com>
* Author: Riku Halonen <riku.halonen@nokia.com>
*
* Copyright (C) 2013 Jolla Ltd.
* Contact: Jakub Adam <jakub.adam@jollamobile.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This 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 St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// User includes.
#include "creporterdaemon.h"
#include "creporterdaemon_p.h"
#include "creporterdaemonadaptor.h"
#include "creporterdaemonmonitor.h"
#include "creporternwsessionmgr.h"
#include "creportersavedstate.h"
#include "creportercoreregistry.h"
#include "creporterutils.h"
#include "creportersettingsobserver.h"
#include "creporternamespace.h"
#include "creporterprivacysettingsmodel.h"
#include "creporternotification.h"
#ifndef CREPORTER_UNIT_TEST
#include "creportersavedstate.h"
#endif
// ======== MEMBER FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterDaemon::CReporterDaemon
// ----------------------------------------------------------------------------
CReporterDaemon::CReporterDaemon() :
d_ptr(new CReporterDaemonPrivate())
{
Q_D(CReporterDaemon);
d->monitor = 0;
d->timerId = 0;
// Create registry instance preserving core locations.
d->registry = new CReporterCoreRegistry();
Q_CHECK_PTR(d->registry);
// Adaptor class is deleted automatically, when the class, it is
// attached to is deleted.
new CReporterDaemonAdaptor(this);
}
// ----------------------------------------------------------------------------
// CReporterDaemon::~CReporterDaemon
// ----------------------------------------------------------------------------
CReporterDaemon::~CReporterDaemon()
{
Q_D(CReporterDaemon);
qDebug() << __PRETTY_FUNCTION__ << "Daemon destroyed.";
if (d->monitor) {
// Delete monitor instance and stop core monitoring.
delete d->monitor;
d->monitor = 0;
}
delete d->registry;
d->registry = 0;
CReporterPrivacySettingsModel::instance()->freeSingleton();
CReporterSavedState::freeSingleton();
delete d_ptr;
d_ptr = 0;
}
// ----------------------------------------------------------------------------
// CReporterDaemon::setDelayedStartup
// ----------------------------------------------------------------------------
void CReporterDaemon::setDelayedStartup(int timeout)
{
Q_D(CReporterDaemon);
qDebug() << __PRETTY_FUNCTION__ << "Delaying startup for" << timeout / 1000 << "seconds.";
if (timeout > 0) {
d->timerId = startTimer(timeout);
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::initiateDaemon
// ----------------------------------------------------------------------------
bool CReporterDaemon::initiateDaemon()
{
qDebug() << __PRETTY_FUNCTION__ << "Starting daemon...";
if (!CReporterPrivacySettingsModel::instance()->isValid())
{
qWarning() << __PRETTY_FUNCTION__ << "Invalid settings";
// Exit, if settings are missing.
return false;
}
QString filename = CReporterPrivacySettingsModel::instance()->settingsFile();
if (!startService())
{
return false;
}
if (CReporterPrivacySettingsModel::instance()->notificationsEnabled()
|| CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())
{
// Read from settings file, if monitor should be started.
startCoreMonitoring();
}
// Create observer to monitor changes in settings.
CReporterSettingsObserver *settingsObserver =
new CReporterSettingsObserver(filename, this);
settingsObserver->addWatcher(Settings::ValueNotifications);
settingsObserver->addWatcher(Settings::ValueAutomaticSending);
settingsObserver->addWatcher(Settings::ValueAutoDeleteDuplicates);
connect(settingsObserver, SIGNAL(valueChanged(QString,QVariant)),
this, SLOT(settingValueChanged(QString,QVariant)));
#ifndef CREPORTER_UNIT_TEST
// Each time daemon is started, we count successful core uploads from zero.
CReporterSavedState *state = CReporterSavedState::instance();
state->setUploadSuccessCount(0);
state->writeSettings();
#endif
if (CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())
{
QStringList files = collectAllCoreFiles();
if (!files.isEmpty() &&
CReporterNwSessionMgr::unpaidConnectionAvailable() &&
!CReporterUtils::notifyAutoUploader(files))
{
qDebug() << __PRETTY_FUNCTION__ << "Failed to add files to the queue.";
}
}
else if (CReporterPrivacySettingsModel::instance()->notificationsEnabled())
{
QStringList files = collectAllCoreFiles();
if (!files.isEmpty()) {
CReporterNotification *notification = new CReporterNotification(
CReporter::ApplicationNotificationEventType,
//% "This system has stored crash reports."
qtTrId("crash_reporter-notify-has_stored_cores"),
QString(), this);
connect(notification, &CReporterNotification::timeouted,
notification, &CReporterNotification::deleteLater);
}
}
return true;
}
// ----------------------------------------------------------------------------
// CReporterDaemon::startCoreMonitoring
// ----------------------------------------------------------------------------
void CReporterDaemon::startCoreMonitoring(const bool fromDBus)
{
Q_D(CReporterDaemon);
qDebug() << __PRETTY_FUNCTION__ << "Core monitoring requested. Called from DBus ="
<< fromDBus;
if (!d->monitor) {
// Create monitor instance and start monitoring cores.
d->monitor = new CReporterDaemonMonitor(d->registry);
Q_CHECK_PTR(d->monitor);
qDebug() << __PRETTY_FUNCTION__ << "Core monitoring started.";
if (fromDBus) {
CReporterPrivacySettingsModel::instance()->setNotificationsEnabled(true);
CReporterPrivacySettingsModel::instance()->writeSettings();
}
d->monitor->setAutoDelete(CReporterPrivacySettingsModel::instance()->autoDeleteDuplicates());
d->monitor->setAutoDeleteMaxSimilarCores(
CReporterPrivacySettingsModel::instance()->autoDeleteMaxSimilarCores());
d->monitor->setAutoUpload(CReporterPrivacySettingsModel::instance()->automaticSendingEnabled());
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::stopCoreMonitoring
// ----------------------------------------------------------------------------
void CReporterDaemon::stopCoreMonitoring(const bool fromDBus)
{
Q_D(CReporterDaemon);
if (d->monitor) {
// Delete monitor instance and stop core monitoring.
delete d->monitor;
d->monitor = 0;
qDebug() << __PRETTY_FUNCTION__ << "Core monitoring stopped.";
if (fromDBus) {
CReporterPrivacySettingsModel::instance()->setNotificationsEnabled(false);
CReporterPrivacySettingsModel::instance()->writeSettings();
}
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::collectAllCoreFiles
// ----------------------------------------------------------------------------
QStringList CReporterDaemon::collectAllCoreFiles()
{
Q_D(CReporterDaemon);
return d->registry->collectAllCoreFiles();
}
// ======== LOCAL FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterDaemon::settingValueChanged
// ----------------------------------------------------------------------------
void CReporterDaemon::settingValueChanged(const QString &key, const QVariant &value)
{
qDebug() << __PRETTY_FUNCTION__ << "Setting:" << key << "has changed; value:" << value;
if (key == Settings::ValueNotifications || key == Settings::ValueAutomaticSending)
{
if (value.toBool())
{
startCoreMonitoring();
}
else if (!CReporterPrivacySettingsModel::instance()->notificationsEnabled()
&& !CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())
{
if (key == Settings::ValueAutomaticSending)
{
if (d_ptr->monitor)
{
d_ptr->monitor->setAutoUpload(value.toBool());
}
}
stopCoreMonitoring();
}
}
else if (key == Settings::ValueAutoDeleteDuplicates)
{
if (d_ptr->monitor)
{
d_ptr->monitor->setAutoDelete(value.toBool());
}
}
if (key == Settings::ValueAutomaticSending)
{
if (d_ptr->monitor)
{
d_ptr->monitor->setAutoUpload(value.toBool());
}
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::timerEvent
// ----------------------------------------------------------------------------
void CReporterDaemon::timerEvent(QTimerEvent *event)
{
Q_D(CReporterDaemon);
qDebug() << __PRETTY_FUNCTION__ << "Startup timer elapsed -> start now.";
if (event->timerId() != d->timerId) return;
// Kill timer and initiate daemon.
killTimer(d->timerId);
d->timerId = 0;
if (!initiateDaemon()) {
// If D-Bus registration fails, quit application.
qApp->quit();
}
}
// ----------------------------------------------------------------------------
// CReporterDaemon::startService
// ----------------------------------------------------------------------------
bool CReporterDaemon::startService()
{
qDebug() << __PRETTY_FUNCTION__ << "Starting D-Bus service...";
if (!QDBusConnection::sessionBus().isConnected()) {
qWarning() << __PRETTY_FUNCTION__ << "D-Bus not running?";
return false;
}
if (!QDBusConnection::sessionBus().registerService(CReporter::DaemonServiceName)) {
qWarning() << __PRETTY_FUNCTION__
<< "Failed to register service, daemon already running?";
return false;
}
qDebug() << __PRETTY_FUNCTION__ << "Service:"
<< CReporter::DaemonServiceName << "registered.";
QDBusConnection::sessionBus().registerObject(CReporter::DaemonObjectPath, this);
qDebug() << __PRETTY_FUNCTION__ << "Object:"
<< CReporter::DaemonObjectPath << "registered.";
// Good to go.
qDebug() << __PRETTY_FUNCTION__ << "D-Bus service started.";
return true;
}
// ----------------------------------------------------------------------------
// CReporterDaemon::stopService
// ----------------------------------------------------------------------------
void CReporterDaemon::stopService()
{
qDebug() << __PRETTY_FUNCTION__ << "Stopping D-Bus service...";
QDBusConnection::sessionBus().unregisterObject(CReporter::DaemonObjectPath);
QDBusConnection::sessionBus().unregisterService(CReporter::DaemonServiceName);
}
// End of file
<|endoftext|>
|
<commit_before>
#include <signal.h>
#include "backend/common/message_queue.h"
#include "backend/common/logger.h"
#define NOTIFY_SIG SIGUSR1
namespace peloton {
void notify_message(mqd_t *mqdp);
std::string get_mq_name(oid_t id) {
return std::string("/backend_" + std::to_string(id));
}
mqd_t create_mq(const std::string queue_name) {
mqd_t mqd = mq_open(queue_name.c_str(),
O_CREAT | O_RDONLY | O_NONBLOCK,
S_IRUSR | S_IWUSR,
NULL);
if (mqd == (mqd_t) -1) {
LOG_ERROR("mq_open during create : %s pid : %d \n",
queue_name.c_str(), getpid());
return mqd;
}
LOG_TRACE("CREATED QUEUE :: %s getpid : %d \n",
queue_name.c_str(), getpid());
return mqd;
}
mqd_t open_mq(const std::string queue_name) {
int flags;
flags = O_WRONLY | O_NONBLOCK;
mqd_t mqd = mq_open(queue_name.c_str(), flags);
if (mqd == (mqd_t) -1) {
perror("mq_open during open");
}
return mqd;
}
void send_message(mqd_t mqd, const std::string message) {
int prio = 0;
LOG_TRACE("TRYING TO SEND MESSAGE :: %s \n", message.c_str());
if (mq_send(mqd, message.c_str(), message.size(), prio) == -1) {
perror("mq_send");
}
LOG_TRACE("SENT MESSAGE \n");
}
static void
handler(int sig)
{
/* Just interrupt sigsuspend() */
}
void receive_message(mqd_t *mqdp) {
ssize_t numRead;
void *buffer;
struct mq_attr attr;
LOG_TRACE("HANDLER START :: pid : %d \n", getpid());
// Determine mq_msgsize for message queue, and allocate space
if (mq_getattr(*mqdp, &attr) == -1)
perror("mq_getattr");
buffer = malloc(attr.mq_msgsize);
if (buffer == NULL)
perror("malloc");
while ((numRead = mq_receive(*mqdp, (char *) buffer, attr.mq_msgsize, NULL)) >= 0)
LOG_TRACE("Read %ld bytes\n", (long) numRead);
if (errno != EAGAIN) /* Unexpected error */
perror("mq_receive");
free(buffer);
LOG_TRACE("HANDLER DONE \n");
}
void notify_message(mqd_t *mqdp)
{
struct sigevent sev;
sigset_t blockMask;
struct sigaction sa;
LOG_TRACE("SETUP NOTIFY \n");
/* Block the notification signal and establish a handler for it */
sigemptyset(&blockMask);
sigaddset(&blockMask, NOTIFY_SIG);
if (sigprocmask(SIG_BLOCK, &blockMask, NULL) == -1)
perror("sigprocmask");
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
if (sigaction(NOTIFY_SIG, &sa, NULL) == -1)
perror("sigaction");
/* Register for message notification via a signal */
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = NOTIFY_SIG;
if (mq_notify(*mqdp, &sev) == -1)
perror("mq_notify");
LOG_TRACE("FINISHED SETUP NOTIFY \n");
}
void wait_for_message(mqd_t *mqdp) {
sigset_t emptyMask;
notify_message(mqdp);
LOG_TRACE("GOING TO SUSPEND :: pid : %d \n", getpid());
sigemptyset(&emptyMask);
sigsuspend(&emptyMask); /* Wait for notification signal */
LOG_TRACE("WOKE UP :: pid : %d \n", getpid());
receive_message(mqdp);
LOG_TRACE("FINISH PAUSE \n");
}
} // End peloton namespace
<commit_msg>Clean up some stuff.<commit_after>
#include <signal.h>
#include "backend/common/message_queue.h"
#include "backend/common/logger.h"
#define NOTIFY_SIG SIGUSR1
namespace peloton {
void notify_message(mqd_t *mqdp);
std::string get_mq_name(oid_t id) {
return std::string("/backend_" + std::to_string(id));
}
mqd_t create_mq(const std::string queue_name) {
mqd_t mqd = mq_open(queue_name.c_str(),
O_CREAT | O_RDONLY | O_NONBLOCK,
S_IRUSR | S_IWUSR,
NULL);
if (mqd == (mqd_t) -1) {
LOG_ERROR("mq_open during create : %s pid : %d \n",
queue_name.c_str(), getpid());
return mqd;
}
LOG_TRACE("CREATED QUEUE :: %s getpid : %d \n",
queue_name.c_str(), getpid());
return mqd;
}
mqd_t open_mq(const std::string queue_name) {
int flags;
flags = O_WRONLY | O_NONBLOCK;
mqd_t mqd = mq_open(queue_name.c_str(), flags);
if (mqd == (mqd_t) -1) {
perror("mq_open during open");
}
return mqd;
}
void send_message(mqd_t mqd, const std::string message) {
int prio = 0;
LOG_TRACE("TRYING TO SEND MESSAGE :: %s \n", message.c_str());
if (mq_send(mqd, message.c_str(), message.size(), prio) == -1) {
perror("mq_send");
}
LOG_TRACE("SENT MESSAGE \n");
}
static void
handler(int sig)
{
// Just interrupt sigsuspend()
}
void receive_message(mqd_t *mqdp) {
ssize_t chars_read;
void *buffer;
struct mq_attr attr;
LOG_TRACE("HANDLER :: pid : %d \n", getpid());
// Determine mq_msgsize for message queue, and allocate space
if (mq_getattr(*mqdp, &attr) == -1)
perror("mq_getattr");
buffer = malloc(attr.mq_msgsize);
if (buffer == NULL)
perror("malloc");
while ((chars_read = mq_receive(*mqdp, (char *) buffer, attr.mq_msgsize, NULL)) >= 0)
LOG_TRACE("Read %ld bytes\n", (long) chars_read);
if (errno != EAGAIN) // Unexpected error
perror("mq_receive");
free(buffer);
}
void notify_message(mqd_t *mqdp)
{
struct sigevent sev;
sigset_t blockMask;
struct sigaction sa;
LOG_TRACE("SETUP NOTIFY \n");
// Block the notification signal and establish a handler for it
sigemptyset(&blockMask);
sigaddset(&blockMask, NOTIFY_SIG);
if (sigprocmask(SIG_BLOCK, &blockMask, NULL) == -1)
perror("sigprocmask");
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
if (sigaction(NOTIFY_SIG, &sa, NULL) == -1)
perror("sigaction");
// Register for message notification via a signal
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = NOTIFY_SIG;
if (mq_notify(*mqdp, &sev) == -1)
perror("mq_notify");
}
void wait_for_message(mqd_t *mqdp) {
sigset_t emptyMask;
notify_message(mqdp);
LOG_TRACE("SUSPENDING :: pid : %d \n", getpid());
sigemptyset(&emptyMask);
sigsuspend(&emptyMask); // Wait for notification signal
LOG_TRACE("WOKE UP :: pid : %d \n", getpid());
receive_message(mqdp);
}
} // End peloton namespace
<|endoftext|>
|
<commit_before>#include "cdriver.h"
struct Apex {
double axis_min, axis_max; // Limits for the movement of this axis.
double rodlength, radius; // Length of the tie rod and the horizontal distance between the vertical position and the zero position.
double x, y, z; // Position of tower on the base plane, and the carriage height at zero position.
};
struct Delta_private {
Apex apex[3];
double angle; // Adjust the front of the printer.
};
#define PRIVATE(s) (*reinterpret_cast <Delta_private *>(s->type_data))
#define APEX(s, a) (PRIVATE(s).apex[a])
static bool check_delta(Space *s, uint8_t a, double *target) { // {{{
double dx = target[0] - APEX(s, a).x;
double dy = target[1] - APEX(s, a).y;
double r2 = dx * dx + dy * dy;
double amax = APEX(s, a).axis_max < APEX(s, a).rodlength ? APEX(s, a).axis_max : APEX(s, a).rodlength;
if (r2 > amax * amax) {
debug ("not ok 1: %f %f %f %f %f %f %f", target[0], target[1], dx, dy, r2, APEX(s, a).rodlength, APEX(s, a).axis_max);
// target is too far away from axis. Pull it towards axis so that it is on the edge.
// target = axis + (target - axis) * (l - epsilon) / r.
double factor(amax / sqrt(r2));
target[0] = APEX(s, a).x + (target[0] - APEX(s, a).x) * factor;
target[1] = APEX(s, a).y + (target[1] - APEX(s, a).y) * factor;
return false;
}
// Inner product shows if projection is inside or outside the printable region.
double projection = -(dx / APEX(s, a).radius * APEX(s, a).x + dy / APEX(s, a).radius * APEX(s, a).y);
double amin = APEX(s, a).axis_min < -APEX(s, a).rodlength ? -APEX(s, a).rodlength : APEX(s, a).axis_min;
if (projection < amin) {
debug ("not ok 2: %f %f %f %f %f", projection, dx, dy, APEX(s, a).x, APEX(s, a).y);
// target is on the wrong side of axis. Pull it towards plane so it is on the edge.
target[0] -= ((amin - projection) / APEX(s, a).radius - .001) * APEX(s, a).x;
target[1] -= ((amin - projection) / APEX(s, a).radius - .001) * APEX(s, a).y;
// Assume this was a small correction; that way, things will work even if numerical errors cause this to be called for the real move.
return false;
}
//debug("ok %d %d %f", s->id, a, projection);
return true;
} // }}}
static inline double delta_to_axis(Space *s, uint8_t a, bool *ok) {
double dx = s->axis[0]->settings.target - APEX(s, a).x;
double dy = s->axis[1]->settings.target - APEX(s, a).y;
double dz = s->axis[2]->settings.target - APEX(s, a).z;
double r2 = dx * dx + dy * dy;
double l2 = APEX(s, a).rodlength * APEX(s, a).rodlength;
double dest = sqrt(l2 - r2) + dz;
//debug("dta dx %f dy %f dz %f z %f, r %f target %f", dx, dy, dz, APEX(s, a).z, r, target);
return dest;
}
static void xyz2motors(Space *s, double *motors, bool *ok) {
if (isnan(s->axis[0]->settings.target) || isnan(s->axis[1]->settings.target) || isnan(s->axis[2]->settings.target)) {
// Fill up missing targets.
for (uint8_t aa = 0; aa < 3; ++aa) {
if (isnan(s->axis[aa]->settings.target))
s->axis[aa]->settings.target = s->axis[aa]->settings.current;
}
}
for (uint8_t a = 0; a < 3; ++a) {
if (motors)
motors[a] = delta_to_axis(s, a, ok);
else
s->motor[a]->settings.endpos = delta_to_axis(s, a, ok);
}
}
static void reset_pos (Space *s) {
// All axes' current_pos must be valid and equal, in other words, x=y=0.
double p[3];
for (uint8_t i = 0; i < 3; ++i)
p[i] = s->motor[i]->settings.current_pos / s->motor[i]->steps_per_unit;
if (p[0] != p[1] || p[0] != p[2]) {
//debug("resetpos fails");
s->axis[0]->settings.source = NAN;
s->axis[1]->settings.source = NAN;
s->axis[2]->settings.source = NAN;
}
else {
//debug("resetpos %f", p[0]);
s->axis[0]->settings.source = 0;
s->axis[1]->settings.source = 0;
s->axis[2]->settings.source = p[0];
}
}
static void check_position(Space *s, double *data) {
if (isnan(data[0]) || isnan(data[1])) {
// Cannot check; assume it's ok.
return;
}
for (uint8_t counter = 0; counter < 2; ++counter) {
bool ok = true;
for (uint8_t a = 0; a < s->num_axes; ++a)
ok &= check_delta(s, a, data);
if (ok)
break;
}
}
static void load(Space *s, uint8_t old_type, int32_t &addr) {
if (!s->setup_nums(3, 3)) {
debug("Failed to set up delta axes");
s->cancel_update();
return;
}
for (uint8_t a = 0; a < 3; ++a) {
APEX(s, a).axis_min = read_float(addr);
APEX(s, a).axis_max = read_float(addr);
APEX(s, a).rodlength = read_float(addr);
APEX(s, a).radius = read_float(addr);
}
PRIVATE(s).angle = read_float(addr);
if (isinf(PRIVATE(s).angle) || isnan(PRIVATE(s).angle))
PRIVATE(s).angle = 0;
#define sin210 -.5
#define cos210 -0.8660254037844386 // .5*sqrt(3)
#define sin330 -.5
#define cos330 0.8660254037844386 // .5*sqrt(3)
#define sin90 1
// Coordinates of axes (at angles 210, 330, 90; each with its own radius).
double x[3], y[3];
x[0] = APEX(s, 0).radius * cos210;
y[0] = APEX(s, 0).radius * sin210;
x[1] = APEX(s, 1).radius * cos330;
y[1] = APEX(s, 1).radius * sin330;
x[2] = 0;
y[2] = APEX(s, 2).radius * sin90;
for (uint8_t a = 0; a < 3; ++a) {
APEX(s, a).x = x[a] * cos(PRIVATE(s).angle) - y[a] * sin(PRIVATE(s).angle);
APEX(s, a).y = y[a] * cos(PRIVATE(s).angle) + x[a] * sin(PRIVATE(s).angle);
APEX(s, a).z = sqrt(APEX(s, a).rodlength * APEX(s, a).rodlength - APEX(s, a).radius * APEX(s, a).radius);
}
}
static void save(Space *s, int32_t &addr) {
for (uint8_t a = 0; a < 3; ++a) {
write_float(addr, APEX(s, a).axis_min);
write_float(addr, APEX(s, a).axis_max);
write_float(addr, APEX(s, a).rodlength);
write_float(addr, APEX(s, a).radius);
}
write_float(addr, PRIVATE(s).angle);
}
static bool init(Space *s) {
s->type_data = new Delta_private;
if (!s->type_data)
return false;
return true;
}
static void free(Space *s) {
delete reinterpret_cast <Delta_private *>(s->type_data);
}
static void afree(Space *s, int a) {
}
static double change0(Space *s, int axis, double value) {
return value;
}
static double unchange0(Space *s, int axis, double value) {
return value;
}
static double probe_speed(Space *s) {
double max_spu = 0;
for (int i = 0; i < s->num_motors; ++i)
if (max_spu < s->motor[i]->steps_per_unit)
max_spu = s->motor[i]->steps_per_unit;
return 1e6 / hwtime_step / max_spu;
}
void Delta_init(int num) {
space_types[num].xyz2motors = xyz2motors;
space_types[num].reset_pos = reset_pos;
space_types[num].check_position = check_position;
space_types[num].load = load;
space_types[num].save = save;
space_types[num].init = init;
space_types[num].free = free;
space_types[num].afree = afree;
space_types[num].change0 = change0;
space_types[num].unchange0 = unchange0;
space_types[num].probe_speed = probe_speed;
}
<commit_msg>fix check_position for single axis moves<commit_after>#include "cdriver.h"
struct Apex {
double axis_min, axis_max; // Limits for the movement of this axis.
double rodlength, radius; // Length of the tie rod and the horizontal distance between the vertical position and the zero position.
double x, y, z; // Position of tower on the base plane, and the carriage height at zero position.
};
struct Delta_private {
Apex apex[3];
double angle; // Adjust the front of the printer.
};
#define PRIVATE(s) (*reinterpret_cast <Delta_private *>(s->type_data))
#define APEX(s, a) (PRIVATE(s).apex[a])
static bool check_delta(Space *s, uint8_t a, double *target) { // {{{
double dx = target[0] - APEX(s, a).x;
double dy = target[1] - APEX(s, a).y;
double r2 = dx * dx + dy * dy;
double amax = APEX(s, a).axis_max < APEX(s, a).rodlength ? APEX(s, a).axis_max : APEX(s, a).rodlength;
if (r2 > amax * amax) {
debug ("not ok 1: %f %f %f %f %f %f %f", target[0], target[1], dx, dy, r2, APEX(s, a).rodlength, APEX(s, a).axis_max);
// target is too far away from axis. Pull it towards axis so that it is on the edge.
// target = axis + (target - axis) * (l - epsilon) / r.
double factor(amax / sqrt(r2));
target[0] = APEX(s, a).x + (target[0] - APEX(s, a).x) * factor;
target[1] = APEX(s, a).y + (target[1] - APEX(s, a).y) * factor;
return false;
}
// Inner product shows if projection is inside or outside the printable region.
double projection = -(dx / APEX(s, a).radius * APEX(s, a).x + dy / APEX(s, a).radius * APEX(s, a).y);
double amin = APEX(s, a).axis_min < -APEX(s, a).rodlength ? -APEX(s, a).rodlength : APEX(s, a).axis_min;
if (projection < amin) {
debug ("not ok 2: %f %f %f %f %f", projection, dx, dy, APEX(s, a).x, APEX(s, a).y);
// target is on the wrong side of axis. Pull it towards plane so it is on the edge.
target[0] -= ((amin - projection) / APEX(s, a).radius - .001) * APEX(s, a).x;
target[1] -= ((amin - projection) / APEX(s, a).radius - .001) * APEX(s, a).y;
// Assume this was a small correction; that way, things will work even if numerical errors cause this to be called for the real move.
return false;
}
//debug("ok %d %d %f", s->id, a, projection);
return true;
} // }}}
static inline double delta_to_axis(Space *s, uint8_t a, bool *ok) {
double dx = s->axis[0]->settings.target - APEX(s, a).x;
double dy = s->axis[1]->settings.target - APEX(s, a).y;
double dz = s->axis[2]->settings.target - APEX(s, a).z;
double r2 = dx * dx + dy * dy;
double l2 = APEX(s, a).rodlength * APEX(s, a).rodlength;
double dest = sqrt(l2 - r2) + dz;
//debug("dta dx %f dy %f dz %f z %f, r %f target %f", dx, dy, dz, APEX(s, a).z, r, target);
return dest;
}
static void xyz2motors(Space *s, double *motors, bool *ok) {
if (isnan(s->axis[0]->settings.target) || isnan(s->axis[1]->settings.target) || isnan(s->axis[2]->settings.target)) {
// Fill up missing targets.
for (uint8_t aa = 0; aa < 3; ++aa) {
if (isnan(s->axis[aa]->settings.target))
s->axis[aa]->settings.target = s->axis[aa]->settings.current;
}
}
for (uint8_t a = 0; a < 3; ++a) {
if (motors)
motors[a] = delta_to_axis(s, a, ok);
else
s->motor[a]->settings.endpos = delta_to_axis(s, a, ok);
}
}
static void reset_pos (Space *s) {
// All axes' current_pos must be valid and equal, in other words, x=y=0.
double p[3];
for (uint8_t i = 0; i < 3; ++i)
p[i] = s->motor[i]->settings.current_pos / s->motor[i]->steps_per_unit;
if (p[0] != p[1] || p[0] != p[2]) {
//debug("resetpos fails");
s->axis[0]->settings.source = NAN;
s->axis[1]->settings.source = NAN;
s->axis[2]->settings.source = NAN;
}
else {
//debug("resetpos %f", p[0]);
s->axis[0]->settings.source = 0;
s->axis[1]->settings.source = 0;
s->axis[2]->settings.source = p[0];
}
}
static void check_position(Space *s, double *data) {
if (isnan(data[0]) || isnan(data[1])) {
if (!isnan(data[0]))
data[1] = s->axis[1]->settings.source;
else if (!isnan(data[1]))
data[0] = s->axis[0]->settings.source;
else {
// Cannot check; assume it's ok.
return;
}
}
for (uint8_t counter = 0; counter < 2; ++counter) {
bool ok = true;
for (uint8_t a = 0; a < s->num_axes; ++a)
ok &= check_delta(s, a, data);
if (ok)
break;
}
}
static void load(Space *s, uint8_t old_type, int32_t &addr) {
if (!s->setup_nums(3, 3)) {
debug("Failed to set up delta axes");
s->cancel_update();
return;
}
for (uint8_t a = 0; a < 3; ++a) {
APEX(s, a).axis_min = read_float(addr);
APEX(s, a).axis_max = read_float(addr);
APEX(s, a).rodlength = read_float(addr);
APEX(s, a).radius = read_float(addr);
}
PRIVATE(s).angle = read_float(addr);
if (isinf(PRIVATE(s).angle) || isnan(PRIVATE(s).angle))
PRIVATE(s).angle = 0;
#define sin210 -.5
#define cos210 -0.8660254037844386 // .5*sqrt(3)
#define sin330 -.5
#define cos330 0.8660254037844386 // .5*sqrt(3)
#define sin90 1
// Coordinates of axes (at angles 210, 330, 90; each with its own radius).
double x[3], y[3];
x[0] = APEX(s, 0).radius * cos210;
y[0] = APEX(s, 0).radius * sin210;
x[1] = APEX(s, 1).radius * cos330;
y[1] = APEX(s, 1).radius * sin330;
x[2] = 0;
y[2] = APEX(s, 2).radius * sin90;
for (uint8_t a = 0; a < 3; ++a) {
APEX(s, a).x = x[a] * cos(PRIVATE(s).angle) - y[a] * sin(PRIVATE(s).angle);
APEX(s, a).y = y[a] * cos(PRIVATE(s).angle) + x[a] * sin(PRIVATE(s).angle);
APEX(s, a).z = sqrt(APEX(s, a).rodlength * APEX(s, a).rodlength - APEX(s, a).radius * APEX(s, a).radius);
}
}
static void save(Space *s, int32_t &addr) {
for (uint8_t a = 0; a < 3; ++a) {
write_float(addr, APEX(s, a).axis_min);
write_float(addr, APEX(s, a).axis_max);
write_float(addr, APEX(s, a).rodlength);
write_float(addr, APEX(s, a).radius);
}
write_float(addr, PRIVATE(s).angle);
}
static bool init(Space *s) {
s->type_data = new Delta_private;
if (!s->type_data)
return false;
return true;
}
static void free(Space *s) {
delete reinterpret_cast <Delta_private *>(s->type_data);
}
static void afree(Space *s, int a) {
}
static double change0(Space *s, int axis, double value) {
return value;
}
static double unchange0(Space *s, int axis, double value) {
return value;
}
static double probe_speed(Space *s) {
double max_spu = 0;
for (int i = 0; i < s->num_motors; ++i)
if (max_spu < s->motor[i]->steps_per_unit)
max_spu = s->motor[i]->steps_per_unit;
return 1e6 / hwtime_step / max_spu;
}
void Delta_init(int num) {
space_types[num].xyz2motors = xyz2motors;
space_types[num].reset_pos = reset_pos;
space_types[num].check_position = check_position;
space_types[num].load = load;
space_types[num].save = save;
space_types[num].init = init;
space_types[num].free = free;
space_types[num].afree = afree;
space_types[num].change0 = change0;
space_types[num].unchange0 = unchange0;
space_types[num].probe_speed = probe_speed;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: validat.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: vg $ $Date: 2007-02-27 11:58:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_VALIDAT_HXX
#define SC_VALIDAT_HXX
#ifndef SC_CONDITIO_HXX
#include "conditio.hxx"
#endif
#ifndef _COM_SUN_STAR_SHEET_TABLEVALIDATIONVISIBILITY_HPP_
#include <com/sun/star/sheet/TableValidationVisibility.hpp>
#endif
namespace ValidListType = ::com::sun::star::sheet::TableValidationVisibility;
class ScPatternAttr;
class ScTokenArray;
class TypedStrCollection;
enum ScValidationMode
{
SC_VALID_ANY,
SC_VALID_WHOLE,
SC_VALID_DECIMAL,
SC_VALID_DATE,
SC_VALID_TIME,
SC_VALID_TEXTLEN,
SC_VALID_LIST,
SC_VALID_CUSTOM
};
enum ScValidErrorStyle
{
SC_VALERR_STOP,
SC_VALERR_WARNING,
SC_VALERR_INFO,
SC_VALERR_MACRO
};
//
// Eintrag fuer Gueltigkeit (es gibt nur eine Bedingung)
//
class ScValidationData : public ScConditionEntry
{
sal_uInt32 nKey; // Index in Attributen
ScValidationMode eDataMode;
BOOL bShowInput;
BOOL bShowError;
ScValidErrorStyle eErrorStyle;
sal_Int16 mnListType; // selection list type: none, unsorted, sorted.
String aInputTitle;
String aInputMessage;
String aErrorTitle;
String aErrorMessage;
BOOL bIsUsed; // temporaer beim Speichern
BOOL DoMacro( const ScAddress& rPos, const String& rInput,
ScFormulaCell* pCell, Window* pParent ) const;
BOOL DoScript( const ScAddress& rPos, const String& rInput,
ScFormulaCell* pCell, Window* pParent ) const;
using ScConditionEntry::operator==;
public:
ScValidationData( ScValidationMode eMode, ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );
ScValidationData( ScValidationMode eMode, ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos );
ScValidationData( const ScValidationData& r );
ScValidationData( ScDocument* pDocument, const ScValidationData& r );
ScValidationData( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
virtual ~ScValidationData();
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
ScValidationData* Clone() const // echte Kopie
{ return new ScValidationData( GetDocument(), *this ); }
ScValidationData* Clone(ScDocument* pNew) const
{ return new ScValidationData( pNew, *this ); }
void ResetInput();
void ResetError();
void SetInput( const String& rTitle, const String& rMsg );
void SetError( const String& rTitle, const String& rMsg,
ScValidErrorStyle eStyle );
BOOL GetInput( String& rTitle, String& rMsg ) const
{ rTitle = aInputTitle; rMsg = aInputMessage; return bShowInput; }
BOOL GetErrMsg( String& rTitle, String& rMsg, ScValidErrorStyle& rStyle ) const;
BOOL HasErrMsg() const { return bShowError; }
ScValidationMode GetDataMode() const { return eDataMode; }
inline sal_Int16 GetListType() const { return mnListType; }
inline void SetListType( sal_Int16 nListType ) { mnListType = nListType; }
/** Returns true, if the validation cell will show a selection list.
@descr Use this instead of GetListType() which returns the raw property
regardless of the validation type. */
bool HasSelectionList() const;
/** Tries to fill the passed collection with list validation entries.
@descr Fills the list only, if this is a list validation and IsShowList() is enabled.
@param rStrings (out-param) The string list to fill with list validation entires.
@return true = rStrings has been filled with at least one entry. */
bool FillSelectionList( TypedStrCollection& rStrings, const ScAddress rPos ) const;
// mit String: bei Eingabe, mit Zelle: fuer Detektiv / RC_FORCED
BOOL IsDataValid( const String& rTest, const ScPatternAttr& rPattern,
const ScAddress& rPos ) const;
BOOL IsDataValid( ScBaseCell* pCell, const ScAddress& rPos ) const;
// TRUE -> Abbruch
BOOL DoError( Window* pParent, const String& rInput, const ScAddress& rPos ) const;
void DoCalcError( ScFormulaCell* pCell ) const;
BOOL IsEmpty() const;
sal_uInt32 GetKey() const { return nKey; }
void SetKey(sal_uInt32 nNew) { nKey = nNew; } // nur wenn nicht eingefuegt!
void SetUsed(BOOL bSet) { bIsUsed = bSet; }
BOOL IsUsed() const { return bIsUsed; }
BOOL EqualEntries( const ScValidationData& r ) const; // fuer Undo
// sortiert (per PTRARR) nach Index
// operator== nur fuer die Sortierung
BOOL operator ==( const ScValidationData& r ) const { return nKey == r.nKey; }
BOOL operator < ( const ScValidationData& r ) const { return nKey < r.nKey; }
private:
/** Tries to get a cell range from a list validation formula.
@descr The formula may contain a cell reference, a defined name or a database range.
@param rRange (out-param) The resulting cell range.
@param rBaseAddr Base address for relative references.
@return true = Cell range found, rRange is valid. */
bool GetRangeFromFormula( ScRange& rRange, const ScAddress& rBaseAddr, ScTokenArray& rTokArr, int nRecCount = 0 ) const;
/** Tests, if pCell is equal to what the passed token array represents. */
bool IsEqualToTokenArray( ScBaseCell* pCell, const ScAddress& rPos, const ScTokenArray& rTokArr ) const;
/** Tests, if contents of pCell occur in cell range referenced by own formula, or in a string list. */
bool IsListValid( ScBaseCell* pCell, const ScAddress& rPos ) const;
};
//
// Liste der Bedingungen:
//
typedef ScValidationData* ScValidationDataPtr;
SV_DECL_PTRARR_SORT(ScValidationEntries_Impl, ScValidationDataPtr,
SC_COND_GROW, SC_COND_GROW)
class ScValidationDataList : public ScValidationEntries_Impl
{
public:
ScValidationDataList() {}
ScValidationDataList(const ScValidationDataList& rList);
ScValidationDataList(ScDocument* pNewDoc, const ScValidationDataList& rList);
~ScValidationDataList() {}
void InsertNew( ScValidationData* pNew )
{ if (!Insert(pNew)) delete pNew; }
ScValidationData* GetData( sal_uInt32 nKey );
void Load( SvStream& rStream, ScDocument* pDocument );
void Store( SvStream& rStream ) const;
void ResetUsed();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
BOOL operator==( const ScValidationDataList& r ) const; // fuer Ref-Undo
};
#endif
<commit_msg>INTEGRATION: CWS dr54 (1.12.58); FILE MERGED 2007/05/25 16:49:45 er 1.12.58.1: #i56566# input validation with dynamic ranges as formua results<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: validat.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2007-07-03 15:46:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_VALIDAT_HXX
#define SC_VALIDAT_HXX
#ifndef SC_CONDITIO_HXX
#include "conditio.hxx"
#endif
#ifndef _COM_SUN_STAR_SHEET_TABLEVALIDATIONVISIBILITY_HPP_
#include <com/sun/star/sheet/TableValidationVisibility.hpp>
#endif
namespace ValidListType = ::com::sun::star::sheet::TableValidationVisibility;
class ScPatternAttr;
class ScTokenArray;
class TypedStrCollection;
enum ScValidationMode
{
SC_VALID_ANY,
SC_VALID_WHOLE,
SC_VALID_DECIMAL,
SC_VALID_DATE,
SC_VALID_TIME,
SC_VALID_TEXTLEN,
SC_VALID_LIST,
SC_VALID_CUSTOM
};
enum ScValidErrorStyle
{
SC_VALERR_STOP,
SC_VALERR_WARNING,
SC_VALERR_INFO,
SC_VALERR_MACRO
};
//
// Eintrag fuer Gueltigkeit (es gibt nur eine Bedingung)
//
class ScValidationData : public ScConditionEntry
{
sal_uInt32 nKey; // Index in Attributen
ScValidationMode eDataMode;
BOOL bShowInput;
BOOL bShowError;
ScValidErrorStyle eErrorStyle;
sal_Int16 mnListType; // selection list type: none, unsorted, sorted.
String aInputTitle;
String aInputMessage;
String aErrorTitle;
String aErrorMessage;
BOOL bIsUsed; // temporaer beim Speichern
BOOL DoMacro( const ScAddress& rPos, const String& rInput,
ScFormulaCell* pCell, Window* pParent ) const;
BOOL DoScript( const ScAddress& rPos, const String& rInput,
ScFormulaCell* pCell, Window* pParent ) const;
using ScConditionEntry::operator==;
public:
ScValidationData( ScValidationMode eMode, ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );
ScValidationData( ScValidationMode eMode, ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos );
ScValidationData( const ScValidationData& r );
ScValidationData( ScDocument* pDocument, const ScValidationData& r );
ScValidationData( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
virtual ~ScValidationData();
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
ScValidationData* Clone() const // echte Kopie
{ return new ScValidationData( GetDocument(), *this ); }
ScValidationData* Clone(ScDocument* pNew) const
{ return new ScValidationData( pNew, *this ); }
void ResetInput();
void ResetError();
void SetInput( const String& rTitle, const String& rMsg );
void SetError( const String& rTitle, const String& rMsg,
ScValidErrorStyle eStyle );
BOOL GetInput( String& rTitle, String& rMsg ) const
{ rTitle = aInputTitle; rMsg = aInputMessage; return bShowInput; }
BOOL GetErrMsg( String& rTitle, String& rMsg, ScValidErrorStyle& rStyle ) const;
BOOL HasErrMsg() const { return bShowError; }
ScValidationMode GetDataMode() const { return eDataMode; }
inline sal_Int16 GetListType() const { return mnListType; }
inline void SetListType( sal_Int16 nListType ) { mnListType = nListType; }
/** Returns true, if the validation cell will show a selection list.
@descr Use this instead of GetListType() which returns the raw property
regardless of the validation type. */
bool HasSelectionList() const;
/** Tries to fill the passed collection with list validation entries.
@descr Fills the list only, if this is a list validation and IsShowList() is enabled.
@param rStrings (out-param) The string list to fill with list validation entires.
@return true = rStrings has been filled with at least one entry. */
bool FillSelectionList( TypedStrCollection& rStrings, const ScAddress& rPos ) const;
// mit String: bei Eingabe, mit Zelle: fuer Detektiv / RC_FORCED
BOOL IsDataValid( const String& rTest, const ScPatternAttr& rPattern,
const ScAddress& rPos ) const;
BOOL IsDataValid( ScBaseCell* pCell, const ScAddress& rPos ) const;
// TRUE -> Abbruch
BOOL DoError( Window* pParent, const String& rInput, const ScAddress& rPos ) const;
void DoCalcError( ScFormulaCell* pCell ) const;
BOOL IsEmpty() const;
sal_uInt32 GetKey() const { return nKey; }
void SetKey(sal_uInt32 nNew) { nKey = nNew; } // nur wenn nicht eingefuegt!
void SetUsed(BOOL bSet) { bIsUsed = bSet; }
BOOL IsUsed() const { return bIsUsed; }
BOOL EqualEntries( const ScValidationData& r ) const; // fuer Undo
// sortiert (per PTRARR) nach Index
// operator== nur fuer die Sortierung
BOOL operator ==( const ScValidationData& r ) const { return nKey == r.nKey; }
BOOL operator < ( const ScValidationData& r ) const { return nKey < r.nKey; }
private:
/** Tries to fill the passed collection with list validation entries.
@descr Fills the list only if it is non-NULL,
@param pStrings (out-param) Optionally NULL, string list to fill with list validation entires.
@param pCell can be NULL if it is not necessary to which element in the list is selected.
@param rPos the base address for relative references.
@param rTokArr Formula token array.
@param rMatch (out-param) the index of the first item that matched, -1 if nothing matched.
@return true = Cell range found, rRange is valid, or an error entry stuffed into the list if pCell==NULL. */
bool GetSelectionFromFormula( TypedStrCollection* pStrings,
ScBaseCell* pCell, const ScAddress& rPos,
const ScTokenArray& rTokArr, int& rMatch ) const;
/** Tests, if pCell is equal to what the passed token array represents. */
bool IsEqualToTokenArray( ScBaseCell* pCell, const ScAddress& rPos, const ScTokenArray& rTokArr ) const;
/** Tests, if contents of pCell occur in cell range referenced by own formula, or in a string list. */
bool IsListValid( ScBaseCell* pCell, const ScAddress& rPos ) const;
};
//
// Liste der Bedingungen:
//
typedef ScValidationData* ScValidationDataPtr;
SV_DECL_PTRARR_SORT(ScValidationEntries_Impl, ScValidationDataPtr,
SC_COND_GROW, SC_COND_GROW)
class ScValidationDataList : public ScValidationEntries_Impl
{
public:
ScValidationDataList() {}
ScValidationDataList(const ScValidationDataList& rList);
ScValidationDataList(ScDocument* pNewDoc, const ScValidationDataList& rList);
~ScValidationDataList() {}
void InsertNew( ScValidationData* pNew )
{ if (!Insert(pNew)) delete pNew; }
ScValidationData* GetData( sal_uInt32 nKey );
void Load( SvStream& rStream, ScDocument* pDocument );
void Store( SvStream& rStream ) const;
void ResetUsed();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
BOOL operator==( const ScValidationDataList& r ) const; // fuer Ref-Undo
};
#endif
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.