Print Dynamic variable inside DynamicModule - dynamic

Why is it that not the value of b gets printed in the following example but the symbolname? How can I force the printing of the actual dynamic value of the variable?
a = {1, 2, 3};
DynamicModule[{b},
Print[Dynamic[b]];
{Dynamic[a], Dynamic[b]}
,
Initialization :> (b = Length[a]; a = a + 2)
]
output:
b$107
Out[2]= {{3, 4, 5}, 3}
Edit (after reading your answers/comments):
Consider the more simple example, without Initialization code (to get around WReach's example):
a = {1, 2, 3};
DynamicModule[{b = Length[a]},
Print[Dynamic[b]];
{Dynamic[a], Dynamic[b]}
]
output:
During evaluation of In[4]:= b$602
Out[5]= {{1, 2, 3}, 3}
Note, that this example does what I want to if I use Module instead of DynamicModule or leave out Dynamic from the Print line. My concerns are:
Why does this second example fail to print the value of b correctly? There is no Initialization, which (according to the help) contains "an expression to evaluate when the DynamicModule is first displayed". Also according to help: "When DynamicModule is first evaluated, initial assignments for local variables are made first, and then any setting for the Initialization option is evaluated."
The help should read: "Initialization: an expression to evaluate when the result of DynamicModule is first displayed", meaning that a Print statement onscreen does not constitute the "result" of the DynamicModule. If this is correct, then (and only then) I understand why the Print statement does not mean that the Dynamic object appears correctly.

I believe this happens because the Dynamic object b has not been displayed at the time the Print statement is called, and therefore the initialization has not been made. As I recall, Dynamic functionality does not operate until it is actually, visibly displayed.
See Why won't this work? Dynamic in a Select for more information.
In response to your update, my theory is that the Dynamic statement within Print in never displayed by the FrontEnd, and therefore it is never actually initialized. That is, it remains a unique placeholder, waiting to be filled by the dynamic value of b when it is finally displayed.
One may see from the example below that the assignment RHS evaluation takes place before the body Print, at least by measure of the display order in the FrontEnd. Further, we see that Print "goes inside" Dynamic and takes the unique symbol name created by DynamicModule, and prints that. We can use ToString to cause Print to display the entire expression as it is. Likewise, if we extract the symbol name from that string, and convert it to an actual symbol, before printing, we get the expected value that has indeed already been assigned.
alarm := (Print["Initialized!"]; 3)
DynamicModule[{b = alarm},
Print # ToString # Dynamic # b;
Print # Symbol # StringTake[ToString#Dynamic#b, {9, -2}];
Print # Dynamic # b;
];
Output:
Initialized!
Dynamic[b$701]
3
b$701

The crucial behaviour is described under the More Information section of the documentation for DynamicModule:
DynamicModule first gives unique names to local variables in expr,
just like Module, then evaluates the resulting expression, and then
returns a version of this wrapped in DynamicModule.
The exact sequence of events becomes more apparent if you add a Print statement to the Initialization option, thus:
a = {1, 2, 3};
DynamicModule[{b},
Print[Dynamic[b]];
{Dynamic[a], Dynamic[b]}
,
Initialization :> (b = Length[a]; Print["init:", b]; a = a + 2)
]
resulting in three cells:
b$107
Out[7]= {{3, 4, 5}, 3}
init:3
The cell containing b$107 is the result of the Print inside the DynamicModule. Then, we get the result cell (tagged Out[7] here). Finally, we see the third cell output by Print statement in the Initialization.
If you inspect the cell expression of the Out[7] cell, you will find that the localized variable is b$$. This is different from the variable in the first cell, which is b$107. This difference is attributable to the "double scoping" described in the DynamicModule documentation. The b$107 cell contains a Dynamic box, as can be seen if we assign a value to b$107.
Update
In response to the updated question...
Returning to the original expression (without the extra Print in the Initialization), the exact sequence of events is as follows:
First, the body of the DynamicModule is evaluated after giving "unique names to local variables [...] just like Module". That is, this expression is evaluated:
Print[Dynamic[b$107]]; {Dynamic[a], Dynamic[b$107]}
The result of this expression is the list {Dynamic[a], Dynamic[b$107]}. As a side-effect, a dynamic cell containing b$107 is created but that cell is now removed from further consideration as it is not part of the result of the evaluation. Now, "a version of [{Dynamic[a], Dynamic[b$107]}] is wrapped in DynamicModule" and returned. This is evaluated and implicitly printed to produce an output cell expression like this:
Cell[BoxData[
DynamicModuleBox[{$CellContext`b$$ = 3},
RowBox[{"{",
RowBox[{
DynamicBox[ToBoxes[$CellContext`a, StandardForm],
ImageSizeCache->{57., {2., 8.}}], ",",
DynamicBox[ToBoxes[$CellContext`b$$, StandardForm],
ImageSizeCache->{7., {0., 8.}}]}], "}"}],
DynamicModuleValues:>{},
Initialization:>($CellContext`b$$ =
Length[$CellContext`a]; $CellContext`a = $CellContext`a + 2)]], "Output"]
Note particularly that b$107 is renamed to $CellContext`b$$ as a function of DynamicModule symbol localization. The Initialization expression is now evaluated as the box is displayed and visible.
The key point is that the printed cell containing b$107 is not coupled in any way to the final DynamicModule cell.

Related

LUA After adding names from _ENV into a table, how do I print the VALUE from the name and not just the "name"

X=123
Y=321
TAB1={}
z=1
for n in pairs(_ENV) do
TAB1[z] = n
z=z+1
end
-- did some more steps that removes general _ENV and only left with my script global variables
TAB2={x, y}
print(TAB2[1])
what I want is "123" but I'm getting "x"
I've tried gmatch, gsub, tostring, but I still can't get it to print the value of x (123). it's only printing "x"
**sorry I don't know how to work this text box correctly for my question
Ive tried gmatch, gsub, tostring, but I still can't get it to print the value of x (123). it's only printing "x"
These functions are for string manipulation so I don't see how they'd be useful here. The reason for the lack of "value" is that your loop is for n in pairs(_ENV) do. pairs is just a wrapper for next which returns key and value, but you're currently discarding the value. Simply add a second variable to the for name list: for name, value in pairs(_ENV) do print(value) end. Alternatively, index _ENV using n: print(_ENV[n]) (inside the loop).

Call for global variable in JS block of Selenium Webdriver test (Python)

I have a string of numbers set by user. Defined in the beginning of the Webdriver test:
numbers = input("prompt")
Then I need to enter value of this variable by JS code like this:
driver.execute_script("document.getElementsByName('phone')[0].value=***")
Where instead of *** I need the value of "numbers" variable. How should I properly insert it to make it work?
Here is what you want to do.
numbers = input("prompt")
driver.execute_script("document.getElementsByName('phone')[0].value={}".format(numbers))
The documentation link:
https://docs.python.org/3/library/string.html
And a snip-it from the docs:
The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument. If the numerical arg_names in a format string are 0, 1, 2, … in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, … will be automatically inserted in that order. Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string. The arg_name can be followed by any number of index or attribute expressions. An expression of the form '.name' selects the named attribute using getattr(), while an expression of the form '[index]' does an index lookup using getitem().
Changed in version 3.1: The positional argument specifiers can be omitted for str.format(), so '{} {}'.format(a, b) is equivalent to '{0} {1}'.format(a, b).
OR
numbers = input("prompt")
driver.execute_script("document.getElementsByName('phone')[0].value=%s" % numbers)
See examples of both here:
https://pyformat.info/
If your python variable's value is simple string without single quotes or special characters, you can simply use:
driver.execute_script("document.getElementsByName('phone')[0].value='" +
python_variable + "'");
If it has quote marks in it, or special characters that need escaping, or if it's not a string at all, you need to obtain JavaScript string representation of your Python variable's value. json.dumps will handle all the necessary formatting and escaping for you, appropriate to the type of your variable:
from json import dumps
driver.execute_script("document.getElementsByName('phone')[0].value=" +
dumps(python_variable))

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].

Velocity Template engine - key-value-map

I have some problems wo use a key-value-map into Velocity.
Someone has an example of this functionality?
$myMap ={}
$myMap.put("mykey1", "myvalue")
$myMap.delete("mykey1")
$myMap.getValue("mykey1")
As Nathan said, you should use:
#set ($myMap = {})
to create a new map and assign it to a variable.
Now, why is the put call printed.
Anything that is not inside a directive, like #set(not printed) or #if(not printed) or #foreach(again not printed), is printed, including free text, variables, and method calls.
Velocity can't distinguish between the different semantics of $myMap.get('mykey') and $myMap.put('key', 'value') (reader vs. writer), so the result of the put call is printed, just like any other method.
Whenever something can't be properly evaluated, because a variable is not defined or somewhere along the line a method returns null, the code that failed to be evaluated is dumped literally into the output.
As the documentation of the put method states, the function returns the previous value stored for that key, or null if no value was set at all.
Summing it all up, it's normal to get that line printed.
To try this theory out, you can do this:
#set ($myMap = {})
$myMap.put('key', 'first value')
$myMap.put('key', 'second value')
$myMap.get('key')
This will be printed:
$myMap.put('key', 'first value')
first value
second value
There are two things you can do so that the line isn't printed:
Store the outcome of the function in a temporary variable: #set ($discard = $myMap.put('key', 'value')
Use the silent method call: $!myMap.put('key', 'value')
I'd recommend the first one, since the second one will still print something when you're replacing an existing value.
Did you try doing:
#set( $myMap = {} )
Also, make sure you are using a modern version of Velocity. Ancient ones did not have map syntax in VTL.
Just add ! to not print put:
$!myMap.put('key', 'second value')

How to suppress VB's "Iteration variable shouldn't been used in lambda expression"

I'm working with LINQ in VB.NET and sometimes I get to a query like
For i = 0 To 10
Dim num = (From n In numbers Where n Mod i = 0 Select n).First()
Next
and then it comes the warning "Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable."
I know it's not a good practice to use the iteration variable in the lambda expression, because lambda expressions are evaluated only when needed. (This question is about that)
Now my question is, how to suppress this warning in cases where the expression is evaluated in-place, with constructions like First(), Single(), ToList(), etc. (It's only a warning, but i like my code clean.)
(Declaring a local variable and passing the iteration variable to it is an option, but I'm looking for a clean solution.)
In this particular case where the lambda is evaluated immediately, then you can safely eliminate the warning by moving the declaration of the iteration variable outside the for loop.
Dim i = 0
For i = 0 To 10
...
I do want to stress though that this only works if the lambda does not escape the for loop (true for your scenario).
Also here is a detailed link to an article I wrote on this warning (why it exists, how to avoid it, etc ...)
http://blogs.msdn.com/b/jaredpar/archive/2007/07/26/closures-in-vb-part-5-looping.aspx