Apache ignite continuous query for sqlfieldQuery in c++ - c++

We are using Apache Ignite SqlFieldQuery. Does continuous query supports SqlFieldQuery? Am looking for some example related to this.
Query looks like:
Cache<int32_t, std::string> cache =
ignite.GetOrCreateCache<int32_t, std::string>(CACHE_NAME);
std::string sql("INSERT INTO \"DG\".TestList (empid,name) values(11, 'name')");
SqlFieldsQuery orgQry(sql);
cache.Query(orgQry);
How to get notification for above query using continuous query ?

You can use simple ContinuousQuery for that. Something like this:
// Assuming your key type is int32_t
class Listener : public event::CacheEntryEventListener<int32_t, TestList>
{
public:
virtual void OnEvent(const CacheEntryEvent<int32_t, TestList>* evts, uint32_t num)
{
// Simply printing events here. You can put your processing code here.
for (uint32_t i = 0; i < num; ++i)
{
std::cout << "Queried entry [key=" << evts[i].GetKey()
<< ", val=" << (evts[i].HasValue() ? evts[i].GetValue() : "<none>")
<< ']' << std::endl;
}
}
};
int main()
{
Ignite ignite = Ignition::Start(cfg);
Cache<int32_t, TestList> cache =
ignite.GetOrCreateCache<int32_t, TestList>(CACHE_NAME);
// Declaring listener.
Listener<int32_t, TestList> listener;
// Declaring continuous query.
continuous::ContinuousQuery<int32_t, TestList> qry(MakeReference(listener));
continuous::ContinuousQueryHandle<int32_t, TestList> handle =
cache.QueryContinuous(qry);
std::string sql("INSERT INTO \"DG\".TestList (empid,name) values(11, 'name')");
SqlFieldsQuery orgQry(sql);
cache.Query(orgQry);
// Waiting here to get notifications.
std::cin.get();
return 0;
}
I've skipped some boilerplate code. You may find fully functional code example here

Related

QLibrary functions work slow on first call

I'm using QLibrary to load functions from one .dll file.
I succesfully load it, succesfully resolve functions.
But when i use some function from that .dll for the first time, this function works very slow(even if it is very simple one). Next time i use it again - and the speed is just fine (immediately, as it should be).
What is the reason for such behaviour? I suspect some caсhing somewhere.
Edit 1: Code:
typedef int(*my_type)(char *t_id);
QLibrary my_lib("Path_to_lib.dll");
my_lib.load();
if(my_lib.isLoaded){
my_type func = (my_type)my_lib.resolve("_func_from_dll");
if(func){
char buf[50] = {0};
char buf2[50] = {0};
//Next line works slow
qint32 resultSlow = func(buf);
//Next line works fast
qint32 resultFast = func(buf2);
}
}
I wouldn't blame QLibrary: func simply takes long the first time it's invoked. I bet that you'll have identical results if you resolve its address using platform-specific code, e.g. dlopen and dlsym on Linux. QLibrary doesn't really do much besides wrapping the platform API. There's nothing specific to it that would make the first call slow.
There is some code smell of doing file I/O in constructors of presumably generic classes: do the users of the class know that the constructor may block on disk I/O and thus ideally shouldn't be invoked from the GUI thread? Qt makes the doing this task asynchronously fairly easy, so I'd at least try to be nice that way:
class MyClass {
QLibrary m_lib;
enum { my_func = 0, other_func = 1 };
QFuture<QVector<FunctionPointer>> m_functions;
my_type my_func() {
static my_type value;
if (Q_UNLIKELY(!value) && m_functions.size() > my_func)
value = reinterpret_cast<my_type>(m_functions.result().at(my_func));
return value;
}
public:
MyClass() {
m_lib.setFileName("Path_to_lib.dll");
m_functions = QtConcurrent::run{
m_lib.load();
if (m_lib.isLoaded()) {
QVector<QFunctionPointer> funs;
funs.push_back(m_lib.resolve("_func_from_dll"));
funs.push_back(m_lib.resolve("_func2_from_dll"));
return funs;
}
return QVector<QFunctionPointer>();
}
}
void use() {
if (my_func()) {
char buf1[50] = {0}, buf2[50] = {0};
QElapsedTimer timer;
timer.start();
auto result1 = my_func()(buf1);
qDebug() << "first call took" << timer.restart() << "ms";
auto result2 = my_func()(buf2);
qDebug() << "second call took" << timer.elapsed() << "ms";
}
}
};

C++ member of class updated outside class

I have a question about pointers and references in C++. I am a programmer who normally programs in C# and PHP.
I have two classes (for now) which are the following.
The X/Y in Controller are continuously changing but i want them up to date in the Commands. I have multiple commands like Forward, Turn, Backward etc.
When i make the commands i give them the controller but the state (X, Y) of the controller are updating every second.
How can i fix that the controller attribute in the Commands are getting updated also every second?
class Forward : ICommand
{
Controller ctrl;
void Execute() {
int CurrentX = ctrl.X;
int CurrentY = ctrl.Y;
//Check here for the current location and calculate where he has to go.
}
}
class Controller
{
int X;
int Y;
void ExecuteCommand(ICommand command) {
command.Execute();
}
}
Main.cpp
Controller controller;
Forward cmd1 = new Forward(1, controller);
Turn cmd2 = new Turn(90, controller);
Forward cmd3 = new Forward(2, controller);
controller.Execute(cmd1);
controller.Execute(cmd2);
controller.Execute(cmd3);
I have read something about pointers and references and i think i have to use this but don't know how to use it in this situation.
(code can have some syntax errors but that's because i typed over. Everything is working further except for the updating).
If you use references rather than copy objects you can see changes.
#include <iostream>
using namespace std;
class ICommand
{
public:
virtual ~ICommand() = default;
virtual void Execute() = 0;
};
class Controller
{
public:
int X = 0;
int Y = 0;
void ExecuteCommand(ICommand & command) {
// ^-------
command.Execute();
}
};//,--- semicolons required
class Forward : public ICommand //note public
{
const int step;
Controller ctrlCopy;
Controller & ctrlReference;
public:
Forward(int step, Controller & ctrl) :
step(step),
ctrlCopy(ctrl), //this is a copy of an object
ctrlReference(ctrl) //this is a reference to an object
{
}
void Execute() {
std::cout << "copy: " << ctrlCopy.X << ", " << ctrlCopy.Y << '\n';
std::cout << " ref: " << ctrlReference.X << ", " << ctrlReference.Y << '\n';
//Check here for the current location and calculate where he has to go.
ctrlCopy.X += 10;
ctrlReference.X += 10;
}
};//<--- semicolons required
int main() {
Controller controller;
Forward cmd1(1, controller);
//Turn cmd2(90, controller); //Left for the OP to do
Forward cmd3(2, controller);
controller.ExecuteCommand(cmd1);
//controller.ExecuteCommand(cmd2);
controller.ExecuteCommand(cmd3);
//Do it again to show the copy and reference difference
std::cout << "Once more, with feeling\n";
controller.ExecuteCommand(cmd1);
controller.ExecuteCommand(cmd3);
}
Giving
copy: 0, 0
ref: 0, 0
copy: 0, 0 // [1]
ref: 10, 0 // [2]
Once more, with feeling
copy: 10, 0
ref: 20, 0
copy: 10, 0
ref: 30, 0
1 shows that the copy has X and Y of 0, while the reference shown in [2] has moved by the stated step (in controller.ExecuteCommand(cmd3))
Note, we don't need to use new to make this work (don't forget delete if you use new).
Also, void ExecuteCommand(ICommand command) now takes a reference instead otherwise the by-value copy does "slicing" (e.g. see here)

Is it better to sort from server and distribute to clients or send unsorted and let clients sort it?

This is an online game and I was paid to implement a game event, which is a Player versus Player game system.
In my design I have a server side class (named PvpEventManager which is the event manager and it processes when a player kills another one, when a player joins or leaves the event, be it by decision, by being disconnected...etc, and has many other functions.
Now, this class also holds a container with the player information during the event (named vPlayerInfo), for all kinds of processing. When a player kills someone else, his kill must be increased and the victim's death too, quite obviously. But it also happens that clients have a scoreboard and since it's the server job to process a kill and tell all other clients connected on the event about this, the container will get updated.
It is necessary that the container be sorted from kill struct member from ascending to descending order so that the scoreboard can be rendered (at client) properly.
What would be better?
To sort the container at server increasing server work and send the already-sorted ready-to-render-at-screen container to all clients.
To send the container unsorted and let every connected game client sort the container itself when receiving it.
Note that the server processes thousands of thousands of packets incoming and outcoming every tick and really processes A LOT, A LOT of other stuff.
This somewhat describes the design of it:
This code describes what is being done when sorting the container on part of the actual code.
#include <iostream>
#include <array>
#include <vector>
#include <map>
#include <algorithm>
struct PlayerScoreBoardInfo
{
std::string name;
unsigned int kill, death, suicide;
unsigned int scorestreak;
PlayerScoreBoardInfo()
{
kill = death = suicide = scorestreak = 0;
name = "";
}
explicit PlayerScoreBoardInfo( std::string strname, unsigned int nkill, unsigned int ndeath, unsigned int nsuicide, unsigned int nscorestreak ) :
name(strname), kill(nkill), death(ndeath), suicide(nsuicide), scorestreak(nscorestreak)
{
}
};
class GameArenaManager
{
private:
GameArenaManager() {}
public:
std::map<u_long, PlayerScoreBoardInfo> m_Infos;
public:
static GameArenaManager& GetInstance()
{
static GameArenaManager InstanceObj;
return InstanceObj;
}
};
template <typename T1, typename T2> inline void SortVecFromMap( std::map<T1,T2>& maptodosort, std::vector<T2>& vectosort )
{
std::vector<T1> feedvector;
feedvector.reserve( maptodosort.size() );
for( const auto& it : maptodosort )
feedvector.push_back(it.second.kill);
std::sort(feedvector.begin(), feedvector.end(), std::greater<T1>());
for(const auto& itV : feedvector ) {
for( const auto& itM : maptodosort ) {
if( itM.second.kill == itV ) {
vectosort.push_back(itM.second );
}
}
}
}
int main()
{
GameArenaManager& Manager = GameArenaManager::GetInstance();
PlayerScoreBoardInfo info[5];
info[0] = PlayerScoreBoardInfo("ArchedukeShrimp", 5,4,0,0);
info[1] = PlayerScoreBoardInfo("EvilLactobacilus", 9,4,0,0);
info[2] = PlayerScoreBoardInfo("DolphinetelyOrcaward", 23,4,0,0);
info[3] = PlayerScoreBoardInfo("ChuckSkeet", 1,4,0,0);
info[4] = PlayerScoreBoardInfo("TrumpMcDuck", 87,4,0,0);
for( int i=0; i<5; i++)
Manager.m_Infos.insert( std::make_pair( i, info[i] ) );
std::vector<PlayerScoreBoardInfo> sortedvec;
SortVecFromMap( Manager.m_Infos, sortedvec );
for( std::vector<PlayerScoreBoardInfo>::iterator it = sortedvec.begin(); it != sortedvec.end(); it++ )
{
std::cout << "Name: " << (*it).name.c_str() << " ";
std::cout << "Kills: " << (*it).kill << std::endl;
}
return 0;
}
Here's a link for ideone compiled code: http://ideone.com/B08y9l
And one link for Wandbox in case you want to edit compile on real time: http://melpon.org/wandbox/permlink/6OVLBGEXiux5Vn34
This question will probably get closed down as "off topic". However,
First question: does the server ever need a sorted scoreboard?
If not, why do the work?
If anything, the server will want to index the scoreboard by player ID, which argues for either sorting by ID (to aid binary searches) or using a hashed container (O1 search time).
Furthermore, the ultimate bottleneck is network bandwidth. You'll eventually want to be in a position to send scoreboard deltas rather than state-of-the-world messages.
This further argues for making the clients do the work of resorting.
There is one more philosophical argument:
Is sorting by anything other than a primary key a data concern or a presentation concern? It's a presentation concern.
What does presentation? A client.
QED

How can I write a file with containing a lua table using sol2

I've settled on using lua as my config management for my programs after seeing posts like this and loving the syntax, and sol2 recently got released so I'm using that.
So my question is, how can I grab all the variables in my lua state and spit them out in a file?
say,
sol::state lua;
lua["foo"]["bar"] = 2;
lua["foo"]["foobar"] = lua.create_table();
would, in turn, eventually spit out
foo = {
bar = 2
foobar = {}
}
Is this at all possible and if so, how?
I used this serializer to serialize my table and print it out, really quite easy!
This is what I came up with
std::string save_table(const std::string& table_name, sol::state& lua)
{
auto table = lua["serpent"];
if (!table.valid()) {
throw std::runtime_error("Serpent not loaded!");
}
if (!lua[table_name].valid()) {
throw std::runtime_error(table_name + " doesn't exist!");
}
std::stringstream out;
out << table_name << " = ";
sol::function block = table["block"];
std::string cont = block(lua[table_name]);
out << cont;
return std::move(out.str());
}

Clang Tool: rewrite ObjCMessageExpr

I want to rewrite all messages in my code,
I need replace only selectors, but I need be able to replace nested expressions
f. e. :
[super foo:[someInstance someMessage:#""] foo2:[someInstance someMessage2]];
I tried do it with clang::Rewriter replaceText and just generate new string,
but there is a problem: It would not be work if I change selectors length, because I replace nested messages with those old positions.
So, I assumed that I need to use clang::Rewriter ReplaceStmt(originalStatement, newStatement);
I am using RecursiveASTVisitor to visit all messages, and I want to copy those messages objects, and replace selectors:
How can I do that?
I tried use ObjCMessageExpr::Create but there is so meny args, I don't know how to get ASTContext &Context and ArrayRef<SourceLocation> SeLocs and Expr *Receiver parameters from the original message.
What is the proper way to replace selectors in nested messages using clang tool (clang tooling interface)?
Update:
Should I use ReplaceStmtWithStmt callback and ASTMatchFinder ?
Update:
I am using following function to rewrite text in file:
void ReplaceText(SourceLocation start, unsigned originalLength, StringRef string) {
m_rewriter.ReplaceText(start, originalLength, string);
m_rewriter.overwriteChangedFiles();
}
And I want to replace all messageExpr in code with new selector f.e:
how it was:
[object someMessage:[object2 someMessage:obj3 calculate:obj4]];
how it should be:
[object newSelector:[object2 newSelector:obj3 newSelector:obj4]];
I am using ReqoursiveASTVisitor:
bool VisitStmt(Stmt *statement) {
if (ObjCMessageExpr *messageExpr = dyn_cast<ObjCMessageExpr>(statement)) {
ReplaceMessage(*messageExpr)
}
return true;
}
I created method for generating new message expr string:
string StringFromObjCMessageExpr(ObjCMessageExpr& messageExpression) {
std::ostringstream stringStream;
const string selectorString = messageExpression.getSelector().getAsString();
cout << selectorString << endl;
vector<string> methodParts;
split(selectorString, ParametersDelimiter, methodParts);
stringStream << "[" ;
const string receiver = GetStringFromLocations(m_compiler, messageExpression.getReceiverRange().getBegin(), messageExpression.getSelectorStartLoc());
stringStream << receiver;
clang::ObjCMessageExpr::arg_iterator argIterator = messageExpression.arg_begin();
for (vector<string>::const_iterator partsIterator = methodParts.begin();
partsIterator != methodParts.end();
++partsIterator) {
stringStream << "newSelector";
if (messageExpression.getNumArgs() != 0) {
const clang::Stmt *argument = *argIterator;
stringStream << ":" << GetStatementString(*argument) << " ";
++argIterator;
}
}
stringStream << "]";
return stringStream.str();
}
void ReplaceMessage(ObjCMessageExpr& messageExpression) {
SourceLocation locStart = messageExpression.getLocStart();
SourceLocation locEnd = messageExpression.getLocEnd();
string newExpr = StringFromObjCMessageExpr(messageExpression);
const int exprStringLegth = m_rewriter.getRangeSize(SourceRange(locStart, locEnd));
ReplaceText(locStart, exprStringLegth, newExpr);
}
The problem occurs when I try to replace nested messages, like that:
[simpleClass doSomeActionWithString:string3 andAnotherString:string4];
[simpleClass doSomeActionWithString:str andAnotherString:str2];
[simpleClass doSomeActionWithString:#"" andAnotherString:#"asdasdsad"];
[simpleClass setSimpleClassZAZAZAZAZAZAZAZA:[simpleClass getSimpleClassZAZAZAZAZAZAZAZA]];
the result is:
[simpleClass newSelector:string3 newSelector:string4 ];
[simpleClass newSelector:str newSelector:str2 ];
[simpleClass newSelector:#"" newSelector:#"asdasdsad" ];
[simpleClass newSelector:[simpleClass getSimp[simpleClass newSelector]];
because messageExpression has "old" value of getLocStart(); and getLocEnd(); How can I fix it?
You can rewrite selector name by replacing only continuous parts of selector name. For example, replace only underlined parts
[object someMessage:[object2 someMessage:obj3 calculate:obj4]];
^~~~~~~~~~~ ^~~~~~~~~~~ ^~~~~~~~~
To achieve this you require only
number of selector parts - ObjCMessageExpr::getNumSelectorLocs()
their locations - ObjCMessageExpr::getSelectorLoc(index)
their lengths - ObjCMessageExpr::getSelector().getNameForSlot(index).size().
Overall, you can rewrite ObjCMessageExpr with the following RecursiveASTVisitor:
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Rewrite/Core/Rewriter.h"
namespace clang_tooling
{
using clang::SourceLocation;
class RewritingVisitor : public clang::ASTConsumer,
public clang::RecursiveASTVisitor<RewritingVisitor>
{
public:
// You can obtain SourceManager and LangOptions from CompilerInstance when
// you are creating visitor (which is also ASTConsumer) in
// clang::ASTFrontendAction::CreateASTConsumer.
RewritingVisitor(clang::SourceManager &sourceManager,
const clang::LangOptions &langOptions)
: _sourceManager(sourceManager), _rewriter(sourceManager, langOptions)
{}
virtual void HandleTranslationUnit(clang::ASTContext &context)
{
TraverseDecl(context.getTranslationUnitDecl());
_rewriter.overwriteChangedFiles();
}
bool VisitObjCMessageExpr(clang::ObjCMessageExpr *messageExpr)
{
if (_sourceManager.isInMainFile(messageExpr->getLocStart()))
{
clang::Selector selector = messageExpr->getSelector();
for (unsigned i = 0, end = messageExpr->getNumSelectorLocs();
i < end; ++i)
{
SourceLocation selectorLoc = messageExpr->getSelectorLoc(i);
_rewriter.ReplaceText(selectorLoc,
selector.getNameForSlot(i).size(),
"newSelector");
}
}
return Base::VisitObjCMessageExpr(messageExpr);
}
private:
typedef clang::RecursiveASTVisitor<RewritingVisitor> Base;
clang::SourceManager &_sourceManager;
clang::Rewriter _rewriter;
};
} // end namespace clang_tooling