Handling CLIPS C functions' return values as string(s) - clips

I'm calling CLIPS Eval() and other functions from my C code and need help understanding how to handle return values that are CLIPSValue or UDFValue. A simple example ...
...
CLIPSValue cv;
UDFValue uv;
EvalError ee;
LoadError le;
entry->env = CreateEnvironment();
le = Load(entry->env, filePathBuffer);
if (le != LE_NO_ERROR)
{
// report the load error ...
}
// Tried this but having trouble handling cv: GetDeftemplateList(entry->env, &cv, NULL);
// Trying with Eval ...
ee = Eval(entry->env, "(list-deftemplates)", &cv);
printf("%d -- %hi -- %ld -- %s", ee, cv.multifieldValue->header.type, cv.multifieldValue->length, cv.multifieldValue->lexemeValue->contents);
...
... the above printf is broken because I'm not correctly understanding cv structure/union.
Also looking into using DataObjectToString(...) but can't see how to convert CLIPSValue to UDFValue which DataObjectToString(...) needs as input.
Further processing of the result is needed, so using something like WriteCLIPSValue(...) isn't sufficient.
Would it be possible to use a router other than STDOUT with WriteCLIPSValue(...) and similar functions to only format response strings sort of like sprintf(...)?
I'm open to whatever approach is best but prefer simple/minimal C code.

This is the code fragment for iterating over the multifield value return by GetDeftemplateList and printing the string values contained in the multifield:
GetDeftemplateList(entry->env,&cv,NULL);
for (i = 0; i < cv.multifieldValue->length; i++)
{
WriteString(mainEnv,STDOUT,cv.multifieldValue->contents[i].lexemeValue->contents);
WriteString(mainEnv,STDOUT,"\n");
}
In the most general case, you'd want to verify that cv.header->type is actually a multifield and cv.multifieldValue->contents[i].header->type is a symbol or string before pulling values out of the multifieldValue or lexemeValue unions, but in this case we know that's what GetDeftemplateList is going to return.

Related

storing a function that was retrieved from FunctionCallbackInfo

I'm pretty much trying to make a AddInputEvent but, after a month, can't find a way to turn a local "function from FunctionCallbackInfo"(i'll just call this argf) in to a Persistent Function so that garbage collection doesn't erase the pointers.
Most stakeoverflow threads and example code I can find just say to Cast argf with a Local Function; then to throw that in to a Persistent New. This results in a error: cannot convert 'v8::Local<v8::Function>' to 'v8::Function*'
here is the code, not completely sure why I can't convert it
class inputevnt_feld{
public:
char* call_on;
v8::Persistent<v8::Function> func;
};
int entvcount = -1;
vector<inputevnt_feld> event_calls; //this is pretty much a array of events that we can call later
// in js looks like this "AddInputEvent("string", function);"
void AddInputEvent( const v8::FunctionCallbackInfo<v8::Value>& args ) {
v8::HandleScope handle_scope(args.GetIsolate());
//gotta make sure that we ain't letting in some trojan horse that has nothing in it
if (args[1]->IsFunction() && args[0]->IsString()) {
inputevnt_feld newt;
//converts js string to char array
v8::String::Utf8Value str(args.GetIsolate(), args[0]);
const char* cstr = ToCString(str);
newt.call_on = (char*)cstr;
//here is where the problem is with function casting
v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[1]);
newt.func = v8::Persistent<v8::Function>::New(args.GetIsolate(), callback);
//push the new stuff in to even array
event_calls.push_back(newt);
//getting vector array size is too much for my smol brain
//so I'ma just do this myself
entvcount++;
//cout << event_calls[entvcount].call_on << endl; //debug
}
}
Most stakeoverflow threads and example code I can find just say to Cast argf with a Local Function; then to throw that in to a Persistent New
Yes, that's correct. If you know how to read it, the C++ type system is your friend for figuring out the details.
If you look at the definition of v8::PersistentBase<T>::New, you'll see that it takes a T* (for its template type T). If you look at the v8::Local<T> class, you'll see that a way to get a T* from it is to use its operator*. That leads to:
v8::Local<v8::Function> callback = ...Cast(args[1]);
... = v8::Persistent<v8::Function>::New(..., *callback);
Alternatively, you can use the Persistent constructor directly, and pass it the Local without dereferencing it first:
v8::Local<v8::Function> callback = ...Cast(args[1]);
... = v8::Persistent<v8::Function>(..., callback);
Both options are entirely equivalent. Personally I'd prefer the latter as it takes slightly fewer characters to spell out, but that's really the only difference.
(Your current code as posted does something else: it ignores the result of the cast and passes the original args[1] directly to Persistent::New -- that's not going to work.)

Dynamic JavaFX buttons action [duplicate]

I want to be able to do something like this:
for(i = 0; i < 10; i++) {
//if any button in the array is pressed, disable it.
button[i].setOnAction( ae -> { button[i].setDisable(true) } );
}
However, I get a error saying "local variables referenced from a lambda expression must be final or effectively final". How might I still do something like the code above (if it is even possible)? If it can't be done, what should be done instead to get a similar result?
As the error message says, local variables referenced from a lambda expression must be final or effectively final ("effectively final" meaning the compiler can make it final for you).
Simple workaround:
for(i = 0; i < 10; i++) {
final int ii = i;
button[i].setOnAction( ae -> { button[ii].setDisable(true) } );
}
Since you are using lambdas, you can benefit also from other features of Java 8, like streams.
For instance, IntStream:
A sequence of primitive int-valued elements supporting sequential and parallel aggregate operations. This is the int primitive specialization of Stream.
can be used to replace the for loop:
IntStream.range(0,10).forEach(i->{...});
so now you have an index that can be used to your purpose:
IntStream.range(0,10)
.forEach(i->button[i].setOnAction(ea->button[i].setDisable(true)));
Also you can generate a stream from an array:
Stream.of(button).forEach(btn->{...});
In this case you won't have an index, so as #shmosel suggests, you can use the source of the event:
Stream.of(button)
.forEach(btn->btn.setOnAction(ea->((Button)ea.getSource()).setDisable(true)));
EDIT
As #James_D suggests, there's no need of downcasting here:
Stream.of(button)
.forEach(btn->btn.setOnAction(ea->btn.setDisable(true)));
In both cases, you can also benefit from parallel operations:
IntStream.range(0,10).parallel()
.forEach(i->button[i].setOnAction(ea->button[i].setDisable(true)));
Stream.of(button).parallel()
.forEach(btn->btn.setOnAction(ea->btn.setDisable(true)));
Use the Event to get the source Node.
for(int i = 0; i < button.length; i++)
{
button[i].setOnAction(event ->{
((Button)event.getSource()).setDisable(true);
});
}
Lambda expressions are effectively like an annonymous method which works on stream. In order to avoid any unsafe operations, Java has made that no external variables which can be modified, can be accessed in a lambda expression.
In order to work around it,
final int index=button[i];
And use index instead of i inside your lambda expression.
You say If the button is pressed, but in your example all the buttons in the list will be disabled. Try to associate a listener to each button rather than just disable it.
For the logic, do you mean something like that :
Arrays.asList(buttons).forEach(
button -> button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setEnabled(false);
}
}));
I Also like Sedrick's answer but you have to add an action listener inside the loop .

Why protobuf serialize "oneof" message use if-else

I has a Message define like this:
message Command{
oneof type{
Point point = 1;
Rotate rotate = 2;
Move move = 3;
... //about 100 messages
}
}
Then protoc generate the SerializeWithCachedSizes function:
void Command::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// ##protoc_insertion_point(serialize_start:coopshare.proto.Command)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .coopshare.proto.Point point = 1;
if (has_point()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *type_.point_, output);
}
// .coopshare.proto.Rotate rotate = 2;
if (has_rotate()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *type_.rotate_, output);
}
// .coopshare.proto.Move move = 3;
if (has_move()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *type_.move_, output);
}
The "oneof" message saves the specific type in _oneof_case_. I think using switch-case is more efficient.
But why protobuf still generate code like this?
Oneofs are internally handled similar to optional fields. In fact, descriptor.proto represents them as a set of optional fields that just have an extra oneof_index to indicate that they belong together. This is a reasonable choice, because it allowed oneofs to be used immediately with many libraries before any special support was added.
I assume that the C++ code generator uses the same structure for both optional fields and oneofs.
It is possible that switch-case could generate more efficient code, and in that case it would be useful to propose that as an improvement to the protobuf project. However, like Jorge Bellón pointed out in the comments, it is entirely possible that the compiler will be able to optimize this structure automatically. One would have to test and benchmark to be sure.

When to use ostream_iterator

As I know, we can use ostream_iterator in c++11 to print a container.
For example,
std::vector<int> myvector;
for (int i=1; i<10; ++i) myvector.push_back(i*10);
std::copy ( myvector.begin(), myvector.end(), std::ostream_iterator<int>{std::cout, " "} );
I don't know when and why we use the code above, instead of traditional way, such as:
for(const auto & i : myvector) std::cout<<i<<" ";
In my opinion, the traditional way is faster because there is no copy, am I right?
std::ostream_iterator is a single-pass OutputIterator, so it can be used in any algorithms which accept such iterator. The use of it for outputing vector of int-s is just for presenting its capabilities.
In my opinion, the traditional way is faster because there is no copy, am I right?
You may find here: http://en.cppreference.com/w/cpp/algorithm/copy that copy is implemented quite similarly to your for-auto loop. It is also specialized for various types to work as efficient as possible. On the other hand writing to std::ostream_iterator is done by assignment to it, and you can read here : http://en.cppreference.com/w/cpp/iterator/ostream_iterator/operator%3D that it resolves to *out_stream << value; operation (if delimiter is ignored).
You may also find that this iterator suffers from the problem of extra trailing delimiter which is inserted at the end. To fix this there will be (possibly in C++17) a new is a single-pass OutputIterator std::experimental::ostream_joiner
A short (and maybe silly) example where using iterator is usefull. The point is that you can direct your data to any sink - a file, console output, memory buffer. Whatever output you choose, MyData::serialize does not needs changes, you only need to provide OutputIterator.
struct MyData {
std::vector<int> data = {1,2,3,4};
template<typename T>
void serialize(T iterator) {
std::copy(data.begin(), data.end(), iterator);
}
};
int main()
{
MyData data;
// Output to stream
data.serialize(std::ostream_iterator<int>(std::cout, ","));
// Output to memory
std::vector<int> copy;
data.serialize(std::back_inserter(copy));
// Other uses with different iterator adaptors:
// std::front_insert_iterator
// other, maybe custom ones
}
The difference is polymorphism vs. hardcoded stream.
std::ostream_iterator builds itself from any class which inherits from std::ostream, so in runtime, you can change or wire the iterator to write to difference output stream type based on the context on which the functions runs.
the second snippet uses a hardcoded std::cout which cannot change in runtime.

How to check if value is number in Varnish?

Cookie String Example:
session=9urt2jipvkq77brfrf; MyId=124 ; PageId=134
I'm using Varnish version 4.1. In the following code, I extract the value of MyId (124) and PageId (134) from the cookie string and then check if the values are the same. If it is, return pass and don't serve cache content. The problem is that anonymous visitors will not have these two cookies in place unless they sign up, and it will accidentally pass the condition and not cache because both values will return the same value session=9urt2jipvkq77brfrf with the regsub function. I want to make sure that both values are entirely number. Is there any function handy for that?
Code:
if(req.http.Cookie){
set req.http.MyId = regsub(req.http.Cookie,".*MyId=(\d+).*","\1");
set req.http.PageId = regsub(req.http.Cookie,".*PageId=(\d+).*","\1");
if(req.http.MyId == req.http.PageId){
return (pass);
}
}
There isn't a handy function like "is_integer" or similar. But you can check it with regular expressions.
This will match any sequence of numbers:
req.http.MyId ~ "[0-9]+"
Or you can match only 3 numbers:
req.http.MyId ~ "[0-9][0-9][0-9]"
You can do it in a vmod or inline C. Here is an inline C example testing a header value:
sub vcl_backend_response
{
// Check some value from your backend server response
if (beresp.http.X-MyCustom-Header)
{
C{
syslog(LOG_ERR, "Received a X-MyCustom-Header");
char *val_to_test;
const struct gethdr_s hdr = { HDR_BERESP, "\022X-MyCustom-Header:" };
val_to_test = VRT_GetHdr(ctx, &hdr);
int val_int = atoi(val_to_test); // or whatever C functions
syslog(LOG_ERR, "My int value was: %d", val_int);
}C
}
...
}
Normally you would package all of that inline C into a vmod and make your life easier but it can be useful for testing before moving to a vmod.

Resources