Filtering return on serial port - visual-studio

I have a CO2 sensor on my Arduino Mega and sometimes randomly when I'm reading the CO2 measurement, the sensor will return a "?". The question mark causes my program to crash and return "input string was not in a correct format".
I haven't tried anything because I don't know what approach would be the best for this. The CO2 sensor returns the measurement in the form of "Z 00000" but when this question mark appears it shows that all that returned was a "\n". Currently, I have the program just reading the 5 digits after the Z.
if (returnString != "")
{
val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
What I expect to return is the digits after Z which works but every so often I will get a random line return which crashes everything.

According to the C# documentation the ToDouble method throws FormatException whenever the input string is invalid. You should catch the exception to avoid further issues.
try {
val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
catch(FormatException e) {
//If you want to do anything in case of an error
//Otherwise you can leave it blank
}
Also I'd recommend using some sort of statemachine for parsing the data in your case, that could discard all invalid characters. Something like this:
bool z_received = false;
int digits = 0;
int value = 0;
//Called whenever you receive a byte from the serial port
void onCharacter(char input) {
if(input == 'Z') {
z_received = true;
}
else if(z_received && input <= '9' && input >= '0') {
value *= 10;
value += (input - '0');
digits++;
if(digits == 5) {
onData(value);
value = 0;
z_received = false;
digits = 0;
}
}
else {
value = 0;
z_received = false;
digits = 0;
}
}
void onData(int data) {
//do something with the data
}
This is just a mock-up, should work in your case if you can direct the COM port's byte stream into the onCharacter function.

Related

Algorithm / data structure for resolving nested interpolated values in this example?

I am working on a compiler and one aspect currently is how to wait for interpolated variable names to be resolved. So I am wondering how to take a nested interpolated variable string and build some sort of simple data model/schema for unwrapping the evaluated string so to speak. Let me demonstrate.
Say we have a string like this:
foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}
That has 1, 2, and 3 levels of nested interpolations in it. So essentially it should resolve something like this:
wait for x, y, one, two, and c to resolve.
when both x and y resolve, then resolve a{x}-{y} immediately.
when both one and two resolve, resolve baz{one}-{two}.
when a{x}-{y}, baz{one}-{two}, and c all resolve, then finally resolve the whole expression.
I am shaky on my understanding of the logic flow for handling something like this, wondering if you could help solidify/clarify the general algorithm (high level pseudocode or something like that). Mainly just looking for how I would structure the data model and algorithm so as to progressively evaluate when the pieces are ready.
I'm starting out trying and it's not clear what to do next:
{
dependencies: [
{
path: [x]
},
{
path: [y]
}
],
parent: {
dependency: a{x}-{y} // interpolated term
parent: {
dependencies: [
{
}
]
}
}
}
Some sort of tree is probably necessary, but I am having trouble figuring out what it might look like, wondering if you could shed some light on that with some pseudocode (or JavaScript even).
watch the leaf nodes at first
then, when the children of a node are completed, propagate upward to resolving the next parent node. This would mean once x and y are done, it could resolve a{x}-{y}, but then wait until the other nodes are ready before doing the final top-level evaluation.
You can just simulate it by sending "events" to the system theoretically, like:
ready('y')
ready('c')
ready('x')
ready('a{x}-{y}')
function ready(variable) {
if ()
}
...actually that may not work, not sure how to handle the interpolated nodes in a hacky way like that. But even a high level description of how to solve this would be helpful.
export type SiteDependencyObserverParentType = {
observer: SiteDependencyObserverType
remaining: number
}
export type SiteDependencyObserverType = {
children: Array<SiteDependencyObserverType>
node: LinkNodeType
parent?: SiteDependencyObserverParentType
path: Array<string>
}
(What I'm currently thinking, some TypeScript)
Here is an approach in JavaScript:
Parse the input string to create a Node instance for each {} term, and create parent-child dependencies between the nodes.
Collect the leaf Nodes of this tree as the tree is being constructed: group these leaf nodes by their identifier. Note that the same identifier could occur multiple times in the input string, leading to multiple Nodes. If a variable x is resolved, then all Nodes with that name (the group) will be resolved.
Each node has a resolve method to set its final value
Each node has a notify method that any of its child nodes can call in order to notify it that the child has been resolved with a value. This may (or may not yet) lead to a cascading call of resolve.
In a demo, a timer is set up that at every tick will resolve a randomly picked variable to some number
I think that in your example, foo, and a might be functions that need to be called, but I didn't elaborate on that, and just considered them as literal text that does not need further treatment. It should not be difficult to extend the algorithm with such function-calling features.
class Node {
constructor(parent) {
this.source = ""; // The slice of the input string that maps to this node
this.texts = []; // Literal text that's not part of interpolation
this.children = []; // Node instances corresponding to interpolation
this.parent = parent; // Link to parent that should get notified when this node resolves
this.value = undefined; // Not yet resolved
}
isResolved() {
return this.value !== undefined;
}
resolve(value) {
if (this.isResolved()) return; // A node is not allowed to resolve twice: ignore
console.log(`Resolving "${this.source}" to "${value}"`);
this.value = value;
if (this.parent) this.parent.notify();
}
notify() {
// Check if all dependencies have been resolved
let value = "";
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (!child.isResolved()) { // Not ready yet
console.log(`"${this.source}" is getting notified, but not all dependecies are ready yet`);
return;
}
value += this.texts[i] + child.value;
}
console.log(`"${this.source}" is getting notified, and all dependecies are ready:`);
this.resolve(value + this.texts.at(-1));
}
}
function makeTree(s) {
const leaves = {}; // nodes keyed by atomic names (like "x" "y" in the example)
const tokens = s.split(/([{}])/);
let i = 0; // Index in s
function dfs(parent=null) {
const node = new Node(parent);
const start = i;
while (tokens.length) {
const token = tokens.shift();
i += token.length;
if (token == "}") break;
if (token == "{") {
node.children.push(dfs(node));
} else {
node.texts.push(token);
}
}
node.source = s.slice(start, i - (tokens.length ? 1 : 0));
if (node.children.length == 0) { // It's a leaf
const label = node.texts[0];
leaves[label] ??= []; // Define as empty array if not yet defined
leaves[label].push(node);
}
return node;
}
dfs();
return leaves;
}
// ------------------- DEMO --------------------
let s = "foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}";
const leaves = makeTree(s);
// Create a random order in which to resolve the atomic variables:
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
[array[j], array[i]] = [array[i], array[j]];
}
return array;
}
const names = shuffle(Object.keys(leaves));
// Use a timer to resolve the variables one by one in the given random order
let index = 0;
function resolveRandomVariable() {
if (index >= names.length) return; // all done
console.log("\n---------------- timer tick --------------");
const name = names[index++];
console.log(`Variable ${name} gets a value: "${index}". Calling resolve() on the connected node instance(s):`);
for (const node of leaves[name]) node.resolve(index);
setTimeout(resolveRandomVariable, 1000);
}
setTimeout(resolveRandomVariable, 1000);
your idea of building a dependency tree it's really likeable.
Anyway I tryed to find a solution as simplest possible.
Even if it already works, there are many optimizations possible, take this just as proof of concept.
The background idea it's produce a List of Strings which you can read in order where each element it's what you need to solve progressively. Each element might be mandatory to solve something that come next in the List, hence for the overall expression. Once you solved all the chunks you have all pieces to solve your original expression.
It's written in Java, I hope it's understandable.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class StackOverflow {
public static void main(String[] args) {
String exp = "foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}";
List<String> chunks = expToChunks(exp);
//it just reverse the order of the list
Collections.reverse(chunks);
System.out.println(chunks);
//output -> [c, two, one, baz{one}-{two}, y, x, a{x}-{y}]
}
public static List<String> expToChunks(String exp) {
List<String> chunks = new ArrayList<>();
//this first piece just find the first inner open parenthesys and its relative close parenthesys
int begin = exp.indexOf("{") + 1;
int numberOfParenthesys = 1;
int end = -1;
for(int i = begin; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '{') numberOfParenthesys ++;
if (c == '}') numberOfParenthesys --;
if (numberOfParenthesys == 0) {
end = i;
break;
}
}
//this if put an end to recursive calls
if(begin > 0 && begin < exp.length() && end > 0) {
//add the chunk to the final list
String substring = exp.substring(begin, end);
chunks.add(substring);
//remove from the starting expression the already considered chunk
String newExp = exp.replace("{" + substring + "}", "");
//recursive call for inner element on the chunk found
chunks.addAll(Objects.requireNonNull(expToChunks(substring)));
//calculate other chunks on the remained expression
chunks.addAll(Objects.requireNonNull(expToChunks(newExp)));
}
return chunks;
}
}
Some details on the code:
The following piece find the begin and the end index of the first outer chunk of expression. The background idea is: in a valid expression the number of open parenthesys must be equal to the number of closing parenthesys. The count of open(+1) and close(-1) parenthesys can't ever be negative.
So using that simple loop once I find the count of parenthesys to be 0, I also found the first chunk of the expression.
int begin = exp.indexOf("{") + 1;
int numberOfParenthesys = 1;
int end = -1;
for(int i = begin; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '{') numberOfParenthesys ++;
if (c == '}') numberOfParenthesys --;
if (numberOfParenthesys == 0) {
end = i;
break;
}
}
The if condition provide validation on the begin and end indexes and stop the recursive call when no more chunks can be found on the remained expression.
if(begin > 0 && begin < exp.length() && end > 0) {
...
}

Expert Advisor timefilter doesn't work (mql5)?

I can't figure out why my timefilter doesn't work. Let's say I would like to only enter to positions between 7:35-11:30 and 14:30-22:30 and I don't want to enter a position on Friday.
The time filter only works when I create a simple EA with only a trade.Buy function and no other conditions.
The more complex EA should only enter a position when the vaule of the Supertrend indicator becomes higher/lower than the price and only in the given time intervals.
It should close the position at the next sell/buy signal (if it was a buy position then the position should be closed at the next 'sell' signal' ). When closing positions the time interval shouldn't matter it should only mater when entering a new position.
The 'TradingIsAllowed' variable should be 'true' when the current time is in the allowed time intervals but it always returns false for some reason and I can't figure out why.
It works perfectly fine when I don't use the supertrend and close trades with a simple tp/sl.
Could you please help me?
#include <Trade\Trade.mqh>
CTrade trade;
ulong posTicket;
input double Lots=0.1;
int stHandle;
int totalBars;
input ENUM_TIMEFRAMES Timeframe = PERIOD_CURRENT;
input int Periods =12;
input double Multiplier = 3.0;
//for the timefilter
input string StartTradingTime="07:35";
input string StopTradingTime="11:30";
input string StartTradingTime2="14:35";
input string StopTradingTime2="22:30";
string CurrentTime;
bool TradingIsAllowed=false;
bool TradingIsAllowed2=false;
int OnInit(){
totalBars=iBars(_Symbol,Timeframe);
stHandle = iCustom(_Symbol, Timeframe, "Supertrend.ex5", Periods, Multiplier);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason){
}
void OnTick(){
//for the timefilter
datetime LocalTime=TimeLocal();
string HoursAndMinutes=TimeToString(LocalTime,TIME_MINUTES);
string YearAndDate=TimeToString(LocalTime, TIME_DATE);
MqlDateTime DateTimeStructure;
TimeToStruct(LocalTime, DateTimeStructure);
int DayOfWeek=DateTimeStructure.day_of_week;
datetime time = TimeLocal();
CurrentTime=TimeToString(time,TIME_MINUTES);
//this should only run if there is a new bar
int bars=iBars(_Symbol, Timeframe);
if(totalBars !=bars){
totalBars=bars;
double st[];
CopyBuffer(stHandle,0,0,3,st);
double close1 = iClose(_Symbol, Timeframe, 1);
double close2 = iClose(_Symbol, Timeframe, 2);
//BUY CONDITION
if(close1 > st[1] && close2 < st[0]){
if(posTicket > 0 ){
if(PositionSelectByTicket(posTicket)){
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL){
if (trade.PositionClose(posTicket)){
Print(__FUNCTION__," > Pos ", posTicket, "was closed..");
}
}
}
}
if(CheckTradingTime()==true || CheckTradingTime2()==true){
if(PositionsTotal()==0 && DayOfWeek!=5){
Print(__FUNCTION__, " > BOUGHT");
if(trade.Buy(Lots, _Symbol)){
if(trade.ResultRetcode() == TRADE_RETCODE_DONE){
posTicket= trade.ResultOrder();
}
}
}
}
}
else if(close1 < st[1] && close2 > st[0]){
if(posTicket > 0 ){
if(PositionSelectByTicket(posTicket)){
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY){
if (trade.PositionClose(posTicket)) {
Print(__FUNCTION__," > Pos ", posTicket, "was closed..");
}
}
}
}
if(CheckTradingTime()==true || CheckTradingTime2()==true){
if(PositionsTotal()==0 && DayOfWeek!=5){
Print(__FUNCTION__, " > SOLD");
if(trade.Sell(Lots, _Symbol)){
if(trade.ResultRetcode() == TRADE_RETCODE_DONE){
posTicket= trade.ResultOrder();
}
}
}
}
}
}
Comment (
"TradingIsAllowed", TradingIsAllowed, TradingIsAllowed2, "\n", //TradingIsAllowed always returns false..
"Current Time=", CurrentTime,"\n",
"Trading Session1=", StartTradingTime,"-" ,StopTradingTime, "\n",
"Trading Session2=", StartTradingTime2, "-", StopTradingTime2,"\n",
"Day of Week", DayOfWeek
);
}
//trading session 1
bool CheckTradingTime()
{
if(StringSubstr(CurrentTime,0,5)==StartTradingTime)
TradingIsAllowed=true;
if(StringSubstr(CurrentTime,0,5)==StopTradingTime)
TradingIsAllowed=false;
return TradingIsAllowed;
}
//trading session 2
bool CheckTradingTime2()
{
if(StringSubstr(CurrentTime,0,5)==StartTradingTime2)
TradingIsAllowed2=true;
if(StringSubstr(CurrentTime,0,5)==StopTradingTime2)
TradingIsAllowed2=false;
return TradingIsAllowed2;
}
you dont neet to write "(StringSubstr(CurrentTime,0,5)==StartTradingTime)"
you can write only "CurrentTime == StartTradingTime"

Java Palindrome always returns true

I tried to create a palindrome java program with JOptionPane by using for loop, but it ends up returning true all the time no matter the input is really a palindrome or not. Can guys please help if you guys know what's wrong with the code below, thanks.
public class program {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JOptionPane.showMessageDialog(null, "Welcome to The Palindrome!", "Hello", JOptionPane.INFORMATION_MESSAGE);
String str = JOptionPane.showInputDialog("Please input a string");
int len = str.length();
int j = len - 1;
int i = 0;
boolean result;
for(i = 0; i <= (len - 1)/2; i++);
{
if(str.charAt(i) != str.charAt(j))
result = false;
j--;
}
if(result = true)
JOptionPane.showMessageDialog(null, str + " is a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
if(result = false)
JOptionPane.showMessageDialog(null, str + " is not a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
}
Instead of using traditional way to check palindrome, just use the smart way. Here you go
boolean result = str.equalsIgnoreCase(new StringBuffer(str).reverse().toString());
When you check for the value of result, you are using =, which assigns that value to the result variable, and always evaluates to true.
To correct your code, you can either remove the equal sign, or use result == true (usually you use the former, as it is more concise).
However, this may result in an error, as you are not initialising the value of result. I recommend setting it's value to true as the default value.

PVS-Studio: warning V595 is generated even if pointer is checked

In the following code there is already check for nullptr in (1):
int msg;
struct x * var[2];
if ((var[0] = get_x()) == nullptr) { // (1)
return;
}
if (var[0]->data != 11) { // (2) <<< V595
msg = 1;
printf("msg1");
}
if (var[0] && var[0]->data == 12) { // (3) <<< V595
msg = 2;
return;
}
but I still get error: V595. Why?
I agree that there is an exceeding check for nullptr in (3).
Analyzer considers this piece of code abnormal. First, the pointer is being deferenced, and after that it is being verified. Even if it cannot be equal to NULL, it looks very suspicious. There's a possibility that wrong variable is used or checked.
So it is possible that the wrong variable is used, and the corrected version of code could look like:
if (FOO->data != 11) {
msg = 1;
printf("msg1");
}
if (var[0] && var[0]->data == 12) {
msg = 2;
return;
}
Or, probably, the condition is incorrect:
if (var[0]->data != 11) {
msg = 1;
printf("msg1");
}
if (FOO && var[0]->data == 12) {
msg = 2;
return;
}
Anyway, the analyzer doesn't like it, and it issues a warning. To eliminate such warnings, remove unnecessary checks which overload the code and confuse other programmers and the analyzer. In this case the analyzer will not issue the warning:
if ((var[0] = get_x()) == nullptr) {
return;
}
if (var[0]->data != 11) {
msg = 1;
printf("msg1");
}
if (var[0]->data == 12) {
msg = 2;
return;
}
If you don't want to remove this check, use one of the following ways to suppress warnings:
Suppression of false alarms
Mass Suppression of Analyzer Messages

text box percentage validation in javascript

How can we do validation for percentage numbers in textbox .
I need to validate these type of data
Ex: 12-3, 33.44a, 44. , a3.56, 123
thanks in advance
sri
''''Add textbox'''''
<asp:TextBox ID="PERCENTAGE" runat="server"
onkeypress="return ispercentage(this, event, true, false);"
MaxLength="18" size="17"></asp:TextBox>
'''''Copy below function as it is and paste in tag..'''''''
<script type="text/javascript">
function ispercentage(obj, e, allowDecimal, allowNegative)
{
var key;
var isCtrl = false;
var keychar;
var reg;
if (window.event)
{
key = e.keyCode;
isCtrl = window.event.ctrlKey
}
else if (e.which)
{
key = e.which;
isCtrl = e.ctrlKey;
}
if (isNaN(key)) return true;
keychar = String.fromCharCode(key);
// check for backspace or delete, or if Ctrl was pressed
if (key == 8 || isCtrl)
{
return true;
}
ctemp = obj.value;
var index = ctemp.indexOf(".");
var length = ctemp.length;
ctemp = ctemp.substring(index, length);
if (index < 0 && length > 1 && keychar != '.' && keychar != '0')
{
obj.focus();
return false;
}
if (ctemp.length > 2)
{
obj.focus();
return false;
}
if (keychar == '0' && length >= 2 && keychar != '.' && ctemp != '10') {
obj.focus();
return false;
}
reg = /\d/;
var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
return isFirstN || isFirstD || reg.test(keychar);
}
</script>
You can further optimize this expression. Currently its working for all given patterns.
^\d*[aA]?[\-.]?\d*[aA]?[\-.]?\d*$
If you're talking about checking that a given text is a valid percentage, you can do one of a few things.
validate it with a regex like ^[0-9]+\.?[0-9]*$ then just convert that to a floating point value and check it's between 0 and 100 (that particular regex requires a zero before the decimal for values less than one but you can adapt it to handle otherwise).
convert it to a float using a method that raises an exception on invalid data (rather than just stopping at the first bad character.
use a convoluted regex which checks for valid entries without having to convert to a float.
just run through the text character by character counting numerics (a), decimal points (b) and non-numerics (c). Provided a is at least one, b is at most one, and c is zero, then convert to a float.
I have no idea whether your environment support any of those options since you haven't actually specified what it is :-)
However, my preference is to go for option 1, 2, 4 and 3 (in that order) since I'm not a big fan of convoluted regexes. I tend to think that they do more harm than good when thet become to complex to understand in less than three seconds.
Finally i tried a simple validation and works good :-(
function validate(){
var str = document.getElementById('percentage').value;
if(isNaN(str))
{
//alert("value out of range or too much decimal");
}
else if(str > 100)
{
//alert("value exceeded");
}
else if(str < 0){
//alert("value not valid");
}
}

Resources