Python - Decoding RS422 data from device - decode

Controller Documentation page 124
Serial Sniffing screenshot
The hardware setup should be OK, everything works as it should when I use their sensorTOOL 1.8., also I made it working with similar code for an optoNCDT 1420 laser sensor (which sends the data in strings with fixed lengths). This one is a confocalDT controller with IFS2406-10 sensor. These sensors are used to measure distance.
I know this script is not the right way to do it.
import serial
import sys
import time
import os
try:
ser = serial.Serial('COM4', 115200)
print("connected")
except:
print("no comm")
while True:
try:
#read 9 Bytes
byte1 = ser.read()
byte2 = ser.read()
byte3 = ser.read()
byte4 = ser.read()
byte5 = ser.read()
byte6 = ser.read()
byte7 = ser.read()
byte8 = ser.read()
byte9 = ser.read()
#convert bytes to int
byte1bits = int.from_bytes(byte1, byteorder=sys.byteorder)
byte2bits = int.from_bytes(byte2, byteorder=sys.byteorder)
byte3bits = int.from_bytes(byte3, byteorder=sys.byteorder)
byte4bits = int.from_bytes(byte4, byteorder=sys.byteorder)
byte5bits = int.from_bytes(byte5, byteorder=sys.byteorder)
byte6bits = int.from_bytes(byte6, byteorder=sys.byteorder)
byte7bits = int.from_bytes(byte7, byteorder=sys.byteorder)
byte8bits = int.from_bytes(byte8, byteorder=sys.byteorder)
byte9bits = int.from_bytes(byte9, byteorder=sys.byteorder)
#print(str(byte1bits) + " " + str(byte2bits) + " " + str(byte3bits) + " " + str(byte4bits) + " " + str(byte5bits) + " " + str(byte6bits) + " " + str(byte7bits) + " " + str(byte8bits) + " " + str(byte9bits))
#convert to bits, store as a string
byte1bits = str(bin(byte1bits)[2:].zfill(8))
byte2bits = str(bin(byte2bits)[2:].zfill(8))
byte3bits = str(bin(byte3bits)[2:].zfill(8))
byte4bits = str(bin(byte4bits)[2:].zfill(8))
byte5bits = str(bin(byte5bits)[2:].zfill(8))
byte6bits = str(bin(byte6bits)[2:].zfill(8))
byte7bits = str(bin(byte7bits)[2:].zfill(8))
byte8bits = str(bin(byte8bits)[2:].zfill(8))
byte9bits = str(bin(byte9bits)[2:].zfill(8))
clear = lambda: os.system("cls")
clear()
print(byte1bits)
print(byte2bits)
print(byte3bits)
print(byte4bits)
print(byte5bits)
print(byte6bits)
print(byte7bits)
print(byte8bits)
print(byte9bits)
LbyteFound = 0
MbyteFound = 0
HbyteFound = 0
#sort L/M/H-Bytes
if byte1bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte1bits)
LbyteFound = 1
print("Lbyte - byte1bits active")
if byte2bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte2bits)
LbyteFound = 1
print("Lbyte - byte2bits active")
if byte3bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte3bits)
LbyteFound = 1
print("Lbyte - byte3bits active")
if byte4bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte4bits)
LbyteFound = 1
print("Lbyte - byte4bits active")
if byte5bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte5bits)
LbyteFound = 1
print("Lbyte - byte5bits active")
if byte6bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte6bits)
LbyteFound = 1
print("Lbyte - byte6bits active")
if byte7bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte7bits)
LbyteFound = 1
print("Lbyte - byte7bits active")
if byte8bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte8bits)
LbyteFound = 1
print("Lbyte - byte8bits active")
if byte9bits.startswith("00") == True and LbyteFound == 0:
Lbyte = str(byte9bits)
LbyteFound = 1
print("Lbyte - byte9bits active")
if byte1bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte1bits)
MbyteFound = 1
print("Mbyte - byte1bits active")
if byte2bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte2bits)
MbyteFound = 1
print("Mbyte - byte2bits active")
if byte3bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte3bits)
MbyteFound = 1
print("Mbyte - byte3bits active")
if byte4bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte4bits)
MbyteFound = 1
print("Mbyte - byte4bits active")
if byte5bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte5bits)
MbyteFound = 1
print("Mbyte - byte5bits active")
if byte6bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte6bits)
MbyteFound = 1
print("Mbyte - byte6bits active")
if byte7bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte7bits)
MbyteFound = 1
print("Mbyte - byte7bits active")
if byte8bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte8bits)
MbyteFound = 1
print("Mbyte - byte8bits active")
if byte9bits.startswith("01") == True and MbyteFound == 0:
Mbyte = str(byte9bits)
MbyteFound = 1
print("Mbyte - byte9bits active")
if byte1bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte1bits)
print("Hbyte - byte1bits active")
HbyteFound=1
if byte2bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte2bits)
print("Hbyte - byte2bits active")
HbyteFound=1
if byte3bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte3bits)
print("Hbyte - byte3bits active")
HbyteFound=1
if byte4bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte4bits)
print("Hbyte - byte4bits active")
HbyteFound=1
if byte5bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte5bits)
print("Hbyte - byte5bits active")
HbyteFound=1
if byte6bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte6bits)
print("Hbyte - byte6bits active")
HbyteFound=1
if byte7bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte7bits)
print("Hbyte - byte7bits active")
HbyteFound=1
if byte8bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte8bits)
print("Hbyte - byte8bits active")
HbyteFound=1
if byte9bits.startswith("10") == True and HbyteFound == 0:
Hbyte = str(byte9bits)
print("Hbyte - byte9bits active")
HbyteFound=1
#reduce to data (ignore ID bits)
Lbyte = Lbyte[2:8]
Mbyte = Mbyte[2:8]
Hbyte6 = Hbyte[2:8]
Hbyte = Hbyte[2:8]
#get 16 bit value
value16 = str(Hbyte) + str(Mbyte) + str(Lbyte)
#print(value16)
#get 18 bit value
value18 = str(Hbyte6) + str(Mbyte) + str(Lbyte)
value18 = int(value18, 2)
#conversion
measure=int(value16, 2)
#print(measure)
#calculate measurement
try:
result=((measure-98232)*10)/65536
except:
print("measurement calculation failed")
#output
if value18 == 262075:
print("Too much data for selected baud rate")
if value18 == 262076:
print("There is no peak present")
if value18 == 262077:
print("Peak is located in front of the measuring range (MR)")
if value18 == 262078:
print("Peak is located behind the measuring range (MR)")
if value18 <= 262074:
NULL=0
print(measure)
print(result)
#ser.read(64)
except:
#NULL=0
print("NO DATA")
time.sleep(0.01)
Script Output:
01001010
10000000
00011010
01000111
11000000
00111001
01000011
11011111
00000100
Lbyte - byte3bits
Mbyte - byte1bits
Hbyte - byte2bits
666
-14.88739013671875
altough the script (sometimes) detects the L/M/H byte I never get any valid calculated measuring value out of it -14.88... instead of 0-10 (millimeters)

Related

End of line without continuation problem again. Need to add this to BTC or ETH

first question here. Just starting to learn PineScript and I just want to add this to my charts. The first error is the usual "end of line without continuation" at line 69 (I tried on that particular line in different ways but with no result), I believe once that's solved there's gonna be another errors related to the use of tabular space right?
If anyone is willing to try to add this to any crypto and tell me what's wrong I would appreciate it.
Here's the actual code (also the original code was in version 4, the change of version affects it?)
Thanks!
study(title="El Loco", overlay=true)//, commission_type=strategy.commission.percent,
commission_value=0.025, default_qty_type=strategy.cash, default_qty_value=10000,
initial_capital=10000, slippage=0
// === INPUT BACKTEST RANGE ===
// useDate = input(true, title='---------------- Use Date ----------------', type=input.bool)
// FromMonth = input(defval=7, title="From Month", minval=1, maxval=12)
// FromDay = input(defval=25, title="From Day", minval=1, maxval=31)
// FromYear = input(defval=2019, title="From Year", minval=2017)
// ToMonth = input(defval=1, title="To Month", minval=1, maxval=12)
// ToDay = input(defval=1, title="To Day", minval=1, maxval=31)
// ToYear = input(defval=9999, title="To Year", minval=2017)
// start = timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start window
// finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest finish window
// window() => // create function "within window of time"
// time >= start and time <= finish ? true : false
// === INPUT BACKTEST RANGE ===
sources = input(defval=close, title="Source")
isHA = input(false, "Use HA Candles", input.bool)
heikenashi_1 = heikinashi(syminfo.tickerid)
security_1 = security(heikenashi_1, timeframe.period, sources)
src = isHA ? security_1 : sources
// Sampling Period
// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
per = input(defval=27, minval=1, title="Sampling Period")
// Range Multiplier
mult = input(defval=1.0, minval=0.1, title="Range Multiplier")
// Smooth Average Range
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ema(abs(x - x[1]), t)
smoothrng = ema(avrng, wper) * m
smoothrng
smrng = smoothrng(src, per, mult)
// Range Filter
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(src, smrng)
// Filter Direction
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])
// Target Bands
hband = filt + smrng
lband = filt - smrng
// Colors
filtcolor = upward > 0 ? color.lime : downward > 0 ? color.red : color.orange
barcolor = src > filt and src > src[1] and upward > 0 ? color.lime :
src > filt and src < src[1] and upward > 0 ? color.green :
src < filt and src < src[1] and downward > 0 ? color.red :
src < filt and src > src[1] and downward > 0 ? color.maroon : color.orange
//filtplot = plot(filt, color=filtcolor, linewidth=3, title="Range Filter")
// Target
hbandplot = plot(hband, color=color.aqua, transp=100, title="High Target")
lbandplot = plot(lband, color=color.fuchsia, transp=100, title="Low Target")
// Fills
//fill(hbandplot, filtplot, color=color.aqua, title="High Target Range")
//fill(lbandplot, filtplot, color=color.fuchsia, title="Low Target Range")
// Bar Color
//barcolor(barcolor)
// Break Outs
longCond = bool(na)
shortCond = bool(na)
longCond := src > filt and src > src[1] and upward > 0 or
src > filt and src < src[1] and upward > 0
shortCond := src < filt and src < src[1] and downward > 0 or
src < filt and src > src[1] and downward > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
longCondition = longCond and CondIni[1] == -1
shortCondition = shortCond and CondIni[1] == 1
//Alerts
plotshape(longCondition, title="Buy Signal", text="⁎", textcolor=color.white,
style=shape.labelup, size=size.large, location=location.belowbar, color=color.black, transp=10)
plotshape(shortCondition, title="Sell Signal", text="⁎", textcolor=color.white,
style=shape.labeldown, size=size.large, location=location.abovebar, color=color.black,
transp=10)
//strategy.entry("Long", strategy.long, stop = hband, when = window() , comment="Long")
//strategy.entry("Short", strategy.short, stop = lband, when = window() , comment="Short")
// strategy.entry("Long", strategy.long, when=longCondition and window(), comment="Long")
// strategy.entry("Short", strategy.short, when=shortCondition and window(),
comment="Short")
// // === Stop LOSS ===
// useStopLoss = input(false, title='----- Use Stop Loss / Take profit -----', type=input.bool)
// sl_inp = input(100, title='Stop Loss %', type=input.float, step=0.25) / 100
// tp_inp = input(1.5, title='Take Profit %', type=input.float, step=0.25) / 100
// stop_level = strategy.position_avg_price * (1 - sl_inp)
// take_level = strategy.position_avg_price * (1 + tp_inp)
// stop_level_short = strategy.position_avg_price * (1 + sl_inp)
// take_level_short = strategy.position_avg_price * (1 - tp_inp)
// // === Stop LOSS ===
// if useStopLoss
// strategy.exit("Stop Loss/Profit Long", "Long", stop=stop_level, limit=take_level)
// strategy.exit("Stop Loss/Profit Short", "Short", stop=stop_level_short,
limit=take_level_short)
// EMA
showEMA = input(false, title="EMA - Enabled")
emaConfig1 = input(21, "EMA 1", input.integer)
emaConfig2 = input(50, "Ema 2", input.integer)
emaConfig3 = input(200, "Ema 3", input.integer)
ema1 = ema(close, emaConfig1)
ema2 = ema(close, emaConfig2)
ema3 = ema(close, emaConfig3)
plot(showEMA ? ema1 : na, title="EMA", color=#FFFF00, linewidth=1)
plot(showEMA ? ema2 : na, title="EMA", color=#FF84D0, linewidth=1)
plot(showEMA ? ema3 : na, title="EMA", color=#9700FF, linewidth=1)
// BB
showBB = input(false, title="BB - Enabled")
length = input(20, minval=1, title="BB - Length")
multBB = input(2.0, minval=0.001, maxval=50, title="BB - StdDev")
basis = sma(close, length)
dev = multBB * stdev(close, length)
upper = basis + dev
lower = basis - dev
offset = input(0, "BB - Offset", type = input.integer, minval = -500, maxval = 500)
plot(showBB ? basis : na, "Basis", color=#872323, offset = offset)
p1 = plot(showBB ? upper : na, "Upper", color=color.teal, offset = offset)
p2 = plot(showBB ? lower : na, "Lower", color=color.teal, offset = offset)
fill(p1, p2, title = "Background", color=#198787, transp=95)
Try putting the lines in one line only like below
//#version=4
study(title="El Loco", overlay=true)//, commission_type=strategy.commission.percent,
commission_value=0.025, default_qty_type=strategy.cash, default_qty_value=10000,
initial_capital=10000, slippage=0
// === INPUT BACKTEST RANGE ===
// useDate = input(true, title='---------------- Use Date ----------------', type=input.bool)
// FromMonth = input(defval=7, title="From Month", minval=1, maxval=12)
// FromDay = input(defval=25, title="From Day", minval=1, maxval=31)
// FromYear = input(defval=2019, title="From Year", minval=2017)
// ToMonth = input(defval=1, title="To Month", minval=1, maxval=12)
// ToDay = input(defval=1, title="To Day", minval=1, maxval=31)
// ToYear = input(defval=9999, title="To Year", minval=2017)
// start = timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start window
// finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest finish window
// window() => // create function "within window of time"
// time >= start and time <= finish ? true : false
// === INPUT BACKTEST RANGE ===
sources = input(defval=close, title="Source")
isHA = input(false, "Use HA Candles", input.bool)
heikenashi_1 = heikinashi(syminfo.tickerid)
security_1 = security(heikenashi_1, timeframe.period, sources)
src = isHA ? security_1 : sources
// Sampling Period
// Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters
per = input(defval=27, minval=1, title="Sampling Period")
// Range Multiplier
mult = input(defval=1.0, minval=0.1, title="Range Multiplier")
// Smooth Average Range
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ema(abs(x - x[1]), t)
smoothrng = ema(avrng, wper) * m
smoothrng
smrng = smoothrng(src, per, mult)
// Range Filter
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(src, smrng)
// Filter Direction
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])
// Target Bands
hband = filt + smrng
lband = filt - smrng
// Colors
filtcolor = upward > 0 ? color.lime : downward > 0 ? color.red : color.orange
barcolor = src > filt and src > src[1] and upward > 0 ? color.lime : src > filt and src < src[1] and upward > 0 ? color.green : src < filt and src < src[1] and downward > 0 ? color.red : src < filt and src > src[1] and downward > 0 ? color.maroon : color.orange
//filtplot = plot(filt, color=filtcolor, linewidth=3, title="Range Filter")
// Target
hbandplot = plot(hband, color=color.aqua, transp=100, title="High Target")
lbandplot = plot(lband, color=color.fuchsia, transp=100, title="Low Target")
// Fills
//fill(hbandplot, filtplot, color=color.aqua, title="High Target Range")
//fill(lbandplot, filtplot, color=color.fuchsia, title="Low Target Range")
// Bar Color
//barcolor(barcolor)
// Break Outs
longCond = bool(na)
shortCond = bool(na)
longCond := src > filt and src > src[1] and upward > 0 or src > filt and src < src[1] and upward > 0
shortCond := src < filt and src < src[1] and downward > 0 or src < filt and src > src[1] and downward > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
longCondition = longCond and CondIni[1] == -1
shortCondition = shortCond and CondIni[1] == 1
//Alerts
plotshape(longCondition, title="Buy Signal", text="⁎", textcolor=color.white,style=shape.labelup, size=size.large, location=location.belowbar, color=color.black, transp=10)
plotshape(shortCondition, title="Sell Signal", text="⁎", textcolor=color.white,style=shape.labeldown, size=size.large, location=location.abovebar, color=color.black,transp=10)
//strategy.entry("Long", strategy.long, stop = hband, when = window() , comment="Long")
//strategy.entry("Short", strategy.short, stop = lband, when = window() , comment="Short")
// strategy.entry("Long", strategy.long, when=longCondition and window(), comment="Long")
// strategy.entry("Short", strategy.short, when=shortCondition and window(),comment="Short")
// // === Stop LOSS ===
// useStopLoss = input(false, title='----- Use Stop Loss / Take profit -----', type=input.bool)
// sl_inp = input(100, title='Stop Loss %', type=input.float, step=0.25) / 100
// tp_inp = input(1.5, title='Take Profit %', type=input.float, step=0.25) / 100
// stop_level = strategy.position_avg_price * (1 - sl_inp)
// take_level = strategy.position_avg_price * (1 + tp_inp)
// stop_level_short = strategy.position_avg_price * (1 + sl_inp)
// take_level_short = strategy.position_avg_price * (1 - tp_inp)
// // === Stop LOSS ===
// if useStopLoss
// strategy.exit("Stop Loss/Profit Long", "Long", stop=stop_level, limit=take_level)
// strategy.exit("Stop Loss/Profit Short", "Short", stop=stop_level_short,limit=take_level_short)
// EMA
showEMA = input(false, title="EMA - Enabled")
emaConfig1 = input(21, "EMA 1", input.integer)
emaConfig2 = input(50, "Ema 2", input.integer)
emaConfig3 = input(200, "Ema 3", input.integer)
ema1 = ema(close, emaConfig1)
ema2 = ema(close, emaConfig2)
ema3 = ema(close, emaConfig3)
plot(showEMA ? ema1 : na, title="EMA", color=#FFFF00, linewidth=1)
plot(showEMA ? ema2 : na, title="EMA", color=#FF84D0, linewidth=1)
plot(showEMA ? ema3 : na, title="EMA", color=#9700FF, linewidth=1)
// BB
showBB = input(false, title="BB - Enabled")
length = input(20, minval=1, title="BB - Length")
multBB = input(2.0, minval=0.001, maxval=50, title="BB - StdDev")
basis = sma(close, length)
dev = multBB * stdev(close, length)
upper = basis + dev
lower = basis - dev
offset = input(0, "BB - Offset", type = input.integer, minval = -500, maxval = 500)
plot(showBB ? basis : na, "Basis", color=#872323, offset = offset)
p1 = plot(showBB ? upper : na, "Upper", color=color.teal, offset = offset)
p2 = plot(showBB ? lower : na, "Lower", color=color.teal, offset = offset)
fill(p1, p2, title = "Background", color=#198787, transp=95)

Script Math's not correct lua minecraft

idk what is wrong but it writes this into the file when it saves the value. If u need more information or have a question please ask me! Thanks for your time and hopefully u your solution!
SebyGHG
My discord: S̸̽̚e̵̓̓b̸̿̕y̴͆͐#4638
Here is a screenshot of the time and the value in the file:
Value in file
Time in game
Code:
name = "Timer"
description = "Just a normal Timer."
positionX = 0
positionY = 0
sizeX = 24
sizeY = 10
scale = 1
START_STOP_KEY = 0x55 --or 'U'
RESET_KEY = 0x4A --or 'J'
--
--[[
Timer Module Script by SebyGHG original script by Onix64(Stopwatch)
if you wish to change the key you can take the key code from here
https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
]] -------------script-code-------------
state = 1
stopTime = 0
startTime = 0
f = io.input("timesave.txt")
result = f :read()
f :close()
stopTime = result
state = 2
function keyboard(key, isDown)
if (isDown == true) then
if (key == RESET_KEY) then
state = 0
elseif (key == START_STOP_KEY) then
if (state == 0) then
state = 1
startTime = os.time()
elseif (state == 1) then
state = 2
io.output("timesave.txt")
timesave= (io.open("timesave.txt","w"))
io.write(stopTime)
io.close(timesave)
stopTime = os.time()
elseif (state == 2) then
state = 1
startTime =startTime + os.time() - stopTime
end
end
end
end
TimerText = "00:00"
TextColor = {r = 30, g = 255, b = 30, a = 255}
function doubleDigit(number)
if (number < 10) then
return "0" .. math.floor(number)
else
return math.floor(number)
end
end
function timeText(time)
local result = ""
local days = 0
while (time > 86399) do
days = days + 1
time = time - 86400
end
local hours = 0
while (time > 3599) do
hours = hours + 1
time = time - 86400
end
local minutes = 0
while (time > 59) do
minutes = minutes + 1
time = time - 60
end
if (days == 0) then
if (hours == 0) then
return doubleDigit(minutes) .. ":" .. doubleDigit(time)
else
return math.floor(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time)
end
else
return math.floor(days) ..
" : " .. doubleDigit(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time)
end
end
function update()
if (state == 0) then
TextColor = {r = 255, g = 0, b = 0, a = 255}
TimerText = "00:00"
elseif (state == 1) then
TimerText = timeText(os.time() - startTime)
TextColor = {r = 0, g = 255, b = 255, a = 255}
elseif (state == 2) then
TimerText = timeText(stopTime - startTime)
TextColor = {r = 255, g = 255, b = 0, a = 255}
end
end
function render()
local font = gui.font()
local tw = font.width(TimerText)
gfx.color(0, 0, 0, 0)
gfx.rect(0, 0, tw + 4, 10)
gfx.color(TextColor.r, TextColor.g, TextColor.b, TextColor.a)
gfx.text(2, 1, TimerText)
end
One error I spot is this part
while (time > 3599) do
hours = hours + 1
time = time - 86400
end
this is most likely supposed to be
while (time > 3599) do
hours = hours + 1
time = time - 3600
end

Error: subscript out of bounds (knight's tour)

im new to R and im trying to solve for the minimum number of moves for a knight visit all the moves in a chess board.
I got the python code from:
https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/
and i tried to translate it to r.
But i am always getting the error and I don't know where I went wrong.
This is my code:
chess = rep(-1, times = 64)
board = matrix(data = chess, nrow = 8, ncol = 8, byrow = TRUE)
move_x = c(2, 1, -1, -2, -2, -1, 1, 2)
move_y = c(1, 2, 2, 1, -1, -2, -2, -1)
board[1, 1] = 0
pos = 1
valid_move <- function (x, y, board) {
if (x >= 1 & y >= 1 & x <= 8 & y <= 8 & board[x, y] == -1) {
return (T)
}
return (F)
}
solve <- function (board, curr_x, curr_y, move_x, move_y, pos) {
if (pos == 64) {
return (T)
}
for (i in seq(1:8)) {
new_x = curr_x + move_x[i]
new_y = curr_y + move_y[i]
if (valid_move(new_x, new_y, board)) {
board[new_x, new_y] = pos
if (solve(board, new_x, new_y, move_x, move_y, pos+1)) {
return (TRUE)
}
board[new_x, new_y] = -1
}
}
}
main <- function() {
sims = 10
ctr = 0
number_of_moves = c()
solve(board, 1, 1, move_x, move_y, pos)
print(paste("Minimum number of moves: ", pos))
}
main()
Thanks!
The problem is that the python code relies on short-circuiting to prevent out-of-bounds errors. & will not short-circuit so you need to use &&.
Here is an example
FALSE && stop()
#> [1] FALSE
FALSE & stop()
#> Error:
Update valid_move to this
valid_move <- function (x, y, board) {
# Changed to && to allow short-circuiting
# if (x >= 1 & y >= 1 & x <= 8 & y <= 8 & board[x, y] == -1) {
if (x >= 1 && y >= 1 && x <= 8 && y <= 8 && board[x, y] == -1) {
return (T)
}
return (F)
}

assign a sector to an angle in R

I have a vector of start and end angels values between 0 and 360.
I would like to have an additional column that specifies in which sector(consider 12 sectors) are my variables.
sectors should be defined as : (15:45], (45,75],(75,105], ..., (345,15]
test = structure(list(start = c(4, 67, 13, 35, 54, 0), end = c(23, 84,
30, 52, 71, 0)), row.names = 2:7, class = "data.frame")
For my test example I thought I have to loop over the number of rows :
for( i in 1:nrow(test)){
if(test$start[i] <= 15 | test$start[i] >345){test$sector_start[i] = 12}
else if(test$start[i] > 15 & test$start[i] <= 45){test$sector_start[i] = 1}
else if(test$start[i] > 45 & test$start[i] <= 75){test$sector_start[i] = 2}
else if(test$start[i] > 75 & test$start[i] <= 105){test$sector_start[i] = 3}
else if(test$start[i] > 105 & test$start[i] <= 135){test$sector_start[i] = 4}
else if(test$start[i] > 135 & test$start[i] <= 165){test$sector_start[i] = 5}
else if(test$start[i] > 165 & test$start[i] <= 195){test$sector_start[i] = 6}
else if(test$start[i] > 195 & test$start[i] <= 225){test$sector_start[i] = 7}
else if(test$start[i] > 225 & test$start[i] <= 255){test$sector_start[i] = 8}
else if(test$start[i] > 255 & test$start[i] <= 285){test$sector_start[i] = 9}
else if(test$start[i] > 285 & test$start[i] <= 315){test$sector_start[i] = 10}
else if(test$start[i] > 315 & test$start[i] <= 345){test$sector_start[i] = 11}
if(test$end[i] <= 15 | test$end[i] >345){test$sector_end[i] = 12}
else if(test$end[i] > 15 & test$end[i] <= 45){test$sector_end[i] = 1}
else if(test$end[i] > 45 & test$end[i] <= 75){test$sector_end[i] = 2}
else if(test$end[i] > 75 & test$end[i] <= 105){test$sector_end[i] = 3}
else if(test$end[i] > 105 & test$end[i] <= 135){test$sector_end[i] = 4}
else if(test$end[i] > 135 & test$end[i] <= 165){test$sector_end[i] = 5}
else if(test$end[i] > 165 & test$end[i] <= 195){test$sector_end[i] = 6}
else if(test$end[i] > 195 & test$end[i] <= 225){test$sector_end[i] = 7}
else if(test$end[i] > 225 & test$end[i] <= 255){test$sector_end[i] = 8}
else if(test$end[i] > 255 & test$end[i] <= 285){test$sector_end[i] = 9}
else if(test$end[i] > 285 & test$end[i] <= 315){test$sector_end[i] = 10}
else if(test$end[i] > 315 & test$end[i] <= 345){test$sector_end[i] = 11}
}
here I could add 2 column to test which is telling me my angles are in which sector. I'm looking for a smarter way of doing this that I could have an option to vary the number of sectors, for example to 24 sectors.
As Roman says, you can use cut. The last step is for angles > 345 or <= 15.
library(dplyr)
test %>%
mutate(sector_start = cut(start, 15 + 30*(0:11), 1:11)
, sector_end = cut(end, 15 + 30*(0:11), 1:11)) %>%
mutate_at(vars(contains('sector')), ~ifelse(is.na(.), 12, .))
In base R:
test[paste0('sector_', names(test))] <-
lapply(test, function(x){
labs <- cut(x, 15 + 30*(0:11), 1:11)
ifelse(is.na(labs), 12, labs)
})

Issues with more than one "&" condition inside if statement in R

I'm doing an IF statement in R to create a variable in R.
I'm having an error that I can't detect to what it refers exactly so I can't fix it. Can somebody help me?
library(install.load)
install_load("checkmate", "expss")
amostra$escol <- NA
educd003 <- data.frame("d003" = 1:9, "codeduc" = c(1,1,3,3,5,5,7,9,9))
educd0091 <- data.frame("d009" = c(1,2,3,4,5,6,7,8,9,10,11,12),
"codeduc" = c(2,2,4,4,4,4,6,6,6,8,10,10))
educd0092 <- data.frame("d009" = c(1,2,3,4,5,6,7,8,9,10,11,12),
"codeduc" = c(1,1,3,3,3,3,5,5,5,7,9,9))
for (i in 1:nrow(amostra)) {
if (is.na(amostra$d001[i]) == TRUE) {
amostra$escol[i] <- 99
} else if (amostra$d001[i] == 2) {
amostra$escol[i] <- 0
} else if (amostra$d002[i] == 1) {
amostra$escol[i] <- vlookup(amostra$d003[i], educd003, result_column = 2, lookup_column = 1)
} else if (amostra$d002[i] == 2 & amostra$d008[i] == 2) {
amostra$escol[i] <- 2
} else if (amostra$d002[i] == 2 & amostra$d008[i] == 1 & amostra$d014[i] == 1) {
amostra$escol[i] <- vlookup(amostra$d009[i], educd0091, result_column = 2, lookup_column = 1)
} else if (amostra$d002[i] == 2 & amostra$d008[i] == 1 & amostra$d014[i] == 2) {
amostra$escol[i] <- vlookup(amostra$d009[i], educd0092, result_column = 2, lookup_column = 1)
} else if (amostra$d002[i] == 2 & amostra$d008[i] == 1 & is.na(amostra$d014[i]) == TRUE) {
amostra$escol[i] <- vlookup(amostra$d009[i], educd0092, result_column = 2, lookup_column = 1)
} else {
amostra$escol[i] <- NA
}
}
Error:
Error in if (amostra$d002[i] == 2 & amostra$d008[i] == 1 & amostra$d014[i] == :
missing value where TRUE/FALSE needed
Thanks,
Wagner
I solved it.
The problem, apparently, was the order.
The code below ran ok:
for (i in 1:nrow(amostra)) {
if (is.na(amostra$d001[i]) == TRUE) {
amostra$escol[i] <- 99
} else if (amostra$d001[i] == 2) {
amostra$escol[i] <- 0
} else if (amostra$d002[i] == 1) {
amostra$escol[i] <- vlookup(amostra$d003[i], educd003, result_column = 2, lookup_column = 1)
} else if (amostra$d002[i] == 2 & amostra$d008[i] == 2) {
amostra$escol[i] <- 2
} else if (amostra$d002[i] == 2 & amostra$d008[i] == 1 & is.na(amostra$d014[i]) == TRUE) {
amostra$escol[i] <- vlookup(amostra$d009[i], educd0092, result_column = 2, lookup_column = 1)
} else if (amostra$d002[i] == 2 & amostra$d008[i] == 1 & amostra$d014[i] == 1) {
amostra$escol[i] <- vlookup(amostra$d009[i], educd0091, result_column = 2, lookup_column = 1)
} else if (amostra$d002[i] == 2 & amostra$d008[i] == 1 & amostra$d014[i] == 2) {
amostra$escol[i] <- vlookup(amostra$d009[i], educd0092, result_column = 2, lookup_column = 1)
} else {
amostra$escol[i] <- NA
}
}
Thank you very much anyway!

Resources