Dart compare two strings return false - dart

Im new to dart and have a problem during building my Flutter application.
I have a firestore database as a backend and im getting data from there.
When i want to compare part of the data called status with the text 'CREATED', using == comparator, dart will return false.
Can someone explain why and how to check it properly?
rideObject is a Map
Update:
Here is the function that has the condition in it:
Widget _getPage() {
if (rideObject == null) {
return OrderRidePage(
address: address,
ridesReference: reference,
setRideReference: this._setRideReference);
} else {
print(rideObject['status']);
if (rideObject['status'] == "CREATED") {
return LoadingPage(
removeRideReference: this._removeRideReference,
rideReference: rideReference);
} else {
return RidePage(
address: address,
ridesReference: reference,
setRideReference: _setRideReference);
}
}
}
The print statement returns to output:
I/flutter (15469): CREATED
Here you can see the structure of the rideObject
Funnily enough, the rideObject["status"] is String type as shown in here in console:
rideObject["status"] is String
true
"CREATED" is String
true
rideObject["status"]
"CREATED"
rideObject["status"] == "CREATED"
false

The String you got from your server is probably encoded and contains special character which you can't see, try to compare the hex values of both of the strings, and then replace all the special characters from the String returned by the server.
Using this, you can see the actual non visible difference between the two strings:
var text1 = utf8.encode(hardcodedText).toString();
var text2 = utf8.encode(textFromServer).toString();

If both are really strings, you can use "compareTo" which will return 0 if both are equal.
if(str1.compareTo(str2)==0){
}
It is explained here:
https://www.tutorialspoint.com/dart_programming/dart_programming_string_compareto_method.htm

I don't have a particular solution to this, but I updated to latest Flutter version that came up today, moved the "CREATED" string into constant and resolved an unrelated warning for another part of the application, and it suddenly started to work.

The answer for this problem is in the documentation of flutter:
https://api.flutter.dev/flutter/dart-core/String/compareTo.html
you can do:
(var.compareTo('WORD') == 0)
are equivalent
.compareTo()
Returns a negative value if is ordered before, a positive value if is ordered after, or zero if and are equivalent.thisother

Building off #yonez's answer, the encoding may be different after a string has been passed through a server.
Instead of: String.fromCharCodes(data)
Try using: utf8.decode(data)

Related

How to find record using $type in mongodb?

I am using ruby on rails with MongoDB. I have one field 'possession' as string type field. I've updated it as 'Integer'.
Now, I want to find old data with specific string(for example, '6') and need to update all as integer values(means 6).
So, instead of doing each loop on all record I will just distinct values and update_all based on distinct values.
Please let me know if anyone has idea about this.
To find data using $type you can use type value as 2 for string. And using forEach function you can update the records.
You can use this query:
db.collection.find({
possession: {
$type: 2
}
}).forEach(function(data){
db.collection.update({
"$set": {
"possession": parseInt(data.possession)
}
})
})
I think #Mayuri has the right idea, but unfortunately did not test their answer. I get an error when I run their code. here is a fix to their solution. I used mongo shell to test...
I also took the liberty of using the $type string name instead of a number code.
db.collection.find({
possession: {
$type: "string"
}
}).forEach(function(data){
db.collection.update({"_id": data._id}, {
"$set": {
"possession": parseInt(data.possession)
}
})
})

MapKit Define the desired type of search results (Country, city, region, etc)

For an app i'm building, I want to implement a feature that allows users to specify the geographical origin of wines (country (e.g. France), region (e.g. Bordeaux), subregion (e.g. Paullac)).
I want to make sure that I don't have to add all available countries myself, and that all information that comes into the database is valid. Therefore, I decided to do it as follows:
User adds a new wine and types the name of the country it comes from
While typing, the app searches in the apple maps database
The results from this search get displayed as suggestions, and when the user taps a suggestion, the app creates a Country object with all relevant information. The wine van only be saved when such an object is present
This works fine, except one thing: Apple maps returns anything, like restaurants, shops, etcetera, from anywhere.
My question: How can I specify WHAT I am looking for? I can only specify the region I'm searching in, which is irrelevant in my case. I would like to be able to tell apple maps to ONLY look for countries, regions, cities, whatever. Is this possible in a way? I have exhausted google for this and found no way thus far.
Going off what #Trevor said, I found rejecting results where either the title or subtitle have numbers yields pretty good results if you only want cities and towns.
Swift 4.1 code:
// Store this as a property if you're searching a lot.
let digitsCharacterSet = NSCharacterSet.decimalDigits
let filteredResults = completer.results.filter { result in
if result.title.rangeOfCharacter(from: digitsCharacterSet) != nil {
return false
}
if result.subtitle.rangeOfCharacter(from: digitsCharacterSet) != nil {
return false
}
return true
}
or more compactly:
let filteredResults = completer.results.filter({ $0.title.rangeOfCharacter(from: digitsCharacterSet) == nil && $0.subtitle.rangeOfCharacter(from: digitsCharacterSet) == nil })
The best solution we found was to filter our results using a comma in the result's title. This mostly returned only results that matched a city's format, e.g Detroit, MI, United States. We added this filter to the ones suggested by #Ben Stahl. Ben's solution filtered out edge cases where a comma formed part of the business' name.
This usually returns the correct result within three characters. To answer the OP's question, you could then parse this string by city, state or country to get the desired result.
For better results you could use the Google Places API.
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
self.searchResults = completer.results.filter { result in
if !result.title.contains(",") {
return false
}
if result.title.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil {
return false
}
if result.subtitle.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil {
return false
}
return true
}
self.searchResultsCollectionView.reloadData()
}
I have worked with MapKit and don't believe you can do autocomplete assistance on user entries as they type the best solution I found is Google Place API autocomplete
iOS right now provides receiving geo-coordinates when sending a well-formatted address , or you can receive an address when sending a pair of coordinates. Or points of interest for locations names or coordinates.
There was a class added to MapKit in iOS 9.3 called MKLocalSearchCompleter which helps with autocompletion. You can filter what is returned by using 'MKSearchCompletionFilterType' but that isn't the most extensive and might not fully help with your situation. It does return cities and countries as results but it also returns businesses when I've used it.
One possible option is to filter the returned results again on the app side and exclude all results that have a numeric character in them.
func setupCompleter() {
self.searchCompleter = MKLocalSearchCompleter()
self.searchCompleter?.delegate = self
self.searchCompleter?.filterType = .locationsOnly
self.searchCompleter?.queryFragment = "Bordeaux"
}
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
print("Results \(completer.results)")
// Do additional filtering on results here
}
In addition to Allan's answer, I've found that if you filter by the subtitle property of a MkLocalSearchCompletion object, you can remove the business entries.

Array.size() returned wrong values (Grails)

I'm developing an app using Grails. I want to get length of array.
I got a wrong value. Here is my code,
def Medias = params.medias
println params.medias // I got [37, 40]
println params.medias.size() // I got 7 but it should be 2
What I did wrong ?
Thanks for help.
What is params.medias (where is it being set)?
If Grials is treating it as a string, then using size() will return the length of the string, rather than an array.
Does:
println params.medias.length
also return 7?
You can check what Grails thinks an object is by using the assert keyword.
If it is indeed a string, you can try the following code to convert it into an array:
def mediasArray = Eval.me(params.medias)
println mediasArray.size()
The downside of this is that Eval presents the possibility of unwanted code execution if the params.medias is provided by an end user, or can be maliciously modified outside of your compiled code.
A good snippet on the "evil (or lack thereof) of eval" is here if you're interested (not mine):
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
I think 7 is result of length of the string : "[37,40]"
Seems your media variable is an array not a collection
Try : params.medias.length
Thanks to everyone. I've found my mistake
First of all, I sent an array from client and my params.medias returned null,so I converted it to string but it is a wrong way.
Finally, I sent and array from client as array and in the grails, I got a params by
params."medias[]"
List medias = params.list('medias')
Documentation: http://grails.github.io/grails-doc/latest/guide/single.html#typeConverters

action script 2.0 simple string comparing with conditional statement

So I have this crazy problem with comparing 2 strings in ActionScript 2.0
I have a global variable which holds some text (usually it is "statistic") from xml feed
_root.var_name = fields.firstChild.attributes.value;
when I trace() it it gives me the expected message
trace(_root.var_name); // echoes "statistik"
and when I try to use it in conditional statement the rest of code is not being executed because comparing :
if(_root.overskrift == "statistik"){
//do stuff
}
returns false!
I tried also with:
if(_root.overskrift.equals("statistik"))
but with the same result.
Any input will be appreciated.
Years later but on a legacy project I had the same problem and the solution was in a comment to this unanswered question. So let's make it an anwer:
Where var a:String="some harmless but in my case long string" and var b:String="some harmless but in my case long string" but (a==b) -> false the following works just fine: (a.indexOf(b)>=0) -> true. If the String were not found indexOf would give -1. Why the actual string comparison fails I coudn't figure out either. AS2 is ancient and almost obsolete...

saveChanges fails if key has a Date field (version 1.2.8)

We have an entity with three key fields, one of which is a date (don't ask - its a summary view with no other obvious key).
Breeze is throwing "This key is already attached" error when processing the response from the server after saving changes to the aforementioned entity.
The problem occurs in MergeEntity after saving changes. It seems that the initial lookup fails to find the entity on the client, so it tries to add it again resulting in the error.
Near the top of MergeEntity we find the following line...
var entityKey = EntityKey._fromRawEntity(node, entityType);
...which returns an entityKey._keyInGroup == "1535:::44:::2013-02-28T11:00:00.000Z". Note the third key field which looks like the JSON date string.
Later, when the new entity is (incorrectly) created its entityKey._keyInGroup == "1535:::44:::Fri Mar 01 2013 00:00:00 GMT+1300 (New Zealand Daylight Time)". Now the third field looks like a true javascript date.
The error finally occurs when we hit this line...
attachEntityCore(em, targetEntity, EntityState.Unchanged);
...get the "This key is already attached" error as the entity we've just saved was obviously already in the client cache all along.
Update: My hacks to Breeze to get this working...
1) I changed the _fromRawEntity function to check for dates and convert them properly so we get the same key values that are produced later for the real entity. (This code was copied from the updateEntity function so should behave identically).
ctor._fromRawEntity = function (rawEntity, entityType) {
var keyValues = entityType.keyProperties.map(function (p) {
var val = rawEntity[p.nameOnServer];
if (p.dataType.isDate && val) {
if (!__isDate(val)) {
val = DataType.parseDateFromServer(val);
}
}
return val;
});
return new EntityKey(entityType, keyValues);
};
2) Breeze now found the entity after saving changes but... I then got an error when Breeze tried to update the entities properties using the values returned from the server. I suspect this is due to an issue in the defaultPropertyInterceptor function which was checking to see if the property value had changed...
// exit if no change
if (newValue === oldValue) {
return;
}
This will always return false when comparing dates so I hacked this line to be:
if (newValue === oldValue || (dataType && dataType.isDate && newValue && oldValue && newValue.valueOf() === oldValue.valueOf())) {
return;
}
From my initial testing everything seems to be working but I'd greatly appreciate any thoughts from folks who are more familiar with breeze :)
Updated: Perhaps the last snippet would be more breeze-ish as...
// exit if no change
var comparable = dataType && getComparableFn(dataType);
if (newValue === oldValue || (comparable && comparable(newValue) === comparable(oldValue))) {
return;
}
...although that adds a bit more code considering it is running in every property set.
Edit: This was fixed in Breeze v1.3.0, available now.
Agreed, this is a bug! It will be fixed in the next release, out early next week. ( and we now have a test that involves a date as part of a primary key :)
and thanks for finding, analyzing and reporting it. The analysis really helped.

Resources