Groovy using a different value from what was initialized - groovy

In my JMeter script i have defined a User Defined Variable i whose value is set to 1. Then i created a JSR22 pre-processor for my HTTP sample that just increments the value of i using the below code.
log.info(vars.get("i"));
Integer intI = vars.get("i");
intI = intI + 1;
vars.put("i", intI.toString());
log.info(vars.get("i"))
The problem seems to be that instead of picking up 1 as the initial value of i it is picking 49 and increment it to 50.
I was able to fix it by changing
Integer intId = vars.get("id")
to
Integer intId = vars.get("id").toInteger();
But i am curious to know what could be causing this.

As requested, the conclusion from the comments as answer:
vars.get() returns a String which, when assigned to an Integer gets implicitly converted to the corresponding ASCII value (if the String is exactly 1 character, otherwise it will cause a runtime exception).
This can be observed in the snippet:
def v = "1"; Integer intId = v; println intId -> prints 49

Related

Global variables as input parameters

I doubt whether it is appropriate to use input variables in functions in cases where the input variable will always be the same.
mynum = int(datetime.today().weekday())
def somefuncion():
result = 3 + mynum
return result
optionA = somefuncion()
def somefunction2(number):
result = 3 + number
return result
optionB = somefunction2(mynum)
print(optionA == optionB) # true
Is there good practice in this respect ? or is it indifferent ?
In your case, it would probably be more appropriate to create constant variables.
MYNUM = 12
MYNUM_PLUS_TREE = MY_NUM + 3
That way, when you modify the value of MYNUM in your development, it automatically modifies the value of all the constant values that are generated from it (here it is MYNUM_PLUS_TREE).
The logic I apply here is the following: if a function always return the same value, then it is a "constant function", as in mathematics. Therefore, using a constant variable is preferable.
If you are sure that you are not going to modify the value of the variable anywhere in the code then you should declare it as a constant and use it that way within the code. i.e. not include it as an input variable.
Python, constants are capitalized (PEP 8 standards) which helps the programmer know it's a constant.
i.e
CONSTANT = "Whatever"
in your example:
MYNUM = int(datetime.today().weekday())
def somefuncion():
result = 3 + MYNUM
return result

How arguments are passed into a cppFunction

I'm puzzled as to how arguments are passed into a cppFunction when we use Rcpp. In particular, I wonder if someone can explain the result of the following code.
library(Rcpp)
cppFunction("void test(double &x, NumericVector y) {
x = 2016;
y[0] = 2016;
}")
a = 1L
b = 1L
c = 1
d = 1
test(a,b)
test(c,d)
cat(a,b,c,d) #this prints "1 1 1 2016"
As stated before in other areas, Rcpp establishes convenient classes around R's SEXP objects.
For the first parameter, the double type does not have a default SEXP object. This is because within R, there is no such thing as a scalar. Thus, new memory is allocate making the & reference incompatible. Hence, the variable scope for the modification is limited to the function and there is never an update to the result. As a result, for both test cases, you will see 1.
For the second case, there is a mismatch between object classes. Within the first call object supplied is of type integer due to the L appended on the end, which conflicts with the C++ function expected type of numeric. The issue is resolved once the L is dropped as the object is instantiated as a numeric. Therefore, an intermediary memory location does not need to be created that is of the correct type to receive the value. Hence, the modification in the second case is able to propagate back to R.
e.g.
a = 1L
class(a)
# "integer"
a = 1
class(a)
# "numeric"

making an and assigning as Array/Object (really basic)

Really basic question.
I have a single form and want to create an object (I think) and assign a value to it.
Dim Devs as Object
For i = 0 To 3
If (Devices And 2 ^ i) Then
Devs(i) = True ' breaks here
Else
Devs(i) = False 'or here (depends on the if obviously)
End If
Next i
With this I get an error: Object variable or With block variable not set
I thought I could just make an Array or Object and assign a value, but I guess I'm wrong.
What is the proper way to do this?
Looks like you want an array of Booleans
Dim Devs(0 To 3) As Boolean
Your current code has an Object variable that is not pointing to any object.
Your Devs variable seems to be an array of type Boolean. Correct?
Dim Devs(0 To 3) As Boolean()
or
Dim Devs() As Boolean()
Furthermore, what is the purpose of 2 ^ i ? Do you intend to validate its value in order to enter the first code bracket.
Dim myCondition As Integer
myCondition = 2
If (Devices = True And 2 ^ i = myCondition)
...

Groovy override 'or' for Integer to 'or' with another Integer

In Groovy everything is Object, even numbers
assert 1.getClass() == Integer
In Groovy you can override existing method in an existing class in runtime
Integer.metaClass.or = { right -> println "$delegate or $right" }
Now we can call or operator on any number using pipe (|)
1.or("hello") // prints: 1 or hello
1 | "hello" // prints: 1 or hello
So far so good. Now let's try to or an Integer with an Integer
2.or(3) // nothing happens
2 | 3 // nothing happens
This leads us to my questions:
Why nothing happens?
Is this an optimization bug?
How to make it work for any type?
It's probably choosing an already existing or method that takes an integer, rather than your more generic Object version.
Does it work if you do:
Integer.metaClass.or = { Integer right -> println "$delegate or $right" }
Not at a computer at the moment though, so can't validate this :-/

Question related to string

I have two statements:
String aStr = new String("ABC");
String bStr = "ABC";
I read in book that in first statement JVM creates two bjects and one reference variable, whereas second statement creates one reference variable and one object.
How is that? When I say new String("ABC") then It's pretty clear that object is created.
Now my question is that for "ABC" value to we do create another object?
Please clarify a bit more here.
Thank you
You will end up with two Strings.
1) the literal "ABC", used to construct aStr and assigned to bStr. The compiler makes sure that this is the same single instance.
2) a newly constructed String aStr (because you forced it to be new'ed, which is really pretty much non-sensical)
Using a string literal will only create a single object for the lifetime of the JVM - or possibly the classloader. (I can't remember the exact details, but it's almost never important.)
That means it's hard to say that the second statement in your code sample really "creates" an object - a certain object has to be present, but if you run the same code in a loop 100 times, it won't create any more objects... whereas the first statement would. (It would require that the object referred to by the "ABC" literal is present and create a new instance on each iteration, by virtue of calling the constructor.)
In particular, if you have:
Object x = "ABC";
Object y = "ABC";
then it's guaranteed (by the language specification) than x and y will refer to the same object. This extends to other constant expressions equal to the same string too:
private static final String A = "a";
Object z = A + "BC"; // x, y and z are still the same reference...
The only time I ever use the String(String) constructor is if I've got a string which may well be backed by a rather larger character array which I don't otherwise need:
String x = readSomeVeryLargeString();
String y = x.substring(5, 10);
String z = new String(y); // Copies the contents
Now if the strings that y and x refer to are eligible for collection but the string that z refers to isn't (e.g. it's passed on to other methods etc) then we don't end up holding all of the original long string in memory, which we would otherwise.

Resources