XSL - Does evaluating conditional expressions "shortcut"? - xslt

Given an XSL 'If' statement:
<xsl:if test="a = 'some value' and b = 'another value'">
If a does not equal 'some value', is the value of b still checked? (As if the first test is false, the only outcome of the and is false.) This is what languages like C# do - I was wondering if the same goes in XSL. Does it depend on the engine/parser?

Yes, it is called lazy-evaluation or short-circuiting, and xsl supports it. See: http://www.w3.org/TR/xpath#booleans
An and expression is evaluated by
evaluating each operand and converting
its value to a boolean as if by a call
to the boolean function. The result is
true if both values are true and false
otherwise. The right operand is not
evaluated if the left operand
evaluates to false.

Yes, this is depending on the implementation. But since XSLT is side-effect-free (as opposed to C# and other languages, where a function call chainging some state or even an assignment can be in the expression), this does not matter.

Related

Print one result after combining multiple expression results using jq

I want to have the output of either true or false.
I have this syntax
.[] | (if (select(.displayName=="display")) then "yes" else "no" end)
This is the json source
[{"displayName":"display","message":"bla bla"}, {"displayName":"test","message":"bla bla"}]
I only need to query against the array and if the value im looking for exists in one of them I need the output to be "yes", and if it doesnt a "no". So a single output value is what I am looking for.
This evaluates to "yes", however, if the value display is not present in the json, it does not output "no", its just empty. Can anyone tell me why?
Here is a snippet to try: https://jqplay.org/s/WKcZh91hk8L
The idea is right, but you shouldn't be using select for this. The way select works is by evaluating the boolean expression provided inside (..) and returning the object, if the expression evaluates to true and skip the object from being considered/printed on false.
On your code, for the object that evaluates to false, select is evaluated as select(false) which as explained above returns nothing - this is not evaluated to boolean false condition. i.e. the return value of select is not a boolean value.
To use explicit boolean conditions, drop the select from expression and to summarise the result to a single value do something like below
if ( [ .[] | .displayName == "display" ] | any ) then "yes" else "no" end
Demo on jqplay
The way this works, is any can evaluate an array of boolean values and produces true as output if any of the elements of the array are true. We collect the match condition results to the array and apply any on it. i.e. [true, false] evaluates to true, thereby printing yes only once
A concise solution is possible with select:
select( any(.displayName=="display") ) | "yes" // "no"

If Statements in Lua

In all other programming languages I've encountered, if statements always require a boolean to work, however in Lua the following code does not contain any errors. What is being checked in this if statement if both true and false statements can't be made? How can you only check "if (variable) then"? I am new to programming and currently working with Roblox Studio, any help would be very appreciated.
function onTouched(Obj)
local h = Obj.Parent:FindFirstChild("Humanoid")
if h then
h.Health = 0
end
end
script.Parent.Touched:Connect(onTouched)
Most languages have their own rules for how values are interpreted in if statements.
In Lua, false and nil are treated as false. All other values are treated as true.
if h == nil (null)
So if it couldn't find a humanoid in the object that touched the script's parent, it will be false (null), otherwise true (not null).
So
if [ObjectName] then
equals to if [ObjectName] != null then
*Only valid for objects (non primitive values)
It's like that in script languages.
if h then end
is basically equivalent to
if h ~= nil and h ~= false then end
In Lua all values that are not nil or false are considered to be logically true.
if h then end is usually used to check wether h is not nil. So if code depends on wether h has been defined you put it in a condition like that.
In your example h is being index. indexing nil values is not allowed. So befor you index it you should make sure it isn't nil to avoid errors.
Checking return values of functions is good practice.

Evaluate constraint expression as boolean

I want to evaluate if a constraint is respected or not in Pyomo when the values of the variables contained in constraint expression are known.
Use case: We know that one particular constraint sometimes makes the problem infeasible, depending on the value of the variable. Instead of sending the problem to the solver to test if the problem is feasible, converting the constraint expression to a boolean type would be enough to determine if the constraint is the culprit.
For the sake of providing a feasible example, here would be the code:
from pyomo.environ import ConcreteModel, Var, Constraint
model = ConcreteModel()
model.X = Var()
def constraint_rule(model):
return model.X <= 1
model.a_constraint = Constraint(rule=constraint_rule)
Now, let's try to work with the expression to evaluate:
# Let's define the expression in this way:
expression = constraint_rule(model)
# Let's show that the expression is what we expected:
print(str(expression))
The previous statement should print X <= 1.0.
Now, the tricky part is how to evaluate the expression.
if expression == True:
print("feasible")
else:
print("infeasible")
creates an TypeError Exception (TypeError: Cannot create an EqualityExpression where one of the sub-expressions is a relational expression: X <= 1.0).
The last example doesn't work because constraint_rule doesn't return a boolean but a Pyomo expression.
Finally, I know that something like
def evaluate_constraint_a_expression(model):
return value(model.X) <= 1
would work, but I can't assume that I will always know the content of my constraint expression, so I need a robust way of evaluating it.
Is there a clever way of achieving this? Like, evaluating the expression as a boolean and evaluating the left hand side and right hand side of the expression at the same time?
The solution is to use value function. Even if it says that it evaluates an expression to a numeric value, it also converts the expression to a boolean value if it is an equality/inequality expression, like the rule of a constraint.
Let's suppose that the model is defined the way it is in the question, then the rest of the code should be:
from pyomo.environ import value
if value(expression) == True:
print("feasible")
else:
print("infeasible")
where expression is defined as written in the question.
However, be advised that numeric precision in Python using this method can be different than the one provided by the solver. Therefore, it is possible that this method will show that a constraint is infeasible while it is just a matter of numeric imprecision of under 1e-10. So, while it is useful in finding if most constraints are feasible, it also generates some false positives.

(XQuery/Conditions) Is it possible to declare variables in an if-statement?

I do not find an example for my problem so here is my question.
I get an error that else is an unexpected token in the following example:
let $var1 := 'true'
if ($var1 = 'true') then
let $var2 := 1
let $var3 := $var1 + 1
else ()
As you see I want to declare variables if the if-statement is true. Is this possible in XQuery? I just saw examples where the value of just one variable can depends on a condition. The following does more or less the same I want to realize with the code at the beginning.. and it works but it is a little bit confusing in my opinion and actually I don't want the variables to be created if the condition is not true. Furthermore you have to think around the corner when you realize it like that especially when there are more than just 2 variables that depends on each other.
let $var1 := 'true'
let $var2 := if ($var1 = 'true') then (1) else (0)
let $var3 := if ($var2 = 1) then ($var2 + 1) else (0)
So my question is. Is there a prettier solution to realize that than my solution?
You could add a return clause to put a full flwor expression inside the condition, e.g. something like this:
let $var := 'true'
if ($var = 'true') then
let $var2 := 1
let $var3 := $var1 + 1
return 0
else ()
But it would be pointless: the binding of $var2 and $var3 would not extend outside of the scope of the then clause.
XQuery is a declarative and functional language, which means that variables do not get assigned, but only bound within a certain scope. This is something that should be thought about in term of space, not time, as there is no elapse of time in an XQuery program, like a ticket allows you to visit a museum but not another.
Let clauses are part of FLWOR (acronym for for-let-where-orderby-return) expressions. A variable bound in a let clause can be used in subsequent clauses, up to and including the return clause. As mholstege explains, beyond the return clause, which is required, the variable is not visible any more, like nobody would accept your ticket outside the museum.
Since expressions nest in a "well-parenthesized" way according to the XQuery grammar, any attempt to start a let clause inside an if-then-else expression requires that a return clause be present before the then (or else) expression ends. This means that a variable bound this way will never be visible after this if-then-else expression.
In general, when I program in XQuery (as opposed to, say, Java), I try to remind myself continuously that I have to write down what I want, and resist the temptation to describe how I want it computed.
Having said that, XQuery does have scripting extensions that introduce variable assignments as you describe, but this did not get standardized so far -- also, such a scripting extension should only be used when side effects to the outside world happen, meaning that one needs a notion of time and succeeding snapshots.
You could avoid using if/else altogether by defining sequences for your possible values, and a predicate that calculates the position() to select the desired value from the sequence:
The following uses number() to evaluate the numeric value of a boolean (0 for false, 1 for true) and selects either the first or the second item in the sequence of values:
let $var1 := 'true'
let $var2 := (0, 1)[number($var1 = 'true') + 1]
let $var3 := (0, $var2 + 1)[number($var2 eq 1) + 1]
return ($var1, $var2, $var3)

Python 2.7 Boolean Operators Logic

I am currently in the course of learning Python 2.7 and have come across the Equality and Boolean operators
My question is:
Why False and 1 is False but True and 1 is 1
Likewise, False or 1 is 1 but True or 1 is True
Can someone kindly explain why this is happening
Many thanks
and returns the first 'falsy' (False, zero, empty string or list, etc.) value it sees, or the final value if none were falsy. Further values are not even evaluated, since they can't change the result.
or likewise returns the first 'truthy' (True, non-zero, non-empty string or list, etc.) value it sees (or the final one if there were none), and doesn't evaluate the rest.
This behavior is sometimes more convenient than strictly returning only True or False.