Catching HTTPerror in python3 from stravalib function - python

My code (for the relevant part) is as follows
myactivities = []
from urllib.error import HTTPError
for activity in client.get_activities(after = activities_from, before=activities_to):
print(activity)
print(activity.id, activity.start_date)
try:
temp = client.get_activity_streams(activity.id, types=types)
except urllib.error.HTTPError:
print("HTTPError")
myactivities.append(temp)
The error print I get is this:
HTTPError Traceback (most recent call last)
<ipython-input-29-fc30cef1e4f3> in <module>()
8 try:
----> 9 temp = client.get_activity_streams(activity.id, types=types)
10 except urllib.error.HTTPError:
C:\Users\Koti\Anaconda3\lib\site-packages\stravalib\client.py in get_activity_streams(self, activity_id, types, resolution, series_type)
1174 # Pack streams into dictionary
-> 1175 return {i.type: i for i in streams}
1176
C:\Users\Koti\Anaconda3\lib\site-packages\stravalib\client.py in <dictcomp>(.0)
1174 # Pack streams into dictionary
-> 1175 return {i.type: i for i in streams}
1176
C:\Users\Koti\Anaconda3\lib\site-packages\stravalib\client.py in __next__(self)
1529 def __next__(self):
-> 1530 return self.next()
1531
C:\Users\Koti\Anaconda3\lib\site-packages\stravalib\client.py in next(self)
1535 if not self._buffer:
-> 1536 self._fill_buffer()
1537 try:
C:\Users\Koti\Anaconda3\lib\site-packages\stravalib\client.py in _fill_buffer(self)
1506
-> 1507 raw_results = self.result_fetcher(page=self._page, per_page=self.per_page)
1508
C:\Users\Koti\Anaconda3\lib\site-packages\stravalib\protocol.py in get(self, url, check_for_errors, use_webhook_server, **kwargs)
245 params = dict([(k, v) for k, v in kwargs.items() if not k in referenced])
--> 246 return self._request(url, params=params, check_for_errors=check_for_errors, use_webhook_server=use_webhook_server)
247
C:\Users\Koti\Anaconda3\lib\site-packages\stravalib\protocol.py in _request(self, url, params, files, method, check_for_errors, use_webhook_server)
169 if check_for_errors:
--> 170 self._handle_protocol_error(raw)
171
C:\Users\Koti\Anaconda3\lib\site-packages\stravalib\protocol.py in _handle_protocol_error(self, response)
214 if x is not None:
--> 215 raise x
216
HTTPError: 404 Client Error: Not Found [Record Not Found: []]
During handling of the above exception, another exception occurred:
NameError Traceback (most recent call last)
<ipython-input-29-fc30cef1e4f3> in <module>()
8 try:
9 temp = client.get_activity_streams(activity.id, types=types)
---> 10 except urllib.error.HTTPError:
11 print("HTTPError")
12 myactivities.append(temp)
NameError: name 'urllib' is not defined
How can I catch that HTTPError succesfully? I tried all the suggestions in catch specific HTTP error in python but none helped.

Try
myactivities = []
from urllib.error import HTTPError
for activity in client.get_activities(after = activities_from, before=activities_to):
print(activity)
print(activity.id, activity.start_date)
try:
temp = client.get_activity_streams(activity.id, types=types)
except HTTPError:
print("HTTPError")
myactivities.append(temp)
You already imported HTTPError, you have to use directly.
Your code shows error.
NameError Traceback (most recent call last)
<ipython-input-29-fc30cef1e4f3> in <module>()
8 try:
9 temp = client.get_activity_streams(activity.id, types=types)
---> 10 except urllib.error.HTTPError:
11 print("HTTPError")
12 myactivities.append(temp)
NameError: name 'urllib' is not defined
Which gives error because urllib is not accessible. You imported HTTPError from that.

Related

Out of sample forecasting

I have the following code to perform an out-of-sample assessment of a time series. The idea is to perform a recursive and rolling method to calculate MAPE and MSPE.
The code is as follows:
long = len(y)
n_estimation = 83
real = y[(n_estimation):len(y)]
n_forecasting = long - n_estimation
horizontes = 2
predicc = np.zeros((horizontes,n_forecasting))
MSFE = np.zeros((horizontes, 1))
MAPE = np.zeros((horizontes, 1))
for Periods_ahead in range(horizontes):
for i in range(0,n_forecasting):
aux_y = y[0:(n_estimation - Periods_ahead + i)]
model = SARIMAX(endog = aux_y, order = (1,1,0), seasonal_order = (1,1,0,4))
model_fit=model.fit(disp=0)
y_pred = fit.forecast(Periods_ahead + 1)
predicc[Periods_ahead][i] = y_pred[0][Periods_ahead]
error = np.array(real) - predicc[Periods_ahead]
MSFE[Periods_ahead] = np.mean(error**2)
MAPE[Periods_ahead] = np.mean(np.abs(error/np.array(real))) * 100
df_pred = pd.DataFrame({"V1":predicc[0], "V2":predicc[1]})
print("MSFE",MSFE)
print("MAPE %",MAPE)
I am getting the following error, most likely related to using a newer version of SARIMAX.
ValueError Traceback (most recent call last)
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexes\range.py:392, in RangeIndex.get_loc(self, key, method, tolerance)
391 try:
--> 392 return self._range.index(new_key)
393 except ValueError as err:
ValueError: 0 is not in range
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
c:\Users\dianaf\OneDrive - Microsoft\Documents\GitHub\big_data_operations\Homework2.ipynb Cell 36 in <cell line: 13>()
17 model_fit=model.fit(disp=0)
18 y_pred = fit.forecast(Periods_ahead + 1)
---> 19 predicc[Periods_ahead][i] = y_pred[0][Periods_ahead]
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\series.py:982, in Series.__getitem__(self, key)
979 return self._values[key]
981 elif key_is_scalar:
--> 982 return self._get_value(key)
984 if is_hashable(key):
985 # Otherwise index.get_value will raise InvalidIndexError
986 try:
987 # For labels that don't resolve as scalars like tuples and frozensets
...
--> 394 raise KeyError(key) from err
395 self._check_indexing_error(key)
396 raise KeyError(key)
KeyError: 0
Any idea how to fix it without downgrading to previous versions of statsmodel?
Thank you!

Issues with loading .s2p file in python notebook using scikit-rf

Hi i am having issues with loading the .s2p file
when i ran the following code
import skrf as rf
from skrf import Network, Frequency
data1 = rf.Network('/Users/pradeeps/Desktop/Project/meas2018_07_06/300MHzNLOSX1DPS.s2p')
It showed the following error as shown below
---------------------------------------------------------------------------
UnpicklingError Traceback (most recent call last)
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/network.py:450, in Network.__init__(self, file, name, params, comments, f_unit, s_def, **kwargs)
449 try:
--> 450 self.read(fid)
451 except UnicodeDecodeError: # Support for pickles created in Python2 and loaded in Python3
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/network.py:2357, in Network.read(self, *args, **kwargs)
2356 from .io.general import read
-> 2357 self.copy_from(read(*args, **kwargs))
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/io/general.py:140, in read(file, *args, **kwargs)
139 try:
--> 140 obj = pickle.load(fid, *args, **kwargs)
141 except (UnpicklingError, UnicodeDecodeError) as e:
142 # if fid is seekable then reset to beginning of file
UnpicklingError: invalid load key, '3'.
During handling of the above exception, another exception occurred:
NotImplementedError Traceback (most recent call last)
Untitled-1.ipynb Cell 2' in <cell line: 1>()
----> 1 data1 = rf.Network('/Users/pradeeps/Desktop/Project/meas2018_07_06/300MHzNLOSX1DPS.s2p')
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/network.py:458, in Network.__init__(self, file, name, params, comments, f_unit, s_def, **kwargs)
456 filename = fid.name
457 fid.close()
--> 458 self.read_touchstone(filename, self.encoding)
460 if name is None and isinstance(file, str):
461 name = os.path.splitext(os.path.basename(file))[0]
File ~/Desktop/Project/project/lib/python3.10/site-packages/skrf/network.py:1956, in Network.read_touchstone(self, filename, encoding)
1953 touchstoneFile = touchstone.Touchstone(filename, encoding=encoding)
1955 if touchstoneFile.get_format().split()[1] != 's':
-> 1956 raise NotImplementedError('only s-parameters supported for now.')
1958 self.comments = touchstoneFile.get_comments()
1960 try:
NotImplementedError: only s-parameters supported for now.
As shown in this particular code i used scikit-rf is there any other package that i should use in this particular instance or am i doing anything wrong.
Thank you

AttributeError: module 'tensorflow' has no attribute 'op'

I try to run this peace of code on Colab:
BATCH_SIZE = 256
train_dataset = tf.data.TextLineDataset(
'/content/training_set.csv'
).map(decode_csv).batch(BATCH_SIZE)
eval_dataset = tf.data.TextLineDataset(
'/content/eval_set.csv'
).map(decode_csv).batch(BATCH_SIZE)
but always get this error:
AttributeError
Traceback (most recent call last)
<ipython-input-22-b4dab8cd6263> in <module>()
1 BATCH_SIZE = 256
2
----> 3 train_dataset = tf.data.TextLineDataset('/content/training_set.csv').map(decode_csv).batch(BATCH_SIZE)
4
5 eval_dataset = tf.data.TextLineDataset('/content/eval_set.csv').map(decode_csv).batch(BATCH_SIZE)
10 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
697 except Exception as e: # pylint:disable=broad-except
698 if hasattr(e, 'ag_error_metadata'):
--> 699 raise e.ag_error_metadata.to_exception(e)
700 else:
701 raise
AttributeError: in user code:
File "<ipython-input-15-099bb5339c8f>", line 18, in decode_csv *
filename, pawpularity = tf.op.decode_csv(csv_row, record_defaults)
AttributeError: module 'tensorflow' has no attribute 'op'

python pathlib resolve does not support Chinese character on windows

On my windows,
pathlib.Path('R:/人')
has no problem to give
WindowsPath('R:/人')
However,
pathlib.Path('R:/人').resolve()
gives
--------------------------------------------------------------------------- OSError Traceback (most recent call
last) in
----> 1 pathlib.Path('R:/人').resolve()
~\anaconda3\lib\pathlib.py in resolve(self, strict) 1178 if
self._closed: 1179 self._raise_closed()
-> 1180 s = self._flavour.resolve(self, strict=strict) 1181 if s is None: 1182 # No symlink resolution => for
consistency, raise an error if
~\anaconda3\lib\pathlib.py in resolve(self, path, strict)
203 while True:
204 try:
--> 205 s = self._ext_to_normal(_getfinalpathname(s))
206 except FileNotFoundError:
207 previous_s = s
OSError: [WinError 1] 函数不正确。: 'R:\人'
What is the problem with resolve in pathlib?
On the other hand,
pathlib.Path('R:/人').absolute()
correctly gives
WindowsPath('R:/人')

Google AdManager getCurrentNetwork() error

I have set up ad manager credentials. I'm trying to access the Admanager API, im getting the following error.
from googleads import ad_manager
client = ad_manager.AdManagerClient.LoadFromStorage()
network_service = client.GetService('NetworkService', version='v201902')
current_network = network_service.getCurrentNetwork()
the error im facing is:
Fault Traceback (most recent call last)
~\Anaconda3\lib\site-packages\googleads\common.py in MakeSoapRequest(*args)
1381 return soap_service_method(
-> 1382 *packed_args, _soapheaders=soap_headers)['body']['rval']
1383 except zeep.exceptions.Fault as e:
~\Anaconda3\lib\site-packages\zeep\proxy.py in __call__(self, *args, **kwargs)
41 self._proxy._client, self._proxy._binding_options,
---> 42 self._op_name, args, kwargs)
43
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in send(self, client, options, operation, args, kwargs)
131
--> 132 return self.process_reply(client, operation_obj, response)
133
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in process_reply(self, client, operation, response)
193 if response.status_code != 200 or fault_node is not None:
--> 194 return self.process_error(doc, operation)
195
~\Anaconda3\lib\site-packages\zeep\wsdl\bindings\soap.py in process_error(self, doc, operation)
287 actor=None,
--> 288 detail=etree_to_string(doc))
289
Fault: Unknown fault occured
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-16-991c0839fc99> in <module>()
----> 1 current_network = network_service.getCurrentNetwork()
~\Anaconda3\lib\site-packages\googleads\common.py in MakeSoapRequest(*args)
1385 if e.detail is not None:
1386 underlying_exception = e.detail.find(
-> 1387 '{%s}ApiExceptionFault' % self._GetBindingNamespace())
1388 fault_type = self.zeep_client.get_element(
1389 '{%s}ApiExceptionFault' % self._GetBindingNamespace())
TypeError: a bytes-like object is required, not 'str'
You are probably missing permissions with your configured service account. Make sure the account has access to ad-manager and scopes are configured properly.
I suggest to do it this way:
class Adx:
def __init__(self):
self.GOOGLEADS_YAML = 'googleads.yaml'
self.GOOGLEADS_VERSION = 'v202111'
self.google_keys = self.GOOGLEADS_YAML
def activate(self):
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage(self.google_keys)

Categories

Resources