how to set a flag (cpp-netlib) - c++

I think my question is really trivial, but I can't get it to work nonetheless
std::string url="www.google.it";
boost::network::http::client client1_(_follow_redirects=true, _cache_resolved=true);
boost::network::http::client::request req(url);
boost::network::http::client::response resp = client1_.get(req);
std::cout << "Body: " << body(resp) << std::endl;
return 0;
the error of course refers to the declaration of the flags...but how can I set them?
/home/snake91/cpp_pricing/underlying.cpp:67: error: C++ requires a type specifier for all declarations
boost::network::http::client client1_(_follow_redirects=true, _cache_resolved=true);
^

client::options options;
options.follow_redirects(true)
.cache_resolved(true);
client client1_(options);
From this page of the docs: http://cpp-netlib.org/0.11.0/reference/http_client.html#general

Related

Could not found the resource definition:BinOcaf.StoragePlugin?

I have the following code, and can be compiled, but when I run it, it fails with error of missing resource.
I have checked the cascade installer and everything is clicked and installed. How could I fix this?
#include <TDocStd_Application.hxx>
#include <TDataStd_Integer.hxx>
int main()
{
Handle(TDocStd_Application) app = new TDocStd_Application;
Handle(TDocStd_Document) doc;
app->NewDocument("BinOcaf", doc);
if (doc.IsNull())
{
std::cout << "Error: cannot create an OCAF document." << std::endl;
return 1;
}
// to access the main label, the transient data framework
TDF_Label mainLab = doc->Main();
// attach some integer value to this label
TDataStd_Integer::Set(mainLab, 1002);
// save document to file
PCDM_StoreStatus sstatus = app->SaveAs(doc, "C:/Users/Administrator/Desktop/test.cbf");
if (sstatus != PCDM_SS_OK)
{
app->Close(doc);
std::cout << "cannot write OCAF document." << std::endl;
return 1;
}
// release the data of doc
app->Close(doc);
return 0;
}
Ok, so after some head scratching I realized one thing. Forgot to define format.
just add the line of code to the main function would fix the problem.
BinDrivers::DefineFormate(app);

What's the equivalent of numpy.spacing(1) in libtorch?

It seems pytorch does have/expose the finfo link, but I can't find it in libtorch. Is it even made available in libtorch yet or not? Using the torch.finfo I could easily do:
esp = torch.finfo(torch.float).eps
which I believe is the counterpart/equivalent of np.spacing(1) but in libtorch I can't do the same thing as I can not find any trace of finfo class. What should I do?
There is a TypeInfo.cpp module (pytorch/torch/csrc/TypeInfo.cpp), unfortunately the method you mentioned (torch.finfo(torch.float).eps) seems to be private, as it's marked static within a translation unit:
static PyObject* THPFInfo_eps(THPFInfo* self, void*) {
return AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(at::kHalf, at::ScalarType::BFloat16,
self->type, "epsilon", [] {
return PyFloat_FromDouble(
std::numeric_limits<
at::scalar_value_type<scalar_t>::type>::epsilon());
});
}
But, within the corresponding header, there's an extern declaration:
extern PyTypeObject THPFInfoType;
THPFInfoType seems to be an instance which contains a pointer for the following function: THPFInfo_str. This function, on the other hand, prints the following:
PyObject* THPFInfo_str(THPFInfo* self) {
std::ostringstream oss;
oss << "finfo(resolution=" << PyFloat_AsDouble(THPFInfo_resolution(self, nullptr));
oss << ", min=" << PyFloat_AsDouble(THPFInfo_min(self, nullptr));
oss << ", max=" << PyFloat_AsDouble(THPFInfo_max(self, nullptr));
oss << ", eps=" << PyFloat_AsDouble(THPFInfo_eps(self, nullptr));
oss << ", tiny=" << PyFloat_AsDouble(THPFInfo_tiny(self, nullptr));
oss << ", dtype=" << PyUnicode_AsUTF8(THPFInfo_dtype(self, nullptr)) << ")";
return THPUtils_packString(oss.str().c_str());
}
Which apparently prints eps information. Maybe you could somehow link your target with TypeInfo.cpp and make use of above definitions?
It turns out, we can simply use std::nextafter just fine. And also torch::nextafter is recently added (#42580) and uses this under the hood!
So if you don't use nighlybuilds, and until 1.7 ships, you can simply use std::nextafter just fine! Concerning the THPFinfo:
THPFInfo and THPFInfo_eps exist to make this information available in
python
Source

Error handling design: Bind error messages to error codes

I have a simple structures to handle errors
enum class Error
{
None = 0,
FirstError,
SecondError,
ThirdError,
...
}
struct ErrorCategory
{
static const std::string& Message(Error aError)
{
static const std::string messages[] =
{
"first error message",
"second error message",
"third error message",
...
}
const auto index = static_cast<size_t>(aError);
assert(index < std::size(messages) && "Invalid error");
return messages[index];
}
};
Also, there are some class and methods to work with those structures.
Though it works, but the amount of errors is growing, so it becomes hard to navigate between error messages and error codes in enum. I want to declare error code and message for it in one place to make it easy to find error code. Is there a way to do it without making my code huge (such as enum + switch cases for messages) so it would be easy to maintain and without using macro?
You can use std::map<Error, std::string> like:
enum class Error : uint8_t {
None = 0,
FirstError = 1,
SecondError = 2,
ThirdError = 3
};
std::map<Error, std::string> error_messages = {
{ Error::None, "unknown error message" },
{ Error::FirstError, "first error message" },
{ Error::SecondError, "second error message" },
{ Error::ThirdError, "third error message" }
};
and then use it afterwards like:
std::cerr << error_messages[Error::None] << std::endl;
std::cerr << error_messages[Error::FirstError] << std::endl;
std::cerr << error_messages[Error::SecondError] << std::endl;
std::cerr << error_messages[Error::ThirdError] << std::endl;
Demo
This type of operation is exactly how most localized UIs work. You map some common structured ID to a user-facing string.
Because of this, there are a huge amount of platform-specific ways of doing this which aim to do exactly what you want. For example on Windows:
(Windows) FormatMessage and Message Compiler
(Windows / .NET) .resx files and ResourceManager

How to use a void* in C++ to hold the value of an uint32_t when the pointer is passed as a reference to a method

I am having issues storing values into a void* and successfully retrieving what I stored in initially. The below is my pseudo code/train of thought:
Inside method 1 on a client
StatusCode doSomething() {
string filename = "somefile.txt";
void* server_checksum;
//Stat signature (string &filename, void* file_status)
StatusCode fileStatus = Stat(filename, &server_checksum); //Passing the address of the pointer
//We received the fileStatus from Stat, I expect the value of server_checksum to match what the server sent
//However, this prints a completely different number, and I do not know how to ensure it holds the right value
cout << *((uint32_t *)serverCrc) << endl;
return StatusCode::OK;
}
Inside the Stat method on the client, there's a protobuf via grpc that has the checksum for the file on the server:
StatusCode Stat(string &filename, void* file_status) {
//call the grpc method on the server (abstracted)
.
.
.
//Contains the checksum of the file on the server - this works fine
uint32_t s_crc = response.server_crc();
// I print it in both the server and the client to confirm it is the same value - this works fine
cout << s_crc << endl;
//In my understanding, here I am assigning the value of s_crc to the void * file status, which I passed the address for inside of method 1 - this works fine
file_status = (uint32_t *) &s_crc;
// I print file_status to make sure it still matches the value the server sent - this works fine
cout<<"file_status " << *((uint32_t *)file_status) << endl;
return StatusCode::OK; -> Continues inside method 1 above
}
There's no reason to use a void* here at all. C++ has a type system; you should use it.
Instead of declaring your out parameter as a void*, declare it to be either a pointer or reference to the type you want to write. In this case that appears to be uint32_t:
StatusCode Stat(const std::string& filename, uint32_t& file_status) {
//call the grpc method on the server (abstracted)
// ...
//Contains the checksum of the file on the server - this works fine
file_status = response.server_crc();
return StatusCode::OK;
}
And then you can call it without doing any special gymnastics:
StatusCode doSomething() {
std::string filename = "somefile.txt";
uint32_t server_checksum;
StatusCode fileStatus = Stat(filename, server_checksum);
std::cout << server_checksum << std::endl;
return StatusCode::OK;
}
Live Demo
If there's some reason you must use a void* and thus explicitly give up the protections offered by the type system then the pointer still has to point to something. In the end the code will look very similar, just with an extra cast and significantly more opportunity to mess up and wander into the realm of undefined behavior:
StatusCode Stat(const std::string& filename, void* file_status) {
//call the grpc method on the server (abstracted)
// ...
// cast to the appropriate pointer type
uint32_t* status_ptr = static_cast<uint32_t*>(file_status);
// now write the status to the object pointed to by the pointer passed to us
*status_ptr = response.server_crc();
return StatusCode::OK;
}
Not much extra is needed when calling the function, since any pointer-to-object type can be implicitly converted to void*:
StatusCode doSomething() {
std::string filename = "somefile.txt";
uint32_t server_checksum;
StatusCode fileStatus = Stat(filename, &server_checksum);
std::cout << server_checksum << std::endl;
return StatusCode::OK;
}
Live Demo

Convenient method in GoogleTest for a double comparison of not equal?

I'm looking for something similar to the ASSERT_EQ / ASSERT_NE for ASSERT_DOUBLE_EQ.
Maybe I'm missing an easy way of doing this without having a ASSERT_DOUBLE_NE?
You can use the companion mocking framework Google Mock. It has a powerful library of matchers (a la Hamcrest), which you can use with the EXPECT_THAT/ASSERT_THAT macros:
EXPECT_THAT(value, FloatEq(1));
EXPECT_THAT(another_value, Not(DoubleEq(3.14)));
It looks like you're out of luck. However, you could add one yourself. I built the following code using ASSERT_DOUBLE_EQ and ASSERT_NE as a pattern.
#define ASSERT_DOUBLE_NE(expected, actual)\
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointNE<double>, \
expected, actual)
// Helper template function for comparing floating-points.
//
// Template parameter:
//
// RawType: the raw floating-point type (either float or double)
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename RawType>
AssertionResult CmpHelperFloatingPointNE(const char* expected_expression,
const char* actual_expression,
RawType expected,
RawType actual) {
const FloatingPoint<RawType> lhs(expected), rhs(actual);
if ( ! lhs.AlmostEquals(rhs)) {
return AssertionSuccess();
}
StrStream expected_ss;
expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< expected;
StrStream actual_ss;
actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< actual;
Message msg;
msg << "Expected: (" << expected_expression << ") != (" << actual_expression
<< "), actual: (" << StrStreamToString(expected_ss) << ") == ("
<< StrStreamToString(actual_ss) << ")";
return AssertionFailure(msg);
}
instead of creating a new CmpHelperFloatingPointNE helper, you can just define the macro as the inverse of the existing helper:
#include "gtest/gtest.h"
#define ASSERT_FLOAT_NE(val1, val2) ASSERT_PRED_FORMAT2( \
!::testing::internal::CmpHelperFloatingPointEQ<float>, val1, val2 \
)
#define ASSERT_DOUBLE_NE(val1, val2) ASSERT_PRED_FORMAT2( \
!::testing::internal::CmpHelperFloatingPointEQ<double>, val1, val2 \
)
This is not as graceful as deft_code's solution because when the assertion fails, there are no specific details like "expected value" and "actual value", just the line number and file of the assertion. For my purposes, though, the line number was enough.