after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def tristimulus_weighting_factors_ASTME202211(cmfs, illuminant, shape):
"""
Returns a table of tristimulus weighting factors for given colour matching
functions and illuminant using practise *ASTM E2022-11* method [1]_.
The computed table of tristimulus weighting factors should be used with
spectral data that has been corrected for spectral bandpass dependence.
Parameters
----------
cmfs : XYZ_ColourMatchingFunctions
Standard observer colour matching functions.
illuminant : SpectralPowerDistribution
Illuminant spectral power distribution.
shape : SpectralShape
Shape used to build the table, only the interval is needed.
Returns
-------
ndarray
Tristimulus weighting factors table.
Raises
------
ValueError
If the colour matching functions or illuminant intervals are not equal
to 1 nm.
Warning
-------
- The tables of tristimulus weighting factors are cached in
:attr:`_TRISTIMULUS_WEIGHTING_FACTORS_CACHE` attribute. Their
identifier key is defined by the colour matching functions and
illuminant names along the current shape such as:
`CIE 1964 10 Degree Standard Observer, A, (360.0, 830.0, 10.0)`
Considering the above, one should be mindful that using similar colour
matching functions and illuminant names but with different spectral
data will lead to unexpected behaviour.
Notes
-----
- Input colour matching functions and illuminant intervals are expected
to be equal to 1 nm. If the illuminant data is not available at 1 nm
interval, it needs to be interpolated using *CIE* recommendations:
The method developed by *Sprague (1880)* should be used for
interpolating functions having a uniformly spaced independent variable
and a *Cubic Spline* method for non-uniformly spaced independent
variable.
Examples
--------
>>> from colour import (
... CMFS,
... CIE_standard_illuminant_A_function,
... SpectralPowerDistribution,
... SpectralShape)
>>> cmfs = CMFS['CIE 1964 10 Degree Standard Observer']
>>> wl = cmfs.shape.range()
>>> A = SpectralPowerDistribution(
... 'A (360, 830, 1)',
... dict(zip(wl, CIE_standard_illuminant_A_function(wl))))
>>> tristimulus_weighting_factors_ASTME202211( # doctest: +ELLIPSIS
... cmfs, A, SpectralShape(360, 830, 20))
array([[ -2.9816934...e-04, -3.1709762...e-05, -1.3301218...e-03],
[ -8.7154955...e-03, -8.9154168...e-04, -4.0743684...e-02],
[ 5.9967988...e-02, 5.0203497...e-03, 2.5650183...e-01],
[ 7.7342255...e-01, 7.7983983...e-02, 3.6965732...e+00],
[ 1.9000905...e+00, 3.0370051...e-01, 9.7554195...e+00],
[ 1.9707727...e+00, 8.5528092...e-01, 1.1486732...e+01],
[ 7.1836236...e-01, 2.1457000...e+00, 6.7845806...e+00],
[ 4.2666758...e-02, 4.8985328...e+00, 2.3208000...e+00],
[ 1.5223302...e+00, 9.6471138...e+00, 7.4306714...e-01],
[ 5.6770329...e+00, 1.4460970...e+01, 1.9581949...e-01],
[ 1.2445174...e+01, 1.7474254...e+01, 5.1826979...e-03],
[ 2.0553577...e+01, 1.7583821...e+01, -2.6512696...e-03],
[ 2.5331538...e+01, 1.4895703...e+01, 0.0000000...e+00],
[ 2.1571157...e+01, 1.0079661...e+01, 0.0000000...e+00],
[ 1.2178581...e+01, 5.0680655...e+00, 0.0000000...e+00],
[ 4.6675746...e+00, 1.8303239...e+00, 0.0000000...e+00],
[ 1.3236117...e+00, 5.1296946...e-01, 0.0000000...e+00],
[ 3.1753258...e-01, 1.2300847...e-01, 0.0000000...e+00],
[ 7.4634128...e-02, 2.9024389...e-02, 0.0000000...e+00],
[ 1.8299016...e-02, 7.1606335...e-03, 0.0000000...e+00],
[ 4.7942065...e-03, 1.8888730...e-03, 0.0000000...e+00],
[ 1.3293045...e-03, 5.2774591...e-04, 0.0000000...e+00],
[ 4.2546928...e-04, 1.7041978...e-04, 0.0000000...e+00],
[ 9.6251115...e-05, 3.8955295...e-05, 0.0000000...e+00]])
"""
if cmfs.shape.interval != 1:
raise ValueError('"{0}" shape "interval" must be 1!'.format(cmfs))
if illuminant.shape.interval != 1:
raise ValueError('"{0}" shape "interval" must be 1!'.format(illuminant))
global _TRISTIMULUS_WEIGHTING_FACTORS_CACHE
if _TRISTIMULUS_WEIGHTING_FACTORS_CACHE is None:
_TRISTIMULUS_WEIGHTING_FACTORS_CACHE = CaseInsensitiveMapping()
name_twf = ", ".join((cmfs.name, illuminant.name, str(shape)))
if name_twf in _TRISTIMULUS_WEIGHTING_FACTORS_CACHE:
return _TRISTIMULUS_WEIGHTING_FACTORS_CACHE[name_twf]
Y = cmfs.values
S = illuminant.values
interval_i = np.int_(shape.interval)
W = S[::interval_i, np.newaxis] * Y[::interval_i, :]
# First and last measurement intervals *Lagrange Coefficients*.
c_c = lagrange_coefficients_ASTME202211(interval_i, "boundary")
# Intermediate measurement intervals *Lagrange Coefficients*.
c_b = lagrange_coefficients_ASTME202211(interval_i, "inner")
# Total wavelengths count.
w_c = len(Y)
# Measurement interval interpolated values count.
r_c = c_b.shape[0]
# Last interval first interpolated wavelength.
w_lif = w_c - (w_c - 1) % interval_i - 1 - r_c
# Intervals count.
i_c = W.shape[0]
i_cm = i_c - 1
for i in range(3):
# First interval.
for j in range(r_c):
for k in range(3):
W[k, i] = W[k, i] + c_c[j, k] * S[j + 1] * Y[j + 1, i]
# Last interval.
for j in range(r_c):
for k in range(i_cm, i_cm - 3, -1):
W[k, i] = (
W[k, i]
+ c_c[r_c - j - 1, i_cm - k] * S[j + w_lif] * Y[j + w_lif, i]
)
# Intermediate intervals.
for j in range(i_c - 3):
for k in range(r_c):
w_i = (r_c + 1) * (j + 1) + 1 + k
W[j, i] = W[j, i] + c_b[k, 0] * S[w_i] * Y[w_i, i]
W[j + 1, i] = W[j + 1, i] + c_b[k, 1] * S[w_i] * Y[w_i, i]
W[j + 2, i] = W[j + 2, i] + c_b[k, 2] * S[w_i] * Y[w_i, i]
W[j + 3, i] = W[j + 3, i] + c_b[k, 3] * S[w_i] * Y[w_i, i]
# Extrapolation of potential incomplete interval.
for j in range(int(w_c - ((w_c - 1) % interval_i)), w_c, 1):
W[i_cm, i] = W[i_cm, i] + S[j] * Y[j, i]
W *= 100 / np.sum(W, axis=0)[1]
_TRISTIMULUS_WEIGHTING_FACTORS_CACHE[name_twf] = W
return W
|
def tristimulus_weighting_factors_ASTME202211(cmfs, illuminant, shape):
"""
Returns a table of tristimulus weighting factors for given colour matching
functions and illuminant using practise *ASTM E2022-11* method [1]_.
The computed table of tristimulus weighting factors should be used with
spectral data that has been corrected for spectral bandpass dependence.
Parameters
----------
cmfs : XYZ_ColourMatchingFunctions
Standard observer colour matching functions.
illuminant : SpectralPowerDistribution
Illuminant spectral power distribution.
shape : SpectralShape
Shape used to build the table, only the interval is needed.
Returns
-------
ndarray
Tristimulus weighting factors table.
Raises
------
ValueError
If the colour matching functions or illuminant intervals are not equal
to 1 nm.
Warning
-------
- The tables of tristimulus weighting factors are cached in
:attr:`_TRISTIMULUS_WEIGHTING_FACTORS_CACHE` attribute. Their
identifier key is defined by the colour matching functions and
illuminant names along the current shape such as:
`CIE 1964 10 Degree Standard Observer, A, (360.0, 830.0, 10.0)`
Considering the above, one should be mindful that using similar colour
matching functions and illuminant names but with different spectral
data will lead to unexpected behaviour.
Notes
-----
- Input colour matching functions and illuminant intervals are expected
to be equal to 1 nm. If the illuminant data is not available at 1 nm
interval, it needs to be interpolated using *CIE* recommendations:
The method developed by *Sprague (1880)* should be used for
interpolating functions having a uniformly spaced independent variable
and a *Cubic Spline* method for non-uniformly spaced independent
variable.
Examples
--------
>>> from colour import (
... CMFS,
... CIE_standard_illuminant_A_function,
... SpectralPowerDistribution,
... SpectralShape)
>>> cmfs = CMFS['CIE 1964 10 Degree Standard Observer']
>>> wl = cmfs.shape.range()
>>> A = SpectralPowerDistribution(
... 'A (360, 830, 1)',
... dict(zip(wl, CIE_standard_illuminant_A_function(wl))))
>>> tristimulus_weighting_factors_ASTME202211( # doctest: +ELLIPSIS
... cmfs, A, SpectralShape(360, 830, 20))
array([[ -2.9816934...e-04, -3.1709762...e-05, -1.3301218...e-03],
[ -8.7154955...e-03, -8.9154168...e-04, -4.0743684...e-02],
[ 5.9967988...e-02, 5.0203497...e-03, 2.5650183...e-01],
[ 7.7342255...e-01, 7.7983983...e-02, 3.6965732...e+00],
[ 1.9000905...e+00, 3.0370051...e-01, 9.7554195...e+00],
[ 1.9707727...e+00, 8.5528092...e-01, 1.1486732...e+01],
[ 7.1836236...e-01, 2.1457000...e+00, 6.7845806...e+00],
[ 4.2666758...e-02, 4.8985328...e+00, 2.3208000...e+00],
[ 1.5223302...e+00, 9.6471138...e+00, 7.4306714...e-01],
[ 5.6770329...e+00, 1.4460970...e+01, 1.9581949...e-01],
[ 1.2445174...e+01, 1.7474254...e+01, 5.1826979...e-03],
[ 2.0553577...e+01, 1.7583821...e+01, -2.6512696...e-03],
[ 2.5331538...e+01, 1.4895703...e+01, 0.0000000...e+00],
[ 2.1571157...e+01, 1.0079661...e+01, 0.0000000...e+00],
[ 1.2178581...e+01, 5.0680655...e+00, 0.0000000...e+00],
[ 4.6675746...e+00, 1.8303239...e+00, 0.0000000...e+00],
[ 1.3236117...e+00, 5.1296946...e-01, 0.0000000...e+00],
[ 3.1753258...e-01, 1.2300847...e-01, 0.0000000...e+00],
[ 7.4634128...e-02, 2.9024389...e-02, 0.0000000...e+00],
[ 1.8299016...e-02, 7.1606335...e-03, 0.0000000...e+00],
[ 4.7942065...e-03, 1.8888730...e-03, 0.0000000...e+00],
[ 1.3293045...e-03, 5.2774591...e-04, 0.0000000...e+00],
[ 4.2546928...e-04, 1.7041978...e-04, 0.0000000...e+00],
[ 9.6251115...e-05, 3.8955295...e-05, 0.0000000...e+00]])
"""
if cmfs.shape.interval != 1:
raise ValueError('"{0}" shape "interval" must be 1!'.format(cmfs))
if illuminant.shape.interval != 1:
raise ValueError('"{0}" shape "interval" must be 1!'.format(illuminant))
global _TRISTIMULUS_WEIGHTING_FACTORS_CACHE
if _TRISTIMULUS_WEIGHTING_FACTORS_CACHE is None:
_TRISTIMULUS_WEIGHTING_FACTORS_CACHE = CaseInsensitiveMapping()
name_twf = ", ".join((cmfs.name, illuminant.name, str(shape)))
if name_twf in _TRISTIMULUS_WEIGHTING_FACTORS_CACHE:
return _TRISTIMULUS_WEIGHTING_FACTORS_CACHE[name_twf]
Y = cmfs.values
S = illuminant.values
W = S[:: shape.interval, np.newaxis] * Y[:: shape.interval, :]
# First and last measurement intervals *Lagrange Coefficients*.
c_c = lagrange_coefficients_ASTME202211(shape.interval, "boundary")
# Intermediate measurement intervals *Lagrange Coefficients*.
c_b = lagrange_coefficients_ASTME202211(shape.interval, "inner")
# Total wavelengths count.
w_c = len(Y)
# Measurement interval interpolated values count.
r_c = c_b.shape[0]
# Last interval first interpolated wavelength.
w_lif = w_c - (w_c - 1) % shape.interval - 1 - r_c
# Intervals count.
i_c = W.shape[0]
i_cm = i_c - 1
for i in range(3):
# First interval.
for j in range(r_c):
for k in range(3):
W[k, i] = W[k, i] + c_c[j, k] * S[j + 1] * Y[j + 1, i]
# Last interval.
for j in range(r_c):
for k in range(i_cm, i_cm - 3, -1):
W[k, i] = (
W[k, i]
+ c_c[r_c - j - 1, i_cm - k] * S[j + w_lif] * Y[j + w_lif, i]
)
# Intermediate intervals.
for j in range(i_c - 3):
for k in range(r_c):
w_i = (r_c + 1) * (j + 1) + 1 + k
W[j, i] = W[j, i] + c_b[k, 0] * S[w_i] * Y[w_i, i]
W[j + 1, i] = W[j + 1, i] + c_b[k, 1] * S[w_i] * Y[w_i, i]
W[j + 2, i] = W[j + 2, i] + c_b[k, 2] * S[w_i] * Y[w_i, i]
W[j + 3, i] = W[j + 3, i] + c_b[k, 3] * S[w_i] * Y[w_i, i]
# Extrapolation of potential incomplete interval.
for j in range(int(w_c - ((w_c - 1) % shape.interval)), w_c, 1):
W[i_cm, i] = W[i_cm, i] + S[j] * Y[j, i]
W *= 100 / np.sum(W, axis=0)[1]
_TRISTIMULUS_WEIGHTING_FACTORS_CACHE[name_twf] = W
return W
|
https://github.com/colour-science/colour/issues/324
|
Traceback (most recent call last):
File "test.py", line 84, in <module>
plot.multi_spd_plot(spds, use_spds_colours=True)
File "/Users/chandler/miniconda2/envs/py6s-env/lib/python2.7/site-packages/colour/plotting/colorimetry.py", line 215, in multi_spd_plot
XYZ = spectral_to_XYZ(spd, cmfs, illuminant) / 100
File "/Users/chandler/miniconda2/envs/py6s-env/lib/python2.7/site-packages/colour/colorimetry/tristimulus.py", line 813, in spectral_to_XYZ
return function(spd, cmfs, illuminant, **kwargs)
File "/Users/chandler/miniconda2/envs/py6s-env/lib/python2.7/site-packages/colour/colorimetry/tristimulus.py", line 698, in spectral_to_XYZ_ASTME30815
XYZ = method(spd, cmfs, illuminant)
File "/Users/chandler/miniconda2/envs/py6s-env/lib/python2.7/site-packages/colour/colorimetry/tristimulus.py", line 555, in spectral_to_XYZ_tristimulus_weighting_factors_ASTME30815
int(cmfs.shape.start), int(cmfs.shape.end), int(spd.shape.interval)))
File "/Users/chandler/miniconda2/envs/py6s-env/lib/python2.7/site-packages/colour/colorimetry/tristimulus.py", line 267, in tristimulus_weighting_factors_ASTME202211
W = S[::shape.interval, np.newaxis] * Y[::shape.interval, :]
TypeError: slice indices must be integers or None or have an __index__ method
|
TypeError
|
def _alexa_wide_gamut_rgb_transfer_function(
value, firmware="SUP 3.x", method="Linear Scene Exposure Factor", EI=800
):
"""
Defines the *ALEXA Wide Gamut* colourspace transfer function.
Parameters
----------
value : numeric
value.
firmware : unicode, optional
{'SUP 3.x', 'SUP 2.x'}
Alexa firmware version.
method : unicode, optional
{'Linear Scene Exposure Factor', 'Normalised Sensor Signal'}
Conversion method.
EI : int, optional
Ei.
Returns
-------
numeric
Companded value.
"""
cut, a, b, c, d, e, f, _ = (
ALEXA_LOG_C_CURVE_CONVERSION_DATA.get(firmware).get(method).get(EI)
)
return c * np.log10(a * value + b) + d if value > cut else e * value + f
|
def _alexa_wide_gamut_rgb_transfer_function(
value, firmware="SUP 3.x", method="Linear Scene Exposure Factor", EI=800
):
"""
Defines the *ALEXA Wide Gamut* value colourspace transfer function.
Parameters
----------
value : numeric
value.
firmware : unicode, optional
{'SUP 3.x', 'SUP 2.x'}
Alexa firmware version.
method : unicode, optional
{'Linear Scene Exposure Factor', 'Normalised Sensor Signal'}
Conversion method.
EI : int, optional
Ei.
Returns
-------
numeric
Companded value.
"""
cut, a, b, c, d, e, f, _ = (
ALEXA_LOG_C_CURVE_CONVERSION_DATA.get(firmware).get(method).get(EI)
)
return c * np.log10(a * value + b) + d if value > cut else e * value + f
|
https://github.com/colour-science/colour/issues/157
|
---------------------------------------------------------------------------
PicklingError Traceback (most recent call last)
<ipython-input-1-6796e1d3ddfb> in <module>()
61 # multi_process_colourspace_volume_MonteCarlo(colour.ADOBE_RGB_1998_COLOURSPACE, 10e3)
62 import pickle
---> 63 pickle.dumps(colour.ADOBE_RGB_1998_COLOURSPACE)
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in dumps(obj, protocol)
1372 def dumps(obj, protocol=None):
1373 file = StringIO()
-> 1374 Pickler(file, protocol).dump(obj)
1375 return file.getvalue()
1376
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in dump(self, obj)
222 if self.proto >= 2:
223 self.write(PROTO + chr(self.proto))
--> 224 self.save(obj)
225 self.write(STOP)
226
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save(self, obj)
329
330 # Save the reduce() output and finally memoize the object
--> 331 self.save_reduce(obj=obj, *rv)
332
333 def persistent_id(self, obj):
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save_reduce(self, func, args, state, listitems, dictitems, obj)
417
418 if state is not None:
--> 419 save(state)
420 write(BUILD)
421
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save(self, obj)
284 f = self.dispatch.get(t)
285 if f:
--> 286 f(self, obj) # Call unbound method with explicit self
287 return
288
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save_dict(self, obj)
647
648 self.memoize(obj)
--> 649 self._batch_setitems(obj.iteritems())
650
651 dispatch[DictionaryType] = save_dict
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in _batch_setitems(self, items)
661 for k, v in items:
662 save(k)
--> 663 save(v)
664 write(SETITEM)
665 return
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save(self, obj)
284 f = self.dispatch.get(t)
285 if f:
--> 286 f(self, obj) # Call unbound method with explicit self
287 return
288
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save_global(self, obj, name, pack)
746 raise PicklingError(
747 "Can't pickle %r: it's not found as %s.%s" %
--> 748 (obj, module, name))
749 else:
750 if klass is not obj:
PicklingError: Can't pickle <function <lambda> at 0x7faae408dc80>: it's not found as colour.models.dataset.adobe_rgb_1998.<lambda>
|
PicklingError
|
def _alexa_wide_gamut_rgb_inverse_transfer_function(
value, firmware="SUP 3.x", method="Linear Scene Exposure Factor", EI=800
):
"""
Defines the *ALEXA Wide Gamut* colourspace inverse transfer function.
Parameters
----------
value : numeric
value.
firmware : unicode, optional
{'SUP 3.x', 'SUP 2.x'}
Alexa firmware version.
method : unicode, optional
{'Linear Scene Exposure Factor', 'Normalised Sensor Signal'}
Conversion method.
EI : int, optional
Ei.
Returns
-------
numeric
Companded value.
"""
cut, a, b, c, d, e, f, _ = (
ALEXA_LOG_C_CURVE_CONVERSION_DATA.get(firmware).get(method).get(EI)
)
return (
(np.power(10.0, (value - d) / c) - b) / a
if value > e * cut + f
else (value - f) / e
)
|
def _alexa_wide_gamut_rgb_inverse_transfer_function(
value, firmware="SUP 3.x", method="Linear Scene Exposure Factor", EI=800
):
"""
Defines the *ALEXA Wide Gamut* value colourspace inverse transfer function.
Parameters
----------
value : numeric
value.
firmware : unicode, optional
{'SUP 3.x', 'SUP 2.x'}
Alexa firmware version.
method : unicode, optional
{'Linear Scene Exposure Factor', 'Normalised Sensor Signal'}
Conversion method.
EI : int, optional
Ei.
Returns
-------
numeric
Companded value.
"""
cut, a, b, c, d, e, f, _ = (
ALEXA_LOG_C_CURVE_CONVERSION_DATA.get(firmware).get(method).get(EI)
)
return (
(np.power(10.0, (value - d) / c) - b) / a
if value > e * cut + f
else (value - f) / e
)
|
https://github.com/colour-science/colour/issues/157
|
---------------------------------------------------------------------------
PicklingError Traceback (most recent call last)
<ipython-input-1-6796e1d3ddfb> in <module>()
61 # multi_process_colourspace_volume_MonteCarlo(colour.ADOBE_RGB_1998_COLOURSPACE, 10e3)
62 import pickle
---> 63 pickle.dumps(colour.ADOBE_RGB_1998_COLOURSPACE)
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in dumps(obj, protocol)
1372 def dumps(obj, protocol=None):
1373 file = StringIO()
-> 1374 Pickler(file, protocol).dump(obj)
1375 return file.getvalue()
1376
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in dump(self, obj)
222 if self.proto >= 2:
223 self.write(PROTO + chr(self.proto))
--> 224 self.save(obj)
225 self.write(STOP)
226
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save(self, obj)
329
330 # Save the reduce() output and finally memoize the object
--> 331 self.save_reduce(obj=obj, *rv)
332
333 def persistent_id(self, obj):
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save_reduce(self, func, args, state, listitems, dictitems, obj)
417
418 if state is not None:
--> 419 save(state)
420 write(BUILD)
421
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save(self, obj)
284 f = self.dispatch.get(t)
285 if f:
--> 286 f(self, obj) # Call unbound method with explicit self
287 return
288
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save_dict(self, obj)
647
648 self.memoize(obj)
--> 649 self._batch_setitems(obj.iteritems())
650
651 dispatch[DictionaryType] = save_dict
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in _batch_setitems(self, items)
661 for k, v in items:
662 save(k)
--> 663 save(v)
664 write(SETITEM)
665 return
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save(self, obj)
284 f = self.dispatch.get(t)
285 if f:
--> 286 f(self, obj) # Call unbound method with explicit self
287 return
288
/home/vagrant/anaconda/envs/python2.7/lib/python2.7/pickle.pyc in save_global(self, obj, name, pack)
746 raise PicklingError(
747 "Can't pickle %r: it's not found as %s.%s" %
--> 748 (obj, module, name))
749 else:
750 if klass is not obj:
PicklingError: Can't pickle <function <lambda> at 0x7faae408dc80>: it's not found as colour.models.dataset.adobe_rgb_1998.<lambda>
|
PicklingError
|
async def _run(
provider,
# AWS
profile,
aws_access_key_id,
aws_secret_access_key,
aws_session_token,
# Azure
cli,
user_account,
user_account_browser,
msi,
service_principal,
file_auth,
tenant_id,
subscription_ids,
all_subscriptions,
client_id,
client_secret,
username,
password,
# GCP
service_account,
project_id,
folder_id,
organization_id,
all_projects,
# Aliyun
access_key_id,
access_key_secret,
# General
report_name,
report_dir,
timestamp,
services,
skipped_services,
list_services,
result_format,
database_name,
host_ip,
host_port,
regions,
excluded_regions,
fetch_local,
update,
ip_ranges,
ip_ranges_name_key,
ruleset,
exceptions,
force_write,
debug,
quiet,
log_file,
no_browser,
programmatic_execution,
**kwargs,
):
"""
Run a scout job.
"""
# Configure the debug level
set_logger_configuration(debug, quiet, log_file)
print_info("Launching Scout")
print_info("Authenticating to cloud provider")
auth_strategy = get_authentication_strategy(provider)
try:
credentials = auth_strategy.authenticate(
profile=profile,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
aws_session_token=aws_session_token,
user_account=user_account,
user_account_browser=user_account_browser,
service_account=service_account,
cli=cli,
msi=msi,
service_principal=service_principal,
file_auth=file_auth,
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret,
username=username,
password=password,
access_key_id=access_key_id,
access_key_secret=access_key_secret,
)
if not credentials:
return 101
except Exception as e:
print_exception("Authentication failure: {}".format(e))
return 101
# Create a cloud provider object
try:
cloud_provider = get_provider(
provider=provider,
# AWS
profile=profile,
# Azure
subscription_ids=subscription_ids,
all_subscriptions=all_subscriptions,
# GCP
project_id=project_id,
folder_id=folder_id,
organization_id=organization_id,
all_projects=all_projects,
# Other
report_dir=report_dir,
timestamp=timestamp,
services=services,
skipped_services=skipped_services,
programmatic_execution=programmatic_execution,
credentials=credentials,
)
except Exception as e:
print_exception("Initialization failure: {}".format(e))
return 102
# Create a new report
try:
report_name = report_name if report_name else cloud_provider.get_report_name()
report = ScoutReport(
cloud_provider.provider_code,
report_name,
report_dir,
timestamp,
result_format=result_format,
)
if database_name:
database_file, _ = get_filename(
"RESULTS", report_name, report_dir, file_extension="db"
)
Server.init(database_file, host_ip, host_port)
return
except Exception as e:
print_exception("Report initialization failure: {}".format(e))
return 103
# If this command, run and exit
if list_services:
available_services = [
x
for x in dir(cloud_provider.services)
if not (x.startswith("_") or x in ["credentials", "fetch"])
]
print_info(
'The available services are: "{}"'.format('", "'.join(available_services))
)
return 0
# Complete run, including pulling data from provider
if not fetch_local:
# Fetch data from provider APIs
try:
print_info("Gathering data from APIs")
await cloud_provider.fetch(
regions=regions, excluded_regions=excluded_regions
)
except KeyboardInterrupt:
print_info("\nCancelled by user")
return 130
except Exception as e:
print_exception(
"Unhandled exception thrown while gathering data: {}".format(e)
)
return 104
# Update means we reload the whole config and overwrite part of it
if update:
try:
print_info("Updating existing data")
current_run_services = copy.deepcopy(cloud_provider.services)
last_run_dict = report.encoder.load_from_file("RESULTS")
cloud_provider.services = last_run_dict["services"]
for service in cloud_provider.service_list:
cloud_provider.services[service] = current_run_services[service]
except Exception as e:
print_exception("Failure while updating report: {}".format(e))
# Partial run, using pre-pulled data
else:
try:
print_info("Using local data")
# Reload to flatten everything into a python dictionary
last_run_dict = report.encoder.load_from_file("RESULTS")
for key in last_run_dict:
setattr(cloud_provider, key, last_run_dict[key])
except Exception as e:
print_exception("Failure while updating report: {}".format(e))
# Pre processing
try:
print_info("Running pre-processing engine")
cloud_provider.preprocessing(ip_ranges, ip_ranges_name_key)
except Exception as e:
print_exception("Failure while running pre-processing engine: {}".format(e))
return 105
# Analyze config
try:
print_info("Running rule engine")
finding_rules = Ruleset(
cloud_provider=cloud_provider.provider_code,
environment_name=cloud_provider.environment,
filename=ruleset,
ip_ranges=ip_ranges,
account_id=cloud_provider.account_id,
)
processing_engine = ProcessingEngine(finding_rules)
processing_engine.run(cloud_provider)
except Exception as e:
print_exception("Failure while running rule engine: {}".format(e))
return 106
# Create display filters
try:
print_info("Applying display filters")
filter_rules = Ruleset(
cloud_provider=cloud_provider.provider_code,
environment_name=cloud_provider.environment,
filename="filters.json",
rule_type="filters",
account_id=cloud_provider.account_id,
)
processing_engine = ProcessingEngine(filter_rules)
processing_engine.run(cloud_provider)
except Exception as e:
print_exception("Failure while applying display filters: {}".format(e))
return 107
# Handle exceptions
if exceptions:
print_info("Applying exceptions")
try:
exceptions = RuleExceptions(exceptions)
exceptions.process(cloud_provider)
exceptions = exceptions.exceptions
except Exception as e:
print_exception("Failed to load exceptions: {}".format(e))
exceptions = {}
else:
exceptions = {}
# Finalize
try:
print_info("Running post-processing engine")
run_parameters = {
"services": services,
"skipped_services": skipped_services,
"regions": regions,
"excluded_regions": excluded_regions,
}
cloud_provider.postprocessing(
report.current_time, finding_rules, run_parameters
)
except Exception as e:
print_exception("Failure while running post-processing engine: {}".format(e))
return 108
# Save config and create HTML report
try:
html_report_path = report.save(cloud_provider, exceptions, force_write, debug)
except Exception as e:
print_exception("Failure while generating HTML report: {}".format(e))
return 109
# Open the report by default
if not no_browser:
print_info("Opening the HTML report")
url = "file://%s" % os.path.abspath(html_report_path)
webbrowser.open(url, new=2)
if ERRORS_LIST: # errors were handled during execution
return 200
else:
return 0
|
async def _run(
provider,
# AWS
profile,
aws_access_key_id,
aws_secret_access_key,
aws_session_token,
# Azure
cli,
user_account,
user_account_browser,
msi,
service_principal,
file_auth,
tenant_id,
subscription_ids,
all_subscriptions,
client_id,
client_secret,
username,
password,
# GCP
service_account,
project_id,
folder_id,
organization_id,
all_projects,
# Aliyun
access_key_id,
access_key_secret,
# General
report_name,
report_dir,
timestamp,
services,
skipped_services,
list_services,
result_format,
database_name,
host_ip,
host_port,
regions,
excluded_regions,
fetch_local,
update,
ip_ranges,
ip_ranges_name_key,
ruleset,
exceptions,
force_write,
debug,
quiet,
log_file,
no_browser,
programmatic_execution,
**kwargs,
):
"""
Run a scout job.
"""
# Configure the debug level
set_logger_configuration(debug, quiet, log_file)
print_info("Launching Scout")
print_info("Authenticating to cloud provider")
auth_strategy = get_authentication_strategy(provider)
try:
credentials = auth_strategy.authenticate(
profile=profile,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
aws_session_token=aws_session_token,
user_account=user_account,
user_account_browser=user_account_browser,
service_account=service_account,
cli=cli,
msi=msi,
service_principal=service_principal,
file_auth=file_auth,
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret,
username=username,
password=password,
access_key_id=access_key_id,
access_key_secret=access_key_secret,
)
if not credentials:
return 101
except Exception as e:
print_exception("Authentication failure: {}".format(e))
return 101
# Create a cloud provider object
try:
cloud_provider = get_provider(
provider=provider,
# AWS
profile=profile,
# Azure
subscription_ids=subscription_ids,
all_subscriptions=all_subscriptions,
# GCP
project_id=project_id,
folder_id=folder_id,
organization_id=organization_id,
all_projects=all_projects,
# Other
report_dir=report_dir,
timestamp=timestamp,
services=services,
skipped_services=skipped_services,
programmatic_execution=programmatic_execution,
credentials=credentials,
)
except Exception as e:
print_exception("Initialization failure: {}".format(e))
return 102
# Create a new report
report_name = report_name if report_name else cloud_provider.get_report_name()
report = ScoutReport(
cloud_provider.provider_code,
report_name,
report_dir,
timestamp,
result_format=result_format,
)
if database_name:
database_file, _ = get_filename(
"RESULTS", report_name, report_dir, file_extension="db"
)
Server.init(database_file, host_ip, host_port)
return
# If this command, run and exit
if list_services:
available_services = [
x
for x in dir(cloud_provider.services)
if not (x.startswith("_") or x in ["credentials", "fetch"])
]
print_info(
'The available services are: "{}"'.format('", "'.join(available_services))
)
return 0
# Complete run, including pulling data from provider
if not fetch_local:
# Fetch data from provider APIs
try:
print_info("Gathering data from APIs")
await cloud_provider.fetch(
regions=regions, excluded_regions=excluded_regions
)
except KeyboardInterrupt:
print_info("\nCancelled by user")
return 130
# Update means we reload the whole config and overwrite part of it
if update:
print_info("Updating existing data")
current_run_services = copy.deepcopy(cloud_provider.services)
last_run_dict = report.encoder.load_from_file("RESULTS")
cloud_provider.services = last_run_dict["services"]
for service in cloud_provider.service_list:
cloud_provider.services[service] = current_run_services[service]
# Partial run, using pre-pulled data
else:
print_info("Using local data")
# Reload to flatten everything into a python dictionary
last_run_dict = report.encoder.load_from_file("RESULTS")
for key in last_run_dict:
setattr(cloud_provider, key, last_run_dict[key])
# Pre processing
cloud_provider.preprocessing(ip_ranges, ip_ranges_name_key)
# Analyze config
print_info("Running rule engine")
finding_rules = Ruleset(
cloud_provider=cloud_provider.provider_code,
environment_name=cloud_provider.environment,
filename=ruleset,
ip_ranges=ip_ranges,
account_id=cloud_provider.account_id,
)
processing_engine = ProcessingEngine(finding_rules)
processing_engine.run(cloud_provider)
# Create display filters
print_info("Applying display filters")
filter_rules = Ruleset(
cloud_provider=cloud_provider.provider_code,
environment_name=cloud_provider.environment,
filename="filters.json",
rule_type="filters",
account_id=cloud_provider.account_id,
)
processing_engine = ProcessingEngine(filter_rules)
processing_engine.run(cloud_provider)
# Handle exceptions
if exceptions:
print_info("Applying exceptions")
try:
exceptions = RuleExceptions(exceptions)
exceptions.process(cloud_provider)
exceptions = exceptions.exceptions
except Exception as e:
print_exception("Failed to load exceptions: {}".format(e))
exceptions = {}
else:
exceptions = {}
run_parameters = {
"services": services,
"skipped_services": skipped_services,
"regions": regions,
"excluded_regions": excluded_regions,
}
# Finalize
cloud_provider.postprocessing(report.current_time, finding_rules, run_parameters)
# Save config and create HTML report
html_report_path = report.save(cloud_provider, exceptions, force_write, debug)
# Open the report by default
if not no_browser:
print_info("Opening the HTML report")
url = "file://%s" % os.path.abspath(html_report_path)
webbrowser.open(url, new=2)
if ERRORS_LIST: # errors were handled during execution
return 200
else:
return 0
|
https://github.com/nccgroup/ScoutSuite/issues/821
|
2020-07-24 03:56:32 ubuntu scout[3614] ERROR aad.py L30: Failed to retrieve user xxx-xxx-xxx-xxx-xxx: Resource 'xxx-xxxx-xxx-xxx-xxx-xx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in get_user
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in <lambda>
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/.local/lib/python3.6/site-packages/azure/graphrbac/operations/users_operations.py", line 218, in get
raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error_py3.GraphErrorException: Resource 'xxx-xxx-xxx-xxx-xxx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "./scout.py", line 8, in <module>
sys.exit(run_from_cli())
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 77, in run_from_cli
programmatic_execution=False)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 131, in run
result = loop.run_until_complete(_run(**locals())) # pass through all the parameters
File "/usr/lib/python3.6/asyncio/base_events.py", line 484, in run_until_complete
return future.result()
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 258, in _run
await cloud_provider.fetch(regions=regions, excluded_regions=excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/base/provider.py", line 81, in fetch
await self.services.fetch(self.service_list, regions, excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/services.py", line 78, in fetch
await self.aad.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/base.py", line 26, in fetch_additional_users
await additional_users.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 17, in fetch_additional_users
id, user = await self._parse_user(raw_user)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 22, in _parse_user
user_dict['id'] = raw_user.object_id
AttributeError: 'list' object has no attribute 'object_id'
|
azure.graphrbac.models.graph_error_py3.GraphErrorException
|
async def get_user(self, user_id):
try:
return await run_concurrently(lambda: self.get_client().users.get(user_id))
except Exception as e:
print_exception("Failed to retrieve user {}: {}".format(user_id, e))
return None
|
async def get_user(self, user_id):
try:
return await run_concurrently(lambda: self.get_client().users.get(user_id))
except Exception as e:
print_exception("Failed to retrieve user {}: {}".format(user_id, e))
return []
|
https://github.com/nccgroup/ScoutSuite/issues/821
|
2020-07-24 03:56:32 ubuntu scout[3614] ERROR aad.py L30: Failed to retrieve user xxx-xxx-xxx-xxx-xxx: Resource 'xxx-xxxx-xxx-xxx-xxx-xx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in get_user
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in <lambda>
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/.local/lib/python3.6/site-packages/azure/graphrbac/operations/users_operations.py", line 218, in get
raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error_py3.GraphErrorException: Resource 'xxx-xxx-xxx-xxx-xxx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "./scout.py", line 8, in <module>
sys.exit(run_from_cli())
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 77, in run_from_cli
programmatic_execution=False)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 131, in run
result = loop.run_until_complete(_run(**locals())) # pass through all the parameters
File "/usr/lib/python3.6/asyncio/base_events.py", line 484, in run_until_complete
return future.result()
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 258, in _run
await cloud_provider.fetch(regions=regions, excluded_regions=excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/base/provider.py", line 81, in fetch
await self.services.fetch(self.service_list, regions, excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/services.py", line 78, in fetch
await self.aad.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/base.py", line 26, in fetch_additional_users
await additional_users.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 17, in fetch_additional_users
id, user = await self._parse_user(raw_user)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 22, in _parse_user
user_dict['id'] = raw_user.object_id
AttributeError: 'list' object has no attribute 'object_id'
|
azure.graphrbac.models.graph_error_py3.GraphErrorException
|
def _match_rbac_roles_and_principals(self):
"""
Matches ARM role assignments to AAD service principals
"""
try:
if "rbac" in self.service_list and "aad" in self.service_list:
for subscription in self.services["rbac"]["subscriptions"]:
for assignment in self.services["rbac"]["subscriptions"][subscription][
"role_assignments"
].values():
role_id = assignment["role_definition_id"].split("/")[-1]
for group in self.services["aad"]["groups"]:
if group == assignment["principal_id"]:
self.services["aad"]["groups"][group]["roles"].append(
{"subscription_id": subscription, "role_id": role_id}
)
self.services["rbac"]["subscriptions"][subscription][
"roles"
][role_id]["assignments"]["groups"].append(group)
self.services["rbac"]["subscriptions"][subscription][
"roles"
][role_id]["assignments_count"] += 1
for user in self.services["aad"]["users"]:
if user == assignment["principal_id"]:
self.services["aad"]["users"][user]["roles"].append(
{"subscription_id": subscription, "role_id": role_id}
)
self.services["rbac"]["subscriptions"][subscription][
"roles"
][role_id]["assignments"]["users"].append(user)
self.services["rbac"]["subscriptions"][subscription][
"roles"
][role_id]["assignments_count"] += 1
for service_principal in self.services["aad"]["service_principals"]:
if service_principal == assignment["principal_id"]:
self.services["aad"]["service_principals"][
service_principal
]["roles"].append(
{"subscription_id": subscription, "role_id": role_id}
)
self.services["rbac"]["subscriptions"][subscription][
"roles"
][role_id]["assignments"]["service_principals"].append(
service_principal
)
self.services["rbac"]["subscriptions"][subscription][
"roles"
][role_id]["assignments_count"] += 1
except Exception as e:
print_exception("Unable to match RBAC roles and principals: {}".format(e))
|
def _match_rbac_roles_and_principals(self):
"""
Matches ARM role assignments to AAD service principals
"""
if "rbac" in self.service_list and "aad" in self.service_list:
for subscription in self.services["rbac"]["subscriptions"]:
for assignment in self.services["rbac"]["subscriptions"][subscription][
"role_assignments"
].values():
role_id = assignment["role_definition_id"].split("/")[-1]
for group in self.services["aad"]["groups"]:
if group == assignment["principal_id"]:
self.services["aad"]["groups"][group]["roles"].append(
{"subscription_id": subscription, "role_id": role_id}
)
self.services["rbac"]["subscriptions"][subscription]["roles"][
role_id
]["assignments"]["groups"].append(group)
self.services["rbac"]["subscriptions"][subscription]["roles"][
role_id
]["assignments_count"] += 1
for user in self.services["aad"]["users"]:
if user == assignment["principal_id"]:
self.services["aad"]["users"][user]["roles"].append(
{"subscription_id": subscription, "role_id": role_id}
)
self.services["rbac"]["subscriptions"][subscription]["roles"][
role_id
]["assignments"]["users"].append(user)
self.services["rbac"]["subscriptions"][subscription]["roles"][
role_id
]["assignments_count"] += 1
for service_principal in self.services["aad"]["service_principals"]:
if service_principal == assignment["principal_id"]:
self.services["aad"]["service_principals"][service_principal][
"roles"
].append({"subscription_id": subscription, "role_id": role_id})
self.services["rbac"]["subscriptions"][subscription]["roles"][
role_id
]["assignments"]["service_principals"].append(service_principal)
self.services["rbac"]["subscriptions"][subscription]["roles"][
role_id
]["assignments_count"] += 1
|
https://github.com/nccgroup/ScoutSuite/issues/821
|
2020-07-24 03:56:32 ubuntu scout[3614] ERROR aad.py L30: Failed to retrieve user xxx-xxx-xxx-xxx-xxx: Resource 'xxx-xxxx-xxx-xxx-xxx-xx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in get_user
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in <lambda>
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/.local/lib/python3.6/site-packages/azure/graphrbac/operations/users_operations.py", line 218, in get
raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error_py3.GraphErrorException: Resource 'xxx-xxx-xxx-xxx-xxx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "./scout.py", line 8, in <module>
sys.exit(run_from_cli())
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 77, in run_from_cli
programmatic_execution=False)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 131, in run
result = loop.run_until_complete(_run(**locals())) # pass through all the parameters
File "/usr/lib/python3.6/asyncio/base_events.py", line 484, in run_until_complete
return future.result()
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 258, in _run
await cloud_provider.fetch(regions=regions, excluded_regions=excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/base/provider.py", line 81, in fetch
await self.services.fetch(self.service_list, regions, excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/services.py", line 78, in fetch
await self.aad.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/base.py", line 26, in fetch_additional_users
await additional_users.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 17, in fetch_additional_users
id, user = await self._parse_user(raw_user)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 22, in _parse_user
user_dict['id'] = raw_user.object_id
AttributeError: 'list' object has no attribute 'object_id'
|
azure.graphrbac.models.graph_error_py3.GraphErrorException
|
async def fetch_additional_users(self, user_list):
"""
Special method to fetch additional users
"""
try:
# fetch the users
additional_users = Users(self.facade)
await additional_users.fetch_additional_users(user_list)
# add them to the resource and update count
self["users"].update(additional_users)
self["users_count"] = len(self["users"].values())
except Exception as e:
print_exception("Unable to fetch additional users: {}".format(e))
finally:
# re-run the finalize method
await self.finalize()
|
async def fetch_additional_users(self, user_list):
"""
Special method to fetch additional users
"""
# fetch the users
additional_users = Users(self.facade)
await additional_users.fetch_additional_users(user_list)
# add them to the resource and update count
self["users"].update(additional_users)
self["users_count"] = len(self["users"].values())
# re-run the finalize method
await self.finalize()
|
https://github.com/nccgroup/ScoutSuite/issues/821
|
2020-07-24 03:56:32 ubuntu scout[3614] ERROR aad.py L30: Failed to retrieve user xxx-xxx-xxx-xxx-xxx: Resource 'xxx-xxxx-xxx-xxx-xxx-xx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in get_user
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in <lambda>
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/.local/lib/python3.6/site-packages/azure/graphrbac/operations/users_operations.py", line 218, in get
raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error_py3.GraphErrorException: Resource 'xxx-xxx-xxx-xxx-xxx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "./scout.py", line 8, in <module>
sys.exit(run_from_cli())
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 77, in run_from_cli
programmatic_execution=False)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 131, in run
result = loop.run_until_complete(_run(**locals())) # pass through all the parameters
File "/usr/lib/python3.6/asyncio/base_events.py", line 484, in run_until_complete
return future.result()
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 258, in _run
await cloud_provider.fetch(regions=regions, excluded_regions=excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/base/provider.py", line 81, in fetch
await self.services.fetch(self.service_list, regions, excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/services.py", line 78, in fetch
await self.aad.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/base.py", line 26, in fetch_additional_users
await additional_users.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 17, in fetch_additional_users
id, user = await self._parse_user(raw_user)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 22, in _parse_user
user_dict['id'] = raw_user.object_id
AttributeError: 'list' object has no attribute 'object_id'
|
azure.graphrbac.models.graph_error_py3.GraphErrorException
|
def assign_group_memberships(self):
"""
Assigns members to groups
"""
try:
for group in self["groups"]:
for user in self["users"]:
if group in self["users"][user]["groups"]:
self["groups"][group]["users"].append(user)
except Exception as e:
print_exception("Unable to assign group memberships: {}".format(e))
|
def assign_group_memberships(self):
"""
Assigns members to groups
"""
for group in self["groups"]:
for user in self["users"]:
if group in self["users"][user]["groups"]:
self["groups"][group]["users"].append(user)
|
https://github.com/nccgroup/ScoutSuite/issues/821
|
2020-07-24 03:56:32 ubuntu scout[3614] ERROR aad.py L30: Failed to retrieve user xxx-xxx-xxx-xxx-xxx: Resource 'xxx-xxxx-xxx-xxx-xxx-xx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in get_user
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in <lambda>
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/.local/lib/python3.6/site-packages/azure/graphrbac/operations/users_operations.py", line 218, in get
raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error_py3.GraphErrorException: Resource 'xxx-xxx-xxx-xxx-xxx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "./scout.py", line 8, in <module>
sys.exit(run_from_cli())
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 77, in run_from_cli
programmatic_execution=False)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 131, in run
result = loop.run_until_complete(_run(**locals())) # pass through all the parameters
File "/usr/lib/python3.6/asyncio/base_events.py", line 484, in run_until_complete
return future.result()
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 258, in _run
await cloud_provider.fetch(regions=regions, excluded_regions=excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/base/provider.py", line 81, in fetch
await self.services.fetch(self.service_list, regions, excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/services.py", line 78, in fetch
await self.aad.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/base.py", line 26, in fetch_additional_users
await additional_users.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 17, in fetch_additional_users
id, user = await self._parse_user(raw_user)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 22, in _parse_user
user_dict['id'] = raw_user.object_id
AttributeError: 'list' object has no attribute 'object_id'
|
azure.graphrbac.models.graph_error_py3.GraphErrorException
|
async def fetch_additional_users(self, user_list):
"""
Alternative method which only fetches defined users
:param user_list: a list of the users to fetch and parse
"""
for user in user_list:
raw_user = await self.facade.aad.get_user(user)
if raw_user:
id, user = await self._parse_user(raw_user)
self[id] = user
|
async def fetch_additional_users(self, user_list):
"""
Alternative method which only fetches defined users
:param user_list: a list of the users to fetch and parse
"""
for user in user_list:
raw_user = await self.facade.aad.get_user(user)
id, user = await self._parse_user(raw_user)
self[id] = user
|
https://github.com/nccgroup/ScoutSuite/issues/821
|
2020-07-24 03:56:32 ubuntu scout[3614] ERROR aad.py L30: Failed to retrieve user xxx-xxx-xxx-xxx-xxx: Resource 'xxx-xxxx-xxx-xxx-xxx-xx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in get_user
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/facade/aad.py", line 30, in <lambda>
return await run_concurrently(lambda: self.get_client().users.get(user_id))
File "/home/victor/.local/lib/python3.6/site-packages/azure/graphrbac/operations/users_operations.py", line 218, in get
raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error_py3.GraphErrorException: Resource 'xxx-xxx-xxx-xxx-xxx' does not exist or one of its queried reference-property objects are not present.
Traceback (most recent call last):
File "./scout.py", line 8, in <module>
sys.exit(run_from_cli())
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 77, in run_from_cli
programmatic_execution=False)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 131, in run
result = loop.run_until_complete(_run(**locals())) # pass through all the parameters
File "/usr/lib/python3.6/asyncio/base_events.py", line 484, in run_until_complete
return future.result()
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/__main__.py", line 258, in _run
await cloud_provider.fetch(regions=regions, excluded_regions=excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/base/provider.py", line 81, in fetch
await self.services.fetch(self.service_list, regions, excluded_regions)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/services.py", line 78, in fetch
await self.aad.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/base.py", line 26, in fetch_additional_users
await additional_users.fetch_additional_users(user_list)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 17, in fetch_additional_users
id, user = await self._parse_user(raw_user)
File "/home/victor/Documents/scout_59/ScoutSuite/ScoutSuite/providers/azure/resources/aad/users.py", line 22, in _parse_user
user_dict['id'] = raw_user.object_id
AttributeError: 'list' object has no attribute 'object_id'
|
azure.graphrbac.models.graph_error_py3.GraphErrorException
|
async def get_keys(self, region: str):
try:
keys = await AWSFacadeUtils.get_all_pages(
"kms", region, self.session, "list_keys", "Keys"
)
await get_and_set_concurrently(
[
self._get_and_set_key_policy,
self._get_and_set_key_metadata,
self._get_and_set_key_aliases,
],
keys,
region=region,
)
except Exception as e:
print_exception("Failed to get KMS keys: {}".format(e))
keys = []
finally:
return keys
|
async def get_keys(self, region: str):
try:
keys = await AWSFacadeUtils.get_all_pages(
"kms", region, self.session, "list_keys", "Keys"
)
await get_and_set_concurrently(
[
self._get_and_set_key_policy,
self._get_and_set_key_metadata,
self._get_and_set_key_rotation_status,
self._get_and_set_key_aliases,
],
keys,
region=region,
)
except Exception as e:
print_exception("Failed to get KMS keys: {}".format(e))
keys = []
finally:
return keys
|
https://github.com/nccgroup/ScoutSuite/issues/697
|
Traceback (most recent call last):
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/aws/facade/kms.py", line 41, in _get_and_set_key_rotation_status
lambda: client.get_key_rotation_status(KeyId=key['KeyId']))
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "<redactedPath>/.pyenv/versions/3.7.2/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/aws/facade/kms.py", line 41, in <lambda>
lambda: client.get_key_rotation_status(KeyId=key['KeyId']))
File "<redactedPath>env/lib/python3.7/site-packages/botocore/client.py", line 316, in _api_call
return self._make_api_call(operation_name, kwargs)
File "<redactedPath>env/lib/python3.7/site-packages/botocore/client.py", line 626, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the GetKeyRotationStatus operation: User: arn:aws:sts::<redacted>:assumed-role/<redacted>/<redacted> is not authorized to perform: kms:GetKeyRotationStatus on resource: arn:aws:kms:us-east-1:<redacted>:key/<redacted>
|
botocore.exceptions.ClientError
|
async def fetch_all(self):
raw_keys = await self.facade.kms.get_keys(self.region)
for raw_key in raw_keys:
key_id, key = await self._parse_key(raw_key)
self[key_id] = key
await self._fetch_children_of_all_resources(
resources=self,
scopes={
key_id: {"region": self.region, "key_id": key["id"]}
for (key_id, key) in self.items()
},
)
|
async def fetch_all(self):
raw_keys = await self.facade.kms.get_keys(self.region)
for raw_key in raw_keys:
key_id, key = self._parse_key(raw_key)
self[key_id] = key
await self._fetch_children_of_all_resources(
resources=self,
scopes={
key_id: {"region": self.region, "key_id": key["id"]}
for (key_id, key) in self.items()
},
)
|
https://github.com/nccgroup/ScoutSuite/issues/697
|
Traceback (most recent call last):
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/aws/facade/kms.py", line 41, in _get_and_set_key_rotation_status
lambda: client.get_key_rotation_status(KeyId=key['KeyId']))
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "<redactedPath>/.pyenv/versions/3.7.2/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/aws/facade/kms.py", line 41, in <lambda>
lambda: client.get_key_rotation_status(KeyId=key['KeyId']))
File "<redactedPath>env/lib/python3.7/site-packages/botocore/client.py", line 316, in _api_call
return self._make_api_call(operation_name, kwargs)
File "<redactedPath>env/lib/python3.7/site-packages/botocore/client.py", line 626, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the GetKeyRotationStatus operation: User: arn:aws:sts::<redacted>:assumed-role/<redacted>/<redacted> is not authorized to perform: kms:GetKeyRotationStatus on resource: arn:aws:kms:us-east-1:<redacted>:key/<redacted>
|
botocore.exceptions.ClientError
|
async def _parse_key(self, raw_key):
key_dict = {}
key_dict["id"] = key_dict["name"] = raw_key.get("KeyId")
key_dict["arn"] = raw_key.get("KeyArn")
key_dict["policy"] = raw_key.get("policy")
if "metadata" in raw_key:
key_dict["creation_date"] = (
raw_key["metadata"]["KeyMetadata"]["CreationDate"]
if raw_key["metadata"]["KeyMetadata"]["CreationDate"]
else None
)
key_dict["key_enabled"] = (
False
if raw_key["metadata"]["KeyMetadata"]["KeyState"] == "Disabled"
else True
)
key_dict["description"] = (
raw_key["metadata"]["KeyMetadata"]["Description"]
if len(raw_key["metadata"]["KeyMetadata"]["Description"].strip()) > 0
else None
)
key_dict["origin"] = (
raw_key["metadata"]["KeyMetadata"]["Origin"]
if len(raw_key["metadata"]["KeyMetadata"]["Origin"].strip()) > 0
else None
)
key_dict["key_manager"] = (
raw_key["metadata"]["KeyMetadata"]["KeyManager"]
if len(raw_key["metadata"]["KeyMetadata"]["KeyManager"].strip()) > 0
else None
)
# Only call this on customer managed CMKs, otherwise the AWS set policies might disallow access and it's always
# enabled anyway
if key_dict["origin"] == "AWS_KMS" and key_dict["key_manager"] == "CUSTOMER":
rotation_status = await self.facade.kms.get_key_rotation_status(
self.region, key_dict["id"]
)
key_dict["rotation_enabled"] = rotation_status.get("KeyRotationEnabled", None)
else:
key_dict["rotation_enabled"] = True
key_dict["aliases"] = []
for raw_alias in raw_key.get("aliases", []):
key_dict["aliases"].append(self._parse_alias(raw_alias))
return key_dict["id"], key_dict
|
def _parse_key(self, raw_key):
key_dict = {}
key_dict["id"] = key_dict["name"] = raw_key.get("KeyId")
key_dict["arn"] = raw_key.get("KeyArn")
key_dict["rotation_enabled"] = (
raw_key["rotation_status"]["KeyRotationEnabled"]
if "rotation_status" in raw_key
else None
)
key_dict["policy"] = raw_key.get("policy")
if "metadata" in raw_key:
key_dict["creation_date"] = (
raw_key["metadata"]["KeyMetadata"]["CreationDate"]
if raw_key["metadata"]["KeyMetadata"]["CreationDate"]
else None
)
key_dict["key_enabled"] = (
False
if raw_key["metadata"]["KeyMetadata"]["KeyState"] == "Disabled"
else True
)
key_dict["description"] = (
raw_key["metadata"]["KeyMetadata"]["Description"]
if len(raw_key["metadata"]["KeyMetadata"]["Description"].strip()) > 0
else None
)
key_dict["origin"] = (
raw_key["metadata"]["KeyMetadata"]["Origin"]
if len(raw_key["metadata"]["KeyMetadata"]["Origin"].strip()) > 0
else None
)
key_dict["key_manager"] = (
raw_key["metadata"]["KeyMetadata"]["KeyManager"]
if len(raw_key["metadata"]["KeyMetadata"]["KeyManager"].strip()) > 0
else None
)
key_dict["aliases"] = {}
for raw_alias in raw_key.get("aliases", []):
alias_id, alias = self._parse_alias(raw_alias)
key_dict["aliases"][alias_id] = alias
return key_dict["id"], key_dict
|
https://github.com/nccgroup/ScoutSuite/issues/697
|
Traceback (most recent call last):
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/aws/facade/kms.py", line 41, in _get_and_set_key_rotation_status
lambda: client.get_key_rotation_status(KeyId=key['KeyId']))
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "<redactedPath>/.pyenv/versions/3.7.2/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/aws/facade/kms.py", line 41, in <lambda>
lambda: client.get_key_rotation_status(KeyId=key['KeyId']))
File "<redactedPath>env/lib/python3.7/site-packages/botocore/client.py", line 316, in _api_call
return self._make_api_call(operation_name, kwargs)
File "<redactedPath>env/lib/python3.7/site-packages/botocore/client.py", line 626, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the GetKeyRotationStatus operation: User: arn:aws:sts::<redacted>:assumed-role/<redacted>/<redacted> is not authorized to perform: kms:GetKeyRotationStatus on resource: arn:aws:kms:us-east-1:<redacted>:key/<redacted>
|
botocore.exceptions.ClientError
|
def _parse_alias(self, raw_alias):
alias_dict = {
# all KMS Aliases are prefixed with alias/, so we'll strip that off
"id": get_non_provider_id(raw_alias.get("AliasArn")),
"name": raw_alias.get("AliasName").split("alias/", 1)[-1],
"arn": raw_alias.get("AliasArn"),
"key_id": raw_alias.get("TargetKeyId"),
}
return alias_dict
|
def _parse_alias(self, raw_alias):
alias_dict = {
# all KMS Aliases are prefixed with alias/, so we'll strip that off
"id": get_non_provider_id(raw_alias.get("AliasArn")),
"name": raw_alias.get("AliasName").split("alias/", 1)[-1],
"arn": raw_alias.get("AliasArn"),
"key_id": raw_alias.get("TargetKeyId"),
}
return alias_dict["id"], alias_dict
|
https://github.com/nccgroup/ScoutSuite/issues/697
|
Traceback (most recent call last):
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/aws/facade/kms.py", line 41, in _get_and_set_key_rotation_status
lambda: client.get_key_rotation_status(KeyId=key['KeyId']))
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/utils.py", line 24, in run_concurrently
return await run_function_concurrently(function)
File "<redactedPath>/.pyenv/versions/3.7.2/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "<redactedPath>env/lib/python3.7/site-packages/ScoutSuite/providers/aws/facade/kms.py", line 41, in <lambda>
lambda: client.get_key_rotation_status(KeyId=key['KeyId']))
File "<redactedPath>env/lib/python3.7/site-packages/botocore/client.py", line 316, in _api_call
return self._make_api_call(operation_name, kwargs)
File "<redactedPath>env/lib/python3.7/site-packages/botocore/client.py", line 626, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the GetKeyRotationStatus operation: User: arn:aws:sts::<redacted>:assumed-role/<redacted>/<redacted> is not authorized to perform: kms:GetKeyRotationStatus on resource: arn:aws:kms:us-east-1:<redacted>:key/<redacted>
|
botocore.exceptions.ClientError
|
def _parse_bucket(self, raw_bucket):
bucket_dict = {}
bucket_dict["id"] = get_non_provider_id(raw_bucket.id)
bucket_dict["name"] = raw_bucket.name
bucket_dict["project_id"] = self.project_id
bucket_dict["project_number"] = raw_bucket.project_number
bucket_dict["creation_date"] = raw_bucket.time_created
bucket_dict["location"] = raw_bucket.location
bucket_dict["storage_class"] = raw_bucket.storage_class.lower()
bucket_dict["versioning_enabled"] = raw_bucket.versioning_enabled
bucket_dict["logging_enabled"] = raw_bucket.logging is not None
iam_configuration = raw_bucket.iam_configuration.get(
"uniformBucketLevelAccess", False
) or raw_bucket.iam_configuration.get("bucketPolicyOnly", False)
if iam_configuration:
bucket_dict["uniform_bucket_level_access"] = iam_configuration.get(
"enabled", False
)
else:
print(
"raw_bucket.iam_configuration missing both uniformBucketLevelAccess and bucketPolicyOnly"
)
raise
if bucket_dict["uniform_bucket_level_access"]:
bucket_dict["acls"] = []
bucket_dict["default_object_acl"] = []
else:
bucket_dict["acls"] = list(raw_bucket.acl)
bucket_dict["default_object_acl"] = list(raw_bucket.default_object_acl)
bucket_dict["acl_configuration"] = self._get_cloudstorage_bucket_acl(
raw_bucket
) # FIXME this should be "IAM"
return bucket_dict["id"], bucket_dict
|
def _parse_bucket(self, raw_bucket):
bucket_dict = {}
bucket_dict["id"] = get_non_provider_id(raw_bucket.id)
bucket_dict["name"] = raw_bucket.name
bucket_dict["project_id"] = self.project_id
bucket_dict["project_number"] = raw_bucket.project_number
bucket_dict["creation_date"] = raw_bucket.time_created
bucket_dict["location"] = raw_bucket.location
bucket_dict["storage_class"] = raw_bucket.storage_class.lower()
bucket_dict["versioning_enabled"] = raw_bucket.versioning_enabled
bucket_dict["logging_enabled"] = raw_bucket.logging is not None
iam_configuration = raw_bucket.iam_configuration.get(
"uniformBucketLevelAccess", False
) or raw_bucket.iam_configuration.get("bucketPolicyOnly", False)
if iam_configuration:
bucket_dict["uniform_bucket_level_access"] = policy.get("enabled", False)
else:
print(
"raw_bucket.iam_configuration missing both uniformBucketLevelAccess and bucketPolicyOnly"
)
raise
if bucket_dict["uniform_bucket_level_access"]:
bucket_dict["acls"] = []
bucket_dict["default_object_acl"] = []
else:
bucket_dict["acls"] = list(raw_bucket.acl)
bucket_dict["default_object_acl"] = list(raw_bucket.default_object_acl)
bucket_dict["acl_configuration"] = self._get_cloudstorage_bucket_acl(
raw_bucket
) # FIXME this should be "IAM"
return bucket_dict["id"], bucket_dict
|
https://github.com/nccgroup/ScoutSuite/issues/673
|
2020-03-16` 17:43:42 renzo-latacora-work asyncio[17820] ERROR Task exception was never retrieved
future: <Task finished coro=<Instances.fetch_all() done, defined at /home/user/Documents/scoutsuite/LatacoraScoutSuite/ScoutSuite/ScoutSuite/providers/gcp/resources/gce/instances.py:17> exception=KeyError('source')>
Traceback (most recent call last):
File "/home/user/Documents/scoutsuite/LatacoraScoutSuite/ScoutSuite/ScoutSuite/providers/gcp/resources/gce/instances.py", line 22, in fetch_all
self[instance_id]['disks'].fetch_all()
File "/home/user/Documents/scoutsuite/LatacoraScoutSuite/ScoutSuite/ScoutSuite/providers/gcp/resources/gce/instance_disks.py", line 12, in fetch_all
disk_id, disk = self._parse_disk(raw_disk)
File "/home/user/Documents/scoutsuite/LatacoraScoutSuite/ScoutSuite/ScoutSuite/providers/gcp/resources/gce/disks.py", line 11, in _parse_disk
disk_dict['source_url'] = raw_disk['source']
KeyError: 'source'
|
KeyError
|
def put_cidr_name(current_config, path, current_path, resource_id, callback_args):
"""Add a display name for all known CIDRs."""
if "cidrs" in current_config:
cidr_list = []
for cidr in current_config["cidrs"]:
if type(cidr) == dict:
cidr = cidr["CIDR"]
if cidr in known_cidrs:
cidr_name = known_cidrs[cidr]
else:
cidr_name = get_cidr_name(
cidr,
callback_args["ip_ranges"],
callback_args["ip_ranges_name_key"],
)
known_cidrs[cidr] = cidr_name
cidr_list.append({"CIDR": cidr, "CIDRName": cidr_name})
current_config["cidrs"] = cidr_list
|
def put_cidr_name(
aws_config, current_config, path, current_path, resource_id, callback_args
):
"""Add a display name for all known CIDRs."""
if "cidrs" in current_config:
cidr_list = []
for cidr in current_config["cidrs"]:
if type(cidr) == dict:
cidr = cidr["CIDR"]
if cidr in known_cidrs:
cidr_name = known_cidrs[cidr]
else:
cidr_name = get_cidr_name(
cidr,
callback_args["ip_ranges"],
callback_args["ip_ranges_name_key"],
)
known_cidrs[cidr] = cidr_name
cidr_list.append({"CIDR": cidr, "CIDRName": cidr_name})
current_config["cidrs"] = cidr_list
|
https://github.com/nccgroup/ScoutSuite/issues/629
|
scout aws --ip-ranges ./ip-ranges-default2.json --ip-ranges-name-key name
scout[78207] INFO Fetching resources for the ACM service
scout[78207] INFO Fetching resources for the Lambda service
scout[78207] INFO Fetching resources for the CloudFormation service
scout[78207] INFO Fetching resources for the CloudTrail service
scout[78207] INFO Fetching resources for the CloudWatch service
scout[78207] INFO Fetching resources for the Config service
scout[78207] INFO Fetching resources for the Direct Connect service
scout[78207] INFO Fetching resources for the EC2 service
scout[78207] INFO Fetching resources for the EFS service
scout[78207] INFO Fetching resources for the ElastiCache service
scout[78207] INFO Fetching resources for the ELB service
scout[78207] INFO Fetching resources for the ELBv2 service
scout[78207] INFO Fetching resources for the EMR service
scout[78207] INFO Fetching resources for the IAM service
scout[78207] INFO Fetching resources for the RDS service
scout[78207] INFO Fetching resources for the RedShift service
scout[78207] INFO Fetching resources for the Route53 service
scout[78207] INFO Fetching resources for the S3 service
scout[78207] INFO Fetching resources for the SES service
scout[78207] INFO Fetching resources for the SNS service
scout[78207] INFO Fetching resources for the SQS service
scout[78207] INFO Fetching resources for the VPC service
scout[78207] ERROR provider.py L315: put_cidr_name() missing 1 required positional argument: 'callback_args'
Traceback (most recent call last):
File "/Users/xxxx.local/share/virtualenvs/security-DQzaLIPv/lib/python3.7/site-packages/ScoutSuite/providers/base/provider.py", line 315, in _go_to_and_do
callback(current_config_key[value], path, current_path, value, callback_args)
TypeError: put_cidr_name() missing 1 required positional argument: 'callback_args'
<< repeated many times >>
scout[78207] INFO Running rule engine
scout[78207] INFO Applying display filters
cat ip-ranges-default2.json
{
"createDate": "2020-01-30-10-50-40",
"prefixes": [
{
"ip_prefix": "10.4.163.0/24",
"name": "My Description"
}
]
}
|
TypeError
|
def _parse_instance(self, raw_instance):
instance_dict = {}
instance_dict["id"] = get_non_provider_id(raw_instance["name"])
instance_dict["project_id"] = self.project_id
instance_dict["name"] = raw_instance["name"]
instance_dict["description"] = self._get_description(raw_instance)
instance_dict["creation_timestamp"] = raw_instance["creationTimestamp"]
instance_dict["zone"] = raw_instance["zone"].split("/")[-1]
instance_dict["tags"] = raw_instance["tags"]
instance_dict["status"] = raw_instance["status"]
instance_dict["zone_url_"] = raw_instance["zone"]
instance_dict["network_interfaces"] = raw_instance["networkInterfaces"]
instance_dict["service_accounts"] = raw_instance.get("serviceAccounts", [])
instance_dict["deletion_protection_enabled"] = raw_instance["deletionProtection"]
instance_dict["block_project_ssh_keys_enabled"] = (
self._is_block_project_ssh_keys_enabled(raw_instance)
)
instance_dict["oslogin_enabled"] = self._is_oslogin_enabled(raw_instance)
instance_dict["ip_forwarding_enabled"] = raw_instance["canIpForward"]
instance_dict["serial_port_enabled"] = self._is_serial_port_enabled(raw_instance)
instance_dict["has_full_access_cloud_apis"] = (
self._has_full_access_to_all_cloud_apis(raw_instance)
)
instance_dict["disks"] = InstanceDisks(self.facade, raw_instance)
return instance_dict["id"], instance_dict
|
def _parse_instance(self, raw_instance):
instance_dict = {}
instance_dict["id"] = get_non_provider_id(raw_instance["name"])
instance_dict["project_id"] = self.project_id
instance_dict["name"] = raw_instance["name"]
instance_dict["description"] = self._get_description(raw_instance)
instance_dict["creation_timestamp"] = raw_instance["creationTimestamp"]
instance_dict["zone"] = raw_instance["zone"].split("/")[-1]
instance_dict["tags"] = raw_instance["tags"]
instance_dict["status"] = raw_instance["status"]
instance_dict["zone_url_"] = raw_instance["zone"]
instance_dict["network_interfaces"] = raw_instance["networkInterfaces"]
instance_dict["service_accounts"] = raw_instance["serviceAccounts"]
instance_dict["deletion_protection_enabled"] = raw_instance["deletionProtection"]
instance_dict["block_project_ssh_keys_enabled"] = (
self._is_block_project_ssh_keys_enabled(raw_instance)
)
instance_dict["oslogin_enabled"] = self._is_oslogin_enabled(raw_instance)
instance_dict["ip_forwarding_enabled"] = raw_instance["canIpForward"]
instance_dict["serial_port_enabled"] = self._is_serial_port_enabled(raw_instance)
instance_dict["has_full_access_cloud_apis"] = (
self._has_full_access_to_all_cloud_apis(raw_instance)
)
instance_dict["disks"] = InstanceDisks(self.facade, raw_instance)
return instance_dict["id"], instance_dict
|
https://github.com/nccgroup/ScoutSuite/issues/396
|
$ scout gcp --user-account
Task exception was never retrieved
future: <Task finished coro=<Instances.fetch_all() done, defined at /home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py:17> exception=KeyError('serviceAccounts')>
Traceback (most recent call last):
File "/home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py", line 20, in fetch_all
instance_id, instance = self._parse_instance(raw_instance)
File "/home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py", line 36, in _parse_instance
instance_dict['service_accounts'] = raw_instance['serviceAccounts']
KeyError: 'serviceAccounts'
|
KeyError
|
def _has_full_access_to_all_cloud_apis(self, raw_instance):
full_access_scope = "https://www.googleapis.com/auth/cloud-platform"
return any(
full_access_scope in service_account["scopes"]
for service_account in raw_instance.get("serviceAccounts", [])
)
|
def _has_full_access_to_all_cloud_apis(self, raw_instance):
full_access_scope = "https://www.googleapis.com/auth/cloud-platform"
return any(
full_access_scope in service_account["scopes"]
for service_account in raw_instance["serviceAccounts"]
)
|
https://github.com/nccgroup/ScoutSuite/issues/396
|
$ scout gcp --user-account
Task exception was never retrieved
future: <Task finished coro=<Instances.fetch_all() done, defined at /home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py:17> exception=KeyError('serviceAccounts')>
Traceback (most recent call last):
File "/home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py", line 20, in fetch_all
instance_id, instance = self._parse_instance(raw_instance)
File "/home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py", line 36, in _parse_instance
instance_dict['service_accounts'] = raw_instance['serviceAccounts']
KeyError: 'serviceAccounts'
|
KeyError
|
def _parse_instance(self, raw_instance):
instance_dict = {}
instance_dict["id"] = get_non_provider_id(raw_instance["name"])
instance_dict["project_id"] = self.project_id
instance_dict["name"] = raw_instance["name"]
instance_dict["description"] = self._get_description(raw_instance)
instance_dict["creation_timestamp"] = raw_instance["creationTimestamp"]
instance_dict["zone"] = raw_instance["zone"].split("/")[-1]
instance_dict["tags"] = raw_instance["tags"]
instance_dict["status"] = raw_instance["status"]
instance_dict["zone_url_"] = raw_instance["zone"]
instance_dict["network_interfaces"] = raw_instance["networkInterfaces"]
instance_dict["service_accounts"] = raw_instance.get("serviceAccounts", [])
instance_dict["deletion_protection_enabled"] = raw_instance["deletionProtection"]
instance_dict["block_project_ssh_keys_enabled"] = (
self._is_block_project_ssh_keys_enabled(raw_instance)
)
instance_dict["oslogin_enabled"] = self._is_oslogin_enabled(raw_instance)
instance_dict["ip_forwarding_enabled"] = raw_instance.get("canIpForward", False)
instance_dict["serial_port_enabled"] = self._is_serial_port_enabled(raw_instance)
instance_dict["has_full_access_cloud_apis"] = (
self._has_full_access_to_all_cloud_apis(raw_instance)
)
instance_dict["disks"] = InstanceDisks(self.facade, raw_instance)
return instance_dict["id"], instance_dict
|
def _parse_instance(self, raw_instance):
instance_dict = {}
instance_dict["id"] = get_non_provider_id(raw_instance["name"])
instance_dict["project_id"] = self.project_id
instance_dict["name"] = raw_instance["name"]
instance_dict["description"] = self._get_description(raw_instance)
instance_dict["creation_timestamp"] = raw_instance["creationTimestamp"]
instance_dict["zone"] = raw_instance["zone"].split("/")[-1]
instance_dict["tags"] = raw_instance["tags"]
instance_dict["status"] = raw_instance["status"]
instance_dict["zone_url_"] = raw_instance["zone"]
instance_dict["network_interfaces"] = raw_instance["networkInterfaces"]
instance_dict["service_accounts"] = raw_instance.get("serviceAccounts", [])
instance_dict["deletion_protection_enabled"] = raw_instance["deletionProtection"]
instance_dict["block_project_ssh_keys_enabled"] = (
self._is_block_project_ssh_keys_enabled(raw_instance)
)
instance_dict["oslogin_enabled"] = self._is_oslogin_enabled(raw_instance)
instance_dict["ip_forwarding_enabled"] = raw_instance["canIpForward"]
instance_dict["serial_port_enabled"] = self._is_serial_port_enabled(raw_instance)
instance_dict["has_full_access_cloud_apis"] = (
self._has_full_access_to_all_cloud_apis(raw_instance)
)
instance_dict["disks"] = InstanceDisks(self.facade, raw_instance)
return instance_dict["id"], instance_dict
|
https://github.com/nccgroup/ScoutSuite/issues/396
|
$ scout gcp --user-account
Task exception was never retrieved
future: <Task finished coro=<Instances.fetch_all() done, defined at /home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py:17> exception=KeyError('serviceAccounts')>
Traceback (most recent call last):
File "/home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py", line 20, in fetch_all
instance_id, instance = self._parse_instance(raw_instance)
File "/home/user/.local/lib/python3.7/site-packages/ScoutSuite/providers/gcp/resources/gce/instances.py", line 36, in _parse_instance
instance_dict['service_accounts'] = raw_instance['serviceAccounts']
KeyError: 'serviceAccounts'
|
KeyError
|
def __init__(self, metadata=None, thread_config=4, **kwargs):
self.cloudformation = CloudFormationConfig(
metadata["management"]["cloudformation"], thread_config
)
self.cloudtrail = CloudTrailConfig(
metadata["management"]["cloudtrail"], thread_config
)
self.cloudwatch = CloudWatchConfig(
metadata["management"]["cloudwatch"], thread_config
)
self.directconnect = DirectConnectConfig(
metadata["network"]["directconnect"], thread_config
)
self.ec2 = EC2Config(metadata["compute"]["ec2"], thread_config)
self.efs = EFSConfig(metadata["storage"]["efs"], thread_config)
self.elasticache = ElastiCacheConfig(
metadata["database"]["elasticache"], thread_config
)
self.elb = ELBConfig(metadata["compute"]["elb"], thread_config)
self.elbv2 = ELBv2Config(metadata["compute"]["elbv2"], thread_config)
self.emr = EMRConfig(metadata["analytics"]["emr"], thread_config)
self.iam = IAMConfig(thread_config)
self.kms = KMSConfig(metadata["security"]["kms"], thread_config)
self.awslambda = LambdaConfig(metadata["compute"]["awslambda"], thread_config)
self.redshift = RedshiftConfig(metadata["database"]["redshift"], thread_config)
self.rds = RDSConfig(metadata["database"]["rds"], thread_config)
self.route53 = Route53Config(thread_config)
self.route53domains = Route53DomainsConfig(thread_config)
self.s3 = S3Config(thread_config)
self.ses = SESConfig(metadata["messaging"]["ses"], thread_config)
self.sns = SNSConfig(metadata["messaging"]["sns"], thread_config)
self.sqs = SQSConfig(metadata["messaging"]["sqs"], thread_config)
self.vpc = VPCConfig(metadata["network"]["vpc"], thread_config)
try:
self.dynamodb = DynamoDBConfig(metadata["database"]["dynamodb"], thread_config)
except NameError as e:
pass
|
def __init__(self, metadata=None, thread_config=4, **kwargs):
self.cloudformation = CloudFormationConfig(
metadata["management"]["cloudformation"], thread_config
)
self.cloudtrail = CloudTrailConfig(
metadata["management"]["cloudtrail"], thread_config
)
self.cloudwatch = CloudWatchConfig(
metadata["management"]["cloudwatch"], thread_config
)
self.directconnect = DirectConnectConfig(
metadata["network"]["directconnect"], thread_config
)
self.ec2 = EC2Config(metadata["compute"]["ec2"], thread_config)
self.efs = EFSConfig(metadata["storage"]["efs"], thread_config)
self.elasticache = ElastiCacheConfig(
metadata["database"]["elasticache"], thread_config
)
self.elb = ELBConfig(metadata["compute"]["elb"], thread_config)
self.elbv2 = ELBv2Config(metadata["compute"]["elbv2"], thread_config)
self.emr = EMRConfig(metadata["analytics"]["emr"], thread_config)
self.iam = IAMConfig(thread_config)
self.kms = KMSConfig(metadata["security"]["kms"], thread_config)
self.awslambda = LambdaConfig(metadata["compute"]["awslambda"], thread_config)
self.redshift = RedshiftConfig(metadata["database"]["redshift"], thread_config)
self.rds = RDSConfig(metadata["database"]["rds"], thread_config)
self.route53 = Route53Config(thread_config)
self.route53domains = Route53DomainsConfig(thread_config)
self.s3 = S3Config(thread_config)
self.ses = SESConfig(metadata["messaging"]["ses"], thread_config)
self.sns = SNSConfig(metadata["messaging"]["sns"], thread_config)
self.sqs = SQSConfig(metadata["messaging"]["sqs"], thread_config)
self.vpc = VPCConfig(metadata["network"]["vpc"], thread_config)
|
https://github.com/nccgroup/ScoutSuite/issues/24
|
File '/report/inc-awsconfig/exceptions.js' already exists. Do you want to overwrite it (y/n)?
EOF when reading a lineCreating /report/report.html ...
File '/report/report.html' already exists. Do you want to overwrite it (y/n)? Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/AWSScout2/output/utils.py", line 22, in prompt_4_yes_no
choice = raw_input().lower()
NameError: name 'raw_input' is not defined
|
NameError
|
def preprocessing(self, ip_ranges=None, ip_ranges_name_key=None):
"""
Tweak the AWS config to match cross-service resources and clean any fetching artifacts
:param ip_ranges:
:param ip_ranges_name_key:
:return: None
"""
ip_ranges = [] if ip_ranges is None else ip_ranges
self._map_all_sgs()
self._map_all_subnets()
self._set_emr_vpc_ids()
# self.parse_elb_policies()
# Various data processing calls
self._check_ec2_zone_distribution()
self._add_security_group_name_to_ec2_grants()
self._add_last_snapshot_date_to_ec2_volumes()
self._process_cloudtrail_trails(self.services["cloudtrail"])
self._add_cidr_display_name(ip_ranges, ip_ranges_name_key)
self._merge_route53_and_route53domains()
self._match_instances_and_roles()
self._match_iam_policies_and_buckets()
super(AWSProvider, self).preprocessing()
|
def preprocessing(self, ip_ranges=None, ip_ranges_name_key=None):
"""
Tweak the AWS config to match cross-service resources and clean any fetching artifacts
:param ip_ranges:
:param ip_ranges_name_key:
:return: None
"""
ip_ranges = [] if ip_ranges is None else ip_ranges
self._map_all_sgs()
self._map_all_subnets()
self._set_emr_vpc_ids()
# self.parse_elb_policies()
# Various data processing calls
self._add_security_group_name_to_ec2_grants()
self._add_last_snapshot_date_to_ec2_volumes()
self._process_cloudtrail_trails(self.services["cloudtrail"])
self._add_cidr_display_name(ip_ranges, ip_ranges_name_key)
self._merge_route53_and_route53domains()
self._match_instances_and_roles()
self._match_iam_policies_and_buckets()
super(AWSProvider, self).preprocessing()
|
https://github.com/nccgroup/ScoutSuite/issues/24
|
File '/report/inc-awsconfig/exceptions.js' already exists. Do you want to overwrite it (y/n)?
EOF when reading a lineCreating /report/report.html ...
File '/report/report.html' already exists. Do you want to overwrite it (y/n)? Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/AWSScout2/output/utils.py", line 22, in prompt_4_yes_no
choice = raw_input().lower()
NameError: name 'raw_input' is not defined
|
NameError
|
def parse_instance(self, global_params, region, reservation):
"""
Parse a single EC2 instance
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param instance: Cluster
"""
for i in reservation["Instances"]:
instance = {}
vpc_id = i["VpcId"] if "VpcId" in i and i["VpcId"] else ec2_classic
manage_dictionary(self.vpcs, vpc_id, VPCConfig(self.vpc_resource_types))
instance["reservation_id"] = reservation["ReservationId"]
instance["id"] = i["InstanceId"]
instance["monitoring_enabled"] = i["Monitoring"]["State"] == "enabled"
get_name(i, instance, "InstanceId")
get_keys(
i,
instance,
[
"KeyName",
"LaunchTime",
"InstanceType",
"State",
"IamInstanceProfile",
"SubnetId",
],
)
# Network interfaces & security groups
manage_dictionary(instance, "network_interfaces", {})
for eni in i["NetworkInterfaces"]:
nic = {}
get_keys(
eni,
nic,
[
"Association",
"Groups",
"PrivateIpAddresses",
"SubnetId",
"Ipv6Addresses",
],
)
instance["network_interfaces"][eni["NetworkInterfaceId"]] = nic
self.vpcs[vpc_id].instances[i["InstanceId"]] = instance
|
def parse_instance(self, global_params, region, reservation):
"""
Parse a single EC2 instance
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param instance: Cluster
"""
for i in reservation["Instances"]:
instance = {}
vpc_id = i["VpcId"] if "VpcId" in i and i["VpcId"] else ec2_classic
manage_dictionary(self.vpcs, vpc_id, VPCConfig(self.vpc_resource_types))
instance["reservation_id"] = reservation["ReservationId"]
instance["id"] = i["InstanceId"]
get_name(i, instance, "InstanceId")
get_keys(
i,
instance,
[
"KeyName",
"LaunchTime",
"InstanceType",
"State",
"IamInstanceProfile",
"SubnetId",
],
)
# Network interfaces & security groups
manage_dictionary(instance, "network_interfaces", {})
for eni in i["NetworkInterfaces"]:
nic = {}
get_keys(
eni,
nic,
[
"Association",
"Groups",
"PrivateIpAddresses",
"SubnetId",
"Ipv6Addresses",
],
)
instance["network_interfaces"][eni["NetworkInterfaceId"]] = nic
self.vpcs[vpc_id].instances[i["InstanceId"]] = instance
|
https://github.com/nccgroup/ScoutSuite/issues/24
|
File '/report/inc-awsconfig/exceptions.js' already exists. Do you want to overwrite it (y/n)?
EOF when reading a lineCreating /report/report.html ...
File '/report/report.html' already exists. Do you want to overwrite it (y/n)? Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/AWSScout2/output/utils.py", line 22, in prompt_4_yes_no
choice = raw_input().lower()
NameError: name 'raw_input' is not defined
|
NameError
|
def __init__(self, metadata=None, thread_config=4, **kwargs):
self.storageaccounts = StorageAccountsConfig(thread_config=thread_config)
self.monitor = MonitorConfig(thread_config=thread_config)
self.sqldatabase = SQLDatabaseConfig(thread_config=thread_config)
self.securitycenter = SecurityCenterConfig(thread_config=thread_config)
self.network = NetworkConfig(thread_config=thread_config)
self.keyvault = KeyVaultConfig(thread_config=thread_config)
try:
self.appgateway = AppGatewayConfig(thread_config=thread_config)
except NameError:
pass
try:
self.rediscache = RedisCacheConfig(thread_config=thread_config)
except NameError:
pass
try:
self.appservice = AppServiceConfig(thread_config=thread_config)
except NameError:
pass
try:
self.loadbalancer = LoadBalancerConfig(thread_config=thread_config)
except NameError:
pass
|
def __init__(self, metadata=None, thread_config=4, **kwargs):
self.storageaccounts = StorageAccountsConfig(thread_config=thread_config)
self.monitor = MonitorConfig(thread_config=thread_config)
self.sqldatabase = SQLDatabaseConfig(thread_config=thread_config)
self.securitycenter = SecurityCenterConfig(thread_config=thread_config)
self.keyvault = KeyVaultConfig(thread_config=thread_config)
try:
self.appgateway = AppGatewayConfig(thread_config=thread_config)
except NameError:
pass
try:
self.rediscache = RedisCacheConfig(thread_config=thread_config)
except NameError:
pass
try:
self.loadbalancer = LoadBalancerConfig(thread_config=thread_config)
except NameError:
pass
|
https://github.com/nccgroup/ScoutSuite/issues/24
|
File '/report/inc-awsconfig/exceptions.js' already exists. Do you want to overwrite it (y/n)?
EOF when reading a lineCreating /report/report.html ...
File '/report/report.html' already exists. Do you want to overwrite it (y/n)? Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/AWSScout2/output/utils.py", line 22, in prompt_4_yes_no
choice = raw_input().lower()
NameError: name 'raw_input' is not defined
|
NameError
|
def azure_connect_service(service, credentials, region_name=None):
try:
if service == "storageaccounts":
return StorageManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "monitor":
return MonitorManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "sqldatabase":
return SqlManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "keyvault":
return KeyVaultManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "appgateway":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "network":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "rediscache":
return RedisManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "securitycenter":
return SecurityCenter(
credentials.credentials, credentials.subscription_id, ""
)
elif service == "appservice":
return WebSiteManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "loadbalancer":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
else:
printException("Service %s not supported" % service)
return None
except Exception as e:
printException(e)
return None
|
def azure_connect_service(service, credentials, region_name=None):
try:
if service == "storageaccounts":
return StorageManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "monitor":
return MonitorManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "sqldatabase":
return SqlManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "keyvault":
return KeyVaultManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "appgateway":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "rediscache":
return RedisManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "securitycenter":
return SecurityCenter(
credentials.credentials, credentials.subscription_id, ""
)
elif service == "loadbalancer":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
else:
printException("Service %s not supported" % service)
return None
except Exception as e:
printException(e)
return None
|
https://github.com/nccgroup/ScoutSuite/issues/24
|
File '/report/inc-awsconfig/exceptions.js' already exists. Do you want to overwrite it (y/n)?
EOF when reading a lineCreating /report/report.html ...
File '/report/report.html' already exists. Do you want to overwrite it (y/n)? Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/AWSScout2/output/utils.py", line 22, in prompt_4_yes_no
choice = raw_input().lower()
NameError: name 'raw_input' is not defined
|
NameError
|
def __init__(self, metadata=None, thread_config=4, **kwargs):
self.storageaccounts = StorageAccountsConfig(thread_config=thread_config)
self.monitor = MonitorConfig(thread_config=thread_config)
self.sqldatabase = SQLDatabaseConfig(thread_config=thread_config)
self.securitycenter = SecurityCenterConfig(thread_config=thread_config)
self.network = NetworkConfig(thread_config=thread_config)
self.keyvault = KeyVaultConfig(thread_config=thread_config)
try:
self.appgateway = AppGatewayConfig(thread_config=thread_config)
except NameError:
pass
try:
self.rediscache = RedisCacheConfig(thread_config=thread_config)
except NameError:
pass
try:
self.appservice = AppServiceConfig(thread_config=thread_config)
except NameError:
pass
try:
self.loadbalancer = LoadBalancerConfig(thread_config=thread_config)
except NameError:
pass
|
def __init__(self, metadata=None, thread_config=4, **kwargs):
self.storageaccounts = StorageAccountsConfig(thread_config=thread_config)
self.monitor = MonitorConfig(thread_config=thread_config)
self.sqldatabase = SQLDatabaseConfig(thread_config=thread_config)
self.securitycenter = SecurityCenterConfig(thread_config=thread_config)
self.network = NetworkConfig(thread_config=thread_config)
self.keyvault = KeyVaultConfig(thread_config=thread_config)
try:
self.appgateway = AppGatewayConfig(thread_config=thread_config)
except NameError:
pass
try:
self.rediscache = RedisCacheConfig(thread_config=thread_config)
except NameError:
pass
try:
self.appservice = AppServiceConfig(thread_config=thread_config)
except NameError:
pass
|
https://github.com/nccgroup/ScoutSuite/issues/24
|
File '/report/inc-awsconfig/exceptions.js' already exists. Do you want to overwrite it (y/n)?
EOF when reading a lineCreating /report/report.html ...
File '/report/report.html' already exists. Do you want to overwrite it (y/n)? Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/AWSScout2/output/utils.py", line 22, in prompt_4_yes_no
choice = raw_input().lower()
NameError: name 'raw_input' is not defined
|
NameError
|
def azure_connect_service(service, credentials, region_name=None):
try:
if service == "storageaccounts":
return StorageManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "monitor":
return MonitorManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "sqldatabase":
return SqlManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "keyvault":
return KeyVaultManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "appgateway":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "network":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "rediscache":
return RedisManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "securitycenter":
return SecurityCenter(
credentials.credentials, credentials.subscription_id, ""
)
elif service == "appservice":
return WebSiteManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "loadbalancer":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
else:
printException("Service %s not supported" % service)
return None
except Exception as e:
printException(e)
return None
|
def azure_connect_service(service, credentials, region_name=None):
try:
if service == "storageaccounts":
return StorageManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "monitor":
return MonitorManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "sqldatabase":
return SqlManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "keyvault":
return KeyVaultManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "appgateway":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "network":
return NetworkManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "rediscache":
return RedisManagementClient(
credentials.credentials, credentials.subscription_id
)
elif service == "securitycenter":
return SecurityCenter(
credentials.credentials, credentials.subscription_id, ""
)
elif service == "appservice":
return WebSiteManagementClient(
credentials.credentials, credentials.subscription_id
)
else:
printException("Service %s not supported" % service)
return None
except Exception as e:
printException(e)
return None
|
https://github.com/nccgroup/ScoutSuite/issues/24
|
File '/report/inc-awsconfig/exceptions.js' already exists. Do you want to overwrite it (y/n)?
EOF when reading a lineCreating /report/report.html ...
File '/report/report.html' already exists. Do you want to overwrite it (y/n)? Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/AWSScout2/output/utils.py", line 22, in prompt_4_yes_no
choice = raw_input().lower()
NameError: name 'raw_input' is not defined
|
NameError
|
def output(self, outs, msg, display_id, cell_index):
if self.clear_before_next_output:
self.outputs = []
self.clear_before_next_output = False
self.parent_header = msg["parent_header"]
content = msg["content"]
if "data" not in content:
output = {
"output_type": "stream",
"text": content["text"],
"name": content["name"],
}
else:
data = content["data"]
output = {"output_type": "display_data", "data": data, "metadata": {}}
if self.outputs:
# try to coalesce/merge output text
last_output = self.outputs[-1]
if (
last_output["output_type"] == "stream"
and output["output_type"] == "stream"
and last_output["name"] == output["name"]
):
last_output["text"] += output["text"]
else:
self.outputs.append(output)
else:
self.outputs.append(output)
self.sync_state()
if hasattr(self.executor, "widget_state"):
# sync the state to the nbconvert state as well, since that is used for testing
self.executor.widget_state[self.comm_id]["outputs"] = self.outputs
|
def output(self, outs, msg, display_id, cell_index):
if self.clear_before_next_output:
self.outputs = []
self.clear_before_next_output = False
self.parent_header = msg["parent_header"]
content = msg["content"]
if "data" not in content:
output = {
"output_type": "stream",
"text": content["text"],
"name": content["name"],
}
else:
data = content["data"]
output = {"output_type": "display_data", "data": data, "metadata": {}}
self.outputs.append(output)
self.sync_state()
if hasattr(self.executor, "widget_state"):
# sync the state to the nbconvert state as well, since that is used for testing
self.executor.widget_state[self.comm_id]["outputs"] = self.outputs
|
https://github.com/voila-dashboards/voila/issues/355
|
Traceback (most recent call last):
...
File "/opt/anaconda3/lib/python3.7/site-packages/voila/execute.py", line 79, in set_state
del self.executor.output_hook[self.msg_id]
KeyError: 'e7108564-b1a38beaf451e1c7095357b2'
|
KeyError
|
def set_state(self, state):
if "msg_id" in state:
msg_id = state.get("msg_id")
if msg_id:
self.executor.register_output_hook(msg_id, self)
self.msg_id = msg_id
else:
self.executor.remove_output_hook(self.msg_id, self)
self.msg_id = msg_id
|
def set_state(self, state):
if "msg_id" in state:
msg_id = state.get("msg_id")
if msg_id:
self.executor.output_hook[msg_id] = self
self.msg_id = msg_id
else:
del self.executor.output_hook[self.msg_id]
self.msg_id = msg_id
|
https://github.com/voila-dashboards/voila/issues/355
|
Traceback (most recent call last):
...
File "/opt/anaconda3/lib/python3.7/site-packages/voila/execute.py", line 79, in set_state
del self.executor.output_hook[self.msg_id]
KeyError: 'e7108564-b1a38beaf451e1c7095357b2'
|
KeyError
|
def preprocess(self, nb, resources, km=None):
self.output_hook_stack = collections.defaultdict(
list
) # maps to list of hooks, where the last is used
self.output_objects = {}
try:
result = super(VoilaExecutePreprocessor, self).preprocess(
nb, resources=resources, km=km
)
except CellExecutionError as e:
self.log.error(e)
result = (nb, resources)
return result
|
def preprocess(self, nb, resources, km=None):
self.output_hook = {}
self.output_objects = {}
try:
result = super(VoilaExecutePreprocessor, self).preprocess(
nb, resources=resources, km=km
)
except CellExecutionError as e:
self.log.error(e)
result = (nb, resources)
return result
|
https://github.com/voila-dashboards/voila/issues/355
|
Traceback (most recent call last):
...
File "/opt/anaconda3/lib/python3.7/site-packages/voila/execute.py", line 79, in set_state
del self.executor.output_hook[self.msg_id]
KeyError: 'e7108564-b1a38beaf451e1c7095357b2'
|
KeyError
|
def output(self, outs, msg, display_id, cell_index):
parent_msg_id = msg["parent_header"].get("msg_id")
if self.output_hook_stack[parent_msg_id]:
hook = self.output_hook_stack[parent_msg_id][-1]
hook.output(outs, msg, display_id, cell_index)
return
super(VoilaExecutePreprocessor, self).output(outs, msg, display_id, cell_index)
|
def output(self, outs, msg, display_id, cell_index):
parent_msg_id = msg["parent_header"].get("msg_id")
if parent_msg_id in self.output_hook:
self.output_hook[parent_msg_id].output(outs, msg, display_id, cell_index)
return
super(VoilaExecutePreprocessor, self).output(outs, msg, display_id, cell_index)
|
https://github.com/voila-dashboards/voila/issues/355
|
Traceback (most recent call last):
...
File "/opt/anaconda3/lib/python3.7/site-packages/voila/execute.py", line 79, in set_state
del self.executor.output_hook[self.msg_id]
KeyError: 'e7108564-b1a38beaf451e1c7095357b2'
|
KeyError
|
def clear_output(self, outs, msg, cell_index):
parent_msg_id = msg["parent_header"].get("msg_id")
if self.output_hook_stack[parent_msg_id]:
hook = self.output_hook_stack[parent_msg_id][-1]
hook.clear_output(outs, msg, cell_index)
return
super(VoilaExecutePreprocessor, self).clear_output(outs, msg, cell_index)
|
def clear_output(self, outs, msg, cell_index):
parent_msg_id = msg["parent_header"].get("msg_id")
if parent_msg_id in self.output_hook:
self.output_hook[parent_msg_id].clear_output(outs, msg, cell_index)
return
super(VoilaExecutePreprocessor, self).clear_output(outs, msg, cell_index)
|
https://github.com/voila-dashboards/voila/issues/355
|
Traceback (most recent call last):
...
File "/opt/anaconda3/lib/python3.7/site-packages/voila/execute.py", line 79, in set_state
del self.executor.output_hook[self.msg_id]
KeyError: 'e7108564-b1a38beaf451e1c7095357b2'
|
KeyError
|
def advanced_settings():
"""Track the existence of <cleanonupdate>true</cleanonupdate>
It is incompatible with plugin paths.
"""
if settings("useDirectPaths") != "0":
return
path = xbmc.translatePath("special://profile/")
file = os.path.join(path, "advancedsettings.xml")
try:
xml = etree.parse(file).getroot()
except Exception:
return
video = xml.find("videolibrary")
if video is not None:
cleanonupdate = video.find("cleanonupdate")
if cleanonupdate is not None and cleanonupdate.text == "true":
LOG.warning("cleanonupdate disabled")
video.remove(cleanonupdate)
tree = etree.ElementTree(xml)
tree.write(file)
dialog("ok", "{jellyfin}", translate(33097))
xbmc.executebuiltin("RestartApp")
return True
|
def advanced_settings():
"""Track the existence of <cleanonupdate>true</cleanonupdate>
It is incompatible with plugin paths.
"""
if settings("useDirectPaths") != "0":
return
path = xbmc.translatePath("special://profile/")
file = os.path.join(path, "advancedsettings.xml")
try:
xml = etree.parse(file).getroot()
except Exception:
return
video = xml.find("videolibrary")
if video is not None:
cleanonupdate = video.find("cleanonupdate")
if cleanonupdate is not None and cleanonupdate.text == "true":
LOG.warning("cleanonupdate disabled")
video.remove(cleanonupdate)
tree = etree.ElementTree(xml)
tree.write(path)
dialog("ok", "{jellyfin}", translate(33097))
xbmc.executebuiltin("RestartApp")
return True
|
https://github.com/jellyfin/jellyfin-kodi/issues/470
|
2021-02-14 03:15:59.646 T:1455395040 NOTICE: JELLYFIN.library -> ERROR::jellyfin_kodi/library.py:319 [Errno 21] Is a directory: u'/home/osmc/.kodi/userdata/'
Traceback (most recent call last):
File "jellyfin_kodi/library.py", line 315, in startup
sync.libraries()
File "jellyfin_kodi/full_sync.py", line 100, in libraries
if not xmls.advanced_settings() and self.sync['Libraries']:
File "jellyfin_kodi/helper/xmls.py", line 130, in advanced_settings
tree.write(path)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 802, in write
file = open(file_or_filename, "wb")
IOError: [Errno 21] Is a directory: u'/home/osmc/.kodi/userdata/'
|
IOError
|
def _add_editcontrol(self, x, y, height, width, password=False):
kwargs = dict(
label="",
font="font13",
textColor="FF00A4DC",
disabledColor="FF888888",
focusTexture="-",
noFocusTexture="-",
)
# TODO: Kodi 17 compat removal cleanup
if kodi_version() < 18:
kwargs["isPassword"] = password
control = xbmcgui.ControlEdit(0, 0, 0, 0, **kwargs)
control.setPosition(x, y)
control.setHeight(height)
control.setWidth(width)
self.addControl(control)
# setType has no effect before the control is added to a window
# TODO: Kodi 17 compat removal cleanup
if password and not kodi_version() < 18:
control.setType(xbmcgui.INPUT_TYPE_PASSWORD, "Please enter password")
return control
|
def _add_editcontrol(self, x, y, height, width, password=False):
kwargs = dict(
label="User",
font="font13",
textColor="FF00A4DC",
disabledColor="FF888888",
focusTexture="-",
noFocusTexture="-",
)
# TODO: Kodi 17 compat removal cleanup
if kodi_version() < 18:
kwargs["isPassword"] = password
control = xbmcgui.ControlEdit(0, 0, 0, 0, **kwargs)
control.setPosition(x, y)
control.setHeight(height)
control.setWidth(width)
self.addControl(control)
# setType has no effect before the control is added to a window
# TODO: Kodi 17 compat removal cleanup
if password and not kodi_version() < 18:
control.setType(xbmcgui.INPUT_TYPE_PASSWORD, "Please enter password")
return control
|
https://github.com/jellyfin/jellyfin-kodi/issues/428
|
2020-11-20 11:12:04.823 T:29417 INFO <general>: JELLYFIN.database -> ERROR::jellyfin_kodi/database/__init__.py:163 type: <class 'sqlite3.OperationalError'> value: no such column: strFanart
2020-11-20 11:12:04.839 T:29417 INFO <general>: JELLYFIN.database -> ERROR::jellyfin_kodi/database/__init__.py:163 type: <class 'sqlite3.OperationalError'> value: no such column: strFanart
2020-11-20 11:12:04.852 T:29246 INFO <general>: Loading skin file: DialogConfirm.xml, load type: KEEP_IN_MEMORY
2020-11-20 11:12:13.154 T:29417 INFO <general>: JELLYFIN.full_sync -> ERROR::jellyfin_kodi/full_sync.py:257 full sync exited unexpectedly
2020-11-20 11:12:13.190 T:29417 INFO <general>: JELLYFIN.full_sync -> ERROR::jellyfin_kodi/full_sync.py:258 no such column: strFanart
Traceback (most recent call last):
File "jellyfin_kodi/full_sync.py", line 243, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi/helper/wrapper.py", line 41, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi/full_sync.py", line 436, in music
obj.artist(item)
File "jellyfin_kodi/helper/wrapper.py", line 65, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi/helper/wrapper.py", line 77, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi/objects/music.py", line 93, in artist
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
File "jellyfin_kodi/objects/kodi/music.py", line 91, in update
self.cursor.execute(QU.update_artist, args)
sqlite3.OperationalError: no such column: strFanart
2020-11-20 11:12:13.203 T:29417 INFO <general>: JELLYFIN.full_sync -> INFO::jellyfin_kodi/full_sync.py:586 --<[ fullsync ]
2020-11-20 11:12:13.212 T:29417 INFO <general>: JELLYFIN.library -> ERROR::jellyfin_kodi/library.py:367 no such column: strFanart
Traceback (most recent call last):
File "jellyfin_kodi/library.py", line 324, in startup
sync.libraries()
File "jellyfin_kodi/full_sync.py", line 101, in libraries
self.start()
File "jellyfin_kodi/full_sync.py", line 186, in start
self.process_library(library)
File "jellyfin_kodi/full_sync.py", line 243, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi/helper/wrapper.py", line 41, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi/full_sync.py", line 436, in music
obj.artist(item)
File "jellyfin_kodi/helper/wrapper.py", line 65, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi/helper/wrapper.py", line 77, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi/objects/music.py", line 93, in artist
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
File "jellyfin_kodi/objects/kodi/music.py", line 91, in update
self.cursor.execute(QU.update_artist, args)
sqlite3.OperationalError: no such column: strFanart
|
sqlite3.OperationalError
|
def _add_editcontrol(self, x, y, height, width):
control = xbmcgui.ControlEdit(
0,
0,
0,
0,
label="",
font="font13",
textColor="FF00A4DC",
disabledColor="FF888888",
focusTexture="-",
noFocusTexture="-",
)
control.setPosition(x, y)
control.setHeight(height)
control.setWidth(width)
self.addControl(control)
return control
|
def _add_editcontrol(self, x, y, height, width):
control = xbmcgui.ControlEdit(
0,
0,
0,
0,
label="User",
font="font13",
textColor="FF00A4DC",
disabledColor="FF888888",
focusTexture="-",
noFocusTexture="-",
)
control.setPosition(x, y)
control.setHeight(height)
control.setWidth(width)
self.addControl(control)
return control
|
https://github.com/jellyfin/jellyfin-kodi/issues/428
|
2020-11-20 11:12:04.823 T:29417 INFO <general>: JELLYFIN.database -> ERROR::jellyfin_kodi/database/__init__.py:163 type: <class 'sqlite3.OperationalError'> value: no such column: strFanart
2020-11-20 11:12:04.839 T:29417 INFO <general>: JELLYFIN.database -> ERROR::jellyfin_kodi/database/__init__.py:163 type: <class 'sqlite3.OperationalError'> value: no such column: strFanart
2020-11-20 11:12:04.852 T:29246 INFO <general>: Loading skin file: DialogConfirm.xml, load type: KEEP_IN_MEMORY
2020-11-20 11:12:13.154 T:29417 INFO <general>: JELLYFIN.full_sync -> ERROR::jellyfin_kodi/full_sync.py:257 full sync exited unexpectedly
2020-11-20 11:12:13.190 T:29417 INFO <general>: JELLYFIN.full_sync -> ERROR::jellyfin_kodi/full_sync.py:258 no such column: strFanart
Traceback (most recent call last):
File "jellyfin_kodi/full_sync.py", line 243, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi/helper/wrapper.py", line 41, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi/full_sync.py", line 436, in music
obj.artist(item)
File "jellyfin_kodi/helper/wrapper.py", line 65, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi/helper/wrapper.py", line 77, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi/objects/music.py", line 93, in artist
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
File "jellyfin_kodi/objects/kodi/music.py", line 91, in update
self.cursor.execute(QU.update_artist, args)
sqlite3.OperationalError: no such column: strFanart
2020-11-20 11:12:13.203 T:29417 INFO <general>: JELLYFIN.full_sync -> INFO::jellyfin_kodi/full_sync.py:586 --<[ fullsync ]
2020-11-20 11:12:13.212 T:29417 INFO <general>: JELLYFIN.library -> ERROR::jellyfin_kodi/library.py:367 no such column: strFanart
Traceback (most recent call last):
File "jellyfin_kodi/library.py", line 324, in startup
sync.libraries()
File "jellyfin_kodi/full_sync.py", line 101, in libraries
self.start()
File "jellyfin_kodi/full_sync.py", line 186, in start
self.process_library(library)
File "jellyfin_kodi/full_sync.py", line 243, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi/helper/wrapper.py", line 41, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi/full_sync.py", line 436, in music
obj.artist(item)
File "jellyfin_kodi/helper/wrapper.py", line 65, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi/helper/wrapper.py", line 77, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi/objects/music.py", line 93, in artist
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
File "jellyfin_kodi/objects/kodi/music.py", line 91, in update
self.cursor.execute(QU.update_artist, args)
sqlite3.OperationalError: no such column: strFanart
|
sqlite3.OperationalError
|
def __init__(self, server_id=None, api_client=None):
self.server_id = server_id or None
if not api_client:
LOG.debug("No api client provided, attempting to use config file")
jellyfin_client = Jellyfin(server_id).get_client()
api_client = jellyfin_client.jellyfin
addon_data = xbmc.translatePath(
"special://profile/addon_data/plugin.video.jellyfin/data.json"
)
try:
with open(addon_data, "rb") as infile:
data = json.load(infile)
server_data = data["Servers"][0]
api_client.config.data["auth.server"] = server_data.get("address")
api_client.config.data["auth.server-name"] = server_data.get("Name")
api_client.config.data["auth.user_id"] = server_data.get("UserId")
api_client.config.data["auth.token"] = server_data.get("AccessToken")
except Exception as e:
LOG.warning("Addon appears to not be configured yet: {}".format(e))
self.api_client = api_client
self.server = self.api_client.config.data["auth.server"]
self.stack = []
|
def __init__(self, server_id=None, api_client=None):
self.server_id = server_id or None
self.api_client = api_client
self.server = self.api_client.config.data["auth.server"]
self.stack = []
|
https://github.com/jellyfin/jellyfin-kodi/issues/428
|
2020-11-20 11:12:04.823 T:29417 INFO <general>: JELLYFIN.database -> ERROR::jellyfin_kodi/database/__init__.py:163 type: <class 'sqlite3.OperationalError'> value: no such column: strFanart
2020-11-20 11:12:04.839 T:29417 INFO <general>: JELLYFIN.database -> ERROR::jellyfin_kodi/database/__init__.py:163 type: <class 'sqlite3.OperationalError'> value: no such column: strFanart
2020-11-20 11:12:04.852 T:29246 INFO <general>: Loading skin file: DialogConfirm.xml, load type: KEEP_IN_MEMORY
2020-11-20 11:12:13.154 T:29417 INFO <general>: JELLYFIN.full_sync -> ERROR::jellyfin_kodi/full_sync.py:257 full sync exited unexpectedly
2020-11-20 11:12:13.190 T:29417 INFO <general>: JELLYFIN.full_sync -> ERROR::jellyfin_kodi/full_sync.py:258 no such column: strFanart
Traceback (most recent call last):
File "jellyfin_kodi/full_sync.py", line 243, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi/helper/wrapper.py", line 41, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi/full_sync.py", line 436, in music
obj.artist(item)
File "jellyfin_kodi/helper/wrapper.py", line 65, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi/helper/wrapper.py", line 77, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi/objects/music.py", line 93, in artist
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
File "jellyfin_kodi/objects/kodi/music.py", line 91, in update
self.cursor.execute(QU.update_artist, args)
sqlite3.OperationalError: no such column: strFanart
2020-11-20 11:12:13.203 T:29417 INFO <general>: JELLYFIN.full_sync -> INFO::jellyfin_kodi/full_sync.py:586 --<[ fullsync ]
2020-11-20 11:12:13.212 T:29417 INFO <general>: JELLYFIN.library -> ERROR::jellyfin_kodi/library.py:367 no such column: strFanart
Traceback (most recent call last):
File "jellyfin_kodi/library.py", line 324, in startup
sync.libraries()
File "jellyfin_kodi/full_sync.py", line 101, in libraries
self.start()
File "jellyfin_kodi/full_sync.py", line 186, in start
self.process_library(library)
File "jellyfin_kodi/full_sync.py", line 243, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi/helper/wrapper.py", line 41, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi/full_sync.py", line 436, in music
obj.artist(item)
File "jellyfin_kodi/helper/wrapper.py", line 65, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi/helper/wrapper.py", line 77, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi/objects/music.py", line 93, in artist
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
File "jellyfin_kodi/objects/kodi/music.py", line 91, in update
self.cursor.execute(QU.update_artist, args)
sqlite3.OperationalError: no such column: strFanart
|
sqlite3.OperationalError
|
def update(self, *args):
if self.version_id < 74:
self.cursor.execute(QU.update_artist74, args)
else:
# No field for backdrops in Kodi 19, so we need to omit that here
args = args[:3] + args[4:]
self.cursor.execute(QU.update_artist82, args)
|
def update(self, *args):
self.cursor.execute(QU.update_artist, args)
|
https://github.com/jellyfin/jellyfin-kodi/issues/428
|
2020-11-20 11:12:04.823 T:29417 INFO <general>: JELLYFIN.database -> ERROR::jellyfin_kodi/database/__init__.py:163 type: <class 'sqlite3.OperationalError'> value: no such column: strFanart
2020-11-20 11:12:04.839 T:29417 INFO <general>: JELLYFIN.database -> ERROR::jellyfin_kodi/database/__init__.py:163 type: <class 'sqlite3.OperationalError'> value: no such column: strFanart
2020-11-20 11:12:04.852 T:29246 INFO <general>: Loading skin file: DialogConfirm.xml, load type: KEEP_IN_MEMORY
2020-11-20 11:12:13.154 T:29417 INFO <general>: JELLYFIN.full_sync -> ERROR::jellyfin_kodi/full_sync.py:257 full sync exited unexpectedly
2020-11-20 11:12:13.190 T:29417 INFO <general>: JELLYFIN.full_sync -> ERROR::jellyfin_kodi/full_sync.py:258 no such column: strFanart
Traceback (most recent call last):
File "jellyfin_kodi/full_sync.py", line 243, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi/helper/wrapper.py", line 41, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi/full_sync.py", line 436, in music
obj.artist(item)
File "jellyfin_kodi/helper/wrapper.py", line 65, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi/helper/wrapper.py", line 77, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi/objects/music.py", line 93, in artist
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
File "jellyfin_kodi/objects/kodi/music.py", line 91, in update
self.cursor.execute(QU.update_artist, args)
sqlite3.OperationalError: no such column: strFanart
2020-11-20 11:12:13.203 T:29417 INFO <general>: JELLYFIN.full_sync -> INFO::jellyfin_kodi/full_sync.py:586 --<[ fullsync ]
2020-11-20 11:12:13.212 T:29417 INFO <general>: JELLYFIN.library -> ERROR::jellyfin_kodi/library.py:367 no such column: strFanart
Traceback (most recent call last):
File "jellyfin_kodi/library.py", line 324, in startup
sync.libraries()
File "jellyfin_kodi/full_sync.py", line 101, in libraries
self.start()
File "jellyfin_kodi/full_sync.py", line 186, in start
self.process_library(library)
File "jellyfin_kodi/full_sync.py", line 243, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi/helper/wrapper.py", line 41, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi/full_sync.py", line 436, in music
obj.artist(item)
File "jellyfin_kodi/helper/wrapper.py", line 65, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi/helper/wrapper.py", line 77, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi/objects/music.py", line 93, in artist
self.update(obj['Genre'], obj['Bio'], obj['Thumb'], obj['Backdrops'], obj['LastScraped'], obj['ArtistId'])
File "jellyfin_kodi/objects/kodi/music.py", line 91, in update
self.cursor.execute(QU.update_artist, args)
sqlite3.OperationalError: no such column: strFanart
|
sqlite3.OperationalError
|
def event(method, data=None, sender=None, hexlify=False):
"""Data is a dictionary."""
data = data or {}
sender = sender or "plugin.video.jellyfin"
if hexlify:
data = ensure_text(binascii.hexlify(ensure_binary(json.dumps(data))))
data = '"[%s]"' % json.dumps(data).replace('"', '\\"')
LOG.debug("---[ event: %s/%s ] %s", sender, method, data)
xbmc.executebuiltin("NotifyAll(%s, %s, %s)" % (sender, method, data))
|
def event(method, data=None, sender=None, hexlify=False):
"""Data is a dictionary."""
data = data or {}
sender = sender or "plugin.video.jellyfin"
if hexlify:
data = '\\"[\\"{0}\\"]\\"'.format(binascii.hexlify(json.dumps(data)))
else:
data = '"[%s]"' % json.dumps(data).replace('"', '\\"')
xbmc.executebuiltin("NotifyAll(%s, %s, %s)" % (sender, method, data))
LOG.debug("---[ event: %s/%s ] %s", sender, method, data)
|
https://github.com/jellyfin/jellyfin-kodi/issues/441
|
2020-12-09 21:34:39.454 T:3534 NOTICE: Creating InputStream
2020-12-09 21:34:47.723 T:3458 NOTICE: VideoInfoScanner: Starting scan ..
2020-12-09 21:34:47.728 T:3458 NOTICE: VideoInfoScanner: Finished scan. Scanning for video info took 00:00
2020-12-09 21:34:53.734 T:3534 NOTICE: Creating Demuxer
2020-12-09 21:34:54.188 T:3534 NOTICE: Opening stream: 1 source: 256
2020-12-09 21:34:54.188 T:3534 NOTICE: Creating video codec with codec id: 173
2020-12-09 21:34:54.188 T:3534 NOTICE: CDVDVideoCodecDRMPRIME::Open - using decoder HEVC (High Efficiency Video Coding)
2020-12-09 21:34:54.190 T:3534 NOTICE: Creating video thread
2020-12-09 21:34:54.191 T:3545 NOTICE: running thread: video_thread
2020-12-09 21:34:54.419 T:3534 NOTICE: Opening stream: 0 source: 256
2020-12-09 21:34:54.420 T:3534 NOTICE: Finding audio codec for: 86018
2020-12-09 21:34:54.422 T:3534 NOTICE: CDVDAudioCodecFFmpeg::Open() Successful opened audio decoder aac
2020-12-09 21:34:54.422 T:3534 NOTICE: Creating audio thread
2020-12-09 21:34:54.427 T:3547 NOTICE: running thread: CVideoPlayerAudio::Process()
2020-12-09 21:34:54.439 T:3547 NOTICE: Creating audio stream (codec id: 86018, channels: 2, sample rate: 48000, no pass-through)
2020-12-09 21:35:08.489 T:3545 WARNING: CRenderManager::WaitForBuffer - timeout waiting for buffer
2020-12-09 21:35:39.038 T:3501 WARNING: Previous line repeats 13 times.
2020-12-09 21:35:39.038 T:3501 ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <class 'TypeError'>
Error Contents: a bytes-like object is required, not 'str'
Traceback (most recent call last):
File "/storage/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/monitor.py", line 252, in onNotification
self.player.report_playback(data.get('Report', True))
File "/storage/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/player.py", line 341, in report_playback
self.next_up()
File "/storage/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/player.py", line 281, in next_up
event("upnext_data", next_info, hexlify=True)
File "/storage/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/helper/utils.py", line 140, in event
data = '\\"[\\"{0}\\"]\\"'.format(binascii.hexlify(json.dumps(data)))
TypeError: a bytes-like object is required, not 'str'
-->End of Python script error report<--
2020-12-09 21:35:39.989 T:3445 NOTICE: Samba is idle. Closing the remaining connections
2020-12-09 21:36:19.394 T:3545 WARNING: CRenderManager::WaitForBuffer - timeout waiting for buffer
|
TypeError
|
def fast_sync(self):
"""Movie and userdata not provided by server yet."""
last_sync = settings("LastIncrementalSync")
include = []
filters = ["tvshows", "boxsets", "musicvideos", "music", "movies"]
sync = get_sync()
LOG.info("--[ retrieve changes ] %s", last_sync)
# Get the item type of each synced library and build list of types to request
for item_id in sync["Whitelist"]:
library = self.server.jellyfin.get_item(item_id)
library_type = library.get("CollectionType")
if library_type in filters:
include.append(library_type)
# Include boxsets if movies are synced
if "movies" in include:
include.append("boxsets")
# Filter down to the list of library types we want to exclude
query_filter = list(set(filters) - set(include))
try:
updated = []
userdata = []
removed = []
# Get list of updates from server for synced library types and populate work queues
result = self.server.jellyfin.get_sync_queue(
last_sync, ",".join([x for x in query_filter])
)
updated.extend(result["ItemsAdded"])
updated.extend(result["ItemsUpdated"])
userdata.extend(result["UserDataChanged"])
removed.extend(result["ItemsRemoved"])
total = len(updated) + len(userdata)
if total > int(settings("syncIndicator") or 99):
""" Inverse yes no, in case the dialog is forced closed by Kodi.
"""
if dialog(
"yesno",
heading="{jellyfin}",
line1=translate(33172).replace("{number}", str(total)),
nolabel=translate(107),
yeslabel=translate(106),
):
LOG.warning("Large updates skipped.")
return True
self.updated(updated)
self.userdata(userdata)
self.removed(removed)
except Exception as error:
LOG.exception(error)
return False
return True
|
def fast_sync(self):
"""Movie and userdata not provided by server yet."""
last_sync = settings("LastIncrementalSync")
filters = ["tvshows", "boxsets", "musicvideos", "music", "movies"]
sync = get_sync()
LOG.info("--[ retrieve changes ] %s", last_sync)
try:
updated = []
userdata = []
removed = []
for media in filters:
result = self.server.jellyfin.get_sync_queue(
last_sync, ",".join([x for x in filters if x != media])
)
updated.extend(result["ItemsAdded"])
updated.extend(result["ItemsUpdated"])
userdata.extend(result["UserDataChanged"])
removed.extend(result["ItemsRemoved"])
total = len(updated) + len(userdata)
if total > int(settings("syncIndicator") or 99):
""" Inverse yes no, in case the dialog is forced closed by Kodi.
"""
if dialog(
"yesno",
heading="{jellyfin}",
line1=translate(33172).replace("{number}", str(total)),
nolabel=translate(107),
yeslabel=translate(106),
):
LOG.warning("Large updates skipped.")
return True
self.updated(updated)
self.userdata(userdata)
self.removed(removed)
"""
result = self.server.jellyfin.get_sync_queue(last_sync)
self.userdata(result['UserDataChanged'])
self.removed(result['ItemsRemoved'])
filters.extend(["tvshows", "boxsets", "musicvideos", "music"])
# Get only movies.
result = self.server.jellyfin.get_sync_queue(last_sync, ",".join(filters))
self.updated(result['ItemsAdded'])
self.updated(result['ItemsUpdated'])
self.userdata(result['UserDataChanged'])
self.removed(result['ItemsRemoved'])
"""
except Exception as error:
LOG.exception(error)
return False
return True
|
https://github.com/jellyfin/jellyfin-kodi/issues/270
|
2020-04-08 20:06:13.443 T:140039749101312 NOTICE: JELLYFIN.objects.music -> ERROR::jellyfin_kodi/objects/music.py:392 'NoneType' object has no attribute '__getitem__'
Traceback (most recent call last):
File "jellyfin_kodi/objects/music.py", line 390, in song_artist_link
temp_obj['ArtistId'] = self.jellyfin_db.get_item_by_id(*values(temp_obj, QUEM.get_item_obj))[0]
TypeError: 'NoneType' object has no attribute '__getitem__'
|
TypeError
|
def run(self):
with Database("jellyfin") as jellyfindb:
database = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)
while True:
try:
item_id = self.queue.get(timeout=1)
except Queue.Empty:
break
try:
media = database.get_media_by_id(item_id)
if media:
self.output[media].put({"Id": item_id, "Type": media})
else:
items = database.get_media_by_parent_id(item_id)
if not items:
LOG.info(
"Could not find media %s in the jellyfin database.", item_id
)
else:
for item in items:
self.output[item[1]].put({"Id": item[0], "Type": item[1]})
except Exception as error:
LOG.exception(error)
self.queue.task_done()
if window("jellyfin_should_stop.bool"):
break
LOG.info("--<[ q:sort/%s ]", id(self))
self.is_done = True
|
def run(self):
with Database("jellyfin") as jellyfindb:
database = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)
while True:
try:
item_id = self.queue.get(timeout=1)
except Queue.Empty:
break
try:
media = database.get_media_by_id(item_id)
self.output[media].put({"Id": item_id, "Type": media})
except Exception as error:
LOG.exception(error)
items = database.get_media_by_parent_id(item_id)
if not items:
LOG.info(
"Could not find media %s in the jellyfin database.", item_id
)
else:
for item in items:
self.output[item[1]].put({"Id": item[0], "Type": item[1]})
self.queue.task_done()
if window("jellyfin_should_stop.bool"):
break
LOG.info("--<[ q:sort/%s ]", id(self))
self.is_done = True
|
https://github.com/jellyfin/jellyfin-kodi/issues/270
|
2020-04-08 20:06:13.443 T:140039749101312 NOTICE: JELLYFIN.objects.music -> ERROR::jellyfin_kodi/objects/music.py:392 'NoneType' object has no attribute '__getitem__'
Traceback (most recent call last):
File "jellyfin_kodi/objects/music.py", line 390, in song_artist_link
temp_obj['ArtistId'] = self.jellyfin_db.get_item_by_id(*values(temp_obj, QUEM.get_item_obj))[0]
TypeError: 'NoneType' object has no attribute '__getitem__'
|
TypeError
|
def format(self, record):
if record.pathname:
record.pathname = ensure_text(record.pathname, get_filesystem_encoding())
self._gen_rel_path(record)
# Call the original formatter class to do the grunt work
result = logging.Formatter.format(self, record)
return result
|
def format(self, record):
if record.pathname:
record.pathname = ensure_text(record.pathname, sys.getfilesystemencoding())
self._gen_rel_path(record)
# Call the original formatter class to do the grunt work
result = logging.Formatter.format(self, record)
return result
|
https://github.com/jellyfin/jellyfin-kodi/issues/285
|
ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.TypeError'>
Error Contents: decode() argument 1 must be string, not None
Traceback (most recent call last):
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/service.py", line 21, in <module>
from entrypoint import Service # noqa: F402
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/__init__.py", line 13, in <module>
from .default import Events
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/default.py", line 14, in <module>
from database import reset, get_sync, Database, jellyfin_db, get_credentials
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/database/__init__.py", line 16, in <module>
from objects import obj
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/__init__.py", line 13, in <module>
Objects().mapping()
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/obj.py", line 37, in mapping
file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/script.module.six/lib/six.py", line 915, in ensure_text
return s.decode(encoding, errors)
TypeError: decode() argument 1 must be string, not None
-->End of Python script error report<--
|
TypeError
|
def formatException(self, exc_info):
_pluginpath_real = os.path.realpath(__pluginpath__)
res = []
for o in traceback.format_exception(*exc_info):
o = ensure_text(o, get_filesystem_encoding())
if o.startswith(' File "'):
# If this split can't handle your file names, you should seriously consider renaming your files.
fn = o.split(' File "', 2)[1].split('", line ', 1)[0]
rfn = os.path.realpath(fn)
if rfn.startswith(_pluginpath_real):
o = o.replace(fn, os.path.relpath(rfn, _pluginpath_real))
res.append(o)
return "".join(res)
|
def formatException(self, exc_info):
_pluginpath_real = os.path.realpath(__pluginpath__)
res = []
for o in traceback.format_exception(*exc_info):
o = ensure_text(o, sys.getfilesystemencoding())
if o.startswith(' File "'):
# If this split can't handle your file names, you should seriously consider renaming your files.
fn = o.split(' File "', 2)[1].split('", line ', 1)[0]
rfn = os.path.realpath(fn)
if rfn.startswith(_pluginpath_real):
o = o.replace(fn, os.path.relpath(rfn, _pluginpath_real))
res.append(o)
return "".join(res)
|
https://github.com/jellyfin/jellyfin-kodi/issues/285
|
ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.TypeError'>
Error Contents: decode() argument 1 must be string, not None
Traceback (most recent call last):
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/service.py", line 21, in <module>
from entrypoint import Service # noqa: F402
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/__init__.py", line 13, in <module>
from .default import Events
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/default.py", line 14, in <module>
from database import reset, get_sync, Database, jellyfin_db, get_credentials
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/database/__init__.py", line 16, in <module>
from objects import obj
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/__init__.py", line 13, in <module>
Objects().mapping()
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/obj.py", line 37, in mapping
file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/script.module.six/lib/six.py", line 915, in ensure_text
return s.decode(encoding, errors)
TypeError: decode() argument 1 must be string, not None
-->End of Python script error report<--
|
TypeError
|
def mapping(self):
"""Load objects mapping."""
file_dir = os.path.dirname(ensure_text(__file__, get_filesystem_encoding()))
with open(os.path.join(file_dir, "obj_map.json")) as infile:
self.objects = json.load(infile)
|
def mapping(self):
"""Load objects mapping."""
file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))
with open(os.path.join(file_dir, "obj_map.json")) as infile:
self.objects = json.load(infile)
|
https://github.com/jellyfin/jellyfin-kodi/issues/285
|
ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.TypeError'>
Error Contents: decode() argument 1 must be string, not None
Traceback (most recent call last):
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/service.py", line 21, in <module>
from entrypoint import Service # noqa: F402
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/__init__.py", line 13, in <module>
from .default import Events
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/default.py", line 14, in <module>
from database import reset, get_sync, Database, jellyfin_db, get_credentials
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/database/__init__.py", line 16, in <module>
from objects import obj
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/__init__.py", line 13, in <module>
Objects().mapping()
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/obj.py", line 37, in mapping
file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/script.module.six/lib/six.py", line 915, in ensure_text
return s.decode(encoding, errors)
TypeError: decode() argument 1 must be string, not None
-->End of Python script error report<--
|
TypeError
|
def format(self, record):
if record.pathname:
record.pathname = ensure_text(record.pathname, sys.getfilesystemencoding())
self._gen_rel_path(record)
# Call the original formatter class to do the grunt work
result = logging.Formatter.format(self, record)
return result
|
def format(self, record):
self._gen_rel_path(record)
# Call the original formatter class to do the grunt work
result = logging.Formatter.format(self, record)
return result
|
https://github.com/jellyfin/jellyfin-kodi/issues/273
|
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.UnicodeDecodeError'>
Error Contents: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
Traceback (most recent call last):
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\service.py", line 22, in <module>
from entrypoint import Service # noqa: F402
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\entrypoint\__init__.py", line 10, in <module>
from helper import loghandler
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\helper\loghandler.py", line 14, in <module>
import database
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\database\__init__.py", line 16, in <module>
from objects import obj
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\__init__.py", line 13, in <module>
Objects().mapping()
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\obj.py", line 35, in mapping
with open(os.path.join(os.path.dirname(__file__), 'obj_map.json')) as infile:
File "C:\Program Files\Kodi\system\python\Lib\ntpath.py", line 85, in join
result_path = result_path + p_path
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
-->End of Python script error report<-- -->
|
UnicodeDecodeError
|
def formatException(self, exc_info):
_pluginpath_real = os.path.realpath(__pluginpath__)
res = []
for o in traceback.format_exception(*exc_info):
o = ensure_text(o, sys.getfilesystemencoding())
if o.startswith(' File "'):
# If this split can't handle your file names, you should seriously consider renaming your files.
fn = o.split(' File "', 2)[1].split('", line ', 1)[0]
rfn = os.path.realpath(fn)
if rfn.startswith(_pluginpath_real):
o = o.replace(fn, os.path.relpath(rfn, _pluginpath_real))
res.append(o)
return "".join(res)
|
def formatException(self, exc_info):
_pluginpath_real = os.path.realpath(__pluginpath__)
res = []
for o in traceback.format_exception(*exc_info):
if o.startswith(' File "'):
# If this split can't handle your file names, you should seriously consider renaming your files.
fn = o.split(' File "', 2)[1].split('", line ', 1)[0]
rfn = os.path.realpath(fn)
if rfn.startswith(_pluginpath_real):
o = o.replace(fn, os.path.relpath(rfn, _pluginpath_real))
res.append(o)
return "".join(res)
|
https://github.com/jellyfin/jellyfin-kodi/issues/273
|
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.UnicodeDecodeError'>
Error Contents: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
Traceback (most recent call last):
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\service.py", line 22, in <module>
from entrypoint import Service # noqa: F402
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\entrypoint\__init__.py", line 10, in <module>
from helper import loghandler
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\helper\loghandler.py", line 14, in <module>
import database
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\database\__init__.py", line 16, in <module>
from objects import obj
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\__init__.py", line 13, in <module>
Objects().mapping()
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\obj.py", line 35, in mapping
with open(os.path.join(os.path.dirname(__file__), 'obj_map.json')) as infile:
File "C:\Program Files\Kodi\system\python\Lib\ntpath.py", line 85, in join
result_path = result_path + p_path
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
-->End of Python script error report<-- -->
|
UnicodeDecodeError
|
def mapping(self):
"""Load objects mapping."""
file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))
with open(os.path.join(file_dir, "obj_map.json")) as infile:
self.objects = json.load(infile)
|
def mapping(self):
"""Load objects mapping."""
with open(os.path.join(os.path.dirname(__file__), "obj_map.json")) as infile:
self.objects = json.load(infile)
|
https://github.com/jellyfin/jellyfin-kodi/issues/273
|
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.UnicodeDecodeError'>
Error Contents: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
Traceback (most recent call last):
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\service.py", line 22, in <module>
from entrypoint import Service # noqa: F402
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\entrypoint\__init__.py", line 10, in <module>
from helper import loghandler
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\helper\loghandler.py", line 14, in <module>
import database
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\database\__init__.py", line 16, in <module>
from objects import obj
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\__init__.py", line 13, in <module>
Objects().mapping()
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\obj.py", line 35, in mapping
with open(os.path.join(os.path.dirname(__file__), 'obj_map.json')) as infile:
File "C:\Program Files\Kodi\system\python\Lib\ntpath.py", line 85, in join
result_path = result_path + p_path
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
-->End of Python script error report<-- -->
|
UnicodeDecodeError
|
def _get_items(query, server_id=None):
"""query = {
'url': string,
'params': dict -- opt, include StartIndex to resume
}
"""
items = {"Items": [], "TotalRecordCount": 0, "RestorePoint": {}}
url = query["url"]
query.setdefault("params", {})
params = query["params"]
try:
test_params = dict(params)
test_params["Limit"] = 1
test_params["EnableTotalRecordCount"] = True
items["TotalRecordCount"] = _get(url, test_params, server_id=server_id)[
"TotalRecordCount"
]
except Exception as error:
LOG.exception(
"Failed to retrieve the server response %s: %s params:%s",
url,
error,
params,
)
else:
params.setdefault("StartIndex", 0)
def get_query_params(params, start, count):
params_copy = dict(params)
params_copy["StartIndex"] = start
params_copy["Limit"] = count
return params_copy
query_params = [
get_query_params(params, offset, LIMIT)
for offset in range(params["StartIndex"], items["TotalRecordCount"], LIMIT)
]
# multiprocessing.dummy.Pool completes all requests in multiple threads but has to
# complete all tasks before allowing any results to be processed. ThreadPoolExecutor
# allows for completed tasks to be processed while other tasks are completed on other
# threads. Dont be a dummy.Pool, be a ThreadPoolExecutor
p = concurrent.futures.ThreadPoolExecutor(DTHREADS)
results = p.map(
lambda params: _get(url, params, server_id=server_id), query_params
)
for params, result in zip(query_params, results):
query["params"] = params
result = result or {"Items": []}
# Mitigates #216 till the server validates the date provided is valid
if result["Items"][0].get("ProductionYear"):
try:
date(result["Items"][0]["ProductionYear"], 1, 1)
except ValueError:
LOG.info(
"#216 mitigation triggered. Setting ProductionYear to None"
)
result["Items"][0]["ProductionYear"] = None
items["Items"].extend(result["Items"])
# Using items to return data and communicate a restore point back to the callee is
# a violation of the SRP. TODO: Seperate responsibilities.
items["RestorePoint"] = query
yield items
del items["Items"][:]
|
def _get_items(query, server_id=None):
"""query = {
'url': string,
'params': dict -- opt, include StartIndex to resume
}
"""
items = {"Items": [], "TotalRecordCount": 0, "RestorePoint": {}}
url = query["url"]
query.setdefault("params", {})
params = query["params"]
try:
test_params = dict(params)
test_params["Limit"] = 1
test_params["EnableTotalRecordCount"] = True
items["TotalRecordCount"] = _get(url, test_params, server_id=server_id)[
"TotalRecordCount"
]
except Exception as error:
LOG.exception(
"Failed to retrieve the server response %s: %s params:%s",
url,
error,
params,
)
else:
params.setdefault("StartIndex", 0)
def get_query_params(params, start, count):
params_copy = dict(params)
params_copy["StartIndex"] = start
params_copy["Limit"] = count
return params_copy
query_params = [
get_query_params(params, offset, LIMIT)
for offset in range(params["StartIndex"], items["TotalRecordCount"], LIMIT)
]
# multiprocessing.dummy.Pool completes all requests in multiple threads but has to
# complete all tasks before allowing any results to be processed. ThreadPoolExecutor
# allows for completed tasks to be processed while other tasks are completed on other
# threads. Dont be a dummy.Pool, be a ThreadPoolExecutor
import concurrent.futures
p = concurrent.futures.ThreadPoolExecutor(DTHREADS)
results = p.map(
lambda params: _get(url, params, server_id=server_id), query_params
)
for params, result in zip(query_params, results):
query["params"] = params
result = result or {"Items": []}
items["Items"].extend(result["Items"])
# Using items to return data and communicate a restore point back to the callee is
# a violation of the SRP. TODO: Seperate responsibilities.
items["RestorePoint"] = query
yield items
del items["Items"][:]
|
https://github.com/jellyfin/jellyfin-kodi/issues/216
|
2020-02-27 16:39:00.274 T:20092
NOTICE: JELLYFIN.full_sync -> ERROR::jellyfin_kodi\full_sync.py:240 year is out of range
Traceback (most recent call last):
File "jellyfin_kodi\full_sync.py", line 231, in process_library
media[library['CollectionType']](library)
File "jellyfin_kodi\helper\wrapper.py", line 40, in wrapper
result = func(self, dialog=dialog, *args, **kwargs)
File "jellyfin_kodi\full_sync.py", line 363, in musicvideos
obj.musicvideo(mvideo, library=library)
File "jellyfin_kodi\helper\wrapper.py", line 102, in wrapper
return func(*args, **kwargs)
File "jellyfin_kodi\helper\wrapper.py", line 116, in wrapper
return func(self, item, e_item=e_item, *args, **kwargs)
File "jellyfin_kodi\helper\wrapper.py", line 175, in wrapper
return func(self, item, *args, **kwargs)
File "jellyfin_kodi\objects\musicvideos.py", line 79, in musicvideo
obj['Premiere'] = Local(obj['Premiere']) if obj['Premiere'] else datetime.date(obj['Year'] or 2021, 1, 1)
ValueError: year is out of range
|
ValueError
|
def get_root(app, request=None):
"""Return a tuple composed of ``(root, closer)`` when provided a
:term:`router` instance as the ``app`` argument. The ``root``
returned is the application root object. The ``closer`` returned
is a callable (accepting no arguments) that should be called when
your scripting application is finished using the root.
``request`` is passed to the :app:`Pyramid` application root
factory to compute the root. If ``request`` is None, a default
will be constructed using the registry's :term:`Request Factory`
via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
"""
registry = app.registry
if request is None:
request = _make_request("/", registry)
request.registry = registry
ctx = RequestContext(request)
ctx.begin()
def closer():
ctx.end()
root = app.root_factory(request)
return root, closer
|
def get_root(app, request=None):
"""Return a tuple composed of ``(root, closer)`` when provided a
:term:`router` instance as the ``app`` argument. The ``root``
returned is the application root object. The ``closer`` returned
is a callable (accepting no arguments) that should be called when
your scripting application is finished using the root.
``request`` is passed to the :app:`Pyramid` application root
factory to compute the root. If ``request`` is None, a default
will be constructed using the registry's :term:`Request Factory`
via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
"""
registry = app.registry
if request is None:
request = _make_request("/", registry)
threadlocals = {"registry": registry, "request": request}
app.threadlocal_manager.push(threadlocals)
def closer(request=request): # keep request alive via this function default
app.threadlocal_manager.pop()
root = app.root_factory(request)
return root, closer
|
https://github.com/Pylons/pyramid/issues/3262
|
# bin/pshell mything/development.ini
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help" for more information.
Environment:
app The WSGI application.
registry Active Pyramid registry.
request Active request object.
root Root of the default resource tree.
root_factory Default root factory used to create `root`.
from pyramid.scripting import get_root
x = get_root(app)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/shane/src/pyramidtest/eggs/pyramid-1.9.1-py3.5.egg/pyramid/scripting.py", line 30, in get_root
app.threadlocal_manager.push(threadlocals)
AttributeError: 'Router' object has no attribute 'threadlocal_manager'
|
AttributeError
|
def closer():
ctx.end()
|
def closer(request=request): # keep request alive via this function default
app.threadlocal_manager.pop()
|
https://github.com/Pylons/pyramid/issues/3262
|
# bin/pshell mything/development.ini
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help" for more information.
Environment:
app The WSGI application.
registry Active Pyramid registry.
request Active request object.
root Root of the default resource tree.
root_factory Default root factory used to create `root`.
from pyramid.scripting import get_root
x = get_root(app)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/shane/src/pyramidtest/eggs/pyramid-1.9.1-py3.5.egg/pyramid/scripting.py", line 30, in get_root
app.threadlocal_manager.push(threadlocals)
AttributeError: 'Router' object has no attribute 'threadlocal_manager'
|
AttributeError
|
def prepare(request=None, registry=None):
"""This function pushes data onto the Pyramid threadlocal stack
(request and registry), making those objects 'current'. It
returns a dictionary useful for bootstrapping a Pyramid
application in a scripting environment.
``request`` is passed to the :app:`Pyramid` application root
factory to compute the root. If ``request`` is None, a default
will be constructed using the registry's :term:`Request Factory`
via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
If ``registry`` is not supplied, the last registry loaded from
:attr:`pyramid.config.global_registries` will be used. If you
have loaded more than one :app:`Pyramid` application in the
current process, you may not want to use the last registry
loaded, thus you can search the ``global_registries`` and supply
the appropriate one based on your own criteria.
The function returns a dictionary composed of ``root``,
``closer``, ``registry``, ``request`` and ``root_factory``. The
``root`` returned is the application's root resource object. The
``closer`` returned is a callable (accepting no arguments) that
should be called when your scripting application is finished
using the root. ``registry`` is the resolved registry object.
``request`` is the request object passed or the constructed request
if no request is passed. ``root_factory`` is the root factory used
to construct the root.
This function may be used as a context manager to call the ``closer``
automatically:
.. code-block:: python
registry = config.registry
with prepare(registry) as env:
request = env['request']
# ...
.. versionchanged:: 1.8
Added the ability to use the return value as a context manager.
"""
if registry is None:
registry = getattr(request, "registry", global_registries.last)
if registry is None:
raise ConfigurationError(
"No valid Pyramid applications could be "
"found, make sure one has been created "
"before trying to activate it."
)
if request is None:
request = _make_request("/", registry)
# NB: even though _make_request might have already set registry on
# request, we reset it in case someone has passed in their own
# request.
request.registry = registry
ctx = RequestContext(request)
ctx.begin()
apply_request_extensions(request)
def closer():
ctx.end()
root_factory = registry.queryUtility(IRootFactory, default=DefaultRootFactory)
root = root_factory(request)
if getattr(request, "context", None) is None:
request.context = root
return AppEnvironment(
root=root,
closer=closer,
registry=registry,
request=request,
root_factory=root_factory,
)
|
def prepare(request=None, registry=None):
"""This function pushes data onto the Pyramid threadlocal stack
(request and registry), making those objects 'current'. It
returns a dictionary useful for bootstrapping a Pyramid
application in a scripting environment.
``request`` is passed to the :app:`Pyramid` application root
factory to compute the root. If ``request`` is None, a default
will be constructed using the registry's :term:`Request Factory`
via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
If ``registry`` is not supplied, the last registry loaded from
:attr:`pyramid.config.global_registries` will be used. If you
have loaded more than one :app:`Pyramid` application in the
current process, you may not want to use the last registry
loaded, thus you can search the ``global_registries`` and supply
the appropriate one based on your own criteria.
The function returns a dictionary composed of ``root``,
``closer``, ``registry``, ``request`` and ``root_factory``. The
``root`` returned is the application's root resource object. The
``closer`` returned is a callable (accepting no arguments) that
should be called when your scripting application is finished
using the root. ``registry`` is the resolved registry object.
``request`` is the request object passed or the constructed request
if no request is passed. ``root_factory`` is the root factory used
to construct the root.
This function may be used as a context manager to call the ``closer``
automatically:
.. code-block:: python
registry = config.registry
with prepare(registry) as env:
request = env['request']
# ...
.. versionchanged:: 1.8
Added the ability to use the return value as a context manager.
"""
if registry is None:
registry = getattr(request, "registry", global_registries.last)
if registry is None:
raise ConfigurationError(
"No valid Pyramid applications could be "
"found, make sure one has been created "
"before trying to activate it."
)
if request is None:
request = _make_request("/", registry)
# NB: even though _make_request might have already set registry on
# request, we reset it in case someone has passed in their own
# request.
request.registry = registry
threadlocals = {"registry": registry, "request": request}
threadlocal_manager.push(threadlocals)
apply_request_extensions(request)
def closer():
threadlocal_manager.pop()
root_factory = registry.queryUtility(IRootFactory, default=DefaultRootFactory)
root = root_factory(request)
if getattr(request, "context", None) is None:
request.context = root
return AppEnvironment(
root=root,
closer=closer,
registry=registry,
request=request,
root_factory=root_factory,
)
|
https://github.com/Pylons/pyramid/issues/3262
|
# bin/pshell mything/development.ini
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help" for more information.
Environment:
app The WSGI application.
registry Active Pyramid registry.
request Active request object.
root Root of the default resource tree.
root_factory Default root factory used to create `root`.
from pyramid.scripting import get_root
x = get_root(app)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/shane/src/pyramidtest/eggs/pyramid-1.9.1-py3.5.egg/pyramid/scripting.py", line 30, in get_root
app.threadlocal_manager.push(threadlocals)
AttributeError: 'Router' object has no attribute 'threadlocal_manager'
|
AttributeError
|
def closer():
ctx.end()
|
def closer():
threadlocal_manager.pop()
|
https://github.com/Pylons/pyramid/issues/3262
|
# bin/pshell mything/development.ini
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help" for more information.
Environment:
app The WSGI application.
registry Active Pyramid registry.
request Active request object.
root Root of the default resource tree.
root_factory Default root factory used to create `root`.
from pyramid.scripting import get_root
x = get_root(app)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/shane/src/pyramidtest/eggs/pyramid-1.9.1-py3.5.egg/pyramid/scripting.py", line 30, in get_root
app.threadlocal_manager.push(threadlocals)
AttributeError: 'Router' object has no attribute 'threadlocal_manager'
|
AttributeError
|
def __init__(
self,
secret,
cookie_name="auth_tkt",
secure=False,
include_ip=False,
timeout=None,
reissue_time=None,
max_age=None,
http_only=False,
path="/",
wild_domain=True,
hashalg="md5",
parent_domain=False,
domain=None,
):
serializer = SimpleSerializer()
self.cookie_profile = CookieProfile(
cookie_name=cookie_name,
secure=secure,
max_age=max_age,
httponly=http_only,
path=path,
serializer=serializer,
)
self.secret = secret
self.cookie_name = cookie_name
self.secure = secure
self.include_ip = include_ip
self.timeout = timeout if timeout is None else int(timeout)
self.reissue_time = reissue_time if reissue_time is None else int(reissue_time)
self.max_age = max_age if max_age is None else int(max_age)
self.wild_domain = wild_domain
self.parent_domain = parent_domain
self.domain = domain
self.hashalg = hashalg
|
def __init__(
self,
secret,
cookie_name="auth_tkt",
secure=False,
include_ip=False,
timeout=None,
reissue_time=None,
max_age=None,
http_only=False,
path="/",
wild_domain=True,
hashalg="md5",
parent_domain=False,
domain=None,
):
serializer = _SimpleSerializer()
self.cookie_profile = CookieProfile(
cookie_name=cookie_name,
secure=secure,
max_age=max_age,
httponly=http_only,
path=path,
serializer=serializer,
)
self.secret = secret
self.cookie_name = cookie_name
self.secure = secure
self.include_ip = include_ip
self.timeout = timeout if timeout is None else int(timeout)
self.reissue_time = reissue_time if reissue_time is None else int(reissue_time)
self.max_age = max_age if max_age is None else int(max_age)
self.wild_domain = wild_domain
self.parent_domain = parent_domain
self.domain = domain
self.hashalg = hashalg
|
https://github.com/Pylons/pyramid/issues/3112
|
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS
|
ImportError
|
def _apply_view_derivers(self, info):
# These derivers are not really derivers and so have fixed order
outer_derivers = [
("attr_wrapped_view", attr_wrapped_view),
("predicated_view", predicated_view),
]
view = info.original_view
derivers = self.registry.getUtility(IViewDerivers)
for name, deriver in reversed(outer_derivers + derivers.sorted()):
view = wraps_view(deriver)(view, info)
return view
|
def _apply_view_derivers(self, info):
d = pyramid.viewderivers
# These derivers are not really derivers and so have fixed order
outer_derivers = [
("attr_wrapped_view", d.attr_wrapped_view),
("predicated_view", d.predicated_view),
]
view = info.original_view
derivers = self.registry.getUtility(IViewDerivers)
for name, deriver in reversed(outer_derivers + derivers.sorted()):
view = wraps_view(deriver)(view, info)
return view
|
https://github.com/Pylons/pyramid/issues/3112
|
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS
|
ImportError
|
def __init__(
self,
cookie_name="csrf_token",
secure=False,
httponly=False,
domain=None,
max_age=None,
path="/",
):
serializer = SimpleSerializer()
self.cookie_profile = CookieProfile(
cookie_name=cookie_name,
secure=secure,
max_age=max_age,
httponly=httponly,
path=path,
domains=[domain],
serializer=serializer,
)
self.cookie_name = cookie_name
|
def __init__(
self,
cookie_name="csrf_token",
secure=False,
httponly=False,
domain=None,
max_age=None,
path="/",
):
serializer = _SimpleSerializer()
self.cookie_profile = CookieProfile(
cookie_name=cookie_name,
secure=secure,
max_age=max_age,
httponly=httponly,
path=path,
domains=[domain],
serializer=serializer,
)
self.cookie_name = cookie_name
|
https://github.com/Pylons/pyramid/issues/3112
|
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS
|
ImportError
|
def __init__(self, predicate):
self.predicate = predicate
|
def __init__(self, val, config):
if is_nonstr_iter(val):
self.val = set(val)
else:
self.val = set((val,))
|
https://github.com/Pylons/pyramid/issues/3112
|
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS
|
ImportError
|
def text(self):
return self._notted_text(self.predicate.text())
|
def text(self):
return "effective_principals = %s" % sorted(list(self.val))
|
https://github.com/Pylons/pyramid/issues/3112
|
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS
|
ImportError
|
def __call__(self, context, request):
result = self.predicate(context, request)
phash = self.phash()
if phash:
result = not result
return result
|
def __call__(self, context, request):
req_principals = request.effective_principals
if is_nonstr_iter(req_principals):
rpset = set(req_principals)
if self.val.issubset(rpset):
return True
return False
|
https://github.com/Pylons/pyramid/issues/3112
|
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS
|
ImportError
|
def phash(self):
return self._notted_text(self.predicate.phash())
|
def phash(self):
# This isn't actually a predicate, it's just a infodict modifier that
# injects ``traverse`` into the matchdict. As a result, we don't
# need to update the hash.
return ""
|
https://github.com/Pylons/pyramid/issues/3112
|
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS
|
ImportError
|
def __init__(
self,
default_before=LAST,
default_after=None,
first=FIRST,
last=LAST,
):
self.names = []
self.req_before = set()
self.req_after = set()
self.name2before = {}
self.name2after = {}
self.name2val = {}
self.order = []
self.default_before = default_before
self.default_after = default_after
self.first = first
self.last = last
|
def __init__(self, file, line, function, src):
self.file = file
self.line = line
self.function = function
self.src = src
|
https://github.com/Pylons/pyramid/issues/3112
|
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS
|
ImportError
|
def execute_actions(self, clear=True, introspector=None):
"""Execute the configuration actions
This calls the action callables after resolving conflicts
For example:
>>> output = []
>>> def f(*a, **k):
... output.append(('f', a, k))
>>> context = ActionState()
>>> context.actions = [
... (1, f, (1,)),
... (1, f, (11,), {}, ('x', )),
... (2, f, (2,)),
... ]
>>> context.execute_actions()
>>> output
[('f', (1,), {}), ('f', (2,), {})]
If the action raises an error, we convert it to a
ConfigurationExecutionError.
>>> output = []
>>> def bad():
... bad.xxx
>>> context.actions = [
... (1, f, (1,)),
... (1, f, (11,), {}, ('x', )),
... (2, f, (2,)),
... (3, bad, (), {}, (), 'oops')
... ]
>>> try:
... v = context.execute_actions()
... except ConfigurationExecutionError, v:
... pass
>>> print(v)
exceptions.AttributeError: 'function' object has no attribute 'xxx'
in:
oops
Note that actions executed before the error still have an effect:
>>> output
[('f', (1,), {}), ('f', (2,), {})]
The execution is re-entrant such that actions may be added by other
actions with the one caveat that the order of any added actions must
be equal to or larger than the current action.
>>> output = []
>>> def f(*a, **k):
... output.append(('f', a, k))
... context.actions.append((3, g, (8,), {}))
>>> def g(*a, **k):
... output.append(('g', a, k))
>>> context.actions = [
... (1, f, (1,)),
... ]
>>> context.execute_actions()
>>> output
[('f', (1,), {}), ('g', (8,), {})]
"""
try:
all_actions = []
executed_actions = []
action_iter = iter([])
conflict_state = ConflictResolverState()
while True:
# We clear the actions list prior to execution so if there
# are some new actions then we add them to the mix and resolve
# conflicts again. This orders the new actions as well as
# ensures that the previously executed actions have no new
# conflicts.
if self.actions:
all_actions.extend(self.actions)
action_iter = resolveConflicts(
self.actions,
state=conflict_state,
)
self.actions = []
action = next(action_iter, None)
if action is None:
# we are done!
break
callable = action["callable"]
args = action["args"]
kw = action["kw"]
info = action["info"]
# we use "get" below in case an action was added via a ZCML
# directive that did not know about introspectables
introspectables = action.get("introspectables", ())
try:
if callable is not None:
callable(*args, **kw)
except Exception:
t, v, tb = sys.exc_info()
try:
reraise(
ConfigurationExecutionError,
ConfigurationExecutionError(t, v, info),
tb,
)
finally:
del t, v, tb
if introspector is not None:
for introspectable in introspectables:
introspectable.register(introspector, info)
executed_actions.append(action)
self.actions = all_actions
return executed_actions
finally:
if clear:
self.actions = []
|
def execute_actions(self, clear=True, introspector=None):
"""Execute the configuration actions
This calls the action callables after resolving conflicts
For example:
>>> output = []
>>> def f(*a, **k):
... output.append(('f', a, k))
>>> context = ActionState()
>>> context.actions = [
... (1, f, (1,)),
... (1, f, (11,), {}, ('x', )),
... (2, f, (2,)),
... ]
>>> context.execute_actions()
>>> output
[('f', (1,), {}), ('f', (2,), {})]
If the action raises an error, we convert it to a
ConfigurationExecutionError.
>>> output = []
>>> def bad():
... bad.xxx
>>> context.actions = [
... (1, f, (1,)),
... (1, f, (11,), {}, ('x', )),
... (2, f, (2,)),
... (3, bad, (), {}, (), 'oops')
... ]
>>> try:
... v = context.execute_actions()
... except ConfigurationExecutionError, v:
... pass
>>> print(v)
exceptions.AttributeError: 'function' object has no attribute 'xxx'
in:
oops
Note that actions executed before the error still have an effect:
>>> output
[('f', (1,), {}), ('f', (2,), {})]
The execution is re-entrant such that actions may be added by other
actions with the one caveat that the order of any added actions must
be equal to or larger than the current action.
>>> output = []
>>> def f(*a, **k):
... output.append(('f', a, k))
... context.actions.append((3, g, (8,), {}))
>>> def g(*a, **k):
... output.append(('g', a, k))
>>> context.actions = [
... (1, f, (1,)),
... ]
>>> context.execute_actions()
>>> output
[('f', (1,), {}), ('g', (8,), {})]
"""
try:
all_actions = []
executed_actions = []
pending_actions = iter([])
# resolve the new action list against what we have already
# executed -- if a new action appears intertwined in the list
# of already-executed actions then someone wrote a broken
# re-entrant action because it scheduled the action *after* it
# should have been executed (as defined by the action order)
def resume(actions):
for a, b in zip_longest(actions, executed_actions):
if b is None and a is not None:
# common case is that we are executing every action
yield a
elif b is not None and a != b:
raise ConfigurationError(
"During execution a re-entrant action was added "
"that modified the planned execution order in a "
"way that is incompatible with what has already "
"been executed."
)
else:
# resolved action is in the same location as before,
# so we are in good shape, but the action is already
# executed so we skip it
assert b is not None and a == b
while True:
# We clear the actions list prior to execution so if there
# are some new actions then we add them to the mix and resolve
# conflicts again. This orders the new actions as well as
# ensures that the previously executed actions have no new
# conflicts.
if self.actions:
# Only resolve the new actions against executed_actions
# and pending_actions instead of everything to avoid
# redundant checks.
# Assume ``actions = resolveConflicts([A, B, C])`` which
# after conflict checks, resulted in ``actions == [A]``
# then we know action A won out or a conflict would have
# been raised. Thus, when action D is added later, we only
# need to check the new action against A.
# ``actions = resolveConflicts([A, D]) should drop the
# number of redundant checks down from O(n^2) closer to
# O(n lg n).
all_actions.extend(self.actions)
pending_actions = resume(
resolveConflicts(
executed_actions + list(pending_actions) + self.actions
)
)
self.actions = []
action = next(pending_actions, None)
if action is None:
# we are done!
break
callable = action["callable"]
args = action["args"]
kw = action["kw"]
info = action["info"]
# we use "get" below in case an action was added via a ZCML
# directive that did not know about introspectables
introspectables = action.get("introspectables", ())
try:
if callable is not None:
callable(*args, **kw)
except (KeyboardInterrupt, SystemExit): # pragma: no cover
raise
except:
t, v, tb = sys.exc_info()
try:
reraise(
ConfigurationExecutionError,
ConfigurationExecutionError(t, v, info),
tb,
)
finally:
del t, v, tb
if introspector is not None:
for introspectable in introspectables:
introspectable.register(introspector, info)
executed_actions.append(action)
finally:
if clear:
del self.actions[:]
else:
self.actions = all_actions
|
https://github.com/Pylons/pyramid/issues/2697
|
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}
|
pyramid.exceptions.ConfigurationError
|
def resolveConflicts(actions, state=None):
"""Resolve conflicting actions
Given an actions list, identify and try to resolve conflicting actions.
Actions conflict if they have the same non-None discriminator.
Conflicting actions can be resolved if the include path of one of
the actions is a prefix of the includepaths of the other
conflicting actions and is unequal to the include paths in the
other conflicting actions.
Actions are resolved on a per-order basis because some discriminators
cannot be computed until earlier actions have executed. An action in an
earlier order may execute successfully only to find out later that it was
overridden by another action with a smaller include path. This will result
in a conflict as there is no way to revert the original action.
``state`` may be an instance of ``ConflictResolverState`` that
can be used to resume execution and resolve the new actions against the
list of executed actions from a previous call.
"""
if state is None:
state = ConflictResolverState()
# pick up where we left off last time, but track the new actions as well
state.remaining_actions.extend(normalize_actions(actions))
actions = state.remaining_actions
def orderandpos(v):
n, v = v
return (v["order"] or 0, n)
def orderonly(v):
n, v = v
return v["order"] or 0
sactions = sorted(enumerate(actions, start=state.start), key=orderandpos)
for order, actiongroup in itertools.groupby(sactions, orderonly):
# "order" is an integer grouping. Actions in a lower order will be
# executed before actions in a higher order. All of the actions in
# one grouping will be executed (its callable, if any will be called)
# before any of the actions in the next.
output = []
unique = {}
# error out if we went backward in order
if state.min_order is not None and order < state.min_order:
r = [
"Actions were added to order={0} after execution had moved "
"on to order={1}. Conflicting actions: ".format(order, state.min_order)
]
for i, action in actiongroup:
for line in str(action["info"]).rstrip().split("\n"):
r.append(" " + line)
raise ConfigurationError("\n".join(r))
for i, action in actiongroup:
# Within an order, actions are executed sequentially based on
# original action ordering ("i").
# "ainfo" is a tuple of (i, action) where "i" is an integer
# expressing the relative position of this action in the action
# list being resolved, and "action" is an action dictionary. The
# purpose of an ainfo is to associate an "i" with a particular
# action; "i" exists for sorting after conflict resolution.
ainfo = (i, action)
# wait to defer discriminators until we are on their order because
# the discriminator may depend on state from a previous order
discriminator = undefer(action["discriminator"])
action["discriminator"] = discriminator
if discriminator is None:
# The discriminator is None, so this action can never conflict.
# We can add it directly to the result.
output.append(ainfo)
continue
L = unique.setdefault(discriminator, [])
L.append(ainfo)
# Check for conflicts
conflicts = {}
for discriminator, ainfos in unique.items():
# We use (includepath, i) as a sort key because we need to
# sort the actions by the paths so that the shortest path with a
# given prefix comes first. The "first" action is the one with the
# shortest include path. We break sorting ties using "i".
def bypath(ainfo):
path, i = ainfo[1]["includepath"], ainfo[0]
return path, order, i
ainfos.sort(key=bypath)
ainfo, rest = ainfos[0], ainfos[1:]
_, action = ainfo
# ensure this new action does not conflict with a previously
# resolved action from an earlier order / invocation
prev_ainfo = state.resolved_ainfos.get(discriminator)
if prev_ainfo is not None:
_, paction = prev_ainfo
basepath, baseinfo = paction["includepath"], paction["info"]
includepath = action["includepath"]
# if the new action conflicts with the resolved action then
# note the conflict, otherwise drop the action as it's
# effectively overriden by the previous action
if includepath[: len(basepath)] != basepath or includepath == basepath:
L = conflicts.setdefault(discriminator, [baseinfo])
L.append(action["info"])
else:
output.append(ainfo)
basepath, baseinfo = action["includepath"], action["info"]
for _, action in rest:
includepath = action["includepath"]
# Test whether path is a prefix of opath
if (
includepath[: len(basepath)] != basepath # not a prefix
or includepath == basepath
):
L = conflicts.setdefault(discriminator, [baseinfo])
L.append(action["info"])
if conflicts:
raise ConfigurationConflictError(conflicts)
# sort resolved actions by "i" and yield them one by one
for i, action in sorted(output, key=operator.itemgetter(0)):
# do not memoize the order until we resolve an action inside it
state.min_order = action["order"]
state.start = i + 1
state.remaining_actions.remove(action)
state.resolved_ainfos[action["discriminator"]] = (i, action)
yield action
|
def resolveConflicts(actions):
"""Resolve conflicting actions
Given an actions list, identify and try to resolve conflicting actions.
Actions conflict if they have the same non-None discriminator.
Conflicting actions can be resolved if the include path of one of
the actions is a prefix of the includepaths of the other
conflicting actions and is unequal to the include paths in the
other conflicting actions.
"""
def orderandpos(v):
n, v = v
if not isinstance(v, dict):
# old-style tuple action
v = expand_action(*v)
return (v["order"] or 0, n)
sactions = sorted(enumerate(actions), key=orderandpos)
def orderonly(v):
n, v = v
if not isinstance(v, dict):
# old-style tuple action
v = expand_action(*v)
return v["order"] or 0
for order, actiongroup in itertools.groupby(sactions, orderonly):
# "order" is an integer grouping. Actions in a lower order will be
# executed before actions in a higher order. All of the actions in
# one grouping will be executed (its callable, if any will be called)
# before any of the actions in the next.
unique = {}
output = []
for i, action in actiongroup:
# Within an order, actions are executed sequentially based on
# original action ordering ("i").
if not isinstance(action, dict):
# old-style tuple action
action = expand_action(*action)
# "ainfo" is a tuple of (order, i, action) where "order" is a
# user-supplied grouping, "i" is an integer expressing the relative
# position of this action in the action list being resolved, and
# "action" is an action dictionary. The purpose of an ainfo is to
# associate an "order" and an "i" with a particular action; "order"
# and "i" exist for sorting purposes after conflict resolution.
ainfo = (order, i, action)
discriminator = undefer(action["discriminator"])
action["discriminator"] = discriminator
if discriminator is None:
# The discriminator is None, so this action can never conflict.
# We can add it directly to the result.
output.append(ainfo)
continue
L = unique.setdefault(discriminator, [])
L.append(ainfo)
# Check for conflicts
conflicts = {}
for discriminator, ainfos in unique.items():
# We use (includepath, order, i) as a sort key because we need to
# sort the actions by the paths so that the shortest path with a
# given prefix comes first. The "first" action is the one with the
# shortest include path. We break sorting ties using "order", then
# "i".
def bypath(ainfo):
path, order, i = ainfo[2]["includepath"], ainfo[0], ainfo[1]
return path, order, i
ainfos.sort(key=bypath)
ainfo, rest = ainfos[0], ainfos[1:]
output.append(ainfo)
_, _, action = ainfo
basepath, baseinfo, discriminator = (
action["includepath"],
action["info"],
action["discriminator"],
)
for _, _, action in rest:
includepath = action["includepath"]
# Test whether path is a prefix of opath
if (
includepath[: len(basepath)] != basepath # not a prefix
or includepath == basepath
):
L = conflicts.setdefault(discriminator, [baseinfo])
L.append(action["info"])
if conflicts:
raise ConfigurationConflictError(conflicts)
# sort conflict-resolved actions by (order, i) and yield them one
# by one
for a in [x[2] for x in sorted(output, key=operator.itemgetter(0, 1))]:
yield a
|
https://github.com/Pylons/pyramid/issues/2697
|
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}
|
pyramid.exceptions.ConfigurationError
|
def orderandpos(v):
n, v = v
return (v["order"] or 0, n)
|
def orderandpos(v):
n, v = v
if not isinstance(v, dict):
# old-style tuple action
v = expand_action(*v)
return (v["order"] or 0, n)
|
https://github.com/Pylons/pyramid/issues/2697
|
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}
|
pyramid.exceptions.ConfigurationError
|
def orderonly(v):
n, v = v
return v["order"] or 0
|
def orderonly(v):
n, v = v
if not isinstance(v, dict):
# old-style tuple action
v = expand_action(*v)
return v["order"] or 0
|
https://github.com/Pylons/pyramid/issues/2697
|
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}
|
pyramid.exceptions.ConfigurationError
|
def bypath(ainfo):
path, i = ainfo[1]["includepath"], ainfo[0]
return path, order, i
|
def bypath(ainfo):
path, order, i = ainfo[2]["includepath"], ainfo[0], ainfo[1]
return path, order, i
|
https://github.com/Pylons/pyramid/issues/2697
|
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}
|
pyramid.exceptions.ConfigurationError
|
def __init__(self):
# keep a set of resolved discriminators to test against to ensure
# that a new action does not conflict with something already executed
self.resolved_ainfos = {}
# actions left over from a previous iteration
self.remaining_actions = []
# after executing an action we memoize its order to avoid any new
# actions sending us backward
self.min_order = None
# unique tracks the index of the action so we need it to increase
# monotonically across invocations to resolveConflicts
self.start = 0
|
def __init__(self):
# NB "actions" is an API, dep'd upon by pyramid_zcml's load_zcml func
self.actions = []
self._seen_files = set()
|
https://github.com/Pylons/pyramid/issues/2697
|
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}
|
pyramid.exceptions.ConfigurationError
|
def install_centos_new(
args: CommandLineArguments, root: str, epel_release: int
) -> List[str]:
# Repos for CentOS 8 and later
gpgpath = "/etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial"
gpgurl = "https://www.centos.org/keys/RPM-GPG-KEY-CentOS-Official"
epel_gpgpath = f"/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-{epel_release}"
epel_gpgurl = (
f"https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-{epel_release}"
)
if args.mirror:
appstream_url = (
f"baseurl={args.mirror}/centos/{args.release}/AppStream/x86_64/os"
)
baseos_url = f"baseurl={args.mirror}/centos/{args.release}/BaseOS/x86_64/os"
extras_url = f"baseurl={args.mirror}/centos/{args.release}/extras/x86_64/os"
centosplus_url = (
f"baseurl={args.mirror}/centos/{args.release}/centosplus/x86_64/os"
)
epel_url = f"baseurl={args.mirror}/epel/{epel_release}/Everything/x86_64"
else:
appstream_url = f"mirrorlist=http://mirrorlist.centos.org/?release={args.release}&arch=x86_64&repo=AppStream"
baseos_url = f"mirrorlist=http://mirrorlist.centos.org/?release={args.release}&arch=x86_64&repo=BaseOS"
extras_url = f"mirrorlist=http://mirrorlist.centos.org/?release={args.release}&arch=x86_64&repo=extras"
centosplus_url = f"mirrorlist=http://mirrorlist.centos.org/?release={args.release}&arch=x86_64&repo=centosplus"
epel_url = f"mirrorlist=https://mirrors.fedoraproject.org/mirrorlist?repo=epel-{epel_release}&arch=x86_64"
setup_dnf(
args,
root,
repos=[
Repo(
"AppStream",
f"CentOS-{args.release} - AppStream",
appstream_url,
gpgpath,
gpgurl,
),
Repo(
"BaseOS", f"CentOS-{args.release} - Base", baseos_url, gpgpath, gpgurl
),
Repo(
"extras", f"CentOS-{args.release} - Extras", extras_url, gpgpath, gpgurl
),
Repo(
"centosplus",
f"CentOS-{args.release} - Plus",
centosplus_url,
gpgpath,
gpgurl,
),
Repo(
"epel",
f"name=Extra Packages for Enterprise Linux {epel_release} - $basearch",
epel_url,
epel_gpgpath,
epel_gpgurl,
),
],
)
return ["AppStream", "BaseOS", "extras", "centosplus"]
|
def install_centos_new(
args: CommandLineArguments, root: str, epel_release: int
) -> List[str]:
# Repos for CentOS 8 and later
gpgpath = "/etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial"
gpgurl = "https://www.centos.org/keys/RPM-GPG-KEY-CentOS-Official"
epel_gpgpath = f"/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-{epel_release}"
epel_gpgurl = (
f"https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-{epel_release}"
)
if args.mirror:
appstream_url = (
f"baseurl={args.mirror}/centos/{args.release}/AppStream/x86_64/os"
)
baseos_url = f"baseurl={args.mirror}/centos/{args.release}/BaseOS/x86_64/os"
extras_url = f"baseurl={args.mirror}/centos/{args.release}/extras/x86_64/os"
centosplus_url = (
f"baseurl={args.mirror}/centos/{args.release}/centosplus/x86_64/os"
)
epel_url = f"baseurl={args.mirror}/epel/{epel_release}/Everything/x86_64/os"
else:
appstream_url = f"mirrorlist=http://mirrorlist.centos.org/?release={args.release}&arch=x86_64&repo=AppStream"
baseos_url = f"mirrorlist=http://mirrorlist.centos.org/?release={args.release}&arch=x86_64&repo=BaseOS"
extras_url = f"mirrorlist=http://mirrorlist.centos.org/?release={args.release}&arch=x86_64&repo=extras"
centosplus_url = f"mirrorlist=http://mirrorlist.centos.org/?release={args.release}&arch=x86_64&repo=centosplus"
epel_url = f"mirrorlist=https://mirrors.fedoraproject.org/mirrorlist?repo=epel-{epel_release}&arch=x86_64"
setup_dnf(
args,
root,
repos=[
Repo(
"AppStream",
f"CentOS-{args.release} - AppStream",
appstream_url,
gpgpath,
gpgurl,
),
Repo(
"BaseOS", f"CentOS-{args.release} - Base", baseos_url, gpgpath, gpgurl
),
Repo(
"extras", f"CentOS-{args.release} - Extras", extras_url, gpgpath, gpgurl
),
Repo(
"centosplus",
f"CentOS-{args.release} - Plus",
centosplus_url,
gpgpath,
gpgurl,
),
Repo(
"epel",
f"name=Extra Packages for Enterprise Linux {epel_release} - $basearch",
epel_url,
epel_gpgpath,
epel_gpgurl,
),
],
)
return ["AppStream", "BaseOS", "extras", "centosplus"]
|
https://github.com/systemd/mkosi/issues/561
|
...
‣ Mounting API VFS...
‣ Mounting API VFS complete.
CentOS-8 - AppStream 8.3 MB/s | 6.2 MB 00:00
CentOS-8 - Base 3.1 MB/s | 2.3 MB 00:00
CentOS-8 - Extras 19 kB/s | 8.1 kB 00:00
CentOS-8 - Plus 949 kB/s | 593 kB 00:00
name=Extra Packages for Enterprise Linux 8 - x86_64 718 B/s | 249 B 00:00
Errors during downloading metadata for repository 'epel':
- Status code: 404 for https://download-cc-rdu01.fedoraproject.org/pub/epel/8/Everything/x86_64/os/repodata/repomd.xml (IP: 8.43.85.72)
Error: Failed to download metadata for repo 'epel': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried
‣ Unmounting API VFS...
‣ Unmounting API VFS complete.
‣ Unmounting Package Cache...
‣ Unmounting Package Cache complete.
‣ Unmounting image...
‣ Unmounting image complete.
‣ Detaching image file...
‣ Detaching image file complete.
Traceback (most recent call last):
File "/usr/lib64/python3.8/runpy.py", line 192, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib64/python3.8/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/root/.local/lib/python3.8/site-packages/mkosi/__main__.py", line 28, in <module>
main()
File "/root/.local/lib/python3.8/site-packages/mkosi/__main__.py", line 22, in main
run_verb(a)
File "/root/.local/lib/python3.8/site-packages/mkosi/__init__.py", line 5497, in run_verb
build_stuff(args)
File "/root/.local/lib/python3.8/site-packages/mkosi/__init__.py", line 5310, in build_stuff
raw, tar, root_hash = build_image(args, root, do_run_build_script=False, cleanup=True)
File "/root/.local/lib/python3.8/site-packages/mkosi/__init__.py", line 5128, in build_image
install_distribution(args, root, do_run_build_script=do_run_build_script, cached=cached_tree)
File "/root/.local/lib/python3.8/site-packages/mkosi/__init__.py", line 2681, in install_distribution
install[args.distribution](args, root, do_run_build_script)
File "/usr/lib64/python3.8/contextlib.py", line 75, in inner
return func(*args, **kwds)
File "/root/.local/lib/python3.8/site-packages/mkosi/__init__.py", line 2122, in install_centos
invoke_dnf_or_yum(args, root, repos, packages)
File "/root/.local/lib/python3.8/site-packages/mkosi/__init__.py", line 2010, in invoke_dnf_or_yum
invoke_dnf(args, root, repositories, packages)
File "/root/.local/lib/python3.8/site-packages/mkosi/__init__.py", line 1698, in invoke_dnf
run(cmdline)
File "/root/.local/lib/python3.8/site-packages/mkosi/__init__.py", line 194, in run
return subprocess.run(cmdline, check=check, **kwargs)
File "/usr/lib64/python3.8/subprocess.py", line 512, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['dnf', '-y', '--config=/var/tmp/mkosi-a1tay8dv/dnf.conf', '--best', '--allowerasing', '--releasever=8', '--installroot=/var/tmp/mkosi-a1tay8dv/root', '--disablerepo=*', '--enablerepo=AppStream', '--enablerepo=BaseOS', '--enablerepo=extras', '--enablerepo=centosplus', '--enablerepo=epel', '--setopt=keepcache=1', '--setopt=install_weak_deps=0', '--nodocs', 'install', 'centos-release', 'systemd', 'epel-release']' returned non-zero exit status 1.
|
subprocess.CalledProcessError
|
def __init__(self, backend, rsa_cdata, evp_pkey):
res = backend._lib.RSA_check_key(rsa_cdata)
if res != 1:
errors = backend._consume_errors_with_text()
raise ValueError("Invalid private key", errors)
self._backend = backend
self._rsa_cdata = rsa_cdata
self._evp_pkey = evp_pkey
n = self._backend._ffi.new("BIGNUM **")
self._backend._lib.RSA_get0_key(
self._rsa_cdata,
n,
self._backend._ffi.NULL,
self._backend._ffi.NULL,
)
self._backend.openssl_assert(n[0] != self._backend._ffi.NULL)
self._key_size = self._backend._lib.BN_num_bits(n[0])
|
def __init__(self, backend, rsa_cdata, evp_pkey):
self._backend = backend
self._rsa_cdata = rsa_cdata
self._evp_pkey = evp_pkey
n = self._backend._ffi.new("BIGNUM **")
self._backend._lib.RSA_get0_key(
self._rsa_cdata,
n,
self._backend._ffi.NULL,
self._backend._ffi.NULL,
)
self._backend.openssl_assert(n[0] != self._backend._ffi.NULL)
self._key_size = self._backend._lib.BN_num_bits(n[0])
|
https://github.com/pyca/cryptography/issues/4706
|
Traceback (most recent call last):
File "bad_crypto.py", line 5, in <module>
jwt.encode({}, my_key, algorithm='RS256')
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/jwt/api_jwt.py", line 65, in encode
json_payload, key, algorithm, headers, json_encoder
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/jwt/api_jws.py", line 114, in encode
signature = alg_obj.sign(signing_input, key)
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/jwt/algorithms.py", line 313, in sign
return key.sign(msg, padding.PKCS1v15(), self.hash_alg())
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 415, in sign
return _rsa_sig_sign(self._backend, padding, algorithm, self, data)
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 239, in _rsa_sig_sign
assert errors[0].lib == backend._lib.ERR_LIB_RSA
AssertionError
|
AssertionError
|
def _openssh_public_key_bytes(self, key):
if isinstance(key, rsa.RSAPublicKey):
public_numbers = key.public_numbers()
return b"ssh-rsa " + base64.b64encode(
ssh._ssh_write_string(b"ssh-rsa")
+ ssh._ssh_write_mpint(public_numbers.e)
+ ssh._ssh_write_mpint(public_numbers.n)
)
elif isinstance(key, dsa.DSAPublicKey):
public_numbers = key.public_numbers()
parameter_numbers = public_numbers.parameter_numbers
return b"ssh-dss " + base64.b64encode(
ssh._ssh_write_string(b"ssh-dss")
+ ssh._ssh_write_mpint(parameter_numbers.p)
+ ssh._ssh_write_mpint(parameter_numbers.q)
+ ssh._ssh_write_mpint(parameter_numbers.g)
+ ssh._ssh_write_mpint(public_numbers.y)
)
elif isinstance(key, ed25519.Ed25519PublicKey):
raw_bytes = key.public_bytes(
serialization.Encoding.Raw, serialization.PublicFormat.Raw
)
return b"ssh-ed25519 " + base64.b64encode(
ssh._ssh_write_string(b"ssh-ed25519") + ssh._ssh_write_string(raw_bytes)
)
else:
assert isinstance(key, ec.EllipticCurvePublicKey)
public_numbers = key.public_numbers()
try:
curve_name = {
ec.SECP256R1: b"nistp256",
ec.SECP384R1: b"nistp384",
ec.SECP521R1: b"nistp521",
}[type(public_numbers.curve)]
except KeyError:
raise ValueError(
"Only SECP256R1, SECP384R1, and SECP521R1 curves are "
"supported by the SSH public key format"
)
point = key.public_bytes(
serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint
)
return (
b"ecdsa-sha2-"
+ curve_name
+ b" "
+ base64.b64encode(
ssh._ssh_write_string(b"ecdsa-sha2-" + curve_name)
+ ssh._ssh_write_string(curve_name)
+ ssh._ssh_write_string(point)
)
)
|
def _openssh_public_key_bytes(self, key):
if isinstance(key, rsa.RSAPublicKey):
public_numbers = key.public_numbers()
return b"ssh-rsa " + base64.b64encode(
ssh._ssh_write_string(b"ssh-rsa")
+ ssh._ssh_write_mpint(public_numbers.e)
+ ssh._ssh_write_mpint(public_numbers.n)
)
elif isinstance(key, dsa.DSAPublicKey):
public_numbers = key.public_numbers()
parameter_numbers = public_numbers.parameter_numbers
return b"ssh-dss " + base64.b64encode(
ssh._ssh_write_string(b"ssh-dss")
+ ssh._ssh_write_mpint(parameter_numbers.p)
+ ssh._ssh_write_mpint(parameter_numbers.q)
+ ssh._ssh_write_mpint(parameter_numbers.g)
+ ssh._ssh_write_mpint(public_numbers.y)
)
else:
assert isinstance(key, ec.EllipticCurvePublicKey)
public_numbers = key.public_numbers()
try:
curve_name = {
ec.SECP256R1: b"nistp256",
ec.SECP384R1: b"nistp384",
ec.SECP521R1: b"nistp521",
}[type(public_numbers.curve)]
except KeyError:
raise ValueError(
"Only SECP256R1, SECP384R1, and SECP521R1 curves are "
"supported by the SSH public key format"
)
point = key.public_bytes(
serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint
)
return (
b"ecdsa-sha2-"
+ curve_name
+ b" "
+ base64.b64encode(
ssh._ssh_write_string(b"ecdsa-sha2-" + curve_name)
+ ssh._ssh_write_string(curve_name)
+ ssh._ssh_write_string(point)
)
)
|
https://github.com/pyca/cryptography/issues/4808
|
print(key.__class__)
<class 'cryptography.hazmat.backends.openssl.ed25519._Ed25519PublicKey'>
key.public_bytes(Encoding.OpenSSH, PublicFormat.OpenSSH)
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/home/richard/.local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/ed25519.py", line 45, in public_bytes
encoding, format, self, self._evp_pkey, None
File "/home/richard/.local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1838, in _public_key_bytes
return self._openssh_public_key_bytes(key)
File "/home/richard/.local/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1886, in _openssh_public_key_bytes
assert isinstance(key, ec.EllipticCurvePublicKey)
AssertionError
|
AssertionError
|
def __init__(self, oid, value):
if not isinstance(oid, ObjectIdentifier):
raise TypeError("oid argument must be an ObjectIdentifier instance.")
if not isinstance(value, six.text_type):
raise TypeError("value argument must be a text type.")
if oid == NameOID.COUNTRY_NAME and len(value.encode("utf8")) != 2:
raise ValueError("Country name must be a 2 character country code")
if len(value) == 0:
raise ValueError("Value cannot be an empty string")
self._oid = oid
self._value = value
|
def __init__(self, oid, value):
if not isinstance(oid, ObjectIdentifier):
raise TypeError("oid argument must be an ObjectIdentifier instance.")
if not isinstance(value, six.text_type):
raise TypeError("value argument must be a text type.")
if oid == NameOID.COUNTRY_NAME and len(value.encode("utf8")) != 2:
raise ValueError("Country name must be a 2 character country code")
self._oid = oid
self._value = value
|
https://github.com/pyca/cryptography/issues/3649
|
Traceback (most recent call last):
File "openssl_error.py", line 19, in <module>
cert = builder.sign(private_key, hashes.SHA256(), default_backend())
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/x509/base.py", line 564, in sign
return backend.create_x509_certificate(self, private_key, algorithm)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 746, in create_x509_certificate
x509_cert, _encode_name_gc(self, builder._subject_name)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py", line 103, in _encode_name_gc
subject = _encode_name(backend, attributes)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py", line 97, in _encode_name
backend.openssl_assert(res == 1)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 107, in openssl_assert
return binding._openssl_assert(self._lib, ok)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 75, in _openssl_assert
errors_with_text
cryptography.exceptions.InternalError: Unknown OpenSSL error. This error is commonly encountered when another library is not cleaning up the OpenSSL error stack. If you are using cryptography with another library that uses OpenSSL try disabling it before reporting a bug. Otherwise please file an issue at https://github.com/pyca/cryptography/issues with information on how to reproduce this. ([_OpenSSLErrorWithText(code=218603672L, lib=13, func=122, reason=152, reason_text='error:0D07A098:asn1 encoding routines:ASN1_mbstring_ncopy:string too short')])
|
cryptography.exceptions.InternalError
|
def load_ssh_public_key(data, backend):
key_parts = data.split(b" ", 2)
if len(key_parts) < 2:
raise ValueError("Key is not in the proper format or contains extra data.")
key_type = key_parts[0]
if key_type == b"ssh-rsa":
loader = _load_ssh_rsa_public_key
elif key_type == b"ssh-dss":
loader = _load_ssh_dss_public_key
elif key_type in [
b"ecdsa-sha2-nistp256",
b"ecdsa-sha2-nistp384",
b"ecdsa-sha2-nistp521",
]:
loader = _load_ssh_ecdsa_public_key
else:
raise UnsupportedAlgorithm("Key type is not supported.")
key_body = key_parts[1]
try:
decoded_data = base64.b64decode(key_body)
except TypeError:
raise ValueError("Key is not in the proper format.")
inner_key_type, rest = _read_next_string(decoded_data)
if inner_key_type != key_type:
raise ValueError("Key header and key body contain different key type values.")
return loader(key_type, rest, backend)
|
def load_ssh_public_key(data, backend):
key_parts = data.split(b" ")
if len(key_parts) != 2 and len(key_parts) != 3:
raise ValueError("Key is not in the proper format or contains extra data.")
key_type = key_parts[0]
if key_type == b"ssh-rsa":
loader = _load_ssh_rsa_public_key
elif key_type == b"ssh-dss":
loader = _load_ssh_dss_public_key
elif key_type in [
b"ecdsa-sha2-nistp256",
b"ecdsa-sha2-nistp384",
b"ecdsa-sha2-nistp521",
]:
loader = _load_ssh_ecdsa_public_key
else:
raise UnsupportedAlgorithm("Key type is not supported.")
key_body = key_parts[1]
try:
decoded_data = base64.b64decode(key_body)
except TypeError:
raise ValueError("Key is not in the proper format.")
inner_key_type, rest = _read_next_string(decoded_data)
if inner_key_type != key_type:
raise ValueError("Key header and key body contain different key type values.")
return loader(key_type, rest, backend)
|
https://github.com/pyca/cryptography/issues/2199
|
from cryptography.hazmat import backends
from cryptography.hazmat.primitives import serialization
key=open('test_key.pub')
keyval = key.read()
serialization.load_ssh_public_key(keyval, backends.default_backend())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mike/.venvs/openstack/lib/python2.7/site-packages/cryptography/hazmat/primitives/serialization.py", line 40, in load_ssh_public_key
'Key is not in the proper format or contains extra data.')
ValueError: Key is not in the proper format or contains extra data.
|
ValueError
|
def encode_example(self, audio_or_path_or_fobj):
if isinstance(audio_or_path_or_fobj, (np.ndarray, list)):
return audio_or_path_or_fobj
elif isinstance(audio_or_path_or_fobj, six.string_types):
filename = audio_or_path_or_fobj
file_format = self._file_format or filename.split(".")[-1]
with tf.io.gfile.GFile(filename, "rb") as audio_f:
try:
return self._encode_file(audio_f, file_format)
except Exception as e: # pylint: disable=broad-except
utils.reraise(e, prefix=f"Error for {filename}: ")
else:
return self._encode_file(audio_or_path_or_fobj, self._file_format)
|
def encode_example(self, audio_or_path_or_fobj):
if isinstance(audio_or_path_or_fobj, (np.ndarray, list)):
return audio_or_path_or_fobj
elif isinstance(audio_or_path_or_fobj, six.string_types):
filename = audio_or_path_or_fobj
file_format = self._file_format or filename.split(".")[-1]
with tf.io.gfile.GFile(filename, "rb") as audio_f:
return self._encode_file(audio_f, file_format)
else:
return self._encode_file(audio_or_path_or_fobj, self._file_format)
|
https://github.com/tensorflow/datasets/issues/2513
|
2020-10-02 00:20:54.722953: I tensorflow_io/core/kernels/cpu_check.cc:128] Your CPU supports instructions that this TensorFlow IO binary was not compiled to use: AVX2 FMA
Running tests under Python 3.7.8: /opt/conda/bin/python3
[ RUN ] AudioSetTest.test_baseclass
INFO:tensorflow:time(__main__.AudioSetTest.test_baseclass): 0.26s
I1002 00:20:55.194009 140623569565056 test_util.py:1973] time(__main__.AudioSetTest.test_baseclass): 0.26s
[ OK ] AudioSetTest.test_baseclass
[ RUN ] AudioSetTest.test_download_and_prepare_as_dataset
Total configs: 0
I1002 00:20:55.196529 140623569565056 dataset_builder.py:358] Generating dataset audioset (/tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0)
Downloading and preparing dataset audioset/0.1.0 (download: Unknown size, generated: Unknown size, total: Unknown size) to /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0...
I1002 00:20:55.240417 140623569565056 dataset_builder.py:988] Generating split train
0 examples [00:00, ? examples/s]2020-10-02 00:20:55.405197: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 2300000000 Hz
2020-10-02 00:20:55.406191: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55a36ca68a90 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-10-02 00:20:55.406231: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version
2020-10-02 00:20:55.406430: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance.
2020-10-02 00:20:55.407146: W tensorflow/core/framework/op_kernel.cc:1767] OP_REQUIRES failed at whole_file_read_ops.cc:116 : Failed precondition: /home/jupyter/datasets/tensorflow_datasets/testing/test_data/fake_examples/audioset/trimmed_audio/.ipynb_checkpoints; Is a directory
Shuffling and writing examples to /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0.incompleteWO0GI5/audioset-train.tfrecord
0%| | 0/4 [00:00<?, ? examples/s]I1002 00:20:55.907156 140623569565056 tfrecords_writer.py:226] Done writing /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0.incompleteWO0GI5/audioset-train.tfrecord. Shard lengths: [4]
/opt/conda/lib/python3.7/site-packages/apache_beam/typehints/typehints.py:524: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working
if not isinstance(type_params, (collections.Sequence, set)):
I1002 00:20:56.328425 140623569565056 dataset_builder.py:413] Skipping computing stats for mode ComputeStatsMode.SKIP.
Dataset audioset downloaded and prepared to /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0. Subsequent calls will reuse this data.
I1002 00:20:56.329698 140623569565056 dataset_builder.py:512] Constructing tf.data.Dataset for split train, from /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0
I1002 00:20:56.386478 140623569565056 dataset_builder.py:512] Constructing tf.data.Dataset for split train, from /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0
I1002 00:20:56.650481 140623569565056 dataset_info.py:355] Load dataset info from /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0
I1002 00:20:56.651347 140623569565056 dataset_builder.py:512] Constructing tf.data.Dataset for split train, from /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0
I1002 00:20:56.678382 140623569565056 dataset_builder.py:512] Constructing tf.data.Dataset for split train, from /tmp/runmulqsrjk/tmp04tb3m6j/audioset/0.1.0
INFO:tensorflow:time(__main__.AudioSetTest.test_download_and_prepare_as_dataset): 1.6s
I1002 00:20:56.796965 140623569565056 test_util.py:1973] time(__main__.AudioSetTest.test_download_and_prepare_as_dataset): 1.6s
WARNING:tensorflow:From /opt/conda/lib/python3.7/contextlib.py:82: TensorFlowTestCase.test_session (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `self.session()` or `self.cached_session()` instead.
W1002 00:20:56.799427 140623569565056 deprecation.py:323] From /opt/conda/lib/python3.7/contextlib.py:82: TensorFlowTestCase.test_session (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `self.session()` or `self.cached_session()` instead.
2020-10-02 00:20:56.800127: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance.
Total configs: 0
I1002 00:20:56.800700 140623569565056 dataset_builder.py:358] Generating dataset audioset (/tmp/runmulqsrjk/tmp8uycbooq/audioset/0.1.0)
Downloading and preparing dataset audioset/0.1.0 (download: Unknown size, generated: Unknown size, total: Unknown size) to /tmp/runmulqsrjk/tmp8uycbooq/audioset/0.1.0...
I1002 00:20:56.801388 140623569565056 dataset_builder.py:988] Generating split train
INFO:tensorflow:time(__main__.AudioSetTest.test_download_and_prepare_as_dataset): 0.05s
I1002 00:20:56.847491 140623569565056 test_util.py:1973] time(__main__.AudioSetTest.test_download_and_prepare_as_dataset): 0.05s
[ FAILED ] AudioSetTest.test_download_and_prepare_as_dataset
Exception ignored in: <generator object Audioset._generate_examples at 0x7fe419f3c7d0>
RuntimeError: generator ignored GeneratorExit
[ RUN ] AudioSetTest.test_info
INFO:tensorflow:time(__main__.AudioSetTest.test_info): 0.0s
I1002 00:20:56.863561 140623569565056 test_util.py:1973] time(__main__.AudioSetTest.test_info): 0.0s
[ OK ] AudioSetTest.test_info
[ RUN ] AudioSetTest.test_registered
INFO:tensorflow:time(__main__.AudioSetTest.test_registered): 0.0s
I1002 00:20:56.865559 140623569565056 test_util.py:1973] time(__main__.AudioSetTest.test_registered): 0.0s
[ OK ] AudioSetTest.test_registered
[ RUN ] AudioSetTest.test_session
[ SKIPPED ] AudioSetTest.test_session
======================================================================
ERROR: test_download_and_prepare_as_dataset (__main__.AudioSetTest)
test_download_and_prepare_as_dataset (__main__.AudioSetTest)
Run the decorated test method.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/jupyter/datasets/tensorflow_datasets/testing/test_utils.py", line 341, in decorated
f(self, *args, **kwargs)
File "/home/jupyter/datasets/tensorflow_datasets/testing/dataset_builder_testing.py", line 306, in test_download_and_prepare_as_dataset
self._download_and_prepare_as_dataset(self.builder)
File "/home/jupyter/datasets/tensorflow_datasets/testing/dataset_builder_testing.py", line 370, in _download_and_prepare_as_dataset
builder.download_and_prepare(download_config=download_config)
File "/home/jupyter/datasets/tensorflow_datasets/core/dataset_builder.py", line 388, in download_and_prepare
download_config=download_config)
File "/home/jupyter/datasets/tensorflow_datasets/core/dataset_builder.py", line 1042, in _download_and_prepare
max_examples_per_split=download_config.max_examples_per_split,
File "/home/jupyter/datasets/tensorflow_datasets/core/dataset_builder.py", line 992, in _download_and_prepare
self._prepare_split(split_generator, **prepare_split_kwargs)
File "/home/jupyter/datasets/tensorflow_datasets/core/dataset_builder.py", line 1058, in _prepare_split
example = self.info.features.encode_example(record)
File "/home/jupyter/datasets/tensorflow_datasets/core/features/features_dict.py", line 195, in encode_example
in utils.zip_dict(self._feature_dict, example_dict)
File "/home/jupyter/datasets/tensorflow_datasets/core/features/features_dict.py", line 194, in <dictcomp>
for k, (feature, example_value)
File "/home/jupyter/datasets/tensorflow_datasets/core/features/feature.py", line 605, in encode_example
example_data = np.array(example_data, dtype=np_dtype)
TypeError: __array__() takes 1 positional argument but 2 were given
----------------------------------------------------------------------
Ran 5 tests in 1.928s
FAILED (errors=1, skipped=1)
|
RuntimeError
|
def as_dataframe(
ds: tf.data.Dataset,
ds_info: Optional[dataset_info.DatasetInfo] = None,
) -> StyledDataFrame:
"""Convert the dataset into a pandas dataframe.
Warning: The dataframe will be loaded entirely in memory, you may
want to call `tfds.as_dataframe` on a subset of the data instead:
```
df = tfds.as_dataframe(ds.take(10), ds_info)
```
Args:
ds: `tf.data.Dataset`. The tf.data.Dataset object to convert to panda
dataframe. Examples should not be batched. The full dataset will be
loaded.
ds_info: Dataset info object. If given, helps improving the formatting.
Available either through `tfds.load('mnist', with_info=True)` or
`tfds.builder('mnist').info`
Returns:
dataframe: The `pandas.DataFrame` object
"""
# Raise a clean error message if panda isn't installed.
lazy_imports_lib.lazy_imports.pandas # pylint: disable=pointless-statement
# Pack `as_supervised=True` datasets
if ds_info:
ds = dataset_info.pack_as_supervised_ds(ds, ds_info)
# Flatten the keys names, specs,... while keeping the feature key definition
# order
columns = _make_columns(ds.element_spec, ds_info=ds_info)
rows = [_make_row_dict(ex, columns) for ex in dataset_utils.as_numpy(ds)]
df = StyledDataFrame(rows)
df.current_style.format({c.name: c.format_fn for c in columns if c.format_fn})
return df
|
def as_dataframe(
ds: tf.data.Dataset,
ds_info: Optional[dataset_info.DatasetInfo] = None,
) -> StyledDataFrame:
"""Convert the dataset into a pandas dataframe.
Warning: The dataframe will be loaded entirely in memory, you may
want to call `tfds.as_dataframe` on a subset of the data instead:
```
df = tfds.as_dataframe(ds.take(10), ds_info)
```
Args:
ds: `tf.data.Dataset`. The tf.data.Dataset object to convert to panda
dataframe. Examples should not be batched. The full dataset will be
loaded.
ds_info: Dataset info object. If given, helps improving the formatting.
Available either through `tfds.load('mnist', with_info=True)` or
`tfds.builder('mnist').info`
Returns:
dataframe: The `pandas.DataFrame` object
"""
# Raise a clean error message if panda isn't installed.
lazy_imports_lib.lazy_imports.pandas # pylint: disable=pointless-statement
# Flatten the keys names, specs,... while keeping the feature key definition
# order
columns = _make_columns(ds.element_spec, ds_info=ds_info)
rows = [_make_row_dict(ex, columns) for ex in dataset_utils.as_numpy(ds)]
df = StyledDataFrame(rows)
df.current_style.format({c.name: c.format_fn for c in columns if c.format_fn})
return df
|
https://github.com/tensorflow/datasets/issues/2476
|
Traceback (most recent call last):
File "mnist_test.py", line 31, in <module>
df = tfds.as_dataframe(ds_test.take(10), ds_info)
File "/home/ubuntu/miniconda3/envs/tensorflow/lib/python3.8/site-packages/tensorflow_datasets/core/as_dataframe.py", line 192, in as_dataframe
columns = _make_columns(ds.element_spec, ds_info=ds_info)
File "/home/ubuntu/miniconda3/envs/tensorflow/lib/python3.8/site-packages/tensorflow_datasets/core/as_dataframe.py", line 148, in _make_columns
return [
File "/home/ubuntu/miniconda3/envs/tensorflow/lib/python3.8/site-packages/tensorflow_datasets/core/as_dataframe.py", line 149, in <listcomp>
ColumnInfo.from_spec(path, ds_info)
File "/home/ubuntu/miniconda3/envs/tensorflow/lib/python3.8/site-packages/tensorflow_datasets/core/as_dataframe.py", line 61, in from_spec
name = '/'.join(path)
TypeError: sequence item 0: expected str instance, int found
|
TypeError
|
def show_examples(
ds: tf.data.Dataset, ds_info: dataset_info.DatasetInfo, **options_kwargs: Any
):
"""Visualize images (and labels) from an image classification dataset.
This function is for interactive use (Colab, Jupyter). It displays and return
a plot of (rows*columns) images from a tf.data.Dataset.
Usage:
```python
ds, ds_info = tfds.load('cifar10', split='train', with_info=True)
fig = tfds.show_examples(ds, ds_info)
```
Args:
ds: `tf.data.Dataset`. The tf.data.Dataset object to visualize. Examples
should not be batched. Examples will be consumed in order until
(rows * cols) are read or the dataset is consumed.
ds_info: The dataset info object to which extract the label and features
info. Available either through `tfds.load('mnist', with_info=True)` or
`tfds.builder('mnist').info`
**options_kwargs: Additional display options, specific to the dataset type
to visualize. Are forwarded to `tfds.visualization.Visualizer.show`.
See the `tfds.visualization` for a list of available visualizers.
Returns:
fig: The `matplotlib.Figure` object
"""
if not isinstance(ds_info, dataset_info.DatasetInfo): # Arguments inverted
# `absl.logging` does not appear on Colab by default, so uses print instead.
print(
"WARNING: For consistency with `tfds.load`, the `tfds.show_examples` "
"signature has been modified from (info, ds) to (ds, info).\n"
"The old signature is deprecated and will be removed. "
"Please change your call to `tfds.show_examples(ds, info)`"
)
ds, ds_info = ds_info, ds
# Pack `as_supervised=True` datasets
ds = dataset_info.pack_as_supervised_ds(ds, ds_info)
for visualizer in _ALL_VISUALIZERS:
if visualizer.match(ds_info):
return visualizer.show(ds, ds_info, **options_kwargs)
raise ValueError(
"Visualisation not supported for dataset `{}`".format(ds_info.name)
)
|
def show_examples(
ds: tf.data.Dataset, ds_info: dataset_info.DatasetInfo, **options_kwargs: Any
):
"""Visualize images (and labels) from an image classification dataset.
This function is for interactive use (Colab, Jupyter). It displays and return
a plot of (rows*columns) images from a tf.data.Dataset.
Usage:
```python
ds, ds_info = tfds.load('cifar10', split='train', with_info=True)
fig = tfds.show_examples(ds, ds_info)
```
Args:
ds: `tf.data.Dataset`. The tf.data.Dataset object to visualize. Examples
should not be batched. Examples will be consumed in order until
(rows * cols) are read or the dataset is consumed.
ds_info: The dataset info object to which extract the label and features
info. Available either through `tfds.load('mnist', with_info=True)` or
`tfds.builder('mnist').info`
**options_kwargs: Additional display options, specific to the dataset type
to visualize. Are forwarded to `tfds.visualization.Visualizer.show`.
See the `tfds.visualization` for a list of available visualizers.
Returns:
fig: The `matplotlib.Figure` object
"""
if not isinstance(ds_info, dataset_info.DatasetInfo): # Arguments inverted
# `absl.logging` does not appear on Colab by default, so uses print instead.
print(
"WARNING: For consistency with `tfds.load`, the `tfds.show_examples` "
"signature has been modified from (info, ds) to (ds, info).\n"
"The old signature is deprecated and will be removed. "
"Please change your call to `tfds.show_examples(ds, info)`"
)
ds, ds_info = ds_info, ds
# Pack `as_supervised=True` datasets
if (
ds_info.supervised_keys
and isinstance(ds.element_spec, tuple)
and len(ds.element_spec) == 2
):
x_key, y_key = ds_info.supervised_keys
ds = ds.map(lambda x, y: {x_key: x, y_key: y})
for visualizer in _ALL_VISUALIZERS:
if visualizer.match(ds_info):
return visualizer.show(ds, ds_info, **options_kwargs)
raise ValueError(
"Visualisation not supported for dataset `{}`".format(ds_info.name)
)
|
https://github.com/tensorflow/datasets/issues/2476
|
Traceback (most recent call last):
File "mnist_test.py", line 31, in <module>
df = tfds.as_dataframe(ds_test.take(10), ds_info)
File "/home/ubuntu/miniconda3/envs/tensorflow/lib/python3.8/site-packages/tensorflow_datasets/core/as_dataframe.py", line 192, in as_dataframe
columns = _make_columns(ds.element_spec, ds_info=ds_info)
File "/home/ubuntu/miniconda3/envs/tensorflow/lib/python3.8/site-packages/tensorflow_datasets/core/as_dataframe.py", line 148, in _make_columns
return [
File "/home/ubuntu/miniconda3/envs/tensorflow/lib/python3.8/site-packages/tensorflow_datasets/core/as_dataframe.py", line 149, in <listcomp>
ColumnInfo.from_spec(path, ds_info)
File "/home/ubuntu/miniconda3/envs/tensorflow/lib/python3.8/site-packages/tensorflow_datasets/core/as_dataframe.py", line 61, in from_spec
name = '/'.join(path)
TypeError: sequence item 0: expected str instance, int found
|
TypeError
|
def __init__(self, num_classes, **kwargs):
self.num_classes = num_classes
if "version" not in kwargs:
kwargs["version"] = tfds.core.Version("1.2.0")
super(VisualDomainDecathlonConfig, self).__init__(**kwargs)
|
def __init__(self, num_classes, **kwargs):
self.num_classes = num_classes
if "version" not in kwargs:
kwargs["version"] = tfds.core.Version("1.1.0")
super(VisualDomainDecathlonConfig, self).__init__(**kwargs)
|
https://github.com/tensorflow/datasets/issues/1978
|
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Chapter9.ipynb의 사본",
"provenance": [],
"collapsed_sections": [],
"toc_visible": true,
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"accelerator": "GPU",
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"e3baa953c78b49f28ad9718fefdf608f": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"state": {
"_view_name": "HBoxView",
"_dom_classes": [],
"_model_name": "HBoxModel",
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.5.0",
"box_style": "",
"layout": "IPY_MODEL_d6fdc2f4fec04d99be1fca2c16bc65d4",
"_model_module": "@jupyter-widgets/controls",
"children": [
"IPY_MODEL_c13ecacfffe446a2bfcb0b19a1c7cfb6",
"IPY_MODEL_92a6feb046f842f2b8da0085c14522d2"
]
}
},
"d6fdc2f4fec04d99be1fca2c16bc65d4": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
},
"c13ecacfffe446a2bfcb0b19a1c7cfb6": {
"model_module": "@jupyter-widgets/controls",
"model_name": "IntProgressModel",
"state": {
"_view_name": "ProgressView",
"style": "IPY_MODEL_39892778554f4031ac965567d6761392",
"_dom_classes": [],
"description": "Dl Completed...: 100%",
"_model_name": "IntProgressModel",
"bar_style": "success",
"max": 1,
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"value": 1,
"_view_count": null,
"_view_module_version": "1.5.0",
"orientation": "horizontal",
"min": 0,
"description_tooltip": null,
"_model_module": "@jupyter-widgets/controls",
"layout": "IPY_MODEL_4656867897a442959569ada6e5527535"
}
},
"92a6feb046f842f2b8da0085c14522d2": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"state": {
"_view_name": "HTMLView",
"style": "IPY_MODEL_d6f5ddf8747543c5aaee3a7c0b77110e",
"_dom_classes": [],
"description": "",
"_model_name": "HTMLModel",
"placeholder": "",
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"value": " 2/2 [00:10<00:00, 5.25s/ url]",
"_view_count": null,
"_view_module_version": "1.5.0",
"description_tooltip": null,
"_model_module": "@jupyter-widgets/controls",
"layout": "IPY_MODEL_485bab8e7bef4bd3884a084a7601c823"
}
},
"39892778554f4031ac965567d6761392": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"state": {
"_view_name": "StyleView",
"_model_name": "ProgressStyleModel",
"description_width": "initial",
"_view_module": "@jupyter-widgets/base",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.2.0",
"bar_color": null,
"_model_module": "@jupyter-widgets/controls"
}
},
"4656867897a442959569ada6e5527535": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
},
"d6f5ddf8747543c5aaee3a7c0b77110e": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"state": {
"_view_name": "StyleView",
"_model_name": "DescriptionStyleModel",
"description_width": "",
"_view_module": "@jupyter-widgets/base",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.2.0",
"_model_module": "@jupyter-widgets/controls"
}
},
"485bab8e7bef4bd3884a084a7601c823": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
},
"4e520630f99a494c9fef00730b023cf5": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"state": {
"_view_name": "HBoxView",
"_dom_classes": [],
"_model_name": "HBoxModel",
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.5.0",
"box_style": "",
"layout": "IPY_MODEL_d130997a576f453d94e85902fc34f487",
"_model_module": "@jupyter-widgets/controls",
"children": [
"IPY_MODEL_8bc81e37fc514d7e9ecc065af6577ade",
"IPY_MODEL_cb5188feaa08467ea4814e2f5a114517"
]
}
},
"d130997a576f453d94e85902fc34f487": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
},
"8bc81e37fc514d7e9ecc065af6577ade": {
"model_module": "@jupyter-widgets/controls",
"model_name": "IntProgressModel",
"state": {
"_view_name": "ProgressView",
"style": "IPY_MODEL_96af3aa75ae74855b31789db7c5ad576",
"_dom_classes": [],
"description": "Dl Size...: 100%",
"_model_name": "IntProgressModel",
"bar_style": "success",
"max": 1,
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"value": 1,
"_view_count": null,
"_view_module_version": "1.5.0",
"orientation": "horizontal",
"min": 0,
"description_tooltip": null,
"_model_module": "@jupyter-widgets/controls",
"layout": "IPY_MODEL_2c6274b3244b47a3afdd5ec31c9b6578"
}
},
"cb5188feaa08467ea4814e2f5a114517": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"state": {
"_view_name": "HTMLView",
"style": "IPY_MODEL_10f9bc6e6e5844dca493bcfd5a60d6a7",
"_dom_classes": [],
"description": "",
"_model_name": "HTMLModel",
"placeholder": "",
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"value": " 773/773 [00:10<00:00, 73.84 MiB/s]",
"_view_count": null,
"_view_module_version": "1.5.0",
"description_tooltip": null,
"_model_module": "@jupyter-widgets/controls",
"layout": "IPY_MODEL_1fcaba23486a469484f3859dbb589dcd"
}
},
"96af3aa75ae74855b31789db7c5ad576": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"state": {
"_view_name": "StyleView",
"_model_name": "ProgressStyleModel",
"description_width": "initial",
"_view_module": "@jupyter-widgets/base",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.2.0",
"bar_color": null,
"_model_module": "@jupyter-widgets/controls"
}
},
"2c6274b3244b47a3afdd5ec31c9b6578": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
},
"10f9bc6e6e5844dca493bcfd5a60d6a7": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"state": {
"_view_name": "StyleView",
"_model_name": "DescriptionStyleModel",
"description_width": "",
"_view_module": "@jupyter-widgets/base",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.2.0",
"_model_module": "@jupyter-widgets/controls"
}
},
"1fcaba23486a469484f3859dbb589dcd": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
},
"230673b52091440c963af32576916202": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"state": {
"_view_name": "HBoxView",
"_dom_classes": [],
"_model_name": "HBoxModel",
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.5.0",
"box_style": "",
"layout": "IPY_MODEL_db8a26866bea412381a8b581e66acb26",
"_model_module": "@jupyter-widgets/controls",
"children": [
"IPY_MODEL_5d6f8b3d1d26429bbc3003808e849e42",
"IPY_MODEL_98c7a1d06e794fcabab1a63c75b1ad09"
]
}
},
"db8a26866bea412381a8b581e66acb26": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
},
"5d6f8b3d1d26429bbc3003808e849e42": {
"model_module": "@jupyter-widgets/controls",
"model_name": "IntProgressModel",
"state": {
"_view_name": "ProgressView",
"style": "IPY_MODEL_417808baf1bf4eeab6b81292b33af0d3",
"_dom_classes": [],
"description": "Extraction completed...: ",
"_model_name": "IntProgressModel",
"bar_style": "success",
"max": 1,
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"value": 0,
"_view_count": null,
"_view_module_version": "1.5.0",
"orientation": "horizontal",
"min": 0,
"description_tooltip": null,
"_model_module": "@jupyter-widgets/controls",
"layout": "IPY_MODEL_6042d93f17b2493fa756926aa6ce262f"
}
},
"98c7a1d06e794fcabab1a63c75b1ad09": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"state": {
"_view_name": "HTMLView",
"style": "IPY_MODEL_a0ed9f9d21684b26944e8858446f040f",
"_dom_classes": [],
"description": "",
"_model_name": "HTMLModel",
"placeholder": "",
"_view_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"value": " 0/0 [00:10<?, ? file/s]",
"_view_count": null,
"_view_module_version": "1.5.0",
"description_tooltip": null,
"_model_module": "@jupyter-widgets/controls",
"layout": "IPY_MODEL_6b805bba85b6416e927d89e8a741730f"
}
},
"417808baf1bf4eeab6b81292b33af0d3": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"state": {
"_view_name": "StyleView",
"_model_name": "ProgressStyleModel",
"description_width": "initial",
"_view_module": "@jupyter-widgets/base",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.2.0",
"bar_color": null,
"_model_module": "@jupyter-widgets/controls"
}
},
"6042d93f17b2493fa756926aa6ce262f": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
},
"a0ed9f9d21684b26944e8858446f040f": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"state": {
"_view_name": "StyleView",
"_model_name": "DescriptionStyleModel",
"description_width": "",
"_view_module": "@jupyter-widgets/base",
"_model_module_version": "1.5.0",
"_view_count": null,
"_view_module_version": "1.2.0",
"_model_module": "@jupyter-widgets/controls"
}
},
"6b805bba85b6416e927d89e8a741730f": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"state": {
"_view_name": "LayoutView",
"grid_template_rows": null,
"right": null,
"justify_content": null,
"_view_module": "@jupyter-widgets/base",
"overflow": null,
"_model_module_version": "1.2.0",
"_view_count": null,
"flex_flow": null,
"width": null,
"min_width": null,
"border": null,
"align_items": null,
"bottom": null,
"_model_module": "@jupyter-widgets/base",
"top": null,
"grid_column": null,
"overflow_y": null,
"overflow_x": null,
"grid_auto_flow": null,
"grid_area": null,
"grid_template_columns": null,
"flex": null,
"_model_name": "LayoutModel",
"justify_items": null,
"grid_row": null,
"max_height": null,
"align_content": null,
"visibility": null,
"align_self": null,
"height": null,
"min_height": null,
"padding": null,
"grid_auto_rows": null,
"grid_gap": null,
"max_width": null,
"order": null,
"_view_module_version": "1.2.0",
"grid_template_areas": null,
"object_position": null,
"object_fit": null,
"grid_auto_columns": null,
"margin": null,
"display": null,
"left": null
}
}
}
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/greentec/f36b550c9b8c51b559ae3bb80588ae53/chapter9-ipynb.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"metadata": {
"id": "sB3yAPlnyOln",
"colab_type": "code",
"colab": {}
},
"source": [
"# select tensorflow 2 version.\n",
"try:\n",
" # %tensorflow_version only exists in Colab.\n",
" %tensorflow_version 2.x\n",
"except Exception:\n",
" pass\n",
"import tensorflow as tf\n",
"import numpy as np"
],
"execution_count": 0,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "Gus3HEyZUFvP",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "3ad85f50-fae8-4765-c59d-c5c5b833c5cf"
},
"source": [
"import sys\n",
"sys.version"
],
"execution_count": 9,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'3.6.9 (default, Nov 7 2019, 10:44:02) \\n[GCC 8.3.0]'"
]
},
"metadata": {
"tags": []
},
"execution_count": 9
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "FNJx8P3bUbVh",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "e93458df-1b0e-4518-fe6e-03ccd37ad015"
},
"source": [
"tfds.__version__"
],
"execution_count": 11,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'2.1.0'"
]
},
"metadata": {
"tags": []
},
"execution_count": 11
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "am6xHi4JUiDn",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "a67f4e6e-94e0-4d8f-8cbc-6e830ad0463e"
},
"source": [
"tf.__version__"
],
"execution_count": 12,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'2.2.0-rc3'"
]
},
"metadata": {
"tags": []
},
"execution_count": 12
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "5Vulg2u9cy5-",
"colab_type": "code",
"outputId": "e329c6be-8073-4436-c4eb-db2db36820cf",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 546,
"referenced_widgets": [
"e3baa953c78b49f28ad9718fefdf608f",
"d6fdc2f4fec04d99be1fca2c16bc65d4",
"c13ecacfffe446a2bfcb0b19a1c7cfb6",
"92a6feb046f842f2b8da0085c14522d2",
"39892778554f4031ac965567d6761392",
"4656867897a442959569ada6e5527535",
"d6f5ddf8747543c5aaee3a7c0b77110e",
"485bab8e7bef4bd3884a084a7601c823",
"4e520630f99a494c9fef00730b023cf5",
"d130997a576f453d94e85902fc34f487",
"8bc81e37fc514d7e9ecc065af6577ade",
"cb5188feaa08467ea4814e2f5a114517",
"96af3aa75ae74855b31789db7c5ad576",
"2c6274b3244b47a3afdd5ec31c9b6578",
"10f9bc6e6e5844dca493bcfd5a60d6a7",
"1fcaba23486a469484f3859dbb589dcd",
"230673b52091440c963af32576916202",
"db8a26866bea412381a8b581e66acb26",
"5d6f8b3d1d26429bbc3003808e849e42",
"98c7a1d06e794fcabab1a63c75b1ad09",
"417808baf1bf4eeab6b81292b33af0d3",
"6042d93f17b2493fa756926aa6ce262f",
"a0ed9f9d21684b26944e8858446f040f",
"6b805bba85b6416e927d89e8a741730f"
]
}
},
"source": [
"# 9.36 Load Oxford Pet Dataset\n",
"import tensorflow_datasets as tfds\n",
"# dataset, info = tfds.load('oxford_iiit_pet:3.0.0', with_info=True)\n",
"dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True)"
],
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"text": [
"\u001b[1mDownloading and preparing dataset oxford_iiit_pet/3.1.0 (download: 801.24 MiB, generated: Unknown size, total: 801.24 MiB) to /root/tensorflow_datasets/oxford_iiit_pet/3.1.0...\u001b[0m\n"
],
"name": "stdout"
},
{
"output_type": "display_data",
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "e3baa953c78b49f28ad9718fefdf608f",
"version_minor": 0,
"version_major": 2
},
"text/plain": [
"HBox(children=(IntProgress(value=1, bar_style='info', description='Dl Completed...', max=1, style=ProgressStyl…"
]
},
"metadata": {
"tags": []
}
},
{
"output_type": "display_data",
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "4e520630f99a494c9fef00730b023cf5",
"version_minor": 0,
"version_major": 2
},
"text/plain": [
"HBox(children=(IntProgress(value=1, bar_style='info', description='Dl Size...', max=1, style=ProgressStyle(des…"
]
},
"metadata": {
"tags": []
}
},
{
"output_type": "display_data",
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "230673b52091440c963af32576916202",
"version_minor": 0,
"version_major": 2
},
"text/plain": [
"HBox(children=(IntProgress(value=1, bar_style='info', description='Extraction completed...', max=1, style=Prog…"
]
},
"metadata": {
"tags": []
}
},
{
"output_type": "stream",
"text": [
"\n",
"\n",
"\n"
],
"name": "stdout"
},
{
"output_type": "error",
"ename": "NonMatchingChecksumError",
"evalue": "ignored",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNonMatchingChecksumError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-5-758162c9ab1a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtensorflow_datasets\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mtfds\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;31m# dataset, info = tfds.load('oxford_iiit_pet:3.0.0', with_info=True)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mdataset\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minfo\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtfds\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mload\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'oxford_iiit_pet:3.*.*'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mwith_info\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/api_utils.py\u001b[0m in \u001b[0;36mdisallow_positional_args_dec\u001b[0;34m(fn, instance, args, kwargs)\u001b[0m\n\u001b[1;32m 50\u001b[0m \u001b[0m_check_no_positional\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mismethod\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mallowed\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mallowed\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 51\u001b[0m \u001b[0m_check_required\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 52\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 53\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 54\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mdisallow_positional_args_dec\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mwrapped\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# pylint: disable=no-value-for-parameter\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/registered.py\u001b[0m in \u001b[0;36mload\u001b[0;34m(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)\u001b[0m\n\u001b[1;32m 303\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mdownload\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 304\u001b[0m \u001b[0mdownload_and_prepare_kwargs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdownload_and_prepare_kwargs\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 305\u001b[0;31m \u001b[0mdbuilder\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdownload_and_prepare\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0mdownload_and_prepare_kwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 306\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 307\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mas_dataset_kwargs\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/api_utils.py\u001b[0m in \u001b[0;36mdisallow_positional_args_dec\u001b[0;34m(fn, instance, args, kwargs)\u001b[0m\n\u001b[1;32m 50\u001b[0m \u001b[0m_check_no_positional\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mismethod\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mallowed\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mallowed\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 51\u001b[0m \u001b[0m_check_required\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 52\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 53\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 54\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mdisallow_positional_args_dec\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mwrapped\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# pylint: disable=no-value-for-parameter\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/dataset_builder.py\u001b[0m in \u001b[0;36mdownload_and_prepare\u001b[0;34m(self, download_dir, download_config)\u001b[0m\n\u001b[1;32m 338\u001b[0m self._download_and_prepare(\n\u001b[1;32m 339\u001b[0m \u001b[0mdl_manager\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdl_manager\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 340\u001b[0;31m download_config=download_config)\n\u001b[0m\u001b[1;32m 341\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 342\u001b[0m \u001b[0;31m# NOTE: If modifying the lines below to put additional information in\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/dataset_builder.py\u001b[0m in \u001b[0;36m_download_and_prepare\u001b[0;34m(self, dl_manager, download_config)\u001b[0m\n\u001b[1;32m 1076\u001b[0m super(GeneratorBasedBuilder, self)._download_and_prepare(\n\u001b[1;32m 1077\u001b[0m \u001b[0mdl_manager\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdl_manager\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1078\u001b[0;31m \u001b[0mmax_examples_per_split\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mdownload_config\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmax_examples_per_split\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1079\u001b[0m )\n\u001b[1;32m 1080\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/dataset_builder.py\u001b[0m in \u001b[0;36m_download_and_prepare\u001b[0;34m(self, dl_manager, **prepare_split_kwargs)\u001b[0m\n\u001b[1;32m 917\u001b[0m prepare_split_kwargs)\n\u001b[1;32m 918\u001b[0m for split_generator in self._split_generators(\n\u001b[0;32m--> 919\u001b[0;31m dl_manager, **split_generators_kwargs):\n\u001b[0m\u001b[1;32m 920\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0msplits_lib\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mSplit\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mALL\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0msplit_generator\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msplit_info\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 921\u001b[0m raise ValueError(\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/image/oxford_iiit_pet.py\u001b[0m in \u001b[0;36m_split_generators\u001b[0;34m(self, dl_manager)\u001b[0m\n\u001b[1;32m 94\u001b[0m \"annotations\": tfds.download.Resource(\n\u001b[1;32m 95\u001b[0m \u001b[0murl\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0m_BASE_URL\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m\"/annotations.tar.gz\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 96\u001b[0;31m extract_method=tfds.download.ExtractMethod.TAR)\n\u001b[0m\u001b[1;32m 97\u001b[0m })\n\u001b[1;32m 98\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/download/download_manager.py\u001b[0m in \u001b[0;36mdownload_and_extract\u001b[0;34m(self, url_or_urls)\u001b[0m\n\u001b[1;32m 372\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_downloader\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtqdm\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 373\u001b[0m \u001b[0;32mwith\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_extractor\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtqdm\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 374\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0m_map_promise\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_download_extract\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0murl_or_urls\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 375\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 376\u001b[0m \u001b[0;34m@\u001b[0m\u001b[0mproperty\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/download/download_manager.py\u001b[0m in \u001b[0;36m_map_promise\u001b[0;34m(map_fn, all_inputs)\u001b[0m\n\u001b[1;32m 413\u001b[0m \u001b[0;34m\"\"\"Map the function into each element and resolve the promise.\"\"\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 414\u001b[0m \u001b[0mall_promises\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mutils\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmap_nested\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmap_fn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mall_inputs\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Apply the function\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 415\u001b[0;31m \u001b[0mres\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mutils\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmap_nested\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_wait_on_promise\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mall_promises\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 416\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mres\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/utils/py_utils.py\u001b[0m in \u001b[0;36mmap_nested\u001b[0;34m(function, data_struct, dict_only, map_tuple)\u001b[0m\n\u001b[1;32m 143\u001b[0m return {\n\u001b[1;32m 144\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mmap_nested\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfunction\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mv\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdict_only\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmap_tuple\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 145\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mv\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdata_struct\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 146\u001b[0m }\n\u001b[1;32m 147\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mdict_only\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/utils/py_utils.py\u001b[0m in \u001b[0;36m<dictcomp>\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m 143\u001b[0m return {\n\u001b[1;32m 144\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mmap_nested\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfunction\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mv\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdict_only\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmap_tuple\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 145\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0mk\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mv\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdata_struct\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mitems\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 146\u001b[0m }\n\u001b[1;32m 147\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mdict_only\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/utils/py_utils.py\u001b[0m in \u001b[0;36mmap_nested\u001b[0;34m(function, data_struct, dict_only, map_tuple)\u001b[0m\n\u001b[1;32m 157\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mtuple\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmapped\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 158\u001b[0m \u001b[0;31m# Singleton\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 159\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunction\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata_struct\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 160\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 161\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/download/download_manager.py\u001b[0m in \u001b[0;36m_wait_on_promise\u001b[0;34m(p)\u001b[0m\n\u001b[1;32m 397\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 398\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_wait_on_promise\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mp\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 399\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 400\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 401\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/promise/promise.py\u001b[0m in \u001b[0;36mget\u001b[0;34m(self, timeout)\u001b[0m\n\u001b[1;32m 510\u001b[0m \u001b[0mtarget\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_target\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 511\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_wait\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtimeout\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mDEFAULT_TIMEOUT\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 512\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_target_settled_value\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_raise\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 513\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 514\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_target_settled_value\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_raise\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/promise/promise.py\u001b[0m in \u001b[0;36m_target_settled_value\u001b[0;34m(self, _raise)\u001b[0m\n\u001b[1;32m 514\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_target_settled_value\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_raise\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 515\u001b[0m \u001b[0;31m# type: (bool) -> Any\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 516\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_target\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_settled_value\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_raise\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 517\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 518\u001b[0m \u001b[0m_value\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_reason\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_target_settled_value\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/promise/promise.py\u001b[0m in \u001b[0;36m_settled_value\u001b[0;34m(self, _raise)\u001b[0m\n\u001b[1;32m 224\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m_raise\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 225\u001b[0m \u001b[0mraise_val\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_fulfillment_handler0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 226\u001b[0;31m \u001b[0mreraise\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mraise_val\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mraise_val\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_traceback\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 227\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_fulfillment_handler0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 228\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/six.py\u001b[0m in \u001b[0;36mreraise\u001b[0;34m(tp, value, tb)\u001b[0m\n\u001b[1;32m 691\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__traceback__\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mtb\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 692\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwith_traceback\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 693\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mvalue\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 694\u001b[0m \u001b[0;32mfinally\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 695\u001b[0m \u001b[0mvalue\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/promise/promise.py\u001b[0m in \u001b[0;36mtry_catch\u001b[0;34m(handler, *args, **kwargs)\u001b[0m\n\u001b[1;32m 85\u001b[0m \u001b[0;31m# type: (Callable, Any, Any) -> Union[Tuple[Any, None], Tuple[None, Tuple[Exception, Optional[TracebackType]]]]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 86\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 87\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mhandler\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 88\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mException\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 89\u001b[0m \u001b[0mtb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mexc_info\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/download/download_manager.py\u001b[0m in \u001b[0;36mcallback\u001b[0;34m(val)\u001b[0m\n\u001b[1;32m 259\u001b[0m \u001b[0mchecksum\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdl_size\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mval\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 260\u001b[0m return self._handle_download_result(\n\u001b[0;32m--> 261\u001b[0;31m resource, download_dir_path, checksum, dl_size)\n\u001b[0m\u001b[1;32m 262\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_downloader\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdownload\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0murl\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdownload_dir_path\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mthen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcallback\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 263\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/usr/local/lib/python3.6/dist-packages/tensorflow_datasets/core/download/download_manager.py\u001b[0m in \u001b[0;36m_handle_download_result\u001b[0;34m(self, resource, tmp_dir_path, sha256, dl_size)\u001b[0m\n\u001b[1;32m 214\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_record_sizes_checksums\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 215\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mdl_size\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msha256\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m!=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_sizes_checksums\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mresource\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0murl\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 216\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mNonMatchingChecksumError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mresource\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0murl\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtmp_path\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 217\u001b[0m \u001b[0mdownload_path\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get_final_dl_path\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mresource\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0murl\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msha256\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 218\u001b[0m resource_lib.write_info_file(resource, download_path, self._dataset_name,\n",
"\u001b[0;31mNonMatchingChecksumError\u001b[0m: Artifact http://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz, downloaded to /root/tensorflow_datasets/downloads/robots.ox.ac.uk_vgg_pets_imageswMR1o1DWRq_DHWToagdXedb7P88RHpceK3WqG77VVwU.tar.gz.tmp.8db056945f8742e1ac3bd55247a766b8/images.tar.gz, has wrong checksum."
]
}
]
}
]
}
|
NonMatchingChecksumError
|
def _split_generators(self, dl_manager):
downloaded_dirs = dl_manager.download(
{
"img_align_celeba": IMG_ALIGNED_DATA,
"list_eval_partition": EVAL_LIST,
"list_attr_celeba": ATTR_DATA,
"landmarks_celeba": LANDMARKS_DATA,
}
)
# Load all images in memory (~1 GiB)
# Use split to convert: `img_align_celeba/000005.jpg` -> `000005.jpg`
all_images = {
os.path.split(k)[-1]: img
for k, img in dl_manager.iter_archive(downloaded_dirs["img_align_celeba"])
}
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs={
"file_id": 0,
"downloaded_dirs": downloaded_dirs,
"downloaded_images": all_images,
},
),
tfds.core.SplitGenerator(
name=tfds.Split.VALIDATION,
gen_kwargs={
"file_id": 1,
"downloaded_dirs": downloaded_dirs,
"downloaded_images": all_images,
},
),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs={
"file_id": 2,
"downloaded_dirs": downloaded_dirs,
"downloaded_images": all_images,
},
),
]
|
def _split_generators(self, dl_manager):
downloaded_dirs = dl_manager.download(
{
"img_align_celeba": IMG_ALIGNED_DATA,
"list_eval_partition": EVAL_LIST,
"list_attr_celeba": ATTR_DATA,
"landmarks_celeba": LANDMARKS_DATA,
}
)
# Load all images in memory (~1 GiB)
# Use split to convert: `img_align_celeba/000005.jpg` -> `000005.jpg`
all_images = {
k.split("/")[-1]: img
for k, img in dl_manager.iter_archive(downloaded_dirs["img_align_celeba"])
}
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs={
"file_id": 0,
"downloaded_dirs": downloaded_dirs,
"downloaded_images": all_images,
},
),
tfds.core.SplitGenerator(
name=tfds.Split.VALIDATION,
gen_kwargs={
"file_id": 1,
"downloaded_dirs": downloaded_dirs,
"downloaded_images": all_images,
},
),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs={
"file_id": 2,
"downloaded_dirs": downloaded_dirs,
"downloaded_images": all_images,
},
),
]
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _generate_examples(self, images, annotations, subdir, image_ids):
"""Yields images and annotations.
Args:
images: object that iterates over the archive of images.
annotations: object that iterates over the archive of annotations.
subdir: subdirectory from which to extract images and annotations, e.g.
training or testing.
image_ids: file ids for images in this split.
Yields:
A tuple containing the example's key, and the example.
"""
cv2 = tfds.core.lazy_imports.cv2
all_annotations = dict()
for fpath, fobj in annotations:
prefix, ext = os.path.splitext(fpath)
if ext != ".txt":
continue
if prefix.split(os.path.sep)[0] != subdir:
continue
# Key is the datapoint id. E.g. training/label_2/label_000016 -> 16.
all_annotations[int(prefix[-6:])] = _parse_kitti_annotations(fobj)
for fpath, fobj in images:
prefix, ext = os.path.splitext(fpath)
if ext != ".png":
continue
if prefix.split(os.path.sep)[0] != subdir:
continue
image_id = int(prefix[-6:])
if image_id not in image_ids:
continue
annotations = all_annotations[image_id]
img = cv2.imdecode(np.fromstring(fobj.read(), dtype=np.uint8), cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
height, width, _ = img.shape
for obj in annotations:
obj["bbox"] = _build_bounding_box(obj["bbox_raw"], height, width)
del obj["bbox_raw"]
_, fname = os.path.split(fpath)
record = {"image": img, "image/file_name": fname, "objects": annotations}
yield fname, record
|
def _generate_examples(self, images, annotations, subdir, image_ids):
"""Yields images and annotations.
Args:
images: object that iterates over the archive of images.
annotations: object that iterates over the archive of annotations.
subdir: subdirectory from which to extract images and annotations, e.g.
training or testing.
image_ids: file ids for images in this split.
Yields:
A tuple containing the example's key, and the example.
"""
cv2 = tfds.core.lazy_imports.cv2
all_annotations = dict()
for fpath, fobj in annotations:
prefix, ext = os.path.splitext(fpath)
if ext != ".txt":
continue
if prefix.split("/")[0] != subdir:
continue
# Key is the datapoint id. E.g. training/label_2/label_000016 -> 16.
all_annotations[int(prefix[-6:])] = _parse_kitti_annotations(fobj)
for fpath, fobj in images:
prefix, ext = os.path.splitext(fpath)
if ext != ".png":
continue
if prefix.split("/")[0] != subdir:
continue
image_id = int(prefix[-6:])
if image_id not in image_ids:
continue
annotations = all_annotations[image_id]
img = cv2.imdecode(np.fromstring(fobj.read(), dtype=np.uint8), cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
height, width, _ = img.shape
for obj in annotations:
obj["bbox"] = _build_bounding_box(obj["bbox_raw"], height, width)
del obj["bbox_raw"]
_, fname = os.path.split(fpath)
record = {"image": img, "image/file_name": fname, "objects": annotations}
yield fname, record
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _build_splits(devkit):
"""Splits the train data into train/val/test by video.
Ensures that images from the same video do not traverse the splits.
Args:
devkit: object that iterates over the devkit archive.
Returns:
train_images: File ids for the training set images.
validation_images: File ids for the validation set images.
test_images: File ids for the test set images.
"""
mapping_line_ids = None
mapping_lines = None
for fpath, fobj in devkit:
if fpath == os.path.join("mapping", "train_rand.txt"):
# Converts 1-based line index to 0-based line index.
mapping_line_ids = [
int(x.strip()) - 1 for x in fobj.read().decode("utf-8").split(",")
]
elif fpath == os.path.join("mapping", "train_mapping.txt"):
mapping_lines = fobj.read().splitlines()
mapping_lines = [x.decode("utf-8") for x in mapping_lines]
assert mapping_line_ids
assert mapping_lines
video_to_image = collections.defaultdict(list)
for image_id, mapping_lineid in enumerate(mapping_line_ids):
line = mapping_lines[mapping_lineid]
video_id = line.split(" ")[1]
video_to_image[video_id].append(image_id)
# Sets numpy random state.
numpy_original_state = np.random.get_state()
np.random.seed(seed=123)
# Max 1 for testing.
num_test_videos = max(1, _TEST_SPLIT_PERCENT_VIDEOS * len(video_to_image) // 100)
num_validation_videos = max(
1, _VALIDATION_SPLIT_PERCENT_VIDEOS * len(video_to_image) // 100
)
test_videos = set(
np.random.choice(
sorted(list(video_to_image.keys())), num_test_videos, replace=False
)
)
validation_videos = set(
np.random.choice(
sorted(list(set(video_to_image.keys()) - set(test_videos))),
num_validation_videos,
replace=False,
)
)
test_images = []
validation_images = []
train_images = []
for k, v in video_to_image.items():
if k in test_videos:
test_images.extend(v)
elif k in validation_videos:
validation_images.extend(v)
else:
train_images.extend(v)
# Resets numpy random state.
np.random.set_state(numpy_original_state)
return train_images, validation_images, test_images
|
def _build_splits(devkit):
"""Splits the train data into train/val/test by video.
Ensures that images from the same video do not traverse the splits.
Args:
devkit: object that iterates over the devkit archive.
Returns:
train_images: File ids for the training set images.
validation_images: File ids for the validation set images.
test_images: File ids for the test set images.
"""
mapping_line_ids = None
mapping_lines = None
for fpath, fobj in devkit:
if fpath == "mapping/train_rand.txt":
# Converts 1-based line index to 0-based line index.
mapping_line_ids = [
int(x.strip()) - 1 for x in fobj.read().decode("utf-8").split(",")
]
if fpath == "mapping/train_mapping.txt":
mapping_lines = fobj.readlines()
mapping_lines = [x.decode("utf-8") for x in mapping_lines]
assert mapping_line_ids
assert mapping_lines
video_to_image = collections.defaultdict(list)
for image_id, mapping_lineid in enumerate(mapping_line_ids):
line = mapping_lines[mapping_lineid]
video_id = line.split(" ")[1]
video_to_image[video_id].append(image_id)
# Sets numpy random state.
numpy_original_state = np.random.get_state()
np.random.seed(seed=123)
# Max 1 for testing.
num_test_videos = max(1, _TEST_SPLIT_PERCENT_VIDEOS * len(video_to_image) // 100)
num_validation_videos = max(
1, _VALIDATION_SPLIT_PERCENT_VIDEOS * len(video_to_image) // 100
)
test_videos = set(
np.random.choice(
sorted(list(video_to_image.keys())), num_test_videos, replace=False
)
)
validation_videos = set(
np.random.choice(
sorted(list(set(video_to_image.keys()) - set(test_videos))),
num_validation_videos,
replace=False,
)
)
test_images = []
validation_images = []
train_images = []
for k, v in video_to_image.items():
if k in test_videos:
test_images.extend(v)
elif k in validation_videos:
validation_images.extend(v)
else:
train_images.extend(v)
# Resets numpy random state.
np.random.set_state(numpy_original_state)
return train_images, validation_images, test_images
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _split_generators(self, dl_manager):
iris_file = dl_manager.download(IRIS_URL)
all_lines = tf.io.gfile.GFile(iris_file).read().splitlines()
records = [l for l in all_lines if l] # get rid of empty lines
# Specify the splits
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN, gen_kwargs={"records": records}
),
]
|
def _split_generators(self, dl_manager):
iris_file = dl_manager.download(IRIS_URL)
all_lines = tf.io.gfile.GFile(iris_file).read().split("\n")
records = [l for l in all_lines if l] # get rid of empty lines
# Specify the splits
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN, gen_kwargs={"records": records}
),
]
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
cfg = self.builder_config
download_urls = {cfg.name: "/".join([_DOWNLOAD_URL, "data", cfg.name + ".jsonl"])}
downloaded_files = dl_manager.download_and_extract(download_urls)
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN, gen_kwargs={"filepath": downloaded_files[cfg.name]}
)
]
|
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
cfg = self.builder_config
download_urls = {cfg.name: os.path.join(_DOWNLOAD_URL, "data", cfg.name + ".jsonl")}
downloaded_files = dl_manager.download_and_extract(download_urls)
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN, gen_kwargs={"filepath": downloaded_files[cfg.name]}
)
]
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
del dl_manager # Unused
lang = self._builder_config.language
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs={
"filepaths": os.path.join(
_DATA_DIRECTORY, "train", "{}_examples-*".format(lang)
)
},
),
tfds.core.SplitGenerator(
name=tfds.Split.VALIDATION,
gen_kwargs={
"filepaths": os.path.join(
_DATA_DIRECTORY, "dev", "{}_examples-*".format(lang)
)
},
),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs={
"filepaths": os.path.join(
_DATA_DIRECTORY, "test", "{}_examples-*".format(lang)
)
},
),
]
|
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
del dl_manager # Unused
lang = self._builder_config.language
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs={
"filepaths": "%s/train/%s_examples-*" % (_DATA_DIRECTORY, lang)
},
),
tfds.core.SplitGenerator(
name=tfds.Split.VALIDATION,
gen_kwargs={"filepaths": "%s/dev/%s_examples-*" % (_DATA_DIRECTORY, lang)},
),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs={"filepaths": "%s/test/%s_examples-*" % (_DATA_DIRECTORY, lang)},
),
]
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _parse_parallel_sentences(f1, f2):
"""Returns examples from parallel SGML or text files, which may be gzipped."""
def _parse_text(path):
"""Returns the sentences from a single text file, which may be gzipped."""
split_path = path.split(".")
if split_path[-1] == "gz":
lang = split_path[-2]
with tf.io.gfile.GFile(path, "rb") as f, gzip.GzipFile(fileobj=f) as g:
return g.read().decode("utf-8").splitlines(), lang
if split_path[-1] == "txt":
# CWMT
lang = split_path[-2].split("_")[-1]
lang = "zh" if lang in ("ch", "cn") else lang
else:
lang = split_path[-1]
with tf.io.gfile.GFile(path) as f:
return f.read().splitlines(), lang
def _parse_sgm(path):
"""Returns sentences from a single SGML file."""
lang = path.split(".")[-2]
sentences = []
# Note: We can't use the XML parser since some of the files are badly
# formatted.
seg_re = re.compile(r"<seg id=\"\d+\">(.*)</seg>")
with tf.io.gfile.GFile(path) as f:
for line in f:
seg_match = re.match(seg_re, line)
if seg_match:
assert len(seg_match.groups()) == 1
sentences.append(seg_match.groups()[0])
return sentences, lang
parse_file = _parse_sgm if f1.endswith(".sgm") else _parse_text
# Some datasets (e.g., CWMT) contain multiple parallel files specified with
# a wildcard. We sort both sets to align them and parse them one by one.
f1_files = tf.io.gfile.glob(f1)
f2_files = tf.io.gfile.glob(f2)
assert f1_files and f2_files, "No matching files found: %s, %s." % (f1, f2)
assert len(f1_files) == len(f2_files), (
"Number of files do not match: %d vs %d for %s vs %s."
% (len(f1_files), len(f2_files), f1, f2)
)
for f_id, (f1_i, f2_i) in enumerate(zip(sorted(f1_files), sorted(f2_files))):
l1_sentences, l1 = parse_file(f1_i)
l2_sentences, l2 = parse_file(f2_i)
assert len(l1_sentences) == len(l2_sentences), (
"Sizes do not match: %d vs %d for %s vs %s."
% (len(l1_sentences), len(l2_sentences), f1_i, f2_i)
)
for line_id, (s1, s2) in enumerate(zip(l1_sentences, l2_sentences)):
key = "{}/{}".format(f_id, line_id)
yield key, {l1: s1, l2: s2}
|
def _parse_parallel_sentences(f1, f2):
"""Returns examples from parallel SGML or text files, which may be gzipped."""
def _parse_text(path):
"""Returns the sentences from a single text file, which may be gzipped."""
split_path = path.split(".")
if split_path[-1] == "gz":
lang = split_path[-2]
with tf.io.gfile.GFile(path, "rb") as f, gzip.GzipFile(fileobj=f) as g:
return g.read().decode("utf-8").split("\n"), lang
if split_path[-1] == "txt":
# CWMT
lang = split_path[-2].split("_")[-1]
lang = "zh" if lang in ("ch", "cn") else lang
else:
lang = split_path[-1]
with tf.io.gfile.GFile(path) as f:
return f.read().split("\n"), lang
def _parse_sgm(path):
"""Returns sentences from a single SGML file."""
lang = path.split(".")[-2]
sentences = []
# Note: We can't use the XML parser since some of the files are badly
# formatted.
seg_re = re.compile(r"<seg id=\"\d+\">(.*)</seg>")
with tf.io.gfile.GFile(path) as f:
for line in f:
seg_match = re.match(seg_re, line)
if seg_match:
assert len(seg_match.groups()) == 1
sentences.append(seg_match.groups()[0])
return sentences, lang
parse_file = _parse_sgm if f1.endswith(".sgm") else _parse_text
# Some datasets (e.g., CWMT) contain multiple parallel files specified with
# a wildcard. We sort both sets to align them and parse them one by one.
f1_files = tf.io.gfile.glob(f1)
f2_files = tf.io.gfile.glob(f2)
assert f1_files and f2_files, "No matching files found: %s, %s." % (f1, f2)
assert len(f1_files) == len(f2_files), (
"Number of files do not match: %d vs %d for %s vs %s."
% (len(f1_files), len(f2_files), f1, f2)
)
for f_id, (f1_i, f2_i) in enumerate(zip(sorted(f1_files), sorted(f2_files))):
l1_sentences, l1 = parse_file(f1_i)
l2_sentences, l2 = parse_file(f2_i)
assert len(l1_sentences) == len(l2_sentences), (
"Sizes do not match: %d vs %d for %s vs %s."
% (len(l1_sentences), len(l2_sentences), f1_i, f2_i)
)
for line_id, (s1, s2) in enumerate(zip(l1_sentences, l2_sentences)):
key = "{}/{}".format(f_id, line_id)
yield key, {l1: s1, l2: s2}
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _parse_text(path):
"""Returns the sentences from a single text file, which may be gzipped."""
split_path = path.split(".")
if split_path[-1] == "gz":
lang = split_path[-2]
with tf.io.gfile.GFile(path, "rb") as f, gzip.GzipFile(fileobj=f) as g:
return g.read().decode("utf-8").splitlines(), lang
if split_path[-1] == "txt":
# CWMT
lang = split_path[-2].split("_")[-1]
lang = "zh" if lang in ("ch", "cn") else lang
else:
lang = split_path[-1]
with tf.io.gfile.GFile(path) as f:
return f.read().splitlines(), lang
|
def _parse_text(path):
"""Returns the sentences from a single text file, which may be gzipped."""
split_path = path.split(".")
if split_path[-1] == "gz":
lang = split_path[-2]
with tf.io.gfile.GFile(path, "rb") as f, gzip.GzipFile(fileobj=f) as g:
return g.read().decode("utf-8").split("\n"), lang
if split_path[-1] == "txt":
# CWMT
lang = split_path[-2].split("_")[-1]
lang = "zh" if lang in ("ch", "cn") else lang
else:
lang = split_path[-1]
with tf.io.gfile.GFile(path) as f:
return f.read().split("\n"), lang
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _parse_frde_bitext(fr_path, de_path):
with tf.io.gfile.GFile(fr_path) as f:
fr_sentences = f.read().splitlines()
with tf.io.gfile.GFile(de_path) as f:
de_sentences = f.read().splitlines()
assert len(fr_sentences) == len(de_sentences), (
"Sizes do not match: %d vs %d for %s vs %s."
% (len(fr_sentences), len(de_sentences), fr_path, de_path)
)
for line_id, (s1, s2) in enumerate(zip(fr_sentences, de_sentences)):
yield line_id, {"fr": s1, "de": s2}
|
def _parse_frde_bitext(fr_path, de_path):
with tf.io.gfile.GFile(fr_path) as f:
fr_sentences = f.read().split("\n")
with tf.io.gfile.GFile(de_path) as f:
de_sentences = f.read().split("\n")
assert len(fr_sentences) == len(de_sentences), (
"Sizes do not match: %d vs %d for %s vs %s."
% (len(fr_sentences), len(de_sentences), fr_path, de_path)
)
for line_id, (s1, s2) in enumerate(zip(fr_sentences, de_sentences)):
yield line_id, {"fr": s1, "de": s2}
|
https://github.com/tensorflow/datasets/issues/1901
|
AssertionError Traceback (most recent call last)
<ipython-input-1-0cac24b5abed> in <module>
1 import tensorflow_datasets as tfds
2
----> 3 ds, ds_info = tfds.load("caltech_birds2011", with_info=True)
4 print(ds_info)
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\registered.py in load(name, split, data_dir, batch_size, in_memory, shuffle_files, download, as_supervised, decoders, read_config, with_info, builder_kwargs, download_and_prepare_kwargs, as_dataset_kwargs, try_gcs)
307 if download:
308 download_and_prepare_kwargs = download_and_prepare_kwargs or {}
--> 309 dbuilder.download_and_prepare(**download_and_prepare_kwargs)
310
311 if as_dataset_kwargs is None:
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\api_utils.py in disallow_positional_args_dec(fn, instance, args, kwargs)
51 _check_no_positional(fn, args, ismethod, allowed=allowed)
52 _check_required(fn, kwargs)
---> 53 return fn(*args, **kwargs)
54
55 return disallow_positional_args_dec(wrapped) # pylint: disable=no-value-for-parameter
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in download_and_prepare(self, download_dir, download_config)
339 self._download_and_prepare(
340 dl_manager=dl_manager,
--> 341 download_config=download_config)
342
343 # NOTE: If modifying the lines below to put additional information in
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, download_config)
1077 super(GeneratorBasedBuilder, self)._download_and_prepare(
1078 dl_manager=dl_manager,
-> 1079 max_examples_per_split=download_config.max_examples_per_split,
1080 )
1081
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _download_and_prepare(self, dl_manager, **prepare_split_kwargs)
930
931 # Prepare split will record examples associated to the split
--> 932 self._prepare_split(split_generator, **prepare_split_kwargs)
933
934 # Update the info object with the splits.
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\dataset_builder.py in _prepare_split(self, split_generator, max_examples_per_split)
1105 example = self.info.features.encode_example(record)
1106 writer.write(key, example)
-> 1107 shard_lengths, total_size = writer.finalize()
1108 split_generator.split_info.shard_lengths.extend(shard_lengths)
1109 split_generator.split_info.num_bytes = total_size
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in finalize(self)
210 print("Shuffling and writing examples to %s" % self._path)
211 shard_specs = _get_shard_specs(self._num_examples, self._shuffler.size,
--> 212 self._shuffler.bucket_lengths, self._path)
213 # Here we just loop over the examples, and don't use the instructions, just
214 # the final number of examples in every shard. Instructions could be used to
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_specs(num_examples, total_size, bucket_lengths, path)
87 """
88 num_shards = _get_number_shards(total_size, num_examples)
---> 89 shard_boundaries = _get_shard_boundaries(num_examples, num_shards)
90 shard_specs = []
91 bucket_indexes = list(range(len(bucket_lengths)))
~\Desktop\TF_TFDS\datasets\tensorflow_datasets\core\tfrecords_writer.py in _get_shard_boundaries(num_examples, number_of_shards)
106 def _get_shard_boundaries(num_examples, number_of_shards):
107 if num_examples == 0:
--> 108 raise AssertionError("No examples were yielded.")
109 if num_examples < number_of_shards:
110 raise AssertionError("num_examples ({}) < number_of_shards ({})".format(
AssertionError: No examples were yielded.
|
AssertionError
|
def _normpath(path):
path = os.path.normpath(path)
if (
path.startswith(".")
or os.path.isabs(path)
or path.endswith("~")
or os.path.basename(path).startswith(".")
):
return None
return path
|
def _normpath(path):
path = os.path.normpath(path)
if path.startswith(".") or os.path.isabs(path):
raise UnsafeArchiveError("Archive at %s is not safe." % path)
if path.endswith("~") or os.path.basename(path).startswith("."):
return None
return path
|
https://github.com/tensorflow/datasets/issues/267
|
Dl Completed...: 0 url [00:00, ? url/s]
Dl Size...: 0 MiB [00:00, ? MiB/s]
Dl Completed...: 0%| | 0/1 [00:00<?, ? url/s]
Dl Size...: 0 MiB [00:00, ? MiB/s]
Dl Completed...: 0%| | 0/1 [00:00<?, ? url/s]
Dl Size...: 0 MiB [00:00, ? MiB/s]
Dl Completed...: 100%|██████████| 1/1 [00:01<00:00, 1.50s/ url]
Dl Size...: 0 MiB [00:01, ? MiB/s]
Dl Completed...: 100%|██████████| 1/1 [00:01<00:00, 1.50s/ url]
Dl Size...: 0 MiB [00:01, ? MiB/s]
Extraction completed...: 0%| | 0/1 [00:01<?, ? file/s]
---------------------------------------------------------------------------
UnsafeArchiveError Traceback (most recent call last)
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/download/extractor.py in _sync_extract(self, resource, to_path)
89 try:
---> 90 for path, handle in iter_archive(from_path, method):
91 _copy(handle, path and os.path.join(to_path_tmp, path) or to_path_tmp)
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/download/extractor.py in iter_tar(arch_f, gz)
139 if extract_file: # File with data (not directory):
--> 140 path = _normpath(member.path)
141 if not path:
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/download/extractor.py in _normpath(path)
116 if path.startswith('.') or os.path.isabs(path):
--> 117 raise UnsafeArchiveError('Archive at %s is not safe.' % path)
118 if path.endswith('~') or os.path.basename(path).startswith('.'):
UnsafeArchiveError: Archive at ._lists is not safe.
During handling of the above exception, another exception occurred:
ExtractError Traceback (most recent call last)
<ipython-input-1-5ecf00c50c12> in <module>
5 _SPLIT_URL = "http://www.vision.caltech.edu/visipedia-data/CUB-200/lists.tgz"
6 dl = tfds.download.DownloadManager(download_dir=download_dir)
----> 7 train_test_split_archive = dl.download_and_extract([_SPLIT_URL])
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/download/download_manager.py in download_and_extract(self, url_or_urls)
329 with self._downloader.tqdm():
330 with self._extractor.tqdm():
--> 331 return _map_promise(self._download_extract, url_or_urls)
332
333 @property
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/download/download_manager.py in _map_promise(map_fn, all_inputs)
365 """Map the function into each element and resolve the promise."""
366 all_promises = utils.map_nested(map_fn, all_inputs) # Apply the function
--> 367 res = utils.map_nested(_wait_on_promise, all_promises)
368 return res
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/utils/py_utils.py in map_nested(function, data_struct, dict_only, map_tuple)
136 if isinstance(data_struct, tuple(types)):
137 mapped = [map_nested(function, v, dict_only, map_tuple)
--> 138 for v in data_struct]
139 if isinstance(data_struct, list):
140 return mapped
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/utils/py_utils.py in <listcomp>(.0)
136 if isinstance(data_struct, tuple(types)):
137 mapped = [map_nested(function, v, dict_only, map_tuple)
--> 138 for v in data_struct]
139 if isinstance(data_struct, list):
140 return mapped
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/utils/py_utils.py in map_nested(function, data_struct, dict_only, map_tuple)
142 return tuple(mapped)
143 # Singleton
--> 144 return function(data_struct)
145
146
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/download/download_manager.py in _wait_on_promise(p)
349
350 def _wait_on_promise(p):
--> 351 return p.get()
352
353 else:
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/promise/promise.py in get(self, timeout)
508 target = self._target()
509 self._wait(timeout or DEFAULT_TIMEOUT)
--> 510 return self._target_settled_value(_raise=True)
511
512 def _target_settled_value(self, _raise=False):
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/promise/promise.py in _target_settled_value(self, _raise)
512 def _target_settled_value(self, _raise=False):
513 # type: (bool) -> Any
--> 514 return self._target()._settled_value(_raise)
515
516 _value = _reason = _target_settled_value
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/promise/promise.py in _settled_value(self, _raise)
222 if _raise:
223 raise_val = self._fulfillment_handler0
--> 224 reraise(type(raise_val), raise_val, self._traceback)
225 return self._fulfillment_handler0
226
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/six.py in reraise(tp, value, tb)
691 if value.__traceback__ is not tb:
692 raise value.with_traceback(tb)
--> 693 raise value
694 finally:
695 value = None
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/promise/promise.py in handle_future_result(future)
840 # type: (Any) -> None
841 try:
--> 842 resolve(future.result())
843 except Exception as e:
844 tb = exc_info()[2]
~/anaconda3/envs/tensorflow/lib/python3.6/concurrent/futures/_base.py in result(self, timeout)
423 raise CancelledError()
424 elif self._state == FINISHED:
--> 425 return self.__get_result()
426
427 self._condition.wait(timeout)
~/anaconda3/envs/tensorflow/lib/python3.6/concurrent/futures/_base.py in __get_result(self)
382 def __get_result(self):
383 if self._exception:
--> 384 raise self._exception
385 else:
386 return self._result
~/anaconda3/envs/tensorflow/lib/python3.6/concurrent/futures/thread.py in run(self)
54
55 try:
---> 56 result = self.fn(*self.args, **self.kwargs)
57 except BaseException as exc:
58 self.future.set_exception(exc)
~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow_datasets/core/download/extractor.py in _sync_extract(self, resource, to_path)
91 _copy(handle, path and os.path.join(to_path_tmp, path) or to_path_tmp)
92 except BaseException as err:
---> 93 raise ExtractError(resource, err)
94 # `tf.io.gfile.Rename(overwrite=True)` doesn't work for non empty
95 # directories, so delete destination first, if it already exists.
ExtractError: Error while extracting file /home/iswariya/Downloads/working/visio.calte.edu_visip-data_CUB-200_listskJqxLvtbYiwxBKy5Tl3x83yeAHQg_hP2VQx6CYqcVLk.tgz (http://www.vision.caltech.edu/visipedia-data/CUB-200/lists.tgz): Archive at ._lists is not safe..
|
UnsafeArchiveError
|
def open_browser():
# Child process
time.sleep(0.5)
webbrowser.open("http://localhost:%d/en/latest/index.html" % PORT, new=2)
|
def open_browser():
# Child process
time.sleep(0.5)
webbrowser.open("http://localhost:%d/en/latest/index.html" % PORT, new="tab")
|
https://github.com/bokeh/bokeh/issues/10105
|
Exception in thread Thread-2:
Traceback (most recent call last):
File "/home/p-himik/soft/miniconda3/envs/bokeh-dev/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/home/p-himik/soft/miniconda3/envs/bokeh-dev/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "docserver.py", line 43, in open_browser
webbrowser.open("http://localhost:%d/en/latest/index.html" % PORT, new="tab")
File "/home/p-himik/soft/miniconda3/envs/bokeh-dev/lib/python3.7/webbrowser.py", line 78, in open
if browser.open(url, new, autoraise):
File "/home/p-himik/soft/miniconda3/envs/bokeh-dev/lib/python3.7/webbrowser.py", line 251, in open
"expected 0, 1, or 2, got %s" % new)
webbrowser.Error: Bad 'new' parameter to open(); expected 0, 1, or 2, got tab
|
webbrowser.Error
|
async def connect(self):
log.info("WebSocket connection opened")
subprotocols = self.scope["subprotocols"]
if len(subprotocols) != 2 or subprotocols[0] != "bokeh":
self.close()
raise RuntimeError("Subprotocol header is not 'bokeh'")
token = subprotocols[1]
if token is None:
self.close()
raise RuntimeError("No token received in subprotocol header")
now = calendar.timegm(dt.datetime.utcnow().utctimetuple())
payload = get_token_payload(token)
if "session_expiry" not in payload:
self.close()
raise RuntimeError("Session expiry has not been provided")
elif now >= payload["session_expiry"]:
self.close()
raise RuntimeError("Token is expired.")
elif not check_token_signature(token, signed=False, secret_key=None):
session_id = get_session_id(token)
log.error("Token for session %r had invalid signature", session_id)
raise RuntimeError("Invalid token signature")
def on_fully_opened(future):
e = future.exception()
if e is not None:
# this isn't really an error (unless we have a
# bug), it just means a client disconnected
# immediately, most likely.
log.debug("Failed to fully open connlocksection %r", e)
future = self._async_open(token)
# rewrite above line using asyncio
# this task is scheduled to run soon once context is back to event loop
task = asyncio.ensure_future(future)
task.add_done_callback(on_fully_opened)
await self.accept("bokeh")
|
async def connect(self):
log.info("WebSocket connection opened")
subprotocols = self.scope["subprotocols"]
if len(subprotocols) != 2 or subprotocols[0] != "bokeh":
self.close()
raise RuntimeError("Subprotocol header is not 'bokeh'")
token = subprotocols[1]
if token is None:
self.close()
raise RuntimeError("No token received in subprotocol header")
now = calendar.timegm(dt.datetime.now().utctimetuple())
payload = get_token_payload(token)
if "session_expiry" not in payload:
self.close()
raise RuntimeError("Session expiry has not been provided")
elif now >= payload["session_expiry"]:
self.close()
raise RuntimeError("Token is expired.")
elif not check_token_signature(token, signed=False, secret_key=None):
session_id = get_session_id(token)
log.error("Token for session %r had invalid signature", session_id)
raise RuntimeError("Invalid token signature")
def on_fully_opened(future):
e = future.exception()
if e is not None:
# this isn't really an error (unless we have a
# bug), it just means a client disconnected
# immediately, most likely.
log.debug("Failed to fully open connlocksection %r", e)
future = self._async_open(token)
# rewrite above line using asyncio
# this task is scheduled to run soon once context is back to event loop
task = asyncio.ensure_future(future)
task.add_done_callback(on_fully_opened)
await self.accept("bokeh")
|
https://github.com/bokeh/bokeh/issues/9938
|
Traceback (most recent call last):
File "/Users/simon/anaconda3/lib/python3.6/site-packages/tornado/websocket.py", line 956, in _accept_connection
open_result = handler.open(*handler.open_args, **handler.open_kwargs)
File "/Users/simon/anaconda3/lib/python3.6/site-packages/bokeh/server/views/ws.py", line 135, in open
raise ProtocolError("Token is expired.")
bokeh.protocol.exceptions.ProtocolError: Token is expired
|
bokeh.protocol.exceptions.ProtocolError
|
def open(self):
"""Initialize a connection to a client.
Returns:
None
"""
log.info("WebSocket connection opened")
token = self._token
if self.selected_subprotocol != "bokeh":
self.close()
raise ProtocolError("Subprotocol header is not 'bokeh'")
elif token is None:
self.close()
raise ProtocolError("No token received in subprotocol header")
now = calendar.timegm(dt.datetime.utcnow().utctimetuple())
payload = get_token_payload(token)
if "session_expiry" not in payload:
self.close()
raise ProtocolError("Session expiry has not been provided")
elif now >= payload["session_expiry"]:
self.close()
raise ProtocolError("Token is expired.")
elif not check_token_signature(
token,
signed=self.application.sign_sessions,
secret_key=self.application.secret_key,
):
session_id = get_session_id(token)
log.error("Token for session %r had invalid signature", session_id)
raise ProtocolError("Invalid token signature")
try:
self.application.io_loop.spawn_callback(self._async_open, self._token)
except Exception as e:
# this isn't really an error (unless we have a
# bug), it just means a client disconnected
# immediately, most likely.
log.debug("Failed to fully open connection %r", e)
|
def open(self):
"""Initialize a connection to a client.
Returns:
None
"""
log.info("WebSocket connection opened")
token = self._token
if self.selected_subprotocol != "bokeh":
self.close()
raise ProtocolError("Subprotocol header is not 'bokeh'")
elif token is None:
self.close()
raise ProtocolError("No token received in subprotocol header")
now = calendar.timegm(dt.datetime.now().utctimetuple())
payload = get_token_payload(token)
if "session_expiry" not in payload:
self.close()
raise ProtocolError("Session expiry has not been provided")
elif now >= payload["session_expiry"]:
self.close()
raise ProtocolError("Token is expired.")
elif not check_token_signature(
token,
signed=self.application.sign_sessions,
secret_key=self.application.secret_key,
):
session_id = get_session_id(token)
log.error("Token for session %r had invalid signature", session_id)
raise ProtocolError("Invalid token signature")
try:
self.application.io_loop.spawn_callback(self._async_open, self._token)
except Exception as e:
# this isn't really an error (unless we have a
# bug), it just means a client disconnected
# immediately, most likely.
log.debug("Failed to fully open connection %r", e)
|
https://github.com/bokeh/bokeh/issues/9938
|
Traceback (most recent call last):
File "/Users/simon/anaconda3/lib/python3.6/site-packages/tornado/websocket.py", line 956, in _accept_connection
open_result = handler.open(*handler.open_args, **handler.open_kwargs)
File "/Users/simon/anaconda3/lib/python3.6/site-packages/bokeh/server/views/ws.py", line 135, in open
raise ProtocolError("Token is expired.")
bokeh.protocol.exceptions.ProtocolError: Token is expired
|
bokeh.protocol.exceptions.ProtocolError
|
def generate_jwt_token(
session_id: str,
secret_key: Optional[bytes] = settings.secret_key_bytes(),
signed: bool = settings.sign_sessions(),
extra_payload: Optional[Dict[str, Any]] = None,
expiration: int = 300,
) -> str:
"""Generates a JWT token given a session_id and additional payload.
Args:
session_id (str):
The session id to add to the token
secret_key (str, optional) :
Secret key (default: value of BOKEH_SECRET_KEY environment varariable)
signed (bool, optional) :
Whether to sign the session ID (default: value of BOKEH_SIGN_SESSIONS
envronment varariable)
extra_payload (dict, optional) :
Extra key/value pairs to include in the Bokeh session token
expiration (int, optional) :
Expiration time
Returns:
str
"""
now = calendar.timegm(dt.datetime.utcnow().utctimetuple())
payload = {"session_id": session_id, "session_expiry": now + expiration}
if extra_payload:
if "session_id" in extra_payload:
raise RuntimeError(
"extra_payload for session tokens may not contain 'session_id'"
)
payload.update(extra_payload)
token = _base64_encode(json.dumps(payload))
secret_key = _ensure_bytes(secret_key)
if not signed:
return token
return token + "." + _signature(token, secret_key)
|
def generate_jwt_token(
session_id: str,
secret_key: Optional[bytes] = settings.secret_key_bytes(),
signed: bool = settings.sign_sessions(),
extra_payload: Optional[Dict[str, Any]] = None,
expiration: int = 300,
) -> str:
"""Generates a JWT token given a session_id and additional payload.
Args:
session_id (str):
The session id to add to the token
secret_key (str, optional) :
Secret key (default: value of BOKEH_SECRET_KEY environment varariable)
signed (bool, optional) :
Whether to sign the session ID (default: value of BOKEH_SIGN_SESSIONS
envronment varariable)
extra_payload (dict, optional) :
Extra key/value pairs to include in the Bokeh session token
expiration (int, optional) :
Expiration time
Returns:
str
"""
now = calendar.timegm(dt.datetime.now().utctimetuple())
payload = {"session_id": session_id, "session_expiry": now + expiration}
if extra_payload:
if "session_id" in extra_payload:
raise RuntimeError(
"extra_payload for session tokens may not contain 'session_id'"
)
payload.update(extra_payload)
token = _base64_encode(json.dumps(payload))
secret_key = _ensure_bytes(secret_key)
if not signed:
return token
return token + "." + _signature(token, secret_key)
|
https://github.com/bokeh/bokeh/issues/9938
|
Traceback (most recent call last):
File "/Users/simon/anaconda3/lib/python3.6/site-packages/tornado/websocket.py", line 956, in _accept_connection
open_result = handler.open(*handler.open_args, **handler.open_kwargs)
File "/Users/simon/anaconda3/lib/python3.6/site-packages/bokeh/server/views/ws.py", line 135, in open
raise ProtocolError("Token is expired.")
bokeh.protocol.exceptions.ProtocolError: Token is expired
|
bokeh.protocol.exceptions.ProtocolError
|
def set_select(self, selector, updates):
"""Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like query dictionary) : you can query by type or by
name,i e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}``
updates (dict) :
Returns:
None
"""
if isclass(selector) and issubclass(selector, Model):
selector = dict(type=selector)
for obj in self.select(selector):
for key, val in updates.items():
setattr(obj, key, val)
|
def set_select(self, selector, updates):
"""Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like query dictionary) : you can query by type or by
name,i e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}``
updates (dict) :
Returns:
None
"""
for obj in self.select(selector):
for key, val in updates.items():
setattr(obj, key, val)
|
https://github.com/bokeh/bokeh/issues/9245
|
Traceback (most recent call last):
File "set_select_plot.py", line 81, in <module>
plot_width=500,
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\model.py", line 628, in set_select
for obj in self.select(selector):
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\core\query.py", line 87, in <genexpr>
return (obj for obj in objs if match(obj, selector, context))
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\core\query.py", line 159, in match
for key, val in selector.items():
AttributeError: type object 'Figure' has no attribute 'items'
|
AttributeError
|
def set_select(self, selector, updates):
"""Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None
"""
if isclass(selector) and issubclass(selector, Model):
selector = dict(type=selector)
for obj in self.select(selector):
for key, val in updates.items():
setattr(obj, key, val)
|
def set_select(self, selector, updates):
"""Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None
"""
for obj in self.select(selector):
for key, val in updates.items():
setattr(obj, key, val)
|
https://github.com/bokeh/bokeh/issues/9245
|
Traceback (most recent call last):
File "set_select_plot.py", line 81, in <module>
plot_width=500,
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\model.py", line 628, in set_select
for obj in self.select(selector):
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\core\query.py", line 87, in <genexpr>
return (obj for obj in objs if match(obj, selector, context))
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\core\query.py", line 159, in match
for key, val in selector.items():
AttributeError: type object 'Figure' has no attribute 'items'
|
AttributeError
|
def detect_phantomjs(version: str = "2.1") -> str:
"""Detect if PhantomJS is avaiable in PATH, at a minimum version.
Args:
version (str, optional) :
Required minimum version for PhantomJS (mostly for testing)
Returns:
str, path to PhantomJS
"""
if settings.phantomjs_path() is not None:
phantomjs_path = settings.phantomjs_path()
else:
phantomjs_path = shutil.which("phantomjs") or "phantomjs"
try:
proc = Popen(
[phantomjs_path, "--version"], stdout=PIPE, stderr=PIPE, stdin=PIPE
)
proc.wait()
out = proc.communicate()
if len(out[1]) > 0:
raise RuntimeError(
"Error encountered in PhantomJS detection: %r" % out[1].decode("utf8")
)
required = V(version)
installed = V(out[0].decode("utf8"))
if installed < required:
raise RuntimeError(
"PhantomJS version to old. Version>=%s required, installed: %s"
% (required, installed)
)
except OSError:
raise RuntimeError(
'PhantomJS is not present in PATH or BOKEH_PHANTOMJS_PATH. Try "conda install phantomjs" or \
"npm install -g phantomjs-prebuilt"'
)
return phantomjs_path
|
def detect_phantomjs(version: str = "2.1") -> str:
"""Detect if PhantomJS is avaiable in PATH, at a minimum version.
Args:
version (str, optional) :
Required minimum version for PhantomJS (mostly for testing)
Returns:
str, path to PhantomJS
"""
if settings.phantomjs_path() is not None:
phantomjs_path = settings.phantomjs_path()
else:
phantomjs_path = shutil.which("phantomjs") or "phantomjs"
try:
proc = Popen([phantomjs_path, "--version"], stdout=PIPE, stderr=PIPE)
proc.wait()
out = proc.communicate()
if len(out[1]) > 0:
raise RuntimeError(
"Error encountered in PhantomJS detection: %r" % out[1].decode("utf8")
)
required = V(version)
installed = V(out[0].decode("utf8"))
if installed < required:
raise RuntimeError(
"PhantomJS version to old. Version>=%s required, installed: %s"
% (required, installed)
)
except OSError:
raise RuntimeError(
'PhantomJS is not present in PATH or BOKEH_PHANTOMJS_PATH. Try "conda install phantomjs" or \
"npm install -g phantomjs-prebuilt"'
)
return phantomjs_path
|
https://github.com/bokeh/bokeh/issues/9579
|
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/savalek/.local/lib/python3.6/site-packages/bokeh/io/export.py", line 97, in export_png
image = get_screenshot_as_png(obj, height=height, width=width, driver=webdriver, timeout=timeout)
File "/home/savalek/.local/lib/python3.6/site-packages/bokeh/io/export.py", line 217, in get_screenshot_as_png
web_driver = driver if driver is not None else webdriver_control.get()
File "/home/savalek/.local/lib/python3.6/site-packages/bokeh/io/webdriver.py", line 116, in get
self.current = self.create()
File "/home/savalek/.local/lib/python3.6/site-packages/bokeh/io/webdriver.py", line 121, in create
return create_phantomjs_webdriver()
File "/home/savalek/.local/lib/python3.6/site-packages/bokeh/io/webdriver.py", line 75, in create_phantomjs_webdriver
phantomjs_path = detect_phantomjs()
File "/home/savalek/.local/lib/python3.6/site-packages/bokeh/util/dependencies.py", line 117, in detect_phantomjs
raise RuntimeError('Error encountered in PhantomJS detection: %r' % out[1].decode('utf8'))
RuntimeError: Error encountered in PhantomJS detection: "events.js:183\n throw er; // Unhandled 'error' event\n ^\n\nError: read ECONNRESET\n at _errnoException (util.js:1022:11)\n at Pipe.onread (net.js:628:25)\n"
|
RuntimeError
|
def unlisten(self):
"""Stop listening on ports. The server will no longer be usable after
calling this function.
Returns:
None
"""
yield self._http.close_all_connections()
self._http.stop()
|
def unlisten(self):
"""Stop listening on ports. The server will no longer be usable after
calling this function.
Returns:
None
"""
self._http.close_all_connections()
self._http.stop()
|
https://github.com/bokeh/bokeh/issues/8719
|
-- Docs: https://docs.pytest.org/en/latest/warnings.html
----------- generated xml file: C:\projects\bokeh\test_results.xml ------------
= 1 failed, 3444 passed, 1 skipped, 981 deselected, 78 warnings in 241.84 seconds =
Task was destroyed but it is pending!
task: <Task pending coro=<RequestHandler._execute() running at C:\Miniconda36-x64\lib\site-packages\tornado\web.py:1699> wait_for=<Future pending cb=[coroutine.<locals>.wrapper.<locals>.<lambda>() at C:\Miniconda36-x64\lib\site-packages\tornado\gen.py:226, <1 more>, <TaskWakeupMethWrapper object at 0x000000A280615888>()]> cb=[_HandlerDelegate.execute.<locals>.<lambda>() at C:\Miniconda36-x64\lib\site-packages\tornado\web.py:2329]>
Exception ignored in: <generator object send at 0x000000A28051F5C8>
Traceback (most recent call last):
File "C:\projects\bokeh\bokeh\protocol\message.py", line 281, in send
raise gen.Return(sent)
File "C:\Miniconda36-x64\lib\site-packages\tornado\locks.py", line 282, in __exit__
self._obj.release()
File "C:\Miniconda36-x64\lib\site-packages\tornado\locks.py", line 482, in release
super(BoundedSemaphore, self).release()
File "C:\Miniconda36-x64\lib\site-packages\tornado\locks.py", line 411, in release
waiter.set_result(_ReleasingContextManager(self))
File "C:\Miniconda36-x64\lib\asyncio\base_events.py", line 575, in call_soon
self._check_closed()
File "C:\Miniconda36-x64\lib\asyncio\base_events.py", line 358, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Future exception was never retrieved
future: <Future finished exception=WebSocketClosedError()>
Traceback (most recent call last):
File "C:\Miniconda36-x64\lib\site-packages\tornado\websocket.py", line 1100, in wrapper
await fut
tornado.iostream.StreamClosedError: Stream is closed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Miniconda36-x64\lib\site-packages\tornado\gen.py", line 736, in run
yielded = self.gen.throw(*exc_info) # type: ignore
File "C:\projects\bokeh\bokeh\server\views\ws.py", line 269, in write_message
yield super(WSHandler, self).write_message(message, binary)
File "C:\Miniconda36-x64\lib\site-packages\tornado\gen.py", line 729, in run
value = future.result()
File "C:\Miniconda36-x64\lib\site-packages\tornado\websocket.py", line 1102, in wrapper
raise WebSocketClosedError()
tornado.websocket.WebSocketClosedError
Exception ignored in: <generator object _needs_document_lock_wrapper at 0x000000A280606B48>
Traceback (most recent call last):
File "C:\projects\bokeh\bokeh\server\session.py", line 78, in _needs_document_lock_wrapper
yield p
File "C:\Miniconda36-x64\lib\site-packages\tornado\locks.py", line 282, in __exit__
self._obj.release()
File "C:\Miniconda36-x64\lib\site-packages\tornado\locks.py", line 482, in release
super(BoundedSemaphore, self).release()
File "C:\Miniconda36-x64\lib\site-packages\tornado\locks.py", line 411, in release
waiter.set_result(_ReleasingContextManager(self))
File "C:\Miniconda36-x64\lib\asyncio\base_events.py", line 575, in call_soon
self._check_closed()
File "C:\Miniconda36-x64\lib\asyncio\base_events.py", line 358, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Command exited with code 1
$wc = New-Object 'System.Net.WebClient'
|
RuntimeError
|
def decode_base64_dict(data):
"""Decode a base64 encoded array into a NumPy array.
Args:
data (dict) : encoded array data to decode
Data should have the format encoded by :func:`encode_base64_dict`.
Returns:
np.ndarray
"""
b64 = base64.b64decode(data["__ndarray__"])
array = np.copy(np.frombuffer(b64, dtype=data["dtype"]))
if len(data["shape"]) > 1:
array = array.reshape(data["shape"])
return array
|
def decode_base64_dict(data):
"""Decode a base64 encoded array into a NumPy array.
Args:
data (dict) : encoded array data to decode
Data should have the format encoded by :func:`encode_base64_dict`.
Returns:
np.ndarray
"""
b64 = base64.b64decode(data["__ndarray__"])
array = np.frombuffer(b64, dtype=data["dtype"])
if len(data["shape"]) > 1:
array = array.reshape(data["shape"])
return array
|
https://github.com/bokeh/bokeh/issues/8232
|
2018-09-10 19:07:29,992 Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x1202aa6a8>, <Future finished exception=ValueError('assignment destination is read-only',)>)
Traceback (most recent call last):
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 759, in _run_callback
ret = callback()
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "/Users/bryanv/work/bokeh/bokeh/util/tornado.py", line 95, in on_done
log.error("".join(format_exception(*future.exc_info())))
AttributeError: '_asyncio.Future' object has no attribute 'exc_info'
|
AttributeError
|
def start(self):
if self._started:
raise RuntimeError("called start() twice on _AsyncPeriodic")
self._started = True
def invoke():
# important to start the sleep before starting callback
# so any initial time spent in callback "counts against"
# the period.
sleep_future = self.sleep()
result = self._func()
# This is needed for Tornado >= 4.5 where convert_yielded will no
# longer raise BadYieldError on None
if result is None:
return sleep_future
try:
callback_future = gen.convert_yielded(result)
except gen.BadYieldError:
# result is not a yieldable thing
return sleep_future
else:
return gen.multi([sleep_future, callback_future])
def on_done(future):
if not self._stopped:
self._loop.add_future(invoke(), on_done)
ex = future.exception()
if ex is not None:
log.error("Error thrown from periodic callback:")
if six.PY2:
lines = format_exception(*future.exc_info())
else:
lines = format_exception(ex.__class__, ex, ex.__traceback__)
log.error("".join(lines))
self._loop.add_future(self.sleep(), on_done)
|
def start(self):
if self._started:
raise RuntimeError("called start() twice on _AsyncPeriodic")
self._started = True
def invoke():
# important to start the sleep before starting callback
# so any initial time spent in callback "counts against"
# the period.
sleep_future = self.sleep()
result = self._func()
# This is needed for Tornado >= 4.5 where convert_yielded will no
# longer raise BadYieldError on None
if result is None:
return sleep_future
try:
callback_future = gen.convert_yielded(result)
except gen.BadYieldError:
# result is not a yieldable thing
return sleep_future
else:
return gen.multi([sleep_future, callback_future])
def on_done(future):
if not self._stopped:
self._loop.add_future(invoke(), on_done)
if future.exception() is not None:
log.error("Error thrown from periodic callback:")
log.error("".join(format_exception(*future.exc_info())))
self._loop.add_future(self.sleep(), on_done)
|
https://github.com/bokeh/bokeh/issues/8232
|
2018-09-10 19:07:29,992 Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x1202aa6a8>, <Future finished exception=ValueError('assignment destination is read-only',)>)
Traceback (most recent call last):
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 759, in _run_callback
ret = callback()
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "/Users/bryanv/work/bokeh/bokeh/util/tornado.py", line 95, in on_done
log.error("".join(format_exception(*future.exc_info())))
AttributeError: '_asyncio.Future' object has no attribute 'exc_info'
|
AttributeError
|
def on_done(future):
if not self._stopped:
self._loop.add_future(invoke(), on_done)
ex = future.exception()
if ex is not None:
log.error("Error thrown from periodic callback:")
if six.PY2:
lines = format_exception(*future.exc_info())
else:
lines = format_exception(ex.__class__, ex, ex.__traceback__)
log.error("".join(lines))
|
def on_done(future):
if not self._stopped:
self._loop.add_future(invoke(), on_done)
if future.exception() is not None:
log.error("Error thrown from periodic callback:")
log.error("".join(format_exception(*future.exc_info())))
|
https://github.com/bokeh/bokeh/issues/8232
|
2018-09-10 19:07:29,992 Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x1202aa6a8>, <Future finished exception=ValueError('assignment destination is read-only',)>)
Traceback (most recent call last):
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 759, in _run_callback
ret = callback()
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "/Users/bryanv/work/bokeh/bokeh/util/tornado.py", line 95, in on_done
log.error("".join(format_exception(*future.exc_info())))
AttributeError: '_asyncio.Future' object has no attribute 'exc_info'
|
AttributeError
|
def modify_document(self, doc):
""" """
module = self._runner.new_module()
# If no module was returned it means the code runner has some permanent
# unfixable problem, e.g. the configured source code has a syntax error
if module is None:
return
# One reason modules are stored is to prevent the module
# from being gc'd before the document is. A symptom of a
# gc'd module is that its globals become None. Additionally
# stored modules are used to provide correct paths to
# custom models resolver.
sys.modules[module.__name__] = module
doc._modules.append(module)
old_doc = curdoc()
set_curdoc(doc)
old_io = self._monkeypatch_io()
try:
def post_check():
newdoc = curdoc()
# script is supposed to edit the doc not replace it
if newdoc is not doc:
raise RuntimeError(
"%s at '%s' replaced the output document"
% (self._origin, self._runner.path)
)
self._runner.run(module, post_check)
finally:
self._unmonkeypatch_io(old_io)
set_curdoc(old_doc)
|
def modify_document(self, doc):
""" """
if self.failed:
return
module = self._runner.new_module()
# One reason modules are stored is to prevent the module
# from being gc'd before the document is. A symptom of a
# gc'd module is that its globals become None. Additionally
# stored modules are used to provide correct paths to
# custom models resolver.
sys.modules[module.__name__] = module
doc._modules.append(module)
old_doc = curdoc()
set_curdoc(doc)
old_io = self._monkeypatch_io()
try:
def post_check():
newdoc = curdoc()
# script is supposed to edit the doc not replace it
if newdoc is not doc:
raise RuntimeError(
"%s at '%s' replaced the output document"
% (self._origin, self._runner.path)
)
self._runner.run(module, post_check)
finally:
self._unmonkeypatch_io(old_io)
set_curdoc(old_doc)
|
https://github.com/bokeh/bokeh/issues/8034
|
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!
2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created
|
Exception
|
def __init__(self, source, path, argv):
"""
Args:
source (str) : python source code
path (str) : a filename to use in any debugging or error output
argv (list[str]) : a list of string arguments to make available
as ``sys.argv`` when the code executes
"""
self._permanent_error = None
self._permanent_error_detail = None
self.reset_run_errors()
import ast
self._code = None
try:
nodes = ast.parse(source, path)
self._code = compile(nodes, filename=path, mode="exec", dont_inherit=True)
except SyntaxError as e:
import traceback
self._code = None
self._permanent_error = 'Invalid syntax in "%s" on line %d:\n%s' % (
os.path.basename(e.filename),
e.lineno,
e.text,
)
self._permanent_error_detail = traceback.format_exc()
self._path = path
self._source = source
self._argv = argv
self.ran = False
|
def __init__(self, source, path, argv):
"""
Args:
source (str) : python source code
path (str) : a filename to use in any debugging or error output
argv (list[str]) : a list of string arguments to make available
as ``sys.argv`` when the code executes
"""
self._failed = False
self._error = None
self._error_detail = None
import ast
self._code = None
try:
nodes = ast.parse(source, path)
self._code = compile(nodes, filename=path, mode="exec", dont_inherit=True)
except SyntaxError as e:
self._failed = True
self._error = 'Invalid syntax in "%s" on line %d:\n%s' % (
os.path.basename(e.filename),
e.lineno,
e.text,
)
import traceback
self._error_detail = traceback.format_exc()
self._path = path
self._source = source
self._argv = argv
self.ran = False
|
https://github.com/bokeh/bokeh/issues/8034
|
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!
2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created
|
Exception
|
def error(self):
"""If code execution fails, may contain a related error message."""
return self._error if self._permanent_error is None else self._permanent_error
|
def error(self):
"""If code execution fails, may contain a related error message."""
return self._error
|
https://github.com/bokeh/bokeh/issues/8034
|
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!
2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created
|
Exception
|
def error_detail(self):
"""If code execution fails, may contain a traceback or other details."""
return (
self._error_detail
if self._permanent_error_detail is None
else self._permanent_error_detail
)
|
def error_detail(self):
"""If code execution fails, may contain a traceback or other details."""
return self._error_detail
|
https://github.com/bokeh/bokeh/issues/8034
|
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!
2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created
|
Exception
|
def failed(self):
"""``True`` if code execution failed"""
return self._failed or self._code is None
|
def failed(self):
"""``True`` if code execution failed"""
return self._failed
|
https://github.com/bokeh/bokeh/issues/8034
|
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!
2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created
|
Exception
|
def new_module(self):
"""Make a fresh module to run in.
Returns:
Module
"""
self.reset_run_errors()
if self._code is None:
return None
module_name = "bk_script_" + make_id().replace("-", "")
module = ModuleType(str(module_name)) # str needed for py2.7
module.__dict__["__file__"] = os.path.abspath(self._path)
return module
|
def new_module(self):
"""Make a fresh module to run in.
Returns:
Module
"""
if self.failed:
return None
module_name = "bk_script_" + make_id().replace("-", "")
module = ModuleType(str(module_name)) # str needed for py2.7
module.__dict__["__file__"] = os.path.abspath(self._path)
return module
|
https://github.com/bokeh/bokeh/issues/8034
|
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!
2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created
|
Exception
|
def run(self, module, post_check):
"""Execute the configured source code in a module and run any post
checks.
Args:
module (Module) : a module to execute the configured code in.
post_check(callable) : a function that can raise an exception
if expected post-conditions are not met after code execution.
"""
try:
# Simulate the sys.path behaviour decribed here:
#
# https://docs.python.org/2/library/sys.html#sys.path
_cwd = os.getcwd()
_sys_path = list(sys.path)
_sys_argv = list(sys.argv)
sys.path.insert(0, os.path.dirname(self._path))
sys.argv = [os.path.basename(self._path)] + self._argv
exec(self._code, module.__dict__)
post_check()
except Exception as e:
self._failed = True
self._error_detail = traceback.format_exc()
_exc_type, _exc_value, exc_traceback = sys.exc_info()
filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]
self._error = '%s\nFile "%s", line %d, in %s:\n%s' % (
str(e),
os.path.basename(filename),
line_number,
func,
txt,
)
finally:
# undo sys.path, CWD fixups
os.chdir(_cwd)
sys.path = _sys_path
sys.argv = _sys_argv
self.ran = True
|
def run(self, module, post_check):
"""Execute the configured source code in a module and run any post
checks.
Args:
module (Module) : a module to execute the configured code in.
post_check(callable) : a function that can raise an exception
if expected post-conditions are not met after code execution.
"""
try:
# Simulate the sys.path behaviour decribed here:
#
# https://docs.python.org/2/library/sys.html#sys.path
_cwd = os.getcwd()
_sys_path = list(sys.path)
_sys_argv = list(sys.argv)
sys.path.insert(0, os.path.dirname(self._path))
sys.argv = [os.path.basename(self._path)] + self._argv
exec(self._code, module.__dict__)
post_check()
except Exception as e:
self._failed = True
self._error_detail = traceback.format_exc()
exc_type, exc_value, exc_traceback = sys.exc_info()
filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]
self._error = '%s\nFile "%s", line %d, in %s:\n%s' % (
str(e),
os.path.basename(filename),
line_number,
func,
txt,
)
finally:
# undo sys.path, CWD fixups
os.chdir(_cwd)
sys.path = _sys_path
sys.argv = _sys_argv
self.ran = True
|
https://github.com/bokeh/bokeh/issues/8034
|
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!
2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created
|
Exception
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.