I am having trouble with this library... My code works fine, the parsers/creator works too, but an err appears, I don't know why:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/thread.hpp>
#include <string>
#include <exception>
#include <set>
#include <iostream>
#include "journal.h"
unsigned short port = 2013;
unsigned short maxConnec = 250;
unsigned short fPort() {return port;}
unsigned short fMaxConnec() {return maxConnec;}
bool load(const std::string &file)
{
using boost::property_tree::ptree;
ptree objectXML;
std::cout << "bbb";
read_xml(file, objectXML);
std::cout << "aaa";
if (file.length() == 0) // By the way, no way to do that better ? "if file doesn't exist..."
{
return 0;
}
else
{
port = objectXML.get<unsigned short>("configuration.server.port");
maxConnec = objectXML.get<unsigned short>("configuration.server.maxConnections");
return 1;
}
}
bool save(const std::string &file)
{
try
{
using boost::property_tree::ptree;
ptree objectXML;
objetXML.put("configuration.server.port", port);
objetXML.put("configuration.server.maxConnections", maxConnec);
write_xml(file, objectXML, std::locale(), boost::property_tree::xml_writer_make_settings<ptree::key_type>(' ', 4));
return 1;
}
catch (std::exception e)
{
return 0;
}
}
void generate()
{
std::string file = "configuration.xml";
try{
if (!load(fichier))
{
save(file);
}
}
catch (std::exception &e)
{
load(file);
}
}
Get a bad path, I totally don't know why because when I try to read data I can and it gets the data in configuration.xml even if I change it...
The ptree_bad_path exception is raised from the throwing version of get and signals that "configuration.server.port" or "configuration.server.maxConnections" path to the XML element doesn't exist.
The error isn't related to the configuration.xml file path.
So you should check the element name or, for optional elements, use the default-value / optional-value version of get.
Related
First of all, this is NOT my own code! It's taken from Google's Android sourcecode https://android.googlesource.com/platform/art/+/android-9.0.0_r10/tools/hiddenapi/hiddenapi.cc
So, it should be tested and should work! But, it fails at the point "insert..."
Short code:
/*...*/
std::unordered_set<std::string> light_greylist_;
/*...*/
/*Caller:*/ OpenApiFile(light_greylist_path_, &light_greylist_);
bool OpenApiFile(const std::string& path, std::unordered_set<std::string>* list) {
std::ifstream api_file(path, std::ifstream::in);
for (std::string line; std::getline(api_file, line);) {
/* line IS filled; I've checked it with a simple fprintf(): [this IS my code for testing]*/
FILE *stream = fopen("test.txt", "a+");
fprintf(stream, "%s\n", line.c_str());
fclose(stream);
/* This is the point where it crashes with an "Illegal instruction (core dumped)"*/
list->insert(line);
}
api_file.close();
return true;
}
What goes wrong?
I'd make list a reference instead of a pointer. It's hard to say why the original code uses pointers since it'll most probably crash if called with NULL. Also check that the file has been successfully opened (even though it seems to have succeeded for you this time).
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unordered_set>
bool OpenApiFile(const std::string& path, std::unordered_set<std::string>& list) {
std::ifstream api_file(path, std::ifstream::in);
if (!api_file) {
return false;
}
for (std::string line; std::getline(api_file, line);) {
list.insert(line);
}
return true;
}
int main(int argc, char* argv[]) {
std::vector<std::string> files(argv+1, argv+argc);
for(auto& light_greylist_path_ : files) {
std::unordered_set<std::string> light_greylist_;
if (OpenApiFile(light_greylist_path_, light_greylist_) == false) {
std::cerr << "failed opening "+light_greylist_path_+"\n";
} else {
for(auto& lg : light_greylist_) {
std::cout << lg << "\n";
}
}
}
return 0;
}
So I'm in the middle of implementing SIFT and the thing is that I don't know how to deal with channel in OpenCV. Here is what I've done so far.
#ifndef QUANTIZATION_DATABASE_DATA_READ_H
#define QUANTIZATION_DATABASE_DATA_READ_H
// C HEADERS
#include <stdlib.h>
#include <fcntl.h>
// C++ HEADERS
#include <iostream>
#include <string>
// OPENCV HEADERS
#include <opencv2/opencv.hpp>
namespace cv
{
class DataReader
{
public:
explicit DataReader(int _flags) : flags(_flags)
{
}
void read(std::string filename, const char *key, Mat &res)
{
try
{
FileStorage fs(filename, FileStorage::Mode::FORMAT_XML | FileStorage::Mode::READ);
fs[key] >> res;
fs.release();
}
catch (Exception e)
{
std::cerr << e.msg << std::endl;
}
}
private:
int flags;
};
}
The algorithm that I want to implement is as follow.
Read the 4 dimensional matrix(NHWC) from a xml file.
Store it in a matrix
Convert it into NHWC
The thing is that I don't have to do step 3 when I do some stuffs using Tensorflow. It just automatically knows the last dimension is channel. So, what should I do?
It seems like there is no way whatsoever to make 4 dimensional buffer to a batch of images. So I decided to change the format of the xml file and it worked like a charm.
Below is temporarily workaround for this problem.
#ifndef QUANTIZATION_DATABASE_DATA_READ_H
#define QUANTIZATION_DATABASE_DATA_READ_H
// C HEADERS
#include <stdlib.h>
#include <fcntl.h>
// C++ HEADERS
#include <iostream>
#include <string>
// OPENCV HEADERS
#include <opencv2/opencv.hpp>
namespace cv
{
class DataReader
{
public:
explicit DataReader(int _flags) : flags(_flags)
{
}
void read(std::string filename, Mat &res)
{
try
{
float length = 0;
FileStorage fs(filename, FileStorage::Mode::FORMAT_XML | FileStorage::Mode::READ);
fs["size"] >> length;
for (int i = 0; i < (int)length; ++i) {
std::string key("image");
std::string index = std::to_string(i);
Mat image;
key = key + index;
fs[key.c_str()] >> image;
std::cout << image.channels() << std::endl;
res.push_back(image);
}
fs.release();
}
catch (Exception e)
{
std::cerr << e.msg << std::endl;
}
}
private:
int flags;
};
}
I am trying to use the Boost 1.60.0 library with Intel Pin 2.14-71313-msvc12-windows. The following piece of code is the simple implementation I did to try things out:
#define _CRT_SECURE_NO_WARNINGS
#include "pin.H"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <time.h>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
namespace boost_network{
#include <boost/asio.hpp>
#include <boost/array.hpp>
}
//Buffersize of lockfree queue to use
const int BUFFERSIZE = 1000;
//Tracefiles for error / debug purpose
std::ofstream TraceFile;
//String wrapper for boost queue
class statement {
public:
statement(){ s = ""; }
statement(const std::string &n) : s(n) {}
std::string s;
};
//string queue to store inserts
boost::lockfree::spsc_queue<statement, boost::lockfree::capacity<BUFFERSIZE>> buffer; // need lockfree queue for multithreading
//Pin Lock to synchronize buffer pushes between threads
PIN_LOCK lock;
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "calltrace.txt", "specify trace file name");
KNOB<BOOL> KnobPrintArgs(KNOB_MODE_WRITEONCE, "pintool", "a", "0", "print call arguments ");
INT32 Usage()
{
cerr << "This tool produces a call trace." << endl << endl;
cerr << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
VOID ImageLoad(IMG img, VOID *)
{
//save module informations
buffer.push(statement("" + IMG_Name(img) + "'; '" + IMG_Name(img).c_str() + "'; " + IMG_LowAddress(img) + ";"));
}
VOID Fini(INT32 code, VOID *v)
{
}
void do_somenetwork(std::string host, int port, std::string message)
{
boost_network::boost::asio::io_service ios;
boost_network::boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
boost_network::boost::asio::ip::tcp::socket socket(ios);
socket.connect(endpoint);
boost_network::boost::system::error_code error;
socket.write_some(boost_network::boost::asio::buffer(message.data(), message.size()), error);
socket.close();
}
void WriteData(void * arg)
{
int popped; //actual amount of popped objects
const int pop_amount = 10000;
statement curr[pop_amount];
string statement = "";
while (1) {
//pop more objects from buffer
while (popped = buffer.pop(curr, pop_amount))
{
//got new statements in buffer to insert into db: clean up statement
statement.clear();
//concat into one statement
for (int i = 0; i < popped; i++){
statement += curr[i].s;
}
do_somenetwork(std::string("127.0.0.1"), 50000, sql_statement.c_str());
}
PIN_Sleep(1);
}
}
int main(int argc, char *argv[])
{
PIN_InitSymbols();
//write address of label to TraceFile
TraceFile.open(KnobOutputFile.Value().c_str());
TraceFile << &label << endl;
TraceFile.close();
// Initialize the lock
PIN_InitLock(&lock);
// Initialize pin
if (PIN_Init(argc, argv)) return Usage();
// Register ImageLoad to be called when an image is loaded
IMG_AddInstrumentFunction(ImageLoad, 0);
//Start writer thread
PIN_SpawnInternalThread(WriteData, 0, 0, 0);
PIN_AddFiniFunction(Fini, 0);
// Never returns
PIN_StartProgram();
return 0;
}
When I build the above code, Visual Studio cannot find boost_network::boost::asio::ip and keeps giving error saying asio::ip does not exist. I had previously posted this question myself:
Sending data from a boost asio client
and after using the provided solution in the same workspace, the code worked fine and I was able to communicate over the network. I am not sure what is going wrong here. For some reason using the different namespace seems to not work out because it says boost must be in the default namespace.
However, if I do not add the namespace, in that case the line,
KNOB<BOOL> KnobPrintArgs(KNOB_MODE_WRITEONCE, "pintool", "a", "0", "print call arguments ");
throws an error saying BOOL is ambiguous.
Kindly suggest what should be a viable solution in this situation. I am using Visual Studio 2013.
The same piece of code with only Pin also works with out the network part and I can write data generated from Pin into a flat file.
Why istream object after calling readsome() method don't give any chars in buffer? Is there any error in class construction?
StreamBuffer.h
#ifndef StreamBuffer_h
#define StreamBuffer_h
#include <string>
#include <fstream>
#include <iostream>
#include <iterator>
enum StreamBufferState
{
STREAMBUFFER_OK = 0,
STREAMBUFFER_EOF = 1
};
class StreamBuffer
{
std::fstream file;
std::istream istrm;
int maxBufferSize;
std::string buffer;
public:
StreamBuffer(int maxBuffSize, const std::string& filename);
~StreamBuffer();
void SetMaxBufferSize(unsigned int maxBuffSize);
StreamBufferState FullBufferWithData();
std::string GetDataBuffer();
};
#endif
StreamBuffer.cpp
#include "StreamBuffer.h"
using namespace std;
StreamBuffer::StreamBuffer(int maxBuffSize, const std::string& filename) : istrm( !filename.empty() ? file.rdbuf() : cin.rdbuf() )
{
SetMaxBufferSize(maxBuffSize);
if(!filename.empty())
{
file.open(filename.c_str(),ios::in | ios::binary);
}
else
{
std::cin>>noskipws;
}
}
StreamBuffer::~StreamBuffer()
{
file.close();
}
void StreamBuffer::SetMaxBufferSize(unsigned int maxBuffSize)
{
maxBufferSize = maxBuffSize;
}
StreamBufferState StreamBuffer::FullBufferWithData()
{
istrm.readsome((char*)&buffer[0],maxBufferSize);
if(istrm.eof())
return STREAMBUFFER_EOF;
return STREAMBUFFER_OK;
}
std::string StreamBuffer::GetDataBuffer()
{
string buf = buffer;
return buf;
}
File is opened, but readsome() don't read buffer.
You have undefined behavior in your code, as you try read into an empty string. You need to set the size of buffer.
An unrelated logical error: In the FullBufferWithData function you will return "OK" even if there is an error reading the file.
I try to serialize to a binary archive then load this archive using the code show below. The issue I have is that when loading the file, I get an "input stream error".
#include "project.h"
// Std
#include <fstream>
// Boost
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/algorithm/string.hpp>
// Qt
#include <QtGui/QMessageBox>
#include <QFileInfo>
#include <QDir>
BOOST_CLASS_VERSION(Tools::CommentModel, 1)
using namespace std;
namespace Sawe {
template<class Archive>
void runSerialization(Archive& ar, Project*& project, QString path)
{
const unsigned magicConst=65553;
unsigned magic = magicConst;
ar & BOOST_SERIALIZATION_NVP(magic);
if (magic != magicConst)
throw std::ios_base::failure("Wrong project type");
ar & BOOST_SERIALIZATION_NVP(project);
}
bool Project::
save()
{
if (project_filename_.empty()) {
return saveAs();
}
try
{
std::ofstream ofs(project_filename_.c_str());
assert(ofs.good());
boost::archive::binary_oarchive xml(ofs);
Project* p = this;
runSerialization(xml, p, project_filename_.c_str());
p->is_modified_ = false;
}
catch (const std::exception& x)
{
QString msg = "Error: " + QString::fromStdString(vartype(x)) +
"\nDetails: " + QString::fromLocal8Bit(x.what());
QMessageBox::warning( 0, "Can't save file", msg );
TaskInfo("======================\nCan't save file\n%s\n======================", msg.toStdString().c_str());
}
return true;
}
#endif
pProject Project::
openProject(std::string project_file)
{
std::ifstream ifs(project_file.c_str());
boost::archive::binary_iarchive xml(ifs);
Project* new_project = 0;
runSerialization(xml, new_project, project_file.c_str());
new_project->project_filename_ = project_file;
new_project->updateWindowTitle();
new_project->is_modified_ = false;
pProject project( new_project );
return project;
}
}
Any idea ?
Thanks in advance for your help!
Cheers
I had the same problem, when i added the binary flag to the fstream ctors everything worked.