can we use two criterias in sort - sorting

I have been using the following code for sorting a domain's results
vpisort.sort{it.price}
I was wondering If i could use something like
vpisort.sort{it.price-it?.discount}

I've found this post. You can try using this in your case:
vpisort.sort { a, b -> a.price <=> b.price ?: a?.discount <=> b?.discount }
It comapres price first and then, only if a and b are equal by price and result is zero, using Elvis operator it compares a and by by discount.

hm. This is not a grails, but a groovy question. With this in mind, the solution is simple:
open the groovy console and give your line a try. Or check out these examples:
http://groovy.codehaus.org/JN1015-Collections
there is also another question like this one on SO:
Groovy list.sort by first, second then third elements
hope that helps!
Update: If you want to have a default sort order for your domain class, take a look at this GORM feature: http://grails.org/doc/latest/guide/single.html#ormdsl (5.5.3 Default Sort Order)

Related

Evaluating an expression in the head of the clause

Is there any way to evaluate this sum inside the findall/3 clause?
findall((A+C,[M,H|_]),(b_to_b(H,M,C),\+ member(M,[H|T])),R).
Here i get values like (1+3,List) and i'm looking for some shortcut so that i get value 4 instead of (1+3)
I understand what is the problem but a shortcut will be nice otherwise i have to revisit the whole list and that's not nice.
Thanks
Assuming A has already been binded to a numeric, just move the evaluation from the template to the goal:
...,
findall((S,[M,H|_]),(b_to_b(H,M,C),\+ member(M,[H|T]), S is A+C),R).
Efficiency hint: you should also change member/2 to memberchk/2.

Why is List.sort method striked through?

I have a map of errors and the number of their occurrences in some situation. I want to have a list, which contains that information in order of descending number of errors (i. e. the most frequent error is first element, the second-most - the second etc.).
I wrote following code:
List<Map.Entry<String,Integer>> entryList = new ArrayList<>(errors.entrySet());
entryList.sort{a, b -> b.value <=> a.value}
It works fine, but the sort is striked through (in Eclipse IDE with the Groovy plugin).
Why? Is that method deperecated? If so, what is the correct way to sort a list in Groovy?
Use the Iterable version of sort instead
Because of deprecation - have a look at the docs. Some of sort methods are deprecated in favor of others.

Ndepend find actual number of method usages

Let's say I have method A.M1.
It is called in B.M2 2 times and in B.M3 3 times.
I need to find all number of usages (like Resharper does through find usages interface). So the sum for method calls would be 5.
Following Query:
from m in Methods
where m.HasAttribute("specific attribute")
orderby m.MethodsCallingMe.Count() descending
select new { m, m.MethodsCallingMe }
gives me only 2 usages for method A.M1.
Could you please help me to find the usages number?
It's difficult or impossible to do with NDepend. NDepends shows which methods are calling specified method and not count in this situation them and even not count them recursively or through call graph.
So try to use other techniques. By first of all, why you need such metric? Some kind of method rank?
Anyway a pretty simple way to achieve it, is using RegEx experssion. You can use also NDepend API or regex and ndepend api together. For example, get all method names from source code base using nDepend API and then using regex for each method name count matches except method definition itself.

Ruby: Best way to parse a conditional array element

I'm doing API calls that will conditionally return a couple different elements. My code is currently:
if array['productId']
value = array['productId'][0]
end
I feel like there is a more succinct way of doing this. Some Ruby magic.
A better way :
value = array['productId'][0] if array['productId']
However, array['productId'][0] is not ruby natural. What does your array consist of ?
Since Ruby 2.3.0, the shortest way is Array#dig:
array.dig('productId', 0)
http://ruby-doc.org/core-2.3.0_preview1/Array.html#method-i-dig
I am not sure if you are using value just temporarily or actually using it later, and what you want to do with value when the condition is not met. If you want to return nil for missing keys, then
array['productId'].to_a[0]
can work. Otherwise, SpyrosP's answer will be the best.
This might be a bit pedantic, but to make sure it works in all circumstances, you should not check 'not-nil', but rather that it is indexable; something like this:
value = array['productId'][0] if array['productId'].is_a? Array
Or even better:
value = array['productId'][0] if array['productId'].respond_to? '[]'
Otherwise your code will fail if array['productId'] == 2 (which on the other hand seems reasonable, given the key used - I would have gone product_ids instead).
You could use a ternary:
value = array['productId'].nil? ? nil : array['productId'][0]
Your code pattern looks OK; it's possible to be slightly shorter...
value = (t = x['productId']) && t[0]
Using the maybe pattern of Ick, terse and explicit:
value = array['productId'].maybe[0]
While I think your code is fine (although I'd prefer SpyrosP's one-line version), you have some possibilities:
Rails has Object#try, which would let you do either array['productId'].try(:[], 0) or array['productId'].try(:at, 0).
Some people like the andand gem, which defines Object#andand and is used like array['productId'].andand[0].
Ha, I love all the options here. But since I didn't see what I use most, I'll add one more!
value = array['productId'] && array['productId'].first
(I prefer .first to [0] because it reads a little better)
This presumes you'll have an array in array['productId'], which is the right way to do it (rather than type-checking).
Otherwise, the biggest diference between this and your original code, is that this results in value having nil assigned to it if the array doesn't have anything, whereas your original results in value not being defined (which may cause errors, depending on how you use it down the road).
Hope that helps!

Why is Ruby's Array.map() also called Array.collect()?

Whenever I see Ruby code that says:
arrayNames.collect { ... }
I forget what collect is and have to look up what it is, and find that it is the same as map().
Map, I can understand, mapping 1 byte to a pixel, and function is to map an x to a y, a 2 to a 4, a 5 to a 25, etc. But where does the name "collect" come from? Maybe that will help to remember what a "collect" method is.
It comes from Smalltalk old days. Smalltalk used collect and select instead of map and filter (as used in many other languages) for iterating on its collections.
To add to the other answers, it is kind of an inside-joke in Smalltalk:
inject:into:
collect:
select:
reject:
detect:
Spot the pattern?
kriss is right that the method name has its origins in Smalltalk but to help remember what it does when you see it used you can think of it as "collecting the results from the block in a new array".

Resources