Returning variable from method - variables

for(Element synonym: Words){
synonyms.add(synonym);
}
return synonyms.get(7);
}
i am retrieving an unknown amount of words every time i add a synonym to the synonyms list, so if i try access a portion of the list that doesnt exist (eg. element 7 when there are only 3), i get an index out of bounds error, how can i check to see if the element exists and if it doesn't, return something else?
i have tried checking to see if there is an element or not but i dont know how

Short answer would be to check for the length of the array for the index that you want to return. If it exists, return that, otherwise do something else.
return synonyms.length == 7 ? synonyms.get(7) : somethingElse;

Related

Kotlin error "Index Out Of Bounds Exception"

I'm newbie to Kotlin, and new to programming also, so pls be gentle :)
Let's say I have a string (it was optimized to NOT have any duplicated character), i want to compare all characters in that string to the alphabet, which declared as a mutable List of character. I want to delete any character from the alphabet which show up in the string. My code is as below
var alphabet=mutableListOf('a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z')
var key="keyword"
println(key)
for (i in key.indices)
{for (j in alphabet.indices)
{if (key[i] == alphabet[j])
alphabet.removeAt(j) // 1. this line have error
//print(alphabet[j]) //2. but this line runs fine
}}}
In above code, I have error at the "alphabet.removeAt(j)" command, so I try another command to print out the characters instead of delete them, and it runs fine. I read some articles and I know this error related to the invalid index, but I used the "indices" key and I think it's pretty safe. Pls help
It is safe to iterate using alphabet.indices, but it is not safe to iterate over a collection while modifying it. Note that indices returned indices for a full alphabet, but then you removed some items from it, making it shorter, so indices are no longer valid.
You don't need to iterate over a collection to find an item to remove. You can just do:
alphabet.remove(key[i])
But honestly, you don't need to do anything of this. Your problem is really a subtracting of two sets and you can solve it much easier:
('a'..'z').toSet() - "keyword".toSet()
You could simplify that whole loop to just:
alphabet.retainAll{ it !in key })
or
alphabet.retainAll { !key.contains(it) }
or if you want the filtered list to be a new list rather than doing it in-place:
val filtered = alphabet.filter { it !in key }
but I used the "indices" key and I think it's pretty safe
Well, the indices collection is only evaluated once when a loop is entered, not at the start of each iteration. Even if you change the size of alphabet in the inner loop, the inner loop will still loop the same number of times, because it doesn't evaluate alphabet.indices again. It would only do that again on the next iteration of the outer loop, but your code would throw an exception before that point.
Other than decreasing j whenever you remove an item, you can also solve this by
key.forEach(alphabet::remove)

Karate - Not able to match each with != [] [duplicate]

I have json object in response. If I try an invalid path to extract value and assert it with match each it always passes.
* match each karate.jsonPath(response,"$[*].non.existing.path") == ["text1"]
Am I doing something wrong here?
Please Not: If I give correct path and the value doesn't match with 'text1' it fails. Absolutely no issue there. Seeing issue only with invalid json path.
Yes, this is by design. match each is actually a loop. If the number of items is zero, the match will never be applied.
If you want to ensure that the array needs to be non-empty, add a second check.
* def foo = [1, 2]
* match foo == '#[_ > 0]'
* match each foo == '#number'
I faced with a situation when my response had an empty array. When i matched it with any value it was passed. Example:
* match each array == '#(value)'

What are the advantages of returning -1 instead of null in indexOf(...)?

When calling List.indexOf(...), what are the advantages of returning -1 rather than null if the value isn't present?
For example:
val list = listOf("a", "b", "c")
val index = list.indexOf("d")
print(index) // Prints -1
Wouldn't it be a cleaner result if index was null instead? If it had an optional return type, then it would be compatible with the elvis operator :? as well as doing things such as index?.let { ... }.
What are the advantages of returning -1 instead of null when there are no matches?
Just speculations but i could think of two reasons:
The first reason is to be compatible with Java and its List.indexOf
As the documentation states:
Returns:
the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element
The second reason is to have the same datatype as kotlins binarySearch.
Return the index of the element, if it is contained in the list within the specified range; otherwise, the inverted insertion point (-insertion point - 1). The insertion point is defined as the index at which the element should be inserted, so that the list (or the specified subrange of list) still remains sorted.
Where the negative values actually hold additional information where to insert the element if absent. But since the normal indexOf method works on unsorted collections you can not infer the insertion position.
To add to the definitive answer of #Burdui, another reason of such behavior is that -1 return value can be expressed with the same primitive Int type as the other possible results of indexOf function.
If indexOf returned null, it would require making its return type nullable, Int?, and that would cause a primitive return value being boxed into an object. indexOf is often used in a tight loop, for example, when searching for all occurrences of a substring in a string, and having boxing on that hot path could make the cost of using indexOf prohibitive.
On the other hand, there definitely can be situations where performance does not so matter, and returning null from indexOf would make code more expressive. There's a request KT-8133 to introduce indexOfOrNull extension for such situations.
Meanwhile a workaround with calling .takeIf { it >= 0 } on the result of indexOf allows to achieve the same.

How to do without delete_if for Active Record?

When I do:
apartments = Apartment.where(apart_params).delete_if{|x| x.floor == x.max_floor }
Ruby's array method delete_if on Active record Relation object results in
NoMethodError (undefined method `delete_if' for #<Apartment::ActiveRecord_Relation:0x00000006d84ea0>
Did you mean? delete
delete_all):
I don't understand why it happens - this object seems to respond like a plain array...
Is there any smarter alternative except using plain each do block?
Maybe you can give an advise on making smart SQL (postgres) query to reject those apartments which are on the last floor?
The relation can be converted to an array and then delete_if can be called:
Apartment.where(apart_params).to_a.delete_if {|x| x.floor == x.max_floor }
About a smarter way, it depends if the floor and max_floor methods are columns. If so, then:
Apartment.where(apart_params).where.not("floor = max_floor")
I would suggest switching your apartments assignment to the following:
apartments = Apartment.where(apart_params).map{|x| x.floor == x.max_floor ? x.delete : x }
Even if the Apartment.where(apart_params) looks like a Array object, it isn't! As the error says, it returns a ActiveRecordRelation, that is not a Array. So, if you want to use array methods on a ActiveRecordRelation, you have to convert your object to a array with to_a
apartments = Apartment.where(apart_params).to_a.delete_if{|x| x.floor == x.max_floor }

How to use Get command in Monkey talk?

Does anybody know how to use the Get command in monkey talk?
In monkey talk guide only the command is written but no syntax is present.
Here is an example for you,
var x = app.label("label1").get("x","value")
Above line will get the value of label1 and store it in variable x. You can change the second parameter "value" to ".text" or ".size" depending on your needs
since the question is not marked Answered and For the future reference i am answering this.
‘GET’ ACTION RETRIEVES COMPONENT PROPERTY VALUES
Syntax:
ComponenType MonkeyId Get varName propName
Works like an assignment statement (varName= propName)
The default property is “value”
// Get label value currently displayed
Label lastname Get name
// Enter name into input field
Input query EnterText ${name}
// Get the first table item
Table countries Get country items1
// Enter into input field
Input * EnterText ${country}
you can refer this document here, thanqs
I will try to explain using example. Suppose there is a ListView(Table) and you want to scroll till its last item.
//Define a variable
Vars * Define row
//Store size of list in variable row using Get. Check use of "Get" here
Table * Get row size %thinktime=20000
//Now stored variable can be used as per need. here I am using for scrolling
Table * ScrollToRow ${row} %thinktime=2000
Hope it helps you !!