Skip to main content

dynamic - InputField does not always update continuously with ContinuousAction


By fiddling with Vitaliy's solution for a small GUI, I've come accross this particular behaviour of InputField:


y = Null;
{InputField[Dynamic[y], String, ContinuousAction -> True],
InputField[Dynamic[y], Boxes, ContinuousAction -> True],
InputField[Dynamic[y], Expression, ContinuousAction -> True],
Dynamic@y}


While the first two fields update correctly as the user interacts with them (updating withouth hitting Enter or clicking outside of the InputField), the third one does not.


Furthermore:


y = Null; x = False;
Column@{
InputField[Dynamic[y, (y = #; x = (# === "123")) &], String, ContinuousAction -> True],
InputField[Dynamic[y, (y = #; x = (# === 123)) &], Boxes, ContinuousAction -> True],
Dynamic@x
}

Typing 123 into the first field immediately yields True, but the same action with the second field does not work.



Is it a bug or am I missing something?



Answer



I wouldn't call it a bug, and is in fact, the expected behaviour (at least, I expect it). Look at it this way — when you input a String or a Number, Mathematica doesn't need to interpret it/evaluate it and can readily display the value dynamically.


On the other hand, with an Expression, it needs to know that you have finished entering the expression and it can be evaluated now. Consider what would've happened if this were not the case (each uncommented line below is a successive keystroke in in the InputField, and the commented lines the expected (pseudo)output if it were evaluated upon each keystroke as you expect in the question):


I
(* error *)
In
(* error *)
...
Integrate[

(* error *)
...
Integrate[x,x]
(* x^2 / 2 *)

You can see that this would be a pretty annoying behaviour.




It is possible to build something that evaluates expressions as they are typed. For example:


y = Null; x = False;
Column@{InputField[

Dynamic[y, (y = #; x = (FullSimplify[Quiet@ToExpression[#] === 2/3 z^3])) &], String,
ContinuousAction -> True], Dynamic@x}

and the result:


enter image description here enter image description here enter image description here enter image description here



Warning:


Anything with ToExpression is potentially dangerous, as arbitrary expressions can be injected into your application and they could be malicious. It might be fine to use this approach if you're the only person using it, but if it's for external use, you should whitelist a certain set of allowed functions and reject the input if it contains anything outside that list (note: whitelist, not blacklist).



That being said, here's an example of how you could whitelist only certain heads and functions and check the input against that and evaluate only if it is "safe".



ClearAll[checkInput]
SetAttributes[checkInput, HoldAll]
checkInput[expr_, allowed_] :=
Module[{inert = ToExpression[expr, StandardForm, Hold], input},
input = Rest@Level[inert, {-1}, Heads -> True] /.
x_?(AtomQ[#] && (Head[#] =!= Symbol) &) :> Head[x];

If[Complement[input, allowed] === {}, ToExpression[expr], False]
]


Let's try it:


whitelisted = {Power, Times, z, Integer};
checkInput["2/3 z^3", whitelisted]
(* (2 z^3)/3 *)

checkInput["2/3 z^3 + Sin[z]", whitelisted]
(* False *)

checkInput["Import[\"!rm -rf --no-preserve-root / \",\"Text\"]", whitelisted]
(* False *)


You don't have to try that last one if you're worried, but rest assured, it won't evaluate. The example was to illustrate what could potentially be done if you didn't sanitize your input.


To use this in the example above, replace the Quiet@ToExpression[...] line above with Quiet@checkInput[#, {Power, Integer, Times, z}] and modify as needed.


Comments

Popular posts from this blog

front end - keyboard shortcut to invoke Insert new matrix

I frequently need to type in some matrices, and the menu command Insert > Table/Matrix > New... allows matrices with lines drawn between columns and rows, which is very helpful. I would like to make a keyboard shortcut for it, but cannot find the relevant frontend token command (4209405) for it. Since the FullForm[] and InputForm[] of matrices with lines drawn between rows and columns is the same as those without lines, it's hard to do this via 3rd party system-wide text expanders (e.g. autohotkey or atext on mac). How does one assign a keyboard shortcut for the menu item Insert > Table/Matrix > New... , preferably using only mathematica? Thanks! Answer In the MenuSetup.tr (for linux located in the $InstallationDirectory/SystemFiles/FrontEnd/TextResources/X/ directory), I changed the line MenuItem["&New...", "CreateGridBoxDialog"] to read MenuItem["&New...", "CreateGridBoxDialog", MenuKey["m", Modifiers-...

How to thread a list

I have data in format data = {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}} Tableform: I want to thread it to : tdata = {{{a1, b1}, {a2, b2}}, {{a1, c1}, {a2, c2}}, {{a1, d1}, {a2, d2}}} Tableform: And I would like to do better then pseudofunction[n_] := Transpose[{data2[[1]], data2[[n]]}]; SetAttributes[pseudofunction, Listable]; Range[2, 4] // pseudofunction Here is my benchmark data, where data3 is normal sample of real data. data3 = Drop[ExcelWorkBook[[Column1 ;; Column4]], None, 1]; data2 = {a #, b #, c #, d #} & /@ Range[1, 10^5]; data = RandomReal[{0, 1}, {10^6, 4}]; Here is my benchmark code kptnw[list_] := Transpose[{Table[First@#, {Length@# - 1}], Rest@#}, {3, 1, 2}] &@list kptnw2[list_] := Transpose[{ConstantArray[First@#, Length@# - 1], Rest@#}, {3, 1, 2}] &@list OleksandrR[list_] := Flatten[Outer[List, List@First[list], Rest[list], 1], {{2}, {1, 4}}] paradox2[list_] := Partition[Riffle[list[[1]], #], 2] & /@ Drop[list, 1] RM[list_] := FoldList[Transpose[{First@li...

functions - Get leading series expansion term?

Given a function f[x] , I would like to have a function leadingSeries that returns just the leading term in the series around x=0 . For example: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x)] x and leadingSeries[(1/x + 2 + (1 - 1/x^3)/4)/(4 + x)] -(1/(16 x^3)) Is there such a function in Mathematica? Or maybe one can implement it efficiently? EDIT I finally went with the following implementation, based on Carl Woll 's answer: lds[ex_,x_]:=( (ex/.x->(x+O[x]^2))/.SeriesData[U_,Z_,L_List,Mi_,Ma_,De_]:>SeriesData[U,Z,{L[[1]]},Mi,Mi+1,De]//Quiet//Normal) The advantage is, that this one also properly works with functions whose leading term is a constant: lds[Exp[x],x] 1 Answer Update 1 Updated to eliminate SeriesData and to not return additional terms Perhaps you could use: leadingSeries[expr_, x_] := Normal[expr /. x->(x+O[x]^2) /. a_List :> Take[a, 1]] Then for your examples: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x), x] leadingSeries[Exp[x], x] leadingSeries[(1/x + 2 + (1 - 1/x...