CEREAL failing to serialise - failed to read from input stream exception - cereal

I found a particular 100MB bin file (CarveObj_k5_rgbThreshold10_triangleCameraMatches.bin in minimal example), where cereal fails to load throwing exception "Failed to read 368 bytes from input stream! Read 288"
The respective 900MB XML file (CarveObj_k5_rgbThreshold10_triangleCameraMatches.xml in minimal example), built from the same data, loads normally.
The XML file was produced by
// {
// std::ofstream outFile(base + "_triangleCameraMatches.xml");
// cereal::XMLOutputArchive oarchive(outFile);
// oarchive(m_triangleCameraMatches);
// }
and the binary version was produced by
// {
// std::ofstream outFile(base + "_triangleCameraMatches.bin");
// cereal::BinaryOutputArchive oarchive(outFile);
// oarchive(m_triangleCameraMatches);
// }
Minimal example: https://www.dropbox.com/sh/fu9e8km0mwbhxvu/AAAfrbqn_9Tnokj4BVXB8miea?dl=0
Version of Cereal used: 1.3.0
MSVS 2017
Windows 10
Is this a bug? Am I missing something obvious?
Created a bug report in the meanwhile: https://github.com/USCiLab/cereal/issues/607

In this particular instance, the "failed to read from input stream exception" thrown from line 105 of binary.hpp arises because the ios::binary flag is missing from the ifstream constructor call. (This is needed, otherwise ifstream will attempt to interpret some of the file contents as carriage return and linefeed characters. See this question for more information.)
So the few lines of code in your minimal example that read from the .bin file should look like this:
vector<vector<float>> testInBinary;
{
std::ifstream is("CarveObj_k5_rgbThreshold10_triangleCameraMatches.bin", ios::binary);
cereal::BinaryInputArchive iarchive(is);
iarchive(testInBinary);
}
However, even after this is fixed there does also seem to be another problem with the data in that particular .bin file, as when I try to read it I get a different exception thrown, seemingly arising from an incorrectly encoded size value. I don't know if this is an artefact of copying to/from Dropbox though.
There doesn't seem to be a fundamental 100MB limit on Cereal binary files. The following minimal example creates a binary file of around 256MB and reads it back fine:
#include <iostream>
#include <fstream>
#include <vector>
#include <cereal/types/vector.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/binary.hpp>
using namespace std;
int main(int argc, char* argv[])
{
vector<vector<double>> test;
test.resize(32768, vector<double>(1024, -1.2345));
{
std::ofstream outFile("test.bin");
cereal::BinaryOutputArchive oarchive(outFile, ios::binary);
oarchive(test);
}
vector<vector<double>> testInBinary;
{
std::ifstream is("test.bin", ios::binary);
cereal::BinaryInputArchive iarchive(is);
iarchive(testInBinary);
}
return 0;
}
It might be worth noting that in your example code on Dropbox, you're also missing the ios::binary flag on the ofstream constructor when you're writing the .bin file:
/// Produced by:
// {
// std::ofstream outFile(base + "_triangleCameraMatches.bin");
// cereal::BinaryOutputArchive oarchive(outFile);
// oarchive(m_triangleCameraMatches);
// }
It might be worth trying with the flag set. Hope some of this helps.

Related

How do i log errors while writing custom varnish module?

I am learning varnish and about extending the varnish vmod with inline c code. And I am starting it with writing my own custom varnish module. I want to log errors and failure from my custom module. How do i achieve that?
I have options to choose from various logging libraries available for C. But i want to check if there is any inbuilt varnish library to make use of it. Below is my sample code of a vmod c file.
#include "vrt.h"
#include "cache/cache.h"
#include "vcc_if.h"
#include <jansson.h>
#define JSON_ERROR "-1"
#define JSON_LOC "/etc/example.json"
VCL_STRING
vmod_validate_mymod(VRT_CTX) {
(void) ctx;
char *return_code = "0";
json_t *jobj;
json_error_t error;
jobj = json_load_file(JSON_LOC,0,&error);
if (!jobj) {
// error log here
return JSON_ERROR;
}
return return_code;
}
I want en error log line to be added in a cutom log file when the the if condition in the code above is true. Please help.
You want VSLb:
VSLb(ctx->vsl, SLT_VCL_Log, "%d", 5);
If you need to build larger string, or need allocations, use the WS_* functions, their allocations are freed at the end of the rquest automatically.
See how std.log() does it: https://github.com/varnishcache/varnish-cache/blob/389d7ba28e0d0e3a2d5c30a959aa517e5166b246/vmod/vmod_std.c#L145-L153

Resource file not loading for a DLL

My code for loading the file from resource is given below
void LoadFileInResource(int name, int type, DWORD& size, const char*& data)
{
HMODULE handle = ::GetModuleHandle(NULL);
HRSRC rc = ::FindResource(handle, MAKEINTRESOURCE(name),MAKEINTRESOURCE(type));
HGLOBAL rcData = ::LoadResource(handle, rc);
size = ::SizeofResource(handle, rc);
data = static_cast<const char*>(::LockResource(rcData));
}
This code works perfect if its just an application. When the same code is used as a DLL, I am getting null in rc, which is post the FindResource.
I have defined the symbols in resourceful file as shows below:
#define TEXTFILE 256
#define IDR_MYTEXTFILE 105
Also the file which I need to add is defined in rc file:
IDR_MYTEXTFILE TEXTFILE "C:/Docs/Lib.XML"
As I mentioned earlier, this code is perfectly working when its an application, converting it to DLL is creating issue.
LoadFileInResource function is called as given below:
LoadFileInResource(IDR_MYTEXTFILE, TEXTFILE, size, data);

Having trouble sending a message to ROS

I am pretty new in ROS. I am just trying to publish a message to a node in a linux server with this code:
#include "stdafx.h"
#include "ros.h"
#include <string>
#include <stdio.h>
#include <Windows.h>
using std::string;
int _tmain(int argc, _TCHAR * argv[])
{
ros::NodeHandle nh;
char *ros_master = "*.*.*.*";
printf("Connecting to server at %s\n", ros_master);
nh.initNode(ros_master);
printf("Advertising cmd_vel message\n");
string sent = "Hello robot";
ros::Publisher cmd_vel_pub("try", sent);
nh.advertise(cmd_vel_pub);
printf("All done!\n");
return 0;
}
The compiler gives me these errors:
Error C2664 'ros::Publisher::Publisher(ros::Publisher &&)': cannot convert argument 2 from 'std::string' to 'ros::Msg *' LeapMotion c:\users\vive-vr-pc\documents\visual studio 2015\projects\leapmotion\leapmotion\leapmotion.cpp 22
Error (active) no instance of constructor "ros::Publisher::Publisher" matches the argument list LeapMotion c:\Users\Vive-VR-PC\Documents\Visual Studio 2015\Projects\LeapMotion\LeapMotion\LeapMotion.cpp 22
I am on Visual Studio and there aren't a lot of tutorial from windows to linux, so I am confused on what to do. Many thanks for the help! :D
Take a look at the Hello World example. You cannot send types which are not defined as messages, i.e. std::string is not a ros message type. What you need is
#include <std_msgs/String.h>
Define and fill the string messages
std_msgs::String sent;
ros::Publisher cmd_vel_pub("try", &sent);
nh.advertise(cmd_vel_pub);
ros::Rate r(1); // once a second
sent.data = "Hello robot";
while (n.ok()){
cmd_vel_pun.publish(sent);
ros::spinOnce();
r.sleep();
}
Check out this blabbler example and these tutorials.

Linux alternative to _NSGetExecutablePath?

Is it possible to side-step _NSGetExecutablePath on Ubuntu Linux in place of a non-Apple specific approach?
I am trying to compile the following code on Ubuntu: https://github.com/Bohdan-Khomtchouk/HeatmapGenerator/blob/master/HeatmapGenerator2_Macintosh_OSX.cxx
As per this prior question that I asked: fatal error: mach-o/dyld.h: No such file or directory, I decided to comment out line 52 and am wondering if there is a general cross-platform (non-Apple specific) way that I can rewrite the code block of line 567 (the _NSGetExecutablePath block) in a manner that is non-Apple specific.
Alen Stojanov's answer to Programmatically retrieving the absolute path of an OS X command-line app and also How do you determine the full path of the currently running executable in go? gave me some ideas on where to start but I want to make certain that I am on the right track here before I go about doing this.
Is there a way to modify _NSGetExecutablePath to be compatible with Ubuntu Linux?
Currently, I am experiencing the following compiler error:
HeatmapGenerator_Macintosh_OSX.cxx:568:13: error: use of undeclared identifier
'_NSGetExecutablePath'
if (_NSGetExecutablePath(path, &size) == 0)
Basic idea how to do it in a way that should be portable across POSIX systems:
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
static char *path;
const char *appPath(void)
{
return path;
}
static void cleanup()
{
free(path);
}
int main(int argc, char **argv)
{
path = realpath(argv[0], 0);
if (!path)
{
perror("realpath");
return 1;
}
atexit(&cleanup);
printf("App path: %s\n", appPath());
return 0;
}
You can define an own module for it, just pass it argv[0] and export the appPath() function from a header.
edit: replaced exported variable by accessor method

Creating a JPG file with Node.JS

In my node.js server I am downloading a file from another server. The downloaded file is a JPG image data encoded with Base64 two times, that means I have to decode it 2 times. Given is my code.
var base64DecodedFileData = new Buffer(file_data, 'base64').toString('binary');
var tmp = base64DecodedFileData.split("base64,");
var base64DecodedFileData = new Buffer(tmp[1], 'base64').toString('binary');
var file = fs.createWriteStream(file_path, stream_options);
file.write(base64DecodedFileData);
file.end();
I know my image data is valid the first time I have decoded it ( I have verified that data in online base64 decoders by decoding it second time and I have got the proper image), but when I decode it second time and create a file with this data. I am not getting a valid JPG file.
I have compared it with the actual image, start and ends of both files seems fine but something is not right in my constructed file. The constructed file is also of bigger in size than the original one.
PS: I am doing the split before decoding second time because the data after the first decoding starts with
data:; base64, DATASTARTS
Any thoughts.
Farrukh Arshad.
I have solve My problem. The problem seems to be in the decoding from the node.js so I have written a C++ addon to do the job. Here is the code. I am pretty much sure the problem will remain if we have image file encoded only once.
.js file
ModUtils.generateImageFromData(file_data, file_path);
c++ addon: This uses the base64 C++ encoder/decoder from
http://www.adp-gmbh.ch/cpp/common/base64.html
#define BUILDING_NODE_EXTENSION
#include <node.h>
#include <iostream>
#include <fstream>
#include "base64.h"
using namespace std;
using namespace v8;
static const std::string decoding_prefix =
"data:;base64,";
// --------------------------------------------------------
// Decode the image data and save it as image
// --------------------------------------------------------
Handle<Value> GenerateImageFromData(const Arguments& args) {
HandleScope scope;
// FIXME: Improve argument checking here.
// FIXME: Add error handling here.
if ( args.Length() < 2) return v8::Undefined();
Handle<Value> fileDataArg = args[0];
Handle<Value> filePathArg = args[1];
String::Utf8Value encodedData(fileDataArg);
String::Utf8Value filePath(filePathArg);
std::string std_FilePath = std::string(*filePath);
// We have received image data which is encoded with Base64 two times
// so we have to decode it twice.
std::string decoderParam = std::string(*encodedData);
std::string decodedString = base64_decode(decoderParam);
// After first decoding the data will also contains a encoding prefix like
// data:;base64,
// We have to remove this prefix to get actual encoded image data.
std::string second_pass = decodedString.substr(decoding_prefix.length(), (decodedString.length() - decoding_prefix.length()));
std::string imageData = base64_decode(second_pass);
// Write image to file
ofstream image;
image.open(std_FilePath.c_str());
image << imageData;
image.close();
return scope.Close(String::New(" "));
//return scope.Close(decoded);
}
void Init(Handle<Object> target) {
// Register all functions here
target->Set(String::NewSymbol("generateImageFromData"),
FunctionTemplate::New(GenerateImageFromData)->GetFunction());
}
NODE_MODULE(modutils, Init);
Hope it will help for someone else.

Resources