gcal and usage of event['colorId'] give me --> KeyError: 'colorId' - properties

I am trying to collect events from gcal using the boilerplate code from https://developers.google.com/calendar/api/quickstart/python
But when I am using the reference to colorId as per docs
print(start + "," + end + "," + event['summary'] + "," + event['colorId'] + "," + organizer
I am getting the expected output but also
2022-11-14T14:00:00+01:00,2022-11-14T15:00:00+01:0,Meet1 ,5,xxx#yyy.com
2022-11-14T15:00:00+01:00,2022-11-14T15:45:00+01:00,Meet2 ,1,xxx#yyy.com
2022-11-14T15:00:00+01:00,2022-11-14T16:00:00+01:00,Meet3 ,8,xxx#yyy.com
Traceback (most recent call last):
File "/Users/xxx/gcal-coll-py/quickstart.py", line 67, in <module>
main()
File "/Users/xxx/gcal-coll-py/quickstart.py", line 54, in main
color = event['colorId']
KeyError: 'colorId'
Looking at the docs it seem to be the right way of requesting it, but whatever I have tried won't work. Other properties seem to be ok

Related

PDF to txt python3

I'm trying to convert pdf file to txt.
`
import re
import PyPDF2
with open('123.pdf', 'rb') as pdfFileObj:
pdfreader = PyPDF2.PdfFileReader(pdfFileObj)
x = pdfreader.numPages
pageObj = pdfreader.getPage(x + 1)
text = pageObj.extractText()
file1 = open(f"C:\\Users\\honorr\\Desktop\\ssssssss\{re.sub('pdf$','txt',pdfFileObj)}", "a")
file1.writelines(text)
file1.close()
Errors:
Traceback (most recent call last):
File "C:\Users\honorr\Desktop\ssssssss\main.py", line 5, in <module>
pageobj = pdfreader.getPage(x + 1)
File "C:\Users\honorr\Desktop\ssssssss\venv\lib\site-packages\PyPDF2\_reader.py", line 477, in getPage
return self._get_page(pageNumber)
File "C:\Users\honorr\Desktop\ssssssss\venv\lib\site-packages\PyPDF2\_reader.py", line 492, in _get_page
return self.flattened_pages[page_number]
IndexError: list index out of range
`
How to fix it?
So i don't know why i have this errors. Maybe somebody tell me another way to convert from PDF to TXT?
You're setting x to the number of pages, but then trying to get page x + 1, which doesn't exist. Depending on how the library is implemented (I'm not familiar with PyPDF2), you may need to try pdfreader.getPage(x) or pdfreader.getPage(x - 1) to get it to work. This will only get the last page in the document though.

using pandas.read_csv, how can one process all errors, receive all non-error data?

Data which, for me, generates an exception instead of invoking the 'on_bad_lines' handler is at:
https://opencalaccess.org/misc/NAMES_CD.TSV
I have this:
bad_lines = list()
def bad_line_finder(x):
bad_lines.append(str(x))
return None
for file in os.listdir(dir):
bad_lines = list()
try:
for df in pd.read_csv(f"{dir}/{file}",
sep='\t',
on_bad_lines=bad_line_finder,
engine='python',
chunksize=1000):
print(f"\n{target}")
df.info()
print(f"Bad Lines: {bad_lines}")
bad_lines = list()
except:
print("EXCEPTION:")
traceback.print_exc()
and this works great. There are errors in the files and the method handles them so that I can keep track of them. Except, why do i still see this:
EXCEPTION:
Traceback (most recent call last):
File "/home/ray/Projects/opencalaccess-data/import.py", line 41, in <module>
for df in pd.read_csv(f"{dir}/{file}",
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1698, in __next__
return self.get_chunk()
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1810, in get_chunk
return self.read(nrows=size)
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/readers.py", line 1778, in read
) = self._engine.read( # type: ignore[attr-defined]
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/python_parser.py", line 250, in read
content = self._get_lines(rows)
File "/home/ray/Projects/opencalaccess-data/.venv/lib/python3.10/site-packages/pandas/io/parsers/python_parser.py", line 1114, in _get_lines
new_rows.append(next(self.data))
_csv.Error: ' ' expected after '"'
What is the "on_bad_lines" option doing if it does not handle all of the bad lines? Which of them will it handle and which will it not?
This is a government data source. There are format errors in the data that cannot be corrected by the agency, because they constitute the 0fficial record. So, I must fix them myself. But which of them throw exceptions and which do not?

I get this error when i try to use Wolfram Alpha in VS code python ValueError: dictionary update sequence element #0 has length 1; 2 is required

This is my code
import wolframalpha
app_id = '876P8Q-R2PY95YEXY'
client = wolframalpha.Client(app_id)
res = client.query(input('Question: '))
print(next(res.results).text)
the question I tried was 1 + 1
and i run it and then i get this error
Traceback (most recent call last):
File "c:/Users/akshi/Desktop/Xander/Untitled.py", line 9, in <module>
print(next(res.results).text)
File "C:\Users\akshi\AppData\Local\Programs\Python\Python38\lib\site-packages\wolframalpha\__init__.py", line 166, in text
return next(iter(self.subpod)).plaintext
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Please help me
I was getting the same error when I tried to run the same code.
You can refer to "Implementing Wolfram Alpha Search" section of this website for better understanding of how the result was extracted from the dictionary returned.
https://medium.com/#salisuwy/build-an-ai-assistant-with-wolfram-alpha-and-wikipedia-in-python-d9bc8ac838fe
Also, I tried the following code by referring to the above website....hope it might help you :)
import wolframalpha
client = wolframalpha.Client('<your app_id>')
query = str(input('Question: '))
res = client.query(query)
if res['#success']=='true':
pod0=res['pod'][0]['subpod']['plaintext']
print(pod0)
pod1=res['pod'][1]
if (('definition' in pod1['#title'].lower()) or ('result' in pod1['#title'].lower()) or (pod1.get('#primary','false') == 'true')):
result = pod1['subpod']['plaintext']
print(result)
else:
print("No answer returned")

python opencv2, error camera interface, only cam light

This is the code for opencv2 Takeimage button.
It doesn't work properly, only the cam light on, but camera interface doesn't show:
def TakeImage():
Id=(txt.get())
name=(txt2.get())
if(is_number(Id) and name.isalpha()):
Video= cv2.VideoCapture(0)
harcascadePath = "haarcascade_frontalfacedafults_.xml"
detector=cv2.CascadeClassifier(harcascadePath)
sampleNum=0
while(True):
ret,img=Video.read();
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=detector.DetectMultiScale(gray,1.2,5);
for(x,y,w,h) in faces:
cv2.recatangle(img,(x,y),(x+w,y+h),(255,0,0),2)
sampleNum=sampleNum+1
cv2.imwrite("TrainImages\ "+name +"."+Id +'.'+str(samlpeNum)+".jpg",gray[y:y+h,x:x+h])
cv2.imshow('Frame',img)
if cv2.waitKey(100) &0XFF == ord('s'):
break
elif sample>60:
break
Video.release()
cv2.destroyAllWindows()
res = "Images Saved for ID: "+ Id + " Name : "+ name
row = [Id, Name]
with open ('studentDetails\studentDetails.csv','a+') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
csvFile.close()
message.configure(text=res)
else:
if(is_number(Id)):
res ="Enter Alphabetical Name"
message.configure(text= res)
if (name.isalpha()):
res="Enter Numberic Id"
message.configure(text=res)
Error showing:
Exception in Tkinter callback Traceback (most recent call last):
File
"C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py",
line 1705, in call
return self.func(*args) File "C:\Users\Lenovo\Desktop\face reconiger system.py", line 87, in TakeImage
faces=detector.DetectMultiScale(gray,1.2,5); AttributeError: 'cv2.CascadeClassifier' object has no attribute 'DetectMultiScale'
The path to the .xml file looks incorrect. You need to replace the following line:
harcascadePath = "haarcascade_frontalfacedafults_.xml"
with
harcascadePath = cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'

pypyodbc execute returns list index out of range error

I have a function that runs 3 queries and returns the result of the last (using the previous ones to create the last) when I get to the 3rd query, it get a list index our of range error. I have ran this exact query as the first query (with manually entered variables) and it worked fine.
This is my code:
import pypyodbc
def sql_conn():
conn = pypyodbc.connect(r'Driver={SQL Server};'
r'Server=HPSQL31\ni1;'
r'Database=tq_hp_prod;'
r'Trusted_Connection=yes;')
cursor = conn.cursor()
return conn, cursor
def get_number_of_jobs(ticket):
# Get Connection
conn, cursor = sql_conn()
# Get asset number
sqlcommand = "select top 1 item from deltickitem where dticket = {} and cat_code = 'Trq sub'".format(ticket)
cursor.execute(sqlcommand)
asset = cursor.fetchone()[0]
print(asset)
# Get last MPI date
sqlcommand = "select last_test from prevent where item = {} and description like '%mpi'".format(asset)
cursor.execute(sqlcommand)
last_recal = cursor.fetchone()[0]
print(last_recal)
# Get number of jobs since last recalibration
sqlcommand = """select count(i.item)
from deltickhdr as d
join deltickitem as i
on d.dticket = i.dticket
where i.start_rent >= '2017-03-03 00:00:00'
and i.meterstart <> i.meterstop
and i.item = '002600395'""" #.format(last_recal, asset)
cursor.execute(sqlcommand)
num_jobs = cursor.fetchone()[0]
print(num_jobs)
cursor.close()
conn.close()
return num_jobs
ticketnumber = 14195 # int(input("Ticket: "))
get_number_of_jobs(ticketnumber)
Below is the error(s) i get when i get to the 3rd cursor.execute(sqlcommand)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\pydevd.py", line 1596, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\pydevd.py", line 974, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/bdrillin/PycharmProjects/Torque_Turn_Data/tt_sub_ui.py", line 56, in <module>
get_number_of_jobs(ticketnumber)
File "C:/Users/bdrillin/PycharmProjects/Torque_Turn_Data/tt_sub_ui.py", line 45, in get_number_of_jobs
cursor.execute(sqlcommand)
File "C:\ProgramData\Anaconda3\lib\site-packages\pypyodbc.py", line 1470, in execute
self._free_stmt(SQL_CLOSE)
File "C:\ProgramData\Anaconda3\lib\site-packages\pypyodbc.py", line 1994, in _free_stmt
check_success(self, ret)
File "C:\ProgramData\Anaconda3\lib\site-packages\pypyodbc.py", line 1007, in check_success
ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
File "C:\ProgramData\Anaconda3\lib\site-packages\pypyodbc.py", line 972, in ctrl_err
state = err_list[0][0]
IndexError: list index out of range
Any help would be great
I've had the same error.
Even though I haven't come to the definite conclusion about what this error means I thought my guessing might help anyone else ending up here.
In my case, the problem was a conflict with a datatype length (NVARCHAR(24) and CHAR(10)).
So I guess this IndexError in ctrl_err function just means there is an error in your SQL code that pypyodbc does not know how to handle.
I know this is not much of an answer, but I know it would have saved me a couple of hours had I known this was not some bug in pypyodbc but an inconsistency in the data I was inserting.
Kind regards,
Luka