The function 'lowest' should be called on each calculation for consistency. It is recommended to extract the call from this scope - extract

I keep getting errors of "highest" and "lowest" in below sytax: may i know what is wrong
var ATRTrailingStop = 0.0
ATRTrailingStop := if close>ATRTrailingStop[1] and close[1]>ATRTrailingStop[1]
max(ATRTrailingStop[1], lowest(l[1], length))
else if close<ATRTrailingStop[1] and close[1]<ATRTrailingStop[1]
min(ATRTrailingStop[1], highest(h[1], length))
else if close>ATRTrailingStop[1]
lowest(l[1], length)
else
highest(h[1], length)

Related

MATLAB recursive function [Factorials]

The code works but I am confused. When n==1, I am assigning a=1, shouldn't that overwrite the value and return only 1?
format compact
fct(5)
function a = fct(n)
if n==1
a = 1;
else
a = n*fct(n-1);
end
end
This is how I picture it... Below is a recursion/factorial diagram that shows the cascading effect of the recursive calls. At the deepest recursive call fct(1) is evaluated which is equal to 1 given by the first if statement. Each recursive call is therefore defined by a deeper recursive call. I typically like to decompose the recursive function until reaching its terminating case. I guess a way to phrase it is "a function within function" not so much of a loop.
Where, fct(1) → 1
format compact
fct(5)
function a = fct(n)
if n == 1
a = 1;
else
a = n*fct(n-1);
fprintf("%d\n",a);
end
end
Cumulative/Recursive Results:
2
6
24
120
ans =
120
My Preferred Structuring:
format compact
fct(5)
function a = fct(n)
if n > 1
a = n*fct(n-1);
else
a = n;
end
end

How to compare numeric values in the function node in node-red?

I've been trying to do a simple numeric comparison since days in my function node but I really don't have any idea why it's not working. I have a function node which accepts two values. I've even converted it from object to Number but still the comparison won't work. Please find the full flow here:
[{"id":"39421a3d.5cda36","type":"function","z":"251d0ac6.958a36","name":"getL1MagneticCount","func":"msg.payload = {\"getCarCount1\":msg.payload};\nreturn msg;","outputs":1,"noerr":0,"x":586.6666259765625,"y":606.6666259765625,"wires":[["31136d74.228fb2"]]},{"id":"a171070a.1ba198","type":"function","z":"251d0ac6.958a36","name":"getL2MagneticCount","func":"msg.payload = {\"getCarCount2\":msg.payload.Car};\nreturn msg;","outputs":1,"noerr":0,"x":586.6666259765625,"y":719.9999732971191,"wires":[["31136d74.228fb2"]]},{"id":"31136d74.228fb2","type":"function","z":"251d0ac6.958a36","name":"comparison","func":"var count1 = Number(msg.payload.getCarCount1);\nvar count2 = Number(msg.payload.getCarCount2);\n\nif(count1 >= count2){\n console.log(\"In\");\n msg.payload = msg.payload.getCarCount1;\n return [msg,null];\n \n} else {\n console.log(\"Out\");\n msg.payload = msg.payload.getCarCount2;\n return [null,msg];\n \n}","outputs":"2","noerr":0,"x":824.4443950653076,"y":663.3333148956299,"wires":[["57c8e7b7.c948e8"],["10b4a39f.16338c"]]},{"id":"57c8e7b7.c948e8","type":"debug","z":"251d0ac6.958a36","name":"","active":true,"console":"false","complete":"payload","x":1025.5556182861328,"y":626.6666140556335,"wires":[]},{"id":"10b4a39f.16338c","type":"debug","z":"251d0ac6.958a36","name":"","active":true,"console":"false","complete":"false","x":1028.8889236450195,"y":709.9999084472656,"wires":[]},{"id":"1a6938ca.0d2bf7","type":"inject","z":"251d0ac6.958a36","name":"","topic":"","payload":"3","payloadType":"str","repeat":"","crontab":"","once":false,"x":256.6666679382324,"y":605.555606842041,"wires":[["39421a3d.5cda36"]]},{"id":"d23e60e5.adb83","type":"inject","z":"251d0ac6.958a36","name":"","topic":"","payload":"0","payloadType":"str","repeat":"","crontab":"","once":false,"x":254.66665649414062,"y":719.5555419921875,"wires":[["a171070a.1ba198"]]}]
Please tell me where my mistake is. Thank you very much.
The problem is that each of the input messages are handled as independent events in the function node, so you only ever have 1 value to compare each time a message arrives.
What you need to do is make use of the context to store values between each message. Something like this:
//get stored values if present
var count1 = context.get("count1");
var count2 = context.get("count2");
if (msg.payload.hasOwnProperty("getCarCount1")) {
count1 = msg.payload.getCarCount1;
context.set("count1", count1);
}
if (msg.payload.hasOwnProperty("getCarCount2")) {
count2 = msg.payload.getCarCount2;
context.set("count2", count2);
}
if (count1 != undefined && count2 != undefined) {
if(count1 >= count2){
console.log("In");
msg.payload = count1;
return [msg,null];
} else {
console.log("Out");
msg.payload = count2;
return [null,msg];
}
}
I'm saving to global variables for the beginning temperature and humidity data from different sensors. In a block I'm checking these variables for "is not null", "nan" and then condition.. Maybe it will help.

Keeping the variable 's value in recursive function, python 3.3

I managed to do it, some other way.
but I have a question, I had this code before
def jumphunt(start, mylist, count = 0):
if count < len(mylist):
place = mylist[start]
print(place)
if place == 0:
return True
elif start >= len(mylist) or start < 0:
return False
move_left = (start - place)
move_right = (start + place)
return jumphunt(move_right, mylist, count+1) or jumphunt(move_left, mylist, count+1)
else:
return False
but for some reason it's not trying both ways
to get to the last item on the list.
for example: [1,2,2,3,4,5,3,2,1,7,0] and ,start=mylist[0]
it supposed to jump like this (from 1-2-4-1-left to 2-left to 5-right to 0)
but it keeps trying to go right and then index is out of range etc.
I thought that if u use return of or this or that, it will try both until it reaches True, why won't it work here?
Thanks!
Include the value you want to keep as a default parameter for the method, like this:
def my_func(int, list, i=0):
a = (i + int)
if int == 0:
return True
elif a > len(list):
i -= int
else:
i += int
int = list[i]
my_func(int, list, i)
Bear in mind that it may not even always be possible to arrive at the end of the list doing the jumping pattern you describe, and even if it is possible, this method may choose the wrong branch.
A better algorithm would look like this:
def branching_search(list, start):
marks = [0]*len(list)
pos = start
while list[pos]!=0:
marks[pos]++
if marks[pos] % 2 == 0 and pos + list[pos] < len(list):
pos += list[pos]
elif marks[pos] % 2 == 1 and pos - list[pos] >= 0:
pos -= list[pos]
else:
return False
if all(item == 0 or item > 1 for item in list)
return False
return True
This way, if it comes to an item that it has already visited, it will decide to go the opposite direction that it went last time. Also, if it comes to an item that it can't leave without going out-of-bounds, or if there is not way to get to the end, it will give up and return.
EDIT: I realized there are a number of flaws in this algorithm! Although it is better than the first approach, it is not guaranteed to work, although the reasons are somewhat complicated.
Just imagine this array (the unimportant elements are left blank):
1, 2, , 5, , , , , 5, 0
The first two elements would get only one mark (thus the loop checking condition would not work), but it would still get stuck looping between the two fives.
Here is a method that will always work:
def flood_search(list):
marks = [[]]*len(list)
marks[0] = [0]
still_moving = True
while still_moving:
still_moving = False
for pos in range(0,len(list)):
if marks[pos]:
if pos + list[pos] < len(list) and not marks[pos + list[pos]]:
marks[pos + list[pos]] = marks[pos] + [list[pos]];
pos += list[pos]
still_moving = True
if pos - list[pos] >= 0 and not marks[pos - list[pos]]:
marks[pos - list[pos]] = marks[pos] + [-list[pos]];
pos -= list[pos]
still_moving = True
return marks[-1]
This works by taking every possible branch at the same time.
You can also use the method to get the actual route taken to get to the end. It can still be used as a condition, since it returns an empty list if no path is found (a falsy value), or a list containing the path if a path is found (a truthy value).
However, you can always just use list[-1] to get the last item.

Tips for function inside while loop and i=i+1, Matlab

I have a problem with a function in matlab. This specific function is for filtering light signals. As you can see below I added the coding I’ve used in the function and in the while loop itself. The code is written for a NXT Lego robot.
Is there any tip how to get the count variable ( i = i + 1 ) to work in the function, so we can plot Light(i)? Because we’re getting a bunch of error messages when we try different codes to make it work.
function [light] = filter_func( i)
lightI(i) = GetLight(SENSOR_3);
if i==1
light(i)=lightI(i)
elseif i==2
light(i) = 0.55*lightI(i) + 0.45*lightI(i-1)
else
light(i) = 0.4*lightI(i) + 0.3*lightI(i-1) + 0.3*lightI(i-2);
end
end
i=1
while true
lightI(i) = GetLight(SENSOR_3); % Get’s a lightvalue between 0 and 1024.
if i>2
light =filter_func(i)
light=round(light);
else
light(i) = GetLight(SENSOR_3);;
end
i=1+i
plot(light(end-90:end), 'r-');
title('Lightvalue')
axis([0 100 0 1023]) ;
end
You probably mainly get errors because you are not allowed to mix script and functions like this in MATLAB (like you are in Python).
Your filter function is only used when i>2 so why are you doing the first 2 tests? It seems like you want lightI as a global variable, but that is not what you have done. The lightI inside the function is not the same as the one in the while loop.
Since your while loop runs forever, maybe you don't need to worry about updating the plot the first two times. In that case you can do this:
filter = [0.4 0.3 0.3]';
latest_filtered_light = nan(90,1);
lightI = [];
p = plot(latest_filtered_light, 'r-');
title('Lightvalue')
axis([0 100 0 1023]) ;
while True
lightI(end+1,1) = rand*1024; % Get’s a lightvalue between 0 and 1024.
if i>=3
new_val = lightI(end-2:end,1)'*filter;
latest_filtered_light = [latest_filtered_light(2:end);...
new_val];
set(p, 'ydata', latest_filtered_light)
drawnow
end
end
I think it is an important point to not call plot every time - at least if you are the least concerned about performance.

How to recognize that short code blocks can be refactored into something cleaner?

i have a bit of code that i wrote a few weeks ago (the code's purpose isn't so much important as its structure):
if (_image.Empty)
{
//Use the true image size if they haven't specified a custom size
if (_glyphSize.Width > 0)
imageSize.Width = _glyphSize.Width //override
else
imageSize.Width = _image.GetWidth;
if (_glyphSize.Height > 0) then
imageSize.Height = _glyphSize.Height
else
imageSize.Height = _image.GetHeight
}
else
{
//No image, but they can still override it with a custom size
if (_glyphSize.Width > 0) then
imageSize.Width = _glyphSize.Width
else
imageSize.Width = 0;
if (_glyphSize.Height > 0)
imageSize.Height = _glyphSize.Height
else
imageSize.Height := 0;
}
i was going over it tonight, and as i was cleaning it up, i realized that the cleaned version is must more concise:
//Figure out the final image width
if (_glyphSize.Width > 0)
imageSize.Width = _glyphSize.Width
else if (not _glyph.Empty)
imageSize.Width = _glyph.GetWidth
else
imageSize.Width = 0;
//Figure out the final image height
if (_glyphSize.Height > 0)
imageSize.Height = _glyphSize.Height
else if (not _glyph.Empty)
imageSize.Height = _glyph.GetHeight
else
imageSize.Height = 0;
Note: i've trimmed down the code to bare logical flow, and obfsucated the source language.
In the end i took the nested if's, and inverted them. Doing that allowed this shortening. My question is: how can i recognize this in the future?
What are the tell-tale signs that i've just written some code that can be refactored into something shorter?
Another example i had from a few weeks ago was something akin to a permission check: the user can perform an action:
if they have the permission they can do it
if they don't have the permission, but the override is in effect
Which i initially coded as:
if ((HasPermission || (!HasPermission and OverrideEnabled))
{
...do stuff
}
The logical conditions on that if clause seemed kind of wordy. i tried to reach back to my boolean algebra course to figure out how to simplify it. In the end i could do it, so i ended up drawing a truth table:
Permission Override Result
0 0 0
0 1 1
1 0 1
1 1 1
Which when i look at it is an OR operation. So my if statement became:
if (HasPermission or OverrideEnabled)
{
...
}
Which is obvious and simple. And so now i'm wondering how i couldn't see that to begin with.
Which brings me back to my SO question: What tell-tale signs could/should i be looking for in order to recognize that some block of code needs some TLC?
Here are some guidelines from Code Complete, off the top of my head. That is a good book to get for this sort of thing.
Nested if-else and repeated statements in blocks
Long for-loops
Repeated lines/statements or frequently used operations can be placed in a function
If for some reasons you are copying and pasting a line of code over and over again
I found discrete maths to have an influence in how I wrote if statements now. Usually, I see I am writing two same IF statements in 2 blocks, then I would do some mental 'factoring'.
Specifically related to boolean evaluation, it's worth noting that most(?) modern languages implement lazy evaluation.
That is, if "a" is true, then if(a) and if(a or b) are logically and functionally equivelant; the interpreter stops evaluating when it sees or after a true variable. This isn't very important when a and b are variables, but if they're callables [e.g. if(a() or b())], b() will not get evaluated when a is true.
You can save a lot of keystrokes (and processor time) by learning this well:
if(!userExists()):
if(!createUser()):
errorHandling()
else:
doStuff()
else: doStuff()
becomes
if(userExists() or createUser()): doStuff()
else: errorHandling()
Well done. Now, when I see this:
//Figure out the final image width
if (_glyphSize.Width > 0)
...
//Figure out the final image height
if (_glyphSize.Height > 0)
...
I think there is still more refactoring to do. Extracting code into methods isn't just a great way to eliminate redundant code. It's also a great way to make the code self documenting:
I'd be inclined to reduce the code to:
set_final_image_size
With set_final_image_size and its minions defined like so:
def set_final_image_size:
imageSize.Width = final_image_width;
imageSize.Height = final_image_height;
def final_image_width:
if (_glyphSize.Width > 0)
return _glyphSize.Width;
else if (not _glyph.Empty)
return _glyph.GetWidth;
else
return 0;
def final_image_height:
if (_glyphSize.Height > 0)
return _glyphSize.Height;
else if (not _glyph.Empty)
return _glyph.GetHeight;
else
return 0;
Now that you've separated the width and height logic, and noticed that it's identical - what if you were to add, say, getDimension(Direction direction) and setDimension(Direction direction, int length) to your classes? Now you've got
if (_glyphSize.getDimension(direction) > 0)
imageSize.setDimension(direction, _glyphSize.getDimension(direction))
else if (not _glyph.Empty)
imageSize.setDimension(direction, _glyph.getDimension(direction))
else
imageSize.setDimension(direction, 0);
Extracting the local brings us:
length = _glyphSize.getDimension(direction);
if (length > 0)
imageSize.setDimension(direction, length)
else if (not _glyph.Empty)
imageSize.setDimension(direction, _glyph.getDimension(direction))
else
imageSize.setDimension(direction, 0);
taking it a little further:
length = _glyphSize.getDimension(direction);
if (length == 0 && !_glyph.Empty)
length = _glyph.getDimension(direction);
imageSize.setDimension(direction, length);
Which, to my eyes at least, is starting to look pretty nice.