KPLR: JSONDecodeError: Expecting value: line 1 column 1 (char 0) - python

I am trying to follow the KPLR tutorial run in Google Colab the last code snippet on the page:
import kplr
client = kplr.API()
# Find the target KOI.
koi = client.koi(952.01)
# Get a list of light curve datasets.
lcs = koi.get_light_curves(short_cadence=False, fetch=True, clobber=True)
# Loop over the datasets and read in the data.
time, flux, ferr, quality = [], [], [], []
for lc in lcs:
with lc.open() as f:
# The lightcurve data are in the first FITS HDU.
hdu_data = f[1].data
time.append(hdu_data["time"])
flux.append(hdu_data["sap_flux"])
ferr.append(hdu_data["sap_flux_err"])
quality.append(hdu_data["sap_quality"])
When I run this though, I receive the following error:
JSONDecodeError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/kplr/api.py in mast_request(self, category, adapter, sort, mission, **params)
197 try:
--> 198 result = json.loads(txt)
199 except ValueError:
7 frames
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
APIError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/kplr/api.py in mast_request(self, category, adapter, sort, mission, **params)
200 full_url = handler.geturl() + "?" + urllib.parse.urlencode(params)
201 raise APIError(code, full_url,
--> 202 "No JSON object could be decoded.\n" + txt)
203
204 # Fake munge the types if no adapter was provided.
Any suggestions?

Related

Python and Pandas KeyError 3 and a refusal to call the function

I am getting KeyError: 3 and a refusal to call the main funciton when trying to use Panda library to import value from excel and use them to send emails according to format importing from an excel file, the code used to work even with KeyError: 3 before I input the file attachment code in. Now the code just refused to work entirely and I even with extensive search I can't pinpoint what is wrong.
The code is a bit messy but please bear with me.
Any help would be appreciate.
from win32com.client import Dispatch
import win32com
import pandas as pd
import win32api
import sys
path = "C:/XXXXX/XXXXX/XXXXX/XXXXX.xlsx"
def mailprepare():
num = range(0, 999)
for k in num:
outlook = win32com.client.Dispatch("Outlook.Application")
for accoun in outlook.Session.Accounts:
if accoun.SmtpAddress == 'XXXXX#XXXXX.com':
newaccount = accoun
break
mail = outlook.CreateItem(0)
mail._oleobj_.Invoke(*(64209, 0, 8, 0, newaccount))
data = pd.ExcelFile(path)
sheet = data.parse('Sheet1')
if (sheet['Send'][k] == 0):
continue
position = sheet['Position'][k]
client = sheet['ClientName'][k]
mailto = sheet['Mails'][k]
company = sheet['Company'][k]
subject = (sheet.iat[0,5])
body = (sheet.iat[0,6])
signature = (sheet.iat[0,7])
mail.To = mailto
mail.Subject = f'{subject}'
mail.Body = f'{company}/n'/
f'{position}/n'/
f'{client}/n'/
f'/n'/
f'{body}/n'/
f'/n'/
f'{signature}'/
if (sheet.iat[0,9]== 1):
filepath = (sheet.iat[0,8])
add_file1 = "C:/XXXXX/XXXXX/XXXXXX/XXXXX.xlsx"
mail.attachments.Add(add_file1)
mail.send
mailprepare()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\range.py:385, in RangeIndex.get_loc(self, key, method, tolerance)
--> 385 return self._range.index(new_key)
ValueError: 3 is not in range
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Input In [1], in <cell line: 49>()
---> 49 mailprepare()
Input In [1], in mailprepare()
---> 23 if (sheet['Send'][k] == 0):
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py:958, in Series.__getitem__(self, key)
--> 958 return self._get_value(key)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\series.py:1069, in Series._get_value(self, label, takeable)
-> 1069 loc = self.index.get_loc(label)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\range.py:387, in RangeIndex.get_loc(self, key, method, tolerance)
--> 387 raise KeyError(key) from err
KeyError: 3

KeyError Traceback (most recent call last)

**from geopy.geocoders import Here
exif = get_exif('earth_postcard_1599147372.jpg')
geotags = get_geotagging(exif)
coords = get_coordinates(geotags)
geocoder = Here(apikey=os.environ['API_KEY'])
print(geocoder.reverse("%s,%s" % coords))**
ERROR
KeyError Traceback (most recent call last)
<ipython-input-13-baa26ae24e59> in <module>
4 geotags = get_geotagging(exif)
5 coords = get_coordinates(geotags)
----> 6 geocoder = Here(apikey=os.environ['API_KEY'])
7 print(geocoder.reverse("%s,%s" % coords))
~\anaconda3\lib\os.py in __getitem__(self, key)
677 except KeyError:
678 # raise KeyError with the original key value
--> 679 raise KeyError(key) from None
680 return self.decodevalue(value)
681
KeyError: 'API_KEY'
Here i try to get the location of using latitude and logitude using geopy library but im getting key error
You should check whether you have set your environment parameter.You can enter into python command line mode then input :
import os
os.environ.keys()
System will output all the environment parameter."API_KEY" should not be set. If you set this key in system parameter list,this error will be gone.

YQLResponseMalformedError: Response malformed on yahoo_finance?

yahoo_finance's get_historical function has been working fine for me until yesterday.
Now it just keeps giving me YQLResponseMalformedError every time I try to call get_historical. Any ideas? I literally did nothing new with the code.
from yahoo_finance import Share
yahoo = Share('YHOO')
yahoo.refresh()
yahoo.get_historical('2014-04-26', '2014-04-29')
---------------------------------------------------------------------------
YQLResponseMalformedError Traceback (most recent call last)
<ipython-input-8-fbc20f9b6d26> in <module>()
----> 1 yahoo.get_historical('2014-04-26', '2014-04-29')
/Users/anjian/anaconda/lib/python2.7/site-packages/yahoo_finance-1.4.0-py2.7.egg/yahoo_finance/__init__.pyc in get_historical(self, start_date, end_date)
340 try:
341 query = self._prepare_query(table='historicaldata', startDate=s, endDate=e)
--> 342 result = self._request(query)
343 if isinstance(result, dict):
344 result = [result]
/Users/anjian/anaconda/lib/python2.7/site-packages/yahoo_finance-1.4.0-py2.7.egg/yahoo_finance/__init__.pyc in _request(self, query)
123 raise YQLQueryError(response['error']['description'])
124 except KeyError:
--> 125 raise YQLResponseMalformedError()
126 else:
127 if self._is_error_in_results(results):
YQLResponseMalformedError: Response malformed.
Answered here: Python and Yahoo finance weird "YQLQueryError(response['error']['description'])" get_historical

Python not catching TypeError exception with regex

I'm not sure how to handle this exception anymore. This is the problematic codeblock. csre and csre_err are compiled regex patterns. I am trying to catch the exception twice, but neither one actually catches the exception. I am trying to at least find an example of the problematic item["notes"], as far as I know they are all strings, but I can't catch it.
try:
mongoj[id_]["notes"] = item["notes"]
try:
if csre.search(item['notes']) is not None:
if csre_err.search(item['notes']) is not None:
pass
else:
mongoj[id_]["container"] = csre.search(item['notes']).group(0)
except TypeError:
print item['notes']
except (KeyError,TypeError):
mongoj[id_]["notes"] = None
I am still getting the following error:
TypeError Traceback (most recent call last)
<ipython-input-97-09b4e442a24e> in <module>()
281 mongoj[id_]["notes"] = item["notes"]
282 try:
--> 283 if csre.search(item['notes']) is not None:
284 if csre_err.search(item['notes']) is not None:
285 pass
TypeError: expected string or buffer

What is the exception for this error: httperror_seek_wrapper: HTTP Error 404: Not Found?

I would like to handle the error:
"httperror_seek_wrapper: HTTP Error 404: Not Found"
And instead just return an empty string. But I'm not sure what the except statement should be. I apologize if there is a duplicate post, but none of the posts that popped up seemed to deal with excepting this error, but rather figuring out what had gone wrong at a deeper level. I, however, just want to pass along and return an empty string.
Basically, I'm looking for what should go in the blank:
try:
....
except _____:
....
Thanks!
_____
Here is the code where the error gets thrown.
---------------------------------------------------------------------------
httperror_seek_wrapper Traceback (most recent call last)
<ipython-input-181-e2b68bf19ff9> in <module>()
5
6 for i in range(len(first)):
----> 7 student_html = get_stud_html(first[i],last[i],'Sophomore')
8 # print type(student_html)
9 # print parse_hfb_page(student_html)
<ipython-input-177-9b1d4294820d> in get_stud_html(first, last, year)
60 #ideally will want to use a regex to do this in case there's more than one link on the page
61 stud_url = 'http://facebook.college.harvard.edu/'+links_lst[12]
---> 62 stud_html = br.open(stud_url)
63 return stud_html.get_data()
64
//anaconda/python.app/Contents/lib/python2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_mechanize.pyc in open(self, url, data, timeout)
201 def open(self, url, data=None,
202 timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT):
--> 203 return self._mech_open(url, data, timeout=timeout)
204
205 def _mech_open(self, url, data=None, update_history=True, visit=None,
//anaconda/python.app/Contents/lib/python2.7/site-packages/mechanize-0.2.5-py2.7.egg/mechanize/_mechanize.pyc in _mech_open(self, url, data, update_history, visit, timeout)
253
254 if not success:
--> 255 raise response
256 return response
257
httperror_seek_wrapper: HTTP Error 404: Not Found
That is a urllib2.HTTPError exception.
from urllib2 import HTTPError
try:
# ...
except HTTPError:
# ...
You can see this in the source of _mechanize.py, where that same exception is caught and assigned to response to be re-raised later.

Categories