Apache Velocity : is it possible to initialize many variables using one #set directive? - velocity

I'm looking for something on the lines of
#set($a = 0, $b = 0)
or
#set($a, $b = 0)
Neither of the above works.
The only alternative I can think of is to initialize an array, and refer each element by its index, but find that a bit cumbersome.
Thanks.

It is not possible to initialize several values in the same statement.
What you could do, for Velocity 2.1+, is just skip initialization and use in-place default values:
${a|0}
will render $a if it exists (or if it is the boolean value false), or 0 otherwise.

Related

Using Numpy.where() with a function on each element

I have a rather complicated function, say:
def func(elem):
// blah blah blah
return True
// blah blah blah
return False
I wish to use the numpy.where() function along the lines of
arr2 = np.where(func(arr1), arr1, 0)
But when I try this syntax and debug, I see that in func, that the entire array is passed rather than individual elements. The typical use cases I see in the documentation/examples only rely on simple comparators like arr < 5, but I need something quite a bit fancier that I don't want to try and write in a single line.
If this is possible, or if there is some vectorized substitute (emphasis on efficiency), any insights appreciated.
I figured out how to do it by using np.vectorize, followed by a list comprehension, not np.where. Maybe from this, one can find out a way to use numpy rather than of a list comprehension.
func_vec = np.vectorize(func)
[arr1 if cond else 0 for cond in func_vec(arr1)]
Anyways, by using func_vec(arr1) you get the True/False values per element.
Note: If you want a new array like arr1, replacing by 0 the elements that return False in your function, then this should work:
arr2 = np.where(func_vec(arr1), arr1, 0)
Edit:
Indeed, np.vectorize is not optimized to performance (by bad), is essentially a for loop under the hood. So I would recommend trying to write your function in a vectorized way rather than trying to vectorize it thereafter.
For example, try converting a function like this:
def func(elem):
if elem > 5:
return True
else:
return False
to something like this:
def func(elem):
return elem > 5
so that you can easily apply func(arr1) without error.
If you really have a function that returns just True or False, I'm pretty sure you can do it, regardless of its complexity. Anyways we're here to help you out!
It seems like you try to get the elements of arr1 you want using func function, but judging from the definition func works for a single element. You need a True/False array of the same shape as arr1 to do so.
If I get it right, a potential solution would be to modify func to operate on the whole array and not only on one element and return the True/False array of shape arr1.shape you need for np.where, since you want to do it in a single line that way.

Checking if condition on Long type for velocity template

Long type from java is not working with velocity if condition
I am using velocity engine for email with Java where one of the variables type is Long.
While trying if condition on that variable it never succeeds.
Tried following ways but none was helpful,
#if($customTypeList.LongTypeId == 1)
#if($customTypeList.LongTypeId == '1')
#if($customTypeList.LongTypeId == "1")
It should go inside the if condition as variables value is 1.
I have validated that with sysout and even by printing in template.
Actually got the answer after number of trials...
Posting to help others.
#if($customTypeList.longTypeId.intValue() == 1)

List repetition (xx) without evaluation?

The list repetition operator (xx) evaluates the list every time it is repeated. For example,
my #input = get() xx 5;
will evaluate to the first 5 lines of STDIN. Is there any way I can repeat just the value of the element 5 times, rather than evaluating it each time? Currently, I've been assigning it to a variable, then repeating it, but it seems a bit cumbersome that way.
my $firstLine = get();
my #firstlineRepeated = $firstLine xx 5;
Is there a prefix or something that lets me do it in one statement?
Using given to contextualize it into $_ is one fairly neat way:
my #input = ($_ xx 5 given get());
say #input;
That, when I type hello, gives:
[hello hello hello hello hello]
Since given simply contextualizes, rather than doing any kind of definedness or truth test, it's a bit safer as a general pattern than andthen.
You could try use the andthen operator:
my #input = (get() andthen $_ xx 5);
From the documentation:
The andthen operator returns Empty upon encountering the first
undefined argument, otherwise the last argument. Last argument is
returned as-is, without being checked for definedness at all.
Short-circuits. The result of the left side is bound to $_ for the
right side, or passed as arguments if the right side is a Callable,
whose count must be 0 or 1.
Using phrase ENTER works too
my #input = ENTER { get() } xx 5;

What's the meaning of 'i' in for loop?

In almost every programming language, they use variable i when they explain for loop. Like,
for i in 'string':
print(i)
or
for(var i ; i<100 ; i++) {
console.log(i);
}
etc...
Does it mean anything? Or just a variable with no meaning?
I couldn't find any information about this in google search.
You have given two different example.
For the first one
for i in 'string':
print(i)
For this one, the variable 'i' is the variable where the value will be put from your parameter (here 'string'). If i gave an array as parameter for instance, each value of array will be put in 'i', step by step (element [0], then element[1], etc...).
Note that this is a simplified view of this question and it doesn't work exactly like that for the program. But you can understand it as it.
For the second one
for(var i ; i<100 ; i++) {
console.log(i);
}
You declare explicitly a variable to be used. This declared will be used by the loop, incrementig by the step you had defined until it reaches limit you also defined.
It is slightly the same thing for both example. Hope i explain well
it is just a common practice. Many people when learning see i being used as a variable name. But that's all it is. It is just a name that could be anything, you could us any other sequence of characters!
i is just a variable. Generally, it is referred to as "iteration for the loop".

Accessing the last element in Perl6

Could someone explain why this accesses the last element in Perl 6
#array[*-1]
and why we need the asterisk *?
Isn't it more logical to do something like this:
#array[-1]
The user documentation explains that *-1 is just a code object, which could also be written as
-> $n { $n - 1 }
When passed to [ ], it will be invoked with the array size as argument to compute the index.
So instead of just being able to start counting backwards from the end of the array, you could use it to eg count forwards from its center via
#array[* div 2] #=> middlemost element
#array[* div 2 + 1] #=> next element after the middlemost one
According to the design documents, the reason for outlawing negative indices (which could have been accepted even with the above generalization in place) is this:
The Perl 6 semantics avoids indexing discontinuities (a source of subtle runtime errors), and provides ordinal access in both directions at both ends of the array.
If you don't like the whatever-star, you can also do:
my $last-elem = #array.tail;
or even
my ($second-last, $last) = #array.tail(2);
Edit: Of course, there's also a head method:
my ($first, $second) = #array.head(2);
The other two answers are excellent. My only reason for answering was to add a little more explanation about the Whatever Star * array indexing syntax.
The equivalent of Perl 6's #array[*-1] syntax in Perl 5 would be $array[ scalar #array - 1]. In Perl 5, in scalar context an array returns the number of items it contains, so scalar #array gives you the length of the array. Subtracting one from this gives you the last index of the array.
Since in Perl 6 indices can be restricted to never be negative, if they are negative then they are definitely out of range. But in Perl 5, a negative index may or may not be "out of range". If it is out of range, then it only gives you an undefined value which isn't easy to distinguish from simply having an undefined value in an element.
For example, the Perl 5 code:
use v5.10;
use strict;
use warnings;
my #array = ('a', undef, 'c');
say $array[-1]; # 'c'
say $array[-2]; # undefined
say $array[-3]; # 'a'
say $array[-4]; # out of range
say "======= FINISHED =======";
results in two nearly identical warnings, but still finishes running:
c
Use of uninitialized value $array[-2] in say at array.pl line 7.
a
Use of uninitialized value in say at array.pl line 9.
======= FINISHED =======
But the Perl 6 code
use v6;
my #array = 'a', Any, 'c';
put #array[*-1]; # evaluated as #array[2] or 'c'
put #array[*-2]; # evaluated as #array[1] or Any (i.e. undefined)
put #array[*-3]; # evaluated as #array[0] or 'a'
put #array[*-4]; # evaluated as #array[-1], which is a syntax error
put "======= FINISHED =======";
will likewise warn about the undefined value being used, but it fails upon the use of an index that comes out less than 0:
c
Use of uninitialized value #array of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to something meaningful.
in block <unit> at array.p6 line 5
a
Effective index out of range. Is: -1, should be in 0..Inf
in block <unit> at array.p6 line 7
Actually thrown at:
in block <unit> at array.p6 line 7
Thus your Perl 6 code can more robust by not allowing negative indices, but you can still index from the end using the Whatever Star syntax.
last word of advice
If you just need the last few elements of an array, I'd recommend using the tail method mentioned in mscha's answer. #array.tail(3) is much more self-explanatory than #array[*-3 .. *-1].