Receiving "not found: value" even the variable is define - scala

I'm receiving not found: value counter even though the variable is defined.
Any help with this? I'm new with scala and everything is new to my eyes. Thanks
#{def counter = 0}
#for(atg <- Activity.groupContiguous(activityGroup)) {
#if(!atg.isEmpty) {
#views.html.activity.activityTypeGroup(atg, counter))
}
counter = counter + 1
}

You code doesn't work because #{def counter = 0} doesn't define anything in the template scope and returns Unit. I don't know any convenient way to define mutable variable in the scala template, and this is actually discouraged.
The code could be easily rewritten using functional approach:
#for((atg, counter) <- Activity.groupContiguous(activityGroup).filterNot(_.isEmpty).zipWithIndex) {
#views.html.activity.activityTypeGroup(atg, counter))
}

Take a look to other similar issue, you can solve it with zipWithIndex https://stackoverflow.com/a/14613877/1066240
Yo'll find there also other useful examples.

Related

ranges::views::generate have generator function signal end of range

I'd like to have a generator that terminates, like python, but I can't tell from ranges::views::generate's interface if this is supported.
You can roll it by hand easily enough:
https://godbolt.org/z/xcGz6657r although it's probably better to use a coroutine generator if you have one available.
You can return an optional in the generator, and stop taking elements when a std::nullopt is generated with views::take_while
auto out = ranges::views::generate(
[i = 0]() mutable -> std::optional<int>
{
if (i > 3)
return std::nullopt;
return { i++ };
})
| ranges::views::take_while([](auto opt){ return opt.has_value();})
;

Should 'require' go inside or outside of the Future?

How do I replace my first conditional with the require function in the context of a Future? Should I wrap the entire inRange method in a Future, and if I do that, how do I handle the last Future so that it doesn't return a Future[Future[List[UserId]], or is there a better way?
I have a block of code that looks something like this:
class RetrieveHomeownersDefault(depA: DependencyA, depB: DependencyB) extends RetrieveHomeowners {
def inRange(range: GpsRange): Future[List[UserId]] = {
// I would like to replace this conditional with `require(count >= 0, "The offset…`
if (count < 0) {
Future.failed(new IllegalArgumentException("The offset must be a positive integer.")
} else {
val retrieveUsers: Future[List[UserId]] = depA.inRange(range)
for (
userIds <- retrieveUsers
homes <- depB.homesForUsers(userIds)
) yield FilterUsers.withoutHomes(userIds, homes)
}
}
}
I started using the require function in other areas of my code, but when I tried to use it in the context of Futures I ran into some hiccups.
class RetrieveHomeownersDefault(depA: DependencyA, depB: DependencyB) extends RetrieveHomeowners {
// Wrapped the entire method with Future, but is that the correct approach?
def inRange(range: GpsRange): Future[List[UserId]] = Future {
require(count >= 0, "The offset must be a positive integer.")
val retrieveUsers: Future[List[UserId]] = depA.inRange(range)
// Now I get Future[Future[List[UserId]]] error in the compiler.
for (
userIds <- retrieveUsers
homes <- depB.homesForUsers(userIds)
) yield FilterUsers.withoutHomes(userIds, homes)
}
}
Any tips, feedback, or suggestions would be greatly appreciated. I'm just getting started with Futures and still having a tough time wrapping my head around many concepts.
Thanks a bunch!
Just remove the outer Future {...} wrapper. It's not necessary. There's no good reason for the require call to go inside the Future. It's actually better outside since then it will report immediately (in the same thread) to the caller that the argument is invalid.
By the way, the original code is wrong too. The Future.failed(...) is created but not returned. So essentially it didn't do anything.

For loop not executing in protractor

I am able to get the count value with the following:
element.all(by.options('type as type for type in types')).then(function(elems){
return elems.length;
})
.then(function(count){
cnt = count;
});
Then later in the code I want to use cnt in a for loop where I also use closure:
for(var x = 1;x < cnt; x++){
search_options(x);
}
function test(y){
console.log('input'+y);
}
function search_options(input){
it('tess', function(){
test(input);
});
}
The problem is that the for does not execute.
Any tips or suggestions, guidance is appreciated or point out any errors.
I have read about IIFE but I find most samples use arrays, I believe 'cnt' has resolved
Unfortunately, I have to use the for loop. 'each' is not suitable.
The problem is that cnt would only be set when the promise would be resolved by the control flow mechanism. The for loop would be executed earlier.
Instead, define cnt as a promise and resolve it in your test:
cnt = element.all(by.options('type as type for type in types')).count();
cnt.then(function (actualCount) {
for(var x = 1; x < actualCount; x++){
search_options(x);
}
});
Also see: Using protractor with loops.
Also, I'm not exactly sure if dynamically creating its this way would actually work, here are some relevant threads:
https://github.com/jasmine/jasmine/issues/830
Can I dynamically create a test spec within a callback?

Play! + Scala: Split string by commnas then Foreach loop

I have a long string similar to this:
"tag1, tag2, tag3, tag4"
Now in my play template I would like to create a foreach loop like this:
#posts.foreach { post =>
#for(tag <- #post.tags.split(",")) {
<span>#tag</span>
}
}
With this, I'm getting this error: ')' expected but '}' found.
I switched ) for a } & it just throws back more errors.
How would I do this in Play! using Scala?
Thx in advance
With the help of #Xyzk, here's the answer: stackoverflow.com/questions/13860227/split-string-assignment
Posting this because the answer marked correct isn't necessarily true, as pointed out in my comment. There are only two things wrong with the original code. One, the foreach returns Unit, so it has no output. The code should actually run, but nothing would get printed to the page. Two, you don't need the magic # symbol within #for(...).
This will work:
#for(post <- posts)
#for(tag <- post.tags.split(",")) {
<span>#tag</span>
}
}
There is in fact nothing wrong with using other functions in play templates.
This should be the problem
#for(tag <- post.tags.split(",")) {
<span>#tag</span>
}

Scala: concise way to express the following construct

I'll give some C-style "bracket" pseudo-code to show what I'd like to express in another way:
for (int i = 0; i < n; i++) {
if (i == 3 || i == 5 || i == 982) {
assertTrue( isCromulent(i) );
} else {
assertFalse( isCromulent(i) );
}
}
The for loop is not very important, that is not the point of my question: I'd like to know how I could rewrite what is inside the loop using Scala.
My goal is not to have the shortest code possible: it's because I'd like to understand what kind of manipulation can be done on method names (?) in Scala.
Can you do something like the following in Scala (following is still some kind of pseudo-code, not Scala code):
assert((i==3 || i==5 || i==982)?True:False)(isCromulent(i))
Or even something like this:
assertTrue( ((i==3 || i==5 || i==982) ? : ! ) isCromulent(i) )
Basically I'd like to know if the result of the test (i==3 || i==5 || i==982) can be used to dispatch between two methods or to add a "not" before an expression.
I don't know if it makes sense so please be kind (look my profile) :)
While pelotom's solution is much better for this case, you can also do this (which is a bit closer to what you asked originally):
(if (i==3||i==5||i==982) assertTrue else assertFalse)(isCromulent(i))
Constructing names dynamically can be done via reflection, but this certainly won't be concise.
assertTrue(isCromulent(i) == (i==3||i==5||i==982))
Within the Scala type system, it isn't possible to dynamically create a method name based on a condition.
But it isn't at all necessary in this case.
val condition = i == 3 || i == 5 || i == 982
assertEquals(condition, isCromulent(i))
I hope nobody minds this response, which is an aside rather than a direct answer.
I found the question and the answers so far very interesting and spent a while looking for a pattern matching based alternative.
The following is an attempt to generalise on this (very specific) category of testing:
class MatchSet(s: Set[Int]) {def unapply(i: Int) = s.contains(i)}
object MatchSet {def apply(s: Int*) = new MatchSet(Set(s:_*))}
val cromulentSet = MatchSet(3, 5, 982)
0 until n foreach {
case i # cromulentSet() => assertTrue(isCromulent(i))
case i => assertFalse(isCromulent(i))
}
The idea is to create ranges of values contained in MatchSet instances rather than use explicit matches.