adding points from a CLLocationCoordinate2D array on MKMapView doesn't work - mkmapview

I am using the following code to add stored pin points to myMKMap on button click ;
func addPoint(){
var count: Int = 0
repeat {
let pin = MKPointAnnotation()
pin.coordinate = CLLocationCoordinate2D(mypointList[count])
pin.title = placenames[count]
pin.subtitle = placedetails[count]
mymap.addAnnotation(pin)
count += 1
}
while count < 3
mypointList[] is like below ;
var mypointList = [CLLocationCoordinate2D(latitude: 37.19722, longitude: 25.82189),
CLLocationCoordinate2D(latitude: 37.20103, longitude: 25.83009),
CLLocationCoordinate2D(latitude: 37.20092, longitude: 25.81781),
CLLocationCoordinate2D(latitude: 37.19989, longitude: 2259.82449)]
var placenames: [String] = ["sample place 1", "sample place 2", "sample place 3", "sample place 4"]
var placedetails: [String] = ["sample place detail 1", "sample place detail 2", "sample place detail 3", "sample place detail 4"]
but pins are not added when I run the application.
By the way, following code works when replace with the "pin.coordinate = CLLocationCoordinate2D(mypointList[count])" line in repeat loop ;
pin.coordinate = CLLocationCoordinate2D(latitude: 37.1972, longitude: 25.2744)
Is there any problem with the array ?
Thank you

However it sounds like a bit weird solution, I've fixed my problem with replacing the following code :
pin.coordinate = CLLocationCoordinate2D(latitude: mypointList[count].latitude as! CLLocationDegrees, longitude: mypointList[count].longitude as! CLLocationDegrees)
It displays the pins correctly now.

Related

How can I exract a full sentence using Apache NLPCraft?

In my model file I am using a macro with a regex extract any space-separated alpha-numeric words to capture an user-input sentence i.e.
macros:
- name: "<GENERIC_INPUT>"
macro: "{//[a-zA-Z0-9 ]+//}"
Then I am trying to capture it as following in the element:
elements:
- id: "prop:title"
description: Set title
synonyms:
- "{set|add} title <GENERIC_INPUT>"
The intent term is as following:
intents:
- "intent=myIntent term(createStory)~{tok_id() == 'prop:createStory'} term(title)~{tok_id() == 'prop:title'}?"
In the Java Model I am correctly capturing the title property:
public NCResult onMatch(
NCIntentMatch ctx,
#NCIntentTerm("createStory") NCToken createStory,
#NCIntentTerm("title") Optional<NCToken> titleList,
{
...
When I run a query against the REST API service the probe is deployed in, I only get the first word of the last element <GENERIC_INPUT> (the regular expression) of the synonym defined as {set|add} title <GENERIC_INPUT> i.e.
HTTP 200 [235ms]
{
"status": "API_OK",
"state": {
"resType": "json",
"mdlId": "Create Story",
"txt": "set title this is my story",
"resMeta": {},
"srvReqId": "GKDY-QLBM-B6TQ-7KYO-KMR8",
"status": "QRY_READY",
"resBody": {
"title": "set title this",
"createStory": true,
},
"usrId": 1,
"intentId": "myIntent"
}
}
In the resBody.title I get set title this rather than the whole string as it should be allowed by the regex i.e. set title this is my story
Any idea why? How can I get it to extract the whole title?
Many thanks
Regex <GENERIC_INPUT> can catch individual token, but not group of tokens.
Please try such way
elements:
- id: "prop:title"
description: "Set title"
synonyms:
- "{set|add} title"
- id: "prop:any"
description: "Set any"
synonyms:
- "//[a-zA-Z0-9 ]+//"
intents:
- "intent=test term(title)={# == 'prop:title'} term(any)={# == 'prop:any'}*"
Callback
#NCIntentRef("test")
#NCIntentSample({
"Set title 1 2",
"Set title a b c"
})
NCResult x(
NCIntentMatch ctx,
#NCIntentTerm("title") NCToken title,
#NCIntentTerm("any") List<NCToken> any) {
System.out.println("title=" + title.getNormalizedText());
System.out.println("any=" + any.stream().map(NCToken::getNormalizedText).collect(Collectors.joining("|")));
return NCResult.text("OK");
}
It should work.
But also please try to drop regex here. It can work too slow and you will have many garbage variants.
You can use one element in intent and extract following words in the callback
Model:
elements:
- id: "prop:title"
description: "Set title"
synonyms:
- "{set|add} title"
intents:
- "intent=test term(title)={# == 'prop:title'}"
Callback:
#NCIntentRef("test")
#NCIntentSample({
"Set title 1 2",
"Set title a b c"
})
NCResult x(
NCIntentMatch ctx,
#NCIntentTerm("title") NCToken title) {
System.out.println("title=" + title.getNormalizedText());
System.out.println("any after=" +
Stream.concat(
ctx.getVariant().getFreeTokens().stream(),
ctx.getVariant().getStopWordTokens().stream()
).sorted(Comparator.comparingInt(NCToken::getStartCharIndex)).
filter(p -> p.getStartCharIndex() > title.getStartCharIndex()).
map(NCToken::getNormalizedText).
collect(Collectors.joining("|"))
);
return NCResult.text("OK");
}
Same result, but without regex.
do you know if the apache nlpcraft provides a built-in method to extract as >>well quoted sentences i.e. 'some sentence like this one'?
There are few workarounds for such request, some of the seem like hacks.
I guess that most straight solution is following:
Make NCCustomParser
public class QuotedSentenceParser implements NCCustomParser {
#Override
public List<NCCustomElement> parse(NCRequest req, NCModelView mdl, List<NCCustomWord> words, List<NCCustomElement> elements) {
String txt = req.getNormalizedText();
if (
txt.charAt(0) == '\'' &&
txt.charAt(txt.length() - 1) == '\'' &&
!txt.substring(1, txt.length() - 1).contains("'")
)
return words.stream().map(
w -> new NCCustomElement() {
#Override
public String getElementId() {
return "qElem";
}
#Override
public List<NCCustomWord> getWords() {
return Collections.singletonList(w);
}
#Override
public Map<String, Object> getMetadata() {
return Collections.emptyMap();
}
}
).collect(Collectors.toList());
return null;
}
}
add configuration (Note, that you have to add qElem dummy element here.. It seems like some bug or unclear feature, I am pretty sure that dynamic definition of this element ID in QuotedSentenceParser must be enough)
elements:
- id: "qElem"
description: "Set title"
synonyms:
- "-"
intents:
- "intent=test term(qElem)={# == 'qElem'}*"
parsers:
- "org.apache.nlpcraft.examples.lightswitch.QuotedSentenceParser"
Usage
#NCIntentRef("test")
#NCIntentSample({
"'Set title a b c'"
})
NCResult x(NCIntentMatch ctx, #NCIntentTerm("qElem") List<NCToken> qElems) {
System.out.println(qElems.stream().map(p -> p.getNormalizedText()).collect(Collectors.joining("|")));
return NCResult.text("OK");
}

java.lang.NumberFormatException: For input string: "16000$" in kotlin

I want to make display show "16000$" before click increase btn or decrease btn.
when I make code like this error caused by :java.lang.NumberFormatException: For input string: "16000$ . but I should display $. Lets check my code and help me plz.
var productprice = findViewById<TextView>(R.id.productPrice)
productprice.text= intent.getStringExtra("price")+"$"
var price = productPrice.text.toString().toInt()
var inc_val= price
var getPrice = price
decrease.isEnabled=false
increase.setOnClickListener {
increaseInteger()
getPrice+= inc_val
productprice.text=getPrice.toString()+"$"
}
decrease.setOnClickListener {
decreaseInteger()
getPrice -= inc_val
productprice.text=getPrice.toString()+"$"
}
You are trying to parse the string with "$" to int, Hence you are getting NumberFormatException.
Try this instead:
var productprice = findViewById<TextView>(R.id.productPrice)
productprice.text= intent.getStringExtra("price")+"$"
var price = parseInt(intent.getStringExtra("price"))
var inc_val= price
var getPrice = price
decrease.isEnabled=false
increase.setOnClickListener {
increaseInteger()
getPrice+= inc_val
productprice.text=getPrice.toString()+"$"
}
decrease.setOnClickListener {
decreaseInteger()
getPrice -= inc_val
productprice.text=getPrice.toString()+"$"
}
var price = productPrice.text.toString().toInt() - you try to convert "16000$" to Int here. Please get substring here first.
Formally, right code is:
val priceText = productPrice.text.toString()
val price = priceText.substring(0, priceText.length - 1).toInt()
However really I advice you to store value internally. You price is part of model. E.g. you can avoid text parsing and just read value from model. E.g. code will be like this:
var price = intent.getIntExtra("price") // we store int value here, not String
var inc_val= price
decrease.isEnabled=false
displayPrice()
increase.setOnClickListener {
intent.setIntExtra(intent.getIntExtra("price") + inc_val) // read, update, save
displayPrice()
}
decrease.setOnClickListener {
intent.setIntExtra(intent.getIntExtra("price") - inc_val) // read, update, save
displayPrice()
}
/*this function just shows price*/
fun displayPrice() {
val price = intent.getIntExtra("price")
productprice.text= "$price\$"
}

Adding data to JSON object with data from variables

So my goal is to have an object variable that will be empty at the start but as the code starts running it would get filled up with data from other varibales. When it gets filled up it should look like this:
var fruits = [banana, apple, ...];
var colors = [yellow, green, ...];
var calories = [300, 250, ...]
//the JSON object
{
banana :
{
"color" : "yellow",
"calories" : 300
},
apple :
{
"color" : "green",
"calories" : 250
},
...
}
As you can see all of the data is supposed to be pulled from other variables and this is where I bump into problems. I've tried the following:
var object.fruits[0] = {colors : calories};
//also tried this
var object.fruits[0] = "{""'" + (colors[0]) + "'":+calories[0]+"}";
//and tried many other things...
I've been failing to counter this for at least an hour now and what makes it worse is that some data is supposed to come from other JSON objects. Any idea how to make it work? Also note that having them in an object array is not a option as the list will be HUGE and therefore the time efficiency will be very poor.
Maybe try something like this
res = {}
fruits.map((key, index) => {
res[key] = {
'color': colors[index],
'calories': calories[index]
}
})
You can do like this but yeah put validations to make sure all three arrays are of equal length.
Whenever you want to add a property to an Object where the property value is a value of another variable it is better to use the bracket notation to add the properties to the object [] as used below.
One more thing better use let and const in place of var.
Finally you can use JSON.stringify() to convert into JSON String from the Javascript Object.
'use strict';
const fruits = ['banana', 'apple'];
const colors = ['yellow', 'green'];
const calories = [300, 250];
const fruits_object = {};
for (let i = 0; i < fruits.length; i++) {
fruits_object[fruits[i]] = {};
fruits_object[fruits[i]]['color'] = colors[i];
fruits_object[fruits[i]]['calories'] = calories[i];
}
console.log(JSON.stringify(fruits_object));
Just do it normally like so:
color: colors[0]
and then call JSON.stringify on the entire object like so
JSON.stringify({color: colors[0]})

Create two child menus for every parent menu in chrome extension

I've searched for this but no luck. I want to create two child menus for every parent menu in Google Chrome extension. But the code I have yet only creates child menus when the context is "page".
Here's the code I'm currently trying:
var contexts = ["page","link","image"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = "";
title = "Do something with this "+context;
var id = chrome.contextMenus.create({"title": title, "contexts":[context]});
var child1 = chrome.contextMenus.create({"title": "someThing1", "parentId": id, "onclick": onClickFunc});
var child2 = chrome.contextMenus.create({"title": "someThing2", "parentId": id, "onclick": onClickFunc});
}
Any idea??
Pretty sure this is answered over here: https://stackoverflow.com/a/18198476/1678601
In short, the create method has an optional param called 'contexts' which defaults to 'page' only.
Here's the doc: http://developer.chrome.com/extensions/contextMenus.html#method-create
So, to demonstrate how to apply the solution to your code (this is only a partial from above):
var child1 = chrome.contextMenus.create({"title": "someThing1", "parentId": id, "onclick": onClickFunc, "contexts": ["page","link","image"]});
var child2 = chrome.contextMenus.create({"title": "someThing2", "parentId": id, "onclick": onClickFunc, "contexts": ["page","link","image"]});

ReSharper chop if long not working

I have the following code that when I run autoformat in ReSharper doesn't not get changed.
I thought Chop if long would cause a chop to occur if the right margin is exceeded.
If I turn on Chop always I get this.
This works, but I would rather not chop short statements like the first, which is what I assume Chop if long means.
Ideas?
Here are my ReSharper settings.
Turning on wrap long lines makes things even worse.
UPDATE1:
Here is the email I sent to JetBrains support.
The believe the central issues I'm facing is I understand the "chop always" setting, but I do not understand "chop if long" or "simple wrap". I have not found any documentation on what these settings mean, so I'm going off what I believe should be happening.
I am setting the "Wrap object collection and initializer".
Chop Always:
cdata.GetByIdData = new Category {
Id = "123",
Name = "category"
};
vdata.GetByIdData = new Vendor {
Id = "456",
Name = "vendor"
};
adata.GetByIdData.Add(new Account {
Id = "789",
Name = "account",
Balance = 5000
});
svc.ExecuteRequest(new AccountTransactionService.Add {
Kind = AccountTransaction.KIND_DEBIT,
Source = "789",
Destination = "dst",
Date = new DateTime(2011, 1, 1),
Categories = new List<AccountTransactionService.CreateCategory> {
new AccountTransactionService.CreateCategory {
Id = "123",
Amount = 200.50m
}
}
});
Chop If Long:
cdata.GetByIdData = new Category { Id = "123", Name = "category" };
vdata.GetByIdData = new Vendor { Id = "456", Name = "vendor" };
adata.GetByIdData.Add(new Account { Id = "789", Name = "account", Balance = 5000 });
svc.ExecuteRequest(new AccountTransactionService.Add { Kind = AccountTransaction.KIND_DEBIT, Source = "789", Destination = "dst", Date = new DateTime(2011, 1, 1), Categories = new List<AccountTransactionService.CreateCategory> { new AccountTransactionService.CreateCategory { Id = "123", Amount = 200.50m } } });
I would expect Chop If Long to look like this given a margin of 80:
cdata.GetByIdData = new Category { Id = "123", Name = "category" };
vdata.GetByIdData = new Vendor { Id = "456", Name = "vendor" };
adata.GetByIdData.Add(new Account { Id = "789", Name = "account", Balance = 5000 });
svc.ExecuteRequest(new AccountTransactionService.Add {
Kind = AccountTransaction.KIND_DEBIT,
Source = "789",
Destination = "dst",
Date = new DateTime(2011, 1, 1),
Categories = new List<AccountTransactionService.CreateCategory> {
new AccountTransactionService.CreateCategory {
Id = "123",
Amount = 200.50m
}
}
});
"Chop if long" works only when you turn on "Wrap long lines" option, so you should turn it on. I guess that http://youtrack.jetbrains.com/issue/RSRP-291146 prevented you from getting the formatting you wanted with "Wrap long lines" turned on. Well, it should be fixed in ReSharper 7.1 EAP - try and write us if you still have problems.
Change "Wrap object collection and initialisers" to "Simple Wrap", that should style your code in the way you want it to.
Unfortunately, I can't look up what Chop if long is supposed to do as the Resharper community site is blocked from work for some strange reason.
There is an issue logged with JetBrains that is depicting the same behavior you describe...
http://youtrack.jetbrains.com/issue/RSRP-291146

Resources