Fallback on geolocation - if-statement

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.

Related

Different results when making a Corda query via API and inside a flow

I’m getting some strange behaviour. When I update a state with a list of partner ids - other nodes - and and read the state afterwards it seems that via rpcOps.vaultQueryBy I can see the updated - or unconsumed - state with the updated list of partners, but if I do same query via serviceHub.vaultService.queryBy it looks like the state’s parner list hasn’t changed at all.
If I get all states in the flow - also the consumed - it looks like there has not been a change, but via API all updates into partners list are visible. Is this some sort of a bug I have encountered or am I just not understanding something?
We're using Corda 4.0.
Via API
var servicestates = rpcOps.vaultQueryBy<ServiceState>().states.map { it.state.data }
var services = getServices().filter {
it.linearId == UniqueIdentifier.fromString(serviceId)
}.single()
Inside flow
val serviceStateAndRef = serviceHub.vaultService.queryBy<ServiceState>(
QueryCriteria.LinearStateQueryCriteria(linearId = listOf(serviceLinearId))
).states.single()
#Ashutosh Meher You got it near enough. The problem was in a previous flow, where, when creating a new partner state the command call for contract, there was only the caller listed.
So
Command(ServiceContract.Commands.AddPartner(),listOf(ourIdentity.owningKey))
had to be edited to include necessary other parties.
Command(ServiceContract.Commands.AddPartner(),updatedServiceState.participants.map { it.owningKey })
That resulted the other node not to see the change. It was right under my eyes all the time... ;)

Conditional triggered transition with Anylogic

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

Facebook API Javascript: document.write() doesn't work?

I started having a look into Facebook API today. I couldn' say enough how ugly and totally unintuitive it is, at least its Javascript implementation. Anyway, here's the two things I found:
a. I struggled whole day getting 'undefined' messages after properly loggin and getting an access_toekn, now when I tried to write response.first_name after calling FB.api ('/me') I got 'undefined' messages..... Well, I burnt my brain until I got someone here in stackoverflow that said the access token should HAVE to be passed in the call! But you can't find THIS CLEARLY specified in the FB official documentation, it's not even mentioned, not even parameter is shown. So this works:
FB.api('/me', {access_token: taccesstokenvalue}, function(response) {
alert(response.first_name); });
b. now, if I change alert() by document.write() , well, it just does nothing.
c. console.log() never worked out, I Tried on chrome, firefox, opera. Nothing
Why can't I use document.write? I need to verbosely write a lot of things coming out from the API, how can I do it ?
Thanks!!
Well, I found out a solution I think. Hope it helps other people...
I solved it this way:
a. create a form on top of the body area, with hidden field called hAPIresponse and hAccessToken
b. instead of trying to dump the API response right inside the function() as in the code above, fill the hidden fields with what the API returns, concatenating fields one after another if needed, like this:
FB.api('/me', {access_token: taccesstokenvalue}, function(response) {
document.getElementById("hAPIresponse").value="first name:" + response.first_name;
document.getElementById("hAccessToken").value="access token:" + taccesstokenvalue;
});
*here I didn't concatenate anything, just got the first_name property from the API
c. taccesstokenvalue variable comes from previously retrieving it from the URL or you can retrieve it directly through the API. Here comes the manual approach:
function Mid(str, start, len)
{
// Make sure start and len are within proper bounds
if (start < 0 || len < 0) return "";
var iEnd, iLen = String(str).length;
if (start + len > iLen)
iEnd = iLen;
else
iEnd = start + len;
return String(str).substring(start,iEnd);
}
var taccesstoken=window.location.href;
var tvecaux=taccesstoken.split('access_token=');
var taccesstokenvalue=Mid(tvecaux[1],0, tvecaux[1].indexOf('&',0) );
As far as I saw, when you get into the FB.api() call the code CONTINUES TO EXECUTE below the FB.API() call and not through the function(response). This one is triggered asynchronously by its own will, when it thinks it's better to finish :) It seems it's so complicated for FB developers adding a sync=true/false property in the FB.Init() so people used to sync coding won't pull their hairs out of their heads as I did..
Hope it helps somebody, I spent nearly 36 hours trying to do something so simple and stupid like calling an API and retrieving a value from it...
Again, this API couldn't be less intuitive, I can't say it enough. I can't imagine what I will find when trying to pull coments to FB Post replies or even trying to interact with the FB chat

SKPaymentQueue addPayment doesn't always trigger native confirm dialog

Ok, I'm implementing IAP into an iOs app and only some products in the store actually trigger the native purchase handling dialogs.
Background:
The app uses cocos2dx with javascript bindings for cross-platformability. We're dipping into the iOs native sectors to implement the store handling.
These calls all work correctly:
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[SKPaymentQueue canMakePayments];
[[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
A note on the last one. All product ids are checked and return as valid in the productsRequest:request didReceiveResponse:response callback but only if I don't include the bundle id in the identifiers that get sent. Most examples I saw said this was needed, but if included they all return as invalidProductIdentifiers. Could this be indicative of a problem?
So currently some products bring up the native purchase confirm dialog after their (previously verified) ids are passed to [[SKPaymentQueue defaultQueue] addPayment:payment]. Most of them simply do nothing afterwards. No callback on paymentQueue:queue updatedTransactions:transactions, no error code, no crash.
I can't see a pattern for why some work and most don't. At least one consumable, non-consumable and subscription work, so I don't think it's that. I found that if I break and step through the code pausing after [[SKPaymentQueue defaultQueue] addPayment:payment], there's a small chance a few products work more often, although it's not consistent. This lead me to think it may be a threading issue, but you can see what I've tried below and it didn't help.
Things I've tried:
Reading around SO and elsewhere, people suggested changing test users, clearing the queue with [[SKPaymentQueue defaultQueue] finishTransaction:transaction], and that Apple's Sandbox server sometimes 'has issues'. But none of this fixed it, and it strikes me as odd that I'm not getting crashes or errors, it just doesn't react at all to certain product ids.
Here's the actual call with some things I've tried:
- (void)purchaseProductWithId:(const char*)item_code
{
/** OCCASIONALLY MAY NEED TO CLEAR THE QUEUE **
NSArray *transactions = [[SKPaymentQueue defaultQueue] transactions];
for(id transaction in transactions){
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}// */
// dispatch_async(dispatch_get_main_queue(),^ {
SKPayment *payment = [SKPayment paymentWithProductIdentifier:[NSString stringWithUTF8String:item_code]];
// [[SKPaymentQueue defaultQueue] performSelectorOnMainThread:#selector(addPayment:) withObject:payment waitUntilDone:NO];
[[SKPaymentQueue defaultQueue] addPayment:payment];
// } );
}
If there's any other code that could be useful let me know.
Thanks for your help.
Edit:
I've added the hasAddObserver check from this question and that's not the problem either.
Turns out it was a temporary thing. I'd hate to accuse Apple's sandbox servers of being flaky, but nothing was changed and then days later it suddenly worked.
So if you have a similar issue maybe take a break and come back to it later?

Ember.js router events as functions not working

I have set up some basic routing in my app by using the examples at http://emberjs.com/guides/outlets/#toc_the-router
Within the root I have some events that trigger from view actions e.g:
gotoStepOne: Ember.Route.transitionTo('stepOne'),
gotoStepTwo: Ember.Route.transitionTo('stepTwo'),
gotoStepThree: Ember.Route.transitionTo('stepThree'),
gotoStepFour: Ember.Route.transitionTo('stepFour'),
gotoStepFive: Ember.Route.transitionTo('stepFive'),
Full example router code at http://jsfiddle.net/hellosmithy/WdjXT/
This all works fine at the moment. The problem is that I'd like to add other code into these events. For example:
gotoStepOne: function() {
if (someCondition) {
Ember.Route.transitionTo('stepOne');
}
someOtherFunction();
}
However doing this breaks the routing without throwing any errors. It just no longer transitions.
Specifically I only want transitions to happen if a certain state is met - something has been selected or input by the user at each stage before they can proceed. Is there a workaround for this, or should I be abstracting this functionality elsewhere?
The way I understand the router is, that it is the representation of the application's state.
Specifically I only want transitions to happen if a certain state is met - something has been selected or input by the user at each stage before they can proceed.
So the user inputting or selecting something puts your application in a certain state which is reflected by the router.
IMHO it should be something like this in a view (or controller):
userDidSomething: function(condition) {
if (condition) {
App.get('router').send('stepOne');
}else{
someOtherFunction();
}
}