Conditional triggered transition with Anylogic - if-statement

I have a model, where there is a =n agent that we want to change the state based on a condition.
my condition is that, the distance between the agent and another agent must be <= 411 before the state changes.
I have tried the following code in my condition field:
if (double distanceTo(getNearestAgent(main.Agent))<=411)
{
return true;
}
i get the syntax errors :
misplaced construct(s), and ( expected
What am I doing wrong ? Plz assist

Since you clarified that "Agent" is the name of your population on Main, your code syntax is wrong. Try this instead:
if (distanceTo(getNearestAgent(main.Agent))<=411) {
return true;
}
btw: Be extremly careful with condition-based transitions, they might not trigger when the condition is actually satisfied. Read in the help and around the web to make sure you get it right. Or better: do not use them at all, they also eat performance unnecessarily

Related

How to make order-independent assertions on Flux output?

I have a test case for a Flux from Project Reactor roughly like this:
testMultipleChunks(StepVerifier.FirstStep<Chunk> verifier, Chunk chunk1, Chunk chunk2) {
verifier.then(() -> {
worker.add(chunk1);
worker.add(chunk2);
worker.update();
})
.expectNext(chunk1, chunk2)
.verifyTimeout(Duration.ofSeconds(5));
}
Thing is, my worker is encouraged to parallelize the work, which means the order of the output is undefined. chunk2, chunk1 would be equally valid.
How can I make assertions on the output in an order-independent way?
Properties I care about:
every element in the expected set is present
there are no unexpected elements
there are no extra (duplicate) events
I tried this:
testMultipleChunks(StepVerifier.FirstStep<Chunk> verifier, Chunk chunk1, Chunk chunk2) {
Set<Chunk> expectedOutput = Set.of(chunk1, chunk2);
verifier.then(() -> {
worker.add(chunk1);
worker.add(chunk2);
worker.update();
})
.recordWith(HashSet::new)
.expectNextCount(expectedOutput.size())
.expectRecordedMatches(expectedOutput::equals)
.verifyTimeout(Duration.ofSeconds(5));
}
While I think that makes the assertions I want, it took a terrible dive in readability. A clear one-line, one-method assertion was replaced with four lines with a lot of extra punctuation.
expectedRecordedMatches is also horribly uninformative when it fails, saying only “expected collection predicate match” without giving any information about what the expectation is or how close the result was.
What's a clearer way to write this test?
StepVerifier is not a good fit for that because it verifies each signal as it gets emitted, and materialize an expected order for asynchronous signals, by design.
It is especially tricky because (it seems) your publisher under test doesn't clearly complete.
If it was completing after N elements (N being the expected amount here), I'd change the publisher passed to StepVerifier.create from flux to flux.collectList(). That way, you get a List view of the onNext and you can assert the list as you see fit (eg. using AssertJ, which I recommend).
One alternative in recent versions of Reactor is the TestSubscriber, which can be used to drive request and cancel() without any particular opinion on blocking or on when to perform the assertions. Instead, it internally stores the events it sees (onNext go into a List, onComplete and onError are stored as a terminal Signal...) and you can access these for arbitrary assertions.

How to prevent orthogonal region transition for error handling

I want to create the following state machine, with Boost MSM:
I would like to be able to prevent the Error event to trigger the AllOk + Error == InError transition if the orthogonal state is on "B". For example, specifying transition for all orthogonal states would be nice. Something like:
{AllOk, B} + Error == {AllOk, A}
However, I cannot find how to do it with Boost MSM, neither with regular UML nomenclature, which makes me think I am going the wrong way.
Is there a classic "UML idiomatic" to handle this kind of behavior?
I see two possible solutions:
Put a guard on AllOk + Error == InError which checks if the other state is B, like this response.
Send a more specific error (in my case, CouldNotComputePath, as I am programming a robot), and somehow transform it in Error if it is not handled. I am not really sure how to do it.
Ok, I find a solution:
The Error event can be "catched" in the MainStateMachine. If it is not, an internal transition is triggered on the MainStateMachine, which will send the EnterError event to make the other orthogonal state switch to InError.

scalatra < squeryl < select ALL | Always

I want to read elements from the database and return them as JSON objects.
Scalatra is set up to return JSON.
Databaseschema is created.
Players are added.
The following code seems to be the main problem:
get("/") {
inTransaction {
List(from(MassTournamentSchema.players)(s => select(s)))
}
}
I get the following error:
"No session is bound to current thread, a session must be created via Session.create and bound to the thread via 'work' or 'bindToCurrentThread' Usually this error occurs when a statement is executed outside of a transaction/inTrasaction block "
I want to do it right so simply adding something like "Session.create" may not really be the right way.
Can anyone help a scalatra-noob? :-)
I think that your comment is on the right track. The inTransaction block will bind a JDBC connection to a thread local variable and start the connection on it. If the select doesn't occur on the same thread, you'll see an error like the one your received. There are two things I would suggest that you try:
Start your transaction later
List(inTransaction {
from(MassTournamentSchema.players)(s => select(s))
})
I'm not familiar with Scalatra's List, but it's possible that it's accepting a by-name parameter and executing it later on a different thread.
Force an eager evaluation of the query
inTransaction {
List(from(MassTournamentSchema.players)(s => select(s)).toList)
}
Here the .toList call will turn the Query object Squeryl returns into a Scala List immediately and guard against any lazy evaluation errors caused by later iteration.

Fallback on geolocation

I'm having trouble with the most basic aspect of geolocation - no matter what I do, I don't seem to be able to get the fallback to trigger. Here's the code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var latNum = parseFloat(latitude);
var longNum = parseFloat(longitude);
This is immediately followed by a nested bunch of if...else if statements that trigger different functions based on the user's location within one of a number of defined areas and an else statement to catch the condition where the user is not in any of the defined locations. This part all works fine, including the 'else' condition at the end. Where it falls over is if the user's device does not have geolocation enabled, or the user denies access to location data when prompted.
The code supposed to capture this is simply:
} else {
function10();
}
I have tried this in FF, Safari and Chrome with the same results: if I disable location services or deny access when prompted, the final 'else' function does not trigger.
I've looked at countless examples of this sort of elegant failure on geolocation and can't see why it doesn't work.
I'd be truly grateful for any clues where I went wrong.
OK - problem solved! I'm not sure if I feel just silly or enlightened, but for the benefit of anyone else with the same problem, here's the solution:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
// Do something here if you get position data
},
function() {
// Do something else if you don't get any position data
}
);
}
Where i went wrong, I think, is that I needed to look for a failure of the function(position)rather than the absence of a geolocation enabled agent. The second function within the same if condition provides the action in the event of no position data being returned from the browser, no matter what the reason. The final 'else' statement in the original code (above) would only be triggered on a device with no geolocation capacity.
This all makes sense now, but I have to say the documentation on Google, and many of the tutorial sites was far from clear on this, with frequent references to my initial syntax covering the situation where geolocation capacity was not enabled (as distinct from not present).
Thanks to this answer on SO for pointing me in the right direction.

Handle Invalid Data Type in CF Remote Function

So I have a remote ColdFusion Function like:
remote string function name (required numeric varname){
This is accessed via AJAX call. Google has taken it upon itself to pass in junk/blank values to the URL to this remote function. How can I gracefully handle those for Bots/Users to manage to get in a junk value. I've tried putting try/catch around/inside the function and doesn't work. I've also tried setting a default value but I still get an error. I'd like to be able to return an error message.
Thoughts?
Right now:
domain.com/path/to/page.cfc?method=function&varname=
Is throwing an error
domain.com/path/to/page.cfc?method=function&varname=5
Is working as expected.
Update:
I am leaving this here for posterity, as it explains the cause of the error and chain of events with validation. However, Adam's response is the correct solution IMO.
remote string function name (required numeric varname){
I've tried putting try/catch around/inside the function and doesn't work.
Because the argument value is validated before CF executes anything inside the function. So it never even gets to the try/catch.
If you want to allow non-numeric values, you must set the argument type to string and perform validation inside the function. ie
// use whatever check is appropriate here
if ( IsNumeric(arguments.varname) ) {
// good value. do something
}
else {
// bad value. do something else
}
I've also tried setting a default value but I still get an error
domain.com/path/to/page.cfc?method=function&varname=
Update
The reason it does not work is because the varname parameter does exists. Its value is an empty string. As long as some value is passed (even an empty string) the default is ignored.
I disagree that the accepted solution is the best approach here.
Firstly, if your method is expecting a numeric and it's being passed a string, then an error is precisely the correct reaction here. You shouldn't feel the need to mitigate for requests that pass invalid values. Consider it like someone making a request to http://some.domain/path/to/file/wrongOne.html (they should have requested http://some.domain/path/to/file/rightOne.html)... it's completely OK for things to return a 404 "error" there, isn't it? An error response is exactly right in that situation.
Similarly, you have dictated that for your remote call URL, that argument is supposed to be numeric. So if it's not numeric... that is an error condition. So your server returning a 500-type error is actually the correct thing to do.
This is an example of the "garbage in, garbage out" rule.
If you are looking for an elegant solution, I'd say you already have the most elegant solution. Don't mess around writing special code to deal with incorrectly made requests. That is not an elegant approach.
You are better off letting the thing error, because then the mechanism requesting the URL will stop doing it. Messing around so that you are returning a 200 OK for a request that wasn't "OK" is the wrong thing to do.
Errors - when they are the correct result - are fine. There's nothing wrong with them.