Adding statement in Sesame using HTTPRepository - add

I'm trying to add some simple statements to a Sesame repository, like so:
RepositoryConnection connection = repository.connection
connection.autoCommit = false
try {
ValueFactory vf = repository.getValueFactory()
def dummyS = vf.createURI("http://some/uri")
def dummyP = vf.createURI("http://some/uri/hasItem")
uris?.each { uri ->
connection.add(listS, listP, vf.createURI(uri))
}
def stmts = connection.getStatements(listS, null, null, true) ...
This works great when executed against a local SailRepository using NativeStore. But when hooking this up to an HTTPRepository hosted on a different server, the 'add' appears to fail silently. No exception is thrown, but the returned stmts is empty.
Anybody have any ideas what could be causing this? Thanks in advance!

The reason this fails is that you are using autoCommit=false. In a local setting, Sesame's transaction isolation takes care that even when not yet committed, added data is visible when querying on the same connection.
However, the HTTPRepository class does not support transaction isolation: the added triples are not visible until you have committed. So, to fix, add:
connection.commit();
before the getStatements() call and you should be fine.

Related

What is the difference between these update CALLBACK functions code?

I had ran the codes shown below. The 1st one runs but 2nd one does not
Can anyone please tell me the reason behind it.
//This runned successfully
updatePost(req,res)
{
let postId = req.params.postId
let posts = req.store.posts
posts[postId] = req.body
res.status(200).send(posts[postId])
}
//This gave error
updatePost(req,res)
{
req.store.posts[req.params.postId]=req.body
res.send(200).send(req.store.posts[req.params.postId])
}
Without knowing the error message....your last line is res.send(200).send(req.store.posts[req.params.postId]),
When it gets to ".send(req.store.posts[req.params.postId])" the response has already been sent.
Try changing it to res.status(200).send(req.store.posts[req.params.postId])
Like you have in the first block of code.
If this isn't your problem (maybe thats just a typo in your question and not in your code), please share the error message and I'll update my answer.

GKTurnBasedMatch - player( receivedExchangeReplies ) not triggered for CurrentParticipant

so Ive been at this for weeks now and never found an answer anywhere in the net. The sourcecode comments, various documentations and various sources claim the function ReceivedExchangeReplies(GKPlayer, GKTurnBasedExchangeReply[], GKTurnBasedExchange, GKTurnBasedMatch) is supposed to be called when all Recipients of the exchange either reply or timeout. It is supposed to be called for both the initiator of the exchange and the currentParticipant.
But in my App it only ever gets called for the initiator of the exchange, not the turnholder. I'm unable to proceed with my coding, since the current turnholder is supposed to merge and resolve the exchanges once they are done. But it cannot do so, since it never gets notified about the exchange becoming completed.
AuthenticationHandler works normal and is to no concern to the problem:
func authenticateLocalPlayer() {
let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(ViewController, error) -> Void in
if((ViewController) != nil) {
self.underlyingViewController.present(ViewController!, animated: true, completion: nil)
} else if (localPlayer.isAuthenticated) {
self.gamecenterEnabled = true
localPlayer.unregisterAllListeners()
localPlayer.register(self)
self.findBattleMatch()
} else {
self.gamecenterEnabled = false
print(error as Any)
}
}
}
Here is how the Exchange Request is sent:
currentMatch.sendExchange(to: [nextParticipant], data: GameState.encodeStruct(structToEncode: structToSend), localizableMessageKey: messageKey, arguments: ["X","Y"], timeout: TimeInterval(timeOutDebug), completionHandler: {(exchangeReq: GKTurnBasedExchange?,error: Error?) -> Void in
if(error == nil ) {
print("Operation successfull")
} else {
print(error as Any)
}
})
Being replied with Reply:
exchange.reply(withLocalizableMessageKey: exchange.message! , arguments: ["XY","Y"], data: GameState.encodeStruct(structToEncode: exchangeReply), completionHandler: {(error: Error?) -> Void in
if(error == nil ) {
print("ExchangeReply sent successfully")
} else {
print(error as Any)
}
})
After that on completion of the exchange, the following overriden function should be called automatically. For both, for the initiator of the exchange and for the current turnholder:
func player(_ player: GKPlayer, receivedExchangeReplies replies: [GKTurnBasedExchangeReply], forCompletedExchange exchange: GKTurnBasedExchange, for match: GKTurnBasedMatch){
print("Exchange was completed, turnholder and Exchange-initiator should act on that in following code.")
...code...
}
This is the Swift-version of the above mentioned ObjectiveC function.
Now the problem like said is, that the above function is being called only for the inititor of the exchange, while it not being called for the current turnholder (like it is supposed to be). The current turnholder is supposer to merge the changes made by exchanges into the savegame data. Him not being notified like he should leaves an issue and a problem, because he cannot act without being notified.
I could implement him being notified manually by another additional exchange (which is the workaround I'm currenly using), but that is somehow beside the point, since he would have to merge the new exchange blindly without any certainty about it being completed.
The first 3 steps are working just fine it seems, since I see the initiator of the exchange being notified. Only problem is the fourth function not being automatically called like described in Documentations and tutorials.
One of my latest interpretations was that the exchange gets completed too fast without the listener ever realizing it was ever active (the exchange is replied to immediately on receival); but that is just a wild guess. Even if I wanted to... whatever I do to delay replying to the exchange (for example saving a reference on the exchange, using DispatchQueue for a delayed function call or similar) results in either the exchange turning out nil or communication errors (message was sent over different proxy error).
Basically I wonder if the turnholder is really supposed to get notified by the above function being called or if it might have been changed.
I would really appreciate help here, Ive been at this for weeks and havent gotten anywhere. Everything else is working fine.
Im using the latest version of Swift with the most recent approach of utilizing GKLocalPlayer instead of implementing the Listener directly (like it is recommended everywhere).
kindly regards, Skeltek

Changing State when Using Scala Concurrency

I have a function in my Controller that takes user input, and then, using an infinite loop, queries a database and sends the object returned from the database to a webpage. This all works fine, except that I needed to introduce concurrency in order to both run this logic and render the webpage.
The code is given by:
def getSearchResult = Action { request =>
val search = request.queryString.get("searchInput").head.head
val databaseSupport = new InteractWithDatabase(comm, db)
val put = Future {
while (true) {
val data = databaseSupport.getFromDatabase(search)
if (data.nonEmpty) {
if (data.head.vendorId.equals(search)) {
comm.communicator ! data.head
}
}
}
}
Ok(views.html.singleElement.render)
}
The issue arises when I want to call this again, but with a different input. Because the first thread is in an infinite loop, it never ceases to run and is still running even when I start the second thread. Therefore, both objects are being sent to the webpage at the same time in two separate threads.
How can I stop the first thread once I call this function again? Or, is there a better implementation of this whole idea so that I could do it without using multithreading?
Note: I tried removing the concurrency from this function (as multithreading has been the thing giving me all of these problems) and instead moving it to the web socket itself, but this posed problems as the web socket is connected to a router, and everything connects to the web socket through the router.
Try AsyncAction where you return a Future[Result] as a result. Make database call in side this result. E.g.(pseudo code),
def getSearchResult = AsyncAction { request =>
val search = request.queryString.get("searchInput").head.head
val databaseSupport = new InteractWithDatabase(comm, db)
Future {
val data = databaseSupport.getFromDatabase(search)
if (data.nonEmpty) {
if (data.head.vendorId.equals(search)) {
comm.communicator ! data.head // A
}
}
Ok(views.html.singleElement.render)
}
}
Better if databaseSupport.getFromDatabase(search) returns a Future but that is a story for another day. The tricky part is to figure how to deal with Actor at "A". Just remember at the exit it must return Future[Result] result type.

how to define functions in redis \ lua?

I'm using Node.js, and the 'redis-scripto' module, and I'm trying to define a function in Lua:
var redis = require("redis");
var redisClient = redis.createClient("6379","127.0.0.1");
var Scripto = require('redis-scripto');
var scriptManager = new Scripto(redisClient);
var scripts = {'add_script':'function add(i,j) return (i+j) end add(i,j)'};
scriptManager.load(scripts);
scriptManager.run('add_script', [], [1,1], function(err, result){
console.log(err || result);
});
so I'm getting this error:
[Error: ERR Error running script (call to .... #enable_strict_lua:7: user_script:1: Script attempted to create global variable 'add']
so I've found that it's a protection, as explained in this thread:
"The doc-string of scriptingEnableGlobalsProtection indicates that intent is to notify script authors of common mistake (not using local)."
but I still didn't understand - where is this scripting.c ? and the solution of changing global tables seems risky to me.
Is there no simple way of setting functions to redis - using lua ?
It looks like the script runner is running your code in a function. So when you create function add(), it thinks you're doing it inside a function by accident. It'll also, likely, have a similar issue with the arguments to the call to add(i,j).
If this is correct then this should work:
local function add(i,j) return (i+j) end return add(1,1)
and if THAT works then hopefully this will too with your arguments passed from the js:
local function add(i,j) return (i+j) end return add(...)
You have to assign an anonymous function to a variable (using local).
local just_return_it = function(value)
return value
end
--// result contains the string "hello world"
local result = just_return_it("hello world")
Alternately, you can create a table and add functions as fields on the table. This allows a more object oriented style.
local obj = {}
function obj.name()
return "my name is Tom"
end
--// result contains "my name is Tom"
local result = obj.name()
Redis requires this to prevent access to the global scope. The entire scripting mechanism is designed to keep persistence out of the scripting layer. Allowing things in the global scope would create an easy way to subvert this, making it much more difficult to track and manage state on the server.
Note: this means you'll have to add the same functions to every script that uses them. They aren't persistent on the server.
This worked for me: (change line 5 from the question above):
var scripts = {
'add_script':'local function add(i,j) return (i+j) end return(add(ARGV[1],ARGV[2]))'};
to pass variables to the script use KEYS[] and ARGV[], as explained in the redis-scripto guide
and also there's a good example in here: "Lua: A Guide for Redis Users"

threading in Windows store app

I am reading sample Hilo provided by MS, under ImageBrowserViewModel.cpp there is some code I am not understand:
// Observe the update after waiting the specified amount of time.
create_task([timeToWait]() {
assert(IsBackgroundThread());
::wait(timeToWait);
}).then([weakThis]() {
assert(IsMainThread());
auto vm = weakThis.Resolve<ImageBrowserViewModel>();
if (nullptr != vm)
{
vm->ObserveFileChange();
vm->m_hasFileUpdateTask = false;
}
}, task_continuation_context::use_current()).then(ObserveException<void>(m_exceptionPolicy));
The quest is app use IsBackgroundThread() & IsMainThread() to assert it should be correctly called under certain context. But for the ::wait(timeToWait) function call, there is no task_continuation_context defined to make sure it runs in background, I just wonder how does it make to work?? Thanks a lot!
The default for constructed tasks (as the first task is in your code snippet) is task_continuation_context::use_arbitrary(), so even though it is not specified this is what it will be. The task continuation lambda does assert this before calling ::wait (which would throw an exception if it attempted to run on the UI thread).

Resources