I cannot understand setg instruction - setx

I learned that setg's condition is "~(SF^OF)&~ZF" and I can understand the case when SF = 0, OF = 0, ZF != 0, it means "greater than zero".
However, I cannot understand "SF = 1, OF = 1, ZF != 0" case. How can I accept this case?
thank you.

Related

trax tl.Relu and tl.ShiftRight layers are nested inside Serial Combinator

I am trying to build an attention model but Relu and ShiftRight layer by default nested inside the Serial Combinator.
This further gives me errors in training.
layer_block = tl.Serial(
tl.Relu(),
tl.LayerNorm(), )
x = np.array([[-2, -1, 0, 1, 2],
[-20, -10, 0, 10, 20]]).astype(np.float32)
layer_block.init(shapes.signature(x)) y = layer_block(x)
print(f'layer_block: {layer_block}')
Output
layer_block: Serial[
Serial[
Relu
]
LayerNorm
]
Expected Output
layer_block: Serial[
Relu
LayerNorm
]
The same problem arises with tl.ShiftRight()
The code above is taken from official documentation Example 5
Thanks in advance
I could not found the exact solution to the above problem, but you can create a custom Function using tl.Fn() and add the Relu and ShiftRight function code in it.
def _zero_pad(x, pad, axis):
"""Helper for jnp.pad with 0s for single-axis case."""
pad_widths = [(0, 0)] * len(x.shape)
pad_widths[axis] = pad # Padding on axis.
return jnp.pad(x, pad_widths, mode='constant')
def f(x):
if mode == 'predict':
return x
padded = _zero_pad(x, (n_positions, 0), 1)
return padded[:, :-n_positions]
# set ShiftRight parameters as global
n_positions = 1
mode='train'
layer_block = tl.Serial(
tl.Fn('Relu', lambda x: jnp.where(x <= 0, jnp.zeros_like(x), x)),
tl.LayerNorm(),
tl.Fn(f'ShiftRight({n_positions})', f)
)
x = np.array([[-2, -1, 0, 1, 2],
[-20, -10, 0, 10, 20]]).astype(np.float32)
layer_block.init(shapes.signature(x))
y = layer_block(x)
print(f'layer_block: {layer_block}')
Output
layer_block: Serial[
Relu
LayerNorm
ShiftRight(1)
]

How do I add a pre determined stop loss and take profit?

This is my first post. I am a prop trader and really trying hard to learn how to code as it would take my trading to another level. It is quite overwhelming at the beginning, but working on things that have use to me is motivating.
I have a script for trading view that I would like to edit. I have tried myself but I am obviously doing something wrong. Any help would be very much appreciated.
I just want to add my own pre determined stop loss and take profit for the strategy, The code is below:
strategy(title="Z-Score Strategy", shorttitle="Z-Score Strategy")
Period = input(20, minval=1)
Trigger = input(0)
reverse = input(false, title="Trade reverse")
hline(Trigger, color=purple, linestyle=line)
xStdDev = stdev(close, Period)
xMA = sma(close, Period)
nRes = (close - xMA) / xStdDev
pos = iff(nRes > Trigger, 1,
iff(nRes < Trigger, -1, nz(pos[1], 0)))
possig = iff(reverse and pos == 1, -1,
iff(reverse and pos == -1, 1, pos))
if (possig == 1)
strategy.entry("Long", strategy.long)
if (possig == -1)
strategy.entry("Short", strategy.short)
barcolor(possig == -1 ? red: possig == 1 ? green : blue )
plot(nRes, color=blue, title="Z-Score")
You should close the position via strategy.exit: https://www.tradingview.com/pine-script-reference/v4/#fun_strategy{dot}exit
//#version=4
strategy("strategy")
strategy.entry("entryId", strategy.long)
strategy.exit("exitId", "entryId", profit = 5, stop=7)

SSRS Divide by zero error

I am getting NaN in 3 places in my SSRS report. I believe it is because I am dividing by 0. I am trying to find the average days for prescriptions on-time, late, and not filled. The 3 expressions that I was given are below. What and where would I need to insert the iif statement addressing the 0 issue. I am new to this
=sum(iif(Fields!DaysDifference.Value >= -1 and Fields!DaysDifference.Value <= 1 and Fields!ActualNextFillDateKey.Value <> 0, Fields!DaysDifference.Value,0))/
sum(iif(Fields!DaysDifference.Value >= -1 and Fields!DaysDifference.Value <= 1 and Fields!ActualNextFillDateKey.Value <> 0, 1,0))
=sum(iif(Fields!DaysDifference.Value > 1 and Fields!ActualNextFillDateKey.Value <> 0, Fields!DaysDifference.Value,0))/
sum(iif(Fields!DaysDifference.Value > 1 and Fields!ActualNextFillDateKey.Value <> 0, 1,0))
=sum(iif(Fields!ActualNextFillDateKey.Value = 0, Fields!DaysDifference.Value, 0))/
sum(iif(Fields!ActualNextFillDateKey.Value = 0, 1, 0))
Instead of using 0, you should be dividing by your field:
=SUM(IIF(Fields!ActualNextFillDateKey.Value = 0, Fields!DaysDifference.Value, 0))/
SUM(IIF(Fields!ActualNextFillDateKey.Value = 0, 1, Fields!ActualNextFillDateKey.Value))

What is the fastest way to check for duplicate digits of a number?

Let's say I want to check if a number n = 123 has duplicate digits. I tried:
#include <iostream>
using namespace std;
int main() {
int n = 123;
int d1 = n % 10;
int d2 = ( n / 10 ) % 10;
int d3 = ( n / 100 ) % 10;
if( d1 != d2 && d1 != d3 && d2 != d3 ) {
cout << n << " does not have duplicate digits.\n";
}
}
Is there any faster solution to this problem?
Update
Sorry for being unclear. The code above was written in C++ only for description purpose. I have to solve this problem in TI-89, with a number of 9 digits. And since the limitation of memory and speed, I'm looking for a fastest way possible.
TI-89 only has several condition keyword:
If
If ... Then
when(
For ... EndFor
While ... EndWhile
Loop ... EndLoop
Custom ... EndCustom
Thanks,
Chan
Not necessarily faster but you should measure anyway, just in case - my optimisation mantra is "measure, don't guess".
But I believe it's clearer in intent (and simple enough to be translated to a simpler calculator language. It's also able to handle arbitrarily sized integers.
int hasDupes (unsigned int n) {
// Flag to indicate digit has been used, all zero to start.
int used[10] = {0};
// More than 10 digits must have duplicates, return true quickly.
if (n > 9999999999) return 1;
// Process each digit in number.
while (n != 0) {
// If duplicate, return true as soon as found.
if (used[n%10]) return 1;
// Otherwise, mark used, go to next digit.
used[n%10] = 1;
n /= 10;
}
// No duplicates after checking all digits, return false.
return 0;
}
If you have a limited range of possibilities, you can use the time-honoured approach of sacrificing space for time. For example, let's say you're talking about numbers between 0 and 999 inclusive (the : : markers simply indicate data I've removed to keep the size of the answer manageable):
const int *hasDupes = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 9
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, // 10 - 19
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, // 20 - 29
: :
0, 0, 1, 0, 0, 1, 0, 0, 0, 0, // 520 - 529
: :
0, 1, 0, 0, 0, 0, 0, 0, 1, 0, // 810 - 819
: :
0, 0, 0, 0, 0, 0, 0, 1, 0, 1, // 970 - 979
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, // 980 - 989
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 990 - 999
};
and just do a table lookup of hasDupes[n]. The table itself could be generated (once) programmatically and then just inserted into your code for usage.
However, based on your edit where you state you need to handle nine-digit numbers, a billion-element array is probably not going to be possible on your calculator. I would therefore opt for the first solution.
template<class T, int radix = 10>
bool has_duplicate_digits(T n) {
int digits_mask = 0;
while (digits_mask |= (1 << (n % radix)), n /= radix)
if (digits_mask & (1 << (n % radix)))
return true;
return false;
}
Something like that should work as long as n is nonnegative and int has at least radix bits.
digits_mask is a bitset (bit 0 represents the occurrence of a 0 digit, bit 1 represents the occurrence of a 1 digit, etc.).
The bitmap is populated with the least significant digit of n, and the rest of the digits are shifted down. If there are more digits, and the new least significant digit is marked as having occurred previously, return true, otherwise repeat.
When there are no more digits, return false.
1 << x returns 1, 2, 4, 8, etc.: masks to use to test/set bits in the bitset.
a |= z is shorthand for a = a | z, which sets bits by the union of a from z.
a & z is the intersection of the bits in a and z, and is zero (false) if none are set and non-zero (true) if any are set.
I did a crash course in TI-89 basic to answer :)
Let's see if this works (I haven't an emulator, so can't check).
Test()
Prgm
{0,0,0,0,0,0,0,0,0,0}->A
Title "Request"
Request "Enter a number",B
EndDlog
Expr(B)->B
While B > 1
MOD(10,B)->C
if A[C+1] = 1 goto K
1->A[C+1]
B-C->B
EndWhile
Title "Done"
Text "Numbers non repeating"
Enddlog
goto J
Lbl K
Title "Done"
Text "Numbers repeating"
Enddlog
Lbl J
EndPrgm

Yield in Mathematica

Can you do something like Python's yield statement in Mathematica, in order to create generators? See e.g. here for the concept.
Update
Here's an example of what I mean, to iterate over all permutations, using only O(n) space: (algorithm as in Sedgewick's Algorithms book):
gen[f_, n_] := Module[{id = -1, val = Table[Null, {n}], visit},
visit[k_] := Module[{t},
id++; If[k != 0, val[[k]] = id];
If[id == n, f[val]];
Do[If[val[[t]] == Null, visit[t]], {t, 1, n}];
id--; val[[k]] = Null;];
visit[0];
]
Then call it it like:
gen[Print,3], printing all 6 permutations of length 3.
As I have previously stated, using Compile will given faster code. Using an algorithm from fxtbook, the following code generates a next partition in lexicographic ordering:
PermutationIterator[f_, n_Integer?Positive, nextFunc_] :=
Module[{this = Range[n]},
While[this =!= {-1}, f[this]; this = nextFunc[n, this]];]
The following code assumes we run version 8:
ClearAll[cfNextPartition];
cfNextPartition[target : "MVM" | "C"] :=
cfNextPartition[target] =
Compile[{{n, _Integer}, {this, _Integer, 1}},
Module[{i = n, j = n, ni, next = this, r, s},
While[Part[next, --i] > Part[next, i + 1],
If[i == 1, i = 0; Break[]]];
If[i == 0, {-1}, ni = Part[next, i];
While[ni > Part[next, j], --j];
next[[i]] = Part[next, j]; next[[j]] = ni;
r = n; s = i + 1;
While[r > s, ni = Part[next, r]; next[[r]] = Part[next, s];
next[[s]] = ni; --r; ++s];
next
]], RuntimeOptions -> "Speed", CompilationTarget -> target
];
Then
In[75]:= Reap[PermutationIterator[Sow, 4, cfNextPartition["C"]]][[2,
1]] === Permutations[Range[4]]
Out[75]= True
This is clearly better in performance than the original gen function.
In[83]:= gen[dummy, 9] // Timing
Out[83]= {26.067, Null}
In[84]:= PermutationIterator[dummy, 9, cfNextPartition["C"]] // Timing
Out[84]= {1.03, Null}
Using Mathematica's virtual machine is not much slower:
In[85]:= PermutationIterator[dummy, 9,
cfNextPartition["MVM"]] // Timing
Out[85]= {1.154, Null}
Of course this is nowhere near C code implementation, yet provides a substantial speed-up over pure top-level code.
You probably mean the question to be more general but the example of iterating over permutations as given on the page you link to happens to be built in to Mathematica:
Scan[Print, Permutations[{1, 2, 3}]]
The Print there can be replaced with any function.

Resources