I keep getting a expected then error when I have the the in the string - computercraft

I keep getting the then expected error on line 61 and I cant find the problem any ideas?
I tried working it out and rearranging it im using computer craft periherals mag card reader and trying to mag a card door
os.loadAPI("SHA")
os.pullEvent = os.pullEventRaw
redstone.setBundledOutput("left",colors.white)
math.randomseed(os.time())
term.clear()
term.setCursorPos(1,1)
print("DKM.inc Doors")
print("thank you")
modem = peripheral.wrap("top")
if moden == nil then
error("Modem not on top")
end
if moden.isPresentRemote("mag card reader_0") then
reader = peripheral.wrap("mag card reader_0")
print("Card reader connected")
else
error("Mag-card reader not found")
end
if modem.isPresentRemote("monitor_0") then
monitor = peripheral.wrap("monitor_0")
print("monitor connected")
else
error("monitor not found")
end
hashedPw = "0706490"
cardsFilePath = "cards"
cards = {""}
chars = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
newpass = ""
cardNum = 0
if fs.exists(cardsFilePath) then
cardsFile = fs.open(cardsFilePath, "r")
cards = textutils.unserialize(cardsFile.readAll())
cardsFile.close()
end
while true do
admin = false
monitor.clear()
monitor.setCursorPos(1,1)
monitor.write("Please insert card")
reader.setInsertCardLight(true)
event, p1,p2,p3 = os.pullEvent()
if event == " mag_swipe" then
if SHA.SHA1_2(p1) == hashePw then
admin = true
end
for x = 1, #cards do
if SHA,SHA1_2(p1) == cards[x] then --line 61 is right here
reader.setInsertCardLight(false)
redstone.setBundledOutput("left", 0)
os.sleep(3)
redstone.setBundledOutput("left", colors.white)
reader.setInsertCardLight(true)
break
end
end
end
if admin == true then
reader.setInsertCardLight(false)
monitor.clear()
monitor.setCursorPos(1,1)
monitor.write("Admin granted insert blank card")
for z = 1,15 do
case math.random(1,2)
a = math.random(1,#chars)
if case == 1 then
x=string.upper(chars[a])
elseif case == 2 then
x=string.lower(chars[a])
end
newpass = newpass..x
end
reader.setInsertCardLight(true)
cardNum = #cards
print(reader.beginWrite(newpass, cardNum..""))
table.insert(cards, SHA,SHA1_2(newpass))
while reader.isWaiting() do
end
reader.setInsertCardLight(false)
monitor.clear()
monitor.setCursorPos(1,1)
monitor.write("new card created")
newpass = ""
end
os.sleep(1)
cardsFile = fs.open(cardsFilePath, "w")
cardsFile.write(textutils.serialize(cards))
cardsFile.close()
end

You miss spelled "modem" with moden on 2 lines.
if moden == nil then
and also..
if moden.isPresentRemote("mag card reader_0") then
As for the error.
if SHA,SHA1_2(p1) == cards[x] then --line 61 is right here
i believe.. should be this..
if SHA.SHA1_2(p1) == cards[x] then --line 61 is right here
swapping the , for a . should do the trick.

Related

Error inserting an email string in sqlite3 and python Tkinter

I am writing a simple program to update a basic db based on data entered on a simple GUI. I'm using string formatting but keep getting an error trying to enter an email address , which I know should be surrounded with double-quotes. I'm sure the solution is simple- I just don't know what it is!
def update_rec():
# Connect to the db
conn = sqlite3.connect("address_book.db")
# create a cursor
c = conn.cursor()
fields = ["f_name", "s_name", "mob", "email"]
# Check which textboxes have data
update_txt = ""
update_field = ""
rec_no = str(id_no.get())
if len(f_name.get()) > 0:
update_txt = f_name.get()
update_field = fields[0]
elif len(s_name.get()) > 0:
update_txt = s_name.get()
update_field = fields[1]
elif len(mob.get()) > 0:
update_txt = mob.get()
update_field = fields[2]
elif len(email.get()) > 0:
update_txt = email.get()
update_field = fields[3]
else:
update_txt = ""
update_field = ""
c.execute("""UPDATE address_book SET {0} = ? WHERE {1} = ?""".format(update_field, update_txt), rec_no)
conn.commit()
conn.close()
I keep getting this error:
c.execute("""UPDATE address_book SET {0} = ? WHERE {1} = ?""".format(update_field, update_txt), rec_no)
sqlite3.OperationalError: near "#gmail": syntax error
What needs to be supplied to .format() is getting confused with what needs to be passed to c.execute().
Do it in two steps so it's easier to understand.
You need to tell us what rec_field should be. It's probably something like id or address_book_id or ?
rec_field = 'id' # you know what this should be...
qry = """UPDATE address_book
SET {0} = ?
WHERE {1} = ?;""".format(update_field, rec_field)
c.execute(qry, (update_txt,rec_no))

Roku (Brightscript) - Playing DRM Protected Video Content

These is a self answering question.
Problem:
Can not play videos which are protected by PlayReady DRM.
Here is the working sample
if m.VideoPlayer = invalid
m.VideoPlayer = m.top.createChild("Video")
m.VideoPlayer.id = "VideoPlayer"
m.VideoPlayer.observeField("state", "OnVideoStateChange")
end if
drmParams = {}
videoContent = createObject("RoSGNode", "ContentNode")
videoContent.Live = remoteContent.IsLive
videoContent.Url = remoteContent.Path
if remoteContent.CodecType = "DashWideVineDrm" then
videoContent.StreamFormat = "dash"
drmparams.licenseServerURL = remoteContent.DrmRightsUrl
drmParams.KeySystem = "widevine"
else if remoteContent.CodecType = "PlayReadyDrm" then
videoContent.StreamFormat = "ism"
drmParams.KeySystem = "playready"
drmParams.encodingType = "PlayReadyLicenseAcquisitionUrl"
drmParams.encodingKey = remoteContent.DrmRightsUrl
else
videoContent.StreamFormat = "mp4"
end if
videoContent.drmParams = drmParams
device = CreateObject("roDeviceInfo")
httpAgent = CreateObject("roHttpAgent")
if httpAgent <> invalid then
httpAgent.SetCertificatesFile("common:/certs/ca-bundle.crt")
httpAgent.InitClientCertificates()
httpAgent.EnableCookies()
httpAgent.AddHeader("X-Roku-Reserved-Dev-Id", "")
if remoteContent.MYCUSTOMHEADER1 <> invalid and remoteContent.MYCUSTOMHEADER1 <> "" then
httpAgent.AddHeader("MY-CUSTOM-HEADER2", remoteContent.MYCUSTOMHEADER1)
end if
if remoteContent.MYCUSTOMHEADER2 <> invalid and remoteContent.MYCUSTOMHEADER2 <> "" then
httpAgent.AddHeader("MY-CUSTOM-HEADER2", remoteContent.MYCUSTOMHEADER2)
end if
m.VideoPlayer.setHttpAgent(httpAgent)
else
headers = []
headers.push("X-Roku-Reserved-Dev-Id:")
if remoteContent.MYCUSTOMHEADER1 <> invalid and remoteContent.MYCUSTOMHEADER1 <> "" then headers.push("MY-CUSTOM-HEADER1:" + remoteContent.MYCUSTOMHEADER1)
if remoteContent.MYCUSTOMHEADER2 <> invalid and remoteContent.MYCUSTOMHEADER2 <> "" then headers.push("MY-CUSTOM-HEADER2:" + remoteContent.MYCUSTOMHEADER2)
videoContent.HttpHeaders = headers
videoContent.HttpSendClientCertificates = true
videoContent.HttpCertificatesFile = "common:/certs/ca-bundle.crt"
m.VideoPlayer.EnableCookies()
m.VideoPlayer.SetCertificatesFile("common:/certs/ca-bundle.crt")
m.VideoPlayer.InitClientCertificates()
end if
m.VideoPlayer.content = videoContent
m.VideoPlayer.control = "play"
NOTE:
If you use PlayReady DO NOT FILL drmParams.licenseServerURL, because it will fail to play with DRM Error (-6).

Syntax Error I Can't Understand [Python 3]

Here's my code:
cont = "y"
cont1 = "0"
cont2 = "yes"
log = 0
data = open("songs.txt", "r")
songs = data.readlines()
songs.sort()
while cont1 == "0":
cont = input("Do you want to make a playlist? [Y or N]") #Need to change to change cont1 if a playlist is not wanted to be created
if cont == "y":
new = "playlist" + str(log) + ".txt"
print(new, "Please remember the number. Thanks")
log = log + 1
else:
break
while cont == "y":
print ("1. ", songs[0],"2. ", songs[1],"3. ", songs[2],"4. ", songs[3],"5. ", songs[4],"6. ", songs[5],"7. ", songs[6],"8. ", songs[7],"9. ", songs[8],"10. ", songs[9],"11. ", songs[10],"12. ", songs[11],"13. ", songs[12],"14. ", songs[13],"15. ", songs[14],"16. ", songs[15],"17. ", songs[16],"18. ", songs[17],"19. ", songs[18],"20. ", songs[19])
choice = int(input("Please enter the first choice of song you would like in your playlist [Type the allocated number please]"))
choice1 = choice - 1
with open("playlist" + str(log) + ".txt", "a") as playlist:
playlist.write(str(songs[choice1]))
cont = input("Do you want to add another song? [Y or N]")
if cont == "n":
break
view = input("Which playlist would you like to view? Please enter the number
you were given before.")
with open("playlist" + str(view) + ".txt", "a") as see:
print(see)
The function of my code is a playlist generator for the user using the songs I already have. That all works up to now, but when trying to allow the user to view the playlist of their choice in this section of the code:
view = input("Which playlist would you like to view? Please enter the number
you were given before.")
with open("playlist" + str(view) + ".txt", "a") as see:
print(see)
I got an error message saying:
<_io.TextIOWrapper name='playlist2.txt' mode='a' encoding='UTF-8'>
Does this make sense to anyone?
Thanks!
By the way, the songs.txt contains a list of 20 songs in it. Cheers!
I think there might be a couple things here. playlist2.txt is not opened in a readable mode, so open needs r instead of a. see is a file object, so print needs see.read() to print the file contents.

Unknown column added in user input form

I have a simple data entry form that writes the inputs to a csv file. Everything seems to be working ok, except that there are extra columns being added to the file in the process somewhere, seems to be during the user input phase. Here is the code:
import pandas as pd
#adds all spreadsheets into one list
Batteries= ["MAT0001.csv","MAT0002.csv", "MAT0003.csv", "MAT0004.csv",
"MAT0005.csv", "MAT0006.csv", "MAT0007.csv", "MAT0008.csv"]
#User selects battery to log
choice = (int(input("Which battery? (1-8):")))
def choosebattery(c):
done = False
while not done:
if(c in range(1,9)):
return Batteries[c]
done = True
else:
print('Sorry, selection must be between 1-8')
cfile = choosebattery(choice)
cbat = pd.read_csv(cfile)
#Collect Cycle input
print ("Enter Current Cycle")
response = None
while response not in {"Y", "N", "y", "n"}:
response = input("Please enter Y or N: ")
cy = response
#Charger input
print ("Enter Current Charger")
response = None
while response not in {"SC-G", "QS", "Bosca", "off", "other"}:
response = input("Please enter one: 'SC-G', 'QS', 'Bosca', 'off', 'other'")
if response == "other":
explain = input("Please explain")
ch = response + ":" + explain
else:
ch = response
#Location
print ("Enter Current Location")
response = None
while response not in {"Rack 1", "Rack 2", "Rack 3", "Rack 4", "EV001", "EV002", "EV003", "EV004", "Floor", "other"}:
response = input("Please enter one: 'Rack 1 - 4', 'EV001 - 004', 'Floor' or 'other'")
if response == "other":
explain = input("Please explain")
lo = response + ":" + explain
else:
lo = response
#Voltage
done = False
while not done:
choice = (float(input("Enter Current Voltage:")))
modchoice = choice * 10
if(modchoice in range(500,700)):
vo = choice
done = True
else:
print('Sorry, selection must be between 50 and 70')
#add inputs to current battery dataframe
log = pd.DataFrame([[cy,ch,lo,vo]],columns=["Cycle", "Charger", "Location", "Voltage"])
clog = pd.concat([cbat,log], axis=0)
clog.to_csv(cfile, index = False)
pd.read_csv(cfile)
And I receive:
Out[18]:
Charger Cycle Location Unnamed: 0 Voltage
0 off n Floor NaN 50.0
Where is the "Unnamed" column coming from?
There's an 'unnamed' column coming from your csv. The reason most likely is that the lines in your input csv files end with a comma (i.e. your separator), so pandas interprets that as an additional (nameless) column. If that's the case, check whether your lines end with your separator. For example, if your files are separated by commas:
Column1,Column2,Column3,
val_11, val12, val12,
...
Into:
Column1,Column2,Column3
val_11, val12, val12
...
Alternatively, try specifying the index column explicitly as in this answer. I believe some of the confusion stems from pandas concat reordering your columns .

Load Excel File To Powerbuilder

I have this code for buttonclicked event to load excel and text file to powerbuilder and the excel data is not copied i.e ll_return_xls <= 0 and thus when i want to load it to db i will get error since it has no value or data in it...The problem here is i get the data from text file but not from the excel file...Any help will be appreciated
long ll_return
long ll_return_xls
OLEObject excel
IF rb_file.checked then
IF dwo.Name = "b_browse_meters" THEN // Browse Button Clicked for Text
ll_return = GetFileOpenName ( "Select Meter File", is_fullname, is_filename, "TXT", &
"Text Files (*.txt), *.txt" )
if ll_return < 1 then
gnv_msg.f_mensaje("EX28", "", "", OK!)
return
end if
END IF // Browse Button Clicked
END IF
IF dwo.Name ="b_browse_meters_xls" THEN // Browse Button Clicked for Excel
ll_return_xls = GetFileOpenName ( "Select Meter File", is_fullname, is_filename, "XLS", &
"Excel Files (*.xls), *.xls" )
if ll_return_xls < 1 then
gnv_msg.f_mensaje("EX28", "", "", OK!)
return
end if
excel = create oleobject
excel.ConnectToNewObject( "excel.application" )
excel.visible = false
excel.workbooks.open( is_fullname)
excel.Range("A1:A2").Select
excel.ActiveCell.CurrentRegion.Select()
ClipBoard('')
excel.Selection.Copy()
ClipBoard('')
excel.ActiveWorkbook.Close
excel.Disconnectobject()
Destroy excel
END IF // Browse Button Clicked
And Function to load it the text and excel data
long ll_return, ll_arr_len, ll_loop, ll_indx, ll_pass = 0
integer li_rc, li_file_nbr, li_fr_rc //File Read Return Code
string ls_file, ls_line, ls_msg
string lsa_meters[], lsa_meter_pass[]
string ls_meters
long ll_total_valid, ll_total_aparatos
SetPointer(HourGlass!)
if IsValid(w_progbar) then Close(w_progbar)
openwithparm(w_progbar,"Uploading file data ...")
w_progbar.uo_progress_bar.set_position(10)
li_rc = SUCCESS
ll_total_aparatos = 0
ll_total_valid = 0
// Open file
if li_rc = SUCCESS then
ls_file = is_fullname
li_file_nbr = FileOpen(ls_file, LineMode!)
if IsNull(li_file_nbr) or li_file_nbr < 1 then
li_rc = NO_ACTION
end if
end if
// Read file, store serial numbers into array lsa_meters[]
if li_rc = SUCCESS then // File Opened
ll_indx = 0
do while ll_indx > -1 and li_rc = SUCCESS
li_fr_rc = FileRead(li_file_nbr, ls_line)
choose case li_fr_rc
case is > 0
ll_indx ++
lsa_meters[ll_indx] = ls_line
case 0, -100
ll_indx = -1
case -1
li_rc = FAILURE
gnv_msg.f_mensaje("EX21", "", "", OK!)
end choose
loop
if li_rc = SUCCESS then // File Read OK
ll_arr_len = UpperBound(lsa_meters)
if ll_arr_len > 0 then // Data found in file
for ll_loop = 1 to ll_arr_len step 1
if ib_meter then
ll_return = wf_luhn_check(lsa_meters[ll_loop])
ll_total_valid ++
else
if Len(lsa_meters[ll_loop]) >= 9 then
ll_return = 1
ll_total_valid ++
else
ll_return = -1
end if
end if
if ll_return = 1 then
if wf_aparatos_check(lsa_meters[ll_loop]) <= 0 then
ll_return = 1
else
ll_return = -1
ll_total_aparatos ++
end if
end if
if ll_return = 1 then
ll_pass++
lsa_meter_pass[ll_pass] = lsa_meters[ll_loop]
ls_meters = ls_meters + lsa_meters[ll_loop] + isk_TAB_PB
end if
w_progbar.uo_progress_bar.set_position(50 + ((ll_loop / ll_arr_len) * 40))
next
ll_arr_len = UpperBound(lsa_meter_pass)
if ll_arr_len > 0 then
dw_datos_ingreso.Object.num_ini[1] = lsa_meter_pass[1]
dw_datos_ingreso.Object.num_fin[1] = lsa_meter_pass[ll_arr_len]
is_meters_passed = ls_meters // Concatenated string of meter serial no.
il_apa_filemeters_count = ll_arr_len // Number of meters
else
li_rc = FAILURE
if ib_meter then
gnv_msg.f_mensaje("EX27", "", "", OK!)
else
gnv_msg.f_mensaje("EX22", "", "", OK!)
end if
if ll_total_valid = ll_total_aparatos then
gnv_msg.f_mensaje("EX23", "", "", OK!)
end if
end if
else
li_rc = FAILURE
gnv_msg.f_mensaje("EX24", "", "", OK!)
end if // Data found in file
end if // File Read OK
end if // File Opened
w_progbar.uo_progress_bar.set_position(100)
Close(w_progbar)
//Clean up
if li_file_nbr > 0 then
if FileClose(li_file_nbr) = FAILURE then
li_rc = FAILURE
gnv_msg.f_mensaje("EX25", "", "", OK!)
end if
end if
if ll_total_aparatos > 0 then
gnv_msg.f_mensaje("EW140", String(ll_total_aparatos) , "", OK!)
end if
if li_rc = FAILURE then
gnv_msg.f_mensaje("EX26", "", "", OK!)
RETURN FALSE
end if
RETURN TRUE
You can use the ODBC driver directly to the Excel file, and then build a Pipeline object that moves the data from the spreadsheet directly into the database. Don't write code you don't need to.

Resources