MongoDB C++ tutorial program fails: 'mongocxx::v_noabi::logic_error' - c++

Im trying to get something done with C++ and MongoDB. So far there has been myriad of problems, but I have pulled through.
Then I got this one:
terminate called after throwing an instance of 'mongocxx::v_noabi::logic_error'
what(): invalid use of default constructed or moved-from mongocxx::client object
Aborted
And frankly, Im losing hope. This is the example Im trying to run:
https://docs.mongodb.com/getting-started/cpp/insert/.
Error appears when I try to run the compiled program. Im able to compile and run the 'hellomongo' example just fine, so at least partly, the driver is installed correctly.
My code:
#include <chrono>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::finalize;
int main(int, char**)
{
mongocxx::instance inst{};
mongocxx::client conn{};
auto db = conn["test"];
bsoncxx::document::value restaurant_doc =
document{} << "address" << open_document << "street"
<< "2 Avenue"
<< "zipcode"
<< "10075"
<< "building"
<< "1480"
<< "coord" << open_array << -73.9557413 << 40.7720266 << close_array
<< close_document << "borough"
<< "Manhattan"
<< "cuisine"
<< "Italian"
<< "grades" << open_array << open_document << "date"
<< bsoncxx::types::b_date { std::chrono::system_clock::time_point {
std::chrono::milliseconds { 12323 } } } << "grade"
<< "A"
<< "score" << 11 << close_document << open_document << "date"
<< bsoncxx::types::b_date { std::chrono::system_clock::time_point {
std::chrono::milliseconds { 12323 } } } << "grade"
<< "B"
<< "score" << 17 << close_document << close_array << "name"
<< "Vella"
<< "restaurant_id"
<< "41704620" << finalize;
// We choose to move in our document here, which transfers ownership to insert_one()
auto res = db["restaurants"].insert_one(std::move(restaurant_doc));
}
I use the following command to compile the example:
c++ --std=c++11 test.cpp -o test $(pkg-config --cflags --libs libmongocxx)
Any help is appreciated! I have very little experience with C++, so I'm bit lost to what could be the problem.

As acm pointed out, the docs on docs.mongodb.com are out of date. Github examples are working fine. I will mark this as answered.

Related

Creating logical device in Vulkan returns -8, but only sometimes

While using a class to hold my window class and Vulkan class, this error VK_ERROR_FEATURE_NOT_PRESENT is returned when I use vkCreateDevice however, when I put the same code the class is running into the main class, it works completely fine. I also had a similar problem with getting the instance extensions via SDL_Vulkan_GetInstanceExtensions.
working main.cpp
window.createWindow();
engine.window = window.window;
try {
engine.initialize();
}
catch (XiError error) {
std::cout << "Error " << error.code << ": " << error.definition << std::endl;
}
window.instance = engine.getVkInstance();
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(engine.physicalDevice, &deviceProperties);
std::cout << deviceProperties.deviceName << ", Driver Version " << deviceProperties.driverVersion << std::endl;
try {
window.createSurface();
}
catch (XiError error) {
std::cout << "Error " << error.code << ": " << error.definition << std::endl;
}
window.mainLoop();
vkDestroyDevice(engine.logicalDevice, nullptr);
vkDestroySurfaceKHR(engine.instance, window.surface, nullptr);
vkDestroyInstance(engine.instance, nullptr);
SDL_DestroyWindow(window.window);
SDL_Quit();
not working main.cpp
try {
app.run();
}
catch (XiError error) {
std::cout << "Error " << error.code << ": " << error.definition << std::endl;
}
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(app.engine.physicalDevice, &deviceProperties);
std::cout << deviceProperties.deviceName << ", Driver Version " << deviceProperties.driverVersion << std::endl;
app.window.mainLoop();
app.shutDown();
app.run()
window.createWindow();
engine.window = window.window;
engine.createVulkanInstance();
window.instance = engine.getVkInstance();
window.createSurface();
engine.getPhysicalDevices();
engine.selectPhysicalDevice();
engine.createLogicalDevice();
window.mainLoop();
app.shutDown()
vkDestroyDevice(engine.logicalDevice, nullptr);
vkDestroySurfaceKHR(engine.instance, window.surface, nullptr);
vkDestroyInstance(engine.instance, nullptr);
SDL_DestroyWindow(window.window);
SDL_Quit();
window engine and app are pre-defined by my own classes
I've tried manually adding the different required and supported extensions, and it works, but it feels hacky and is quite a large bulk of code. If this is a weird out of scope error, I've really no idea. if any other code is needed I'll be happy to provide it and the GitHub can also be found here: https://github.com/XiniaDev/Xinia-Engine
I think your problem is that requiredFeatures in XiEngine is not initialised. You set a few values to true, but I think you need a memset(&requiredFeatures, 0, sizeof(requiredFeatures)); or similar at the start of XiEngine::XiEngine to fix it.

C++ date library fails with timezone

This used to play once. I am trying to get some data from the C++ date library but an exception is caught. I am compiling with
-DUSE_AUTOLOAD=0 -DHAS_REMOTE_API=0 -DUSE_OS_TZDB=1
what is wrong with the code?
#include <iostream>
#include "date/tz.h"
#include <exception>
using namespace date;
using namespace std::chrono;
int main(int argc, char** argv) {
try {
auto current_time_zone = make_zoned("Europe/Athens", std::chrono::system_clock::now());
auto current_day = date::format("%A", current_time_zone);
auto current_time = date::format("%H:%M", current_time_zone);
std::cout << "day: " << current_day << ", time: " << current_time << " in timezone: " << current_time_zone << std::endl;
//std::cout << " in timezone: " << current_time_zone << std::endl;
} catch ( std::exception& e) {
std::cout << e.what() << std::endl;
}
}
You need to use the -pthread flag. tz.cpp uses call_once to do part of the initialisation. And without -pthread it's not going to work (as underneath it need something like __gthread_once). See this for more details.
You can verify if that's the problem by running your example with gdb (use the catch throw).
I'm not positive what the problem is, but I can tell you that this library does not throw an exception that contains the message "Unknown error".
Try adding -DONLY_C_LOCALE=1 to your build flags. This will avoid your std::lib's time_put facet, but will limit you to only the "C" locale. If this fixes the problem, then it is your std::lib's std::time_put facet that threw the exception.

How do you disconnect from a boost signal2 using a functor to a method of a class?

I am not getting the behavior I am expecting when disconnecting a slot (that is a class method) from from a boost::signals2. My terminology is probably off, so I will provide a minimal working example (MWE) below demonstrating what I see and what I expect. The short version is that I am disconnecting from the signal, but it is staying there. Everything works great if I do this with a stand-alone function, it is when I use a class method that I run into this behavior.
Any help would be greatly appreciated!
>> tree
.
├── main.cpp
└── SConstruct
0 directories, 2 files
>> cat SConstruct
Program('main.cpp')
>> cat main.cpp
#include <boost/signals2.hpp>
#include <iostream>
struct foo {
void bar(int n) {
std::cout << "Called foo::bar with " << n << std::endl;
}
};
typedef boost::function<void(int)> Signal_f;
int main() {
foo f;
boost::signals2::signal< void(int) > my_signal;
Signal_f functor = boost::bind(&foo::bar, f, _1);
std::cout << "Created signal, and it has "
<< my_signal.num_slots() << " subscribers." << std::endl;
my_signal.connect(functor);
std::cout << "Subscribed to signal, and it has "
<< my_signal.num_slots() << " subsciber." << std::endl;
my_signal(1);
my_signal.disconnect(&functor);
std::cout << "Un-Subscribed to signal, but it still has "
<< my_signal.num_slots()
<< " subsciber, and it should not have any now." << std::endl;
my_signal(2);
return 0;
}
>> scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
g++ -o main.o -c main.cpp
g++ -o main main.o
scons: done building targets.
>> ./main
Created signal, and it has 0 subscribers.
Subscribed to signal, and it has 1 subsciber.
Called foo::bar with 1
Un-Subscribed to signal, but it still has 1 subsciber, and it should not have any now.
Called foo::bar with 2
re-implementing using scoped_connection:
#include <boost/signals2.hpp>
#include <iostream>
struct foo {
void bar(int n) {
std::cout << "Called foo::bar with " << n << std::endl;
}
};
typedef boost::function<void(int)> Signal_f;
int main() {
using boost::signals2::scoped_connection;
foo f;
boost::signals2::signal< void(int) > my_signal;
Signal_f functor = boost::bind(&foo::bar, f, _1);
std::cout << "Created signal, and it has "
<< my_signal.num_slots() << " subscribers." << std::endl;
// the scoped_connection object is RAII
auto con = scoped_connection(my_signal.connect(functor));
std::cout << "Subscribed to signal, and it has "
<< my_signal.num_slots() << " subsciber." << std::endl;
my_signal(1);
// disconnect the connection object, not the signal
con.disconnect();
std::cout << "Un-Subscribed to signal, and it now has "
<< my_signal.num_slots()
<< " subscibers." << std::endl;
my_signal(2);
return 0;
}
expected output:
Created signal, and it has 0 subscribers.
Subscribed to signal, and it has 1 subsciber.
Called foo::bar with 1
Un-Subscribed to signal, and it still has 0 subscibers.
I do disconnect from a boost::signal2::signal using boost::signals2::connection object returned by connect method.

Can't connect to MongoDB from the C++ code

Windows 7, msys2, compiler MinGW
Trying to connect to the MongoDB instance from the C++ code. Running mongod with the next command:
mongod --dbpath ./dev-db --bind_ip 127.0.0.1 --port 27017
I can normally connect to this database by mongo and in Robomongo.
For the c++ code, I successfully compiled and installed tha last stable Mongo C++ Driver. Code I take from the official tutorial:
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
mongocxx::uri uri("mongodb://127.0.0.1:27017");
mongocxx::client conn{uri};
auto db = conn["test"];
bsoncxx::document::value restaurant_doc =
document{} << "address" << open_document << "street"
<< "2 Avenue"
<< "zipcode"
<< "10075"
<< "building"
<< "1480"
<< "coord" << open_array << -73.9557413 << 40.7720266 << close_array
<< close_document << "borough"
<< "Manhattan"
<< "cuisine"
<< "Italian"
<< "grades" << open_array << open_document << "date"
<< bsoncxx::types::b_date{std::chrono::milliseconds{12323}} << "grade"
<< "A"
<< "score" << 11 << close_document << open_document << "date"
<< bsoncxx::types::b_date{std::chrono::milliseconds{121212}} << "grade"
<< "B"
<< "score" << 17 << close_document << close_array << "name"
<< "Vella"
<< "restaurant_id"
<< "41704620" << finalize;
auto res = db["restaurants"].insert_one(std::move(restaurant_doc))
And this provide the next error:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of 'mongocxx::v_noabi::bulk_write_exception'
what(): No suitable servers found (`serverSelectionTryOnce` set): [Failed to resolve '127.0.0.1']: generic server error
How can I avoid this issue and connect to the database?
Your copy is missing the first line of the example:
mongocxx::instance inst{};
See http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/#make-a-connection. The mongocxx::instance constructor and destructor initialize and shut down the driver, respectively, so a mongocxx::instance must be created before using the driver and must remain alive for as long as the driver is in use.
It looks like it is attempting a DNS lookup of 127.0.0.1. Try changing it to be localhost instead (which will resolve to the same IP)
mongocxx::uri uri("mongodb://localhost:27017");

How do I use CUDA driver functions?

I have a GUI application with a producer thread and an OpenGL thread, the OpenGL thread needs to call CUDA functions and the producer needs to call cudaMemcpy etc.
No matter what I do I can't seem to get the CUDA driver api to work. Every time I try to use these function I get a cudaErrorMissingConfiguration.
I want to use multi-threaded CUDA, what is the paradigmatic way to accomplish this?
Original
void program::initCuda()
{
CUresult a;pctx=0;
cudaSafeCall(cudaSetDevice(0));
cudaSafeCall(cudaGLSetGLDevice(0));
a=cuInit(0);
cudaSafeCall(cudaFree(0));
cout <<"cuInit :" <<a << endl;assert(a == cudaSuccess);
//a=cuCtxGetCurrent(pctx);
a=cuCtxCreate(pctx,CU_CTX_SCHED_AUTO,0);
cout <<"GetContext :" <<a << endl;assert(a == cudaSuccess);
//Fails with cudaErrorMissingConfiguration
a=cuCtxPopCurrent(pctx);
cout <<"cuCtxPopCurrent :" <<a << endl;assert(a == cudaSuccess);
cout <<"Initialized CUDA" << endl;
}
Revised
void glStream::initCuda()
{
CUresult a;
pctx=0;
cudaSafeCall(cudaSetDevice(0));
cudaSafeCall(cudaGLSetGLDevice(0));
cudaFree(0);// From post http://stackoverflow.com/questions/10415204/how-to-create-a-cuda-context seems to indicate that `cudaSetDevice` should make a context.
a=cuCtxGetCurrent(pctx);
cout <<"GetContext :" <<a << endl;assert(a == cudaSuccess);
a=cuCtxPopCurrent(pctx);
cout <<"cuCtxPopCurrent :" <<a << endl;assert(a == cudaSuccess);
cout <<"Initialized CUDA" << endl;
}
The simplest version of your second code should look like this:
#include <iostream>
#include <assert.h>
#include <cuda.h>
#include <cuda_runtime.h>
int main(void)
{
CUresult a;
CUcontext pctx;
cudaSetDevice(0); // runtime API creates context here
a = cuCtxGetCurrent(&pctx);
std::cout << "GetContext : " << a << std::endl;
assert(a == CUDA_SUCCESS);
a = cuCtxPopCurrent(&pctx);
std::cout << "cuCtxPopCurrent : " << a << std::endl;
assert(a == CUDA_SUCCESS);
std::cout << "Initialized CUDA" << std::endl;
return 0;
}
which yields the following on OS X 10.6 with CUDA 5.0:
$ g++ -I/usr/local/cuda/include -L/usr/local/cuda/lib driver.cc -lcuda -lcudart
$ ./a.out
GetContext :0
cuCtxPopCurrent :0
Initialized CUDA
ie. "just works". Here the context is lazily initiated by the cudaSetDevice call (note I incorrectly asserted that cudaSetDevice doesn't establish a context, but at least in CUDA 5 it appears to. This behaviour may have changed when the runtime API was revised in CUDA 4).
Alternatively, you can use the driver API to initiate the context:
#include <iostream>
#include <assert.h>
#include <cuda.h>
#include <cuda_runtime.h>
int main(void)
{
CUresult a;
CUcontext pctx;
CUdevice device;
cuInit(0);
cuDeviceGet(&device, 0);
std::cout << "DeviceGet : " << a << std::endl;
cuCtxCreate(&pctx, CU_CTX_SCHED_AUTO, device ); // explicit context here
std::cout << "CtxCreate : " << a << std::endl;
assert(a == CUDA_SUCCESS);
a = cuCtxPopCurrent(&pctx);
std::cout << "cuCtxPopCurrent : " << a << std::endl;
assert(a == CUDA_SUCCESS);
std::cout << "Initialized CUDA" << std::endl;
return 0;
}
which also "just works":
$ g++ -I/usr/local/cuda/include -L/usr/local/cuda/lib driver.cc -lcuda -lcudart
$ ./a.out
DeviceGet : 0
CtxCreate : 0
cuCtxPopCurrent : 0
Initialized CUDA
What you shouldn't do is mix both as in your first example. All I can suggest is try both of these and confirm they work for you, then adopt the call sequences to whatever it is you are actually trying to achieve.