max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
tests/test_rand.py
yl3dy/pylibressl
2
6624251
<reponame>yl3dy/pylibressl import pytest from pylibressl.rand import get_random_bytes, libressl_get_random_bytes from pylibressl.rand import getrandbits class GenericRandTest: _randfunc = (None,) # ugly hack to prevent making _randfunc a method def test_too_short_length(self): _randfunc = self._randfunc[0] with pytest.raises(ValueError): random = _randfunc(0) def test_too_short_length(self): _randfunc = self._randfunc[0] with pytest.raises(ValueError): random = _randfunc(-10) def test_non_int_length(self): _randfunc = self._randfunc[0] with pytest.raises(TypeError): random = _randfunc('asdfasdf') def test_output_length(self): _randfunc = self._randfunc[0] length = 64 assert len(_randfunc(length)) == length def test_repeated_invocation(self): _randfunc = self._randfunc[0] randstr1 = _randfunc(64) randstr2 = _randfunc(64) assert randstr1 != randstr2 class TestSystemRand(GenericRandTest): _randfunc = (get_random_bytes,) class TestLibreSSLRand(GenericRandTest): _randfunc = (libressl_get_random_bytes,) class TestGetrandbits: def test_non_int_length(self): with pytest.raises(TypeError): getrandbits('asdfasdf') def test_too_short_length(self): with pytest.raises(ValueError): getrandbits(-10) def test_output_length(self): length = 13 rv = getrandbits(length) assert rv <= ((1 << length) - 1)
import pytest from pylibressl.rand import get_random_bytes, libressl_get_random_bytes from pylibressl.rand import getrandbits class GenericRandTest: _randfunc = (None,) # ugly hack to prevent making _randfunc a method def test_too_short_length(self): _randfunc = self._randfunc[0] with pytest.raises(ValueError): random = _randfunc(0) def test_too_short_length(self): _randfunc = self._randfunc[0] with pytest.raises(ValueError): random = _randfunc(-10) def test_non_int_length(self): _randfunc = self._randfunc[0] with pytest.raises(TypeError): random = _randfunc('asdfasdf') def test_output_length(self): _randfunc = self._randfunc[0] length = 64 assert len(_randfunc(length)) == length def test_repeated_invocation(self): _randfunc = self._randfunc[0] randstr1 = _randfunc(64) randstr2 = _randfunc(64) assert randstr1 != randstr2 class TestSystemRand(GenericRandTest): _randfunc = (get_random_bytes,) class TestLibreSSLRand(GenericRandTest): _randfunc = (libressl_get_random_bytes,) class TestGetrandbits: def test_non_int_length(self): with pytest.raises(TypeError): getrandbits('asdfasdf') def test_too_short_length(self): with pytest.raises(ValueError): getrandbits(-10) def test_output_length(self): length = 13 rv = getrandbits(length) assert rv <= ((1 << length) - 1)
en
0.623094
# ugly hack to prevent making _randfunc a method
2.336395
2
lilypadz/__init__.py
Weiqi97/LilyPadz
2
6624252
"""Project structure."""
"""Project structure."""
en
0.659098
Project structure.
1.021487
1
hic/diffusionTesting.py
zelhar/mg21
0
6624253
if __name__ == '__main__': from mymodule import * else: from .mymodule import * A = np.random.rand(10,8) * 1e-5 plt.matshow(A) filepath1 = "./hicdata/191-98_hg19_no_hap_EBV_MAPQ30_merged.mcool" bedpath = "./hicdata/191-98_reconstruction.bed" filepath2 = "./hicdata/CL17-08_hg19_no_hap_EBV_MAPQ30_merged.mcool" bedpath = "./hicdata/CL17-08_reconstruction.bed" reffilepath = "./hicdata/CL18-38_hg19_no_hap_EBV_MAPQ30_merged.mcool" # no bed it's the reference matrix bedDF = pd.read_csv( bedpath, names=[ "chr", "start", "end", "foo", "bar", "orientation", "derivative_chr", "scaffold", ], sep="\t", ) bedDF # loading cooler matrix with cooler's API c = cooler.Cooler(filepath2 + "::resolutions/250000") arr = c.matrix(balance='KR', sparse=False)[:,:] arr = np.nan_to_num(arr) c2 = cooler.Cooler(reffilepath+"::resolutions/500000") refarr = c2.matrix(balance='KR', sparse=False)[:,:] refarr = np.nan_to_num(refarr) plotHicMat(arr+1) plotHicMat(refarr+1) # slicing by chromosomes a2b5 = c.matrix(balance='KR').fetch('2', '5') a2b5 = np.nan_to_num(a2b5) plotHicMat(a2b5 + 1) A = np.random.random((4,5)) A @ A.T A = a2b5 @ a2b5.T A = A + np.identity(len(A)) A # column normalize: A = A / A.sum(axis = 0) x = np.ones((2,3)) x[0,1] = 3 x y = x.T @ x y y y.sum(axis=0) y.sum(axis=1) z = diffusionMatrix(y) z.sum(axis=0) z.sum(axis=1) A.sum(axis=0) K = diffusionMatrix(A) K.sum(axis=0) p = K @ np.ones(len(K)) plt.bar(range(len(K)), p) mymax = np.argmax(p) mymax plotHicMat(a2b5) plt.hlines(mymax, 0, 100, color='blue') mymaxes = np.argsort(p)[-1:-10:-1] plt.hlines(mymaxes, 0, 250, color='purple') morelocations = np.argsort(p)[-1:-150:-1] plt.hlines(morelocations, 0, 70, color='green') plt.close() plt.cla() # loading cooler matrix with cooler's API c = cooler.Cooler(filepath1 + "::resolutions/250000") c2 = cooler.Cooler(filepath2 + "::resolutions/250000") # slicing by chromosomes a16b11 = c2.matrix(balance='KR').fetch('16', '11') a16b11 = np.nan_to_num(a16b11) plotHicMat(a16b11 + 1) arr = c.matrix(balance='KR', sparse=False)[:,:] arr = np.nan_to_num(arr) arr2 = c2.matrix(balance='KR', sparse=False)[:,:] arr2 = np.nan_to_num(arr2) plotHicMat(arr +1) plotHicMat(arr2 +1) x = c2.matrix(balance='KR').fetch('2', '11') x = np.nan_to_num(x) plotHicMat(x + 1)
if __name__ == '__main__': from mymodule import * else: from .mymodule import * A = np.random.rand(10,8) * 1e-5 plt.matshow(A) filepath1 = "./hicdata/191-98_hg19_no_hap_EBV_MAPQ30_merged.mcool" bedpath = "./hicdata/191-98_reconstruction.bed" filepath2 = "./hicdata/CL17-08_hg19_no_hap_EBV_MAPQ30_merged.mcool" bedpath = "./hicdata/CL17-08_reconstruction.bed" reffilepath = "./hicdata/CL18-38_hg19_no_hap_EBV_MAPQ30_merged.mcool" # no bed it's the reference matrix bedDF = pd.read_csv( bedpath, names=[ "chr", "start", "end", "foo", "bar", "orientation", "derivative_chr", "scaffold", ], sep="\t", ) bedDF # loading cooler matrix with cooler's API c = cooler.Cooler(filepath2 + "::resolutions/250000") arr = c.matrix(balance='KR', sparse=False)[:,:] arr = np.nan_to_num(arr) c2 = cooler.Cooler(reffilepath+"::resolutions/500000") refarr = c2.matrix(balance='KR', sparse=False)[:,:] refarr = np.nan_to_num(refarr) plotHicMat(arr+1) plotHicMat(refarr+1) # slicing by chromosomes a2b5 = c.matrix(balance='KR').fetch('2', '5') a2b5 = np.nan_to_num(a2b5) plotHicMat(a2b5 + 1) A = np.random.random((4,5)) A @ A.T A = a2b5 @ a2b5.T A = A + np.identity(len(A)) A # column normalize: A = A / A.sum(axis = 0) x = np.ones((2,3)) x[0,1] = 3 x y = x.T @ x y y y.sum(axis=0) y.sum(axis=1) z = diffusionMatrix(y) z.sum(axis=0) z.sum(axis=1) A.sum(axis=0) K = diffusionMatrix(A) K.sum(axis=0) p = K @ np.ones(len(K)) plt.bar(range(len(K)), p) mymax = np.argmax(p) mymax plotHicMat(a2b5) plt.hlines(mymax, 0, 100, color='blue') mymaxes = np.argsort(p)[-1:-10:-1] plt.hlines(mymaxes, 0, 250, color='purple') morelocations = np.argsort(p)[-1:-150:-1] plt.hlines(morelocations, 0, 70, color='green') plt.close() plt.cla() # loading cooler matrix with cooler's API c = cooler.Cooler(filepath1 + "::resolutions/250000") c2 = cooler.Cooler(filepath2 + "::resolutions/250000") # slicing by chromosomes a16b11 = c2.matrix(balance='KR').fetch('16', '11') a16b11 = np.nan_to_num(a16b11) plotHicMat(a16b11 + 1) arr = c.matrix(balance='KR', sparse=False)[:,:] arr = np.nan_to_num(arr) arr2 = c2.matrix(balance='KR', sparse=False)[:,:] arr2 = np.nan_to_num(arr2) plotHicMat(arr +1) plotHicMat(arr2 +1) x = c2.matrix(balance='KR').fetch('2', '11') x = np.nan_to_num(x) plotHicMat(x + 1)
en
0.894507
# no bed it's the reference matrix # loading cooler matrix with cooler's API # slicing by chromosomes # column normalize: # loading cooler matrix with cooler's API # slicing by chromosomes
2.163982
2
feets/tests/test_original_FATS_test_library.py
ryanjmccall/feets
0
6624254
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2015, 2016, 2017, 2018 # <NAME>, <NAME>, <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """Original tests of FATS: Removed: - Commented ones - The Stetson test because don't work anyway (the original test not provides all the data required for the Stetson indexes. Orignal Version: https://github.com/isadoranun/FATS/blob/b45b5c1/FATS/test_library.py """ # ============================================================================= # IMPORTS # ============================================================================= import numpy as np import pytest from six.moves import range from ..core import FeatureSpace # ============================================================================= # FIXTURES # ============================================================================= # FIX the random state random = np.random.RandomState(42) @pytest.fixture def white_noise(): data = random.normal(size=10000) mjd = np.arange(10000) error = random.normal(loc=0.01, scale=0.8, size=10000) second_data = random.normal(size=10000) aligned_data = data aligned_second_data = second_data aligned_mjd = mjd lc = { "magnitude": data, "time": mjd, "error": error, "magnitude2": second_data, "aligned_magnitude": aligned_data, "aligned_magnitude2": aligned_second_data, "aligned_time": aligned_mjd} return lc @pytest.fixture def periodic_lc(): N = 100 mjd_periodic = np.arange(N) Period = 20 cov = np.zeros([N, N]) mean = np.zeros(N) for i in np.arange(N): for j in np.arange(N): cov[i, j] = np.exp(-(np.sin((np.pi/Period) * (i-j)) ** 2)) data_periodic = random.multivariate_normal(mean, cov) lc = { "magnitude": data_periodic, "time": mjd_periodic} return lc @pytest.fixture def uniform_lc(): mjd_uniform = np.arange(1000000) data_uniform = random.uniform(size=1000000) lc = { "magnitude": data_uniform, "time": mjd_uniform} return lc @pytest.fixture def random_walk(): N = 10000 alpha = 1. sigma = 0.5 data_rw = np.zeros([N, 1]) data_rw[0] = 1 time_rw = range(1, N) for t in time_rw: data_rw[t] = alpha * data_rw[t-1] + random.normal(loc=0.0, scale=sigma) time_rw = np.array(range(0, N)) + 1 * random.uniform(size=N) data_rw = data_rw.squeeze() lc = { "magnitude": data_rw, "time": time_rw} return lc # ============================================================================= # TESTS # ============================================================================= def test_Beyond1Std(white_noise): fs = FeatureSpace(only=['Beyond1Std']) result = fs.extract(**white_noise)[1][0] assert result >= 0.30 and result <= 0.40 def test_Mean(white_noise): fs = FeatureSpace(only=['Mean']) result = fs.extract(**white_noise)[1][0] assert result >= -0.1 and result <= 0.1 def test_Con(white_noise): fs = FeatureSpace(only=['Con'], Con={"consecutiveStar": 1}) result = fs.extract(**white_noise)[1][0] assert result >= 0.04 and result <= 0.05 def test_Eta_color(white_noise): fs = FeatureSpace(only=['Eta_color']) result = fs.extract(**white_noise)[1][0] assert result >= 1.9 and result <= 2.1 def test_Eta_e(white_noise): fs = FeatureSpace(only=['Eta_e']) result = fs.extract(**white_noise)[1][0] assert result >= 1.9 and result <= 2.1 def test_FluxPercentile(white_noise): fs = FeatureSpace(only=[ 'FluxPercentileRatioMid20', 'FluxPercentileRatioMid35', 'FluxPercentileRatioMid50', 'FluxPercentileRatioMid65', 'FluxPercentileRatioMid80']) result = fs.extract(**white_noise)[1] assert result[0] >= 0.145 and result[0] <= 0.160 assert result[1] >= 0.260 and result[1] <= 0.290 assert result[2] >= 0.350 and result[2] <= 0.450 assert result[3] >= 0.540 and result[3] <= 0.580 assert result[4] >= 0.760 and result[4] <= 0.800 def test_LinearTrend(white_noise): fs = FeatureSpace(only=['LinearTrend']) result = fs.extract(**white_noise)[1][0] assert result >= -0.1 and result <= 0.1 def test_Meanvariance(uniform_lc): fs = FeatureSpace(only=['Meanvariance']) result = fs.extract(**uniform_lc)[1][0] assert result >= 0.575 and result <= 0.580 def test_MedianAbsDev(white_noise): fs = FeatureSpace(only=['MedianAbsDev']) result = fs.extract(**white_noise)[1][0] assert result >= 0.630 and result <= 0.700 def test_PairSlopeTrend(white_noise): fs = FeatureSpace(only=['PairSlopeTrend']) result = fs.extract(**white_noise)[1][0] assert result >= -0.25 and result <= 0.25 def test_Period_Psi(periodic_lc): params = { "lscargle_kwds": { "autopower_kwds": { "normalization": "standard", "nyquist_factor": 1, } } } fs = FeatureSpace(only=['PeriodLS'], LombScargle=params) result = fs.extract(**periodic_lc)[1][0] assert result >= 19 and result <= 21 def test_Q31(white_noise): fs = FeatureSpace(only=['Q31']) result = fs.extract(**white_noise)[1][0] assert result >= 1.30 and result <= 1.38 def test_Rcs(white_noise): fs = FeatureSpace(only=['Rcs']) result = fs.extract(**white_noise)[1][0] assert result >= 0 and result <= 0.1 def test_Skew(white_noise): fs = FeatureSpace(only=['Skew']) result = fs.extract(**white_noise)[1][0] assert result >= -0.1 and result <= 0.1 def test_SmallKurtosis(white_noise): fs = FeatureSpace(only=['SmallKurtosis']) result = fs.extract(**white_noise)[1][0] assert result >= -0.2 and result <= 0.2 def test_Std(white_noise): fs = FeatureSpace(only=['Std']) result = fs.extract(**white_noise)[1][0] assert result >= 0.9 and result <= 1.1 def test_Gskew(white_noise): fs = FeatureSpace(only=['Gskew']) result = fs.extract(**white_noise)[1][0] assert result >= -0.2 and result <= 0.2 def test_StructureFunction(random_walk): fs = FeatureSpace(only=[ 'StructureFunction_index_21', 'StructureFunction_index_31', 'StructureFunction_index_32']) result = fs.extract(**random_walk)[1] assert(result[0] >= 1.520 and result[0] <= 2.067) assert(result[1] >= 1.821 and result[1] <= 3.162) assert(result[2] >= 1.243 and result[2] <= 1.562)
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2015, 2016, 2017, 2018 # <NAME>, <NAME>, <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """Original tests of FATS: Removed: - Commented ones - The Stetson test because don't work anyway (the original test not provides all the data required for the Stetson indexes. Orignal Version: https://github.com/isadoranun/FATS/blob/b45b5c1/FATS/test_library.py """ # ============================================================================= # IMPORTS # ============================================================================= import numpy as np import pytest from six.moves import range from ..core import FeatureSpace # ============================================================================= # FIXTURES # ============================================================================= # FIX the random state random = np.random.RandomState(42) @pytest.fixture def white_noise(): data = random.normal(size=10000) mjd = np.arange(10000) error = random.normal(loc=0.01, scale=0.8, size=10000) second_data = random.normal(size=10000) aligned_data = data aligned_second_data = second_data aligned_mjd = mjd lc = { "magnitude": data, "time": mjd, "error": error, "magnitude2": second_data, "aligned_magnitude": aligned_data, "aligned_magnitude2": aligned_second_data, "aligned_time": aligned_mjd} return lc @pytest.fixture def periodic_lc(): N = 100 mjd_periodic = np.arange(N) Period = 20 cov = np.zeros([N, N]) mean = np.zeros(N) for i in np.arange(N): for j in np.arange(N): cov[i, j] = np.exp(-(np.sin((np.pi/Period) * (i-j)) ** 2)) data_periodic = random.multivariate_normal(mean, cov) lc = { "magnitude": data_periodic, "time": mjd_periodic} return lc @pytest.fixture def uniform_lc(): mjd_uniform = np.arange(1000000) data_uniform = random.uniform(size=1000000) lc = { "magnitude": data_uniform, "time": mjd_uniform} return lc @pytest.fixture def random_walk(): N = 10000 alpha = 1. sigma = 0.5 data_rw = np.zeros([N, 1]) data_rw[0] = 1 time_rw = range(1, N) for t in time_rw: data_rw[t] = alpha * data_rw[t-1] + random.normal(loc=0.0, scale=sigma) time_rw = np.array(range(0, N)) + 1 * random.uniform(size=N) data_rw = data_rw.squeeze() lc = { "magnitude": data_rw, "time": time_rw} return lc # ============================================================================= # TESTS # ============================================================================= def test_Beyond1Std(white_noise): fs = FeatureSpace(only=['Beyond1Std']) result = fs.extract(**white_noise)[1][0] assert result >= 0.30 and result <= 0.40 def test_Mean(white_noise): fs = FeatureSpace(only=['Mean']) result = fs.extract(**white_noise)[1][0] assert result >= -0.1 and result <= 0.1 def test_Con(white_noise): fs = FeatureSpace(only=['Con'], Con={"consecutiveStar": 1}) result = fs.extract(**white_noise)[1][0] assert result >= 0.04 and result <= 0.05 def test_Eta_color(white_noise): fs = FeatureSpace(only=['Eta_color']) result = fs.extract(**white_noise)[1][0] assert result >= 1.9 and result <= 2.1 def test_Eta_e(white_noise): fs = FeatureSpace(only=['Eta_e']) result = fs.extract(**white_noise)[1][0] assert result >= 1.9 and result <= 2.1 def test_FluxPercentile(white_noise): fs = FeatureSpace(only=[ 'FluxPercentileRatioMid20', 'FluxPercentileRatioMid35', 'FluxPercentileRatioMid50', 'FluxPercentileRatioMid65', 'FluxPercentileRatioMid80']) result = fs.extract(**white_noise)[1] assert result[0] >= 0.145 and result[0] <= 0.160 assert result[1] >= 0.260 and result[1] <= 0.290 assert result[2] >= 0.350 and result[2] <= 0.450 assert result[3] >= 0.540 and result[3] <= 0.580 assert result[4] >= 0.760 and result[4] <= 0.800 def test_LinearTrend(white_noise): fs = FeatureSpace(only=['LinearTrend']) result = fs.extract(**white_noise)[1][0] assert result >= -0.1 and result <= 0.1 def test_Meanvariance(uniform_lc): fs = FeatureSpace(only=['Meanvariance']) result = fs.extract(**uniform_lc)[1][0] assert result >= 0.575 and result <= 0.580 def test_MedianAbsDev(white_noise): fs = FeatureSpace(only=['MedianAbsDev']) result = fs.extract(**white_noise)[1][0] assert result >= 0.630 and result <= 0.700 def test_PairSlopeTrend(white_noise): fs = FeatureSpace(only=['PairSlopeTrend']) result = fs.extract(**white_noise)[1][0] assert result >= -0.25 and result <= 0.25 def test_Period_Psi(periodic_lc): params = { "lscargle_kwds": { "autopower_kwds": { "normalization": "standard", "nyquist_factor": 1, } } } fs = FeatureSpace(only=['PeriodLS'], LombScargle=params) result = fs.extract(**periodic_lc)[1][0] assert result >= 19 and result <= 21 def test_Q31(white_noise): fs = FeatureSpace(only=['Q31']) result = fs.extract(**white_noise)[1][0] assert result >= 1.30 and result <= 1.38 def test_Rcs(white_noise): fs = FeatureSpace(only=['Rcs']) result = fs.extract(**white_noise)[1][0] assert result >= 0 and result <= 0.1 def test_Skew(white_noise): fs = FeatureSpace(only=['Skew']) result = fs.extract(**white_noise)[1][0] assert result >= -0.1 and result <= 0.1 def test_SmallKurtosis(white_noise): fs = FeatureSpace(only=['SmallKurtosis']) result = fs.extract(**white_noise)[1][0] assert result >= -0.2 and result <= 0.2 def test_Std(white_noise): fs = FeatureSpace(only=['Std']) result = fs.extract(**white_noise)[1][0] assert result >= 0.9 and result <= 1.1 def test_Gskew(white_noise): fs = FeatureSpace(only=['Gskew']) result = fs.extract(**white_noise)[1][0] assert result >= -0.2 and result <= 0.2 def test_StructureFunction(random_walk): fs = FeatureSpace(only=[ 'StructureFunction_index_21', 'StructureFunction_index_31', 'StructureFunction_index_32']) result = fs.extract(**random_walk)[1] assert(result[0] >= 1.520 and result[0] <= 2.067) assert(result[1] >= 1.821 and result[1] <= 3.162) assert(result[2] >= 1.243 and result[2] <= 1.562)
en
0.672153
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2015, 2016, 2017, 2018 # <NAME>, <NAME>, <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. Original tests of FATS: Removed: - Commented ones - The Stetson test because don't work anyway (the original test not provides all the data required for the Stetson indexes. Orignal Version: https://github.com/isadoranun/FATS/blob/b45b5c1/FATS/test_library.py # ============================================================================= # IMPORTS # ============================================================================= # ============================================================================= # FIXTURES # ============================================================================= # FIX the random state # ============================================================================= # TESTS # =============================================================================
1.387776
1
sikfa.py
SHI3DO/sikfa
1
6624255
import torch dtype = torch.float device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') global loss def find(x: list, y: list, weightsnum: int, trainnum: int, learning_rate: float): global loss x2 = torch.FloatTensor(x) y2 = torch.FloatTensor(y) coefficient_list = [] for i in range(0, weightsnum): coefficient_list.append(torch.randn((), device=device, dtype=dtype, requires_grad=True)) for k in range(trainnum): y_pred = 0 for h in range(0, len(coefficient_list)): y_pred += coefficient_list[h] * x2 ** h loss = (y_pred - y2).pow(2).sum() if k % 10000 == 9999: print(k, loss.item()) if not torch.isfinite(loss): print('non-finite loss, ending training') learning_rate = learning_rate / 10 trainnum = trainnum * 2 print(f'using {device}') print(f'next learning_rate = {learning_rate}') print(f'next trainnum = {trainnum}') print('restarting...') find(x, y, weightsnum, trainnum, learning_rate) exit(1) loss.backward() with torch.no_grad(): for h in range(0, len(coefficient_list)): coefficient_list[h] -= learning_rate * coefficient_list[h].grad coefficient_list[h].grad = None if loss > 100: print('too-big loss, ending training') learning_rate = learning_rate / 10 trainnum = trainnum * 2 print(f'using {device}') print(f'next learning_rate = {learning_rate}') print(f'next trainnum = {trainnum}') print('restarting...') find(x, y, weightsnum, trainnum, learning_rate) exit(1) print(f'loss = {loss.item()}') return coefficient_list
import torch dtype = torch.float device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') global loss def find(x: list, y: list, weightsnum: int, trainnum: int, learning_rate: float): global loss x2 = torch.FloatTensor(x) y2 = torch.FloatTensor(y) coefficient_list = [] for i in range(0, weightsnum): coefficient_list.append(torch.randn((), device=device, dtype=dtype, requires_grad=True)) for k in range(trainnum): y_pred = 0 for h in range(0, len(coefficient_list)): y_pred += coefficient_list[h] * x2 ** h loss = (y_pred - y2).pow(2).sum() if k % 10000 == 9999: print(k, loss.item()) if not torch.isfinite(loss): print('non-finite loss, ending training') learning_rate = learning_rate / 10 trainnum = trainnum * 2 print(f'using {device}') print(f'next learning_rate = {learning_rate}') print(f'next trainnum = {trainnum}') print('restarting...') find(x, y, weightsnum, trainnum, learning_rate) exit(1) loss.backward() with torch.no_grad(): for h in range(0, len(coefficient_list)): coefficient_list[h] -= learning_rate * coefficient_list[h].grad coefficient_list[h].grad = None if loss > 100: print('too-big loss, ending training') learning_rate = learning_rate / 10 trainnum = trainnum * 2 print(f'using {device}') print(f'next learning_rate = {learning_rate}') print(f'next trainnum = {trainnum}') print('restarting...') find(x, y, weightsnum, trainnum, learning_rate) exit(1) print(f'loss = {loss.item()}') return coefficient_list
none
1
2.695684
3
examples/development/simulate_policy.py
bandofstraycats/dr-sac
0
6624256
import argparse from distutils.util import strtobool import json import os import pickle import tensorflow as tf from softlearning.environments.utils import get_environment_from_params from softlearning.policies.utils import get_policy_from_variant from softlearning.samplers import rollouts from softlearning.misc.utils import save_video from collections import OrderedDict import numpy as np import csv from gym import wrappers DEFAULT_RENDER_KWARGS = { 'mode': 'human', } def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('checkpoint_path', type=str, help='Path to the checkpoint.') parser.add_argument('--max-path-length', '-l', type=int, default=1000) parser.add_argument('--num-rollouts', '-n', type=int, default=10) parser.add_argument('--render-kwargs', '-r', type=json.loads, default='{}', help="Kwargs for rollouts renderer.") parser.add_argument('--deterministic', '-d', type=lambda x: bool(strtobool(x)), nargs='?', const=True, default=True, help="Evaluate policy deterministically.") parser.add_argument('--record-video', dest='record_video', action='store_true', help="Whether to record a video or store the metrics.") args = parser.parse_args() return args def simulate_policy(args): session = tf.keras.backend.get_session() checkpoint_path = args.checkpoint_path.rstrip('/') experiment_path = os.path.dirname(checkpoint_path) variant_path = os.path.join(experiment_path, 'params.pkl') with open(variant_path, 'rb') as f: variant = pickle.load(f) with session.as_default(): pickle_path = os.path.join(checkpoint_path, 'checkpoint.pkl') with open(pickle_path, 'rb') as f: picklable = pickle.load(f) environment_params = ( variant['environment_params']['evaluation'] if 'evaluation' in variant['environment_params'] else variant['environment_params']['training']) evaluation_environment = get_environment_from_params(environment_params) evaluation_environment.seed(variant['run_params']['seed']) if args.record_video: video_dir = os.path.join(experiment_path, 'test-video') evaluation_environment._env = wrappers.Monitor(evaluation_environment._env, video_dir, force=True) policy = ( get_policy_from_variant(variant, evaluation_environment)) policy.set_weights(picklable['policy_weights']) render_kwargs = {**DEFAULT_RENDER_KWARGS, **args.render_kwargs} with policy.set_deterministic(args.deterministic): paths = rollouts(args.num_rollouts, evaluation_environment, policy, path_length=args.max_path_length, render_kwargs=render_kwargs) if not args.record_video: evaluation_metrics = evaluate_rollouts(paths, evaluation_environment) evaluation_file_path = os.path.join(experiment_path, 'final_eval.csv') with open(evaluation_file_path, 'w') as f: w = csv.DictWriter(f, evaluation_metrics.keys()) w.writeheader() w.writerow(evaluation_metrics) if args.render_kwargs.get('mode') == 'rgb_array': fps = 1 // getattr(evaluation_environment, 'dt', 1/30) for i, path in enumerate(paths): video_save_dir = os.path.expanduser('/tmp/simulate_policy/') video_save_path = os.path.join(video_save_dir, f'episode_{i}.mp4') save_video(path['images'], video_save_path, fps=fps) return paths def evaluate_rollouts(paths, env): """Compute evaluation metrics for the given rollouts.""" total_returns = [path['rewards'].sum() for path in paths] episode_lengths = [len(p['rewards']) for p in paths] diagnostics = OrderedDict(( ('return-average', np.mean(total_returns)), ('return-min', np.min(total_returns)), ('return-max', np.max(total_returns)), ('return-std', np.std(total_returns)), ('episode-length-avg', np.mean(episode_lengths)), ('episode-length-min', np.min(episode_lengths)), ('episode-length-max', np.max(episode_lengths)), ('episode-length-std', np.std(episode_lengths)), )) env_infos = env.get_path_infos(paths) for key, value in env_infos.items(): diagnostics[f'env_infos/{key}'] = value return diagnostics if __name__ == '__main__': args = parse_args() simulate_policy(args)
import argparse from distutils.util import strtobool import json import os import pickle import tensorflow as tf from softlearning.environments.utils import get_environment_from_params from softlearning.policies.utils import get_policy_from_variant from softlearning.samplers import rollouts from softlearning.misc.utils import save_video from collections import OrderedDict import numpy as np import csv from gym import wrappers DEFAULT_RENDER_KWARGS = { 'mode': 'human', } def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('checkpoint_path', type=str, help='Path to the checkpoint.') parser.add_argument('--max-path-length', '-l', type=int, default=1000) parser.add_argument('--num-rollouts', '-n', type=int, default=10) parser.add_argument('--render-kwargs', '-r', type=json.loads, default='{}', help="Kwargs for rollouts renderer.") parser.add_argument('--deterministic', '-d', type=lambda x: bool(strtobool(x)), nargs='?', const=True, default=True, help="Evaluate policy deterministically.") parser.add_argument('--record-video', dest='record_video', action='store_true', help="Whether to record a video or store the metrics.") args = parser.parse_args() return args def simulate_policy(args): session = tf.keras.backend.get_session() checkpoint_path = args.checkpoint_path.rstrip('/') experiment_path = os.path.dirname(checkpoint_path) variant_path = os.path.join(experiment_path, 'params.pkl') with open(variant_path, 'rb') as f: variant = pickle.load(f) with session.as_default(): pickle_path = os.path.join(checkpoint_path, 'checkpoint.pkl') with open(pickle_path, 'rb') as f: picklable = pickle.load(f) environment_params = ( variant['environment_params']['evaluation'] if 'evaluation' in variant['environment_params'] else variant['environment_params']['training']) evaluation_environment = get_environment_from_params(environment_params) evaluation_environment.seed(variant['run_params']['seed']) if args.record_video: video_dir = os.path.join(experiment_path, 'test-video') evaluation_environment._env = wrappers.Monitor(evaluation_environment._env, video_dir, force=True) policy = ( get_policy_from_variant(variant, evaluation_environment)) policy.set_weights(picklable['policy_weights']) render_kwargs = {**DEFAULT_RENDER_KWARGS, **args.render_kwargs} with policy.set_deterministic(args.deterministic): paths = rollouts(args.num_rollouts, evaluation_environment, policy, path_length=args.max_path_length, render_kwargs=render_kwargs) if not args.record_video: evaluation_metrics = evaluate_rollouts(paths, evaluation_environment) evaluation_file_path = os.path.join(experiment_path, 'final_eval.csv') with open(evaluation_file_path, 'w') as f: w = csv.DictWriter(f, evaluation_metrics.keys()) w.writeheader() w.writerow(evaluation_metrics) if args.render_kwargs.get('mode') == 'rgb_array': fps = 1 // getattr(evaluation_environment, 'dt', 1/30) for i, path in enumerate(paths): video_save_dir = os.path.expanduser('/tmp/simulate_policy/') video_save_path = os.path.join(video_save_dir, f'episode_{i}.mp4') save_video(path['images'], video_save_path, fps=fps) return paths def evaluate_rollouts(paths, env): """Compute evaluation metrics for the given rollouts.""" total_returns = [path['rewards'].sum() for path in paths] episode_lengths = [len(p['rewards']) for p in paths] diagnostics = OrderedDict(( ('return-average', np.mean(total_returns)), ('return-min', np.min(total_returns)), ('return-max', np.max(total_returns)), ('return-std', np.std(total_returns)), ('episode-length-avg', np.mean(episode_lengths)), ('episode-length-min', np.min(episode_lengths)), ('episode-length-max', np.max(episode_lengths)), ('episode-length-std', np.std(episode_lengths)), )) env_infos = env.get_path_infos(paths) for key, value in env_infos.items(): diagnostics[f'env_infos/{key}'] = value return diagnostics if __name__ == '__main__': args = parse_args() simulate_policy(args)
en
0.764365
Compute evaluation metrics for the given rollouts.
1.977108
2
scripts/practice/FB/MaximumSumBSTinBinaryTree.py
bhimeshchauhan/competitive_programming
0
6624257
""" Maximum Sum BST in Binary Tree Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] Output: 20 Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. Example 2: Input: root = [4,3,null,1,2] Output: 2 Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. Example 3: Input: root = [-4,-2,-5] Output: 0 Explanation: All values are negatives. Return an empty BST. Example 4: Input: root = [2,1,3] Output: 6 Example 5: Input: root = [5,4,8,3,null,6,3] Output: 7 Constraints: The number of nodes in the tree is in the range [1, 4 * 104]. -4 * 104 <= Node.val <= 4 * 104 """ """ Most solutions discussed here solve this using Post Order traversal. I tried to solve this using preorder traversal (using the floor and ceiling method to check validity of BST like in here), and got confused. For this problem we need to build the solution from the bottom-up i.e., from the leaf nodes towards the root. Only then can we check if the current sub-tree is a valid BST, and then update the maximum sum. This means post order is the ideal way to traverse the tree. Here's a solution using this idea: """ class Solution: def __init__(self): self.maxSum = 0 def maxSumBST(self, root): def postOrderTraverse(node): """ Perform post order traversal of tree to determine sub trees which are BSTs and calculate maximum sum of its elements. Returns: isValidBST: True if valid BST else False currentSum: sum of current sub tree. None if not a valid BST. currentMin: minimum value of current sub tree currentMax: maximum value of current sub tree """ if not node: return True, 0, float('inf'), float('-inf') # Empty sub tree lValidBST, lSum, lMin, lMax = postOrderTraverse(node.left) rValidBST, rSum, rMin, rMax = postOrderTraverse(node.right) # Check if current subtree is a valid BST if lValidBST and rValidBST and lMax < node.val < rMin: currSum = lSum + rSum + node.val currMin = lMin if lMin != float('inf') else node.val currMax = rMax if rMax != float('-inf') else node.val self.maxSum = max(self.maxSum, currSum) # update max sum return True, currSum, currMin, currMax return False, None, None, None postOrderTraverse(root) return self.maxSum
""" Maximum Sum BST in Binary Tree Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] Output: 20 Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. Example 2: Input: root = [4,3,null,1,2] Output: 2 Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. Example 3: Input: root = [-4,-2,-5] Output: 0 Explanation: All values are negatives. Return an empty BST. Example 4: Input: root = [2,1,3] Output: 6 Example 5: Input: root = [5,4,8,3,null,6,3] Output: 7 Constraints: The number of nodes in the tree is in the range [1, 4 * 104]. -4 * 104 <= Node.val <= 4 * 104 """ """ Most solutions discussed here solve this using Post Order traversal. I tried to solve this using preorder traversal (using the floor and ceiling method to check validity of BST like in here), and got confused. For this problem we need to build the solution from the bottom-up i.e., from the leaf nodes towards the root. Only then can we check if the current sub-tree is a valid BST, and then update the maximum sum. This means post order is the ideal way to traverse the tree. Here's a solution using this idea: """ class Solution: def __init__(self): self.maxSum = 0 def maxSumBST(self, root): def postOrderTraverse(node): """ Perform post order traversal of tree to determine sub trees which are BSTs and calculate maximum sum of its elements. Returns: isValidBST: True if valid BST else False currentSum: sum of current sub tree. None if not a valid BST. currentMin: minimum value of current sub tree currentMax: maximum value of current sub tree """ if not node: return True, 0, float('inf'), float('-inf') # Empty sub tree lValidBST, lSum, lMin, lMax = postOrderTraverse(node.left) rValidBST, rSum, rMin, rMax = postOrderTraverse(node.right) # Check if current subtree is a valid BST if lValidBST and rValidBST and lMax < node.val < rMin: currSum = lSum + rSum + node.val currMin = lMin if lMin != float('inf') else node.val currMax = rMax if rMax != float('-inf') else node.val self.maxSum = max(self.maxSum, currSum) # update max sum return True, currSum, currMin, currMax return False, None, None, None postOrderTraverse(root) return self.maxSum
en
0.832744
Maximum Sum BST in Binary Tree Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] Output: 20 Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. Example 2: Input: root = [4,3,null,1,2] Output: 2 Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. Example 3: Input: root = [-4,-2,-5] Output: 0 Explanation: All values are negatives. Return an empty BST. Example 4: Input: root = [2,1,3] Output: 6 Example 5: Input: root = [5,4,8,3,null,6,3] Output: 7 Constraints: The number of nodes in the tree is in the range [1, 4 * 104]. -4 * 104 <= Node.val <= 4 * 104 Most solutions discussed here solve this using Post Order traversal. I tried to solve this using preorder traversal (using the floor and ceiling method to check validity of BST like in here), and got confused. For this problem we need to build the solution from the bottom-up i.e., from the leaf nodes towards the root. Only then can we check if the current sub-tree is a valid BST, and then update the maximum sum. This means post order is the ideal way to traverse the tree. Here's a solution using this idea: Perform post order traversal of tree to determine sub trees which are BSTs and calculate maximum sum of its elements. Returns: isValidBST: True if valid BST else False currentSum: sum of current sub tree. None if not a valid BST. currentMin: minimum value of current sub tree currentMax: maximum value of current sub tree # Empty sub tree # Check if current subtree is a valid BST # update max sum
3.830828
4
dashathon/scraping/scrape_london_data.py
wfrierson/dashathon
1
6624258
<filename>dashathon/scraping/scrape_london_data.py from dashathon.scraping.scraping_methods import scrape_london_marathon_urls from dashathon.scraping.scraping_methods import scrape_london_marathon headers_london = ['year', 'bib', 'age_group', 'gender', 'country', 'overall', 'rank_gender', 'rank_age_group', '5k', '10k', '15k', '20k', 'half', '25k', '30k', '35k', '40k', 'finish'] print('Scraping URLs: 2017 M') london_marathon_urls_2017_M = scrape_london_marathon_urls(url='http://results-2017.virginmoneylondonmarathon.com/2017/', year=2017, event='MAS', gender='M', num_results_per_page=1000) london_marathon_urls_2017_M_elite = scrape_london_marathon_urls(url=('http://results-2017.virginmoneylondonmarathon.com' '/2017/'), year=2017, event='ELIT', gender='M', num_results_per_page=1000) print('Scraping Split Times: 2017 M') scrape_london_marathon(path_input='london_marathon_2017_M_urls.csv', path_output='london_marathon_2017_M.csv', path_error='london_marathon_2017_M_error_log.csv', year=2017, gender='M', headers=headers_london, df_urls=london_marathon_urls_2017_M) scrape_london_marathon(path_input='london_marathon_2017_M_elite_urls.csv', path_output='london_marathon_2017_M_elite.csv', path_error='london_marathon_2017_M_elite_error_log.csv', year=2017, gender='M', headers=headers_london, df_urls=london_marathon_urls_2017_M_elite) print('Scraping URLs: 2017 W') london_marathon_urls_2017_W = scrape_london_marathon_urls(url='http://results-2017.virginmoneylondonmarathon.com/2017/', year=2017, event='MAS', gender='W', num_results_per_page=1000) london_marathon_urls_2017_W_elite = scrape_london_marathon_urls(url=('http://results-2017.virginmoneylondonmarathon.com' '/2017/'), year=2017, event='ELIT', gender='W', num_results_per_page=1000) print('Scraping Split Times: 2017 W') scrape_london_marathon(path_input='london_marathon_2017_W_urls.csv', path_output='london_marathon_2017_W.csv', path_error='london_marathon_2017_W_error_log.csv', year=2017, gender='W', headers=headers_london, df_urls=london_marathon_urls_2017_W) scrape_london_marathon(path_input='london_marathon_2017_W_elite_urls.csv', path_output='london_marathon_2017_W_elite.csv', path_error='london_marathon_2017_W_elite_error_log.csv', year=2017, gender='W', headers=headers_london, df_urls=london_marathon_urls_2017_W_elite) print('Scraping URLs: 2016 M') london_marathon_urls_2016_M = scrape_london_marathon_urls(url='http://results-2016.virginmoneylondonmarathon.com/2016/', year=2016, event='MAS', gender='M', num_results_per_page=1000) london_marathon_urls_2016_M_elite = scrape_london_marathon_urls(url=('http://results-2016.virginmoneylondonmarathon.com' '/2016/'), year=2016, event='ELIT', gender='M', num_results_per_page=1000) print('Scraping Split Times: 2016 M') scrape_london_marathon(path_input='london_marathon_2016_M_urls.csv', path_output='london_marathon_2016_M.csv', path_error='london_marathon_2016_M_error_log.csv', year=2016, gender='M', headers=headers_london, df_urls=london_marathon_urls_2016_M) scrape_london_marathon(path_input='london_marathon_2016_M_elite_urls.csv', path_output='london_marathon_2016_M_elite.csv', path_error='london_marathon_2016_M_elite_error_log.csv', year=2016, gender='M', headers=headers_london, df_urls=london_marathon_urls_2016_M_elite) print('Scraping URLs: 2016 W') london_marathon_urls_2016_W = scrape_london_marathon_urls(url='http://results-2016.virginmoneylondonmarathon.com/2016/', year=2016, event='MAS', gender='W', num_results_per_page=1000) london_marathon_urls_2016_W_elite = scrape_london_marathon_urls(url=('http://results-2016.virginmoneylondonmarathon.com' '/2016/'), year=2016, event='ELIT', gender='W', num_results_per_page=1000) print('Scraping Split Times: 2016 W') scrape_london_marathon(path_input='london_marathon_2016_W_urls.csv', path_output='london_marathon_2016_W.csv', path_error='london_marathon_2016_W_error_log.csv', year=2016, gender='W', headers=headers_london, df_urls=london_marathon_urls_2016_W) scrape_london_marathon(path_input='london_marathon_2016_W_elite_urls.csv', path_output='london_marathon_2016_W_elite.csv', path_error='london_marathon_2016_W_elite_error_log.csv', year=2016, gender='W', headers=headers_london, df_urls=london_marathon_urls_2016_W_elite) print('Scraping URLs: 2015 M') london_marathon_urls_2015_M = scrape_london_marathon_urls(url='http://results-2015.virginmoneylondonmarathon.com/2015/', year=2015, event='MAS', gender='M', num_results_per_page=1000) london_marathon_urls_2015_M_elite = scrape_london_marathon_urls(url=('http://results-2015.virginmoneylondonmarathon.com' '/2015/'), year=2015, event='ELIT', gender='M', num_results_per_page=1000) print('Scraping Split Times: 2015 M') scrape_london_marathon(path_input='london_marathon_2015_M_urls.csv', path_output='london_marathon_2015_M.csv', path_error='london_marathon_2015_M_error_log.csv', year=2015, gender='M', headers=headers_london, df_urls=london_marathon_urls_2015_M) scrape_london_marathon(path_input='london_marathon_2015_M_elite_urls.csv', path_output='london_marathon_2015_M_elite.csv', path_error='london_marathon_2015_M_elite_error_log.csv', year=2015, gender='M', headers=headers_london, df_urls=london_marathon_urls_2015_M_elite) print('Scraping URLs: 2015 W') london_marathon_urls_2015_W = scrape_london_marathon_urls(url='http://results-2015.virginmoneylondonmarathon.com/2015/', year=2015, event='MAS', gender='W', num_results_per_page=1000) london_marathon_urls_2015_W_elite = scrape_london_marathon_urls(url=('http://results-2015.virginmoneylondonmarathon.com' '/2015/'), year=2015, event='ELIT', gender='W', num_results_per_page=1000) print('Scraping Split Times: 2015 W') scrape_london_marathon(path_input='london_marathon_2015_W_urls.csv', path_output='london_marathon_2015_W.csv', path_error='london_marathon_2015_W_error_log.csv', year=2015, gender='W', headers=headers_london, df_urls=london_marathon_urls_2015_W) scrape_london_marathon(path_input='london_marathon_2015_W_elite_urls.csv', path_output='london_marathon_2015_W_elite.csv', path_error='london_marathon_2015_W_elite_error_log.csv', year=2015, gender='W', headers=headers_london, df_urls=london_marathon_urls_2015_W_elite) print('Scraping URLs: 2014 M') london_marathon_urls_2014_M = scrape_london_marathon_urls(url='http://results-2014.virginmoneylondonmarathon.com/2014/', year=2014, event='MAS', gender='M', num_results_per_page=1000) london_marathon_urls_2014_M_elite = scrape_london_marathon_urls(url=('http://results-2014.virginmoneylondonmarathon.com' '/2014/'), year=2014, event='ELIT', gender='M', num_results_per_page=1000) print('Scraping Split Times: 2014 M') scrape_london_marathon(path_input='london_marathon_2014_M_urls.csv', path_output='london_marathon_2014_M.csv', path_error='london_marathon_2014_M_error_log.csv', year=2014, gender='M', headers=headers_london, df_urls=london_marathon_urls_2014_M) scrape_london_marathon(path_input='london_marathon_2014_M_elite_urls.csv', path_output='london_marathon_2014_M_elite.csv', path_error='london_marathon_2014_M_elite_error_log.csv', year=2014, gender='M', headers=headers_london, df_urls=london_marathon_urls_2014_M_elite) print('Scraping URLs: 2014 W') london_marathon_urls_2014_W = scrape_london_marathon_urls(url='http://results-2014.virginmoneylondonmarathon.com/2014/', year=2014, event='MAS', gender='W', num_results_per_page=1000) london_marathon_urls_2014_W_elite = scrape_london_marathon_urls(url=('http://results-2014.virginmoneylondonmarathon.com' '/2014/'), year=2014, event='ELIT', gender='W', num_results_per_page=1000) print('Scraping Split Times: 2014 W') scrape_london_marathon(path_input='london_marathon_2014_W_urls.csv', path_output='london_marathon_2014_W.csv', path_error='london_marathon_2014_W_error_log.csv', year=2014, gender='W', headers=headers_london, df_urls=london_marathon_urls_2014_W) scrape_london_marathon(path_input='london_marathon_2014_W_elite_urls.csv', path_output='london_marathon_2014_W_elite.csv', path_error='london_marathon_2014_W_elite_error_log.csv', year=2014, gender='W', headers=headers_london, df_urls=london_marathon_urls_2014_W_elite)
<filename>dashathon/scraping/scrape_london_data.py from dashathon.scraping.scraping_methods import scrape_london_marathon_urls from dashathon.scraping.scraping_methods import scrape_london_marathon headers_london = ['year', 'bib', 'age_group', 'gender', 'country', 'overall', 'rank_gender', 'rank_age_group', '5k', '10k', '15k', '20k', 'half', '25k', '30k', '35k', '40k', 'finish'] print('Scraping URLs: 2017 M') london_marathon_urls_2017_M = scrape_london_marathon_urls(url='http://results-2017.virginmoneylondonmarathon.com/2017/', year=2017, event='MAS', gender='M', num_results_per_page=1000) london_marathon_urls_2017_M_elite = scrape_london_marathon_urls(url=('http://results-2017.virginmoneylondonmarathon.com' '/2017/'), year=2017, event='ELIT', gender='M', num_results_per_page=1000) print('Scraping Split Times: 2017 M') scrape_london_marathon(path_input='london_marathon_2017_M_urls.csv', path_output='london_marathon_2017_M.csv', path_error='london_marathon_2017_M_error_log.csv', year=2017, gender='M', headers=headers_london, df_urls=london_marathon_urls_2017_M) scrape_london_marathon(path_input='london_marathon_2017_M_elite_urls.csv', path_output='london_marathon_2017_M_elite.csv', path_error='london_marathon_2017_M_elite_error_log.csv', year=2017, gender='M', headers=headers_london, df_urls=london_marathon_urls_2017_M_elite) print('Scraping URLs: 2017 W') london_marathon_urls_2017_W = scrape_london_marathon_urls(url='http://results-2017.virginmoneylondonmarathon.com/2017/', year=2017, event='MAS', gender='W', num_results_per_page=1000) london_marathon_urls_2017_W_elite = scrape_london_marathon_urls(url=('http://results-2017.virginmoneylondonmarathon.com' '/2017/'), year=2017, event='ELIT', gender='W', num_results_per_page=1000) print('Scraping Split Times: 2017 W') scrape_london_marathon(path_input='london_marathon_2017_W_urls.csv', path_output='london_marathon_2017_W.csv', path_error='london_marathon_2017_W_error_log.csv', year=2017, gender='W', headers=headers_london, df_urls=london_marathon_urls_2017_W) scrape_london_marathon(path_input='london_marathon_2017_W_elite_urls.csv', path_output='london_marathon_2017_W_elite.csv', path_error='london_marathon_2017_W_elite_error_log.csv', year=2017, gender='W', headers=headers_london, df_urls=london_marathon_urls_2017_W_elite) print('Scraping URLs: 2016 M') london_marathon_urls_2016_M = scrape_london_marathon_urls(url='http://results-2016.virginmoneylondonmarathon.com/2016/', year=2016, event='MAS', gender='M', num_results_per_page=1000) london_marathon_urls_2016_M_elite = scrape_london_marathon_urls(url=('http://results-2016.virginmoneylondonmarathon.com' '/2016/'), year=2016, event='ELIT', gender='M', num_results_per_page=1000) print('Scraping Split Times: 2016 M') scrape_london_marathon(path_input='london_marathon_2016_M_urls.csv', path_output='london_marathon_2016_M.csv', path_error='london_marathon_2016_M_error_log.csv', year=2016, gender='M', headers=headers_london, df_urls=london_marathon_urls_2016_M) scrape_london_marathon(path_input='london_marathon_2016_M_elite_urls.csv', path_output='london_marathon_2016_M_elite.csv', path_error='london_marathon_2016_M_elite_error_log.csv', year=2016, gender='M', headers=headers_london, df_urls=london_marathon_urls_2016_M_elite) print('Scraping URLs: 2016 W') london_marathon_urls_2016_W = scrape_london_marathon_urls(url='http://results-2016.virginmoneylondonmarathon.com/2016/', year=2016, event='MAS', gender='W', num_results_per_page=1000) london_marathon_urls_2016_W_elite = scrape_london_marathon_urls(url=('http://results-2016.virginmoneylondonmarathon.com' '/2016/'), year=2016, event='ELIT', gender='W', num_results_per_page=1000) print('Scraping Split Times: 2016 W') scrape_london_marathon(path_input='london_marathon_2016_W_urls.csv', path_output='london_marathon_2016_W.csv', path_error='london_marathon_2016_W_error_log.csv', year=2016, gender='W', headers=headers_london, df_urls=london_marathon_urls_2016_W) scrape_london_marathon(path_input='london_marathon_2016_W_elite_urls.csv', path_output='london_marathon_2016_W_elite.csv', path_error='london_marathon_2016_W_elite_error_log.csv', year=2016, gender='W', headers=headers_london, df_urls=london_marathon_urls_2016_W_elite) print('Scraping URLs: 2015 M') london_marathon_urls_2015_M = scrape_london_marathon_urls(url='http://results-2015.virginmoneylondonmarathon.com/2015/', year=2015, event='MAS', gender='M', num_results_per_page=1000) london_marathon_urls_2015_M_elite = scrape_london_marathon_urls(url=('http://results-2015.virginmoneylondonmarathon.com' '/2015/'), year=2015, event='ELIT', gender='M', num_results_per_page=1000) print('Scraping Split Times: 2015 M') scrape_london_marathon(path_input='london_marathon_2015_M_urls.csv', path_output='london_marathon_2015_M.csv', path_error='london_marathon_2015_M_error_log.csv', year=2015, gender='M', headers=headers_london, df_urls=london_marathon_urls_2015_M) scrape_london_marathon(path_input='london_marathon_2015_M_elite_urls.csv', path_output='london_marathon_2015_M_elite.csv', path_error='london_marathon_2015_M_elite_error_log.csv', year=2015, gender='M', headers=headers_london, df_urls=london_marathon_urls_2015_M_elite) print('Scraping URLs: 2015 W') london_marathon_urls_2015_W = scrape_london_marathon_urls(url='http://results-2015.virginmoneylondonmarathon.com/2015/', year=2015, event='MAS', gender='W', num_results_per_page=1000) london_marathon_urls_2015_W_elite = scrape_london_marathon_urls(url=('http://results-2015.virginmoneylondonmarathon.com' '/2015/'), year=2015, event='ELIT', gender='W', num_results_per_page=1000) print('Scraping Split Times: 2015 W') scrape_london_marathon(path_input='london_marathon_2015_W_urls.csv', path_output='london_marathon_2015_W.csv', path_error='london_marathon_2015_W_error_log.csv', year=2015, gender='W', headers=headers_london, df_urls=london_marathon_urls_2015_W) scrape_london_marathon(path_input='london_marathon_2015_W_elite_urls.csv', path_output='london_marathon_2015_W_elite.csv', path_error='london_marathon_2015_W_elite_error_log.csv', year=2015, gender='W', headers=headers_london, df_urls=london_marathon_urls_2015_W_elite) print('Scraping URLs: 2014 M') london_marathon_urls_2014_M = scrape_london_marathon_urls(url='http://results-2014.virginmoneylondonmarathon.com/2014/', year=2014, event='MAS', gender='M', num_results_per_page=1000) london_marathon_urls_2014_M_elite = scrape_london_marathon_urls(url=('http://results-2014.virginmoneylondonmarathon.com' '/2014/'), year=2014, event='ELIT', gender='M', num_results_per_page=1000) print('Scraping Split Times: 2014 M') scrape_london_marathon(path_input='london_marathon_2014_M_urls.csv', path_output='london_marathon_2014_M.csv', path_error='london_marathon_2014_M_error_log.csv', year=2014, gender='M', headers=headers_london, df_urls=london_marathon_urls_2014_M) scrape_london_marathon(path_input='london_marathon_2014_M_elite_urls.csv', path_output='london_marathon_2014_M_elite.csv', path_error='london_marathon_2014_M_elite_error_log.csv', year=2014, gender='M', headers=headers_london, df_urls=london_marathon_urls_2014_M_elite) print('Scraping URLs: 2014 W') london_marathon_urls_2014_W = scrape_london_marathon_urls(url='http://results-2014.virginmoneylondonmarathon.com/2014/', year=2014, event='MAS', gender='W', num_results_per_page=1000) london_marathon_urls_2014_W_elite = scrape_london_marathon_urls(url=('http://results-2014.virginmoneylondonmarathon.com' '/2014/'), year=2014, event='ELIT', gender='W', num_results_per_page=1000) print('Scraping Split Times: 2014 W') scrape_london_marathon(path_input='london_marathon_2014_W_urls.csv', path_output='london_marathon_2014_W.csv', path_error='london_marathon_2014_W_error_log.csv', year=2014, gender='W', headers=headers_london, df_urls=london_marathon_urls_2014_W) scrape_london_marathon(path_input='london_marathon_2014_W_elite_urls.csv', path_output='london_marathon_2014_W_elite.csv', path_error='london_marathon_2014_W_elite_error_log.csv', year=2014, gender='W', headers=headers_london, df_urls=london_marathon_urls_2014_W_elite)
none
1
3.123307
3
gen_fault_codes.py
gitguige/openpilot0.8.9
0
6624259
<reponame>gitguige/openpilot0.8.9 import os import numpy as np import random def gen_add_code(trigger_code, trigger, t1, t2, variable, stuck_value, additional_code): assert(len(variable) == len(stuck_value)) if trigger_code: code = trigger_code else: if len(trigger)>1: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[1], t2) else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) for v, s in zip(variable, stuck_value): l = '//%s+=%s' % (v,s) code = code + l code = code + additional_code return code def gen_sub_code(trigger_code, trigger, t1, t2, variable, stuck_value, additional_code): assert(len(variable) == len(stuck_value)) if trigger_code: code = trigger_code else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) for v, s in zip(variable, stuck_value): l = '//%s-=%s' % (v,s) code = code + l code = code + additional_code return code def gen_none_code(trigger_code, trigger, t1, t2, additional_code): if trigger_code: code = trigger_code else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) l = '//none' code = code + l code = code + additional_code return code def gen_uniform_rand_code(trigger_code, trigger, t1, t2, variable, d1, d2, additional_code): if trigger_code: code = trigger_code else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) for i in range(len(variable)): delta = random.uniform(d1,d2) + (i*3.7) l = '//%s+=(%s)' % (variable[i],str(delta)) code = code + l code = code + additional_code return code def gen_stuck_code(trigger_code, trigger, t1, t2, variable, stuck_value, additional_code): assert(len(variable) == len(stuck_value)) if trigger_code: code = trigger_code else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) for v, s in zip(variable, stuck_value): l = '//%s=%s' % (v,s) code = code + l code = code + additional_code return code ### Write codes to fault library file def write_to_file(fileName, code, param, exp_name, target_file, faultLoc): if os.path.isdir('fault_library') != True: os.makedirs('fault_library') fileName = 'fault_library/scenario_'+str(sceneNum) out_file = fileName+'.txt' param_file = fileName+'_params.csv' with open(out_file, 'w') as outfile: print out_file outfile.write('title:' + exp_name + '\n') outfile.write('location//' + target_file+ '//'+faultLoc + '\n') for i, line in enumerate(code): outfile.write('fault ' + str(i+1) + '//' + line + '\n') outfile.write('Total number of fault cases: '+str(i+1)) with open(param_file, 'w') as outfile: for i, line in enumerate(param): outfile.write(str(i) + ',' + line + '\n') with open('run_fault_inject_campaign.sh', 'a+') as runFile: runFile.write('python run.py '+fileName+'\n') ### Write codes to fault library file -- for vision effects def write_to_vision_file(fileName, code, param, exp_name, target_file, faultLoc): if os.path.isdir('fault_library') != True: os.makedirs('fault_library') effect = fileName fileName = 'fault_library/scenario_'+str(sceneNum) out_file = fileName+'.txt' param_file = fileName+'_params.csv' with open(out_file, 'w') as outfile: print out_file outfile.write('title:' + exp_name + '\n') outfile.write('location//' + target_file+ '//'+faultLoc + '\n') for i, line in enumerate(code): outfile.write('fault ' + str(i+1) + '//' + line + '\n') outfile.write('Total number of fault cases: '+str(i+1)) with open(param_file, 'w') as outfile: for i, line in enumerate(param): outfile.write(str(i) + ',' + line + '\n') with open('run_fault_inject_campaign.sh', 'a+') as runFile: for thickness in range(1,11): if os.path.isdir('../output_files/'+str(sceneNum)+'_vision_'+effect+'/'+str(thickness)) != True: os.makedirs('../output_files/'+str(sceneNum)+'_vision_'+effect+'/'+str(thickness)) runFile.write('./run_matlab_openpilot.sh '+effect+' '+str(thickness)+'\n') runFile.write('python run.py '+fileName+'\n') runFile.write('cp -R '+'../output_files/'+exp_name+' '+'../output_files/'+str(sceneNum)+'_vision_'+effect+'/'+str(thickness)+'/\n') ########################################################### ### d_rel-add-incRADAR-H1 def gen_rel_dist_add_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-add-incRADAR-H1' faultLibFile = 'fault_library/dRelPlantRad' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:','if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['radar_dRel'] deltaRange = np.arange(15,190,10) invRange = np.arange(201,256,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) t1 = random.randint(2,29) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) for dt in [30.0]: t2 = dt for d in invRange: delta = random.randint(d,d+9) t1 = random.randint(2,29) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### v_rel-add-incRADAR-H1 def gen_rel_vel_add_fault_plant(sceneNum): title = str(sceneNum)+'_v_rel-add-incRADAR-H1' faultLibFile = 'fault_library/vRelPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:','if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['v_rel'] deltaRange = np.arange(10,61,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: t1 = random.randint(2,29) delta = random.randint(d,d+9) if delta > 60: delta = 60 delta = delta*0.44704 # 1MPH = 0.44704 m/s code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative speed',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-sub-incRADAR-H2 def gen_rel_dist_sub_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-sub-incRADAR-H2' faultLibFile = 'fault_library/dRelPlantRad' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['radar_dRel'] deltaRange = np.arange(10,255,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.]: t2 = dt t1 = random.randint(2,29) delta = random.randint(d,d+9) code.append(gen_sub_code('',trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'<0:'+'// '+variable[0]+'= 0')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### v_rel-sub-incRADAR-H2 def gen_rel_vel_sub_fault_plant(sceneNum): title = str(sceneNum)+'_v_rel-sub-incRADAR-H2' faultLibFile = 'fault_library/vRelPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['v_rel'] deltaRange = np.arange(10,61,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.]: t2 = dt delta = random.randint(d,d+9) t1 = random.randint(2,29) if delta > 60: delta = 60 delta = delta*0.44704 # 1MPH = 0.44704 m/s code.append(gen_sub_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative speed',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### radar-none-incRADAR-H1 def gen_radar_jamming_fault_plant_H1(sceneNum): title = str(sceneNum)+'_radar-none-incRADAR-H1' faultLibFile = 'fault_library/radJamPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_none:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 or RSpeed>0:', 'if headway_time>2.0 or RSpeed<=0:', 'if headway_time<=2.0 or RSpeed<=0:'] # reverse of actual trigger code = [] param = [] variable = [] for trig in np.arange(0,len(trigger_code)): for dt in [0.0]: t1 = random.randint(2,29) t2 = dt code.append(gen_none_code('', trigger, t2*100., t1*100., '')) param.append(','.join(['radar jamming',str(t1),str(dt),'none'])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### radar-none-incRADAR-H2 def gen_radar_jamming_fault_plant_H2(sceneNum): title = str(sceneNum)+'_radar-none-incRADAR-H2' faultLibFile = 'fault_library/radJamPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_none:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 or RSpeed>0:'] code = [] param = [] variable = [] for trig in np.arange(0,len(trigger_code)): for dt in [0.0]: t1 = random.randint(2,29) t2 = dt code.append(gen_none_code('', trigger, t2*100., t1*100., '')) param.append(','.join(['radar jamming',str(t1),str(dt),'none'])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### curr_sp-sub-incProcPlant-H1 def gen_curr_sp_sub_fault_plant(sceneNum): title = str(sceneNum)+'_curr_sp-sub-incProcPlant-H1' faultLibFile = 'fault_library/vCurrSpPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#speed:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['speed2send'] deltaRange = np.arange(10,61,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) if delta > 60: delta = 60 delta = delta*0.44704 # 1MPH = 0.44704 m/s t1 = random.randint(2,29) code.append(gen_sub_code('', trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'<0:'+'// '+variable[0]+'= 0')) param.append(','.join(['current speed',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### curr_sp-add-incProcPlant-H2 def gen_curr_sp_add_fault_plant(sceneNum): title = str(sceneNum)+'_curr_sp-add-incProcPlant-H2' faultLibFile = 'fault_library/vCurrSpPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#speed:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['speed2send'] deltaRange = np.arange(10,61,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.]: t2 = dt delta = random.randint(d,d+9) if delta > 60: delta = 60 delta = delta*0.44704 # 1MPH = 0.44704 m/s t1 = random.randint(2,29) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'>=85.0:'+'// '+variable[0]+'= 85.0')) param.append(','.join(['current speed',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### md-rand-incProcPlant-H3 def gen_md_rand_val_plant(lane,sceneNum): title = str(sceneNum)+'_'+lane+'Lane-rand-incProcPlant-H3' faultLibFile = 'fault_library/mdPlant_'+lane fileLoc = 'selfdrive/test/plant/maneuver.py' faultLoc = '#md:HOOK#' trigger = ['self.frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed>=0:', 'if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:','if headway_time>2.0 and RSpeed>0:'] code = [] param = [] if lane.lower()=='left': variable = ['self.lLane'] elif lane.lower()=='right': variable = ['self.rLane'] else: variable = ['self.lLane','self.rLane'] deltaRange = np.arange(-2.5,2.5,0.5) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d1 in deltaRange: d2 = d1+1 t1 = random.randint(2,29) code.append(gen_uniform_rand_code('', trigger, t1*100., t2*100., variable, d1, d2, '')) param.append(','.join(['path model',str(t1),str(dt),str(d1),str(d2)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### angSteer-add-incProcPlant-H3 def gen_angle_steer_add_plant(sceneNum): title = str(sceneNum)+'_angSteer-add-incProcPlant-H3' faultLibFile = 'fault_library/angSteerPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#angle_steer:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed>=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:','if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['angle_steer2send'] deltaRange = np.arange(-45,46,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) if d > 45: alpha = 45*3.1416/180.0 else: alpha = delta*3.1416/180.0 t1 = random.randint(2,29) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, ['('+str(alpha)+')'], '')) param.append(','.join(['steer angle',str(t1),str(dt),str(alpha)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### vision-none-miscommVisPlant-H3 def gen_vision_miscomm_fault_plant(sceneNum): title = str(sceneNum)+'_vision-none-miscommVisPlant-H3' faultLibFile = 'fault_library/visMiscommPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#md_none:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 or RSpeed<0:','if headway_time>2.0 or RSpeed>0', 'if headway_time<=2.0 or RSpeed<=0', 'if headway_time<=2.0 or RSpeed>0'] code = [] param = [] variable = [] for trig in np.arange(0,len(trigger_code)): for dt in [0.0]: t2 = dt t1 = random.randint(2,29) code.append(gen_none_code('', trigger, t2*100., t1*100., '')) param.append(','.join(['vision miscomm',str(t1),str(dt),'none'])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### vision-effect-noisyInputManeuver-H3 def gen_vision_noisyInput_fault_Maneuver(effect, sceneNum): title = str(sceneNum)+'_vision-effect-noisyInputManeuver-H3' faultLibFile = '' fileLoc = 'selfdrive/test/plant/maneuver.py' faultLoc = '#visionFault:HOOK#' trigger = ['self.frameIdx'] trigger_code = ['if headway_time<=2.5 and RSpeed>=0:', 'if headway_time>2.5 and RSpeed>0:','if headway_time>2.5 and RSpeed<=0:','if headway_time<=2.5 and RSpeed<0:'] code = [] param = [] #variable = ['left_line','right_line'] #deltaRange = ['lanes[0]','lanes[1]'] variable = ['self.effect', 'self.thickness'] if effect <7: range_th = range(1,11) elif effect == 7: range_th = range(3,7) elif effect == 8: range_th = [3,5,7] elif effect == 9: range_th = [3,5] for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: for th in range_th: t2 = dt t1 = random.randint(2,29) code.append(gen_stuck_code('', trigger, t1*100., t2*100., variable, [str(effect), str(th)], '')) param.append(','.join(['vision noisyInput',str(t1),str(dt),'none'])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-add-incVision-H1 def gen_vision_dRel_add_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-add-incVision-H1' faultLibFile = 'fault_library/dRelPlantVis' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#vision_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:','if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['vision_dRel'] deltaRange = np.arange(15,255,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) t1 = random.randint(2,29) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-sub-incVision-H2 def gen_vision_dRel_sub_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-sub-incVision-H2' faultLibFile = 'fault_library/dRelPlantVis' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#vision_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['vision_dRel'] deltaRange = np.arange(10,255,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.0]: t2 = dt delta = random.randint(d,d+9) t1 = random.randint(2,29) code.append(gen_sub_code('',trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'<0:'+'// '+variable[0]+'= 0')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-add-incRadVis-H1 def gen_RadVis_dRel_add_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-add-incRadVis-H1' faultLibFile = 'fault_library/dRelPlantRadVis' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#RadVis_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['d_rel'] deltaRange = np.arange(15,255,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) t1 = random.randint(2,29) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-sub-incRadVis-H2 def gen_RadVis_dRel_sub_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-sub-incRadVis-H2' faultLibFile = 'fault_library/dRelPlantRadVis' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#RadVis_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['d_rel'] deltaRange = np.arange(10,255,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.0]: t2 = dt delta = random.randint(d,d+9) t1 = random.randint(2,29) code.append(gen_sub_code('',trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'<0:'+'// '+variable[0]+'= 0')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ########################################## ###_main_### with open('run_fault_inject_campaign.sh', 'w') as runFile: runFile.write('#Usage: python run.py target_fault_library\n') scenarios = { 1 : gen_rel_dist_add_fault_plant, 2 : gen_rel_vel_add_fault_plant, 3 : gen_rel_dist_sub_fault_plant, 4 : gen_rel_vel_sub_fault_plant, 5 : gen_radar_jamming_fault_plant_H1, 6 : gen_radar_jamming_fault_plant_H2, 9 : gen_curr_sp_sub_fault_plant, 12 : gen_curr_sp_add_fault_plant, 13 : gen_md_rand_val_plant, 14 : gen_md_rand_val_plant, 15 : gen_md_rand_val_plant, 16 : gen_angle_steer_add_plant, 34 : gen_vision_miscomm_fault_plant, 35 : gen_vision_noisyInput_fault_Maneuver, 36 : gen_vision_noisyInput_fault_Maneuver, 37 : gen_vision_noisyInput_fault_Maneuver, 38 : gen_vision_noisyInput_fault_Maneuver, 39 : gen_vision_dRel_add_fault_plant, 40 : gen_vision_dRel_sub_fault_plant, 41 : gen_RadVis_dRel_add_fault_plant, 42 : gen_RadVis_dRel_sub_fault_plant, 43 : gen_vision_noisyInput_fault_Maneuver, 44 : gen_vision_noisyInput_fault_Maneuver, 45 : gen_vision_noisyInput_fault_Maneuver, 46 : gen_vision_noisyInput_fault_Maneuver, 47 : gen_vision_noisyInput_fault_Maneuver } lanes = ['left','right','both'] # 'left','right','both' poly = ['p_path','left','right','d_path'] # 'p_path','left','right','d_path' #effects = ['rain', 'fog', 'snow', 'occlusion'] effects = [1,2,3,4,5,6,7,8,9] for sceneNum in [1,2,3,4,5,6,9,12,13,14,15,16,34,39,40,41,42]: # experiments without the vision #for sceneNum in [35,36,37,38,43,44,45,46,47]: # for testing the faults in input images #for sceneNum in [1,2,3,4,5,6,9,12,13,14,15,16,34,35,36,37,38,39,40,41,42,43,44,45,46,47]: # for testing the faults in inputs # for sceneNum in [44,45,46,47]: print sceneNum cmd = 'cp '+ 'fault_library/scenario_'+str(sceneNum)+'.txt '+'fault_library/scenario_'+str(sceneNum)+'_prev.txt' os.system(cmd) if sceneNum >= 13 and sceneNum <=15: scenarios[sceneNum](lanes[sceneNum-13],sceneNum) elif sceneNum >= 28 and sceneNum <=31: scenarios[sceneNum](poly[sceneNum-28],sceneNum) elif sceneNum >= 35 and sceneNum <=38: scenarios[sceneNum](effects[sceneNum-35],sceneNum) elif sceneNum >= 43 and sceneNum <=47: scenarios[sceneNum](effects[sceneNum+4-43],sceneNum) else: scenarios[sceneNum](sceneNum)
import os import numpy as np import random def gen_add_code(trigger_code, trigger, t1, t2, variable, stuck_value, additional_code): assert(len(variable) == len(stuck_value)) if trigger_code: code = trigger_code else: if len(trigger)>1: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[1], t2) else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) for v, s in zip(variable, stuck_value): l = '//%s+=%s' % (v,s) code = code + l code = code + additional_code return code def gen_sub_code(trigger_code, trigger, t1, t2, variable, stuck_value, additional_code): assert(len(variable) == len(stuck_value)) if trigger_code: code = trigger_code else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) for v, s in zip(variable, stuck_value): l = '//%s-=%s' % (v,s) code = code + l code = code + additional_code return code def gen_none_code(trigger_code, trigger, t1, t2, additional_code): if trigger_code: code = trigger_code else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) l = '//none' code = code + l code = code + additional_code return code def gen_uniform_rand_code(trigger_code, trigger, t1, t2, variable, d1, d2, additional_code): if trigger_code: code = trigger_code else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) for i in range(len(variable)): delta = random.uniform(d1,d2) + (i*3.7) l = '//%s+=(%s)' % (variable[i],str(delta)) code = code + l code = code + additional_code return code def gen_stuck_code(trigger_code, trigger, t1, t2, variable, stuck_value, additional_code): assert(len(variable) == len(stuck_value)) if trigger_code: code = trigger_code else: code = 'if %s>=%s and %s<=%s:' % \ (trigger[0], t1, trigger[0], t2) for v, s in zip(variable, stuck_value): l = '//%s=%s' % (v,s) code = code + l code = code + additional_code return code ### Write codes to fault library file def write_to_file(fileName, code, param, exp_name, target_file, faultLoc): if os.path.isdir('fault_library') != True: os.makedirs('fault_library') fileName = 'fault_library/scenario_'+str(sceneNum) out_file = fileName+'.txt' param_file = fileName+'_params.csv' with open(out_file, 'w') as outfile: print out_file outfile.write('title:' + exp_name + '\n') outfile.write('location//' + target_file+ '//'+faultLoc + '\n') for i, line in enumerate(code): outfile.write('fault ' + str(i+1) + '//' + line + '\n') outfile.write('Total number of fault cases: '+str(i+1)) with open(param_file, 'w') as outfile: for i, line in enumerate(param): outfile.write(str(i) + ',' + line + '\n') with open('run_fault_inject_campaign.sh', 'a+') as runFile: runFile.write('python run.py '+fileName+'\n') ### Write codes to fault library file -- for vision effects def write_to_vision_file(fileName, code, param, exp_name, target_file, faultLoc): if os.path.isdir('fault_library') != True: os.makedirs('fault_library') effect = fileName fileName = 'fault_library/scenario_'+str(sceneNum) out_file = fileName+'.txt' param_file = fileName+'_params.csv' with open(out_file, 'w') as outfile: print out_file outfile.write('title:' + exp_name + '\n') outfile.write('location//' + target_file+ '//'+faultLoc + '\n') for i, line in enumerate(code): outfile.write('fault ' + str(i+1) + '//' + line + '\n') outfile.write('Total number of fault cases: '+str(i+1)) with open(param_file, 'w') as outfile: for i, line in enumerate(param): outfile.write(str(i) + ',' + line + '\n') with open('run_fault_inject_campaign.sh', 'a+') as runFile: for thickness in range(1,11): if os.path.isdir('../output_files/'+str(sceneNum)+'_vision_'+effect+'/'+str(thickness)) != True: os.makedirs('../output_files/'+str(sceneNum)+'_vision_'+effect+'/'+str(thickness)) runFile.write('./run_matlab_openpilot.sh '+effect+' '+str(thickness)+'\n') runFile.write('python run.py '+fileName+'\n') runFile.write('cp -R '+'../output_files/'+exp_name+' '+'../output_files/'+str(sceneNum)+'_vision_'+effect+'/'+str(thickness)+'/\n') ########################################################### ### d_rel-add-incRADAR-H1 def gen_rel_dist_add_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-add-incRADAR-H1' faultLibFile = 'fault_library/dRelPlantRad' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:','if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['radar_dRel'] deltaRange = np.arange(15,190,10) invRange = np.arange(201,256,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) t1 = random.randint(2,29) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) for dt in [30.0]: t2 = dt for d in invRange: delta = random.randint(d,d+9) t1 = random.randint(2,29) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### v_rel-add-incRADAR-H1 def gen_rel_vel_add_fault_plant(sceneNum): title = str(sceneNum)+'_v_rel-add-incRADAR-H1' faultLibFile = 'fault_library/vRelPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:','if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['v_rel'] deltaRange = np.arange(10,61,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: t1 = random.randint(2,29) delta = random.randint(d,d+9) if delta > 60: delta = 60 delta = delta*0.44704 # 1MPH = 0.44704 m/s code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative speed',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-sub-incRADAR-H2 def gen_rel_dist_sub_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-sub-incRADAR-H2' faultLibFile = 'fault_library/dRelPlantRad' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['radar_dRel'] deltaRange = np.arange(10,255,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.]: t2 = dt t1 = random.randint(2,29) delta = random.randint(d,d+9) code.append(gen_sub_code('',trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'<0:'+'// '+variable[0]+'= 0')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### v_rel-sub-incRADAR-H2 def gen_rel_vel_sub_fault_plant(sceneNum): title = str(sceneNum)+'_v_rel-sub-incRADAR-H2' faultLibFile = 'fault_library/vRelPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['v_rel'] deltaRange = np.arange(10,61,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.]: t2 = dt delta = random.randint(d,d+9) t1 = random.randint(2,29) if delta > 60: delta = 60 delta = delta*0.44704 # 1MPH = 0.44704 m/s code.append(gen_sub_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative speed',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### radar-none-incRADAR-H1 def gen_radar_jamming_fault_plant_H1(sceneNum): title = str(sceneNum)+'_radar-none-incRADAR-H1' faultLibFile = 'fault_library/radJamPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_none:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 or RSpeed>0:', 'if headway_time>2.0 or RSpeed<=0:', 'if headway_time<=2.0 or RSpeed<=0:'] # reverse of actual trigger code = [] param = [] variable = [] for trig in np.arange(0,len(trigger_code)): for dt in [0.0]: t1 = random.randint(2,29) t2 = dt code.append(gen_none_code('', trigger, t2*100., t1*100., '')) param.append(','.join(['radar jamming',str(t1),str(dt),'none'])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### radar-none-incRADAR-H2 def gen_radar_jamming_fault_plant_H2(sceneNum): title = str(sceneNum)+'_radar-none-incRADAR-H2' faultLibFile = 'fault_library/radJamPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#radar_none:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 or RSpeed>0:'] code = [] param = [] variable = [] for trig in np.arange(0,len(trigger_code)): for dt in [0.0]: t1 = random.randint(2,29) t2 = dt code.append(gen_none_code('', trigger, t2*100., t1*100., '')) param.append(','.join(['radar jamming',str(t1),str(dt),'none'])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### curr_sp-sub-incProcPlant-H1 def gen_curr_sp_sub_fault_plant(sceneNum): title = str(sceneNum)+'_curr_sp-sub-incProcPlant-H1' faultLibFile = 'fault_library/vCurrSpPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#speed:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['speed2send'] deltaRange = np.arange(10,61,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) if delta > 60: delta = 60 delta = delta*0.44704 # 1MPH = 0.44704 m/s t1 = random.randint(2,29) code.append(gen_sub_code('', trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'<0:'+'// '+variable[0]+'= 0')) param.append(','.join(['current speed',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### curr_sp-add-incProcPlant-H2 def gen_curr_sp_add_fault_plant(sceneNum): title = str(sceneNum)+'_curr_sp-add-incProcPlant-H2' faultLibFile = 'fault_library/vCurrSpPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#speed:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['speed2send'] deltaRange = np.arange(10,61,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.]: t2 = dt delta = random.randint(d,d+9) if delta > 60: delta = 60 delta = delta*0.44704 # 1MPH = 0.44704 m/s t1 = random.randint(2,29) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'>=85.0:'+'// '+variable[0]+'= 85.0')) param.append(','.join(['current speed',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### md-rand-incProcPlant-H3 def gen_md_rand_val_plant(lane,sceneNum): title = str(sceneNum)+'_'+lane+'Lane-rand-incProcPlant-H3' faultLibFile = 'fault_library/mdPlant_'+lane fileLoc = 'selfdrive/test/plant/maneuver.py' faultLoc = '#md:HOOK#' trigger = ['self.frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed>=0:', 'if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:','if headway_time>2.0 and RSpeed>0:'] code = [] param = [] if lane.lower()=='left': variable = ['self.lLane'] elif lane.lower()=='right': variable = ['self.rLane'] else: variable = ['self.lLane','self.rLane'] deltaRange = np.arange(-2.5,2.5,0.5) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d1 in deltaRange: d2 = d1+1 t1 = random.randint(2,29) code.append(gen_uniform_rand_code('', trigger, t1*100., t2*100., variable, d1, d2, '')) param.append(','.join(['path model',str(t1),str(dt),str(d1),str(d2)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### angSteer-add-incProcPlant-H3 def gen_angle_steer_add_plant(sceneNum): title = str(sceneNum)+'_angSteer-add-incProcPlant-H3' faultLibFile = 'fault_library/angSteerPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#angle_steer:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed>=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:','if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['angle_steer2send'] deltaRange = np.arange(-45,46,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) if d > 45: alpha = 45*3.1416/180.0 else: alpha = delta*3.1416/180.0 t1 = random.randint(2,29) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, ['('+str(alpha)+')'], '')) param.append(','.join(['steer angle',str(t1),str(dt),str(alpha)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### vision-none-miscommVisPlant-H3 def gen_vision_miscomm_fault_plant(sceneNum): title = str(sceneNum)+'_vision-none-miscommVisPlant-H3' faultLibFile = 'fault_library/visMiscommPlant' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#md_none:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 or RSpeed<0:','if headway_time>2.0 or RSpeed>0', 'if headway_time<=2.0 or RSpeed<=0', 'if headway_time<=2.0 or RSpeed>0'] code = [] param = [] variable = [] for trig in np.arange(0,len(trigger_code)): for dt in [0.0]: t2 = dt t1 = random.randint(2,29) code.append(gen_none_code('', trigger, t2*100., t1*100., '')) param.append(','.join(['vision miscomm',str(t1),str(dt),'none'])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### vision-effect-noisyInputManeuver-H3 def gen_vision_noisyInput_fault_Maneuver(effect, sceneNum): title = str(sceneNum)+'_vision-effect-noisyInputManeuver-H3' faultLibFile = '' fileLoc = 'selfdrive/test/plant/maneuver.py' faultLoc = '#visionFault:HOOK#' trigger = ['self.frameIdx'] trigger_code = ['if headway_time<=2.5 and RSpeed>=0:', 'if headway_time>2.5 and RSpeed>0:','if headway_time>2.5 and RSpeed<=0:','if headway_time<=2.5 and RSpeed<0:'] code = [] param = [] #variable = ['left_line','right_line'] #deltaRange = ['lanes[0]','lanes[1]'] variable = ['self.effect', 'self.thickness'] if effect <7: range_th = range(1,11) elif effect == 7: range_th = range(3,7) elif effect == 8: range_th = [3,5,7] elif effect == 9: range_th = [3,5] for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: for th in range_th: t2 = dt t1 = random.randint(2,29) code.append(gen_stuck_code('', trigger, t1*100., t2*100., variable, [str(effect), str(th)], '')) param.append(','.join(['vision noisyInput',str(t1),str(dt),'none'])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-add-incVision-H1 def gen_vision_dRel_add_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-add-incVision-H1' faultLibFile = 'fault_library/dRelPlantVis' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#vision_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:','if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['vision_dRel'] deltaRange = np.arange(15,255,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) t1 = random.randint(2,29) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-sub-incVision-H2 def gen_vision_dRel_sub_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-sub-incVision-H2' faultLibFile = 'fault_library/dRelPlantVis' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#vision_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['vision_dRel'] deltaRange = np.arange(10,255,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.0]: t2 = dt delta = random.randint(d,d+9) t1 = random.randint(2,29) code.append(gen_sub_code('',trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'<0:'+'// '+variable[0]+'= 0')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-add-incRadVis-H1 def gen_RadVis_dRel_add_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-add-incRadVis-H1' faultLibFile = 'fault_library/dRelPlantRadVis' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#RadVis_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed<=0:'] code = [] param = [] variable = ['d_rel'] deltaRange = np.arange(15,255,10) for trig in np.arange(0,len(trigger_code)): for dt in [30.0]: t2 = dt for d in deltaRange: delta = random.randint(d,d+9) t1 = random.randint(2,29) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) code.append(gen_add_code('', trigger, t1*100., t2*100., variable, [delta], '')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ### d_rel-sub-incRadVis-H2 def gen_RadVis_dRel_sub_fault_plant(sceneNum): title = str(sceneNum)+'_d_rel-sub-incRadVis-H2' faultLibFile = 'fault_library/dRelPlantRadVis' fileLoc = 'selfdrive/test/plant/plant.py' faultLoc = '#RadVis_dRel:HOOK#' trigger = ['frameIdx'] trigger_code = ['if headway_time>2.0 and RSpeed<=0:','if headway_time<=2.0 and RSpeed<=0:', 'if headway_time<=2.0 and RSpeed>0:', 'if headway_time>2.0 and RSpeed>0:'] code = [] param = [] variable = ['d_rel'] deltaRange = np.arange(10,255,10) for trig in np.arange(0,len(trigger_code)): for d in deltaRange: for dt in [30.0]: t2 = dt delta = random.randint(d,d+9) t1 = random.randint(2,29) code.append(gen_sub_code('',trigger, t1*100., t2*100., variable, [delta], '//if '+variable[0]+'<0:'+'// '+variable[0]+'= 0')) param.append(','.join(['relative distance',str(t1),str(dt),str(delta)])) write_to_file(faultLibFile, code, param, title, fileLoc, faultLoc) ########################################## ###_main_### with open('run_fault_inject_campaign.sh', 'w') as runFile: runFile.write('#Usage: python run.py target_fault_library\n') scenarios = { 1 : gen_rel_dist_add_fault_plant, 2 : gen_rel_vel_add_fault_plant, 3 : gen_rel_dist_sub_fault_plant, 4 : gen_rel_vel_sub_fault_plant, 5 : gen_radar_jamming_fault_plant_H1, 6 : gen_radar_jamming_fault_plant_H2, 9 : gen_curr_sp_sub_fault_plant, 12 : gen_curr_sp_add_fault_plant, 13 : gen_md_rand_val_plant, 14 : gen_md_rand_val_plant, 15 : gen_md_rand_val_plant, 16 : gen_angle_steer_add_plant, 34 : gen_vision_miscomm_fault_plant, 35 : gen_vision_noisyInput_fault_Maneuver, 36 : gen_vision_noisyInput_fault_Maneuver, 37 : gen_vision_noisyInput_fault_Maneuver, 38 : gen_vision_noisyInput_fault_Maneuver, 39 : gen_vision_dRel_add_fault_plant, 40 : gen_vision_dRel_sub_fault_plant, 41 : gen_RadVis_dRel_add_fault_plant, 42 : gen_RadVis_dRel_sub_fault_plant, 43 : gen_vision_noisyInput_fault_Maneuver, 44 : gen_vision_noisyInput_fault_Maneuver, 45 : gen_vision_noisyInput_fault_Maneuver, 46 : gen_vision_noisyInput_fault_Maneuver, 47 : gen_vision_noisyInput_fault_Maneuver } lanes = ['left','right','both'] # 'left','right','both' poly = ['p_path','left','right','d_path'] # 'p_path','left','right','d_path' #effects = ['rain', 'fog', 'snow', 'occlusion'] effects = [1,2,3,4,5,6,7,8,9] for sceneNum in [1,2,3,4,5,6,9,12,13,14,15,16,34,39,40,41,42]: # experiments without the vision #for sceneNum in [35,36,37,38,43,44,45,46,47]: # for testing the faults in input images #for sceneNum in [1,2,3,4,5,6,9,12,13,14,15,16,34,35,36,37,38,39,40,41,42,43,44,45,46,47]: # for testing the faults in inputs # for sceneNum in [44,45,46,47]: print sceneNum cmd = 'cp '+ 'fault_library/scenario_'+str(sceneNum)+'.txt '+'fault_library/scenario_'+str(sceneNum)+'_prev.txt' os.system(cmd) if sceneNum >= 13 and sceneNum <=15: scenarios[sceneNum](lanes[sceneNum-13],sceneNum) elif sceneNum >= 28 and sceneNum <=31: scenarios[sceneNum](poly[sceneNum-28],sceneNum) elif sceneNum >= 35 and sceneNum <=38: scenarios[sceneNum](effects[sceneNum-35],sceneNum) elif sceneNum >= 43 and sceneNum <=47: scenarios[sceneNum](effects[sceneNum+4-43],sceneNum) else: scenarios[sceneNum](sceneNum)
en
0.282757
### Write codes to fault library file ### Write codes to fault library file -- for vision effects ########################################################### ### d_rel-add-incRADAR-H1 #' #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) ### v_rel-add-incRADAR-H1 #' # 1MPH = 0.44704 m/s ### d_rel-sub-incRADAR-H2 #' ### v_rel-sub-incRADAR-H2 #' # 1MPH = 0.44704 m/s ### radar-none-incRADAR-H1 #' # reverse of actual trigger ### radar-none-incRADAR-H2 #' ### curr_sp-sub-incProcPlant-H1 #' # 1MPH = 0.44704 m/s ### curr_sp-add-incProcPlant-H2 #' # 1MPH = 0.44704 m/s ### md-rand-incProcPlant-H3 #' ### angSteer-add-incProcPlant-H3 #' ### vision-none-miscommVisPlant-H3 #' ### vision-effect-noisyInputManeuver-H3 #' #variable = ['left_line','right_line'] #deltaRange = ['lanes[0]','lanes[1]'] ### d_rel-add-incVision-H1 #' #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) ### d_rel-sub-incVision-H2 #' ### d_rel-add-incRadVis-H1 #' #code.append(gen_add_code(trigger_code, trigger, t1, t2, variable, [delta], '//if '+variable[0]+'>=255:'+'// '+variable[0]+'= 254')) ### d_rel-sub-incRadVis-H2 #' ########################################## ###_main_### # 'left','right','both' # 'p_path','left','right','d_path' #effects = ['rain', 'fog', 'snow', 'occlusion'] # experiments without the vision #for sceneNum in [35,36,37,38,43,44,45,46,47]: # for testing the faults in input images #for sceneNum in [1,2,3,4,5,6,9,12,13,14,15,16,34,35,36,37,38,39,40,41,42,43,44,45,46,47]: # for testing the faults in inputs # for sceneNum in [44,45,46,47]:
2.792949
3
download_module.py
ashvinoli/Anime-no-tomodachi
2
6624260
from tree import * import pathlib import sys import time import math no_interruption_mode = False interruption_response = None anime_name_response = None selection_response = None choice_response = None if len(sys.argv) == 2: #First argument is file name lines = [] if os.path.exists("repeat.txt"): if sys.argv[1] == "-r": repeat = open("repeat.txt","r") for line in repeat: lines.append(line.rstrip()) if len(lines)>=4: interruption_response = lines[0] anime_name_response = lines[1] selection_response = lines[2] choice_response = lines[3] repeat.close() def video_quality_selection(my_playlist,anime_directory,episode_name): #This function prompts the user to select quality global default_mode chunks = anime_directory + "/Chunks" index = 1 length = len(my_playlist) print("Video qualities available for "+ episode_name) for _ in my_playlist: print(str(index) + "----->"+ _[0]) index += 1 while True: resp = input("Choose the quality of video:") if resp.isnumeric() and int(resp) <= length and int(resp) >= 1: my_quality_video = provide_video_chunks(my_playlist[int(resp)-1][1]) if len(my_quality_video) == 0: my_quality_video = provide_video_chunks_new(my_playlist[int(resp)-1][1]) ans = input("Do you want to keep it as default quality for the next videos? Type y/n:") quality_file = open(chunks +"/quality.txt","w") quality_file.write(my_playlist[int(resp)-1][0]) quality_file.close() if ans == "y": default_mode = my_playlist[int(resp)-1][0] download_chunks(my_quality_video,anime_directory,episode_name) break else: resp = input("Bad quality!!!!!! Re-enter quality y/n?") if resp != "y": break def download_in_a_different_way(episode_link): global headers series_name = "-".join(episode_link.split("/")[-1].split("-")[:-2]) episode_name = episode_link.split("/")[-1] program_path = os.path.dirname(os.path.realpath(__file__)) anime_directory = program_path + "/" + series_name + "/" + episode_name chunks = anime_directory + "/Chunks" if os.path.exists(anime_directory + "/" +episode_name+".mp4"): print(episode_name+" has already been downloaded") return if not os.path.exists(chunks): pathlib.Path(chunks).mkdir(parents=True, exist_ok=True) vid_stream_link = BeautifulSoup(requests.get(episode_link).text,"html.parser").findAll("a",{"href":re.compile(r"https://vidstreaming.io/download.*")})[0].get("href") #print(vid_stream_link) write_to_log_file("Video stream link from download in different way:\n",vid_stream_link) download_link = BeautifulSoup(requests.get(vid_stream_link).text,"html.parser").findAll("a",{"href":re.compile(r"https://st\dx.cdnfile.info.*")})[0].get("href") #print(download_link) write_to_log_file("Download link for episode " +episode_link +":\n",download_link) #size = requests.head(download_link).headers.get("Content-length") The headers couldn't be retrieved so I had to comment this out #print(size) #write_to_log_file("Size of episode:\n",size) files = requests.get(download_link,headers = headers,stream=True) files.raise_for_status index = 1 print("Downloading "+episode_link) time_prev = time.time() standard_size = 1048576 file_pieces = files.iter_content(chunk_size = standard_size) for piece in files.iter_content(chunk_size = standard_size): chunk_name = chunks+"/"+"chunk_"+str(index)+".mp4" chunk_file = open(chunk_name,"wb") chunk_file.write(piece) chunk_file.close() time_new = time.time() time_difference = time_new-time_prev time_prev = time_new #percentage = int(index*standard_size/int(size)*100) #if percentage >= 100: # percentage = 100 average_speed = (standard_size)/(1024*time_difference) print(str(index)+" chunks downloaded. Average internet speed = %.2f KB/s" % (average_speed),end="") index += 1 append_them_all(index-1,anime_directory,episode_name,chunks) def download_single_video(final_link,episode_link): global default_mode global no_interruption_mode series_name = "-".join(episode_link.split("/")[-1].split("-")[:-2]) episode_name = episode_link.split("/")[-1] program_path = os.path.dirname(os.path.realpath(__file__)) anime_directory = program_path + "/" + series_name + "/" + episode_name chunks = anime_directory + "/Chunks" if not os.path.exists(chunks): pathlib.Path(chunks).mkdir(parents=True, exist_ok=True) #default_mode = None else: if os.path.exists(chunks +"/quality.txt"): quality = chunks + "/quality.txt" quality_file = open(quality,"r") for _ in quality_file: quality = _.rstrip() default_mode = quality #NOTE if 1-6 like range are given and 1 file has been downloaded it will tip the default_mode to quality of 1 and further videos will be downloaded wih the same quality if not os.path.exists(anime_directory): pathlib.Path(anime_directory).mkdir(parents=True, exist_ok=True) if not (os.path.exists(anime_directory + "/" + episode_name + ".mp4") or os.path.exists(anime_directory + "/" + episode_name.split("-")[-1]+ ".mp4")): my_playlist = get_child_m3u8(get_playlist_m3u8(final_link)) #print(my_playlist) matched = False length = len(my_playlist) if length != 0: if default_mode == None: video_quality_selection(my_playlist,anime_directory,episode_name) else: for _ in my_playlist: if _[0] == default_mode: quality_file = open(chunks +"/quality.txt","w") quality_file.write(default_mode) quality_file.close() my_quality_video = provide_video_chunks(_[1]) if len(my_quality_video) ==0: my_quality_video = provide_video_chunks_new(_[1]) download_chunks(my_quality_video,anime_directory,episode_name) matched = True break if not matched: if no_interruption_mode: download_chunks(my_playlist[0][1],anime_directory,episode_name) else: default_mode = None print("Sorry, your default quality is unavailable for this video. So please select quality again.") video_quality_selection(my_playlist,anime_directory, episode_name) else: print("Sorry, the video you requested is currently not available! Will fix this problem soon!") #This problem is caused by the alternate hls10x site else: print(episode_name+" has already been downloaded!") def download_chunks(video_chunks,anime_directory, episode_name): #print(video_chunks) write_to_log_file("Video chunks for "+ episode_name+"\n","\n".join(video_chunks)) chunks = anime_directory + "/Chunks" index = 1 average_speed = math.inf global headers if not os.path.exists(chunks): pathlib.Path(chunks).mkdir(parents=True, exist_ok=True) print("Downloading "+episode_name+"...") length = len(video_chunks) file_count = len([name for name in os.listdir(chunks)]) #Code below had to be written to ensure that no incomeplete files exists. I resorted to it after requests.head().headers.get() failed. Code below fails to check the last file chunk. File count also counts the quality file if file_count >=2 and file_count <= length+1: #length + 1 because of the quality file os.remove(chunks+"/"+"chunk_"+str(file_count-1)+".mp4") for chunk in video_chunks: tries = 1 chunk_name = chunks+"/"+"chunk_"+str(index)+".mp4" while True: if not os.path.exists(chunk_name): chunk_file = open(chunk_name,"wb") try: begin_time = time.time() current_chunk = requests.get(chunk,headers=headers).content #print(current_chunk)#the headers for file request have been removed end_time = time.time() time_difference = end_time-begin_time chunk_file.write(current_chunk) chunk_file.close() size = os.path.getsize(chunk_name) average_speed = size/(1024*time_difference) break except: chunk_file.close() if tries <= 5: print("\nError on chunk "+str(index)+". Retrying.... Attempt:"+str(tries)) os.remove(chunk_name) tries += 1 else: print("Error on chunk "+str(index)+". " + str(tries-1) +" downloading attempt failed! Continuing download for another episode. Please redownload " + episode_name) #os.remove(chunk_name) return else: break percentage = int((index/length) * 100) #print(percentage,end="") #print("% complete.") print("\r%d%% complete. Average internet speed = %.2f KB/s" % (percentage,average_speed),end="") index += 1 append_them_all(length,anime_directory, episode_name,chunks) def append_them_all(length,anime_directory,episode_name, chunks): print("\nAppending Pieces together......") big_episode = anime_directory + "/" + episode_name + ".mp4" if len(big_episode) >= 250: big_episode = anime_directory + "/" + episode_name.split("-")[-1]+ ".mp4" big_file = open(big_episode,"wb") for i in range (1,length+1): chunk_name = chunks+"/"+"chunk_"+str(i)+".mp4" chunk_file = open(chunk_name,"rb") big_file.write(chunk_file.read()) chunk_file.close() os.remove(chunk_name) big_file.close() print("Done appending. "+episode_name+" has been successfully downloaded!") print("\n") def download_command_line(): global no_interruption_mode global interruption_response global anime_name_response global selection_response global choice_response repeat = open("repeat.txt","w") if interruption_response == None: interruption = input("Do you want to turn no interruption mode on? Type y/n:") else: interruption = interruption_response repeat.write(interruption+"\n") if interruption == "y": no_interruption_mode = True while True: os.system("cls") print("NOTE: IF YOU WANT TO SKIP ANY TYPING OR QUESTION JUST PRESS \"ENTER\" KEY.\nBUT DONOT PRESS ENTER FOR THIS FIRST QUESTION!\n") if anime_name_response == None: anime_name = input("Please enter the anime name (example:one-piece). Mind the dash(-) sign:") else: anime_name = anime_name_response match_dict=[] f=open("all_animes.txt","r") found = False for line in f: if anime_name in line: match_dict.append(line) found = True f.close() if found: try: repeat.write(anime_name+"\n") except: pass for i in range(len(match_dict)): print(str(i+1) + "--->" + match_dict[i]) while True: if selection_response == None: selection = input("Please select your option among the SEARCHED RESULTS:") else: selection = selection_response if selection.isnumeric(): selection = int(selection)-1 if selection > len(match_dict)-1 or selection < 0: resp = input("Your selection is not available! Make reselection? Type y/n:") if resp != "y": break else: try: repeat.write(str(selection+1)+"\n") except: pass num = str(num_of_episodes(match_dict[selection])) while True: if choice_response == None: choice = input("There are " + num + " episodes for "+ match_dict[selection] +"Type single number eg: 1 or 2 to download single episode, '1-5' to download range, 'A' or 'a' to download all episodes:") else: choice = choice_response interruption_response = None anime_name_response = None selection_response = None choice_response = None if choice.isnumeric(): choice = int(choice) if choice > int(num) or choice < 1: print("Sorry, the episode you requested is not available yet!") resp = input("Want to download another episode? Type y/n:") if resp != "y": break else: try: repeat.write(str(choice)+"\n") repeat.close() except: pass while True: if choice > int(num): print("Sorry, we are now out of episodes!") break my_episode = get_single_episode(match_dict[selection].rstrip(),choice) my_link = write_to_file(my_episode[0]) final_link = my_link.split("//")[-1] final_link = "https://"+final_link #print(final_link) write_to_log_file("Link to episode:\n",final_link) my_m3u8 = get_playlist_m3u8(final_link) #print(my_m3u8) write_to_log_file("M3U8 for episode:\n",my_m3u8) if re.match("https://hls\d\dx",my_m3u8): try: download_in_a_different_way(my_episode[0]) except: print(my_episode[0] + " couldn't be download due to some errors. Please considering redownloading it.") else: download_single_video(final_link,my_episode[0]) #webbrowser.open_new(final_link) resp = input("Want to download next episode? Type y/n:") if resp != 'y': break else: choice += 1 elif re.match("^\d+-\d+$",choice): #don't miss the ^ and $ to exact match try: repeat.write(str(choice)+"\n") repeat.close() except: pass begin = int(choice.split("-")[0]) end = int(choice.split("-")[1]) for i in range(begin,end+1): my_episode = get_single_episode(match_dict[selection].rstrip(),i) my_link = write_to_file(my_episode[0]) final_link = my_link.split("//")[-1] final_link = "https://"+final_link write_to_log_file("M3U8 for episode:\n",final_link) my_m3u8 = get_playlist_m3u8(final_link) #print(final_link) write_to_log_file("M3U8 for episode:\n",my_m3u8) if re.match("https://hls\d\dx",my_m3u8): try: download_in_a_different_way(my_episode[0]) except: print(my_episode[0] + " couldn't be download due to some errors. Please considering redownloading it.") else: download_single_video(final_link,my_episode[0]) elif choice == "A" or choice == "a": try: repeat.write(str(choice)+"\n") repeat.close() except: pass episodes_num = num_of_episodes(match_dict[selection].rstrip()) for i in range(1,episodes_num+1): my_episode = get_single_episode(match_dict[selection].rstrip(),i) my_link = write_to_file(my_episode[0]) final_link = my_link.split("//")[-1] final_link = "https://"+final_link #print(final_link) write_to_log_file("M3U8 for episode:\n",final_link) my_m3u8 = get_playlist_m3u8(final_link) write_to_log_file("M3U8 for episode:\n",my_m3u8) if re.match("https://hls\d\dx",my_m3u8): try: download_in_a_different_way(my_episode[0]) except: print(my_episode[0] + " couldn't be download due to some errors. Please considering redownloading it.") else: download_single_video(final_link,my_episode[0]) else: resp=input("Invalid option input. Reinput? Type y/n:") if resp != "y": break else: resp=input("Invalid option input. Reinput? Type y/n:") if resp != "y": break else: print("No match found! Try researching for shorter string") retry = input("Research for another anime? y/n:") if retry != "y": break if __name__ == "__main__": download_command_line()
from tree import * import pathlib import sys import time import math no_interruption_mode = False interruption_response = None anime_name_response = None selection_response = None choice_response = None if len(sys.argv) == 2: #First argument is file name lines = [] if os.path.exists("repeat.txt"): if sys.argv[1] == "-r": repeat = open("repeat.txt","r") for line in repeat: lines.append(line.rstrip()) if len(lines)>=4: interruption_response = lines[0] anime_name_response = lines[1] selection_response = lines[2] choice_response = lines[3] repeat.close() def video_quality_selection(my_playlist,anime_directory,episode_name): #This function prompts the user to select quality global default_mode chunks = anime_directory + "/Chunks" index = 1 length = len(my_playlist) print("Video qualities available for "+ episode_name) for _ in my_playlist: print(str(index) + "----->"+ _[0]) index += 1 while True: resp = input("Choose the quality of video:") if resp.isnumeric() and int(resp) <= length and int(resp) >= 1: my_quality_video = provide_video_chunks(my_playlist[int(resp)-1][1]) if len(my_quality_video) == 0: my_quality_video = provide_video_chunks_new(my_playlist[int(resp)-1][1]) ans = input("Do you want to keep it as default quality for the next videos? Type y/n:") quality_file = open(chunks +"/quality.txt","w") quality_file.write(my_playlist[int(resp)-1][0]) quality_file.close() if ans == "y": default_mode = my_playlist[int(resp)-1][0] download_chunks(my_quality_video,anime_directory,episode_name) break else: resp = input("Bad quality!!!!!! Re-enter quality y/n?") if resp != "y": break def download_in_a_different_way(episode_link): global headers series_name = "-".join(episode_link.split("/")[-1].split("-")[:-2]) episode_name = episode_link.split("/")[-1] program_path = os.path.dirname(os.path.realpath(__file__)) anime_directory = program_path + "/" + series_name + "/" + episode_name chunks = anime_directory + "/Chunks" if os.path.exists(anime_directory + "/" +episode_name+".mp4"): print(episode_name+" has already been downloaded") return if not os.path.exists(chunks): pathlib.Path(chunks).mkdir(parents=True, exist_ok=True) vid_stream_link = BeautifulSoup(requests.get(episode_link).text,"html.parser").findAll("a",{"href":re.compile(r"https://vidstreaming.io/download.*")})[0].get("href") #print(vid_stream_link) write_to_log_file("Video stream link from download in different way:\n",vid_stream_link) download_link = BeautifulSoup(requests.get(vid_stream_link).text,"html.parser").findAll("a",{"href":re.compile(r"https://st\dx.cdnfile.info.*")})[0].get("href") #print(download_link) write_to_log_file("Download link for episode " +episode_link +":\n",download_link) #size = requests.head(download_link).headers.get("Content-length") The headers couldn't be retrieved so I had to comment this out #print(size) #write_to_log_file("Size of episode:\n",size) files = requests.get(download_link,headers = headers,stream=True) files.raise_for_status index = 1 print("Downloading "+episode_link) time_prev = time.time() standard_size = 1048576 file_pieces = files.iter_content(chunk_size = standard_size) for piece in files.iter_content(chunk_size = standard_size): chunk_name = chunks+"/"+"chunk_"+str(index)+".mp4" chunk_file = open(chunk_name,"wb") chunk_file.write(piece) chunk_file.close() time_new = time.time() time_difference = time_new-time_prev time_prev = time_new #percentage = int(index*standard_size/int(size)*100) #if percentage >= 100: # percentage = 100 average_speed = (standard_size)/(1024*time_difference) print(str(index)+" chunks downloaded. Average internet speed = %.2f KB/s" % (average_speed),end="") index += 1 append_them_all(index-1,anime_directory,episode_name,chunks) def download_single_video(final_link,episode_link): global default_mode global no_interruption_mode series_name = "-".join(episode_link.split("/")[-1].split("-")[:-2]) episode_name = episode_link.split("/")[-1] program_path = os.path.dirname(os.path.realpath(__file__)) anime_directory = program_path + "/" + series_name + "/" + episode_name chunks = anime_directory + "/Chunks" if not os.path.exists(chunks): pathlib.Path(chunks).mkdir(parents=True, exist_ok=True) #default_mode = None else: if os.path.exists(chunks +"/quality.txt"): quality = chunks + "/quality.txt" quality_file = open(quality,"r") for _ in quality_file: quality = _.rstrip() default_mode = quality #NOTE if 1-6 like range are given and 1 file has been downloaded it will tip the default_mode to quality of 1 and further videos will be downloaded wih the same quality if not os.path.exists(anime_directory): pathlib.Path(anime_directory).mkdir(parents=True, exist_ok=True) if not (os.path.exists(anime_directory + "/" + episode_name + ".mp4") or os.path.exists(anime_directory + "/" + episode_name.split("-")[-1]+ ".mp4")): my_playlist = get_child_m3u8(get_playlist_m3u8(final_link)) #print(my_playlist) matched = False length = len(my_playlist) if length != 0: if default_mode == None: video_quality_selection(my_playlist,anime_directory,episode_name) else: for _ in my_playlist: if _[0] == default_mode: quality_file = open(chunks +"/quality.txt","w") quality_file.write(default_mode) quality_file.close() my_quality_video = provide_video_chunks(_[1]) if len(my_quality_video) ==0: my_quality_video = provide_video_chunks_new(_[1]) download_chunks(my_quality_video,anime_directory,episode_name) matched = True break if not matched: if no_interruption_mode: download_chunks(my_playlist[0][1],anime_directory,episode_name) else: default_mode = None print("Sorry, your default quality is unavailable for this video. So please select quality again.") video_quality_selection(my_playlist,anime_directory, episode_name) else: print("Sorry, the video you requested is currently not available! Will fix this problem soon!") #This problem is caused by the alternate hls10x site else: print(episode_name+" has already been downloaded!") def download_chunks(video_chunks,anime_directory, episode_name): #print(video_chunks) write_to_log_file("Video chunks for "+ episode_name+"\n","\n".join(video_chunks)) chunks = anime_directory + "/Chunks" index = 1 average_speed = math.inf global headers if not os.path.exists(chunks): pathlib.Path(chunks).mkdir(parents=True, exist_ok=True) print("Downloading "+episode_name+"...") length = len(video_chunks) file_count = len([name for name in os.listdir(chunks)]) #Code below had to be written to ensure that no incomeplete files exists. I resorted to it after requests.head().headers.get() failed. Code below fails to check the last file chunk. File count also counts the quality file if file_count >=2 and file_count <= length+1: #length + 1 because of the quality file os.remove(chunks+"/"+"chunk_"+str(file_count-1)+".mp4") for chunk in video_chunks: tries = 1 chunk_name = chunks+"/"+"chunk_"+str(index)+".mp4" while True: if not os.path.exists(chunk_name): chunk_file = open(chunk_name,"wb") try: begin_time = time.time() current_chunk = requests.get(chunk,headers=headers).content #print(current_chunk)#the headers for file request have been removed end_time = time.time() time_difference = end_time-begin_time chunk_file.write(current_chunk) chunk_file.close() size = os.path.getsize(chunk_name) average_speed = size/(1024*time_difference) break except: chunk_file.close() if tries <= 5: print("\nError on chunk "+str(index)+". Retrying.... Attempt:"+str(tries)) os.remove(chunk_name) tries += 1 else: print("Error on chunk "+str(index)+". " + str(tries-1) +" downloading attempt failed! Continuing download for another episode. Please redownload " + episode_name) #os.remove(chunk_name) return else: break percentage = int((index/length) * 100) #print(percentage,end="") #print("% complete.") print("\r%d%% complete. Average internet speed = %.2f KB/s" % (percentage,average_speed),end="") index += 1 append_them_all(length,anime_directory, episode_name,chunks) def append_them_all(length,anime_directory,episode_name, chunks): print("\nAppending Pieces together......") big_episode = anime_directory + "/" + episode_name + ".mp4" if len(big_episode) >= 250: big_episode = anime_directory + "/" + episode_name.split("-")[-1]+ ".mp4" big_file = open(big_episode,"wb") for i in range (1,length+1): chunk_name = chunks+"/"+"chunk_"+str(i)+".mp4" chunk_file = open(chunk_name,"rb") big_file.write(chunk_file.read()) chunk_file.close() os.remove(chunk_name) big_file.close() print("Done appending. "+episode_name+" has been successfully downloaded!") print("\n") def download_command_line(): global no_interruption_mode global interruption_response global anime_name_response global selection_response global choice_response repeat = open("repeat.txt","w") if interruption_response == None: interruption = input("Do you want to turn no interruption mode on? Type y/n:") else: interruption = interruption_response repeat.write(interruption+"\n") if interruption == "y": no_interruption_mode = True while True: os.system("cls") print("NOTE: IF YOU WANT TO SKIP ANY TYPING OR QUESTION JUST PRESS \"ENTER\" KEY.\nBUT DONOT PRESS ENTER FOR THIS FIRST QUESTION!\n") if anime_name_response == None: anime_name = input("Please enter the anime name (example:one-piece). Mind the dash(-) sign:") else: anime_name = anime_name_response match_dict=[] f=open("all_animes.txt","r") found = False for line in f: if anime_name in line: match_dict.append(line) found = True f.close() if found: try: repeat.write(anime_name+"\n") except: pass for i in range(len(match_dict)): print(str(i+1) + "--->" + match_dict[i]) while True: if selection_response == None: selection = input("Please select your option among the SEARCHED RESULTS:") else: selection = selection_response if selection.isnumeric(): selection = int(selection)-1 if selection > len(match_dict)-1 or selection < 0: resp = input("Your selection is not available! Make reselection? Type y/n:") if resp != "y": break else: try: repeat.write(str(selection+1)+"\n") except: pass num = str(num_of_episodes(match_dict[selection])) while True: if choice_response == None: choice = input("There are " + num + " episodes for "+ match_dict[selection] +"Type single number eg: 1 or 2 to download single episode, '1-5' to download range, 'A' or 'a' to download all episodes:") else: choice = choice_response interruption_response = None anime_name_response = None selection_response = None choice_response = None if choice.isnumeric(): choice = int(choice) if choice > int(num) or choice < 1: print("Sorry, the episode you requested is not available yet!") resp = input("Want to download another episode? Type y/n:") if resp != "y": break else: try: repeat.write(str(choice)+"\n") repeat.close() except: pass while True: if choice > int(num): print("Sorry, we are now out of episodes!") break my_episode = get_single_episode(match_dict[selection].rstrip(),choice) my_link = write_to_file(my_episode[0]) final_link = my_link.split("//")[-1] final_link = "https://"+final_link #print(final_link) write_to_log_file("Link to episode:\n",final_link) my_m3u8 = get_playlist_m3u8(final_link) #print(my_m3u8) write_to_log_file("M3U8 for episode:\n",my_m3u8) if re.match("https://hls\d\dx",my_m3u8): try: download_in_a_different_way(my_episode[0]) except: print(my_episode[0] + " couldn't be download due to some errors. Please considering redownloading it.") else: download_single_video(final_link,my_episode[0]) #webbrowser.open_new(final_link) resp = input("Want to download next episode? Type y/n:") if resp != 'y': break else: choice += 1 elif re.match("^\d+-\d+$",choice): #don't miss the ^ and $ to exact match try: repeat.write(str(choice)+"\n") repeat.close() except: pass begin = int(choice.split("-")[0]) end = int(choice.split("-")[1]) for i in range(begin,end+1): my_episode = get_single_episode(match_dict[selection].rstrip(),i) my_link = write_to_file(my_episode[0]) final_link = my_link.split("//")[-1] final_link = "https://"+final_link write_to_log_file("M3U8 for episode:\n",final_link) my_m3u8 = get_playlist_m3u8(final_link) #print(final_link) write_to_log_file("M3U8 for episode:\n",my_m3u8) if re.match("https://hls\d\dx",my_m3u8): try: download_in_a_different_way(my_episode[0]) except: print(my_episode[0] + " couldn't be download due to some errors. Please considering redownloading it.") else: download_single_video(final_link,my_episode[0]) elif choice == "A" or choice == "a": try: repeat.write(str(choice)+"\n") repeat.close() except: pass episodes_num = num_of_episodes(match_dict[selection].rstrip()) for i in range(1,episodes_num+1): my_episode = get_single_episode(match_dict[selection].rstrip(),i) my_link = write_to_file(my_episode[0]) final_link = my_link.split("//")[-1] final_link = "https://"+final_link #print(final_link) write_to_log_file("M3U8 for episode:\n",final_link) my_m3u8 = get_playlist_m3u8(final_link) write_to_log_file("M3U8 for episode:\n",my_m3u8) if re.match("https://hls\d\dx",my_m3u8): try: download_in_a_different_way(my_episode[0]) except: print(my_episode[0] + " couldn't be download due to some errors. Please considering redownloading it.") else: download_single_video(final_link,my_episode[0]) else: resp=input("Invalid option input. Reinput? Type y/n:") if resp != "y": break else: resp=input("Invalid option input. Reinput? Type y/n:") if resp != "y": break else: print("No match found! Try researching for shorter string") retry = input("Research for another anime? y/n:") if retry != "y": break if __name__ == "__main__": download_command_line()
en
0.768484
#First argument is file name #This function prompts the user to select quality #print(vid_stream_link) #print(download_link) #size = requests.head(download_link).headers.get("Content-length") The headers couldn't be retrieved so I had to comment this out #print(size) #write_to_log_file("Size of episode:\n",size) #percentage = int(index*standard_size/int(size)*100) #if percentage >= 100: # percentage = 100 #default_mode = None #NOTE if 1-6 like range are given and 1 file has been downloaded it will tip the default_mode to quality of 1 and further videos will be downloaded wih the same quality #print(my_playlist) #This problem is caused by the alternate hls10x site #print(video_chunks) #Code below had to be written to ensure that no incomeplete files exists. I resorted to it after requests.head().headers.get() failed. Code below fails to check the last file chunk. File count also counts the quality file #length + 1 because of the quality file #print(current_chunk)#the headers for file request have been removed #os.remove(chunk_name) #print(percentage,end="") #print("% complete.") #print(final_link) #print(my_m3u8) #webbrowser.open_new(final_link) #don't miss the ^ and $ to exact match #print(final_link) #print(final_link)
3.266046
3
utils.py
sgtlaggy/lagbot
3
6624261
<reponame>sgtlaggy/lagbot import os UPPER_PATH = os.path.split(os.path.abspath(__file__))[0] def rzip(*iterables): """Like builtin `zip`, but uses the right end of longer iterables instead of the left. Examples: rzip([1,2,3], [4,5]) -> ((2, 4), (3, 5)) """ lens = [len(it) for it in iterables] min_len = min(lens) diffs = [len_ - min_len for len_ in lens] return tuple(tuple(it[i + diffs[diff_ind]] for diff_ind, it in enumerate(iterables)) for i in range(min_len)) def pluralize(singular, plural, n, fmt='{n} {s}'): """Similar to `gettext.ngettext`, but returns a string including the number. `fmt` is an optional format string with fields `{n}` and `{s}` being replaced by the number and singular or plural string, respectively. Examples: pluralize('dog', 'dogs', 1) -> '1 dog' pluralize('dog', 'dogs', 3) -> '3 dogs' pluralize('dog', 'dogs', 3, '{n} ... {s}') -> 'dogs ... 3' """ if n == 1: return fmt.format(n=n, s=singular) else: return fmt.format(n=n, s=plural) def tb_args(exc): """Easily format arguments for `traceback` functions.""" return (type(exc), exc, exc.__traceback__) def commaize(seq): seq = tuple(seq) length = len(seq) if length == 0: return '' if length == 1: return seq[0] elif length == 2: return ' and '.join(seq) else: return ', and '.join([', '.join(seq[:-1]), seq[-1]]) def clamp(value, low=None, high=None): if low is not None and value < low: value = low elif high is not None and value > high: value = high return value
import os UPPER_PATH = os.path.split(os.path.abspath(__file__))[0] def rzip(*iterables): """Like builtin `zip`, but uses the right end of longer iterables instead of the left. Examples: rzip([1,2,3], [4,5]) -> ((2, 4), (3, 5)) """ lens = [len(it) for it in iterables] min_len = min(lens) diffs = [len_ - min_len for len_ in lens] return tuple(tuple(it[i + diffs[diff_ind]] for diff_ind, it in enumerate(iterables)) for i in range(min_len)) def pluralize(singular, plural, n, fmt='{n} {s}'): """Similar to `gettext.ngettext`, but returns a string including the number. `fmt` is an optional format string with fields `{n}` and `{s}` being replaced by the number and singular or plural string, respectively. Examples: pluralize('dog', 'dogs', 1) -> '1 dog' pluralize('dog', 'dogs', 3) -> '3 dogs' pluralize('dog', 'dogs', 3, '{n} ... {s}') -> 'dogs ... 3' """ if n == 1: return fmt.format(n=n, s=singular) else: return fmt.format(n=n, s=plural) def tb_args(exc): """Easily format arguments for `traceback` functions.""" return (type(exc), exc, exc.__traceback__) def commaize(seq): seq = tuple(seq) length = len(seq) if length == 0: return '' if length == 1: return seq[0] elif length == 2: return ' and '.join(seq) else: return ', and '.join([', '.join(seq[:-1]), seq[-1]]) def clamp(value, low=None, high=None): if low is not None and value < low: value = low elif high is not None and value > high: value = high return value
en
0.67431
Like builtin `zip`, but uses the right end of longer iterables instead of the left. Examples: rzip([1,2,3], [4,5]) -> ((2, 4), (3, 5)) Similar to `gettext.ngettext`, but returns a string including the number. `fmt` is an optional format string with fields `{n}` and `{s}` being replaced by the number and singular or plural string, respectively. Examples: pluralize('dog', 'dogs', 1) -> '1 dog' pluralize('dog', 'dogs', 3) -> '3 dogs' pluralize('dog', 'dogs', 3, '{n} ... {s}') -> 'dogs ... 3' Easily format arguments for `traceback` functions.
3.647791
4
Curso_de_Python_ Curso_em_Video/PythonExercicios/ex107a112/utilidades/dados/__init__.py
DanilooSilva/Cursos_de_Python
0
6624262
<gh_stars>0 def leiaDienheiro(msg): while True: leia = str(input(msg)) if leia.replace(',', '').replace('.', '').isdigit(): valor = leia.replace(',', '.') return float(valor) break else: print(f'\033[031mERRO! \'{leia}\' é um preço inválido!\033[m')
def leiaDienheiro(msg): while True: leia = str(input(msg)) if leia.replace(',', '').replace('.', '').isdigit(): valor = leia.replace(',', '.') return float(valor) break else: print(f'\033[031mERRO! \'{leia}\' é um preço inválido!\033[m')
none
1
3.47558
3
test_arm_ric/test_by_phone.py
OlesyaF/basic_tests_zvs
0
6624263
# -*- encoding: utf-8 -*- import time import allure # Проверка изменения информации о Горячей линии РИЦ на вкладке По телефону @allure.title("Проверка изменения информации о Горячей линии РИЦ на вкладке По телефону") def test_change_hotline_info(app): print("test_change_hotline_info.py is running") num = str(app.calc_check_sum_from_date()) hotline_info = "RIC autotest contact info (part 1) " + num app.go_to_arm_ric() app.login_agent() time.sleep(7) app.go_to_by_phone() time.sleep(2) app.change_ric_info(hotline_info) app.go_to_by_phone() hotline_info_form = app.get_hotline_info_arm_ric() print("Информация о Горячей линии РИЦ, отображающаяся на вкладке По телефону:", hotline_info_form) print("Новая информация о Горячей линии РИЦ:", hotline_info) if (hotline_info_form == hotline_info): print("Измененная информация о Горячей линии РИЦ корректно отображается на вкладке По телефону") else: print("ОШИБКА!!! Измененная информации о Горячей линии РИЦ не корректно отображается на вкладке По телефону!") assert (hotline_info_form == hotline_info) app.logout_agent() print("test_change_hotline_info.py is done successfully")
# -*- encoding: utf-8 -*- import time import allure # Проверка изменения информации о Горячей линии РИЦ на вкладке По телефону @allure.title("Проверка изменения информации о Горячей линии РИЦ на вкладке По телефону") def test_change_hotline_info(app): print("test_change_hotline_info.py is running") num = str(app.calc_check_sum_from_date()) hotline_info = "RIC autotest contact info (part 1) " + num app.go_to_arm_ric() app.login_agent() time.sleep(7) app.go_to_by_phone() time.sleep(2) app.change_ric_info(hotline_info) app.go_to_by_phone() hotline_info_form = app.get_hotline_info_arm_ric() print("Информация о Горячей линии РИЦ, отображающаяся на вкладке По телефону:", hotline_info_form) print("Новая информация о Горячей линии РИЦ:", hotline_info) if (hotline_info_form == hotline_info): print("Измененная информация о Горячей линии РИЦ корректно отображается на вкладке По телефону") else: print("ОШИБКА!!! Измененная информации о Горячей линии РИЦ не корректно отображается на вкладке По телефону!") assert (hotline_info_form == hotline_info) app.logout_agent() print("test_change_hotline_info.py is done successfully")
ru
0.899669
# -*- encoding: utf-8 -*- # Проверка изменения информации о Горячей линии РИЦ на вкладке По телефону
2.43538
2
pyrez/models/BaseMatchDetail.py
CLeendert/Pyrez
25
6624264
from .MatchBase import MatchBase class BaseMatchDetail(MatchBase): def __init__(self, **kwargs): super().__init__(**kwargs) self.damageBot = kwargs.get("Damage_Bot", 0) or 0 self.damageDoneInHand = kwargs.get("Damage_Done_In_Hand", 0) or 0 self.damageDoneMagical = kwargs.get("Damage_Done_Magical", 0) or 0 self.damageDonePhysical = kwargs.get("Damage_Done_Physical", 0) or 0 self.damageMitigated = kwargs.get("Damage_Mitigated", 0) or 0 self.damageStructure = kwargs.get("Damage_Structure", 0) or 0 self.damageTaken = kwargs.get("Damage_Taken", 0) or 0 self.damageTakenMagical = kwargs.get("Damage_Taken_Magical", 0) or 0 self.damageTakenPhysical = kwargs.get("Damage_Taken_Physical", 0) or 0 self.deaths = kwargs.get("Deaths", 0) or 0 self.distanceTraveled = kwargs.get("Distance_Traveled", 0) or 0 self.healing = kwargs.get("Healing", 0) or 0 self.healingBot = kwargs.get("Healing_Bot", 0) or 0 self.healingPlayerSelf = kwargs.get("Healing_Player_Self", 0) or 0 self.killingSpree = kwargs.get("Killing_Spree", 0) or 0 self.mapName = kwargs.get("Map_Game", '') or '' self.matchMinutes = kwargs.get("Minutes", 0) or 0 self.matchRegion = kwargs.get("Region", '') or '' self.matchTimeSecond = kwargs.get("Time_In_Match_Seconds", 0) or 0 self.multiKillMax = kwargs.get("Multi_kill_Max", 0) or 0 self.objectiveAssists = kwargs.get("Objective_Assists", 0) or 0 self.playerName = kwargs.get("playerName", '') or '' self.surrendered = kwargs.get("Surrendered", '') or '' self.team1Score = kwargs.get("Team1Score", 0) or 0 self.team2Score = kwargs.get("Team2Score", 0) or 0 self.wardsPlaced = kwargs.get("Wards_Placed", 0) or 0 self.winStatus = kwargs.get("Win_Status", '') or '' self.winningTaskForce = kwargs.get("Winning_TaskForce", 0) or 0
from .MatchBase import MatchBase class BaseMatchDetail(MatchBase): def __init__(self, **kwargs): super().__init__(**kwargs) self.damageBot = kwargs.get("Damage_Bot", 0) or 0 self.damageDoneInHand = kwargs.get("Damage_Done_In_Hand", 0) or 0 self.damageDoneMagical = kwargs.get("Damage_Done_Magical", 0) or 0 self.damageDonePhysical = kwargs.get("Damage_Done_Physical", 0) or 0 self.damageMitigated = kwargs.get("Damage_Mitigated", 0) or 0 self.damageStructure = kwargs.get("Damage_Structure", 0) or 0 self.damageTaken = kwargs.get("Damage_Taken", 0) or 0 self.damageTakenMagical = kwargs.get("Damage_Taken_Magical", 0) or 0 self.damageTakenPhysical = kwargs.get("Damage_Taken_Physical", 0) or 0 self.deaths = kwargs.get("Deaths", 0) or 0 self.distanceTraveled = kwargs.get("Distance_Traveled", 0) or 0 self.healing = kwargs.get("Healing", 0) or 0 self.healingBot = kwargs.get("Healing_Bot", 0) or 0 self.healingPlayerSelf = kwargs.get("Healing_Player_Self", 0) or 0 self.killingSpree = kwargs.get("Killing_Spree", 0) or 0 self.mapName = kwargs.get("Map_Game", '') or '' self.matchMinutes = kwargs.get("Minutes", 0) or 0 self.matchRegion = kwargs.get("Region", '') or '' self.matchTimeSecond = kwargs.get("Time_In_Match_Seconds", 0) or 0 self.multiKillMax = kwargs.get("Multi_kill_Max", 0) or 0 self.objectiveAssists = kwargs.get("Objective_Assists", 0) or 0 self.playerName = kwargs.get("playerName", '') or '' self.surrendered = kwargs.get("Surrendered", '') or '' self.team1Score = kwargs.get("Team1Score", 0) or 0 self.team2Score = kwargs.get("Team2Score", 0) or 0 self.wardsPlaced = kwargs.get("Wards_Placed", 0) or 0 self.winStatus = kwargs.get("Win_Status", '') or '' self.winningTaskForce = kwargs.get("Winning_TaskForce", 0) or 0
none
1
2.232028
2
class 2708/exercise1.py
Gabriel-Fernandes1917/lab-the-python
0
6624265
<reponame>Gabriel-Fernandes1917/lab-the-python dictionary ={None:None} loop = "sim" while(loop == "sim"): dictionary[0]=input('informe o nome\n') dictionary[1]=input('informe o cpf\n') loop = input('deseja continuar ?') print(dictionary)
dictionary ={None:None} loop = "sim" while(loop == "sim"): dictionary[0]=input('informe o nome\n') dictionary[1]=input('informe o cpf\n') loop = input('deseja continuar ?') print(dictionary)
none
1
3.865597
4
iqmon/pipelines/ingest.py
joshwalawender/IQMon
9
6624266
<filename>iqmon/pipelines/ingest.py from keckdrpframework.pipelines.base_pipeline import BasePipeline from keckdrpframework.models.processing_context import ProcessingContext # MODIFY THIS IMPORT to reflect the name of the module created in the primitives directory from iqmon.primitives.file_handling import (ReadFITS, PopulateAdditionalMetaData, CopyFile, DeleteOriginal) from iqmon.primitives.database import RecordFile class IngestPipeline(BasePipeline): """ This pipeline ingests files from their raw location on disk and rewrites them to the destination directory with a checksum. It then (if spcified) deletes the original file. Finally, some basic image information and statistics are recorded to the mongo database. This is meant to be a very quick sequence which moves the file and records the file's existence to the database. """ event_table = { "next_file": ("ReadFITS", "reading_file", "populate_metadata"), "populate_metadata": ("PopulateAdditionalMetaData", "populating_metadata", "copy_file"), "copy_file": ("CopyFile", "copying_file", "delete_original"), "delete_original": ("DeleteOriginal", "deleting_original", "record_file"), "record_file": ("RecordFile", "recording", None), } def __init__(self, context: ProcessingContext): BasePipeline.__init__(self, context)
<filename>iqmon/pipelines/ingest.py from keckdrpframework.pipelines.base_pipeline import BasePipeline from keckdrpframework.models.processing_context import ProcessingContext # MODIFY THIS IMPORT to reflect the name of the module created in the primitives directory from iqmon.primitives.file_handling import (ReadFITS, PopulateAdditionalMetaData, CopyFile, DeleteOriginal) from iqmon.primitives.database import RecordFile class IngestPipeline(BasePipeline): """ This pipeline ingests files from their raw location on disk and rewrites them to the destination directory with a checksum. It then (if spcified) deletes the original file. Finally, some basic image information and statistics are recorded to the mongo database. This is meant to be a very quick sequence which moves the file and records the file's existence to the database. """ event_table = { "next_file": ("ReadFITS", "reading_file", "populate_metadata"), "populate_metadata": ("PopulateAdditionalMetaData", "populating_metadata", "copy_file"), "copy_file": ("CopyFile", "copying_file", "delete_original"), "delete_original": ("DeleteOriginal", "deleting_original", "record_file"), "record_file": ("RecordFile", "recording", None), } def __init__(self, context: ProcessingContext): BasePipeline.__init__(self, context)
en
0.928398
# MODIFY THIS IMPORT to reflect the name of the module created in the primitives directory This pipeline ingests files from their raw location on disk and rewrites them to the destination directory with a checksum. It then (if spcified) deletes the original file. Finally, some basic image information and statistics are recorded to the mongo database. This is meant to be a very quick sequence which moves the file and records the file's existence to the database.
2.200226
2
slybot/slybot/fieldtypes/images.py
hackrush01/portia
6,390
6624267
"""Images.""" from scrapely.extractors import extract_image_url from slybot.fieldtypes.url import UrlFieldTypeProcessor class ImagesFieldTypeProcessor(UrlFieldTypeProcessor): name = 'image' description = 'extracts image URLs' def extract(self, text): if text is not None: return extract_image_url(text) or '' return ''
"""Images.""" from scrapely.extractors import extract_image_url from slybot.fieldtypes.url import UrlFieldTypeProcessor class ImagesFieldTypeProcessor(UrlFieldTypeProcessor): name = 'image' description = 'extracts image URLs' def extract(self, text): if text is not None: return extract_image_url(text) or '' return ''
none
1
2.949233
3
test/uw_spot/spot_post.py
sbutler/spotseeker_server
0
6624268
<filename>test/uw_spot/spot_post.py<gh_stars>0 """ Copyright 2012, 2013 UW Information Technology, University of Washington Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.test import TransactionTestCase from django.conf import settings from django.test.client import Client from spotseeker_server.models import Spot import simplejson as json import random from django.test.utils import override_settings from mock import patch from django.core import cache from spotseeker_server import models @override_settings(SPOTSEEKER_AUTH_MODULE='spotseeker_server.auth.all_ok') @override_settings(SPOTSEEKER_SPOT_FORM='spotseeker_server.org_forms.uw_spot.UWSpotForm') @override_settings(SPOTSEEKER_SPOTEXTENDEDINFO_FORM='spotseeker_server.org_forms.uw_spot.UWSpotExtendedInfoForm') @override_settings(SPOTSEEKER_AUTH_ADMINS=('demo_user',)) class UWSpotPOSTTest(TransactionTestCase): """ Tests creating a new Spot via POST. """ def test_valid_json(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 json_string = '{"name":"%s","capacity":"%s","location":{"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"true","manager":"Bob","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") self.assertIn("Location", response, "The response has a location header") self.spot = Spot.objects.get(name=new_name) self.assertEquals(response["Location"], "http://testserver" + self.spot.rest_url(), "The uri for the new spot is correct") get_response = c.get(response["Location"]) self.assertEquals(get_response.status_code, 200, "OK in response to GETing the new spot") spot_json = json.loads(get_response.content) self.assertEquals(spot_json["name"], new_name, "The right name was stored") self.assertEquals(spot_json["capacity"], new_capacity, "The right capacity was stored") def test_non_json(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() response = c.post('/api/v1/spot/', 'just a string', content_type="application/json", follow=False) self.assertEquals(response.status_code, 400) def test_invalid_json(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() response = c.post('/api/v1/spot/', '{}', content_type="application/json", follow=False) self.assertEquals(response.status_code, 400) def test_uw_field_has_whiteboards(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 whiteboards = 12 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"%s","has_outlets":"true","manager":"John","organization":"UW"}}' % (new_name, new_capacity, whiteboards) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_whiteboards field did not pass validation") whiteboards = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"%s","has_outlets":"true","manager":"John","organization":"UW"}}' % (new_name, new_capacity, whiteboards) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_outlets(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 outlets = 12 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"false","manager":"Harry","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_outlets was not included") json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"false","has_outlets":"%s","manager":"Harry","organization":"UW"}}' % (new_name, new_capacity, outlets) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_outlets field did not pass validation") outlets = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"%s","manager":"Harry","organization":"UW"}}' % (new_name, new_capacity, outlets) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_printing(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 printer = 12 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_printing":"%s","manager":"Gary","organization":"UW"}}' % (new_name, new_capacity, printer) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_printing field did not pass validation") printer = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_printing":"%s","manager":"Gary","organization":"UW"}}' % (new_name, new_capacity, printer) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_scanner(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 scanner = 'There are none' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_scanner":"%s","manager":"Sally","organization":"UW"}}' % (new_name, new_capacity, scanner) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_scanner field did not pass validation") scanner = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_scanner":"%s","manager":"Sally","organization":"UW"}}' % (new_name, new_capacity, scanner) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_displays(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 has_displays = 'There are none' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_displays":"%s","manager":"Fred","organization":"UW"}}' % (new_name, new_capacity, has_displays) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_displays field did not pass validation") has_displays = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_displays":"%s","manager":"Fred","organization":"UW"}}' % (new_name, new_capacity, has_displays) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_projector(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 has_projector = 'There are none' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_projector":"%s","manager":"George","organization":"UW"}}' % (new_name, new_capacity, has_projector) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_projector field did not pass validation") has_projector = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_projector":"%s","manager":"George","organization":"UW"}}' % (new_name, new_capacity, has_projector) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_computers(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 computers = 'There are none' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_computers":"%s","manager":"Tina","organization":"UW"}}' % (new_name, new_capacity, computers) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_computers field did not pass validation") json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_computers":"true","manager":"Tina","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_num_computers(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 computers = "invalid_int" json_string = '{"name":"%s","capacity":"%s","location":{"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_computers":"true","num_computers":"%s","manager":"Tina","organization":"UW"}}' % (new_name, new_capacity, computers) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Make sure not to create the spot because num_computers field did not pass validation") json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_computers":"true","num_computers":"15","manager":"Tina","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_natural_light(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 has_natural_light = 'Nope!' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_natural_light":"%s","manager":"Mary","organization":"UW"}}' % (new_name, new_capacity, has_natural_light) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_natural_light field did not pass validation") has_natural_light = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_natural_light":"%s","manager":"Mary","organization":"UW"}}' % (new_name, new_capacity, has_natural_light) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_noise_level(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 noise_level = 'Rock Concert' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","noise_level":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, noise_level) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because noise_level field did not pass validation") noise_level = 'moderate' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","noise_level":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, noise_level) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_food_nearby(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 food_nearby = 'In the area' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","food_nearby":"%s","manager":"Kristy","organization":"UW"}}' % (new_name, new_capacity, food_nearby) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because food_nearby field did not pass validation") food_nearby = 'building' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","food_nearby":"%s","manager":"Kristy","organization":"UW"}}' % (new_name, new_capacity, food_nearby) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_reservable(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 reservable = 'You bet' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","reservable":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, reservable) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because reservable field did not pass validation") reservable = 'reservations' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","reservable":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, reservable) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_location_description(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 desc = 'This is a description' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude":-30},"extended_info":{"has_outlets":"true","location_description":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, desc) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") spot = Spot.objects.get(name=new_name) spot_desc = spot.spotextendedinfo_set.get(key='location_description').value self.assertEquals(desc, spot_desc, "The Spot's description matches what was POSTed.") def test_valid_json_but_invalid_extended_info(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude":-30},"extended_info":{"has_outlets":"true","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) bad_json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"wub wub wub wu wu wuhhhh WUB WUB WUBBBBUB","manager":"Sam","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', bad_json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Doesn't add spot info with invalid extended info") self.assertEquals(Spot.objects.count(), 2, "Doesn't POST spots with invalid extended info") def test_valid_json_but_no_extended_info(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude":-30}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) error_message = json.loads(response.content)['error'] self.assertEquals(error_message, "[u'UWSpot must have extended info']", "Doesn't add spot info with invalid extended info")
<filename>test/uw_spot/spot_post.py<gh_stars>0 """ Copyright 2012, 2013 UW Information Technology, University of Washington Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.test import TransactionTestCase from django.conf import settings from django.test.client import Client from spotseeker_server.models import Spot import simplejson as json import random from django.test.utils import override_settings from mock import patch from django.core import cache from spotseeker_server import models @override_settings(SPOTSEEKER_AUTH_MODULE='spotseeker_server.auth.all_ok') @override_settings(SPOTSEEKER_SPOT_FORM='spotseeker_server.org_forms.uw_spot.UWSpotForm') @override_settings(SPOTSEEKER_SPOTEXTENDEDINFO_FORM='spotseeker_server.org_forms.uw_spot.UWSpotExtendedInfoForm') @override_settings(SPOTSEEKER_AUTH_ADMINS=('demo_user',)) class UWSpotPOSTTest(TransactionTestCase): """ Tests creating a new Spot via POST. """ def test_valid_json(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 json_string = '{"name":"%s","capacity":"%s","location":{"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"true","manager":"Bob","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") self.assertIn("Location", response, "The response has a location header") self.spot = Spot.objects.get(name=new_name) self.assertEquals(response["Location"], "http://testserver" + self.spot.rest_url(), "The uri for the new spot is correct") get_response = c.get(response["Location"]) self.assertEquals(get_response.status_code, 200, "OK in response to GETing the new spot") spot_json = json.loads(get_response.content) self.assertEquals(spot_json["name"], new_name, "The right name was stored") self.assertEquals(spot_json["capacity"], new_capacity, "The right capacity was stored") def test_non_json(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() response = c.post('/api/v1/spot/', 'just a string', content_type="application/json", follow=False) self.assertEquals(response.status_code, 400) def test_invalid_json(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() response = c.post('/api/v1/spot/', '{}', content_type="application/json", follow=False) self.assertEquals(response.status_code, 400) def test_uw_field_has_whiteboards(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 whiteboards = 12 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"%s","has_outlets":"true","manager":"John","organization":"UW"}}' % (new_name, new_capacity, whiteboards) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_whiteboards field did not pass validation") whiteboards = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"%s","has_outlets":"true","manager":"John","organization":"UW"}}' % (new_name, new_capacity, whiteboards) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_outlets(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 outlets = 12 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"false","manager":"Harry","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_outlets was not included") json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"false","has_outlets":"%s","manager":"Harry","organization":"UW"}}' % (new_name, new_capacity, outlets) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_outlets field did not pass validation") outlets = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"%s","manager":"Harry","organization":"UW"}}' % (new_name, new_capacity, outlets) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_printing(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 printer = 12 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_printing":"%s","manager":"Gary","organization":"UW"}}' % (new_name, new_capacity, printer) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_printing field did not pass validation") printer = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_printing":"%s","manager":"Gary","organization":"UW"}}' % (new_name, new_capacity, printer) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_scanner(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 scanner = 'There are none' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_scanner":"%s","manager":"Sally","organization":"UW"}}' % (new_name, new_capacity, scanner) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_scanner field did not pass validation") scanner = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_scanner":"%s","manager":"Sally","organization":"UW"}}' % (new_name, new_capacity, scanner) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_displays(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 has_displays = 'There are none' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_displays":"%s","manager":"Fred","organization":"UW"}}' % (new_name, new_capacity, has_displays) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_displays field did not pass validation") has_displays = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_displays":"%s","manager":"Fred","organization":"UW"}}' % (new_name, new_capacity, has_displays) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_projector(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 has_projector = 'There are none' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_projector":"%s","manager":"George","organization":"UW"}}' % (new_name, new_capacity, has_projector) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_projector field did not pass validation") has_projector = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_projector":"%s","manager":"George","organization":"UW"}}' % (new_name, new_capacity, has_projector) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_computers(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 computers = 'There are none' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_computers":"%s","manager":"Tina","organization":"UW"}}' % (new_name, new_capacity, computers) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_computers field did not pass validation") json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_computers":"true","manager":"Tina","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_num_computers(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 computers = "invalid_int" json_string = '{"name":"%s","capacity":"%s","location":{"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_computers":"true","num_computers":"%s","manager":"Tina","organization":"UW"}}' % (new_name, new_capacity, computers) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Make sure not to create the spot because num_computers field did not pass validation") json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_computers":"true","num_computers":"15","manager":"Tina","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_has_natural_light(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 has_natural_light = 'Nope!' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_natural_light":"%s","manager":"Mary","organization":"UW"}}' % (new_name, new_capacity, has_natural_light) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because has_natural_light field did not pass validation") has_natural_light = 'true' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","has_natural_light":"%s","manager":"Mary","organization":"UW"}}' % (new_name, new_capacity, has_natural_light) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_noise_level(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 noise_level = 'Rock Concert' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","noise_level":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, noise_level) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because noise_level field did not pass validation") noise_level = 'moderate' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","noise_level":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, noise_level) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_food_nearby(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 food_nearby = 'In the area' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","food_nearby":"%s","manager":"Kristy","organization":"UW"}}' % (new_name, new_capacity, food_nearby) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because food_nearby field did not pass validation") food_nearby = 'building' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","food_nearby":"%s","manager":"Kristy","organization":"UW"}}' % (new_name, new_capacity, food_nearby) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_reservable(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 reservable = 'You bet' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","reservable":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, reservable) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Not created because reservable field did not pass validation") reservable = 'reservations' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_outlets":"true","reservable":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, reservable) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") def test_uw_field_location_description(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 desc = 'This is a description' json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude":-30},"extended_info":{"has_outlets":"true","location_description":"%s","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity, desc) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") spot = Spot.objects.get(name=new_name) spot_desc = spot.spotextendedinfo_set.get(key='location_description').value self.assertEquals(desc, spot_desc, "The Spot's description matches what was POSTed.") def test_valid_json_but_invalid_extended_info(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude":-30},"extended_info":{"has_outlets":"true","manager":"Patty","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 201, "Gives a Created response to creating a Spot") response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) bad_json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude": -30},"extended_info":{"has_whiteboards":"true","has_outlets":"wub wub wub wu wu wuhhhh WUB WUB WUBBBBUB","manager":"Sam","organization":"UW"}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', bad_json_string, content_type="application/json", follow=False) self.assertEquals(response.status_code, 400, "Doesn't add spot info with invalid extended info") self.assertEquals(Spot.objects.count(), 2, "Doesn't POST spots with invalid extended info") def test_valid_json_but_no_extended_info(self): dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache') with patch.object(models, 'cache', dummy_cache): c = Client() new_name = "testing POST name: {0}".format(random.random()) new_capacity = 10 json_string = '{"name":"%s","capacity":"%s","location": {"latitude": 55, "longitude":-30}}' % (new_name, new_capacity) response = c.post('/api/v1/spot/', json_string, content_type="application/json", follow=False) error_message = json.loads(response.content)['error'] self.assertEquals(error_message, "[u'UWSpot must have extended info']", "Doesn't add spot info with invalid extended info")
en
0.841316
Copyright 2012, 2013 UW Information Technology, University of Washington Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Tests creating a new Spot via POST.
1.961097
2
version_2.0/help_scripts/bot_logic/extension_functions_compiled.py
Isak-Landin/AlienWorldsBot
0
6624269
<filename>version_2.0/help_scripts/bot_logic/extension_functions_compiled.py<gh_stars>0 from selenium import webdriver import time import random import json from help_scripts import selenium_operator as sop import traceback from help_scripts import bot_actions from help_scripts import get_proxies from pathlib import Path from selenium.webdriver.common.keys import Keys def setup_extension(driver, window_id): driver = driver region = (window_id.topleft[0], window_id.topleft[1], window_id.width, window_id.height) parent_handle = driver.window_handles[0] driver = download_extension(driver=driver, window_id=window_id, region=region, parent_handle=parent_handle) configure_extension(driver=driver, window_id=window_id) driver = activate_profile(driver=driver) return driver def download_extension(driver, window_id, region, parent_handle): driver.get('https://chrome.google.com/webstore/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif') accept_cookies, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=25, _xpath='/html/body/c-wiz/div/div/div/div[2]/div[1]/div[4]/form/div/div/button' ) if succeeded is False: print('Failed to find accept_cookies') print(traceback.print_exc()) exit() accept_cookies.click() add_extension, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=7, _xpath='/html/body/div[3]/div[2]/div/div/div[2]/div[2]/div' ) time.sleep(2) if succeeded is False: add_extension, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=7, _xpath='/html/body/div[5]/div[2]/div/div/div[2]/div[2]/div' ) # /html/body/div[5]/div[2]/div/div/div[2]/div[2]/div if succeeded is False: print('Failed to find add_extension') print(traceback.print_exc()) exit() add_extension.click() window_id.minimize() time.sleep(0.2) window_id.restore() add_extension_region = bot_actions.VisualActions.find_image( image=str(Path().resolve()) + r'\alienworlds_program_data\images\add_extension.png', region=region, confidence=0.85 ) start_time = time.time() while add_extension_region is None: add_extension_region = bot_actions.VisualActions.find_image( image=str(Path().resolve()) + r'\alienworlds_program_data\images\add_extension.png', region=region, confidence=0.85 ) if time.time() - start_time > 12: exit('SHUTDOWN due to waiting too long for add_extension.png') add_extension_region_center = bot_actions.VisualActions.get_center(add_extension_region) bot_actions.VisualActions.move_to_click(coordinates=add_extension_region_center, duration=0.15) while len(driver.window_handles) < 2: time.sleep(0.2) print('Looking for new handle') for handle in driver.window_handles: if handle != parent_handle: driver.close() parent_handle = handle driver.switch_to.window(parent_handle) return driver def configure_extension(driver, window_id): skip_guide, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=15, _xpath='/html/body/div[4]/div/div/div[3]/button[1]' ) if succeeded is False: print('Failed to find skip_guide') exit('Failed to find skip_guide') sop.click_object(skip_guide) proxy_profile, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=15, _xpath='/html/body/div[1]/header/nav/li[7]/a' ) if succeeded is False: print('Failed to find proxy_profile') exit('Failed to find proxy_profile') sop.click_object(proxy_profile) server_ip, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=10, _xpath='/html/body/div[1]/main/div[2]/div/section[1]/div/table/tbody[1]/tr[1]/td[3]/input' ) if succeeded is False: print('Failed to find server_ip') exit('Failed to find server_ip') server_port, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=15, _xpath='/html/body/div[1]/main/div[2]/div/section[1]/div/table/tbody[1]/tr[1]/td[4]/input' ) if succeeded is False: print('Failed to find server_port') exit('Failed to find server_port') proxies = get_proxies.get_ten_and_check_online() random_index = random.randint(0, len(proxies) - 1) proxy_port = proxies.pop(random_index)[0] proxy = proxy_port.split(':')[0] port = proxy_port.split(':')[1] server_ip.clear() server_port.clear() server_ip.send_keys(proxy) server_port.send_keys(port) time.sleep(2) apply_changes, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=10, _xpath='/html/body/div[1]/header/nav/li[12]/a' ) if succeeded is False: print('Failed to find apply_changes') exit('Failed to find apply_changes') sop.click_object(apply_changes) def activate_profile(driver): time.sleep(3) driver.get('chrome-extension://padekgcemlokbadohgkifijomclgjgif/popup/index.html') old_handle = driver.window_handles[0] time.sleep(0.15) driver.execute_script('''window.open("http://www.blankwebsite.com/", "_blank");''') time.sleep(1) new_handle = None for handle in driver.window_handles: if handle != old_handle: new_handle = handle break time.sleep(2) proxy_profile, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=10, _xpath='//*[@id="js-profile-1"]' ) if succeeded is False: print('Failed to find your proxy_profile, please contact us or try again') exit('Failed to find your proxy_profile, please contact us or try again') sop.click_object(proxy_profile) time.sleep(2) driver.switch_to.window(new_handle) return driver
<filename>version_2.0/help_scripts/bot_logic/extension_functions_compiled.py<gh_stars>0 from selenium import webdriver import time import random import json from help_scripts import selenium_operator as sop import traceback from help_scripts import bot_actions from help_scripts import get_proxies from pathlib import Path from selenium.webdriver.common.keys import Keys def setup_extension(driver, window_id): driver = driver region = (window_id.topleft[0], window_id.topleft[1], window_id.width, window_id.height) parent_handle = driver.window_handles[0] driver = download_extension(driver=driver, window_id=window_id, region=region, parent_handle=parent_handle) configure_extension(driver=driver, window_id=window_id) driver = activate_profile(driver=driver) return driver def download_extension(driver, window_id, region, parent_handle): driver.get('https://chrome.google.com/webstore/detail/proxy-switchyomega/padekgcemlokbadohgkifijomclgjgif') accept_cookies, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=25, _xpath='/html/body/c-wiz/div/div/div/div[2]/div[1]/div[4]/form/div/div/button' ) if succeeded is False: print('Failed to find accept_cookies') print(traceback.print_exc()) exit() accept_cookies.click() add_extension, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=7, _xpath='/html/body/div[3]/div[2]/div/div/div[2]/div[2]/div' ) time.sleep(2) if succeeded is False: add_extension, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=7, _xpath='/html/body/div[5]/div[2]/div/div/div[2]/div[2]/div' ) # /html/body/div[5]/div[2]/div/div/div[2]/div[2]/div if succeeded is False: print('Failed to find add_extension') print(traceback.print_exc()) exit() add_extension.click() window_id.minimize() time.sleep(0.2) window_id.restore() add_extension_region = bot_actions.VisualActions.find_image( image=str(Path().resolve()) + r'\alienworlds_program_data\images\add_extension.png', region=region, confidence=0.85 ) start_time = time.time() while add_extension_region is None: add_extension_region = bot_actions.VisualActions.find_image( image=str(Path().resolve()) + r'\alienworlds_program_data\images\add_extension.png', region=region, confidence=0.85 ) if time.time() - start_time > 12: exit('SHUTDOWN due to waiting too long for add_extension.png') add_extension_region_center = bot_actions.VisualActions.get_center(add_extension_region) bot_actions.VisualActions.move_to_click(coordinates=add_extension_region_center, duration=0.15) while len(driver.window_handles) < 2: time.sleep(0.2) print('Looking for new handle') for handle in driver.window_handles: if handle != parent_handle: driver.close() parent_handle = handle driver.switch_to.window(parent_handle) return driver def configure_extension(driver, window_id): skip_guide, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=15, _xpath='/html/body/div[4]/div/div/div[3]/button[1]' ) if succeeded is False: print('Failed to find skip_guide') exit('Failed to find skip_guide') sop.click_object(skip_guide) proxy_profile, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=15, _xpath='/html/body/div[1]/header/nav/li[7]/a' ) if succeeded is False: print('Failed to find proxy_profile') exit('Failed to find proxy_profile') sop.click_object(proxy_profile) server_ip, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=10, _xpath='/html/body/div[1]/main/div[2]/div/section[1]/div/table/tbody[1]/tr[1]/td[3]/input' ) if succeeded is False: print('Failed to find server_ip') exit('Failed to find server_ip') server_port, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=15, _xpath='/html/body/div[1]/main/div[2]/div/section[1]/div/table/tbody[1]/tr[1]/td[4]/input' ) if succeeded is False: print('Failed to find server_port') exit('Failed to find server_port') proxies = get_proxies.get_ten_and_check_online() random_index = random.randint(0, len(proxies) - 1) proxy_port = proxies.pop(random_index)[0] proxy = proxy_port.split(':')[0] port = proxy_port.split(':')[1] server_ip.clear() server_port.clear() server_ip.send_keys(proxy) server_port.send_keys(port) time.sleep(2) apply_changes, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=10, _xpath='/html/body/div[1]/header/nav/li[12]/a' ) if succeeded is False: print('Failed to find apply_changes') exit('Failed to find apply_changes') sop.click_object(apply_changes) def activate_profile(driver): time.sleep(3) driver.get('chrome-extension://padekgcemlokbadohgkifijomclgjgif/popup/index.html') old_handle = driver.window_handles[0] time.sleep(0.15) driver.execute_script('''window.open("http://www.blankwebsite.com/", "_blank");''') time.sleep(1) new_handle = None for handle in driver.window_handles: if handle != old_handle: new_handle = handle break time.sleep(2) proxy_profile, succeeded = sop.find_object_XPATH( driver=driver, time_to_wait=10, _xpath='//*[@id="js-profile-1"]' ) if succeeded is False: print('Failed to find your proxy_profile, please contact us or try again') exit('Failed to find your proxy_profile, please contact us or try again') sop.click_object(proxy_profile) time.sleep(2) driver.switch_to.window(new_handle) return driver
en
0.229378
# /html/body/div[5]/div[2]/div/div/div[2]/div[2]/div window.open("http://www.blankwebsite.com/", "_blank");
2.290654
2
chmap/data/corrections/lbcc/LBCC_create_mu-hist.py
predsci/CHD
3
6624270
<reponame>predsci/CHD<filename>chmap/data/corrections/lbcc/LBCC_create_mu-hist.py """ construct mu-histogram and push to database for any time period """ import os # This can be a computationally intensive process. # To limit number of threads numpy can spawn: # os.environ["OMP_NUM_THREADS"] = "4" import time import datetime import numpy as np from chmap.settings.app import App import chmap.database.db_classes as db_class from chmap.database.db_funs import init_db_conn_old, query_euv_images, add_hist, get_method_id, query_hist import chmap.utilities.datatypes.datatypes as psi_d_types ###### ------ PARAMETERS TO UPDATE -------- ######## # TIME RANGE hist_query_time_min = datetime.datetime(2020, 12, 31, 0, 0, 0) hist_query_time_max = datetime.datetime(2021, 1, 1, 0, 0, 0) # define instruments and wavelengths to include inst_list = ["AIA", "EUVI-A", "EUVI-B"] wavelengths = [193, 195] # define number of bins n_mu_bins = 18 n_intensity_bins = 200 # declare map and binning parameters R0 = 1.01 log10 = True lat_band = [- np.pi / 64., np.pi / 64.] # recover local filesystem paths raw_data_dir = App.RAW_DATA_HOME hdf_data_dir = App.PROCESSED_DATA_HOME # designate which database to connect to use_db = "mysql-Q" # 'sqlite' Use local sqlite file-based db # 'mysql-Q' Use the remote MySQL database on Q user = "turtle" # only needed for remote databases. password = "" # See <PASSWORD> for setting-up an encrypted password. In this case leave password="", and # init_db_conn_old() will automatically find and use your saved password. Otherwise, enter your MySQL password here. # setup local database paths (only used for use_db='sqlite') database_dir = App.DATABASE_HOME sqlite_filename = App.DATABASE_FNAME # ------------ NO NEED TO UPDATE ANYTHING BELOW ------------- # # setup database connection if use_db == 'sqlite': # setup database connection to local sqlite file sqlite_path = os.path.join(database_dir, sqlite_filename) if os.path.exists(sqlite_path): os.remove(sqlite_path) print("\nPrevious file ", sqlite_filename, " deleted.\n") db_session = init_db_conn_old(db_name=use_db, chd_base=db_class.Base, sqlite_path=sqlite_path) elif use_db in ['mysql-Q', 'mysql-Q_test']: # setup database connection to MySQL database on Q db_session = init_db_conn_old(db_name=use_db, chd_base=db_class.Base, user=user, password=password) # start time start_time_tot = time.time() # creates mu bin & intensity bin arrays mu_bin_edges = np.linspace(0.1, 1.0, n_mu_bins + 1, dtype='float') image_intensity_bin_edges = np.linspace(0, 5, num=n_intensity_bins + 1, dtype='float') # create LBC method meth_name = 'LBCC' meth_desc = 'LBCC Theoretic Fit Method' method_id = get_method_id(db_session, meth_name, meth_desc, var_names=None, var_descs=None, create=True) # loop over instrument for instrument in inst_list: # query EUV images query_instrument = [instrument, ] query_pd_all = query_euv_images(db_session=db_session, time_min=hist_query_time_min, time_max=hist_query_time_max, instrument=query_instrument, wavelength=wavelengths) # query LBCC histograms hist_pd = query_hist(db_session, meth_id=method_id[1], n_mu_bins=n_mu_bins, n_intensity_bins=n_intensity_bins, lat_band=lat_band, time_min=hist_query_time_min, time_max=hist_query_time_max, instrument=query_instrument, wavelength=wavelengths) # compare image results to hist results based on image_id in_index = query_pd_all.data_id.isin(hist_pd.image_id) # return only images that do not have corresponding histograms query_pd = query_pd_all[~in_index] # check that images remain that need histograms if query_pd.shape[0] == 0: print("All" + instrument + " images in timeframe already have associated histograms.") continue for index, row in query_pd.iterrows(): print("Processing image number", row.data_id, ".") if row.fname_hdf == "": print("Warning: Image # " + str(row.data_id) + " does not have an associated hdf file. Skipping") continue hdf_path = os.path.join(hdf_data_dir, row.fname_hdf) # attempt to open and read file try: los_temp = psi_d_types.read_los_image(hdf_path) except: print("Something went wrong opening: ", hdf_path, ". Skipping") continue # add coordinates to los object los_temp.get_coordinates(R0=R0) # perform 2D histogram on mu and image intensity temp_hist = los_temp.mu_hist(image_intensity_bin_edges, mu_bin_edges, lat_band=lat_band, log10=log10) hist_lbcc = psi_d_types.create_lbcc_hist(hdf_path, row.data_id, method_id[1], mu_bin_edges, image_intensity_bin_edges, lat_band, temp_hist) # add this histogram and meta data to database add_hist(db_session, hist_lbcc) db_session.close() end_time_tot = time.time() print("Histograms have been created and saved to the database.") print("Total elapsed time for histogram creation: " + str(round(end_time_tot - start_time_tot, 3)) + " seconds.")
""" construct mu-histogram and push to database for any time period """ import os # This can be a computationally intensive process. # To limit number of threads numpy can spawn: # os.environ["OMP_NUM_THREADS"] = "4" import time import datetime import numpy as np from chmap.settings.app import App import chmap.database.db_classes as db_class from chmap.database.db_funs import init_db_conn_old, query_euv_images, add_hist, get_method_id, query_hist import chmap.utilities.datatypes.datatypes as psi_d_types ###### ------ PARAMETERS TO UPDATE -------- ######## # TIME RANGE hist_query_time_min = datetime.datetime(2020, 12, 31, 0, 0, 0) hist_query_time_max = datetime.datetime(2021, 1, 1, 0, 0, 0) # define instruments and wavelengths to include inst_list = ["AIA", "EUVI-A", "EUVI-B"] wavelengths = [193, 195] # define number of bins n_mu_bins = 18 n_intensity_bins = 200 # declare map and binning parameters R0 = 1.01 log10 = True lat_band = [- np.pi / 64., np.pi / 64.] # recover local filesystem paths raw_data_dir = App.RAW_DATA_HOME hdf_data_dir = App.PROCESSED_DATA_HOME # designate which database to connect to use_db = "mysql-Q" # 'sqlite' Use local sqlite file-based db # 'mysql-Q' Use the remote MySQL database on Q user = "turtle" # only needed for remote databases. password = "" # See <PASSWORD> for setting-up an encrypted password. In this case leave password="", and # init_db_conn_old() will automatically find and use your saved password. Otherwise, enter your MySQL password here. # setup local database paths (only used for use_db='sqlite') database_dir = App.DATABASE_HOME sqlite_filename = App.DATABASE_FNAME # ------------ NO NEED TO UPDATE ANYTHING BELOW ------------- # # setup database connection if use_db == 'sqlite': # setup database connection to local sqlite file sqlite_path = os.path.join(database_dir, sqlite_filename) if os.path.exists(sqlite_path): os.remove(sqlite_path) print("\nPrevious file ", sqlite_filename, " deleted.\n") db_session = init_db_conn_old(db_name=use_db, chd_base=db_class.Base, sqlite_path=sqlite_path) elif use_db in ['mysql-Q', 'mysql-Q_test']: # setup database connection to MySQL database on Q db_session = init_db_conn_old(db_name=use_db, chd_base=db_class.Base, user=user, password=password) # start time start_time_tot = time.time() # creates mu bin & intensity bin arrays mu_bin_edges = np.linspace(0.1, 1.0, n_mu_bins + 1, dtype='float') image_intensity_bin_edges = np.linspace(0, 5, num=n_intensity_bins + 1, dtype='float') # create LBC method meth_name = 'LBCC' meth_desc = 'LBCC Theoretic Fit Method' method_id = get_method_id(db_session, meth_name, meth_desc, var_names=None, var_descs=None, create=True) # loop over instrument for instrument in inst_list: # query EUV images query_instrument = [instrument, ] query_pd_all = query_euv_images(db_session=db_session, time_min=hist_query_time_min, time_max=hist_query_time_max, instrument=query_instrument, wavelength=wavelengths) # query LBCC histograms hist_pd = query_hist(db_session, meth_id=method_id[1], n_mu_bins=n_mu_bins, n_intensity_bins=n_intensity_bins, lat_band=lat_band, time_min=hist_query_time_min, time_max=hist_query_time_max, instrument=query_instrument, wavelength=wavelengths) # compare image results to hist results based on image_id in_index = query_pd_all.data_id.isin(hist_pd.image_id) # return only images that do not have corresponding histograms query_pd = query_pd_all[~in_index] # check that images remain that need histograms if query_pd.shape[0] == 0: print("All" + instrument + " images in timeframe already have associated histograms.") continue for index, row in query_pd.iterrows(): print("Processing image number", row.data_id, ".") if row.fname_hdf == "": print("Warning: Image # " + str(row.data_id) + " does not have an associated hdf file. Skipping") continue hdf_path = os.path.join(hdf_data_dir, row.fname_hdf) # attempt to open and read file try: los_temp = psi_d_types.read_los_image(hdf_path) except: print("Something went wrong opening: ", hdf_path, ". Skipping") continue # add coordinates to los object los_temp.get_coordinates(R0=R0) # perform 2D histogram on mu and image intensity temp_hist = los_temp.mu_hist(image_intensity_bin_edges, mu_bin_edges, lat_band=lat_band, log10=log10) hist_lbcc = psi_d_types.create_lbcc_hist(hdf_path, row.data_id, method_id[1], mu_bin_edges, image_intensity_bin_edges, lat_band, temp_hist) # add this histogram and meta data to database add_hist(db_session, hist_lbcc) db_session.close() end_time_tot = time.time() print("Histograms have been created and saved to the database.") print("Total elapsed time for histogram creation: " + str(round(end_time_tot - start_time_tot, 3)) + " seconds.")
en
0.717887
construct mu-histogram and push to database for any time period # This can be a computationally intensive process. # To limit number of threads numpy can spawn: # os.environ["OMP_NUM_THREADS"] = "4" ###### ------ PARAMETERS TO UPDATE -------- ######## # TIME RANGE # define instruments and wavelengths to include # define number of bins # declare map and binning parameters # recover local filesystem paths # designate which database to connect to # 'sqlite' Use local sqlite file-based db # 'mysql-Q' Use the remote MySQL database on Q # only needed for remote databases. # See <PASSWORD> for setting-up an encrypted password. In this case leave password="", and # init_db_conn_old() will automatically find and use your saved password. Otherwise, enter your MySQL password here. # setup local database paths (only used for use_db='sqlite') # ------------ NO NEED TO UPDATE ANYTHING BELOW ------------- # # setup database connection # setup database connection to local sqlite file # setup database connection to MySQL database on Q # start time # creates mu bin & intensity bin arrays # create LBC method # loop over instrument # query EUV images # query LBCC histograms # compare image results to hist results based on image_id # return only images that do not have corresponding histograms # check that images remain that need histograms # " + str(row.data_id) + " does not have an associated hdf file. Skipping") # attempt to open and read file # add coordinates to los object # perform 2D histogram on mu and image intensity # add this histogram and meta data to database
2.451869
2
examples/pyScripts/setDesiredEstimator.py
pseudoPixels/bokehBot
2
6624271
<reponame>pseudoPixels/bokehBot import iSeaborn as isn from bokeh.plotting import output_file, save from numpy import median tips = isn.load_dataset("tips") fig = isn.barplot(x="day", y="tip", data=tips, estimator=median) output_file("setDesiredEstimator.html") save(fig)
import iSeaborn as isn from bokeh.plotting import output_file, save from numpy import median tips = isn.load_dataset("tips") fig = isn.barplot(x="day", y="tip", data=tips, estimator=median) output_file("setDesiredEstimator.html") save(fig)
none
1
2.525855
3
airflow/modules/tests/proxypool/test_proxypool_validator.py
phuonglvh/DataEngineeringProject
417
6624272
from unittest.mock import patch from proxypool import ProxyPoolValidator from ..fixtures import web_parser, raw_content, proxy_record @patch("parser.web_parser.WebParser.get_content") def test_validate_proxy(get_content, raw_content, web_parser, proxy_record): expected = True get_content.return_value = raw_content("proxy_list_file.txt") validator = ProxyPoolValidator("https://google.com", sleep_interval=0) validator.parser = web_parser proxy_record = validator.validate_proxy(proxy_record) result = proxy_record.is_valid assert result == expected @patch("parser.web_parser.WebParser.get_content") def test_invalid_proxy(get_content, raw_content, web_parser, proxy_record): expected = False get_content.return_value = None validator = ProxyPoolValidator("https://google.com", sleep_interval=0) validator.parser = web_parser proxy_record = validator.validate_proxy(proxy_record) result = proxy_record.is_valid assert result == expected @patch("parser.web_parser.WebParser.get_content") def test_unstable_valid_proxy(get_content, raw_content, web_parser, proxy_record): expected = True valid_content = raw_content("proxy_list_file.txt") get_content.side_effect = [valid_content, valid_content, None] validator = ProxyPoolValidator("https://google.com", sleep_interval=0) validator.parser = web_parser proxy_record = validator.validate_proxy(proxy_record) result = proxy_record.is_valid assert result == expected assert round(proxy_record.health, 2) == 0.67 @patch("parser.web_parser.WebParser.get_content") def test_unstable_invalid_proxy(get_content, raw_content, web_parser, proxy_record): expected = False valid_content = raw_content("proxy_list_file.txt") get_content.side_effect = [None, None, valid_content] validator = ProxyPoolValidator("https://google.com", sleep_interval=0) validator.parser = web_parser proxy_record = validator.validate_proxy(proxy_record) result = proxy_record.is_valid assert result == expected assert round(proxy_record.health, 2) == 0.33
from unittest.mock import patch from proxypool import ProxyPoolValidator from ..fixtures import web_parser, raw_content, proxy_record @patch("parser.web_parser.WebParser.get_content") def test_validate_proxy(get_content, raw_content, web_parser, proxy_record): expected = True get_content.return_value = raw_content("proxy_list_file.txt") validator = ProxyPoolValidator("https://google.com", sleep_interval=0) validator.parser = web_parser proxy_record = validator.validate_proxy(proxy_record) result = proxy_record.is_valid assert result == expected @patch("parser.web_parser.WebParser.get_content") def test_invalid_proxy(get_content, raw_content, web_parser, proxy_record): expected = False get_content.return_value = None validator = ProxyPoolValidator("https://google.com", sleep_interval=0) validator.parser = web_parser proxy_record = validator.validate_proxy(proxy_record) result = proxy_record.is_valid assert result == expected @patch("parser.web_parser.WebParser.get_content") def test_unstable_valid_proxy(get_content, raw_content, web_parser, proxy_record): expected = True valid_content = raw_content("proxy_list_file.txt") get_content.side_effect = [valid_content, valid_content, None] validator = ProxyPoolValidator("https://google.com", sleep_interval=0) validator.parser = web_parser proxy_record = validator.validate_proxy(proxy_record) result = proxy_record.is_valid assert result == expected assert round(proxy_record.health, 2) == 0.67 @patch("parser.web_parser.WebParser.get_content") def test_unstable_invalid_proxy(get_content, raw_content, web_parser, proxy_record): expected = False valid_content = raw_content("proxy_list_file.txt") get_content.side_effect = [None, None, valid_content] validator = ProxyPoolValidator("https://google.com", sleep_interval=0) validator.parser = web_parser proxy_record = validator.validate_proxy(proxy_record) result = proxy_record.is_valid assert result == expected assert round(proxy_record.health, 2) == 0.33
none
1
2.777025
3
examples/local/execute_module.py
wils0ns/saltypie
1
6624273
import logging from saltypie import Salt LOG = logging.getLogger() logging.basicConfig(level=logging.DEBUG) def main(): salt = Salt( url='https://localhost:8000', username='admin', passwd='<PASSWORD>', trust_host=True ) salt.eauth = 'pam' ret = salt.local_async( target='*', fun='test.arg', kwargs={'a': 1, 'b': 2}, wait=True ) print(ret) main()
import logging from saltypie import Salt LOG = logging.getLogger() logging.basicConfig(level=logging.DEBUG) def main(): salt = Salt( url='https://localhost:8000', username='admin', passwd='<PASSWORD>', trust_host=True ) salt.eauth = 'pam' ret = salt.local_async( target='*', fun='test.arg', kwargs={'a': 1, 'b': 2}, wait=True ) print(ret) main()
none
1
2.309823
2
app_stanford.py
ilos-vigil/id-pos-tagger
0
6624274
# source : https://stanfordnlp.github.io/stanfordnlp/pos.html import stanfordnlp nlp = stanfordnlp.Pipeline(processors='tokenize,mwt,pos', lang='id') doc = nlp('Bahasa Indonesia adalah bahasa Melayu yang dijadikan sebagai bahasa resmi Republik Indonesia dan bahasa persatuan bangsa Indonesia. ' 'Bahasa Indonesia diresmikan penggunaannya setelah Proklamasi Kemerdekaan Indonesia, tepatnya sehari sesudahnya, bersamaan dengan mulai berlakunya konstitusi. ' 'Di Timor Leste, bahasa Indonesia berstatus sebagai bahasa kerja. ' 'Kentang (Solanum tuberosum L.) adalah tanaman dari suku Solanaceae yang memiliki umbi batang yang dapat dimakan dan disebut "kentang" pula. ' 'Umbi kentang sekarang telah menjadi salah satu makanan pokok penting di Eropa walaupun pada awalnya didatangkan dari Amerika Selatan. ' 'Penjelajah Spanyol dan Portugis pertama kali membawa ke Eropa dan mengembangbiakkan tanaman ini.') print(*[f'(\'{word.text}\', \'{word.pos}\')' for sent in doc.sentences for word in sent.words], sep='\n')
# source : https://stanfordnlp.github.io/stanfordnlp/pos.html import stanfordnlp nlp = stanfordnlp.Pipeline(processors='tokenize,mwt,pos', lang='id') doc = nlp('Bahasa Indonesia adalah bahasa Melayu yang dijadikan sebagai bahasa resmi Republik Indonesia dan bahasa persatuan bangsa Indonesia. ' 'Bahasa Indonesia diresmikan penggunaannya setelah Proklamasi Kemerdekaan Indonesia, tepatnya sehari sesudahnya, bersamaan dengan mulai berlakunya konstitusi. ' 'Di Timor Leste, bahasa Indonesia berstatus sebagai bahasa kerja. ' 'Kentang (Solanum tuberosum L.) adalah tanaman dari suku Solanaceae yang memiliki umbi batang yang dapat dimakan dan disebut "kentang" pula. ' 'Umbi kentang sekarang telah menjadi salah satu makanan pokok penting di Eropa walaupun pada awalnya didatangkan dari Amerika Selatan. ' 'Penjelajah Spanyol dan Portugis pertama kali membawa ke Eropa dan mengembangbiakkan tanaman ini.') print(*[f'(\'{word.text}\', \'{word.pos}\')' for sent in doc.sentences for word in sent.words], sep='\n')
en
0.195268
# source : https://stanfordnlp.github.io/stanfordnlp/pos.html
2.82337
3
Lesson 10/MinPerimeterRectangle.py
whirlpool27/codility-lessons-solution
1
6624275
<filename>Lesson 10/MinPerimeterRectangle.py # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(N): # write your code in Python 3.6 factorCandidate = 1 minPerimeter = 4_000_000_000 while factorCandidate*factorCandidate <= N: if N % factorCandidate == 0: minPerimeter = min(minPerimeter, 2*(factorCandidate + N//factorCandidate)) factorCandidate += 1 return minPerimeter
<filename>Lesson 10/MinPerimeterRectangle.py # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(N): # write your code in Python 3.6 factorCandidate = 1 minPerimeter = 4_000_000_000 while factorCandidate*factorCandidate <= N: if N % factorCandidate == 0: minPerimeter = min(minPerimeter, 2*(factorCandidate + N//factorCandidate)) factorCandidate += 1 return minPerimeter
en
0.754381
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") # write your code in Python 3.6
3.633426
4
labs/lab4/backend/config.py
alice-cloud/dockerAndK8s
0
6624276
<gh_stars>0 import os class Config(object): REDIS_URL = "redis://{}:6379/0".format(os.environ.get("REDIS_SERVER")) SECRET_KEY = 'oh_so_secret' FLASK_PIKA_PARAMS = { 'host':'amqp', #amqp.server.com 'username': 'guest', #convenience param for username 'password': '<PASSWORD>', #convenience param for password 'port': 5672, #amqp server port 'virtual_host':'vhost' #amqp vhost }
import os class Config(object): REDIS_URL = "redis://{}:6379/0".format(os.environ.get("REDIS_SERVER")) SECRET_KEY = 'oh_so_secret' FLASK_PIKA_PARAMS = { 'host':'amqp', #amqp.server.com 'username': 'guest', #convenience param for username 'password': '<PASSWORD>', #convenience param for password 'port': 5672, #amqp server port 'virtual_host':'vhost' #amqp vhost }
en
0.365617
#amqp.server.com #convenience param for username #convenience param for password #amqp server port #amqp vhost
2.161572
2
src/utils/cn2arab.py
aquadrop/memory
2
6624277
import pycnnum chs_arabic_map = {'零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10, '百': 100, '千': 1000, '万': 10000, '〇': 0, '壹': 1, '贰': 2, '叁': 3, '肆': 4, '伍': 5, '陆': 6, '柒': 7, '捌': 8, '玖': 9, '拾': 10, '佰': 100, '仟': 10000, '萬': 10000, '亿': 100000000, '億': 100000000, '幺': 1, '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '两': 2} digit_list = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '万', '〇', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾', '佰', '仟', '萬', '亿', '億', '幺', '两', '点'] skip_gram = ['三星', '一加', '三菱', '三门','万达','一楼','二楼','三楼','四楼','五楼','六楼'] convert_list = {'0':'零','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'久'} lead_digits = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '两'] def new_cn2arab(query): if query.isdigit(): return float(query) if len(query) == 0: return query result = [] numstring = [] for i in range(len(query)): char = query[i] if char not in digit_list: if len(numstring) > 0: numstring = ''.join([str(num) for num in numstring]) result.append(pycnnum.cn2num(numstring)) numstring = [] result.append(char) else: if char == '点': try: pre = query[i - 1] post = query[i + 1] if pre in digit_list and post in digit_list: numstring.append(char) else: result.append(char) continue except: continue # if char in convert_list: # char = convert_list[char] if i < len(query) - 1: test = char + query[i + 1] if test in skip_gram: result.append(char) continue numstring.append(char) if len(numstring) > 0: numstring = ''.join([str(num) for num in numstring]) result.append(pycnnum.cn2num(numstring)) result = [str(r) for r in result] return "".join(result) def cn2arab(chinese_digits): if len(chinese_digits) == 0: return False, '' # chinese_digits = chinese_digits.decode("utf-8") prefix = [] digit = [] suffix = [] pre_flag = False dig_flag = False for char in chinese_digits: if char not in digit_list and not pre_flag: prefix.append(char) elif char in digit_list and not dig_flag: digit.append(char) pre_flag = True else: dig_flag = True suffix.append(char) if len(digit) == 0: return False, ''.join(prefix) # print 'prefix', _uniout.unescape(str(prefix), 'utf-8') # print 'digit', _uniout.unescape(str(digit), 'utf-8') # print 'suffix', _uniout.unescape(str(suffix), 'utf-8') suffix = ''.join(suffix) if suffix: transferred, suffix = cn2arab(suffix) else: transferred = False return transferred or pre_flag, ''.join(prefix) + str(cn2arab_core(''.join(digit))) + suffix def cn2arab_core(chinese_digits): if chinese_digits.isdigit(): return int(chinese_digits) dig_mul = 1 ## 100百万,取出100这个数字 head_digits = [] head = False for c in chinese_digits: if c.isdigit(): head = True head_digits.append(c) else: break if len(head_digits) > 0: head_d = ''.join(head_digits) chinese_digits = chinese_digits.replace(head_d, '') dig_mul = float(head_d) if chinese_digits[0] not in lead_digits: chinese_digits = u'一' + chinese_digits result = 0 tmp = 0 hnd_mln = 0 for count in range(len(chinese_digits)): curr_char = chinese_digits[count] curr_digit = chs_arabic_map.get(curr_char, None) # meet 「亿」 or 「億」 if curr_digit == 10 ** 8: result = result + tmp result = result * curr_digit # get result before 「亿」 and store it into hnd_mln # reset `result` hnd_mln = hnd_mln * 10 ** 8 + result result = 0 tmp = 0 # meet 「万」 or 「萬」 elif curr_digit == 10 ** 4: result = result + tmp result = result * curr_digit tmp = 0 # meet 「十」, 「百」, 「千」 or their traditional version elif curr_digit >= 10: tmp = 1 if tmp == 0 else tmp result = result + curr_digit * tmp tmp = 0 # meet single digit elif curr_digit is not None: tmp = tmp * 10 + curr_digit else: return float(result) result = result + tmp result = result + hnd_mln return float(result * dig_mul) if __name__ == '__main__': s = ['十五哪点事','那点,42到50买一个三星手机两千一点五','3千','五十点二','三百','3百','两万','2万','2十万','100万','35','两千','1千零1百', '我要买一个两千到三千点二的手机'] for ss in s: # print(ss, cn2arab(ss)[1]) print(new_cn2arab(ss))
import pycnnum chs_arabic_map = {'零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10, '百': 100, '千': 1000, '万': 10000, '〇': 0, '壹': 1, '贰': 2, '叁': 3, '肆': 4, '伍': 5, '陆': 6, '柒': 7, '捌': 8, '玖': 9, '拾': 10, '佰': 100, '仟': 10000, '萬': 10000, '亿': 100000000, '億': 100000000, '幺': 1, '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '两': 2} digit_list = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '万', '〇', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾', '佰', '仟', '萬', '亿', '億', '幺', '两', '点'] skip_gram = ['三星', '一加', '三菱', '三门','万达','一楼','二楼','三楼','四楼','五楼','六楼'] convert_list = {'0':'零','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'久'} lead_digits = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '两'] def new_cn2arab(query): if query.isdigit(): return float(query) if len(query) == 0: return query result = [] numstring = [] for i in range(len(query)): char = query[i] if char not in digit_list: if len(numstring) > 0: numstring = ''.join([str(num) for num in numstring]) result.append(pycnnum.cn2num(numstring)) numstring = [] result.append(char) else: if char == '点': try: pre = query[i - 1] post = query[i + 1] if pre in digit_list and post in digit_list: numstring.append(char) else: result.append(char) continue except: continue # if char in convert_list: # char = convert_list[char] if i < len(query) - 1: test = char + query[i + 1] if test in skip_gram: result.append(char) continue numstring.append(char) if len(numstring) > 0: numstring = ''.join([str(num) for num in numstring]) result.append(pycnnum.cn2num(numstring)) result = [str(r) for r in result] return "".join(result) def cn2arab(chinese_digits): if len(chinese_digits) == 0: return False, '' # chinese_digits = chinese_digits.decode("utf-8") prefix = [] digit = [] suffix = [] pre_flag = False dig_flag = False for char in chinese_digits: if char not in digit_list and not pre_flag: prefix.append(char) elif char in digit_list and not dig_flag: digit.append(char) pre_flag = True else: dig_flag = True suffix.append(char) if len(digit) == 0: return False, ''.join(prefix) # print 'prefix', _uniout.unescape(str(prefix), 'utf-8') # print 'digit', _uniout.unescape(str(digit), 'utf-8') # print 'suffix', _uniout.unescape(str(suffix), 'utf-8') suffix = ''.join(suffix) if suffix: transferred, suffix = cn2arab(suffix) else: transferred = False return transferred or pre_flag, ''.join(prefix) + str(cn2arab_core(''.join(digit))) + suffix def cn2arab_core(chinese_digits): if chinese_digits.isdigit(): return int(chinese_digits) dig_mul = 1 ## 100百万,取出100这个数字 head_digits = [] head = False for c in chinese_digits: if c.isdigit(): head = True head_digits.append(c) else: break if len(head_digits) > 0: head_d = ''.join(head_digits) chinese_digits = chinese_digits.replace(head_d, '') dig_mul = float(head_d) if chinese_digits[0] not in lead_digits: chinese_digits = u'一' + chinese_digits result = 0 tmp = 0 hnd_mln = 0 for count in range(len(chinese_digits)): curr_char = chinese_digits[count] curr_digit = chs_arabic_map.get(curr_char, None) # meet 「亿」 or 「億」 if curr_digit == 10 ** 8: result = result + tmp result = result * curr_digit # get result before 「亿」 and store it into hnd_mln # reset `result` hnd_mln = hnd_mln * 10 ** 8 + result result = 0 tmp = 0 # meet 「万」 or 「萬」 elif curr_digit == 10 ** 4: result = result + tmp result = result * curr_digit tmp = 0 # meet 「十」, 「百」, 「千」 or their traditional version elif curr_digit >= 10: tmp = 1 if tmp == 0 else tmp result = result + curr_digit * tmp tmp = 0 # meet single digit elif curr_digit is not None: tmp = tmp * 10 + curr_digit else: return float(result) result = result + tmp result = result + hnd_mln return float(result * dig_mul) if __name__ == '__main__': s = ['十五哪点事','那点,42到50买一个三星手机两千一点五','3千','五十点二','三百','3百','两万','2万','2十万','100万','35','两千','1千零1百', '我要买一个两千到三千点二的手机'] for ss in s: # print(ss, cn2arab(ss)[1]) print(new_cn2arab(ss))
ja
0.308412
# if char in convert_list: # char = convert_list[char] # chinese_digits = chinese_digits.decode("utf-8") # print 'prefix', _uniout.unescape(str(prefix), 'utf-8') # print 'digit', _uniout.unescape(str(digit), 'utf-8') # print 'suffix', _uniout.unescape(str(suffix), 'utf-8') ## 100百万,取出100这个数字 # meet 「亿」 or 「億」 # get result before 「亿」 and store it into hnd_mln # reset `result` # meet 「万」 or 「萬」 # meet 「十」, 「百」, 「千」 or their traditional version # meet single digit # print(ss, cn2arab(ss)[1])
2.24685
2
encurtador_de_url.py
evertoont/Projetos_diversos
1
6624278
<reponame>evertoont/Projetos_diversos<filename>encurtador_de_url.py ''' Script realiza um encurtamento da URL usando o TinyURL. Após ser encurtada, a URL é copiada para área de transferência. - Necessário instalar as lib pyshorteners e clipboard - pip install pyshorteners - pip install clipboard ''' import pyshorteners import clipboard url = input("Digite url a ser encurtada: ") url_encurtada = pyshorteners.Shortener().tinyurl.short(url) print('---------------------------------------') print("Sua url: ", url_encurtada) print('---------------------------------------') clipboard.copy(url_encurtada) print("Url foi copiada para a área de transferencia")
''' Script realiza um encurtamento da URL usando o TinyURL. Após ser encurtada, a URL é copiada para área de transferência. - Necessário instalar as lib pyshorteners e clipboard - pip install pyshorteners - pip install clipboard ''' import pyshorteners import clipboard url = input("Digite url a ser encurtada: ") url_encurtada = pyshorteners.Shortener().tinyurl.short(url) print('---------------------------------------') print("Sua url: ", url_encurtada) print('---------------------------------------') clipboard.copy(url_encurtada) print("Url foi copiada para a área de transferencia")
pt
0.815814
Script realiza um encurtamento da URL usando o TinyURL. Após ser encurtada, a URL é copiada para área de transferência. - Necessário instalar as lib pyshorteners e clipboard - pip install pyshorteners - pip install clipboard
4.0688
4
models.py
atxarib99/stonks
0
6624279
<reponame>atxarib99/stonks # holds different models that can be pulled into the learner. # each method takes data as input and will output cleaned data and model import tensorflow as tf import numpy as np import pandas as pd def singleHighOutput(data, lstm_layer_size=128, lstm_layer_count=2): dataset_x = [] dataset_y = [] train_x = [] train_y = [] for i in range(30, len(data) - 1): dataset_x.append(data[i-30:i]) dataset_y.append(data[i+1][0]) train_x, train_y, valid_x, valid_y, test_x, test_y = splitdata(dataset_x, dataset_y, [.8,0,.2]) #reshape train_x = np.array(train_x) train_y = np.array(train_y) train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 6)) train_y = np.reshape(train_y, (train_y.shape[0], 1)) test_x = np.array(test_x) test_y = np.array(test_y) test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 6)) test_y = np.reshape(test_y, (test_y.shape[0], 1)) layers = [] for i in range(0, lstm_layer_count): if i != lstm_layer_count - 1: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=True, input_shape=(30,6), kernel_initializer='glorot_uniform')) else: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=False, input_shape=(30,6), kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dropout(.2)) layers.append(tf.keras.layers.Dense(6, kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dense(1, kernel_initializer='glorot_uniform')) model = tf.keras.Sequential(layers) return (model, train_x, train_y, valid_x, valid_y, test_x, test_y) def next5HighOutput(data, lstm_layer_size=64, lstm_layer_count=4, prev_days=30): dataset_x = [] dataset_y = [] train_x = [] train_y = [] for i in range(prev_days, len(data) - 5): dataset_x.append(data[i-prev_days:i]) dataset_y.append([row[0] for row in data[i+1:i+6]]) train_x, train_y, valid_x, valid_y, test_x, test_y = splitdata(dataset_x, dataset_y, [.8,0,.2]) #reshape train_x = np.array(train_x) train_y = np.array(train_y) train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 6)) train_y = np.reshape(train_y, (train_y.shape[0], 5)) test_x = np.array(test_x) test_y = np.array(test_y) test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 6)) test_y = np.reshape(test_y, (test_y.shape[0], 5)) layers = [] for i in range(0, lstm_layer_count): if i != lstm_layer_count - 1: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=True, input_shape=(prev_days,6), kernel_initializer='glorot_uniform')) else: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=False, input_shape=(prev_days,6), kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dropout(.3)) layers.append(tf.keras.layers.Dense(125, kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dense(5, kernel_initializer='glorot_uniform')) model = tf.keras.Sequential(layers) return (model, train_x, train_y, valid_x, valid_y, test_x, test_y) def next1AllOutput(data, lstm_layer_size=256, lstm_layer_count=3): dataset_x = [] dataset_y = [] train_x = [] train_y = [] for i in range(30, len(data) - 1): dataset_x.append(data[i-30:i]) dataset_y.append(data[i+1]) train_x, train_y, valid_x, valid_y, test_x, test_y = splitdata(dataset_x, dataset_y, [.8,0,.2]) #reshape train_x = np.array(train_x) train_y = np.array(train_y) train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 6)) train_y = np.reshape(train_y, (train_y.shape[0], 6)) test_x = np.array(test_x) test_y = np.array(test_y) test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 6)) test_y = np.reshape(test_y, (test_y.shape[0], 6)) layers = [] for i in range(0, lstm_layer_count): if i != lstm_layer_count - 1: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=True, input_shape=(30,6), kernel_initializer='glorot_uniform')) else: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=False, input_shape=(30,6), kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dropout(.2)) layers.append(tf.keras.layers.Dense(6, kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dense(6, kernel_initializer='glorot_uniform')) model = tf.keras.Sequential(layers) return (model, train_x, train_y, valid_x, valid_y, test_x, test_y) def splitdata(dataset_x, dataset_y, splitdef): train_size = splitdef[0] valid_size = splitdef[1] test_size = splitdef[2] if train_size + valid_size + test_size != 1: print('data split definition does not add to 1!') return None #80:20 test train split train_x = dataset_x[0:int(len(dataset_x)*train_size)] valid_x = [] if valid_size == 0: valid_x = dataset_x[int(len(dataset_x)*train_size):int(len(dataset_x)*(train_size+valid_size))] test_x = dataset_x[int(len(dataset_x)*(train_size + valid_size)):len(dataset_x)] train_y = dataset_y[0:int(len(dataset_y)*train_size)] valid_y = [] if valid_size == 0: valid_y = dataset_y[int(len(dataset_y)*train_size):int(len(dataset_y)*(train_size+valid_size))] test_y = dataset_y[int(len(dataset_y)*(train_size + valid_size)):len(dataset_y)] return (train_x, train_y, valid_x, valid_y, test_x, test_y)
# holds different models that can be pulled into the learner. # each method takes data as input and will output cleaned data and model import tensorflow as tf import numpy as np import pandas as pd def singleHighOutput(data, lstm_layer_size=128, lstm_layer_count=2): dataset_x = [] dataset_y = [] train_x = [] train_y = [] for i in range(30, len(data) - 1): dataset_x.append(data[i-30:i]) dataset_y.append(data[i+1][0]) train_x, train_y, valid_x, valid_y, test_x, test_y = splitdata(dataset_x, dataset_y, [.8,0,.2]) #reshape train_x = np.array(train_x) train_y = np.array(train_y) train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 6)) train_y = np.reshape(train_y, (train_y.shape[0], 1)) test_x = np.array(test_x) test_y = np.array(test_y) test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 6)) test_y = np.reshape(test_y, (test_y.shape[0], 1)) layers = [] for i in range(0, lstm_layer_count): if i != lstm_layer_count - 1: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=True, input_shape=(30,6), kernel_initializer='glorot_uniform')) else: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=False, input_shape=(30,6), kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dropout(.2)) layers.append(tf.keras.layers.Dense(6, kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dense(1, kernel_initializer='glorot_uniform')) model = tf.keras.Sequential(layers) return (model, train_x, train_y, valid_x, valid_y, test_x, test_y) def next5HighOutput(data, lstm_layer_size=64, lstm_layer_count=4, prev_days=30): dataset_x = [] dataset_y = [] train_x = [] train_y = [] for i in range(prev_days, len(data) - 5): dataset_x.append(data[i-prev_days:i]) dataset_y.append([row[0] for row in data[i+1:i+6]]) train_x, train_y, valid_x, valid_y, test_x, test_y = splitdata(dataset_x, dataset_y, [.8,0,.2]) #reshape train_x = np.array(train_x) train_y = np.array(train_y) train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 6)) train_y = np.reshape(train_y, (train_y.shape[0], 5)) test_x = np.array(test_x) test_y = np.array(test_y) test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 6)) test_y = np.reshape(test_y, (test_y.shape[0], 5)) layers = [] for i in range(0, lstm_layer_count): if i != lstm_layer_count - 1: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=True, input_shape=(prev_days,6), kernel_initializer='glorot_uniform')) else: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=False, input_shape=(prev_days,6), kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dropout(.3)) layers.append(tf.keras.layers.Dense(125, kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dense(5, kernel_initializer='glorot_uniform')) model = tf.keras.Sequential(layers) return (model, train_x, train_y, valid_x, valid_y, test_x, test_y) def next1AllOutput(data, lstm_layer_size=256, lstm_layer_count=3): dataset_x = [] dataset_y = [] train_x = [] train_y = [] for i in range(30, len(data) - 1): dataset_x.append(data[i-30:i]) dataset_y.append(data[i+1]) train_x, train_y, valid_x, valid_y, test_x, test_y = splitdata(dataset_x, dataset_y, [.8,0,.2]) #reshape train_x = np.array(train_x) train_y = np.array(train_y) train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 6)) train_y = np.reshape(train_y, (train_y.shape[0], 6)) test_x = np.array(test_x) test_y = np.array(test_y) test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 6)) test_y = np.reshape(test_y, (test_y.shape[0], 6)) layers = [] for i in range(0, lstm_layer_count): if i != lstm_layer_count - 1: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=True, input_shape=(30,6), kernel_initializer='glorot_uniform')) else: layers.append(tf.keras.layers.LSTM(lstm_layer_size, return_sequences=False, input_shape=(30,6), kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dropout(.2)) layers.append(tf.keras.layers.Dense(6, kernel_initializer='glorot_uniform')) layers.append(tf.keras.layers.Dense(6, kernel_initializer='glorot_uniform')) model = tf.keras.Sequential(layers) return (model, train_x, train_y, valid_x, valid_y, test_x, test_y) def splitdata(dataset_x, dataset_y, splitdef): train_size = splitdef[0] valid_size = splitdef[1] test_size = splitdef[2] if train_size + valid_size + test_size != 1: print('data split definition does not add to 1!') return None #80:20 test train split train_x = dataset_x[0:int(len(dataset_x)*train_size)] valid_x = [] if valid_size == 0: valid_x = dataset_x[int(len(dataset_x)*train_size):int(len(dataset_x)*(train_size+valid_size))] test_x = dataset_x[int(len(dataset_x)*(train_size + valid_size)):len(dataset_x)] train_y = dataset_y[0:int(len(dataset_y)*train_size)] valid_y = [] if valid_size == 0: valid_y = dataset_y[int(len(dataset_y)*train_size):int(len(dataset_y)*(train_size+valid_size))] test_y = dataset_y[int(len(dataset_y)*(train_size + valid_size)):len(dataset_y)] return (train_x, train_y, valid_x, valid_y, test_x, test_y)
en
0.945008
# holds different models that can be pulled into the learner. # each method takes data as input and will output cleaned data and model #reshape #reshape #reshape #80:20 test train split
2.841473
3
app/bot/base.py
anderskswanson/xtensible
1
6624280
<reponame>anderskswanson/xtensible<gh_stars>1-10 from inspect import getmembers import importlib import os class BaseModule: """ Module of native features for XtensibleBot Available functions: - lsmod - describemod - addmod - delmod - help """ _NOT_LOADED = 'Module {} is not loaded into Xtensible-Bot' def __init__(self): self._modules = {'base': self} static_modules = [os.path.basename(item.path) for item in os.scandir("app/modules") if item.is_dir() and '__pycache__' not in item.path] for mod in static_modules: self._load_module(mod) def __len__(self): return len(self._modules) def __getitem__(self, key): return self._modules[key] def __setitem__(self, key, value): self._modules[key] = value def __contains__(self, key): return key in self._modules def __delitem__(self, key): self._modules.pop(key) # add a module script into the module list def _load_module(self, module): module_path = 'app/modules/{}/module_exports.py'.format(module) import_string = 'app.modules.{}.module_exports'.format(module) if not os.path.exists(os.path.join(module_path)): raise ModuleNotFoundError(self._NOT_LOADED.format(module)) key = importlib.import_module(import_string) self[module] = key def keys(self): """ Internal representation of lsmod !base keys """ return self._modules.keys() # merge iterable of module names or string module name into the module dict def addmod(self, item): """ Add module/s from the modules directory into the Xtensible-Bot !base addmod <module1 module2 ...> """ loaded_modules = [] failed_loads = [] if not isinstance(item, list): item = [item] # merge module hashmaps for name in item: try: module_obj = self._load_module(name) self[name] = module_obj loaded_modules.append(name) except ModuleNotFoundError: failed_loads.append(name) return loaded_modules, failed_loads def lsmod(self): """ List all modules loaded into the Xtensible-Bot !base lsmod """ return 'Loaded Modules:\n{}'.format( '\n'.join([module for module in self._modules])) def delmod(self, module): """ Delete (unload) a module from the Xtensible-Bot !base delmod <module> """ if module in self: del self[module] return 'Removed module {}'.format(module) else: return self._NOT_LOADED.format(module) def describemod(self, module): """ Return a description of each member function of a module !base describemod module """ if module in self: attrs = getmembers(self[module]) methods = ['{}: {}'.format(attr[0], attr[1].__doc__) for attr in attrs if not attr[0].startswith('_')] return '\n'.join(methods) else: return self._NOT_LOADED.format(module)
from inspect import getmembers import importlib import os class BaseModule: """ Module of native features for XtensibleBot Available functions: - lsmod - describemod - addmod - delmod - help """ _NOT_LOADED = 'Module {} is not loaded into Xtensible-Bot' def __init__(self): self._modules = {'base': self} static_modules = [os.path.basename(item.path) for item in os.scandir("app/modules") if item.is_dir() and '__pycache__' not in item.path] for mod in static_modules: self._load_module(mod) def __len__(self): return len(self._modules) def __getitem__(self, key): return self._modules[key] def __setitem__(self, key, value): self._modules[key] = value def __contains__(self, key): return key in self._modules def __delitem__(self, key): self._modules.pop(key) # add a module script into the module list def _load_module(self, module): module_path = 'app/modules/{}/module_exports.py'.format(module) import_string = 'app.modules.{}.module_exports'.format(module) if not os.path.exists(os.path.join(module_path)): raise ModuleNotFoundError(self._NOT_LOADED.format(module)) key = importlib.import_module(import_string) self[module] = key def keys(self): """ Internal representation of lsmod !base keys """ return self._modules.keys() # merge iterable of module names or string module name into the module dict def addmod(self, item): """ Add module/s from the modules directory into the Xtensible-Bot !base addmod <module1 module2 ...> """ loaded_modules = [] failed_loads = [] if not isinstance(item, list): item = [item] # merge module hashmaps for name in item: try: module_obj = self._load_module(name) self[name] = module_obj loaded_modules.append(name) except ModuleNotFoundError: failed_loads.append(name) return loaded_modules, failed_loads def lsmod(self): """ List all modules loaded into the Xtensible-Bot !base lsmod """ return 'Loaded Modules:\n{}'.format( '\n'.join([module for module in self._modules])) def delmod(self, module): """ Delete (unload) a module from the Xtensible-Bot !base delmod <module> """ if module in self: del self[module] return 'Removed module {}'.format(module) else: return self._NOT_LOADED.format(module) def describemod(self, module): """ Return a description of each member function of a module !base describemod module """ if module in self: attrs = getmembers(self[module]) methods = ['{}: {}'.format(attr[0], attr[1].__doc__) for attr in attrs if not attr[0].startswith('_')] return '\n'.join(methods) else: return self._NOT_LOADED.format(module)
en
0.381062
Module of native features for XtensibleBot Available functions: - lsmod - describemod - addmod - delmod - help # add a module script into the module list Internal representation of lsmod !base keys # merge iterable of module names or string module name into the module dict Add module/s from the modules directory into the Xtensible-Bot !base addmod <module1 module2 ...> # merge module hashmaps List all modules loaded into the Xtensible-Bot !base lsmod Delete (unload) a module from the Xtensible-Bot !base delmod <module> Return a description of each member function of a module !base describemod module
2.409501
2
Besttimetobuyandsellstock.py
pgupta119/LeetCode
0
6624281
# You are given an array prices where prices[i] is the price of a given stock on the ith day. # You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. # Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. #Example # Input: prices = [7,1,5,3,6,4] # Output: 5 # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. # Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. #Solution; class Solution: def maxProfit(self, prices): #Initially maximum difference is zero max_diff=0 # Initialize the maximum of the array at the last index. max_number=prices[-1] # loop for checking the maximum difference and assign maximum value for j in range(len(prices)-2,-1,-1): # if current index value is greater than max_number then assign the current value to max_number if(prices[j]>max_number): max_number=prices[j] # otherwise take the difference of max_number and current value,and compare with max_difference which provide max value usin max function else: max_diff= max (max_diff,(max_number-prices[j])) #return the max difference after execution of the loop return max_diff sol=Solution() print(sol.maxProfit([7,1,5,3,6,4])) #output should be 5
# You are given an array prices where prices[i] is the price of a given stock on the ith day. # You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. # Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. #Example # Input: prices = [7,1,5,3,6,4] # Output: 5 # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. # Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. #Solution; class Solution: def maxProfit(self, prices): #Initially maximum difference is zero max_diff=0 # Initialize the maximum of the array at the last index. max_number=prices[-1] # loop for checking the maximum difference and assign maximum value for j in range(len(prices)-2,-1,-1): # if current index value is greater than max_number then assign the current value to max_number if(prices[j]>max_number): max_number=prices[j] # otherwise take the difference of max_number and current value,and compare with max_difference which provide max value usin max function else: max_diff= max (max_diff,(max_number-prices[j])) #return the max difference after execution of the loop return max_diff sol=Solution() print(sol.maxProfit([7,1,5,3,6,4])) #output should be 5
en
0.873971
# You are given an array prices where prices[i] is the price of a given stock on the ith day. # You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. # Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. #Example # Input: prices = [7,1,5,3,6,4] # Output: 5 # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. # Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. #Solution; #Initially maximum difference is zero # Initialize the maximum of the array at the last index. # loop for checking the maximum difference and assign maximum value # if current index value is greater than max_number then assign the current value to max_number # otherwise take the difference of max_number and current value,and compare with max_difference which provide max value usin max function #return the max difference after execution of the loop #output should be 5
4.252072
4
Shop/migrations/0010_auto_20210506_2155.py
KumarSantosh22/TheShoppingCArt
0
6624282
# Generated by Django 3.1.7 on 2021-05-06 16:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Shop', '0009_auto_20210506_2154'), ] operations = [ migrations.AlterField( model_name='seller', name='phone', field=models.CharField(max_length=10), ), ]
# Generated by Django 3.1.7 on 2021-05-06 16:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Shop', '0009_auto_20210506_2154'), ] operations = [ migrations.AlterField( model_name='seller', name='phone', field=models.CharField(max_length=10), ), ]
en
0.7881
# Generated by Django 3.1.7 on 2021-05-06 16:25
1.501177
2
uscensus/__init__.py
nkrishnaswami/census
4
6624283
<reponame>nkrishnaswami/census from .data.discovery import DiscoveryInterface from .data.states import get_state_codes from .geocode.bulk import CensusBulkGeocoder from .util.errors import CensusError from .util.errors import DBError from .util.nopcache import NopCache from .util.sqlalchemycache import SqlAlchemyCache """This module reads the Census's API discovery interface at http://api.census.gov/data.json, and provides callable wrappers for each API it finds. It indexes each of their metadata fields to make the APIs and variables related to them easier to find. The fields in the dataset discovery interface are described at https://project-open-data.cio.gov/v1.1/schema/ . Using this module requires a Census API key, which you can request at https://www.census.gov/developers/ . Exceptions: * CensusError(Exception): base class for module exceptions * DBError(CensusError): errors accessing databases Classes: * SqlAlchemyCache: caches APIa metadata in any SqlAlchemy compatible DBMS * DBAPICache: caches API metadata in any DBAPI compatible DBMS * DiscoveryInterface: retrieves and caches census API metadata. This indexes metadata and has a dict of wrapper objects for each API. * model.CensusDataEndpoint: wraps a Census API endpoint given its metadata. These are constructed by the DiscoveryInterface. * NopCache: dummy implementation of the cache interface Functions: * get_state_codes: retrieve state codes/names/abbreviations Usage: Instantiate a DiscoveryInterface using a DBAPICache and your Census API key. Call census APIs and receive the results as a pandas DataFrame. """ __all__ = [ "CensusBulkGeocoder", "DiscoveryInterface", "DBAPICache", "SqlAlchemyCache", "NopCache", "CensusError", "DBError", "get_state_codes", ]
from .data.discovery import DiscoveryInterface from .data.states import get_state_codes from .geocode.bulk import CensusBulkGeocoder from .util.errors import CensusError from .util.errors import DBError from .util.nopcache import NopCache from .util.sqlalchemycache import SqlAlchemyCache """This module reads the Census's API discovery interface at http://api.census.gov/data.json, and provides callable wrappers for each API it finds. It indexes each of their metadata fields to make the APIs and variables related to them easier to find. The fields in the dataset discovery interface are described at https://project-open-data.cio.gov/v1.1/schema/ . Using this module requires a Census API key, which you can request at https://www.census.gov/developers/ . Exceptions: * CensusError(Exception): base class for module exceptions * DBError(CensusError): errors accessing databases Classes: * SqlAlchemyCache: caches APIa metadata in any SqlAlchemy compatible DBMS * DBAPICache: caches API metadata in any DBAPI compatible DBMS * DiscoveryInterface: retrieves and caches census API metadata. This indexes metadata and has a dict of wrapper objects for each API. * model.CensusDataEndpoint: wraps a Census API endpoint given its metadata. These are constructed by the DiscoveryInterface. * NopCache: dummy implementation of the cache interface Functions: * get_state_codes: retrieve state codes/names/abbreviations Usage: Instantiate a DiscoveryInterface using a DBAPICache and your Census API key. Call census APIs and receive the results as a pandas DataFrame. """ __all__ = [ "CensusBulkGeocoder", "DiscoveryInterface", "DBAPICache", "SqlAlchemyCache", "NopCache", "CensusError", "DBError", "get_state_codes", ]
en
0.726619
This module reads the Census's API discovery interface at http://api.census.gov/data.json, and provides callable wrappers for each API it finds. It indexes each of their metadata fields to make the APIs and variables related to them easier to find. The fields in the dataset discovery interface are described at https://project-open-data.cio.gov/v1.1/schema/ . Using this module requires a Census API key, which you can request at https://www.census.gov/developers/ . Exceptions: * CensusError(Exception): base class for module exceptions * DBError(CensusError): errors accessing databases Classes: * SqlAlchemyCache: caches APIa metadata in any SqlAlchemy compatible DBMS * DBAPICache: caches API metadata in any DBAPI compatible DBMS * DiscoveryInterface: retrieves and caches census API metadata. This indexes metadata and has a dict of wrapper objects for each API. * model.CensusDataEndpoint: wraps a Census API endpoint given its metadata. These are constructed by the DiscoveryInterface. * NopCache: dummy implementation of the cache interface Functions: * get_state_codes: retrieve state codes/names/abbreviations Usage: Instantiate a DiscoveryInterface using a DBAPICache and your Census API key. Call census APIs and receive the results as a pandas DataFrame.
2.457949
2
riptide_engine_docker/container_builder.py
theCapypara/riptide-engine-docker
1
6624284
<filename>riptide_engine_docker/container_builder.py """Container builder module.""" from collections import OrderedDict import os import platform from pathlib import PurePosixPath from typing import List, Union from docker.types import Mount, Ulimit from riptide.config.document.command import Command from riptide.config.document.service import Service from riptide.config.hosts import get_localhost_hosts from riptide.config.service.ports import find_open_port_starting_at from riptide.lib.cross_platform.cpuser import getgid, getuid from riptide_engine_docker.assets import riptide_engine_docker_assets_dir ENTRYPOINT_SH = 'entrypoint.sh' RIPTIDE_DOCKER_LABEL_IS_RIPTIDE = 'riptide' RIPTIDE_DOCKER_LABEL_SERVICE = "riptide_service" RIPTIDE_DOCKER_LABEL_PROJECT = "riptide_project" RIPTIDE_DOCKER_LABEL_MAIN = "riptide_main" RIPTIDE_DOCKER_LABEL_HTTP_PORT = "riptide_port" ENTRYPOINT_CONTAINER_PATH = '/entrypoint_riptide.sh' EENV_DONT_RUN_CMD = "RIPTIDE__DOCKER_DONT_RUN_CMD" EENV_USER = "RIPTIDE__DOCKER_USER" EENV_USER_RUN = "RIPTIDE__DOCKER_USER_RUN" EENV_GROUP = "RIPTIDE__DOCKER_GROUP" EENV_RUN_MAIN_CMD_AS_USER = "RIPTIDE__DOCKER_RUN_MAIN_CMD_AS_USER" EENV_ORIGINAL_ENTRYPOINT = "RIPTIDE__DOCKER_ORIGINAL_ENTRYPOINT" EENV_COMMAND_LOG_PREFIX = "RIPTIDE__DOCKER_CMD_LOGGING_" EENV_NO_STDOUT_REDIRECT = "RIPTIDE__DOCKER_NO_STDOUT_REDIRECT" EENV_NAMED_VOLUMES = "RIPTIDE__DOCKER_NAMED_VOLUMES" EENV_ON_LINUX = "RIPTIDE__DOCKER_ON_LINUX" EENV_HOST_SYSTEM_HOSTNAMES = "RIPTIDE__DOCKER_HOST_SYSTEM_HOSTNAMES" EENV_OVERLAY_TARGETS = "RIPTIDE__DOCKER_OVERLAY_TARGETS" # For services map HTTP main port to a host port starting here DOCKER_ENGINE_HTTP_PORT_BND_START = 30000 class ContainerBuilder: """ ContainerBuilder. Builds Riptide Docker containers for use with the Python API and the Docker CLI """ def __init__(self, image: str, command: Union[List, str, None]) -> None: """Create a new container builder. Specify image and command to run.""" self.env = OrderedDict() self.labels = OrderedDict() self.mounts = OrderedDict() self.ports = OrderedDict() self.network = None self.name = None self.entrypoint = None self.command = command self.args = [] self.work_dir = None self.image = image self.set_label(RIPTIDE_DOCKER_LABEL_IS_RIPTIDE, "1") self.run_as_root = False self.hostname = None self.allow_full_memlock = False self.cap_sys_admin = False self.on_linux = platform.system().lower().startswith('linux') self.set_env(EENV_ON_LINUX, "1" if self.on_linux else "0") self.named_volumes_in_cnt = [] def set_env(self, name: str, val: str): self.env[name] = val return self def set_label(self, name: str, val: str): self.labels[name] = val return self def set_mount(self, host_path: str, container_path: str, mode='rw'): self.mounts[host_path] = Mount( target=container_path, source=host_path, type='bind', read_only=mode == 'ro', consistency='delegated' # Performance setting for Docker Desktop on Mac ) return self def set_named_volume_mount(self, name: str, container_path: str, mode='rw'): """ Add a named volume. Name is automatically prefixed with riptide__. """ from riptide_engine_docker.named_volumes import NAMED_VOLUME_INTERNAL_PREFIX vol_name = NAMED_VOLUME_INTERNAL_PREFIX + name self.mounts[name] = Mount( target=container_path, source=vol_name, type='volume', read_only=mode == 'ro', labels={RIPTIDE_DOCKER_LABEL_IS_RIPTIDE: "1"} ) self.named_volumes_in_cnt.append(container_path) return self def set_port(self, cnt: int, host: int): self.ports[cnt] = host return self def set_network(self, network: str): self.network = network return self def set_name(self, name: str): self.name = name return self def set_entrypoint(self, entrypoint: str): self.entrypoint = entrypoint return self def set_args(self, args: List[str]): self.args = args return self def set_workdir(self, work_dir: str): self.work_dir = work_dir return self def set_hostname(self, hostname: str): self.hostname = hostname return self def set_allow_full_memlock(self, flag: bool): self.allow_full_memlock = flag return self def enable_riptide_entrypoint(self, image_config): """Add the Riptide entrypoint script and configure it.""" # The original entrypoint of the image is replaced with # this custom entrypoint script, which may call the original entrypoint # if present # If the entrypoint is enabled, then run the entrypoint # as root. It will handle the rest. self.run_as_root = True entrypoint_script = os.path.join(riptide_engine_docker_assets_dir(), ENTRYPOINT_SH) self.set_mount(entrypoint_script, ENTRYPOINT_CONTAINER_PATH, 'ro') # Collect entrypoint settings for key, val in parse_entrypoint(image_config["Entrypoint"]).items(): self.set_env(key, val) self.set_entrypoint(ENTRYPOINT_CONTAINER_PATH) return self def add_host_hostnames(self): """ Adds all hostnames that must be routable to the host system within the container as a environment variable. """ self.set_env(EENV_HOST_SYSTEM_HOSTNAMES, ' '.join(get_localhost_hosts())) def _init_common(self, doc: Union[Service, Command], image_config, use_named_volume, unimportant_paths): self.enable_riptide_entrypoint(image_config) self.add_host_hostnames() # Add volumes for host, volume in doc.collect_volumes().items(): if use_named_volume and 'name' in volume: self.set_named_volume_mount(volume['name'], volume['bind'], volume['mode'] or 'rw') else: self.set_mount(host, volume['bind'], volume['mode'] or 'rw') # Collect environment for key, val in doc.collect_environment().items(): self.set_env(key, val) # Add unimportant paths to the list of dirs to be used with overlayfs self.set_env(EENV_OVERLAY_TARGETS, ':'.join(unimportant_paths)) # Mounting bind/overlayfs will require SYS_ADMIN caps: if len(unimportant_paths) > 0: self.cap_sys_admin = True def init_from_service(self, service: Service, image_config): """ Initialize some data of this builder with the given service object. You need to call service_add_main_port separately. """ perf_settings = service.get_project().parent()['performance'] project_absolute_unimportant_paths = [] if perf_settings['dont_sync_unimportant_src'] and 'unimportant_paths' in service.parent(): project_absolute_unimportant_paths = [_make_abs_to_src(p) for p in service.parent()['unimportant_paths']] self._init_common( service, image_config, perf_settings['dont_sync_named_volumes_with_host'], project_absolute_unimportant_paths ) # Collect labels labels = service_collect_labels(service, service.get_project()["name"]) # Collect (and process!) additional_ports ports = service.collect_ports() # All command logging commands are added as environment variables for the # riptide entrypoint environment_updates = service_collect_logging_commands(service) # User settings for the entrypoint environment_updates.update(service_collect_entrypoint_user_settings(service, getuid(), getgid(), image_config)) # Add to builder for key, value in environment_updates.items(): self.set_env(key, value) for name, val in labels.items(): self.set_label(name, val) for container, host in ports.items(): self.set_port(container, host) # Check if ulimit memlock setting is enabled if "allow_full_memlock" in service and service["allow_full_memlock"]: self.set_allow_full_memlock(True) return self def service_add_main_port(self, service: Service): """ Add main service port. Not thread-safe! If starting multiple services in multiple threads: This has to be done separately, right before start, and with a lock in place, so that multiple service starts don't reserve the same port. """ if "port" in service: main_port = find_open_port_starting_at(DOCKER_ENGINE_HTTP_PORT_BND_START) self.set_label(RIPTIDE_DOCKER_LABEL_HTTP_PORT, str(main_port)) self.set_port(service["port"], main_port) def init_from_command(self, command: Command, image_config): """ Initialize some data of this builder with the given command object. """ perf_settings = command.get_project().parent()['performance'] project_absolute_unimportant_paths = [] if perf_settings['dont_sync_unimportant_src'] and 'unimportant_paths' in command.parent(): project_absolute_unimportant_paths = [_make_abs_to_src(p) for p in command.parent()['unimportant_paths']] self._init_common( command, image_config, perf_settings['dont_sync_named_volumes_with_host'], project_absolute_unimportant_paths ) return self def build_docker_api(self) -> dict: """ Build the docker container in the form of Docker API containers.run arguments. """ args = { 'image': self.image } if self.command is None: args['command'] = None elif isinstance(self.command, str): # COMMAND IS STRING args['command'] = self.command if len(self.args) > 0: args['command'] += " " + " ".join(f'"{w}"' for w in self.args) else: list_command = self.command.copy() # COMMAND IS LIST if len(self.args) > 0: list_command += self.args # Strange Docker API Bug (?) requires args with spaces to be quoted... args['command'] = [] for item in list_command: if " " in item: args['command'].append('"' + item + '"') else: args['command'].append(item) if self.name: args['name'] = self.name if self.network: args['network'] = self.network if self.entrypoint: args['entrypoint'] = [self.entrypoint] if self.work_dir: args['working_dir'] = self.work_dir if self.run_as_root: args['user'] = 0 if self.hostname: args['hostname'] = self.hostname if self.allow_full_memlock: args['ulimits'] = [Ulimit(name='memlock', soft=-1, hard=-1)] if self.cap_sys_admin: args['cap_add'] = ['SYS_ADMIN'] # Ubuntu and possibly other Distros: if self.on_linux: args['security_opt'] = ['apparmor:unconfined'] args['environment'] = self.env.copy() # Add list of named volume paths for Docker to chown if len(self.named_volumes_in_cnt) > 0: args['environment'][EENV_NAMED_VOLUMES] = ':'.join(self.named_volumes_in_cnt) args['labels'] = self.labels args['ports'] = self.ports args['mounts'] = list(self.mounts.values()) return args def build_docker_cli(self) -> List[str]: """ Build the docker container in the form of a Docker CLI command. """ shell = [ "docker", "run", "--rm", "-it" ] if self.name: shell += ["--name", self.name] if self.network: shell += ["--network", self.network] if self.entrypoint: shell += ["--entrypoint", self.entrypoint] if self.work_dir: shell += ["-w", self.work_dir] if self.run_as_root: shell += ["-u", str(0)] if self.hostname: shell += ["--hostname", self.hostname] for key, value in self.env.items(): shell += ['-e', key + '=' + value] # Add list of named volume paths for Docker to chown if len(self.named_volumes_in_cnt) > 0: shell += ['-e', EENV_NAMED_VOLUMES + '=' + ':'.join(self.named_volumes_in_cnt)] for key, value in self.labels.items(): shell += ['--label', key + '=' + value] for container, host in self.ports.items(): shell += ['-p', str(host) + ':' + str(container)] # Mac: Add delegated mac_add = ':delegated' if platform.system().lower().startswith('mac') else '' for mount in self.mounts.values(): mode = 'ro' if mount['ReadOnly'] else 'rw' if mount["Type"] == "bind": shell += ['-v', mount['Source'] + ':' + mount['Target'] + ':' + mode + mac_add] else: shell += ['--mount', f'type=volume,target={mount["Target"]},src={mount["Source"]},ro={"0" if mode == "rw" else "1"},' f'volume-label={RIPTIDE_DOCKER_LABEL_IS_RIPTIDE}=1'] # ulimits if self.allow_full_memlock: shell += ['--ulimit', 'memlock=-1:-1'] if self.cap_sys_admin: shell += ['--cap-add=SYS_ADMIN'] # On Ubuntu and possibly other distros: if self.on_linux: shell += ['--security-opt', 'apparmor:unconfined'] command = self.command if command is None: command = "" if isinstance(command, list): command = self.command[0] # If the command itself contains arguments, they have to be joined with # quotes, just like self.args if len(self.command) > 1: command += " " + " ".join(f'"{w}"' for w in self.command[1:]) shell += [ self.image, (command + " " + " ".join(f'"{w}"' for w in self.args)).rstrip() ] return shell def get_cmd_container_name(project_name: str, command_name: str): return 'riptide__' + project_name + '__cmd__' + command_name + '__' + str(os.getpid()) def get_network_name(project_name: str): return 'riptide__' + project_name def get_service_container_name(project_name: str, service_name: str): return 'riptide__' + project_name + '__' + service_name def parse_entrypoint(entrypoint): """ Parse the original entrypoint of an image and return a map of variables for the riptide entrypoint script. RIPTIDE__DOCKER_ORIGINAL_ENTRYPOINT: Original entrypoint as string to be used with exec. Empty if original entrypoint is not set. RIPTIDE__DOCKER_DONT_RUN_CMD: true or unset. When the original entrypoint is a string, the command does not get run. See table at https://docs.docker.com/engine/reference/builder/#shell-form-entrypoint-example """ # Is the original entrypoint set? if not entrypoint: return {EENV_ORIGINAL_ENTRYPOINT: ""} # Is the original entrypoint shell or exec format? if isinstance(entrypoint, list): # exec format # Turn the list into a string, but quote all arguments command = entrypoint.pop(0) arguments = " ".join([f'"{entry}"' for entry in entrypoint]) return { EENV_ORIGINAL_ENTRYPOINT: command + " " + arguments } else: # shell format return { EENV_ORIGINAL_ENTRYPOINT: "/bin/sh -c " + entrypoint, EENV_DONT_RUN_CMD: "true" } pass def service_collect_logging_commands(service: Service) -> dict: """Collect logging commands environment variables for this service""" environment = {} if "logging" in service and "commands" in service["logging"]: for cmdname, command in service["logging"]["commands"].items(): environment[EENV_COMMAND_LOG_PREFIX + cmdname] = command return environment def service_collect_entrypoint_user_settings(service: Service, user, user_group, image_config) -> dict: environment = {} if not service["dont_create_user"]: environment[EENV_USER] = str(user) environment[EENV_GROUP] = str(user_group) if service["run_as_current_user"]: # Run with the current system user environment[EENV_RUN_MAIN_CMD_AS_USER] = "yes" elif "User" in image_config and image_config["User"] != "": # If run_as_current_user is false and an user is configured in the image config, tell the entrypoint to run # with this user environment[EENV_RUN_MAIN_CMD_AS_USER] = "yes" environment[EENV_USER_RUN] = image_config["User"] return environment def service_collect_labels(service: Service, project_name): labels = { RIPTIDE_DOCKER_LABEL_IS_RIPTIDE: '1', RIPTIDE_DOCKER_LABEL_PROJECT: project_name, RIPTIDE_DOCKER_LABEL_SERVICE: service["$name"], RIPTIDE_DOCKER_LABEL_MAIN: "0" } if "roles" in service and "main" in service["roles"]: labels[RIPTIDE_DOCKER_LABEL_MAIN] = "1" return labels def _make_abs_to_src(p): """Convert the given relative path to an absolute path. Relative base is /src/.""" return str(PurePosixPath("/src").joinpath(p))
<filename>riptide_engine_docker/container_builder.py """Container builder module.""" from collections import OrderedDict import os import platform from pathlib import PurePosixPath from typing import List, Union from docker.types import Mount, Ulimit from riptide.config.document.command import Command from riptide.config.document.service import Service from riptide.config.hosts import get_localhost_hosts from riptide.config.service.ports import find_open_port_starting_at from riptide.lib.cross_platform.cpuser import getgid, getuid from riptide_engine_docker.assets import riptide_engine_docker_assets_dir ENTRYPOINT_SH = 'entrypoint.sh' RIPTIDE_DOCKER_LABEL_IS_RIPTIDE = 'riptide' RIPTIDE_DOCKER_LABEL_SERVICE = "riptide_service" RIPTIDE_DOCKER_LABEL_PROJECT = "riptide_project" RIPTIDE_DOCKER_LABEL_MAIN = "riptide_main" RIPTIDE_DOCKER_LABEL_HTTP_PORT = "riptide_port" ENTRYPOINT_CONTAINER_PATH = '/entrypoint_riptide.sh' EENV_DONT_RUN_CMD = "RIPTIDE__DOCKER_DONT_RUN_CMD" EENV_USER = "RIPTIDE__DOCKER_USER" EENV_USER_RUN = "RIPTIDE__DOCKER_USER_RUN" EENV_GROUP = "RIPTIDE__DOCKER_GROUP" EENV_RUN_MAIN_CMD_AS_USER = "RIPTIDE__DOCKER_RUN_MAIN_CMD_AS_USER" EENV_ORIGINAL_ENTRYPOINT = "RIPTIDE__DOCKER_ORIGINAL_ENTRYPOINT" EENV_COMMAND_LOG_PREFIX = "RIPTIDE__DOCKER_CMD_LOGGING_" EENV_NO_STDOUT_REDIRECT = "RIPTIDE__DOCKER_NO_STDOUT_REDIRECT" EENV_NAMED_VOLUMES = "RIPTIDE__DOCKER_NAMED_VOLUMES" EENV_ON_LINUX = "RIPTIDE__DOCKER_ON_LINUX" EENV_HOST_SYSTEM_HOSTNAMES = "RIPTIDE__DOCKER_HOST_SYSTEM_HOSTNAMES" EENV_OVERLAY_TARGETS = "RIPTIDE__DOCKER_OVERLAY_TARGETS" # For services map HTTP main port to a host port starting here DOCKER_ENGINE_HTTP_PORT_BND_START = 30000 class ContainerBuilder: """ ContainerBuilder. Builds Riptide Docker containers for use with the Python API and the Docker CLI """ def __init__(self, image: str, command: Union[List, str, None]) -> None: """Create a new container builder. Specify image and command to run.""" self.env = OrderedDict() self.labels = OrderedDict() self.mounts = OrderedDict() self.ports = OrderedDict() self.network = None self.name = None self.entrypoint = None self.command = command self.args = [] self.work_dir = None self.image = image self.set_label(RIPTIDE_DOCKER_LABEL_IS_RIPTIDE, "1") self.run_as_root = False self.hostname = None self.allow_full_memlock = False self.cap_sys_admin = False self.on_linux = platform.system().lower().startswith('linux') self.set_env(EENV_ON_LINUX, "1" if self.on_linux else "0") self.named_volumes_in_cnt = [] def set_env(self, name: str, val: str): self.env[name] = val return self def set_label(self, name: str, val: str): self.labels[name] = val return self def set_mount(self, host_path: str, container_path: str, mode='rw'): self.mounts[host_path] = Mount( target=container_path, source=host_path, type='bind', read_only=mode == 'ro', consistency='delegated' # Performance setting for Docker Desktop on Mac ) return self def set_named_volume_mount(self, name: str, container_path: str, mode='rw'): """ Add a named volume. Name is automatically prefixed with riptide__. """ from riptide_engine_docker.named_volumes import NAMED_VOLUME_INTERNAL_PREFIX vol_name = NAMED_VOLUME_INTERNAL_PREFIX + name self.mounts[name] = Mount( target=container_path, source=vol_name, type='volume', read_only=mode == 'ro', labels={RIPTIDE_DOCKER_LABEL_IS_RIPTIDE: "1"} ) self.named_volumes_in_cnt.append(container_path) return self def set_port(self, cnt: int, host: int): self.ports[cnt] = host return self def set_network(self, network: str): self.network = network return self def set_name(self, name: str): self.name = name return self def set_entrypoint(self, entrypoint: str): self.entrypoint = entrypoint return self def set_args(self, args: List[str]): self.args = args return self def set_workdir(self, work_dir: str): self.work_dir = work_dir return self def set_hostname(self, hostname: str): self.hostname = hostname return self def set_allow_full_memlock(self, flag: bool): self.allow_full_memlock = flag return self def enable_riptide_entrypoint(self, image_config): """Add the Riptide entrypoint script and configure it.""" # The original entrypoint of the image is replaced with # this custom entrypoint script, which may call the original entrypoint # if present # If the entrypoint is enabled, then run the entrypoint # as root. It will handle the rest. self.run_as_root = True entrypoint_script = os.path.join(riptide_engine_docker_assets_dir(), ENTRYPOINT_SH) self.set_mount(entrypoint_script, ENTRYPOINT_CONTAINER_PATH, 'ro') # Collect entrypoint settings for key, val in parse_entrypoint(image_config["Entrypoint"]).items(): self.set_env(key, val) self.set_entrypoint(ENTRYPOINT_CONTAINER_PATH) return self def add_host_hostnames(self): """ Adds all hostnames that must be routable to the host system within the container as a environment variable. """ self.set_env(EENV_HOST_SYSTEM_HOSTNAMES, ' '.join(get_localhost_hosts())) def _init_common(self, doc: Union[Service, Command], image_config, use_named_volume, unimportant_paths): self.enable_riptide_entrypoint(image_config) self.add_host_hostnames() # Add volumes for host, volume in doc.collect_volumes().items(): if use_named_volume and 'name' in volume: self.set_named_volume_mount(volume['name'], volume['bind'], volume['mode'] or 'rw') else: self.set_mount(host, volume['bind'], volume['mode'] or 'rw') # Collect environment for key, val in doc.collect_environment().items(): self.set_env(key, val) # Add unimportant paths to the list of dirs to be used with overlayfs self.set_env(EENV_OVERLAY_TARGETS, ':'.join(unimportant_paths)) # Mounting bind/overlayfs will require SYS_ADMIN caps: if len(unimportant_paths) > 0: self.cap_sys_admin = True def init_from_service(self, service: Service, image_config): """ Initialize some data of this builder with the given service object. You need to call service_add_main_port separately. """ perf_settings = service.get_project().parent()['performance'] project_absolute_unimportant_paths = [] if perf_settings['dont_sync_unimportant_src'] and 'unimportant_paths' in service.parent(): project_absolute_unimportant_paths = [_make_abs_to_src(p) for p in service.parent()['unimportant_paths']] self._init_common( service, image_config, perf_settings['dont_sync_named_volumes_with_host'], project_absolute_unimportant_paths ) # Collect labels labels = service_collect_labels(service, service.get_project()["name"]) # Collect (and process!) additional_ports ports = service.collect_ports() # All command logging commands are added as environment variables for the # riptide entrypoint environment_updates = service_collect_logging_commands(service) # User settings for the entrypoint environment_updates.update(service_collect_entrypoint_user_settings(service, getuid(), getgid(), image_config)) # Add to builder for key, value in environment_updates.items(): self.set_env(key, value) for name, val in labels.items(): self.set_label(name, val) for container, host in ports.items(): self.set_port(container, host) # Check if ulimit memlock setting is enabled if "allow_full_memlock" in service and service["allow_full_memlock"]: self.set_allow_full_memlock(True) return self def service_add_main_port(self, service: Service): """ Add main service port. Not thread-safe! If starting multiple services in multiple threads: This has to be done separately, right before start, and with a lock in place, so that multiple service starts don't reserve the same port. """ if "port" in service: main_port = find_open_port_starting_at(DOCKER_ENGINE_HTTP_PORT_BND_START) self.set_label(RIPTIDE_DOCKER_LABEL_HTTP_PORT, str(main_port)) self.set_port(service["port"], main_port) def init_from_command(self, command: Command, image_config): """ Initialize some data of this builder with the given command object. """ perf_settings = command.get_project().parent()['performance'] project_absolute_unimportant_paths = [] if perf_settings['dont_sync_unimportant_src'] and 'unimportant_paths' in command.parent(): project_absolute_unimportant_paths = [_make_abs_to_src(p) for p in command.parent()['unimportant_paths']] self._init_common( command, image_config, perf_settings['dont_sync_named_volumes_with_host'], project_absolute_unimportant_paths ) return self def build_docker_api(self) -> dict: """ Build the docker container in the form of Docker API containers.run arguments. """ args = { 'image': self.image } if self.command is None: args['command'] = None elif isinstance(self.command, str): # COMMAND IS STRING args['command'] = self.command if len(self.args) > 0: args['command'] += " " + " ".join(f'"{w}"' for w in self.args) else: list_command = self.command.copy() # COMMAND IS LIST if len(self.args) > 0: list_command += self.args # Strange Docker API Bug (?) requires args with spaces to be quoted... args['command'] = [] for item in list_command: if " " in item: args['command'].append('"' + item + '"') else: args['command'].append(item) if self.name: args['name'] = self.name if self.network: args['network'] = self.network if self.entrypoint: args['entrypoint'] = [self.entrypoint] if self.work_dir: args['working_dir'] = self.work_dir if self.run_as_root: args['user'] = 0 if self.hostname: args['hostname'] = self.hostname if self.allow_full_memlock: args['ulimits'] = [Ulimit(name='memlock', soft=-1, hard=-1)] if self.cap_sys_admin: args['cap_add'] = ['SYS_ADMIN'] # Ubuntu and possibly other Distros: if self.on_linux: args['security_opt'] = ['apparmor:unconfined'] args['environment'] = self.env.copy() # Add list of named volume paths for Docker to chown if len(self.named_volumes_in_cnt) > 0: args['environment'][EENV_NAMED_VOLUMES] = ':'.join(self.named_volumes_in_cnt) args['labels'] = self.labels args['ports'] = self.ports args['mounts'] = list(self.mounts.values()) return args def build_docker_cli(self) -> List[str]: """ Build the docker container in the form of a Docker CLI command. """ shell = [ "docker", "run", "--rm", "-it" ] if self.name: shell += ["--name", self.name] if self.network: shell += ["--network", self.network] if self.entrypoint: shell += ["--entrypoint", self.entrypoint] if self.work_dir: shell += ["-w", self.work_dir] if self.run_as_root: shell += ["-u", str(0)] if self.hostname: shell += ["--hostname", self.hostname] for key, value in self.env.items(): shell += ['-e', key + '=' + value] # Add list of named volume paths for Docker to chown if len(self.named_volumes_in_cnt) > 0: shell += ['-e', EENV_NAMED_VOLUMES + '=' + ':'.join(self.named_volumes_in_cnt)] for key, value in self.labels.items(): shell += ['--label', key + '=' + value] for container, host in self.ports.items(): shell += ['-p', str(host) + ':' + str(container)] # Mac: Add delegated mac_add = ':delegated' if platform.system().lower().startswith('mac') else '' for mount in self.mounts.values(): mode = 'ro' if mount['ReadOnly'] else 'rw' if mount["Type"] == "bind": shell += ['-v', mount['Source'] + ':' + mount['Target'] + ':' + mode + mac_add] else: shell += ['--mount', f'type=volume,target={mount["Target"]},src={mount["Source"]},ro={"0" if mode == "rw" else "1"},' f'volume-label={RIPTIDE_DOCKER_LABEL_IS_RIPTIDE}=1'] # ulimits if self.allow_full_memlock: shell += ['--ulimit', 'memlock=-1:-1'] if self.cap_sys_admin: shell += ['--cap-add=SYS_ADMIN'] # On Ubuntu and possibly other distros: if self.on_linux: shell += ['--security-opt', 'apparmor:unconfined'] command = self.command if command is None: command = "" if isinstance(command, list): command = self.command[0] # If the command itself contains arguments, they have to be joined with # quotes, just like self.args if len(self.command) > 1: command += " " + " ".join(f'"{w}"' for w in self.command[1:]) shell += [ self.image, (command + " " + " ".join(f'"{w}"' for w in self.args)).rstrip() ] return shell def get_cmd_container_name(project_name: str, command_name: str): return 'riptide__' + project_name + '__cmd__' + command_name + '__' + str(os.getpid()) def get_network_name(project_name: str): return 'riptide__' + project_name def get_service_container_name(project_name: str, service_name: str): return 'riptide__' + project_name + '__' + service_name def parse_entrypoint(entrypoint): """ Parse the original entrypoint of an image and return a map of variables for the riptide entrypoint script. RIPTIDE__DOCKER_ORIGINAL_ENTRYPOINT: Original entrypoint as string to be used with exec. Empty if original entrypoint is not set. RIPTIDE__DOCKER_DONT_RUN_CMD: true or unset. When the original entrypoint is a string, the command does not get run. See table at https://docs.docker.com/engine/reference/builder/#shell-form-entrypoint-example """ # Is the original entrypoint set? if not entrypoint: return {EENV_ORIGINAL_ENTRYPOINT: ""} # Is the original entrypoint shell or exec format? if isinstance(entrypoint, list): # exec format # Turn the list into a string, but quote all arguments command = entrypoint.pop(0) arguments = " ".join([f'"{entry}"' for entry in entrypoint]) return { EENV_ORIGINAL_ENTRYPOINT: command + " " + arguments } else: # shell format return { EENV_ORIGINAL_ENTRYPOINT: "/bin/sh -c " + entrypoint, EENV_DONT_RUN_CMD: "true" } pass def service_collect_logging_commands(service: Service) -> dict: """Collect logging commands environment variables for this service""" environment = {} if "logging" in service and "commands" in service["logging"]: for cmdname, command in service["logging"]["commands"].items(): environment[EENV_COMMAND_LOG_PREFIX + cmdname] = command return environment def service_collect_entrypoint_user_settings(service: Service, user, user_group, image_config) -> dict: environment = {} if not service["dont_create_user"]: environment[EENV_USER] = str(user) environment[EENV_GROUP] = str(user_group) if service["run_as_current_user"]: # Run with the current system user environment[EENV_RUN_MAIN_CMD_AS_USER] = "yes" elif "User" in image_config and image_config["User"] != "": # If run_as_current_user is false and an user is configured in the image config, tell the entrypoint to run # with this user environment[EENV_RUN_MAIN_CMD_AS_USER] = "yes" environment[EENV_USER_RUN] = image_config["User"] return environment def service_collect_labels(service: Service, project_name): labels = { RIPTIDE_DOCKER_LABEL_IS_RIPTIDE: '1', RIPTIDE_DOCKER_LABEL_PROJECT: project_name, RIPTIDE_DOCKER_LABEL_SERVICE: service["$name"], RIPTIDE_DOCKER_LABEL_MAIN: "0" } if "roles" in service and "main" in service["roles"]: labels[RIPTIDE_DOCKER_LABEL_MAIN] = "1" return labels def _make_abs_to_src(p): """Convert the given relative path to an absolute path. Relative base is /src/.""" return str(PurePosixPath("/src").joinpath(p))
en
0.818224
Container builder module. # For services map HTTP main port to a host port starting here ContainerBuilder. Builds Riptide Docker containers for use with the Python API and the Docker CLI Create a new container builder. Specify image and command to run. # Performance setting for Docker Desktop on Mac Add a named volume. Name is automatically prefixed with riptide__. Add the Riptide entrypoint script and configure it. # The original entrypoint of the image is replaced with # this custom entrypoint script, which may call the original entrypoint # if present # If the entrypoint is enabled, then run the entrypoint # as root. It will handle the rest. # Collect entrypoint settings Adds all hostnames that must be routable to the host system within the container as a environment variable. # Add volumes # Collect environment # Add unimportant paths to the list of dirs to be used with overlayfs # Mounting bind/overlayfs will require SYS_ADMIN caps: Initialize some data of this builder with the given service object. You need to call service_add_main_port separately. # Collect labels # Collect (and process!) additional_ports # All command logging commands are added as environment variables for the # riptide entrypoint # User settings for the entrypoint # Add to builder # Check if ulimit memlock setting is enabled Add main service port. Not thread-safe! If starting multiple services in multiple threads: This has to be done separately, right before start, and with a lock in place, so that multiple service starts don't reserve the same port. Initialize some data of this builder with the given command object. Build the docker container in the form of Docker API containers.run arguments. # COMMAND IS STRING # COMMAND IS LIST # Strange Docker API Bug (?) requires args with spaces to be quoted... # Ubuntu and possibly other Distros: # Add list of named volume paths for Docker to chown Build the docker container in the form of a Docker CLI command. # Add list of named volume paths for Docker to chown # Mac: Add delegated # ulimits # On Ubuntu and possibly other distros: # If the command itself contains arguments, they have to be joined with # quotes, just like self.args Parse the original entrypoint of an image and return a map of variables for the riptide entrypoint script. RIPTIDE__DOCKER_ORIGINAL_ENTRYPOINT: Original entrypoint as string to be used with exec. Empty if original entrypoint is not set. RIPTIDE__DOCKER_DONT_RUN_CMD: true or unset. When the original entrypoint is a string, the command does not get run. See table at https://docs.docker.com/engine/reference/builder/#shell-form-entrypoint-example # Is the original entrypoint set? # Is the original entrypoint shell or exec format? # exec format # Turn the list into a string, but quote all arguments # shell format Collect logging commands environment variables for this service # Run with the current system user # If run_as_current_user is false and an user is configured in the image config, tell the entrypoint to run # with this user Convert the given relative path to an absolute path. Relative base is /src/.
1.964997
2
nmeta/api_definitions/switches_api.py
mattjhayes/nmeta
18
6624285
<filename>nmeta/api_definitions/switches_api.py # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. #*** nmeta - Network Metadata - API definition file switches_schema = { 'dpid': { 'type': 'integer' }, 'ip_address': { 'type': 'string' }, 'port': { 'type': 'integer' }, 'time_connected': { 'type': 'string' }, 'mfr_desc': { 'type': 'string' }, 'hw_desc': { 'type': 'string' }, 'sw_desc': { 'type': 'string' }, 'serial_num': { 'type': 'string' }, 'dp_desc': { 'type': 'string' } } switches_settings = { 'url': 'infrastructure/switches', 'item_title': 'OpenFlow Switches', 'schema': switches_schema } #*** A count of the number of connected switches: switches_count_schema = { 'connected_switches': { 'type': 'integer' } } switches_count_settings = { 'url': 'infrastructure/switches/stats/connected_switches', 'item_title': 'Count of Connected OpenFlow Switches', 'schema': switches_count_schema }
<filename>nmeta/api_definitions/switches_api.py # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. #*** nmeta - Network Metadata - API definition file switches_schema = { 'dpid': { 'type': 'integer' }, 'ip_address': { 'type': 'string' }, 'port': { 'type': 'integer' }, 'time_connected': { 'type': 'string' }, 'mfr_desc': { 'type': 'string' }, 'hw_desc': { 'type': 'string' }, 'sw_desc': { 'type': 'string' }, 'serial_num': { 'type': 'string' }, 'dp_desc': { 'type': 'string' } } switches_settings = { 'url': 'infrastructure/switches', 'item_title': 'OpenFlow Switches', 'schema': switches_schema } #*** A count of the number of connected switches: switches_count_schema = { 'connected_switches': { 'type': 'integer' } } switches_count_settings = { 'url': 'infrastructure/switches/stats/connected_switches', 'item_title': 'Count of Connected OpenFlow Switches', 'schema': switches_count_schema }
en
0.836088
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. #*** nmeta - Network Metadata - API definition file #*** A count of the number of connected switches:
1.55326
2
apps/gsekit/process/models.py
iSecloud/bk-process-config-manager
8
6624286
<filename>apps/gsekit/process/models.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from collections import defaultdict from typing import Dict, List from django.db import models from django.utils.translation import ugettext_lazy as _ from apps.gsekit.cmdb.constants import BK_SET_ENV_CHOICES from apps.gsekit.process.exceptions import ProcessInstDoseNotExistException, GenerateProcessObjException class Process(models.Model): class ProcessObjectType(object): INSTANCE = "INSTANCE" TEMPLATE = "TEMPLATE" PROCESS_OBJECT_TYPE_CHOICE = ( (ProcessObjectType.INSTANCE, _("进程实例")), (ProcessObjectType.TEMPLATE, _("进程模板")), ) class ProcessStatus(object): # 对于GSE,0/2都为终止状态 UNREGISTERED = 0 RUNNING = 1 TERMINATED = 2 PROCESS_STATUS_CHOICE = ( (ProcessStatus.RUNNING, _("运行中")), (ProcessStatus.TERMINATED, _("未运行")), ) IS_AUTO_CHOICE = ((False, _("未托管")), (True, _("已托管"))) bk_biz_id = models.IntegerField(_("业务ID"), db_index=True) expression = models.CharField(_("实例表达式"), max_length=256, db_index=True, default="待完善") bk_host_innerip = models.GenericIPAddressField(_("主机IP"), db_index=True) bk_cloud_id = models.IntegerField(_("云区域ID"), db_index=True) bk_set_env = models.CharField(_("集群环境类型"), choices=BK_SET_ENV_CHOICES, max_length=4, db_index=True) bk_set_id = models.IntegerField(_("集群ID"), db_index=True) bk_module_id = models.IntegerField(_("模块ID"), db_index=True) service_template_id = models.IntegerField(_("服务模板ID"), null=True, blank=True, db_index=True) service_instance_id = models.IntegerField(_("服务实例ID"), db_index=True) bk_process_name = models.CharField(_("进程名称"), max_length=64, null=True, blank=True, db_index=True) bk_process_id = models.IntegerField(_("进程ID"), primary_key=True) process_template_id = models.IntegerField(_("进程模板ID"), db_index=True) process_status = models.IntegerField(_("进程状态"), db_index=True, default=ProcessStatus.TERMINATED) is_auto = models.BooleanField(_("托管状态"), db_index=True, default=False) @classmethod def generate_process_obj(cls, bk_process_id: int = None, process_template_id: int = None) -> Dict: # 优先判定为进程模板 if process_template_id: return {"process_object_type": cls.ProcessObjectType.TEMPLATE, "process_object_id": process_template_id} elif bk_process_id: return {"process_object_type": cls.ProcessObjectType.INSTANCE, "process_object_id": bk_process_id} else: raise GenerateProcessObjException() def to_process_obj(self) -> Dict: return self.generate_process_obj(bk_process_id=self.bk_process_id, process_template_id=self.process_template_id) class Meta: verbose_name = _("业务进程缓存") verbose_name_plural = _("业务进程缓存") class ProcessInst(models.Model): # 默认启动数量 DEFAULT_PROC_NUM = 1 LOCAL_INST_ID_UNIQ_KEY_TMPL = "{bk_host_innerip}-{bk_cloud_id}-{bk_process_name}-{local_inst_id}" INST_ID_UNIQ_KEY_TMPL = "{bk_module_id}-{bk_process_name}-{inst_id}" BK_HOST_NUM_KEY_TMPL = "{bk_host_innerip}-{bk_cloud_id}-{bk_process_name}" bk_biz_id = models.IntegerField(_("业务ID"), db_index=True) bk_host_num = models.IntegerField(_("主机编号"), db_index=True) bk_host_innerip = models.GenericIPAddressField(_("主机IP"), db_index=True) bk_cloud_id = models.IntegerField(_("云区域ID"), db_index=True) bk_process_id = models.IntegerField(_("进程ID"), db_index=True) bk_module_id = models.IntegerField(_("模块ID"), db_index=True) bk_process_name = models.CharField(_("进程名称"), max_length=64, db_index=True) inst_id = models.IntegerField(_("InstID"), db_index=True) process_status = models.IntegerField(_("进程状态"), db_index=True, default=Process.ProcessStatus.TERMINATED) is_auto = models.BooleanField(_("托管状态"), db_index=True, default=False) local_inst_id = models.IntegerField(_("LocalInstID"), db_index=True) local_inst_id_uniq_key = models.CharField(_("进程实例唯一标识"), max_length=256, db_index=True, default="") proc_num = models.IntegerField(_("启动数量"), default=DEFAULT_PROC_NUM) @classmethod def get_process_inst_map(cls, bk_process_ids: List[int]) -> Dict: """根据进程ID列表查询""" proc_inst_map = defaultdict(list) for proc_inst in ProcessInst.objects.filter(bk_process_id__in=bk_process_ids).values( "bk_process_id", "inst_id", "local_inst_id" ): proc_inst_map[proc_inst["bk_process_id"]].append( {"inst_id": proc_inst["inst_id"], "local_inst_id": proc_inst["local_inst_id"]} ) return proc_inst_map @classmethod def get_single_inst(cls, bk_process_id): """根据bk_process_id获取第一个实例""" proc_inst = cls.objects.filter(bk_process_id=bk_process_id).first() if not proc_inst: raise ProcessInstDoseNotExistException() return proc_inst @property def inst_id_uniq_key(self): return self.INST_ID_UNIQ_KEY_TMPL.format( bk_module_id=self.bk_module_id, bk_process_name=self.bk_process_name, inst_id=self.inst_id ) @property def bk_host_num_key(self): return self.BK_HOST_NUM_KEY_TMPL.format( bk_host_innerip=self.bk_host_innerip, bk_cloud_id=self.bk_cloud_id, bk_process_name=self.bk_process_name ) class Meta: unique_together = [ ["bk_module_id", "bk_process_name", "inst_id"], ["bk_host_innerip", "bk_cloud_id", "bk_process_name", "local_inst_id"], ] verbose_name = _("进程实例") verbose_name_plural = _("进程实例")
<filename>apps/gsekit/process/models.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from collections import defaultdict from typing import Dict, List from django.db import models from django.utils.translation import ugettext_lazy as _ from apps.gsekit.cmdb.constants import BK_SET_ENV_CHOICES from apps.gsekit.process.exceptions import ProcessInstDoseNotExistException, GenerateProcessObjException class Process(models.Model): class ProcessObjectType(object): INSTANCE = "INSTANCE" TEMPLATE = "TEMPLATE" PROCESS_OBJECT_TYPE_CHOICE = ( (ProcessObjectType.INSTANCE, _("进程实例")), (ProcessObjectType.TEMPLATE, _("进程模板")), ) class ProcessStatus(object): # 对于GSE,0/2都为终止状态 UNREGISTERED = 0 RUNNING = 1 TERMINATED = 2 PROCESS_STATUS_CHOICE = ( (ProcessStatus.RUNNING, _("运行中")), (ProcessStatus.TERMINATED, _("未运行")), ) IS_AUTO_CHOICE = ((False, _("未托管")), (True, _("已托管"))) bk_biz_id = models.IntegerField(_("业务ID"), db_index=True) expression = models.CharField(_("实例表达式"), max_length=256, db_index=True, default="待完善") bk_host_innerip = models.GenericIPAddressField(_("主机IP"), db_index=True) bk_cloud_id = models.IntegerField(_("云区域ID"), db_index=True) bk_set_env = models.CharField(_("集群环境类型"), choices=BK_SET_ENV_CHOICES, max_length=4, db_index=True) bk_set_id = models.IntegerField(_("集群ID"), db_index=True) bk_module_id = models.IntegerField(_("模块ID"), db_index=True) service_template_id = models.IntegerField(_("服务模板ID"), null=True, blank=True, db_index=True) service_instance_id = models.IntegerField(_("服务实例ID"), db_index=True) bk_process_name = models.CharField(_("进程名称"), max_length=64, null=True, blank=True, db_index=True) bk_process_id = models.IntegerField(_("进程ID"), primary_key=True) process_template_id = models.IntegerField(_("进程模板ID"), db_index=True) process_status = models.IntegerField(_("进程状态"), db_index=True, default=ProcessStatus.TERMINATED) is_auto = models.BooleanField(_("托管状态"), db_index=True, default=False) @classmethod def generate_process_obj(cls, bk_process_id: int = None, process_template_id: int = None) -> Dict: # 优先判定为进程模板 if process_template_id: return {"process_object_type": cls.ProcessObjectType.TEMPLATE, "process_object_id": process_template_id} elif bk_process_id: return {"process_object_type": cls.ProcessObjectType.INSTANCE, "process_object_id": bk_process_id} else: raise GenerateProcessObjException() def to_process_obj(self) -> Dict: return self.generate_process_obj(bk_process_id=self.bk_process_id, process_template_id=self.process_template_id) class Meta: verbose_name = _("业务进程缓存") verbose_name_plural = _("业务进程缓存") class ProcessInst(models.Model): # 默认启动数量 DEFAULT_PROC_NUM = 1 LOCAL_INST_ID_UNIQ_KEY_TMPL = "{bk_host_innerip}-{bk_cloud_id}-{bk_process_name}-{local_inst_id}" INST_ID_UNIQ_KEY_TMPL = "{bk_module_id}-{bk_process_name}-{inst_id}" BK_HOST_NUM_KEY_TMPL = "{bk_host_innerip}-{bk_cloud_id}-{bk_process_name}" bk_biz_id = models.IntegerField(_("业务ID"), db_index=True) bk_host_num = models.IntegerField(_("主机编号"), db_index=True) bk_host_innerip = models.GenericIPAddressField(_("主机IP"), db_index=True) bk_cloud_id = models.IntegerField(_("云区域ID"), db_index=True) bk_process_id = models.IntegerField(_("进程ID"), db_index=True) bk_module_id = models.IntegerField(_("模块ID"), db_index=True) bk_process_name = models.CharField(_("进程名称"), max_length=64, db_index=True) inst_id = models.IntegerField(_("InstID"), db_index=True) process_status = models.IntegerField(_("进程状态"), db_index=True, default=Process.ProcessStatus.TERMINATED) is_auto = models.BooleanField(_("托管状态"), db_index=True, default=False) local_inst_id = models.IntegerField(_("LocalInstID"), db_index=True) local_inst_id_uniq_key = models.CharField(_("进程实例唯一标识"), max_length=256, db_index=True, default="") proc_num = models.IntegerField(_("启动数量"), default=DEFAULT_PROC_NUM) @classmethod def get_process_inst_map(cls, bk_process_ids: List[int]) -> Dict: """根据进程ID列表查询""" proc_inst_map = defaultdict(list) for proc_inst in ProcessInst.objects.filter(bk_process_id__in=bk_process_ids).values( "bk_process_id", "inst_id", "local_inst_id" ): proc_inst_map[proc_inst["bk_process_id"]].append( {"inst_id": proc_inst["inst_id"], "local_inst_id": proc_inst["local_inst_id"]} ) return proc_inst_map @classmethod def get_single_inst(cls, bk_process_id): """根据bk_process_id获取第一个实例""" proc_inst = cls.objects.filter(bk_process_id=bk_process_id).first() if not proc_inst: raise ProcessInstDoseNotExistException() return proc_inst @property def inst_id_uniq_key(self): return self.INST_ID_UNIQ_KEY_TMPL.format( bk_module_id=self.bk_module_id, bk_process_name=self.bk_process_name, inst_id=self.inst_id ) @property def bk_host_num_key(self): return self.BK_HOST_NUM_KEY_TMPL.format( bk_host_innerip=self.bk_host_innerip, bk_cloud_id=self.bk_cloud_id, bk_process_name=self.bk_process_name ) class Meta: unique_together = [ ["bk_module_id", "bk_process_name", "inst_id"], ["bk_host_innerip", "bk_cloud_id", "bk_process_name", "local_inst_id"], ] verbose_name = _("进程实例") verbose_name_plural = _("进程实例")
en
0.818072
# -*- coding: utf-8 -*- Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # 对于GSE,0/2都为终止状态 # 优先判定为进程模板 # 默认启动数量 根据进程ID列表查询 根据bk_process_id获取第一个实例
1.735579
2
day4/task.py
dsky1990/python_30days
1
6624287
<reponame>dsky1990/python_30days # def fib(max): # n, a, b = 0, 0, 1 # while n < max: # print(b) # a, b = b, a + b # n = n + 1 # else: # print('done') # fib(9) def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n += 1 return "done" n = fib(10) while True: try: x = next(n) print("n:%d" %x) except StopIteration as e: print("Generation return value:", e.value) break
# def fib(max): # n, a, b = 0, 0, 1 # while n < max: # print(b) # a, b = b, a + b # n = n + 1 # else: # print('done') # fib(9) def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n += 1 return "done" n = fib(10) while True: try: x = next(n) print("n:%d" %x) except StopIteration as e: print("Generation return value:", e.value) break
en
0.506416
# def fib(max): # n, a, b = 0, 0, 1 # while n < max: # print(b) # a, b = b, a + b # n = n + 1 # else: # print('done') # fib(9)
3.888305
4
bakery_cli/pipe/__init__.py
jessamynsmith/fontbakery
0
6624288
from bakery_cli.pipe.copy import (Copy, CopyLicense, CopyDescription, CopyTxtFiles, CopyFontLog, CopyMetadata) from bakery_cli.pipe.build import Build from bakery_cli.pipe.ttfautohint import TTFAutoHint from bakery_cli.pipe.pyftsubset import PyFtSubset from bakery_cli.pipe.pyfontaine import PyFontaine from bakery_cli.pipe.metadata import Metadata from bakery_cli.pipe.fontlint import FontLint from bakery_cli.pipe.optimize import Optimize from bakery_cli.pipe.checkout import Checkout from bakery_cli.pipe.zip import Zip from bakery_cli.pipe.metadatalint import MetadataLint from bakery_cli.pipe.upstreamlint import UpstreamLint from bakery_cli.pipe.font_crunch import FontCrunch
from bakery_cli.pipe.copy import (Copy, CopyLicense, CopyDescription, CopyTxtFiles, CopyFontLog, CopyMetadata) from bakery_cli.pipe.build import Build from bakery_cli.pipe.ttfautohint import TTFAutoHint from bakery_cli.pipe.pyftsubset import PyFtSubset from bakery_cli.pipe.pyfontaine import PyFontaine from bakery_cli.pipe.metadata import Metadata from bakery_cli.pipe.fontlint import FontLint from bakery_cli.pipe.optimize import Optimize from bakery_cli.pipe.checkout import Checkout from bakery_cli.pipe.zip import Zip from bakery_cli.pipe.metadatalint import MetadataLint from bakery_cli.pipe.upstreamlint import UpstreamLint from bakery_cli.pipe.font_crunch import FontCrunch
none
1
1.201987
1
flashpandas/pages/create.py
MaxTechniche/flash-pandas
0
6624289
import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output, State, Input from pymongo.errors import DuplicateKeyError from flask import session from flashpandas.app import APP, users, cards, Card logged_out_layout = html.Div( [ "Must be logged in in order to create.", dbc.NavLink(dbc.Button("Login"), href="/login"), ], style={"text-align": "center"}, ) header = html.Div( [ dbc.Label("Card Creation", style={"font-size": "20px", "margin-bottom": "0px"}), dcc.Markdown("---"), ], style={"text-align": "center"}, ) question_and_answer_input = dbc.Row( [ dbc.Col( [ dbc.Label( children=[ "Question Input (uses ", html.A( "Markdown", href="https://www.markdownguide.org/", target="_blank", ), ")", ] ), dbc.Textarea( id="question-input", persistence=True, persistence_type="memory", style={"margin-bottom": "15px"}, ), ], style={"min-width": "250px"}, ), dbc.Col( [ dbc.Label( children=[ "Answer Input (uses ", html.A( "Markdown", href="https://www.markdownguide.org/", target="_blank", ), ")", ] ), dbc.Textarea( id="answer-input", persistence=True, persistence_type="memory", style={"margin-bottom": "15px"}, ), ], style={"min-width": "250px"}, ), ] ) question_and_answer_view = dbc.Row( [ dbc.Col( [ dbc.Label("Question View"), dcc.Markdown( id="question-view", style={ "border": "2px solid #C8E4F4", "border-radius": "3px", "padding": "5px", "margin-bottom": "15px", }, ), dcc.Markdown("---"), ], style={"min-width": "250px"}, ), dbc.Col( [ dbc.Label("Answer View"), dcc.Markdown( id="answer-view", style={ "border": "2px solid #C8E4F4", "border-radius": "3px", "padding": "5px", "margin-bottom": "15px", }, ), dcc.Markdown("---"), ], style={"min-width": "250px"}, ), ] ) tags_and_title = dbc.Row( [ dbc.Col( [ dbc.Label("Tags (future goal) (comma separated)"), dbc.Input( id="tags-input", persistence=True, persistence_type="memory", ), ], style={"min-width": "200px"}, ), dbc.Col( [ dbc.Label("Title or Summary"), dbc.Input( id="title-input", persistence=True, persistence_type="memory", ), ], style={"min-width": "200px"}, ), ] ) public_and_submit = html.Div( [ dcc.Markdown("---"), html.Div( [ dbc.Checkbox( id="public-check", persistence=True, checked=False, persistence_type="memory", ), dbc.Label("Make Public", style={"padding-left": "5px"}), ] ), dbc.Col( [ dbc.Button("Submit Card", id="card-submit", color="success"), html.Div(), dbc.Label(id="error-info", style={"padding-top": "10px"}), ] ), ], style={"text-align": "center"}, ) layout = html.Div( children=[ header, question_and_answer_input, question_and_answer_view, tags_and_title, public_and_submit, ], id="create-layout", ) @APP.callback( [Output("question-view", "children"), Output("answer-view", "children")], [Input("question-input", "value"), Input("answer-input", "value")], ) def mirror_text(question, answer): return [question, answer] @APP.callback( Output("error-info", "children"), Input("card-submit", "n_clicks"), [ State("question-input", "value"), State("answer-input", "value"), State("tags-input", "value"), State("title-input", "value"), State("public-check", "checked"), ], ) def submit_card(n_clicks, q_input, a_input, tags, title, public): if n_clicks: if not q_input: return "No question provided" if not a_input: return "No answer provided" card = Card( title=title or "", q_text=q_input, a_text=a_input, tags=tags.strip().split(",") if tags else [], public=public or False, creator=session.get("username", None), ) cards.insert_one(card.to_json()) return dcc.Location("url", "/cards") return ""
import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output, State, Input from pymongo.errors import DuplicateKeyError from flask import session from flashpandas.app import APP, users, cards, Card logged_out_layout = html.Div( [ "Must be logged in in order to create.", dbc.NavLink(dbc.Button("Login"), href="/login"), ], style={"text-align": "center"}, ) header = html.Div( [ dbc.Label("Card Creation", style={"font-size": "20px", "margin-bottom": "0px"}), dcc.Markdown("---"), ], style={"text-align": "center"}, ) question_and_answer_input = dbc.Row( [ dbc.Col( [ dbc.Label( children=[ "Question Input (uses ", html.A( "Markdown", href="https://www.markdownguide.org/", target="_blank", ), ")", ] ), dbc.Textarea( id="question-input", persistence=True, persistence_type="memory", style={"margin-bottom": "15px"}, ), ], style={"min-width": "250px"}, ), dbc.Col( [ dbc.Label( children=[ "Answer Input (uses ", html.A( "Markdown", href="https://www.markdownguide.org/", target="_blank", ), ")", ] ), dbc.Textarea( id="answer-input", persistence=True, persistence_type="memory", style={"margin-bottom": "15px"}, ), ], style={"min-width": "250px"}, ), ] ) question_and_answer_view = dbc.Row( [ dbc.Col( [ dbc.Label("Question View"), dcc.Markdown( id="question-view", style={ "border": "2px solid #C8E4F4", "border-radius": "3px", "padding": "5px", "margin-bottom": "15px", }, ), dcc.Markdown("---"), ], style={"min-width": "250px"}, ), dbc.Col( [ dbc.Label("Answer View"), dcc.Markdown( id="answer-view", style={ "border": "2px solid #C8E4F4", "border-radius": "3px", "padding": "5px", "margin-bottom": "15px", }, ), dcc.Markdown("---"), ], style={"min-width": "250px"}, ), ] ) tags_and_title = dbc.Row( [ dbc.Col( [ dbc.Label("Tags (future goal) (comma separated)"), dbc.Input( id="tags-input", persistence=True, persistence_type="memory", ), ], style={"min-width": "200px"}, ), dbc.Col( [ dbc.Label("Title or Summary"), dbc.Input( id="title-input", persistence=True, persistence_type="memory", ), ], style={"min-width": "200px"}, ), ] ) public_and_submit = html.Div( [ dcc.Markdown("---"), html.Div( [ dbc.Checkbox( id="public-check", persistence=True, checked=False, persistence_type="memory", ), dbc.Label("Make Public", style={"padding-left": "5px"}), ] ), dbc.Col( [ dbc.Button("Submit Card", id="card-submit", color="success"), html.Div(), dbc.Label(id="error-info", style={"padding-top": "10px"}), ] ), ], style={"text-align": "center"}, ) layout = html.Div( children=[ header, question_and_answer_input, question_and_answer_view, tags_and_title, public_and_submit, ], id="create-layout", ) @APP.callback( [Output("question-view", "children"), Output("answer-view", "children")], [Input("question-input", "value"), Input("answer-input", "value")], ) def mirror_text(question, answer): return [question, answer] @APP.callback( Output("error-info", "children"), Input("card-submit", "n_clicks"), [ State("question-input", "value"), State("answer-input", "value"), State("tags-input", "value"), State("title-input", "value"), State("public-check", "checked"), ], ) def submit_card(n_clicks, q_input, a_input, tags, title, public): if n_clicks: if not q_input: return "No question provided" if not a_input: return "No answer provided" card = Card( title=title or "", q_text=q_input, a_text=a_input, tags=tags.strip().split(",") if tags else [], public=public or False, creator=session.get("username", None), ) cards.insert_one(card.to_json()) return dcc.Location("url", "/cards") return ""
hu
0.348993
#C8E4F4", #C8E4F4",
2.334763
2
combat.py
tawnkramer/Adventure
2
6624290
import random from prettytable import * from util import * from commentary import * HP_RECOVERED_FROM_REST = 1 class CombatStats(object): COMBAT_STATUS_NONE = 0 COMBAT_STATUS_FIGHTING = 1 COMBAT_STATUS_RAN = 2 COMBAT_STATUS_WON = 3 COMBAT_STATUS_ALL_DIED = 4 def __init__(self): self.players_died = [] self.just_died = None self.players_wounded = [] self.monsters_slain = [] self.monsters_wounded = [] self.rounds = 0 self.total_dam_to_players = 0 self.total_dam_to_monsters = 0 self.players_perfect_blow = [] self.gold_won = 0 self.treasure_won = [] self.combat_status = self.COMBAT_STATUS_NONE class CombatAction(object): def __init__(self, name, description): self.name = name self.description = description def is_combat_action(self): return True def is_weapon(self): return False def is_spell(self): return False def all_dead(group): for p in group: if p.is_alive(): return False return True def add_unique(actions, item): for a in actions: if a.name == item.name: return actions.append(item) def choose_action_and_target(attacker, others): actions = [] if attacker.active_weapon is not None and attacker.active_weapon.is_weapon() and attacker.has_skill(attacker.active_weapon.cat): add_unique(actions, attacker.active_weapon) mana_adj = 0 #casting spells while in armor happens at a deficit if attacker.is_wearing_non_magic_armor(): mana_adj = 1 for item in attacker.inventory: if item.is_spell() and (item.mana + mana_adj) <= attacker.cur_mana and attacker.has_skill(item.cat): add_unique(actions, item) if attacker.has_potions(): actions.append(CombatAction('drink', 'drink potion.')) if attacker.has_scrolls(): actions.append(CombatAction('read', 'read scroll.')) if attacker.has_wands(): actions.append(CombatAction('wand', 'use wand.')) actions.append(CombatAction('draw', 'draw a new weapon to use.')) actions.append(CombatAction('block', 'attempt to withdaw, rest, and avoid damage.')) actions.append(CombatAction('run', 'flee to the nearest exit!')) if attacker.can_hide(): if attacker.is_hidden(): actions.append(CombatAction('stay hidden', 'recover hp and wait for right moment for suprise attack.')) else: actions.append(CombatAction('hide', 'use your stealth skill to hide in shadows.')) print "\n\nActions" t = PrettyTable(['sel', 'action', 'max damage', 'mana', 'description']) i = 1 for a in actions: if a.is_spell(): t.add_row([i, a.name, a.damage, a.mana + mana_adj, a.description]) elif a.is_weapon(): t.add_row([i, a.name, a.damage, ' ', a.description]) elif a.is_combat_action(): t.add_row([i, a.name, ' ', ' ', a.description]) i = i + 1 print t.get_string(hrules=HEADER) print print "Targets" t = PrettyTable(['sel', 'target', 'hp', 'ac', 'disabled']) i = 1 for m in others: if m.disabled: disabled = 'Yes' else: disabled = 'No' t.add_row([i, m.name, m.cur_hp, m.ac, disabled]) i = i + 1 print t.get_string(hrules=HEADER) print show_player_status(attacker) #get input valid = False target = None while not valid: print sel = get_input( attacker.name + " - Enter number of sel action (and optional sel target) -> ") iAction = 0 iTarget = 0 try: if(sel.find(' ') != -1): args = sel.split(' ') if len(args) == 2: iAction = int(args[0]) iTarget = int(args[1]) else: iAction = int(sel) except: pass if iAction > 0 and iAction <= len(actions): if iTarget != 0: if iTarget > 0 and iTarget <= len(others): target = others[iTarget - 1] while target is None or not target.is_alive(): if iTarget < 0 or iTarget >= len(others): iTarget = 0 target = others[iTarget] iTarget += 1 valid = True return [actions[iAction - 1], target ] def random_action_target(monster, players, player_actions): if len(players) == 0 or all_dead(players): return [None, None, None] iAction = random.randint(0, len(monster.attacks) - 1) iPlayer = random.randint(0, len(players) - 1) while not players[iPlayer].is_alive(): iPlayer = random.randint(0, len(players) - 1) return [ monster.attacks[iAction], players[iPlayer], player_actions[iPlayer] ] def random_target(monster, attack, players, player_actions): if len(players) == 0 or all_dead(players): return [None, None, None] iPlayer = random.randint(0, len(players) - 1) while not players[iPlayer].is_alive(): iPlayer = random.randint(0, len(players) - 1) return [ attack, players[iPlayer], player_actions[iPlayer] ] def show_player_status(p): if p.is_trapped(): print p.get_trapped_desc() elif p.is_disabled(): print p.name, 'hp:', p.cur_hp, ' is disabled!' else: print p.name, 'hp:', p.cur_hp, 'ac:', p.get_ac(), 'mana:', p.cur_mana def party_comment(comment, party): for p in party: if p.is_alive(): print comment % p.name break def show_status(players): print 'Status:' for p in players: show_player_status(p) print def award_experience(players, monsters): exp_total = 0 for m in monsters: m.on_combat_end() if not m.is_alive(): exp_total += m.xp_award total_living_players = 0 for p in players: p.on_combat_end() if p.is_alive(): total_living_players += 1 if total_living_players == 0: return reward = exp_total / total_living_players for p in players: if p.is_alive() and reward > 0: p.add_xp( reward ) def one_dead(group): d = 0 for m in group: if not m.is_alive(): d = d + 1 return d == 1 def half_dead(group): d = 0 for m in group: if not m.is_alive(): d = d + 1 return d == int(len(group) / 2) #a list of the player targets. We adjust the frequency of monster focus #by adding attacking players 3 times, spell or blocking characters once. def add_player_target(player, action, player_targets, player_actions): if player.is_hidden(): return if action.is_weapon(): player_targets.append(player) player_targets.append(player) player_actions.append(action) player_actions.append(action) player_targets.append(player) player_actions.append(action) def get_tohit_mod(round): #to simulate fatigue and increasing #likeliness to give and receive damage, #adjust to hit up as rounds go on. #Also helps reduce super long slogging battles #where everyone misses. tohit_mod = round / 2 #cap it at a ridiculous 10. Though 30 rounds is a SUPER long battle. if tohit_mod > 10: tohit_mod = 10 return tohit_mod def fight(players, monsters, room, level, mon_attack_first): done = False round = 1 moral_check_on_first_dead = False moral_check_on_half_dead = False level.combat_stats = CombatStats() while not done: print '-------------------------------------------------------' print 'Round', round, '\n' #make sure the armor class is up to date. for p in players: p.update_armor_class() #show all player status show_status(players) #adjust tohit modifiers to account for fatigue tohit_mod = get_tohit_mod(round) #a list of the player targets. We adjust the frequency of monster focus #by adding attacking players 3 times, spell or blocking characters once. player_targets = [] player_actions = [] for player in players: if not player.is_alive(): continue if all_dead(monsters): continue if mon_attack_first: add_player_target(player, CombatAction('suprised', ''), player_targets, player_actions) continue if player.is_disabled() or player.is_trapped(): add_player_target(player, CombatAction('disabled', ''), player_targets, player_actions) continue action, target = choose_action_and_target(player, monsters) if action is None: continue if action.is_spell(): player.cur_mana -= action.mana #wearing armor incurs a 1 pt mana expense if player.is_wearing_non_magic_armor(): player.cur_mana -= 1 if action.targets_environment(): action.cast_at_environ(player, monsters, players, room, level) elif target is None or action.targets_group(): action.cast(player, monsters, players) else: action.cast_at_target(player, target) elif action.is_weapon(): if target is None: action.attack(player, monsters, players, tohit_mod) else: action.attack_target(player, target, tohit_mod) elif action.is_combat_action(): if action.name == 'block': hp_rec = HP_RECOVERED_FROM_REST * player.level if player.cur_hp <= (player.hp / 2) - hp_rec: player.cur_hp += hp_rec print player.name, 'regains', hp_rec, 'hp after blocking and resting.' elif action.name == 'run': num_items = len(player.inventory) if num_items > 0: iDrop = random.randint(0, num_items - 1) item = player.inventory[iDrop] if not item.is_weapon() and not item.is_spell() and not item.is_armor(): print player.name, 'bolts for the door and drops his', item.name, 'in haste!' player.remove(item.name) room.items.append(item) award_experience(players, monsters) #all monsters heal when you leave. for m in monsters: if m.is_alive(): m.cur_hp = m.hp pause() return "run" elif action.name == 'hide': roll = random.randint(1, 20) print player.name, 'rolls %d.' % roll if roll >= player.get_hide_roll_thresh(): print player.name, 'slips into the shadows silently.' player.set_hidden(True) else: print player.name, 'was not able to hide.' elif action.name == 'draw': room.activate([player]) elif action.name == 'drink': player.drink_potion() elif action.name == 'read': player.read_scroll(monsters, players, room, level) elif action.name == 'wand': player.use_wand(monsters, players, room, level) pause() if player.is_hidden(): if action.is_spell() or action.is_weapon(): player.set_hidden(False) elif action.name != 'run': hp_rec = HP_RECOVERED_FROM_REST * player.level if player.cur_hp <= (player.hp / 2) - hp_rec: player.cur_hp += hp_rec print player.name, 'regains', hp_rec, 'hp while hiding.' add_player_target(player, action, player_targets, player_actions) #check for morale of monsters if not moral_check_on_first_dead and one_dead(monsters) and len(monsters) > 1: moral_check_on_first_dead = True if random.randint(1, 10) < 4: print 'The rest of the creatures flee in terror!' award_experience(players, monsters) return 'won' if not moral_check_on_half_dead and half_dead(monsters) and len(monsters) > 3: moral_check_on_half_dead = True if random.randint(1, 10) < 5: print 'The rest of the creatures flee in terror!' award_experience(players, monsters) return 'won' #only use once. Surprise attack if mon_attack_first: if random.randint(1, 2) < 2: print "It's a surprise attack!" tohit_mod += 2 else: party_comment('%s yells, "Look out!"', players) mon_attack_first = False for monster in monsters: action = monster.take_combat_turn(player_targets, player_actions, room, level, tohit_mod) if action and action.name == 'run': monsters.remove(monster) if all_dead(monsters): print "You defeated all the enemies!!\n" sitch = [WON] print_comment(sitch, players, room, level) award_experience(players, monsters) return 'won' if all_dead(players): print 'And everything fades to black. Better to have run.. oh well!!' return 'died' for monster in monsters: if monster.is_alive(): monster.on_combat_round_ended() for player in players: if player.is_alive(): player.on_combat_round_ended() print round = round + 1
import random from prettytable import * from util import * from commentary import * HP_RECOVERED_FROM_REST = 1 class CombatStats(object): COMBAT_STATUS_NONE = 0 COMBAT_STATUS_FIGHTING = 1 COMBAT_STATUS_RAN = 2 COMBAT_STATUS_WON = 3 COMBAT_STATUS_ALL_DIED = 4 def __init__(self): self.players_died = [] self.just_died = None self.players_wounded = [] self.monsters_slain = [] self.monsters_wounded = [] self.rounds = 0 self.total_dam_to_players = 0 self.total_dam_to_monsters = 0 self.players_perfect_blow = [] self.gold_won = 0 self.treasure_won = [] self.combat_status = self.COMBAT_STATUS_NONE class CombatAction(object): def __init__(self, name, description): self.name = name self.description = description def is_combat_action(self): return True def is_weapon(self): return False def is_spell(self): return False def all_dead(group): for p in group: if p.is_alive(): return False return True def add_unique(actions, item): for a in actions: if a.name == item.name: return actions.append(item) def choose_action_and_target(attacker, others): actions = [] if attacker.active_weapon is not None and attacker.active_weapon.is_weapon() and attacker.has_skill(attacker.active_weapon.cat): add_unique(actions, attacker.active_weapon) mana_adj = 0 #casting spells while in armor happens at a deficit if attacker.is_wearing_non_magic_armor(): mana_adj = 1 for item in attacker.inventory: if item.is_spell() and (item.mana + mana_adj) <= attacker.cur_mana and attacker.has_skill(item.cat): add_unique(actions, item) if attacker.has_potions(): actions.append(CombatAction('drink', 'drink potion.')) if attacker.has_scrolls(): actions.append(CombatAction('read', 'read scroll.')) if attacker.has_wands(): actions.append(CombatAction('wand', 'use wand.')) actions.append(CombatAction('draw', 'draw a new weapon to use.')) actions.append(CombatAction('block', 'attempt to withdaw, rest, and avoid damage.')) actions.append(CombatAction('run', 'flee to the nearest exit!')) if attacker.can_hide(): if attacker.is_hidden(): actions.append(CombatAction('stay hidden', 'recover hp and wait for right moment for suprise attack.')) else: actions.append(CombatAction('hide', 'use your stealth skill to hide in shadows.')) print "\n\nActions" t = PrettyTable(['sel', 'action', 'max damage', 'mana', 'description']) i = 1 for a in actions: if a.is_spell(): t.add_row([i, a.name, a.damage, a.mana + mana_adj, a.description]) elif a.is_weapon(): t.add_row([i, a.name, a.damage, ' ', a.description]) elif a.is_combat_action(): t.add_row([i, a.name, ' ', ' ', a.description]) i = i + 1 print t.get_string(hrules=HEADER) print print "Targets" t = PrettyTable(['sel', 'target', 'hp', 'ac', 'disabled']) i = 1 for m in others: if m.disabled: disabled = 'Yes' else: disabled = 'No' t.add_row([i, m.name, m.cur_hp, m.ac, disabled]) i = i + 1 print t.get_string(hrules=HEADER) print show_player_status(attacker) #get input valid = False target = None while not valid: print sel = get_input( attacker.name + " - Enter number of sel action (and optional sel target) -> ") iAction = 0 iTarget = 0 try: if(sel.find(' ') != -1): args = sel.split(' ') if len(args) == 2: iAction = int(args[0]) iTarget = int(args[1]) else: iAction = int(sel) except: pass if iAction > 0 and iAction <= len(actions): if iTarget != 0: if iTarget > 0 and iTarget <= len(others): target = others[iTarget - 1] while target is None or not target.is_alive(): if iTarget < 0 or iTarget >= len(others): iTarget = 0 target = others[iTarget] iTarget += 1 valid = True return [actions[iAction - 1], target ] def random_action_target(monster, players, player_actions): if len(players) == 0 or all_dead(players): return [None, None, None] iAction = random.randint(0, len(monster.attacks) - 1) iPlayer = random.randint(0, len(players) - 1) while not players[iPlayer].is_alive(): iPlayer = random.randint(0, len(players) - 1) return [ monster.attacks[iAction], players[iPlayer], player_actions[iPlayer] ] def random_target(monster, attack, players, player_actions): if len(players) == 0 or all_dead(players): return [None, None, None] iPlayer = random.randint(0, len(players) - 1) while not players[iPlayer].is_alive(): iPlayer = random.randint(0, len(players) - 1) return [ attack, players[iPlayer], player_actions[iPlayer] ] def show_player_status(p): if p.is_trapped(): print p.get_trapped_desc() elif p.is_disabled(): print p.name, 'hp:', p.cur_hp, ' is disabled!' else: print p.name, 'hp:', p.cur_hp, 'ac:', p.get_ac(), 'mana:', p.cur_mana def party_comment(comment, party): for p in party: if p.is_alive(): print comment % p.name break def show_status(players): print 'Status:' for p in players: show_player_status(p) print def award_experience(players, monsters): exp_total = 0 for m in monsters: m.on_combat_end() if not m.is_alive(): exp_total += m.xp_award total_living_players = 0 for p in players: p.on_combat_end() if p.is_alive(): total_living_players += 1 if total_living_players == 0: return reward = exp_total / total_living_players for p in players: if p.is_alive() and reward > 0: p.add_xp( reward ) def one_dead(group): d = 0 for m in group: if not m.is_alive(): d = d + 1 return d == 1 def half_dead(group): d = 0 for m in group: if not m.is_alive(): d = d + 1 return d == int(len(group) / 2) #a list of the player targets. We adjust the frequency of monster focus #by adding attacking players 3 times, spell or blocking characters once. def add_player_target(player, action, player_targets, player_actions): if player.is_hidden(): return if action.is_weapon(): player_targets.append(player) player_targets.append(player) player_actions.append(action) player_actions.append(action) player_targets.append(player) player_actions.append(action) def get_tohit_mod(round): #to simulate fatigue and increasing #likeliness to give and receive damage, #adjust to hit up as rounds go on. #Also helps reduce super long slogging battles #where everyone misses. tohit_mod = round / 2 #cap it at a ridiculous 10. Though 30 rounds is a SUPER long battle. if tohit_mod > 10: tohit_mod = 10 return tohit_mod def fight(players, monsters, room, level, mon_attack_first): done = False round = 1 moral_check_on_first_dead = False moral_check_on_half_dead = False level.combat_stats = CombatStats() while not done: print '-------------------------------------------------------' print 'Round', round, '\n' #make sure the armor class is up to date. for p in players: p.update_armor_class() #show all player status show_status(players) #adjust tohit modifiers to account for fatigue tohit_mod = get_tohit_mod(round) #a list of the player targets. We adjust the frequency of monster focus #by adding attacking players 3 times, spell or blocking characters once. player_targets = [] player_actions = [] for player in players: if not player.is_alive(): continue if all_dead(monsters): continue if mon_attack_first: add_player_target(player, CombatAction('suprised', ''), player_targets, player_actions) continue if player.is_disabled() or player.is_trapped(): add_player_target(player, CombatAction('disabled', ''), player_targets, player_actions) continue action, target = choose_action_and_target(player, monsters) if action is None: continue if action.is_spell(): player.cur_mana -= action.mana #wearing armor incurs a 1 pt mana expense if player.is_wearing_non_magic_armor(): player.cur_mana -= 1 if action.targets_environment(): action.cast_at_environ(player, monsters, players, room, level) elif target is None or action.targets_group(): action.cast(player, monsters, players) else: action.cast_at_target(player, target) elif action.is_weapon(): if target is None: action.attack(player, monsters, players, tohit_mod) else: action.attack_target(player, target, tohit_mod) elif action.is_combat_action(): if action.name == 'block': hp_rec = HP_RECOVERED_FROM_REST * player.level if player.cur_hp <= (player.hp / 2) - hp_rec: player.cur_hp += hp_rec print player.name, 'regains', hp_rec, 'hp after blocking and resting.' elif action.name == 'run': num_items = len(player.inventory) if num_items > 0: iDrop = random.randint(0, num_items - 1) item = player.inventory[iDrop] if not item.is_weapon() and not item.is_spell() and not item.is_armor(): print player.name, 'bolts for the door and drops his', item.name, 'in haste!' player.remove(item.name) room.items.append(item) award_experience(players, monsters) #all monsters heal when you leave. for m in monsters: if m.is_alive(): m.cur_hp = m.hp pause() return "run" elif action.name == 'hide': roll = random.randint(1, 20) print player.name, 'rolls %d.' % roll if roll >= player.get_hide_roll_thresh(): print player.name, 'slips into the shadows silently.' player.set_hidden(True) else: print player.name, 'was not able to hide.' elif action.name == 'draw': room.activate([player]) elif action.name == 'drink': player.drink_potion() elif action.name == 'read': player.read_scroll(monsters, players, room, level) elif action.name == 'wand': player.use_wand(monsters, players, room, level) pause() if player.is_hidden(): if action.is_spell() or action.is_weapon(): player.set_hidden(False) elif action.name != 'run': hp_rec = HP_RECOVERED_FROM_REST * player.level if player.cur_hp <= (player.hp / 2) - hp_rec: player.cur_hp += hp_rec print player.name, 'regains', hp_rec, 'hp while hiding.' add_player_target(player, action, player_targets, player_actions) #check for morale of monsters if not moral_check_on_first_dead and one_dead(monsters) and len(monsters) > 1: moral_check_on_first_dead = True if random.randint(1, 10) < 4: print 'The rest of the creatures flee in terror!' award_experience(players, monsters) return 'won' if not moral_check_on_half_dead and half_dead(monsters) and len(monsters) > 3: moral_check_on_half_dead = True if random.randint(1, 10) < 5: print 'The rest of the creatures flee in terror!' award_experience(players, monsters) return 'won' #only use once. Surprise attack if mon_attack_first: if random.randint(1, 2) < 2: print "It's a surprise attack!" tohit_mod += 2 else: party_comment('%s yells, "Look out!"', players) mon_attack_first = False for monster in monsters: action = monster.take_combat_turn(player_targets, player_actions, room, level, tohit_mod) if action and action.name == 'run': monsters.remove(monster) if all_dead(monsters): print "You defeated all the enemies!!\n" sitch = [WON] print_comment(sitch, players, room, level) award_experience(players, monsters) return 'won' if all_dead(players): print 'And everything fades to black. Better to have run.. oh well!!' return 'died' for monster in monsters: if monster.is_alive(): monster.on_combat_round_ended() for player in players: if player.is_alive(): player.on_combat_round_ended() print round = round + 1
en
0.868608
#casting spells while in armor happens at a deficit #get input #a list of the player targets. We adjust the frequency of monster focus #by adding attacking players 3 times, spell or blocking characters once. #to simulate fatigue and increasing #likeliness to give and receive damage, #adjust to hit up as rounds go on. #Also helps reduce super long slogging battles #where everyone misses. #cap it at a ridiculous 10. Though 30 rounds is a SUPER long battle. #make sure the armor class is up to date. #show all player status #adjust tohit modifiers to account for fatigue #a list of the player targets. We adjust the frequency of monster focus #by adding attacking players 3 times, spell or blocking characters once. #wearing armor incurs a 1 pt mana expense #all monsters heal when you leave. #check for morale of monsters #only use once. Surprise attack
2.874856
3
app/forms/UpdatePasswordForm.py
jonzxz/project-piscator
0
6624291
<reponame>jonzxz/project-piscator<filename>app/forms/UpdatePasswordForm.py from flask_wtf import FlaskForm from app.models import User from wtforms import PasswordField, SubmitField, DecimalField from wtforms.validators import DataRequired # WTForm for updating password after request for password reset class UpdatePasswordForm(FlaskForm): token = DecimalField('Six Digit Code'\ , render_kw={"placeholder" : "Six-digit code"}, validators=[DataRequired()]) new_password = PasswordField('<PASSWORD>'\ , render_kw={"placeholder" : "New Password"}, validators=[DataRequired()]) submit = SubmitField('Reset')
from flask_wtf import FlaskForm from app.models import User from wtforms import PasswordField, SubmitField, DecimalField from wtforms.validators import DataRequired # WTForm for updating password after request for password reset class UpdatePasswordForm(FlaskForm): token = DecimalField('Six Digit Code'\ , render_kw={"placeholder" : "Six-digit code"}, validators=[DataRequired()]) new_password = PasswordField('<PASSWORD>'\ , render_kw={"placeholder" : "New Password"}, validators=[DataRequired()]) submit = SubmitField('Reset')
en
0.790713
# WTForm for updating password after request for password reset
2.74826
3
mmdglm/convkernels/base.py
adehad/mmd-glm
0
6624292
<filename>mmdglm/convkernels/base.py<gh_stars>0 import numpy as np import matplotlib.pyplot as plt from scipy.signal import fftconvolve import torch from ..utils import get_arg_support, get_dt, searchsorted class Kernel: def __init__(self): pass def interpolate(self, t): pass def interpolate_basis(self, t): pass def convolve_continuous(self, t, x): """Implements the convolution of a time series with the kernel using scipy fftconvolve. Args: t (array): time points x (array): time series to be convolved mode (str): Returns: array: convolved time series """ dt = get_dt(t) arg_support0, arg_supportf = get_arg_support(dt, self.support) t_support = np.arange(arg_support0, arg_supportf, 1) * dt kernel_values = self.interpolate(t_support) shape = (kernel_values.shape[0], ) + tuple([1] * (x.ndim - 1)) kernel_values = kernel_values.reshape(shape) convolution = np.zeros(x.shape) full_convolution = fftconvolve(kernel_values, x, mode='full', axes=0) if arg_support0 >= 0: convolution[arg_support0:, ...] = full_convolution[:len(t) - arg_support0, ...] elif arg_support0 < 0 and arg_supportf >= 0: # or to arg_support0 < 0 and len(t) - arg_support0 <= len(t) + arg_supportf - arg_support0: convolution = full_convolution[-arg_support0:len(t) - arg_support0, ...] else: # or arg0 < 0 and len(t) - arg0 > len(t) + arg_supportf - arg0: convolution[:len(t) + arg_supportf, ...] = full_convolution[-arg_supportf:, ...] convolution *= dt return torch.from_numpy(convolution) def convolve_discrete(self, t, s, A=None, shape=None, renewal=False): """Implements the convolution of discrete events in time with the kernel Args: t (array): time points s (array): time events mode (str): Returns: array: convolved time series """ if type(s) is not tuple: s = (s,) if A is None: A = (1. for ii in range(s[0].size)) if shape is None: shape = tuple([max(s[dim]) + 1 for dim in range(1, len(s))]) arg_s = searchsorted(t, s[0]) arg_s = np.atleast_1d(arg_s) convolution = np.zeros((len(t), ) + shape) for ii, (arg, A) in enumerate(zip(arg_s, A)): index = tuple([slice(arg, None)] + [s[dim][ii] for dim in range(1, len(s))]) if not(renewal): convolution[index] += A * self.interpolate(t[arg:] - t[arg]) else: convolution[index] = A * self.interpolate(t[arg:] - t[arg]) return torch.from_numpy(convolution) def fit(self, t, input, output, mask=None): if mask is None: mask = np.ones(input.shape, dtype=bool) X = self.convolve_basis_continuous(t, input) X = X[mask, :] output = output[mask] self.coefs = np.linalg.lstsq(X, output, rcond=None)[0] def correlate_continuous(self, t, x): return self.convolve_continuous(t, x[::-1])[::-1] def plot(self, t=None, ax=None, offset=0, invert_t=False, invert_values=False, gain=False, **kwargs): if t is None: t = np.arange(self.support[0], self.support[1] + self.dt, self.dt) if ax is None: fig, ax = plt.subplots() y = self.interpolate(t) + offset if invert_t: t = -t if invert_values: y = -y if gain: y = np.exp(y) ax.plot(t, y, **kwargs) return ax
<filename>mmdglm/convkernels/base.py<gh_stars>0 import numpy as np import matplotlib.pyplot as plt from scipy.signal import fftconvolve import torch from ..utils import get_arg_support, get_dt, searchsorted class Kernel: def __init__(self): pass def interpolate(self, t): pass def interpolate_basis(self, t): pass def convolve_continuous(self, t, x): """Implements the convolution of a time series with the kernel using scipy fftconvolve. Args: t (array): time points x (array): time series to be convolved mode (str): Returns: array: convolved time series """ dt = get_dt(t) arg_support0, arg_supportf = get_arg_support(dt, self.support) t_support = np.arange(arg_support0, arg_supportf, 1) * dt kernel_values = self.interpolate(t_support) shape = (kernel_values.shape[0], ) + tuple([1] * (x.ndim - 1)) kernel_values = kernel_values.reshape(shape) convolution = np.zeros(x.shape) full_convolution = fftconvolve(kernel_values, x, mode='full', axes=0) if arg_support0 >= 0: convolution[arg_support0:, ...] = full_convolution[:len(t) - arg_support0, ...] elif arg_support0 < 0 and arg_supportf >= 0: # or to arg_support0 < 0 and len(t) - arg_support0 <= len(t) + arg_supportf - arg_support0: convolution = full_convolution[-arg_support0:len(t) - arg_support0, ...] else: # or arg0 < 0 and len(t) - arg0 > len(t) + arg_supportf - arg0: convolution[:len(t) + arg_supportf, ...] = full_convolution[-arg_supportf:, ...] convolution *= dt return torch.from_numpy(convolution) def convolve_discrete(self, t, s, A=None, shape=None, renewal=False): """Implements the convolution of discrete events in time with the kernel Args: t (array): time points s (array): time events mode (str): Returns: array: convolved time series """ if type(s) is not tuple: s = (s,) if A is None: A = (1. for ii in range(s[0].size)) if shape is None: shape = tuple([max(s[dim]) + 1 for dim in range(1, len(s))]) arg_s = searchsorted(t, s[0]) arg_s = np.atleast_1d(arg_s) convolution = np.zeros((len(t), ) + shape) for ii, (arg, A) in enumerate(zip(arg_s, A)): index = tuple([slice(arg, None)] + [s[dim][ii] for dim in range(1, len(s))]) if not(renewal): convolution[index] += A * self.interpolate(t[arg:] - t[arg]) else: convolution[index] = A * self.interpolate(t[arg:] - t[arg]) return torch.from_numpy(convolution) def fit(self, t, input, output, mask=None): if mask is None: mask = np.ones(input.shape, dtype=bool) X = self.convolve_basis_continuous(t, input) X = X[mask, :] output = output[mask] self.coefs = np.linalg.lstsq(X, output, rcond=None)[0] def correlate_continuous(self, t, x): return self.convolve_continuous(t, x[::-1])[::-1] def plot(self, t=None, ax=None, offset=0, invert_t=False, invert_values=False, gain=False, **kwargs): if t is None: t = np.arange(self.support[0], self.support[1] + self.dt, self.dt) if ax is None: fig, ax = plt.subplots() y = self.interpolate(t) + offset if invert_t: t = -t if invert_values: y = -y if gain: y = np.exp(y) ax.plot(t, y, **kwargs) return ax
en
0.672171
Implements the convolution of a time series with the kernel using scipy fftconvolve. Args: t (array): time points x (array): time series to be convolved mode (str): Returns: array: convolved time series # or to arg_support0 < 0 and len(t) - arg_support0 <= len(t) + arg_supportf - arg_support0: # or arg0 < 0 and len(t) - arg0 > len(t) + arg_supportf - arg0: Implements the convolution of discrete events in time with the kernel Args: t (array): time points s (array): time events mode (str): Returns: array: convolved time series
2.177561
2
dangdang/dangdang/spiders/dd.py
ValueXu/DangDangScrapy
1
6624293
<reponame>ValueXu/DangDangScrapy # -*- coding: utf-8 -*- import scrapy from dangdang.items import DangdangItem from scrapy.http import Request class Ddspider(scrapy.Spider): name = "dd" allowed_domains = ["dangdang.com"] start_urls = ('http://www.dangdang.com/',) def parse(self, response): item=DangdangItem() item["title"]=response.xpath("//a[@class='pic']/@title").extract() item["link"] = response.xpath("//a[@class='pic']/@href").extract() item["comment"] = response.xpath("//a[@name='itemlist-review']/text()").extract() item["price"]=response.xpath("//p[@class='price']/span[@class='search_now_price']/text()").extract() yield item for i in range(2,101): url="http://category.dangdang.com/pg" +str(i)+"-cp01.54.06.00.00.00.html" yield Request(url,callback=self.parse)
# -*- coding: utf-8 -*- import scrapy from dangdang.items import DangdangItem from scrapy.http import Request class Ddspider(scrapy.Spider): name = "dd" allowed_domains = ["dangdang.com"] start_urls = ('http://www.dangdang.com/',) def parse(self, response): item=DangdangItem() item["title"]=response.xpath("//a[@class='pic']/@title").extract() item["link"] = response.xpath("//a[@class='pic']/@href").extract() item["comment"] = response.xpath("//a[@name='itemlist-review']/text()").extract() item["price"]=response.xpath("//p[@class='price']/span[@class='search_now_price']/text()").extract() yield item for i in range(2,101): url="http://category.dangdang.com/pg" +str(i)+"-cp01.54.06.00.00.00.html" yield Request(url,callback=self.parse)
en
0.769321
# -*- coding: utf-8 -*-
3.02353
3
033_Search_in_Rotated_Sorted_Array.py
adwardlee/leetcode_solutions
0
6624294
<reponame>adwardlee/leetcode_solutions<gh_stars>0 ''' Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 ''' class Solution: def search(self, nums, target: int) -> int: self.nums = nums length = len(nums) if length == 0: return -1 left = 0 right = length - 1 mid = (left + right) // 2 return max(self.quicksort(left, mid, target), self.quicksort(mid + 1, right, target)) def quicksort(self, left, right, target): if left > right: return -1 if left == right: if self.nums[left] == target: return left else: return -1 mid = (left + right) // 2 if self.nums[mid] == target: return mid if self.nums[left] < self.nums[right]: if self.nums[left] <= target and target <= self.nums[right]: return max(self.quicksort(left, mid, target), self.quicksort(mid + 1, right, target)) else: return -1 else: if self.nums[left] > target and self.nums[right] < target: return -1 else: return max(self.quicksort(left, mid, target), self.quicksort(mid + 1, right, target))
''' Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 ''' class Solution: def search(self, nums, target: int) -> int: self.nums = nums length = len(nums) if length == 0: return -1 left = 0 right = length - 1 mid = (left + right) // 2 return max(self.quicksort(left, mid, target), self.quicksort(mid + 1, right, target)) def quicksort(self, left, right, target): if left > right: return -1 if left == right: if self.nums[left] == target: return left else: return -1 mid = (left + right) // 2 if self.nums[mid] == target: return mid if self.nums[left] < self.nums[right]: if self.nums[left] <= target and target <= self.nums[right]: return max(self.quicksort(left, mid, target), self.quicksort(mid + 1, right, target)) else: return -1 else: if self.nums[left] > target and self.nums[right] < target: return -1 else: return max(self.quicksort(left, mid, target), self.quicksort(mid + 1, right, target))
en
0.879945
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1
3.962535
4
gsm_layer3_protocol/sms_protocol/rp_data.py
matan1008/gsm-layer3-protocol
0
6624295
<filename>gsm_layer3_protocol/sms_protocol/rp_data.py from construct import * from gsm_layer3_protocol.enums import rp_mti from gsm_layer3_protocol.sms_protocol.called_party_bcd_address import zero_lengthed_bcd_address, service_center_address from gsm_layer3_protocol.sms_protocol.sms_submit import sms_submit_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_command import sms_command_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_deliver import sms_deliver_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_status_report import sms_status_report_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_submit_report_rp_ack import sms_submit_report_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_deliver_report_rp_ack import sms_deliver_report_tpdu_struct class RpDataMsToN(Container): def __init__(self, message_reference, rp_destination_address, tpdu=None): super().__init__(message_reference=message_reference, rp_originator_address=None, rp_destination_address=rp_destination_address, rp_user_data={"tpdu": tpdu}) class RpDataNToMs(Container): def __init__(self, message_reference, rp_originator_address, tpdu=None): super().__init__(message_reference=message_reference, rp_originator_address=rp_originator_address, rp_destination_address=None, rp_user_data={"tpdu": tpdu}) rp_data_struct = Struct( "message_reference" / Byte, "rp_originator_address" / IfThenElse(this._.mti == rp_mti.RP_DATA_MS_TO_N, zero_lengthed_bcd_address, service_center_address), "rp_destination_address" / IfThenElse(this._.mti == rp_mti.RP_DATA_MS_TO_N, service_center_address, zero_lengthed_bcd_address), "rp_user_data" / Struct("tpdu" / Prefixed( "tpdu_length" / Byte, IfThenElse( this._._.mti == rp_mti.RP_DATA_MS_TO_N, Select(sms_deliver_report_tpdu_struct, sms_command_tpdu_struct, sms_submit_tpdu_struct), Select(sms_deliver_tpdu_struct, sms_status_report_tpdu_struct, sms_submit_report_tpdu_struct) ) )) )
<filename>gsm_layer3_protocol/sms_protocol/rp_data.py from construct import * from gsm_layer3_protocol.enums import rp_mti from gsm_layer3_protocol.sms_protocol.called_party_bcd_address import zero_lengthed_bcd_address, service_center_address from gsm_layer3_protocol.sms_protocol.sms_submit import sms_submit_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_command import sms_command_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_deliver import sms_deliver_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_status_report import sms_status_report_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_submit_report_rp_ack import sms_submit_report_tpdu_struct from gsm_layer3_protocol.sms_protocol.sms_deliver_report_rp_ack import sms_deliver_report_tpdu_struct class RpDataMsToN(Container): def __init__(self, message_reference, rp_destination_address, tpdu=None): super().__init__(message_reference=message_reference, rp_originator_address=None, rp_destination_address=rp_destination_address, rp_user_data={"tpdu": tpdu}) class RpDataNToMs(Container): def __init__(self, message_reference, rp_originator_address, tpdu=None): super().__init__(message_reference=message_reference, rp_originator_address=rp_originator_address, rp_destination_address=None, rp_user_data={"tpdu": tpdu}) rp_data_struct = Struct( "message_reference" / Byte, "rp_originator_address" / IfThenElse(this._.mti == rp_mti.RP_DATA_MS_TO_N, zero_lengthed_bcd_address, service_center_address), "rp_destination_address" / IfThenElse(this._.mti == rp_mti.RP_DATA_MS_TO_N, service_center_address, zero_lengthed_bcd_address), "rp_user_data" / Struct("tpdu" / Prefixed( "tpdu_length" / Byte, IfThenElse( this._._.mti == rp_mti.RP_DATA_MS_TO_N, Select(sms_deliver_report_tpdu_struct, sms_command_tpdu_struct, sms_submit_tpdu_struct), Select(sms_deliver_tpdu_struct, sms_status_report_tpdu_struct, sms_submit_report_tpdu_struct) ) )) )
none
1
2.195377
2
_BACKUPS_v3/v3_1/LightPicture_Test.py
nagame/LightPicture
0
6624296
from LightPicture import * import unittest class TestConstructor_Coordinate(unittest.TestCase): """ Test Coordinate class calls """ def test_none(self): """ Calling Coordinates class with no key (kay = None) """ c0 = Coordinates() self.assertIsNot(c0, None) self.assertIsInstance(c0, Coordinates) def test_iterable(self): """ Calling Coordinates class with key conaining simple types """ c0 = Coordinates([1]) self.assertIsNot(c0, None) self.assertIsInstance(c0, Coordinates) c1 = Coordinates([1, 2, 3]) self.assertIsNot(c1, None) self.assertIsInstance(c1, Coordinates) c2 = Coordinates('xyz') c3 = Coordinates(['x', 'y', 'z', 5]) self.assertIsNot(c2, None) self.assertIsInstance(c2, Coordinates) def test_iterable_specific(self): """ Calling Coordinates class with key containing specific types """ # Call Coordinates object with Vertex object as key v = Vertex() c = Coordinates(v) self.assertIsInstance(c, Coordinates) # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # # Check auto reference building and synchronisation # # between Vertex and Coordinates # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # Action: Coordinate class call with Vertex object as key # Expect: Vertex object assigns Coordinates object as self coordinates a_v0 = Vertex() a_c0 = Coordinates(a_v0) a_r0 = a_v0.coordinates() self.assertIs(a_r0, a_c0) # Action: Coordinate class call with Vertex object as key # Expect: Vertex object is 'parent' of Coordinate object b_v0 = Vertex() b_c0 = Coordinates(b_v0) b_r0 = b_c0.parents() b_pass = b_v0 in b_r0 self.assertIs(b_pass, True) class TestConstructor_Vertex(unittest.TestCase): """ Test Vertex class calls """ def test_none(self): """ Calling Vertex class with no key (key = None) """ v0 = Vertex() self.assertIsNot(v0, None) self.assertIsInstance(v0, Vertex) def test_iterable_simple(self): """ Calling Vertex class with key containing simple types """ v0 = Vertex([1]) self.assertIsNot(v0, None) self.assertIsInstance(v0, Vertex) v1 = Vertex([1, 2, 3]) self.assertIsNot(v1, None) self.assertIsInstance(v1, Vertex) # check if Vertex has built a Coordinates object using the iterable passed as key self.assertIsInstance(v1.coordinates(), Coordinates) v2 = Vertex('xyz') self.assertIsNot(v2, None) self.assertIsInstance(v2, Vertex) self.assertIsInstance(v2.coordinates(), Coordinates) v3 = Vertex(['x', 'y', 'z', 5]) self.assertIsNot(v3, None) self.assertIsInstance(v3, Vertex) self.assertIsInstance(v3.coordinates(), Coordinates) def test_iterable_specific(self): """ Calling Vertex class with key containing specific types """ # Call Vertex class with Coordinate object as key c = Coordinates() v = Vertex(c) self.assertIsInstance(v, Vertex) # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # # Check auto reference building # # between Vertex and Coordinates # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # Action: Vertex class call with Coordinate object as key # Expect: Vertex object assigns Coordinates object as self coordinates a_c0 = Coordinates([11, 12, 13]) a_v0 = Vertex(a_c0) a_r0 = a_v0.coordinates() self.assertIs(a_r0, a_c0) # Action: Vertex class call with Coordinate object as key # Expect: Vertex object is 'parent' of Coordinate object b_c0 = Coordinates([11, 12, 13]) b_v0 = Vertex(b_c0) b_r0 = b_c0.parents() b_pass = b_v0 in b_r0 self.assertIs(b_pass, True) class TestConstructor_Triangle(unittest.TestCase): """ Test Triangle class call """ def test_none(self): """ Calling Triangle class with no key (key = None) """ t0 = Triangle() self.assertIsNot(t0, None) self.assertIsInstance(t0, Triangle) def test_iterable(self): """ Calling Vertex class with iterable key """ # simple types iterables t1 = Triangle([1, 2, 3]) self.assertIsNot(t1, None) self.assertIsInstance(t1, Triangle) t2 = Triangle('xyz') self.assertIsNot(t2, None) self.assertIsInstance(t2, Triangle) t3 = Triangle(['x', 'y', 'z']) self.assertIsNot(t3, None) self.assertIsInstance(t3, Triangle) # check vertices assignment t1 = Triangle([1001, 1002, 1003]) self.assertIsNot(t1, None) self.assertIsInstance(t1, Triangle) result = t1.vertices() self.assertIsInstance(result, list) [r0, r1, r2] = result self.assertEqual(r0, 1001) self.assertEqual(r1, 1002) self.assertEqual(r2, 1003) t2 = Triangle('xyz') self.assertIsNot(t2, None) self.assertIsInstance(t2, Triangle) t3 = Triangle(['x', 'y', 'z']) self.assertIsNot(t3, None) self.assertIsInstance(t3, Triangle) def test_iterable_specific(self): """ Calling Vertex class with key containing specific types """ # Action: Triangle class call with Coordinate object as key # Expects: Vertex assigns Coordinates object as self coordinates c0 = Coordinates() c1 = Coordinates() c2 = Coordinates() t0 = Triangle([c0, c1, c2]) self.assertIsInstance(t0, Triangle) class TestTemporary(unittest.TestCase): """ Temporary tests or test currently in development """ def test_draft(self): pass if __name__ == '__main__': unittest.main()
from LightPicture import * import unittest class TestConstructor_Coordinate(unittest.TestCase): """ Test Coordinate class calls """ def test_none(self): """ Calling Coordinates class with no key (kay = None) """ c0 = Coordinates() self.assertIsNot(c0, None) self.assertIsInstance(c0, Coordinates) def test_iterable(self): """ Calling Coordinates class with key conaining simple types """ c0 = Coordinates([1]) self.assertIsNot(c0, None) self.assertIsInstance(c0, Coordinates) c1 = Coordinates([1, 2, 3]) self.assertIsNot(c1, None) self.assertIsInstance(c1, Coordinates) c2 = Coordinates('xyz') c3 = Coordinates(['x', 'y', 'z', 5]) self.assertIsNot(c2, None) self.assertIsInstance(c2, Coordinates) def test_iterable_specific(self): """ Calling Coordinates class with key containing specific types """ # Call Coordinates object with Vertex object as key v = Vertex() c = Coordinates(v) self.assertIsInstance(c, Coordinates) # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # # Check auto reference building and synchronisation # # between Vertex and Coordinates # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # Action: Coordinate class call with Vertex object as key # Expect: Vertex object assigns Coordinates object as self coordinates a_v0 = Vertex() a_c0 = Coordinates(a_v0) a_r0 = a_v0.coordinates() self.assertIs(a_r0, a_c0) # Action: Coordinate class call with Vertex object as key # Expect: Vertex object is 'parent' of Coordinate object b_v0 = Vertex() b_c0 = Coordinates(b_v0) b_r0 = b_c0.parents() b_pass = b_v0 in b_r0 self.assertIs(b_pass, True) class TestConstructor_Vertex(unittest.TestCase): """ Test Vertex class calls """ def test_none(self): """ Calling Vertex class with no key (key = None) """ v0 = Vertex() self.assertIsNot(v0, None) self.assertIsInstance(v0, Vertex) def test_iterable_simple(self): """ Calling Vertex class with key containing simple types """ v0 = Vertex([1]) self.assertIsNot(v0, None) self.assertIsInstance(v0, Vertex) v1 = Vertex([1, 2, 3]) self.assertIsNot(v1, None) self.assertIsInstance(v1, Vertex) # check if Vertex has built a Coordinates object using the iterable passed as key self.assertIsInstance(v1.coordinates(), Coordinates) v2 = Vertex('xyz') self.assertIsNot(v2, None) self.assertIsInstance(v2, Vertex) self.assertIsInstance(v2.coordinates(), Coordinates) v3 = Vertex(['x', 'y', 'z', 5]) self.assertIsNot(v3, None) self.assertIsInstance(v3, Vertex) self.assertIsInstance(v3.coordinates(), Coordinates) def test_iterable_specific(self): """ Calling Vertex class with key containing specific types """ # Call Vertex class with Coordinate object as key c = Coordinates() v = Vertex(c) self.assertIsInstance(v, Vertex) # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # # Check auto reference building # # between Vertex and Coordinates # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # Action: Vertex class call with Coordinate object as key # Expect: Vertex object assigns Coordinates object as self coordinates a_c0 = Coordinates([11, 12, 13]) a_v0 = Vertex(a_c0) a_r0 = a_v0.coordinates() self.assertIs(a_r0, a_c0) # Action: Vertex class call with Coordinate object as key # Expect: Vertex object is 'parent' of Coordinate object b_c0 = Coordinates([11, 12, 13]) b_v0 = Vertex(b_c0) b_r0 = b_c0.parents() b_pass = b_v0 in b_r0 self.assertIs(b_pass, True) class TestConstructor_Triangle(unittest.TestCase): """ Test Triangle class call """ def test_none(self): """ Calling Triangle class with no key (key = None) """ t0 = Triangle() self.assertIsNot(t0, None) self.assertIsInstance(t0, Triangle) def test_iterable(self): """ Calling Vertex class with iterable key """ # simple types iterables t1 = Triangle([1, 2, 3]) self.assertIsNot(t1, None) self.assertIsInstance(t1, Triangle) t2 = Triangle('xyz') self.assertIsNot(t2, None) self.assertIsInstance(t2, Triangle) t3 = Triangle(['x', 'y', 'z']) self.assertIsNot(t3, None) self.assertIsInstance(t3, Triangle) # check vertices assignment t1 = Triangle([1001, 1002, 1003]) self.assertIsNot(t1, None) self.assertIsInstance(t1, Triangle) result = t1.vertices() self.assertIsInstance(result, list) [r0, r1, r2] = result self.assertEqual(r0, 1001) self.assertEqual(r1, 1002) self.assertEqual(r2, 1003) t2 = Triangle('xyz') self.assertIsNot(t2, None) self.assertIsInstance(t2, Triangle) t3 = Triangle(['x', 'y', 'z']) self.assertIsNot(t3, None) self.assertIsInstance(t3, Triangle) def test_iterable_specific(self): """ Calling Vertex class with key containing specific types """ # Action: Triangle class call with Coordinate object as key # Expects: Vertex assigns Coordinates object as self coordinates c0 = Coordinates() c1 = Coordinates() c2 = Coordinates() t0 = Triangle([c0, c1, c2]) self.assertIsInstance(t0, Triangle) class TestTemporary(unittest.TestCase): """ Temporary tests or test currently in development """ def test_draft(self): pass if __name__ == '__main__': unittest.main()
en
0.914016
Test Coordinate class calls Calling Coordinates class with no key (kay = None) Calling Coordinates class with key conaining simple types Calling Coordinates class with key containing specific types # Call Coordinates object with Vertex object as key # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # # Check auto reference building and synchronisation # # between Vertex and Coordinates # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # Action: Coordinate class call with Vertex object as key # Expect: Vertex object assigns Coordinates object as self coordinates # Action: Coordinate class call with Vertex object as key # Expect: Vertex object is 'parent' of Coordinate object Test Vertex class calls Calling Vertex class with no key (key = None) Calling Vertex class with key containing simple types # check if Vertex has built a Coordinates object using the iterable passed as key Calling Vertex class with key containing specific types # Call Vertex class with Coordinate object as key # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # # Check auto reference building # # between Vertex and Coordinates # # = = = = = = = = = = = = = = = = = = = = = = = = = = = # Action: Vertex class call with Coordinate object as key # Expect: Vertex object assigns Coordinates object as self coordinates # Action: Vertex class call with Coordinate object as key # Expect: Vertex object is 'parent' of Coordinate object Test Triangle class call Calling Triangle class with no key (key = None) Calling Vertex class with iterable key # simple types iterables # check vertices assignment Calling Vertex class with key containing specific types # Action: Triangle class call with Coordinate object as key # Expects: Vertex assigns Coordinates object as self coordinates Temporary tests or test currently in development
3.026361
3
src/bot_cogs/minecraft.py
ryancflam/-findseed
0
6624297
<reponame>ryancflam/-findseed # Credit - https://github.com/Sharpieman20/Sharpies-Speedrunning-Tools # For blindtravel, doubletravel, educatedtravel, safeblind, triangulation # Credit - https://github.com/FourGoesFast/PerfectTravelBot # For divinetravel, perfecttravel from asyncio import TimeoutError from base64 import b64decode from json import loads from random import choice, randint from time import time import numpy as np from discord import Colour, Embed, File from discord.ext import commands from src.utils import funcs from src.utils.base_cog import BaseCog BARTER_LIMIT = 896 class Minecraft(BaseCog, name="Minecraft", description="Commands relating to *Minecraft* in general and *Minecraft: Java Edition* speedrunning."): def __init__(self, botInstance, *args, **kwargs): super().__init__(botInstance, *args, **kwargs) self.client.loop.create_task(self.__readFiles()) async def __readFiles(self): self.divinetravel = await funcs.readJson(funcs.getResource(self.name, "divine_travel.json")) self.perfecttravel = await funcs.readJson(funcs.getResource(self.name, "perfect_travel.json")) self.eyedata = await funcs.readJson(funcs.getResource(self.name, "eye_data.json")) self.loottable = await self.piglinLootTable() await funcs.generateJson( "findseed", { "calls": 0, "highest": { "found": 0, "number": 0, "time": int(time()) } } ) await funcs.generateJson("finddream", {"iteration": 0, "mostPearls": 0, "mostRods": 0}) async def piglinLootTable(self): lt = await funcs.readJson(funcs.getResource(self.name, "piglin_loot_table.json")) ltnew = [] for i in lt: if i["id"] < 5: item = i["item"] for j in range(1, 4): i["item"] = f"{item} {j}" for _ in range(i["weight"]): ltnew.append(i.copy()) i["id"] += 1 else: for _ in range(i["weight"] * 3): ltnew.append(i) return ltnew @staticmethod def randomEyes(): eyes = 0 for _ in range(12): eyes += 1 if funcs.oneIn(10) else 0 return eyes @staticmethod def getExcessStr(item): stacks, excess = funcs.stacksAndExcess(item) return "" if not stacks and excess == item \ else f" ({'{:,} stack{}'.format(stacks, '' if stacks == 1 else 's') if stacks else ''}" + \ f"{' + ' if stacks and excess else ''}{str(excess) if excess else ''})" @staticmethod def chargeableAnchors(glowdust: int, cryobby: int): return min([glowdust // 16, cryobby // 6]) @staticmethod def f3iProcessing(clipboard): try: args = clipboard.split(" ") return int(args[1]), int(args[2]), int(args[3]) except Exception: raise Exception("Invalid input. Please do not modify your F3+I clipboard.") @staticmethod def f3cProcessing(clipboard): try: args = clipboard.split(" ") return float(args[6]), float(args[8]), float(args[9]) % 360 except Exception: raise Exception("Invalid input. Please do not modify your F3+C clipboard.") @staticmethod def angleProcessing(angle): if angle >= 0: return (angle + 90) % 360 return (angle - 270) % 360 @staticmethod def coordsDist(x, z): return np.sqrt([x * x + z * z])[0] def coordsDifference(self, coords1: tuple, coords2: tuple): return self.coordsDist(coords1[0] - coords2[0], coords1[1] - coords2[1]) def strongholdCalc(self, x0, z0, f0, x1, z1, f1): a0 = np.tan([self.angleProcessing(f0) * np.pi / 180])[0] a1 = np.tan([self.angleProcessing(f1) * np.pi / 180])[0] b = z0 - x0 * a0 xp = ((z1 - x1 * a1) - b) / (a0 - a1) zp = xp * a0 + b blocks = round(self.coordsDifference((x1, z1), (xp, zp))) return xp, zp, blocks @commands.cooldown(1, 5, commands.BucketType.user) @commands.command(name="findseed", description="Everyone's favourite command. Test your luck using this command!", aliases=["fs", "seed", "findseeds", "f"]) async def findseed(self, ctx): eyes = self.randomEyes() data = await funcs.readJson("data/findseed.json") odds = self.eyedata[str(eyes)]["percent"] onein = self.eyedata[str(eyes)]["onein"] update = False if eyes >= data["highest"]["number"]: data["highest"]["found"] -= data["highest"]["found"] - 1 if eyes > data["highest"]["number"] else -1 data["highest"]["number"] = eyes data["highest"]["time"] = int(time()) update = True highest = data["highest"]["number"] highestTime = data["highest"]["time"] highestTotal = data["highest"]["found"] data["calls"] += 1 calls = data["calls"] await funcs.dumpJson("data/findseed.json", data) file = File( funcs.PATH + funcs.getResource(self.name, "portal_frame_images/") + f"{eyes}eye.png", filename="portal.png" ) foundTime = "just now" if not update: timestr = funcs.timeDifferenceStr(time(), highestTime) timestr_0 = int(timestr.split(" ")[0]) if timestr_0 > 2: foundTime = f"{timestr_0} days" else: foundTime = timestr e = Embed(title=f"{self.client.command_prefix}findseed", description=f"Requested by: {ctx.message.author.mention}") e.add_field(name="Your Eyes", value=f"`{eyes}`") e.add_field(name="Probability", value=f"`{odds}% (1 in {onein})`") e.add_field(name="Most Eyes Found", inline=False, value=f"`{highest} (last found {foundTime}{' ago' if not update else ''}" + f", found {'{:,}'.format(highestTotal)} time{'' if highestTotal == 1 else 's'})`") e.set_footer(text=f"The command has been called {'{:,}'.format(calls)} time{'' if calls == 1 else 's'}. !eyeodds") e.set_image(url="attachment://portal.png") await ctx.reply(embed=e, file=file) @commands.cooldown(1, 10, commands.BucketType.user) @commands.command(name="eyeodds", description="Shows the odds of getting each type of end portal.", aliases=["odds", "eyes", "eye", "eyeodd", "eyeood", "eyeoods"]) async def eyeodds(self, ctx): msg = "" for i in range(13): odds = self.eyedata[str(i)]["percent"] msg += f"{i} eye - `{odds}% (1 in {self.eyedata[str(i)]['onein']})`\n" await ctx.reply(msg) @commands.cooldown(1, 5, commands.BucketType.user) @commands.command(name="finddream", description="Can you get Dream's *Minecraft* speedrunning \"luck\"? " + "Test your luck using this command!", aliases=["dream", "dreamsimulator", "dreamsim", "dreamluck", "fd"], hidden=True) async def finddream(self, ctx): pearls, rods = 0, 0 dpearls, drods = 262, 305 data = await funcs.readJson("data/finddream.json") mostPearls = data["mostPearls"] mostRods = data["mostRods"] for _ in range(dpearls): pearls += 1 if randint(0, 422) < 20 else 0 for _ in range(drods): rods += 1 if funcs.oneIn(2) else 0 data["mostPearls"] = pearls if pearls >= mostPearls else mostPearls data["mostRods"] = rods if rods >= mostRods else mostRods data["iteration"] += 1 iters = data['iteration'] await funcs.dumpJson("data/finddream.json", data) e = Embed( title=f"{self.client.command_prefix}finddream", description=f"Dream got 42 ender pearl trades in {dpearls} plus 211 blaze rod drops in {drods}. " + f"Can you achieve his 'luck'?\n\nRequested by: {ctx.author.mention}" ) e.add_field(name="Your Pearl Trades", value=f"`{pearls} ({round(pearls / dpearls * 100, 3)}%)`") e.add_field(name="Your Rod Drops", value=f"`{rods} ({round(rods / drods * 100, 3)}%)`") e.set_footer( text=f"The command has been called {'{:,}'.format(iters)} time{'' if iters == 1 else 's'}. " + f"| Most pearl trades: {data['mostPearls']}; most rod drops: {data['mostRods']}" ) e.set_thumbnail(url="https://static.wikia.nocookie.net/dream_team/images/7/7b/Dream.jpeg") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findbreak", description="You throw an ender eye. Does it break or do you get to keep it?" + " Test your luck using this command!", aliases=["break", "eyebreak", "breakeye", "findeye"], hidden=True) async def findbreak(self, ctx): e = Embed(title=f"{self.client.command_prefix}findbreak", description=f"Requested by: {ctx.message.author.mention}") badluckonein = 5 goodluck = not funcs.oneIn(badluckonein) e.add_field(name="Result", value=f"`{'No Break!' if goodluck else 'Break...'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771404776410972161/938407577975418900/unknown.png") e.set_image(url="https://cdn.discordapp.com/attachments/771404776410972161/938408463946637312/2022-02-02_20.20.06.png" if goodluck else "https://media.discordapp.net/attachments/771404776410972161/938408658411327528/unknown.png") e.set_footer(text=f"Odds: {str(badluckonein - 1) if goodluck else '1'}/{str(badluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findcleric", description="Will you get the ender pearl trade from the cleric, " + "or will you get one-thirded? Test your luck using this command!", aliases=["cleric", "stupidvillager"], hidden=True) async def findcleric(self, ctx): e = Embed(title=f"{self.client.command_prefix}findcleric", description=f"Requested by: {ctx.message.author.mention}") badluckonein = 3 goodluck = not funcs.oneIn(badluckonein) e.add_field(name="Result", value=f"`{'Pearl' if goodluck else 'Bottle'} Trade{'!' if goodluck else '...'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771404776410972161/856203578615529532/cleric.png") e.set_image(url="https://media.discordapp.net/attachments/771404776410972161/856203574337601536/pearl.png" if goodluck else "https://media.discordapp.net/attachments/771404776410972161/856203573113520138/bottle.png") e.set_footer(text=f"Odds: {str(badluckonein - 1) if goodluck else '1'}/{str(badluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findgravel", description="Will you get flint from gravel? Test your luck using this command!", aliases=["gravel", "flint", "findflint", "fg"], hidden=True) async def findgravel(self, ctx): e = Embed(title=f"{self.client.command_prefix}findgravel", description=f"Requested by: {ctx.message.author.mention}") goodluckonein = 10 badluck = not funcs.oneIn(goodluckonein) e.add_field(name="Result", value=f"`{'Gravel' if badluck else 'Flint'}{'...' if badluck else '!'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771698457391136798/856209821383917608/gravel.png") e.set_image(url="https://media.discordapp.net/attachments/771698457391136798/856209821383917608/gravel.png" if badluck else "https://media.discordapp.net/attachments/771698457391136798/856209843174244362/flint.png") e.set_footer(text=f"Odds: {str(goodluckonein - 1) if badluck else '1'}/{str(goodluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findperch", description="You are in insane pace and about to kill the dragon..." + "but does it perch instantly? Test your luck using this command!", aliases=["dragon", "fp", "finddragon"], hidden=True) async def findperch(self, ctx): e = Embed(title=f"{self.client.command_prefix}findperch", description=f"Requested by: {ctx.message.author.mention}") goodluckonein = 13 badluck = not funcs.oneIn(goodluckonein) e.add_field(name="Result", value=f"`{'No Perch' if badluck else 'Perch'}{'...' if badluck else '!'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771404776410972161/928297045486370857/dragon.png") e.set_image(url="https://media.discordapp.net/attachments/771404776410972161/928299016259776613/2022-01-05_22.48.45.png" if badluck else "https://media.discordapp.net/attachments/771404776410972161/928298549861572638/2022-01-05_22.46.50.png") e.set_footer(text=f"Odds: {str(goodluckonein - 1) if badluck else '1'}/{str(goodluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findskull", description="You kill a wither skeleton...but does it drop a wither skull?" + " Test your luck using this command!", aliases=["skull", "witherskull", "findwitherskull", "findwither"], hidden=True) async def findskull(self, ctx): e = Embed(title=f"{self.client.command_prefix}findskull", description=f"Requested by: {ctx.message.author.mention}") goodluckonein = 40 badluck = not funcs.oneIn(goodluckonein) e.add_field(name="Result", value=f"`{'No Skull' if badluck else 'Skull'}{'...' if badluck else '!'}`") e.set_thumbnail(url="https://cdn.discordapp.com/attachments/771404776410972161/935204890639233054/unknown.png") e.set_image( url="" if badluck else "https://cdn.discordapp.com/attachments/771404776410972161/935204919651205250/unknown.png" ) e.set_footer(text=f"Odds: {str(goodluckonein - 1) if badluck else '1'}/{str(goodluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findblaze", description="You kill a blaze...but does it drop a rod? Test your luck using this command!", aliases=["rod", "blazerod", "findrod", "findblazerod"], hidden=True) async def findblaze(self, ctx): e = Embed(title=f"{self.client.command_prefix}findblaze", description=f"Requested by: {ctx.message.author.mention}") badluckonein = 2 goodluck = not funcs.oneIn(badluckonein) e.add_field(name="Result", value=f"`{'Rod' if goodluck else 'No Rod'} Drop{'!' if goodluck else '...'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771698457391136798/856213640809414666/blaze.png") e.set_image(url="https://media.discordapp.net/attachments/771698457391136798/856213641020178472/rod.png" if goodluck else "https://cdn.discordapp.com/attachments/771698457391136798/856213642173612032/norod.png") e.set_footer(text=f"Odds: {str(badluckonein - 1) if goodluck else '1'}/{str(badluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="perchcmd", description="Shows the command to force the the ender dragon perch.", aliases=["perch"]) async def perchcmd(self, ctx): await ctx.reply("```1.13+: /data merge entity @e[type=ender_dragon,limit=1] {DragonPhase:2}\n\n" + "1.9-1.12: /entitydata @e[type=ender_dragon] {DragonPhase:2}```") @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="logs", description="Calculates how many logs you will need to trade for a certain number of emeralds.", aliases=["log", "wood"], usage="<amount of emeralds needed>") async def logs(self, ctx, emeralds): try: emeralds = int(emeralds) if emeralds < 1: raise Exception log = emeralds * 4 await ctx.reply("You want **{:,}** emerald{}.\n\nYou will need **{:,}** logs{}.".format( emeralds, "" if emeralds == 1 else "s", int(log), self.getExcessStr(log) )) except Exception as ex: funcs.printError(ctx, ex) await ctx.reply( embed=funcs.errorEmbed(None, "Invalid input. Please make sure you are entering positive, non-zero integers.") ) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="haybales", aliases=["hay", "haybale"], usage="<amount of emeralds needed>", description="Calculates how many hay bales you will need to trade for a certain number of emeralds.") async def haybales(self, ctx, emeralds): try: emeralds = int(emeralds) if emeralds < 1: raise Exception hay = 20 * emeralds / 9 hay = funcs.strictRounding(hay) await ctx.reply("You want **{:,}** emerald{}.\n\nYou will need **{:,}** hay bales{}.".format( emeralds, "" if emeralds == 1 else "s", int(hay), self.getExcessStr(hay) )) except Exception as ex: funcs.printError(ctx, ex) await ctx.reply( embed=funcs.errorEmbed(None, "Invalid input. Please make sure you are entering positive, non-zero integers.") ) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="books", aliases=["book", "bookshelf", "bookshelves", "library"], usage="<books per emerald> <emeralds per eye> [eyes needed]", description="Calculates how many books you will need to get eyes of ender for pre-1.9 trading.") async def books(self, ctx, book, emeralds, eyes="12"): try: book = int(book) emeralds = int(emeralds) eyes = int(eyes) if not 8 <= book <= 10: return await ctx.send(embed=funcs.errorEmbed(None, "Books per emerald must be 8-10 inclusive.")) if not 7 <= emeralds <= 11: return await ctx.send(embed=funcs.errorEmbed(None, "Emeralds per eye must be 7-11 inclusive.")) if not 1 <= eyes <= 12: return await ctx.send(embed=funcs.errorEmbed(None, "Eyes needed must be 1-12 inclusive.")) totalEmeralds = emeralds * eyes totalBooks = totalEmeralds * book booksPerEye = emeralds * book bookshelves = funcs.strictRounding(totalBooks / 3) await ctx.send("You want **{}** eye{} of ender.\nThe librarian sells one emera".format(eyes, "" if eyes == 1 else "s") + "ld for **{}** books.\nThe cleric sells one eye of ender for **{}** emeralds.\n".format(book, emeralds) + "\nYou will need:\n\n**{:,}** books{} for a total of".format(totalBooks, self.getExcessStr(totalBooks)) + " **{}** emeralds{}\nBooks per eye:".format(totalEmeralds, self.getExcessStr(totalEmeralds)) + " **{}**\nBookshelves to break: **{}**\n\n".format(booksPerEye, bookshelves) + "Big library: 699 books\nSmall library: 483 books") except Exception as ex: funcs.printError(ctx, ex) await ctx.reply( embed=funcs.errorEmbed(None, "Invalid input.") ) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="anchors", description="Calculates how many chargeable respawn anchors you can craft based on how " + "much glowstone dust and crying obsidian you have.", aliases=["anchor"], usage="<amount of glowstone dust> <amount of crying obdisian>") async def anchors(self, ctx, glowdust, cryobby): try: glowdust = int(glowdust) cryobby = int(cryobby) if glowdust < 1 or cryobby < 1: raise Exception anchors = self.chargeableAnchors(glowdust, cryobby) charge = " and sufficiently charge {}".format("it" if anchors == 1 else "them") if anchors else "" await ctx.reply( "You have **{:,}** glowstone dust and **{:,}** crying obsidian.\n\nYou can make **".format(glowdust, cryobby) + "{:,}** respawn anchor{}{}.".format(anchors, "" if anchors == 1 else "s", charge) ) except Exception as ex: funcs.printError(ctx, ex) await ctx.reply( embed=funcs.errorEmbed(None, "Invalid input. Please make sure you are entering positive, non-zero integers.") ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(description="Simulates *Minecraft: Java Edition* 1.16.1 piglin bartering. Test your luck using this command!", aliases=["barter", "piglin", "poglin", "bartering", "barteringsim"], name="bartersim", usage=f"[gold ingots up to 10,000]\n\nAlternative usage(s):\n\n- <gold blocks up to 1,111 (ending with b)>") async def bartersim(self, ctx, goldingots: str="1"): try: try: goldingots = int(goldingots) except: goldingots = int(goldingots[:-1]) * 9 if not 0 < goldingots < 10001: return await ctx.reply(embed=funcs.errorEmbed(None, f"Value must be between 1 and 10,000.")) except ValueError: return await ctx.reply(embed=funcs.errorEmbed(None, "Invalid input.")) trades = {} string, glowdust, cryobby = 0, 0, 0 for _ in range(goldingots): trade = choice(self.loottable) if trade["id"] not in list(trades.keys()): trades[trade["id"]] = {} trades[trade["id"]]["item"] = trade["item"] n = choice(trade["quantity"]) trades[trade["id"]]["quantity"] = n trades[trade["id"]]["trades"] = 1 else: n = choice(trade["quantity"]) trades[trade["id"]]["quantity"] += n trades[trade["id"]]["trades"] += 1 if trade["id"] == 13: string += n elif trade["id"] == 10: glowdust += n elif trade["id"] == 19: cryobby += n res = "You bartered {:,} gold ingot{} for:\n\n".format(goldingots, "" if goldingots == 1 else "s") for i in sorted(trades): t = trades[i] res += "{}{:,} x {} ({:,} trade{})\n".format( "*** " if i in [7, 8, 10, 12, 13, 18, 19] else " ", t["quantity"], t["item"], t["trades"], "" if t["trades"] == 1 else "s" ) anchors = self.chargeableAnchors(glowdust, cryobby) beds = string // 12 explosives = anchors + beds if explosives: res += "\nExplosives you can craft ({:,}):\n\n".format(explosives) if beds: res += " {:,} x Bed\n".format(beds) if anchors: res += " {:,} x Respawn Anchor (w/ enough glowstone to power)".format(anchors) await ctx.reply(funcs.formatting(res)) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="pearlbarter", description="Finds the probability of getting 12 or more ender pearls" + " in a given number of piglin trades in *Minecraft* 1.16.1.", aliases=["pearltrade", "pearlbartering", "barteringpearl", "barterpearl", "barterpearls"], usage=f"[total gold ingots up to {BARTER_LIMIT}]") async def pearlbarter(self, ctx, trades: str="2"): try: n = int(trades) if not 2 <= n <= BARTER_LIMIT: return await ctx.reply(embed=funcs.errorEmbed(None, f"Value must be between 2 and {BARTER_LIMIT}.")) except ValueError: return await ctx.reply(embed=funcs.errorEmbed(None, "Invalid input.")) x = 1 - (403 / 423) ** n - n * (20 / 423) * ((403 / 423) ** (n - 1)) - (2 / 5) * (n * (n - 1) / 2) \ * ((403 / 423) ** (n - 2)) * ((20 / 423) ** 2) await ctx.reply(f"**[1.16.1]** The probability of getting 12 or more ender pearls" + f" with {n} gold ingots is:\n\n`{round(x * 100, 5)}%` (1 in {round(1 / x, 5)})") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="blindtravel", description="A *Minecraft: Java Edition* speedrunning tool that " + "should be used when you want to build another por" + "tal in the Nether before throwing any eyes of end" + "er. To use this command, in the game, press F3+C," + " pause, come over to Discord, paste your clipboar" + "d as an argument for the command, and then build " + "your portal at the suggested coordinates in the N" + "ether. This command is for versions 1.13+ and may " + "not be 100% accurate. This command MAY not be used" + " in a real speedrun.", aliases=["bt", "blind", "blindtrav"], usage="<F3+C data>") async def blindtravel(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, _ = self.f3cProcessing(f3c) dist = self.coordsDist(x, z) o = 190 if dist < 190 else dist if dist < 290 else 290 if dist < 442 else 580 if dist < 580 else dist \ if dist < 692 else 686 if dist < 825 else 970 if dist < 970 else dist if dist < 1060 else 1060 t = np.arctan([z / x])[0] xp = np.sign(x) * np.absolute([o * np.cos([t])[0]])[0] zp = np.sign(z) * np.absolute([o * np.sin([t])[0]])[0] blocks = round(self.coordsDifference((x, z), (xp, zp))) await ctx.reply( f"Build your portal at: **{round(xp)}, {round(zp)}** " + f"({'{:,}'.format(blocks)} block{'' if blocks == 1 else 's'} away)" ) except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="educatedtravel", description="A *Minecraft: Java Edition* speedrunning tool th" + "at should be used when you want to build anoth" + "er portal in the Nether after throwing an eye " + "of ender. To use this command, in the game, th" + "row an eye, stand still, put your mouse direct" + "ly over the eye, press F3+C, pause, come over " + "to Discord, paste your clipboard as an argumen" + "t for the command, and then build your portal " + "at the suggested coordinates in the Nether. Th" + "is command is for versions 1.13+ and may not be" + " 100% accurate. This command MAY not be used in" + " a real speedrun.", aliases=["et", "educated", "nethertravel"], usage="<F3+C data>") async def educatedtravel(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, f = self.f3cProcessing(f3c) f = (360 + f if f < 0 else f) - 180 o = 640 if self.coordsDist(x, z) > 3584 else 216 m1 = -np.tan([(90 - f) * (np.pi / 180)])[0] a = 1 + (m1 ** 2) b1 = -m1 * (x / 8) + (z / 8) b = 2 * m1 * b1 xp = ((-b) + (np.sign(f) * np.sqrt([b ** 2 - 4 * a * (b1 ** 2 - o ** 2)])[0])) / (2 * a) zp = m1 * xp + b1 await ctx.reply(f"Build your portal at: **{round(xp)}, {round(zp)}** ") except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="doubletravel", description="A *Minecraft: Java Edition* speedrunning tool that" + ", whilst you are in the Nether, gets a spot for " + "you to make your first portal inside the second " + "ring of strongholds. To use this command, in the" + " game, press F3+C, pause, come over to Discord, " + "paste your clipboard as an argument for the comm" + "and, and then build your portal at the suggested" + " coordinates in the Nether. `educatedtravel` shou" + "ld then be used after exiting the Nether which s" + "hould do a good job of getting you to the right " + "spot in the Nether to build your second portal. " + "This command is for versions 1.13+ and may not be" + " 100% accurate. This command MAY not be used in a " + "real speedrun.", aliases=["double"], usage="<F3+C data>") async def doubletravel(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, _ = self.f3cProcessing(f3c) o = 520 t = np.arctan([z / x])[0] xp = np.sign(x) * np.absolute([o * np.cos([t])[0]])[0] zp = np.sign(z) * np.absolute([o * np.sin([t])[0]])[0] blocks = round(self.coordsDifference((x, z), (xp, zp))) await ctx.reply( f"Build your first portal at: **{round(xp)}, {round(zp)}** " + f"({'{:,}'.format(blocks)} block{'' if blocks == 1 else 's'} away)\n\n" + f"Use `{self.client.command_prefix}educatedtravel` afterwards." ) except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="safeblind", description="A *Minecraft: Java Edition* speedrunning tool that, s" + "imilar to `blindtravel`, should be used when you wan" + "t to build another portal in the Nether before thro" + "wing any eyes of ender. This on average will get yo" + "u closer to the stronghold compared to `blindtravel`" + ", but time may be lost. To use this command, in the" + " game, press F3+C, pause, come over to Discord, pas" + "te your clipboard as an argument for the command, a" + "nd then build your portal at the suggested coordina" + "tes in the Nether. This command is for versions 1.13" + "+ and may not be 100% accurate. This command MAY not" + " be used in a real speedrun.", aliases=["sb", "safetravel", "safe", "st"], usage="<F3+C data>", hidden=True) async def safeblind(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, _ = self.f3cProcessing(f3c) dist = self.coordsDist(x, z) o = 222 if dist < 222 else dist if dist < 250 else 250 if dist < 480 else 615 if dist < 615 \ else dist if dist < 645 else 645 if dist < 832 else 1005 if dist < 1005 else dist if dist < 1032 \ else 1032 t = np.arctan([z / x])[0] xp = np.sign(x) * np.absolute([o * np.cos([t])[0]])[0] zp = np.sign(z) * np.absolute([o * np.sin([t])[0]])[0] blocks = round(self.coordsDifference((x, z), (xp, zp))) await ctx.reply( f"Build your portal at: **{round(xp)}, {round(zp)}** " + f"({'{:,}'.format(blocks)} block{'' if blocks == 1 else 's'} away)" ) except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="perfecttravel", description="A *Minecraft: Java Edition* speedrunning tool that att" + "empts to take you directly to the stronghold portal " + "room with the use of two Nether portals and F3 data." + " To use this command, in the game, leave your first " + "portal, find a chunk intersection and stand on the c" + 'hunk coordinate "0, 0" right in the centre, press F3' + "+C, pause, come over to Discord, paste your clipboar" + "d as an argument for the command, go back to the Net" + "her, and then build your second portal at the sugges" + "ted coordinates in the Nether. This command is for v" + "ersions 1.13+ and may not be 100% accurate. This com" + "mand MAY not be used in a real speedrun.", aliases=["perfectt", "perfect", "ptravel", "ptrav", "ptr", "pt"], usage='<F3+C data> ["calc"]\n\n' + 'Note: Add "calc" at the end if you do not want to manually calculate the portal coordinates yourself.') async def perfecttravel(self, ctx, *, f3c): calc = True if f3c.casefold().split()[-1] == "calc" else False try: nx, nz, px, pz = None, None, None, None x, z, f = self.f3cProcessing(f3c) if f > 180: f -= 360 if f < -180: f += 360 targetchunk = self.perfecttravel[str(round(f, 2))][0] if calc: await ctx.send("**Note:** Second Nether portal coordinates are calculated for you. " + "Your run is now most likely invalid.") else: await ctx.send("**Note:** Although no calculations are done and only a lookup table is being used, " + f"note that you may still risk invalidating your run or at least have it kept under close scrutiny.") try: targetchunkx, targetchunkz = targetchunk.split(" ") px, pz = int(x / 16) + (0 if x > 0 else -1), int(z / 16) + (0 if z > 0 else -1) nx = ((px + int(targetchunkx)) * 2) if calc else targetchunkx nz = ((pz + int(targetchunkz)) * 2) if calc else targetchunkz except: targetchunk = "" if targetchunk: if calc: await ctx.reply( f"Build your second portal at: **" + f"{round(nx + (1 if nx < 0 else 0))}, {round(nz + (1 if nz < 0 else 0))}** " + "\n\nMore info: https://youtu.be/YpV7I9X-Jso" ) else: await ctx.reply( f"Offset: **{nx}, {nz}**\n\nYour current chunk for reference: **" + f"{px}, {pz}**" + "\n\nMore info: https://youtu.be/YpV7I9X-Jso" ) else: await ctx.reply(f"Cannot find ideal coordinates...") except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="triangulationsimple", description="A simple stronghold triangulation command that takes in 6 values.", aliases=["trisimple", "simpletri", "strongholdsimple", "simplestronghold", "trisimp", "simptri", "simpletriangulation", "strongholdsimp", "simpstronghold"], usage="<x #1> <z #1> <angle #1> <x #2> <z #2> <angle #2>") async def triangulationsimple(self, ctx, x0, z0, f0, x1, z1, f1): try: xp, zp, blocks = self.strongholdCalc(float(x0), float(z0), float(f0), float(x1), float(z1), float(f1)) await ctx.reply( f"The stronghold could be at: **{round(xp)}, {round(zp)}** ({'{:,}'.format(blocks)} block" + f"{'' if blocks == 1 else 's'} away)" ) except Exception as ex: funcs.printError(ctx, ex) await ctx.reply(embed=funcs.errorEmbed(None, "Invalid input.")) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="triangulation", description="A *Minecraft: Java Edition* speedrunning tool tha" + "t attempts to locate the stronghold using both " + 'the "8, 8" rule and triangulation. To use this ' + "command, in the game, throw and eye, stand stil" + "l, put your mouse directly over the eye, press " + "F3+C, pause, come over to Discord, paste your c" + "lipboard as an argument for the command, and th" + "e command should return a set of coordinates ca" + 'lculated using the "8, 8" rule. You may continu' + "e using this command by parsing more F3+C clipb" + "oards as regular messages as you get closer to " + "the stronghold. Once the program knows you are " + "fairly close to the stronghold, it will automat" + "ically stop. This command is for versions 1.13+" + " and may not be 100% accurate. This command MAY" + " not be used in a real speedrun.", aliases=["triangulate", "triangle", "trian", "tri", "88", "44"], usage="<F3+C data>") async def triangulation(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, f = self.f3cProcessing(f3c) x0, z0, f0 = x, z, f f = (360 + f if f < 0 else f) - 180 r = (90 - f) * (np.pi / 180) b = 8 - np.absolute([np.absolute([x])[0] % 16])[0] + 16 l = [] s = 0 while s < 11904: d = b * np.sign(f) x += d z += d * -np.tan([r])[0] v = np.absolute([np.absolute([np.absolute([z])[0] % 16])[0] - 8])[0] + 0.5 s = self.coordsDist(x, z) if s > 1408: l.append({"k": x, "v": v, "j": v * v * np.sqrt([1 + len(l)])[0], "r": z}) b = 16 l.sort(key=lambda i: i["j"]) xp, zp = l[0]["k"], l[0]["r"] blocks = round(self.coordsDifference((x0, z0), (xp, zp))) await ctx.reply( f"The stronghold could be at: **{round(xp)}, {round(zp)}** ({'{:,}'.format(blocks)} block" + f"{'' if blocks == 1 else 's'} away)\n\nMethod: 8, 8\n\nPaste your F3+C clipboard here once " + "you are ready. The program will stop after 20 minutes of inactivity. Type `!cancel` to cancel." ) except Exception as ex: return await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) x1, z1, f1 = None, None, None blocks = 100 try: while blocks > 40: while True: msg = await self.client.wait_for( "message", timeout=1200, check=lambda m: ctx.author == m.author and ctx.channel == m.channel ) try: x1, z1, f1 = self.f3cProcessing(msg.content) except: if msg.content.casefold() == "!cancel": return await ctx.reply("Cancelling triangulation.") continue if x1 == x0 and z1 == z0 and f1 == f0: continue break try: xp, zp, blocks = self.strongholdCalc(x0, z0, f0, x1, z1, f1) except: continue await msg.reply( f"The stronghold could be at: **{round(xp)}, {round(zp)}** ({'{:,}'.format(blocks)} block" + f"{'' if blocks == 1 else 's'} away)\n\nMethod: Triangulation\n\nPaste your F3+C clipboard here once " + "you are ready. The program will stop after 20 minutes of inactivity. Type `!cancel` to cancel." ) x0, z0, f0 = x1, z1, f1 await ctx.send("You are close to the stronghold, stopping triangulation program.") except TimeoutError: await ctx.send("You have been inactive for over 20 minutes, stopping triangulation program.") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="coordsdist", description="Calculates the distance between two sets of coordinates.", aliases=["coords", "distance", "dist", "coord", "coordinates", "coordinate"], usage="<x #1> <z #1> <x #2> <z #2>\n\nAlternative usage(s):\n\n- <F3+C data> <x> <z>") async def coords(self, ctx, *, inp: str): inp = funcs.replaceCharacters(inp, [",", "(", ")", ";"]) args = inp.split(" ") try: try: x1, z1, _ = self.f3cProcessing(inp) except: x1, z1 = float(args[0]), float(args[1]) x2, z2 = float(args[-2]), float(args[-1]) except ValueError: return await ctx.reply(embed=funcs.errorEmbed(None, "Invalid arguments.")) await ctx.reply( "The distance between (**{}**; **{}**) and (**{}**; **{}**) is: ".format( funcs.removeDotZero(round(x1, 5)), funcs.removeDotZero(round(z1, 5)), funcs.removeDotZero(round(x2, 5)), funcs.removeDotZero(round(z2, 5)) ) + f"**{funcs.removeDotZero(round(self.coordsDifference((x1, z1), (x2, z2)), 5))}**" ) @commands.cooldown(1, 30, commands.BucketType.user) @commands.command(name="speedrunwr", description="Shows the current world records for the solo Any% Glitchless " + "*Minecraft: Java Edition* speedrun categories.", aliases=["worldrecord", "wr", "mcwr", "ssg", "rsg"]) async def speedrunwr(self, ctx): await ctx.send("Getting speedrun.com data. Please wait...") try: e = Embed(description="https://www.speedrun.com/mc") e.set_author(name="Minecraft Speedrun World Records - Solo Any% Glitchless", icon_url="https://cdn.discordapp.com/attachments/771698457391136798/842103816761114624/mc.png") urls = [ "klrzpjo1&var-wl33kewl=gq7zo9p1", "klrzpjo1&var-wl33kewl=21go6e6q", "klrzpjo1&var-wl33kewl=4qye4731", "21d4zvp1&var-wl33kewl=gq7zo9p1", "21d4zvp1&var-wl33kewl=21go6e6q", "21d4zvp1&var-wl33kewl=4qye4731" ] categories = [ "Set Seed Glitchless (Pre-1.9)", "Set Seed Glitchless (1.9-1.15)", "Set Seed Glitchless (1.16+)", "Random Seed Glitchless (Pre-1.9)", "Random Seed Glitchless (1.9-1.15)", "Random Seed Glitchless (1.16+)" ] count = 0 for category in urls: res = await funcs.getRequest( "https://www.speedrun.com/api/v1/leaderboards/j1npme6p/category/mkeyl926?var-r8rg67rn=" + category ) wrdata = res.json()["data"]["runs"][0]["run"] igt = wrdata["times"]["primary_t"] res = await funcs.getRequest(wrdata["players"][0]["uri"]) runner = res.json()["data"]["names"]["international"] d, h, m, s, ms = funcs.timeDifferenceStr(igt, 0, noStr=True) e.add_field(name=categories[count], inline=False, value=f"`{funcs.timeStr(d, h, m, s, ms)} ({runner})`") count += 1 e.set_footer(text="Click the link above for more speedrun categories.", icon_url="https://cdn.discordapp.com/attachments/771698457391136798/842103813585240124/src.png") except Exception as ex: funcs.printError(ctx, ex) e = funcs.errorEmbed(None, "Possible server error.") await ctx.reply(embed=e) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="skin", description="Gets the skin of a *Minecraft: Java Edition* user.", aliases=["mcskin"], usage="[username]", hidden=True) async def skin(self, ctx, username: str=""): if username == "": username = ctx.message.author.name try: data = await funcs.getRequest(f"https://api.mojang.com/users/profiles/minecraft/{username}") username = data.json()["name"] res = await funcs.getRequest( f"https://sessionserver.mojang.com/session/minecraft/profile/{str(data.json()['id'])}" ) data = loads(b64decode(res.json()["properties"][0]["value"])) skin = data["textures"]["SKIN"]["url"] e = Embed( title=username, description=f"https://namemc.com/profile/{username}" ) e.set_image(url=skin) except Exception as ex: funcs.printError(ctx, ex) e = funcs.errorEmbed(None, "Invalid skin or server error.") await ctx.reply(embed=e) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="mcserver", description="Gets the current status of a *Minecraft: Java Edition* server.", usage="[server address]") async def mcserver(self, ctx, *, ipaddress: str=""): ipaddress = ipaddress.casefold().replace(" ", "") or "mc.hypixel.net" try: res = await funcs.getRequest(f"https://api.mcsrvstat.us/2/{ipaddress}", headers={"accept": "application/json"}) data = res.json() status = data["online"] e = Embed(title="Minecraft Server Status", colour=Colour.green() if status else Colour.red()) e.add_field(name="Server Address", value=f"`{ipaddress}`") e.add_field(name="Online", value=f"`{status}`") if status: players = data["players"]["online"] e.add_field(name="Player Count", value="`{:,}/{:,}`".format(players, data['players']['max'])) if players: try: playerLimit = 25 playerList = data["players"]["list"][:playerLimit] listStr = ", ".join(f"`{player}`" for player in playerList) if len(playerList) != players: listStr += f" *and {players - playerLimit} more...*" e.add_field(name="Players", value=listStr) except: pass e.add_field(name="Version", value=f'`{data["version"]}`') e.add_field(name="Port", value=f'`{data["port"]}`') e.set_thumbnail(url=f"https://eu.mc-api.net/v3/server/favicon/{ipaddress}") try: e.add_field(name="Software", value=f'`{data["software"]}`') except: pass motd = data["motd"]["clean"] try: secondLine = f"\n{motd[1].strip().replace('&amp;', '&')}" except: secondLine = "" e.set_footer(text=motd[0].strip().replace('&amp;', '&') + secondLine) except Exception as ex: funcs.printError(ctx, ex) e = funcs.errorEmbed(None, "Invalid server address or server error?") await ctx.reply(embed=e) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="fossils", description="Brings up a fossil identification chart for divine travel.", aliases=["ft", "fossiltable", "fossilchart", "fossil"]) async def fossils(self, ctx): url = "https://cdn.discordapp.com/attachments/771404776410972161/842022227347636264/fossiltable.jpg" await funcs.sendImage( ctx, url, message="PDF: https://cdn.discordapp.com/attachments/817309668924719144/"+ "818310310153814056/Fossil_origin_identification_1.pdf" ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="divinetravel", aliases=["dt", "divine", "div", "dv"], usage="[option OR F3+I data]", description="Either brings up the chart for divine travel or gets certain divine coordinates. You can use o" + "ptions like `fossilX` with X being the x-coordinate of the fossil origin, or look at the fo" + "ssil origin in the game, press F3+I, and paste your clipboard as an argument for this command.") async def divinetravel(self, ctx, *, option: str=""): if option: try: try: x, _, _ = self.f3iProcessing(option) option = "fossil" + str(x) except: pass res = self.divinetravel[option.casefold().replace(" ", "")].split(" | ") e = Embed(title="Divine Travel: " + option.casefold().replace(" ", "")) for i, c in enumerate(res): if i > 2: text = f"High Roll #{i - 2}" else: text = f"Stronghold #{i + 1}" e.add_field(name=f"{text}", value=f"`{c.split(': ')[1]}`") except KeyError: e = funcs.errorEmbed( "Invalid option!", "Valid options:\n\n{}".format(", ".join(f"`{opt}`" for opt in self.divinetravel.keys())) ) await ctx.reply(embed=e) else: url = "https://media.discordapp.net/attachments/771698457391136798/934726825811275816/unknown.png" await funcs.sendImage(ctx, url) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="bastions", description="Shows the comprehensive guides to bastions.", hidden=True, aliases=["bastion"]) async def bastions(self, ctx): await ctx.reply("Guides: https://youtube.com/playlist?list=PL7Q35RXRsOR-udeKzwlYGJd0ZrvGJ0fwu\n\nP" + "ractice Map: https://github.com/LlamaPag/bastion\n\nGuide to Practice Map: <https://youtu.be/jlA-jW7VGqw>") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="endpractice", description="Shows the end practice map by ryguy2k4.", hidden=True, aliases=["end", "endfight", "endpractise"]) async def endpractice(self, ctx): await ctx.reply("https://github.com/ryguy2k4/ryguy2k4endpractice/releases") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="obt", description="Shows the One Block Tower tutorial for 1.7.", hidden=True, aliases=["tower1.7", "1.7tower", "oneblock", "oneblocktower"]) async def obt(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=nYI6wOM1U4A") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="zentower", description="Shows the Zen Tower tutorial for 1.8.", hidden=True, aliases=["tower1.8", "1.8tower", "zen"]) async def zentower(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=ryo3QbH2Zko") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="1.15route", description="Shows the 1.15 route.", hidden=True, aliases=["route1.15", "1.15routing", "routing1.15", "routing115", "115route", "115routing", "route115", "1.15", "115", "doubleday"]) async def route115(self, ctx): await ctx.reply("https://imgur.com/gallery/CFJYKmw\n\nDouble Day In-Depth Guide: " + "https://docs.google.com/document/d/1JhDCCpDww3o3oueROpP1lp01JaulaTdm-EhGOfgvkmk/edit") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="mapless", description="Shows the mapless treasure tutorial and practice map.", hidden=True, aliases=["buriedtreasure"]) async def mapless(self, ctx): await ctx.reply("Tutorials: https://youtu.be/ho1rwmooHRg\n\nhttps://youtu.be/_dyD8ZwagDg" + "\n\nPractice Map: <https://cdn.discordapp.com/att" + "achments/405839885509984256/885694752056541234/Mapless_Map.zip>") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="quadrants1.16", description="Shows the four Nether quadrants for versions 1.16+.", hidden=True, aliases=["netheregions", "netheregion", "netherregion", "netherregions", "nether", "quadrant", "quadrants"]) async def quadrants116(self, ctx): await funcs.sendImage(ctx, "https://media.discordapp.net/attachments/771404776410972161/937755369072107520/ejAZNGq.png") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="bedtiming", description="Shows the accurate bed timing for end fights.", hidden=True, aliases=["bedtimings", "onecycle", "timingbed", "bedtime", "bed", "beds"]) async def bedtiming(self, ctx): await funcs.sendImage(ctx, "https://media.discordapp.net/attachments/771698457391136798/937078099789635614/unknown.png") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="1.8trading", description="Shows the trading tutorial for 1.8.", hidden=True, aliases=["pre1.9trading", "trading1.8", "trading18", "18trading", "tradingpre1.9", "trading"]) async def trading18(self, ctx): await funcs.sendImage(ctx, "https://cdn.discordapp.com/attachments/771404776410972161/959506805908705320/unknown.png", message="https://youtu.be/1ksc3SSJkxs") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="ninjabrainbot", aliases=["ninjabot", "ninjabrain", "nb", "nbb"], hidden=True, description="Shows the Ninjabrain Bot tutorial and repository page.") async def ninjabrainbot(self, ctx): await ctx.reply("Tutorial: https://youtu.be/Rx8i7e5lu7g\n\nRepository: https://github.com/Ninjabrain1/Ninjabrain-Bot") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="blazefights", aliases=["blazefight", "blaze", "blazes", "fortress", "fortresses"], hidden=True, description="Shows the tutorial for Nether fortresses and blaze fights.") async def blazefights(self, ctx): await ctx.reply("https://youtu.be/pmx9LyUvLTk") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="eray", aliases=["eraying", "microlensing"], hidden=True, description="Shows the microlensing tutorial.") async def eray(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=jvTfMLPnMSw") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="magmaravines", aliases=["ravine", "magmaravine", "magma", "ravines", "oceanravine", "oceanravines"], description="Shows the guide to magma ravines.", hidden=True) async def magmaravines(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=yGyMWYhHYoQ") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="hypermodern", aliases=["hyperm", "hmodern"], hidden=True, description="Shows the guide to hypermodern speedruns.") async def hypermodern(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=gAHMJfsrHe4") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="blindtravelcoords", aliases=["rings", "strongholdrings", "strongholdring"], hidden=True, description="Shows the ideal blind travel coordinates for the first to third stronghold rings.") async def blindtravelcoords(self, ctx): await ctx.reply("https://imgur.com/gallery/i3fIanf") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="mcspeedrunning", description="Shows some important *Minecraft: Java Edition* speedrunning resources.", aliases=["mcspeedrun", "minecraftspeedrun", "minecraftspeedrunning", "mcsr", "speedrun"]) async def mcspeedrunning(self, ctx): await ctx.reply( "Setup Guide: https://www.youtube.com/watch?v=GAbnKAyireM\n\nWebsite: https://www.minecraftspeedrunning.com/" ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="doubleinstant", aliases=["doubleinstanttravel", "doubleinstanttrav", "dit", "di"], description="Shows the tutorial for Double Instant Travel for pre-1.9 trading.", hidden=True) async def doubleinstant(self, ctx): await ctx.reply("https://youtu.be/XuZWIJRCyaY") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="speedrunigt", aliases=["igt"], description="Download the SpeedRunIGT mod here.", hidden=True) async def speedrunigt(self, ctx): await ctx.reply("https://redlime.github.io/SpeedRunIGT/") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="contariacalc", description="Download ContariaCalc here.", hidden=True) async def contariacalc(self, ctx): await ctx.reply("https://github.com/KingContaria/ContariaCalc") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="strongholdnav", aliases=["stronghold", "sh", "strongholds", "nav"], description="Shows the guides to stronghold navigation and hidden rooms.", hidden=True) async def strongholdnav(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=hEZfeUWA3hM\n\nhttps://www.youtube.com/watch?v=vztJNmUdyBY" + "\n\nhttps://www.youtube.com/watch?v=2dWq2wXy43M (**NEW**)") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="ruinedportals", description="Shows some useful ruined portal resources.", hidden=True, aliases=["rp", "ruinedportal", "ruined", "ruinportal", "ruinportals", "ruin"]) async def ruinedportals(self, ctx): await ctx.reply( "Quick Completion Guide: https://www.youtube.com/watch?v=Bg_TVoo8waM", file=(await funcs.getImageFile( "https://media.discordapp.net/attachments/771404776410972161/939500126903336960/unknown.png" )) ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="zerocycle", description="Shows some useful Zero Cycle resources.", hidden=True, aliases=["0cycle", "0c", "zero", "zeroc", "zc", "0"]) async def zerocycle(self, ctx): await ctx.reply( "Full Zero Cycle Guide: https://youtu.be/iClDGWL0e5s\n\nResources: https://zerocycle.repl.co/", file=(await funcs.getImageFile( "https://media.discordapp.net/attachments/771404776410972161/938843696009469952/unknown.png" )) ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="fsg", description="Shows a list of FSG seed generators.", hidden=True, aliases=["fsgseed", "fsgseeds"]) async def fsg(self, ctx): await ctx.reply("Use one of the allowed generators: " + "<https://docs.google.com/spreadsheets/d/1ilu72GJ-vJZq2LFU68rycGMeTbWPjHJnO8PGfp4QjA8/edit#gid=0>\n\n" + "If you would like to use the generator locally for shorter wait times, follow this: " + "<https://youtu.be/Gl7zOn2lLo4>\n\nPlease play the seed within 30 seconds after it has been generated.") setup = Minecraft.setup
# Credit - https://github.com/Sharpieman20/Sharpies-Speedrunning-Tools # For blindtravel, doubletravel, educatedtravel, safeblind, triangulation # Credit - https://github.com/FourGoesFast/PerfectTravelBot # For divinetravel, perfecttravel from asyncio import TimeoutError from base64 import b64decode from json import loads from random import choice, randint from time import time import numpy as np from discord import Colour, Embed, File from discord.ext import commands from src.utils import funcs from src.utils.base_cog import BaseCog BARTER_LIMIT = 896 class Minecraft(BaseCog, name="Minecraft", description="Commands relating to *Minecraft* in general and *Minecraft: Java Edition* speedrunning."): def __init__(self, botInstance, *args, **kwargs): super().__init__(botInstance, *args, **kwargs) self.client.loop.create_task(self.__readFiles()) async def __readFiles(self): self.divinetravel = await funcs.readJson(funcs.getResource(self.name, "divine_travel.json")) self.perfecttravel = await funcs.readJson(funcs.getResource(self.name, "perfect_travel.json")) self.eyedata = await funcs.readJson(funcs.getResource(self.name, "eye_data.json")) self.loottable = await self.piglinLootTable() await funcs.generateJson( "findseed", { "calls": 0, "highest": { "found": 0, "number": 0, "time": int(time()) } } ) await funcs.generateJson("finddream", {"iteration": 0, "mostPearls": 0, "mostRods": 0}) async def piglinLootTable(self): lt = await funcs.readJson(funcs.getResource(self.name, "piglin_loot_table.json")) ltnew = [] for i in lt: if i["id"] < 5: item = i["item"] for j in range(1, 4): i["item"] = f"{item} {j}" for _ in range(i["weight"]): ltnew.append(i.copy()) i["id"] += 1 else: for _ in range(i["weight"] * 3): ltnew.append(i) return ltnew @staticmethod def randomEyes(): eyes = 0 for _ in range(12): eyes += 1 if funcs.oneIn(10) else 0 return eyes @staticmethod def getExcessStr(item): stacks, excess = funcs.stacksAndExcess(item) return "" if not stacks and excess == item \ else f" ({'{:,} stack{}'.format(stacks, '' if stacks == 1 else 's') if stacks else ''}" + \ f"{' + ' if stacks and excess else ''}{str(excess) if excess else ''})" @staticmethod def chargeableAnchors(glowdust: int, cryobby: int): return min([glowdust // 16, cryobby // 6]) @staticmethod def f3iProcessing(clipboard): try: args = clipboard.split(" ") return int(args[1]), int(args[2]), int(args[3]) except Exception: raise Exception("Invalid input. Please do not modify your F3+I clipboard.") @staticmethod def f3cProcessing(clipboard): try: args = clipboard.split(" ") return float(args[6]), float(args[8]), float(args[9]) % 360 except Exception: raise Exception("Invalid input. Please do not modify your F3+C clipboard.") @staticmethod def angleProcessing(angle): if angle >= 0: return (angle + 90) % 360 return (angle - 270) % 360 @staticmethod def coordsDist(x, z): return np.sqrt([x * x + z * z])[0] def coordsDifference(self, coords1: tuple, coords2: tuple): return self.coordsDist(coords1[0] - coords2[0], coords1[1] - coords2[1]) def strongholdCalc(self, x0, z0, f0, x1, z1, f1): a0 = np.tan([self.angleProcessing(f0) * np.pi / 180])[0] a1 = np.tan([self.angleProcessing(f1) * np.pi / 180])[0] b = z0 - x0 * a0 xp = ((z1 - x1 * a1) - b) / (a0 - a1) zp = xp * a0 + b blocks = round(self.coordsDifference((x1, z1), (xp, zp))) return xp, zp, blocks @commands.cooldown(1, 5, commands.BucketType.user) @commands.command(name="findseed", description="Everyone's favourite command. Test your luck using this command!", aliases=["fs", "seed", "findseeds", "f"]) async def findseed(self, ctx): eyes = self.randomEyes() data = await funcs.readJson("data/findseed.json") odds = self.eyedata[str(eyes)]["percent"] onein = self.eyedata[str(eyes)]["onein"] update = False if eyes >= data["highest"]["number"]: data["highest"]["found"] -= data["highest"]["found"] - 1 if eyes > data["highest"]["number"] else -1 data["highest"]["number"] = eyes data["highest"]["time"] = int(time()) update = True highest = data["highest"]["number"] highestTime = data["highest"]["time"] highestTotal = data["highest"]["found"] data["calls"] += 1 calls = data["calls"] await funcs.dumpJson("data/findseed.json", data) file = File( funcs.PATH + funcs.getResource(self.name, "portal_frame_images/") + f"{eyes}eye.png", filename="portal.png" ) foundTime = "just now" if not update: timestr = funcs.timeDifferenceStr(time(), highestTime) timestr_0 = int(timestr.split(" ")[0]) if timestr_0 > 2: foundTime = f"{timestr_0} days" else: foundTime = timestr e = Embed(title=f"{self.client.command_prefix}findseed", description=f"Requested by: {ctx.message.author.mention}") e.add_field(name="Your Eyes", value=f"`{eyes}`") e.add_field(name="Probability", value=f"`{odds}% (1 in {onein})`") e.add_field(name="Most Eyes Found", inline=False, value=f"`{highest} (last found {foundTime}{' ago' if not update else ''}" + f", found {'{:,}'.format(highestTotal)} time{'' if highestTotal == 1 else 's'})`") e.set_footer(text=f"The command has been called {'{:,}'.format(calls)} time{'' if calls == 1 else 's'}. !eyeodds") e.set_image(url="attachment://portal.png") await ctx.reply(embed=e, file=file) @commands.cooldown(1, 10, commands.BucketType.user) @commands.command(name="eyeodds", description="Shows the odds of getting each type of end portal.", aliases=["odds", "eyes", "eye", "eyeodd", "eyeood", "eyeoods"]) async def eyeodds(self, ctx): msg = "" for i in range(13): odds = self.eyedata[str(i)]["percent"] msg += f"{i} eye - `{odds}% (1 in {self.eyedata[str(i)]['onein']})`\n" await ctx.reply(msg) @commands.cooldown(1, 5, commands.BucketType.user) @commands.command(name="finddream", description="Can you get Dream's *Minecraft* speedrunning \"luck\"? " + "Test your luck using this command!", aliases=["dream", "dreamsimulator", "dreamsim", "dreamluck", "fd"], hidden=True) async def finddream(self, ctx): pearls, rods = 0, 0 dpearls, drods = 262, 305 data = await funcs.readJson("data/finddream.json") mostPearls = data["mostPearls"] mostRods = data["mostRods"] for _ in range(dpearls): pearls += 1 if randint(0, 422) < 20 else 0 for _ in range(drods): rods += 1 if funcs.oneIn(2) else 0 data["mostPearls"] = pearls if pearls >= mostPearls else mostPearls data["mostRods"] = rods if rods >= mostRods else mostRods data["iteration"] += 1 iters = data['iteration'] await funcs.dumpJson("data/finddream.json", data) e = Embed( title=f"{self.client.command_prefix}finddream", description=f"Dream got 42 ender pearl trades in {dpearls} plus 211 blaze rod drops in {drods}. " + f"Can you achieve his 'luck'?\n\nRequested by: {ctx.author.mention}" ) e.add_field(name="Your Pearl Trades", value=f"`{pearls} ({round(pearls / dpearls * 100, 3)}%)`") e.add_field(name="Your Rod Drops", value=f"`{rods} ({round(rods / drods * 100, 3)}%)`") e.set_footer( text=f"The command has been called {'{:,}'.format(iters)} time{'' if iters == 1 else 's'}. " + f"| Most pearl trades: {data['mostPearls']}; most rod drops: {data['mostRods']}" ) e.set_thumbnail(url="https://static.wikia.nocookie.net/dream_team/images/7/7b/Dream.jpeg") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findbreak", description="You throw an ender eye. Does it break or do you get to keep it?" + " Test your luck using this command!", aliases=["break", "eyebreak", "breakeye", "findeye"], hidden=True) async def findbreak(self, ctx): e = Embed(title=f"{self.client.command_prefix}findbreak", description=f"Requested by: {ctx.message.author.mention}") badluckonein = 5 goodluck = not funcs.oneIn(badluckonein) e.add_field(name="Result", value=f"`{'No Break!' if goodluck else 'Break...'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771404776410972161/938407577975418900/unknown.png") e.set_image(url="https://cdn.discordapp.com/attachments/771404776410972161/938408463946637312/2022-02-02_20.20.06.png" if goodluck else "https://media.discordapp.net/attachments/771404776410972161/938408658411327528/unknown.png") e.set_footer(text=f"Odds: {str(badluckonein - 1) if goodluck else '1'}/{str(badluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findcleric", description="Will you get the ender pearl trade from the cleric, " + "or will you get one-thirded? Test your luck using this command!", aliases=["cleric", "stupidvillager"], hidden=True) async def findcleric(self, ctx): e = Embed(title=f"{self.client.command_prefix}findcleric", description=f"Requested by: {ctx.message.author.mention}") badluckonein = 3 goodluck = not funcs.oneIn(badluckonein) e.add_field(name="Result", value=f"`{'Pearl' if goodluck else 'Bottle'} Trade{'!' if goodluck else '...'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771404776410972161/856203578615529532/cleric.png") e.set_image(url="https://media.discordapp.net/attachments/771404776410972161/856203574337601536/pearl.png" if goodluck else "https://media.discordapp.net/attachments/771404776410972161/856203573113520138/bottle.png") e.set_footer(text=f"Odds: {str(badluckonein - 1) if goodluck else '1'}/{str(badluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findgravel", description="Will you get flint from gravel? Test your luck using this command!", aliases=["gravel", "flint", "findflint", "fg"], hidden=True) async def findgravel(self, ctx): e = Embed(title=f"{self.client.command_prefix}findgravel", description=f"Requested by: {ctx.message.author.mention}") goodluckonein = 10 badluck = not funcs.oneIn(goodluckonein) e.add_field(name="Result", value=f"`{'Gravel' if badluck else 'Flint'}{'...' if badluck else '!'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771698457391136798/856209821383917608/gravel.png") e.set_image(url="https://media.discordapp.net/attachments/771698457391136798/856209821383917608/gravel.png" if badluck else "https://media.discordapp.net/attachments/771698457391136798/856209843174244362/flint.png") e.set_footer(text=f"Odds: {str(goodluckonein - 1) if badluck else '1'}/{str(goodluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findperch", description="You are in insane pace and about to kill the dragon..." + "but does it perch instantly? Test your luck using this command!", aliases=["dragon", "fp", "finddragon"], hidden=True) async def findperch(self, ctx): e = Embed(title=f"{self.client.command_prefix}findperch", description=f"Requested by: {ctx.message.author.mention}") goodluckonein = 13 badluck = not funcs.oneIn(goodluckonein) e.add_field(name="Result", value=f"`{'No Perch' if badluck else 'Perch'}{'...' if badluck else '!'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771404776410972161/928297045486370857/dragon.png") e.set_image(url="https://media.discordapp.net/attachments/771404776410972161/928299016259776613/2022-01-05_22.48.45.png" if badluck else "https://media.discordapp.net/attachments/771404776410972161/928298549861572638/2022-01-05_22.46.50.png") e.set_footer(text=f"Odds: {str(goodluckonein - 1) if badluck else '1'}/{str(goodluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findskull", description="You kill a wither skeleton...but does it drop a wither skull?" + " Test your luck using this command!", aliases=["skull", "witherskull", "findwitherskull", "findwither"], hidden=True) async def findskull(self, ctx): e = Embed(title=f"{self.client.command_prefix}findskull", description=f"Requested by: {ctx.message.author.mention}") goodluckonein = 40 badluck = not funcs.oneIn(goodluckonein) e.add_field(name="Result", value=f"`{'No Skull' if badluck else 'Skull'}{'...' if badluck else '!'}`") e.set_thumbnail(url="https://cdn.discordapp.com/attachments/771404776410972161/935204890639233054/unknown.png") e.set_image( url="" if badluck else "https://cdn.discordapp.com/attachments/771404776410972161/935204919651205250/unknown.png" ) e.set_footer(text=f"Odds: {str(goodluckonein - 1) if badluck else '1'}/{str(goodluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="findblaze", description="You kill a blaze...but does it drop a rod? Test your luck using this command!", aliases=["rod", "blazerod", "findrod", "findblazerod"], hidden=True) async def findblaze(self, ctx): e = Embed(title=f"{self.client.command_prefix}findblaze", description=f"Requested by: {ctx.message.author.mention}") badluckonein = 2 goodluck = not funcs.oneIn(badluckonein) e.add_field(name="Result", value=f"`{'Rod' if goodluck else 'No Rod'} Drop{'!' if goodluck else '...'}`") e.set_thumbnail(url="https://media.discordapp.net/attachments/771698457391136798/856213640809414666/blaze.png") e.set_image(url="https://media.discordapp.net/attachments/771698457391136798/856213641020178472/rod.png" if goodluck else "https://cdn.discordapp.com/attachments/771698457391136798/856213642173612032/norod.png") e.set_footer(text=f"Odds: {str(badluckonein - 1) if goodluck else '1'}/{str(badluckonein)}") await ctx.reply(embed=e) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="perchcmd", description="Shows the command to force the the ender dragon perch.", aliases=["perch"]) async def perchcmd(self, ctx): await ctx.reply("```1.13+: /data merge entity @e[type=ender_dragon,limit=1] {DragonPhase:2}\n\n" + "1.9-1.12: /entitydata @e[type=ender_dragon] {DragonPhase:2}```") @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="logs", description="Calculates how many logs you will need to trade for a certain number of emeralds.", aliases=["log", "wood"], usage="<amount of emeralds needed>") async def logs(self, ctx, emeralds): try: emeralds = int(emeralds) if emeralds < 1: raise Exception log = emeralds * 4 await ctx.reply("You want **{:,}** emerald{}.\n\nYou will need **{:,}** logs{}.".format( emeralds, "" if emeralds == 1 else "s", int(log), self.getExcessStr(log) )) except Exception as ex: funcs.printError(ctx, ex) await ctx.reply( embed=funcs.errorEmbed(None, "Invalid input. Please make sure you are entering positive, non-zero integers.") ) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="haybales", aliases=["hay", "haybale"], usage="<amount of emeralds needed>", description="Calculates how many hay bales you will need to trade for a certain number of emeralds.") async def haybales(self, ctx, emeralds): try: emeralds = int(emeralds) if emeralds < 1: raise Exception hay = 20 * emeralds / 9 hay = funcs.strictRounding(hay) await ctx.reply("You want **{:,}** emerald{}.\n\nYou will need **{:,}** hay bales{}.".format( emeralds, "" if emeralds == 1 else "s", int(hay), self.getExcessStr(hay) )) except Exception as ex: funcs.printError(ctx, ex) await ctx.reply( embed=funcs.errorEmbed(None, "Invalid input. Please make sure you are entering positive, non-zero integers.") ) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="books", aliases=["book", "bookshelf", "bookshelves", "library"], usage="<books per emerald> <emeralds per eye> [eyes needed]", description="Calculates how many books you will need to get eyes of ender for pre-1.9 trading.") async def books(self, ctx, book, emeralds, eyes="12"): try: book = int(book) emeralds = int(emeralds) eyes = int(eyes) if not 8 <= book <= 10: return await ctx.send(embed=funcs.errorEmbed(None, "Books per emerald must be 8-10 inclusive.")) if not 7 <= emeralds <= 11: return await ctx.send(embed=funcs.errorEmbed(None, "Emeralds per eye must be 7-11 inclusive.")) if not 1 <= eyes <= 12: return await ctx.send(embed=funcs.errorEmbed(None, "Eyes needed must be 1-12 inclusive.")) totalEmeralds = emeralds * eyes totalBooks = totalEmeralds * book booksPerEye = emeralds * book bookshelves = funcs.strictRounding(totalBooks / 3) await ctx.send("You want **{}** eye{} of ender.\nThe librarian sells one emera".format(eyes, "" if eyes == 1 else "s") + "ld for **{}** books.\nThe cleric sells one eye of ender for **{}** emeralds.\n".format(book, emeralds) + "\nYou will need:\n\n**{:,}** books{} for a total of".format(totalBooks, self.getExcessStr(totalBooks)) + " **{}** emeralds{}\nBooks per eye:".format(totalEmeralds, self.getExcessStr(totalEmeralds)) + " **{}**\nBookshelves to break: **{}**\n\n".format(booksPerEye, bookshelves) + "Big library: 699 books\nSmall library: 483 books") except Exception as ex: funcs.printError(ctx, ex) await ctx.reply( embed=funcs.errorEmbed(None, "Invalid input.") ) @commands.cooldown(1, 1, commands.BucketType.user) @commands.command(name="anchors", description="Calculates how many chargeable respawn anchors you can craft based on how " + "much glowstone dust and crying obsidian you have.", aliases=["anchor"], usage="<amount of glowstone dust> <amount of crying obdisian>") async def anchors(self, ctx, glowdust, cryobby): try: glowdust = int(glowdust) cryobby = int(cryobby) if glowdust < 1 or cryobby < 1: raise Exception anchors = self.chargeableAnchors(glowdust, cryobby) charge = " and sufficiently charge {}".format("it" if anchors == 1 else "them") if anchors else "" await ctx.reply( "You have **{:,}** glowstone dust and **{:,}** crying obsidian.\n\nYou can make **".format(glowdust, cryobby) + "{:,}** respawn anchor{}{}.".format(anchors, "" if anchors == 1 else "s", charge) ) except Exception as ex: funcs.printError(ctx, ex) await ctx.reply( embed=funcs.errorEmbed(None, "Invalid input. Please make sure you are entering positive, non-zero integers.") ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(description="Simulates *Minecraft: Java Edition* 1.16.1 piglin bartering. Test your luck using this command!", aliases=["barter", "piglin", "poglin", "bartering", "barteringsim"], name="bartersim", usage=f"[gold ingots up to 10,000]\n\nAlternative usage(s):\n\n- <gold blocks up to 1,111 (ending with b)>") async def bartersim(self, ctx, goldingots: str="1"): try: try: goldingots = int(goldingots) except: goldingots = int(goldingots[:-1]) * 9 if not 0 < goldingots < 10001: return await ctx.reply(embed=funcs.errorEmbed(None, f"Value must be between 1 and 10,000.")) except ValueError: return await ctx.reply(embed=funcs.errorEmbed(None, "Invalid input.")) trades = {} string, glowdust, cryobby = 0, 0, 0 for _ in range(goldingots): trade = choice(self.loottable) if trade["id"] not in list(trades.keys()): trades[trade["id"]] = {} trades[trade["id"]]["item"] = trade["item"] n = choice(trade["quantity"]) trades[trade["id"]]["quantity"] = n trades[trade["id"]]["trades"] = 1 else: n = choice(trade["quantity"]) trades[trade["id"]]["quantity"] += n trades[trade["id"]]["trades"] += 1 if trade["id"] == 13: string += n elif trade["id"] == 10: glowdust += n elif trade["id"] == 19: cryobby += n res = "You bartered {:,} gold ingot{} for:\n\n".format(goldingots, "" if goldingots == 1 else "s") for i in sorted(trades): t = trades[i] res += "{}{:,} x {} ({:,} trade{})\n".format( "*** " if i in [7, 8, 10, 12, 13, 18, 19] else " ", t["quantity"], t["item"], t["trades"], "" if t["trades"] == 1 else "s" ) anchors = self.chargeableAnchors(glowdust, cryobby) beds = string // 12 explosives = anchors + beds if explosives: res += "\nExplosives you can craft ({:,}):\n\n".format(explosives) if beds: res += " {:,} x Bed\n".format(beds) if anchors: res += " {:,} x Respawn Anchor (w/ enough glowstone to power)".format(anchors) await ctx.reply(funcs.formatting(res)) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="pearlbarter", description="Finds the probability of getting 12 or more ender pearls" + " in a given number of piglin trades in *Minecraft* 1.16.1.", aliases=["pearltrade", "pearlbartering", "barteringpearl", "barterpearl", "barterpearls"], usage=f"[total gold ingots up to {BARTER_LIMIT}]") async def pearlbarter(self, ctx, trades: str="2"): try: n = int(trades) if not 2 <= n <= BARTER_LIMIT: return await ctx.reply(embed=funcs.errorEmbed(None, f"Value must be between 2 and {BARTER_LIMIT}.")) except ValueError: return await ctx.reply(embed=funcs.errorEmbed(None, "Invalid input.")) x = 1 - (403 / 423) ** n - n * (20 / 423) * ((403 / 423) ** (n - 1)) - (2 / 5) * (n * (n - 1) / 2) \ * ((403 / 423) ** (n - 2)) * ((20 / 423) ** 2) await ctx.reply(f"**[1.16.1]** The probability of getting 12 or more ender pearls" + f" with {n} gold ingots is:\n\n`{round(x * 100, 5)}%` (1 in {round(1 / x, 5)})") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="blindtravel", description="A *Minecraft: Java Edition* speedrunning tool that " + "should be used when you want to build another por" + "tal in the Nether before throwing any eyes of end" + "er. To use this command, in the game, press F3+C," + " pause, come over to Discord, paste your clipboar" + "d as an argument for the command, and then build " + "your portal at the suggested coordinates in the N" + "ether. This command is for versions 1.13+ and may " + "not be 100% accurate. This command MAY not be used" + " in a real speedrun.", aliases=["bt", "blind", "blindtrav"], usage="<F3+C data>") async def blindtravel(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, _ = self.f3cProcessing(f3c) dist = self.coordsDist(x, z) o = 190 if dist < 190 else dist if dist < 290 else 290 if dist < 442 else 580 if dist < 580 else dist \ if dist < 692 else 686 if dist < 825 else 970 if dist < 970 else dist if dist < 1060 else 1060 t = np.arctan([z / x])[0] xp = np.sign(x) * np.absolute([o * np.cos([t])[0]])[0] zp = np.sign(z) * np.absolute([o * np.sin([t])[0]])[0] blocks = round(self.coordsDifference((x, z), (xp, zp))) await ctx.reply( f"Build your portal at: **{round(xp)}, {round(zp)}** " + f"({'{:,}'.format(blocks)} block{'' if blocks == 1 else 's'} away)" ) except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="educatedtravel", description="A *Minecraft: Java Edition* speedrunning tool th" + "at should be used when you want to build anoth" + "er portal in the Nether after throwing an eye " + "of ender. To use this command, in the game, th" + "row an eye, stand still, put your mouse direct" + "ly over the eye, press F3+C, pause, come over " + "to Discord, paste your clipboard as an argumen" + "t for the command, and then build your portal " + "at the suggested coordinates in the Nether. Th" + "is command is for versions 1.13+ and may not be" + " 100% accurate. This command MAY not be used in" + " a real speedrun.", aliases=["et", "educated", "nethertravel"], usage="<F3+C data>") async def educatedtravel(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, f = self.f3cProcessing(f3c) f = (360 + f if f < 0 else f) - 180 o = 640 if self.coordsDist(x, z) > 3584 else 216 m1 = -np.tan([(90 - f) * (np.pi / 180)])[0] a = 1 + (m1 ** 2) b1 = -m1 * (x / 8) + (z / 8) b = 2 * m1 * b1 xp = ((-b) + (np.sign(f) * np.sqrt([b ** 2 - 4 * a * (b1 ** 2 - o ** 2)])[0])) / (2 * a) zp = m1 * xp + b1 await ctx.reply(f"Build your portal at: **{round(xp)}, {round(zp)}** ") except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="doubletravel", description="A *Minecraft: Java Edition* speedrunning tool that" + ", whilst you are in the Nether, gets a spot for " + "you to make your first portal inside the second " + "ring of strongholds. To use this command, in the" + " game, press F3+C, pause, come over to Discord, " + "paste your clipboard as an argument for the comm" + "and, and then build your portal at the suggested" + " coordinates in the Nether. `educatedtravel` shou" + "ld then be used after exiting the Nether which s" + "hould do a good job of getting you to the right " + "spot in the Nether to build your second portal. " + "This command is for versions 1.13+ and may not be" + " 100% accurate. This command MAY not be used in a " + "real speedrun.", aliases=["double"], usage="<F3+C data>") async def doubletravel(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, _ = self.f3cProcessing(f3c) o = 520 t = np.arctan([z / x])[0] xp = np.sign(x) * np.absolute([o * np.cos([t])[0]])[0] zp = np.sign(z) * np.absolute([o * np.sin([t])[0]])[0] blocks = round(self.coordsDifference((x, z), (xp, zp))) await ctx.reply( f"Build your first portal at: **{round(xp)}, {round(zp)}** " + f"({'{:,}'.format(blocks)} block{'' if blocks == 1 else 's'} away)\n\n" + f"Use `{self.client.command_prefix}educatedtravel` afterwards." ) except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="safeblind", description="A *Minecraft: Java Edition* speedrunning tool that, s" + "imilar to `blindtravel`, should be used when you wan" + "t to build another portal in the Nether before thro" + "wing any eyes of ender. This on average will get yo" + "u closer to the stronghold compared to `blindtravel`" + ", but time may be lost. To use this command, in the" + " game, press F3+C, pause, come over to Discord, pas" + "te your clipboard as an argument for the command, a" + "nd then build your portal at the suggested coordina" + "tes in the Nether. This command is for versions 1.13" + "+ and may not be 100% accurate. This command MAY not" + " be used in a real speedrun.", aliases=["sb", "safetravel", "safe", "st"], usage="<F3+C data>", hidden=True) async def safeblind(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, _ = self.f3cProcessing(f3c) dist = self.coordsDist(x, z) o = 222 if dist < 222 else dist if dist < 250 else 250 if dist < 480 else 615 if dist < 615 \ else dist if dist < 645 else 645 if dist < 832 else 1005 if dist < 1005 else dist if dist < 1032 \ else 1032 t = np.arctan([z / x])[0] xp = np.sign(x) * np.absolute([o * np.cos([t])[0]])[0] zp = np.sign(z) * np.absolute([o * np.sin([t])[0]])[0] blocks = round(self.coordsDifference((x, z), (xp, zp))) await ctx.reply( f"Build your portal at: **{round(xp)}, {round(zp)}** " + f"({'{:,}'.format(blocks)} block{'' if blocks == 1 else 's'} away)" ) except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="perfecttravel", description="A *Minecraft: Java Edition* speedrunning tool that att" + "empts to take you directly to the stronghold portal " + "room with the use of two Nether portals and F3 data." + " To use this command, in the game, leave your first " + "portal, find a chunk intersection and stand on the c" + 'hunk coordinate "0, 0" right in the centre, press F3' + "+C, pause, come over to Discord, paste your clipboar" + "d as an argument for the command, go back to the Net" + "her, and then build your second portal at the sugges" + "ted coordinates in the Nether. This command is for v" + "ersions 1.13+ and may not be 100% accurate. This com" + "mand MAY not be used in a real speedrun.", aliases=["perfectt", "perfect", "ptravel", "ptrav", "ptr", "pt"], usage='<F3+C data> ["calc"]\n\n' + 'Note: Add "calc" at the end if you do not want to manually calculate the portal coordinates yourself.') async def perfecttravel(self, ctx, *, f3c): calc = True if f3c.casefold().split()[-1] == "calc" else False try: nx, nz, px, pz = None, None, None, None x, z, f = self.f3cProcessing(f3c) if f > 180: f -= 360 if f < -180: f += 360 targetchunk = self.perfecttravel[str(round(f, 2))][0] if calc: await ctx.send("**Note:** Second Nether portal coordinates are calculated for you. " + "Your run is now most likely invalid.") else: await ctx.send("**Note:** Although no calculations are done and only a lookup table is being used, " + f"note that you may still risk invalidating your run or at least have it kept under close scrutiny.") try: targetchunkx, targetchunkz = targetchunk.split(" ") px, pz = int(x / 16) + (0 if x > 0 else -1), int(z / 16) + (0 if z > 0 else -1) nx = ((px + int(targetchunkx)) * 2) if calc else targetchunkx nz = ((pz + int(targetchunkz)) * 2) if calc else targetchunkz except: targetchunk = "" if targetchunk: if calc: await ctx.reply( f"Build your second portal at: **" + f"{round(nx + (1 if nx < 0 else 0))}, {round(nz + (1 if nz < 0 else 0))}** " + "\n\nMore info: https://youtu.be/YpV7I9X-Jso" ) else: await ctx.reply( f"Offset: **{nx}, {nz}**\n\nYour current chunk for reference: **" + f"{px}, {pz}**" + "\n\nMore info: https://youtu.be/YpV7I9X-Jso" ) else: await ctx.reply(f"Cannot find ideal coordinates...") except Exception as ex: await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="triangulationsimple", description="A simple stronghold triangulation command that takes in 6 values.", aliases=["trisimple", "simpletri", "strongholdsimple", "simplestronghold", "trisimp", "simptri", "simpletriangulation", "strongholdsimp", "simpstronghold"], usage="<x #1> <z #1> <angle #1> <x #2> <z #2> <angle #2>") async def triangulationsimple(self, ctx, x0, z0, f0, x1, z1, f1): try: xp, zp, blocks = self.strongholdCalc(float(x0), float(z0), float(f0), float(x1), float(z1), float(f1)) await ctx.reply( f"The stronghold could be at: **{round(xp)}, {round(zp)}** ({'{:,}'.format(blocks)} block" + f"{'' if blocks == 1 else 's'} away)" ) except Exception as ex: funcs.printError(ctx, ex) await ctx.reply(embed=funcs.errorEmbed(None, "Invalid input.")) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="triangulation", description="A *Minecraft: Java Edition* speedrunning tool tha" + "t attempts to locate the stronghold using both " + 'the "8, 8" rule and triangulation. To use this ' + "command, in the game, throw and eye, stand stil" + "l, put your mouse directly over the eye, press " + "F3+C, pause, come over to Discord, paste your c" + "lipboard as an argument for the command, and th" + "e command should return a set of coordinates ca" + 'lculated using the "8, 8" rule. You may continu' + "e using this command by parsing more F3+C clipb" + "oards as regular messages as you get closer to " + "the stronghold. Once the program knows you are " + "fairly close to the stronghold, it will automat" + "ically stop. This command is for versions 1.13+" + " and may not be 100% accurate. This command MAY" + " not be used in a real speedrun.", aliases=["triangulate", "triangle", "trian", "tri", "88", "44"], usage="<F3+C data>") async def triangulation(self, ctx, *, f3c): await ctx.send("**Note:** This command, along with other speedrunning calculators, MAY not be used in a real speedrun.") try: x, z, f = self.f3cProcessing(f3c) x0, z0, f0 = x, z, f f = (360 + f if f < 0 else f) - 180 r = (90 - f) * (np.pi / 180) b = 8 - np.absolute([np.absolute([x])[0] % 16])[0] + 16 l = [] s = 0 while s < 11904: d = b * np.sign(f) x += d z += d * -np.tan([r])[0] v = np.absolute([np.absolute([np.absolute([z])[0] % 16])[0] - 8])[0] + 0.5 s = self.coordsDist(x, z) if s > 1408: l.append({"k": x, "v": v, "j": v * v * np.sqrt([1 + len(l)])[0], "r": z}) b = 16 l.sort(key=lambda i: i["j"]) xp, zp = l[0]["k"], l[0]["r"] blocks = round(self.coordsDifference((x0, z0), (xp, zp))) await ctx.reply( f"The stronghold could be at: **{round(xp)}, {round(zp)}** ({'{:,}'.format(blocks)} block" + f"{'' if blocks == 1 else 's'} away)\n\nMethod: 8, 8\n\nPaste your F3+C clipboard here once " + "you are ready. The program will stop after 20 minutes of inactivity. Type `!cancel` to cancel." ) except Exception as ex: return await ctx.reply(embed=funcs.errorEmbed(None, str(ex))) x1, z1, f1 = None, None, None blocks = 100 try: while blocks > 40: while True: msg = await self.client.wait_for( "message", timeout=1200, check=lambda m: ctx.author == m.author and ctx.channel == m.channel ) try: x1, z1, f1 = self.f3cProcessing(msg.content) except: if msg.content.casefold() == "!cancel": return await ctx.reply("Cancelling triangulation.") continue if x1 == x0 and z1 == z0 and f1 == f0: continue break try: xp, zp, blocks = self.strongholdCalc(x0, z0, f0, x1, z1, f1) except: continue await msg.reply( f"The stronghold could be at: **{round(xp)}, {round(zp)}** ({'{:,}'.format(blocks)} block" + f"{'' if blocks == 1 else 's'} away)\n\nMethod: Triangulation\n\nPaste your F3+C clipboard here once " + "you are ready. The program will stop after 20 minutes of inactivity. Type `!cancel` to cancel." ) x0, z0, f0 = x1, z1, f1 await ctx.send("You are close to the stronghold, stopping triangulation program.") except TimeoutError: await ctx.send("You have been inactive for over 20 minutes, stopping triangulation program.") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="coordsdist", description="Calculates the distance between two sets of coordinates.", aliases=["coords", "distance", "dist", "coord", "coordinates", "coordinate"], usage="<x #1> <z #1> <x #2> <z #2>\n\nAlternative usage(s):\n\n- <F3+C data> <x> <z>") async def coords(self, ctx, *, inp: str): inp = funcs.replaceCharacters(inp, [",", "(", ")", ";"]) args = inp.split(" ") try: try: x1, z1, _ = self.f3cProcessing(inp) except: x1, z1 = float(args[0]), float(args[1]) x2, z2 = float(args[-2]), float(args[-1]) except ValueError: return await ctx.reply(embed=funcs.errorEmbed(None, "Invalid arguments.")) await ctx.reply( "The distance between (**{}**; **{}**) and (**{}**; **{}**) is: ".format( funcs.removeDotZero(round(x1, 5)), funcs.removeDotZero(round(z1, 5)), funcs.removeDotZero(round(x2, 5)), funcs.removeDotZero(round(z2, 5)) ) + f"**{funcs.removeDotZero(round(self.coordsDifference((x1, z1), (x2, z2)), 5))}**" ) @commands.cooldown(1, 30, commands.BucketType.user) @commands.command(name="speedrunwr", description="Shows the current world records for the solo Any% Glitchless " + "*Minecraft: Java Edition* speedrun categories.", aliases=["worldrecord", "wr", "mcwr", "ssg", "rsg"]) async def speedrunwr(self, ctx): await ctx.send("Getting speedrun.com data. Please wait...") try: e = Embed(description="https://www.speedrun.com/mc") e.set_author(name="Minecraft Speedrun World Records - Solo Any% Glitchless", icon_url="https://cdn.discordapp.com/attachments/771698457391136798/842103816761114624/mc.png") urls = [ "klrzpjo1&var-wl33kewl=gq7zo9p1", "klrzpjo1&var-wl33kewl=21go6e6q", "klrzpjo1&var-wl33kewl=4qye4731", "21d4zvp1&var-wl33kewl=gq7zo9p1", "21d4zvp1&var-wl33kewl=21go6e6q", "21d4zvp1&var-wl33kewl=4qye4731" ] categories = [ "Set Seed Glitchless (Pre-1.9)", "Set Seed Glitchless (1.9-1.15)", "Set Seed Glitchless (1.16+)", "Random Seed Glitchless (Pre-1.9)", "Random Seed Glitchless (1.9-1.15)", "Random Seed Glitchless (1.16+)" ] count = 0 for category in urls: res = await funcs.getRequest( "https://www.speedrun.com/api/v1/leaderboards/j1npme6p/category/mkeyl926?var-r8rg67rn=" + category ) wrdata = res.json()["data"]["runs"][0]["run"] igt = wrdata["times"]["primary_t"] res = await funcs.getRequest(wrdata["players"][0]["uri"]) runner = res.json()["data"]["names"]["international"] d, h, m, s, ms = funcs.timeDifferenceStr(igt, 0, noStr=True) e.add_field(name=categories[count], inline=False, value=f"`{funcs.timeStr(d, h, m, s, ms)} ({runner})`") count += 1 e.set_footer(text="Click the link above for more speedrun categories.", icon_url="https://cdn.discordapp.com/attachments/771698457391136798/842103813585240124/src.png") except Exception as ex: funcs.printError(ctx, ex) e = funcs.errorEmbed(None, "Possible server error.") await ctx.reply(embed=e) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="skin", description="Gets the skin of a *Minecraft: Java Edition* user.", aliases=["mcskin"], usage="[username]", hidden=True) async def skin(self, ctx, username: str=""): if username == "": username = ctx.message.author.name try: data = await funcs.getRequest(f"https://api.mojang.com/users/profiles/minecraft/{username}") username = data.json()["name"] res = await funcs.getRequest( f"https://sessionserver.mojang.com/session/minecraft/profile/{str(data.json()['id'])}" ) data = loads(b64decode(res.json()["properties"][0]["value"])) skin = data["textures"]["SKIN"]["url"] e = Embed( title=username, description=f"https://namemc.com/profile/{username}" ) e.set_image(url=skin) except Exception as ex: funcs.printError(ctx, ex) e = funcs.errorEmbed(None, "Invalid skin or server error.") await ctx.reply(embed=e) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="mcserver", description="Gets the current status of a *Minecraft: Java Edition* server.", usage="[server address]") async def mcserver(self, ctx, *, ipaddress: str=""): ipaddress = ipaddress.casefold().replace(" ", "") or "mc.hypixel.net" try: res = await funcs.getRequest(f"https://api.mcsrvstat.us/2/{ipaddress}", headers={"accept": "application/json"}) data = res.json() status = data["online"] e = Embed(title="Minecraft Server Status", colour=Colour.green() if status else Colour.red()) e.add_field(name="Server Address", value=f"`{ipaddress}`") e.add_field(name="Online", value=f"`{status}`") if status: players = data["players"]["online"] e.add_field(name="Player Count", value="`{:,}/{:,}`".format(players, data['players']['max'])) if players: try: playerLimit = 25 playerList = data["players"]["list"][:playerLimit] listStr = ", ".join(f"`{player}`" for player in playerList) if len(playerList) != players: listStr += f" *and {players - playerLimit} more...*" e.add_field(name="Players", value=listStr) except: pass e.add_field(name="Version", value=f'`{data["version"]}`') e.add_field(name="Port", value=f'`{data["port"]}`') e.set_thumbnail(url=f"https://eu.mc-api.net/v3/server/favicon/{ipaddress}") try: e.add_field(name="Software", value=f'`{data["software"]}`') except: pass motd = data["motd"]["clean"] try: secondLine = f"\n{motd[1].strip().replace('&amp;', '&')}" except: secondLine = "" e.set_footer(text=motd[0].strip().replace('&amp;', '&') + secondLine) except Exception as ex: funcs.printError(ctx, ex) e = funcs.errorEmbed(None, "Invalid server address or server error?") await ctx.reply(embed=e) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="fossils", description="Brings up a fossil identification chart for divine travel.", aliases=["ft", "fossiltable", "fossilchart", "fossil"]) async def fossils(self, ctx): url = "https://cdn.discordapp.com/attachments/771404776410972161/842022227347636264/fossiltable.jpg" await funcs.sendImage( ctx, url, message="PDF: https://cdn.discordapp.com/attachments/817309668924719144/"+ "818310310153814056/Fossil_origin_identification_1.pdf" ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="divinetravel", aliases=["dt", "divine", "div", "dv"], usage="[option OR F3+I data]", description="Either brings up the chart for divine travel or gets certain divine coordinates. You can use o" + "ptions like `fossilX` with X being the x-coordinate of the fossil origin, or look at the fo" + "ssil origin in the game, press F3+I, and paste your clipboard as an argument for this command.") async def divinetravel(self, ctx, *, option: str=""): if option: try: try: x, _, _ = self.f3iProcessing(option) option = "fossil" + str(x) except: pass res = self.divinetravel[option.casefold().replace(" ", "")].split(" | ") e = Embed(title="Divine Travel: " + option.casefold().replace(" ", "")) for i, c in enumerate(res): if i > 2: text = f"High Roll #{i - 2}" else: text = f"Stronghold #{i + 1}" e.add_field(name=f"{text}", value=f"`{c.split(': ')[1]}`") except KeyError: e = funcs.errorEmbed( "Invalid option!", "Valid options:\n\n{}".format(", ".join(f"`{opt}`" for opt in self.divinetravel.keys())) ) await ctx.reply(embed=e) else: url = "https://media.discordapp.net/attachments/771698457391136798/934726825811275816/unknown.png" await funcs.sendImage(ctx, url) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="bastions", description="Shows the comprehensive guides to bastions.", hidden=True, aliases=["bastion"]) async def bastions(self, ctx): await ctx.reply("Guides: https://youtube.com/playlist?list=PL7Q35RXRsOR-udeKzwlYGJd0ZrvGJ0fwu\n\nP" + "ractice Map: https://github.com/LlamaPag/bastion\n\nGuide to Practice Map: <https://youtu.be/jlA-jW7VGqw>") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="endpractice", description="Shows the end practice map by ryguy2k4.", hidden=True, aliases=["end", "endfight", "endpractise"]) async def endpractice(self, ctx): await ctx.reply("https://github.com/ryguy2k4/ryguy2k4endpractice/releases") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="obt", description="Shows the One Block Tower tutorial for 1.7.", hidden=True, aliases=["tower1.7", "1.7tower", "oneblock", "oneblocktower"]) async def obt(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=nYI6wOM1U4A") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="zentower", description="Shows the Zen Tower tutorial for 1.8.", hidden=True, aliases=["tower1.8", "1.8tower", "zen"]) async def zentower(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=ryo3QbH2Zko") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="1.15route", description="Shows the 1.15 route.", hidden=True, aliases=["route1.15", "1.15routing", "routing1.15", "routing115", "115route", "115routing", "route115", "1.15", "115", "doubleday"]) async def route115(self, ctx): await ctx.reply("https://imgur.com/gallery/CFJYKmw\n\nDouble Day In-Depth Guide: " + "https://docs.google.com/document/d/1JhDCCpDww3o3oueROpP1lp01JaulaTdm-EhGOfgvkmk/edit") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="mapless", description="Shows the mapless treasure tutorial and practice map.", hidden=True, aliases=["buriedtreasure"]) async def mapless(self, ctx): await ctx.reply("Tutorials: https://youtu.be/ho1rwmooHRg\n\nhttps://youtu.be/_dyD8ZwagDg" + "\n\nPractice Map: <https://cdn.discordapp.com/att" + "achments/405839885509984256/885694752056541234/Mapless_Map.zip>") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="quadrants1.16", description="Shows the four Nether quadrants for versions 1.16+.", hidden=True, aliases=["netheregions", "netheregion", "netherregion", "netherregions", "nether", "quadrant", "quadrants"]) async def quadrants116(self, ctx): await funcs.sendImage(ctx, "https://media.discordapp.net/attachments/771404776410972161/937755369072107520/ejAZNGq.png") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="bedtiming", description="Shows the accurate bed timing for end fights.", hidden=True, aliases=["bedtimings", "onecycle", "timingbed", "bedtime", "bed", "beds"]) async def bedtiming(self, ctx): await funcs.sendImage(ctx, "https://media.discordapp.net/attachments/771698457391136798/937078099789635614/unknown.png") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="1.8trading", description="Shows the trading tutorial for 1.8.", hidden=True, aliases=["pre1.9trading", "trading1.8", "trading18", "18trading", "tradingpre1.9", "trading"]) async def trading18(self, ctx): await funcs.sendImage(ctx, "https://cdn.discordapp.com/attachments/771404776410972161/959506805908705320/unknown.png", message="https://youtu.be/1ksc3SSJkxs") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="ninjabrainbot", aliases=["ninjabot", "ninjabrain", "nb", "nbb"], hidden=True, description="Shows the Ninjabrain Bot tutorial and repository page.") async def ninjabrainbot(self, ctx): await ctx.reply("Tutorial: https://youtu.be/Rx8i7e5lu7g\n\nRepository: https://github.com/Ninjabrain1/Ninjabrain-Bot") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="blazefights", aliases=["blazefight", "blaze", "blazes", "fortress", "fortresses"], hidden=True, description="Shows the tutorial for Nether fortresses and blaze fights.") async def blazefights(self, ctx): await ctx.reply("https://youtu.be/pmx9LyUvLTk") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="eray", aliases=["eraying", "microlensing"], hidden=True, description="Shows the microlensing tutorial.") async def eray(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=jvTfMLPnMSw") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="magmaravines", aliases=["ravine", "magmaravine", "magma", "ravines", "oceanravine", "oceanravines"], description="Shows the guide to magma ravines.", hidden=True) async def magmaravines(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=yGyMWYhHYoQ") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="hypermodern", aliases=["hyperm", "hmodern"], hidden=True, description="Shows the guide to hypermodern speedruns.") async def hypermodern(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=gAHMJfsrHe4") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="blindtravelcoords", aliases=["rings", "strongholdrings", "strongholdring"], hidden=True, description="Shows the ideal blind travel coordinates for the first to third stronghold rings.") async def blindtravelcoords(self, ctx): await ctx.reply("https://imgur.com/gallery/i3fIanf") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="mcspeedrunning", description="Shows some important *Minecraft: Java Edition* speedrunning resources.", aliases=["mcspeedrun", "minecraftspeedrun", "minecraftspeedrunning", "mcsr", "speedrun"]) async def mcspeedrunning(self, ctx): await ctx.reply( "Setup Guide: https://www.youtube.com/watch?v=GAbnKAyireM\n\nWebsite: https://www.minecraftspeedrunning.com/" ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="doubleinstant", aliases=["doubleinstanttravel", "doubleinstanttrav", "dit", "di"], description="Shows the tutorial for Double Instant Travel for pre-1.9 trading.", hidden=True) async def doubleinstant(self, ctx): await ctx.reply("https://youtu.be/XuZWIJRCyaY") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="speedrunigt", aliases=["igt"], description="Download the SpeedRunIGT mod here.", hidden=True) async def speedrunigt(self, ctx): await ctx.reply("https://redlime.github.io/SpeedRunIGT/") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="contariacalc", description="Download ContariaCalc here.", hidden=True) async def contariacalc(self, ctx): await ctx.reply("https://github.com/KingContaria/ContariaCalc") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="strongholdnav", aliases=["stronghold", "sh", "strongholds", "nav"], description="Shows the guides to stronghold navigation and hidden rooms.", hidden=True) async def strongholdnav(self, ctx): await ctx.reply("https://www.youtube.com/watch?v=hEZfeUWA3hM\n\nhttps://www.youtube.com/watch?v=vztJNmUdyBY" + "\n\nhttps://www.youtube.com/watch?v=2dWq2wXy43M (**NEW**)") @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="ruinedportals", description="Shows some useful ruined portal resources.", hidden=True, aliases=["rp", "ruinedportal", "ruined", "ruinportal", "ruinportals", "ruin"]) async def ruinedportals(self, ctx): await ctx.reply( "Quick Completion Guide: https://www.youtube.com/watch?v=Bg_TVoo8waM", file=(await funcs.getImageFile( "https://media.discordapp.net/attachments/771404776410972161/939500126903336960/unknown.png" )) ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="zerocycle", description="Shows some useful Zero Cycle resources.", hidden=True, aliases=["0cycle", "0c", "zero", "zeroc", "zc", "0"]) async def zerocycle(self, ctx): await ctx.reply( "Full Zero Cycle Guide: https://youtu.be/iClDGWL0e5s\n\nResources: https://zerocycle.repl.co/", file=(await funcs.getImageFile( "https://media.discordapp.net/attachments/771404776410972161/938843696009469952/unknown.png" )) ) @commands.cooldown(1, 3, commands.BucketType.user) @commands.command(name="fsg", description="Shows a list of FSG seed generators.", hidden=True, aliases=["fsgseed", "fsgseeds"]) async def fsg(self, ctx): await ctx.reply("Use one of the allowed generators: " + "<https://docs.google.com/spreadsheets/d/1ilu72GJ-vJZq2LFU68rycGMeTbWPjHJnO8PGfp4QjA8/edit#gid=0>\n\n" + "If you would like to use the generator locally for shorter wait times, follow this: " + "<https://youtu.be/Gl7zOn2lLo4>\n\nPlease play the seed within 30 seconds after it has been generated.") setup = Minecraft.setup
en
0.519113
# Credit - https://github.com/Sharpieman20/Sharpies-Speedrunning-Tools # For blindtravel, doubletravel, educatedtravel, safeblind, triangulation # Credit - https://github.com/FourGoesFast/PerfectTravelBot # For divinetravel, perfecttravel #1> <z #1> <angle #1> <x #2> <z #2> <angle #2>") #1> <z #1> <x #2> <z #2>\n\nAlternative usage(s):\n\n- <F3+C data> <x> <z>") #{i - 2}" #{i + 1}" #gid=0>\n\n" +
2.119382
2
pytak/functions.py
joshuafuller/pytak
22
6624298
<filename>pytak/functions.py #!/usr/bin/env python # -*- coding: utf-8 -*- """PyTAK Functions.""" import asyncio import datetime import os import socket import ssl import xml import xml.etree.ElementTree import pytak import pytak.asyncio_dgram __author__ = "<NAME> W2GMD <<EMAIL>>" __copyright__ = "Copyright 2021 Orion Labs, Inc." __license__ = "Apache License, Version 2.0" def split_host(host, port: int = None) -> tuple: """Given a host:port and/or port, returns host, port.""" if ":" in host: addr, port = host.split(":") port = int(port) elif port: addr = host port = int(port) else: addr = host port = int(pytak.DEFAULT_COT_PORT) return addr, port def parse_cot_url(url) -> tuple: """Parses a Cursor on Target destination URL.""" if ":" in url.path: host, port = str(url.path).split(":") else: host = url.path if "broadcast" in url.scheme: port = pytak.DEFAULT_BROADCAST_PORT else: port = pytak.DEFAULT_COT_PORT return host, port def hello_event(uid="pytak") -> str: """Generates a Hello CoT Event.""" time = datetime.datetime.now(datetime.timezone.utc) root = xml.etree.ElementTree.Element("event") root.set("version", "2.0") root.set("type", "t-x-d-d") root.set("uid", uid) root.set("how", "m-g") root.set("time", time.strftime(pytak.ISO_8601_UTC)) root.set("start", time.strftime(pytak.ISO_8601_UTC)) root.set("stale", (time + datetime.timedelta(hours=1)).strftime(pytak.ISO_8601_UTC) ) return xml.etree.ElementTree.tostring(root)
<filename>pytak/functions.py #!/usr/bin/env python # -*- coding: utf-8 -*- """PyTAK Functions.""" import asyncio import datetime import os import socket import ssl import xml import xml.etree.ElementTree import pytak import pytak.asyncio_dgram __author__ = "<NAME> W2GMD <<EMAIL>>" __copyright__ = "Copyright 2021 Orion Labs, Inc." __license__ = "Apache License, Version 2.0" def split_host(host, port: int = None) -> tuple: """Given a host:port and/or port, returns host, port.""" if ":" in host: addr, port = host.split(":") port = int(port) elif port: addr = host port = int(port) else: addr = host port = int(pytak.DEFAULT_COT_PORT) return addr, port def parse_cot_url(url) -> tuple: """Parses a Cursor on Target destination URL.""" if ":" in url.path: host, port = str(url.path).split(":") else: host = url.path if "broadcast" in url.scheme: port = pytak.DEFAULT_BROADCAST_PORT else: port = pytak.DEFAULT_COT_PORT return host, port def hello_event(uid="pytak") -> str: """Generates a Hello CoT Event.""" time = datetime.datetime.now(datetime.timezone.utc) root = xml.etree.ElementTree.Element("event") root.set("version", "2.0") root.set("type", "t-x-d-d") root.set("uid", uid) root.set("how", "m-g") root.set("time", time.strftime(pytak.ISO_8601_UTC)) root.set("start", time.strftime(pytak.ISO_8601_UTC)) root.set("stale", (time + datetime.timedelta(hours=1)).strftime(pytak.ISO_8601_UTC) ) return xml.etree.ElementTree.tostring(root)
en
0.437154
#!/usr/bin/env python # -*- coding: utf-8 -*- PyTAK Functions. Given a host:port and/or port, returns host, port. Parses a Cursor on Target destination URL. Generates a Hello CoT Event.
2.651839
3
advenshare.py
ssfrr/adventshare
0
6624299
<gh_stars>0 HTML_DIR = '' from flask import Flask, send_from_directory # , request from flask_sockets import Sockets from geventwebsocket import WebSocketError import json import logging import coloredlogs app = Flask(__name__) sockets = Sockets(app) coloredlogs.install(logging.INFO) logger = logging.getLogger(__name__) # list of sessions is keyed on their IDs sessions = {} # define message type strings ANNOUNCE = 'announce' JOIN_SESSION = 'joinSession' JOIN_SESSION_RESPONSE = 'joinSessionResponse' CREATE_SESSION = 'createSession' USER_LEFT_SESSION = 'userLeftSession' GET_SESSION_INFO = 'getSessionInfo' MOUSE_DOWN = 'mouseDown' MOUSE_UP = 'mouseUp' MOUSE_MOVE = 'mouseMove' MOUSE_OUT = 'mouseOut' MOUSE_MSGS = [MOUSE_MOVE, MOUSE_DOWN, MOUSE_UP, MOUSE_OUT] class Session(object): def __init__(self, id, name, host): self.id = id self.name = name self.host = host self.guests = {} self.active_user = host host.session = self def add_guest(self, user): self.guests[user.id] = user user.session = self def remove_guest(self, user): if user == self.active_user: self.active_user = self.host del self.guests[user.id] user.session = None msg = { 'type': USER_LEFT_SESSION, 'id': user.id } self.host.send(msg) for guest in self.guests.values(): guest.send(msg) def handle_msg(self, msg, src_user): destID = msg['destID'] if msg['type'] == MOUSE_DOWN: self.active_user = src_user logger.info("Setting active user to %s for session %s" % (src_user.name, self.name)) if destID == '*': if src_user != self.host: self.host.send(msg) for guest in self.guests.itervalues(): if guest != src_user: guest.send(msg) elif destID == self.host.id: self.host.send(msg) else: try: self.guests[destID].send(msg) except KeyError: user_error(src_user.ws, "Unknown Destination: %s" % msg) def close(self): # it's important here that values() makes a copy because we're about to # start mutating the guests dict self.host.session = None for guest in self.guests.values(): self.remove_guest(guest) def to_dict(self): return { 'id': self.id, 'name': self.name, 'host': self.host.to_dict(), 'guests': [guest.to_dict() for guest in self.guests.values()] } def to_json(self): return json.dumps(self.to_dict()) class User(object): def __init__(self, ws, id, name, active_mouse_only=False): self.id = id self.ws = ws self.name = name self.session = None self.active_mouse_only = active_mouse_only def send(self, msg): if msg['type'] in MOUSE_MSGS and \ self.active_mouse_only and \ self.session is not None and \ msg['srcID'] != self.session.active_user.id: # this isn't from the active user, so don't send it down return msg_str = json.dumps(msg) try: self.ws.send(msg_str) except WebSocketError: if self.session is not None: self.session.remove_guest(self) def is_host(self): if self.session is None: return False if self.session.host is None: return False if self.session.host == self: return True def disconnect(self): if self.session is None: return if self.is_host(): self.session.close() else: self.session.remove_guest(self) def to_dict(self): return { 'id': self.id, 'name': self.name, } def to_json(self): return json.dumps(self.to_dict()) @app.route('/') def index_view(): return send_from_directory(HTML_DIR, 'index.html') @sockets.route('/ws/user') def user_ws_view(ws): user = None logger.info("User Connected") # wait for the session offer while(True): try: msg = ws.receive() except: logger.info("User Disconnected") if user is not None: user.disconnect() return if msg is None: logger.info("Got None from User, Disconnected") if user is not None: user.disconnect() return try: msg = json.loads(msg) except: user_error(ws, 'Invalid JSON: "%s"' % msg) continue logging.info('Received WS Msg: %s' % msg) if not msg_is_valid(ws, msg): continue if user is None: if msg['type'] == ANNOUNCE: active_mouse_only = False if 'activeMouseOnly' in msg: active_mouse_only = msg['activeMouseOnly'] user = User(ws, msg['srcID'], msg['userName'], active_mouse_only) else: user_error(ws, 'First message must be of type "%s"' % ANNOUNCE) continue elif msg['type'] == ANNOUNCE: logger.warning("Double-announce. Ignored.") continue elif msg['srcID'] != user.id: user_error( ws, "Can't change User ID within the same connection") continue handle_user_msg(msg, user) def all_present(dic, attrs): '''Tests to make sure all the listed attributes are present in the given dictionary''' for attr in attrs: if attr not in dic: return False return True def handle_user_msg(msg, user): if msg['type'] == CREATE_SESSION: session = Session(msg['sessionID'], msg['sessionName'], user) sessions[session.id] = session logger.info('Session "%s" created by %s. ID: %s' % ( session.name, session.host.name, session.id)) return if msg['type'] == JOIN_SESSION: try: session = sessions[msg['sessionID']] except KeyError: user.send({ 'type': JOIN_SESSION_RESPONSE, 'status': "Invalid sessionID: %s" % msg['sessionID'] }) logger.warn("Invalid sessionID: %s" % msg['sessionID']) return session.add_guest(user) resp = { 'type': JOIN_SESSION_RESPONSE, 'status': 'success', } resp.update(session.to_dict()) user.send(resp) logger.info('User %s joined session %s' % (user.name, session.name)) return # all other messages get dispatched to their session try: sessions[msg['sessionID']].handle_msg(msg, user) except KeyError: user_error(user.ws, "Invalid sessionID: %s" % msg['sessionID']) def user_error(ws, msg): logger.warn(msg) err = json.dumps({ 'type': 'error', 'message': msg }) ws.send(err) common_required_msg_fields = ['type', 'srcID'] required_msg_fields = { ANNOUNCE: ['userName'], JOIN_SESSION: ['sessionID'], CREATE_SESSION: ['sessionName', 'sessionID'] } def msg_is_valid(ws, msg): if 'type' not in msg: user_error(ws, 'No "type" field in msg: "%s"' % msg) return False extra_fields = required_msg_fields.get(msg['type'], []) fields = common_required_msg_fields + extra_fields for field in fields: if field not in msg: user_error(ws, 'No "%s" field in msg: "%s"' % (field, msg)) return False return True
HTML_DIR = '' from flask import Flask, send_from_directory # , request from flask_sockets import Sockets from geventwebsocket import WebSocketError import json import logging import coloredlogs app = Flask(__name__) sockets = Sockets(app) coloredlogs.install(logging.INFO) logger = logging.getLogger(__name__) # list of sessions is keyed on their IDs sessions = {} # define message type strings ANNOUNCE = 'announce' JOIN_SESSION = 'joinSession' JOIN_SESSION_RESPONSE = 'joinSessionResponse' CREATE_SESSION = 'createSession' USER_LEFT_SESSION = 'userLeftSession' GET_SESSION_INFO = 'getSessionInfo' MOUSE_DOWN = 'mouseDown' MOUSE_UP = 'mouseUp' MOUSE_MOVE = 'mouseMove' MOUSE_OUT = 'mouseOut' MOUSE_MSGS = [MOUSE_MOVE, MOUSE_DOWN, MOUSE_UP, MOUSE_OUT] class Session(object): def __init__(self, id, name, host): self.id = id self.name = name self.host = host self.guests = {} self.active_user = host host.session = self def add_guest(self, user): self.guests[user.id] = user user.session = self def remove_guest(self, user): if user == self.active_user: self.active_user = self.host del self.guests[user.id] user.session = None msg = { 'type': USER_LEFT_SESSION, 'id': user.id } self.host.send(msg) for guest in self.guests.values(): guest.send(msg) def handle_msg(self, msg, src_user): destID = msg['destID'] if msg['type'] == MOUSE_DOWN: self.active_user = src_user logger.info("Setting active user to %s for session %s" % (src_user.name, self.name)) if destID == '*': if src_user != self.host: self.host.send(msg) for guest in self.guests.itervalues(): if guest != src_user: guest.send(msg) elif destID == self.host.id: self.host.send(msg) else: try: self.guests[destID].send(msg) except KeyError: user_error(src_user.ws, "Unknown Destination: %s" % msg) def close(self): # it's important here that values() makes a copy because we're about to # start mutating the guests dict self.host.session = None for guest in self.guests.values(): self.remove_guest(guest) def to_dict(self): return { 'id': self.id, 'name': self.name, 'host': self.host.to_dict(), 'guests': [guest.to_dict() for guest in self.guests.values()] } def to_json(self): return json.dumps(self.to_dict()) class User(object): def __init__(self, ws, id, name, active_mouse_only=False): self.id = id self.ws = ws self.name = name self.session = None self.active_mouse_only = active_mouse_only def send(self, msg): if msg['type'] in MOUSE_MSGS and \ self.active_mouse_only and \ self.session is not None and \ msg['srcID'] != self.session.active_user.id: # this isn't from the active user, so don't send it down return msg_str = json.dumps(msg) try: self.ws.send(msg_str) except WebSocketError: if self.session is not None: self.session.remove_guest(self) def is_host(self): if self.session is None: return False if self.session.host is None: return False if self.session.host == self: return True def disconnect(self): if self.session is None: return if self.is_host(): self.session.close() else: self.session.remove_guest(self) def to_dict(self): return { 'id': self.id, 'name': self.name, } def to_json(self): return json.dumps(self.to_dict()) @app.route('/') def index_view(): return send_from_directory(HTML_DIR, 'index.html') @sockets.route('/ws/user') def user_ws_view(ws): user = None logger.info("User Connected") # wait for the session offer while(True): try: msg = ws.receive() except: logger.info("User Disconnected") if user is not None: user.disconnect() return if msg is None: logger.info("Got None from User, Disconnected") if user is not None: user.disconnect() return try: msg = json.loads(msg) except: user_error(ws, 'Invalid JSON: "%s"' % msg) continue logging.info('Received WS Msg: %s' % msg) if not msg_is_valid(ws, msg): continue if user is None: if msg['type'] == ANNOUNCE: active_mouse_only = False if 'activeMouseOnly' in msg: active_mouse_only = msg['activeMouseOnly'] user = User(ws, msg['srcID'], msg['userName'], active_mouse_only) else: user_error(ws, 'First message must be of type "%s"' % ANNOUNCE) continue elif msg['type'] == ANNOUNCE: logger.warning("Double-announce. Ignored.") continue elif msg['srcID'] != user.id: user_error( ws, "Can't change User ID within the same connection") continue handle_user_msg(msg, user) def all_present(dic, attrs): '''Tests to make sure all the listed attributes are present in the given dictionary''' for attr in attrs: if attr not in dic: return False return True def handle_user_msg(msg, user): if msg['type'] == CREATE_SESSION: session = Session(msg['sessionID'], msg['sessionName'], user) sessions[session.id] = session logger.info('Session "%s" created by %s. ID: %s' % ( session.name, session.host.name, session.id)) return if msg['type'] == JOIN_SESSION: try: session = sessions[msg['sessionID']] except KeyError: user.send({ 'type': JOIN_SESSION_RESPONSE, 'status': "Invalid sessionID: %s" % msg['sessionID'] }) logger.warn("Invalid sessionID: %s" % msg['sessionID']) return session.add_guest(user) resp = { 'type': JOIN_SESSION_RESPONSE, 'status': 'success', } resp.update(session.to_dict()) user.send(resp) logger.info('User %s joined session %s' % (user.name, session.name)) return # all other messages get dispatched to their session try: sessions[msg['sessionID']].handle_msg(msg, user) except KeyError: user_error(user.ws, "Invalid sessionID: %s" % msg['sessionID']) def user_error(ws, msg): logger.warn(msg) err = json.dumps({ 'type': 'error', 'message': msg }) ws.send(err) common_required_msg_fields = ['type', 'srcID'] required_msg_fields = { ANNOUNCE: ['userName'], JOIN_SESSION: ['sessionID'], CREATE_SESSION: ['sessionName', 'sessionID'] } def msg_is_valid(ws, msg): if 'type' not in msg: user_error(ws, 'No "type" field in msg: "%s"' % msg) return False extra_fields = required_msg_fields.get(msg['type'], []) fields = common_required_msg_fields + extra_fields for field in fields: if field not in msg: user_error(ws, 'No "%s" field in msg: "%s"' % (field, msg)) return False return True
en
0.941869
# , request # list of sessions is keyed on their IDs # define message type strings # it's important here that values() makes a copy because we're about to # start mutating the guests dict # this isn't from the active user, so don't send it down # wait for the session offer Tests to make sure all the listed attributes are present in the given dictionary # all other messages get dispatched to their session
2.331361
2
appimagebuilder/recipe/recipe.py
srevinsaju/appimage-builder
0
6624300
# Copyright 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. from appimagebuilder.recipe.errors import RecipeError from appimagebuilder.recipe.schema import RecipeSchema class Recipe: class ItemResolver: def __init__(self, dict, path, fallback=None): self.root = dict self.path = path self.fallback = fallback self.left = None self.right = None self.cur = None self.key = None def resolve(self): self.cur = self.root self.left = [] self.right = self.path.split("/") try: self._resolve_item() except KeyError: self._fallback_or_raise() return self.cur def _resolve_item(self): while self.right: self.key = self.right.pop(0) self.cur = self.cur[self.key] self.left.append(self.key) def _fallback_or_raise(self): if self.fallback is not None: self.cur = self.fallback else: raise RecipeError( "'%s' key required in: %s" % (self.key, "/".join(self.left)) ) def __init__(self, data): self._data = data def get_item(self, path, fallback=None): resolver = Recipe.ItemResolver(self._data, path, fallback) return resolver.resolve()
# Copyright 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. from appimagebuilder.recipe.errors import RecipeError from appimagebuilder.recipe.schema import RecipeSchema class Recipe: class ItemResolver: def __init__(self, dict, path, fallback=None): self.root = dict self.path = path self.fallback = fallback self.left = None self.right = None self.cur = None self.key = None def resolve(self): self.cur = self.root self.left = [] self.right = self.path.split("/") try: self._resolve_item() except KeyError: self._fallback_or_raise() return self.cur def _resolve_item(self): while self.right: self.key = self.right.pop(0) self.cur = self.cur[self.key] self.left.append(self.key) def _fallback_or_raise(self): if self.fallback is not None: self.cur = self.fallback else: raise RecipeError( "'%s' key required in: %s" % (self.key, "/".join(self.left)) ) def __init__(self, data): self._data = data def get_item(self, path, fallback=None): resolver = Recipe.ItemResolver(self._data, path, fallback) return resolver.resolve()
en
0.882815
# Copyright 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software.
2.121066
2
mcs-jr.py
clarkdever/mission-control-station-pi
0
6624301
import mplayer, evdev # Joystics pl1 = evdev.InputDevice('/dev/input/by-path/platform-3f980000.usb-usb-0:1.5:1.0-event-joystick') pl2 = evdev.InputDevice('/dev/input/by-path/platform-3f980000.usb-usb-0:1.3:1.0-event-joystick') # Initialize video p = mplayer.Player() p.loadfile("ChildrensMCS.mp4") p.fullstrceen = True p.loop = 0 p.osdlevel = 0 # Disables on-screen UI scrub_speed = 5 # How many seconds skipping ahead/back playhead = p.time_pos playhead_dirty = False vid_length = p.length # Player inputs stick = { 'UP': 297, 'DOWN': 296, 'LEFT': 299, 'RIGHT': 298, 'LWHITE': 290, 'LBLACK': 288, 'GREEN': 291, 'YELLOW': 289, 'BLUE': 292, 'RED': 293, 'RWHITE': 294, 'RBLACK': 295 } # Dictionary of clips clips = { 'Solar System': { 'start': 0, 'length': 232 }, 'Mission Control': { 'start': 233, 'length': 62 }, 'Orbital Mechanics': { 'start': 294, 'length': 148 }, 'Apollo 8 Launch': { 'start': 442, 'length': 221 }, 'STS Launch': { 'start': 654, 'length': 136 }, 'STS Landing': { 'start': 789, 'length': 53 }, 'Insight Landing': { 'start': 852, 'length': 142 }, 'Moon Rocks': { 'start': 994, 'length': 55 }, 'ISS': { 'start': 1049, 'length': 51 }, 'Baby Shark': { 'start': 1100, 'length': 95 }, 'Minions Babarang': { 'start': 1196, 'length': 39 }, 'Minions Happy': { 'start': 1235, 'length': 233 }, 'Moana - You\'re Welcome': { 'start': 1467, 'length': 164 }, 'Be Our Guest': { 'start': 1631, 'length': 209 }, 'Ho Hey': { 'start': 1840, 'length': 160 }, '<NAME>': { 'start': 2001, 'length': 230 }, 'Moana - How Far I\'ll Go': { 'start': 2231, 'length': 151 }, 'Under The Sea': { 'start': 2382, 'length': 197 }, 'Whistle While You Work': { 'start': 2581, 'length': 216 }, 'Let It Go': { 'start': 2795, 'length': 220 }, 'Dad': { 'start': 3051, 'length': 15 } } clip_end = clips['Solar System']['length'] def scrub(val): global playhead global playhead_dirty global vid_length if playhead is None or vid_length is None: return # mplayer's time_pos is None when spinning up the process/loading the video x = playhead + val if x < 0: playhead = vid_length + x if x > vid_length: playhead = 0 + (x - vid_length) else: playhead += val playhead_dirty = True def pause(): p.pause() def play_clip(clip): global playhead global playhead_dirty global clip_end try: playhead = clips[clip]['start'] playhead_dirty = True except: print("Error playing clip", clip) def print_btn(btn): print(btn.name) def poll_input(): ev1 = pl1.read_one() ev2 = pl2.read_one() #if ev1 is not None: while True: ev1 = pl1.read_one() if ev1 is None: break # No more input, so break out of the loop # Do player 1 stuff here if ev1.type == 1 and ev1.value == 1: # Button Input if ev1.code == stick['LEFT']: scrub(-scrub_speed) if ev1.code == stick['RIGHT']: scrub(scrub_speed) if ev1.code == stick['UP']: pause() if ev1.code == stick['DOWN']: play_clip('Solar System') if ev1.code == stick['LWHITE']: play_clip('Mission Control') if ev1.code == stick['GREEN']: play_clip('Orbital Mechanics') if ev1.code == stick['BLUE']: play_clip('Apollo 8 Launch') if ev1.code == stick['RWHITE']: play_clip('STS Launch') if ev1.code == stick['LBLACK']: play_clip('STS Landing') if ev1.code == stick['YELLOW']: play_clip('Insight Landing') if ev1.code == stick['RED']: play_clip('Moon Rocks') if ev1.code == stick['RBLACK']: play_clip('ISS') while True: ev2 = pl2.read_one() if ev2 is None: break # Do player 2 stuff here if ev2.type == 1 and ev2.value == 1: if ev2.code == stick['LEFT']: play_clip('B<NAME>') if ev2.code == stick['RIGHT']: play_clip('Minions Babarang') if ev2.code == stick['UP']: play_clip('Minions Happy') if ev2.code == stick['DOWN']: play_clip('Moana - You\'re Welcome') if ev2.code == stick['LWHITE']: play_clip('Be Our Guest') if ev2.code == stick['GREEN']: play_clip('Ho Hey') if ev2.code == stick['BLUE']: play_clip('<NAME>') if ev2.code == stick['RWHITE']: play_clip('Moana - How Far I\'ll Go') if ev2.code == stick['LBLACK']: play_clip('Under The Sea') if ev2.code == stick['YELLOW']: play_clip('Whistle While You Work') if ev2.code == stick['RED']: play_clip('Let It Go') if ev2.code == stick['RBLACK']: play_clip('Dad') while True: if not p.fullscreen: p.fullscreen = True poll_input() if vid_length is None: vid_length = p.length if playhead_dirty: p.time_pos = playhead playhead_dirty = False else: playhead = p.time_pos
import mplayer, evdev # Joystics pl1 = evdev.InputDevice('/dev/input/by-path/platform-3f980000.usb-usb-0:1.5:1.0-event-joystick') pl2 = evdev.InputDevice('/dev/input/by-path/platform-3f980000.usb-usb-0:1.3:1.0-event-joystick') # Initialize video p = mplayer.Player() p.loadfile("ChildrensMCS.mp4") p.fullstrceen = True p.loop = 0 p.osdlevel = 0 # Disables on-screen UI scrub_speed = 5 # How many seconds skipping ahead/back playhead = p.time_pos playhead_dirty = False vid_length = p.length # Player inputs stick = { 'UP': 297, 'DOWN': 296, 'LEFT': 299, 'RIGHT': 298, 'LWHITE': 290, 'LBLACK': 288, 'GREEN': 291, 'YELLOW': 289, 'BLUE': 292, 'RED': 293, 'RWHITE': 294, 'RBLACK': 295 } # Dictionary of clips clips = { 'Solar System': { 'start': 0, 'length': 232 }, 'Mission Control': { 'start': 233, 'length': 62 }, 'Orbital Mechanics': { 'start': 294, 'length': 148 }, 'Apollo 8 Launch': { 'start': 442, 'length': 221 }, 'STS Launch': { 'start': 654, 'length': 136 }, 'STS Landing': { 'start': 789, 'length': 53 }, 'Insight Landing': { 'start': 852, 'length': 142 }, 'Moon Rocks': { 'start': 994, 'length': 55 }, 'ISS': { 'start': 1049, 'length': 51 }, 'Baby Shark': { 'start': 1100, 'length': 95 }, 'Minions Babarang': { 'start': 1196, 'length': 39 }, 'Minions Happy': { 'start': 1235, 'length': 233 }, 'Moana - You\'re Welcome': { 'start': 1467, 'length': 164 }, 'Be Our Guest': { 'start': 1631, 'length': 209 }, 'Ho Hey': { 'start': 1840, 'length': 160 }, '<NAME>': { 'start': 2001, 'length': 230 }, 'Moana - How Far I\'ll Go': { 'start': 2231, 'length': 151 }, 'Under The Sea': { 'start': 2382, 'length': 197 }, 'Whistle While You Work': { 'start': 2581, 'length': 216 }, 'Let It Go': { 'start': 2795, 'length': 220 }, 'Dad': { 'start': 3051, 'length': 15 } } clip_end = clips['Solar System']['length'] def scrub(val): global playhead global playhead_dirty global vid_length if playhead is None or vid_length is None: return # mplayer's time_pos is None when spinning up the process/loading the video x = playhead + val if x < 0: playhead = vid_length + x if x > vid_length: playhead = 0 + (x - vid_length) else: playhead += val playhead_dirty = True def pause(): p.pause() def play_clip(clip): global playhead global playhead_dirty global clip_end try: playhead = clips[clip]['start'] playhead_dirty = True except: print("Error playing clip", clip) def print_btn(btn): print(btn.name) def poll_input(): ev1 = pl1.read_one() ev2 = pl2.read_one() #if ev1 is not None: while True: ev1 = pl1.read_one() if ev1 is None: break # No more input, so break out of the loop # Do player 1 stuff here if ev1.type == 1 and ev1.value == 1: # Button Input if ev1.code == stick['LEFT']: scrub(-scrub_speed) if ev1.code == stick['RIGHT']: scrub(scrub_speed) if ev1.code == stick['UP']: pause() if ev1.code == stick['DOWN']: play_clip('Solar System') if ev1.code == stick['LWHITE']: play_clip('Mission Control') if ev1.code == stick['GREEN']: play_clip('Orbital Mechanics') if ev1.code == stick['BLUE']: play_clip('Apollo 8 Launch') if ev1.code == stick['RWHITE']: play_clip('STS Launch') if ev1.code == stick['LBLACK']: play_clip('STS Landing') if ev1.code == stick['YELLOW']: play_clip('Insight Landing') if ev1.code == stick['RED']: play_clip('Moon Rocks') if ev1.code == stick['RBLACK']: play_clip('ISS') while True: ev2 = pl2.read_one() if ev2 is None: break # Do player 2 stuff here if ev2.type == 1 and ev2.value == 1: if ev2.code == stick['LEFT']: play_clip('B<NAME>') if ev2.code == stick['RIGHT']: play_clip('Minions Babarang') if ev2.code == stick['UP']: play_clip('Minions Happy') if ev2.code == stick['DOWN']: play_clip('Moana - You\'re Welcome') if ev2.code == stick['LWHITE']: play_clip('Be Our Guest') if ev2.code == stick['GREEN']: play_clip('Ho Hey') if ev2.code == stick['BLUE']: play_clip('<NAME>') if ev2.code == stick['RWHITE']: play_clip('Moana - How Far I\'ll Go') if ev2.code == stick['LBLACK']: play_clip('Under The Sea') if ev2.code == stick['YELLOW']: play_clip('Whistle While You Work') if ev2.code == stick['RED']: play_clip('Let It Go') if ev2.code == stick['RBLACK']: play_clip('Dad') while True: if not p.fullscreen: p.fullscreen = True poll_input() if vid_length is None: vid_length = p.length if playhead_dirty: p.time_pos = playhead playhead_dirty = False else: playhead = p.time_pos
en
0.790344
# Joystics # Initialize video # Disables on-screen UI # How many seconds skipping ahead/back # Player inputs # Dictionary of clips # mplayer's time_pos is None when spinning up the process/loading the video #if ev1 is not None: # No more input, so break out of the loop # Do player 1 stuff here # Button Input # Do player 2 stuff here
1.862079
2
tests/test_cli_mutation_map.py
DerThorsten/kipoi-veff
5
6624302
import sys import pytest import os import subprocess import config if config.install_req: INSTALL_FLAG = "--install_req" else: INSTALL_FLAG = "" EXAMPLES_TO_RUN = ["rbp"] @pytest.mark.parametrize("example", EXAMPLES_TO_RUN) @pytest.mark.parametrize("new_dataloader_kwargs_format", [False, True]) def test_generate_mutation_maps_example(example, new_dataloader_kwargs_format, tmpdir): """kipoi predict ... """ if (example not in {"rbp"}) or (sys.version_info[0] == 2): pytest.skip("Only rbp example testable at the moment, which only runs on py3") example_dir = "tests/models/{0}/".format(example) tmpdir_here = tmpdir.mkdir("example") # restricted_bed = False mm_tmpfile = str(tmpdir_here.join("out_mm.hdf5")) plt_tmpfile = str(tmpdir_here.join("plot.png")) dataloader_kwargs = {"fasta_file": "example_files/hg38_chr22.fa", "preproc_transformer": "dataloader_files/encodeSplines.pkl", "gtf_file": "example_files/gencode_v25_chr22.gtf.pkl.gz", "intervals_file": "example_files/variant_intervals.tsv"} dataloader_kwargs = {k: example_dir + v for k, v in dataloader_kwargs.items()} if not new_dataloader_kwargs_format: import json dataloader_kwargs_str = json.dumps(dataloader_kwargs) args = ["python", os.path.abspath("./kipoi_veff/cli.py"), "create_mutation_map", # "./", # directory example_dir, "--source=dir", "--batch_size=4", "--dataloader_args='%s'" % dataloader_kwargs_str, "--regions_file", example_dir + "example_files/first_variant.vcf", "--output", mm_tmpfile] else: dataloader_kwargs_list = ["{0}={1}".format(key, val) for key,val in dataloader_kwargs.items()] args = ["python", os.path.abspath("./kipoi_veff/cli.py"), "create_mutation_map", # "./", # directory example_dir, "--source=dir", "--batch_size=4", "--dataloader_args"] + dataloader_kwargs_list + ["--regions_file", example_dir + "example_files/first_variant.vcf", "--output", mm_tmpfile] # run the if INSTALL_FLAG: args.append(INSTALL_FLAG) returncode = subprocess.call(args=args, cwd=".") assert returncode == 0 assert os.path.exists(mm_tmpfile) # make the plot args = ["python", os.path.abspath("./kipoi_veff/cli.py"), "plot_mutation_map", "--input_file=" + mm_tmpfile, "--input_entry=0", "--model_seq_input=seq", "--scoring_key=diff", "--model_output=rbp_prb", "--limit_region_genomic", "21541588", "21541592", "--rc_plot", "--output", plt_tmpfile] returncode = subprocess.call(args=args, cwd=os.path.realpath(example_dir)) assert returncode == 0 assert os.path.exists(plt_tmpfile) os.unlink(mm_tmpfile) os.unlink(plt_tmpfile)
import sys import pytest import os import subprocess import config if config.install_req: INSTALL_FLAG = "--install_req" else: INSTALL_FLAG = "" EXAMPLES_TO_RUN = ["rbp"] @pytest.mark.parametrize("example", EXAMPLES_TO_RUN) @pytest.mark.parametrize("new_dataloader_kwargs_format", [False, True]) def test_generate_mutation_maps_example(example, new_dataloader_kwargs_format, tmpdir): """kipoi predict ... """ if (example not in {"rbp"}) or (sys.version_info[0] == 2): pytest.skip("Only rbp example testable at the moment, which only runs on py3") example_dir = "tests/models/{0}/".format(example) tmpdir_here = tmpdir.mkdir("example") # restricted_bed = False mm_tmpfile = str(tmpdir_here.join("out_mm.hdf5")) plt_tmpfile = str(tmpdir_here.join("plot.png")) dataloader_kwargs = {"fasta_file": "example_files/hg38_chr22.fa", "preproc_transformer": "dataloader_files/encodeSplines.pkl", "gtf_file": "example_files/gencode_v25_chr22.gtf.pkl.gz", "intervals_file": "example_files/variant_intervals.tsv"} dataloader_kwargs = {k: example_dir + v for k, v in dataloader_kwargs.items()} if not new_dataloader_kwargs_format: import json dataloader_kwargs_str = json.dumps(dataloader_kwargs) args = ["python", os.path.abspath("./kipoi_veff/cli.py"), "create_mutation_map", # "./", # directory example_dir, "--source=dir", "--batch_size=4", "--dataloader_args='%s'" % dataloader_kwargs_str, "--regions_file", example_dir + "example_files/first_variant.vcf", "--output", mm_tmpfile] else: dataloader_kwargs_list = ["{0}={1}".format(key, val) for key,val in dataloader_kwargs.items()] args = ["python", os.path.abspath("./kipoi_veff/cli.py"), "create_mutation_map", # "./", # directory example_dir, "--source=dir", "--batch_size=4", "--dataloader_args"] + dataloader_kwargs_list + ["--regions_file", example_dir + "example_files/first_variant.vcf", "--output", mm_tmpfile] # run the if INSTALL_FLAG: args.append(INSTALL_FLAG) returncode = subprocess.call(args=args, cwd=".") assert returncode == 0 assert os.path.exists(mm_tmpfile) # make the plot args = ["python", os.path.abspath("./kipoi_veff/cli.py"), "plot_mutation_map", "--input_file=" + mm_tmpfile, "--input_entry=0", "--model_seq_input=seq", "--scoring_key=diff", "--model_output=rbp_prb", "--limit_region_genomic", "21541588", "21541592", "--rc_plot", "--output", plt_tmpfile] returncode = subprocess.call(args=args, cwd=os.path.realpath(example_dir)) assert returncode == 0 assert os.path.exists(plt_tmpfile) os.unlink(mm_tmpfile) os.unlink(plt_tmpfile)
en
0.58231
kipoi predict ... # restricted_bed = False # "./", # directory # "./", # directory # run the # make the plot
1.7612
2
connectors/interfaces/leaf_connector_interface.py
kefir/snakee
0
6624303
<reponame>kefir/snakee<gh_stars>0 from abc import ABC, abstractmethod from typing import Optional try: # Assume we're a sub-module in a package. from streams.interfaces.abstract_stream_interface import StreamInterface from connectors.content_format.content_type import ContentType from connectors.interfaces.connector_interface import ConnectorInterface from connectors.interfaces.format_interface import ContentFormatInterface except ImportError: # Apparently no higher-level package has been imported, fall back to a local import. from ...streams.interfaces.abstract_stream_interface import StreamInterface from ..content_format.content_type import ContentType from .connector_interface import ConnectorInterface from .format_interface import ContentFormatInterface class LeafConnectorInterface(ConnectorInterface, StreamInterface, ABC): @abstractmethod def get_content_type(self) -> ContentType: pass @abstractmethod def get_content_format(self) -> ContentFormatInterface: pass @abstractmethod def set_content_format(self, content_format: ContentFormatInterface, inplace: bool) -> Optional[ConnectorInterface]: pass @abstractmethod def get_declared_format(self) -> ContentFormatInterface: pass @abstractmethod def is_existing(self) -> bool: pass @abstractmethod def get_first_line(self, close: bool = True) -> Optional[str]: pass @abstractmethod def check(self, must_exists: bool = True): pass @abstractmethod def write_stream(self, stream: StreamInterface, verbose: bool = True): pass @abstractmethod def from_stream(self, stream: StreamInterface): pass @abstractmethod def to_stream(self, **kwargs) -> StreamInterface: pass
from abc import ABC, abstractmethod from typing import Optional try: # Assume we're a sub-module in a package. from streams.interfaces.abstract_stream_interface import StreamInterface from connectors.content_format.content_type import ContentType from connectors.interfaces.connector_interface import ConnectorInterface from connectors.interfaces.format_interface import ContentFormatInterface except ImportError: # Apparently no higher-level package has been imported, fall back to a local import. from ...streams.interfaces.abstract_stream_interface import StreamInterface from ..content_format.content_type import ContentType from .connector_interface import ConnectorInterface from .format_interface import ContentFormatInterface class LeafConnectorInterface(ConnectorInterface, StreamInterface, ABC): @abstractmethod def get_content_type(self) -> ContentType: pass @abstractmethod def get_content_format(self) -> ContentFormatInterface: pass @abstractmethod def set_content_format(self, content_format: ContentFormatInterface, inplace: bool) -> Optional[ConnectorInterface]: pass @abstractmethod def get_declared_format(self) -> ContentFormatInterface: pass @abstractmethod def is_existing(self) -> bool: pass @abstractmethod def get_first_line(self, close: bool = True) -> Optional[str]: pass @abstractmethod def check(self, must_exists: bool = True): pass @abstractmethod def write_stream(self, stream: StreamInterface, verbose: bool = True): pass @abstractmethod def from_stream(self, stream: StreamInterface): pass @abstractmethod def to_stream(self, **kwargs) -> StreamInterface: pass
en
0.845231
# Assume we're a sub-module in a package. # Apparently no higher-level package has been imported, fall back to a local import.
2.60356
3
slither/core/geodetic.py
AlexanderFabisch/slither
2
6624304
import numpy as np import pyproj from .config import config def haversine_dist(lat1, long1, lat2, long2, earth_radius=6371000.0): """Haversine distance between two positions on earth. This is a simple approximation. A better way is to use pyproj, which uses a WGS84 model of the earth. Parameters ---------- lat1 : array-like or float latitude of position 1 in radians long1 : array-like or float longitude of position 1 in radians lat2 : array-like or float latitude of position 2 in radians long2 : array-like or float longitude of position 2 in radians earth_radius : float average radius of the earth in meters, should be between 6353000 and 6384000 Returns ------- distance : float Distance between two positions on the surface of the earth in meters """ lat_dist = lat2 - lat1 long_dist = long2 - long1 a = (np.sin(0.5 * lat_dist) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(0.5 * long_dist) ** 2) angular_dist = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) return earth_radius * angular_dist class PyprojDist: def __init__(self, config): if "geodetic" in config and "ellipsoid" in config["geodetic"]: ellps = config["geodetic"]["ellipsoid"] else: ellps = "WGS84" self.geod = pyproj.Geod(ellps=ellps) def __call__(self, lat1, long1, lat2, long2): """Compute distance between two positions on earth. Parameters ---------- lat1 : array-like or float latitude of position 1 in radians long1 : array-like or float longitude of position 1 in radians lat2 : array-like or float latitude of position 2 in radians long2 : array-like or float longitude of position 2 in radians Returns ------- distance : float Distance between two positions on the surface of the earth in meters """ _, _, dist = self.geod.inv(long1, lat1, long2, lat2, radians=True) return dist dist_on_earth = PyprojDist(config) def compute_velocities(timestamps, coords): """Compute velocities from geodetic coordinates. Parameters ---------- timestamps : array, shape (n_steps,) Timestamps coords : array, shape (n_steps, 2) Latitudes and longitudes in radians Returns ------- velocities : array, shape (n_steps,) Velocities in meters per second total_distance : float Total distance in meters """ delta_t = np.diff(timestamps) dists = dist_on_earth( coords[:-1, 0], coords[:-1, 1], coords[1:, 0], coords[1:, 1]) n_steps = len(timestamps) velocities = np.empty(n_steps) velocities[0] = 0.0 total_distance = 0.0 for t in range(1, n_steps): dt = delta_t[t - 1] if dt <= 0.0: velocity = velocities[t - 1] else: velocity = dists[t - 1] / dt total_distance += dists[t - 1] velocities[t] = velocity return velocities, total_distance
import numpy as np import pyproj from .config import config def haversine_dist(lat1, long1, lat2, long2, earth_radius=6371000.0): """Haversine distance between two positions on earth. This is a simple approximation. A better way is to use pyproj, which uses a WGS84 model of the earth. Parameters ---------- lat1 : array-like or float latitude of position 1 in radians long1 : array-like or float longitude of position 1 in radians lat2 : array-like or float latitude of position 2 in radians long2 : array-like or float longitude of position 2 in radians earth_radius : float average radius of the earth in meters, should be between 6353000 and 6384000 Returns ------- distance : float Distance between two positions on the surface of the earth in meters """ lat_dist = lat2 - lat1 long_dist = long2 - long1 a = (np.sin(0.5 * lat_dist) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(0.5 * long_dist) ** 2) angular_dist = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) return earth_radius * angular_dist class PyprojDist: def __init__(self, config): if "geodetic" in config and "ellipsoid" in config["geodetic"]: ellps = config["geodetic"]["ellipsoid"] else: ellps = "WGS84" self.geod = pyproj.Geod(ellps=ellps) def __call__(self, lat1, long1, lat2, long2): """Compute distance between two positions on earth. Parameters ---------- lat1 : array-like or float latitude of position 1 in radians long1 : array-like or float longitude of position 1 in radians lat2 : array-like or float latitude of position 2 in radians long2 : array-like or float longitude of position 2 in radians Returns ------- distance : float Distance between two positions on the surface of the earth in meters """ _, _, dist = self.geod.inv(long1, lat1, long2, lat2, radians=True) return dist dist_on_earth = PyprojDist(config) def compute_velocities(timestamps, coords): """Compute velocities from geodetic coordinates. Parameters ---------- timestamps : array, shape (n_steps,) Timestamps coords : array, shape (n_steps, 2) Latitudes and longitudes in radians Returns ------- velocities : array, shape (n_steps,) Velocities in meters per second total_distance : float Total distance in meters """ delta_t = np.diff(timestamps) dists = dist_on_earth( coords[:-1, 0], coords[:-1, 1], coords[1:, 0], coords[1:, 1]) n_steps = len(timestamps) velocities = np.empty(n_steps) velocities[0] = 0.0 total_distance = 0.0 for t in range(1, n_steps): dt = delta_t[t - 1] if dt <= 0.0: velocity = velocities[t - 1] else: velocity = dists[t - 1] / dt total_distance += dists[t - 1] velocities[t] = velocity return velocities, total_distance
en
0.624181
Haversine distance between two positions on earth. This is a simple approximation. A better way is to use pyproj, which uses a WGS84 model of the earth. Parameters ---------- lat1 : array-like or float latitude of position 1 in radians long1 : array-like or float longitude of position 1 in radians lat2 : array-like or float latitude of position 2 in radians long2 : array-like or float longitude of position 2 in radians earth_radius : float average radius of the earth in meters, should be between 6353000 and 6384000 Returns ------- distance : float Distance between two positions on the surface of the earth in meters Compute distance between two positions on earth. Parameters ---------- lat1 : array-like or float latitude of position 1 in radians long1 : array-like or float longitude of position 1 in radians lat2 : array-like or float latitude of position 2 in radians long2 : array-like or float longitude of position 2 in radians Returns ------- distance : float Distance between two positions on the surface of the earth in meters Compute velocities from geodetic coordinates. Parameters ---------- timestamps : array, shape (n_steps,) Timestamps coords : array, shape (n_steps, 2) Latitudes and longitudes in radians Returns ------- velocities : array, shape (n_steps,) Velocities in meters per second total_distance : float Total distance in meters
3.512784
4
dipy/reconst/dti.py
Garyfallidis/dipy
3
6624305
<reponame>Garyfallidis/dipy #!/usr/bin/python """ Classes and functions for fitting tensors """ # 5/17/2010 import numpy as np from dipy.reconst.maskedview import MaskedView, _makearray, _filled from dipy.reconst.modelarray import ModelArray from dipy.data import get_sphere class Tensor(ModelArray): """ Fits a diffusion tensor given diffusion-weighted signals and gradient info Tensor object that when initialized calculates single self diffusion tensor [1]_ in each voxel using selected fitting algorithm (DEFAULT: weighted least squares [2]_) Requires a given gradient table, b value for each diffusion-weighted gradient vector, and image data given all as arrays. Parameters ---------- data : array ([X, Y, Z, ...], g) Diffusion-weighted signals. The dimension corresponding to the diffusion weighting must be the last dimenssion bval : array (g,) Diffusion weighting factor b for each vector in gtab. gtab : array (g, 3) Diffusion gradient table found in DICOM header as a array. mask : array, optional The tensor will only be fit where mask is True. Mask must must broadcast to the shape of data and must have fewer dimensions than data thresh : float, default = None The tensor will not be fit where data[bval == 0] < thresh. If multiple b0 volumes are given, the minimum b0 signal is used. fit_method : funciton or string, default = 'WLS' The method to be used to fit the given data to a tensor. Any function that takes the B matrix and the data and returns eigen values and eigen vectors can be passed as the fit method. Any of the common fit methods can be passed as a string. *args, **kargs : Any other arguments or keywards will be passed to fit_method. common fit methods: 'WLS' : weighted least squares dti.wls_fit_tensor 'LS' : ordinary least squares dti.ols_fit_tensor Attributes ---------- D : array (..., 3, 3) Self diffusion tensor calculated from cached eigenvalues and eigenvectors. mask : array True in voxels where a tensor was fit, false if the voxel was skipped B : array (g, 7) Design matrix or B matrix constructed from given gradient table and b-value vector. evals : array (..., 3) Cached eigenvalues of self diffusion tensor for given index. (eval1, eval2, eval3) evecs : array (..., 3, 3) Cached associated eigenvectors of self diffusion tensor for given index. Note: evals[..., j] is associated with evecs[..., :, j] Methods ------- fa : array Calculates fractional anisotropy [2]_. md : array Calculates the mean diffusivity [2]_. Note: [units ADC] ~ [units b value]*10**-1 See Also -------- dipy.io.bvectxt.read_bvec_file, dipy.core.qball.ODF References ---------- .. [1] <NAME>., <NAME>., <NAME>., 1994. Estimation of the effective self-diffusion tensor from the NMR spin echo. J Magn Reson B 103, 247-254. .. [2] <NAME>., <NAME>., 1996. Microstructural and physiological features of tissues elucidated by quantitative diffusion-tensor MRI. Journal of Magnetic Resonance 111, 209-219. Examples ---------- For a complete example have a look at the main dipy/examples folder """ ### Eigenvalues Property ### @property def evals(self): """ Returns the eigenvalues of the tensor as an array """ return _filled(self.model_params[..., :3]) ### Eigenvectors Property ### @property def evecs(self): """ Returns the eigenvectors of teh tensor as an array """ evecs = _filled(self.model_params[..., 3:]) return evecs.reshape(self.shape + (3, 3)) def __init__(self, data, b_values, grad_table, mask=True, thresh=None, fit_method='WLS', verbose=False, *args, **kargs): """ Fits a tensors to diffusion weighted data. """ if not callable(fit_method): try: fit_method = common_fit_methods[fit_method] except KeyError: raise ValueError('"'+str(fit_method)+'" is not a known fit '+ 'method, the fit method should either be a '+ 'function or one of the common fit methods') #64 bit design matrix makes for faster pinv B = design_matrix(grad_table.T, b_values) self.B = B mask = np.atleast_1d(mask) if thresh is not None: #Define total mask from thresh and mask #mask = mask & (np.min(data[..., b_values == 0], -1) > #thresh) #the assumption that the lowest b_value is always 0 is #incorrect the lowest b_value could also be higher than 0 #this is common with grid q-spaces min_b0_sig = np.min(data[..., b_values == b_values.min()], -1) mask = mask & (min_b0_sig > thresh) #if mask is all False if not mask.any(): raise ValueError('between mask and thresh, there is no data to '+ 'fit') #and the mask is not all True if not mask.all(): #leave only data[mask is True] data = data[mask] data = MaskedView(mask, data, fill_value=0) #Perform WLS fit on masked data dti_params = fit_method(B, data, *args, **kargs) self.model_params = dti_params ### Self Diffusion Tensor Property ### def _getD(self): """Calculates the 3x3 diffusion tensor for each voxel""" params, wrap = _makearray(self.model_params) evals = params[..., :3] evecs = params[..., 3:] evals_flat = evals.reshape((-1, 3)) evecs_flat = evecs.reshape((-1, 3, 3)) D_flat = np.empty(evecs_flat.shape) for ii in xrange(len(D_flat)): Q = evecs_flat[ii] L = evals_flat[ii] D_flat[ii] = np.dot(Q*L, Q.T) D = _filled(wrap(D_flat)) D.shape = self.shape + (3, 3) return D D = property(_getD, doc = "Self diffusion tensor") def lower_triangular(self, b0=None): D = self._getD() return lower_triangular(D, b0) def fa(self, fill_value=0, nonans=True): r""" Fractional anisotropy (FA) calculated from cached eigenvalues. Parameters ---------- fill_value : float value of fa where self.mask == True. nonans : Bool When True, fa is 0 when all eigenvalues are 0, otherwise fa is nan Returns --------- fa : array (V, 1) Calculated FA. Note: range is 0 <= FA <= 1. Notes -------- FA is calculated with the following equation: .. math:: FA = \sqrt{\frac{1}{2}\frac{(\lambda_1-\lambda_2)^2+(\lambda_1- \lambda_3)^2+(\lambda_2-lambda_3)^2}{\lambda_1^2+ \lambda_2^2+\lambda_3^2} } """ evals, wrap = _makearray(self.model_params[..., :3]) ev1 = evals[..., 0] ev2 = evals[..., 1] ev3 = evals[..., 2] if nonans: all_zero = (ev1 == 0) & (ev2 == 0) & (ev3 == 0) else: all_zero = 0. fa = np.sqrt(0.5 * ((ev1 - ev2)**2 + (ev2 - ev3)**2 + (ev3 - ev1)**2) / (ev1*ev1 + ev2*ev2 + ev3*ev3 + all_zero)) fa = wrap(np.asarray(fa)) return _filled(fa, fill_value) def md(self): r""" Mean diffusitivity (MD) calculated from cached eigenvalues. Returns --------- md : array (V, 1) Calculated MD. Notes -------- MD is calculated with the following equation: .. math:: ADC = \frac{\lambda_1+\lambda_2+\lambda_3}{3} """ #adc/md = (ev1+ev2+ev3)/3 return self.evals.mean(-1) def ind(self): ''' Quantizes eigenvectors with maximum eigenvalues on an evenly distributed sphere so that the can be used for tractography. Returns --------- IN : array, shape(x,y,z) integer indices for the points of the evenly distributed sphere representing tensor eigenvectors of maximum eigenvalue ''' return quantize_evecs(self.evecs,odf_vertices=None) def wls_fit_tensor(design_matrix, data, min_signal=1): r""" Computes weighted least squares (WLS) fit to calculate self-diffusion tensor using a linear regression model [1]_. Parameters ---------- design_matrix : array (g, 7) Design matrix holding the covariants used to solve for the regression coefficients. data : array ([X, Y, Z, ...], g) Data or response variables holding the data. Note that the last dimension should contain the data. It makes no copies of data. min_signal : default = 1 All values below min_signal are repalced with min_signal. This is done in order to avaid taking log(0) durring the tensor fitting. Returns ------- eigvals : array (..., 3) Eigenvalues from eigen decomposition of the tensor. eigvecs : array (..., 3, 3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- decompose_tensor Notes ----- In Chung, et al. 2006, the regression of the WLS fit needed an unbiased preliminary estimate of the weights and therefore the ordinary least squares (OLS) estimates were used. A "two pass" method was implemented: 1. calculate OLS estimates of the data 2. apply the OLS estimates as weights to the WLS fit of the data This ensured heteroscadasticity could be properly modeled for various types of bootstrap resampling (namely residual bootstrap). .. math:: y = \mathrm{data} \\ X = \mathrm{design matrix} \\ \hat{\beta}_\mathrm{WLS} = \mathrm{desired regression coefficients (e.g. tensor)}\\ \\ \hat{\beta}_\mathrm{WLS} = (X^T W X)^{-1} X^T W y \\ \\ W = \mathrm{diag}((X \hat{\beta}_\mathrm{OLS})^2), \mathrm{where} \hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y References ---------- .. _[1] <NAME>., <NAME>., <NAME>., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541. """ if min_signal <= 0: raise ValueError('min_signal must be > 0') data, wrap = _makearray(data) data_flat = data.reshape((-1, data.shape[-1])) dti_params = np.empty((len(data_flat), 4, 3)) #obtain OLS fitting matrix #U,S,V = np.linalg.svd(design_matrix, False) #math: beta_ols = inv(X.T*X)*X.T*y #math: ols_fit = X*beta_ols*inv(y) #ols_fit = np.dot(U, U.T) ols_fit = _ols_fit_matrix(design_matrix) for param, sig in zip(dti_params, data_flat): param[0], param[1:] = _wls_iter(ols_fit, design_matrix, sig, min_signal=min_signal) dti_params.shape = data.shape[:-1]+(12,) dti_params = wrap(dti_params) return dti_params def _wls_iter(ols_fit, design_matrix, sig, min_signal=1): ''' Function used by wls_fit_tensor for later optimization. ''' sig = np.maximum(sig, min_signal) #throw out zero signals log_s = np.log(sig) w = np.exp(np.dot(ols_fit, log_s)) D = np.dot(np.linalg.pinv(design_matrix*w[:,None]), w*log_s) tensor = from_lower_triangular(D) return decompose_tensor(tensor) def _ols_iter(inv_design, sig, min_signal=1): ''' Function used by ols_fit_tensor for later optimization. ''' sig = np.maximum(sig, min_signal) #throw out zero signals log_s = np.log(sig) D = np.dot(inv_design, log_s) tensor = from_lower_triangular(D) return decompose_tensor(tensor) def ols_fit_tensor(design_matrix, data, min_signal=1): r""" Computes ordinary least squares (OLS) fit to calculate self-diffusion tensor using a linear regression model [1]_. Parameters ---------- design_matrix : array (g, 7) Design matrix holding the covariants used to solve for the regression coefficients. Use design_matrix to build a valid design matrix from bvalues and a gradient table. data : array ([X, Y, Z, ...], g) Data or response variables holding the data. Note that the last dimension should contain the data. It makes no copies of data. min_signal : default = 1 All values below min_signal are repalced with min_signal. This is done in order to avaid taking log(0) durring the tensor fitting. Returns ------- eigvals : array (..., 3) Eigenvalues from eigen decomposition of the tensor. eigvecs : array (..., 3, 3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- WLS_fit_tensor, decompose_tensor, design_matrix Notes ----- This function is offered mainly as a quick comparison to WLS. .. math:: y = \mathrm{data} \\ X = \mathrm{design matrix} \\ \hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y References ---------- .. [1] <NAME>., <NAME>., <NAME>., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541. """ data, wrap = _makearray(data) data_flat = data.reshape((-1, data.shape[-1])) evals = np.empty((len(data_flat), 3)) evecs = np.empty((len(data_flat), 3, 3)) dti_params = np.empty((len(data_flat), 4, 3)) #obtain OLS fitting matrix #U,S,V = np.linalg.svd(design_matrix, False) #math: beta_ols = inv(X.T*X)*X.T*y #math: ols_fit = X*beta_ols*inv(y) #ols_fit = np.dot(U, U.T) inv_design = np.linalg.pinv(design_matrix) for param, sig in zip(dti_params, data_flat): param[0], param[1:] = _ols_iter(inv_design, sig, min_signal) dti_params.shape = data.shape[:-1]+(12,) dti_params = wrap(dti_params) return dti_params def _ols_fit_matrix(design_matrix): """ Helper function to calculate the ordinary least squares (OLS) fit as a matrix multiplication. Mainly used to calculate WLS weights. Can be used to calculate regression coefficients in OLS but not recommended. See Also: --------- wls_fit_tensor, ols_fit_tensor Example: -------- ols_fit = _ols_fit_matrix(design_mat) ols_data = np.dot(ols_fit, data) """ U,S,V = np.linalg.svd(design_matrix, False) return np.dot(U, U.T) _lt_indices = np.array([[0, 1, 3], [1, 2, 4], [3, 4, 5]]) def from_lower_triangular(D): """ Returns a tensor given the six unique tensor elements Given the six unique tensor elments (in the order: Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) returns a 3 by 3 tensor. All elements after the sixth are ignored. Parameters: ----------- D : array_like, (..., >6) Unique elements of the tensors Returns: -------- tensor : ndarray (..., 3, 3) 3 by 3 tensors """ return D[..., _lt_indices] _lt_rows = np.array([0, 1, 1, 2, 2, 2]) _lt_cols = np.array([0, 0, 1, 0, 1, 2]) def lower_triangular(tensor, b0=None): """ Returns the six lower triangular values of the tensor and a dummy variable if b0 is not None Parameters: ---------- tensor - array_like (..., 3, 3) a collection of 3, 3 diffusion tensors b0 - float if b0 is not none log(b0) is returned as the dummy variable Returns: ------- D - ndarray If b0 is none, then the shape will be (..., 6) otherwise (..., 7) """ if tensor.shape[-2:] != (3, 3): raise ValueError("Diffusion tensors should be (..., 3, 3)") if b0 is None: return tensor[..., _lt_rows, _lt_cols] else: D = np.empty(tensor.shape[:-2] + (7,), dtype=tensor.dtype) D[..., 6] = -np.log(b0) D[..., :6] = tensor[..., _lt_rows, _lt_cols] return D def tensor_eig_from_lo_tri(B, data): """Calculates parameters for creating a Tensor instance Calculates tensor parameters from the six unique tensor elements. This function can be passed to the Tensor class as a fit_method for creating a Tensor instance from tensors stored in a nifti file. Parameters: ----------- B : not currently used data : array_like (..., 6) diffusion tensors elements stored in lower triangular order Returns ------- dti_params Eigen values and vectors, used by the Tensor class to create an instance """ data, wrap = _makearray(data) data_flat = data.reshape((-1, data.shape[-1])) dti_params = np.empty((len(data_flat), 4, 3)) for ii in xrange(len(data_flat)): tensor = from_lower_triangular(data_flat[ii]) eigvals, eigvecs = decompose_tensor(tensor) dti_params[ii, 0] = eigvals dti_params[ii, 1:] = eigvecs dti_params.shape = data.shape[:-1]+(12,) dti_params = wrap(dti_params) return dti_params def decompose_tensor(tensor): """ Returns eigenvalues and eigenvectors given a diffusion tensor Computes tensor eigen decomposition to calculate eigenvalues and eigenvectors of self-diffusion tensor. (Basser et al., 1994a) Parameters ---------- D : array (3,3) array holding a tensor. Assumes D has units on order of ~ 10^-4 mm^2/s Returns ------- eigvals : array (3,) Eigenvalues from eigen decomposition of the tensor. Negative eigenvalues are replaced by zero. Sorted from largest to smallest. eigvecs : array (3,3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- numpy.linalg.eig """ #outputs multiplicity as well so need to unique eigenvals, eigenvecs = np.linalg.eig(tensor) #need to sort the eigenvalues and associated eigenvectors order = eigenvals.argsort()[::-1] eigenvecs = eigenvecs[:, order] eigenvals = eigenvals[order] #Forcing negative eigenvalues to 0 eigenvals = np.maximum(eigenvals, 0) # b ~ 10^3 s/mm^2 and D ~ 10^-4 mm^2/s # eigenvecs: each vector is columnar return eigenvals, eigenvecs def design_matrix(gtab, bval, dtype=None): """ Constructs design matrix for DTI weighted least squares or least squares fitting. (Basser et al., 1994a) Parameters ---------- gtab : array with shape (3,g) Diffusion gradient table found in DICOM header as a numpy array. bval : array with shape (g,) Diffusion weighting factor b for each vector in gtab. dtype : string Parameter to control the dtype of returned designed matrix Returns ------- design_matrix : array (g,7) Design matrix or B matrix assuming Gaussian distributed tensor model. Note: design_matrix[j,:] = (Bxx,Byy,Bzz,Bxy,Bxz,Byz,dummy) """ G = gtab B = np.zeros((bval.size, 7), dtype = G.dtype) if gtab.shape[1] != bval.shape[0]: raise ValueError('The number of b values and gradient directions must' +' be the same') B[:, 0] = G[0, :] * G[0, :] * 1. * bval #Bxx B[:, 1] = G[0, :] * G[1, :] * 2. * bval #Bxy B[:, 2] = G[1, :] * G[1, :] * 1. * bval #Byy B[:, 3] = G[0, :] * G[2, :] * 2. * bval #Bxz B[:, 4] = G[1, :] * G[2, :] * 2. * bval #Byz B[:, 5] = G[2, :] * G[2, :] * 1. * bval #Bzz B[:, 6] = np.ones(bval.size) return -B def quantize_evecs(evecs, odf_vertices=None): ''' Find the closest orientation of an evenly distributed sphere Parameters ---------- evecs : ndarray odf_vertices : None or ndarray If None, then set vertices from symmetric362 sphere. Otherwise use passed ndarray as vertices Returns ------- IN : ndarray ''' max_evecs=evecs[...,:,0] if odf_vertices==None: odf_vertices, _ = get_sphere('symmetric362') tup=max_evecs.shape[:-1] mec=max_evecs.reshape(np.prod(np.array(tup)),3) IN=np.array([np.argmin(np.dot(odf_vertices,m)) for m in mec]) IN=IN.reshape(tup) return IN class TensorStepper(object): """Used for tracking diffusion tensors, has a next_step method""" def _get_angel_limit(self): return np.arccos(self.dot_limit)*180/pi def _set_angel_limit(self, angle): if angle >= 0 and angle <= 90: self.dot_limit = cos(angle*pi/180) else: raise ValueError("angle should be between 0 and 180") angel_limit = property(_get_angel_limit, _set_angel_limit) def _get_fa_limit(self): return self._fa_limit def _set_fa_limit(self, arg): self._fa_limit = arg mask = self.fa_vol > arg self._interp_inst = _interpolator(self.evec1_vol, self.voxe_size, mask) fa_limit = property(_get_fa_limit, _set_fa_limit) def __init__(self, fa_vol, evec1_vol, voxel_size, interpolator, fa_limit=None, angle_limit=None): self.voxel_size = voxel_size self.angle_limit = angle_limit if fa_vol.shape != evec1_vol.shape[:-1]: msg = "the fa and eigen vector volumes are not the same shape" raise ValueError(msg) if evec1_vol.shape[-1] != 3: msg = "eigen vector volume should have vecetors of length 3 " + \ "along the last dimmension" raise ValueError(msg) self.evec1_vol = evec1_vol self.fa_vol = fa_vol self._interpolator = interpolator #self._interp_inst is created when fa_limit is set self.fa_limit = fa_limit def next_step(location, prev_step): """Returns the nearest neighbor tensor for location""" step = self._interp_inst[location] angle_dot = dot(step, prev_step) if np.abs(angle_dot) < self.dot_limit: raise StopIteration if angle_dot > 0: return step else: return -step def stepper_from_tensor(tensor, *args, **kargs): """stepper_from_tensor(tensor, fa_vol, evec1_vol, voxel_size, interpolator) """ fa_vol = tensor.fa() evec1_vol = tensor.evec[..., 0] stepper = TensorStepper(fa_vol, evec1_vol, *args, **kargs) return stepper common_fit_methods = {'WLS': wls_fit_tensor, 'LS': ols_fit_tensor, 'from lower triangular': tensor_eig_from_lo_tri, }
#!/usr/bin/python """ Classes and functions for fitting tensors """ # 5/17/2010 import numpy as np from dipy.reconst.maskedview import MaskedView, _makearray, _filled from dipy.reconst.modelarray import ModelArray from dipy.data import get_sphere class Tensor(ModelArray): """ Fits a diffusion tensor given diffusion-weighted signals and gradient info Tensor object that when initialized calculates single self diffusion tensor [1]_ in each voxel using selected fitting algorithm (DEFAULT: weighted least squares [2]_) Requires a given gradient table, b value for each diffusion-weighted gradient vector, and image data given all as arrays. Parameters ---------- data : array ([X, Y, Z, ...], g) Diffusion-weighted signals. The dimension corresponding to the diffusion weighting must be the last dimenssion bval : array (g,) Diffusion weighting factor b for each vector in gtab. gtab : array (g, 3) Diffusion gradient table found in DICOM header as a array. mask : array, optional The tensor will only be fit where mask is True. Mask must must broadcast to the shape of data and must have fewer dimensions than data thresh : float, default = None The tensor will not be fit where data[bval == 0] < thresh. If multiple b0 volumes are given, the minimum b0 signal is used. fit_method : funciton or string, default = 'WLS' The method to be used to fit the given data to a tensor. Any function that takes the B matrix and the data and returns eigen values and eigen vectors can be passed as the fit method. Any of the common fit methods can be passed as a string. *args, **kargs : Any other arguments or keywards will be passed to fit_method. common fit methods: 'WLS' : weighted least squares dti.wls_fit_tensor 'LS' : ordinary least squares dti.ols_fit_tensor Attributes ---------- D : array (..., 3, 3) Self diffusion tensor calculated from cached eigenvalues and eigenvectors. mask : array True in voxels where a tensor was fit, false if the voxel was skipped B : array (g, 7) Design matrix or B matrix constructed from given gradient table and b-value vector. evals : array (..., 3) Cached eigenvalues of self diffusion tensor for given index. (eval1, eval2, eval3) evecs : array (..., 3, 3) Cached associated eigenvectors of self diffusion tensor for given index. Note: evals[..., j] is associated with evecs[..., :, j] Methods ------- fa : array Calculates fractional anisotropy [2]_. md : array Calculates the mean diffusivity [2]_. Note: [units ADC] ~ [units b value]*10**-1 See Also -------- dipy.io.bvectxt.read_bvec_file, dipy.core.qball.ODF References ---------- .. [1] <NAME>., <NAME>., <NAME>., 1994. Estimation of the effective self-diffusion tensor from the NMR spin echo. J Magn Reson B 103, 247-254. .. [2] <NAME>., <NAME>., 1996. Microstructural and physiological features of tissues elucidated by quantitative diffusion-tensor MRI. Journal of Magnetic Resonance 111, 209-219. Examples ---------- For a complete example have a look at the main dipy/examples folder """ ### Eigenvalues Property ### @property def evals(self): """ Returns the eigenvalues of the tensor as an array """ return _filled(self.model_params[..., :3]) ### Eigenvectors Property ### @property def evecs(self): """ Returns the eigenvectors of teh tensor as an array """ evecs = _filled(self.model_params[..., 3:]) return evecs.reshape(self.shape + (3, 3)) def __init__(self, data, b_values, grad_table, mask=True, thresh=None, fit_method='WLS', verbose=False, *args, **kargs): """ Fits a tensors to diffusion weighted data. """ if not callable(fit_method): try: fit_method = common_fit_methods[fit_method] except KeyError: raise ValueError('"'+str(fit_method)+'" is not a known fit '+ 'method, the fit method should either be a '+ 'function or one of the common fit methods') #64 bit design matrix makes for faster pinv B = design_matrix(grad_table.T, b_values) self.B = B mask = np.atleast_1d(mask) if thresh is not None: #Define total mask from thresh and mask #mask = mask & (np.min(data[..., b_values == 0], -1) > #thresh) #the assumption that the lowest b_value is always 0 is #incorrect the lowest b_value could also be higher than 0 #this is common with grid q-spaces min_b0_sig = np.min(data[..., b_values == b_values.min()], -1) mask = mask & (min_b0_sig > thresh) #if mask is all False if not mask.any(): raise ValueError('between mask and thresh, there is no data to '+ 'fit') #and the mask is not all True if not mask.all(): #leave only data[mask is True] data = data[mask] data = MaskedView(mask, data, fill_value=0) #Perform WLS fit on masked data dti_params = fit_method(B, data, *args, **kargs) self.model_params = dti_params ### Self Diffusion Tensor Property ### def _getD(self): """Calculates the 3x3 diffusion tensor for each voxel""" params, wrap = _makearray(self.model_params) evals = params[..., :3] evecs = params[..., 3:] evals_flat = evals.reshape((-1, 3)) evecs_flat = evecs.reshape((-1, 3, 3)) D_flat = np.empty(evecs_flat.shape) for ii in xrange(len(D_flat)): Q = evecs_flat[ii] L = evals_flat[ii] D_flat[ii] = np.dot(Q*L, Q.T) D = _filled(wrap(D_flat)) D.shape = self.shape + (3, 3) return D D = property(_getD, doc = "Self diffusion tensor") def lower_triangular(self, b0=None): D = self._getD() return lower_triangular(D, b0) def fa(self, fill_value=0, nonans=True): r""" Fractional anisotropy (FA) calculated from cached eigenvalues. Parameters ---------- fill_value : float value of fa where self.mask == True. nonans : Bool When True, fa is 0 when all eigenvalues are 0, otherwise fa is nan Returns --------- fa : array (V, 1) Calculated FA. Note: range is 0 <= FA <= 1. Notes -------- FA is calculated with the following equation: .. math:: FA = \sqrt{\frac{1}{2}\frac{(\lambda_1-\lambda_2)^2+(\lambda_1- \lambda_3)^2+(\lambda_2-lambda_3)^2}{\lambda_1^2+ \lambda_2^2+\lambda_3^2} } """ evals, wrap = _makearray(self.model_params[..., :3]) ev1 = evals[..., 0] ev2 = evals[..., 1] ev3 = evals[..., 2] if nonans: all_zero = (ev1 == 0) & (ev2 == 0) & (ev3 == 0) else: all_zero = 0. fa = np.sqrt(0.5 * ((ev1 - ev2)**2 + (ev2 - ev3)**2 + (ev3 - ev1)**2) / (ev1*ev1 + ev2*ev2 + ev3*ev3 + all_zero)) fa = wrap(np.asarray(fa)) return _filled(fa, fill_value) def md(self): r""" Mean diffusitivity (MD) calculated from cached eigenvalues. Returns --------- md : array (V, 1) Calculated MD. Notes -------- MD is calculated with the following equation: .. math:: ADC = \frac{\lambda_1+\lambda_2+\lambda_3}{3} """ #adc/md = (ev1+ev2+ev3)/3 return self.evals.mean(-1) def ind(self): ''' Quantizes eigenvectors with maximum eigenvalues on an evenly distributed sphere so that the can be used for tractography. Returns --------- IN : array, shape(x,y,z) integer indices for the points of the evenly distributed sphere representing tensor eigenvectors of maximum eigenvalue ''' return quantize_evecs(self.evecs,odf_vertices=None) def wls_fit_tensor(design_matrix, data, min_signal=1): r""" Computes weighted least squares (WLS) fit to calculate self-diffusion tensor using a linear regression model [1]_. Parameters ---------- design_matrix : array (g, 7) Design matrix holding the covariants used to solve for the regression coefficients. data : array ([X, Y, Z, ...], g) Data or response variables holding the data. Note that the last dimension should contain the data. It makes no copies of data. min_signal : default = 1 All values below min_signal are repalced with min_signal. This is done in order to avaid taking log(0) durring the tensor fitting. Returns ------- eigvals : array (..., 3) Eigenvalues from eigen decomposition of the tensor. eigvecs : array (..., 3, 3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- decompose_tensor Notes ----- In Chung, et al. 2006, the regression of the WLS fit needed an unbiased preliminary estimate of the weights and therefore the ordinary least squares (OLS) estimates were used. A "two pass" method was implemented: 1. calculate OLS estimates of the data 2. apply the OLS estimates as weights to the WLS fit of the data This ensured heteroscadasticity could be properly modeled for various types of bootstrap resampling (namely residual bootstrap). .. math:: y = \mathrm{data} \\ X = \mathrm{design matrix} \\ \hat{\beta}_\mathrm{WLS} = \mathrm{desired regression coefficients (e.g. tensor)}\\ \\ \hat{\beta}_\mathrm{WLS} = (X^T W X)^{-1} X^T W y \\ \\ W = \mathrm{diag}((X \hat{\beta}_\mathrm{OLS})^2), \mathrm{where} \hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y References ---------- .. _[1] <NAME>., <NAME>., <NAME>., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541. """ if min_signal <= 0: raise ValueError('min_signal must be > 0') data, wrap = _makearray(data) data_flat = data.reshape((-1, data.shape[-1])) dti_params = np.empty((len(data_flat), 4, 3)) #obtain OLS fitting matrix #U,S,V = np.linalg.svd(design_matrix, False) #math: beta_ols = inv(X.T*X)*X.T*y #math: ols_fit = X*beta_ols*inv(y) #ols_fit = np.dot(U, U.T) ols_fit = _ols_fit_matrix(design_matrix) for param, sig in zip(dti_params, data_flat): param[0], param[1:] = _wls_iter(ols_fit, design_matrix, sig, min_signal=min_signal) dti_params.shape = data.shape[:-1]+(12,) dti_params = wrap(dti_params) return dti_params def _wls_iter(ols_fit, design_matrix, sig, min_signal=1): ''' Function used by wls_fit_tensor for later optimization. ''' sig = np.maximum(sig, min_signal) #throw out zero signals log_s = np.log(sig) w = np.exp(np.dot(ols_fit, log_s)) D = np.dot(np.linalg.pinv(design_matrix*w[:,None]), w*log_s) tensor = from_lower_triangular(D) return decompose_tensor(tensor) def _ols_iter(inv_design, sig, min_signal=1): ''' Function used by ols_fit_tensor for later optimization. ''' sig = np.maximum(sig, min_signal) #throw out zero signals log_s = np.log(sig) D = np.dot(inv_design, log_s) tensor = from_lower_triangular(D) return decompose_tensor(tensor) def ols_fit_tensor(design_matrix, data, min_signal=1): r""" Computes ordinary least squares (OLS) fit to calculate self-diffusion tensor using a linear regression model [1]_. Parameters ---------- design_matrix : array (g, 7) Design matrix holding the covariants used to solve for the regression coefficients. Use design_matrix to build a valid design matrix from bvalues and a gradient table. data : array ([X, Y, Z, ...], g) Data or response variables holding the data. Note that the last dimension should contain the data. It makes no copies of data. min_signal : default = 1 All values below min_signal are repalced with min_signal. This is done in order to avaid taking log(0) durring the tensor fitting. Returns ------- eigvals : array (..., 3) Eigenvalues from eigen decomposition of the tensor. eigvecs : array (..., 3, 3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- WLS_fit_tensor, decompose_tensor, design_matrix Notes ----- This function is offered mainly as a quick comparison to WLS. .. math:: y = \mathrm{data} \\ X = \mathrm{design matrix} \\ \hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y References ---------- .. [1] <NAME>., <NAME>., <NAME>., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541. """ data, wrap = _makearray(data) data_flat = data.reshape((-1, data.shape[-1])) evals = np.empty((len(data_flat), 3)) evecs = np.empty((len(data_flat), 3, 3)) dti_params = np.empty((len(data_flat), 4, 3)) #obtain OLS fitting matrix #U,S,V = np.linalg.svd(design_matrix, False) #math: beta_ols = inv(X.T*X)*X.T*y #math: ols_fit = X*beta_ols*inv(y) #ols_fit = np.dot(U, U.T) inv_design = np.linalg.pinv(design_matrix) for param, sig in zip(dti_params, data_flat): param[0], param[1:] = _ols_iter(inv_design, sig, min_signal) dti_params.shape = data.shape[:-1]+(12,) dti_params = wrap(dti_params) return dti_params def _ols_fit_matrix(design_matrix): """ Helper function to calculate the ordinary least squares (OLS) fit as a matrix multiplication. Mainly used to calculate WLS weights. Can be used to calculate regression coefficients in OLS but not recommended. See Also: --------- wls_fit_tensor, ols_fit_tensor Example: -------- ols_fit = _ols_fit_matrix(design_mat) ols_data = np.dot(ols_fit, data) """ U,S,V = np.linalg.svd(design_matrix, False) return np.dot(U, U.T) _lt_indices = np.array([[0, 1, 3], [1, 2, 4], [3, 4, 5]]) def from_lower_triangular(D): """ Returns a tensor given the six unique tensor elements Given the six unique tensor elments (in the order: Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) returns a 3 by 3 tensor. All elements after the sixth are ignored. Parameters: ----------- D : array_like, (..., >6) Unique elements of the tensors Returns: -------- tensor : ndarray (..., 3, 3) 3 by 3 tensors """ return D[..., _lt_indices] _lt_rows = np.array([0, 1, 1, 2, 2, 2]) _lt_cols = np.array([0, 0, 1, 0, 1, 2]) def lower_triangular(tensor, b0=None): """ Returns the six lower triangular values of the tensor and a dummy variable if b0 is not None Parameters: ---------- tensor - array_like (..., 3, 3) a collection of 3, 3 diffusion tensors b0 - float if b0 is not none log(b0) is returned as the dummy variable Returns: ------- D - ndarray If b0 is none, then the shape will be (..., 6) otherwise (..., 7) """ if tensor.shape[-2:] != (3, 3): raise ValueError("Diffusion tensors should be (..., 3, 3)") if b0 is None: return tensor[..., _lt_rows, _lt_cols] else: D = np.empty(tensor.shape[:-2] + (7,), dtype=tensor.dtype) D[..., 6] = -np.log(b0) D[..., :6] = tensor[..., _lt_rows, _lt_cols] return D def tensor_eig_from_lo_tri(B, data): """Calculates parameters for creating a Tensor instance Calculates tensor parameters from the six unique tensor elements. This function can be passed to the Tensor class as a fit_method for creating a Tensor instance from tensors stored in a nifti file. Parameters: ----------- B : not currently used data : array_like (..., 6) diffusion tensors elements stored in lower triangular order Returns ------- dti_params Eigen values and vectors, used by the Tensor class to create an instance """ data, wrap = _makearray(data) data_flat = data.reshape((-1, data.shape[-1])) dti_params = np.empty((len(data_flat), 4, 3)) for ii in xrange(len(data_flat)): tensor = from_lower_triangular(data_flat[ii]) eigvals, eigvecs = decompose_tensor(tensor) dti_params[ii, 0] = eigvals dti_params[ii, 1:] = eigvecs dti_params.shape = data.shape[:-1]+(12,) dti_params = wrap(dti_params) return dti_params def decompose_tensor(tensor): """ Returns eigenvalues and eigenvectors given a diffusion tensor Computes tensor eigen decomposition to calculate eigenvalues and eigenvectors of self-diffusion tensor. (Basser et al., 1994a) Parameters ---------- D : array (3,3) array holding a tensor. Assumes D has units on order of ~ 10^-4 mm^2/s Returns ------- eigvals : array (3,) Eigenvalues from eigen decomposition of the tensor. Negative eigenvalues are replaced by zero. Sorted from largest to smallest. eigvecs : array (3,3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- numpy.linalg.eig """ #outputs multiplicity as well so need to unique eigenvals, eigenvecs = np.linalg.eig(tensor) #need to sort the eigenvalues and associated eigenvectors order = eigenvals.argsort()[::-1] eigenvecs = eigenvecs[:, order] eigenvals = eigenvals[order] #Forcing negative eigenvalues to 0 eigenvals = np.maximum(eigenvals, 0) # b ~ 10^3 s/mm^2 and D ~ 10^-4 mm^2/s # eigenvecs: each vector is columnar return eigenvals, eigenvecs def design_matrix(gtab, bval, dtype=None): """ Constructs design matrix for DTI weighted least squares or least squares fitting. (Basser et al., 1994a) Parameters ---------- gtab : array with shape (3,g) Diffusion gradient table found in DICOM header as a numpy array. bval : array with shape (g,) Diffusion weighting factor b for each vector in gtab. dtype : string Parameter to control the dtype of returned designed matrix Returns ------- design_matrix : array (g,7) Design matrix or B matrix assuming Gaussian distributed tensor model. Note: design_matrix[j,:] = (Bxx,Byy,Bzz,Bxy,Bxz,Byz,dummy) """ G = gtab B = np.zeros((bval.size, 7), dtype = G.dtype) if gtab.shape[1] != bval.shape[0]: raise ValueError('The number of b values and gradient directions must' +' be the same') B[:, 0] = G[0, :] * G[0, :] * 1. * bval #Bxx B[:, 1] = G[0, :] * G[1, :] * 2. * bval #Bxy B[:, 2] = G[1, :] * G[1, :] * 1. * bval #Byy B[:, 3] = G[0, :] * G[2, :] * 2. * bval #Bxz B[:, 4] = G[1, :] * G[2, :] * 2. * bval #Byz B[:, 5] = G[2, :] * G[2, :] * 1. * bval #Bzz B[:, 6] = np.ones(bval.size) return -B def quantize_evecs(evecs, odf_vertices=None): ''' Find the closest orientation of an evenly distributed sphere Parameters ---------- evecs : ndarray odf_vertices : None or ndarray If None, then set vertices from symmetric362 sphere. Otherwise use passed ndarray as vertices Returns ------- IN : ndarray ''' max_evecs=evecs[...,:,0] if odf_vertices==None: odf_vertices, _ = get_sphere('symmetric362') tup=max_evecs.shape[:-1] mec=max_evecs.reshape(np.prod(np.array(tup)),3) IN=np.array([np.argmin(np.dot(odf_vertices,m)) for m in mec]) IN=IN.reshape(tup) return IN class TensorStepper(object): """Used for tracking diffusion tensors, has a next_step method""" def _get_angel_limit(self): return np.arccos(self.dot_limit)*180/pi def _set_angel_limit(self, angle): if angle >= 0 and angle <= 90: self.dot_limit = cos(angle*pi/180) else: raise ValueError("angle should be between 0 and 180") angel_limit = property(_get_angel_limit, _set_angel_limit) def _get_fa_limit(self): return self._fa_limit def _set_fa_limit(self, arg): self._fa_limit = arg mask = self.fa_vol > arg self._interp_inst = _interpolator(self.evec1_vol, self.voxe_size, mask) fa_limit = property(_get_fa_limit, _set_fa_limit) def __init__(self, fa_vol, evec1_vol, voxel_size, interpolator, fa_limit=None, angle_limit=None): self.voxel_size = voxel_size self.angle_limit = angle_limit if fa_vol.shape != evec1_vol.shape[:-1]: msg = "the fa and eigen vector volumes are not the same shape" raise ValueError(msg) if evec1_vol.shape[-1] != 3: msg = "eigen vector volume should have vecetors of length 3 " + \ "along the last dimmension" raise ValueError(msg) self.evec1_vol = evec1_vol self.fa_vol = fa_vol self._interpolator = interpolator #self._interp_inst is created when fa_limit is set self.fa_limit = fa_limit def next_step(location, prev_step): """Returns the nearest neighbor tensor for location""" step = self._interp_inst[location] angle_dot = dot(step, prev_step) if np.abs(angle_dot) < self.dot_limit: raise StopIteration if angle_dot > 0: return step else: return -step def stepper_from_tensor(tensor, *args, **kargs): """stepper_from_tensor(tensor, fa_vol, evec1_vol, voxel_size, interpolator) """ fa_vol = tensor.fa() evec1_vol = tensor.evec[..., 0] stepper = TensorStepper(fa_vol, evec1_vol, *args, **kargs) return stepper common_fit_methods = {'WLS': wls_fit_tensor, 'LS': ols_fit_tensor, 'from lower triangular': tensor_eig_from_lo_tri, }
en
0.684925
#!/usr/bin/python Classes and functions for fitting tensors # 5/17/2010 Fits a diffusion tensor given diffusion-weighted signals and gradient info Tensor object that when initialized calculates single self diffusion tensor [1]_ in each voxel using selected fitting algorithm (DEFAULT: weighted least squares [2]_) Requires a given gradient table, b value for each diffusion-weighted gradient vector, and image data given all as arrays. Parameters ---------- data : array ([X, Y, Z, ...], g) Diffusion-weighted signals. The dimension corresponding to the diffusion weighting must be the last dimenssion bval : array (g,) Diffusion weighting factor b for each vector in gtab. gtab : array (g, 3) Diffusion gradient table found in DICOM header as a array. mask : array, optional The tensor will only be fit where mask is True. Mask must must broadcast to the shape of data and must have fewer dimensions than data thresh : float, default = None The tensor will not be fit where data[bval == 0] < thresh. If multiple b0 volumes are given, the minimum b0 signal is used. fit_method : funciton or string, default = 'WLS' The method to be used to fit the given data to a tensor. Any function that takes the B matrix and the data and returns eigen values and eigen vectors can be passed as the fit method. Any of the common fit methods can be passed as a string. *args, **kargs : Any other arguments or keywards will be passed to fit_method. common fit methods: 'WLS' : weighted least squares dti.wls_fit_tensor 'LS' : ordinary least squares dti.ols_fit_tensor Attributes ---------- D : array (..., 3, 3) Self diffusion tensor calculated from cached eigenvalues and eigenvectors. mask : array True in voxels where a tensor was fit, false if the voxel was skipped B : array (g, 7) Design matrix or B matrix constructed from given gradient table and b-value vector. evals : array (..., 3) Cached eigenvalues of self diffusion tensor for given index. (eval1, eval2, eval3) evecs : array (..., 3, 3) Cached associated eigenvectors of self diffusion tensor for given index. Note: evals[..., j] is associated with evecs[..., :, j] Methods ------- fa : array Calculates fractional anisotropy [2]_. md : array Calculates the mean diffusivity [2]_. Note: [units ADC] ~ [units b value]*10**-1 See Also -------- dipy.io.bvectxt.read_bvec_file, dipy.core.qball.ODF References ---------- .. [1] <NAME>., <NAME>., <NAME>., 1994. Estimation of the effective self-diffusion tensor from the NMR spin echo. J Magn Reson B 103, 247-254. .. [2] <NAME>., <NAME>., 1996. Microstructural and physiological features of tissues elucidated by quantitative diffusion-tensor MRI. Journal of Magnetic Resonance 111, 209-219. Examples ---------- For a complete example have a look at the main dipy/examples folder ### Eigenvalues Property ### Returns the eigenvalues of the tensor as an array ### Eigenvectors Property ### Returns the eigenvectors of teh tensor as an array Fits a tensors to diffusion weighted data. #64 bit design matrix makes for faster pinv #Define total mask from thresh and mask #mask = mask & (np.min(data[..., b_values == 0], -1) > #thresh) #the assumption that the lowest b_value is always 0 is #incorrect the lowest b_value could also be higher than 0 #this is common with grid q-spaces #if mask is all False #and the mask is not all True #leave only data[mask is True] #Perform WLS fit on masked data ### Self Diffusion Tensor Property ### Calculates the 3x3 diffusion tensor for each voxel Fractional anisotropy (FA) calculated from cached eigenvalues. Parameters ---------- fill_value : float value of fa where self.mask == True. nonans : Bool When True, fa is 0 when all eigenvalues are 0, otherwise fa is nan Returns --------- fa : array (V, 1) Calculated FA. Note: range is 0 <= FA <= 1. Notes -------- FA is calculated with the following equation: .. math:: FA = \sqrt{\frac{1}{2}\frac{(\lambda_1-\lambda_2)^2+(\lambda_1- \lambda_3)^2+(\lambda_2-lambda_3)^2}{\lambda_1^2+ \lambda_2^2+\lambda_3^2} } Mean diffusitivity (MD) calculated from cached eigenvalues. Returns --------- md : array (V, 1) Calculated MD. Notes -------- MD is calculated with the following equation: .. math:: ADC = \frac{\lambda_1+\lambda_2+\lambda_3}{3} #adc/md = (ev1+ev2+ev3)/3 Quantizes eigenvectors with maximum eigenvalues on an evenly distributed sphere so that the can be used for tractography. Returns --------- IN : array, shape(x,y,z) integer indices for the points of the evenly distributed sphere representing tensor eigenvectors of maximum eigenvalue Computes weighted least squares (WLS) fit to calculate self-diffusion tensor using a linear regression model [1]_. Parameters ---------- design_matrix : array (g, 7) Design matrix holding the covariants used to solve for the regression coefficients. data : array ([X, Y, Z, ...], g) Data or response variables holding the data. Note that the last dimension should contain the data. It makes no copies of data. min_signal : default = 1 All values below min_signal are repalced with min_signal. This is done in order to avaid taking log(0) durring the tensor fitting. Returns ------- eigvals : array (..., 3) Eigenvalues from eigen decomposition of the tensor. eigvecs : array (..., 3, 3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- decompose_tensor Notes ----- In Chung, et al. 2006, the regression of the WLS fit needed an unbiased preliminary estimate of the weights and therefore the ordinary least squares (OLS) estimates were used. A "two pass" method was implemented: 1. calculate OLS estimates of the data 2. apply the OLS estimates as weights to the WLS fit of the data This ensured heteroscadasticity could be properly modeled for various types of bootstrap resampling (namely residual bootstrap). .. math:: y = \mathrm{data} \\ X = \mathrm{design matrix} \\ \hat{\beta}_\mathrm{WLS} = \mathrm{desired regression coefficients (e.g. tensor)}\\ \\ \hat{\beta}_\mathrm{WLS} = (X^T W X)^{-1} X^T W y \\ \\ W = \mathrm{diag}((X \hat{\beta}_\mathrm{OLS})^2), \mathrm{where} \hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y References ---------- .. _[1] <NAME>., <NAME>., <NAME>., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541. #obtain OLS fitting matrix #U,S,V = np.linalg.svd(design_matrix, False) #math: beta_ols = inv(X.T*X)*X.T*y #math: ols_fit = X*beta_ols*inv(y) #ols_fit = np.dot(U, U.T) Function used by wls_fit_tensor for later optimization. #throw out zero signals Function used by ols_fit_tensor for later optimization. #throw out zero signals Computes ordinary least squares (OLS) fit to calculate self-diffusion tensor using a linear regression model [1]_. Parameters ---------- design_matrix : array (g, 7) Design matrix holding the covariants used to solve for the regression coefficients. Use design_matrix to build a valid design matrix from bvalues and a gradient table. data : array ([X, Y, Z, ...], g) Data or response variables holding the data. Note that the last dimension should contain the data. It makes no copies of data. min_signal : default = 1 All values below min_signal are repalced with min_signal. This is done in order to avaid taking log(0) durring the tensor fitting. Returns ------- eigvals : array (..., 3) Eigenvalues from eigen decomposition of the tensor. eigvecs : array (..., 3, 3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- WLS_fit_tensor, decompose_tensor, design_matrix Notes ----- This function is offered mainly as a quick comparison to WLS. .. math:: y = \mathrm{data} \\ X = \mathrm{design matrix} \\ \hat{\beta}_\mathrm{OLS} = (X^T X)^{-1} X^T y References ---------- .. [1] <NAME>., <NAME>., <NAME>., 2006. Comparison of bootstrap approaches for estimation of uncertainties of DTI parameters. NeuroImage 33, 531-541. #obtain OLS fitting matrix #U,S,V = np.linalg.svd(design_matrix, False) #math: beta_ols = inv(X.T*X)*X.T*y #math: ols_fit = X*beta_ols*inv(y) #ols_fit = np.dot(U, U.T) Helper function to calculate the ordinary least squares (OLS) fit as a matrix multiplication. Mainly used to calculate WLS weights. Can be used to calculate regression coefficients in OLS but not recommended. See Also: --------- wls_fit_tensor, ols_fit_tensor Example: -------- ols_fit = _ols_fit_matrix(design_mat) ols_data = np.dot(ols_fit, data) Returns a tensor given the six unique tensor elements Given the six unique tensor elments (in the order: Dxx, Dxy, Dyy, Dxz, Dyz, Dzz) returns a 3 by 3 tensor. All elements after the sixth are ignored. Parameters: ----------- D : array_like, (..., >6) Unique elements of the tensors Returns: -------- tensor : ndarray (..., 3, 3) 3 by 3 tensors Returns the six lower triangular values of the tensor and a dummy variable if b0 is not None Parameters: ---------- tensor - array_like (..., 3, 3) a collection of 3, 3 diffusion tensors b0 - float if b0 is not none log(b0) is returned as the dummy variable Returns: ------- D - ndarray If b0 is none, then the shape will be (..., 6) otherwise (..., 7) Calculates parameters for creating a Tensor instance Calculates tensor parameters from the six unique tensor elements. This function can be passed to the Tensor class as a fit_method for creating a Tensor instance from tensors stored in a nifti file. Parameters: ----------- B : not currently used data : array_like (..., 6) diffusion tensors elements stored in lower triangular order Returns ------- dti_params Eigen values and vectors, used by the Tensor class to create an instance Returns eigenvalues and eigenvectors given a diffusion tensor Computes tensor eigen decomposition to calculate eigenvalues and eigenvectors of self-diffusion tensor. (Basser et al., 1994a) Parameters ---------- D : array (3,3) array holding a tensor. Assumes D has units on order of ~ 10^-4 mm^2/s Returns ------- eigvals : array (3,) Eigenvalues from eigen decomposition of the tensor. Negative eigenvalues are replaced by zero. Sorted from largest to smallest. eigvecs : array (3,3) Associated eigenvectors from eigen decomposition of the tensor. Eigenvectors are columnar (e.g. eigvecs[:,j] is associated with eigvals[j]) See Also -------- numpy.linalg.eig #outputs multiplicity as well so need to unique #need to sort the eigenvalues and associated eigenvectors #Forcing negative eigenvalues to 0 # b ~ 10^3 s/mm^2 and D ~ 10^-4 mm^2/s # eigenvecs: each vector is columnar Constructs design matrix for DTI weighted least squares or least squares fitting. (Basser et al., 1994a) Parameters ---------- gtab : array with shape (3,g) Diffusion gradient table found in DICOM header as a numpy array. bval : array with shape (g,) Diffusion weighting factor b for each vector in gtab. dtype : string Parameter to control the dtype of returned designed matrix Returns ------- design_matrix : array (g,7) Design matrix or B matrix assuming Gaussian distributed tensor model. Note: design_matrix[j,:] = (Bxx,Byy,Bzz,Bxy,Bxz,Byz,dummy) #Bxx #Bxy #Byy #Bxz #Byz #Bzz Find the closest orientation of an evenly distributed sphere Parameters ---------- evecs : ndarray odf_vertices : None or ndarray If None, then set vertices from symmetric362 sphere. Otherwise use passed ndarray as vertices Returns ------- IN : ndarray Used for tracking diffusion tensors, has a next_step method #self._interp_inst is created when fa_limit is set Returns the nearest neighbor tensor for location stepper_from_tensor(tensor, fa_vol, evec1_vol, voxel_size, interpolator)
3.000198
3
statistics/hyphotesis/testing.py
Fernakamuta/machine
0
6624306
<reponame>Fernakamuta/machine<filename>statistics/hyphotesis/testing.py import scipy.stats as st # Get z-score from p-value (To the left) print(st.norm.ppf(0.09012267246445244)) # Get p-Value from normal a Z-score (AREA TO THE LEFT) print(st.norm.cdf(-1.34))
import scipy.stats as st # Get z-score from p-value (To the left) print(st.norm.ppf(0.09012267246445244)) # Get p-Value from normal a Z-score (AREA TO THE LEFT) print(st.norm.cdf(-1.34))
en
0.819507
# Get z-score from p-value (To the left) # Get p-Value from normal a Z-score (AREA TO THE LEFT)
2.543419
3
exercicio 061.py
rayanesousa31/Python-Curso-em-video-Mundo-2
0
6624307
<reponame>rayanesousa31/Python-Curso-em-video-Mundo-2<filename>exercicio 061.py #Refaça o DESAFIO 051, # lendo o primeiro termo e a razão de uma PA, # mostrado os 10 primeiros termos da progressão # usando a estrutura while. n = int(input('Digite um numero: ')) razao = int(input('Digite uma razao: ')) termo = n cont = 1 while cont <= 10: print(' {}'.format(termo),end=' ') termo += razao cont+= 1 print('Fim')
061.py #Refaça o DESAFIO 051, # lendo o primeiro termo e a razão de uma PA, # mostrado os 10 primeiros termos da progressão # usando a estrutura while. n = int(input('Digite um numero: ')) razao = int(input('Digite uma razao: ')) termo = n cont = 1 while cont <= 10: print(' {}'.format(termo),end=' ') termo += razao cont+= 1 print('Fim')
pt
0.990197
#Refaça o DESAFIO 051, # lendo o primeiro termo e a razão de uma PA, # mostrado os 10 primeiros termos da progressão # usando a estrutura while.
3.843789
4
src/rocommand/test/TestROSRS_Session.py
A-Mazurek/ro-manager
11
6624308
#!/usr/bin/env python """ Module to test RO SRS APIfunctions """ __author__ = "<NAME> (<EMAIL>)" __copyright__ = "Copyright 2011-2013, University of Oxford" __license__ = "MIT (http://opensource.org/licenses/MIT)" import os, os.path import sys import unittest import logging import json import re import StringIO import httplib import urlparse import rdflib, rdflib.graph if __name__ == "__main__": # Add main project directory and ro manager directories at start of python path sys.path.insert(0, "../..") sys.path.insert(0, "..") from MiscUtils import TestUtils from MiscUtils.HttpSession import testSplitValues, testParseLinks from ro_namespaces import RDF, RDFS, ORE, RO, DCTERMS, AO from ROSRS_Session import ROSRS_Error, ROSRS_Session from TestConfig import ro_test_config # Logging object log = logging.getLogger(__name__) # Base directory for file access tests in this module testbase = os.path.dirname(__file__) # Test config details class Config: ROSRS_API_URI = ro_test_config.ROSRS_URI # "http://sandbox.wf4ever-project.org/rodl/ROs/" AUTHORIZATION = ro_test_config.ROSRS_ACCESS_TOKEN TEST_RO_NAME = "TestSessionRO" TEST_RO_PATH = TEST_RO_NAME+"/" TEST_RO_URI = ROSRS_API_URI+TEST_RO_PATH # Test cases class TestROSRS_Session(unittest.TestCase): """ This test suite tests the ROSRS_Session client implementation of the ROSRS API """ def setUp(self): super(TestROSRS_Session, self).setUp() self.rosrs = ROSRS_Session(Config.ROSRS_API_URI, accesskey=Config.AUTHORIZATION) # Clean up from previous runs self.rosrs.deleteRO(Config.TEST_RO_PATH, purge=True) self.createdTestRO = None return def tearDown(self): super(TestROSRS_Session, self).tearDown() # Clean up self.rosrs.deleteRO(Config.TEST_RO_PATH) if self.createdTestRO: self.rosrs.deleteRO(self.createdTestRO, purge=True) self.rosrs.close() return def createTestRO(self): (status, reason, rouri, manifest) = self.rosrs.createRO(Config.TEST_RO_NAME, "Test RO for ROSRS_Session", "TestROSRS_Session.py", "2012-09-06") self.assertEqual(status, 201) self.createdTestRO = rouri return (status, reason, rouri, manifest) # Actual tests follow def testHelpers(self): testSplitValues() testParseLinks() return def testListROs(self): ros = self.rosrs.listROs() return def testCreateRO(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) self.assertEqual(reason, "Created") self.assertEqual(str(rouri)[:len(Config.TEST_RO_URI)-1]+"/", Config.TEST_RO_URI) self.assertIn((rouri, RDF.type, RO.ResearchObject), manifest) rolist = self.rosrs.listROs() self.assertIn(str(rouri), [ r["uri"] for r in rolist ]) return def testDeleteRO(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Test that new RO is in collection rolist = self.rosrs.listROs() self.assertIn(str(rouri), [ r["uri"] for r in rolist ]) # Delete RO (status, reason) = self.rosrs.deleteRO(rouri) self.assertEqual(status, 204) self.assertEqual(reason, "No Content") # Test that new RO is not in collection rolist = self.rosrs.listROs() self.assertNotIn(str(rouri), [ r["uri"] for r in rolist ]) # Delete again (status, reason) = self.rosrs.deleteRO(rouri) self.assertEqual(status, 404) self.assertEqual(reason, "Not Found") return def testGetROManifest(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Get manifest (status, reason, headers, manifesturi, manifest) = self.rosrs.getROManifest(rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "application/rdf+xml") # Check manifest RDF graph self.assertIn((rouri, RDF.type, RO.ResearchObject), manifest) self.assertIn((rouri, DCTERMS.creator, None), manifest) self.assertIn((rouri, DCTERMS.created, None), manifest) self.assertIn((rouri, ORE.isDescribedBy, manifesturi), manifest) return def testGetROPage(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Get landing page (status, reason, headers, pageuri, page) = self.rosrs.getROLandingPage(rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "text/html;charset=UTF-8") return def testGetROZip(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Get manifest (status, reason, headers, datauri, data) = self.rosrs.getROZip(rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "application/zip") # @@TODO test content of zip (data)? return def testAggregateResourceInt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Aggregate internal resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/path", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) self.assertEqual(reason, "Created") self.assertEqual(str(resuri), str(rouri)+"test/path") # GET content (status, reason, headers, uri, data) = self.rosrs.getROResource( "test/path", rouri) self.assertEqual(status, 200) self.assertEqual(headers["content-type"], "text/plain") self.assertEqual(data, rescontent) # GET proxy (getproxyuri, manifest) = self.rosrs.getROResourceProxy( "test/path", rouri=rouri) self.assertEqual(getproxyuri, proxyuri) return def testDeleteResourceInt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/path", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # GET content (status, reason, headers, uri, data) = self.rosrs.getROResource( "test/path", rouri) self.assertEqual(status, 200) # Delete resource (status, reason) = self.rosrs.removeResource(rouri, resuri) self.assertEqual(status, 204) self.assertEqual(reason, "No Content") # Check that resource is no longer available (status, reason, headers, uri, data) = self.rosrs.getROResource(resuri) self.assertEqual(status, 404) return def testAggregateResourceExt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Aggregate external resource externaluri = rdflib.URIRef("http://example.com/external/resource.txt") (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceExt( rouri, externaluri) self.assertEqual(status, 201) self.assertEqual(reason, "Created") self.assertEqual(resuri, externaluri) # GET proxy (note: using rdflib.URIRef value for path) (getproxyuri, manifest) = self.rosrs.getROResourceProxy( externaluri, rouri) self.assertEqual(getproxyuri, proxyuri) return def testDeleteResourceExt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create test resource externaluri = rdflib.URIRef("http://example.com/external/resource.txt") (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceExt( rouri, externaluri) self.assertEqual(status, 201) self.assertEqual(resuri, externaluri) # GET proxy (note: using rdflib.URIRef for path) (getproxyuri, manifest) = self.rosrs.getROResourceProxy( externaluri, rouri) self.assertEqual(getproxyuri, proxyuri) # Delete resource (status, reason) = self.rosrs.removeResource(rouri, resuri) self.assertEqual(status, 204) self.assertEqual(reason, "No Content") (getproxyuri, manifest) = self.rosrs.getROResourceProxy( externaluri, rouri) self.assertIsNone(getproxyuri) self.assertIsNotNone(manifest) return def testGetROResource(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/path", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # GET content (status, reason, headers, uri, data) = self.rosrs.getROResource( "test/path", rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "text/plain") self.assertEqual(data, rescontent) return def testGetROResourceRDF(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" > <rdf:Description rdf:about="http://example.org/file1.txt"> <dct:title>Title for file1.txt</dct:title> </rdf:Description> </rdf:RDF> """ (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file1.rdf", ctype="application/rdf+xml", body=rescontent) self.assertEqual(status, 201) # Get resource content (status, reason, headers, uri, graph)= self.rosrs.getROResourceRDF( "test/file1.rdf", rouri=rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "application/rdf+xml") s = rdflib.URIRef("http://example.org/file1.txt") self.assertIn((s, DCTERMS.title, rdflib.Literal("Title for file1.txt")), graph) return def testGetROResourceProxy(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/path", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Get resource proxy (getproxyuri, manifest) = self.rosrs.getROResourceProxy( "test/path", rouri=rouri) self.assertEqual(getproxyuri, proxyuri) return def testCreateROAnnotationInt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file.txt", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Create internal annotation annbody = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph = rdflib.graph.Graph() agraph.parse(data=annbody, format="xml") (status, reason, annuri, bodyuri) = self.rosrs.createROAnnotationInt( rouri, resuri, agraph) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris) buris = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri, buris) # Retrieve annotation (status, reason, bodyuri, anngr) = self.rosrs.getROAnnotation(annuri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title for test/file.txt")), anngr) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test")), anngr) return def testGetROAnnotationGraph(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file.txt", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Create internal annotation annbody = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph = rdflib.graph.Graph() agraph.parse(data=annbody, format="xml") (status, reason, annuri, bodyuri) = self.rosrs.createROAnnotationInt( rouri, resuri, agraph) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve merged annotations anngr = self.rosrs.getROAnnotationGraph(rouri, resuri) annts = list(anngr.triples((None, None, None))) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title for test/file.txt")), annts) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test")), annts) return def testCreateROAnnotationExt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create external test resource (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceExt( rouri, rdflib.URIRef("http://example.org/ext")) self.assertEqual(status, 201) # Create annotation using external body reference bodyuri = rdflib.URIRef("http://example.org/ext/ann.rdf") (status, reason, annuri) = self.rosrs.createROAnnotationExt(rouri, resuri, bodyuri) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris) buris = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri, buris) return def testUpdateROAnnotationInt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file.txt", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Create internal annotation annbody1 = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title 1</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test1" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph1 = rdflib.graph.Graph() agraph1.parse(data=annbody1, format="xml") (status, reason, annuri, bodyuri1) = self.rosrs.createROAnnotationInt( rouri, resuri, agraph1) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris1 = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris1) buris1 = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri1, buris1) # Retrieve annotation (status, reason, auri1, anngr1a) = self.rosrs.getROAnnotation(annuri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") annts1a = list(anngr1a.triples((None, None, None))) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title 1")), annts1a) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test1")), annts1a) # Retrieve merged annotations anngr1b = self.rosrs.getROAnnotationGraph(rouri, resuri) annts1b = list(anngr1b.triples((None, None, None))) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title 1")), annts1b) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test1")), annts1b) # Update internal annotation annbody2 = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title 2</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test2" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph2 = rdflib.graph.Graph() agraph2.parse(data=annbody2, format="xml") (status, reason, bodyuri2) = self.rosrs.updateROAnnotationInt( rouri, annuri, resuri, agraph2) self.assertEqual(status, 200) self.assertEqual(reason, "OK") # Retrieve annotation URIs auris2 = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris2) buris2 = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri2, buris2) # Retrieve annotation (status, reason, auri2a, anngr2a) = self.rosrs.getROAnnotation(annuri) annts2a = list(anngr2a.triples((None, None, None))) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertNotIn((resuri, DCTERMS.title, rdflib.Literal("Title 1")), annts2a) self.assertNotIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test1")), annts2a) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title 2")), annts2a) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test2")), annts2a) # Retrieve merged annotations anngr2b = self.rosrs.getROAnnotationGraph(rouri, resuri) annts2b = list(anngr2b.triples((None, None, None))) self.assertNotIn((resuri, DCTERMS.title, rdflib.Literal("Title 1")), annts2b) self.assertNotIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test1")), annts2b) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title 2")), annts2b) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test2")), annts2b) return def testUpdateROAnnotationExt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create external test resource (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceExt( rouri, rdflib.URIRef("http://example.org/ext")) self.assertEqual(status, 201) # Create annotation using external body reference bodyuri1 = rdflib.URIRef("http://example.org/ext/ann1.rdf") (status, reason, annuri) = self.rosrs.createROAnnotationExt(rouri, resuri, bodyuri1) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris1 = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris1) buris1 = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) self.assertIn(bodyuri1, buris1) # Update annotation using external body reference # @@TODO - this doesn't check that old annotation is removed. # @@TODO - currently, update is not fully implemented (2013-05). bodyuri2 = rdflib.URIRef("http://example.org/ext/ann2.rdf") (status, reason, annuri) = self.rosrs.createROAnnotationExt(rouri, resuri, bodyuri2) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris2 = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris2) buris2 = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) self.assertIn(bodyuri1, buris2) return def testRemoveROAnnotation(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file.txt", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Create internal annotation annbody = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph = rdflib.graph.Graph() agraph.parse(data=annbody, format="xml") (status, reason, annuri, bodyuri) = self.rosrs.createROAnnotationInt( rouri, resuri, agraph) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris) buris = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri, buris) # Remove the annotation (status, reason) = self.rosrs.removeROAnnotation(rouri, annuri) self.assertEqual(status, 204) self.assertEqual(reason, "No Content") # Retrieve annotation URIs auris = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertNotIn(annuri, auris) buris = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertNotIn(bodyuri, buris) return # Evolution tests def testCopyRO(self): return def testCancelCopyRO(self): return def testUpdateROStatus(self): return def testGetROEvolution(self): return # Sentinel/placeholder tests def testUnits(self): assert (True) def testComponents(self): assert (True) def testIntegration(self): assert (True) def testPending(self): assert (False), "Pending tests follow" # Assemble test suite def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" return suite of pending tests name a single named test to be run """ testdict = { "unit": [ "testUnits" , "testHelpers" , "testListROs" , "testCreateRO" , "testDeleteRO" , "testGetROManifest" , "testGetROPage" , "testGetROZip" # Resource tests , "testAggregateResourceInt" , "testDeleteResourceInt" , "testAggregateResourceExt" , "testDeleteResourceExt" , "testGetROResource" , "testGetROResourceRDF" , "testGetROResourceProxy" # Annotation tests , "testCreateROAnnotationInt" , "testGetROAnnotationGraph" , "testCreateROAnnotationExt" , "testUpdateROAnnotationInt" , "testUpdateROAnnotationExt" , "testRemoveROAnnotation" # Evolution tests , "testCopyRO" , "testCancelCopyRO" , "testUpdateROStatus" , "testGetROEvolution" ], "component": [ "testComponents" ], "integration": [ "testIntegration" ], "pending": [ "testPending" ] } return TestUtils.getTestSuite(TestROSRS_Session, testdict, select=select) if __name__ == "__main__": TestUtils.runTests("TestROSRS_Session.log", getTestSuite, sys.argv) # End.
#!/usr/bin/env python """ Module to test RO SRS APIfunctions """ __author__ = "<NAME> (<EMAIL>)" __copyright__ = "Copyright 2011-2013, University of Oxford" __license__ = "MIT (http://opensource.org/licenses/MIT)" import os, os.path import sys import unittest import logging import json import re import StringIO import httplib import urlparse import rdflib, rdflib.graph if __name__ == "__main__": # Add main project directory and ro manager directories at start of python path sys.path.insert(0, "../..") sys.path.insert(0, "..") from MiscUtils import TestUtils from MiscUtils.HttpSession import testSplitValues, testParseLinks from ro_namespaces import RDF, RDFS, ORE, RO, DCTERMS, AO from ROSRS_Session import ROSRS_Error, ROSRS_Session from TestConfig import ro_test_config # Logging object log = logging.getLogger(__name__) # Base directory for file access tests in this module testbase = os.path.dirname(__file__) # Test config details class Config: ROSRS_API_URI = ro_test_config.ROSRS_URI # "http://sandbox.wf4ever-project.org/rodl/ROs/" AUTHORIZATION = ro_test_config.ROSRS_ACCESS_TOKEN TEST_RO_NAME = "TestSessionRO" TEST_RO_PATH = TEST_RO_NAME+"/" TEST_RO_URI = ROSRS_API_URI+TEST_RO_PATH # Test cases class TestROSRS_Session(unittest.TestCase): """ This test suite tests the ROSRS_Session client implementation of the ROSRS API """ def setUp(self): super(TestROSRS_Session, self).setUp() self.rosrs = ROSRS_Session(Config.ROSRS_API_URI, accesskey=Config.AUTHORIZATION) # Clean up from previous runs self.rosrs.deleteRO(Config.TEST_RO_PATH, purge=True) self.createdTestRO = None return def tearDown(self): super(TestROSRS_Session, self).tearDown() # Clean up self.rosrs.deleteRO(Config.TEST_RO_PATH) if self.createdTestRO: self.rosrs.deleteRO(self.createdTestRO, purge=True) self.rosrs.close() return def createTestRO(self): (status, reason, rouri, manifest) = self.rosrs.createRO(Config.TEST_RO_NAME, "Test RO for ROSRS_Session", "TestROSRS_Session.py", "2012-09-06") self.assertEqual(status, 201) self.createdTestRO = rouri return (status, reason, rouri, manifest) # Actual tests follow def testHelpers(self): testSplitValues() testParseLinks() return def testListROs(self): ros = self.rosrs.listROs() return def testCreateRO(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) self.assertEqual(reason, "Created") self.assertEqual(str(rouri)[:len(Config.TEST_RO_URI)-1]+"/", Config.TEST_RO_URI) self.assertIn((rouri, RDF.type, RO.ResearchObject), manifest) rolist = self.rosrs.listROs() self.assertIn(str(rouri), [ r["uri"] for r in rolist ]) return def testDeleteRO(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Test that new RO is in collection rolist = self.rosrs.listROs() self.assertIn(str(rouri), [ r["uri"] for r in rolist ]) # Delete RO (status, reason) = self.rosrs.deleteRO(rouri) self.assertEqual(status, 204) self.assertEqual(reason, "No Content") # Test that new RO is not in collection rolist = self.rosrs.listROs() self.assertNotIn(str(rouri), [ r["uri"] for r in rolist ]) # Delete again (status, reason) = self.rosrs.deleteRO(rouri) self.assertEqual(status, 404) self.assertEqual(reason, "Not Found") return def testGetROManifest(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Get manifest (status, reason, headers, manifesturi, manifest) = self.rosrs.getROManifest(rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "application/rdf+xml") # Check manifest RDF graph self.assertIn((rouri, RDF.type, RO.ResearchObject), manifest) self.assertIn((rouri, DCTERMS.creator, None), manifest) self.assertIn((rouri, DCTERMS.created, None), manifest) self.assertIn((rouri, ORE.isDescribedBy, manifesturi), manifest) return def testGetROPage(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Get landing page (status, reason, headers, pageuri, page) = self.rosrs.getROLandingPage(rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "text/html;charset=UTF-8") return def testGetROZip(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Get manifest (status, reason, headers, datauri, data) = self.rosrs.getROZip(rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "application/zip") # @@TODO test content of zip (data)? return def testAggregateResourceInt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Aggregate internal resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/path", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) self.assertEqual(reason, "Created") self.assertEqual(str(resuri), str(rouri)+"test/path") # GET content (status, reason, headers, uri, data) = self.rosrs.getROResource( "test/path", rouri) self.assertEqual(status, 200) self.assertEqual(headers["content-type"], "text/plain") self.assertEqual(data, rescontent) # GET proxy (getproxyuri, manifest) = self.rosrs.getROResourceProxy( "test/path", rouri=rouri) self.assertEqual(getproxyuri, proxyuri) return def testDeleteResourceInt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/path", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # GET content (status, reason, headers, uri, data) = self.rosrs.getROResource( "test/path", rouri) self.assertEqual(status, 200) # Delete resource (status, reason) = self.rosrs.removeResource(rouri, resuri) self.assertEqual(status, 204) self.assertEqual(reason, "No Content") # Check that resource is no longer available (status, reason, headers, uri, data) = self.rosrs.getROResource(resuri) self.assertEqual(status, 404) return def testAggregateResourceExt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Aggregate external resource externaluri = rdflib.URIRef("http://example.com/external/resource.txt") (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceExt( rouri, externaluri) self.assertEqual(status, 201) self.assertEqual(reason, "Created") self.assertEqual(resuri, externaluri) # GET proxy (note: using rdflib.URIRef value for path) (getproxyuri, manifest) = self.rosrs.getROResourceProxy( externaluri, rouri) self.assertEqual(getproxyuri, proxyuri) return def testDeleteResourceExt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create test resource externaluri = rdflib.URIRef("http://example.com/external/resource.txt") (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceExt( rouri, externaluri) self.assertEqual(status, 201) self.assertEqual(resuri, externaluri) # GET proxy (note: using rdflib.URIRef for path) (getproxyuri, manifest) = self.rosrs.getROResourceProxy( externaluri, rouri) self.assertEqual(getproxyuri, proxyuri) # Delete resource (status, reason) = self.rosrs.removeResource(rouri, resuri) self.assertEqual(status, 204) self.assertEqual(reason, "No Content") (getproxyuri, manifest) = self.rosrs.getROResourceProxy( externaluri, rouri) self.assertIsNone(getproxyuri) self.assertIsNotNone(manifest) return def testGetROResource(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/path", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # GET content (status, reason, headers, uri, data) = self.rosrs.getROResource( "test/path", rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "text/plain") self.assertEqual(data, rescontent) return def testGetROResourceRDF(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" > <rdf:Description rdf:about="http://example.org/file1.txt"> <dct:title>Title for file1.txt</dct:title> </rdf:Description> </rdf:RDF> """ (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file1.rdf", ctype="application/rdf+xml", body=rescontent) self.assertEqual(status, 201) # Get resource content (status, reason, headers, uri, graph)= self.rosrs.getROResourceRDF( "test/file1.rdf", rouri=rouri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertEqual(headers["content-type"], "application/rdf+xml") s = rdflib.URIRef("http://example.org/file1.txt") self.assertIn((s, DCTERMS.title, rdflib.Literal("Title for file1.txt")), graph) return def testGetROResourceProxy(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/path", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Get resource proxy (getproxyuri, manifest) = self.rosrs.getROResourceProxy( "test/path", rouri=rouri) self.assertEqual(getproxyuri, proxyuri) return def testCreateROAnnotationInt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file.txt", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Create internal annotation annbody = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph = rdflib.graph.Graph() agraph.parse(data=annbody, format="xml") (status, reason, annuri, bodyuri) = self.rosrs.createROAnnotationInt( rouri, resuri, agraph) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris) buris = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri, buris) # Retrieve annotation (status, reason, bodyuri, anngr) = self.rosrs.getROAnnotation(annuri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title for test/file.txt")), anngr) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test")), anngr) return def testGetROAnnotationGraph(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file.txt", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Create internal annotation annbody = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph = rdflib.graph.Graph() agraph.parse(data=annbody, format="xml") (status, reason, annuri, bodyuri) = self.rosrs.createROAnnotationInt( rouri, resuri, agraph) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve merged annotations anngr = self.rosrs.getROAnnotationGraph(rouri, resuri) annts = list(anngr.triples((None, None, None))) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title for test/file.txt")), annts) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test")), annts) return def testCreateROAnnotationExt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create external test resource (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceExt( rouri, rdflib.URIRef("http://example.org/ext")) self.assertEqual(status, 201) # Create annotation using external body reference bodyuri = rdflib.URIRef("http://example.org/ext/ann.rdf") (status, reason, annuri) = self.rosrs.createROAnnotationExt(rouri, resuri, bodyuri) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris) buris = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri, buris) return def testUpdateROAnnotationInt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file.txt", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Create internal annotation annbody1 = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title 1</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test1" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph1 = rdflib.graph.Graph() agraph1.parse(data=annbody1, format="xml") (status, reason, annuri, bodyuri1) = self.rosrs.createROAnnotationInt( rouri, resuri, agraph1) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris1 = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris1) buris1 = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri1, buris1) # Retrieve annotation (status, reason, auri1, anngr1a) = self.rosrs.getROAnnotation(annuri) self.assertEqual(status, 200) self.assertEqual(reason, "OK") annts1a = list(anngr1a.triples((None, None, None))) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title 1")), annts1a) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test1")), annts1a) # Retrieve merged annotations anngr1b = self.rosrs.getROAnnotationGraph(rouri, resuri) annts1b = list(anngr1b.triples((None, None, None))) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title 1")), annts1b) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test1")), annts1b) # Update internal annotation annbody2 = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title 2</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test2" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph2 = rdflib.graph.Graph() agraph2.parse(data=annbody2, format="xml") (status, reason, bodyuri2) = self.rosrs.updateROAnnotationInt( rouri, annuri, resuri, agraph2) self.assertEqual(status, 200) self.assertEqual(reason, "OK") # Retrieve annotation URIs auris2 = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris2) buris2 = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri2, buris2) # Retrieve annotation (status, reason, auri2a, anngr2a) = self.rosrs.getROAnnotation(annuri) annts2a = list(anngr2a.triples((None, None, None))) self.assertEqual(status, 200) self.assertEqual(reason, "OK") self.assertNotIn((resuri, DCTERMS.title, rdflib.Literal("Title 1")), annts2a) self.assertNotIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test1")), annts2a) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title 2")), annts2a) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test2")), annts2a) # Retrieve merged annotations anngr2b = self.rosrs.getROAnnotationGraph(rouri, resuri) annts2b = list(anngr2b.triples((None, None, None))) self.assertNotIn((resuri, DCTERMS.title, rdflib.Literal("Title 1")), annts2b) self.assertNotIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test1")), annts2b) self.assertIn((resuri, DCTERMS.title, rdflib.Literal("Title 2")), annts2b) self.assertIn((resuri, RDFS.seeAlso, rdflib.URIRef("http://example.org/test2")), annts2b) return def testUpdateROAnnotationExt(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create external test resource (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceExt( rouri, rdflib.URIRef("http://example.org/ext")) self.assertEqual(status, 201) # Create annotation using external body reference bodyuri1 = rdflib.URIRef("http://example.org/ext/ann1.rdf") (status, reason, annuri) = self.rosrs.createROAnnotationExt(rouri, resuri, bodyuri1) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris1 = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris1) buris1 = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) self.assertIn(bodyuri1, buris1) # Update annotation using external body reference # @@TODO - this doesn't check that old annotation is removed. # @@TODO - currently, update is not fully implemented (2013-05). bodyuri2 = rdflib.URIRef("http://example.org/ext/ann2.rdf") (status, reason, annuri) = self.rosrs.createROAnnotationExt(rouri, resuri, bodyuri2) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris2 = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris2) buris2 = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) self.assertIn(bodyuri1, buris2) return def testRemoveROAnnotation(self): (status, reason, rouri, manifest) = self.createTestRO() self.assertEqual(status, 201) # Create internal test resource rescontent = "Resource content\n" (status, reason, proxyuri, resuri) = self.rosrs.aggregateResourceInt( rouri, "test/file.txt", ctype="text/plain", body=rescontent) self.assertEqual(status, 201) # Create internal annotation annbody = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> """%(str(rouri)) agraph = rdflib.graph.Graph() agraph.parse(data=annbody, format="xml") (status, reason, annuri, bodyuri) = self.rosrs.createROAnnotationInt( rouri, resuri, agraph) self.assertEqual(status, 201) self.assertEqual(reason, "Created") # Retrieve annotation URIs auris = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertIn(annuri, auris) buris = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertIn(bodyuri, buris) # Remove the annotation (status, reason) = self.rosrs.removeROAnnotation(rouri, annuri) self.assertEqual(status, 204) self.assertEqual(reason, "No Content") # Retrieve annotation URIs auris = list(self.rosrs.getROAnnotationUris(rouri, resuri)) self.assertNotIn(annuri, auris) buris = list(self.rosrs.getROAnnotationBodyUris(rouri, resuri)) ### self.assertNotIn(bodyuri, buris) return # Evolution tests def testCopyRO(self): return def testCancelCopyRO(self): return def testUpdateROStatus(self): return def testGetROEvolution(self): return # Sentinel/placeholder tests def testUnits(self): assert (True) def testComponents(self): assert (True) def testIntegration(self): assert (True) def testPending(self): assert (False), "Pending tests follow" # Assemble test suite def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" return suite of pending tests name a single named test to be run """ testdict = { "unit": [ "testUnits" , "testHelpers" , "testListROs" , "testCreateRO" , "testDeleteRO" , "testGetROManifest" , "testGetROPage" , "testGetROZip" # Resource tests , "testAggregateResourceInt" , "testDeleteResourceInt" , "testAggregateResourceExt" , "testDeleteResourceExt" , "testGetROResource" , "testGetROResourceRDF" , "testGetROResourceProxy" # Annotation tests , "testCreateROAnnotationInt" , "testGetROAnnotationGraph" , "testCreateROAnnotationExt" , "testUpdateROAnnotationInt" , "testUpdateROAnnotationExt" , "testRemoveROAnnotation" # Evolution tests , "testCopyRO" , "testCancelCopyRO" , "testUpdateROStatus" , "testGetROEvolution" ], "component": [ "testComponents" ], "integration": [ "testIntegration" ], "pending": [ "testPending" ] } return TestUtils.getTestSuite(TestROSRS_Session, testdict, select=select) if __name__ == "__main__": TestUtils.runTests("TestROSRS_Session.log", getTestSuite, sys.argv) # End.
en
0.426088
#!/usr/bin/env python Module to test RO SRS APIfunctions # Add main project directory and ro manager directories at start of python path # Logging object # Base directory for file access tests in this module # Test config details # "http://sandbox.wf4ever-project.org/rodl/ROs/" # Test cases This test suite tests the ROSRS_Session client implementation of the ROSRS API # Clean up from previous runs # Clean up # Actual tests follow # Test that new RO is in collection # Delete RO # Test that new RO is not in collection # Delete again # Get manifest # Check manifest RDF graph # Get landing page # Get manifest # @@TODO test content of zip (data)? # Aggregate internal resource # GET content # GET proxy # Create test resource # GET content # Delete resource # Check that resource is no longer available # Aggregate external resource # GET proxy (note: using rdflib.URIRef value for path) # Create test resource # GET proxy (note: using rdflib.URIRef for path) # Delete resource # Create test resource # GET content # Create internal test resource <?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" > <rdf:Description rdf:about="http://example.org/file1.txt"> <dct:title>Title for file1.txt</dct:title> </rdf:Description> </rdf:RDF> # Get resource content # Create internal test resource # Get resource proxy # Create internal test resource # Create internal annotation <?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> # Retrieve annotation URIs ### self.assertIn(bodyuri, buris) # Retrieve annotation # Create internal test resource # Create internal annotation <?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> # Retrieve merged annotations # Create external test resource # Create annotation using external body reference # Retrieve annotation URIs ### self.assertIn(bodyuri, buris) # Create internal test resource # Create internal annotation <?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title 1</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test1" /> </rdf:Description> </rdf:RDF> # Retrieve annotation URIs ### self.assertIn(bodyuri1, buris1) # Retrieve annotation # Retrieve merged annotations # Update internal annotation <?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title 2</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test2" /> </rdf:Description> </rdf:RDF> # Retrieve annotation URIs ### self.assertIn(bodyuri2, buris2) # Retrieve annotation # Retrieve merged annotations # Create external test resource # Create annotation using external body reference # Retrieve annotation URIs # Update annotation using external body reference # @@TODO - this doesn't check that old annotation is removed. # @@TODO - currently, update is not fully implemented (2013-05). # Retrieve annotation URIs # Create internal test resource # Create internal annotation <?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xml:base="%s" > <rdf:Description rdf:about="test/file.txt"> <dct:title>Title for test/file.txt</dct:title> <rdfs:seeAlso rdf:resource="http://example.org/test" /> </rdf:Description> </rdf:RDF> # Retrieve annotation URIs ### self.assertIn(bodyuri, buris) # Remove the annotation # Retrieve annotation URIs ### self.assertNotIn(bodyuri, buris) # Evolution tests # Sentinel/placeholder tests # Assemble test suite Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" return suite of pending tests name a single named test to be run # Resource tests # Annotation tests # Evolution tests # End.
2.211821
2
docs_src/tutorial/body/tutorial_002.py
dantownsend/xpresso
75
6624309
from typing import Dict, Optional from pydantic import BaseModel, Field from xpresso import App, FromJson, Path from xpresso.typing import Annotated class Item(BaseModel): name: str price: Annotated[ float, Field( gt=0, description="Item price without tax. Must be greater than zero.", ), ] tax: Optional[float] = None async def create_receipt(item: FromJson[Item]) -> Dict[str, float]: return {item.name: item.price + (item.tax or 0)} app = App( routes=[ Path( "/items/", post=create_receipt, ) ] )
from typing import Dict, Optional from pydantic import BaseModel, Field from xpresso import App, FromJson, Path from xpresso.typing import Annotated class Item(BaseModel): name: str price: Annotated[ float, Field( gt=0, description="Item price without tax. Must be greater than zero.", ), ] tax: Optional[float] = None async def create_receipt(item: FromJson[Item]) -> Dict[str, float]: return {item.name: item.price + (item.tax or 0)} app = App( routes=[ Path( "/items/", post=create_receipt, ) ] )
none
1
2.557941
3
tests/integration_tests/IT_test_transformBertTextTokenise.py
elangovana/kegg-pathway-extractor
10
6624310
import os from unittest import TestCase from algorithms.transform_berttext_tokenise import TransformBertTextTokenise class ITTransformBertTextTokenise(TestCase): def test___init__(self): base_model_dir = os.path.join(os.path.dirname(__file__), "..", "temp", "biobert") assert len(os.listdir( base_model_dir)) >= 3, "The dir {} should contain the model bin and config and vocab files. If not download the biobert model".format( base_model_dir) # Arrange max_feature_lens = [30, 7, 7] case_insensitive = False sut = TransformBertTextTokenise(base_model_dir, max_feature_lens, case_insensitive) input = [ # batch [ # X [ # 3 columns [ "This is a map PROTEIN1. PROTEIN1 phophorylates PROTEIN2" ] , [ "PROTEIN1" ] , [ "PROTEIN2" ] ] , # y [ "Yes" ] ] ] expected = [ # batch [ # x [ # 3 columns [ ["[CLS]", 'This', 'is', 'a', 'map', 'PR', '##OT', '##EI', '##N', '##1', '.', 'PR', '##OT', '##EI', '##N', '##1', 'p', '##hop', '##hor', '##yla', '##tes', 'PR', '##OT', '##EI', '##N', '##2', "[PAD]", "[PAD]", "[PAD]", "[SEP]"] ] , [ ["[CLS]", 'PR', '##OT', '##EI', '##N', '##1', "[SEP]"] ] , [ ["[CLS]", 'PR', '##OT', '##EI', '##N', '##2', "[SEP]"] ] ] # end of x # Y , [ # batch size 1 "Yes" ] ] # end of batch ] # Act actual = sut.fit_transform(input) print(actual) print(expected) # Assert self.assertSequenceEqual(expected, actual)
import os from unittest import TestCase from algorithms.transform_berttext_tokenise import TransformBertTextTokenise class ITTransformBertTextTokenise(TestCase): def test___init__(self): base_model_dir = os.path.join(os.path.dirname(__file__), "..", "temp", "biobert") assert len(os.listdir( base_model_dir)) >= 3, "The dir {} should contain the model bin and config and vocab files. If not download the biobert model".format( base_model_dir) # Arrange max_feature_lens = [30, 7, 7] case_insensitive = False sut = TransformBertTextTokenise(base_model_dir, max_feature_lens, case_insensitive) input = [ # batch [ # X [ # 3 columns [ "This is a map PROTEIN1. PROTEIN1 phophorylates PROTEIN2" ] , [ "PROTEIN1" ] , [ "PROTEIN2" ] ] , # y [ "Yes" ] ] ] expected = [ # batch [ # x [ # 3 columns [ ["[CLS]", 'This', 'is', 'a', 'map', 'PR', '##OT', '##EI', '##N', '##1', '.', 'PR', '##OT', '##EI', '##N', '##1', 'p', '##hop', '##hor', '##yla', '##tes', 'PR', '##OT', '##EI', '##N', '##2', "[PAD]", "[PAD]", "[PAD]", "[SEP]"] ] , [ ["[CLS]", 'PR', '##OT', '##EI', '##N', '##1', "[SEP]"] ] , [ ["[CLS]", 'PR', '##OT', '##EI', '##N', '##2', "[SEP]"] ] ] # end of x # Y , [ # batch size 1 "Yes" ] ] # end of batch ] # Act actual = sut.fit_transform(input) print(actual) print(expected) # Assert self.assertSequenceEqual(expected, actual)
en
0.061851
# Arrange # batch # X # 3 columns # y # batch # x # 3 columns #OT', '##EI', '##N', '##1', '.', 'PR', '##OT', #EI', #N', '##1', 'p', '##hop', '##hor', '##yla', '##tes', 'PR', '##OT', '##EI', '##N', '##2', #OT', '##EI', '##N', '##1', "[SEP]"] #OT', '##EI', '##N', '##2', "[SEP]"] # end of x # Y # batch size 1 # end of batch # Act # Assert
2.472718
2
snyk/register.py
aarlaud-snyk/snyk-pants-plugin
0
6624311
<reponame>aarlaud-snyk/snyk-pants-plugin from pants.goal.goal import Goal from pants.goal.task_registrar import TaskRegistrar as task from snyk.tasks.snyk import SnykTask from snyk.tasks.dependencies import DependenciesTask def register_goals(): Goal.register(name="snyktest", description="Snyk Test your dependencies for vulnerabilities") task(name='dependencies', action=DependenciesTask).install('snyktest') task(name='snyk', action=SnykTask).install('snyktest')
from pants.goal.goal import Goal from pants.goal.task_registrar import TaskRegistrar as task from snyk.tasks.snyk import SnykTask from snyk.tasks.dependencies import DependenciesTask def register_goals(): Goal.register(name="snyktest", description="Snyk Test your dependencies for vulnerabilities") task(name='dependencies', action=DependenciesTask).install('snyktest') task(name='snyk', action=SnykTask).install('snyktest')
none
1
1.894094
2
auth.py
EnsembleGetMagic/nft-rater-retweet
0
6624312
import os import tweepy from dotenv import load_dotenv load_dotenv() #Load enviroment keys CONSUMER_KEY = os.getenv('CONSUMER_KEY') CONSUMER_SECRET = os.getenv('CONSUMER_SECRET') ACCESS_TOKEN = os.getenv('ACCESS_TOKEN') ACCESS_SECRET = os.getenv('ACCESS_SECRET') #Set up api auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) api = tweepy.API(auth, wait_on_rate_limit = True) #Check API try: api.verify_credentials() print('OK') except: print('Authentication error')
import os import tweepy from dotenv import load_dotenv load_dotenv() #Load enviroment keys CONSUMER_KEY = os.getenv('CONSUMER_KEY') CONSUMER_SECRET = os.getenv('CONSUMER_SECRET') ACCESS_TOKEN = os.getenv('ACCESS_TOKEN') ACCESS_SECRET = os.getenv('ACCESS_SECRET') #Set up api auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) api = tweepy.API(auth, wait_on_rate_limit = True) #Check API try: api.verify_credentials() print('OK') except: print('Authentication error')
en
0.463028
#Load enviroment keys #Set up api #Check API
2.613133
3
tests/core/test_config_utils.py
ethyca/fides
153
6624313
<reponame>ethyca/fides<filename>tests/core/test_config_utils.py # pylint: disable=missing-docstring, redefined-outer-name import os from typing import Generator import pytest from py._path.local import LocalPath from toml import dump, load from fidesctl.core.config import FidesctlConfig from fidesctl.core.config.utils import update_config_file @pytest.fixture def test_change_config() -> Generator: """Create a dictionary to be used as an example config file""" yield {"cli": {"analytics_id": "initial_id"}} @pytest.mark.unit def test_update_config_file_new_value( test_change_config: FidesctlConfig, tmpdir: LocalPath ) -> None: """ Create an example config.toml and validate both updating an existing config setting and adding a new section and setting. """ config_path = os.path.join(tmpdir, "test_writing_config.toml") with open(config_path, "w") as config_file: dump(test_change_config, config_file) config_updates = { "cli": {"analytics_id": "updated_id"}, "user": {"analytics_opt_out": True}, } update_config_file(config_updates, config_path) updated_config = load(config_path) assert updated_config["cli"] is not None, "updated_config.cli should exist" assert ( updated_config["cli"]["analytics_id"] == "updated_id" ), "updated_config.cli.analytics_id should be 'updated_id'" assert updated_config["user"] is not None, "updated_config.user should exist" assert updated_config["user"][ "analytics_opt_out" ], "updated_config.user.analytics_opt_out should be True"
# pylint: disable=missing-docstring, redefined-outer-name import os from typing import Generator import pytest from py._path.local import LocalPath from toml import dump, load from fidesctl.core.config import FidesctlConfig from fidesctl.core.config.utils import update_config_file @pytest.fixture def test_change_config() -> Generator: """Create a dictionary to be used as an example config file""" yield {"cli": {"analytics_id": "initial_id"}} @pytest.mark.unit def test_update_config_file_new_value( test_change_config: FidesctlConfig, tmpdir: LocalPath ) -> None: """ Create an example config.toml and validate both updating an existing config setting and adding a new section and setting. """ config_path = os.path.join(tmpdir, "test_writing_config.toml") with open(config_path, "w") as config_file: dump(test_change_config, config_file) config_updates = { "cli": {"analytics_id": "updated_id"}, "user": {"analytics_opt_out": True}, } update_config_file(config_updates, config_path) updated_config = load(config_path) assert updated_config["cli"] is not None, "updated_config.cli should exist" assert ( updated_config["cli"]["analytics_id"] == "updated_id" ), "updated_config.cli.analytics_id should be 'updated_id'" assert updated_config["user"] is not None, "updated_config.user should exist" assert updated_config["user"][ "analytics_opt_out" ], "updated_config.user.analytics_opt_out should be True"
en
0.704285
# pylint: disable=missing-docstring, redefined-outer-name Create a dictionary to be used as an example config file Create an example config.toml and validate both updating an existing config setting and adding a new section and setting.
2.18516
2
public/python/setgoals.py
aaronmsimon/nhl94-season-replay
0
6624314
#!C:/Program Files/Python38/python.exe import binascii import csv # open save file filename = r'C:\Users\Aaron\AppData\Roaming\RetroArch\states\nhl94_updated.state' with open(filename,'rb') as inputfile: content = inputfile.read() hexFile = binascii.hexlify(content).decode('utf-8') n = 2 hexes = [(hexFile[i:i+n]) for i in range(0, len(hexFile), n)] # check points playerstats = {} players = [] for h in range(0,24): players.append([int(hexes[51089 + h + (h + 1) % 2 * 2],16), int(hexes[51115 + h + (h + 1) % 2 * 2],16) ]) playerstats['home'] = players players = [] for a in range(0,24): players.append([int(hexes[51957 + a + (a + 1) % 2 * 2],16), int(hexes[51983 + a + (a + 1) % 2 * 2],16) ]) playerstats['away'] = players # parse scoringsummary with open("www\scoringsummary.txt",'r') as goalfile: goal_list = csv.reader(goalfile,delimiter=',') for goal in goal_list: # goal scorer hexes[int(goal[0]) + 2] = format(int(goal[1]),'02x') # determine team for which set of player stats to update if hexes[int(goal[0]) + 3][:1] == '0': scoresummary_team = 'home' else: scoresummary_team = 'away' # player stats # check if assist1 is different if hexes[int(goal[0]) + 5] != format(int(goal[2]),'02x'): # check if the original assist was not empty if hexes[int(goal[0]) + 5] != 'ff': # if not, then reduce the original assist by one playerstats[scoresummary_team][int(hexes[int(goal[0]) + 5],16)][1] = int(playerstats[scoresummary_team][int(hexes[int(goal[0]) + 5],16)][1] - 1) # always increase the new assist by one playerstats[scoresummary_team][int(goal[2])][1] = int(playerstats[scoresummary_team][int(goal[2])][1] + 1) # print('original assist2={}'.format(hexes[int(goal[0]) + 4])) # print('new assist2={}'.format(format(int(goal[3]),'02x'))) if hexes[int(goal[0]) + 4] != format(int(goal[3]),'02x'): if hexes[int(goal[0]) + 4] != 'ff': playerstats[scoresummary_team][int(hexes[int(goal[0]) + 4],16)][1] = int(playerstats[scoresummary_team][int(hexes[int(goal[0]) + 4],16)][1] - 1) playerstats[scoresummary_team][int(goal[3])][1] = int(playerstats[scoresummary_team][int(goal[3])][1] + 1) # scoring summary hexes[int(goal[0]) + 5] = 'ff' if goal[2] == '255' else format(int(goal[2]),'02x') hexes[int(goal[0]) + 4] = 'ff' if goal[3] == '255' else format(int(goal[3]),'02x') # write back to hexes for h in range(0,24): hexes[51115 + h + (h + 1) % 2 * 2] = format(playerstats['home'][h][1],'02x') # print(hexes[51985]) for a in range(0,24): hexes[51983 + a + (a + 1) % 2 * 2] = format(playerstats['away'][a][1],'02x') # print(hexes[51985]) newhexes = [] for i in range(0,len(hexes)): newhexes.append(int(str(hexes[i]),16)) switchedfile = bytearray(newhexes) with open(filename,'wb') as writefile: writefile.write(switchedfile)
#!C:/Program Files/Python38/python.exe import binascii import csv # open save file filename = r'C:\Users\Aaron\AppData\Roaming\RetroArch\states\nhl94_updated.state' with open(filename,'rb') as inputfile: content = inputfile.read() hexFile = binascii.hexlify(content).decode('utf-8') n = 2 hexes = [(hexFile[i:i+n]) for i in range(0, len(hexFile), n)] # check points playerstats = {} players = [] for h in range(0,24): players.append([int(hexes[51089 + h + (h + 1) % 2 * 2],16), int(hexes[51115 + h + (h + 1) % 2 * 2],16) ]) playerstats['home'] = players players = [] for a in range(0,24): players.append([int(hexes[51957 + a + (a + 1) % 2 * 2],16), int(hexes[51983 + a + (a + 1) % 2 * 2],16) ]) playerstats['away'] = players # parse scoringsummary with open("www\scoringsummary.txt",'r') as goalfile: goal_list = csv.reader(goalfile,delimiter=',') for goal in goal_list: # goal scorer hexes[int(goal[0]) + 2] = format(int(goal[1]),'02x') # determine team for which set of player stats to update if hexes[int(goal[0]) + 3][:1] == '0': scoresummary_team = 'home' else: scoresummary_team = 'away' # player stats # check if assist1 is different if hexes[int(goal[0]) + 5] != format(int(goal[2]),'02x'): # check if the original assist was not empty if hexes[int(goal[0]) + 5] != 'ff': # if not, then reduce the original assist by one playerstats[scoresummary_team][int(hexes[int(goal[0]) + 5],16)][1] = int(playerstats[scoresummary_team][int(hexes[int(goal[0]) + 5],16)][1] - 1) # always increase the new assist by one playerstats[scoresummary_team][int(goal[2])][1] = int(playerstats[scoresummary_team][int(goal[2])][1] + 1) # print('original assist2={}'.format(hexes[int(goal[0]) + 4])) # print('new assist2={}'.format(format(int(goal[3]),'02x'))) if hexes[int(goal[0]) + 4] != format(int(goal[3]),'02x'): if hexes[int(goal[0]) + 4] != 'ff': playerstats[scoresummary_team][int(hexes[int(goal[0]) + 4],16)][1] = int(playerstats[scoresummary_team][int(hexes[int(goal[0]) + 4],16)][1] - 1) playerstats[scoresummary_team][int(goal[3])][1] = int(playerstats[scoresummary_team][int(goal[3])][1] + 1) # scoring summary hexes[int(goal[0]) + 5] = 'ff' if goal[2] == '255' else format(int(goal[2]),'02x') hexes[int(goal[0]) + 4] = 'ff' if goal[3] == '255' else format(int(goal[3]),'02x') # write back to hexes for h in range(0,24): hexes[51115 + h + (h + 1) % 2 * 2] = format(playerstats['home'][h][1],'02x') # print(hexes[51985]) for a in range(0,24): hexes[51983 + a + (a + 1) % 2 * 2] = format(playerstats['away'][a][1],'02x') # print(hexes[51985]) newhexes = [] for i in range(0,len(hexes)): newhexes.append(int(str(hexes[i]),16)) switchedfile = bytearray(newhexes) with open(filename,'wb') as writefile: writefile.write(switchedfile)
en
0.740993
#!C:/Program Files/Python38/python.exe # open save file # check points # parse scoringsummary # goal scorer # determine team for which set of player stats to update # player stats # check if assist1 is different # check if the original assist was not empty # if not, then reduce the original assist by one # always increase the new assist by one # print('original assist2={}'.format(hexes[int(goal[0]) + 4])) # print('new assist2={}'.format(format(int(goal[3]),'02x'))) # scoring summary # write back to hexes # print(hexes[51985]) # print(hexes[51985])
2.725025
3
VAT/utils.py
vamoscy/DeepLearning2019
0
6624315
<filename>VAT/utils.py<gh_stars>0 from collections import OrderedDict import logging import logzero from pathlib import Path from tensorboardX import SummaryWriter import torch class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, top_k=(1,)): """Computes the precision@k for the specified values of k""" max_k = max(top_k) batch_size = target.size(0) _, pred = output.topk(max_k, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in top_k: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) if len(res) == 1: res = res[0] return res def save_checkpoint(model, epoch, filename, optimizer=None): if optimizer is None: torch.save({ 'epoch': epoch, 'state_dict': model.state_dict(), }, filename) else: torch.save({ 'epoch': epoch, 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), }, filename) def load_checkpoint(model, path, optimizer=None): resume = torch.load(path) if ('module' in list(resume['state_dict'].keys())[0]) \ and not (isinstance(model, torch.nn.DataParallel)): new_state_dict = OrderedDict() for k, v in resume['state_dict'].items(): name = k[7:] # remove `module.` new_state_dict[name] = v model.load_state_dict(new_state_dict) else: model.load_state_dict(resume['state_dict']) if optimizer is not None: optimizer.load_state_dict(resume['optimizer']) return model, optimizer else: return model def set_logger(path, loglevel=logging.INFO, tf_board_path=None): path_dir = '/'.join(path.split('/')[:-1]) if not Path(path_dir).exists(): Path(path_dir).mkdir(parents=True) logzero.loglevel(loglevel) logzero.formatter(logging.Formatter('[%(asctime)s %(levelname)s] %(message)s')) logzero.logfile(path) if tf_board_path is not None: tb_path_dir = '/'.join(tf_board_path.split('/')[:-1]) if not Path(tb_path_dir).exists(): Path(tb_path_dir).mkdir(parents=True) writer = SummaryWriter(tf_board_path) return writer
<filename>VAT/utils.py<gh_stars>0 from collections import OrderedDict import logging import logzero from pathlib import Path from tensorboardX import SummaryWriter import torch class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, top_k=(1,)): """Computes the precision@k for the specified values of k""" max_k = max(top_k) batch_size = target.size(0) _, pred = output.topk(max_k, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in top_k: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) if len(res) == 1: res = res[0] return res def save_checkpoint(model, epoch, filename, optimizer=None): if optimizer is None: torch.save({ 'epoch': epoch, 'state_dict': model.state_dict(), }, filename) else: torch.save({ 'epoch': epoch, 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict(), }, filename) def load_checkpoint(model, path, optimizer=None): resume = torch.load(path) if ('module' in list(resume['state_dict'].keys())[0]) \ and not (isinstance(model, torch.nn.DataParallel)): new_state_dict = OrderedDict() for k, v in resume['state_dict'].items(): name = k[7:] # remove `module.` new_state_dict[name] = v model.load_state_dict(new_state_dict) else: model.load_state_dict(resume['state_dict']) if optimizer is not None: optimizer.load_state_dict(resume['optimizer']) return model, optimizer else: return model def set_logger(path, loglevel=logging.INFO, tf_board_path=None): path_dir = '/'.join(path.split('/')[:-1]) if not Path(path_dir).exists(): Path(path_dir).mkdir(parents=True) logzero.loglevel(loglevel) logzero.formatter(logging.Formatter('[%(asctime)s %(levelname)s] %(message)s')) logzero.logfile(path) if tf_board_path is not None: tb_path_dir = '/'.join(tf_board_path.split('/')[:-1]) if not Path(tb_path_dir).exists(): Path(tb_path_dir).mkdir(parents=True) writer = SummaryWriter(tf_board_path) return writer
en
0.383527
Computes and stores the average and current value Computes the precision@k for the specified values of k # remove `module.`
2.264258
2
stage01/rogue.py
kantel/tkbuchhaim
0
6624316
import tkinter as tk import os root = tk.Tk() root.title("Rogue Stage 1") cw, ch = 640, 480 canvas = tk.Canvas(root, width = cw, height = ch, bg = "royalblue") canvas.grid(row = 0, column = 0) # Hier wird der Pfad zum Verzeichnis des ».py«-Files gesetzt # Erspart einem das Herumgehample in TextMate mit dem os.getcwd() # und os.path.join() file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) rogue = tk.PhotoImage(file = "../images/hildegunst.gif") canvas.create_image(cw//2, ch//2, anchor = tk.NW, image = rogue) canvas.update() root.mainloop()
import tkinter as tk import os root = tk.Tk() root.title("Rogue Stage 1") cw, ch = 640, 480 canvas = tk.Canvas(root, width = cw, height = ch, bg = "royalblue") canvas.grid(row = 0, column = 0) # Hier wird der Pfad zum Verzeichnis des ».py«-Files gesetzt # Erspart einem das Herumgehample in TextMate mit dem os.getcwd() # und os.path.join() file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) rogue = tk.PhotoImage(file = "../images/hildegunst.gif") canvas.create_image(cw//2, ch//2, anchor = tk.NW, image = rogue) canvas.update() root.mainloop()
de
0.993798
# Hier wird der Pfad zum Verzeichnis des ».py«-Files gesetzt # Erspart einem das Herumgehample in TextMate mit dem os.getcwd() # und os.path.join()
2.871483
3
HunterAdminApi/web_app.py
tt9133github/hunter
322
6624317
<filename>HunterAdminApi/web_app.py #!/ usr/bin/env # coding=utf-8 # # Copyright 2019 ztosec & https://www.zto.com/ # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ author: b5mali4 """ import os from datetime import timedelta from flask import Flask, session, Response, jsonify, request, redirect, render_template from api.hunter_user_web_api import user_web_api from api.hunter_admin_web_api import admin_web_api from api.authentication.default_auth_module import account_web_api from api.authentication.ldap_auth_module import ldap_web_api flask_app = Flask(__name__) # flask_app = Flask(__name__, static_url_path="/static", static_folder="api/resource/templates/") flask_app.config['SECRET_KEY'] = os.urandom(24) flask_app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2) # flask_app.config.update(RESTFUL_JSON=dict(ensure_ascii=False)) # 注册到蓝图 flask_app.register_blueprint(user_web_api) flask_app.register_blueprint(admin_web_api) flask_app.register_blueprint(account_web_api) flask_app.register_blueprint(ldap_web_api) @flask_app.after_request def handle_after_request(response): """ 设置CORS源 :param response: :return: """ if request.headers.has_key("Origin"): response.headers["Access-Control-Allow-Origin"] = request.headers["Origin"] response.headers["Access-Control-Allow-Methods"] = "GET,POST,PUT,HEAD,OPTIONS,DELETE,PATCH" response.headers["Access-Control-Allow-Credentials"] = "true" response.headers["Access-Control-Allow-Headers"] = "Content-Type,x-requested-with" return response @flask_app.route('/', methods=['GET'], endpoint='index') def index(): return render_template("index.html") if __name__ == "__main__": flask_app.config['JSON_AS_ASCII'] = False flask_app.run(host="0.0.0.0", port=8888)
<filename>HunterAdminApi/web_app.py #!/ usr/bin/env # coding=utf-8 # # Copyright 2019 ztosec & https://www.zto.com/ # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ author: b5mali4 """ import os from datetime import timedelta from flask import Flask, session, Response, jsonify, request, redirect, render_template from api.hunter_user_web_api import user_web_api from api.hunter_admin_web_api import admin_web_api from api.authentication.default_auth_module import account_web_api from api.authentication.ldap_auth_module import ldap_web_api flask_app = Flask(__name__) # flask_app = Flask(__name__, static_url_path="/static", static_folder="api/resource/templates/") flask_app.config['SECRET_KEY'] = os.urandom(24) flask_app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2) # flask_app.config.update(RESTFUL_JSON=dict(ensure_ascii=False)) # 注册到蓝图 flask_app.register_blueprint(user_web_api) flask_app.register_blueprint(admin_web_api) flask_app.register_blueprint(account_web_api) flask_app.register_blueprint(ldap_web_api) @flask_app.after_request def handle_after_request(response): """ 设置CORS源 :param response: :return: """ if request.headers.has_key("Origin"): response.headers["Access-Control-Allow-Origin"] = request.headers["Origin"] response.headers["Access-Control-Allow-Methods"] = "GET,POST,PUT,HEAD,OPTIONS,DELETE,PATCH" response.headers["Access-Control-Allow-Credentials"] = "true" response.headers["Access-Control-Allow-Headers"] = "Content-Type,x-requested-with" return response @flask_app.route('/', methods=['GET'], endpoint='index') def index(): return render_template("index.html") if __name__ == "__main__": flask_app.config['JSON_AS_ASCII'] = False flask_app.run(host="0.0.0.0", port=8888)
en
0.729797
#!/ usr/bin/env # coding=utf-8 # # Copyright 2019 ztosec & https://www.zto.com/ # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. author: b5mali4 # flask_app = Flask(__name__, static_url_path="/static", static_folder="api/resource/templates/") # flask_app.config.update(RESTFUL_JSON=dict(ensure_ascii=False)) # 注册到蓝图 设置CORS源 :param response: :return:
1.553249
2
src/datamgr/metasdk/metadata_client/event/subscriber.py
Chromico/bk-base
84
6624318
<reponame>Chromico/bk-base<filename>src/datamgr/metasdk/metadata_client/event/subscriber.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础计算平台 available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Copyright © 2012-2018 Tencent BlueKing. # All Rights Reserved. # 蓝鲸智云 版权所有 from __future__ import absolute_import, print_function, unicode_literals import inspect import re import socket import time from metadata_client.exc import EventSubscribeConfigError from metadata_client.resource import resource_lock from metadata_client.support.rabbitmq import BackendClient, RabbitMQConsumer class MetaEventSubscriber(object): META_EVENT_PREFIX = "meta.event" backend = None """ 订阅队列后端实例 """ subscriber_existed = False """ 订阅器是否已注册 """ def __init__(self, subscribe_config=None, supports_config=None): self.subscribe_orders = dict() self.subscriber = None self.callbacks = [] if subscribe_config and isinstance(subscribe_config, dict): self.set_subscribe_config(**subscribe_config) if supports_config: self.backend = BackendClient(supports_config) def gen_subscribe_orders(self, config): """ 根据用户输入构建订阅参数,生成订阅单 :param config: dict 用户输入配置参数 :return: tuple (order_name, order) 订阅单 """ order_name = "{}.{}.{}".format(config["refer"], config["key"], config["name"]) routing_key = "{}.{}".format(self.META_EVENT_PREFIX, config["key"]) order = dict(routing_key=routing_key) return order_name, order @staticmethod def _verify_config_item(item): """ 校验配置项字符串的合法性 :param item: 配置项 :return: boolean """ if re.match("^[_a-zA-Z0-9]+$", str(item)) is None: return False return True def set_subscribe_config(self, name=None, key=None, refer=None, *args, **kwargs): """ 设置订阅配置 :param name: 订阅名称 :param key: 订阅关键字 :param refer: 订阅者所属来源 :param args: 其他参数 :param kwargs: 其他关键字参数 :return: None """ config = dict( name=name if self._verify_config_item(name) else None, key=key if self._verify_config_item(key) else None, refer=refer if self._verify_config_item(refer) else None, ) if all(config.values()): order_name, order = self.gen_subscribe_orders(config) self.subscribe_orders[order_name] = order else: raise EventSubscribeConfigError(message_kv={"detail": config}) def set_callback(self, callbacks=None): """ 设置回调函数 :param callbacks: 回调函数列表 :return: None """ if not isinstance(callbacks, list): callbacks = [callbacks] valid_callbacks = [callback for callback in callbacks if inspect.isfunction(callback)] if valid_callbacks: self.callbacks.extend(valid_callbacks) def register_subscriber(self): """ 注册订阅器,每个进程仅能注册一次 :return: None """ if self.subscribe_orders and not self.__class__.subscriber_existed: with resource_lock: if not self.__class__.subscriber_existed: self.__class__.subscriber_existed = True consumer = RabbitMQConsumer( self.backend, queue_mapping=self.subscribe_orders, exchange_name="meta_event_system", callbacks=self.callbacks, ) self.subscriber = consumer def start_to_listening(self, timeout=1, detection_interval=1): """ 开始接收订阅消息 :param timeout: int 每次探测等待消息到来的超时时间(s) :param detection_interval: int 探测间隔(s) :return: None """ self.register_subscriber() if self.subscriber: try: while True: try: self.subscriber.start_scan(timeout) except socket.timeout: time.sleep(detection_interval) except Exception: print("stop listening") raise finally: self.subscriber.release()
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础计算平台 available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Copyright © 2012-2018 Tencent BlueKing. # All Rights Reserved. # 蓝鲸智云 版权所有 from __future__ import absolute_import, print_function, unicode_literals import inspect import re import socket import time from metadata_client.exc import EventSubscribeConfigError from metadata_client.resource import resource_lock from metadata_client.support.rabbitmq import BackendClient, RabbitMQConsumer class MetaEventSubscriber(object): META_EVENT_PREFIX = "meta.event" backend = None """ 订阅队列后端实例 """ subscriber_existed = False """ 订阅器是否已注册 """ def __init__(self, subscribe_config=None, supports_config=None): self.subscribe_orders = dict() self.subscriber = None self.callbacks = [] if subscribe_config and isinstance(subscribe_config, dict): self.set_subscribe_config(**subscribe_config) if supports_config: self.backend = BackendClient(supports_config) def gen_subscribe_orders(self, config): """ 根据用户输入构建订阅参数,生成订阅单 :param config: dict 用户输入配置参数 :return: tuple (order_name, order) 订阅单 """ order_name = "{}.{}.{}".format(config["refer"], config["key"], config["name"]) routing_key = "{}.{}".format(self.META_EVENT_PREFIX, config["key"]) order = dict(routing_key=routing_key) return order_name, order @staticmethod def _verify_config_item(item): """ 校验配置项字符串的合法性 :param item: 配置项 :return: boolean """ if re.match("^[_a-zA-Z0-9]+$", str(item)) is None: return False return True def set_subscribe_config(self, name=None, key=None, refer=None, *args, **kwargs): """ 设置订阅配置 :param name: 订阅名称 :param key: 订阅关键字 :param refer: 订阅者所属来源 :param args: 其他参数 :param kwargs: 其他关键字参数 :return: None """ config = dict( name=name if self._verify_config_item(name) else None, key=key if self._verify_config_item(key) else None, refer=refer if self._verify_config_item(refer) else None, ) if all(config.values()): order_name, order = self.gen_subscribe_orders(config) self.subscribe_orders[order_name] = order else: raise EventSubscribeConfigError(message_kv={"detail": config}) def set_callback(self, callbacks=None): """ 设置回调函数 :param callbacks: 回调函数列表 :return: None """ if not isinstance(callbacks, list): callbacks = [callbacks] valid_callbacks = [callback for callback in callbacks if inspect.isfunction(callback)] if valid_callbacks: self.callbacks.extend(valid_callbacks) def register_subscriber(self): """ 注册订阅器,每个进程仅能注册一次 :return: None """ if self.subscribe_orders and not self.__class__.subscriber_existed: with resource_lock: if not self.__class__.subscriber_existed: self.__class__.subscriber_existed = True consumer = RabbitMQConsumer( self.backend, queue_mapping=self.subscribe_orders, exchange_name="meta_event_system", callbacks=self.callbacks, ) self.subscriber = consumer def start_to_listening(self, timeout=1, detection_interval=1): """ 开始接收订阅消息 :param timeout: int 每次探测等待消息到来的超时时间(s) :param detection_interval: int 探测间隔(s) :return: None """ self.register_subscriber() if self.subscriber: try: while True: try: self.subscriber.start_scan(timeout) except socket.timeout: time.sleep(detection_interval) except Exception: print("stop listening") raise finally: self.subscriber.release()
en
0.53726
# -*- coding: utf-8 -*- Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础计算平台 available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # Copyright © 2012-2018 Tencent BlueKing. # All Rights Reserved. # 蓝鲸智云 版权所有 订阅队列后端实例 订阅器是否已注册 根据用户输入构建订阅参数,生成订阅单 :param config: dict 用户输入配置参数 :return: tuple (order_name, order) 订阅单 校验配置项字符串的合法性 :param item: 配置项 :return: boolean 设置订阅配置 :param name: 订阅名称 :param key: 订阅关键字 :param refer: 订阅者所属来源 :param args: 其他参数 :param kwargs: 其他关键字参数 :return: None 设置回调函数 :param callbacks: 回调函数列表 :return: None 注册订阅器,每个进程仅能注册一次 :return: None 开始接收订阅消息 :param timeout: int 每次探测等待消息到来的超时时间(s) :param detection_interval: int 探测间隔(s) :return: None
1.779035
2
mvmm_sim/simulation/sim_naming.py
idc9/mvmm_sim
0
6624319
<filename>mvmm_sim/simulation/sim_naming.py import names import numpy as np import os def load_all_names(): all_names = [] for gen in ['male', 'female']: fpath = names.full_path('dist.{}.first'.format(gen)) with open(fpath) as name_file: for line in name_file: name, _, cummulative, _ = line.split() all_names.append(name.lower()) return all_names def get_subfolders(folder): return [name for name in os.listdir(folder) if os.path.isdir(name)] def get_new_name(folder): all_names = load_all_names() existing_names = get_subfolders(folder) possibilities = set(all_names).difference(existing_names) assert len(possibilities) > 0 possibilities = np.array(list(possibilities)) possibilities = np.sort(possibilities) return possibilities[0]
<filename>mvmm_sim/simulation/sim_naming.py import names import numpy as np import os def load_all_names(): all_names = [] for gen in ['male', 'female']: fpath = names.full_path('dist.{}.first'.format(gen)) with open(fpath) as name_file: for line in name_file: name, _, cummulative, _ = line.split() all_names.append(name.lower()) return all_names def get_subfolders(folder): return [name for name in os.listdir(folder) if os.path.isdir(name)] def get_new_name(folder): all_names = load_all_names() existing_names = get_subfolders(folder) possibilities = set(all_names).difference(existing_names) assert len(possibilities) > 0 possibilities = np.array(list(possibilities)) possibilities = np.sort(possibilities) return possibilities[0]
none
1
2.819432
3
scripts/sources/s_default_probabilities.py
dpopadic/arpmRes
6
6624320
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # s_default_probabilities [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_default_probabilities&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-supervised-machine-learning). # + import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.special import logit from sklearn.ensemble import GradientBoostingClassifier from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import OneHotEncoder, PolynomialFeatures, \ QuantileTransformer from sklearn import tree from sklearn.metrics import auc, roc_curve, confusion_matrix from sklearn.model_selection import StratifiedKFold, train_test_split from arpym.tools import add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-parameters) test_size = 0.2 # proportion of the test set n_sample = 10000 # num. of samples in the database; set =30000 to catch it all pol_degree = 2 # degrees in polynomial features lambda_lasso = 0.05 # lasso parameter max_depth_tree = 10 # maximum depth of decision tree classifier cross_val = 0 # set "1" to do cross-validation (computational time increases) k_ = 5 # parameter of Stratified K-Folds cross-validator # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step00): Import data and pre-process database # + # Import data path = '../../../databases/global-databases/credit/' + \ 'db_default_data_creditcardsclients/' df = pd.read_csv(path+'db_default_data_creditcardsclients.csv') df = df.iloc[:, 1:df.shape[1]] # exlude ID # Sort database so that the categorical features are at the beginning # indexes of the categorical features ind_cat = np.r_[np.arange(1, 4), np.arange(5, 11)] n_cat = len(ind_cat) # number of categorical features # indexes of the continuous features ind_cont = np.r_[np.array([0, 4]), np.arange(11, df.shape[1])] n_cont = len(ind_cont) # number of categorical features df = df.iloc[:n_sample, np.r_[ind_cat, ind_cont]] # Outputs and features z = np.array(df.iloc[:, :-1]) # features x = np.array(df.iloc[:, -1]) # labels # Standardize continuous features quantile_transformer = QuantileTransformer(output_distribution='normal') z_cont = quantile_transformer.fit_transform(z[:, -n_cont:]) # Transform categorical features via one-hot encoding # shift up, because the OneHotEncoder takes only positive inputs enc = OneHotEncoder() z_cat = enc.fit_transform(np.abs(np.min(z[:, :n_cat], axis=0)) + z[:, :n_cat]).toarray() n_enc = z_cat.shape[1] # number of encoded categorical features z = np.concatenate((z_cat, z_cont), axis=1) # Define test set and estimation set z_estimation, z_test, x_estimation, x_test = train_test_split(z, x) # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step01): Logistic regression on continuous features # Set C = +infinity to have 0 Lasso parameter lg = LogisticRegression(penalty='l1', C=10**5, class_weight='balanced') lg = lg.fit(z_estimation[:, -n_cont:], x_estimation) # fit the model p_z_lg = lg.predict_proba(z_test[:, -n_cont:])[:, 1] # predict the probs cm_lg = confusion_matrix(x_test, lg.predict(z_test[:, -n_cont:])) # conf. mat. er_lg = -np.sum(np.log(p_z_lg)) # error print('Logistic error: %1.4f' % er_lg) # conditional scores s_0_lg = logit(lg.predict_proba(z_test[:, -n_cont:])[ np.where(x_test == 0)[0], 1]) s_1_lg = logit(lg.predict_proba(z_test[:, -n_cont:])[ np.where(x_test == 1)[0], 1]) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step02): Add interactions to logistic regression # + # Add interactions poly = PolynomialFeatures(degree=pol_degree) z_estimation_inter = poly.fit_transform(z_estimation[:, -n_cont:]) z_test_inter = poly.fit_transform(z_test[:, -n_cont:]) # Set C = +infinity to have 0 Lasso parameter lg_inter = LogisticRegression(penalty='l1', C=10**5, class_weight='balanced') lg_inter = lg_inter.fit(z_estimation_inter, x_estimation) # fit the model p_z_inter = lg_inter.predict_proba(z_test_inter)[:, 1] # pred. the probs. cm_inter = confusion_matrix(x_test, lg_inter.predict(z_test_inter)) er_inter = -np.sum(np.log(p_z_inter)) # error print('Logistic with interactions error: %1.4f' % er_inter) # conditional scores s_0_inter = logit(lg_inter.predict_proba(z_test_inter)[ np.where(x_test == 0)[0], 1]) s_1_inter = logit(lg_inter.predict_proba(z_test_inter)[ np.where(x_test == 1)[0], 1]) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step03): Add encoded categorical features to logistic regression # + z_enc_estimation = np.concatenate((z_estimation[:, :n_enc], z_estimation_inter), axis=1) z_enc_test = np.concatenate((z_test[:, :n_enc], z_test_inter), axis=1) # Set C = +infinity to have 0 Lasso parameter lg_enc = LogisticRegression(penalty='l1', C=10**5, class_weight='balanced') lg_enc = lg_enc.fit(z_enc_estimation, x_estimation) # fit the model p_z_enc = lg_enc.predict_proba(z_enc_test)[:, 1] # pred. the probs. cm_enc = confusion_matrix(x_test, lg_enc.predict(z_enc_test)) er_enc = -np.sum(np.log(p_z_enc)) # error print('Logistic with interactions and categorical error: %1.4f' % er_enc) # conditional scores s_0_enc = logit(lg_enc.predict_proba(z_enc_test)[np.where(x_test == 0)[0], 1]) s_1_enc = logit(lg_enc.predict_proba(z_enc_test)[np.where(x_test == 1)[0], 1]) # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step04): Add lasso regularization lg_lasso = LogisticRegression(penalty='l1', C=10**5, class_weight='balanced') lg_lasso = lg_lasso.fit(z_enc_estimation, x_estimation) # fit the model p_z_lasso = lg_lasso.predict_proba(z_enc_test)[:, 1] # predict the probs. cm_lasso = confusion_matrix(x_test, lg_lasso.predict(z_enc_test)) # conf. mat. er_lasso = -np.sum(np.log(p_z_lasso)) # error print('Logistic with lasso error: %1.4f' % er_lasso) # conditional scores s_0_lasso = logit(lg_lasso.predict_proba(z_enc_test)[ np.where(x_test == 0)[0], 1]) s_1_lasso = logit(lg_lasso.predict_proba(z_enc_test)[ np.where(x_test == 1)[0], 1]) # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step05): CART classifier tree_clf = tree.DecisionTreeClassifier(max_depth=max_depth_tree, class_weight='balanced') # def. method tree_clf = tree_clf.fit(z_enc_estimation, x_estimation) # fit the model p_z_tree = tree_clf.predict_proba(z_enc_test)[:, 1] # predict the scores cm_tree = confusion_matrix(x_test, tree_clf.predict(z_enc_test)) # conf. mat. er_tree = (cm_tree[0, 1]/np.sum(x_test == 0) + cm_tree[1, 0]/np.sum(x_test == 1)) # error print('CART classifier error: %1.4f' % er_tree) # conditional scores eps = 10**-5 # set threshold to avoid numerical noise in the logit function p_0_tree = tree_clf.predict_proba(z_enc_test)[np.where(x_test == 0)[0], 1] p_0_tree[p_0_tree < eps] = eps p_0_tree[p_0_tree > 1-eps] = 1-eps p_1_tree = tree_clf.predict_proba(z_enc_test)[np.where(x_test == 1)[0], 1] p_1_tree[p_1_tree < eps] = eps p_1_tree[p_1_tree > 1-eps] = 1-eps s_0_tree = logit(p_0_tree) s_1_tree = logit(p_1_tree) # ## [Step 6](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step06): Add gradient boosting to CART classifier boost_clf = GradientBoostingClassifier(max_depth=max_depth_tree) # method boost_clf = boost_clf.fit(z_enc_estimation, x_estimation) # fit the model p_z_boost = boost_clf.predict_proba(z_enc_test)[:, 1] # predict the probs. cm_boost = confusion_matrix(x_test, boost_clf.predict(z_enc_test)) # conf. mat er_boost = (cm_boost[0, 1]/np.sum(x_test == 0) + cm_boost[1, 0]/np.sum(x_test == 1)) # error print('CART classifier with gradient boosting error: %1.4f' % er_boost) # conditional scores s_0_boost = logit(boost_clf.predict_proba(z_enc_test)[ np.where(x_test == 0)[0], 1]) s_1_boost = logit(boost_clf.predict_proba(z_enc_test)[ np.where(x_test == 1)[0], 1]) # ## [Step 7](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step07): Compute fpr, tpr and AUC on the test set # + # 1) Logistic fpr_lg, tpr_lg, _ = roc_curve(x_test, p_z_lg) auc_lg = auc(fpr_lg, tpr_lg) print('Logistic AUC: %1.3f' % auc_lg) # 2) Logistic with interactions fpr_inter, tpr_inter, _ = roc_curve(x_test, p_z_inter) auc_inter = auc(fpr_inter, tpr_inter) print('Logistic with interactions AUC: %1.3f' % auc_inter) # 3) Logistic with interactions and encoded categorical features fpr_enc, tpr_enc, _ = roc_curve(x_test, p_z_enc) auc_enc = auc(fpr_enc, tpr_enc) print('Logistic with interactions and categorical AUC: %1.3f' % auc_enc) # 4) Logistic lasso with interactions and encoded categorical features fpr_lasso, tpr_lasso, _ = roc_curve(x_test, p_z_lasso) auc_lasso = auc(fpr_lasso, tpr_lasso) print('Logistic with lasso AUC: %1.3f' % auc_lasso) # 5) CART classifier fpr_tree, tpr_tree, _ = roc_curve(x_test, p_z_tree) auc_tree = auc(fpr_tree, tpr_tree) print('CART classifier AUC: %1.3f' % auc_tree) # 6) Gradient boosting classifier fpr_boost, tpr_boost, _ = roc_curve(x_test, p_z_boost) auc_boost = auc(fpr_boost, tpr_boost) print('Gradient boosting classifier AUC: %1.3f' % auc_boost) # - # ## [Step 8](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step08): Choose best probabilistic and point predictors via cross-validation if cross_val == 1: # Split the estimation set into training and validation sets for k-fold # cross-validation k_fold = StratifiedKFold(n_splits=k_) z_train = [] z_train_inter = [] z_train_enc = [] x_train = [] z_val = [] z_val_inter = [] z_val_enc = [] x_val = [] for train, val in k_fold.split(z_estimation, x_estimation): z_train.append(z_estimation[train]) x_train.append(x_estimation[train]) z_val.append(z_estimation[val]) x_val.append(x_estimation[val]) for train, val in k_fold.split(z_estimation_inter, x_estimation): z_train_inter.append(z_estimation_inter[train]) z_val_inter.append(z_estimation_inter[val]) for train, val in k_fold.split(z_enc_estimation, x_estimation): z_train_enc.append(z_enc_estimation[train]) z_val_enc.append(z_enc_estimation[val]) # Probabilistic cv_er_lg = [] cv_er_lasso = [] cv_er_inter = [] cv_er_enc = [] for k in range(k_): # Logistic p_cv_lg = lg.fit(z_train[k], x_train[k]).predict_proba(z_val[k]) cv_er_lg.append(-np.sum(np.log(p_cv_lg))) # Lasso p_cv_lasso = lg_lasso.fit(z_train[k], x_train[k]).predict_proba(z_val[k]) cv_er_lasso.append(-np.sum(np.log(p_cv_lasso))) # Interactions p_cv_inter = lg_inter.fit(z_train_inter[k], x_train[k]).predict_proba(z_val_inter[k]) cv_er_inter.append(-np.sum(np.log(p_cv_inter))) # Encoded categorical p_cv_enc = lg_inter.fit(z_train_enc[k], x_train[k]).predict_proba(z_val_enc[k]) cv_er_enc.append(-np.sum(np.log(p_cv_enc))) cv_er_lg = np.mean(cv_er_lg) cv_er_lasso = np.mean(cv_er_lasso) cv_er_inter = np.mean(cv_er_inter) cv_er_enc = np.mean(cv_er_enc) # Point cv_er_tree = [] cv_er_boost = [] for k in range(k_): # Tree cm_tree_cv =\ confusion_matrix(x_val[k], tree_clf.fit(z_train[k], x_train[k]).predict(z_val[k])) er_tree_cv = (cm_tree_cv[0, 1]/np.sum(x_val[k] == 0) + cm_tree_cv[1, 0]/np.sum(x_val[k] == 1)) # error cv_er_tree.append(er_tree_cv) # Gradient boosting cm_boost_cv =\ confusion_matrix(x_val[k], boost_clf.fit(z_train[k], x_train[k]).predict(z_val[k])) er_boost_cv = (cm_boost_cv[0, 1]/np.sum(x_val[k] == 0) + cm_boost_cv[1, 0]/np.sum(x_val[k] == 1)) # error cv_er_boost.append(er_boost_cv) cv_er_tree = np.mean(cv_er_tree) cv_er_boost = np.mean(cv_er_boost) print('Logistic CV error: %1.3f' % cv_er_lg) print('Logistic with interactions CV error: %1.3f' % cv_er_inter) print('Logistic with interactions and categorical CV error: %1.3f' % cv_er_enc) print('Logistic with lasso CV error: %1.3f' % cv_er_lasso) print('CART classifier CV error: %1.3f' % cv_er_tree) print('CART classifier with gradient boosting CV error: %1.3f' % cv_er_boost) # ## Plots plt.style.use('arpm') # ## 1) Logistic regression # + fig1 = plt.figure() ax11 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax12 = plt.subplot2grid((2, 2), (0, 1)) ax13 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax11) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_lg, tpr_lg, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_lg) plt.text(0.05, 0.85, 'Error = %.2f' % er_lg) plt.title('Logistic regression (test set)') # Scores plt.sca(ax12) plt.hist(s_0_lg, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_lg, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax13) cax_1 = plt.bar([0, 1], [cm_lg[0, 1]/np.sum(x_test == 0), cm_lg[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig1, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## 2) Logistic regression with interactions # + fig2 = plt.figure() ax31 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax32 = plt.subplot2grid((2, 2), (0, 1)) ax33 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax31) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_inter, tpr_inter, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_inter) plt.text(0.05, 0.85, 'Error = %.2f' % er_inter) plt.title('Logistic regression with interactions deg. = %1i (test set)' % pol_degree) # Scores plt.sca(ax32) plt.hist(s_0_inter, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_inter, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax33) cax_1 = plt.bar([0, 1], [cm_inter[0, 1]/np.sum(x_test == 0), cm_inter[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig2, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## 3) Logistic regression with interactions and encoded categorical features # + fig3 = plt.figure() ax21 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax22 = plt.subplot2grid((2, 2), (0, 1)) ax23 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax21) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_enc, tpr_enc, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_enc) plt.text(0.05, 0.85, 'Error = %.2f' % er_enc) plt.title('Logistic regression with interactions and categorical features') # Scores plt.sca(ax22) plt.hist(s_0_enc, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_enc, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax23) cax_1 = plt.bar([0, 1], [cm_enc[0, 1]/np.sum(x_test == 0), cm_enc[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig3, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## 4) Logistic regression with lasso # + fig4 = plt.figure() ax21 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax22 = plt.subplot2grid((2, 2), (0, 1)) ax23 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax21) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_lasso, tpr_lasso, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_lasso) plt.text(0.05, 0.85, 'Error = %.2f' % er_lasso) plt.title('Logistic regression with Lasso param. = %1.2e (test set)' % lambda_lasso) # Scores plt.sca(ax22) plt.hist(s_0_lasso, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_lasso, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax23) cax_1 = plt.bar([0, 1], [cm_lasso[0, 1]/np.sum(x_test == 0), cm_lasso[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig4, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## 5) CART classifier # + fig5 = plt.figure() ax1 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax1) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_tree, tpr_tree, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_tree) plt.text(0.05, 0.85, 'Error = %.2f' % er_tree) plt.title('CART classifier: max. depth of tree = %1i (test set)' % max_depth_tree) # Scores plt.sca(ax2) plt.hist(s_0_tree[~np.isinf(s_0_tree)], 80, density=True, alpha=0.7, color='r') plt.hist(s_1_tree[~np.isinf(s_1_tree)], 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax3) cax_1 = plt.bar([0, 1], [cm_tree[0, 1]/np.sum(x_test == 0), cm_tree[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig5, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## Decision regions # + fig6 = plt.figure() # Parameters n_classes = 2 plot_colors = "rb" plot_step = 0.2 k1 = -10 k2 = -12 z_k1_min = z_estimation[:, k1].min() z_k1_max = z_estimation[:, k1].max() z_k2_min = z_estimation[:, k2].min() z_k2_max = z_estimation[:, k2].max() zz_k1, zz_k2 = np.meshgrid(np.arange(z_k1_min, z_k1_max, plot_step), np.arange(z_k2_min, z_k2_max, plot_step)) tree_clf_plot = tree.DecisionTreeClassifier(max_depth=max_depth_tree, class_weight='balanced') p_plot = tree_clf_plot.fit(z_estimation[:, [k1, k2]], x_estimation).predict_proba(np.c_[zz_k1.ravel(), zz_k2.ravel()])[:, 1] p_plot = p_plot.reshape(zz_k1.shape) cs = plt.contourf(zz_k1, zz_k2, p_plot, cmap=plt.cm.RdYlBu) for i, color in zip(range(n_classes), plot_colors): idx = np.where(x_estimation == i) plt.scatter(z_estimation[idx, k1], z_estimation[idx, k2], c=color, label=['0', '1'][i], cmap=plt.cm.RdYlBu, edgecolor='black', s=15) plt.xlabel(list(df)[k1]) plt.ylabel(list(df)[k2]) plt.xlim([z_k1_min, z_k1_max]) plt.ylim([z_k2_min, z_k2_max]) plt.title('CART classifier decision regions') add_logo(fig6, alpha=0.8, location=3) plt.tight_layout() # - # ## 6) Gradient boosting classifier # + fig7 = plt.figure() ax1 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax1) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_boost, tpr_boost, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_tree) plt.text(0.05, 0.85, 'Error = %.2f' % er_tree) plt.title('CART classifier with gradient boosting (test set)') # Scores plt.sca(ax2) plt.hist(s_0_boost, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_boost, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax3) cax_1 = plt.bar([0, 1], [cm_boost[0, 1]/np.sum(x_test == 0), cm_boost[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig7, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## Decision regions # + fig8 = plt.figure() # Parameters n_classes = 2 plot_colors = "rb" plot_step = 0.2 k1 = -10 k2 = -12 z_k1_min = z_estimation[:, k1].min() z_k1_max = z_estimation[:, k1].max() z_k2_min = z_estimation[:, k2].min() z_k2_max = z_estimation[:, k2].max() zz_k1, zz_k2 = np.meshgrid(np.arange(z_k1_min, z_k1_max, plot_step), np.arange(z_k2_min, z_k2_max, plot_step)) boost_clf_plot = GradientBoostingClassifier() p_plot = boost_clf_plot.fit(z_estimation[:, [k1, k2]], x_estimation).predict_proba(np.c_[zz_k1.ravel(), zz_k2.ravel()])[:, 1] p_plot = p_plot.reshape(zz_k1.shape) cs = plt.contourf(zz_k1, zz_k2, p_plot, cmap=plt.cm.RdYlBu) for i, color in zip(range(n_classes), plot_colors): idx = np.where(x_estimation == i) plt.scatter(z_estimation[idx, k1], z_estimation[idx, k2], c=color, label=['0', '1'][i], cmap=plt.cm.RdYlBu, edgecolor='black', s=15) plt.xlabel(list(df)[k1]) plt.ylabel(list(df)[k2]) plt.xlim([z_k1_min, z_k1_max]) plt.ylim([z_k2_min, z_k2_max]) plt.title('CART classifier with gradient boosting decision regions') add_logo(fig8, alpha=0.8, location=3) plt.tight_layout()
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # s_default_probabilities [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_default_probabilities&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-supervised-machine-learning). # + import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.special import logit from sklearn.ensemble import GradientBoostingClassifier from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import OneHotEncoder, PolynomialFeatures, \ QuantileTransformer from sklearn import tree from sklearn.metrics import auc, roc_curve, confusion_matrix from sklearn.model_selection import StratifiedKFold, train_test_split from arpym.tools import add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-parameters) test_size = 0.2 # proportion of the test set n_sample = 10000 # num. of samples in the database; set =30000 to catch it all pol_degree = 2 # degrees in polynomial features lambda_lasso = 0.05 # lasso parameter max_depth_tree = 10 # maximum depth of decision tree classifier cross_val = 0 # set "1" to do cross-validation (computational time increases) k_ = 5 # parameter of Stratified K-Folds cross-validator # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step00): Import data and pre-process database # + # Import data path = '../../../databases/global-databases/credit/' + \ 'db_default_data_creditcardsclients/' df = pd.read_csv(path+'db_default_data_creditcardsclients.csv') df = df.iloc[:, 1:df.shape[1]] # exlude ID # Sort database so that the categorical features are at the beginning # indexes of the categorical features ind_cat = np.r_[np.arange(1, 4), np.arange(5, 11)] n_cat = len(ind_cat) # number of categorical features # indexes of the continuous features ind_cont = np.r_[np.array([0, 4]), np.arange(11, df.shape[1])] n_cont = len(ind_cont) # number of categorical features df = df.iloc[:n_sample, np.r_[ind_cat, ind_cont]] # Outputs and features z = np.array(df.iloc[:, :-1]) # features x = np.array(df.iloc[:, -1]) # labels # Standardize continuous features quantile_transformer = QuantileTransformer(output_distribution='normal') z_cont = quantile_transformer.fit_transform(z[:, -n_cont:]) # Transform categorical features via one-hot encoding # shift up, because the OneHotEncoder takes only positive inputs enc = OneHotEncoder() z_cat = enc.fit_transform(np.abs(np.min(z[:, :n_cat], axis=0)) + z[:, :n_cat]).toarray() n_enc = z_cat.shape[1] # number of encoded categorical features z = np.concatenate((z_cat, z_cont), axis=1) # Define test set and estimation set z_estimation, z_test, x_estimation, x_test = train_test_split(z, x) # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step01): Logistic regression on continuous features # Set C = +infinity to have 0 Lasso parameter lg = LogisticRegression(penalty='l1', C=10**5, class_weight='balanced') lg = lg.fit(z_estimation[:, -n_cont:], x_estimation) # fit the model p_z_lg = lg.predict_proba(z_test[:, -n_cont:])[:, 1] # predict the probs cm_lg = confusion_matrix(x_test, lg.predict(z_test[:, -n_cont:])) # conf. mat. er_lg = -np.sum(np.log(p_z_lg)) # error print('Logistic error: %1.4f' % er_lg) # conditional scores s_0_lg = logit(lg.predict_proba(z_test[:, -n_cont:])[ np.where(x_test == 0)[0], 1]) s_1_lg = logit(lg.predict_proba(z_test[:, -n_cont:])[ np.where(x_test == 1)[0], 1]) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step02): Add interactions to logistic regression # + # Add interactions poly = PolynomialFeatures(degree=pol_degree) z_estimation_inter = poly.fit_transform(z_estimation[:, -n_cont:]) z_test_inter = poly.fit_transform(z_test[:, -n_cont:]) # Set C = +infinity to have 0 Lasso parameter lg_inter = LogisticRegression(penalty='l1', C=10**5, class_weight='balanced') lg_inter = lg_inter.fit(z_estimation_inter, x_estimation) # fit the model p_z_inter = lg_inter.predict_proba(z_test_inter)[:, 1] # pred. the probs. cm_inter = confusion_matrix(x_test, lg_inter.predict(z_test_inter)) er_inter = -np.sum(np.log(p_z_inter)) # error print('Logistic with interactions error: %1.4f' % er_inter) # conditional scores s_0_inter = logit(lg_inter.predict_proba(z_test_inter)[ np.where(x_test == 0)[0], 1]) s_1_inter = logit(lg_inter.predict_proba(z_test_inter)[ np.where(x_test == 1)[0], 1]) # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step03): Add encoded categorical features to logistic regression # + z_enc_estimation = np.concatenate((z_estimation[:, :n_enc], z_estimation_inter), axis=1) z_enc_test = np.concatenate((z_test[:, :n_enc], z_test_inter), axis=1) # Set C = +infinity to have 0 Lasso parameter lg_enc = LogisticRegression(penalty='l1', C=10**5, class_weight='balanced') lg_enc = lg_enc.fit(z_enc_estimation, x_estimation) # fit the model p_z_enc = lg_enc.predict_proba(z_enc_test)[:, 1] # pred. the probs. cm_enc = confusion_matrix(x_test, lg_enc.predict(z_enc_test)) er_enc = -np.sum(np.log(p_z_enc)) # error print('Logistic with interactions and categorical error: %1.4f' % er_enc) # conditional scores s_0_enc = logit(lg_enc.predict_proba(z_enc_test)[np.where(x_test == 0)[0], 1]) s_1_enc = logit(lg_enc.predict_proba(z_enc_test)[np.where(x_test == 1)[0], 1]) # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step04): Add lasso regularization lg_lasso = LogisticRegression(penalty='l1', C=10**5, class_weight='balanced') lg_lasso = lg_lasso.fit(z_enc_estimation, x_estimation) # fit the model p_z_lasso = lg_lasso.predict_proba(z_enc_test)[:, 1] # predict the probs. cm_lasso = confusion_matrix(x_test, lg_lasso.predict(z_enc_test)) # conf. mat. er_lasso = -np.sum(np.log(p_z_lasso)) # error print('Logistic with lasso error: %1.4f' % er_lasso) # conditional scores s_0_lasso = logit(lg_lasso.predict_proba(z_enc_test)[ np.where(x_test == 0)[0], 1]) s_1_lasso = logit(lg_lasso.predict_proba(z_enc_test)[ np.where(x_test == 1)[0], 1]) # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step05): CART classifier tree_clf = tree.DecisionTreeClassifier(max_depth=max_depth_tree, class_weight='balanced') # def. method tree_clf = tree_clf.fit(z_enc_estimation, x_estimation) # fit the model p_z_tree = tree_clf.predict_proba(z_enc_test)[:, 1] # predict the scores cm_tree = confusion_matrix(x_test, tree_clf.predict(z_enc_test)) # conf. mat. er_tree = (cm_tree[0, 1]/np.sum(x_test == 0) + cm_tree[1, 0]/np.sum(x_test == 1)) # error print('CART classifier error: %1.4f' % er_tree) # conditional scores eps = 10**-5 # set threshold to avoid numerical noise in the logit function p_0_tree = tree_clf.predict_proba(z_enc_test)[np.where(x_test == 0)[0], 1] p_0_tree[p_0_tree < eps] = eps p_0_tree[p_0_tree > 1-eps] = 1-eps p_1_tree = tree_clf.predict_proba(z_enc_test)[np.where(x_test == 1)[0], 1] p_1_tree[p_1_tree < eps] = eps p_1_tree[p_1_tree > 1-eps] = 1-eps s_0_tree = logit(p_0_tree) s_1_tree = logit(p_1_tree) # ## [Step 6](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step06): Add gradient boosting to CART classifier boost_clf = GradientBoostingClassifier(max_depth=max_depth_tree) # method boost_clf = boost_clf.fit(z_enc_estimation, x_estimation) # fit the model p_z_boost = boost_clf.predict_proba(z_enc_test)[:, 1] # predict the probs. cm_boost = confusion_matrix(x_test, boost_clf.predict(z_enc_test)) # conf. mat er_boost = (cm_boost[0, 1]/np.sum(x_test == 0) + cm_boost[1, 0]/np.sum(x_test == 1)) # error print('CART classifier with gradient boosting error: %1.4f' % er_boost) # conditional scores s_0_boost = logit(boost_clf.predict_proba(z_enc_test)[ np.where(x_test == 0)[0], 1]) s_1_boost = logit(boost_clf.predict_proba(z_enc_test)[ np.where(x_test == 1)[0], 1]) # ## [Step 7](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step07): Compute fpr, tpr and AUC on the test set # + # 1) Logistic fpr_lg, tpr_lg, _ = roc_curve(x_test, p_z_lg) auc_lg = auc(fpr_lg, tpr_lg) print('Logistic AUC: %1.3f' % auc_lg) # 2) Logistic with interactions fpr_inter, tpr_inter, _ = roc_curve(x_test, p_z_inter) auc_inter = auc(fpr_inter, tpr_inter) print('Logistic with interactions AUC: %1.3f' % auc_inter) # 3) Logistic with interactions and encoded categorical features fpr_enc, tpr_enc, _ = roc_curve(x_test, p_z_enc) auc_enc = auc(fpr_enc, tpr_enc) print('Logistic with interactions and categorical AUC: %1.3f' % auc_enc) # 4) Logistic lasso with interactions and encoded categorical features fpr_lasso, tpr_lasso, _ = roc_curve(x_test, p_z_lasso) auc_lasso = auc(fpr_lasso, tpr_lasso) print('Logistic with lasso AUC: %1.3f' % auc_lasso) # 5) CART classifier fpr_tree, tpr_tree, _ = roc_curve(x_test, p_z_tree) auc_tree = auc(fpr_tree, tpr_tree) print('CART classifier AUC: %1.3f' % auc_tree) # 6) Gradient boosting classifier fpr_boost, tpr_boost, _ = roc_curve(x_test, p_z_boost) auc_boost = auc(fpr_boost, tpr_boost) print('Gradient boosting classifier AUC: %1.3f' % auc_boost) # - # ## [Step 8](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step08): Choose best probabilistic and point predictors via cross-validation if cross_val == 1: # Split the estimation set into training and validation sets for k-fold # cross-validation k_fold = StratifiedKFold(n_splits=k_) z_train = [] z_train_inter = [] z_train_enc = [] x_train = [] z_val = [] z_val_inter = [] z_val_enc = [] x_val = [] for train, val in k_fold.split(z_estimation, x_estimation): z_train.append(z_estimation[train]) x_train.append(x_estimation[train]) z_val.append(z_estimation[val]) x_val.append(x_estimation[val]) for train, val in k_fold.split(z_estimation_inter, x_estimation): z_train_inter.append(z_estimation_inter[train]) z_val_inter.append(z_estimation_inter[val]) for train, val in k_fold.split(z_enc_estimation, x_estimation): z_train_enc.append(z_enc_estimation[train]) z_val_enc.append(z_enc_estimation[val]) # Probabilistic cv_er_lg = [] cv_er_lasso = [] cv_er_inter = [] cv_er_enc = [] for k in range(k_): # Logistic p_cv_lg = lg.fit(z_train[k], x_train[k]).predict_proba(z_val[k]) cv_er_lg.append(-np.sum(np.log(p_cv_lg))) # Lasso p_cv_lasso = lg_lasso.fit(z_train[k], x_train[k]).predict_proba(z_val[k]) cv_er_lasso.append(-np.sum(np.log(p_cv_lasso))) # Interactions p_cv_inter = lg_inter.fit(z_train_inter[k], x_train[k]).predict_proba(z_val_inter[k]) cv_er_inter.append(-np.sum(np.log(p_cv_inter))) # Encoded categorical p_cv_enc = lg_inter.fit(z_train_enc[k], x_train[k]).predict_proba(z_val_enc[k]) cv_er_enc.append(-np.sum(np.log(p_cv_enc))) cv_er_lg = np.mean(cv_er_lg) cv_er_lasso = np.mean(cv_er_lasso) cv_er_inter = np.mean(cv_er_inter) cv_er_enc = np.mean(cv_er_enc) # Point cv_er_tree = [] cv_er_boost = [] for k in range(k_): # Tree cm_tree_cv =\ confusion_matrix(x_val[k], tree_clf.fit(z_train[k], x_train[k]).predict(z_val[k])) er_tree_cv = (cm_tree_cv[0, 1]/np.sum(x_val[k] == 0) + cm_tree_cv[1, 0]/np.sum(x_val[k] == 1)) # error cv_er_tree.append(er_tree_cv) # Gradient boosting cm_boost_cv =\ confusion_matrix(x_val[k], boost_clf.fit(z_train[k], x_train[k]).predict(z_val[k])) er_boost_cv = (cm_boost_cv[0, 1]/np.sum(x_val[k] == 0) + cm_boost_cv[1, 0]/np.sum(x_val[k] == 1)) # error cv_er_boost.append(er_boost_cv) cv_er_tree = np.mean(cv_er_tree) cv_er_boost = np.mean(cv_er_boost) print('Logistic CV error: %1.3f' % cv_er_lg) print('Logistic with interactions CV error: %1.3f' % cv_er_inter) print('Logistic with interactions and categorical CV error: %1.3f' % cv_er_enc) print('Logistic with lasso CV error: %1.3f' % cv_er_lasso) print('CART classifier CV error: %1.3f' % cv_er_tree) print('CART classifier with gradient boosting CV error: %1.3f' % cv_er_boost) # ## Plots plt.style.use('arpm') # ## 1) Logistic regression # + fig1 = plt.figure() ax11 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax12 = plt.subplot2grid((2, 2), (0, 1)) ax13 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax11) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_lg, tpr_lg, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_lg) plt.text(0.05, 0.85, 'Error = %.2f' % er_lg) plt.title('Logistic regression (test set)') # Scores plt.sca(ax12) plt.hist(s_0_lg, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_lg, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax13) cax_1 = plt.bar([0, 1], [cm_lg[0, 1]/np.sum(x_test == 0), cm_lg[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig1, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## 2) Logistic regression with interactions # + fig2 = plt.figure() ax31 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax32 = plt.subplot2grid((2, 2), (0, 1)) ax33 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax31) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_inter, tpr_inter, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_inter) plt.text(0.05, 0.85, 'Error = %.2f' % er_inter) plt.title('Logistic regression with interactions deg. = %1i (test set)' % pol_degree) # Scores plt.sca(ax32) plt.hist(s_0_inter, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_inter, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax33) cax_1 = plt.bar([0, 1], [cm_inter[0, 1]/np.sum(x_test == 0), cm_inter[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig2, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## 3) Logistic regression with interactions and encoded categorical features # + fig3 = plt.figure() ax21 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax22 = plt.subplot2grid((2, 2), (0, 1)) ax23 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax21) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_enc, tpr_enc, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_enc) plt.text(0.05, 0.85, 'Error = %.2f' % er_enc) plt.title('Logistic regression with interactions and categorical features') # Scores plt.sca(ax22) plt.hist(s_0_enc, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_enc, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax23) cax_1 = plt.bar([0, 1], [cm_enc[0, 1]/np.sum(x_test == 0), cm_enc[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig3, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## 4) Logistic regression with lasso # + fig4 = plt.figure() ax21 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax22 = plt.subplot2grid((2, 2), (0, 1)) ax23 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax21) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_lasso, tpr_lasso, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_lasso) plt.text(0.05, 0.85, 'Error = %.2f' % er_lasso) plt.title('Logistic regression with Lasso param. = %1.2e (test set)' % lambda_lasso) # Scores plt.sca(ax22) plt.hist(s_0_lasso, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_lasso, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax23) cax_1 = plt.bar([0, 1], [cm_lasso[0, 1]/np.sum(x_test == 0), cm_lasso[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig4, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## 5) CART classifier # + fig5 = plt.figure() ax1 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax1) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_tree, tpr_tree, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_tree) plt.text(0.05, 0.85, 'Error = %.2f' % er_tree) plt.title('CART classifier: max. depth of tree = %1i (test set)' % max_depth_tree) # Scores plt.sca(ax2) plt.hist(s_0_tree[~np.isinf(s_0_tree)], 80, density=True, alpha=0.7, color='r') plt.hist(s_1_tree[~np.isinf(s_1_tree)], 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax3) cax_1 = plt.bar([0, 1], [cm_tree[0, 1]/np.sum(x_test == 0), cm_tree[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig5, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## Decision regions # + fig6 = plt.figure() # Parameters n_classes = 2 plot_colors = "rb" plot_step = 0.2 k1 = -10 k2 = -12 z_k1_min = z_estimation[:, k1].min() z_k1_max = z_estimation[:, k1].max() z_k2_min = z_estimation[:, k2].min() z_k2_max = z_estimation[:, k2].max() zz_k1, zz_k2 = np.meshgrid(np.arange(z_k1_min, z_k1_max, plot_step), np.arange(z_k2_min, z_k2_max, plot_step)) tree_clf_plot = tree.DecisionTreeClassifier(max_depth=max_depth_tree, class_weight='balanced') p_plot = tree_clf_plot.fit(z_estimation[:, [k1, k2]], x_estimation).predict_proba(np.c_[zz_k1.ravel(), zz_k2.ravel()])[:, 1] p_plot = p_plot.reshape(zz_k1.shape) cs = plt.contourf(zz_k1, zz_k2, p_plot, cmap=plt.cm.RdYlBu) for i, color in zip(range(n_classes), plot_colors): idx = np.where(x_estimation == i) plt.scatter(z_estimation[idx, k1], z_estimation[idx, k2], c=color, label=['0', '1'][i], cmap=plt.cm.RdYlBu, edgecolor='black', s=15) plt.xlabel(list(df)[k1]) plt.ylabel(list(df)[k2]) plt.xlim([z_k1_min, z_k1_max]) plt.ylim([z_k2_min, z_k2_max]) plt.title('CART classifier decision regions') add_logo(fig6, alpha=0.8, location=3) plt.tight_layout() # - # ## 6) Gradient boosting classifier # + fig7 = plt.figure() ax1 = plt.subplot2grid((2, 2), (0, 0), rowspan=2) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 1)) # out of sample ROC curve plt.sca(ax1) plt.plot([0, 1], [0, 1], 'k--', lw=1) plt.plot([0, 0, 1], [0, 1, 1], 'g') plt.plot(fpr_boost, tpr_boost, 'b') plt.xlim([-0.01, 1.01]) plt.ylim([-0.01, 1.01]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(['Random fit', 'Perfect fit', 'ROC curve']) plt.text(0.05, 0.8, 'AUC = %.2f' % auc_tree) plt.text(0.05, 0.85, 'Error = %.2f' % er_tree) plt.title('CART classifier with gradient boosting (test set)') # Scores plt.sca(ax2) plt.hist(s_0_boost, 80, density=True, alpha=0.7, color='r') plt.hist(s_1_boost, 80, density=True, alpha=0.7, color='b') plt.legend(['S | 0', 'S | 1']) plt.title('Scores distribution') # Confusion matrix plt.sca(ax3) cax_1 = plt.bar([0, 1], [cm_boost[0, 1]/np.sum(x_test == 0), cm_boost[1, 0]/np.sum(x_test == 1)]) plt.ylim([0, 1.1]) plt.xticks([0, 1], ('$fpr$', '$fnr$')) plt.title('Confusion matrix') add_logo(fig7, location=1, size_frac_x=1/8) plt.tight_layout() # - # ## Decision regions # + fig8 = plt.figure() # Parameters n_classes = 2 plot_colors = "rb" plot_step = 0.2 k1 = -10 k2 = -12 z_k1_min = z_estimation[:, k1].min() z_k1_max = z_estimation[:, k1].max() z_k2_min = z_estimation[:, k2].min() z_k2_max = z_estimation[:, k2].max() zz_k1, zz_k2 = np.meshgrid(np.arange(z_k1_min, z_k1_max, plot_step), np.arange(z_k2_min, z_k2_max, plot_step)) boost_clf_plot = GradientBoostingClassifier() p_plot = boost_clf_plot.fit(z_estimation[:, [k1, k2]], x_estimation).predict_proba(np.c_[zz_k1.ravel(), zz_k2.ravel()])[:, 1] p_plot = p_plot.reshape(zz_k1.shape) cs = plt.contourf(zz_k1, zz_k2, p_plot, cmap=plt.cm.RdYlBu) for i, color in zip(range(n_classes), plot_colors): idx = np.where(x_estimation == i) plt.scatter(z_estimation[idx, k1], z_estimation[idx, k2], c=color, label=['0', '1'][i], cmap=plt.cm.RdYlBu, edgecolor='black', s=15) plt.xlabel(list(df)[k1]) plt.ylabel(list(df)[k2]) plt.xlim([z_k1_min, z_k1_max]) plt.ylim([z_k2_min, z_k2_max]) plt.title('CART classifier with gradient boosting decision regions') add_logo(fig8, alpha=0.8, location=3) plt.tight_layout()
en
0.615117
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # s_default_probabilities [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_default_probabilities&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-supervised-machine-learning). # + # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-parameters) # proportion of the test set # num. of samples in the database; set =30000 to catch it all # degrees in polynomial features # lasso parameter # maximum depth of decision tree classifier # set "1" to do cross-validation (computational time increases) # parameter of Stratified K-Folds cross-validator # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step00): Import data and pre-process database # + # Import data # exlude ID # Sort database so that the categorical features are at the beginning # indexes of the categorical features # number of categorical features # indexes of the continuous features # number of categorical features # Outputs and features # features # labels # Standardize continuous features # Transform categorical features via one-hot encoding # shift up, because the OneHotEncoder takes only positive inputs # number of encoded categorical features # Define test set and estimation set # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step01): Logistic regression on continuous features # Set C = +infinity to have 0 Lasso parameter # fit the model # predict the probs # conf. mat. # error # conditional scores # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step02): Add interactions to logistic regression # + # Add interactions # Set C = +infinity to have 0 Lasso parameter # fit the model # pred. the probs. # error # conditional scores # - # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step03): Add encoded categorical features to logistic regression # + # Set C = +infinity to have 0 Lasso parameter # fit the model # pred. the probs. # error # conditional scores # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step04): Add lasso regularization # fit the model # predict the probs. # conf. mat. # error # conditional scores # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step05): CART classifier # def. method # fit the model # predict the scores # conf. mat. # error # conditional scores # set threshold to avoid numerical noise in the logit function # ## [Step 6](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step06): Add gradient boosting to CART classifier # method # fit the model # predict the probs. # conf. mat # error # conditional scores # ## [Step 7](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step07): Compute fpr, tpr and AUC on the test set # + # 1) Logistic # 2) Logistic with interactions # 3) Logistic with interactions and encoded categorical features # 4) Logistic lasso with interactions and encoded categorical features # 5) CART classifier # 6) Gradient boosting classifier # - # ## [Step 8](https://www.arpm.co/lab/redirect.php?permalink=s_default_probabilities-implementation-step08): Choose best probabilistic and point predictors via cross-validation # Split the estimation set into training and validation sets for k-fold # cross-validation # Probabilistic # Logistic # Lasso # Interactions # Encoded categorical # Point # Tree # error # Gradient boosting # error # ## Plots # ## 1) Logistic regression # + # out of sample ROC curve # Scores # Confusion matrix # - # ## 2) Logistic regression with interactions # + # out of sample ROC curve # Scores # Confusion matrix # - # ## 3) Logistic regression with interactions and encoded categorical features # + # out of sample ROC curve # Scores # Confusion matrix # - # ## 4) Logistic regression with lasso # + # out of sample ROC curve # Scores # Confusion matrix # - # ## 5) CART classifier # + # out of sample ROC curve # Scores # Confusion matrix # - # ## Decision regions # + # Parameters # - # ## 6) Gradient boosting classifier # + # out of sample ROC curve # Scores # Confusion matrix # - # ## Decision regions # + # Parameters
2.391799
2
tools/pvacfuse/net_chop.py
atwollam/pVACtools
0
6624321
<reponame>atwollam/pVACtools<gh_stars>0 import sys from lib.net_chop import * def define_parser(): return NetChop.parser('pvacfuse') def main(args_input = sys.argv[1:]): parser = define_parser() args = parser.parse_args(args_input) NetChop(args.input_file, args.input_fasta, args.output_file, args.method, args.threshold, 'pVACfuse').execute() if __name__ == "__main__": main()
import sys from lib.net_chop import * def define_parser(): return NetChop.parser('pvacfuse') def main(args_input = sys.argv[1:]): parser = define_parser() args = parser.parse_args(args_input) NetChop(args.input_file, args.input_fasta, args.output_file, args.method, args.threshold, 'pVACfuse').execute() if __name__ == "__main__": main()
none
1
2.665367
3
learning.py
dan840611/Python
0
6624322
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 4 20:55:11 2017 @author: Dan """ import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt ''' y = np.random.standard_normal(20) y2 = y * 100 plt.plot(y.cumsum(), 'b', lw = 1.5, label='1st') plt.plot(y.cumsum(), 'ro') plt.plot(y, 'r', label = '2nd') #參數: tight 所影數據可見;[xmin, xmax, ymin, ymax] plt.axis('tight') plt.xlabel('index') plt.ylabel('value') plt.title('Practice') # 0 為最佳位置 plt.legend(loc=0) #雙座標軸 ax1 = plt.subplots() plt.plot(y.cumsum(), 'b', label = '1st') plt.plot(y.cumsum(), 'ro') plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.legend(loc=0) plt.grid(True) ax2 = ax1.twinx() plt.plot(y2, 'r', label = '2st') plt.legend(loc = 0) plt.ylabel('2nd y ') #多圖 plt.subplot(211) #121 plt.plot(y.cumsum(), 'b', label = '1st') plt.plot(y.cumsum(), 'ro') plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.legend(loc=0) plt.grid(True) plt.subplot(212) #122 plt.plot(y2, 'r', label = '2st') plt.legend(loc = 0) plt.ylabel('2nd y ') ''' ''' ############################## #scatter y = np.random.standard_normal((1000, 2)) c = np.random.randint(0 , 10, len(y)) plt.scatter(y[:, 0], y[:, 1] , c = c, marker = 'o') plt.colorbar() plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.title('test') plt.legend(loc=0) plt.grid(True) #histogram plt.hist(y, label= ['1st', '2nd'], bins = 25) plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.title('test') plt.legend(loc=0) plt.grid(True) #boxplot plt.boxplot(y) plt.grid(True) plt.setp(ax, xticklabels = ['1st', '2nd']) plt.xlabel('dataset') plt.ylabel('valur') plt.title('Boxplot') ''' #finance plot import matplotlib.finance as mpf start = (2010, 1, 1) end = (2017, 9, 22) quotes = mpf.quotes_historical_yahoo_ochl('^GDAXI', start, end)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 4 20:55:11 2017 @author: Dan """ import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt ''' y = np.random.standard_normal(20) y2 = y * 100 plt.plot(y.cumsum(), 'b', lw = 1.5, label='1st') plt.plot(y.cumsum(), 'ro') plt.plot(y, 'r', label = '2nd') #參數: tight 所影數據可見;[xmin, xmax, ymin, ymax] plt.axis('tight') plt.xlabel('index') plt.ylabel('value') plt.title('Practice') # 0 為最佳位置 plt.legend(loc=0) #雙座標軸 ax1 = plt.subplots() plt.plot(y.cumsum(), 'b', label = '1st') plt.plot(y.cumsum(), 'ro') plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.legend(loc=0) plt.grid(True) ax2 = ax1.twinx() plt.plot(y2, 'r', label = '2st') plt.legend(loc = 0) plt.ylabel('2nd y ') #多圖 plt.subplot(211) #121 plt.plot(y.cumsum(), 'b', label = '1st') plt.plot(y.cumsum(), 'ro') plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.legend(loc=0) plt.grid(True) plt.subplot(212) #122 plt.plot(y2, 'r', label = '2st') plt.legend(loc = 0) plt.ylabel('2nd y ') ''' ''' ############################## #scatter y = np.random.standard_normal((1000, 2)) c = np.random.randint(0 , 10, len(y)) plt.scatter(y[:, 0], y[:, 1] , c = c, marker = 'o') plt.colorbar() plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.title('test') plt.legend(loc=0) plt.grid(True) #histogram plt.hist(y, label= ['1st', '2nd'], bins = 25) plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.title('test') plt.legend(loc=0) plt.grid(True) #boxplot plt.boxplot(y) plt.grid(True) plt.setp(ax, xticklabels = ['1st', '2nd']) plt.xlabel('dataset') plt.ylabel('valur') plt.title('Boxplot') ''' #finance plot import matplotlib.finance as mpf start = (2010, 1, 1) end = (2017, 9, 22) quotes = mpf.quotes_historical_yahoo_ochl('^GDAXI', start, end)
zh
0.069251
#!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Mon Sep 4 20:55:11 2017 @author: Dan y = np.random.standard_normal(20) y2 = y * 100 plt.plot(y.cumsum(), 'b', lw = 1.5, label='1st') plt.plot(y.cumsum(), 'ro') plt.plot(y, 'r', label = '2nd') #參數: tight 所影數據可見;[xmin, xmax, ymin, ymax] plt.axis('tight') plt.xlabel('index') plt.ylabel('value') plt.title('Practice') # 0 為最佳位置 plt.legend(loc=0) #雙座標軸 ax1 = plt.subplots() plt.plot(y.cumsum(), 'b', label = '1st') plt.plot(y.cumsum(), 'ro') plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.legend(loc=0) plt.grid(True) ax2 = ax1.twinx() plt.plot(y2, 'r', label = '2st') plt.legend(loc = 0) plt.ylabel('2nd y ') #多圖 plt.subplot(211) #121 plt.plot(y.cumsum(), 'b', label = '1st') plt.plot(y.cumsum(), 'ro') plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.legend(loc=0) plt.grid(True) plt.subplot(212) #122 plt.plot(y2, 'r', label = '2st') plt.legend(loc = 0) plt.ylabel('2nd y ') ############################## #scatter y = np.random.standard_normal((1000, 2)) c = np.random.randint(0 , 10, len(y)) plt.scatter(y[:, 0], y[:, 1] , c = c, marker = 'o') plt.colorbar() plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.title('test') plt.legend(loc=0) plt.grid(True) #histogram plt.hist(y, label= ['1st', '2nd'], bins = 25) plt.xlabel('x') plt.ylabel('y') plt.axis('tight') plt.title('test') plt.legend(loc=0) plt.grid(True) #boxplot plt.boxplot(y) plt.grid(True) plt.setp(ax, xticklabels = ['1st', '2nd']) plt.xlabel('dataset') plt.ylabel('valur') plt.title('Boxplot') #finance plot
3.08585
3
texts/objects/cache/sqlite_ner_cache.py
nicolay-r/frame-based-attitude-extraction-workflow
0
6624323
from itertools import chain from os.path import join from core.processing.lemmatization.base import Stemmer from core.processing.ner.base import NamedEntityRecognition from core.processing.ner.obj_decs import NerObjectDescriptor from texts.extraction.text_parser import terms_utils from texts.objects.cache.sqlite_base import BaseSQLiteObjectCache from texts.readers.utils import NewsInfo class SQLiteNERCacheData(BaseSQLiteObjectCache): """ NOTE: There is a bug in deep_pavlov == 0.11.0 -- returns an invalid data for other elements in batch (>1). With deep_ner it is OK, so the size might be increased which is positively affects on the processing performance """ # region static fields BATCH_SIZE = 1 CREATE_TABLE_IF_NOT_EXISTS_SQLITE_CMD = """ CREATE TABLE IF NOT EXISTS {table} ( filename TEXT, sentence_ind INTEGER, ner_data TEXT, PRIMARY KEY (filename, sentence_ind)) """ INSERT_RECORD_SQLITE_CMD = "INSERT INTO {table} VALUES ('{filename}', {s_ind}, '{ner_data}')" SELECT_BY_SENTENCE_IND = "SELECT ner_data from {table} where sentence_ind=?" # endregion def __init__(self, stemmer, ner, db_filepath): assert(isinstance(stemmer, Stemmer) or stemmer is None) assert(isinstance(ner, NamedEntityRecognition) or ner is None) super(SQLiteNERCacheData, self).__init__(db_filepath=db_filepath) print("NER cache: {}".format(db_filepath)) self.__ner = ner self.__stemmer = None if ner is not None: self.__stemmer = stemmer if ner.NeedLemmatization else None # region class methods @classmethod def init_for_rw(cls, stemmer, ner, folder): db_filepath = SQLiteNERCacheData.__create_db_name(ner_name=str(ner), folder=folder) return cls(stemmer=stemmer, ner=ner, db_filepath=db_filepath) @classmethod def init_as_read_only(cls, filepath): return cls(stemmer=None, ner=None, db_filepath=filepath) # endregion # region public methods @staticmethod def get_table_name(): return "cache" def register_news(self, news_info, is_valid_title_by_ner_types=None): assert(isinstance(news_info, NewsInfo)) assert(callable(is_valid_title_by_ner_types) or is_valid_title_by_ner_types is None) filename = news_info.FileName # Skipping existed news. if self._is_news_exists_in_cache(filename): return batches_it = self.__iter_sentences_grouped_in_batches( news_info=news_info, reject_by_non_valid_title=True) check_title_func = is_valid_title_by_ner_types \ if is_valid_title_by_ner_types is not None else \ lambda types: True for s_inds, s_input_terms in batches_it: accepted = self.__register_sentences(filename=filename, input_sequences=s_input_terms, s_inds=s_inds, is_valid_title_by_ner_types=check_title_func) if not accepted: break # Commiting results into database. self._conn.commit() # endregion # region private methods @staticmethod def __create_db_name(ner_name, folder): return join(folder, "ner_cache_{ner_name}.db".format(ner_name=ner_name)) def __iter_sentences_grouped_in_batches(self, news_info, reject_by_non_valid_title): assert(isinstance(news_info, NewsInfo)) assert(isinstance(reject_by_non_valid_title, bool)) b_inds, b_sentences = [], [] def need_release(): return len(b_inds) > 0 it_contents = chain([news_info.Title], news_info.iter_sentences()) for s_ind, sentence in enumerate(it_contents): assert(isinstance(sentence, str)) actual_ind = s_ind - 1 if len(b_inds) == self.BATCH_SIZE: # release. yield b_inds, b_sentences b_inds, b_sentences = [], [] s_input_terms = terms_utils.to_input_terms( text=sentence, stemmer=self.__stemmer, ner=self.__ner, return_parsed_text=False) if self.__is_valid_input(s_input_terms): # add in list. b_inds.append(actual_ind) b_sentences.append(s_input_terms) elif self.__is_title(actual_ind) and reject_by_non_valid_title: break # release residual part if exists. if need_release(): yield b_inds, b_sentences def __is_title(self, s_ind): return s_ind == self.TITLE_SENT_IND def __serialize_ner_data(self, ner_objs_data): assert(isinstance(ner_objs_data, list)) objects = [] for obj_desc in ner_objs_data: assert(isinstance(obj_desc, NerObjectDescriptor)) s_obj = self.PARAMS_SEP.join([str(obj_desc.Position), str(obj_desc.Length), obj_desc.ObjectType]) objects.append(s_obj) return self.ENTRY_SEP.join(objects) def __register_sentences(self, filename, input_sequences, s_inds, is_valid_title_by_ner_types): assert(len(input_sequences) > 0) assert(callable(is_valid_title_by_ner_types)) ner_data = self.__ner.extract(input_sequences, return_single=False) first_obj_desc = ner_data[0] assert(isinstance(first_obj_desc, NerObjectDescriptor)) # checking title by ner types appeared in it if s_inds[0] == self.TITLE_SENT_IND and not is_valid_title_by_ner_types(first_obj_desc.ObjectType): return False # composing requests. for seq_ind in range(len(input_sequences)): request = self.INSERT_RECORD_SQLITE_CMD.format( table=self.get_table_name(), filename=filename, s_ind=s_inds[seq_ind], ner_data=self.__serialize_ner_data(ner_data)) self._cursor.execute(request) return True def __is_valid_input(self, input_sequence): return self.__ner.InputLimitation > len(input_sequence) > 0 # endregion # region protected methods def _deserialize_item(self, data_item): assert (isinstance(data_item, str)) pos, length, obj_type = data_item.split(BaseSQLiteObjectCache.PARAMS_SEP) return NerObjectDescriptor(pos=int(pos), length=int(length), obj_type=obj_type) # endregion def __enter__(self): super(SQLiteNERCacheData, self).__enter__() self._cursor.execute(self.CREATE_TABLE_IF_NOT_EXISTS_SQLITE_CMD.format(table=self.get_table_name()))
from itertools import chain from os.path import join from core.processing.lemmatization.base import Stemmer from core.processing.ner.base import NamedEntityRecognition from core.processing.ner.obj_decs import NerObjectDescriptor from texts.extraction.text_parser import terms_utils from texts.objects.cache.sqlite_base import BaseSQLiteObjectCache from texts.readers.utils import NewsInfo class SQLiteNERCacheData(BaseSQLiteObjectCache): """ NOTE: There is a bug in deep_pavlov == 0.11.0 -- returns an invalid data for other elements in batch (>1). With deep_ner it is OK, so the size might be increased which is positively affects on the processing performance """ # region static fields BATCH_SIZE = 1 CREATE_TABLE_IF_NOT_EXISTS_SQLITE_CMD = """ CREATE TABLE IF NOT EXISTS {table} ( filename TEXT, sentence_ind INTEGER, ner_data TEXT, PRIMARY KEY (filename, sentence_ind)) """ INSERT_RECORD_SQLITE_CMD = "INSERT INTO {table} VALUES ('{filename}', {s_ind}, '{ner_data}')" SELECT_BY_SENTENCE_IND = "SELECT ner_data from {table} where sentence_ind=?" # endregion def __init__(self, stemmer, ner, db_filepath): assert(isinstance(stemmer, Stemmer) or stemmer is None) assert(isinstance(ner, NamedEntityRecognition) or ner is None) super(SQLiteNERCacheData, self).__init__(db_filepath=db_filepath) print("NER cache: {}".format(db_filepath)) self.__ner = ner self.__stemmer = None if ner is not None: self.__stemmer = stemmer if ner.NeedLemmatization else None # region class methods @classmethod def init_for_rw(cls, stemmer, ner, folder): db_filepath = SQLiteNERCacheData.__create_db_name(ner_name=str(ner), folder=folder) return cls(stemmer=stemmer, ner=ner, db_filepath=db_filepath) @classmethod def init_as_read_only(cls, filepath): return cls(stemmer=None, ner=None, db_filepath=filepath) # endregion # region public methods @staticmethod def get_table_name(): return "cache" def register_news(self, news_info, is_valid_title_by_ner_types=None): assert(isinstance(news_info, NewsInfo)) assert(callable(is_valid_title_by_ner_types) or is_valid_title_by_ner_types is None) filename = news_info.FileName # Skipping existed news. if self._is_news_exists_in_cache(filename): return batches_it = self.__iter_sentences_grouped_in_batches( news_info=news_info, reject_by_non_valid_title=True) check_title_func = is_valid_title_by_ner_types \ if is_valid_title_by_ner_types is not None else \ lambda types: True for s_inds, s_input_terms in batches_it: accepted = self.__register_sentences(filename=filename, input_sequences=s_input_terms, s_inds=s_inds, is_valid_title_by_ner_types=check_title_func) if not accepted: break # Commiting results into database. self._conn.commit() # endregion # region private methods @staticmethod def __create_db_name(ner_name, folder): return join(folder, "ner_cache_{ner_name}.db".format(ner_name=ner_name)) def __iter_sentences_grouped_in_batches(self, news_info, reject_by_non_valid_title): assert(isinstance(news_info, NewsInfo)) assert(isinstance(reject_by_non_valid_title, bool)) b_inds, b_sentences = [], [] def need_release(): return len(b_inds) > 0 it_contents = chain([news_info.Title], news_info.iter_sentences()) for s_ind, sentence in enumerate(it_contents): assert(isinstance(sentence, str)) actual_ind = s_ind - 1 if len(b_inds) == self.BATCH_SIZE: # release. yield b_inds, b_sentences b_inds, b_sentences = [], [] s_input_terms = terms_utils.to_input_terms( text=sentence, stemmer=self.__stemmer, ner=self.__ner, return_parsed_text=False) if self.__is_valid_input(s_input_terms): # add in list. b_inds.append(actual_ind) b_sentences.append(s_input_terms) elif self.__is_title(actual_ind) and reject_by_non_valid_title: break # release residual part if exists. if need_release(): yield b_inds, b_sentences def __is_title(self, s_ind): return s_ind == self.TITLE_SENT_IND def __serialize_ner_data(self, ner_objs_data): assert(isinstance(ner_objs_data, list)) objects = [] for obj_desc in ner_objs_data: assert(isinstance(obj_desc, NerObjectDescriptor)) s_obj = self.PARAMS_SEP.join([str(obj_desc.Position), str(obj_desc.Length), obj_desc.ObjectType]) objects.append(s_obj) return self.ENTRY_SEP.join(objects) def __register_sentences(self, filename, input_sequences, s_inds, is_valid_title_by_ner_types): assert(len(input_sequences) > 0) assert(callable(is_valid_title_by_ner_types)) ner_data = self.__ner.extract(input_sequences, return_single=False) first_obj_desc = ner_data[0] assert(isinstance(first_obj_desc, NerObjectDescriptor)) # checking title by ner types appeared in it if s_inds[0] == self.TITLE_SENT_IND and not is_valid_title_by_ner_types(first_obj_desc.ObjectType): return False # composing requests. for seq_ind in range(len(input_sequences)): request = self.INSERT_RECORD_SQLITE_CMD.format( table=self.get_table_name(), filename=filename, s_ind=s_inds[seq_ind], ner_data=self.__serialize_ner_data(ner_data)) self._cursor.execute(request) return True def __is_valid_input(self, input_sequence): return self.__ner.InputLimitation > len(input_sequence) > 0 # endregion # region protected methods def _deserialize_item(self, data_item): assert (isinstance(data_item, str)) pos, length, obj_type = data_item.split(BaseSQLiteObjectCache.PARAMS_SEP) return NerObjectDescriptor(pos=int(pos), length=int(length), obj_type=obj_type) # endregion def __enter__(self): super(SQLiteNERCacheData, self).__enter__() self._cursor.execute(self.CREATE_TABLE_IF_NOT_EXISTS_SQLITE_CMD.format(table=self.get_table_name()))
en
0.768165
NOTE: There is a bug in deep_pavlov == 0.11.0 -- returns an invalid data for other elements in batch (>1). With deep_ner it is OK, so the size might be increased which is positively affects on the processing performance # region static fields CREATE TABLE IF NOT EXISTS {table} ( filename TEXT, sentence_ind INTEGER, ner_data TEXT, PRIMARY KEY (filename, sentence_ind)) # endregion # region class methods # endregion # region public methods # Skipping existed news. # Commiting results into database. # endregion # region private methods # release. # add in list. # release residual part if exists. # checking title by ner types appeared in it # composing requests. # endregion # region protected methods # endregion
2.183004
2
chatty_back/partners/views.py
always-awake/chatty_back
0
6624324
<reponame>always-awake/chatty_back<gh_stars>0 from django.utils.decorators import method_decorator from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . import models, serializers from chatty_back.diary.views import check_user def get_partner(self, partner_id, creator): try: found_partner = models.Partner.objects.get(id=partner_id, creator=creator) return found_partner except models.Partner.DoesNotExist: return None class Partner(APIView): @method_decorator(check_user()) def post(self, request, user, format=None): new_partner_name = request.data.get('name', None) try: found_partner = models.Partner.objects.get(name=new_partner_name, creator=user) except models.Partner.DoesNotExist: serializer = serializers.CreatePartnerSerializer(data=request.data, partial=True) if serializer.is_valid(): new_partner = serializer.save(creator=user) #파트너가 생성된 후, 직전에 생성된 파트너를 함께 일기 쓸 파트너로 선택하기 user.partner = new_partner user.save() print(user.partner.name) return Response(data=serializer.data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PartnerProfile(APIView): @method_decorator(check_user()) def get(self, request, user, partner_id, format=None): found_partner = get_partner(self, partner_id, user) if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = serializers.PartnerProfileSerializer(found_partner) return Response(data=serializer.data, status=status.HTTP_200_OK) @method_decorator(check_user()) def put(self, request, user, partner_id, format=None): found_partner = get_partner(self, partner_id, user) if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = serializers.PartnerProfileSerializer( found_partner, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=status.HTTP_200_OK) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) class DeletePartner(APIView): @method_decorator(check_user()) def delete(self, request, user, partner_id, format=None): found_partner = get_partner(self, partner_id, user) if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: found_partner.delete() return Response(status=status.HTTP_204_NO_CONTENT) class SetPartner(APIView): @method_decorator(check_user()) def put(self, request, user, partner_id, format=None): found_partner = get_partner(self, partner_id, user) if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: user.partner = found_partner user.save() return Response(status=status.HTTP_200_OK) # Main 화면에 있는 Partner 부분(Main 화면의 module화를 위한 API) class Partner_Main(APIView): @method_decorator(check_user()) def get(self, request, user, format=None): found_partner = user.partner if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = serializers.MainPartnerSerializer(found_partner) return Response(data=serializer.data, status=status.HTTP_200_OK) class PartnerProfile_setting(APIView): @method_decorator(check_user()) def get(self, request, user, format=None): found_partner = user.partner if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = serializers.PartnerProfileSerializer(found_partner) return Response(data=serializer.data, status=status.HTTP_200_OK)
from django.utils.decorators import method_decorator from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . import models, serializers from chatty_back.diary.views import check_user def get_partner(self, partner_id, creator): try: found_partner = models.Partner.objects.get(id=partner_id, creator=creator) return found_partner except models.Partner.DoesNotExist: return None class Partner(APIView): @method_decorator(check_user()) def post(self, request, user, format=None): new_partner_name = request.data.get('name', None) try: found_partner = models.Partner.objects.get(name=new_partner_name, creator=user) except models.Partner.DoesNotExist: serializer = serializers.CreatePartnerSerializer(data=request.data, partial=True) if serializer.is_valid(): new_partner = serializer.save(creator=user) #파트너가 생성된 후, 직전에 생성된 파트너를 함께 일기 쓸 파트너로 선택하기 user.partner = new_partner user.save() print(user.partner.name) return Response(data=serializer.data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PartnerProfile(APIView): @method_decorator(check_user()) def get(self, request, user, partner_id, format=None): found_partner = get_partner(self, partner_id, user) if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = serializers.PartnerProfileSerializer(found_partner) return Response(data=serializer.data, status=status.HTTP_200_OK) @method_decorator(check_user()) def put(self, request, user, partner_id, format=None): found_partner = get_partner(self, partner_id, user) if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = serializers.PartnerProfileSerializer( found_partner, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=status.HTTP_200_OK) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) class DeletePartner(APIView): @method_decorator(check_user()) def delete(self, request, user, partner_id, format=None): found_partner = get_partner(self, partner_id, user) if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: found_partner.delete() return Response(status=status.HTTP_204_NO_CONTENT) class SetPartner(APIView): @method_decorator(check_user()) def put(self, request, user, partner_id, format=None): found_partner = get_partner(self, partner_id, user) if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: user.partner = found_partner user.save() return Response(status=status.HTTP_200_OK) # Main 화면에 있는 Partner 부분(Main 화면의 module화를 위한 API) class Partner_Main(APIView): @method_decorator(check_user()) def get(self, request, user, format=None): found_partner = user.partner if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = serializers.MainPartnerSerializer(found_partner) return Response(data=serializer.data, status=status.HTTP_200_OK) class PartnerProfile_setting(APIView): @method_decorator(check_user()) def get(self, request, user, format=None): found_partner = user.partner if found_partner is None: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = serializers.PartnerProfileSerializer(found_partner) return Response(data=serializer.data, status=status.HTTP_200_OK)
ko
0.999671
#파트너가 생성된 후, 직전에 생성된 파트너를 함께 일기 쓸 파트너로 선택하기 # Main 화면에 있는 Partner 부분(Main 화면의 module화를 위한 API)
2.313189
2
alsek/core/message.py
TariqAHassan/alsek
1
6624325
""" Message """ from __future__ import annotations from copy import deepcopy from typing import Any, Dict, Iterable, List, Optional, Tuple, Union from uuid import uuid1 from alsek._defaults import DEFAULT_MECHANISM, DEFAULT_QUEUE, DEFAULT_TASK_TIMEOUT from alsek._utils.printing import auto_repr from alsek._utils.temporal import fromtimestamp_ms, utcnow_timestamp_ms from alsek.core.backoff import ExponentialBackoff, settings2backoff from alsek.core.concurrency import Lock def _make_uuid() -> str: return str(uuid1()) def _collect_callback_uuids(callback_message_data: Dict[str, Any]) -> Iterable[str]: yield callback_message_data["uuid"] if callback_message_data["callback_message_data"]: yield from _collect_callback_uuids( callback_message_data["callback_message_data"] ) class Message: """Alsek Message. Args: task_name (str): the name of the task for which the message is intended queue (str, optional): the queue for which the message was intended. If ``None`` the default queue will be set. args (list, tuple, optional): positional arguments to pass to the task's function during the execution of ``op()`` kwargs (dict, optional): keyword arguments to pass to the task's function during the execution of ``op()`` metadata (dict, optional): a dictionary of user-defined message metadata. This can store any data types supported by the backend's serializer. result_ttl (int, optional): time to live (in milliseconds) for the result in the result store. If a result store is provided and this parameter is ``None``, the result will be persisted indefinitely. uuid (str, optional): universal unique identifier for the message. If ``None``, one will be generated automatically. progenitor_uuid (str, optional): universal unique identifier for the message from which this message descended. (This field is only set in for tasks with triggers and/or callbacks.) retries (int): number of retries timeout (int): the maximum amount of time (in milliseconds) a task is permitted to run against this message. created_at (int): UTC timestamp (in milliseconds) for when the message was created updated_at (int): UTC timestamp (in milliseconds) for when the message was last updated delay (int): delay before the message becomes ready previous_result (any, optional): the output of any previously executed task. (This will only be non-null in cases where callbacks are used.) previous_message_uuid (str, optional): universal unique identifier for the message for the preceeding message (This will only be non-null in cases where callbacks are used.) callback_message_data (dict, optional): data to construct a new message as part of a callback operation backoff_settings (dict, optional): parameters to control backoff. Expected to be of the form ``{"algorithm": str, "parameters": dict}``. mechanism (str): mechanism for executing the task. Must be either "process" or "thread". Notes: * While *not* recommended, ``timeout`` can be disabled, in effect, by setting it to a very large integer. """ def __init__( self, task_name: str, queue: Optional[str] = None, args: Optional[Union[List[Any], Tuple[Any, ...]]] = None, kwargs: Optional[Dict[Any, Any]] = None, metadata: Optional[Dict[Any, Any]] = None, result_ttl: Optional[int] = None, uuid: Optional[str] = None, progenitor_uuid: Optional[str] = None, retries: int = 0, timeout: int = DEFAULT_TASK_TIMEOUT, created_at: Optional[int] = None, updated_at: Optional[int] = None, delay: Optional[int] = None, previous_result: Optional[Any] = None, previous_message_uuid: Optional[str] = None, callback_message_data: Optional[Dict[str, Any]] = None, backoff_settings: Optional[Dict[str, int]] = None, mechanism: str = DEFAULT_MECHANISM, ) -> None: self.task_name = task_name self.queue = queue or DEFAULT_QUEUE self.args = tuple(args) if args else tuple() self.kwargs = kwargs or dict() self.metadata = metadata self.result_ttl = result_ttl self.retries = retries self.timeout = timeout self.uuid = uuid or _make_uuid() self.progenitor_uuid = progenitor_uuid self.delay = delay or 0 self.previous_result = previous_result self.previous_message_uuid = previous_message_uuid self.callback_message_data = callback_message_data self.backoff_settings = backoff_settings or ExponentialBackoff().settings self.mechanism = mechanism if created_at is None and updated_at is None: self.created_at = self.updated_at = utcnow_timestamp_ms() elif created_at is None or updated_at is None: raise ValueError("Time data is corrupt") else: self.created_at, self.updated_at = created_at, updated_at self._lock: Optional[str] = None @property def data(self) -> Dict[str, Any]: """Underlying message data.""" return dict( task_name=self.task_name, queue=self.queue, args=self.args, kwargs=self.kwargs, metadata=self.metadata, result_ttl=self.result_ttl, uuid=self.uuid, progenitor_uuid=self.progenitor_uuid, retries=self.retries, timeout=self.timeout, created_at=self.created_at, updated_at=self.updated_at, delay=self.delay, previous_result=self.previous_result, previous_message_uuid=self.previous_message_uuid, callback_message_data=self.callback_message_data, backoff_settings=self.backoff_settings, mechanism=self.mechanism, ) def __repr__(self) -> str: params = self.data for k in ("created_at", "updated_at"): params[k] = fromtimestamp_ms(params[k]) return auto_repr(self, **params) @property def summary(self) -> str: """High-level summary of the message object.""" return auto_repr( self, new_line_threshold=None, uuid=self.uuid, queue=self.queue, task=self.task_name, ) def get_backoff_duration(self) -> int: """Get the amount of time to backoff (wait) before the message is eligible for processing again, should it fail. Returns: duration (int): duration of the backoff in milliseconds """ return settings2backoff(self.backoff_settings).get(self.retries) @property def ready_at(self) -> int: """Timestamp denoting when the message will be ready for processing.""" return self.created_at + self.delay + self.get_backoff_duration() @property def ready(self) -> bool: """If the messages is currently ready for processing.""" return self.ready_at <= utcnow_timestamp_ms() @property def ttr(self) -> int: """Time to ready in milliseconds.""" if self.ready: return 0 return max(self.ready_at - utcnow_timestamp_ms(), 0) @property def descendant_uuids(self) -> Optional[List[str]]: """A list of uuids which have or will decent from this message.""" if self.callback_message_data: return list(_collect_callback_uuids(self.callback_message_data)) else: return None def _link_lock(self, lock: Lock, override: bool = False) -> Message: """Link a lock to the current message. Links are formed against the ``long_name`` of ``lock``. Args: lock (Lock): a concurrency lock override (bool): if ``True`` replace any existing lock Returns: message (Message): the updated message Warning: * Locks links are formed in memory and are never persisted to the data backend. """ if self._lock and not override: raise AttributeError(f"Already linked to '{self._lock}'") else: self._lock = lock.long_name return self def _unlink_lock(self, missing_ok: bool = False) -> Optional[str]: """Clear the lock linked to the message. Args: missing_ok (bool): if ``True`` do not raise if no lock is found Returns: lock (str, optional): the name of the lock which was cleared Raises: AttributeError: if no lock is associated with the message and ``missing_ok`` is not ``True``. """ if self._lock: lock = self._lock self._lock = None return lock elif missing_ok: return None else: raise AttributeError("No lock linked to message") def clone(self) -> Message: """Create an exact copy of the current message. Returns: clone (Message): the cloned message """ return Message(**deepcopy(self.data)) def update(self, **data: Any) -> Message: """Update the ``data`` in the current message. Args: **data (Keyword Args): key value pairs of data to update Returns: updated_message (Message): the updated message Warning: * This method operates 'in place'. To avoid changing the current message, first call ``.clone()``, e.g., ``message.clone().update(...)``. * Changes are *not* automatically persisted to the backend. """ for k, v in data.items(): if k in self.data: setattr(self, k, v) else: raise KeyError(f"Unsupported key '{k}'") return self def duplicate(self, uuid: Optional[str] = None) -> Message: """Create a duplicate of the current message, changing only ``uuid``. Args: uuid (str, optional): universal unique identifier for the new message. If ``None``, one will be generated automatically. Returns: duplicate_message (Message): the duplicate message Warning: * Linked locks are not conserved """ return self.clone().update(uuid=uuid or _make_uuid()) def increment(self) -> Message: """Update a message by increasing the number of retries. Returns: message (Message): the updated message Notes: * ``updated_at`` will be updated to the current time. Warning: * Changes are *not* automatically persisted to the backend. """ return self.update(retries=self.retries + 1, updated_at=utcnow_timestamp_ms())
""" Message """ from __future__ import annotations from copy import deepcopy from typing import Any, Dict, Iterable, List, Optional, Tuple, Union from uuid import uuid1 from alsek._defaults import DEFAULT_MECHANISM, DEFAULT_QUEUE, DEFAULT_TASK_TIMEOUT from alsek._utils.printing import auto_repr from alsek._utils.temporal import fromtimestamp_ms, utcnow_timestamp_ms from alsek.core.backoff import ExponentialBackoff, settings2backoff from alsek.core.concurrency import Lock def _make_uuid() -> str: return str(uuid1()) def _collect_callback_uuids(callback_message_data: Dict[str, Any]) -> Iterable[str]: yield callback_message_data["uuid"] if callback_message_data["callback_message_data"]: yield from _collect_callback_uuids( callback_message_data["callback_message_data"] ) class Message: """Alsek Message. Args: task_name (str): the name of the task for which the message is intended queue (str, optional): the queue for which the message was intended. If ``None`` the default queue will be set. args (list, tuple, optional): positional arguments to pass to the task's function during the execution of ``op()`` kwargs (dict, optional): keyword arguments to pass to the task's function during the execution of ``op()`` metadata (dict, optional): a dictionary of user-defined message metadata. This can store any data types supported by the backend's serializer. result_ttl (int, optional): time to live (in milliseconds) for the result in the result store. If a result store is provided and this parameter is ``None``, the result will be persisted indefinitely. uuid (str, optional): universal unique identifier for the message. If ``None``, one will be generated automatically. progenitor_uuid (str, optional): universal unique identifier for the message from which this message descended. (This field is only set in for tasks with triggers and/or callbacks.) retries (int): number of retries timeout (int): the maximum amount of time (in milliseconds) a task is permitted to run against this message. created_at (int): UTC timestamp (in milliseconds) for when the message was created updated_at (int): UTC timestamp (in milliseconds) for when the message was last updated delay (int): delay before the message becomes ready previous_result (any, optional): the output of any previously executed task. (This will only be non-null in cases where callbacks are used.) previous_message_uuid (str, optional): universal unique identifier for the message for the preceeding message (This will only be non-null in cases where callbacks are used.) callback_message_data (dict, optional): data to construct a new message as part of a callback operation backoff_settings (dict, optional): parameters to control backoff. Expected to be of the form ``{"algorithm": str, "parameters": dict}``. mechanism (str): mechanism for executing the task. Must be either "process" or "thread". Notes: * While *not* recommended, ``timeout`` can be disabled, in effect, by setting it to a very large integer. """ def __init__( self, task_name: str, queue: Optional[str] = None, args: Optional[Union[List[Any], Tuple[Any, ...]]] = None, kwargs: Optional[Dict[Any, Any]] = None, metadata: Optional[Dict[Any, Any]] = None, result_ttl: Optional[int] = None, uuid: Optional[str] = None, progenitor_uuid: Optional[str] = None, retries: int = 0, timeout: int = DEFAULT_TASK_TIMEOUT, created_at: Optional[int] = None, updated_at: Optional[int] = None, delay: Optional[int] = None, previous_result: Optional[Any] = None, previous_message_uuid: Optional[str] = None, callback_message_data: Optional[Dict[str, Any]] = None, backoff_settings: Optional[Dict[str, int]] = None, mechanism: str = DEFAULT_MECHANISM, ) -> None: self.task_name = task_name self.queue = queue or DEFAULT_QUEUE self.args = tuple(args) if args else tuple() self.kwargs = kwargs or dict() self.metadata = metadata self.result_ttl = result_ttl self.retries = retries self.timeout = timeout self.uuid = uuid or _make_uuid() self.progenitor_uuid = progenitor_uuid self.delay = delay or 0 self.previous_result = previous_result self.previous_message_uuid = previous_message_uuid self.callback_message_data = callback_message_data self.backoff_settings = backoff_settings or ExponentialBackoff().settings self.mechanism = mechanism if created_at is None and updated_at is None: self.created_at = self.updated_at = utcnow_timestamp_ms() elif created_at is None or updated_at is None: raise ValueError("Time data is corrupt") else: self.created_at, self.updated_at = created_at, updated_at self._lock: Optional[str] = None @property def data(self) -> Dict[str, Any]: """Underlying message data.""" return dict( task_name=self.task_name, queue=self.queue, args=self.args, kwargs=self.kwargs, metadata=self.metadata, result_ttl=self.result_ttl, uuid=self.uuid, progenitor_uuid=self.progenitor_uuid, retries=self.retries, timeout=self.timeout, created_at=self.created_at, updated_at=self.updated_at, delay=self.delay, previous_result=self.previous_result, previous_message_uuid=self.previous_message_uuid, callback_message_data=self.callback_message_data, backoff_settings=self.backoff_settings, mechanism=self.mechanism, ) def __repr__(self) -> str: params = self.data for k in ("created_at", "updated_at"): params[k] = fromtimestamp_ms(params[k]) return auto_repr(self, **params) @property def summary(self) -> str: """High-level summary of the message object.""" return auto_repr( self, new_line_threshold=None, uuid=self.uuid, queue=self.queue, task=self.task_name, ) def get_backoff_duration(self) -> int: """Get the amount of time to backoff (wait) before the message is eligible for processing again, should it fail. Returns: duration (int): duration of the backoff in milliseconds """ return settings2backoff(self.backoff_settings).get(self.retries) @property def ready_at(self) -> int: """Timestamp denoting when the message will be ready for processing.""" return self.created_at + self.delay + self.get_backoff_duration() @property def ready(self) -> bool: """If the messages is currently ready for processing.""" return self.ready_at <= utcnow_timestamp_ms() @property def ttr(self) -> int: """Time to ready in milliseconds.""" if self.ready: return 0 return max(self.ready_at - utcnow_timestamp_ms(), 0) @property def descendant_uuids(self) -> Optional[List[str]]: """A list of uuids which have or will decent from this message.""" if self.callback_message_data: return list(_collect_callback_uuids(self.callback_message_data)) else: return None def _link_lock(self, lock: Lock, override: bool = False) -> Message: """Link a lock to the current message. Links are formed against the ``long_name`` of ``lock``. Args: lock (Lock): a concurrency lock override (bool): if ``True`` replace any existing lock Returns: message (Message): the updated message Warning: * Locks links are formed in memory and are never persisted to the data backend. """ if self._lock and not override: raise AttributeError(f"Already linked to '{self._lock}'") else: self._lock = lock.long_name return self def _unlink_lock(self, missing_ok: bool = False) -> Optional[str]: """Clear the lock linked to the message. Args: missing_ok (bool): if ``True`` do not raise if no lock is found Returns: lock (str, optional): the name of the lock which was cleared Raises: AttributeError: if no lock is associated with the message and ``missing_ok`` is not ``True``. """ if self._lock: lock = self._lock self._lock = None return lock elif missing_ok: return None else: raise AttributeError("No lock linked to message") def clone(self) -> Message: """Create an exact copy of the current message. Returns: clone (Message): the cloned message """ return Message(**deepcopy(self.data)) def update(self, **data: Any) -> Message: """Update the ``data`` in the current message. Args: **data (Keyword Args): key value pairs of data to update Returns: updated_message (Message): the updated message Warning: * This method operates 'in place'. To avoid changing the current message, first call ``.clone()``, e.g., ``message.clone().update(...)``. * Changes are *not* automatically persisted to the backend. """ for k, v in data.items(): if k in self.data: setattr(self, k, v) else: raise KeyError(f"Unsupported key '{k}'") return self def duplicate(self, uuid: Optional[str] = None) -> Message: """Create a duplicate of the current message, changing only ``uuid``. Args: uuid (str, optional): universal unique identifier for the new message. If ``None``, one will be generated automatically. Returns: duplicate_message (Message): the duplicate message Warning: * Linked locks are not conserved """ return self.clone().update(uuid=uuid or _make_uuid()) def increment(self) -> Message: """Update a message by increasing the number of retries. Returns: message (Message): the updated message Notes: * ``updated_at`` will be updated to the current time. Warning: * Changes are *not* automatically persisted to the backend. """ return self.update(retries=self.retries + 1, updated_at=utcnow_timestamp_ms())
en
0.753568
Message Alsek Message. Args: task_name (str): the name of the task for which the message is intended queue (str, optional): the queue for which the message was intended. If ``None`` the default queue will be set. args (list, tuple, optional): positional arguments to pass to the task's function during the execution of ``op()`` kwargs (dict, optional): keyword arguments to pass to the task's function during the execution of ``op()`` metadata (dict, optional): a dictionary of user-defined message metadata. This can store any data types supported by the backend's serializer. result_ttl (int, optional): time to live (in milliseconds) for the result in the result store. If a result store is provided and this parameter is ``None``, the result will be persisted indefinitely. uuid (str, optional): universal unique identifier for the message. If ``None``, one will be generated automatically. progenitor_uuid (str, optional): universal unique identifier for the message from which this message descended. (This field is only set in for tasks with triggers and/or callbacks.) retries (int): number of retries timeout (int): the maximum amount of time (in milliseconds) a task is permitted to run against this message. created_at (int): UTC timestamp (in milliseconds) for when the message was created updated_at (int): UTC timestamp (in milliseconds) for when the message was last updated delay (int): delay before the message becomes ready previous_result (any, optional): the output of any previously executed task. (This will only be non-null in cases where callbacks are used.) previous_message_uuid (str, optional): universal unique identifier for the message for the preceeding message (This will only be non-null in cases where callbacks are used.) callback_message_data (dict, optional): data to construct a new message as part of a callback operation backoff_settings (dict, optional): parameters to control backoff. Expected to be of the form ``{"algorithm": str, "parameters": dict}``. mechanism (str): mechanism for executing the task. Must be either "process" or "thread". Notes: * While *not* recommended, ``timeout`` can be disabled, in effect, by setting it to a very large integer. Underlying message data. High-level summary of the message object. Get the amount of time to backoff (wait) before the message is eligible for processing again, should it fail. Returns: duration (int): duration of the backoff in milliseconds Timestamp denoting when the message will be ready for processing. If the messages is currently ready for processing. Time to ready in milliseconds. A list of uuids which have or will decent from this message. Link a lock to the current message. Links are formed against the ``long_name`` of ``lock``. Args: lock (Lock): a concurrency lock override (bool): if ``True`` replace any existing lock Returns: message (Message): the updated message Warning: * Locks links are formed in memory and are never persisted to the data backend. Clear the lock linked to the message. Args: missing_ok (bool): if ``True`` do not raise if no lock is found Returns: lock (str, optional): the name of the lock which was cleared Raises: AttributeError: if no lock is associated with the message and ``missing_ok`` is not ``True``. Create an exact copy of the current message. Returns: clone (Message): the cloned message Update the ``data`` in the current message. Args: **data (Keyword Args): key value pairs of data to update Returns: updated_message (Message): the updated message Warning: * This method operates 'in place'. To avoid changing the current message, first call ``.clone()``, e.g., ``message.clone().update(...)``. * Changes are *not* automatically persisted to the backend. Create a duplicate of the current message, changing only ``uuid``. Args: uuid (str, optional): universal unique identifier for the new message. If ``None``, one will be generated automatically. Returns: duplicate_message (Message): the duplicate message Warning: * Linked locks are not conserved Update a message by increasing the number of retries. Returns: message (Message): the updated message Notes: * ``updated_at`` will be updated to the current time. Warning: * Changes are *not* automatically persisted to the backend.
2.314607
2
tests/callbacks/test_finetuning_callback.py
caillonantoine/pytorch-lightning
0
6624326
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import OrderedDict import pytest import torch from torch import nn from torch.optim import Optimizer, SGD from torch.utils.data import DataLoader from pytorch_lightning import LightningModule, seed_everything, Trainer from pytorch_lightning.callbacks import BackboneFinetuning, BaseFinetuning, ModelCheckpoint from tests.helpers import BoringModel, RandomDataset class TestBackboneFinetuningCallback(BackboneFinetuning): def on_train_epoch_start(self, trainer, pl_module): super().on_train_epoch_start(trainer, pl_module) epoch = trainer.current_epoch if self.unfreeze_backbone_at_epoch <= epoch: optimizer = trainer.optimizers[0] current_lr = optimizer.param_groups[0]["lr"] backbone_lr = self.previous_backbone_lr if epoch < 6: assert backbone_lr <= current_lr else: assert backbone_lr == current_lr def test_finetuning_callback(tmpdir): """Test finetuning callbacks works as expected.""" seed_everything(42) class FinetuningBoringModel(BoringModel): def __init__(self): super().__init__() self.backbone = nn.Sequential(nn.Linear(32, 32, bias=False), nn.BatchNorm1d(32), nn.ReLU()) self.layer = torch.nn.Linear(32, 2) self.backbone.has_been_used = False def training_step(self, batch, batch_idx): output = self(batch) loss = self.loss(batch, output) return {"loss": loss} def forward(self, x): self.backbone.has_been_used = True x = self.backbone(x) return self.layer(x) def configure_optimizers(self): optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.7) return [optimizer], [lr_scheduler] def train_dataloader(self): return DataLoader(RandomDataset(32, 64), batch_size=2) model = FinetuningBoringModel() callback = TestBackboneFinetuningCallback(unfreeze_backbone_at_epoch=3, verbose=False) trainer = Trainer(limit_train_batches=4, default_root_dir=tmpdir, callbacks=[callback], max_epochs=8) trainer.fit(model) assert model.backbone.has_been_used class TestBackboneFinetuningWarningCallback(BackboneFinetuning): def finetune_function(self, pl_module, epoch: int, optimizer, opt_idx: int): """Called when the epoch begins.""" if epoch == 0: self.unfreeze_and_add_param_group( pl_module.backbone, optimizer, 0.1, train_bn=self.train_bn, initial_denom_lr=self.initial_denom_lr ) def test_finetuning_callback_warning(tmpdir): """Test finetuning callbacks works as expected.""" seed_everything(42) class FinetuningBoringModel(BoringModel): def __init__(self): super().__init__() self.backbone = nn.Linear(32, 2, bias=False) self.layer = None self.backbone.has_been_used = False def training_step(self, batch, batch_idx): output = self(batch) loss = self.loss(batch, output) return {"loss": loss} def forward(self, x): self.backbone.has_been_used = True x = self.backbone(x) return x def train_dataloader(self): return DataLoader(RandomDataset(32, 64), batch_size=2) def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), lr=0.1) return optimizer chk = ModelCheckpoint(dirpath=tmpdir, save_last=True) model = FinetuningBoringModel() model.validation_step = None callback = TestBackboneFinetuningWarningCallback(unfreeze_backbone_at_epoch=3, verbose=False) with pytest.warns(UserWarning, match="Did you init your optimizer in"): trainer = Trainer(limit_train_batches=1, default_root_dir=tmpdir, callbacks=[callback, chk], max_epochs=2) trainer.fit(model) assert model.backbone.has_been_used trainer = Trainer(max_epochs=3) trainer.fit(model, ckpt_path=chk.last_model_path) def test_freeze_unfreeze_function(tmpdir): """Test freeze properly sets requires_grad on the modules.""" seed_everything(42) class FreezeModel(LightningModule): def __init__(self): super().__init__() self.backbone = nn.Sequential(nn.Linear(32, 32), nn.BatchNorm1d(32), nn.ReLU(), nn.Linear(32, 2)) model = FreezeModel() BaseFinetuning.freeze(model, train_bn=True) assert not model.backbone[0].weight.requires_grad assert model.backbone[1].weight.requires_grad assert not model.backbone[3].weight.requires_grad BaseFinetuning.freeze(model, train_bn=False) assert not model.backbone[0].weight.requires_grad assert not model.backbone[1].weight.requires_grad assert not model.backbone[3].weight.requires_grad BaseFinetuning.make_trainable(model) assert model.backbone[0].weight.requires_grad assert model.backbone[1].weight.requires_grad assert model.backbone[3].weight.requires_grad BaseFinetuning.freeze(model.backbone[0], train_bn=False) assert not model.backbone[0].weight.requires_grad BaseFinetuning.freeze(([(model.backbone[1]), [model.backbone[3]]]), train_bn=True) assert model.backbone[1].weight.requires_grad assert not model.backbone[3].weight.requires_grad def test_unfreeze_and_add_param_group_function(tmpdir): """Test unfreeze_and_add_param_group properly unfreeze parameters and add to the correct param_group.""" seed_everything(42) class FreezeModel(LightningModule): def __init__(self): super().__init__() self.backbone = nn.Sequential( nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=False), nn.BatchNorm1d(32), ) model = FreezeModel() optimizer = SGD(model.backbone[0].parameters(), lr=0.01) with pytest.warns(UserWarning, match="The provided params to be frozen already"): BaseFinetuning.unfreeze_and_add_param_group(model.backbone[0], optimizer=optimizer) assert optimizer.param_groups[0]["lr"] == 0.01 model.backbone[1].weight.requires_grad = False BaseFinetuning.unfreeze_and_add_param_group(model.backbone[1], optimizer=optimizer) assert len(optimizer.param_groups) == 2 assert optimizer.param_groups[1]["lr"] == 0.001 assert torch.equal(optimizer.param_groups[1]["params"][0], model.backbone[1].weight) assert model.backbone[1].weight.requires_grad with pytest.warns(UserWarning, match="The provided params to be frozen already"): BaseFinetuning.unfreeze_and_add_param_group(model, optimizer=optimizer, lr=100, train_bn=False) assert len(optimizer.param_groups) == 3 assert optimizer.param_groups[2]["lr"] == 100 assert len(optimizer.param_groups[2]["params"]) == 3 for group_idx, group in enumerate(optimizer.param_groups): if group_idx == 0: assert torch.equal(optimizer.param_groups[0]["params"][0], model.backbone[0].weight) if group_idx == 2: assert torch.equal(optimizer.param_groups[2]["params"][0], model.backbone[2].weight) assert torch.equal(optimizer.param_groups[2]["params"][1], model.backbone[3].weight) assert torch.equal(optimizer.param_groups[2]["params"][2], model.backbone[4].weight) class OnEpochLayerFinetuning(BaseFinetuning): def freeze_before_training(self, pl_module: LightningModule): self.freeze(pl_module.layer) def finetune_function(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer, opt_idx: int): self.unfreeze_and_add_param_group(pl_module.layer[epoch + 1], optimizer) def test_base_finetuning_internal_optimizer_metadata(tmpdir): """Test the param_groups updates are properly saved within the internal state of the BaseFinetuning Callbacks.""" seed_everything(42) class FreezeModel(BoringModel): def __init__(self): super().__init__() self.layer = nn.Sequential( nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=True), nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=True), nn.Linear(32, 32, bias=False), nn.Linear(32, 2, bias=True), ) def forward(self, x): return self.layer(x) def configure_optimizers(self): return torch.optim.SGD(self.layer[0].parameters(), lr=0.1) cb = OnEpochLayerFinetuning() chk = ModelCheckpoint(dirpath=tmpdir, save_last=True) model = FreezeModel() trainer = Trainer(default_root_dir=tmpdir, max_epochs=5, limit_train_batches=1, callbacks=[cb, chk]) trainer.fit(model) assert len(cb._internal_optimizer_metadata[0]) == 6 assert cb._internal_optimizer_metadata[0][0]["params"] == ["layer.0.weight"] assert cb._internal_optimizer_metadata[0][1]["params"] == ["layer.1.weight", "layer.1.bias"] assert cb._internal_optimizer_metadata[0][2]["params"] == ["layer.2.weight"] assert cb._internal_optimizer_metadata[0][3]["params"] == ["layer.3.weight", "layer.3.bias"] assert cb._internal_optimizer_metadata[0][4]["params"] == ["layer.4.weight"] assert cb._internal_optimizer_metadata[0][5]["params"] == ["layer.5.weight", "layer.5.bias"] model = FreezeModel() cb = OnEpochLayerFinetuning() trainer = Trainer(max_epochs=10, callbacks=[cb]) with pytest.raises(IndexError, match="index 6 is out of range"): trainer.fit(model, ckpt_path=chk.last_model_path) class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.conv = nn.Conv2d(in_channels, out_channels, 3) self.act = nn.ReLU() self.bn = nn.BatchNorm2d(out_channels) def forward(self, x): x = self.conv(x) x = self.act(x) return self.bn(x) class ConvBlockParam(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.module_dict = nn.ModuleDict({"conv": nn.Conv2d(in_channels, out_channels, 3), "act": nn.ReLU()}) # add trivial test parameter to convblock to validate parent (non-leaf) module parameter handling self.parent_param = nn.Parameter(torch.zeros((1), dtype=torch.float)) self.bn = nn.BatchNorm2d(out_channels) def forward(self, x): x = self.module_dict["conv"](x) x = self.module_dict["act"](x) return self.bn(x) def test_complex_nested_model(): """Test flattening, freezing, and thawing of models which contain parent (non-leaf) modules with parameters directly themselves rather than exclusively their submodules containing parameters.""" model = nn.Sequential( OrderedDict( [("encoder", nn.Sequential(ConvBlockParam(3, 64), ConvBlock(64, 128))), ("decoder", ConvBlock(128, 10))] ) ) # There are 10 leaf modules or parent modules w/ parameters in the test model assert len(BaseFinetuning.flatten_modules(model)) == 10 BaseFinetuning.freeze(model.encoder, train_bn=True) assert not model.encoder[0].module_dict["conv"].weight.requires_grad # Validate a leaf module parameter is frozen assert not model.encoder[0].parent_param.requires_grad # Validate the parent module parameter is frozen assert model.encoder[0].bn.weight.requires_grad BaseFinetuning.make_trainable(model) encoder_params = list(BaseFinetuning.filter_params(model.encoder, train_bn=True)) # The 9 parameters of the encoder are: # conv0.weight, conv0.bias, bn0.weight, bn0.bias, parent_param # conv1.weight, conv1.bias, bn1.weight, bn1.bias assert len(encoder_params) == 9 class TestCallbacksRestoreCallback(BaseFinetuning): def freeze_before_training(self, pl_module): self.freeze(pl_module.layer[:3]) def finetune_function(self, pl_module, epoch, optimizer, opt_idx): if epoch >= 1: self.unfreeze_and_add_param_group(pl_module.layer[epoch - 1], optimizer) class FinetuningBoringModel(BoringModel): def __init__(self): super().__init__() self.layer = nn.Sequential(nn.Linear(32, 32), nn.Linear(32, 32), nn.Linear(32, 32), nn.Linear(32, 2)) def configure_optimizers(self): parameters = filter(lambda x: x.requires_grad, self.parameters()) optimizer = torch.optim.SGD(parameters, lr=0.1) return optimizer def test_callbacks_restore(tmpdir): """Test callbacks restore is called after optimizers have been re-created but before optimizer states reload.""" chk = ModelCheckpoint(dirpath=tmpdir, save_last=True) model = FinetuningBoringModel() callback = TestCallbacksRestoreCallback() trainer_kwargs = dict( default_root_dir=tmpdir, limit_train_batches=1, limit_val_batches=1, callbacks=[callback, chk], max_epochs=2 ) trainer = Trainer(**trainer_kwargs) trainer.fit(model) # only 1 optimizer assert len(callback._internal_optimizer_metadata) == 1 # only 2 param groups assert len(callback._internal_optimizer_metadata[0]) == 2 # original parameters assert callback._internal_optimizer_metadata[0][0] == { "lr": 0.1, "momentum": 0, "dampening": 0, "weight_decay": 0, "nesterov": False, "params": ["layer.3.weight", "layer.3.bias"], } # new param group assert callback._internal_optimizer_metadata[0][1] == { "lr": 0.01, "momentum": 0, "dampening": 0, "weight_decay": 0, "nesterov": False, "params": ["layer.0.weight", "layer.0.bias"], } trainer_kwargs["max_epochs"] = 3 trainer = Trainer(**trainer_kwargs) trainer.fit(model, ckpt_path=chk.last_model_path) def test_callbacks_restore_backbone(tmpdir): """Test callbacks restore is called after optimizers have been re-created but before optimizer states reload.""" class BackboneBoringModel(BoringModel): def __init__(self): super().__init__() self.layer = nn.Linear(32, 2) self.backbone = nn.Linear(32, 32) def forward(self, x): return self.layer(self.backbone(x)) ckpt = ModelCheckpoint(dirpath=tmpdir, save_last=True) trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=1, limit_val_batches=1, max_epochs=2, enable_progress_bar=False, callbacks=[ckpt, BackboneFinetuning(unfreeze_backbone_at_epoch=1)], ) trainer.fit(BackboneBoringModel()) # initialize a trainer that continues the previous training trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=1, limit_val_batches=1, max_epochs=3, enable_progress_bar=False, callbacks=BackboneFinetuning(unfreeze_backbone_at_epoch=1), ) trainer.fit(BackboneBoringModel(), ckpt_path=ckpt.last_model_path)
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import OrderedDict import pytest import torch from torch import nn from torch.optim import Optimizer, SGD from torch.utils.data import DataLoader from pytorch_lightning import LightningModule, seed_everything, Trainer from pytorch_lightning.callbacks import BackboneFinetuning, BaseFinetuning, ModelCheckpoint from tests.helpers import BoringModel, RandomDataset class TestBackboneFinetuningCallback(BackboneFinetuning): def on_train_epoch_start(self, trainer, pl_module): super().on_train_epoch_start(trainer, pl_module) epoch = trainer.current_epoch if self.unfreeze_backbone_at_epoch <= epoch: optimizer = trainer.optimizers[0] current_lr = optimizer.param_groups[0]["lr"] backbone_lr = self.previous_backbone_lr if epoch < 6: assert backbone_lr <= current_lr else: assert backbone_lr == current_lr def test_finetuning_callback(tmpdir): """Test finetuning callbacks works as expected.""" seed_everything(42) class FinetuningBoringModel(BoringModel): def __init__(self): super().__init__() self.backbone = nn.Sequential(nn.Linear(32, 32, bias=False), nn.BatchNorm1d(32), nn.ReLU()) self.layer = torch.nn.Linear(32, 2) self.backbone.has_been_used = False def training_step(self, batch, batch_idx): output = self(batch) loss = self.loss(batch, output) return {"loss": loss} def forward(self, x): self.backbone.has_been_used = True x = self.backbone(x) return self.layer(x) def configure_optimizers(self): optimizer = torch.optim.SGD(self.layer.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.7) return [optimizer], [lr_scheduler] def train_dataloader(self): return DataLoader(RandomDataset(32, 64), batch_size=2) model = FinetuningBoringModel() callback = TestBackboneFinetuningCallback(unfreeze_backbone_at_epoch=3, verbose=False) trainer = Trainer(limit_train_batches=4, default_root_dir=tmpdir, callbacks=[callback], max_epochs=8) trainer.fit(model) assert model.backbone.has_been_used class TestBackboneFinetuningWarningCallback(BackboneFinetuning): def finetune_function(self, pl_module, epoch: int, optimizer, opt_idx: int): """Called when the epoch begins.""" if epoch == 0: self.unfreeze_and_add_param_group( pl_module.backbone, optimizer, 0.1, train_bn=self.train_bn, initial_denom_lr=self.initial_denom_lr ) def test_finetuning_callback_warning(tmpdir): """Test finetuning callbacks works as expected.""" seed_everything(42) class FinetuningBoringModel(BoringModel): def __init__(self): super().__init__() self.backbone = nn.Linear(32, 2, bias=False) self.layer = None self.backbone.has_been_used = False def training_step(self, batch, batch_idx): output = self(batch) loss = self.loss(batch, output) return {"loss": loss} def forward(self, x): self.backbone.has_been_used = True x = self.backbone(x) return x def train_dataloader(self): return DataLoader(RandomDataset(32, 64), batch_size=2) def configure_optimizers(self): optimizer = torch.optim.SGD(self.parameters(), lr=0.1) return optimizer chk = ModelCheckpoint(dirpath=tmpdir, save_last=True) model = FinetuningBoringModel() model.validation_step = None callback = TestBackboneFinetuningWarningCallback(unfreeze_backbone_at_epoch=3, verbose=False) with pytest.warns(UserWarning, match="Did you init your optimizer in"): trainer = Trainer(limit_train_batches=1, default_root_dir=tmpdir, callbacks=[callback, chk], max_epochs=2) trainer.fit(model) assert model.backbone.has_been_used trainer = Trainer(max_epochs=3) trainer.fit(model, ckpt_path=chk.last_model_path) def test_freeze_unfreeze_function(tmpdir): """Test freeze properly sets requires_grad on the modules.""" seed_everything(42) class FreezeModel(LightningModule): def __init__(self): super().__init__() self.backbone = nn.Sequential(nn.Linear(32, 32), nn.BatchNorm1d(32), nn.ReLU(), nn.Linear(32, 2)) model = FreezeModel() BaseFinetuning.freeze(model, train_bn=True) assert not model.backbone[0].weight.requires_grad assert model.backbone[1].weight.requires_grad assert not model.backbone[3].weight.requires_grad BaseFinetuning.freeze(model, train_bn=False) assert not model.backbone[0].weight.requires_grad assert not model.backbone[1].weight.requires_grad assert not model.backbone[3].weight.requires_grad BaseFinetuning.make_trainable(model) assert model.backbone[0].weight.requires_grad assert model.backbone[1].weight.requires_grad assert model.backbone[3].weight.requires_grad BaseFinetuning.freeze(model.backbone[0], train_bn=False) assert not model.backbone[0].weight.requires_grad BaseFinetuning.freeze(([(model.backbone[1]), [model.backbone[3]]]), train_bn=True) assert model.backbone[1].weight.requires_grad assert not model.backbone[3].weight.requires_grad def test_unfreeze_and_add_param_group_function(tmpdir): """Test unfreeze_and_add_param_group properly unfreeze parameters and add to the correct param_group.""" seed_everything(42) class FreezeModel(LightningModule): def __init__(self): super().__init__() self.backbone = nn.Sequential( nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=False), nn.BatchNorm1d(32), ) model = FreezeModel() optimizer = SGD(model.backbone[0].parameters(), lr=0.01) with pytest.warns(UserWarning, match="The provided params to be frozen already"): BaseFinetuning.unfreeze_and_add_param_group(model.backbone[0], optimizer=optimizer) assert optimizer.param_groups[0]["lr"] == 0.01 model.backbone[1].weight.requires_grad = False BaseFinetuning.unfreeze_and_add_param_group(model.backbone[1], optimizer=optimizer) assert len(optimizer.param_groups) == 2 assert optimizer.param_groups[1]["lr"] == 0.001 assert torch.equal(optimizer.param_groups[1]["params"][0], model.backbone[1].weight) assert model.backbone[1].weight.requires_grad with pytest.warns(UserWarning, match="The provided params to be frozen already"): BaseFinetuning.unfreeze_and_add_param_group(model, optimizer=optimizer, lr=100, train_bn=False) assert len(optimizer.param_groups) == 3 assert optimizer.param_groups[2]["lr"] == 100 assert len(optimizer.param_groups[2]["params"]) == 3 for group_idx, group in enumerate(optimizer.param_groups): if group_idx == 0: assert torch.equal(optimizer.param_groups[0]["params"][0], model.backbone[0].weight) if group_idx == 2: assert torch.equal(optimizer.param_groups[2]["params"][0], model.backbone[2].weight) assert torch.equal(optimizer.param_groups[2]["params"][1], model.backbone[3].weight) assert torch.equal(optimizer.param_groups[2]["params"][2], model.backbone[4].weight) class OnEpochLayerFinetuning(BaseFinetuning): def freeze_before_training(self, pl_module: LightningModule): self.freeze(pl_module.layer) def finetune_function(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer, opt_idx: int): self.unfreeze_and_add_param_group(pl_module.layer[epoch + 1], optimizer) def test_base_finetuning_internal_optimizer_metadata(tmpdir): """Test the param_groups updates are properly saved within the internal state of the BaseFinetuning Callbacks.""" seed_everything(42) class FreezeModel(BoringModel): def __init__(self): super().__init__() self.layer = nn.Sequential( nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=True), nn.Linear(32, 32, bias=False), nn.Linear(32, 32, bias=True), nn.Linear(32, 32, bias=False), nn.Linear(32, 2, bias=True), ) def forward(self, x): return self.layer(x) def configure_optimizers(self): return torch.optim.SGD(self.layer[0].parameters(), lr=0.1) cb = OnEpochLayerFinetuning() chk = ModelCheckpoint(dirpath=tmpdir, save_last=True) model = FreezeModel() trainer = Trainer(default_root_dir=tmpdir, max_epochs=5, limit_train_batches=1, callbacks=[cb, chk]) trainer.fit(model) assert len(cb._internal_optimizer_metadata[0]) == 6 assert cb._internal_optimizer_metadata[0][0]["params"] == ["layer.0.weight"] assert cb._internal_optimizer_metadata[0][1]["params"] == ["layer.1.weight", "layer.1.bias"] assert cb._internal_optimizer_metadata[0][2]["params"] == ["layer.2.weight"] assert cb._internal_optimizer_metadata[0][3]["params"] == ["layer.3.weight", "layer.3.bias"] assert cb._internal_optimizer_metadata[0][4]["params"] == ["layer.4.weight"] assert cb._internal_optimizer_metadata[0][5]["params"] == ["layer.5.weight", "layer.5.bias"] model = FreezeModel() cb = OnEpochLayerFinetuning() trainer = Trainer(max_epochs=10, callbacks=[cb]) with pytest.raises(IndexError, match="index 6 is out of range"): trainer.fit(model, ckpt_path=chk.last_model_path) class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.conv = nn.Conv2d(in_channels, out_channels, 3) self.act = nn.ReLU() self.bn = nn.BatchNorm2d(out_channels) def forward(self, x): x = self.conv(x) x = self.act(x) return self.bn(x) class ConvBlockParam(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.module_dict = nn.ModuleDict({"conv": nn.Conv2d(in_channels, out_channels, 3), "act": nn.ReLU()}) # add trivial test parameter to convblock to validate parent (non-leaf) module parameter handling self.parent_param = nn.Parameter(torch.zeros((1), dtype=torch.float)) self.bn = nn.BatchNorm2d(out_channels) def forward(self, x): x = self.module_dict["conv"](x) x = self.module_dict["act"](x) return self.bn(x) def test_complex_nested_model(): """Test flattening, freezing, and thawing of models which contain parent (non-leaf) modules with parameters directly themselves rather than exclusively their submodules containing parameters.""" model = nn.Sequential( OrderedDict( [("encoder", nn.Sequential(ConvBlockParam(3, 64), ConvBlock(64, 128))), ("decoder", ConvBlock(128, 10))] ) ) # There are 10 leaf modules or parent modules w/ parameters in the test model assert len(BaseFinetuning.flatten_modules(model)) == 10 BaseFinetuning.freeze(model.encoder, train_bn=True) assert not model.encoder[0].module_dict["conv"].weight.requires_grad # Validate a leaf module parameter is frozen assert not model.encoder[0].parent_param.requires_grad # Validate the parent module parameter is frozen assert model.encoder[0].bn.weight.requires_grad BaseFinetuning.make_trainable(model) encoder_params = list(BaseFinetuning.filter_params(model.encoder, train_bn=True)) # The 9 parameters of the encoder are: # conv0.weight, conv0.bias, bn0.weight, bn0.bias, parent_param # conv1.weight, conv1.bias, bn1.weight, bn1.bias assert len(encoder_params) == 9 class TestCallbacksRestoreCallback(BaseFinetuning): def freeze_before_training(self, pl_module): self.freeze(pl_module.layer[:3]) def finetune_function(self, pl_module, epoch, optimizer, opt_idx): if epoch >= 1: self.unfreeze_and_add_param_group(pl_module.layer[epoch - 1], optimizer) class FinetuningBoringModel(BoringModel): def __init__(self): super().__init__() self.layer = nn.Sequential(nn.Linear(32, 32), nn.Linear(32, 32), nn.Linear(32, 32), nn.Linear(32, 2)) def configure_optimizers(self): parameters = filter(lambda x: x.requires_grad, self.parameters()) optimizer = torch.optim.SGD(parameters, lr=0.1) return optimizer def test_callbacks_restore(tmpdir): """Test callbacks restore is called after optimizers have been re-created but before optimizer states reload.""" chk = ModelCheckpoint(dirpath=tmpdir, save_last=True) model = FinetuningBoringModel() callback = TestCallbacksRestoreCallback() trainer_kwargs = dict( default_root_dir=tmpdir, limit_train_batches=1, limit_val_batches=1, callbacks=[callback, chk], max_epochs=2 ) trainer = Trainer(**trainer_kwargs) trainer.fit(model) # only 1 optimizer assert len(callback._internal_optimizer_metadata) == 1 # only 2 param groups assert len(callback._internal_optimizer_metadata[0]) == 2 # original parameters assert callback._internal_optimizer_metadata[0][0] == { "lr": 0.1, "momentum": 0, "dampening": 0, "weight_decay": 0, "nesterov": False, "params": ["layer.3.weight", "layer.3.bias"], } # new param group assert callback._internal_optimizer_metadata[0][1] == { "lr": 0.01, "momentum": 0, "dampening": 0, "weight_decay": 0, "nesterov": False, "params": ["layer.0.weight", "layer.0.bias"], } trainer_kwargs["max_epochs"] = 3 trainer = Trainer(**trainer_kwargs) trainer.fit(model, ckpt_path=chk.last_model_path) def test_callbacks_restore_backbone(tmpdir): """Test callbacks restore is called after optimizers have been re-created but before optimizer states reload.""" class BackboneBoringModel(BoringModel): def __init__(self): super().__init__() self.layer = nn.Linear(32, 2) self.backbone = nn.Linear(32, 32) def forward(self, x): return self.layer(self.backbone(x)) ckpt = ModelCheckpoint(dirpath=tmpdir, save_last=True) trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=1, limit_val_batches=1, max_epochs=2, enable_progress_bar=False, callbacks=[ckpt, BackboneFinetuning(unfreeze_backbone_at_epoch=1)], ) trainer.fit(BackboneBoringModel()) # initialize a trainer that continues the previous training trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=1, limit_val_batches=1, max_epochs=3, enable_progress_bar=False, callbacks=BackboneFinetuning(unfreeze_backbone_at_epoch=1), ) trainer.fit(BackboneBoringModel(), ckpt_path=ckpt.last_model_path)
en
0.765446
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Test finetuning callbacks works as expected. Called when the epoch begins. Test finetuning callbacks works as expected. Test freeze properly sets requires_grad on the modules. Test unfreeze_and_add_param_group properly unfreeze parameters and add to the correct param_group. Test the param_groups updates are properly saved within the internal state of the BaseFinetuning Callbacks. # add trivial test parameter to convblock to validate parent (non-leaf) module parameter handling Test flattening, freezing, and thawing of models which contain parent (non-leaf) modules with parameters directly themselves rather than exclusively their submodules containing parameters. # There are 10 leaf modules or parent modules w/ parameters in the test model # Validate a leaf module parameter is frozen # Validate the parent module parameter is frozen # The 9 parameters of the encoder are: # conv0.weight, conv0.bias, bn0.weight, bn0.bias, parent_param # conv1.weight, conv1.bias, bn1.weight, bn1.bias Test callbacks restore is called after optimizers have been re-created but before optimizer states reload. # only 1 optimizer # only 2 param groups # original parameters # new param group Test callbacks restore is called after optimizers have been re-created but before optimizer states reload. # initialize a trainer that continues the previous training
2.217494
2
airhttprunner/ext/locust/__init__.py
BSTester/httprunner
0
6624327
import sys if "locust" in sys.argv[0]: try: # monkey patch all at beginning to avoid RecursionError when running locust. # `from gevent import monkey; monkey.patch_all()` will be triggered when importing locust from locust import main as locust_main print("NOTICE: gevent monkey patches have been applied !!!") except ImportError: msg = """ Locust is not installed, install first and try again. install with pip: $ pip install locust """ print(msg) sys.exit(1) import importlib.util import inspect import os from typing import List from loguru import logger """ converted pytest files from YAML/JSON testcases """ pytest_files: List = [] def is_httprunner_testcase(item): """ check if a variable is a HttpRunner testcase class """ from airhttprunner import HttpRunner # TODO: skip referenced testcase return bool( inspect.isclass(item) and issubclass(item, HttpRunner) and item.__name__ != "HttpRunner" ) def prepare_locust_tests() -> List: """ prepare locust testcases Returns: list: testcase class list """ locust_tests = [] for pytest_file in pytest_files: spec = importlib.util.spec_from_file_location("module.name", pytest_file) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) for name, item in vars(module).items(): if not is_httprunner_testcase(item): continue for _ in range(item.config.weight): locust_tests.append(item) return locust_tests def main_locusts(): """ locusts entrance """ from airhttprunner.utils import init_sentry_sdk from sentry_sdk import capture_message init_sentry_sdk() capture_message("start to run locusts") # avoid print too much log details in console logger.remove() logger.add(sys.stderr, level="WARNING") sys.argv[0] = "locust" if len(sys.argv) == 1: sys.argv.extend(["-h"]) if sys.argv[1] in ["-h", "--help", "-V", "--version"]: locust_main.main() def get_arg_index(*target_args): for arg in target_args: if arg not in sys.argv: continue return sys.argv.index(arg) + 1 return None # get testcase file path testcase_index = get_arg_index("-f", "--locustfile") if not testcase_index: print("Testcase file is not specified, exit 1.") sys.exit(1) from airhttprunner.make import main_make global pytest_files testcase_file_path = sys.argv[testcase_index] pytest_files = main_make([testcase_file_path]) if not pytest_files: print("No valid testcases found, exit 1.") sys.exit(1) sys.argv[testcase_index] = os.path.join(os.path.dirname(__file__), "locustfile.py") locust_main.main()
import sys if "locust" in sys.argv[0]: try: # monkey patch all at beginning to avoid RecursionError when running locust. # `from gevent import monkey; monkey.patch_all()` will be triggered when importing locust from locust import main as locust_main print("NOTICE: gevent monkey patches have been applied !!!") except ImportError: msg = """ Locust is not installed, install first and try again. install with pip: $ pip install locust """ print(msg) sys.exit(1) import importlib.util import inspect import os from typing import List from loguru import logger """ converted pytest files from YAML/JSON testcases """ pytest_files: List = [] def is_httprunner_testcase(item): """ check if a variable is a HttpRunner testcase class """ from airhttprunner import HttpRunner # TODO: skip referenced testcase return bool( inspect.isclass(item) and issubclass(item, HttpRunner) and item.__name__ != "HttpRunner" ) def prepare_locust_tests() -> List: """ prepare locust testcases Returns: list: testcase class list """ locust_tests = [] for pytest_file in pytest_files: spec = importlib.util.spec_from_file_location("module.name", pytest_file) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) for name, item in vars(module).items(): if not is_httprunner_testcase(item): continue for _ in range(item.config.weight): locust_tests.append(item) return locust_tests def main_locusts(): """ locusts entrance """ from airhttprunner.utils import init_sentry_sdk from sentry_sdk import capture_message init_sentry_sdk() capture_message("start to run locusts") # avoid print too much log details in console logger.remove() logger.add(sys.stderr, level="WARNING") sys.argv[0] = "locust" if len(sys.argv) == 1: sys.argv.extend(["-h"]) if sys.argv[1] in ["-h", "--help", "-V", "--version"]: locust_main.main() def get_arg_index(*target_args): for arg in target_args: if arg not in sys.argv: continue return sys.argv.index(arg) + 1 return None # get testcase file path testcase_index = get_arg_index("-f", "--locustfile") if not testcase_index: print("Testcase file is not specified, exit 1.") sys.exit(1) from airhttprunner.make import main_make global pytest_files testcase_file_path = sys.argv[testcase_index] pytest_files = main_make([testcase_file_path]) if not pytest_files: print("No valid testcases found, exit 1.") sys.exit(1) sys.argv[testcase_index] = os.path.join(os.path.dirname(__file__), "locustfile.py") locust_main.main()
en
0.64286
# monkey patch all at beginning to avoid RecursionError when running locust. # `from gevent import monkey; monkey.patch_all()` will be triggered when importing locust Locust is not installed, install first and try again. install with pip: $ pip install locust converted pytest files from YAML/JSON testcases check if a variable is a HttpRunner testcase class # TODO: skip referenced testcase prepare locust testcases Returns: list: testcase class list locusts entrance # avoid print too much log details in console # get testcase file path
2.371588
2
release/scripts/startup/bl_ui/space_view3d_toolbar.py
AFWSI/blender_source_testing
1
6624328
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> from bpy.types import Menu, Panel, UIList from bl_ui.properties_grease_pencil_common import ( GreasePencilStrokeEditPanel, GreasePencilStrokeSculptPanel, GreasePencilSculptOptionsPanel, GreasePencilAppearancePanel, ) from bl_ui.properties_paint_common import ( UnifiedPaintPanel, brush_mask_texture_settings, brush_texpaint_common, brush_texpaint_common_color, brush_texpaint_common_gradient, brush_texpaint_common_clone, brush_texpaint_common_options, brush_texture_settings, ) from bl_ui.utils import PresetPanel class VIEW3D_MT_brush_context_menu(Menu): bl_label = "Material Specials" def draw(self, context): layout = self.layout settings = UnifiedPaintPanel.paint_settings(context) brush = getattr(settings, "brush", None) # skip if no active brush if not brush: layout.label(text="No Brushes currently available", icon='INFO') return # brush paint modes layout.menu("VIEW3D_MT_brush_paint_modes") # brush tool if context.image_paint_object: layout.prop_menu_enum(brush, "image_tool") elif context.vertex_paint_object: layout.prop_menu_enum(brush, "vertex_tool") elif context.weight_paint_object: layout.prop_menu_enum(brush, "weight_tool") elif context.sculpt_object: layout.prop_menu_enum(brush, "sculpt_tool") layout.operator("brush.reset") class VIEW3D_MT_brush_context_menu_paint_modes(Menu): bl_label = "Enabled Modes" def draw(self, context): layout = self.layout settings = UnifiedPaintPanel.paint_settings(context) brush = settings.brush layout.prop(brush, "use_paint_sculpt", text="Sculpt") layout.prop(brush, "use_paint_uv_sculpt", text="UV Sculpt") layout.prop(brush, "use_paint_vertex", text="Vertex Paint") layout.prop(brush, "use_paint_weight", text="Weight Paint") layout.prop(brush, "use_paint_image", text="Texture Paint") class View3DPanel: bl_space_type = 'VIEW_3D' bl_region_type = 'UI' # **************** standard tool clusters ****************** # Used by vertex & weight paint def draw_vpaint_symmetry(layout, vpaint): split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Mirror") col = split.column() row = col.row(align=True) row.prop(vpaint, "use_symmetry_x", text="X", toggle=True) row.prop(vpaint, "use_symmetry_y", text="Y", toggle=True) row.prop(vpaint, "use_symmetry_z", text="Z", toggle=True) col = layout.column() col.use_property_split = True col.use_property_decorate = False col.prop(vpaint, "radial_symmetry", text="Radial") # Most of these panels should not be visible in GP edit modes def is_not_gpencil_edit_mode(context): is_gpmode = ( context.active_object and context.active_object.mode in {'EDIT_GPENCIL', 'PAINT_GPENCIL', 'SCULPT_GPENCIL', 'WEIGHT_GPENCIL'} ) return not is_gpmode # ********** default tools for object mode **************** class VIEW3D_PT_tools_object_options(View3DPanel, Panel): bl_category = "Tool" bl_context = ".objectmode" # dot on purpose (access from topbar) bl_label = "Options" def draw(self, context): # layout = self.layout pass class VIEW3D_PT_tools_object_options_transform(View3DPanel, Panel): bl_category = "Tool" bl_context = ".objectmode" # dot on purpose (access from topbar) bl_label = "Transform" bl_parent_id = "VIEW3D_PT_tools_object_options" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings layout.label(text="Affect Only") layout.prop(tool_settings, "use_transform_data_origin", text="Origins") layout.prop(tool_settings, "use_transform_pivot_point_align", text="Locations") layout.prop(tool_settings, "use_transform_skip_children", text="Parents") # ********** default tools for editmode_mesh **************** class VIEW3D_PT_tools_meshedit_options(View3DPanel, Panel): bl_category = "Tool" bl_context = ".mesh_edit" # dot on purpose (access from topbar) bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return context.active_object def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False ob = context.active_object mesh = ob.data split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Mirror") col = split.column() row = col.row(align=True) row.prop(mesh, "use_mirror_x", text="X", toggle=True) row.prop(mesh, "use_mirror_y", text="Y", toggle=True) row.prop(mesh, "use_mirror_z", text="Z", toggle=True) row = layout.row(align=True) row.active = ob.data.use_mirror_x or ob.data.use_mirror_y or ob.data.use_mirror_z row.prop(mesh, "use_mirror_topology") class VIEW3D_PT_tools_meshedit_options_automerge(View3DPanel, Panel): bl_category = "Tool" bl_context = ".mesh_edit" # dot on purpose (access from topbar) bl_label = "Auto Merge" bl_parent_id = "VIEW3D_PT_tools_meshedit_options" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return context.active_object def draw_header(self, context): tool_settings = context.tool_settings self.layout.prop(tool_settings, "use_mesh_automerge", text="", toggle=False) def draw(self, context): layout = self.layout tool_settings = context.tool_settings layout.use_property_split = True layout.use_property_decorate = False col = layout.column(align=True) col.active = tool_settings.use_mesh_automerge col.prop(tool_settings, "use_mesh_automerge_and_split", toggle=False) col.prop(tool_settings, "double_threshold", text="Threshold") # ********** default tools for editmode_curve **************** class VIEW3D_PT_tools_curveedit_options_stroke(View3DPanel, Panel): bl_category = "Tool" bl_context = ".curve_edit" # dot on purpose (access from topbar) bl_label = "Curve Stroke" def draw(self, context): layout = self.layout tool_settings = context.tool_settings cps = tool_settings.curve_paint_settings col = layout.column() col.prop(cps, "curve_type") if cps.curve_type == 'BEZIER': col.label(text="Bezier Options:") col.prop(cps, "error_threshold") col.prop(cps, "fit_method") col.prop(cps, "use_corners_detect") col = layout.column() col.active = cps.use_corners_detect col.prop(cps, "corner_angle") col.label(text="Pressure Radius:") row = layout.row(align=True) rowsub = row.row(align=True) rowsub.prop(cps, "radius_min", text="Min") rowsub.prop(cps, "radius_max", text="Max") row.prop(cps, "use_pressure_radius", text="", icon_only=True) col = layout.column() col.label(text="Taper Radius:") row = layout.row(align=True) row.prop(cps, "radius_taper_start", text="Start") row.prop(cps, "radius_taper_end", text="End") col = layout.column() col.label(text="Projection Depth:") row = layout.row(align=True) row.prop(cps, "depth_mode", expand=True) col = layout.column() if cps.depth_mode == 'SURFACE': col.prop(cps, "surface_offset") col.prop(cps, "use_offset_absolute") col.prop(cps, "use_stroke_endpoints") if cps.use_stroke_endpoints: colsub = layout.column(align=True) colsub.prop(cps, "surface_plane", expand=True) # ********** default tools for editmode_armature **************** class VIEW3D_PT_tools_armatureedit_options(View3DPanel, Panel): bl_category = "Tool" bl_context = ".armature_edit" # dot on purpose (access from topbar) bl_label = "Options" def draw(self, context): arm = context.active_object.data self.layout.prop(arm, "use_mirror_x") # ********** default tools for pose-mode **************** class VIEW3D_PT_tools_posemode_options(View3DPanel, Panel): bl_category = "Tool" bl_context = ".posemode" # dot on purpose (access from topbar) bl_label = "Pose Options" def draw(self, context): pose = context.active_object.pose layout = self.layout tool_settings = context.tool_settings layout.prop(pose, "use_auto_ik") layout.prop(pose, "use_mirror_x") col = layout.column() col.active = pose.use_mirror_x col.prop(pose, "use_mirror_relative") layout.label(text="Affect Only") layout.prop(tool_settings, "use_transform_pivot_point_align", text="Locations") # ********** default tools for paint modes **************** class View3DPaintPanel(UnifiedPaintPanel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Tool" class VIEW3D_PT_tools_particlemode(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Particle tools" bl_options = {'HIDE_HEADER'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and context.particle_edit_object) def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush tool = settings.tool layout.use_property_split = True layout.use_property_decorate = False # No animation. if tool is not None: col = layout.column() col.prop(brush, "size", slider=True) if tool == 'ADD': col.prop(brush, "count") col = layout.column() col.prop(settings, "use_default_interpolate") col.prop(brush, "steps", slider=True) col.prop(settings, "default_key_count", slider=True) else: col.prop(brush, "strength", slider=True) if tool == 'LENGTH': layout.row().prop(brush, "length_mode", expand=True) elif tool == 'PUFF': layout.row().prop(brush, "puff_mode", expand=True) layout.prop(brush, "use_puff_volume") elif tool == 'COMB': layout.prop(settings, "use_emitter_deflect", text="Deflect Emitter") col = layout.column() col.active = settings.use_emitter_deflect col.prop(settings, "emitter_distance", text="Distance") # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Brush" @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and (context.sculpt_object or context.vertex_paint_object or context.weight_paint_object or context.image_paint_object)) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False # No animation. settings = self.paint_settings(context) brush = settings.brush if not self.is_popover: row = layout.row() row.column().template_ID_preview(settings, "brush", new="brush.add", rows=3, cols=8) row.menu("VIEW3D_MT_brush_context_menu", icon='DOWNARROW_HLT', text="") # Sculpt Mode # if context.sculpt_object and brush: from bl_ui.properties_paint_common import ( brush_basic_sculpt_settings, ) capabilities = brush.sculpt_capabilities col = layout.column() if not self.is_popover: brush_basic_sculpt_settings(col, context, brush) # normal_radius_factor col.separator() row = col.row() row.prop(brush, "normal_radius_factor", slider=True) if brush.sculpt_tool == 'ELASTIC_DEFORM': col.separator() row = col.row() row.prop(brush, "elastic_deform_type") row = col.row() row.prop(brush, "elastic_deform_volume_preservation", slider=True) elif brush.sculpt_tool == 'POSE': row = col.row() row.prop(brush, "pose_offset") elif brush.sculpt_tool == 'GRAB': col.separator() row = col.row() row.prop(brush, "use_grab_active_vertex") # topology_rake_factor if ( capabilities.has_topology_rake and context.sculpt_object.use_dynamic_topology_sculpting ): row = col.row() row.prop(brush, "topology_rake_factor", slider=True) # auto_smooth_factor and use_inverse_smooth_pressure if capabilities.has_auto_smooth: row = col.row(align=True) row.prop(brush, "auto_smooth_factor", slider=True) row.prop(brush, "use_inverse_smooth_pressure", toggle=True, text="") # normal_weight if capabilities.has_normal_weight: row = col.row(align=True) row.prop(brush, "normal_weight", slider=True) # crease_pinch_factor if capabilities.has_pinch_factor: row = col.row(align=True) if brush.sculpt_tool in {'BLOB', 'SNAKE_HOOK'}: row.prop(brush, "crease_pinch_factor", slider=True, text="Magnify") else: row.prop(brush, "crease_pinch_factor", slider=True, text="Pinch") # rake_factor if capabilities.has_rake_factor: row = col.row(align=True) row.prop(brush, "rake_factor", slider=True) if brush.sculpt_tool == 'MASK': col.prop(brush, "mask_tool") # plane_offset, use_offset_pressure, use_plane_trim, plane_trim if capabilities.has_plane_offset: row = col.row(align=True) row.prop(brush, "plane_offset", slider=True) row.prop(brush, "use_offset_pressure", text="") col.separator() row = col.row() row.prop(brush, "use_plane_trim", text="Plane Trim") row = col.row() row.active = brush.use_plane_trim row.prop(brush, "plane_trim", slider=True, text="Distance") # height if capabilities.has_height: row = col.row() row.prop(brush, "height", slider=True, text="Height") # use_persistent, set_persistent_base if capabilities.has_persistence: ob = context.sculpt_object do_persistent = True # not supported yet for this case for md in ob.modifiers: if md.type == 'MULTIRES': do_persistent = False break if do_persistent: col.prop(brush, "use_persistent") col.operator("sculpt.set_persistent_base") # Texture Paint Mode # elif context.image_paint_object and brush: brush_texpaint_common(self, context, layout, brush, settings, projpaint=True) # Weight Paint Mode # elif context.weight_paint_object and brush: from bl_ui.properties_paint_common import ( brush_basic_wpaint_settings, ) col = layout.column() if not self.is_popover: brush_basic_wpaint_settings(col, context, brush) # Vertex Paint Mode # elif context.vertex_paint_object and brush: from bl_ui.properties_paint_common import ( brush_basic_vpaint_settings, ) col = layout.column() if not self.is_popover: brush_basic_vpaint_settings(col, context, brush) class VIEW3D_PT_tools_brush_color(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_brush" bl_label = "Color Picker" @classmethod def poll(cls, context): settings = cls.paint_settings(context) brush = settings.brush if context.image_paint_object: capabilities = brush.image_paint_capabilities return capabilities.has_color elif context.vertex_paint_object: capabilities = brush.vertex_paint_capabilities return capabilities.has_color def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush if context.vertex_paint_object: brush_texpaint_common_color(self, context, layout, brush, settings, projpaint=True) else: layout.prop(brush, "color_type", expand=True) if brush.color_type == 'COLOR': brush_texpaint_common_color(self, context, layout, brush, settings, projpaint=True) elif brush.color_type == 'GRADIENT': brush_texpaint_common_gradient(self, context, layout, brush, settings, projpaint=True) class VIEW3D_PT_tools_brush_swatches(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_brush" bl_label = "Color Palette" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) brush = settings.brush if context.image_paint_object: capabilities = brush.image_paint_capabilities return capabilities.has_color elif context.vertex_paint_object: capabilities = brush.vertex_paint_capabilities return capabilities.has_color def draw(self, context): layout = self.layout settings = self.paint_settings(context) layout.template_ID(settings, "palette", new="palette.new") if settings.palette: layout.template_palette(settings, "palette", color=True) class VIEW3D_PT_tools_brush_clone(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_brush" bl_label = "Clone from Paint Slot" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) brush = settings.brush return brush.image_tool == 'CLONE' def draw_header(self, context): settings = self.paint_settings(context) self.layout.prop(settings, "use_clone_layer", text="") def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush layout.active = settings.use_clone_layer brush_texpaint_common_clone(self, context, layout, brush, settings, projpaint=True) class VIEW3D_PT_tools_brush_options(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_brush" bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout tool_settings = context.tool_settings settings = self.paint_settings(context) brush = settings.brush capabilities = brush.sculpt_capabilities layout.use_property_split = True layout.use_property_decorate = False # No animation. col = layout.column() if context.image_paint_object and brush: brush_texpaint_common_options(self, context, layout, brush, settings, projpaint=True) elif context.sculpt_object and brush: col.prop(brush, "use_automasking_topology") if capabilities.has_accumulate: col.prop(brush, "use_accumulate") UnifiedPaintPanel.prop_unified_size(col, context, brush, "use_locked_size") if capabilities.has_sculpt_plane: col.prop(brush, "sculpt_plane") col.prop(brush, "use_original_normal") col.prop(brush, "use_original_plane") col.prop(brush, "use_frontface", text="Front Faces Only") col.prop(brush, "use_projected") elif context.weight_paint_object and brush: if brush.weight_tool != 'SMEAR': col.prop(brush, "use_accumulate") col.prop(brush, "use_frontface", text="Front Faces Only") col.prop(brush, "use_projected") col.prop(tool_settings, "use_auto_normalize", text="Auto Normalize") col.prop(tool_settings, "use_multipaint", text="Multi-Paint") elif context.vertex_paint_object and brush: if brush.vertex_tool != 'SMEAR': col.prop(brush, "use_accumulate") col.prop(brush, "use_alpha") col.prop(brush, "use_frontface", text="Front Faces Only") col.prop(brush, "use_projected") class TEXTURE_UL_texpaintslots(UIList): def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): # mat = data if self.layout_type in {'DEFAULT', 'COMPACT'}: layout.prop(item, "name", text="", emboss=False, icon_value=icon) elif self.layout_type == 'GRID': layout.alignment = 'CENTER' layout.label(text="") class VIEW3D_MT_tools_projectpaint_uvlayer(Menu): bl_label = "Clone Layer" def draw(self, context): layout = self.layout for i, uv_layer in enumerate(context.active_object.data.uv_layers): props = layout.operator("wm.context_set_int", text=uv_layer.name, translate=False) props.data_path = "active_object.data.uv_layers.active_index" props.value = i class VIEW3D_PT_slots_projectpaint(View3DPanel, Panel): bl_category = "Tool" bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Texture Slots" @classmethod def poll(cls, context): brush = context.tool_settings.image_paint.brush ob = context.active_object return (brush is not None and ob is not None) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = context.tool_settings.image_paint ob = context.active_object layout.prop(settings, "mode", text="Mode") layout.separator() if settings.mode == 'MATERIAL': if len(ob.material_slots) > 1: layout.template_list("MATERIAL_UL_matslots", "layers", ob, "material_slots", ob, "active_material_index", rows=2) mat = ob.active_material if mat and mat.texture_paint_images: row = layout.row() row.template_list("TEXTURE_UL_texpaintslots", "", mat, "texture_paint_images", mat, "paint_active_slot", rows=2) if mat.texture_paint_slots: slot = mat.texture_paint_slots[mat.paint_active_slot] else: slot = None have_image = slot is not None else: row = layout.row() box = row.box() box.label(text="No Textures") have_image = False sub = row.column(align=True) sub.operator_menu_enum("paint.add_texture_paint_slot", "type", icon='ADD', text="") elif settings.mode == 'IMAGE': mesh = ob.data uv_text = mesh.uv_layers.active.name if mesh.uv_layers.active else "" layout.template_ID(settings, "canvas", new="image.new", open="image.open") if settings.missing_uvs: layout.operator("paint.add_simple_uvs", icon='ADD', text="Add UVs") else: layout.menu("VIEW3D_MT_tools_projectpaint_uvlayer", text=uv_text, translate=False) have_image = settings.canvas is not None layout.prop(settings, "interpolation", text="") if settings.missing_uvs: layout.separator() split = layout.split() split.label(text="UV Map Needed", icon='INFO') split.operator("paint.add_simple_uvs", icon='ADD', text="Add Simple UVs") elif have_image: layout.separator() layout.operator("image.save_all_modified", text="Save All Images", icon='FILE_TICK') # TODO, move to space_view3d.py class VIEW3D_PT_stencil_projectpaint(View3DPanel, Panel): bl_category = "Tool" bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Mask" bl_options = {'DEFAULT_CLOSED'} bl_ui_units_x = 14 @classmethod def poll(cls, context): brush = context.tool_settings.image_paint.brush ob = context.active_object return (brush is not None and ob is not None) def draw_header(self, context): ipaint = context.tool_settings.image_paint self.layout.prop(ipaint, "use_stencil_layer", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings ipaint = tool_settings.image_paint ob = context.active_object mesh = ob.data col = layout.column() col.active = ipaint.use_stencil_layer col.label(text="Stencil Image") col.template_ID(ipaint, "stencil_image", new="image.new", open="image.open") stencil_text = mesh.uv_layer_stencil.name if mesh.uv_layer_stencil else "" col.separator() split = col.split() colsub = split.column() colsub.alignment = 'RIGHT' colsub.label(text="UV Layer") split.column().menu("VIEW3D_MT_tools_projectpaint_stencil", text=stencil_text, translate=False) col.separator() row = col.row(align=True) row.prop(ipaint, "stencil_color", text="Display Color") row.prop(ipaint, "invert_stencil", text="", icon='IMAGE_ALPHA') # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush_display(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Display" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and (context.sculpt_object or context.vertex_paint_object or context.weight_paint_object or context.image_paint_object)) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = self.paint_settings(context) brush = settings.brush tex_slot = brush.texture_slot tex_slot_mask = brush.mask_texture_slot col = layout.column() row = col.row(align=True) sub = row.row(align=True) sub.prop(brush, "cursor_overlay_alpha", text="Curve Alpha") sub.prop(brush, "use_cursor_overlay_override", toggle=True, text="", icon='BRUSH_DATA') row.prop( brush, "use_cursor_overlay", text="", toggle=True, icon='HIDE_OFF' if brush.use_cursor_overlay else 'HIDE_ON', ) col.active = brush.brush_capabilities.has_overlay if context.image_paint_object or context.sculpt_object or context.vertex_paint_object: row = col.row(align=True) sub = row.row(align=True) sub.prop(brush, "texture_overlay_alpha", text="Texture Alpha") sub.prop(brush, "use_primary_overlay_override", toggle=True, text="", icon='BRUSH_DATA') if tex_slot.map_mode != 'STENCIL': row.prop( brush, "use_primary_overlay", text="", toggle=True, icon='HIDE_OFF' if brush.use_primary_overlay else 'HIDE_ON', ) if context.image_paint_object: row = col.row(align=True) sub = row.row(align=True) sub.prop(brush, "mask_overlay_alpha", text="Mask Texture Alpha") sub.prop(brush, "use_secondary_overlay_override", toggle=True, text="", icon='BRUSH_DATA') if tex_slot_mask.map_mode != 'STENCIL': row.prop( brush, "use_secondary_overlay", text="", toggle=True, icon='HIDE_OFF' if brush.use_secondary_overlay else 'HIDE_ON', ) # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush_texture(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Texture" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and (context.sculpt_object or context.image_paint_object or context.vertex_paint_object)) def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.template_ID_preview(brush, "texture", new="texture.new", rows=3, cols=8) brush_texture_settings(col, brush, context.sculpt_object) # TODO, move to space_view3d.py class VIEW3D_PT_tools_mask_texture(Panel, View3DPaintPanel): bl_category = "Tool" bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Texture Mask" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and context.image_paint_object) def draw(self, context): layout = self.layout brush = context.tool_settings.image_paint.brush col = layout.column() col.template_ID_preview(brush, "mask_texture", new="texture.new", rows=3, cols=8) brush_mask_texture_settings(col, brush) # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush_stroke(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Stroke" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and (context.sculpt_object or context.vertex_paint_object or context.weight_paint_object or context.image_paint_object)) def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush layout.use_property_split = True layout.use_property_decorate = False col = layout.column() col.prop(brush, "stroke_method") if brush.use_anchor: col.prop(brush, "use_edge_to_edge", text="Edge To Edge") if brush.use_airbrush: col.prop(brush, "rate", text="Rate", slider=True) if brush.use_space: row = col.row(align=True) row.prop(brush, "spacing", text="Spacing") row.prop(brush, "use_pressure_spacing", toggle=True, text="") if brush.use_line or brush.use_curve: row = col.row(align=True) row.prop(brush, "spacing", text="Spacing") if brush.use_curve: col.template_ID(brush, "paint_curve", new="paintcurve.new") col.operator("paintcurve.draw") if context.sculpt_object: if brush.sculpt_capabilities.has_space_attenuation: col.prop(brush, "use_space_attenuation") col.prop(brush, "use_scene_spacing") if brush.sculpt_capabilities.has_jitter: row = col.row(align=True) if brush.use_relative_jitter: row.prop(brush, "jitter", slider=True) else: row.prop(brush, "jitter_absolute") row.prop(brush, "use_relative_jitter", icon_only=True) row.prop(brush, "use_pressure_jitter", toggle=True, text="") else: row = col.row(align=True) if brush.use_relative_jitter: row.prop(brush, "jitter", slider=True) else: row.prop(brush, "jitter_absolute") row.prop(brush, "use_relative_jitter", icon_only=True) row.prop(brush, "use_pressure_jitter", toggle=True, text="") col.prop(settings, "input_samples") class VIEW3D_PT_tools_brush_stroke_smooth_stroke(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Smooth Stroke" bl_parent_id = "VIEW3D_PT_tools_brush_stroke" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) brush = settings.brush if brush.brush_capabilities.has_smooth_stroke: return True def draw_header(self, context): settings = self.paint_settings(context) brush = settings.brush self.layout.prop(brush, "use_smooth_stroke", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.active = brush.use_smooth_stroke col.prop(brush, "smooth_stroke_radius", text="Radius", slider=True) col.prop(brush, "smooth_stroke_factor", text="Factor", slider=True) # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush_falloff(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Falloff" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and settings.brush.curve) def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush col = layout.column(align=True) row = col.row(align=True) row.prop(brush, "curve_preset", text="") if brush.curve_preset == 'CUSTOM': layout.template_curve_mapping(brush, "curve", brush=True) col = layout.column(align=True) row = col.row(align=True) row.operator("brush.curve_preset", icon='SMOOTHCURVE', text="").shape = 'SMOOTH' row.operator("brush.curve_preset", icon='SPHERECURVE', text="").shape = 'ROUND' row.operator("brush.curve_preset", icon='ROOTCURVE', text="").shape = 'ROOT' row.operator("brush.curve_preset", icon='SHARPCURVE', text="").shape = 'SHARP' row.operator("brush.curve_preset", icon='LINCURVE', text="").shape = 'LINE' row.operator("brush.curve_preset", icon='NOCURVE', text="").shape = 'MAX' class VIEW3D_PT_tools_brush_falloff_frontface(View3DPaintPanel, Panel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Frontface Falloff" bl_parent_id = "VIEW3D_PT_tools_brush_falloff" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return (context.weight_paint_object or context.vertex_paint_object) def draw_header(self, context): settings = self.paint_settings(context) brush = settings.brush self.layout.prop(brush, "use_frontface_falloff", text="") def draw(self, context): settings = self.paint_settings(context) brush = settings.brush layout = self.layout layout.use_property_split = True layout.use_property_decorate = False layout.active = brush.use_frontface_falloff layout.prop(brush, "falloff_angle", text="Angle") class VIEW3D_PT_tools_brush_falloff_normal(View3DPaintPanel, Panel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Normal Falloff" bl_parent_id = "VIEW3D_PT_tools_brush_falloff" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return context.image_paint_object def draw_header(self, context): tool_settings = context.tool_settings ipaint = tool_settings.image_paint self.layout.prop(ipaint, "use_normal_falloff", text="") def draw(self, context): tool_settings = context.tool_settings ipaint = tool_settings.image_paint layout = self.layout layout.use_property_split = True layout.use_property_decorate = False layout.active = ipaint.use_normal_falloff layout.prop(ipaint, "normal_angle", text="Angle") # TODO, move to space_view3d.py class VIEW3D_PT_sculpt_dyntopo(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Dyntopo" bl_options = {'DEFAULT_CLOSED'} bl_ui_units_x = 12 @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw_header(self, context): is_popover = self.is_popover layout = self.layout layout.operator( "sculpt.dynamic_topology_toggle", icon='CHECKBOX_HLT' if context.sculpt_object.use_dynamic_topology_sculpting else 'CHECKBOX_DEHLT', text="", emboss=is_popover, ) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings sculpt = tool_settings.sculpt settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.active = context.sculpt_object.use_dynamic_topology_sculpting sub = col.column() sub.active = (brush and brush.sculpt_tool != 'MASK') if sculpt.detail_type_method in {'CONSTANT', 'MANUAL'}: row = sub.row(align=True) row.prop(sculpt, "constant_detail_resolution") row.operator("sculpt.sample_detail_size", text="", icon='EYEDROPPER') elif (sculpt.detail_type_method == 'BRUSH'): sub.prop(sculpt, "detail_percent") else: sub.prop(sculpt, "detail_size") sub.prop(sculpt, "detail_refine_method", text="Refine Method") sub.prop(sculpt, "detail_type_method", text="Detailing") col.prop(sculpt, "use_smooth_shading") class VIEW3D_PT_sculpt_dyntopo_remesh(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Remesh" bl_parent_id = "VIEW3D_PT_sculpt_dyntopo" bl_options = {'DEFAULT_CLOSED'} bl_ui_units_x = 12 def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings sculpt = tool_settings.sculpt col = layout.column() col.active = context.sculpt_object.use_dynamic_topology_sculpting col.prop(sculpt, "symmetrize_direction") flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) col = flow.column() col.operator("sculpt.symmetrize") col = flow.column() col.operator("sculpt.optimize") if sculpt.detail_type_method in {'CONSTANT', 'MANUAL'}: col = flow.column() col.operator("sculpt.detail_flood_fill") class VIEW3D_PT_sculpt_voxel_remesh(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Remesh" bl_options = {'DEFAULT_CLOSED'} bl_ui_units_x = 12 @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False col = layout.column() mesh = context.active_object.data col.prop(mesh, "remesh_voxel_size") col.prop(mesh, "remesh_voxel_adaptivity") col.prop(mesh, "use_remesh_fix_poles") col.prop(mesh, "use_remesh_smooth_normals") col.prop(mesh, "use_remesh_preserve_volume") col.prop(mesh, "use_remesh_preserve_paint_mask") col.operator("object.voxel_remesh", text="Remesh") # TODO, move to space_view3d.py class VIEW3D_PT_sculpt_options(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings sculpt = tool_settings.sculpt flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) col = flow.column() col.prop(sculpt, "use_threaded", text="Threaded Sculpt") col = flow.column() col.prop(sculpt, "show_low_resolution") col = flow.column() col.prop(sculpt, "use_deform_only") class VIEW3D_PT_sculpt_options_unified(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_sculpt_options" bl_label = "Unified Brush" @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False self.unified_paint_settings(layout, context) class VIEW3D_PT_sculpt_options_gravity(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_sculpt_options" bl_label = "Gravity" @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings sculpt = tool_settings.sculpt capabilities = sculpt.brush.sculpt_capabilities col = layout.column() col.active = capabilities.has_gravity col.prop(sculpt, "gravity", slider=True, text="Factor") col.prop(sculpt, "gravity_object") # TODO, move to space_view3d.py class VIEW3D_PT_sculpt_symmetry(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Symmetry" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return ( (context.sculpt_object and context.tool_settings.sculpt) and # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. (context.region.type != 'TOOL_HEADER') ) def draw(self, context): layout = self.layout sculpt = context.tool_settings.sculpt split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Mirror") col = split.column() row = col.row(align=True) row.prop(sculpt, "use_symmetry_x", text="X", toggle=True) row.prop(sculpt, "use_symmetry_y", text="Y", toggle=True) row.prop(sculpt, "use_symmetry_z", text="Z", toggle=True) split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Lock") col = split.column() row = col.row(align=True) row.prop(sculpt, "lock_x", text="X", toggle=True) row.prop(sculpt, "lock_y", text="Y", toggle=True) row.prop(sculpt, "lock_z", text="Z", toggle=True) split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Tiling") col = split.column() row = col.row(align=True) row.prop(sculpt, "tile_x", text="X", toggle=True) row.prop(sculpt, "tile_y", text="Y", toggle=True) row.prop(sculpt, "tile_z", text="Z", toggle=True) layout.use_property_split = True layout.use_property_decorate = False layout.prop(sculpt, "use_symmetry_feather", text="Feather") layout.column().prop(sculpt, "radial_symmetry", text="Radial") layout.column().prop(sculpt, "tile_offset", text="Tile Offset") class VIEW3D_PT_sculpt_symmetry_for_topbar(Panel): bl_space_type = 'TOPBAR' bl_region_type = 'HEADER' bl_label = "Symmetry" draw = VIEW3D_PT_sculpt_symmetry.draw class VIEW3D_PT_tools_brush_display_show_brush(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Show Brush" bl_parent_id = "VIEW3D_PT_tools_brush_display" bl_options = {'DEFAULT_CLOSED'} def draw_header(self, context): settings = self.paint_settings(context) self.layout.prop(settings, "show_brush", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.active = settings.show_brush if context.sculpt_object and context.tool_settings.sculpt: if brush.sculpt_capabilities.has_secondary_color: col.prop(brush, "cursor_color_add", text="Add") col.prop(brush, "cursor_color_subtract", text="Subtract") else: col.prop(brush, "cursor_color_add", text="Color") else: col.prop(brush, "cursor_color_add", text="Color") class VIEW3D_PT_tools_brush_display_custom_icon(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Custom Icon" bl_parent_id = "VIEW3D_PT_tools_brush_display" bl_options = {'DEFAULT_CLOSED'} def draw_header(self, context): settings = self.paint_settings(context) brush = settings.brush self.layout.prop(brush, "use_custom_icon", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.active = brush.use_custom_icon col.prop(brush, "icon_filepath", text="") # ********** default tools for weight-paint **************** # TODO, move to space_view3d.py class VIEW3D_PT_tools_weightpaint_symmetry(Panel, View3DPaintPanel): bl_context = ".weightpaint" bl_options = {'DEFAULT_CLOSED'} bl_label = "Symmetry" @classmethod def poll(cls, context): # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. return (context.region.type != 'TOOL_HEADER') def draw(self, context): layout = self.layout tool_settings = context.tool_settings wpaint = tool_settings.weight_paint draw_vpaint_symmetry(layout, wpaint) class VIEW3D_PT_tools_weightpaint_symmetry_for_topbar(Panel): bl_space_type = 'TOPBAR' bl_region_type = 'HEADER' bl_label = "Symmetry" draw = VIEW3D_PT_tools_weightpaint_symmetry.draw # TODO, move to space_view3d.py class VIEW3D_PT_tools_weightpaint_options(Panel, View3DPaintPanel): bl_context = ".weightpaint" bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings wpaint = tool_settings.weight_paint col = layout.column() col.prop(wpaint, "use_group_restrict") obj = context.weight_paint_object if obj.type == 'MESH': mesh = obj.data col.prop(mesh, "use_mirror_x") row = col.row() row.active = mesh.use_mirror_x row.prop(mesh, "use_mirror_topology") class VIEW3D_PT_tools_weightpaint_options_unified(Panel, View3DPaintPanel): bl_context = ".weightpaint" bl_label = "Unified Brush" bl_parent_id = "VIEW3D_PT_tools_weightpaint_options" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False self.unified_paint_settings(layout, context) # ********** default tools for vertex-paint **************** # TODO, move to space_view3d.py class VIEW3D_PT_tools_vertexpaint_options(Panel, View3DPaintPanel): bl_context = ".vertexpaint" # dot on purpose (access from topbar) bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.label(text="Unified Brush") layout.use_property_split = True layout.use_property_decorate = False self.unified_paint_settings(layout, context) # TODO, move to space_view3d.py class VIEW3D_PT_tools_vertexpaint_symmetry(Panel, View3DPaintPanel): bl_context = ".vertexpaint" # dot on purpose (access from topbar) bl_options = {'DEFAULT_CLOSED'} bl_label = "Symmetry" @classmethod def poll(cls, context): # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. return (context.region.type != 'TOOL_HEADER') def draw(self, context): layout = self.layout tool_settings = context.tool_settings vpaint = tool_settings.vertex_paint draw_vpaint_symmetry(layout, vpaint) class VIEW3D_PT_tools_vertexpaint_symmetry_for_topbar(Panel): bl_space_type = 'TOPBAR' bl_region_type = 'HEADER' bl_label = "Symmetry" draw = VIEW3D_PT_tools_vertexpaint_symmetry.draw # ********** default tools for texture-paint **************** # TODO, move to space_view3d.py class VIEW3D_PT_tools_imagepaint_options_external(Panel, View3DPaintPanel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "External" bl_parent_id = "VIEW3D_PT_tools_imagepaint_options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings ipaint = tool_settings.image_paint layout.prop(ipaint, "screen_grab_size", text="Screen Grab Size") layout.separator() flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) col = flow.column() col.operator("image.project_edit", text="Quick Edit") col = flow.column() col.operator("image.project_apply", text="Apply") col = flow.column() col.operator("paint.project_image", text="Apply Camera Image") # TODO, move to space_view3d.py class VIEW3D_PT_tools_imagepaint_symmetry(Panel, View3DPaintPanel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Symmetry" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. return (context.region.type != 'TOOL_HEADER') def draw(self, context): layout = self.layout tool_settings = context.tool_settings ipaint = tool_settings.image_paint split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Mirror") col = split.column() row = col.row(align=True) row.prop(ipaint, "use_symmetry_x", text="X", toggle=True) row.prop(ipaint, "use_symmetry_y", text="Y", toggle=True) row.prop(ipaint, "use_symmetry_z", text="Z", toggle=True) # TODO, move to space_view3d.py class VIEW3D_PT_tools_imagepaint_options(View3DPaintPanel, Panel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): brush = context.tool_settings.image_paint.brush return (brush is not None) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings ipaint = tool_settings.image_paint layout.prop(ipaint, "seam_bleed") layout.prop(ipaint, "dither", slider=True) flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) col = flow.column() col.prop(ipaint, "use_occlude") col = flow.column() col.prop(ipaint, "use_backface_culling", text="Backface Culling") class VIEW3D_PT_tools_imagepaint_options_unified(Panel, View3DPaintPanel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_imagepaint_options" bl_label = "Unified Brush" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False self.unified_paint_settings(layout, context) class VIEW3D_PT_tools_imagepaint_options_cavity(View3DPaintPanel, Panel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Cavity Mask" bl_parent_id = "VIEW3D_PT_tools_imagepaint_options" bl_options = {'DEFAULT_CLOSED'} def draw_header(self, context): tool_settings = context.tool_settings ipaint = tool_settings.image_paint self.layout.prop(ipaint, "use_cavity", text="") def draw(self, context): layout = self.layout tool_settings = context.tool_settings ipaint = tool_settings.image_paint layout.active = ipaint.use_cavity layout.template_curve_mapping(ipaint, "cavity_curve", brush=True, use_negative_slope=True) # TODO, move to space_view3d.py class VIEW3D_PT_imagepaint_options(View3DPaintPanel): bl_label = "Options" @classmethod def poll(cls, context): return (context.image_paint_object and context.tool_settings.image_paint) def draw(self, context): layout = self.layout col = layout.column() self.unified_paint_settings(col, context) class VIEW3D_MT_tools_projectpaint_stencil(Menu): bl_label = "Mask Layer" def draw(self, context): layout = self.layout for i, uv_layer in enumerate(context.active_object.data.uv_layers): props = layout.operator("wm.context_set_int", text=uv_layer.name, translate=False) props.data_path = "active_object.data.uv_layer_stencil_index" props.value = i # TODO, move to space_view3d.py class VIEW3D_PT_tools_particlemode_options(View3DPanel, Panel): """Default tools for particle mode""" bl_category = "Tool" bl_context = ".particlemode" bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False # No animation. pe = context.tool_settings.particle_edit ob = pe.object layout.prop(pe, "type", text="Editing Type") ptcache = None if pe.type == 'PARTICLES': if ob.particle_systems: if len(ob.particle_systems) > 1: layout.template_list("UI_UL_list", "particle_systems", ob, "particle_systems", ob.particle_systems, "active_index", rows=2, maxrows=3) ptcache = ob.particle_systems.active.point_cache else: for md in ob.modifiers: if md.type == pe.type: ptcache = md.point_cache if ptcache and len(ptcache.point_caches) > 1: layout.template_list("UI_UL_list", "particles_point_caches", ptcache, "point_caches", ptcache.point_caches, "active_index", rows=2, maxrows=3) if not pe.is_editable: layout.label(text="Point cache must be baked") layout.label(text="in memory to enable editing!") col = layout.column(align=True) col.active = pe.is_editable col.prop(ob.data, "use_mirror_x") col.separator() col.prop(pe, "use_preserve_length", text="Preserve Strand Lengths") col.prop(pe, "use_preserve_root", text="Preserve Root Positions") if not pe.is_hair: col.prop(pe, "use_auto_velocity", text="Auto-Velocity") class VIEW3D_PT_tools_particlemode_options_shapecut(View3DPanel, Panel): """Default tools for particle mode""" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_particlemode_options" bl_label = "Cut Particles to Shape" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False # No animation. pe = context.tool_settings.particle_edit layout.prop(pe, "shape_object") layout.operator("particle.shape_cut", text="Cut") class VIEW3D_PT_tools_particlemode_options_display(View3DPanel, Panel): """Default tools for particle mode""" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_particlemode_options" bl_label = "Viewport Display" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False # No animation. pe = context.tool_settings.particle_edit col = layout.column() col.active = pe.is_editable col.prop(pe, "display_step", text="Path Steps") if pe.is_hair: col.prop(pe, "show_particles", text="Children") else: if pe.type == 'PARTICLES': col.prop(pe, "show_particles", text="Particles") col.prop(pe, "use_fade_time") sub = col.row(align=True) sub.active = pe.use_fade_time sub.prop(pe, "fade_frames", slider=True) # ********** grease pencil object tool panels **************** # Grease Pencil drawing brushes class VIEW3D_PT_tools_grease_pencil_brush(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Brush" bl_category = "Tool" @classmethod def poll(cls, context): is_3d_view = context.space_data.type == 'VIEW_3D' if is_3d_view: if context.gpencil_data is None: return False gpd = context.gpencil_data return bool(gpd.is_stroke_paint_mode) else: return True def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.scene.tool_settings gpencil_paint = tool_settings.gpencil_paint row = layout.row() col = row.column() col.template_ID_preview(gpencil_paint, "brush", new="brush.add_gpencil", rows=3, cols=8) col = row.column() brush = gpencil_paint.brush sub = col.column(align=True) sub.operator("gpencil.brush_presets_create", icon='PRESET_NEW', text="") if brush is not None: gp_settings = brush.gpencil_settings if brush.gpencil_tool in {'DRAW', 'FILL'}: row = layout.row(align=True) row_mat = row.row() if gp_settings.use_material_pin: row_mat.template_ID(gp_settings, "material", live_icon=True) else: row_mat.template_ID(context.active_object, "active_material", live_icon=True) row_mat.enabled = False # will otherwise allow to change material in active slot row.prop(gp_settings, "use_material_pin", text="") if not self.is_popover: from bl_ui.properties_paint_common import ( brush_basic_gpencil_paint_settings, ) tool = context.workspace.tools.from_space_view3d_mode(context.mode, create=False) brush_basic_gpencil_paint_settings(layout, context, brush, tool, compact=True, is_toolbar=False) # Grease Pencil drawing brushes options class VIEW3D_PT_tools_grease_pencil_brush_option(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Options" bl_category = "Tool" @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool not in {'ERASE', 'FILL'} def draw_header_preset(self, _context): VIEW3D_PT_gpencil_brush_presets.draw_panel_header(self.layout) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False brush = context.tool_settings.gpencil_paint.brush if brush is not None: gp_settings = brush.gpencil_settings col = layout.column(align=True) col.prop(gp_settings, "input_samples") col.separator() col.prop(gp_settings, "active_smooth_factor") col.separator() col.prop(gp_settings, "angle", slider=True) col.prop(gp_settings, "angle_factor", text="Factor", slider=True) ob = context.object if ob and brush.gpencil_settings.use_material_pin is False: ma = ob.active_material elif brush.gpencil_settings.material: ma = brush.gpencil_settings.material else: ma = None col.separator() subcol = col.column(align=True) if ma and ma.grease_pencil.mode == 'LINE': subcol.enabled = False subcol.prop(gp_settings, "gradient_factor", slider=True) subcol.prop(gp_settings, "gradient_shape") class VIEW3D_PT_tools_grease_pencil_brush_stabilizer(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_parent_id = 'VIEW3D_PT_tools_grease_pencil_brush_option' bl_label = "Stabilize" bl_category = "Tool" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool == 'DRAW' def draw_header(self, context): brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings self.layout.prop(gp_settings, "use_settings_stabilizer", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.active = gp_settings.use_settings_stabilizer layout.prop(brush, "smooth_stroke_radius", text="Radius", slider=True) layout.prop(brush, "smooth_stroke_factor", text="Factor", slider=True) class VIEW3D_PT_tools_grease_pencil_brush_settings(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_parent_id = 'VIEW3D_PT_tools_grease_pencil_brush_option' bl_label = "Post-Processing" bl_category = "Tool" @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool != 'ERASE' def draw_header(self, context): brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings self.layout.prop(gp_settings, "use_settings_postprocess", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.active = gp_settings.use_settings_postprocess col = layout.column(align=True) col.prop(gp_settings, "pen_smooth_factor") col.prop(gp_settings, "pen_smooth_steps") col = layout.column(align=True) col.prop(gp_settings, "pen_thick_smooth_factor") col.prop(gp_settings, "pen_thick_smooth_steps", text="Iterations") col = layout.column(align=True) col.prop(gp_settings, "pen_subdivision_steps") col.prop(gp_settings, "random_subdiv", text="Randomness", slider=True) col = layout.column(align=True) col.prop(gp_settings, "simplify_factor") col = layout.column(align=True) col.prop(gp_settings, "trim") class VIEW3D_PT_tools_grease_pencil_brush_random(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_parent_id = 'VIEW3D_PT_tools_grease_pencil_brush_option' bl_label = "Randomize" bl_category = "Tool" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool != 'ERASE' def draw_header(self, context): brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings self.layout.prop(gp_settings, "use_settings_random", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.active = gp_settings.use_settings_random layout.prop(gp_settings, "random_pressure", text="Pressure", slider=True) layout.prop(gp_settings, "random_strength", text="Strength", slider=True) layout.prop(gp_settings, "uv_random", text="UV", slider=True) row = layout.row(align=True) row.prop(gp_settings, "pen_jitter", slider=True) row.prop(gp_settings, "use_jitter_pressure", text="", icon='STYLUS_PRESSURE') # Grease Pencil drawingcurves class VIEW3D_PT_tools_grease_pencil_brushcurves(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Curves" bl_category = "Tool" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool not in {'ERASE', 'FILL'} def draw(self, context): pass class VIEW3D_PT_tools_grease_pencil_brushcurves_sensitivity(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Sensitivity" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_grease_pencil_brushcurves" def draw(self, context): layout = self.layout layout.use_property_split = True brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.template_curve_mapping(gp_settings, "curve_sensitivity", brush=True, use_negative_slope=True) class VIEW3D_PT_tools_grease_pencil_brushcurves_strength(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Strength" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_grease_pencil_brushcurves" def draw(self, context): layout = self.layout layout.use_property_split = True brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.template_curve_mapping(gp_settings, "curve_strength", brush=True, use_negative_slope=True) class VIEW3D_PT_tools_grease_pencil_brushcurves_jitter(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Jitter" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_grease_pencil_brushcurves" def draw(self, context): layout = self.layout layout.use_property_split = True brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.template_curve_mapping(gp_settings, "curve_jitter", brush=True, use_negative_slope=True) # Grease Pencil stroke editing tools class VIEW3D_PT_tools_grease_pencil_edit(GreasePencilStrokeEditPanel, Panel): bl_space_type = 'VIEW_3D' bl_category = "Tool" # Grease Pencil stroke interpolation tools class VIEW3D_PT_tools_grease_pencil_interpolate(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'HEADER' bl_label = "Interpolate" @classmethod def poll(cls, context): if context.gpencil_data is None: return False gpd = context.gpencil_data return bool(context.editable_gpencil_strokes) and bool(gpd.use_stroke_edit_mode) def draw(self, context): layout = self.layout settings = context.tool_settings.gpencil_interpolate col = layout.column(align=True) col.label(text="Interpolate Strokes") col.operator("gpencil.interpolate", text="Interpolate") col.operator("gpencil.interpolate_sequence", text="Sequence") col.operator("gpencil.interpolate_reverse", text="Remove Breakdowns") col = layout.column(align=True) col.label(text="Options:") col.prop(settings, "interpolate_all_layers") col.prop(settings, "interpolate_selected_only") col = layout.column(align=True) col.label(text="Sequence Options:") col.prop(settings, "type") if settings.type == 'CUSTOM': # TODO: Options for loading/saving curve presets? col.template_curve_mapping(settings, "interpolation_curve", brush=True, use_negative_slope=True) elif settings.type != 'LINEAR': col.prop(settings, "easing") if settings.type == 'BACK': layout.prop(settings, "back") elif settings.type == 'ELASTIC': sub = layout.column(align=True) sub.prop(settings, "amplitude") sub.prop(settings, "period") # Grease Pencil stroke sculpting tools class VIEW3D_PT_tools_grease_pencil_sculpt(GreasePencilStrokeSculptPanel, View3DPanel, Panel): bl_context = ".greasepencil_sculpt" bl_category = "Tools" bl_label = "Brush" bl_category = "Tool" # Grease Pencil weight painting tools class VIEW3D_PT_tools_grease_pencil_weight_paint(View3DPanel, Panel): bl_context = ".greasepencil_weight" bl_category = "Tools" bl_label = "Brush" bl_category = "Tool" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = context.tool_settings.gpencil_sculpt brush = settings.brush layout.template_icon_view(settings, "weight_tool", show_labels=True) col = layout.column() if not self.is_popover: from bl_ui.properties_paint_common import ( brush_basic_gpencil_weight_settings, ) brush_basic_gpencil_weight_settings(col, context, brush) # Grease Pencil Brush Appearance (one for each mode) class VIEW3D_PT_tools_grease_pencil_paint_appearance(GreasePencilAppearancePanel, View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Display" bl_category = "Tool" class VIEW3D_PT_tools_grease_pencil_sculpt_appearance(GreasePencilAppearancePanel, View3DPanel, Panel): bl_context = ".greasepencil_sculpt" bl_label = "Display" bl_category = "Tool" class VIEW3D_PT_tools_grease_pencil_sculpt_options(GreasePencilSculptOptionsPanel, View3DPanel, Panel): bl_context = ".greasepencil_sculpt" bl_label = "Sculpt Strokes" bl_parent_id = 'VIEW3D_PT_tools_grease_pencil_sculpt' bl_category = "Tool" class VIEW3D_PT_tools_grease_pencil_weight_appearance(GreasePencilAppearancePanel, View3DPanel, Panel): bl_context = ".greasepencil_weight" bl_label = "Display" bl_category = "Tool" class VIEW3D_PT_gpencil_brush_presets(PresetPanel, Panel): """Brush settings""" bl_label = "Brush Presets" preset_subdir = "gpencil_brush" preset_operator = "script.execute_preset" preset_add_operator = "scene.gpencil_brush_preset_add" classes = ( VIEW3D_MT_brush_context_menu, VIEW3D_MT_brush_context_menu_paint_modes, VIEW3D_PT_tools_object_options, VIEW3D_PT_tools_object_options_transform, VIEW3D_PT_tools_meshedit_options, VIEW3D_PT_tools_meshedit_options_automerge, VIEW3D_PT_tools_curveedit_options_stroke, VIEW3D_PT_tools_armatureedit_options, VIEW3D_PT_tools_posemode_options, VIEW3D_PT_slots_projectpaint, VIEW3D_PT_tools_brush, VIEW3D_PT_tools_brush_color, VIEW3D_PT_tools_brush_swatches, VIEW3D_PT_tools_brush_clone, VIEW3D_PT_tools_brush_options, TEXTURE_UL_texpaintslots, VIEW3D_MT_tools_projectpaint_uvlayer, VIEW3D_PT_stencil_projectpaint, VIEW3D_PT_tools_brush_texture, VIEW3D_PT_tools_mask_texture, VIEW3D_PT_tools_brush_stroke, VIEW3D_PT_tools_brush_stroke_smooth_stroke, VIEW3D_PT_tools_brush_falloff, VIEW3D_PT_tools_brush_falloff_frontface, VIEW3D_PT_tools_brush_falloff_normal, VIEW3D_PT_tools_brush_display, VIEW3D_PT_tools_brush_display_show_brush, VIEW3D_PT_tools_brush_display_custom_icon, VIEW3D_PT_sculpt_dyntopo, VIEW3D_PT_sculpt_dyntopo_remesh, VIEW3D_PT_sculpt_voxel_remesh, VIEW3D_PT_sculpt_symmetry, VIEW3D_PT_sculpt_symmetry_for_topbar, VIEW3D_PT_sculpt_options, VIEW3D_PT_sculpt_options_unified, VIEW3D_PT_sculpt_options_gravity, VIEW3D_PT_tools_weightpaint_symmetry, VIEW3D_PT_tools_weightpaint_symmetry_for_topbar, VIEW3D_PT_tools_weightpaint_options, VIEW3D_PT_tools_weightpaint_options_unified, VIEW3D_PT_tools_vertexpaint_symmetry, VIEW3D_PT_tools_vertexpaint_symmetry_for_topbar, VIEW3D_PT_tools_vertexpaint_options, VIEW3D_PT_tools_imagepaint_symmetry, VIEW3D_PT_tools_imagepaint_options, VIEW3D_PT_tools_imagepaint_options_cavity, VIEW3D_PT_tools_imagepaint_options_unified, VIEW3D_PT_tools_imagepaint_options_external, VIEW3D_MT_tools_projectpaint_stencil, VIEW3D_PT_tools_particlemode, VIEW3D_PT_tools_particlemode_options, VIEW3D_PT_tools_particlemode_options_shapecut, VIEW3D_PT_tools_particlemode_options_display, VIEW3D_PT_gpencil_brush_presets, VIEW3D_PT_tools_grease_pencil_brush, VIEW3D_PT_tools_grease_pencil_brush_option, VIEW3D_PT_tools_grease_pencil_brush_settings, VIEW3D_PT_tools_grease_pencil_brush_stabilizer, VIEW3D_PT_tools_grease_pencil_brush_random, VIEW3D_PT_tools_grease_pencil_brushcurves, VIEW3D_PT_tools_grease_pencil_brushcurves_sensitivity, VIEW3D_PT_tools_grease_pencil_brushcurves_strength, VIEW3D_PT_tools_grease_pencil_brushcurves_jitter, VIEW3D_PT_tools_grease_pencil_sculpt, VIEW3D_PT_tools_grease_pencil_weight_paint, VIEW3D_PT_tools_grease_pencil_paint_appearance, VIEW3D_PT_tools_grease_pencil_sculpt_options, VIEW3D_PT_tools_grease_pencil_sculpt_appearance, VIEW3D_PT_tools_grease_pencil_weight_appearance, VIEW3D_PT_tools_grease_pencil_interpolate, ) if __name__ == "__main__": # only for live edit. from bpy.utils import register_class for cls in classes: register_class(cls)
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> from bpy.types import Menu, Panel, UIList from bl_ui.properties_grease_pencil_common import ( GreasePencilStrokeEditPanel, GreasePencilStrokeSculptPanel, GreasePencilSculptOptionsPanel, GreasePencilAppearancePanel, ) from bl_ui.properties_paint_common import ( UnifiedPaintPanel, brush_mask_texture_settings, brush_texpaint_common, brush_texpaint_common_color, brush_texpaint_common_gradient, brush_texpaint_common_clone, brush_texpaint_common_options, brush_texture_settings, ) from bl_ui.utils import PresetPanel class VIEW3D_MT_brush_context_menu(Menu): bl_label = "Material Specials" def draw(self, context): layout = self.layout settings = UnifiedPaintPanel.paint_settings(context) brush = getattr(settings, "brush", None) # skip if no active brush if not brush: layout.label(text="No Brushes currently available", icon='INFO') return # brush paint modes layout.menu("VIEW3D_MT_brush_paint_modes") # brush tool if context.image_paint_object: layout.prop_menu_enum(brush, "image_tool") elif context.vertex_paint_object: layout.prop_menu_enum(brush, "vertex_tool") elif context.weight_paint_object: layout.prop_menu_enum(brush, "weight_tool") elif context.sculpt_object: layout.prop_menu_enum(brush, "sculpt_tool") layout.operator("brush.reset") class VIEW3D_MT_brush_context_menu_paint_modes(Menu): bl_label = "Enabled Modes" def draw(self, context): layout = self.layout settings = UnifiedPaintPanel.paint_settings(context) brush = settings.brush layout.prop(brush, "use_paint_sculpt", text="Sculpt") layout.prop(brush, "use_paint_uv_sculpt", text="UV Sculpt") layout.prop(brush, "use_paint_vertex", text="Vertex Paint") layout.prop(brush, "use_paint_weight", text="Weight Paint") layout.prop(brush, "use_paint_image", text="Texture Paint") class View3DPanel: bl_space_type = 'VIEW_3D' bl_region_type = 'UI' # **************** standard tool clusters ****************** # Used by vertex & weight paint def draw_vpaint_symmetry(layout, vpaint): split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Mirror") col = split.column() row = col.row(align=True) row.prop(vpaint, "use_symmetry_x", text="X", toggle=True) row.prop(vpaint, "use_symmetry_y", text="Y", toggle=True) row.prop(vpaint, "use_symmetry_z", text="Z", toggle=True) col = layout.column() col.use_property_split = True col.use_property_decorate = False col.prop(vpaint, "radial_symmetry", text="Radial") # Most of these panels should not be visible in GP edit modes def is_not_gpencil_edit_mode(context): is_gpmode = ( context.active_object and context.active_object.mode in {'EDIT_GPENCIL', 'PAINT_GPENCIL', 'SCULPT_GPENCIL', 'WEIGHT_GPENCIL'} ) return not is_gpmode # ********** default tools for object mode **************** class VIEW3D_PT_tools_object_options(View3DPanel, Panel): bl_category = "Tool" bl_context = ".objectmode" # dot on purpose (access from topbar) bl_label = "Options" def draw(self, context): # layout = self.layout pass class VIEW3D_PT_tools_object_options_transform(View3DPanel, Panel): bl_category = "Tool" bl_context = ".objectmode" # dot on purpose (access from topbar) bl_label = "Transform" bl_parent_id = "VIEW3D_PT_tools_object_options" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings layout.label(text="Affect Only") layout.prop(tool_settings, "use_transform_data_origin", text="Origins") layout.prop(tool_settings, "use_transform_pivot_point_align", text="Locations") layout.prop(tool_settings, "use_transform_skip_children", text="Parents") # ********** default tools for editmode_mesh **************** class VIEW3D_PT_tools_meshedit_options(View3DPanel, Panel): bl_category = "Tool" bl_context = ".mesh_edit" # dot on purpose (access from topbar) bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return context.active_object def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False ob = context.active_object mesh = ob.data split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Mirror") col = split.column() row = col.row(align=True) row.prop(mesh, "use_mirror_x", text="X", toggle=True) row.prop(mesh, "use_mirror_y", text="Y", toggle=True) row.prop(mesh, "use_mirror_z", text="Z", toggle=True) row = layout.row(align=True) row.active = ob.data.use_mirror_x or ob.data.use_mirror_y or ob.data.use_mirror_z row.prop(mesh, "use_mirror_topology") class VIEW3D_PT_tools_meshedit_options_automerge(View3DPanel, Panel): bl_category = "Tool" bl_context = ".mesh_edit" # dot on purpose (access from topbar) bl_label = "Auto Merge" bl_parent_id = "VIEW3D_PT_tools_meshedit_options" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return context.active_object def draw_header(self, context): tool_settings = context.tool_settings self.layout.prop(tool_settings, "use_mesh_automerge", text="", toggle=False) def draw(self, context): layout = self.layout tool_settings = context.tool_settings layout.use_property_split = True layout.use_property_decorate = False col = layout.column(align=True) col.active = tool_settings.use_mesh_automerge col.prop(tool_settings, "use_mesh_automerge_and_split", toggle=False) col.prop(tool_settings, "double_threshold", text="Threshold") # ********** default tools for editmode_curve **************** class VIEW3D_PT_tools_curveedit_options_stroke(View3DPanel, Panel): bl_category = "Tool" bl_context = ".curve_edit" # dot on purpose (access from topbar) bl_label = "Curve Stroke" def draw(self, context): layout = self.layout tool_settings = context.tool_settings cps = tool_settings.curve_paint_settings col = layout.column() col.prop(cps, "curve_type") if cps.curve_type == 'BEZIER': col.label(text="Bezier Options:") col.prop(cps, "error_threshold") col.prop(cps, "fit_method") col.prop(cps, "use_corners_detect") col = layout.column() col.active = cps.use_corners_detect col.prop(cps, "corner_angle") col.label(text="Pressure Radius:") row = layout.row(align=True) rowsub = row.row(align=True) rowsub.prop(cps, "radius_min", text="Min") rowsub.prop(cps, "radius_max", text="Max") row.prop(cps, "use_pressure_radius", text="", icon_only=True) col = layout.column() col.label(text="Taper Radius:") row = layout.row(align=True) row.prop(cps, "radius_taper_start", text="Start") row.prop(cps, "radius_taper_end", text="End") col = layout.column() col.label(text="Projection Depth:") row = layout.row(align=True) row.prop(cps, "depth_mode", expand=True) col = layout.column() if cps.depth_mode == 'SURFACE': col.prop(cps, "surface_offset") col.prop(cps, "use_offset_absolute") col.prop(cps, "use_stroke_endpoints") if cps.use_stroke_endpoints: colsub = layout.column(align=True) colsub.prop(cps, "surface_plane", expand=True) # ********** default tools for editmode_armature **************** class VIEW3D_PT_tools_armatureedit_options(View3DPanel, Panel): bl_category = "Tool" bl_context = ".armature_edit" # dot on purpose (access from topbar) bl_label = "Options" def draw(self, context): arm = context.active_object.data self.layout.prop(arm, "use_mirror_x") # ********** default tools for pose-mode **************** class VIEW3D_PT_tools_posemode_options(View3DPanel, Panel): bl_category = "Tool" bl_context = ".posemode" # dot on purpose (access from topbar) bl_label = "Pose Options" def draw(self, context): pose = context.active_object.pose layout = self.layout tool_settings = context.tool_settings layout.prop(pose, "use_auto_ik") layout.prop(pose, "use_mirror_x") col = layout.column() col.active = pose.use_mirror_x col.prop(pose, "use_mirror_relative") layout.label(text="Affect Only") layout.prop(tool_settings, "use_transform_pivot_point_align", text="Locations") # ********** default tools for paint modes **************** class View3DPaintPanel(UnifiedPaintPanel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Tool" class VIEW3D_PT_tools_particlemode(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Particle tools" bl_options = {'HIDE_HEADER'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and context.particle_edit_object) def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush tool = settings.tool layout.use_property_split = True layout.use_property_decorate = False # No animation. if tool is not None: col = layout.column() col.prop(brush, "size", slider=True) if tool == 'ADD': col.prop(brush, "count") col = layout.column() col.prop(settings, "use_default_interpolate") col.prop(brush, "steps", slider=True) col.prop(settings, "default_key_count", slider=True) else: col.prop(brush, "strength", slider=True) if tool == 'LENGTH': layout.row().prop(brush, "length_mode", expand=True) elif tool == 'PUFF': layout.row().prop(brush, "puff_mode", expand=True) layout.prop(brush, "use_puff_volume") elif tool == 'COMB': layout.prop(settings, "use_emitter_deflect", text="Deflect Emitter") col = layout.column() col.active = settings.use_emitter_deflect col.prop(settings, "emitter_distance", text="Distance") # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Brush" @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and (context.sculpt_object or context.vertex_paint_object or context.weight_paint_object or context.image_paint_object)) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False # No animation. settings = self.paint_settings(context) brush = settings.brush if not self.is_popover: row = layout.row() row.column().template_ID_preview(settings, "brush", new="brush.add", rows=3, cols=8) row.menu("VIEW3D_MT_brush_context_menu", icon='DOWNARROW_HLT', text="") # Sculpt Mode # if context.sculpt_object and brush: from bl_ui.properties_paint_common import ( brush_basic_sculpt_settings, ) capabilities = brush.sculpt_capabilities col = layout.column() if not self.is_popover: brush_basic_sculpt_settings(col, context, brush) # normal_radius_factor col.separator() row = col.row() row.prop(brush, "normal_radius_factor", slider=True) if brush.sculpt_tool == 'ELASTIC_DEFORM': col.separator() row = col.row() row.prop(brush, "elastic_deform_type") row = col.row() row.prop(brush, "elastic_deform_volume_preservation", slider=True) elif brush.sculpt_tool == 'POSE': row = col.row() row.prop(brush, "pose_offset") elif brush.sculpt_tool == 'GRAB': col.separator() row = col.row() row.prop(brush, "use_grab_active_vertex") # topology_rake_factor if ( capabilities.has_topology_rake and context.sculpt_object.use_dynamic_topology_sculpting ): row = col.row() row.prop(brush, "topology_rake_factor", slider=True) # auto_smooth_factor and use_inverse_smooth_pressure if capabilities.has_auto_smooth: row = col.row(align=True) row.prop(brush, "auto_smooth_factor", slider=True) row.prop(brush, "use_inverse_smooth_pressure", toggle=True, text="") # normal_weight if capabilities.has_normal_weight: row = col.row(align=True) row.prop(brush, "normal_weight", slider=True) # crease_pinch_factor if capabilities.has_pinch_factor: row = col.row(align=True) if brush.sculpt_tool in {'BLOB', 'SNAKE_HOOK'}: row.prop(brush, "crease_pinch_factor", slider=True, text="Magnify") else: row.prop(brush, "crease_pinch_factor", slider=True, text="Pinch") # rake_factor if capabilities.has_rake_factor: row = col.row(align=True) row.prop(brush, "rake_factor", slider=True) if brush.sculpt_tool == 'MASK': col.prop(brush, "mask_tool") # plane_offset, use_offset_pressure, use_plane_trim, plane_trim if capabilities.has_plane_offset: row = col.row(align=True) row.prop(brush, "plane_offset", slider=True) row.prop(brush, "use_offset_pressure", text="") col.separator() row = col.row() row.prop(brush, "use_plane_trim", text="Plane Trim") row = col.row() row.active = brush.use_plane_trim row.prop(brush, "plane_trim", slider=True, text="Distance") # height if capabilities.has_height: row = col.row() row.prop(brush, "height", slider=True, text="Height") # use_persistent, set_persistent_base if capabilities.has_persistence: ob = context.sculpt_object do_persistent = True # not supported yet for this case for md in ob.modifiers: if md.type == 'MULTIRES': do_persistent = False break if do_persistent: col.prop(brush, "use_persistent") col.operator("sculpt.set_persistent_base") # Texture Paint Mode # elif context.image_paint_object and brush: brush_texpaint_common(self, context, layout, brush, settings, projpaint=True) # Weight Paint Mode # elif context.weight_paint_object and brush: from bl_ui.properties_paint_common import ( brush_basic_wpaint_settings, ) col = layout.column() if not self.is_popover: brush_basic_wpaint_settings(col, context, brush) # Vertex Paint Mode # elif context.vertex_paint_object and brush: from bl_ui.properties_paint_common import ( brush_basic_vpaint_settings, ) col = layout.column() if not self.is_popover: brush_basic_vpaint_settings(col, context, brush) class VIEW3D_PT_tools_brush_color(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_brush" bl_label = "Color Picker" @classmethod def poll(cls, context): settings = cls.paint_settings(context) brush = settings.brush if context.image_paint_object: capabilities = brush.image_paint_capabilities return capabilities.has_color elif context.vertex_paint_object: capabilities = brush.vertex_paint_capabilities return capabilities.has_color def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush if context.vertex_paint_object: brush_texpaint_common_color(self, context, layout, brush, settings, projpaint=True) else: layout.prop(brush, "color_type", expand=True) if brush.color_type == 'COLOR': brush_texpaint_common_color(self, context, layout, brush, settings, projpaint=True) elif brush.color_type == 'GRADIENT': brush_texpaint_common_gradient(self, context, layout, brush, settings, projpaint=True) class VIEW3D_PT_tools_brush_swatches(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_brush" bl_label = "Color Palette" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) brush = settings.brush if context.image_paint_object: capabilities = brush.image_paint_capabilities return capabilities.has_color elif context.vertex_paint_object: capabilities = brush.vertex_paint_capabilities return capabilities.has_color def draw(self, context): layout = self.layout settings = self.paint_settings(context) layout.template_ID(settings, "palette", new="palette.new") if settings.palette: layout.template_palette(settings, "palette", color=True) class VIEW3D_PT_tools_brush_clone(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_brush" bl_label = "Clone from Paint Slot" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) brush = settings.brush return brush.image_tool == 'CLONE' def draw_header(self, context): settings = self.paint_settings(context) self.layout.prop(settings, "use_clone_layer", text="") def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush layout.active = settings.use_clone_layer brush_texpaint_common_clone(self, context, layout, brush, settings, projpaint=True) class VIEW3D_PT_tools_brush_options(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_brush" bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout tool_settings = context.tool_settings settings = self.paint_settings(context) brush = settings.brush capabilities = brush.sculpt_capabilities layout.use_property_split = True layout.use_property_decorate = False # No animation. col = layout.column() if context.image_paint_object and brush: brush_texpaint_common_options(self, context, layout, brush, settings, projpaint=True) elif context.sculpt_object and brush: col.prop(brush, "use_automasking_topology") if capabilities.has_accumulate: col.prop(brush, "use_accumulate") UnifiedPaintPanel.prop_unified_size(col, context, brush, "use_locked_size") if capabilities.has_sculpt_plane: col.prop(brush, "sculpt_plane") col.prop(brush, "use_original_normal") col.prop(brush, "use_original_plane") col.prop(brush, "use_frontface", text="Front Faces Only") col.prop(brush, "use_projected") elif context.weight_paint_object and brush: if brush.weight_tool != 'SMEAR': col.prop(brush, "use_accumulate") col.prop(brush, "use_frontface", text="Front Faces Only") col.prop(brush, "use_projected") col.prop(tool_settings, "use_auto_normalize", text="Auto Normalize") col.prop(tool_settings, "use_multipaint", text="Multi-Paint") elif context.vertex_paint_object and brush: if brush.vertex_tool != 'SMEAR': col.prop(brush, "use_accumulate") col.prop(brush, "use_alpha") col.prop(brush, "use_frontface", text="Front Faces Only") col.prop(brush, "use_projected") class TEXTURE_UL_texpaintslots(UIList): def draw_item(self, _context, layout, _data, item, icon, _active_data, _active_propname, _index): # mat = data if self.layout_type in {'DEFAULT', 'COMPACT'}: layout.prop(item, "name", text="", emboss=False, icon_value=icon) elif self.layout_type == 'GRID': layout.alignment = 'CENTER' layout.label(text="") class VIEW3D_MT_tools_projectpaint_uvlayer(Menu): bl_label = "Clone Layer" def draw(self, context): layout = self.layout for i, uv_layer in enumerate(context.active_object.data.uv_layers): props = layout.operator("wm.context_set_int", text=uv_layer.name, translate=False) props.data_path = "active_object.data.uv_layers.active_index" props.value = i class VIEW3D_PT_slots_projectpaint(View3DPanel, Panel): bl_category = "Tool" bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Texture Slots" @classmethod def poll(cls, context): brush = context.tool_settings.image_paint.brush ob = context.active_object return (brush is not None and ob is not None) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = context.tool_settings.image_paint ob = context.active_object layout.prop(settings, "mode", text="Mode") layout.separator() if settings.mode == 'MATERIAL': if len(ob.material_slots) > 1: layout.template_list("MATERIAL_UL_matslots", "layers", ob, "material_slots", ob, "active_material_index", rows=2) mat = ob.active_material if mat and mat.texture_paint_images: row = layout.row() row.template_list("TEXTURE_UL_texpaintslots", "", mat, "texture_paint_images", mat, "paint_active_slot", rows=2) if mat.texture_paint_slots: slot = mat.texture_paint_slots[mat.paint_active_slot] else: slot = None have_image = slot is not None else: row = layout.row() box = row.box() box.label(text="No Textures") have_image = False sub = row.column(align=True) sub.operator_menu_enum("paint.add_texture_paint_slot", "type", icon='ADD', text="") elif settings.mode == 'IMAGE': mesh = ob.data uv_text = mesh.uv_layers.active.name if mesh.uv_layers.active else "" layout.template_ID(settings, "canvas", new="image.new", open="image.open") if settings.missing_uvs: layout.operator("paint.add_simple_uvs", icon='ADD', text="Add UVs") else: layout.menu("VIEW3D_MT_tools_projectpaint_uvlayer", text=uv_text, translate=False) have_image = settings.canvas is not None layout.prop(settings, "interpolation", text="") if settings.missing_uvs: layout.separator() split = layout.split() split.label(text="UV Map Needed", icon='INFO') split.operator("paint.add_simple_uvs", icon='ADD', text="Add Simple UVs") elif have_image: layout.separator() layout.operator("image.save_all_modified", text="Save All Images", icon='FILE_TICK') # TODO, move to space_view3d.py class VIEW3D_PT_stencil_projectpaint(View3DPanel, Panel): bl_category = "Tool" bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Mask" bl_options = {'DEFAULT_CLOSED'} bl_ui_units_x = 14 @classmethod def poll(cls, context): brush = context.tool_settings.image_paint.brush ob = context.active_object return (brush is not None and ob is not None) def draw_header(self, context): ipaint = context.tool_settings.image_paint self.layout.prop(ipaint, "use_stencil_layer", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings ipaint = tool_settings.image_paint ob = context.active_object mesh = ob.data col = layout.column() col.active = ipaint.use_stencil_layer col.label(text="Stencil Image") col.template_ID(ipaint, "stencil_image", new="image.new", open="image.open") stencil_text = mesh.uv_layer_stencil.name if mesh.uv_layer_stencil else "" col.separator() split = col.split() colsub = split.column() colsub.alignment = 'RIGHT' colsub.label(text="UV Layer") split.column().menu("VIEW3D_MT_tools_projectpaint_stencil", text=stencil_text, translate=False) col.separator() row = col.row(align=True) row.prop(ipaint, "stencil_color", text="Display Color") row.prop(ipaint, "invert_stencil", text="", icon='IMAGE_ALPHA') # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush_display(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Display" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and (context.sculpt_object or context.vertex_paint_object or context.weight_paint_object or context.image_paint_object)) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = self.paint_settings(context) brush = settings.brush tex_slot = brush.texture_slot tex_slot_mask = brush.mask_texture_slot col = layout.column() row = col.row(align=True) sub = row.row(align=True) sub.prop(brush, "cursor_overlay_alpha", text="Curve Alpha") sub.prop(brush, "use_cursor_overlay_override", toggle=True, text="", icon='BRUSH_DATA') row.prop( brush, "use_cursor_overlay", text="", toggle=True, icon='HIDE_OFF' if brush.use_cursor_overlay else 'HIDE_ON', ) col.active = brush.brush_capabilities.has_overlay if context.image_paint_object or context.sculpt_object or context.vertex_paint_object: row = col.row(align=True) sub = row.row(align=True) sub.prop(brush, "texture_overlay_alpha", text="Texture Alpha") sub.prop(brush, "use_primary_overlay_override", toggle=True, text="", icon='BRUSH_DATA') if tex_slot.map_mode != 'STENCIL': row.prop( brush, "use_primary_overlay", text="", toggle=True, icon='HIDE_OFF' if brush.use_primary_overlay else 'HIDE_ON', ) if context.image_paint_object: row = col.row(align=True) sub = row.row(align=True) sub.prop(brush, "mask_overlay_alpha", text="Mask Texture Alpha") sub.prop(brush, "use_secondary_overlay_override", toggle=True, text="", icon='BRUSH_DATA') if tex_slot_mask.map_mode != 'STENCIL': row.prop( brush, "use_secondary_overlay", text="", toggle=True, icon='HIDE_OFF' if brush.use_secondary_overlay else 'HIDE_ON', ) # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush_texture(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Texture" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and (context.sculpt_object or context.image_paint_object or context.vertex_paint_object)) def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.template_ID_preview(brush, "texture", new="texture.new", rows=3, cols=8) brush_texture_settings(col, brush, context.sculpt_object) # TODO, move to space_view3d.py class VIEW3D_PT_tools_mask_texture(Panel, View3DPaintPanel): bl_category = "Tool" bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Texture Mask" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and context.image_paint_object) def draw(self, context): layout = self.layout brush = context.tool_settings.image_paint.brush col = layout.column() col.template_ID_preview(brush, "mask_texture", new="texture.new", rows=3, cols=8) brush_mask_texture_settings(col, brush) # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush_stroke(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Stroke" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and (context.sculpt_object or context.vertex_paint_object or context.weight_paint_object or context.image_paint_object)) def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush layout.use_property_split = True layout.use_property_decorate = False col = layout.column() col.prop(brush, "stroke_method") if brush.use_anchor: col.prop(brush, "use_edge_to_edge", text="Edge To Edge") if brush.use_airbrush: col.prop(brush, "rate", text="Rate", slider=True) if brush.use_space: row = col.row(align=True) row.prop(brush, "spacing", text="Spacing") row.prop(brush, "use_pressure_spacing", toggle=True, text="") if brush.use_line or brush.use_curve: row = col.row(align=True) row.prop(brush, "spacing", text="Spacing") if brush.use_curve: col.template_ID(brush, "paint_curve", new="paintcurve.new") col.operator("paintcurve.draw") if context.sculpt_object: if brush.sculpt_capabilities.has_space_attenuation: col.prop(brush, "use_space_attenuation") col.prop(brush, "use_scene_spacing") if brush.sculpt_capabilities.has_jitter: row = col.row(align=True) if brush.use_relative_jitter: row.prop(brush, "jitter", slider=True) else: row.prop(brush, "jitter_absolute") row.prop(brush, "use_relative_jitter", icon_only=True) row.prop(brush, "use_pressure_jitter", toggle=True, text="") else: row = col.row(align=True) if brush.use_relative_jitter: row.prop(brush, "jitter", slider=True) else: row.prop(brush, "jitter_absolute") row.prop(brush, "use_relative_jitter", icon_only=True) row.prop(brush, "use_pressure_jitter", toggle=True, text="") col.prop(settings, "input_samples") class VIEW3D_PT_tools_brush_stroke_smooth_stroke(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Smooth Stroke" bl_parent_id = "VIEW3D_PT_tools_brush_stroke" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) brush = settings.brush if brush.brush_capabilities.has_smooth_stroke: return True def draw_header(self, context): settings = self.paint_settings(context) brush = settings.brush self.layout.prop(brush, "use_smooth_stroke", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.active = brush.use_smooth_stroke col.prop(brush, "smooth_stroke_radius", text="Radius", slider=True) col.prop(brush, "smooth_stroke_factor", text="Factor", slider=True) # TODO, move to space_view3d.py class VIEW3D_PT_tools_brush_falloff(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Falloff" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): settings = cls.paint_settings(context) return (settings and settings.brush and settings.brush.curve) def draw(self, context): layout = self.layout settings = self.paint_settings(context) brush = settings.brush col = layout.column(align=True) row = col.row(align=True) row.prop(brush, "curve_preset", text="") if brush.curve_preset == 'CUSTOM': layout.template_curve_mapping(brush, "curve", brush=True) col = layout.column(align=True) row = col.row(align=True) row.operator("brush.curve_preset", icon='SMOOTHCURVE', text="").shape = 'SMOOTH' row.operator("brush.curve_preset", icon='SPHERECURVE', text="").shape = 'ROUND' row.operator("brush.curve_preset", icon='ROOTCURVE', text="").shape = 'ROOT' row.operator("brush.curve_preset", icon='SHARPCURVE', text="").shape = 'SHARP' row.operator("brush.curve_preset", icon='LINCURVE', text="").shape = 'LINE' row.operator("brush.curve_preset", icon='NOCURVE', text="").shape = 'MAX' class VIEW3D_PT_tools_brush_falloff_frontface(View3DPaintPanel, Panel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Frontface Falloff" bl_parent_id = "VIEW3D_PT_tools_brush_falloff" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return (context.weight_paint_object or context.vertex_paint_object) def draw_header(self, context): settings = self.paint_settings(context) brush = settings.brush self.layout.prop(brush, "use_frontface_falloff", text="") def draw(self, context): settings = self.paint_settings(context) brush = settings.brush layout = self.layout layout.use_property_split = True layout.use_property_decorate = False layout.active = brush.use_frontface_falloff layout.prop(brush, "falloff_angle", text="Angle") class VIEW3D_PT_tools_brush_falloff_normal(View3DPaintPanel, Panel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Normal Falloff" bl_parent_id = "VIEW3D_PT_tools_brush_falloff" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return context.image_paint_object def draw_header(self, context): tool_settings = context.tool_settings ipaint = tool_settings.image_paint self.layout.prop(ipaint, "use_normal_falloff", text="") def draw(self, context): tool_settings = context.tool_settings ipaint = tool_settings.image_paint layout = self.layout layout.use_property_split = True layout.use_property_decorate = False layout.active = ipaint.use_normal_falloff layout.prop(ipaint, "normal_angle", text="Angle") # TODO, move to space_view3d.py class VIEW3D_PT_sculpt_dyntopo(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Dyntopo" bl_options = {'DEFAULT_CLOSED'} bl_ui_units_x = 12 @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw_header(self, context): is_popover = self.is_popover layout = self.layout layout.operator( "sculpt.dynamic_topology_toggle", icon='CHECKBOX_HLT' if context.sculpt_object.use_dynamic_topology_sculpting else 'CHECKBOX_DEHLT', text="", emboss=is_popover, ) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings sculpt = tool_settings.sculpt settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.active = context.sculpt_object.use_dynamic_topology_sculpting sub = col.column() sub.active = (brush and brush.sculpt_tool != 'MASK') if sculpt.detail_type_method in {'CONSTANT', 'MANUAL'}: row = sub.row(align=True) row.prop(sculpt, "constant_detail_resolution") row.operator("sculpt.sample_detail_size", text="", icon='EYEDROPPER') elif (sculpt.detail_type_method == 'BRUSH'): sub.prop(sculpt, "detail_percent") else: sub.prop(sculpt, "detail_size") sub.prop(sculpt, "detail_refine_method", text="Refine Method") sub.prop(sculpt, "detail_type_method", text="Detailing") col.prop(sculpt, "use_smooth_shading") class VIEW3D_PT_sculpt_dyntopo_remesh(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Remesh" bl_parent_id = "VIEW3D_PT_sculpt_dyntopo" bl_options = {'DEFAULT_CLOSED'} bl_ui_units_x = 12 def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings sculpt = tool_settings.sculpt col = layout.column() col.active = context.sculpt_object.use_dynamic_topology_sculpting col.prop(sculpt, "symmetrize_direction") flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) col = flow.column() col.operator("sculpt.symmetrize") col = flow.column() col.operator("sculpt.optimize") if sculpt.detail_type_method in {'CONSTANT', 'MANUAL'}: col = flow.column() col.operator("sculpt.detail_flood_fill") class VIEW3D_PT_sculpt_voxel_remesh(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Remesh" bl_options = {'DEFAULT_CLOSED'} bl_ui_units_x = 12 @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False col = layout.column() mesh = context.active_object.data col.prop(mesh, "remesh_voxel_size") col.prop(mesh, "remesh_voxel_adaptivity") col.prop(mesh, "use_remesh_fix_poles") col.prop(mesh, "use_remesh_smooth_normals") col.prop(mesh, "use_remesh_preserve_volume") col.prop(mesh, "use_remesh_preserve_paint_mask") col.operator("object.voxel_remesh", text="Remesh") # TODO, move to space_view3d.py class VIEW3D_PT_sculpt_options(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings sculpt = tool_settings.sculpt flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) col = flow.column() col.prop(sculpt, "use_threaded", text="Threaded Sculpt") col = flow.column() col.prop(sculpt, "show_low_resolution") col = flow.column() col.prop(sculpt, "use_deform_only") class VIEW3D_PT_sculpt_options_unified(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_sculpt_options" bl_label = "Unified Brush" @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False self.unified_paint_settings(layout, context) class VIEW3D_PT_sculpt_options_gravity(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_sculpt_options" bl_label = "Gravity" @classmethod def poll(cls, context): return (context.sculpt_object and context.tool_settings.sculpt) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings sculpt = tool_settings.sculpt capabilities = sculpt.brush.sculpt_capabilities col = layout.column() col.active = capabilities.has_gravity col.prop(sculpt, "gravity", slider=True, text="Factor") col.prop(sculpt, "gravity_object") # TODO, move to space_view3d.py class VIEW3D_PT_sculpt_symmetry(Panel, View3DPaintPanel): bl_context = ".sculpt_mode" # dot on purpose (access from topbar) bl_label = "Symmetry" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): return ( (context.sculpt_object and context.tool_settings.sculpt) and # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. (context.region.type != 'TOOL_HEADER') ) def draw(self, context): layout = self.layout sculpt = context.tool_settings.sculpt split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Mirror") col = split.column() row = col.row(align=True) row.prop(sculpt, "use_symmetry_x", text="X", toggle=True) row.prop(sculpt, "use_symmetry_y", text="Y", toggle=True) row.prop(sculpt, "use_symmetry_z", text="Z", toggle=True) split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Lock") col = split.column() row = col.row(align=True) row.prop(sculpt, "lock_x", text="X", toggle=True) row.prop(sculpt, "lock_y", text="Y", toggle=True) row.prop(sculpt, "lock_z", text="Z", toggle=True) split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Tiling") col = split.column() row = col.row(align=True) row.prop(sculpt, "tile_x", text="X", toggle=True) row.prop(sculpt, "tile_y", text="Y", toggle=True) row.prop(sculpt, "tile_z", text="Z", toggle=True) layout.use_property_split = True layout.use_property_decorate = False layout.prop(sculpt, "use_symmetry_feather", text="Feather") layout.column().prop(sculpt, "radial_symmetry", text="Radial") layout.column().prop(sculpt, "tile_offset", text="Tile Offset") class VIEW3D_PT_sculpt_symmetry_for_topbar(Panel): bl_space_type = 'TOPBAR' bl_region_type = 'HEADER' bl_label = "Symmetry" draw = VIEW3D_PT_sculpt_symmetry.draw class VIEW3D_PT_tools_brush_display_show_brush(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Show Brush" bl_parent_id = "VIEW3D_PT_tools_brush_display" bl_options = {'DEFAULT_CLOSED'} def draw_header(self, context): settings = self.paint_settings(context) self.layout.prop(settings, "show_brush", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.active = settings.show_brush if context.sculpt_object and context.tool_settings.sculpt: if brush.sculpt_capabilities.has_secondary_color: col.prop(brush, "cursor_color_add", text="Add") col.prop(brush, "cursor_color_subtract", text="Subtract") else: col.prop(brush, "cursor_color_add", text="Color") else: col.prop(brush, "cursor_color_add", text="Color") class VIEW3D_PT_tools_brush_display_custom_icon(Panel, View3DPaintPanel): bl_context = ".paint_common" # dot on purpose (access from topbar) bl_label = "Custom Icon" bl_parent_id = "VIEW3D_PT_tools_brush_display" bl_options = {'DEFAULT_CLOSED'} def draw_header(self, context): settings = self.paint_settings(context) brush = settings.brush self.layout.prop(brush, "use_custom_icon", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = self.paint_settings(context) brush = settings.brush col = layout.column() col.active = brush.use_custom_icon col.prop(brush, "icon_filepath", text="") # ********** default tools for weight-paint **************** # TODO, move to space_view3d.py class VIEW3D_PT_tools_weightpaint_symmetry(Panel, View3DPaintPanel): bl_context = ".weightpaint" bl_options = {'DEFAULT_CLOSED'} bl_label = "Symmetry" @classmethod def poll(cls, context): # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. return (context.region.type != 'TOOL_HEADER') def draw(self, context): layout = self.layout tool_settings = context.tool_settings wpaint = tool_settings.weight_paint draw_vpaint_symmetry(layout, wpaint) class VIEW3D_PT_tools_weightpaint_symmetry_for_topbar(Panel): bl_space_type = 'TOPBAR' bl_region_type = 'HEADER' bl_label = "Symmetry" draw = VIEW3D_PT_tools_weightpaint_symmetry.draw # TODO, move to space_view3d.py class VIEW3D_PT_tools_weightpaint_options(Panel, View3DPaintPanel): bl_context = ".weightpaint" bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings wpaint = tool_settings.weight_paint col = layout.column() col.prop(wpaint, "use_group_restrict") obj = context.weight_paint_object if obj.type == 'MESH': mesh = obj.data col.prop(mesh, "use_mirror_x") row = col.row() row.active = mesh.use_mirror_x row.prop(mesh, "use_mirror_topology") class VIEW3D_PT_tools_weightpaint_options_unified(Panel, View3DPaintPanel): bl_context = ".weightpaint" bl_label = "Unified Brush" bl_parent_id = "VIEW3D_PT_tools_weightpaint_options" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False self.unified_paint_settings(layout, context) # ********** default tools for vertex-paint **************** # TODO, move to space_view3d.py class VIEW3D_PT_tools_vertexpaint_options(Panel, View3DPaintPanel): bl_context = ".vertexpaint" # dot on purpose (access from topbar) bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.label(text="Unified Brush") layout.use_property_split = True layout.use_property_decorate = False self.unified_paint_settings(layout, context) # TODO, move to space_view3d.py class VIEW3D_PT_tools_vertexpaint_symmetry(Panel, View3DPaintPanel): bl_context = ".vertexpaint" # dot on purpose (access from topbar) bl_options = {'DEFAULT_CLOSED'} bl_label = "Symmetry" @classmethod def poll(cls, context): # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. return (context.region.type != 'TOOL_HEADER') def draw(self, context): layout = self.layout tool_settings = context.tool_settings vpaint = tool_settings.vertex_paint draw_vpaint_symmetry(layout, vpaint) class VIEW3D_PT_tools_vertexpaint_symmetry_for_topbar(Panel): bl_space_type = 'TOPBAR' bl_region_type = 'HEADER' bl_label = "Symmetry" draw = VIEW3D_PT_tools_vertexpaint_symmetry.draw # ********** default tools for texture-paint **************** # TODO, move to space_view3d.py class VIEW3D_PT_tools_imagepaint_options_external(Panel, View3DPaintPanel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "External" bl_parent_id = "VIEW3D_PT_tools_imagepaint_options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings ipaint = tool_settings.image_paint layout.prop(ipaint, "screen_grab_size", text="Screen Grab Size") layout.separator() flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) col = flow.column() col.operator("image.project_edit", text="Quick Edit") col = flow.column() col.operator("image.project_apply", text="Apply") col = flow.column() col.operator("paint.project_image", text="Apply Camera Image") # TODO, move to space_view3d.py class VIEW3D_PT_tools_imagepaint_symmetry(Panel, View3DPaintPanel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Symmetry" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. return (context.region.type != 'TOOL_HEADER') def draw(self, context): layout = self.layout tool_settings = context.tool_settings ipaint = tool_settings.image_paint split = layout.split() col = split.column() col.alignment = 'RIGHT' col.label(text="Mirror") col = split.column() row = col.row(align=True) row.prop(ipaint, "use_symmetry_x", text="X", toggle=True) row.prop(ipaint, "use_symmetry_y", text="Y", toggle=True) row.prop(ipaint, "use_symmetry_z", text="Z", toggle=True) # TODO, move to space_view3d.py class VIEW3D_PT_tools_imagepaint_options(View3DPaintPanel, Panel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): brush = context.tool_settings.image_paint.brush return (brush is not None) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.tool_settings ipaint = tool_settings.image_paint layout.prop(ipaint, "seam_bleed") layout.prop(ipaint, "dither", slider=True) flow = layout.grid_flow(row_major=True, columns=0, even_columns=True, even_rows=False, align=False) col = flow.column() col.prop(ipaint, "use_occlude") col = flow.column() col.prop(ipaint, "use_backface_culling", text="Backface Culling") class VIEW3D_PT_tools_imagepaint_options_unified(Panel, View3DPaintPanel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_parent_id = "VIEW3D_PT_tools_imagepaint_options" bl_label = "Unified Brush" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False self.unified_paint_settings(layout, context) class VIEW3D_PT_tools_imagepaint_options_cavity(View3DPaintPanel, Panel): bl_context = ".imagepaint" # dot on purpose (access from topbar) bl_label = "Cavity Mask" bl_parent_id = "VIEW3D_PT_tools_imagepaint_options" bl_options = {'DEFAULT_CLOSED'} def draw_header(self, context): tool_settings = context.tool_settings ipaint = tool_settings.image_paint self.layout.prop(ipaint, "use_cavity", text="") def draw(self, context): layout = self.layout tool_settings = context.tool_settings ipaint = tool_settings.image_paint layout.active = ipaint.use_cavity layout.template_curve_mapping(ipaint, "cavity_curve", brush=True, use_negative_slope=True) # TODO, move to space_view3d.py class VIEW3D_PT_imagepaint_options(View3DPaintPanel): bl_label = "Options" @classmethod def poll(cls, context): return (context.image_paint_object and context.tool_settings.image_paint) def draw(self, context): layout = self.layout col = layout.column() self.unified_paint_settings(col, context) class VIEW3D_MT_tools_projectpaint_stencil(Menu): bl_label = "Mask Layer" def draw(self, context): layout = self.layout for i, uv_layer in enumerate(context.active_object.data.uv_layers): props = layout.operator("wm.context_set_int", text=uv_layer.name, translate=False) props.data_path = "active_object.data.uv_layer_stencil_index" props.value = i # TODO, move to space_view3d.py class VIEW3D_PT_tools_particlemode_options(View3DPanel, Panel): """Default tools for particle mode""" bl_category = "Tool" bl_context = ".particlemode" bl_label = "Options" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False # No animation. pe = context.tool_settings.particle_edit ob = pe.object layout.prop(pe, "type", text="Editing Type") ptcache = None if pe.type == 'PARTICLES': if ob.particle_systems: if len(ob.particle_systems) > 1: layout.template_list("UI_UL_list", "particle_systems", ob, "particle_systems", ob.particle_systems, "active_index", rows=2, maxrows=3) ptcache = ob.particle_systems.active.point_cache else: for md in ob.modifiers: if md.type == pe.type: ptcache = md.point_cache if ptcache and len(ptcache.point_caches) > 1: layout.template_list("UI_UL_list", "particles_point_caches", ptcache, "point_caches", ptcache.point_caches, "active_index", rows=2, maxrows=3) if not pe.is_editable: layout.label(text="Point cache must be baked") layout.label(text="in memory to enable editing!") col = layout.column(align=True) col.active = pe.is_editable col.prop(ob.data, "use_mirror_x") col.separator() col.prop(pe, "use_preserve_length", text="Preserve Strand Lengths") col.prop(pe, "use_preserve_root", text="Preserve Root Positions") if not pe.is_hair: col.prop(pe, "use_auto_velocity", text="Auto-Velocity") class VIEW3D_PT_tools_particlemode_options_shapecut(View3DPanel, Panel): """Default tools for particle mode""" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_particlemode_options" bl_label = "Cut Particles to Shape" bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False # No animation. pe = context.tool_settings.particle_edit layout.prop(pe, "shape_object") layout.operator("particle.shape_cut", text="Cut") class VIEW3D_PT_tools_particlemode_options_display(View3DPanel, Panel): """Default tools for particle mode""" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_particlemode_options" bl_label = "Viewport Display" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False # No animation. pe = context.tool_settings.particle_edit col = layout.column() col.active = pe.is_editable col.prop(pe, "display_step", text="Path Steps") if pe.is_hair: col.prop(pe, "show_particles", text="Children") else: if pe.type == 'PARTICLES': col.prop(pe, "show_particles", text="Particles") col.prop(pe, "use_fade_time") sub = col.row(align=True) sub.active = pe.use_fade_time sub.prop(pe, "fade_frames", slider=True) # ********** grease pencil object tool panels **************** # Grease Pencil drawing brushes class VIEW3D_PT_tools_grease_pencil_brush(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Brush" bl_category = "Tool" @classmethod def poll(cls, context): is_3d_view = context.space_data.type == 'VIEW_3D' if is_3d_view: if context.gpencil_data is None: return False gpd = context.gpencil_data return bool(gpd.is_stroke_paint_mode) else: return True def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False tool_settings = context.scene.tool_settings gpencil_paint = tool_settings.gpencil_paint row = layout.row() col = row.column() col.template_ID_preview(gpencil_paint, "brush", new="brush.add_gpencil", rows=3, cols=8) col = row.column() brush = gpencil_paint.brush sub = col.column(align=True) sub.operator("gpencil.brush_presets_create", icon='PRESET_NEW', text="") if brush is not None: gp_settings = brush.gpencil_settings if brush.gpencil_tool in {'DRAW', 'FILL'}: row = layout.row(align=True) row_mat = row.row() if gp_settings.use_material_pin: row_mat.template_ID(gp_settings, "material", live_icon=True) else: row_mat.template_ID(context.active_object, "active_material", live_icon=True) row_mat.enabled = False # will otherwise allow to change material in active slot row.prop(gp_settings, "use_material_pin", text="") if not self.is_popover: from bl_ui.properties_paint_common import ( brush_basic_gpencil_paint_settings, ) tool = context.workspace.tools.from_space_view3d_mode(context.mode, create=False) brush_basic_gpencil_paint_settings(layout, context, brush, tool, compact=True, is_toolbar=False) # Grease Pencil drawing brushes options class VIEW3D_PT_tools_grease_pencil_brush_option(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Options" bl_category = "Tool" @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool not in {'ERASE', 'FILL'} def draw_header_preset(self, _context): VIEW3D_PT_gpencil_brush_presets.draw_panel_header(self.layout) def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False brush = context.tool_settings.gpencil_paint.brush if brush is not None: gp_settings = brush.gpencil_settings col = layout.column(align=True) col.prop(gp_settings, "input_samples") col.separator() col.prop(gp_settings, "active_smooth_factor") col.separator() col.prop(gp_settings, "angle", slider=True) col.prop(gp_settings, "angle_factor", text="Factor", slider=True) ob = context.object if ob and brush.gpencil_settings.use_material_pin is False: ma = ob.active_material elif brush.gpencil_settings.material: ma = brush.gpencil_settings.material else: ma = None col.separator() subcol = col.column(align=True) if ma and ma.grease_pencil.mode == 'LINE': subcol.enabled = False subcol.prop(gp_settings, "gradient_factor", slider=True) subcol.prop(gp_settings, "gradient_shape") class VIEW3D_PT_tools_grease_pencil_brush_stabilizer(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_parent_id = 'VIEW3D_PT_tools_grease_pencil_brush_option' bl_label = "Stabilize" bl_category = "Tool" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool == 'DRAW' def draw_header(self, context): brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings self.layout.prop(gp_settings, "use_settings_stabilizer", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.active = gp_settings.use_settings_stabilizer layout.prop(brush, "smooth_stroke_radius", text="Radius", slider=True) layout.prop(brush, "smooth_stroke_factor", text="Factor", slider=True) class VIEW3D_PT_tools_grease_pencil_brush_settings(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_parent_id = 'VIEW3D_PT_tools_grease_pencil_brush_option' bl_label = "Post-Processing" bl_category = "Tool" @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool != 'ERASE' def draw_header(self, context): brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings self.layout.prop(gp_settings, "use_settings_postprocess", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.active = gp_settings.use_settings_postprocess col = layout.column(align=True) col.prop(gp_settings, "pen_smooth_factor") col.prop(gp_settings, "pen_smooth_steps") col = layout.column(align=True) col.prop(gp_settings, "pen_thick_smooth_factor") col.prop(gp_settings, "pen_thick_smooth_steps", text="Iterations") col = layout.column(align=True) col.prop(gp_settings, "pen_subdivision_steps") col.prop(gp_settings, "random_subdiv", text="Randomness", slider=True) col = layout.column(align=True) col.prop(gp_settings, "simplify_factor") col = layout.column(align=True) col.prop(gp_settings, "trim") class VIEW3D_PT_tools_grease_pencil_brush_random(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_parent_id = 'VIEW3D_PT_tools_grease_pencil_brush_option' bl_label = "Randomize" bl_category = "Tool" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool != 'ERASE' def draw_header(self, context): brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings self.layout.prop(gp_settings, "use_settings_random", text="") def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.active = gp_settings.use_settings_random layout.prop(gp_settings, "random_pressure", text="Pressure", slider=True) layout.prop(gp_settings, "random_strength", text="Strength", slider=True) layout.prop(gp_settings, "uv_random", text="UV", slider=True) row = layout.row(align=True) row.prop(gp_settings, "pen_jitter", slider=True) row.prop(gp_settings, "use_jitter_pressure", text="", icon='STYLUS_PRESSURE') # Grease Pencil drawingcurves class VIEW3D_PT_tools_grease_pencil_brushcurves(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Curves" bl_category = "Tool" bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): brush = context.tool_settings.gpencil_paint.brush return brush is not None and brush.gpencil_tool not in {'ERASE', 'FILL'} def draw(self, context): pass class VIEW3D_PT_tools_grease_pencil_brushcurves_sensitivity(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Sensitivity" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_grease_pencil_brushcurves" def draw(self, context): layout = self.layout layout.use_property_split = True brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.template_curve_mapping(gp_settings, "curve_sensitivity", brush=True, use_negative_slope=True) class VIEW3D_PT_tools_grease_pencil_brushcurves_strength(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Strength" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_grease_pencil_brushcurves" def draw(self, context): layout = self.layout layout.use_property_split = True brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.template_curve_mapping(gp_settings, "curve_strength", brush=True, use_negative_slope=True) class VIEW3D_PT_tools_grease_pencil_brushcurves_jitter(View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Jitter" bl_category = "Tool" bl_parent_id = "VIEW3D_PT_tools_grease_pencil_brushcurves" def draw(self, context): layout = self.layout layout.use_property_split = True brush = context.tool_settings.gpencil_paint.brush gp_settings = brush.gpencil_settings layout.template_curve_mapping(gp_settings, "curve_jitter", brush=True, use_negative_slope=True) # Grease Pencil stroke editing tools class VIEW3D_PT_tools_grease_pencil_edit(GreasePencilStrokeEditPanel, Panel): bl_space_type = 'VIEW_3D' bl_category = "Tool" # Grease Pencil stroke interpolation tools class VIEW3D_PT_tools_grease_pencil_interpolate(Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'HEADER' bl_label = "Interpolate" @classmethod def poll(cls, context): if context.gpencil_data is None: return False gpd = context.gpencil_data return bool(context.editable_gpencil_strokes) and bool(gpd.use_stroke_edit_mode) def draw(self, context): layout = self.layout settings = context.tool_settings.gpencil_interpolate col = layout.column(align=True) col.label(text="Interpolate Strokes") col.operator("gpencil.interpolate", text="Interpolate") col.operator("gpencil.interpolate_sequence", text="Sequence") col.operator("gpencil.interpolate_reverse", text="Remove Breakdowns") col = layout.column(align=True) col.label(text="Options:") col.prop(settings, "interpolate_all_layers") col.prop(settings, "interpolate_selected_only") col = layout.column(align=True) col.label(text="Sequence Options:") col.prop(settings, "type") if settings.type == 'CUSTOM': # TODO: Options for loading/saving curve presets? col.template_curve_mapping(settings, "interpolation_curve", brush=True, use_negative_slope=True) elif settings.type != 'LINEAR': col.prop(settings, "easing") if settings.type == 'BACK': layout.prop(settings, "back") elif settings.type == 'ELASTIC': sub = layout.column(align=True) sub.prop(settings, "amplitude") sub.prop(settings, "period") # Grease Pencil stroke sculpting tools class VIEW3D_PT_tools_grease_pencil_sculpt(GreasePencilStrokeSculptPanel, View3DPanel, Panel): bl_context = ".greasepencil_sculpt" bl_category = "Tools" bl_label = "Brush" bl_category = "Tool" # Grease Pencil weight painting tools class VIEW3D_PT_tools_grease_pencil_weight_paint(View3DPanel, Panel): bl_context = ".greasepencil_weight" bl_category = "Tools" bl_label = "Brush" bl_category = "Tool" def draw(self, context): layout = self.layout layout.use_property_split = True layout.use_property_decorate = False settings = context.tool_settings.gpencil_sculpt brush = settings.brush layout.template_icon_view(settings, "weight_tool", show_labels=True) col = layout.column() if not self.is_popover: from bl_ui.properties_paint_common import ( brush_basic_gpencil_weight_settings, ) brush_basic_gpencil_weight_settings(col, context, brush) # Grease Pencil Brush Appearance (one for each mode) class VIEW3D_PT_tools_grease_pencil_paint_appearance(GreasePencilAppearancePanel, View3DPanel, Panel): bl_context = ".greasepencil_paint" bl_label = "Display" bl_category = "Tool" class VIEW3D_PT_tools_grease_pencil_sculpt_appearance(GreasePencilAppearancePanel, View3DPanel, Panel): bl_context = ".greasepencil_sculpt" bl_label = "Display" bl_category = "Tool" class VIEW3D_PT_tools_grease_pencil_sculpt_options(GreasePencilSculptOptionsPanel, View3DPanel, Panel): bl_context = ".greasepencil_sculpt" bl_label = "Sculpt Strokes" bl_parent_id = 'VIEW3D_PT_tools_grease_pencil_sculpt' bl_category = "Tool" class VIEW3D_PT_tools_grease_pencil_weight_appearance(GreasePencilAppearancePanel, View3DPanel, Panel): bl_context = ".greasepencil_weight" bl_label = "Display" bl_category = "Tool" class VIEW3D_PT_gpencil_brush_presets(PresetPanel, Panel): """Brush settings""" bl_label = "Brush Presets" preset_subdir = "gpencil_brush" preset_operator = "script.execute_preset" preset_add_operator = "scene.gpencil_brush_preset_add" classes = ( VIEW3D_MT_brush_context_menu, VIEW3D_MT_brush_context_menu_paint_modes, VIEW3D_PT_tools_object_options, VIEW3D_PT_tools_object_options_transform, VIEW3D_PT_tools_meshedit_options, VIEW3D_PT_tools_meshedit_options_automerge, VIEW3D_PT_tools_curveedit_options_stroke, VIEW3D_PT_tools_armatureedit_options, VIEW3D_PT_tools_posemode_options, VIEW3D_PT_slots_projectpaint, VIEW3D_PT_tools_brush, VIEW3D_PT_tools_brush_color, VIEW3D_PT_tools_brush_swatches, VIEW3D_PT_tools_brush_clone, VIEW3D_PT_tools_brush_options, TEXTURE_UL_texpaintslots, VIEW3D_MT_tools_projectpaint_uvlayer, VIEW3D_PT_stencil_projectpaint, VIEW3D_PT_tools_brush_texture, VIEW3D_PT_tools_mask_texture, VIEW3D_PT_tools_brush_stroke, VIEW3D_PT_tools_brush_stroke_smooth_stroke, VIEW3D_PT_tools_brush_falloff, VIEW3D_PT_tools_brush_falloff_frontface, VIEW3D_PT_tools_brush_falloff_normal, VIEW3D_PT_tools_brush_display, VIEW3D_PT_tools_brush_display_show_brush, VIEW3D_PT_tools_brush_display_custom_icon, VIEW3D_PT_sculpt_dyntopo, VIEW3D_PT_sculpt_dyntopo_remesh, VIEW3D_PT_sculpt_voxel_remesh, VIEW3D_PT_sculpt_symmetry, VIEW3D_PT_sculpt_symmetry_for_topbar, VIEW3D_PT_sculpt_options, VIEW3D_PT_sculpt_options_unified, VIEW3D_PT_sculpt_options_gravity, VIEW3D_PT_tools_weightpaint_symmetry, VIEW3D_PT_tools_weightpaint_symmetry_for_topbar, VIEW3D_PT_tools_weightpaint_options, VIEW3D_PT_tools_weightpaint_options_unified, VIEW3D_PT_tools_vertexpaint_symmetry, VIEW3D_PT_tools_vertexpaint_symmetry_for_topbar, VIEW3D_PT_tools_vertexpaint_options, VIEW3D_PT_tools_imagepaint_symmetry, VIEW3D_PT_tools_imagepaint_options, VIEW3D_PT_tools_imagepaint_options_cavity, VIEW3D_PT_tools_imagepaint_options_unified, VIEW3D_PT_tools_imagepaint_options_external, VIEW3D_MT_tools_projectpaint_stencil, VIEW3D_PT_tools_particlemode, VIEW3D_PT_tools_particlemode_options, VIEW3D_PT_tools_particlemode_options_shapecut, VIEW3D_PT_tools_particlemode_options_display, VIEW3D_PT_gpencil_brush_presets, VIEW3D_PT_tools_grease_pencil_brush, VIEW3D_PT_tools_grease_pencil_brush_option, VIEW3D_PT_tools_grease_pencil_brush_settings, VIEW3D_PT_tools_grease_pencil_brush_stabilizer, VIEW3D_PT_tools_grease_pencil_brush_random, VIEW3D_PT_tools_grease_pencil_brushcurves, VIEW3D_PT_tools_grease_pencil_brushcurves_sensitivity, VIEW3D_PT_tools_grease_pencil_brushcurves_strength, VIEW3D_PT_tools_grease_pencil_brushcurves_jitter, VIEW3D_PT_tools_grease_pencil_sculpt, VIEW3D_PT_tools_grease_pencil_weight_paint, VIEW3D_PT_tools_grease_pencil_paint_appearance, VIEW3D_PT_tools_grease_pencil_sculpt_options, VIEW3D_PT_tools_grease_pencil_sculpt_appearance, VIEW3D_PT_tools_grease_pencil_weight_appearance, VIEW3D_PT_tools_grease_pencil_interpolate, ) if __name__ == "__main__": # only for live edit. from bpy.utils import register_class for cls in classes: register_class(cls)
en
0.670043
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> # skip if no active brush # brush paint modes # brush tool # **************** standard tool clusters ****************** # Used by vertex & weight paint # Most of these panels should not be visible in GP edit modes # ********** default tools for object mode **************** # dot on purpose (access from topbar) # layout = self.layout # dot on purpose (access from topbar) # ********** default tools for editmode_mesh **************** # dot on purpose (access from topbar) # dot on purpose (access from topbar) # ********** default tools for editmode_curve **************** # dot on purpose (access from topbar) # ********** default tools for editmode_armature **************** # dot on purpose (access from topbar) # ********** default tools for pose-mode **************** # dot on purpose (access from topbar) # ********** default tools for paint modes **************** # dot on purpose (access from topbar) # No animation. # TODO, move to space_view3d.py # dot on purpose (access from topbar) # No animation. # Sculpt Mode # # normal_radius_factor # topology_rake_factor # auto_smooth_factor and use_inverse_smooth_pressure # normal_weight # crease_pinch_factor # rake_factor # plane_offset, use_offset_pressure, use_plane_trim, plane_trim # height # use_persistent, set_persistent_base # not supported yet for this case # Texture Paint Mode # # Weight Paint Mode # # Vertex Paint Mode # # dot on purpose (access from topbar) # dot on purpose (access from topbar) # dot on purpose (access from topbar) # dot on purpose (access from topbar) # No animation. # mat = data # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # dot on purpose (access from topbar) # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # dot on purpose (access from topbar) # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # dot on purpose (access from topbar) # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. # dot on purpose (access from topbar) # dot on purpose (access from topbar) # ********** default tools for weight-paint **************** # TODO, move to space_view3d.py # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. # TODO, move to space_view3d.py # ********** default tools for vertex-paint **************** # TODO, move to space_view3d.py # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. # ********** default tools for texture-paint **************** # TODO, move to space_view3d.py # dot on purpose (access from topbar) # TODO, move to space_view3d.py # dot on purpose (access from topbar) # When used in the tool header, this is explicitly included next to the XYZ symmetry buttons. # TODO, move to space_view3d.py # dot on purpose (access from topbar) # dot on purpose (access from topbar) # dot on purpose (access from topbar) # TODO, move to space_view3d.py # TODO, move to space_view3d.py Default tools for particle mode # No animation. Default tools for particle mode # No animation. Default tools for particle mode # No animation. # ********** grease pencil object tool panels **************** # Grease Pencil drawing brushes # will otherwise allow to change material in active slot # Grease Pencil drawing brushes options # Grease Pencil drawingcurves # Grease Pencil stroke editing tools # Grease Pencil stroke interpolation tools # TODO: Options for loading/saving curve presets? # Grease Pencil stroke sculpting tools # Grease Pencil weight painting tools # Grease Pencil Brush Appearance (one for each mode) Brush settings # only for live edit.
1.69388
2
samsungctl/__init__.py
bolesgb/samsungctl
0
6624329
<filename>samsungctl/__init__.py """Remote control Samsung televisions via TCP/IP connection""" from .remote import Remote __title__ = "samsungctl" __version__ = "0.7.1+1" __url__ = "https://github.com/bboles/samsungctl" __author__ = "<NAME> + <NAME>" __author_email__ = "<EMAIL>" __license__ = "MIT"
<filename>samsungctl/__init__.py """Remote control Samsung televisions via TCP/IP connection""" from .remote import Remote __title__ = "samsungctl" __version__ = "0.7.1+1" __url__ = "https://github.com/bboles/samsungctl" __author__ = "<NAME> + <NAME>" __author_email__ = "<EMAIL>" __license__ = "MIT"
en
0.546437
Remote control Samsung televisions via TCP/IP connection
1.589035
2
homeassistant/data_entry_flow.py
Natrinicle/home-assistant
0
6624330
<reponame>Natrinicle/home-assistant """Classes to help gather user submissions.""" import logging import uuid import voluptuous as vol from typing import Dict, Any, Callable, Hashable, List, Optional # noqa pylint: disable=unused-import from .core import callback, HomeAssistant from .exceptions import HomeAssistantError _LOGGER = logging.getLogger(__name__) RESULT_TYPE_FORM = 'form' RESULT_TYPE_CREATE_ENTRY = 'create_entry' RESULT_TYPE_ABORT = 'abort' class FlowError(HomeAssistantError): """Error while configuring an account.""" class UnknownHandler(FlowError): """Unknown handler specified.""" class UnknownFlow(FlowError): """Uknown flow specified.""" class UnknownStep(FlowError): """Unknown step specified.""" class FlowManager: """Manage all the flows that are in progress.""" def __init__(self, hass: HomeAssistant, async_create_flow: Callable, async_finish_flow: Callable) -> None: """Initialize the flow manager.""" self.hass = hass self._progress = {} # type: Dict[str, Any] self._async_create_flow = async_create_flow self._async_finish_flow = async_finish_flow @callback def async_progress(self) -> List[Dict]: """Return the flows in progress.""" return [{ 'flow_id': flow.flow_id, 'handler': flow.handler, 'context': flow.context, } for flow in self._progress.values()] async def async_init(self, handler: Hashable, *, context: Optional[Dict] = None, data: Any = None) -> Any: """Start a configuration flow.""" flow = await self._async_create_flow( handler, context=context, data=data) flow.hass = self.hass flow.handler = handler flow.flow_id = uuid.uuid4().hex flow.context = context self._progress[flow.flow_id] = flow return await self._async_handle_step(flow, flow.init_step, data) async def async_configure( self, flow_id: str, user_input: Optional[str] = None) -> Any: """Continue a configuration flow.""" flow = self._progress.get(flow_id) if flow is None: raise UnknownFlow step_id, data_schema = flow.cur_step if data_schema is not None and user_input is not None: user_input = data_schema(user_input) return await self._async_handle_step( flow, step_id, user_input) @callback def async_abort(self, flow_id: str) -> None: """Abort a flow.""" if self._progress.pop(flow_id, None) is None: raise UnknownFlow async def _async_handle_step(self, flow: Any, step_id: str, user_input: Optional[str]) -> Dict: """Handle a step of a flow.""" method = "async_step_{}".format(step_id) if not hasattr(flow, method): self._progress.pop(flow.flow_id) raise UnknownStep("Handler {} doesn't support step {}".format( flow.__class__.__name__, step_id)) result = await getattr(flow, method)(user_input) # type: Dict if result['type'] not in (RESULT_TYPE_FORM, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_ABORT): raise ValueError( 'Handler returned incorrect type: {}'.format(result['type'])) if result['type'] == RESULT_TYPE_FORM: flow.cur_step = (result['step_id'], result['data_schema']) return result # Abort and Success results both finish the flow self._progress.pop(flow.flow_id) # We pass a copy of the result because we're mutating our version entry = await self._async_finish_flow(flow.context, dict(result)) if result['type'] == RESULT_TYPE_CREATE_ENTRY: result['result'] = entry return result class FlowHandler: """Handle the configuration flow of a component.""" # Set by flow manager flow_id = None hass = None handler = None cur_step = None context = None # Set by _async_create_flow callback init_step = 'init' # Set by developer VERSION = 1 @callback def async_show_form(self, *, step_id: str, data_schema: vol.Schema = None, errors: Optional[Dict] = None, description_placeholders: Optional[Dict] = None) \ -> Dict: """Return the definition of a form to gather user input.""" return { 'type': RESULT_TYPE_FORM, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': step_id, 'data_schema': data_schema, 'errors': errors, 'description_placeholders': description_placeholders, } @callback def async_create_entry(self, *, title: str, data: Dict) -> Dict: """Finish config flow and create a config entry.""" return { 'version': self.VERSION, 'type': RESULT_TYPE_CREATE_ENTRY, 'flow_id': self.flow_id, 'handler': self.handler, 'title': title, 'data': data, } @callback def async_abort(self, *, reason: str) -> Dict: """Abort the config flow.""" return { 'type': RESULT_TYPE_ABORT, 'flow_id': self.flow_id, 'handler': self.handler, 'reason': reason }
"""Classes to help gather user submissions.""" import logging import uuid import voluptuous as vol from typing import Dict, Any, Callable, Hashable, List, Optional # noqa pylint: disable=unused-import from .core import callback, HomeAssistant from .exceptions import HomeAssistantError _LOGGER = logging.getLogger(__name__) RESULT_TYPE_FORM = 'form' RESULT_TYPE_CREATE_ENTRY = 'create_entry' RESULT_TYPE_ABORT = 'abort' class FlowError(HomeAssistantError): """Error while configuring an account.""" class UnknownHandler(FlowError): """Unknown handler specified.""" class UnknownFlow(FlowError): """Uknown flow specified.""" class UnknownStep(FlowError): """Unknown step specified.""" class FlowManager: """Manage all the flows that are in progress.""" def __init__(self, hass: HomeAssistant, async_create_flow: Callable, async_finish_flow: Callable) -> None: """Initialize the flow manager.""" self.hass = hass self._progress = {} # type: Dict[str, Any] self._async_create_flow = async_create_flow self._async_finish_flow = async_finish_flow @callback def async_progress(self) -> List[Dict]: """Return the flows in progress.""" return [{ 'flow_id': flow.flow_id, 'handler': flow.handler, 'context': flow.context, } for flow in self._progress.values()] async def async_init(self, handler: Hashable, *, context: Optional[Dict] = None, data: Any = None) -> Any: """Start a configuration flow.""" flow = await self._async_create_flow( handler, context=context, data=data) flow.hass = self.hass flow.handler = handler flow.flow_id = uuid.uuid4().hex flow.context = context self._progress[flow.flow_id] = flow return await self._async_handle_step(flow, flow.init_step, data) async def async_configure( self, flow_id: str, user_input: Optional[str] = None) -> Any: """Continue a configuration flow.""" flow = self._progress.get(flow_id) if flow is None: raise UnknownFlow step_id, data_schema = flow.cur_step if data_schema is not None and user_input is not None: user_input = data_schema(user_input) return await self._async_handle_step( flow, step_id, user_input) @callback def async_abort(self, flow_id: str) -> None: """Abort a flow.""" if self._progress.pop(flow_id, None) is None: raise UnknownFlow async def _async_handle_step(self, flow: Any, step_id: str, user_input: Optional[str]) -> Dict: """Handle a step of a flow.""" method = "async_step_{}".format(step_id) if not hasattr(flow, method): self._progress.pop(flow.flow_id) raise UnknownStep("Handler {} doesn't support step {}".format( flow.__class__.__name__, step_id)) result = await getattr(flow, method)(user_input) # type: Dict if result['type'] not in (RESULT_TYPE_FORM, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_ABORT): raise ValueError( 'Handler returned incorrect type: {}'.format(result['type'])) if result['type'] == RESULT_TYPE_FORM: flow.cur_step = (result['step_id'], result['data_schema']) return result # Abort and Success results both finish the flow self._progress.pop(flow.flow_id) # We pass a copy of the result because we're mutating our version entry = await self._async_finish_flow(flow.context, dict(result)) if result['type'] == RESULT_TYPE_CREATE_ENTRY: result['result'] = entry return result class FlowHandler: """Handle the configuration flow of a component.""" # Set by flow manager flow_id = None hass = None handler = None cur_step = None context = None # Set by _async_create_flow callback init_step = 'init' # Set by developer VERSION = 1 @callback def async_show_form(self, *, step_id: str, data_schema: vol.Schema = None, errors: Optional[Dict] = None, description_placeholders: Optional[Dict] = None) \ -> Dict: """Return the definition of a form to gather user input.""" return { 'type': RESULT_TYPE_FORM, 'flow_id': self.flow_id, 'handler': self.handler, 'step_id': step_id, 'data_schema': data_schema, 'errors': errors, 'description_placeholders': description_placeholders, } @callback def async_create_entry(self, *, title: str, data: Dict) -> Dict: """Finish config flow and create a config entry.""" return { 'version': self.VERSION, 'type': RESULT_TYPE_CREATE_ENTRY, 'flow_id': self.flow_id, 'handler': self.handler, 'title': title, 'data': data, } @callback def async_abort(self, *, reason: str) -> Dict: """Abort the config flow.""" return { 'type': RESULT_TYPE_ABORT, 'flow_id': self.flow_id, 'handler': self.handler, 'reason': reason }
en
0.834911
Classes to help gather user submissions. # noqa pylint: disable=unused-import Error while configuring an account. Unknown handler specified. Uknown flow specified. Unknown step specified. Manage all the flows that are in progress. Initialize the flow manager. # type: Dict[str, Any] Return the flows in progress. Start a configuration flow. Continue a configuration flow. Abort a flow. Handle a step of a flow. # type: Dict # Abort and Success results both finish the flow # We pass a copy of the result because we're mutating our version Handle the configuration flow of a component. # Set by flow manager # Set by _async_create_flow callback # Set by developer Return the definition of a form to gather user input. Finish config flow and create a config entry. Abort the config flow.
2.58532
3
nssrc/com/citrix/netscaler/nitro/resource/config/videooptimization/videooptimizationpacingpolicylabel_binding.py
guardicore/nitro-python
0
6624331
# # Copyright (c) 2021 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class videooptimizationpacingpolicylabel_binding(base_resource): """ Binding class showing the resources that can be bound to videooptimizationpacingpolicylabel_binding. """ def __init__(self) : self._labelname = None self.videooptimizationpacingpolicylabel_videooptimizationpacingpolicy_binding = [] self.videooptimizationpacingpolicylabel_policybinding_binding = [] @property def labelname(self) : r"""Name of the videooptimization pacing policy label. """ try : return self._labelname except Exception as e: raise e @labelname.setter def labelname(self, labelname) : r"""Name of the videooptimization pacing policy label. """ try : self._labelname = labelname except Exception as e: raise e @property def videooptimizationpacingpolicylabel_policybinding_bindings(self) : r"""policybinding that can be bound to videooptimizationpacingpolicylabel. """ try : return self._videooptimizationpacingpolicylabel_policybinding_binding except Exception as e: raise e @property def videooptimizationpacingpolicylabel_videooptimizationpacingpolicy_bindings(self) : r"""videooptimizationpacingpolicy that can be bound to videooptimizationpacingpolicylabel. """ try : return self._videooptimizationpacingpolicylabel_videooptimizationpacingpolicy_binding except Exception as e: raise e def _get_nitro_response(self, service, response) : r""" converts nitro response into object and returns the object array in case of get request. """ try : result = service.payload_formatter.string_to_resource(videooptimizationpacingpolicylabel_binding_response, response, self.__class__.__name__) if(result.errorcode != 0) : if (result.errorcode == 444) : service.clear_session(self) if result.severity : if (result.severity == "ERROR") : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) else : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) return result.videooptimizationpacingpolicylabel_binding except Exception as e : raise e def _get_object_name(self) : r""" Returns the value of object identifier argument """ try : if self.labelname is not None : return str(self.labelname) return None except Exception as e : raise e @classmethod def get(self, service, labelname="", option_="") : r""" Use this API to fetch videooptimizationpacingpolicylabel_binding resource. """ try : if not labelname : obj = videooptimizationpacingpolicylabel_binding() response = obj.get_resources(service, option_) elif type(labelname) is not list : obj = videooptimizationpacingpolicylabel_binding() obj.labelname = labelname response = obj.get_resource(service) else : if labelname and len(labelname) > 0 : obj = [videooptimizationpacingpolicylabel_binding() for _ in range(len(labelname))] for i in range(len(labelname)) : obj[i].labelname = labelname[i]; response[i] = obj[i].get_resource(service) return response except Exception as e: raise e class videooptimizationpacingpolicylabel_binding_response(base_response) : def __init__(self, length=1) : self.videooptimizationpacingpolicylabel_binding = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.videooptimizationpacingpolicylabel_binding = [videooptimizationpacingpolicylabel_binding() for _ in range(length)]
# # Copyright (c) 2021 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class videooptimizationpacingpolicylabel_binding(base_resource): """ Binding class showing the resources that can be bound to videooptimizationpacingpolicylabel_binding. """ def __init__(self) : self._labelname = None self.videooptimizationpacingpolicylabel_videooptimizationpacingpolicy_binding = [] self.videooptimizationpacingpolicylabel_policybinding_binding = [] @property def labelname(self) : r"""Name of the videooptimization pacing policy label. """ try : return self._labelname except Exception as e: raise e @labelname.setter def labelname(self, labelname) : r"""Name of the videooptimization pacing policy label. """ try : self._labelname = labelname except Exception as e: raise e @property def videooptimizationpacingpolicylabel_policybinding_bindings(self) : r"""policybinding that can be bound to videooptimizationpacingpolicylabel. """ try : return self._videooptimizationpacingpolicylabel_policybinding_binding except Exception as e: raise e @property def videooptimizationpacingpolicylabel_videooptimizationpacingpolicy_bindings(self) : r"""videooptimizationpacingpolicy that can be bound to videooptimizationpacingpolicylabel. """ try : return self._videooptimizationpacingpolicylabel_videooptimizationpacingpolicy_binding except Exception as e: raise e def _get_nitro_response(self, service, response) : r""" converts nitro response into object and returns the object array in case of get request. """ try : result = service.payload_formatter.string_to_resource(videooptimizationpacingpolicylabel_binding_response, response, self.__class__.__name__) if(result.errorcode != 0) : if (result.errorcode == 444) : service.clear_session(self) if result.severity : if (result.severity == "ERROR") : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) else : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) return result.videooptimizationpacingpolicylabel_binding except Exception as e : raise e def _get_object_name(self) : r""" Returns the value of object identifier argument """ try : if self.labelname is not None : return str(self.labelname) return None except Exception as e : raise e @classmethod def get(self, service, labelname="", option_="") : r""" Use this API to fetch videooptimizationpacingpolicylabel_binding resource. """ try : if not labelname : obj = videooptimizationpacingpolicylabel_binding() response = obj.get_resources(service, option_) elif type(labelname) is not list : obj = videooptimizationpacingpolicylabel_binding() obj.labelname = labelname response = obj.get_resource(service) else : if labelname and len(labelname) > 0 : obj = [videooptimizationpacingpolicylabel_binding() for _ in range(len(labelname))] for i in range(len(labelname)) : obj[i].labelname = labelname[i]; response[i] = obj[i].get_resource(service) return response except Exception as e: raise e class videooptimizationpacingpolicylabel_binding_response(base_response) : def __init__(self, length=1) : self.videooptimizationpacingpolicylabel_binding = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.videooptimizationpacingpolicylabel_binding = [videooptimizationpacingpolicylabel_binding() for _ in range(length)]
en
0.78468
# # Copyright (c) 2021 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Binding class showing the resources that can be bound to videooptimizationpacingpolicylabel_binding. Name of the videooptimization pacing policy label. Name of the videooptimization pacing policy label. policybinding that can be bound to videooptimizationpacingpolicylabel. videooptimizationpacingpolicy that can be bound to videooptimizationpacingpolicylabel. converts nitro response into object and returns the object array in case of get request. Returns the value of object identifier argument Use this API to fetch videooptimizationpacingpolicylabel_binding resource.
1.820405
2
jsb/plugs/common/tinyurl.py
NURDspace/jsonbot
1
6624332
# jsb/plugs/common/tinyurl.py # # """ tinyurl.com feeder """ __author__ = "Wijnand 'tehmaze' Modderman - http://tehmaze.com" __license__ = 'BSD' ## jsb imports from jsb.lib.commands import cmnds from jsb.utils.url import striphtml, useragent from jsb.lib.examples import examples from jsb.utils.exception import handle_exception from jsb.lib.persistconfig import PersistConfig from jsb.lib.cache import get, set ## plug config plugcfg = PersistConfig() plugcfg.define("url", 'http://tinyurl.com/create.php') ## simpljejson from jsb.imports import getjson json = getjson() ## basic imports import urllib import urllib2 import urlparse import re import logging ## defines re_url_match = re.compile(u'((?:http|https)://\S+)') urlcache = {} ## functions def valid_url(url): """ check if url is valid """ if not re_url_match.search(url): return False parts = urlparse.urlparse(url) cleanurl = '%s://%s' % (parts[0], parts[1]) if parts[2]: cleanurl = '%s%s' % (cleanurl, parts[2]) if parts[3]: cleanurl = '%s;%s' % (cleanurl, parts[3]) if parts[4]: cleanurl = '%s?%s' % (cleanurl, parts[4]) return cleanurl ## callbacks def precb(bot, ievent): test_url = re_url_match.search(ievent.txt) if test_url: return True def privmsgcb(bot, ievent): """ callback for urlcaching """ test_url = re_url_match.search(ievent.txt) if test_url: url = test_url.group(1) if not urlcache.has_key(bot.cfg.name): urlcache[bot.cfg.name] = {} urlcache[bot.cfg.name][ievent.target] = url # not enabled right now #callbacks.add('PRIVMSG', privmsgcb, precb) def get_tinyurl(url): """ grab a tinyurl. """ res = get(url, namespace='tinyurl') ; logging.debug('tinyurl - cache - %s' % unicode(res)) if res and res[0] == '[': return json.loads(res) postarray = [ ('submit', 'submit'), ('url', url), ] postdata = urllib.urlencode(postarray) req = urllib2.Request(url=plugcfg.url, data=postdata) req.add_header('User-agent', useragent()) try: res = urllib2.urlopen(req).readlines() except urllib2.URLError, e: logging.warn('tinyurl - %s - URLError: %s' % (url, str(e))) ; return except urllib2.HTTPError, e: logging.warn('tinyurl - %s - HTTP error: %s' % (url, str(e))) ; return except Exception, ex: if "DownloadError" in str(ex): logging.warn('tinyurl - %s - DownloadError: %s' % (url, str(e))) else: handle_exception() return urls = [] for line in res: if line.startswith('<blockquote><b>'): urls.append(striphtml(line.strip()).split('[Open')[0]) if len(urls) == 3: urls.pop(0) set(url, json.dumps(urls), namespace='tinyurl') return urls ## tinyurl command def handle_tinyurl(bot, ievent): """ arguments: <url> - get tinyurl from provided url. """ if not ievent.rest and (not urlcache.has_key(bot.cfg.name) or not urlcache[bot.cfg.name].has_key(ievent.target)): ievent.missing('<url>') return elif not ievent.rest: url = urlcache[bot.cfg.name][ievent.target] else: url = ievent.rest url = valid_url(url) if not url: ievent.reply('invalid or bad URL') ; return tinyurl = get_tinyurl(url) if tinyurl: ievent.reply(' .. '.join(tinyurl)) else: ievent.reply('failed to create tinyurl') cmnds.add('tinyurl', handle_tinyurl, ['OPER', 'USER', 'GUEST'], threaded=True) examples.add('tinyurl', 'show a tinyurl', 'tinyurl http://jsonbbot.org')
# jsb/plugs/common/tinyurl.py # # """ tinyurl.com feeder """ __author__ = "Wijnand 'tehmaze' Modderman - http://tehmaze.com" __license__ = 'BSD' ## jsb imports from jsb.lib.commands import cmnds from jsb.utils.url import striphtml, useragent from jsb.lib.examples import examples from jsb.utils.exception import handle_exception from jsb.lib.persistconfig import PersistConfig from jsb.lib.cache import get, set ## plug config plugcfg = PersistConfig() plugcfg.define("url", 'http://tinyurl.com/create.php') ## simpljejson from jsb.imports import getjson json = getjson() ## basic imports import urllib import urllib2 import urlparse import re import logging ## defines re_url_match = re.compile(u'((?:http|https)://\S+)') urlcache = {} ## functions def valid_url(url): """ check if url is valid """ if not re_url_match.search(url): return False parts = urlparse.urlparse(url) cleanurl = '%s://%s' % (parts[0], parts[1]) if parts[2]: cleanurl = '%s%s' % (cleanurl, parts[2]) if parts[3]: cleanurl = '%s;%s' % (cleanurl, parts[3]) if parts[4]: cleanurl = '%s?%s' % (cleanurl, parts[4]) return cleanurl ## callbacks def precb(bot, ievent): test_url = re_url_match.search(ievent.txt) if test_url: return True def privmsgcb(bot, ievent): """ callback for urlcaching """ test_url = re_url_match.search(ievent.txt) if test_url: url = test_url.group(1) if not urlcache.has_key(bot.cfg.name): urlcache[bot.cfg.name] = {} urlcache[bot.cfg.name][ievent.target] = url # not enabled right now #callbacks.add('PRIVMSG', privmsgcb, precb) def get_tinyurl(url): """ grab a tinyurl. """ res = get(url, namespace='tinyurl') ; logging.debug('tinyurl - cache - %s' % unicode(res)) if res and res[0] == '[': return json.loads(res) postarray = [ ('submit', 'submit'), ('url', url), ] postdata = urllib.urlencode(postarray) req = urllib2.Request(url=plugcfg.url, data=postdata) req.add_header('User-agent', useragent()) try: res = urllib2.urlopen(req).readlines() except urllib2.URLError, e: logging.warn('tinyurl - %s - URLError: %s' % (url, str(e))) ; return except urllib2.HTTPError, e: logging.warn('tinyurl - %s - HTTP error: %s' % (url, str(e))) ; return except Exception, ex: if "DownloadError" in str(ex): logging.warn('tinyurl - %s - DownloadError: %s' % (url, str(e))) else: handle_exception() return urls = [] for line in res: if line.startswith('<blockquote><b>'): urls.append(striphtml(line.strip()).split('[Open')[0]) if len(urls) == 3: urls.pop(0) set(url, json.dumps(urls), namespace='tinyurl') return urls ## tinyurl command def handle_tinyurl(bot, ievent): """ arguments: <url> - get tinyurl from provided url. """ if not ievent.rest and (not urlcache.has_key(bot.cfg.name) or not urlcache[bot.cfg.name].has_key(ievent.target)): ievent.missing('<url>') return elif not ievent.rest: url = urlcache[bot.cfg.name][ievent.target] else: url = ievent.rest url = valid_url(url) if not url: ievent.reply('invalid or bad URL') ; return tinyurl = get_tinyurl(url) if tinyurl: ievent.reply(' .. '.join(tinyurl)) else: ievent.reply('failed to create tinyurl') cmnds.add('tinyurl', handle_tinyurl, ['OPER', 'USER', 'GUEST'], threaded=True) examples.add('tinyurl', 'show a tinyurl', 'tinyurl http://jsonbbot.org')
en
0.242603
# jsb/plugs/common/tinyurl.py # # tinyurl.com feeder ## jsb imports ## plug config ## simpljejson ## basic imports ## defines ## functions check if url is valid ## callbacks callback for urlcaching # not enabled right now #callbacks.add('PRIVMSG', privmsgcb, precb) grab a tinyurl. ## tinyurl command arguments: <url> - get tinyurl from provided url.
2.194623
2
ee/clickhouse/models/action.py
tmilicic/posthog
0
6624333
<reponame>tmilicic/posthog import re from typing import Dict, List, Tuple from django.forms.models import model_to_dict from posthog.constants import AUTOCAPTURE_EVENT, TREND_FILTER_TYPE_ACTIONS from posthog.models import Action, Entity, Filter from posthog.models.action_step import ActionStep from posthog.models.event import Selector def format_action_filter(action: Action, prepend: str = "action", index=0, use_loop: bool = False) -> Tuple[str, Dict]: # get action steps params = {"team_id": action.team.pk} steps = action.steps.all() if len(steps) == 0: # If no steps, it shouldn't match this part of the query return "1=2", {} or_queries = [] for index, step in enumerate(steps): conditions: List[str] = [] # filter element if step.event == AUTOCAPTURE_EVENT: el_conditions, element_params = filter_element(step, "{}{}".format(index, prepend)) params = {**params, **element_params} conditions += el_conditions # filter event conditions (ie URL) event_conditions, event_params = filter_event(step, "{}{}".format(index, prepend), index) params = {**params, **event_params} conditions += event_conditions if step.properties: from ee.clickhouse.models.property import parse_prop_clauses prop_query, prop_params = parse_prop_clauses( Filter(data={"properties": step.properties}).properties, action.team.pk, prepend="action_props_{}".format(index), ) conditions.append(prop_query.replace("AND", "", 1)) params = {**params, **prop_params} if len(conditions) > 0: or_queries.append(" AND ".join(conditions)) if use_loop: formatted_query = "SELECT uuid FROM events WHERE {} AND team_id = %(team_id)s".format( ") OR uuid IN (SELECT uuid FROM events WHERE team_id = %(team_id)s AND ".join(or_queries) ) else: formatted_query = "(({}))".format(") OR (".join(or_queries)) return formatted_query, params def filter_event(step: ActionStep, prepend: str = "event", index: int = 0) -> Tuple[List[str], Dict]: params = {"{}_{}".format(prepend, index): step.event} conditions = [] if step.url: if step.url_matching == ActionStep.EXACT: conditions.append( "JSONExtractString(properties, '$current_url') = %({}_prop_val_{})s".format(prepend, index) ) params.update({"{}_prop_val_{}".format(prepend, index): step.url}) elif step.url_matching == ActionStep.REGEX: conditions.append( "match(JSONExtractString(properties, '$current_url'), %({}_prop_val_{})s)".format(prepend, index) ) params.update({"{}_prop_val_{}".format(prepend, index): step.url}) else: conditions.append( "JSONExtractString(properties, '$current_url') LIKE %({}_prop_val_{})s".format(prepend, index) ) params.update({"{}_prop_val_{}".format(prepend, index): "%" + step.url + "%"}) conditions.append("event = %({}_{})s".format(prepend, index)) return conditions, params def _create_regex(selector: Selector) -> str: regex = r"" for idx, tag in enumerate(selector.parts): if tag.data.get("tag_name") and isinstance(tag.data["tag_name"], str): if tag.data["tag_name"] == "*": regex += ".+" else: regex += tag.data["tag_name"] if tag.data.get("attr_class__contains"): regex += r".*?\.{}".format(r"\..*?".join(sorted(tag.data["attr_class__contains"]))) if tag.ch_attributes: regex += ".*?" for key, value in sorted(tag.ch_attributes.items()): regex += '{}="{}".*?'.format(key, value) regex += r"([-_a-zA-Z0-9\.]*?)?($|;|:([^;^\s]*(;|$|\s)))" if tag.direct_descendant: regex += ".*" return regex def filter_element(step: ActionStep, prepend: str = "") -> Tuple[List[str], Dict]: filters = model_to_dict(step) params = {} conditions = [] if filters.get("selector"): selector = Selector(filters["selector"], escape_slashes=False) params["{}selector_regex".format(prepend)] = _create_regex(selector) conditions.append("match(elements_chain, %({}selector_regex)s)".format(prepend)) if filters.get("tag_name"): params["{}tag_name_regex".format(prepend)] = r"(^|;){}(\.|$|;|:)".format(filters["tag_name"]) conditions.append("match(elements_chain, %({}tag_name_regex)s)".format(prepend)) attributes: Dict[str, str] = {} for key in ["href", "text"]: if filters.get(key): attributes[key] = re.escape(filters[key]) if len(attributes.keys()) > 0: params["{}attributes_regex".format(prepend)] = ".*?({}).*?".format( ".*?".join(['{}="{}"'.format(key, value) for key, value in attributes.items()]) ) conditions.append("match(elements_chain, %({}attributes_regex)s)".format(prepend)) return (conditions, params) def format_entity_filter(entity: Entity, prepend: str = "action") -> Tuple[str, Dict]: if entity.type == TREND_FILTER_TYPE_ACTIONS: try: action = Action.objects.get(pk=entity.id) entity_filter, params = format_action_filter(action, prepend=prepend) except Action.DoesNotExist: raise ValueError("This action does not exist") else: entity_filter = "event = %(event)s" params = {"event": entity.id} return entity_filter, params
import re from typing import Dict, List, Tuple from django.forms.models import model_to_dict from posthog.constants import AUTOCAPTURE_EVENT, TREND_FILTER_TYPE_ACTIONS from posthog.models import Action, Entity, Filter from posthog.models.action_step import ActionStep from posthog.models.event import Selector def format_action_filter(action: Action, prepend: str = "action", index=0, use_loop: bool = False) -> Tuple[str, Dict]: # get action steps params = {"team_id": action.team.pk} steps = action.steps.all() if len(steps) == 0: # If no steps, it shouldn't match this part of the query return "1=2", {} or_queries = [] for index, step in enumerate(steps): conditions: List[str] = [] # filter element if step.event == AUTOCAPTURE_EVENT: el_conditions, element_params = filter_element(step, "{}{}".format(index, prepend)) params = {**params, **element_params} conditions += el_conditions # filter event conditions (ie URL) event_conditions, event_params = filter_event(step, "{}{}".format(index, prepend), index) params = {**params, **event_params} conditions += event_conditions if step.properties: from ee.clickhouse.models.property import parse_prop_clauses prop_query, prop_params = parse_prop_clauses( Filter(data={"properties": step.properties}).properties, action.team.pk, prepend="action_props_{}".format(index), ) conditions.append(prop_query.replace("AND", "", 1)) params = {**params, **prop_params} if len(conditions) > 0: or_queries.append(" AND ".join(conditions)) if use_loop: formatted_query = "SELECT uuid FROM events WHERE {} AND team_id = %(team_id)s".format( ") OR uuid IN (SELECT uuid FROM events WHERE team_id = %(team_id)s AND ".join(or_queries) ) else: formatted_query = "(({}))".format(") OR (".join(or_queries)) return formatted_query, params def filter_event(step: ActionStep, prepend: str = "event", index: int = 0) -> Tuple[List[str], Dict]: params = {"{}_{}".format(prepend, index): step.event} conditions = [] if step.url: if step.url_matching == ActionStep.EXACT: conditions.append( "JSONExtractString(properties, '$current_url') = %({}_prop_val_{})s".format(prepend, index) ) params.update({"{}_prop_val_{}".format(prepend, index): step.url}) elif step.url_matching == ActionStep.REGEX: conditions.append( "match(JSONExtractString(properties, '$current_url'), %({}_prop_val_{})s)".format(prepend, index) ) params.update({"{}_prop_val_{}".format(prepend, index): step.url}) else: conditions.append( "JSONExtractString(properties, '$current_url') LIKE %({}_prop_val_{})s".format(prepend, index) ) params.update({"{}_prop_val_{}".format(prepend, index): "%" + step.url + "%"}) conditions.append("event = %({}_{})s".format(prepend, index)) return conditions, params def _create_regex(selector: Selector) -> str: regex = r"" for idx, tag in enumerate(selector.parts): if tag.data.get("tag_name") and isinstance(tag.data["tag_name"], str): if tag.data["tag_name"] == "*": regex += ".+" else: regex += tag.data["tag_name"] if tag.data.get("attr_class__contains"): regex += r".*?\.{}".format(r"\..*?".join(sorted(tag.data["attr_class__contains"]))) if tag.ch_attributes: regex += ".*?" for key, value in sorted(tag.ch_attributes.items()): regex += '{}="{}".*?'.format(key, value) regex += r"([-_a-zA-Z0-9\.]*?)?($|;|:([^;^\s]*(;|$|\s)))" if tag.direct_descendant: regex += ".*" return regex def filter_element(step: ActionStep, prepend: str = "") -> Tuple[List[str], Dict]: filters = model_to_dict(step) params = {} conditions = [] if filters.get("selector"): selector = Selector(filters["selector"], escape_slashes=False) params["{}selector_regex".format(prepend)] = _create_regex(selector) conditions.append("match(elements_chain, %({}selector_regex)s)".format(prepend)) if filters.get("tag_name"): params["{}tag_name_regex".format(prepend)] = r"(^|;){}(\.|$|;|:)".format(filters["tag_name"]) conditions.append("match(elements_chain, %({}tag_name_regex)s)".format(prepend)) attributes: Dict[str, str] = {} for key in ["href", "text"]: if filters.get(key): attributes[key] = re.escape(filters[key]) if len(attributes.keys()) > 0: params["{}attributes_regex".format(prepend)] = ".*?({}).*?".format( ".*?".join(['{}="{}"'.format(key, value) for key, value in attributes.items()]) ) conditions.append("match(elements_chain, %({}attributes_regex)s)".format(prepend)) return (conditions, params) def format_entity_filter(entity: Entity, prepend: str = "action") -> Tuple[str, Dict]: if entity.type == TREND_FILTER_TYPE_ACTIONS: try: action = Action.objects.get(pk=entity.id) entity_filter, params = format_action_filter(action, prepend=prepend) except Action.DoesNotExist: raise ValueError("This action does not exist") else: entity_filter = "event = %(event)s" params = {"event": entity.id} return entity_filter, params
en
0.801444
# get action steps # If no steps, it shouldn't match this part of the query # filter element # filter event conditions (ie URL)
2.045673
2
Assignment_1/163059009.py
SeeTheC/Machine-Learning
0
6624334
# coding: utf-8 # In[3]: print("Hello bye"); row=list(); ft=open("train.csv"); data=ft.read(); print(data); # In[10]: import numpy as np; from numpy.linalg import inv; from numpy.linalg import det; import math; trainDSSizePercentage=0.7; # x*100 percentage. 1-x data set will be used for validating # Will read the file and convert it into two dataset one train data other validate data def readTrainData(fileName): row_index=0; phi=list(); y=list(); with open(fileName) as f: for line in f: if row_index >0: phi_i=list((float(n) for n in line.split('\n')[0].split(",") )); phi_i[0]=1; # last row is value of yi y_i=phi_i.pop(len(phi_i)-1); phi.append(phi_i); y.append(y_i); row_index+=1; return [phi,y]; #End-readTrainData # Will read the file and convert it into dataset for Testing the Model def readTestData(fileName): row_index=0; phi=list(); y=list(); with open(fileName) as f: for line in f: if row_index >0: phi_i=list((float(n) for n in line.split('\n')[0].split(",") )); phi_i[0]=1; phi.append(phi_i); row_index+=1; m=len(phi); return phi; #End-readTrainData #split train data into Train and Validate def spitTrainDataset(phi,y): m=len(phi); tdsSize=int(m*trainDSSizePercentage); trainDatasetPhi=phi[0:tdsSize]; trainDatasetY=y[0:tdsSize]; validateDatasetPhi=phi[tdsSize:m]; validateDatasetY=y[tdsSize:m]; return [trainDatasetPhi,trainDatasetY,validateDatasetPhi,validateDatasetY]; pass #write-output def writeTestData(ystar): fo = open("output.csv", "w"); fo.write("ID,MEDV\n"); m=len(ystar); for i in range(m): fo.write(str(i)+","+str(ystar[i])+"\n"); fo.close(); pass; # Return det of matrix def getDet(A): d=det(A); if(d<10**-10): return 0; return d; #Return RMS: root mean square error def getRMS(y,yStar): m=len(y); sigma=0; for i in range(m): delta=(y[i]-yStar[i]); delta=delta*delta; sigma=sigma+delta; meanSq=sigma/m; rms=math.sqrt(meanSq); return rms; pass; #For ploting graph of RMS VS Iteration def plotGraph(x,y): import matplotlib.pyplot as plt; plt.plot(x,y) plt.ylabel('rms') plt.xlabel('iteration'); plt.show(); pass; #Record readings for gradient descent def writeReadingInFile(filename,alpha,lam,iteration,rms,p): import os.path; import datetime; import time; ts = datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y %H:%M:%S') if(os.path.exists(filename)==False): fo = open(filename, "w"); fo.write("iteration,norm,alpha,lam,rms,timestamp\n"); fo.write(str(iteration)+","+str(p)+","+str(alpha)+","+str(lam)+","+str(rms)+","+str(ts)+"\n"); else: fo = open(filename, "a"); fo.write(str(iteration)+","+str(p)+","+str(alpha)+","+str(lam)+","+str(rms)+","+str(ts)+"\n"); fo.close(); pass; #normalize the data set ny (x-u)/s where s is max-min def normalizePhi(unNormalizedPhi): phi=np.array(unNormalizedPhi); print("Normalizing Phi..."); std=phi.std(0); mean=phi.mean(0); std[0]=1; mean[0]=0; phi_normalize=(phi-mean)/std; print("Normalization done."); return phi_normalize; pass; #pridict of y* given w* QW=y* def pridict(dataset,weight): phi=np.array(dataset); w=np.array(weight); ystar=np.dot(phi,w); return ystar; pass; # Finding w*=(QTQ)^-1QTY def trainUsingClosedFormEquation(dataset,output): m=len(dataset); n=len(dataset[0]); print("------------------"); #print(dataset); phi=np.array(dataset); print("------------------"); #print(phi); y=np.array(output); phiT=np.transpose(phi); #(QTQ) phiT_phi=np.dot(phiT,phi); d=getDet(phiT_phi) if(d>0): #(QTQ)^-1 phiT_phi_inv=inv(phiT_phi); #(QTQ)^-1QT phiT_phi_inv_phiT=np.dot(phiT_phi_inv,phiT); #(QTQ)^-1QT*Y w=np.dot(phiT_phi_inv_phiT,y); return w; else: print("Error:Phi is NOT full column rank."); return None; pass; # Finding w*=(QTQ+lamI)^-1QTY def trainUsingClosedFormRidgeEq(dataset,output): m=len(dataset); n=len(dataset[0]); phi=np.array(dataset); y=np.array(output); phiT=np.transpose(phi); #(QTQ) phiT_phi=np.dot(phiT,phi); n=len(phiT_phi); lam=0.3; I=np.identity(n); lamI=lam*I; d=getDet(phiT_phi) #-------------------------------------- if(d>0): #(QTQ+lamI)^-1 phiT_phi_inv=inv((phiT_phi+lamI)); #(QTQ+lamI)^-1QT phiT_phi_inv_phiT=np.dot(phiT_phi_inv,phiT); #(QTQ+lamI)^-1QT*Y w=np.dot(phiT_phi_inv_phiT,y); return w; else: print("Error:Phi is NOT full column rank."); return None; pass; def numpiTestFun(): A2= np.matrix([[4,6],[2,8]]) A3= np.matrix([[1,2,3],[4,5,7],[7,8,9]]) A=A2; print(A); print(np.power(A,0.5)); print(A); print("Det(A):"+str(getDet(A))); B= np.transpose(A); C=inv(A); #print(C); print(np.dot(A,C)); print(A.std(0)); print(A.mean(0)); print(normalizePhi(A)); norm=(A-A.mean(0))/A.std(0); print(norm); print(); pass; def mainClosedFormSol(): #--------------------[Closed Form Sol without Regularlization]-------------------------------- #Find w* wStar=trainUsingClosedFormEquation(trainDatasetPhi,trainDatasetY); #Predict y* for Validate Data ystar=pridict(validateDatasetPhi,wStar); #checking for RMS for Validate Data rms=getRMS(validateDatasetY,ystar); #Predict y* for TestData ystar=pridict(testDS_norm,wStar); writeTestData(ystar); print("ClosedFormSolWithoutReg RMS:",rms); #--------------------------------------------------------------------------------------------- pass; def mainRidgeClosedFormSol(): #--------------------[Closed Form Sol without Regularlization]-------------------------------- #Find w* wStar=trainUsingClosedFormRidgeEq(trainDatasetPhi,trainDatasetY); #Predict y* for Validate Data ystar=pridict(validateDatasetPhi,wStar); #checking for RMS for Validate Data rms=getRMS(validateDatasetY,ystar); #Predict y* for TestData ystar=pridict(testDS_norm,wStar); writeTestData(ystar); print("ClosedFormSolWithoutReg RMS:",rms); #--------------------------------------------------------------------------------------------- pass; # In[12]: # GD: Least Sq. Without Regularlization def gardientDescentErrorFun(phi,y): m=len(y);#no of data points n=len(phi[0]);# no. of features alpha=0.22;# learning parameter maxIteration=10000; phi=np.array(phi); y=(np.array(y));#converting row vector to col vector wk0=np.zeros(n);# Nx1 vector phiT=np.transpose(phi); phiTphi=np.dot(phiT,phi); phiTy=np.dot(phiT,y); alphaBym=alpha/m; xaxis=list(); yaxis=list(); #---------------------- print("Training Started (Least Sq. Without Regularlization) ..."); for i in range(maxIteration): wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(i); yaxis.append(rms); percentComplete=((i+1)*100)/maxIteration; if( percentComplete%10==0 ): print("Percent Completed",percentComplete); wk0=wk1; print("Final Trained RMS:",rms); plotGraph(xaxis,yaxis); return wk1; pass; # GD: Least Sq. With Ridges def gardientDescentWithRidge(phi,y): m=len(y);#no of data points n=len(phi[0]);# no. of features alpha=0.212;# learning parameter maxIteration=10000; phi=np.array(phi); y=(np.array(y));#converting row vector to col vector wk0=np.zeros(n);# Nx1 vector #wk0=phi[14];#14 phiT=np.transpose(phi); phiTphi=np.dot(phiT,phi); phiTy=np.dot(phiT,y); alphaBym=alpha/m; lam=0.301; xaxis=list(); yaxis=list(); algFixedIteration=False; logReading=True; diff=0; #----------------------------------------------------------------- #Best Tested Constant #aplha=.212 lamda=.301 datasie=0.7 o/p=4.8310 rms #Tried for different initial wk0 but o/p remain same #----------------------------------------------------------------- print("Training Started (Least Sq. With Ridge) ..."); if (algFixedIteration): for iteration in range(0,maxIteration): wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy)+(lam*wk0))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(iteration); yaxis.append(rms); percentComplete=((iteration+1)*100)/maxIteration; if( percentComplete%10==0 ): print("Percent Completed",percentComplete); wk0=wk1; else: diffOffset=1e-20; iteration=0; oldRms=0; voldRms=0; while (True): wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy)+(lam*wk0))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(iteration); yaxis.append(rms); diff=oldRms-rms; vystar=pridict(validateDatasetPhi,wk1); vrms=getRMS(validateDatasetY,vystar); vdiff=voldRms-vrms; if(iteration>0 and diff<diffOffset): break; if(False and iteration%100==0 ): print("# iteration: ",iteration," rms:",rms,"diff:",diff," vrms:",vrms," vdiff:", vdiff); wk0=wk1; oldRms=rms; voldRms=vrms; iteration+=1; print("# iteration: ",iteration," rms:",rms,"diff:",diff," vrms:",vrms," vdiff:", vdiff); print("Final Trained RMS:",rms ,". Iteration needed ", iteration); #------------------------------------------------------------- if(logReading): writeReadingInFile("ridge.csv",alpha,lam,iteration,rms,2); plotGraph(xaxis,yaxis); return wk1; # GD: Least Sq. With ||w||_(1.5)^(1.5) def gardientDescentWithPnom(phi,y,p): m=len(y);#no of data points n=len(phi[0]);# no. of features alpha=0.2 #learning parameter maxIteration=100000; phi=np.array(phi); y=(np.array(y));#converting row vector to col vector wk0=np.zeros(n);# Nx1 vector wk0=phi[1]; phiT=np.transpose(phi); phiTphi=np.dot(phiT,phi); phiTy=np.dot(phiT,y); alphaBym=alpha/m; lam=0.31; xaxis=list(); yaxis=list(); algFixedIteration=False; logReading=True; diff=0; wPow=p-1; if (p<=1): print("Error: norm p is less than 1 i.p p=",wPow); return None; #----------------------------------------------------------------- print("Training Started (Least Sq. With Ridge) ..."); if (algFixedIteration): for iteration in range(0,maxIteration): if (wPow>1): wk0Pow=np.power(wk0,wPow); else: wk0Pow=wk0; wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy)+(lam*wk0Pow))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(iteration); yaxis.append(rms); percentComplete=((iteration+1)*100)/maxIteration; if( percentComplete%10==0 ): print("Percent Completed",percentComplete); wk0=wk1; else: diffOffset=1e-20; iteration=0; oldRms=0; voldRms=0; while (True): if (wPow>1): wk0Pow=np.power(wk0,wPow); else: wk0Pow=wk0; wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy)+(lam*wk0Pow))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(iteration); yaxis.append(rms); diff=oldRms-rms; vystar=pridict(validateDatasetPhi,wk1); vrms=getRMS(validateDatasetY,vystar); vdiff=voldRms-vrms; if(iteration>0 and diff<=diffOffset): break; if(False and iteration%100==0 ): print("# iteration: ",iteration," rms:",rms,"diff:",diff," vrms:",vrms," vdiff:", vdiff); wk0=wk1; oldRms=rms; voldRms=vrms; iteration+=1; print("# iteration: ",iteration," rms:",rms,"diff:",diff," vrms:",vrms," vdiff:", vdiff); print("Final Trained RMS:",rms ,". Iteration needed ", iteration); #------------------------------------------------------------- if(logReading): writeReadingInFile("pnom.csv",alpha,lam,iteration,rms,p); plotGraph(xaxis,yaxis); return wk1; #wStart=gardientDescentWithRidge(trainDatasetPhi,trainDatasetY); wStart=gardientDescentWithPnom(trainDatasetPhi,trainDatasetY,(4/3)); # In[ ]: # In[11]: #--settings-- np.set_printoptions(suppress=True) #---init--- dir="" trainFile=dir+"train.csv"; testFile=dir+"test.csv"; print("Fetching Trained Dataset from file..."); dataset=readTrainData(trainFile); phiSet=dataset[0]; ySet=dataset[1]; phiSet_norm=normalizePhi(phiSet); dataset=spitTrainDataset(phiSet_norm,ySet); testDS=readTestData(testFile); testDS_norm=normalizePhi(testDS); print("Fetching of data Completed."); #train set trainDatasetPhi=dataset[0]; trainDatasetY=dataset[1]; #validate set validateDatasetPhi=dataset[2]; validateDatasetY=dataset[3]; #print(testDS); #print(testDS_norm); print("Train Size:"+str(len(trainDatasetPhi))); print("Validate Size:"+str(len(validateDatasetPhi))); #numpiTestFun(); #mainClosedFormSol(); #mainRidgeClosedFormSol(); #--------------------[Gradient decent without Regularlization]-------------------------------- wStar=gardientDescentWithRidge(trainDatasetPhi,trainDatasetY); #wStar=gardientDescentWithPnom(trainDatasetPhi,trainDatasetY,(4/3)); #Predict y* for Validate Data ystar=pridict(validateDatasetPhi,wStar); #checking for RMS for Validate Data rms=getRMS(validateDatasetY,ystar); #Predict y* for TestData #ystar=pridict(testDS_norm,wStar); #writeTestData(ystar); print("ClosedFormSolWithReg RMS:",rms); #--------------------------------------------------------------------------------------------- # In[ ]: # In[ ]:
# coding: utf-8 # In[3]: print("Hello bye"); row=list(); ft=open("train.csv"); data=ft.read(); print(data); # In[10]: import numpy as np; from numpy.linalg import inv; from numpy.linalg import det; import math; trainDSSizePercentage=0.7; # x*100 percentage. 1-x data set will be used for validating # Will read the file and convert it into two dataset one train data other validate data def readTrainData(fileName): row_index=0; phi=list(); y=list(); with open(fileName) as f: for line in f: if row_index >0: phi_i=list((float(n) for n in line.split('\n')[0].split(",") )); phi_i[0]=1; # last row is value of yi y_i=phi_i.pop(len(phi_i)-1); phi.append(phi_i); y.append(y_i); row_index+=1; return [phi,y]; #End-readTrainData # Will read the file and convert it into dataset for Testing the Model def readTestData(fileName): row_index=0; phi=list(); y=list(); with open(fileName) as f: for line in f: if row_index >0: phi_i=list((float(n) for n in line.split('\n')[0].split(",") )); phi_i[0]=1; phi.append(phi_i); row_index+=1; m=len(phi); return phi; #End-readTrainData #split train data into Train and Validate def spitTrainDataset(phi,y): m=len(phi); tdsSize=int(m*trainDSSizePercentage); trainDatasetPhi=phi[0:tdsSize]; trainDatasetY=y[0:tdsSize]; validateDatasetPhi=phi[tdsSize:m]; validateDatasetY=y[tdsSize:m]; return [trainDatasetPhi,trainDatasetY,validateDatasetPhi,validateDatasetY]; pass #write-output def writeTestData(ystar): fo = open("output.csv", "w"); fo.write("ID,MEDV\n"); m=len(ystar); for i in range(m): fo.write(str(i)+","+str(ystar[i])+"\n"); fo.close(); pass; # Return det of matrix def getDet(A): d=det(A); if(d<10**-10): return 0; return d; #Return RMS: root mean square error def getRMS(y,yStar): m=len(y); sigma=0; for i in range(m): delta=(y[i]-yStar[i]); delta=delta*delta; sigma=sigma+delta; meanSq=sigma/m; rms=math.sqrt(meanSq); return rms; pass; #For ploting graph of RMS VS Iteration def plotGraph(x,y): import matplotlib.pyplot as plt; plt.plot(x,y) plt.ylabel('rms') plt.xlabel('iteration'); plt.show(); pass; #Record readings for gradient descent def writeReadingInFile(filename,alpha,lam,iteration,rms,p): import os.path; import datetime; import time; ts = datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y %H:%M:%S') if(os.path.exists(filename)==False): fo = open(filename, "w"); fo.write("iteration,norm,alpha,lam,rms,timestamp\n"); fo.write(str(iteration)+","+str(p)+","+str(alpha)+","+str(lam)+","+str(rms)+","+str(ts)+"\n"); else: fo = open(filename, "a"); fo.write(str(iteration)+","+str(p)+","+str(alpha)+","+str(lam)+","+str(rms)+","+str(ts)+"\n"); fo.close(); pass; #normalize the data set ny (x-u)/s where s is max-min def normalizePhi(unNormalizedPhi): phi=np.array(unNormalizedPhi); print("Normalizing Phi..."); std=phi.std(0); mean=phi.mean(0); std[0]=1; mean[0]=0; phi_normalize=(phi-mean)/std; print("Normalization done."); return phi_normalize; pass; #pridict of y* given w* QW=y* def pridict(dataset,weight): phi=np.array(dataset); w=np.array(weight); ystar=np.dot(phi,w); return ystar; pass; # Finding w*=(QTQ)^-1QTY def trainUsingClosedFormEquation(dataset,output): m=len(dataset); n=len(dataset[0]); print("------------------"); #print(dataset); phi=np.array(dataset); print("------------------"); #print(phi); y=np.array(output); phiT=np.transpose(phi); #(QTQ) phiT_phi=np.dot(phiT,phi); d=getDet(phiT_phi) if(d>0): #(QTQ)^-1 phiT_phi_inv=inv(phiT_phi); #(QTQ)^-1QT phiT_phi_inv_phiT=np.dot(phiT_phi_inv,phiT); #(QTQ)^-1QT*Y w=np.dot(phiT_phi_inv_phiT,y); return w; else: print("Error:Phi is NOT full column rank."); return None; pass; # Finding w*=(QTQ+lamI)^-1QTY def trainUsingClosedFormRidgeEq(dataset,output): m=len(dataset); n=len(dataset[0]); phi=np.array(dataset); y=np.array(output); phiT=np.transpose(phi); #(QTQ) phiT_phi=np.dot(phiT,phi); n=len(phiT_phi); lam=0.3; I=np.identity(n); lamI=lam*I; d=getDet(phiT_phi) #-------------------------------------- if(d>0): #(QTQ+lamI)^-1 phiT_phi_inv=inv((phiT_phi+lamI)); #(QTQ+lamI)^-1QT phiT_phi_inv_phiT=np.dot(phiT_phi_inv,phiT); #(QTQ+lamI)^-1QT*Y w=np.dot(phiT_phi_inv_phiT,y); return w; else: print("Error:Phi is NOT full column rank."); return None; pass; def numpiTestFun(): A2= np.matrix([[4,6],[2,8]]) A3= np.matrix([[1,2,3],[4,5,7],[7,8,9]]) A=A2; print(A); print(np.power(A,0.5)); print(A); print("Det(A):"+str(getDet(A))); B= np.transpose(A); C=inv(A); #print(C); print(np.dot(A,C)); print(A.std(0)); print(A.mean(0)); print(normalizePhi(A)); norm=(A-A.mean(0))/A.std(0); print(norm); print(); pass; def mainClosedFormSol(): #--------------------[Closed Form Sol without Regularlization]-------------------------------- #Find w* wStar=trainUsingClosedFormEquation(trainDatasetPhi,trainDatasetY); #Predict y* for Validate Data ystar=pridict(validateDatasetPhi,wStar); #checking for RMS for Validate Data rms=getRMS(validateDatasetY,ystar); #Predict y* for TestData ystar=pridict(testDS_norm,wStar); writeTestData(ystar); print("ClosedFormSolWithoutReg RMS:",rms); #--------------------------------------------------------------------------------------------- pass; def mainRidgeClosedFormSol(): #--------------------[Closed Form Sol without Regularlization]-------------------------------- #Find w* wStar=trainUsingClosedFormRidgeEq(trainDatasetPhi,trainDatasetY); #Predict y* for Validate Data ystar=pridict(validateDatasetPhi,wStar); #checking for RMS for Validate Data rms=getRMS(validateDatasetY,ystar); #Predict y* for TestData ystar=pridict(testDS_norm,wStar); writeTestData(ystar); print("ClosedFormSolWithoutReg RMS:",rms); #--------------------------------------------------------------------------------------------- pass; # In[12]: # GD: Least Sq. Without Regularlization def gardientDescentErrorFun(phi,y): m=len(y);#no of data points n=len(phi[0]);# no. of features alpha=0.22;# learning parameter maxIteration=10000; phi=np.array(phi); y=(np.array(y));#converting row vector to col vector wk0=np.zeros(n);# Nx1 vector phiT=np.transpose(phi); phiTphi=np.dot(phiT,phi); phiTy=np.dot(phiT,y); alphaBym=alpha/m; xaxis=list(); yaxis=list(); #---------------------- print("Training Started (Least Sq. Without Regularlization) ..."); for i in range(maxIteration): wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(i); yaxis.append(rms); percentComplete=((i+1)*100)/maxIteration; if( percentComplete%10==0 ): print("Percent Completed",percentComplete); wk0=wk1; print("Final Trained RMS:",rms); plotGraph(xaxis,yaxis); return wk1; pass; # GD: Least Sq. With Ridges def gardientDescentWithRidge(phi,y): m=len(y);#no of data points n=len(phi[0]);# no. of features alpha=0.212;# learning parameter maxIteration=10000; phi=np.array(phi); y=(np.array(y));#converting row vector to col vector wk0=np.zeros(n);# Nx1 vector #wk0=phi[14];#14 phiT=np.transpose(phi); phiTphi=np.dot(phiT,phi); phiTy=np.dot(phiT,y); alphaBym=alpha/m; lam=0.301; xaxis=list(); yaxis=list(); algFixedIteration=False; logReading=True; diff=0; #----------------------------------------------------------------- #Best Tested Constant #aplha=.212 lamda=.301 datasie=0.7 o/p=4.8310 rms #Tried for different initial wk0 but o/p remain same #----------------------------------------------------------------- print("Training Started (Least Sq. With Ridge) ..."); if (algFixedIteration): for iteration in range(0,maxIteration): wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy)+(lam*wk0))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(iteration); yaxis.append(rms); percentComplete=((iteration+1)*100)/maxIteration; if( percentComplete%10==0 ): print("Percent Completed",percentComplete); wk0=wk1; else: diffOffset=1e-20; iteration=0; oldRms=0; voldRms=0; while (True): wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy)+(lam*wk0))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(iteration); yaxis.append(rms); diff=oldRms-rms; vystar=pridict(validateDatasetPhi,wk1); vrms=getRMS(validateDatasetY,vystar); vdiff=voldRms-vrms; if(iteration>0 and diff<diffOffset): break; if(False and iteration%100==0 ): print("# iteration: ",iteration," rms:",rms,"diff:",diff," vrms:",vrms," vdiff:", vdiff); wk0=wk1; oldRms=rms; voldRms=vrms; iteration+=1; print("# iteration: ",iteration," rms:",rms,"diff:",diff," vrms:",vrms," vdiff:", vdiff); print("Final Trained RMS:",rms ,". Iteration needed ", iteration); #------------------------------------------------------------- if(logReading): writeReadingInFile("ridge.csv",alpha,lam,iteration,rms,2); plotGraph(xaxis,yaxis); return wk1; # GD: Least Sq. With ||w||_(1.5)^(1.5) def gardientDescentWithPnom(phi,y,p): m=len(y);#no of data points n=len(phi[0]);# no. of features alpha=0.2 #learning parameter maxIteration=100000; phi=np.array(phi); y=(np.array(y));#converting row vector to col vector wk0=np.zeros(n);# Nx1 vector wk0=phi[1]; phiT=np.transpose(phi); phiTphi=np.dot(phiT,phi); phiTy=np.dot(phiT,y); alphaBym=alpha/m; lam=0.31; xaxis=list(); yaxis=list(); algFixedIteration=False; logReading=True; diff=0; wPow=p-1; if (p<=1): print("Error: norm p is less than 1 i.p p=",wPow); return None; #----------------------------------------------------------------- print("Training Started (Least Sq. With Ridge) ..."); if (algFixedIteration): for iteration in range(0,maxIteration): if (wPow>1): wk0Pow=np.power(wk0,wPow); else: wk0Pow=wk0; wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy)+(lam*wk0Pow))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(iteration); yaxis.append(rms); percentComplete=((iteration+1)*100)/maxIteration; if( percentComplete%10==0 ): print("Percent Completed",percentComplete); wk0=wk1; else: diffOffset=1e-20; iteration=0; oldRms=0; voldRms=0; while (True): if (wPow>1): wk0Pow=np.power(wk0,wPow); else: wk0Pow=wk0; wk1=wk0-(alphaBym*((np.dot(phiTphi,wk0)-phiTy)+(lam*wk0Pow))); ystar=pridict(phi,wk1); rms=getRMS(y,ystar); xaxis.append(iteration); yaxis.append(rms); diff=oldRms-rms; vystar=pridict(validateDatasetPhi,wk1); vrms=getRMS(validateDatasetY,vystar); vdiff=voldRms-vrms; if(iteration>0 and diff<=diffOffset): break; if(False and iteration%100==0 ): print("# iteration: ",iteration," rms:",rms,"diff:",diff," vrms:",vrms," vdiff:", vdiff); wk0=wk1; oldRms=rms; voldRms=vrms; iteration+=1; print("# iteration: ",iteration," rms:",rms,"diff:",diff," vrms:",vrms," vdiff:", vdiff); print("Final Trained RMS:",rms ,". Iteration needed ", iteration); #------------------------------------------------------------- if(logReading): writeReadingInFile("pnom.csv",alpha,lam,iteration,rms,p); plotGraph(xaxis,yaxis); return wk1; #wStart=gardientDescentWithRidge(trainDatasetPhi,trainDatasetY); wStart=gardientDescentWithPnom(trainDatasetPhi,trainDatasetY,(4/3)); # In[ ]: # In[11]: #--settings-- np.set_printoptions(suppress=True) #---init--- dir="" trainFile=dir+"train.csv"; testFile=dir+"test.csv"; print("Fetching Trained Dataset from file..."); dataset=readTrainData(trainFile); phiSet=dataset[0]; ySet=dataset[1]; phiSet_norm=normalizePhi(phiSet); dataset=spitTrainDataset(phiSet_norm,ySet); testDS=readTestData(testFile); testDS_norm=normalizePhi(testDS); print("Fetching of data Completed."); #train set trainDatasetPhi=dataset[0]; trainDatasetY=dataset[1]; #validate set validateDatasetPhi=dataset[2]; validateDatasetY=dataset[3]; #print(testDS); #print(testDS_norm); print("Train Size:"+str(len(trainDatasetPhi))); print("Validate Size:"+str(len(validateDatasetPhi))); #numpiTestFun(); #mainClosedFormSol(); #mainRidgeClosedFormSol(); #--------------------[Gradient decent without Regularlization]-------------------------------- wStar=gardientDescentWithRidge(trainDatasetPhi,trainDatasetY); #wStar=gardientDescentWithPnom(trainDatasetPhi,trainDatasetY,(4/3)); #Predict y* for Validate Data ystar=pridict(validateDatasetPhi,wStar); #checking for RMS for Validate Data rms=getRMS(validateDatasetY,ystar); #Predict y* for TestData #ystar=pridict(testDS_norm,wStar); #writeTestData(ystar); print("ClosedFormSolWithReg RMS:",rms); #--------------------------------------------------------------------------------------------- # In[ ]: # In[ ]:
en
0.340087
# coding: utf-8 # In[3]: # In[10]: # x*100 percentage. 1-x data set will be used for validating # Will read the file and convert it into two dataset one train data other validate data # last row is value of yi #End-readTrainData # Will read the file and convert it into dataset for Testing the Model #End-readTrainData #split train data into Train and Validate #write-output # Return det of matrix #Return RMS: root mean square error #For ploting graph of RMS VS Iteration #Record readings for gradient descent #normalize the data set ny (x-u)/s where s is max-min #pridict of y* given w* QW=y* # Finding w*=(QTQ)^-1QTY #print(dataset); #print(phi); #(QTQ) #(QTQ)^-1 #(QTQ)^-1QT #(QTQ)^-1QT*Y # Finding w*=(QTQ+lamI)^-1QTY #(QTQ) #-------------------------------------- #(QTQ+lamI)^-1 #(QTQ+lamI)^-1QT #(QTQ+lamI)^-1QT*Y #print(C); #--------------------[Closed Form Sol without Regularlization]-------------------------------- #Find w* #Predict y* for Validate Data #checking for RMS for Validate Data #Predict y* for TestData #--------------------------------------------------------------------------------------------- #--------------------[Closed Form Sol without Regularlization]-------------------------------- #Find w* #Predict y* for Validate Data #checking for RMS for Validate Data #Predict y* for TestData #--------------------------------------------------------------------------------------------- # In[12]: # GD: Least Sq. Without Regularlization #no of data points # no. of features # learning parameter #converting row vector to col vector # Nx1 vector #---------------------- # GD: Least Sq. With Ridges #no of data points # no. of features # learning parameter #converting row vector to col vector # Nx1 vector #wk0=phi[14];#14 #----------------------------------------------------------------- #Best Tested Constant #aplha=.212 lamda=.301 datasie=0.7 o/p=4.8310 rms #Tried for different initial wk0 but o/p remain same #----------------------------------------------------------------- #------------------------------------------------------------- # GD: Least Sq. With ||w||_(1.5)^(1.5) #no of data points # no. of features #learning parameter #converting row vector to col vector # Nx1 vector #----------------------------------------------------------------- #------------------------------------------------------------- #wStart=gardientDescentWithRidge(trainDatasetPhi,trainDatasetY); # In[ ]: # In[11]: #--settings-- #---init--- #train set #validate set #print(testDS); #print(testDS_norm); #numpiTestFun(); #mainClosedFormSol(); #mainRidgeClosedFormSol(); #--------------------[Gradient decent without Regularlization]-------------------------------- #wStar=gardientDescentWithPnom(trainDatasetPhi,trainDatasetY,(4/3)); #Predict y* for Validate Data #checking for RMS for Validate Data #Predict y* for TestData #ystar=pridict(testDS_norm,wStar); #writeTestData(ystar); #--------------------------------------------------------------------------------------------- # In[ ]: # In[ ]:
3.280512
3
src/mars_profiling/report/structure/variables/render_url.py
wjsi/mars-profiling
1
6624335
from mars_profiling.config import config from mars_profiling.report.presentation.core import ( Container, FrequencyTable, FrequencyTableSmall, Table, VariableInfo, ) from mars_profiling.report.presentation.frequency_table_utils import freq_table from mars_profiling.report.structure.variables import render_common def render_url(summary): varid = summary["varid"] n_freq_table_max = config["n_freq_table_max"].get(int) n_obs_cat = config["vars"]["cat"]["n_obs"].get(int) redact = config["vars"]["cat"]["redact"].get(bool) template_variables = render_common(summary) keys = ["scheme", "netloc", "path", "query", "fragment"] for url_part in keys: template_variables[f"freqtable_{url_part}"] = freq_table( freqtable=summary[f"{url_part}_counts"], n=summary["n"], max_number_to_print=n_freq_table_max, ) full_frequency_table = FrequencyTable( template_variables["freq_table_rows"], name="Full", anchor_id=f"{varid}full_frequency", redact=redact, ) scheme_frequency_table = FrequencyTable( template_variables["freqtable_scheme"], name="Scheme", anchor_id=f"{varid}scheme_frequency", redact=redact, ) netloc_frequency_table = FrequencyTable( template_variables["freqtable_netloc"], name="Netloc", anchor_id=f"{varid}netloc_frequency", redact=redact, ) path_frequency_table = FrequencyTable( template_variables["freqtable_path"], name="Path", anchor_id=f"{varid}path_frequency", redact=redact, ) query_frequency_table = FrequencyTable( template_variables["freqtable_query"], name="Query", anchor_id=f"{varid}query_frequency", redact=redact, ) fragment_frequency_table = FrequencyTable( template_variables["freqtable_fragment"], name="Fragment", anchor_id=f"{varid}fragment_frequency", redact=redact, ) items = [ full_frequency_table, scheme_frequency_table, netloc_frequency_table, path_frequency_table, query_frequency_table, fragment_frequency_table, ] template_variables["bottom"] = Container( items, sequence_type="tabs", name="url stats", anchor_id=f"{varid}urlstats" ) # Element composition info = VariableInfo( summary["varid"], summary["varname"], "URL", summary["warnings"], summary["description"], ) table = Table( [ { "name": "Distinct", "value": summary["n_distinct"], "fmt": "fmt", "alert": "n_distinct" in summary["warn_fields"], }, { "name": "Distinct (%)", "value": summary["p_distinct"], "fmt": "fmt_percent", "alert": "p_distinct" in summary["warn_fields"], }, { "name": "Missing", "value": summary["n_missing"], "fmt": "fmt", "alert": "n_missing" in summary["warn_fields"], }, { "name": "Missing (%)", "value": summary["p_missing"], "fmt": "fmt_percent", "alert": "p_missing" in summary["warn_fields"], }, { "name": "Memory size", "value": summary["memory_size"], "fmt": "fmt_bytesize", "alert": False, }, ] ) fqm = FrequencyTableSmall( freq_table( freqtable=summary["value_counts"], n=summary["n"], max_number_to_print=n_obs_cat, ), redact=redact, ) template_variables["top"] = Container([info, table, fqm], sequence_type="grid") return template_variables
from mars_profiling.config import config from mars_profiling.report.presentation.core import ( Container, FrequencyTable, FrequencyTableSmall, Table, VariableInfo, ) from mars_profiling.report.presentation.frequency_table_utils import freq_table from mars_profiling.report.structure.variables import render_common def render_url(summary): varid = summary["varid"] n_freq_table_max = config["n_freq_table_max"].get(int) n_obs_cat = config["vars"]["cat"]["n_obs"].get(int) redact = config["vars"]["cat"]["redact"].get(bool) template_variables = render_common(summary) keys = ["scheme", "netloc", "path", "query", "fragment"] for url_part in keys: template_variables[f"freqtable_{url_part}"] = freq_table( freqtable=summary[f"{url_part}_counts"], n=summary["n"], max_number_to_print=n_freq_table_max, ) full_frequency_table = FrequencyTable( template_variables["freq_table_rows"], name="Full", anchor_id=f"{varid}full_frequency", redact=redact, ) scheme_frequency_table = FrequencyTable( template_variables["freqtable_scheme"], name="Scheme", anchor_id=f"{varid}scheme_frequency", redact=redact, ) netloc_frequency_table = FrequencyTable( template_variables["freqtable_netloc"], name="Netloc", anchor_id=f"{varid}netloc_frequency", redact=redact, ) path_frequency_table = FrequencyTable( template_variables["freqtable_path"], name="Path", anchor_id=f"{varid}path_frequency", redact=redact, ) query_frequency_table = FrequencyTable( template_variables["freqtable_query"], name="Query", anchor_id=f"{varid}query_frequency", redact=redact, ) fragment_frequency_table = FrequencyTable( template_variables["freqtable_fragment"], name="Fragment", anchor_id=f"{varid}fragment_frequency", redact=redact, ) items = [ full_frequency_table, scheme_frequency_table, netloc_frequency_table, path_frequency_table, query_frequency_table, fragment_frequency_table, ] template_variables["bottom"] = Container( items, sequence_type="tabs", name="url stats", anchor_id=f"{varid}urlstats" ) # Element composition info = VariableInfo( summary["varid"], summary["varname"], "URL", summary["warnings"], summary["description"], ) table = Table( [ { "name": "Distinct", "value": summary["n_distinct"], "fmt": "fmt", "alert": "n_distinct" in summary["warn_fields"], }, { "name": "Distinct (%)", "value": summary["p_distinct"], "fmt": "fmt_percent", "alert": "p_distinct" in summary["warn_fields"], }, { "name": "Missing", "value": summary["n_missing"], "fmt": "fmt", "alert": "n_missing" in summary["warn_fields"], }, { "name": "Missing (%)", "value": summary["p_missing"], "fmt": "fmt_percent", "alert": "p_missing" in summary["warn_fields"], }, { "name": "Memory size", "value": summary["memory_size"], "fmt": "fmt_bytesize", "alert": False, }, ] ) fqm = FrequencyTableSmall( freq_table( freqtable=summary["value_counts"], n=summary["n"], max_number_to_print=n_obs_cat, ), redact=redact, ) template_variables["top"] = Container([info, table, fqm], sequence_type="grid") return template_variables
en
0.552708
# Element composition
2.194871
2
src/ankidmpy/copier.py
gitonthescene/ankidmpy
1
6624336
<filename>src/ankidmpy/copier.py import ankidmpy.util as util import shutil import os.path def copy(deck1, deck2, base): deck1_path = os.path.join(base, 'decks', util.deckToFilename(deck1)) if not os.path.isdir(deck1_path): util.err("Source deck not found: %s" % (deck1,)) deck2_suffix = "" if deck2: deck2_path = os.path.join(base, 'decks', util.deckToFilename(deck2)) else: i = 1 while True: deck2_suffix = " (%d)" % (i,) deck2_path = deck1_path + deck2_suffix if not os.path.exists(deck2_path): break i += 1 try: shutil.copytree(deck1_path, deck2_path) except PermissionError: util.err("Cannot copy files") deck_build = util.getJson(os.path.join(deck2_path, 'build.json')) deck_build['deck']['uuid'] = util.createUuid() deck_build['config']['uuid'] = util.createUuid() deck_build['model']['uuid'] = util.createUuid() with open(os.path.join(deck2_path, 'build.json'), 'w') as f: f.write(util.toJson(deck_build)) util.msg("Created deck: %s" % deck2 if deck2 else deck1 + deck2_suffix)
<filename>src/ankidmpy/copier.py import ankidmpy.util as util import shutil import os.path def copy(deck1, deck2, base): deck1_path = os.path.join(base, 'decks', util.deckToFilename(deck1)) if not os.path.isdir(deck1_path): util.err("Source deck not found: %s" % (deck1,)) deck2_suffix = "" if deck2: deck2_path = os.path.join(base, 'decks', util.deckToFilename(deck2)) else: i = 1 while True: deck2_suffix = " (%d)" % (i,) deck2_path = deck1_path + deck2_suffix if not os.path.exists(deck2_path): break i += 1 try: shutil.copytree(deck1_path, deck2_path) except PermissionError: util.err("Cannot copy files") deck_build = util.getJson(os.path.join(deck2_path, 'build.json')) deck_build['deck']['uuid'] = util.createUuid() deck_build['config']['uuid'] = util.createUuid() deck_build['model']['uuid'] = util.createUuid() with open(os.path.join(deck2_path, 'build.json'), 'w') as f: f.write(util.toJson(deck_build)) util.msg("Created deck: %s" % deck2 if deck2 else deck1 + deck2_suffix)
none
1
2.745165
3
Concept_Name_Generation/gentaxo.py
DM2-ND/GenTaxo
2
6624337
import torch from modules import MSA, BiLSTM, GraphTrans, BiGRU from utlis import * from torch import nn import dgl class GenTaxo(nn.Module): def __init__(self, args): super(GenTaxo, self).__init__() self.args = args if args.seq: self.seq_emb = nn.Embedding(len(args.seq_vocab), args.nhid, padding_idx=0) # self.seq_enc = BiLSTM(args, enc_type='title') self.seq_enc = BiGRU(args, enc_type='seq') self.seq_attn = MSA(args) self.ent_emb = nn.Embedding(len(args.ent_text_vocab), args.nhid, padding_idx=0) self.tar_emb = nn.Embedding(len(args.text_vocab), args.nhid, padding_idx=0) self.linear_combine = nn.Linear(args.nhid, 1) self.activate_f = nn.Sigmoid() if args.seq: nn.init.xavier_normal_(self.seq_emb.weight) nn.init.xavier_normal_(self.ent_emb.weight) self.rel_emb = nn.Embedding(len(args.rel_vocab), args.nhid, padding_idx=0) nn.init.xavier_normal_(self.rel_emb.weight) if args.enc_seq_type == "LSTM": self.decode_seq = nn.LSTMCell(args.dec_ninp, args.nhid) self.ent_enc = BiLSTM(args, enc_type='entity') if args.enc_seq_type == "GRU": self.decode_seq = nn.GRUCell(args.dec_ninp, args.nhid) self.ent_enc = BiGRU(args, enc_type='entity') self.graph_enc = GraphTrans(args) self.ent_attn = MSA(args) self.copy_attn = MSA(args, mode='copy') self.copy_fc = nn.Linear(args.dec_ninp, 1) self.pred_v_fc = nn.Linear(args.dec_ninp, len(args.text_vocab)) def enc_forward(self, batch, ent_mask, ent_text_mask, ent_len, rel_mask, parent_mask, child_mask, sibling_mask): seq_enc = None if self.args.seq: parent_enc = self.seq_enc(self.seq_emb(batch['parent']), parent_mask) child_enc = self.seq_enc(self.seq_emb(batch['child']), child_mask) sibling_enc = self.seq_enc(self.seq_emb(batch['sibling']), sibling_mask) ent_enc = self.ent_enc(self.ent_emb(batch['ent_text']), ent_text_mask, ent_len = batch['ent_len']) rel_emb = self.rel_emb(batch['rel']) g_ent, g_root = self.graph_enc(ent_enc, ent_mask, ent_len, rel_emb, rel_mask, batch['graph']) parent_enc = self.seq_attn(g_root, parent_enc) child_enc = self.seq_attn(g_root, child_enc) sibling_enc = self.seq_attn(g_root, sibling_enc) w_p = self.activate_f((self.linear_combine(parent_enc))) w_c = self.activate_f((self.linear_combine(child_enc))) w_s = self.activate_f((self.linear_combine(sibling_enc))) w = torch.cat([w_p,w_c,w_s],1) seq_enc = torch.cat([parent_enc,child_enc,sibling_enc],0) m = nn.Softmax(dim=1) w = m(w) seq_enc = w @ seq_enc return g_ent, g_root, seq_enc, ent_enc def forward(self, batch, beam_size=-1): ent_mask = len2mask(batch['ent_len'], self.args.device) ent_text_mask = batch['ent_text']==0 rel_mask = batch['rel']==0 # 0 means the <PAD> parent_mask = batch['parent']==0 child_mask = batch['child']==0 sibling_mask = batch['sibling']==0 g_ent, g_root, seq_enc, ent_enc = self.enc_forward(batch, ent_mask, ent_text_mask, batch['ent_len'], rel_mask, parent_mask, child_mask, sibling_mask) _h, _c = g_root, g_root.clone().detach() ctx = _h + self.ent_attn(_h, g_ent, mask=ent_mask) ctx = torch.cat([ctx, seq_enc], 1) if beam_size<1: # training outs = [] tar_inp = self.tar_emb(batch['text'].transpose(0,1)) for t, xt in enumerate(tar_inp): _xt = torch.cat([ctx, xt], 1) if self.args.enc_seq_type == "LSTM": _h, _c = self.decode_seq(_xt, (_h, _c)) if self.args.enc_seq_type == "GRU": _h = self.decode_seq(_xt, _h) ctx = _h + self.ent_attn(_h, g_ent, mask=ent_mask) if self.args.seq: ctx = torch.cat([ctx, seq_enc], 1) outs.append(torch.cat([_h, ctx], 1)) outs = torch.stack(outs, 1) copy_gate = torch.sigmoid(self.copy_fc(outs)) EPSI = 1e-6 # copy pred_v = torch.log(copy_gate+EPSI) + torch.log_softmax(self.pred_v_fc(outs), -1) pred_c = torch.log((1. - copy_gate)+EPSI) + torch.log_softmax(self.copy_attn(outs, ent_enc, mask=ent_mask), -1) pred = torch.cat([pred_v, pred_c], -1) return pred else: if beam_size==1: # greedy device = g_ent.device B = g_ent.shape[0] ent_type = batch['ent_type'].view(B, -1) seq = (torch.ones(B,).long().to(device) * self.args.text_vocab('<BOS>')).unsqueeze(1) for t in range(self.args.beam_max_len): _inp = replace_ent(seq[:,-1], ent_type, len(self.args.text_vocab)) xt = self.tar_emb(_inp) _xt = torch.cat([ctx, xt], 1) if self.args.enc_seq_type == "LSTM": _h, _c = self.decode_seq(_xt, (_h, _c)) if self.args.enc_seq_type == "GRU": _h = self.decode_seq(_xt, _h) ctx = _h + self.ent_attn(_h, g_ent, mask=ent_mask) if self.args.seq: ctx = torch.cat([ctx, seq_enc], 1) _y = torch.cat([_h, ctx], 1) copy_gate = torch.sigmoid(self.copy_fc(_y)) pred_v = torch.log(copy_gate) + torch.log_softmax(self.pred_v_fc(_y), -1) pred_c = torch.log((1. - copy_gate)) + torch.log_softmax(self.copy_attn(_y.unsqueeze(1), ent_enc, mask=ent_mask).squeeze(1), -1) pred = torch.cat([pred_v, pred_c], -1).view(B,-1) for ban_item in ['<BOS>', '<PAD>', '<UNK>']: pred[:, self.args.text_vocab(ban_item)] = -1e8 _, word = pred.max(-1) seq = torch.cat([seq, word.unsqueeze(1)], 1) return seq else: # beam search device = g_ent.device B = g_ent.shape[0] BSZ = B * beam_size _h = _h.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) _c = _c.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) ent_mask = ent_mask.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) if self.args.title: title_mask = title_mask.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) title_enc = title_enc.view(B, 1, title_enc.size(1), -1).repeat(1, beam_size, 1, 1).view(BSZ, title_enc.size(1), -1) ctx = ctx.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) ent_type = batch['ent_type'].view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) g_ent = g_ent.view(B, 1, g_ent.size(1), -1).repeat(1, beam_size, 1, 1).view(BSZ, g_ent.size(1), -1) ent_enc = ent_enc.view(B, 1, ent_enc.size(1), -1).repeat(1, beam_size, 1, 1).view(BSZ, ent_enc.size(1), -1) beam_best = torch.zeros(B).to(device) - 1e9 beam_best_seq = [None] * B beam_seq = (torch.ones(B, beam_size).long().to(device) * self.args.text_vocab('<BOS>')).unsqueeze(-1) beam_score = torch.zeros(B, beam_size).to(device) done_flag = torch.zeros(B, beam_size) for t in range(self.args.beam_max_len): _inp = replace_ent(beam_seq[:,:,-1].view(-1), ent_type, len(self.args.text_vocab)) xt = self.tar_emb(_inp) _xt = torch.cat([ctx, xt], 1) _h, _c = self.decode_seq(_xt, (_h, _c)) ctx = _h + self.ent_attn(_h, g_ent, mask=ent_mask) if self.args.title: attn = _h + self.title_attn(_h, title_enc, mask=title_mask) ctx = torch.cat([ctx, attn], 1) _y = torch.cat([_h, ctx], 1) copy_gate = torch.sigmoid(self.copy_fc(_y)) pred_v = torch.log(copy_gate) + torch.log_softmax(self.pred_v_fc(_y), -1) pred_c = torch.log((1. - copy_gate)) + torch.log_softmax(self.copy_attn(_y.unsqueeze(1), ent_enc, mask=ent_mask).squeeze(1), -1) pred = torch.cat([pred_v, pred_c], -1).view(B, beam_size, -1) for ban_item in ['<BOS>', '<PAD>', '<UNK>']: pred[:, :, self.args.text_vocab(ban_item)] = -1e8 if t==self.args.beam_max_len-1: # force ending tt = pred[:, :, self.args.text_vocab('<EOS>')] pred = pred*0-1e8 pred[:, :, self.args.text_vocab('<EOS>')] = tt cum_score = beam_score.view(B,beam_size,1) + pred score, word = cum_score.topk(dim=-1, k=beam_size) # B, beam_size, beam_size score, word = score.view(B,-1), word.view(B,-1) eos_idx = self.args.text_vocab('<EOS>') if beam_seq.size(2)==1: new_idx = torch.arange(beam_size).to(word) new_idx = new_idx[None,:].repeat(B,1) else: _, new_idx = score.topk(dim=-1, k=beam_size) new_src, new_score, new_word, new_done = [], [], [], [] LP = beam_seq.size(2) ** self.args.lp for i in range(B): for j in range(beam_size): tmp_score = score[i][new_idx[i][j]] tmp_word = word[i][new_idx[i][j]] src_idx = new_idx[i][j]//beam_size new_src.append(src_idx) if tmp_word == eos_idx: new_score.append(-1e8) else: new_score.append(tmp_score) new_word.append(tmp_word) if tmp_word == eos_idx and done_flag[i][src_idx]==0 and tmp_score/LP>beam_best[i]: beam_best[i] = tmp_score/LP beam_best_seq[i] = beam_seq[i][src_idx] if tmp_word == eos_idx: new_done.append(1) else: new_done.append(done_flag[i][src_idx]) new_score = torch.Tensor(new_score).view(B,beam_size).to(beam_score) new_word = torch.Tensor(new_word).view(B,beam_size).to(beam_seq) new_src = torch.LongTensor(new_src).view(B,beam_size).to(device) new_done = torch.Tensor(new_done).view(B,beam_size).to(done_flag) beam_score = new_score done_flag = new_done beam_seq = beam_seq.view(B,beam_size,-1)[torch.arange(B)[:,None].to(device), new_src] beam_seq = torch.cat([beam_seq, new_word.unsqueeze(2)], 2) _h = _h.view(B,beam_size,-1)[torch.arange(B)[:,None].to(device), new_src].view(BSZ,-1) _c = _c.view(B,beam_size,-1)[torch.arange(B)[:,None].to(device), new_src].view(BSZ,-1) ctx = ctx.view(B,beam_size,-1)[torch.arange(B)[:,None].to(device), new_src].view(BSZ,-1) return beam_best_seq
import torch from modules import MSA, BiLSTM, GraphTrans, BiGRU from utlis import * from torch import nn import dgl class GenTaxo(nn.Module): def __init__(self, args): super(GenTaxo, self).__init__() self.args = args if args.seq: self.seq_emb = nn.Embedding(len(args.seq_vocab), args.nhid, padding_idx=0) # self.seq_enc = BiLSTM(args, enc_type='title') self.seq_enc = BiGRU(args, enc_type='seq') self.seq_attn = MSA(args) self.ent_emb = nn.Embedding(len(args.ent_text_vocab), args.nhid, padding_idx=0) self.tar_emb = nn.Embedding(len(args.text_vocab), args.nhid, padding_idx=0) self.linear_combine = nn.Linear(args.nhid, 1) self.activate_f = nn.Sigmoid() if args.seq: nn.init.xavier_normal_(self.seq_emb.weight) nn.init.xavier_normal_(self.ent_emb.weight) self.rel_emb = nn.Embedding(len(args.rel_vocab), args.nhid, padding_idx=0) nn.init.xavier_normal_(self.rel_emb.weight) if args.enc_seq_type == "LSTM": self.decode_seq = nn.LSTMCell(args.dec_ninp, args.nhid) self.ent_enc = BiLSTM(args, enc_type='entity') if args.enc_seq_type == "GRU": self.decode_seq = nn.GRUCell(args.dec_ninp, args.nhid) self.ent_enc = BiGRU(args, enc_type='entity') self.graph_enc = GraphTrans(args) self.ent_attn = MSA(args) self.copy_attn = MSA(args, mode='copy') self.copy_fc = nn.Linear(args.dec_ninp, 1) self.pred_v_fc = nn.Linear(args.dec_ninp, len(args.text_vocab)) def enc_forward(self, batch, ent_mask, ent_text_mask, ent_len, rel_mask, parent_mask, child_mask, sibling_mask): seq_enc = None if self.args.seq: parent_enc = self.seq_enc(self.seq_emb(batch['parent']), parent_mask) child_enc = self.seq_enc(self.seq_emb(batch['child']), child_mask) sibling_enc = self.seq_enc(self.seq_emb(batch['sibling']), sibling_mask) ent_enc = self.ent_enc(self.ent_emb(batch['ent_text']), ent_text_mask, ent_len = batch['ent_len']) rel_emb = self.rel_emb(batch['rel']) g_ent, g_root = self.graph_enc(ent_enc, ent_mask, ent_len, rel_emb, rel_mask, batch['graph']) parent_enc = self.seq_attn(g_root, parent_enc) child_enc = self.seq_attn(g_root, child_enc) sibling_enc = self.seq_attn(g_root, sibling_enc) w_p = self.activate_f((self.linear_combine(parent_enc))) w_c = self.activate_f((self.linear_combine(child_enc))) w_s = self.activate_f((self.linear_combine(sibling_enc))) w = torch.cat([w_p,w_c,w_s],1) seq_enc = torch.cat([parent_enc,child_enc,sibling_enc],0) m = nn.Softmax(dim=1) w = m(w) seq_enc = w @ seq_enc return g_ent, g_root, seq_enc, ent_enc def forward(self, batch, beam_size=-1): ent_mask = len2mask(batch['ent_len'], self.args.device) ent_text_mask = batch['ent_text']==0 rel_mask = batch['rel']==0 # 0 means the <PAD> parent_mask = batch['parent']==0 child_mask = batch['child']==0 sibling_mask = batch['sibling']==0 g_ent, g_root, seq_enc, ent_enc = self.enc_forward(batch, ent_mask, ent_text_mask, batch['ent_len'], rel_mask, parent_mask, child_mask, sibling_mask) _h, _c = g_root, g_root.clone().detach() ctx = _h + self.ent_attn(_h, g_ent, mask=ent_mask) ctx = torch.cat([ctx, seq_enc], 1) if beam_size<1: # training outs = [] tar_inp = self.tar_emb(batch['text'].transpose(0,1)) for t, xt in enumerate(tar_inp): _xt = torch.cat([ctx, xt], 1) if self.args.enc_seq_type == "LSTM": _h, _c = self.decode_seq(_xt, (_h, _c)) if self.args.enc_seq_type == "GRU": _h = self.decode_seq(_xt, _h) ctx = _h + self.ent_attn(_h, g_ent, mask=ent_mask) if self.args.seq: ctx = torch.cat([ctx, seq_enc], 1) outs.append(torch.cat([_h, ctx], 1)) outs = torch.stack(outs, 1) copy_gate = torch.sigmoid(self.copy_fc(outs)) EPSI = 1e-6 # copy pred_v = torch.log(copy_gate+EPSI) + torch.log_softmax(self.pred_v_fc(outs), -1) pred_c = torch.log((1. - copy_gate)+EPSI) + torch.log_softmax(self.copy_attn(outs, ent_enc, mask=ent_mask), -1) pred = torch.cat([pred_v, pred_c], -1) return pred else: if beam_size==1: # greedy device = g_ent.device B = g_ent.shape[0] ent_type = batch['ent_type'].view(B, -1) seq = (torch.ones(B,).long().to(device) * self.args.text_vocab('<BOS>')).unsqueeze(1) for t in range(self.args.beam_max_len): _inp = replace_ent(seq[:,-1], ent_type, len(self.args.text_vocab)) xt = self.tar_emb(_inp) _xt = torch.cat([ctx, xt], 1) if self.args.enc_seq_type == "LSTM": _h, _c = self.decode_seq(_xt, (_h, _c)) if self.args.enc_seq_type == "GRU": _h = self.decode_seq(_xt, _h) ctx = _h + self.ent_attn(_h, g_ent, mask=ent_mask) if self.args.seq: ctx = torch.cat([ctx, seq_enc], 1) _y = torch.cat([_h, ctx], 1) copy_gate = torch.sigmoid(self.copy_fc(_y)) pred_v = torch.log(copy_gate) + torch.log_softmax(self.pred_v_fc(_y), -1) pred_c = torch.log((1. - copy_gate)) + torch.log_softmax(self.copy_attn(_y.unsqueeze(1), ent_enc, mask=ent_mask).squeeze(1), -1) pred = torch.cat([pred_v, pred_c], -1).view(B,-1) for ban_item in ['<BOS>', '<PAD>', '<UNK>']: pred[:, self.args.text_vocab(ban_item)] = -1e8 _, word = pred.max(-1) seq = torch.cat([seq, word.unsqueeze(1)], 1) return seq else: # beam search device = g_ent.device B = g_ent.shape[0] BSZ = B * beam_size _h = _h.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) _c = _c.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) ent_mask = ent_mask.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) if self.args.title: title_mask = title_mask.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) title_enc = title_enc.view(B, 1, title_enc.size(1), -1).repeat(1, beam_size, 1, 1).view(BSZ, title_enc.size(1), -1) ctx = ctx.view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) ent_type = batch['ent_type'].view(B, 1, -1).repeat(1, beam_size, 1).view(BSZ, -1) g_ent = g_ent.view(B, 1, g_ent.size(1), -1).repeat(1, beam_size, 1, 1).view(BSZ, g_ent.size(1), -1) ent_enc = ent_enc.view(B, 1, ent_enc.size(1), -1).repeat(1, beam_size, 1, 1).view(BSZ, ent_enc.size(1), -1) beam_best = torch.zeros(B).to(device) - 1e9 beam_best_seq = [None] * B beam_seq = (torch.ones(B, beam_size).long().to(device) * self.args.text_vocab('<BOS>')).unsqueeze(-1) beam_score = torch.zeros(B, beam_size).to(device) done_flag = torch.zeros(B, beam_size) for t in range(self.args.beam_max_len): _inp = replace_ent(beam_seq[:,:,-1].view(-1), ent_type, len(self.args.text_vocab)) xt = self.tar_emb(_inp) _xt = torch.cat([ctx, xt], 1) _h, _c = self.decode_seq(_xt, (_h, _c)) ctx = _h + self.ent_attn(_h, g_ent, mask=ent_mask) if self.args.title: attn = _h + self.title_attn(_h, title_enc, mask=title_mask) ctx = torch.cat([ctx, attn], 1) _y = torch.cat([_h, ctx], 1) copy_gate = torch.sigmoid(self.copy_fc(_y)) pred_v = torch.log(copy_gate) + torch.log_softmax(self.pred_v_fc(_y), -1) pred_c = torch.log((1. - copy_gate)) + torch.log_softmax(self.copy_attn(_y.unsqueeze(1), ent_enc, mask=ent_mask).squeeze(1), -1) pred = torch.cat([pred_v, pred_c], -1).view(B, beam_size, -1) for ban_item in ['<BOS>', '<PAD>', '<UNK>']: pred[:, :, self.args.text_vocab(ban_item)] = -1e8 if t==self.args.beam_max_len-1: # force ending tt = pred[:, :, self.args.text_vocab('<EOS>')] pred = pred*0-1e8 pred[:, :, self.args.text_vocab('<EOS>')] = tt cum_score = beam_score.view(B,beam_size,1) + pred score, word = cum_score.topk(dim=-1, k=beam_size) # B, beam_size, beam_size score, word = score.view(B,-1), word.view(B,-1) eos_idx = self.args.text_vocab('<EOS>') if beam_seq.size(2)==1: new_idx = torch.arange(beam_size).to(word) new_idx = new_idx[None,:].repeat(B,1) else: _, new_idx = score.topk(dim=-1, k=beam_size) new_src, new_score, new_word, new_done = [], [], [], [] LP = beam_seq.size(2) ** self.args.lp for i in range(B): for j in range(beam_size): tmp_score = score[i][new_idx[i][j]] tmp_word = word[i][new_idx[i][j]] src_idx = new_idx[i][j]//beam_size new_src.append(src_idx) if tmp_word == eos_idx: new_score.append(-1e8) else: new_score.append(tmp_score) new_word.append(tmp_word) if tmp_word == eos_idx and done_flag[i][src_idx]==0 and tmp_score/LP>beam_best[i]: beam_best[i] = tmp_score/LP beam_best_seq[i] = beam_seq[i][src_idx] if tmp_word == eos_idx: new_done.append(1) else: new_done.append(done_flag[i][src_idx]) new_score = torch.Tensor(new_score).view(B,beam_size).to(beam_score) new_word = torch.Tensor(new_word).view(B,beam_size).to(beam_seq) new_src = torch.LongTensor(new_src).view(B,beam_size).to(device) new_done = torch.Tensor(new_done).view(B,beam_size).to(done_flag) beam_score = new_score done_flag = new_done beam_seq = beam_seq.view(B,beam_size,-1)[torch.arange(B)[:,None].to(device), new_src] beam_seq = torch.cat([beam_seq, new_word.unsqueeze(2)], 2) _h = _h.view(B,beam_size,-1)[torch.arange(B)[:,None].to(device), new_src].view(BSZ,-1) _c = _c.view(B,beam_size,-1)[torch.arange(B)[:,None].to(device), new_src].view(BSZ,-1) ctx = ctx.view(B,beam_size,-1)[torch.arange(B)[:,None].to(device), new_src].view(BSZ,-1) return beam_best_seq
en
0.556119
# self.seq_enc = BiLSTM(args, enc_type='title') # 0 means the <PAD> # training # copy # greedy # beam search # force ending # B, beam_size, beam_size
2.370899
2
LSTM/edit.py
justinhyou/movement-classification-via-CNN-LSTM
4
6624338
<gh_stars>1-10 import numpy as np import matplotlib import matplotlib.pyplot as plt import tensorflow as tf # Version r0.10 from sklearn import metrics import sklearn import os # Useful Constants # Those are separate normalised input features for the neural network INPUT_SIGNAL_TYPES = [ "body_acc_x_", "body_acc_y_", "body_acc_z_", "body_gyro_x_", "body_gyro_y_", "body_gyro_z_", "total_acc_x_", "total_acc_y_", "total_acc_z_" ] # Output classes to learn how to classify LABELS = [ "WALKING", "WALKING_UPSTAIRS", "WALKING_DOWNSTAIRS", "SITTING", "STANDING", "LAYING" ] DATA_PATH = "data/" DATASET_PATH = DATA_PATH + "UCI HAR Dataset/" print("\n" + "Dataset is now located at: " + DATASET_PATH) TRAIN = "train/" TEST = "test/" # Load "X" (the neural network's training and testing inputs) def load_X(X_signals_paths): X_signals = [] for signal_type_path in X_signals_paths: file = open(signal_type_path, 'rb') # Read dataset from disk, dealing with text files' syntax X_signals.append( [np.array(serie, dtype=np.float32) for serie in [ row.replace(' ', ' ').strip().split(' ') for row in file ]] ) file.close() return np.transpose(np.array(X_signals), (1, 2, 0)) X_train_signals_paths = [ DATASET_PATH + TRAIN + "Inertial Signals/" + signal + "train.txt" for signal in INPUT_SIGNAL_TYPES ] X_test_signals_paths = [ DATASET_PATH + TEST + "Inertial Signals/" + signal + "test.txt" for signal in INPUT_SIGNAL_TYPES ] X_train = load_X(X_train_signals_paths) X_test = load_X(X_test_signals_paths) # Load "y" (the neural network's training and testing outputs) def load_y(y_path): file = open(y_path, 'rb') # Read dataset from disk, dealing with text file's syntax y_ = np.array( [elem for elem in [ row.replace(' ', ' ').strip().split(' ') for row in file ]], dtype=np.int32 ) file.close() # Substract 1 to each output class for friendly 0-based indexing return y_ - 1 y_train_path = DATASET_PATH + TRAIN + "y_train.txt" y_test_path = DATASET_PATH + TEST + "y_test.txt" y_train = load_y(y_train_path) y_test = load_y(y_test_path) # Input Data training_data_count = len(X_train) # 7352 training series (with 50% overlap between each serie) test_data_count = len(X_test) # 2947 testing series n_steps = len(X_train[0]) # 128 timesteps per series n_input = len(X_train[0][0]) # 9 input parameters per timestep # LSTM Neural Network's internal structure n_hidden = 32 # Hidden layer num of features n_classes = 6 # Total classes (should go up, or should go down) # Training learning_rate = 0.0025 lambda_loss_amount = 0.0015 training_iters = training_data_count * 300 # Loop 300 times on the dataset batch_size = 1500 display_iter = 30000 # To show test set accuracy during training # Some debugging info print "Some useful info to get an insight on dataset's shape and normalisation:" print "(X shape, y shape, every X's mean, every X's standard deviation)" print (X_test.shape, y_test.shape, np.mean(X_test), np.std(X_test)) print "The dataset is therefore properly normalised, as expected, but not yet one-hot encoded." """ NEW!!!! """ def CNN(_X, _weights, _biases): """Model function for CNN.""" # Input Layer input_layer = tf.reshape(features, [-1, 28, 28, 1]) # Convolutional Layer #1 conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling Layer #1 pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) # Convolutional Layer #2 and Pooling Layer #2 conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # Dense Layer pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) dropout = tf.layers.dropout( inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN) # Logits Layer logits = tf.layers.dense(inputs=dropout, units=10) loss = None train_op = None # Calculate Loss (for both TRAIN and EVAL modes) if mode != learn.ModeKeys.INFER: onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10) loss = tf.losses.softmax_cross_entropy( onehot_labels=onehot_labels, logits=logits) # Configure the Training Op (for TRAIN mode) if mode == learn.ModeKeys.TRAIN: train_op = tf.contrib.layers.optimize_loss( loss=loss, global_step=tf.contrib.framework.get_global_step(), learning_rate=0.001, optimizer="SGD") # Generate Predictions predictions = { "classes": tf.argmax( input=logits, axis=1), "probabilities": tf.nn.softmax( logits, name="softmax_tensor") } # Return a ModelFnOps object return model_fn_lib.ModelFnOps( mode=mode, predictions=predictions, loss=loss, train_op=train_op) """ NEW!!!! """ def LSTM_RNN(_X, _weights, _biases): # Function returns a tensorflow LSTM (RNN) artificial neural network from given parameters. # Moreover, two LSTM cells are stacked which adds deepness to the neural network. # Note, some code of this notebook is inspired from an slightly different # RNN architecture used on another dataset: # https://tensorhub.com/aymericdamien/tensorflow-rnn # (NOTE: This step could be greatly optimised by shaping the dataset once # input shape: (batch_size, n_steps, n_input) _X = tf.transpose(_X, [1, 0, 2]) # permute n_steps and batch_size # Reshape to prepare input to hidden activation _X = tf.reshape(_X, [-1, n_input]) # new shape: (n_steps*batch_size, n_input) # Linear activation _X = tf.nn.relu(tf.matmul(_X, _weights['hidden']) + _biases['hidden']) # Split data because rnn cell needs a list of inputs for the RNN inner loop _X = tf.split(0, n_steps, _X) # new shape: n_steps * (batch_size, n_hidden) input_layer = tf.reshape(_X, [128, 1500, 4, 1]) input_layer = _X input_layer = tf.reshape(_X, [4]) #CNN #1 conv_1 = tf.nn.conv2d(input = input_layer, filter = 32, strides=[1, 2, 2, 1], padding = "SAME") # Pooling Layer #1 pool1 = tf.nn.max_pooling2d(input=conv1, pool_size=[2, 2], strides=2) # Convolutional Layer #2 and Pooling Layer #2 conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling Layer #2 pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # Dense Layer pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) dense = tf.nn.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) dropout = tf.nn.dropout( inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN) # Logits Layer logits = tf.nn.dense(inputs=dropout, units=10) # Define two stacked LSTM cells (two recurrent layers deep) with tensorflow lstm_cell_1 = tf.nn.rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True) lstm_cell_2 = tf.nn.rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True) lstm_cells = tf.nn.rnn_cell.MultiRNNCell([lstm_cell_1, lstm_cell_2], state_is_tuple=True) # Get LSTM cell output outputs, states = tf.nn.rnn(lstm_cells, _X, dtype=tf.float32) # Get last time step's output feature for a "many to one" style classifier, # as in the image describing RNNs at the top of this page lstm_last_output = outputs[-1] # Linear activation return tf.matmul(lstm_last_output, _weights['out']) + _biases['out'] def extract_batch_size(_train, step, batch_size): # Function to fetch a "batch_size" amount of data from "(X|y)_train" data. shape = list(_train.shape) shape[0] = batch_size batch_s = np.empty(shape) for i in range(batch_size): # Loop index index = ((step-1)*batch_size + i) % len(_train) batch_s[i] = _train[index] return batch_s def one_hot(y_): # Function to encode output labels from number indexes # e.g.: [[5], [0], [3]] --> [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]] y_ = y_.reshape(len(y_)) n_values = np.max(y_) + 1 return np.eye(n_values)[np.array(y_, dtype=np.int32)] # Returns FLOATS # Graph input/output x = tf.placeholder(tf.float32, [None, n_steps, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) # Graph weights weights = { 'hidden': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights 'out': tf.Variable(tf.random_normal([n_hidden, n_classes], mean=1.0)) } biases = { 'hidden': tf.Variable(tf.random_normal([n_hidden])), 'out': tf.Variable(tf.random_normal([n_classes])) } pred = LSTM_RNN(x, weights, biases) # Loss, optimizer and evaluation l2 = lambda_loss_amount * sum( tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables() ) # L2 loss prevents this overkill neural network to overfit the data cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) + l2 # Softmax loss optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # To keep track of training's performance test_losses = [] test_accuracies = [] train_losses = [] train_accuracies = [] # Launch the graph sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=True)) init = tf.initialize_all_variables() sess.run(init) # In each loop, perform training steps with "batch_size" amount of given data step = 1 while step * batch_size <= training_iters: batch_xs = extract_batch_size(X_train, step, batch_size) batch_ys = one_hot(extract_batch_size(y_train, step, batch_size)) # Fit training using batch _, loss, acc = sess.run( [optimizer, cost, accuracy], feed_dict={ x: batch_xs, y: batch_ys } ) train_losses.append(loss) train_accuracies.append(acc) # show network details at specified intervals if (step*batch_size % display_iter == 0) or (step == 1) or (step * batch_size > training_iters): # show accuracy and loss print "Training iter #" + str(step*batch_size) + \ ": Batch Loss = " + "{:.6f}".format(loss) + \ ", Accuracy = {}".format(acc) # evaluate the test set loss, acc = sess.run( [cost, accuracy], feed_dict={ x: X_test, y: one_hot(y_test) } ) test_losses.append(loss) test_accuracies.append(acc) print "PERFORMANCE ON TEST SET: " + \ "Batch Loss = {}".format(loss) + \ ", Accuracy = {}".format(acc) step += 1 # Accuracy for test data one_hot_predictions, accuracy, final_loss = sess.run( [pred, accuracy, cost], feed_dict={ x: X_test, y: one_hot(y_test) } ) test_losses.append(final_loss) test_accuracies.append(accuracy) print "FINAL RESULT: " + \ "Batch Loss = {}".format(final_loss) + \ ", Accuracy = {}".format(accuracy) # (Inline plots: ) #%matplotlib inline font = { 'family' : 'Bitstream Vera Sans', 'weight' : 'bold', 'size' : 18 } matplotlib.rc('font', **font) width = 12 height = 12 plt.figure(figsize=(width, height)) indep_train_axis = np.array(range(batch_size, (len(train_losses)+1)*batch_size, batch_size)) plt.plot(indep_train_axis, np.array(train_losses), "b--", label="Train losses") plt.plot(indep_train_axis, np.array(train_accuracies), "g--", label="Train accuracies") indep_test_axis = np.array(range(batch_size, len(test_losses)*display_iter, display_iter)[:-1] + [training_iters]) plt.plot(indep_test_axis, np.array(test_losses), "b-", label="Test losses") plt.plot(indep_test_axis, np.array(test_accuracies), "g-", label="Test accuracies") plt.title("Training session's progress over iterations") plt.legend(loc='upper right', shadow=True) plt.ylabel('Training Progress (Loss or Accuracy values)') plt.xlabel('Training iteration') plt.show() # Results predictions = one_hot_predictions.argmax(1) print "Testing Accuracy: {}%".format(100*accuracy) print "" print "Precision: {}%".format(100*metrics.precision_score(y_test, predictions, average="weighted")) print "Recall: {}%".format(100*metrics.recall_score(y_test, predictions, average="weighted")) print "f1_score: {}%".format(100*metrics.f1_score(y_test, predictions, average="weighted")) print "" print "Confusion Matrix:" confusion_matrix = metrics.confusion_matrix(y_test, predictions) print confusion_matrix normalised_confusion_matrix = np.array(confusion_matrix, dtype=np.float32)/np.sum(confusion_matrix)*100 print "" print "Confusion matrix (normalised to % of total test data):" print normalised_confusion_matrix print ("Note: training and testing data is not equally distributed amongst classes, " "so it is normal that more than a 6th of the data is correctly classified in the last category.") # Plot Results: width = 12 height = 12 plt.figure(figsize=(width, height)) plt.imshow( normalised_confusion_matrix, interpolation='nearest', cmap=plt.cm.rainbow ) plt.title("Confusion matrix \n(normalised to % of total test data)") plt.colorbar() tick_marks = np.arange(n_classes) plt.xticks(tick_marks, LABELS, rotation=90) plt.yticks(tick_marks, LABELS) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() sess.close()
import numpy as np import matplotlib import matplotlib.pyplot as plt import tensorflow as tf # Version r0.10 from sklearn import metrics import sklearn import os # Useful Constants # Those are separate normalised input features for the neural network INPUT_SIGNAL_TYPES = [ "body_acc_x_", "body_acc_y_", "body_acc_z_", "body_gyro_x_", "body_gyro_y_", "body_gyro_z_", "total_acc_x_", "total_acc_y_", "total_acc_z_" ] # Output classes to learn how to classify LABELS = [ "WALKING", "WALKING_UPSTAIRS", "WALKING_DOWNSTAIRS", "SITTING", "STANDING", "LAYING" ] DATA_PATH = "data/" DATASET_PATH = DATA_PATH + "UCI HAR Dataset/" print("\n" + "Dataset is now located at: " + DATASET_PATH) TRAIN = "train/" TEST = "test/" # Load "X" (the neural network's training and testing inputs) def load_X(X_signals_paths): X_signals = [] for signal_type_path in X_signals_paths: file = open(signal_type_path, 'rb') # Read dataset from disk, dealing with text files' syntax X_signals.append( [np.array(serie, dtype=np.float32) for serie in [ row.replace(' ', ' ').strip().split(' ') for row in file ]] ) file.close() return np.transpose(np.array(X_signals), (1, 2, 0)) X_train_signals_paths = [ DATASET_PATH + TRAIN + "Inertial Signals/" + signal + "train.txt" for signal in INPUT_SIGNAL_TYPES ] X_test_signals_paths = [ DATASET_PATH + TEST + "Inertial Signals/" + signal + "test.txt" for signal in INPUT_SIGNAL_TYPES ] X_train = load_X(X_train_signals_paths) X_test = load_X(X_test_signals_paths) # Load "y" (the neural network's training and testing outputs) def load_y(y_path): file = open(y_path, 'rb') # Read dataset from disk, dealing with text file's syntax y_ = np.array( [elem for elem in [ row.replace(' ', ' ').strip().split(' ') for row in file ]], dtype=np.int32 ) file.close() # Substract 1 to each output class for friendly 0-based indexing return y_ - 1 y_train_path = DATASET_PATH + TRAIN + "y_train.txt" y_test_path = DATASET_PATH + TEST + "y_test.txt" y_train = load_y(y_train_path) y_test = load_y(y_test_path) # Input Data training_data_count = len(X_train) # 7352 training series (with 50% overlap between each serie) test_data_count = len(X_test) # 2947 testing series n_steps = len(X_train[0]) # 128 timesteps per series n_input = len(X_train[0][0]) # 9 input parameters per timestep # LSTM Neural Network's internal structure n_hidden = 32 # Hidden layer num of features n_classes = 6 # Total classes (should go up, or should go down) # Training learning_rate = 0.0025 lambda_loss_amount = 0.0015 training_iters = training_data_count * 300 # Loop 300 times on the dataset batch_size = 1500 display_iter = 30000 # To show test set accuracy during training # Some debugging info print "Some useful info to get an insight on dataset's shape and normalisation:" print "(X shape, y shape, every X's mean, every X's standard deviation)" print (X_test.shape, y_test.shape, np.mean(X_test), np.std(X_test)) print "The dataset is therefore properly normalised, as expected, but not yet one-hot encoded." """ NEW!!!! """ def CNN(_X, _weights, _biases): """Model function for CNN.""" # Input Layer input_layer = tf.reshape(features, [-1, 28, 28, 1]) # Convolutional Layer #1 conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling Layer #1 pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) # Convolutional Layer #2 and Pooling Layer #2 conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # Dense Layer pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) dropout = tf.layers.dropout( inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN) # Logits Layer logits = tf.layers.dense(inputs=dropout, units=10) loss = None train_op = None # Calculate Loss (for both TRAIN and EVAL modes) if mode != learn.ModeKeys.INFER: onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10) loss = tf.losses.softmax_cross_entropy( onehot_labels=onehot_labels, logits=logits) # Configure the Training Op (for TRAIN mode) if mode == learn.ModeKeys.TRAIN: train_op = tf.contrib.layers.optimize_loss( loss=loss, global_step=tf.contrib.framework.get_global_step(), learning_rate=0.001, optimizer="SGD") # Generate Predictions predictions = { "classes": tf.argmax( input=logits, axis=1), "probabilities": tf.nn.softmax( logits, name="softmax_tensor") } # Return a ModelFnOps object return model_fn_lib.ModelFnOps( mode=mode, predictions=predictions, loss=loss, train_op=train_op) """ NEW!!!! """ def LSTM_RNN(_X, _weights, _biases): # Function returns a tensorflow LSTM (RNN) artificial neural network from given parameters. # Moreover, two LSTM cells are stacked which adds deepness to the neural network. # Note, some code of this notebook is inspired from an slightly different # RNN architecture used on another dataset: # https://tensorhub.com/aymericdamien/tensorflow-rnn # (NOTE: This step could be greatly optimised by shaping the dataset once # input shape: (batch_size, n_steps, n_input) _X = tf.transpose(_X, [1, 0, 2]) # permute n_steps and batch_size # Reshape to prepare input to hidden activation _X = tf.reshape(_X, [-1, n_input]) # new shape: (n_steps*batch_size, n_input) # Linear activation _X = tf.nn.relu(tf.matmul(_X, _weights['hidden']) + _biases['hidden']) # Split data because rnn cell needs a list of inputs for the RNN inner loop _X = tf.split(0, n_steps, _X) # new shape: n_steps * (batch_size, n_hidden) input_layer = tf.reshape(_X, [128, 1500, 4, 1]) input_layer = _X input_layer = tf.reshape(_X, [4]) #CNN #1 conv_1 = tf.nn.conv2d(input = input_layer, filter = 32, strides=[1, 2, 2, 1], padding = "SAME") # Pooling Layer #1 pool1 = tf.nn.max_pooling2d(input=conv1, pool_size=[2, 2], strides=2) # Convolutional Layer #2 and Pooling Layer #2 conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling Layer #2 pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # Dense Layer pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) dense = tf.nn.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) dropout = tf.nn.dropout( inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN) # Logits Layer logits = tf.nn.dense(inputs=dropout, units=10) # Define two stacked LSTM cells (two recurrent layers deep) with tensorflow lstm_cell_1 = tf.nn.rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True) lstm_cell_2 = tf.nn.rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True) lstm_cells = tf.nn.rnn_cell.MultiRNNCell([lstm_cell_1, lstm_cell_2], state_is_tuple=True) # Get LSTM cell output outputs, states = tf.nn.rnn(lstm_cells, _X, dtype=tf.float32) # Get last time step's output feature for a "many to one" style classifier, # as in the image describing RNNs at the top of this page lstm_last_output = outputs[-1] # Linear activation return tf.matmul(lstm_last_output, _weights['out']) + _biases['out'] def extract_batch_size(_train, step, batch_size): # Function to fetch a "batch_size" amount of data from "(X|y)_train" data. shape = list(_train.shape) shape[0] = batch_size batch_s = np.empty(shape) for i in range(batch_size): # Loop index index = ((step-1)*batch_size + i) % len(_train) batch_s[i] = _train[index] return batch_s def one_hot(y_): # Function to encode output labels from number indexes # e.g.: [[5], [0], [3]] --> [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]] y_ = y_.reshape(len(y_)) n_values = np.max(y_) + 1 return np.eye(n_values)[np.array(y_, dtype=np.int32)] # Returns FLOATS # Graph input/output x = tf.placeholder(tf.float32, [None, n_steps, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) # Graph weights weights = { 'hidden': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights 'out': tf.Variable(tf.random_normal([n_hidden, n_classes], mean=1.0)) } biases = { 'hidden': tf.Variable(tf.random_normal([n_hidden])), 'out': tf.Variable(tf.random_normal([n_classes])) } pred = LSTM_RNN(x, weights, biases) # Loss, optimizer and evaluation l2 = lambda_loss_amount * sum( tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables() ) # L2 loss prevents this overkill neural network to overfit the data cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) + l2 # Softmax loss optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # To keep track of training's performance test_losses = [] test_accuracies = [] train_losses = [] train_accuracies = [] # Launch the graph sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=True)) init = tf.initialize_all_variables() sess.run(init) # In each loop, perform training steps with "batch_size" amount of given data step = 1 while step * batch_size <= training_iters: batch_xs = extract_batch_size(X_train, step, batch_size) batch_ys = one_hot(extract_batch_size(y_train, step, batch_size)) # Fit training using batch _, loss, acc = sess.run( [optimizer, cost, accuracy], feed_dict={ x: batch_xs, y: batch_ys } ) train_losses.append(loss) train_accuracies.append(acc) # show network details at specified intervals if (step*batch_size % display_iter == 0) or (step == 1) or (step * batch_size > training_iters): # show accuracy and loss print "Training iter #" + str(step*batch_size) + \ ": Batch Loss = " + "{:.6f}".format(loss) + \ ", Accuracy = {}".format(acc) # evaluate the test set loss, acc = sess.run( [cost, accuracy], feed_dict={ x: X_test, y: one_hot(y_test) } ) test_losses.append(loss) test_accuracies.append(acc) print "PERFORMANCE ON TEST SET: " + \ "Batch Loss = {}".format(loss) + \ ", Accuracy = {}".format(acc) step += 1 # Accuracy for test data one_hot_predictions, accuracy, final_loss = sess.run( [pred, accuracy, cost], feed_dict={ x: X_test, y: one_hot(y_test) } ) test_losses.append(final_loss) test_accuracies.append(accuracy) print "FINAL RESULT: " + \ "Batch Loss = {}".format(final_loss) + \ ", Accuracy = {}".format(accuracy) # (Inline plots: ) #%matplotlib inline font = { 'family' : 'Bitstream Vera Sans', 'weight' : 'bold', 'size' : 18 } matplotlib.rc('font', **font) width = 12 height = 12 plt.figure(figsize=(width, height)) indep_train_axis = np.array(range(batch_size, (len(train_losses)+1)*batch_size, batch_size)) plt.plot(indep_train_axis, np.array(train_losses), "b--", label="Train losses") plt.plot(indep_train_axis, np.array(train_accuracies), "g--", label="Train accuracies") indep_test_axis = np.array(range(batch_size, len(test_losses)*display_iter, display_iter)[:-1] + [training_iters]) plt.plot(indep_test_axis, np.array(test_losses), "b-", label="Test losses") plt.plot(indep_test_axis, np.array(test_accuracies), "g-", label="Test accuracies") plt.title("Training session's progress over iterations") plt.legend(loc='upper right', shadow=True) plt.ylabel('Training Progress (Loss or Accuracy values)') plt.xlabel('Training iteration') plt.show() # Results predictions = one_hot_predictions.argmax(1) print "Testing Accuracy: {}%".format(100*accuracy) print "" print "Precision: {}%".format(100*metrics.precision_score(y_test, predictions, average="weighted")) print "Recall: {}%".format(100*metrics.recall_score(y_test, predictions, average="weighted")) print "f1_score: {}%".format(100*metrics.f1_score(y_test, predictions, average="weighted")) print "" print "Confusion Matrix:" confusion_matrix = metrics.confusion_matrix(y_test, predictions) print confusion_matrix normalised_confusion_matrix = np.array(confusion_matrix, dtype=np.float32)/np.sum(confusion_matrix)*100 print "" print "Confusion matrix (normalised to % of total test data):" print normalised_confusion_matrix print ("Note: training and testing data is not equally distributed amongst classes, " "so it is normal that more than a 6th of the data is correctly classified in the last category.") # Plot Results: width = 12 height = 12 plt.figure(figsize=(width, height)) plt.imshow( normalised_confusion_matrix, interpolation='nearest', cmap=plt.cm.rainbow ) plt.title("Confusion matrix \n(normalised to % of total test data)") plt.colorbar() tick_marks = np.arange(n_classes) plt.xticks(tick_marks, LABELS, rotation=90) plt.yticks(tick_marks, LABELS) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() sess.close()
en
0.811717
# Version r0.10 # Useful Constants # Those are separate normalised input features for the neural network # Output classes to learn how to classify # Load "X" (the neural network's training and testing inputs) # Read dataset from disk, dealing with text files' syntax # Load "y" (the neural network's training and testing outputs) # Read dataset from disk, dealing with text file's syntax # Substract 1 to each output class for friendly 0-based indexing # Input Data # 7352 training series (with 50% overlap between each serie) # 2947 testing series # 128 timesteps per series # 9 input parameters per timestep # LSTM Neural Network's internal structure # Hidden layer num of features # Total classes (should go up, or should go down) # Training # Loop 300 times on the dataset # To show test set accuracy during training # Some debugging info NEW!!!! Model function for CNN. # Input Layer # Convolutional Layer #1 # Pooling Layer #1 # Convolutional Layer #2 and Pooling Layer #2 # Dense Layer # Logits Layer # Calculate Loss (for both TRAIN and EVAL modes) # Configure the Training Op (for TRAIN mode) # Generate Predictions # Return a ModelFnOps object NEW!!!! # Function returns a tensorflow LSTM (RNN) artificial neural network from given parameters. # Moreover, two LSTM cells are stacked which adds deepness to the neural network. # Note, some code of this notebook is inspired from an slightly different # RNN architecture used on another dataset: # https://tensorhub.com/aymericdamien/tensorflow-rnn # (NOTE: This step could be greatly optimised by shaping the dataset once # input shape: (batch_size, n_steps, n_input) # permute n_steps and batch_size # Reshape to prepare input to hidden activation # new shape: (n_steps*batch_size, n_input) # Linear activation # Split data because rnn cell needs a list of inputs for the RNN inner loop # new shape: n_steps * (batch_size, n_hidden) #CNN #1 # Pooling Layer #1 # Convolutional Layer #2 and Pooling Layer #2 # Pooling Layer #2 # Dense Layer # Logits Layer # Define two stacked LSTM cells (two recurrent layers deep) with tensorflow # Get LSTM cell output # Get last time step's output feature for a "many to one" style classifier, # as in the image describing RNNs at the top of this page # Linear activation # Function to fetch a "batch_size" amount of data from "(X|y)_train" data. # Loop index # Function to encode output labels from number indexes # e.g.: [[5], [0], [3]] --> [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]] # Returns FLOATS # Graph input/output # Graph weights # Hidden layer weights # Loss, optimizer and evaluation # L2 loss prevents this overkill neural network to overfit the data # Softmax loss # Adam Optimizer # To keep track of training's performance # Launch the graph # In each loop, perform training steps with "batch_size" amount of given data # Fit training using batch # show network details at specified intervals # show accuracy and loss #" + str(step*batch_size) + \ # evaluate the test set # Accuracy for test data # (Inline plots: ) #%matplotlib inline # Results # Plot Results:
3.113014
3
Retrofit2Server/retrofit2server/app.py
rakeshcusat/Retrofit2-example
0
6624339
from flask import Flask app = Flask(__name__.split('.')[0]) app.debug = True from retrofit2server.controllers.user import create_user_routes # noqa # Setup the routes create_user_routes(app)
from flask import Flask app = Flask(__name__.split('.')[0]) app.debug = True from retrofit2server.controllers.user import create_user_routes # noqa # Setup the routes create_user_routes(app)
en
0.636427
# noqa # Setup the routes
1.868569
2
topasgraphsim/src/resources/TkinterDnD2/__init__.py
sebasj13/topasgraphsim
2
6624340
# dnd actions PRIVATE = 'private' NONE = 'none' ASK = 'ask' COPY = 'copy' MOVE = 'move' LINK = 'link' REFUSE_DROP = 'refuse_drop' # dnd types DND_TEXT = 'DND_Text' DND_FILES = 'DND_Files' DND_ALL = '*' CF_UNICODETEXT = 'CF_UNICODETEXT' CF_TEXT = 'CF_TEXT' CF_HDROP = 'CF_HDROP' FileGroupDescriptor = 'FileGroupDescriptor - FileContents'# ?? FileGroupDescriptorW = 'FileGroupDescriptorW - FileContents'# ?? from TkinterDnD2 import TkinterDnD
# dnd actions PRIVATE = 'private' NONE = 'none' ASK = 'ask' COPY = 'copy' MOVE = 'move' LINK = 'link' REFUSE_DROP = 'refuse_drop' # dnd types DND_TEXT = 'DND_Text' DND_FILES = 'DND_Files' DND_ALL = '*' CF_UNICODETEXT = 'CF_UNICODETEXT' CF_TEXT = 'CF_TEXT' CF_HDROP = 'CF_HDROP' FileGroupDescriptor = 'FileGroupDescriptor - FileContents'# ?? FileGroupDescriptorW = 'FileGroupDescriptorW - FileContents'# ?? from TkinterDnD2 import TkinterDnD
en
0.726105
# dnd actions # dnd types
1.840055
2
Python Book/6. Complex Conditions/8_trade_comissions/trade_comissions.py
alexanderivanov2/Softuni-Software-Engineering
0
6624341
<reponame>alexanderivanov2/Softuni-Software-Engineering<filename>Python Book/6. Complex Conditions/8_trade_comissions/trade_comissions.py city = input().title() s = float(input()) #number of sales comission = 0 error = "error" if city == "Sofia": if 0 <= s <= 500: comission += s * 0.05 elif 500 < s <= 1000: comission += s * 0.07 elif 1000 < s <= 10000: comission += s * 0.08 elif s > 10000: comission += s * 0.12 else: print("error") elif city == "Varna": if 0 <= s <= 500: comission += s * 0.045 elif 500 < s <= 1000: comission += s * 0.075 elif 1000 < s <= 10000: comission += s * 0.10 elif s > 10000: comission += s * 0.13 elif s < 0: error = "error" elif city == "Plovdiv": if 0 <= s <= 500: comission += s * 0.055 elif 500 < s <= 1000: comission += s * 0.08 elif 1000 < s <= 10000: comission += s * 0.12 elif s > 10000: comission += s * 0.145 else: print(error) else: print("error") if comission > 0: print(f"{comission:.2f}")
Book/6. Complex Conditions/8_trade_comissions/trade_comissions.py city = input().title() s = float(input()) #number of sales comission = 0 error = "error" if city == "Sofia": if 0 <= s <= 500: comission += s * 0.05 elif 500 < s <= 1000: comission += s * 0.07 elif 1000 < s <= 10000: comission += s * 0.08 elif s > 10000: comission += s * 0.12 else: print("error") elif city == "Varna": if 0 <= s <= 500: comission += s * 0.045 elif 500 < s <= 1000: comission += s * 0.075 elif 1000 < s <= 10000: comission += s * 0.10 elif s > 10000: comission += s * 0.13 elif s < 0: error = "error" elif city == "Plovdiv": if 0 <= s <= 500: comission += s * 0.055 elif 500 < s <= 1000: comission += s * 0.08 elif 1000 < s <= 10000: comission += s * 0.12 elif s > 10000: comission += s * 0.145 else: print(error) else: print("error") if comission > 0: print(f"{comission:.2f}")
en
0.693578
#number of sales
3.746414
4
email_actions/plugins/exec.py
shantanugoel/fake-email-actions
37
6624342
<gh_stars>10-100 from subprocess import Popen import logging from email_actions.config import read_config_plugin PLUGIN_NAME = 'exec' def exec_notify(filter_name, msg_from, msg_to, msg_subject, msg_content): params = { 'cmd': None, 'args': [], 'env': { 'EA_ENV_MSG_FROM': msg_from, 'EA_ENV_MSG_TO': msg_to, 'EA_ENV_MSG_SUBJECT': msg_subject, 'EA_ENV_MSG_CONTENT': msg_content, } } plugin_cfg = read_config_plugin(filter_name, PLUGIN_NAME) for key in plugin_cfg.keys(): if key == 'env': try: for env_key in plugin_cfg[key].keys(): params[key][env_key] = plugin_cfg[key][env_key] except: # Ignore stray env element in config without any actual env param pass else: params[key] = plugin_cfg[key] if not params['cmd']: logging.error('No command specified for plugin %s' % (PLUGIN_NAME)) return popen_args = [params['cmd']] for arg in params['args']: popen_args.append(arg) Popen(popen_args, env=params['env'])
from subprocess import Popen import logging from email_actions.config import read_config_plugin PLUGIN_NAME = 'exec' def exec_notify(filter_name, msg_from, msg_to, msg_subject, msg_content): params = { 'cmd': None, 'args': [], 'env': { 'EA_ENV_MSG_FROM': msg_from, 'EA_ENV_MSG_TO': msg_to, 'EA_ENV_MSG_SUBJECT': msg_subject, 'EA_ENV_MSG_CONTENT': msg_content, } } plugin_cfg = read_config_plugin(filter_name, PLUGIN_NAME) for key in plugin_cfg.keys(): if key == 'env': try: for env_key in plugin_cfg[key].keys(): params[key][env_key] = plugin_cfg[key][env_key] except: # Ignore stray env element in config without any actual env param pass else: params[key] = plugin_cfg[key] if not params['cmd']: logging.error('No command specified for plugin %s' % (PLUGIN_NAME)) return popen_args = [params['cmd']] for arg in params['args']: popen_args.append(arg) Popen(popen_args, env=params['env'])
en
0.20756
# Ignore stray env element in config without any actual env param
2.280437
2
tests/gis_tests/geoapp/tests.py
lfaraone/python-django-dpkg
0
6624343
from __future__ import unicode_literals import re import tempfile from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union from django.contrib.gis.geos import ( GeometryCollection, GEOSGeometry, LinearRing, LineString, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import connection from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.utils import six from django.utils.deprecation import ( RemovedInDjango20Warning, RemovedInDjango110Warning, ) from ..utils import no_oracle, oracle, postgis, skipUnlessGISLookup, spatialite from .models import ( City, Country, Feature, MinusOneSRID, NonConcreteModel, PennsylvaniaCity, State, Track, ) def postgis_bug_version(): spatial_version = getattr(connection.ops, "spatial_version", (0, 0, 0)) return spatial_version and (2, 0, 0) <= spatial_version <= (2, 0, 1) @skipUnlessDBFeature("gis_enabled") class GeoModelTest(TestCase): fixtures = ['initial'] def test_fixtures(self): "Testing geographic model initialization from fixtures." # Ensuring that data was loaded from initial data fixtures. self.assertEqual(2, Country.objects.count()) self.assertEqual(8, City.objects.count()) self.assertEqual(2, State.objects.count()) def test_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." # Testing on a Point pnt = Point(0, 0) nullcity = City(name='NullCity', point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: try: nullcity.point = bad except TypeError: pass else: self.fail('Should throw a TypeError') # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name='NullCity').point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.save() self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.delete() # Testing on a Polygon shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name='NullState') self.assertEqual(ply, ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. if gdal.HAS_GDAL: self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertIsInstance(ns.poly.srs, gdal.SpatialReference) self.assertEqual('WGS 84', ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual(ply, State.objects.get(name='NullState').poly) ns.delete() @skipUnlessDBFeature("supports_transform") def test_lookup_insert_transform(self): "Testing automatic transform for lookups and inserts." # San Antonio in 'WGS84' (SRID 4326) sa_4326 = 'POINT (-98.493183 29.424170)' wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # Oracle doesn't have SRID 3084, using 41157. if oracle: # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157) # Used the following Oracle SQL to get this value: # SELECT SDO_UTIL.TO_WKTGEOMETRY( # SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) # ) # FROM DUAL; nad_wkt = 'POINT (300662.034646583 5416427.45974934)' nad_srid = 41157 else: # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) # Used ogr.py in gdal 1.4.1 for this transform nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' nad_srid = 3084 # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. nad_pnt = fromstr(nad_wkt, srid=nad_srid) if oracle: tx = Country.objects.get(mpoly__contains=nad_pnt) else: tx = Country.objects.get(mpoly__intersects=nad_pnt) self.assertEqual('Texas', tx.name) # Creating San Antonio. Remember the Alamo. sa = City.objects.create(name='San Antonio', point=nad_pnt) # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name='San Antonio') self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) # If the GeometryField SRID is -1, then we shouldn't perform any # transformation if the SRID of the input geometry is different. if spatialite and connection.ops.spatial_version < (3, 0, 0): # SpatiaLite < 3 does not support missing SRID values. return m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) m1.save() self.assertEqual(-1, m1.geom.srid) def test_createnull(self): "Testing creating a model instance and the geometry being None" c = City() self.assertEqual(c.point, None) def test_geometryfield(self): "Testing the general GeometryField." Feature(name='Point', geom=Point(1, 1)).save() Feature(name='LineString', geom=LineString((0, 0), (1, 1), (5, 5))).save() Feature(name='Polygon', geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0)))).save() Feature(name='GeometryCollection', geom=GeometryCollection(Point(2, 2), LineString((0, 0), (2, 2)), Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))).save() f_1 = Feature.objects.get(name='Point') self.assertIsInstance(f_1.geom, Point) self.assertEqual((1.0, 1.0), f_1.geom.tuple) f_2 = Feature.objects.get(name='LineString') self.assertIsInstance(f_2.geom, LineString) self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple) f_3 = Feature.objects.get(name='Polygon') self.assertIsInstance(f_3.geom, Polygon) f_4 = Feature.objects.get(name='GeometryCollection') self.assertIsInstance(f_4.geom, GeometryCollection) self.assertEqual(f_3.geom, f_4.geom[2]) @skipUnlessDBFeature("supports_transform") def test_inherited_geofields(self): "Test GeoQuerySet methods on inherited Geometry fields." # Creating a Pennsylvanian city. PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)') # All transformation SQL will need to be performed on the # _parent_ table. qs = PennsylvaniaCity.objects.transform(32128) self.assertEqual(1, qs.count()) for pc in qs: self.assertEqual(32128, pc.point.srid) def test_raw_sql_query(self): "Testing raw SQL query." cities1 = City.objects.all() # Only PostGIS would support a 'select *' query because of its recognized # HEXEWKB format for geometry fields as_text = 'ST_AsText(%s)' if postgis else connection.ops.select cities2 = City.objects.raw( 'select id, name, %s from geoapp_city' % as_text % 'point' ) self.assertEqual(len(cities1), len(list(cities2))) self.assertIsInstance(cities2[0].point, Point) def test_dumpdata_loaddata_cycle(self): """ Test a dumpdata/loaddata cycle with geographic data. """ out = six.StringIO() original_data = list(City.objects.all().order_by('name')) call_command('dumpdata', 'geoapp.City', stdout=out) result = out.getvalue() houston = City.objects.get(name='Houston') self.assertIn('"point": "%s"' % houston.point.ewkt, result) # Reload now dumped data with tempfile.NamedTemporaryFile(mode='w', suffix='.json') as tmp: tmp.write(result) tmp.seek(0) call_command('loaddata', tmp.name, verbosity=0) self.assertListEqual(original_data, list(City.objects.all().order_by('name'))) @skipUnlessDBFeature("gis_enabled") class GeoLookupTest(TestCase): fixtures = ['initial'] def test_disjoint_lookup(self): "Testing the `disjoint` lookup type." ptown = City.objects.get(name='Pueblo') qs1 = City.objects.filter(point__disjoint=ptown.point) self.assertEqual(7, qs1.count()) if connection.features.supports_real_shape_operations: qs2 = State.objects.filter(poly__disjoint=ptown.point) self.assertEqual(1, qs2.count()) self.assertEqual('Kansas', qs2[0].name) def test_contains_contained_lookups(self): "Testing the 'contained', 'contains', and 'bbcontains' lookup types." # Getting Texas, yes we were a country -- once ;) texas = Country.objects.get(name='Texas') # Seeing what cities are in Texas, should get Houston and Dallas, # and Oklahoma City because 'contained' only checks on the # _bounding box_ of the Geometries. if connection.features.supports_contained_lookup: qs = City.objects.filter(point__contained=texas.mpoly) self.assertEqual(3, qs.count()) cities = ['Houston', 'Dallas', 'Oklahoma City'] for c in qs: self.assertIn(c.name, cities) # Pulling out some cities. houston = City.objects.get(name='Houston') wellington = City.objects.get(name='Wellington') pueblo = City.objects.get(name='Pueblo') okcity = City.objects.get(name='Oklahoma City') lawrence = City.objects.get(name='Lawrence') # Now testing contains on the countries using the points for # Houston and Wellington. tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry nz = Country.objects.get(mpoly__contains=wellington.point.hex) # Query w/EWKBHEX self.assertEqual('Texas', tx.name) self.assertEqual('New Zealand', nz.name) # Spatialite 2.3 thinks that Lawrence is in Puerto Rico (a NULL geometry). if not (spatialite and connection.ops.spatial_version < (3, 0, 0)): ks = State.objects.get(poly__contains=lawrence.point) self.assertEqual('Kansas', ks.name) # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas) # are not contained in Texas or New Zealand. self.assertEqual(len(Country.objects.filter(mpoly__contains=pueblo.point)), 0) # Query w/GEOSGeometry object self.assertEqual(len(Country.objects.filter(mpoly__contains=okcity.point.wkt)), 0 if connection.features.supports_real_shape_operations else 1) # Query w/WKT # OK City is contained w/in bounding box of Texas. if connection.features.supports_bbcontains_lookup: qs = Country.objects.filter(mpoly__bbcontains=okcity.point) self.assertEqual(1, len(qs)) self.assertEqual('Texas', qs[0].name) @skipUnlessDBFeature("supports_crosses_lookup") def test_crosses_lookup(self): Track.objects.create( name='Line1', line=LineString([(-95, 29), (-60, 0)]) ) self.assertEqual( Track.objects.filter(line__crosses=LineString([(-95, 0), (-60, 29)])).count(), 1 ) self.assertEqual( Track.objects.filter(line__crosses=LineString([(-95, 30), (0, 30)])).count(), 0 ) @skipUnlessDBFeature("supports_left_right_lookups") def test_left_right_lookups(self): "Testing the 'left' and 'right' lookup types." # Left: A << B => true if xmax(A) < xmin(B) # Right: A >> B => true if xmin(A) > xmax(B) # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source. # The left/right lookup tests are known failures on PostGIS 2.0/2.0.1 # http://trac.osgeo.org/postgis/ticket/2035 if postgis_bug_version(): self.skipTest("PostGIS 2.0/2.0.1 left and right lookups are known to be buggy.") # Getting the borders for Colorado & Kansas co_border = State.objects.get(name='Colorado').poly ks_border = State.objects.get(name='Kansas').poly # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. # These cities should be strictly to the right of the CO border. cities = ['Houston', 'Dallas', 'Oklahoma City', 'Lawrence', 'Chicago', 'Wellington'] qs = City.objects.filter(point__right=co_border) self.assertEqual(6, len(qs)) for c in qs: self.assertIn(c.name, cities) # These cities should be strictly to the right of the KS border. cities = ['Chicago', 'Wellington'] qs = City.objects.filter(point__right=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. vic = City.objects.get(point__left=co_border) self.assertEqual('Victoria', vic.name) cities = ['Pueblo', 'Victoria'] qs = City.objects.filter(point__left=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) @skipUnlessGISLookup("strictly_above", "strictly_below") def test_strictly_above_below_lookups(self): dallas = City.objects.get(name='Dallas') self.assertQuerysetEqual( City.objects.filter(point__strictly_above=dallas.point).order_by('name'), ['Chicago', 'Lawrence', 'Oklahoma City', 'Pueblo', 'Victoria'], lambda b: b.name ) self.assertQuerysetEqual( City.objects.filter(point__strictly_below=dallas.point).order_by('name'), ['Houston', 'Wellington'], lambda b: b.name ) def test_equals_lookups(self): "Testing the 'same_as' and 'equals' lookup types." pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326) c1 = City.objects.get(point=pnt) c2 = City.objects.get(point__same_as=pnt) c3 = City.objects.get(point__equals=pnt) for c in [c1, c2, c3]: self.assertEqual('Houston', c.name) @skipUnlessDBFeature("supports_null_geometries") def test_null_geometries(self): "Testing NULL geometry support, and the `isnull` lookup type." # Creating a state with a NULL boundary. State.objects.create(name='Puerto Rico') # Querying for both NULL and Non-NULL values. nullqs = State.objects.filter(poly__isnull=True) validqs = State.objects.filter(poly__isnull=False) # Puerto Rico should be NULL (it's a commonwealth unincorporated territory) self.assertEqual(1, len(nullqs)) self.assertEqual('Puerto Rico', nullqs[0].name) # The valid states should be Colorado & Kansas self.assertEqual(2, len(validqs)) state_names = [s.name for s in validqs] self.assertIn('Colorado', state_names) self.assertIn('Kansas', state_names) # Saving another commonwealth w/a NULL geometry. nmi = State.objects.create(name='Northern Mariana Islands', poly=None) self.assertEqual(nmi.poly, None) # Assigning a geometry and saving -- then UPDATE back to NULL. nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))' nmi.save() State.objects.filter(name='Northern Mariana Islands').update(poly=None) self.assertIsNone(State.objects.get(name='Northern Mariana Islands').poly) @skipUnlessDBFeature("supports_relate_lookup") def test_relate_lookup(self): "Testing the 'relate' lookup type." # To make things more interesting, we will have our Texas reference point in # different SRIDs. pnt1 = fromstr('POINT (649287.0363174 4177429.4494686)', srid=2847) pnt2 = fromstr('POINT(-98.4919715741052 29.4333344025053)', srid=4326) # Not passing in a geometry as first param should # raise a type error when initializing the GeoQuerySet self.assertRaises(ValueError, Country.objects.filter, mpoly__relate=(23, 'foo')) # Making sure the right exception is raised for the given # bad arguments. for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]: qs = Country.objects.filter(mpoly__relate=bad_args) self.assertRaises(e, qs.count) # Relate works differently for the different backends. if postgis or spatialite: contains_mask = 'T*T***FF*' within_mask = 'T*F**F***' intersects_mask = 'T********' elif oracle: contains_mask = 'contains' within_mask = 'inside' # TODO: This is not quite the same as the PostGIS mask above intersects_mask = 'overlapbdyintersect' # Testing contains relation mask. self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name) self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name) # Testing within relation mask. ks = State.objects.get(name='Kansas') self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, within_mask)).name) # Testing intersection relation mask. if not oracle: self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name) self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name) self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, intersects_mask)).name) @skipUnlessDBFeature("gis_enabled") @ignore_warnings(category=RemovedInDjango20Warning) class GeoQuerySetTest(TestCase): fixtures = ['initial'] # Please keep the tests in GeoQuerySet method's alphabetic order @skipUnlessDBFeature("has_centroid_method") def test_centroid(self): "Testing the `centroid` GeoQuerySet method." qs = State.objects.exclude(poly__isnull=True).centroid() if oracle: tol = 0.1 elif spatialite: tol = 0.000001 else: tol = 0.000000001 for s in qs: self.assertTrue(s.poly.centroid.equals_exact(s.centroid, tol)) @skipUnlessDBFeature( "has_difference_method", "has_intersection_method", "has_sym_difference_method", "has_union_method") def test_diff_intersection_union(self): "Testing the `difference`, `intersection`, `sym_difference`, and `union` GeoQuerySet methods." geom = Point(5, 23) qs = Country.objects.all().difference(geom).sym_difference(geom).union(geom) # XXX For some reason SpatiaLite does something screwy with the Texas geometry here. Also, # XXX it doesn't like the null intersection. if spatialite: qs = qs.exclude(name='Texas') else: qs = qs.intersection(geom) for c in qs: if oracle: # Should be able to execute the queries; however, they won't be the same # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or # SpatiaLite). pass else: self.assertEqual(c.mpoly.difference(geom), c.difference) if not spatialite: self.assertEqual(c.mpoly.intersection(geom), c.intersection) # Ordering might differ in collections self.assertSetEqual(set(g.wkt for g in c.mpoly.sym_difference(geom)), set(g.wkt for g in c.sym_difference)) self.assertSetEqual(set(g.wkt for g in c.mpoly.union(geom)), set(g.wkt for g in c.union)) @skipUnlessDBFeature("has_envelope_method") def test_envelope(self): "Testing the `envelope` GeoQuerySet method." countries = Country.objects.all().envelope() for country in countries: self.assertIsInstance(country.envelope, Polygon) @skipUnlessDBFeature("supports_extent_aggr") @ignore_warnings(category=RemovedInDjango110Warning) def test_extent(self): """ Testing the (deprecated) `extent` GeoQuerySet method and the Extent aggregate. """ # Reference query: # `SELECT ST_extent(point) FROM geoapp_city WHERE (name='Houston' or name='Dallas');` # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203) expected = (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820) qs = City.objects.filter(name__in=('Houston', 'Dallas')) extent1 = qs.extent() extent2 = qs.aggregate(Extent('point'))['point__extent'] for extent in (extent1, extent2): for val, exp in zip(extent, expected): self.assertAlmostEqual(exp, val, 4) self.assertIsNone(City.objects.filter(name=('Smalltown')).extent()) self.assertIsNone(City.objects.filter(name=('Smalltown')).aggregate(Extent('point'))['point__extent']) @skipUnlessDBFeature("supports_extent_aggr") def test_extent_with_limit(self): """ Testing if extent supports limit. """ extent1 = City.objects.all().aggregate(Extent('point'))['point__extent'] extent2 = City.objects.all()[:3].aggregate(Extent('point'))['point__extent'] self.assertNotEqual(extent1, extent2) @skipUnlessDBFeature("has_force_rhr_method") def test_force_rhr(self): "Testing GeoQuerySet.force_rhr()." rings = ( ((0, 0), (5, 0), (0, 5), (0, 0)), ((1, 1), (1, 3), (3, 1), (1, 1)), ) rhr_rings = ( ((0, 0), (0, 5), (5, 0), (0, 0)), ((1, 1), (3, 1), (1, 3), (1, 1)), ) State.objects.create(name='Foo', poly=Polygon(*rings)) s = State.objects.force_rhr().get(name='Foo') self.assertEqual(rhr_rings, s.force_rhr.coords) @skipUnlessDBFeature("has_geohash_method") def test_geohash(self): "Testing GeoQuerySet.geohash()." # Reference query: # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston'; # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston'; ref_hash = '9vk1mfq8jx0c8e0386z6' h1 = City.objects.geohash().get(name='Houston') h2 = City.objects.geohash(precision=5).get(name='Houston') self.assertEqual(ref_hash, h1.geohash) self.assertEqual(ref_hash[:5], h2.geohash) def test_geojson(self): "Testing GeoJSON output from the database using GeoQuerySet.geojson()." # Only PostGIS and SpatiaLite 3.0+ support GeoJSON. if not connection.ops.geojson: self.assertRaises(NotImplementedError, Country.objects.all().geojson, field_name='mpoly') return pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' houston_json = ( '{"type":"Point","crs":{"type":"name","properties":' '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}' ) victoria_json = ( '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],' '"coordinates":[-123.305196,48.462611]}' ) chicago_json = ( '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},' '"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}' ) if spatialite: victoria_json = ( '{"type":"Point","bbox":[-123.305196,48.462611,-123.305196,48.462611],' '"coordinates":[-123.305196,48.462611]}' ) # Precision argument should only be an integer self.assertRaises(TypeError, City.objects.geojson, precision='foo') # Reference queries and values. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo'; self.assertEqual(pueblo_json, City.objects.geojson().get(name='Pueblo').geojson) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we want to include the CRS by using the `crs` keyword. self.assertEqual(houston_json, City.objects.geojson(crs=True, model_att='json').get(name='Houston').json) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we include the bounding box by using the `bbox` keyword. self.assertEqual(victoria_json, City.objects.geojson(bbox=True).get(name='Victoria').geojson) # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Chicago'; # Finally, we set every available keyword. self.assertEqual( chicago_json, City.objects.geojson(bbox=True, crs=True, precision=5).get(name='Chicago').geojson ) @skipUnlessDBFeature("has_gml_method") def test_gml(self): "Testing GML output from the database using GeoQuerySet.gml()." # Should throw a TypeError when trying to obtain GML from a # non-geometry field. qs = City.objects.all() self.assertRaises(TypeError, qs.gml, field_name='name') ptown1 = City.objects.gml(field_name='point', precision=9).get(name='Pueblo') ptown2 = City.objects.gml(precision=9).get(name='Pueblo') if oracle: # No precision parameter for Oracle :-/ gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326" xmlns:gml="http://www.opengis.net/gml">' r'<gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ ' r'</gml:coordinates></gml:Point>' ) elif spatialite and connection.ops.spatial_version < (3, 0, 0): # Spatialite before 3.0 has extra colon in SrsName gml_regex = re.compile( r'^<gml:Point SrsName="EPSG::4326"><gml:coordinates decimal="\." ' r'cs="," ts=" ">-104.609251\d+,38.255001</gml:coordinates></gml:Point>' ) else: gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>' r'-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>' ) for ptown in [ptown1, ptown2]: self.assertTrue(gml_regex.match(ptown.gml)) if postgis: self.assertIn('<gml:pos srsDimension="2">', City.objects.gml(version=3).get(name='Pueblo').gml) @skipUnlessDBFeature("has_kml_method") def test_kml(self): "Testing KML output from the database using GeoQuerySet.kml()." # Should throw a TypeError when trying to obtain KML from a # non-geometry field. qs = City.objects.all() self.assertRaises(TypeError, qs.kml, 'name') # Ensuring the KML is as expected. ptown1 = City.objects.kml(field_name='point', precision=9).get(name='Pueblo') ptown2 = City.objects.kml(precision=9).get(name='Pueblo') for ptown in [ptown1, ptown2]: self.assertEqual('<Point><coordinates>-104.609252,38.255001</coordinates></Point>', ptown.kml) @ignore_warnings(category=RemovedInDjango110Warning) def test_make_line(self): """ Testing the (deprecated) `make_line` GeoQuerySet method and the MakeLine aggregate. """ if not connection.features.supports_make_line_aggr: # Only PostGIS has support for the MakeLine aggregate. For other # backends, test that NotImplementedError is raised self.assertRaises( NotImplementedError, City.objects.all().aggregate, MakeLine('point') ) return # Ensuring that a `TypeError` is raised on models without PointFields. self.assertRaises(TypeError, State.objects.make_line) self.assertRaises(TypeError, Country.objects.make_line) # MakeLine on an inappropriate field returns simply None self.assertIsNone(State.objects.aggregate(MakeLine('poly'))['poly__makeline']) # Reference query: # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city; ref_line = GEOSGeometry( 'LINESTRING(-95.363151 29.763374,-96.801611 32.782057,' '-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,' '-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)', srid=4326 ) # We check for equality with a tolerance of 10e-5 which is a lower bound # of the precisions of ref_line coordinates line1 = City.objects.make_line() line2 = City.objects.aggregate(MakeLine('point'))['point__makeline'] for line in (line1, line2): self.assertTrue(ref_line.equals_exact(line, tolerance=10e-5), "%s != %s" % (ref_line, line)) @skipUnlessDBFeature("has_num_geom_method") def test_num_geom(self): "Testing the `num_geom` GeoQuerySet method." # Both 'countries' only have two geometries. for c in Country.objects.num_geom(): self.assertEqual(2, c.num_geom) for c in City.objects.filter(point__isnull=False).num_geom(): # Oracle and PostGIS 2.0+ will return 1 for the number of # geometries on non-collections. self.assertEqual(1, c.num_geom) @skipUnlessDBFeature("supports_num_points_poly") def test_num_points(self): "Testing the `num_points` GeoQuerySet method." for c in Country.objects.num_points(): self.assertEqual(c.mpoly.num_points, c.num_points) if not oracle: # Oracle cannot count vertices in Point geometries. for c in City.objects.num_points(): self.assertEqual(1, c.num_points) @skipUnlessDBFeature("has_point_on_surface_method") def test_point_on_surface(self): "Testing the `point_on_surface` GeoQuerySet method." # Reference values. if oracle: # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05)) # FROM GEOAPP_COUNTRY; ref = {'New Zealand': fromstr('POINT (174.616364 -36.100861)', srid=4326), 'Texas': fromstr('POINT (-103.002434 36.500397)', srid=4326), } else: # Using GEOSGeometry to compute the reference point on surface values # -- since PostGIS also uses GEOS these should be the same. ref = {'New Zealand': Country.objects.get(name='New Zealand').mpoly.point_on_surface, 'Texas': Country.objects.get(name='Texas').mpoly.point_on_surface } for c in Country.objects.point_on_surface(): if spatialite: # XXX This seems to be a WKT-translation-related precision issue? tol = 0.00001 else: tol = 0.000000001 self.assertTrue(ref[c.name].equals_exact(c.point_on_surface, tol)) @skipUnlessDBFeature("has_reverse_method") def test_reverse_geom(self): "Testing GeoQuerySet.reverse_geom()." coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name='Foo', line=LineString(coords)) t = Track.objects.reverse_geom().get(name='Foo') coords.reverse() self.assertEqual(tuple(coords), t.reverse_geom.coords) if oracle: self.assertRaises(TypeError, State.objects.reverse_geom) @skipUnlessDBFeature("has_scale_method") def test_scale(self): "Testing the `scale` GeoQuerySet method." xfac, yfac = 2, 3 tol = 5 # XXX The low precision tolerance is for SpatiaLite qs = Country.objects.scale(xfac, yfac, model_att='scaled') for c in qs: for p1, p2 in zip(c.mpoly, c.scaled): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): self.assertAlmostEqual(c1[0] * xfac, c2[0], tol) self.assertAlmostEqual(c1[1] * yfac, c2[1], tol) @skipUnlessDBFeature("has_snap_to_grid_method") def test_snap_to_grid(self): "Testing GeoQuerySet.snap_to_grid()." # Let's try and break snap_to_grid() with bad combinations of arguments. for bad_args in ((), range(3), range(5)): self.assertRaises(ValueError, Country.objects.snap_to_grid, *bad_args) for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))): self.assertRaises(TypeError, Country.objects.snap_to_grid, *bad_args) # Boundary for San Marino, courtesy of <NAME> of thematicmapping.org # from the world borders dataset he provides. wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,' '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,' '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,' '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,' '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,' '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,' '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,' '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))') Country.objects.create(name='San Marino', mpoly=fromstr(wkt)) # Because floating-point arithmetic isn't exact, we set a tolerance # to pass into GEOS `equals_exact`. tol = 0.000000001 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))') self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.1).get(name='San Marino').snap_to_grid, tol)) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))') self.assertTrue( ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23).get(name='San Marino').snap_to_grid, tol) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr( 'MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))' ) self.assertTrue( ref.equals_exact( Country.objects.snap_to_grid(0.05, 0.23, 0.5, 0.17).get(name='San Marino').snap_to_grid, tol ) ) @skipUnlessDBFeature("has_svg_method") def test_svg(self): "Testing SVG output using GeoQuerySet.svg()." self.assertRaises(TypeError, City.objects.svg, precision='foo') # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo'; svg1 = 'cx="-104.609252" cy="-38.255001"' # Even though relative, only one point so it's practically the same except for # the 'c' letter prefix on the x,y values. svg2 = svg1.replace('c', '') self.assertEqual(svg1, City.objects.svg().get(name='Pueblo').svg) self.assertEqual(svg2, City.objects.svg(relative=5).get(name='Pueblo').svg) @skipUnlessDBFeature("has_transform_method") def test_transform(self): "Testing the transform() GeoQuerySet method." # Pre-transformed points for Houston and Pueblo. htown = fromstr('POINT(1947516.83115183 6322297.06040572)', srid=3084) ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774) prec = 3 # Precision is low due to version variations in PROJ and GDAL. # Asserting the result of the transform operation with the values in # the pre-transformed points. Oracle does not have the 3084 SRID. if not oracle: h = City.objects.transform(htown.srid).get(name='Houston') self.assertEqual(3084, h.point.srid) self.assertAlmostEqual(htown.x, h.point.x, prec) self.assertAlmostEqual(htown.y, h.point.y, prec) p1 = City.objects.transform(ptown.srid, field_name='point').get(name='Pueblo') p2 = City.objects.transform(srid=ptown.srid).get(name='Pueblo') for p in [p1, p2]: self.assertEqual(2774, p.point.srid) self.assertAlmostEqual(ptown.x, p.point.x, prec) self.assertAlmostEqual(ptown.y, p.point.y, prec) @skipUnlessDBFeature("has_translate_method") def test_translate(self): "Testing the `translate` GeoQuerySet method." xfac, yfac = 5, -23 qs = Country.objects.translate(xfac, yfac, model_att='translated') for c in qs: for p1, p2 in zip(c.mpoly, c.translated): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): # XXX The low precision is for SpatiaLite self.assertAlmostEqual(c1[0] + xfac, c2[0], 5) self.assertAlmostEqual(c1[1] + yfac, c2[1], 5) # TODO: Oracle can be made to pass if # union1 = union2 = fromstr('POINT (-97.5211570000000023 34.4646419999999978)') # but this seems unexpected and should be investigated to determine the cause. @skipUnlessDBFeature("has_unionagg_method") @no_oracle @ignore_warnings(category=RemovedInDjango110Warning) def test_unionagg(self): """ Testing the (deprecated) `unionagg` (aggregate union) GeoQuerySet method and the Union aggregate. """ tx = Country.objects.get(name='Texas').mpoly # Houston, Dallas -- Ordering may differ depending on backend or GEOS version. union1 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)') union2 = fromstr('MULTIPOINT(-95.363151 29.763374,-96.801611 32.782057)') qs = City.objects.filter(point__within=tx) self.assertRaises(TypeError, qs.unionagg, 'name') self.assertRaises(ValueError, qs.aggregate, Union('name')) # Using `field_name` keyword argument in one query and specifying an # order in the other (which should not be used because this is # an aggregate method on a spatial column) u1 = qs.unionagg(field_name='point') u2 = qs.order_by('name').unionagg() u3 = qs.aggregate(Union('point'))['point__union'] u4 = qs.order_by('name').aggregate(Union('point'))['point__union'] tol = 0.00001 self.assertTrue(union1.equals_exact(u1, tol) or union2.equals_exact(u1, tol)) self.assertTrue(union1.equals_exact(u2, tol) or union2.equals_exact(u2, tol)) self.assertTrue(union1.equals_exact(u3, tol) or union2.equals_exact(u3, tol)) self.assertTrue(union1.equals_exact(u4, tol) or union2.equals_exact(u4, tol)) qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.unionagg(field_name='point')) self.assertIsNone(qs.aggregate(Union('point'))['point__union']) def test_within_subquery(self): """ Test that using a queryset inside a geo lookup is working (using a subquery) (#14483). """ tex_cities = City.objects.filter( point__within=Country.objects.filter(name='Texas').values('mpoly')).order_by('name') expected = ['Dallas', 'Houston'] if not connection.features.supports_real_shape_operations: expected.append('Oklahoma City') self.assertEqual( list(tex_cities.values_list('name', flat=True)), expected ) def test_non_concrete_field(self): NonConcreteModel.objects.create(point=Point(0, 0), name='name') list(NonConcreteModel.objects.all())
from __future__ import unicode_literals import re import tempfile from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union from django.contrib.gis.geos import ( GeometryCollection, GEOSGeometry, LinearRing, LineString, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import connection from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.utils import six from django.utils.deprecation import ( RemovedInDjango20Warning, RemovedInDjango110Warning, ) from ..utils import no_oracle, oracle, postgis, skipUnlessGISLookup, spatialite from .models import ( City, Country, Feature, MinusOneSRID, NonConcreteModel, PennsylvaniaCity, State, Track, ) def postgis_bug_version(): spatial_version = getattr(connection.ops, "spatial_version", (0, 0, 0)) return spatial_version and (2, 0, 0) <= spatial_version <= (2, 0, 1) @skipUnlessDBFeature("gis_enabled") class GeoModelTest(TestCase): fixtures = ['initial'] def test_fixtures(self): "Testing geographic model initialization from fixtures." # Ensuring that data was loaded from initial data fixtures. self.assertEqual(2, Country.objects.count()) self.assertEqual(8, City.objects.count()) self.assertEqual(2, State.objects.count()) def test_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." # Testing on a Point pnt = Point(0, 0) nullcity = City(name='NullCity', point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: try: nullcity.point = bad except TypeError: pass else: self.fail('Should throw a TypeError') # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name='NullCity').point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.save() self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.delete() # Testing on a Polygon shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name='NullState') self.assertEqual(ply, ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. if gdal.HAS_GDAL: self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertIsInstance(ns.poly.srs, gdal.SpatialReference) self.assertEqual('WGS 84', ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual(ply, State.objects.get(name='NullState').poly) ns.delete() @skipUnlessDBFeature("supports_transform") def test_lookup_insert_transform(self): "Testing automatic transform for lookups and inserts." # San Antonio in 'WGS84' (SRID 4326) sa_4326 = 'POINT (-98.493183 29.424170)' wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # Oracle doesn't have SRID 3084, using 41157. if oracle: # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157) # Used the following Oracle SQL to get this value: # SELECT SDO_UTIL.TO_WKTGEOMETRY( # SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) # ) # FROM DUAL; nad_wkt = 'POINT (300662.034646583 5416427.45974934)' nad_srid = 41157 else: # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) # Used ogr.py in gdal 1.4.1 for this transform nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' nad_srid = 3084 # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. nad_pnt = fromstr(nad_wkt, srid=nad_srid) if oracle: tx = Country.objects.get(mpoly__contains=nad_pnt) else: tx = Country.objects.get(mpoly__intersects=nad_pnt) self.assertEqual('Texas', tx.name) # Creating San Antonio. Remember the Alamo. sa = City.objects.create(name='San Antonio', point=nad_pnt) # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name='San Antonio') self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) # If the GeometryField SRID is -1, then we shouldn't perform any # transformation if the SRID of the input geometry is different. if spatialite and connection.ops.spatial_version < (3, 0, 0): # SpatiaLite < 3 does not support missing SRID values. return m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) m1.save() self.assertEqual(-1, m1.geom.srid) def test_createnull(self): "Testing creating a model instance and the geometry being None" c = City() self.assertEqual(c.point, None) def test_geometryfield(self): "Testing the general GeometryField." Feature(name='Point', geom=Point(1, 1)).save() Feature(name='LineString', geom=LineString((0, 0), (1, 1), (5, 5))).save() Feature(name='Polygon', geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0)))).save() Feature(name='GeometryCollection', geom=GeometryCollection(Point(2, 2), LineString((0, 0), (2, 2)), Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))).save() f_1 = Feature.objects.get(name='Point') self.assertIsInstance(f_1.geom, Point) self.assertEqual((1.0, 1.0), f_1.geom.tuple) f_2 = Feature.objects.get(name='LineString') self.assertIsInstance(f_2.geom, LineString) self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple) f_3 = Feature.objects.get(name='Polygon') self.assertIsInstance(f_3.geom, Polygon) f_4 = Feature.objects.get(name='GeometryCollection') self.assertIsInstance(f_4.geom, GeometryCollection) self.assertEqual(f_3.geom, f_4.geom[2]) @skipUnlessDBFeature("supports_transform") def test_inherited_geofields(self): "Test GeoQuerySet methods on inherited Geometry fields." # Creating a Pennsylvanian city. PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)') # All transformation SQL will need to be performed on the # _parent_ table. qs = PennsylvaniaCity.objects.transform(32128) self.assertEqual(1, qs.count()) for pc in qs: self.assertEqual(32128, pc.point.srid) def test_raw_sql_query(self): "Testing raw SQL query." cities1 = City.objects.all() # Only PostGIS would support a 'select *' query because of its recognized # HEXEWKB format for geometry fields as_text = 'ST_AsText(%s)' if postgis else connection.ops.select cities2 = City.objects.raw( 'select id, name, %s from geoapp_city' % as_text % 'point' ) self.assertEqual(len(cities1), len(list(cities2))) self.assertIsInstance(cities2[0].point, Point) def test_dumpdata_loaddata_cycle(self): """ Test a dumpdata/loaddata cycle with geographic data. """ out = six.StringIO() original_data = list(City.objects.all().order_by('name')) call_command('dumpdata', 'geoapp.City', stdout=out) result = out.getvalue() houston = City.objects.get(name='Houston') self.assertIn('"point": "%s"' % houston.point.ewkt, result) # Reload now dumped data with tempfile.NamedTemporaryFile(mode='w', suffix='.json') as tmp: tmp.write(result) tmp.seek(0) call_command('loaddata', tmp.name, verbosity=0) self.assertListEqual(original_data, list(City.objects.all().order_by('name'))) @skipUnlessDBFeature("gis_enabled") class GeoLookupTest(TestCase): fixtures = ['initial'] def test_disjoint_lookup(self): "Testing the `disjoint` lookup type." ptown = City.objects.get(name='Pueblo') qs1 = City.objects.filter(point__disjoint=ptown.point) self.assertEqual(7, qs1.count()) if connection.features.supports_real_shape_operations: qs2 = State.objects.filter(poly__disjoint=ptown.point) self.assertEqual(1, qs2.count()) self.assertEqual('Kansas', qs2[0].name) def test_contains_contained_lookups(self): "Testing the 'contained', 'contains', and 'bbcontains' lookup types." # Getting Texas, yes we were a country -- once ;) texas = Country.objects.get(name='Texas') # Seeing what cities are in Texas, should get Houston and Dallas, # and Oklahoma City because 'contained' only checks on the # _bounding box_ of the Geometries. if connection.features.supports_contained_lookup: qs = City.objects.filter(point__contained=texas.mpoly) self.assertEqual(3, qs.count()) cities = ['Houston', 'Dallas', 'Oklahoma City'] for c in qs: self.assertIn(c.name, cities) # Pulling out some cities. houston = City.objects.get(name='Houston') wellington = City.objects.get(name='Wellington') pueblo = City.objects.get(name='Pueblo') okcity = City.objects.get(name='Oklahoma City') lawrence = City.objects.get(name='Lawrence') # Now testing contains on the countries using the points for # Houston and Wellington. tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry nz = Country.objects.get(mpoly__contains=wellington.point.hex) # Query w/EWKBHEX self.assertEqual('Texas', tx.name) self.assertEqual('New Zealand', nz.name) # Spatialite 2.3 thinks that Lawrence is in Puerto Rico (a NULL geometry). if not (spatialite and connection.ops.spatial_version < (3, 0, 0)): ks = State.objects.get(poly__contains=lawrence.point) self.assertEqual('Kansas', ks.name) # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas) # are not contained in Texas or New Zealand. self.assertEqual(len(Country.objects.filter(mpoly__contains=pueblo.point)), 0) # Query w/GEOSGeometry object self.assertEqual(len(Country.objects.filter(mpoly__contains=okcity.point.wkt)), 0 if connection.features.supports_real_shape_operations else 1) # Query w/WKT # OK City is contained w/in bounding box of Texas. if connection.features.supports_bbcontains_lookup: qs = Country.objects.filter(mpoly__bbcontains=okcity.point) self.assertEqual(1, len(qs)) self.assertEqual('Texas', qs[0].name) @skipUnlessDBFeature("supports_crosses_lookup") def test_crosses_lookup(self): Track.objects.create( name='Line1', line=LineString([(-95, 29), (-60, 0)]) ) self.assertEqual( Track.objects.filter(line__crosses=LineString([(-95, 0), (-60, 29)])).count(), 1 ) self.assertEqual( Track.objects.filter(line__crosses=LineString([(-95, 30), (0, 30)])).count(), 0 ) @skipUnlessDBFeature("supports_left_right_lookups") def test_left_right_lookups(self): "Testing the 'left' and 'right' lookup types." # Left: A << B => true if xmax(A) < xmin(B) # Right: A >> B => true if xmin(A) > xmax(B) # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source. # The left/right lookup tests are known failures on PostGIS 2.0/2.0.1 # http://trac.osgeo.org/postgis/ticket/2035 if postgis_bug_version(): self.skipTest("PostGIS 2.0/2.0.1 left and right lookups are known to be buggy.") # Getting the borders for Colorado & Kansas co_border = State.objects.get(name='Colorado').poly ks_border = State.objects.get(name='Kansas').poly # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. # These cities should be strictly to the right of the CO border. cities = ['Houston', 'Dallas', 'Oklahoma City', 'Lawrence', 'Chicago', 'Wellington'] qs = City.objects.filter(point__right=co_border) self.assertEqual(6, len(qs)) for c in qs: self.assertIn(c.name, cities) # These cities should be strictly to the right of the KS border. cities = ['Chicago', 'Wellington'] qs = City.objects.filter(point__right=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. vic = City.objects.get(point__left=co_border) self.assertEqual('Victoria', vic.name) cities = ['Pueblo', 'Victoria'] qs = City.objects.filter(point__left=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) @skipUnlessGISLookup("strictly_above", "strictly_below") def test_strictly_above_below_lookups(self): dallas = City.objects.get(name='Dallas') self.assertQuerysetEqual( City.objects.filter(point__strictly_above=dallas.point).order_by('name'), ['Chicago', 'Lawrence', 'Oklahoma City', 'Pueblo', 'Victoria'], lambda b: b.name ) self.assertQuerysetEqual( City.objects.filter(point__strictly_below=dallas.point).order_by('name'), ['Houston', 'Wellington'], lambda b: b.name ) def test_equals_lookups(self): "Testing the 'same_as' and 'equals' lookup types." pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326) c1 = City.objects.get(point=pnt) c2 = City.objects.get(point__same_as=pnt) c3 = City.objects.get(point__equals=pnt) for c in [c1, c2, c3]: self.assertEqual('Houston', c.name) @skipUnlessDBFeature("supports_null_geometries") def test_null_geometries(self): "Testing NULL geometry support, and the `isnull` lookup type." # Creating a state with a NULL boundary. State.objects.create(name='Puerto Rico') # Querying for both NULL and Non-NULL values. nullqs = State.objects.filter(poly__isnull=True) validqs = State.objects.filter(poly__isnull=False) # Puerto Rico should be NULL (it's a commonwealth unincorporated territory) self.assertEqual(1, len(nullqs)) self.assertEqual('Puerto Rico', nullqs[0].name) # The valid states should be Colorado & Kansas self.assertEqual(2, len(validqs)) state_names = [s.name for s in validqs] self.assertIn('Colorado', state_names) self.assertIn('Kansas', state_names) # Saving another commonwealth w/a NULL geometry. nmi = State.objects.create(name='Northern Mariana Islands', poly=None) self.assertEqual(nmi.poly, None) # Assigning a geometry and saving -- then UPDATE back to NULL. nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))' nmi.save() State.objects.filter(name='Northern Mariana Islands').update(poly=None) self.assertIsNone(State.objects.get(name='Northern Mariana Islands').poly) @skipUnlessDBFeature("supports_relate_lookup") def test_relate_lookup(self): "Testing the 'relate' lookup type." # To make things more interesting, we will have our Texas reference point in # different SRIDs. pnt1 = fromstr('POINT (649287.0363174 4177429.4494686)', srid=2847) pnt2 = fromstr('POINT(-98.4919715741052 29.4333344025053)', srid=4326) # Not passing in a geometry as first param should # raise a type error when initializing the GeoQuerySet self.assertRaises(ValueError, Country.objects.filter, mpoly__relate=(23, 'foo')) # Making sure the right exception is raised for the given # bad arguments. for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]: qs = Country.objects.filter(mpoly__relate=bad_args) self.assertRaises(e, qs.count) # Relate works differently for the different backends. if postgis or spatialite: contains_mask = 'T*T***FF*' within_mask = 'T*F**F***' intersects_mask = 'T********' elif oracle: contains_mask = 'contains' within_mask = 'inside' # TODO: This is not quite the same as the PostGIS mask above intersects_mask = 'overlapbdyintersect' # Testing contains relation mask. self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name) self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name) # Testing within relation mask. ks = State.objects.get(name='Kansas') self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, within_mask)).name) # Testing intersection relation mask. if not oracle: self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name) self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name) self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, intersects_mask)).name) @skipUnlessDBFeature("gis_enabled") @ignore_warnings(category=RemovedInDjango20Warning) class GeoQuerySetTest(TestCase): fixtures = ['initial'] # Please keep the tests in GeoQuerySet method's alphabetic order @skipUnlessDBFeature("has_centroid_method") def test_centroid(self): "Testing the `centroid` GeoQuerySet method." qs = State.objects.exclude(poly__isnull=True).centroid() if oracle: tol = 0.1 elif spatialite: tol = 0.000001 else: tol = 0.000000001 for s in qs: self.assertTrue(s.poly.centroid.equals_exact(s.centroid, tol)) @skipUnlessDBFeature( "has_difference_method", "has_intersection_method", "has_sym_difference_method", "has_union_method") def test_diff_intersection_union(self): "Testing the `difference`, `intersection`, `sym_difference`, and `union` GeoQuerySet methods." geom = Point(5, 23) qs = Country.objects.all().difference(geom).sym_difference(geom).union(geom) # XXX For some reason SpatiaLite does something screwy with the Texas geometry here. Also, # XXX it doesn't like the null intersection. if spatialite: qs = qs.exclude(name='Texas') else: qs = qs.intersection(geom) for c in qs: if oracle: # Should be able to execute the queries; however, they won't be the same # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or # SpatiaLite). pass else: self.assertEqual(c.mpoly.difference(geom), c.difference) if not spatialite: self.assertEqual(c.mpoly.intersection(geom), c.intersection) # Ordering might differ in collections self.assertSetEqual(set(g.wkt for g in c.mpoly.sym_difference(geom)), set(g.wkt for g in c.sym_difference)) self.assertSetEqual(set(g.wkt for g in c.mpoly.union(geom)), set(g.wkt for g in c.union)) @skipUnlessDBFeature("has_envelope_method") def test_envelope(self): "Testing the `envelope` GeoQuerySet method." countries = Country.objects.all().envelope() for country in countries: self.assertIsInstance(country.envelope, Polygon) @skipUnlessDBFeature("supports_extent_aggr") @ignore_warnings(category=RemovedInDjango110Warning) def test_extent(self): """ Testing the (deprecated) `extent` GeoQuerySet method and the Extent aggregate. """ # Reference query: # `SELECT ST_extent(point) FROM geoapp_city WHERE (name='Houston' or name='Dallas');` # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203) expected = (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820) qs = City.objects.filter(name__in=('Houston', 'Dallas')) extent1 = qs.extent() extent2 = qs.aggregate(Extent('point'))['point__extent'] for extent in (extent1, extent2): for val, exp in zip(extent, expected): self.assertAlmostEqual(exp, val, 4) self.assertIsNone(City.objects.filter(name=('Smalltown')).extent()) self.assertIsNone(City.objects.filter(name=('Smalltown')).aggregate(Extent('point'))['point__extent']) @skipUnlessDBFeature("supports_extent_aggr") def test_extent_with_limit(self): """ Testing if extent supports limit. """ extent1 = City.objects.all().aggregate(Extent('point'))['point__extent'] extent2 = City.objects.all()[:3].aggregate(Extent('point'))['point__extent'] self.assertNotEqual(extent1, extent2) @skipUnlessDBFeature("has_force_rhr_method") def test_force_rhr(self): "Testing GeoQuerySet.force_rhr()." rings = ( ((0, 0), (5, 0), (0, 5), (0, 0)), ((1, 1), (1, 3), (3, 1), (1, 1)), ) rhr_rings = ( ((0, 0), (0, 5), (5, 0), (0, 0)), ((1, 1), (3, 1), (1, 3), (1, 1)), ) State.objects.create(name='Foo', poly=Polygon(*rings)) s = State.objects.force_rhr().get(name='Foo') self.assertEqual(rhr_rings, s.force_rhr.coords) @skipUnlessDBFeature("has_geohash_method") def test_geohash(self): "Testing GeoQuerySet.geohash()." # Reference query: # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston'; # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston'; ref_hash = '9vk1mfq8jx0c8e0386z6' h1 = City.objects.geohash().get(name='Houston') h2 = City.objects.geohash(precision=5).get(name='Houston') self.assertEqual(ref_hash, h1.geohash) self.assertEqual(ref_hash[:5], h2.geohash) def test_geojson(self): "Testing GeoJSON output from the database using GeoQuerySet.geojson()." # Only PostGIS and SpatiaLite 3.0+ support GeoJSON. if not connection.ops.geojson: self.assertRaises(NotImplementedError, Country.objects.all().geojson, field_name='mpoly') return pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' houston_json = ( '{"type":"Point","crs":{"type":"name","properties":' '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}' ) victoria_json = ( '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],' '"coordinates":[-123.305196,48.462611]}' ) chicago_json = ( '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},' '"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}' ) if spatialite: victoria_json = ( '{"type":"Point","bbox":[-123.305196,48.462611,-123.305196,48.462611],' '"coordinates":[-123.305196,48.462611]}' ) # Precision argument should only be an integer self.assertRaises(TypeError, City.objects.geojson, precision='foo') # Reference queries and values. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo'; self.assertEqual(pueblo_json, City.objects.geojson().get(name='Pueblo').geojson) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we want to include the CRS by using the `crs` keyword. self.assertEqual(houston_json, City.objects.geojson(crs=True, model_att='json').get(name='Houston').json) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we include the bounding box by using the `bbox` keyword. self.assertEqual(victoria_json, City.objects.geojson(bbox=True).get(name='Victoria').geojson) # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Chicago'; # Finally, we set every available keyword. self.assertEqual( chicago_json, City.objects.geojson(bbox=True, crs=True, precision=5).get(name='Chicago').geojson ) @skipUnlessDBFeature("has_gml_method") def test_gml(self): "Testing GML output from the database using GeoQuerySet.gml()." # Should throw a TypeError when trying to obtain GML from a # non-geometry field. qs = City.objects.all() self.assertRaises(TypeError, qs.gml, field_name='name') ptown1 = City.objects.gml(field_name='point', precision=9).get(name='Pueblo') ptown2 = City.objects.gml(precision=9).get(name='Pueblo') if oracle: # No precision parameter for Oracle :-/ gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326" xmlns:gml="http://www.opengis.net/gml">' r'<gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ ' r'</gml:coordinates></gml:Point>' ) elif spatialite and connection.ops.spatial_version < (3, 0, 0): # Spatialite before 3.0 has extra colon in SrsName gml_regex = re.compile( r'^<gml:Point SrsName="EPSG::4326"><gml:coordinates decimal="\." ' r'cs="," ts=" ">-104.609251\d+,38.255001</gml:coordinates></gml:Point>' ) else: gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>' r'-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>' ) for ptown in [ptown1, ptown2]: self.assertTrue(gml_regex.match(ptown.gml)) if postgis: self.assertIn('<gml:pos srsDimension="2">', City.objects.gml(version=3).get(name='Pueblo').gml) @skipUnlessDBFeature("has_kml_method") def test_kml(self): "Testing KML output from the database using GeoQuerySet.kml()." # Should throw a TypeError when trying to obtain KML from a # non-geometry field. qs = City.objects.all() self.assertRaises(TypeError, qs.kml, 'name') # Ensuring the KML is as expected. ptown1 = City.objects.kml(field_name='point', precision=9).get(name='Pueblo') ptown2 = City.objects.kml(precision=9).get(name='Pueblo') for ptown in [ptown1, ptown2]: self.assertEqual('<Point><coordinates>-104.609252,38.255001</coordinates></Point>', ptown.kml) @ignore_warnings(category=RemovedInDjango110Warning) def test_make_line(self): """ Testing the (deprecated) `make_line` GeoQuerySet method and the MakeLine aggregate. """ if not connection.features.supports_make_line_aggr: # Only PostGIS has support for the MakeLine aggregate. For other # backends, test that NotImplementedError is raised self.assertRaises( NotImplementedError, City.objects.all().aggregate, MakeLine('point') ) return # Ensuring that a `TypeError` is raised on models without PointFields. self.assertRaises(TypeError, State.objects.make_line) self.assertRaises(TypeError, Country.objects.make_line) # MakeLine on an inappropriate field returns simply None self.assertIsNone(State.objects.aggregate(MakeLine('poly'))['poly__makeline']) # Reference query: # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city; ref_line = GEOSGeometry( 'LINESTRING(-95.363151 29.763374,-96.801611 32.782057,' '-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,' '-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)', srid=4326 ) # We check for equality with a tolerance of 10e-5 which is a lower bound # of the precisions of ref_line coordinates line1 = City.objects.make_line() line2 = City.objects.aggregate(MakeLine('point'))['point__makeline'] for line in (line1, line2): self.assertTrue(ref_line.equals_exact(line, tolerance=10e-5), "%s != %s" % (ref_line, line)) @skipUnlessDBFeature("has_num_geom_method") def test_num_geom(self): "Testing the `num_geom` GeoQuerySet method." # Both 'countries' only have two geometries. for c in Country.objects.num_geom(): self.assertEqual(2, c.num_geom) for c in City.objects.filter(point__isnull=False).num_geom(): # Oracle and PostGIS 2.0+ will return 1 for the number of # geometries on non-collections. self.assertEqual(1, c.num_geom) @skipUnlessDBFeature("supports_num_points_poly") def test_num_points(self): "Testing the `num_points` GeoQuerySet method." for c in Country.objects.num_points(): self.assertEqual(c.mpoly.num_points, c.num_points) if not oracle: # Oracle cannot count vertices in Point geometries. for c in City.objects.num_points(): self.assertEqual(1, c.num_points) @skipUnlessDBFeature("has_point_on_surface_method") def test_point_on_surface(self): "Testing the `point_on_surface` GeoQuerySet method." # Reference values. if oracle: # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05)) # FROM GEOAPP_COUNTRY; ref = {'New Zealand': fromstr('POINT (174.616364 -36.100861)', srid=4326), 'Texas': fromstr('POINT (-103.002434 36.500397)', srid=4326), } else: # Using GEOSGeometry to compute the reference point on surface values # -- since PostGIS also uses GEOS these should be the same. ref = {'New Zealand': Country.objects.get(name='New Zealand').mpoly.point_on_surface, 'Texas': Country.objects.get(name='Texas').mpoly.point_on_surface } for c in Country.objects.point_on_surface(): if spatialite: # XXX This seems to be a WKT-translation-related precision issue? tol = 0.00001 else: tol = 0.000000001 self.assertTrue(ref[c.name].equals_exact(c.point_on_surface, tol)) @skipUnlessDBFeature("has_reverse_method") def test_reverse_geom(self): "Testing GeoQuerySet.reverse_geom()." coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name='Foo', line=LineString(coords)) t = Track.objects.reverse_geom().get(name='Foo') coords.reverse() self.assertEqual(tuple(coords), t.reverse_geom.coords) if oracle: self.assertRaises(TypeError, State.objects.reverse_geom) @skipUnlessDBFeature("has_scale_method") def test_scale(self): "Testing the `scale` GeoQuerySet method." xfac, yfac = 2, 3 tol = 5 # XXX The low precision tolerance is for SpatiaLite qs = Country.objects.scale(xfac, yfac, model_att='scaled') for c in qs: for p1, p2 in zip(c.mpoly, c.scaled): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): self.assertAlmostEqual(c1[0] * xfac, c2[0], tol) self.assertAlmostEqual(c1[1] * yfac, c2[1], tol) @skipUnlessDBFeature("has_snap_to_grid_method") def test_snap_to_grid(self): "Testing GeoQuerySet.snap_to_grid()." # Let's try and break snap_to_grid() with bad combinations of arguments. for bad_args in ((), range(3), range(5)): self.assertRaises(ValueError, Country.objects.snap_to_grid, *bad_args) for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))): self.assertRaises(TypeError, Country.objects.snap_to_grid, *bad_args) # Boundary for San Marino, courtesy of <NAME> of thematicmapping.org # from the world borders dataset he provides. wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,' '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,' '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,' '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,' '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,' '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,' '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,' '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))') Country.objects.create(name='San Marino', mpoly=fromstr(wkt)) # Because floating-point arithmetic isn't exact, we set a tolerance # to pass into GEOS `equals_exact`. tol = 0.000000001 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))') self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.1).get(name='San Marino').snap_to_grid, tol)) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))') self.assertTrue( ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23).get(name='San Marino').snap_to_grid, tol) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr( 'MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))' ) self.assertTrue( ref.equals_exact( Country.objects.snap_to_grid(0.05, 0.23, 0.5, 0.17).get(name='San Marino').snap_to_grid, tol ) ) @skipUnlessDBFeature("has_svg_method") def test_svg(self): "Testing SVG output using GeoQuerySet.svg()." self.assertRaises(TypeError, City.objects.svg, precision='foo') # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo'; svg1 = 'cx="-104.609252" cy="-38.255001"' # Even though relative, only one point so it's practically the same except for # the 'c' letter prefix on the x,y values. svg2 = svg1.replace('c', '') self.assertEqual(svg1, City.objects.svg().get(name='Pueblo').svg) self.assertEqual(svg2, City.objects.svg(relative=5).get(name='Pueblo').svg) @skipUnlessDBFeature("has_transform_method") def test_transform(self): "Testing the transform() GeoQuerySet method." # Pre-transformed points for Houston and Pueblo. htown = fromstr('POINT(1947516.83115183 6322297.06040572)', srid=3084) ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774) prec = 3 # Precision is low due to version variations in PROJ and GDAL. # Asserting the result of the transform operation with the values in # the pre-transformed points. Oracle does not have the 3084 SRID. if not oracle: h = City.objects.transform(htown.srid).get(name='Houston') self.assertEqual(3084, h.point.srid) self.assertAlmostEqual(htown.x, h.point.x, prec) self.assertAlmostEqual(htown.y, h.point.y, prec) p1 = City.objects.transform(ptown.srid, field_name='point').get(name='Pueblo') p2 = City.objects.transform(srid=ptown.srid).get(name='Pueblo') for p in [p1, p2]: self.assertEqual(2774, p.point.srid) self.assertAlmostEqual(ptown.x, p.point.x, prec) self.assertAlmostEqual(ptown.y, p.point.y, prec) @skipUnlessDBFeature("has_translate_method") def test_translate(self): "Testing the `translate` GeoQuerySet method." xfac, yfac = 5, -23 qs = Country.objects.translate(xfac, yfac, model_att='translated') for c in qs: for p1, p2 in zip(c.mpoly, c.translated): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): # XXX The low precision is for SpatiaLite self.assertAlmostEqual(c1[0] + xfac, c2[0], 5) self.assertAlmostEqual(c1[1] + yfac, c2[1], 5) # TODO: Oracle can be made to pass if # union1 = union2 = fromstr('POINT (-97.5211570000000023 34.4646419999999978)') # but this seems unexpected and should be investigated to determine the cause. @skipUnlessDBFeature("has_unionagg_method") @no_oracle @ignore_warnings(category=RemovedInDjango110Warning) def test_unionagg(self): """ Testing the (deprecated) `unionagg` (aggregate union) GeoQuerySet method and the Union aggregate. """ tx = Country.objects.get(name='Texas').mpoly # Houston, Dallas -- Ordering may differ depending on backend or GEOS version. union1 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)') union2 = fromstr('MULTIPOINT(-95.363151 29.763374,-96.801611 32.782057)') qs = City.objects.filter(point__within=tx) self.assertRaises(TypeError, qs.unionagg, 'name') self.assertRaises(ValueError, qs.aggregate, Union('name')) # Using `field_name` keyword argument in one query and specifying an # order in the other (which should not be used because this is # an aggregate method on a spatial column) u1 = qs.unionagg(field_name='point') u2 = qs.order_by('name').unionagg() u3 = qs.aggregate(Union('point'))['point__union'] u4 = qs.order_by('name').aggregate(Union('point'))['point__union'] tol = 0.00001 self.assertTrue(union1.equals_exact(u1, tol) or union2.equals_exact(u1, tol)) self.assertTrue(union1.equals_exact(u2, tol) or union2.equals_exact(u2, tol)) self.assertTrue(union1.equals_exact(u3, tol) or union2.equals_exact(u3, tol)) self.assertTrue(union1.equals_exact(u4, tol) or union2.equals_exact(u4, tol)) qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.unionagg(field_name='point')) self.assertIsNone(qs.aggregate(Union('point'))['point__union']) def test_within_subquery(self): """ Test that using a queryset inside a geo lookup is working (using a subquery) (#14483). """ tex_cities = City.objects.filter( point__within=Country.objects.filter(name='Texas').values('mpoly')).order_by('name') expected = ['Dallas', 'Houston'] if not connection.features.supports_real_shape_operations: expected.append('Oklahoma City') self.assertEqual( list(tex_cities.values_list('name', flat=True)), expected ) def test_non_concrete_field(self): NonConcreteModel.objects.create(point=Point(0, 0), name='name') list(NonConcreteModel.objects.all())
en
0.791639
# Ensuring that data was loaded from initial data fixtures. # Testing on a Point # Making sure TypeError is thrown when trying to set with an # incompatible type. # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. # Ensuring the point was saved correctly after saving # Setting the X and Y of the Point # Checking assignments pre & post-save. # Testing on a Polygon # Creating a State object using a built Polygon # SRID auto-set from None # Testing the `ogr` and `srs` lazy-geometry properties. # Changing the interior ring on the poly attribute. # San Antonio in 'WGS84' (SRID 4326) # Our reference point in WGS84 # Oracle doesn't have SRID 3084, using 41157. # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157) # Used the following Oracle SQL to get this value: # SELECT SDO_UTIL.TO_WKTGEOMETRY( # SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) # ) # FROM DUAL; # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) # Used ogr.py in gdal 1.4.1 for this transform # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. # Creating San Antonio. Remember the Alamo. # Now verifying that San Antonio was transformed correctly # If the GeometryField SRID is -1, then we shouldn't perform any # transformation if the SRID of the input geometry is different. # SpatiaLite < 3 does not support missing SRID values. # Creating a Pennsylvanian city. # All transformation SQL will need to be performed on the # _parent_ table. # Only PostGIS would support a 'select *' query because of its recognized # HEXEWKB format for geometry fields Test a dumpdata/loaddata cycle with geographic data. # Reload now dumped data # Getting Texas, yes we were a country -- once ;) # Seeing what cities are in Texas, should get Houston and Dallas, # and Oklahoma City because 'contained' only checks on the # _bounding box_ of the Geometries. # Pulling out some cities. # Now testing contains on the countries using the points for # Houston and Wellington. # Query w/GEOSGeometry # Query w/EWKBHEX # Spatialite 2.3 thinks that Lawrence is in Puerto Rico (a NULL geometry). # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas) # are not contained in Texas or New Zealand. # Query w/GEOSGeometry object # Query w/WKT # OK City is contained w/in bounding box of Texas. # Left: A << B => true if xmax(A) < xmin(B) # Right: A >> B => true if xmin(A) > xmax(B) # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source. # The left/right lookup tests are known failures on PostGIS 2.0/2.0.1 # http://trac.osgeo.org/postgis/ticket/2035 # Getting the borders for Colorado & Kansas # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. # These cities should be strictly to the right of the CO border. # These cities should be strictly to the right of the KS border. # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. # Creating a state with a NULL boundary. # Querying for both NULL and Non-NULL values. # Puerto Rico should be NULL (it's a commonwealth unincorporated territory) # The valid states should be Colorado & Kansas # Saving another commonwealth w/a NULL geometry. # Assigning a geometry and saving -- then UPDATE back to NULL. # To make things more interesting, we will have our Texas reference point in # different SRIDs. # Not passing in a geometry as first param should # raise a type error when initializing the GeoQuerySet # Making sure the right exception is raised for the given # bad arguments. # Relate works differently for the different backends. # TODO: This is not quite the same as the PostGIS mask above # Testing contains relation mask. # Testing within relation mask. # Testing intersection relation mask. # Please keep the tests in GeoQuerySet method's alphabetic order # XXX For some reason SpatiaLite does something screwy with the Texas geometry here. Also, # XXX it doesn't like the null intersection. # Should be able to execute the queries; however, they won't be the same # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or # SpatiaLite). # Ordering might differ in collections Testing the (deprecated) `extent` GeoQuerySet method and the Extent aggregate. # Reference query: # `SELECT ST_extent(point) FROM geoapp_city WHERE (name='Houston' or name='Dallas');` # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203) Testing if extent supports limit. # Reference query: # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston'; # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston'; # Only PostGIS and SpatiaLite 3.0+ support GeoJSON. # Precision argument should only be an integer # Reference queries and values. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo'; # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we want to include the CRS by using the `crs` keyword. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we include the bounding box by using the `bbox` keyword. # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Chicago'; # Finally, we set every available keyword. # Should throw a TypeError when trying to obtain GML from a # non-geometry field. # No precision parameter for Oracle :-/ # Spatialite before 3.0 has extra colon in SrsName # Should throw a TypeError when trying to obtain KML from a # non-geometry field. # Ensuring the KML is as expected. Testing the (deprecated) `make_line` GeoQuerySet method and the MakeLine aggregate. # Only PostGIS has support for the MakeLine aggregate. For other # backends, test that NotImplementedError is raised # Ensuring that a `TypeError` is raised on models without PointFields. # MakeLine on an inappropriate field returns simply None # Reference query: # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city; # We check for equality with a tolerance of 10e-5 which is a lower bound # of the precisions of ref_line coordinates # Both 'countries' only have two geometries. # Oracle and PostGIS 2.0+ will return 1 for the number of # geometries on non-collections. # Oracle cannot count vertices in Point geometries. # Reference values. # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05)) # FROM GEOAPP_COUNTRY; # Using GEOSGeometry to compute the reference point on surface values # -- since PostGIS also uses GEOS these should be the same. # XXX This seems to be a WKT-translation-related precision issue? # XXX The low precision tolerance is for SpatiaLite # Let's try and break snap_to_grid() with bad combinations of arguments. # Boundary for San Marino, courtesy of <NAME> of thematicmapping.org # from the world borders dataset he provides. # Because floating-point arithmetic isn't exact, we set a tolerance # to pass into GEOS `equals_exact`. # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo'; # Even though relative, only one point so it's practically the same except for # the 'c' letter prefix on the x,y values. # Pre-transformed points for Houston and Pueblo. # Precision is low due to version variations in PROJ and GDAL. # Asserting the result of the transform operation with the values in # the pre-transformed points. Oracle does not have the 3084 SRID. # XXX The low precision is for SpatiaLite # TODO: Oracle can be made to pass if # union1 = union2 = fromstr('POINT (-97.5211570000000023 34.4646419999999978)') # but this seems unexpected and should be investigated to determine the cause. Testing the (deprecated) `unionagg` (aggregate union) GeoQuerySet method and the Union aggregate. # Houston, Dallas -- Ordering may differ depending on backend or GEOS version. # Using `field_name` keyword argument in one query and specifying an # order in the other (which should not be used because this is # an aggregate method on a spatial column) Test that using a queryset inside a geo lookup is working (using a subquery) (#14483).
2.0635
2
tools/convert_fcos_weight.py
abhishreeshetty/IDL-CrossViz
0
6624344
import argparse from collections import OrderedDict import torch def get_parser(): parser = argparse.ArgumentParser(description='FCOS Detectron2 Converter') parser.add_argument( '--model', default='weights/fcos_R_50_1x_official.pth', metavar='FILE', help='path to model weights', ) parser.add_argument( '--output', default='weights/fcos_R_50_1x_converted.pth', metavar='FILE', help='path to model weights', ) return parser def rename_resnet_param_names(ckpt_state_dict): converted_state_dict = OrderedDict() for key in ckpt_state_dict.keys(): value = ckpt_state_dict[key] key = key.replace('module.', '') key = key.replace('body', 'bottom_up') # adding a . ahead to avoid renaming the fpn modules # this can happen after fpn renaming key = key.replace('.layer1', '.res2') key = key.replace('.layer2', '.res3') key = key.replace('.layer3', '.res4') key = key.replace('.layer4', '.res5') key = key.replace('downsample.0', 'shortcut') key = key.replace('downsample.1', 'shortcut.norm') key = key.replace('bn1', 'conv1.norm') key = key.replace('bn2', 'conv2.norm') key = key.replace('bn3', 'conv3.norm') key = key.replace('fpn_inner2', 'fpn_lateral3') key = key.replace('fpn_inner3', 'fpn_lateral4') key = key.replace('fpn_inner4', 'fpn_lateral5') key = key.replace('fpn_layer2', 'fpn_output3') key = key.replace('fpn_layer3', 'fpn_output4') key = key.replace('fpn_layer4', 'fpn_output5') key = key.replace('top_blocks', 'top_block') key = key.replace('fpn.', '') key = key.replace('rpn', 'proposal_generator') key = key.replace('head', 'fcos_head') converted_state_dict[key] = value return converted_state_dict if __name__ == '__main__': args = get_parser().parse_args() ckpt = torch.load(args.model) model = rename_resnet_param_names(ckpt['model']) torch.save(model, args.output)
import argparse from collections import OrderedDict import torch def get_parser(): parser = argparse.ArgumentParser(description='FCOS Detectron2 Converter') parser.add_argument( '--model', default='weights/fcos_R_50_1x_official.pth', metavar='FILE', help='path to model weights', ) parser.add_argument( '--output', default='weights/fcos_R_50_1x_converted.pth', metavar='FILE', help='path to model weights', ) return parser def rename_resnet_param_names(ckpt_state_dict): converted_state_dict = OrderedDict() for key in ckpt_state_dict.keys(): value = ckpt_state_dict[key] key = key.replace('module.', '') key = key.replace('body', 'bottom_up') # adding a . ahead to avoid renaming the fpn modules # this can happen after fpn renaming key = key.replace('.layer1', '.res2') key = key.replace('.layer2', '.res3') key = key.replace('.layer3', '.res4') key = key.replace('.layer4', '.res5') key = key.replace('downsample.0', 'shortcut') key = key.replace('downsample.1', 'shortcut.norm') key = key.replace('bn1', 'conv1.norm') key = key.replace('bn2', 'conv2.norm') key = key.replace('bn3', 'conv3.norm') key = key.replace('fpn_inner2', 'fpn_lateral3') key = key.replace('fpn_inner3', 'fpn_lateral4') key = key.replace('fpn_inner4', 'fpn_lateral5') key = key.replace('fpn_layer2', 'fpn_output3') key = key.replace('fpn_layer3', 'fpn_output4') key = key.replace('fpn_layer4', 'fpn_output5') key = key.replace('top_blocks', 'top_block') key = key.replace('fpn.', '') key = key.replace('rpn', 'proposal_generator') key = key.replace('head', 'fcos_head') converted_state_dict[key] = value return converted_state_dict if __name__ == '__main__': args = get_parser().parse_args() ckpt = torch.load(args.model) model = rename_resnet_param_names(ckpt['model']) torch.save(model, args.output)
en
0.776403
# adding a . ahead to avoid renaming the fpn modules # this can happen after fpn renaming
2.220082
2
spacy/en/tokenizer_exceptions.py
EnjoyLifeFund/macHighSierra-py36-pkgs
1
6624345
<gh_stars>1-10 # coding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA EXC = {} EXCLUDE_EXC = ["Ill", "ill", "Its", "its", "Hell", "hell", "Shell", "shell", "Shed", "shed", "were", "Were", "Well", "well", "Whore", "whore"] # Pronouns for pron in ["i"]: for orth in [pron, pron.title()]: EXC[orth + "'m"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'m", LEMMA: "be", TAG: "VBP", "tenspect": 1, "number": 1} ] EXC[orth + "m"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "m", LEMMA: "be", TAG: "VBP", "tenspect": 1, "number": 1 } ] EXC[orth + "'ma"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'m", LEMMA: "be", NORM: "am"}, {ORTH: "a", LEMMA: "going to", NORM: "gonna"} ] EXC[orth + "ma"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "m", LEMMA: "be", NORM: "am"}, {ORTH: "a", LEMMA: "going to", NORM: "gonna"} ] for pron in ["i", "you", "he", "she", "it", "we", "they"]: for orth in [pron, pron.title()]: EXC[orth + "'ll"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'ll", LEMMA: "will", TAG: "MD"} ] EXC[orth + "ll"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "ll", LEMMA: "will", TAG: "MD"} ] EXC[orth + "'ll've"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'ll", LEMMA: "will", TAG: "MD"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "llve"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "ll", LEMMA: "will", TAG: "MD"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "'d"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'d", LEMMA: "would", TAG: "MD"} ] EXC[orth + "d"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "d", LEMMA: "would", TAG: "MD"} ] EXC[orth + "'d've"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'d", LEMMA: "would", TAG: "MD"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "dve"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "d", LEMMA: "would", TAG: "MD"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] for pron in ["i", "you", "we", "they"]: for orth in [pron, pron.title()]: EXC[orth + "'ve"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "ve"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] for pron in ["you", "we", "they"]: for orth in [pron, pron.title()]: EXC[orth + "'re"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'re", LEMMA: "be", NORM: "are"} ] EXC[orth + "re"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "re", LEMMA: "be", NORM: "are", TAG: "VBZ"} ] for pron in ["he", "she", "it"]: for orth in [pron, pron.title()]: EXC[orth + "'s"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'s"} ] EXC[orth + "s"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "s"} ] # W-words, relative pronouns, prepositions etc. for word in ["who", "what", "when", "where", "why", "how", "there", "that"]: for orth in [word, word.title()]: EXC[orth + "'s"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'s"} ] EXC[orth + "s"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "s"} ] EXC[orth + "'ll"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'ll", LEMMA: "will", TAG: "MD"} ] EXC[orth + "ll"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "ll", LEMMA: "will", TAG: "MD"} ] EXC[orth + "'ll've"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'ll", LEMMA: "will", TAG: "MD"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "llve"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "ll", LEMMA: "will", TAG: "MD"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "'re"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'re", LEMMA: "be", NORM: "are"} ] EXC[orth + "re"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "re", LEMMA: "be", NORM: "are"} ] EXC[orth + "'ve"] = [ {ORTH: orth}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "ve"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "'d"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'d"} ] EXC[orth + "d"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "d"} ] EXC[orth + "'d've"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'d", LEMMA: "would", TAG: "MD"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "dve"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "d", LEMMA: "would", TAG: "MD"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] # Verbs for verb_data in [ {ORTH: "ca", LEMMA: "can", TAG: "MD"}, {ORTH: "could", TAG: "MD"}, {ORTH: "do", LEMMA: "do"}, {ORTH: "does", LEMMA: "do"}, {ORTH: "did", LEMMA: "do", TAG: "VBD"}, {ORTH: "had", LEMMA: "have", TAG: "VBD"}, {ORTH: "may", TAG: "MD"}, {ORTH: "might", TAG: "MD"}, {ORTH: "must", TAG: "MD"}, {ORTH: "need"}, {ORTH: "ought"}, {ORTH: "sha", LEMMA: "shall", TAG: "MD"}, {ORTH: "should", TAG: "MD"}, {ORTH: "wo", LEMMA: "will", TAG: "MD"}, {ORTH: "would", TAG: "MD"} ]: verb_data_tc = dict(verb_data) verb_data_tc[ORTH] = verb_data_tc[ORTH].title() for data in [verb_data, verb_data_tc]: EXC[data[ORTH] + "n't"] = [ dict(data), {ORTH: "n't", LEMMA: "not", TAG: "RB"} ] EXC[data[ORTH] + "nt"] = [ dict(data), {ORTH: "nt", LEMMA: "not", TAG: "RB"} ] EXC[data[ORTH] + "n't've"] = [ dict(data), {ORTH: "n't", LEMMA: "not", TAG: "RB"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[data[ORTH] + "ntve"] = [ dict(data), {ORTH: "nt", LEMMA: "not", TAG: "RB"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] for verb_data in [ {ORTH: "could", TAG: "MD"}, {ORTH: "might"}, {ORTH: "must"}, {ORTH: "should"} ]: verb_data_tc = dict(verb_data) verb_data_tc[ORTH] = verb_data_tc[ORTH].title() for data in [verb_data, verb_data_tc]: EXC[data[ORTH] + "'ve"] = [ dict(data), {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[data[ORTH] + "ve"] = [ dict(data), {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] for verb_data in [ {ORTH: "ai", TAG: "VBP", "number": 2, LEMMA: "be"}, {ORTH: "are", LEMMA: "be", TAG: "VBP", "number": 2}, {ORTH: "is", LEMMA: "be", TAG: "VBZ"}, {ORTH: "was", LEMMA: "be"}, {ORTH: "were", LEMMA: "be"} ]: verb_data_tc = dict(verb_data) verb_data_tc[ORTH] = verb_data_tc[ORTH].title() for data in [verb_data, verb_data_tc]: EXC[data[ORTH] + "n't"] = [ dict(data), {ORTH: "n't", LEMMA: "not", TAG: "RB"} ] EXC[data[ORTH] + "nt"] = [ dict(data), {ORTH: "nt", LEMMA: "not", TAG: "RB"} ] # Other contractions with trailing apostrophe for exc_data in [ {ORTH: "doin", LEMMA: "do", NORM: "doing"}, {ORTH: "goin", LEMMA: "go", NORM: "going"}, {ORTH: "nothin", LEMMA: "nothing"}, {ORTH: "nuthin", LEMMA: "nothing"}, {ORTH: "ol", LEMMA: "old"}, {ORTH: "somethin", LEMMA: "something"} ]: exc_data_tc = dict(exc_data) exc_data_tc[ORTH] = exc_data_tc[ORTH].title() for data in [exc_data, exc_data_tc]: data_apos = dict(data) data_apos[ORTH] = data_apos[ORTH] + "'" EXC[data[ORTH]] = [ dict(data) ] EXC[data_apos[ORTH]] = [ dict(data_apos) ] # Other contractions with leading apostrophe for exc_data in [ {ORTH: "cause", LEMMA: "because"}, {ORTH: "em", LEMMA: PRON_LEMMA, NORM: "them"}, {ORTH: "ll", LEMMA: "will"}, {ORTH: "nuff", LEMMA: "enough"} ]: exc_data_apos = dict(exc_data) exc_data_apos[ORTH] = "'" + exc_data_apos[ORTH] for data in [exc_data, exc_data_apos]: EXC[data[ORTH]] = [ dict(data) ] # Times for h in range(1, 12 + 1): hour = str(h) for period in ["a.m.", "am"]: EXC[hour + period] = [ {ORTH: hour}, {ORTH: period, LEMMA: "a.m."} ] for period in ["p.m.", "pm"]: EXC[hour + period] = [ {ORTH: hour}, {ORTH: period, LEMMA: "p.m."} ] # Rest OTHER = { " ": [ {ORTH: " ", TAG: "SP"} ], "\u00a0": [ {ORTH: "\u00a0", TAG: "SP", LEMMA: " "} ], "'S": [ {ORTH: "'S", LEMMA: "'s"} ], "'s": [ {ORTH: "'s", LEMMA: "'s"} ], "'re": [ {ORTH: "'re", LEMMA: "be", NORM: "are"} ], "\u2018S": [ {ORTH: "\u2018S", LEMMA: "'s"} ], "\u2018s": [ {ORTH: "\u2018s", LEMMA: "'s"} ], "and/or": [ {ORTH: "and/or", LEMMA: "and/or", TAG: "CC"} ], "'Cause": [ {ORTH: "'Cause", LEMMA: "because"} ], "y'all": [ {ORTH: "y'", LEMMA: PRON_LEMMA, NORM: "you"}, {ORTH: "all"} ], "yall": [ {ORTH: "y", LEMMA: PRON_LEMMA, NORM: "you"}, {ORTH: "all"} ], "ma'am": [ {ORTH: "ma'am", LEMMA: "madam"} ], "Ma'am": [ {ORTH: "Ma'am", LEMMA: "madam"} ], "o'clock": [ {ORTH: "o'clock", LEMMA: "o'clock"} ], "O'clock": [ {ORTH: "O'clock", LEMMA: "o'clock"} ], "how'd'y": [ {ORTH: "how", LEMMA: "how"}, {ORTH: "'d", LEMMA: "do"}, {ORTH: "'y", LEMMA: PRON_LEMMA, NORM: "you"} ], "How'd'y": [ {ORTH: "How", LEMMA: "how"}, {ORTH: "'d", LEMMA: "do"}, {ORTH: "'y", LEMMA: PRON_LEMMA, NORM: "you"} ], "not've": [ {ORTH: "not", LEMMA: "not", TAG: "RB"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ], "notve": [ {ORTH: "not", LEMMA: "not", TAG: "RB"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ], "Not've": [ {ORTH: "Not", LEMMA: "not", TAG: "RB"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ], "Notve": [ {ORTH: "Not", LEMMA: "not", TAG: "RB"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ], "cannot": [ {ORTH: "can", LEMMA: "can", TAG: "MD"}, {ORTH: "not", LEMMA: "not", TAG: "RB"} ], "Cannot": [ {ORTH: "Can", LEMMA: "can", TAG: "MD"}, {ORTH: "not", LEMMA: "not", TAG: "RB"} ], "gonna": [ {ORTH: "gon", LEMMA: "go", NORM: "going"}, {ORTH: "na", LEMMA: "to"} ], "Gonna": [ {ORTH: "Gon", LEMMA: "go", NORM: "going"}, {ORTH: "na", LEMMA: "to"} ], "gotta": [ {ORTH: "got"}, {ORTH: "ta", LEMMA: "to"} ], "Gotta": [ {ORTH: "Got"}, {ORTH: "ta", LEMMA: "to"} ], "let's": [ {ORTH: "let"}, {ORTH: "'s", LEMMA: PRON_LEMMA, NORM: "us"} ], "Let's": [ {ORTH: "Let", LEMMA: "let"}, {ORTH: "'s", LEMMA: PRON_LEMMA, NORM: "us"} ], "\u2014": [ {ORTH: "\u2014", TAG: ":", LEMMA: "--"} ], "\n": [ {ORTH: "\n", TAG: "SP"} ], "\t": [ {ORTH: "\t", TAG: "SP"} ] } # Abbreviations ABBREVIATIONS = { "Mt.": [ {ORTH: "Mt.", LEMMA: "Mount"} ], "Ak.": [ {ORTH: "Ak.", LEMMA: "Alaska"} ], "Ala.": [ {ORTH: "Ala.", LEMMA: "Alabama"} ], "Apr.": [ {ORTH: "Apr.", LEMMA: "April"} ], "Ariz.": [ {ORTH: "Ariz.", LEMMA: "Arizona"} ], "Ark.": [ {ORTH: "Ark.", LEMMA: "Arkansas"} ], "Aug.": [ {ORTH: "Aug.", LEMMA: "August"} ], "Calif.": [ {ORTH: "Calif.", LEMMA: "California"} ], "Colo.": [ {ORTH: "Colo.", LEMMA: "Colorado"} ], "Conn.": [ {ORTH: "Conn.", LEMMA: "Connecticut"} ], "Dec.": [ {ORTH: "Dec.", LEMMA: "December"} ], "Del.": [ {ORTH: "Del.", LEMMA: "Delaware"} ], "Feb.": [ {ORTH: "Feb.", LEMMA: "February"} ], "Fla.": [ {ORTH: "Fla.", LEMMA: "Florida"} ], "Ga.": [ {ORTH: "Ga.", LEMMA: "Georgia"} ], "Ia.": [ {ORTH: "Ia.", LEMMA: "Iowa"} ], "Id.": [ {ORTH: "Id.", LEMMA: "Idaho"} ], "Ill.": [ {ORTH: "Ill.", LEMMA: "Illinois"} ], "Ind.": [ {ORTH: "Ind.", LEMMA: "Indiana"} ], "Jan.": [ {ORTH: "Jan.", LEMMA: "January"} ], "Jul.": [ {ORTH: "Jul.", LEMMA: "July"} ], "Jun.": [ {ORTH: "Jun.", LEMMA: "June"} ], "Kan.": [ {ORTH: "Kan.", LEMMA: "Kansas"} ], "Kans.": [ {ORTH: "Kans.", LEMMA: "Kansas"} ], "Ky.": [ {ORTH: "Ky.", LEMMA: "Kentucky"} ], "La.": [ {ORTH: "La.", LEMMA: "Louisiana"} ], "Mar.": [ {ORTH: "Mar.", LEMMA: "March"} ], "Mass.": [ {ORTH: "Mass.", LEMMA: "Massachusetts"} ], "May.": [ {ORTH: "May.", LEMMA: "May"} ], "Mich.": [ {ORTH: "Mich.", LEMMA: "Michigan"} ], "Minn.": [ {ORTH: "Minn.", LEMMA: "Minnesota"} ], "Miss.": [ {ORTH: "Miss.", LEMMA: "Mississippi"} ], "N.C.": [ {ORTH: "N.C.", LEMMA: "North Carolina"} ], "N.D.": [ {ORTH: "N.D.", LEMMA: "North Dakota"} ], "N.H.": [ {ORTH: "N.H.", LEMMA: "New Hampshire"} ], "N.J.": [ {ORTH: "N.J.", LEMMA: "New Jersey"} ], "N.M.": [ {ORTH: "N.M.", LEMMA: "New Mexico"} ], "N.Y.": [ {ORTH: "N.Y.", LEMMA: "New York"} ], "Neb.": [ {ORTH: "Neb.", LEMMA: "Nebraska"} ], "Nebr.": [ {ORTH: "Nebr.", LEMMA: "Nebraska"} ], "Nev.": [ {ORTH: "Nev.", LEMMA: "Nevada"} ], "Nov.": [ {ORTH: "Nov.", LEMMA: "November"} ], "Oct.": [ {ORTH: "Oct.", LEMMA: "October"} ], "Okla.": [ {ORTH: "Okla.", LEMMA: "Oklahoma"} ], "Ore.": [ {ORTH: "Ore.", LEMMA: "Oregon"} ], "Pa.": [ {ORTH: "Pa.", LEMMA: "Pennsylvania"} ], "S.C.": [ {ORTH: "S.C.", LEMMA: "South Carolina"} ], "Sep.": [ {ORTH: "Sep.", LEMMA: "September"} ], "Sept.": [ {ORTH: "Sept.", LEMMA: "September"} ], "Tenn.": [ {ORTH: "Tenn.", LEMMA: "Tennessee"} ], "Va.": [ {ORTH: "Va.", LEMMA: "Virginia"} ], "Wash.": [ {ORTH: "Wash.", LEMMA: "Washington"} ], "Wis.": [ {ORTH: "Wis.", LEMMA: "Wisconsin"} ] } TOKENIZER_EXCEPTIONS = dict(EXC) TOKENIZER_EXCEPTIONS.update(OTHER) TOKENIZER_EXCEPTIONS.update(ABBREVIATIONS) # Remove EXCLUDE_EXC if in exceptions for string in EXCLUDE_EXC: if string in TOKENIZER_EXCEPTIONS: TOKENIZER_EXCEPTIONS.pop(string) # Abbreviations with only one ORTH token ORTH_ONLY = [ "'d", "a.m.", "Adm.", "Bros.", "co.", "Co.", "Corp.", "D.C.", "Dr.", "e.g.", "E.g.", "E.G.", "Gen.", "Gov.", "i.e.", "I.e.", "I.E.", "Inc.", "Jr.", "Ltd.", "Md.", "Messrs.", "Mo.", "Mont.", "Mr.", "Mrs.", "Ms.", "p.m.", "Ph.D.", "Rep.", "Rev.", "Sen.", "St.", "vs.", ]
# coding: utf8 from __future__ import unicode_literals from ..symbols import * from ..language_data import PRON_LEMMA EXC = {} EXCLUDE_EXC = ["Ill", "ill", "Its", "its", "Hell", "hell", "Shell", "shell", "Shed", "shed", "were", "Were", "Well", "well", "Whore", "whore"] # Pronouns for pron in ["i"]: for orth in [pron, pron.title()]: EXC[orth + "'m"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'m", LEMMA: "be", TAG: "VBP", "tenspect": 1, "number": 1} ] EXC[orth + "m"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "m", LEMMA: "be", TAG: "VBP", "tenspect": 1, "number": 1 } ] EXC[orth + "'ma"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'m", LEMMA: "be", NORM: "am"}, {ORTH: "a", LEMMA: "going to", NORM: "gonna"} ] EXC[orth + "ma"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "m", LEMMA: "be", NORM: "am"}, {ORTH: "a", LEMMA: "going to", NORM: "gonna"} ] for pron in ["i", "you", "he", "she", "it", "we", "they"]: for orth in [pron, pron.title()]: EXC[orth + "'ll"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'ll", LEMMA: "will", TAG: "MD"} ] EXC[orth + "ll"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "ll", LEMMA: "will", TAG: "MD"} ] EXC[orth + "'ll've"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'ll", LEMMA: "will", TAG: "MD"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "llve"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "ll", LEMMA: "will", TAG: "MD"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "'d"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'d", LEMMA: "would", TAG: "MD"} ] EXC[orth + "d"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "d", LEMMA: "would", TAG: "MD"} ] EXC[orth + "'d've"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'d", LEMMA: "would", TAG: "MD"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "dve"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "d", LEMMA: "would", TAG: "MD"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] for pron in ["i", "you", "we", "they"]: for orth in [pron, pron.title()]: EXC[orth + "'ve"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "ve"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] for pron in ["you", "we", "they"]: for orth in [pron, pron.title()]: EXC[orth + "'re"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'re", LEMMA: "be", NORM: "are"} ] EXC[orth + "re"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "re", LEMMA: "be", NORM: "are", TAG: "VBZ"} ] for pron in ["he", "she", "it"]: for orth in [pron, pron.title()]: EXC[orth + "'s"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "'s"} ] EXC[orth + "s"] = [ {ORTH: orth, LEMMA: PRON_LEMMA, TAG: "PRP"}, {ORTH: "s"} ] # W-words, relative pronouns, prepositions etc. for word in ["who", "what", "when", "where", "why", "how", "there", "that"]: for orth in [word, word.title()]: EXC[orth + "'s"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'s"} ] EXC[orth + "s"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "s"} ] EXC[orth + "'ll"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'ll", LEMMA: "will", TAG: "MD"} ] EXC[orth + "ll"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "ll", LEMMA: "will", TAG: "MD"} ] EXC[orth + "'ll've"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'ll", LEMMA: "will", TAG: "MD"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "llve"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "ll", LEMMA: "will", TAG: "MD"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "'re"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'re", LEMMA: "be", NORM: "are"} ] EXC[orth + "re"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "re", LEMMA: "be", NORM: "are"} ] EXC[orth + "'ve"] = [ {ORTH: orth}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "ve"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "'d"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'d"} ] EXC[orth + "d"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "d"} ] EXC[orth + "'d've"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "'d", LEMMA: "would", TAG: "MD"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[orth + "dve"] = [ {ORTH: orth, LEMMA: word}, {ORTH: "d", LEMMA: "would", TAG: "MD"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] # Verbs for verb_data in [ {ORTH: "ca", LEMMA: "can", TAG: "MD"}, {ORTH: "could", TAG: "MD"}, {ORTH: "do", LEMMA: "do"}, {ORTH: "does", LEMMA: "do"}, {ORTH: "did", LEMMA: "do", TAG: "VBD"}, {ORTH: "had", LEMMA: "have", TAG: "VBD"}, {ORTH: "may", TAG: "MD"}, {ORTH: "might", TAG: "MD"}, {ORTH: "must", TAG: "MD"}, {ORTH: "need"}, {ORTH: "ought"}, {ORTH: "sha", LEMMA: "shall", TAG: "MD"}, {ORTH: "should", TAG: "MD"}, {ORTH: "wo", LEMMA: "will", TAG: "MD"}, {ORTH: "would", TAG: "MD"} ]: verb_data_tc = dict(verb_data) verb_data_tc[ORTH] = verb_data_tc[ORTH].title() for data in [verb_data, verb_data_tc]: EXC[data[ORTH] + "n't"] = [ dict(data), {ORTH: "n't", LEMMA: "not", TAG: "RB"} ] EXC[data[ORTH] + "nt"] = [ dict(data), {ORTH: "nt", LEMMA: "not", TAG: "RB"} ] EXC[data[ORTH] + "n't've"] = [ dict(data), {ORTH: "n't", LEMMA: "not", TAG: "RB"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[data[ORTH] + "ntve"] = [ dict(data), {ORTH: "nt", LEMMA: "not", TAG: "RB"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] for verb_data in [ {ORTH: "could", TAG: "MD"}, {ORTH: "might"}, {ORTH: "must"}, {ORTH: "should"} ]: verb_data_tc = dict(verb_data) verb_data_tc[ORTH] = verb_data_tc[ORTH].title() for data in [verb_data, verb_data_tc]: EXC[data[ORTH] + "'ve"] = [ dict(data), {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ] EXC[data[ORTH] + "ve"] = [ dict(data), {ORTH: "ve", LEMMA: "have", TAG: "VB"} ] for verb_data in [ {ORTH: "ai", TAG: "VBP", "number": 2, LEMMA: "be"}, {ORTH: "are", LEMMA: "be", TAG: "VBP", "number": 2}, {ORTH: "is", LEMMA: "be", TAG: "VBZ"}, {ORTH: "was", LEMMA: "be"}, {ORTH: "were", LEMMA: "be"} ]: verb_data_tc = dict(verb_data) verb_data_tc[ORTH] = verb_data_tc[ORTH].title() for data in [verb_data, verb_data_tc]: EXC[data[ORTH] + "n't"] = [ dict(data), {ORTH: "n't", LEMMA: "not", TAG: "RB"} ] EXC[data[ORTH] + "nt"] = [ dict(data), {ORTH: "nt", LEMMA: "not", TAG: "RB"} ] # Other contractions with trailing apostrophe for exc_data in [ {ORTH: "doin", LEMMA: "do", NORM: "doing"}, {ORTH: "goin", LEMMA: "go", NORM: "going"}, {ORTH: "nothin", LEMMA: "nothing"}, {ORTH: "nuthin", LEMMA: "nothing"}, {ORTH: "ol", LEMMA: "old"}, {ORTH: "somethin", LEMMA: "something"} ]: exc_data_tc = dict(exc_data) exc_data_tc[ORTH] = exc_data_tc[ORTH].title() for data in [exc_data, exc_data_tc]: data_apos = dict(data) data_apos[ORTH] = data_apos[ORTH] + "'" EXC[data[ORTH]] = [ dict(data) ] EXC[data_apos[ORTH]] = [ dict(data_apos) ] # Other contractions with leading apostrophe for exc_data in [ {ORTH: "cause", LEMMA: "because"}, {ORTH: "em", LEMMA: PRON_LEMMA, NORM: "them"}, {ORTH: "ll", LEMMA: "will"}, {ORTH: "nuff", LEMMA: "enough"} ]: exc_data_apos = dict(exc_data) exc_data_apos[ORTH] = "'" + exc_data_apos[ORTH] for data in [exc_data, exc_data_apos]: EXC[data[ORTH]] = [ dict(data) ] # Times for h in range(1, 12 + 1): hour = str(h) for period in ["a.m.", "am"]: EXC[hour + period] = [ {ORTH: hour}, {ORTH: period, LEMMA: "a.m."} ] for period in ["p.m.", "pm"]: EXC[hour + period] = [ {ORTH: hour}, {ORTH: period, LEMMA: "p.m."} ] # Rest OTHER = { " ": [ {ORTH: " ", TAG: "SP"} ], "\u00a0": [ {ORTH: "\u00a0", TAG: "SP", LEMMA: " "} ], "'S": [ {ORTH: "'S", LEMMA: "'s"} ], "'s": [ {ORTH: "'s", LEMMA: "'s"} ], "'re": [ {ORTH: "'re", LEMMA: "be", NORM: "are"} ], "\u2018S": [ {ORTH: "\u2018S", LEMMA: "'s"} ], "\u2018s": [ {ORTH: "\u2018s", LEMMA: "'s"} ], "and/or": [ {ORTH: "and/or", LEMMA: "and/or", TAG: "CC"} ], "'Cause": [ {ORTH: "'Cause", LEMMA: "because"} ], "y'all": [ {ORTH: "y'", LEMMA: PRON_LEMMA, NORM: "you"}, {ORTH: "all"} ], "yall": [ {ORTH: "y", LEMMA: PRON_LEMMA, NORM: "you"}, {ORTH: "all"} ], "ma'am": [ {ORTH: "ma'am", LEMMA: "madam"} ], "Ma'am": [ {ORTH: "Ma'am", LEMMA: "madam"} ], "o'clock": [ {ORTH: "o'clock", LEMMA: "o'clock"} ], "O'clock": [ {ORTH: "O'clock", LEMMA: "o'clock"} ], "how'd'y": [ {ORTH: "how", LEMMA: "how"}, {ORTH: "'d", LEMMA: "do"}, {ORTH: "'y", LEMMA: PRON_LEMMA, NORM: "you"} ], "How'd'y": [ {ORTH: "How", LEMMA: "how"}, {ORTH: "'d", LEMMA: "do"}, {ORTH: "'y", LEMMA: PRON_LEMMA, NORM: "you"} ], "not've": [ {ORTH: "not", LEMMA: "not", TAG: "RB"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ], "notve": [ {ORTH: "not", LEMMA: "not", TAG: "RB"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ], "Not've": [ {ORTH: "Not", LEMMA: "not", TAG: "RB"}, {ORTH: "'ve", LEMMA: "have", TAG: "VB"} ], "Notve": [ {ORTH: "Not", LEMMA: "not", TAG: "RB"}, {ORTH: "ve", LEMMA: "have", TAG: "VB"} ], "cannot": [ {ORTH: "can", LEMMA: "can", TAG: "MD"}, {ORTH: "not", LEMMA: "not", TAG: "RB"} ], "Cannot": [ {ORTH: "Can", LEMMA: "can", TAG: "MD"}, {ORTH: "not", LEMMA: "not", TAG: "RB"} ], "gonna": [ {ORTH: "gon", LEMMA: "go", NORM: "going"}, {ORTH: "na", LEMMA: "to"} ], "Gonna": [ {ORTH: "Gon", LEMMA: "go", NORM: "going"}, {ORTH: "na", LEMMA: "to"} ], "gotta": [ {ORTH: "got"}, {ORTH: "ta", LEMMA: "to"} ], "Gotta": [ {ORTH: "Got"}, {ORTH: "ta", LEMMA: "to"} ], "let's": [ {ORTH: "let"}, {ORTH: "'s", LEMMA: PRON_LEMMA, NORM: "us"} ], "Let's": [ {ORTH: "Let", LEMMA: "let"}, {ORTH: "'s", LEMMA: PRON_LEMMA, NORM: "us"} ], "\u2014": [ {ORTH: "\u2014", TAG: ":", LEMMA: "--"} ], "\n": [ {ORTH: "\n", TAG: "SP"} ], "\t": [ {ORTH: "\t", TAG: "SP"} ] } # Abbreviations ABBREVIATIONS = { "Mt.": [ {ORTH: "Mt.", LEMMA: "Mount"} ], "Ak.": [ {ORTH: "Ak.", LEMMA: "Alaska"} ], "Ala.": [ {ORTH: "Ala.", LEMMA: "Alabama"} ], "Apr.": [ {ORTH: "Apr.", LEMMA: "April"} ], "Ariz.": [ {ORTH: "Ariz.", LEMMA: "Arizona"} ], "Ark.": [ {ORTH: "Ark.", LEMMA: "Arkansas"} ], "Aug.": [ {ORTH: "Aug.", LEMMA: "August"} ], "Calif.": [ {ORTH: "Calif.", LEMMA: "California"} ], "Colo.": [ {ORTH: "Colo.", LEMMA: "Colorado"} ], "Conn.": [ {ORTH: "Conn.", LEMMA: "Connecticut"} ], "Dec.": [ {ORTH: "Dec.", LEMMA: "December"} ], "Del.": [ {ORTH: "Del.", LEMMA: "Delaware"} ], "Feb.": [ {ORTH: "Feb.", LEMMA: "February"} ], "Fla.": [ {ORTH: "Fla.", LEMMA: "Florida"} ], "Ga.": [ {ORTH: "Ga.", LEMMA: "Georgia"} ], "Ia.": [ {ORTH: "Ia.", LEMMA: "Iowa"} ], "Id.": [ {ORTH: "Id.", LEMMA: "Idaho"} ], "Ill.": [ {ORTH: "Ill.", LEMMA: "Illinois"} ], "Ind.": [ {ORTH: "Ind.", LEMMA: "Indiana"} ], "Jan.": [ {ORTH: "Jan.", LEMMA: "January"} ], "Jul.": [ {ORTH: "Jul.", LEMMA: "July"} ], "Jun.": [ {ORTH: "Jun.", LEMMA: "June"} ], "Kan.": [ {ORTH: "Kan.", LEMMA: "Kansas"} ], "Kans.": [ {ORTH: "Kans.", LEMMA: "Kansas"} ], "Ky.": [ {ORTH: "Ky.", LEMMA: "Kentucky"} ], "La.": [ {ORTH: "La.", LEMMA: "Louisiana"} ], "Mar.": [ {ORTH: "Mar.", LEMMA: "March"} ], "Mass.": [ {ORTH: "Mass.", LEMMA: "Massachusetts"} ], "May.": [ {ORTH: "May.", LEMMA: "May"} ], "Mich.": [ {ORTH: "Mich.", LEMMA: "Michigan"} ], "Minn.": [ {ORTH: "Minn.", LEMMA: "Minnesota"} ], "Miss.": [ {ORTH: "Miss.", LEMMA: "Mississippi"} ], "N.C.": [ {ORTH: "N.C.", LEMMA: "North Carolina"} ], "N.D.": [ {ORTH: "N.D.", LEMMA: "North Dakota"} ], "N.H.": [ {ORTH: "N.H.", LEMMA: "New Hampshire"} ], "N.J.": [ {ORTH: "N.J.", LEMMA: "New Jersey"} ], "N.M.": [ {ORTH: "N.M.", LEMMA: "New Mexico"} ], "N.Y.": [ {ORTH: "N.Y.", LEMMA: "New York"} ], "Neb.": [ {ORTH: "Neb.", LEMMA: "Nebraska"} ], "Nebr.": [ {ORTH: "Nebr.", LEMMA: "Nebraska"} ], "Nev.": [ {ORTH: "Nev.", LEMMA: "Nevada"} ], "Nov.": [ {ORTH: "Nov.", LEMMA: "November"} ], "Oct.": [ {ORTH: "Oct.", LEMMA: "October"} ], "Okla.": [ {ORTH: "Okla.", LEMMA: "Oklahoma"} ], "Ore.": [ {ORTH: "Ore.", LEMMA: "Oregon"} ], "Pa.": [ {ORTH: "Pa.", LEMMA: "Pennsylvania"} ], "S.C.": [ {ORTH: "S.C.", LEMMA: "South Carolina"} ], "Sep.": [ {ORTH: "Sep.", LEMMA: "September"} ], "Sept.": [ {ORTH: "Sept.", LEMMA: "September"} ], "Tenn.": [ {ORTH: "Tenn.", LEMMA: "Tennessee"} ], "Va.": [ {ORTH: "Va.", LEMMA: "Virginia"} ], "Wash.": [ {ORTH: "Wash.", LEMMA: "Washington"} ], "Wis.": [ {ORTH: "Wis.", LEMMA: "Wisconsin"} ] } TOKENIZER_EXCEPTIONS = dict(EXC) TOKENIZER_EXCEPTIONS.update(OTHER) TOKENIZER_EXCEPTIONS.update(ABBREVIATIONS) # Remove EXCLUDE_EXC if in exceptions for string in EXCLUDE_EXC: if string in TOKENIZER_EXCEPTIONS: TOKENIZER_EXCEPTIONS.pop(string) # Abbreviations with only one ORTH token ORTH_ONLY = [ "'d", "a.m.", "Adm.", "Bros.", "co.", "Co.", "Corp.", "D.C.", "Dr.", "e.g.", "E.g.", "E.G.", "Gen.", "Gov.", "i.e.", "I.e.", "I.E.", "Inc.", "Jr.", "Ltd.", "Md.", "Messrs.", "Mo.", "Mont.", "Mr.", "Mrs.", "Ms.", "p.m.", "Ph.D.", "Rep.", "Rev.", "Sen.", "St.", "vs.", ]
en
0.776783
# coding: utf8 # Pronouns # W-words, relative pronouns, prepositions etc. # Verbs # Other contractions with trailing apostrophe # Other contractions with leading apostrophe # Times # Rest # Abbreviations # Remove EXCLUDE_EXC if in exceptions # Abbreviations with only one ORTH token
2.356212
2
smarts/env/wrappers/frame_stack.py
MCZhi/SMARTS
2
6624346
<reponame>MCZhi/SMARTS<filename>smarts/env/wrappers/frame_stack.py # MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import copy from collections import defaultdict, deque from typing import Dict, List, Tuple, Union import gym from smarts.core import sensors class FrameStack(gym.Wrapper): """Wrapper stacks num_stack (default=3) consecutive frames, in a moving-window fashion, and returns the stacked_frames. Note: Wrapper returns a deepcopy of the stacked frames, which may be expensive for large frames and large num_stack values. """ def __init__(self, env: gym.Env, num_stack: int = 3): """ Args: env (gym.Env): Gym environment to be wrapped. num_stack (int, optional): Number of frames to be stacked. Defaults to 3. """ assert num_stack > 1, f"Expected num_stack > 1, but got {num_stack}." super(FrameStack, self).__init__(env) self._num_stack = num_stack self._frames = { key: deque(maxlen=self._num_stack) for key in self.env.agent_specs.keys() } if self.observation_space: self.observation_space = gym.spaces.Dict( { agent_id: gym.spaces.Tuple([space] * self._num_stack) for agent_id, space in self.observation_space.spaces.items() } ) def _get_observations( self, frame: Dict[str, sensors.Observation] ) -> Dict[str, List[sensors.Observation]]: """Update and return frames stack with given latest single frame.""" new_frames = defaultdict(list) for agent_id, observation in frame.items(): self._frames[agent_id].appendleft(observation) frames_list = list(self._frames[agent_id]) new_frames[agent_id] = copy.deepcopy(frames_list) return dict(new_frames) def step( self, agent_actions: Dict ) -> Tuple[ Dict[str, List[sensors.Observation]], Dict[str, float], Dict[str, bool], Dict[str, Dict[str, Union[float, sensors.Observation]]], ]: """Steps the environment by one step. Args: agent_actions (Dict): Actions for each agent. Returns: Tuple[ Dict[str, List[sensors.Observation]], Dict[str, float], Dict[str, bool], Dict[str, Dict[str, Union[float, sensors.Observation]]] ]: Observation, reward, done, info, for each agent. """ env_observations, rewards, dones, infos = super(FrameStack, self).step( agent_actions ) return self._get_observations(env_observations), rewards, dones, infos def reset(self) -> Dict[str, List[sensors.Observation]]: """Resets the environment. Returns: Dict[str, List[sensors.Observation]]: Observation upon reset for each agent. """ env_observations = super(FrameStack, self).reset() for agent_id, observation in env_observations.items(): for _ in range(self._num_stack - 1): self._frames[agent_id].appendleft(observation) return self._get_observations(env_observations)
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import copy from collections import defaultdict, deque from typing import Dict, List, Tuple, Union import gym from smarts.core import sensors class FrameStack(gym.Wrapper): """Wrapper stacks num_stack (default=3) consecutive frames, in a moving-window fashion, and returns the stacked_frames. Note: Wrapper returns a deepcopy of the stacked frames, which may be expensive for large frames and large num_stack values. """ def __init__(self, env: gym.Env, num_stack: int = 3): """ Args: env (gym.Env): Gym environment to be wrapped. num_stack (int, optional): Number of frames to be stacked. Defaults to 3. """ assert num_stack > 1, f"Expected num_stack > 1, but got {num_stack}." super(FrameStack, self).__init__(env) self._num_stack = num_stack self._frames = { key: deque(maxlen=self._num_stack) for key in self.env.agent_specs.keys() } if self.observation_space: self.observation_space = gym.spaces.Dict( { agent_id: gym.spaces.Tuple([space] * self._num_stack) for agent_id, space in self.observation_space.spaces.items() } ) def _get_observations( self, frame: Dict[str, sensors.Observation] ) -> Dict[str, List[sensors.Observation]]: """Update and return frames stack with given latest single frame.""" new_frames = defaultdict(list) for agent_id, observation in frame.items(): self._frames[agent_id].appendleft(observation) frames_list = list(self._frames[agent_id]) new_frames[agent_id] = copy.deepcopy(frames_list) return dict(new_frames) def step( self, agent_actions: Dict ) -> Tuple[ Dict[str, List[sensors.Observation]], Dict[str, float], Dict[str, bool], Dict[str, Dict[str, Union[float, sensors.Observation]]], ]: """Steps the environment by one step. Args: agent_actions (Dict): Actions for each agent. Returns: Tuple[ Dict[str, List[sensors.Observation]], Dict[str, float], Dict[str, bool], Dict[str, Dict[str, Union[float, sensors.Observation]]] ]: Observation, reward, done, info, for each agent. """ env_observations, rewards, dones, infos = super(FrameStack, self).step( agent_actions ) return self._get_observations(env_observations), rewards, dones, infos def reset(self) -> Dict[str, List[sensors.Observation]]: """Resets the environment. Returns: Dict[str, List[sensors.Observation]]: Observation upon reset for each agent. """ env_observations = super(FrameStack, self).reset() for agent_id, observation in env_observations.items(): for _ in range(self._num_stack - 1): self._frames[agent_id].appendleft(observation) return self._get_observations(env_observations)
en
0.699389
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. Wrapper stacks num_stack (default=3) consecutive frames, in a moving-window fashion, and returns the stacked_frames. Note: Wrapper returns a deepcopy of the stacked frames, which may be expensive for large frames and large num_stack values. Args: env (gym.Env): Gym environment to be wrapped. num_stack (int, optional): Number of frames to be stacked. Defaults to 3. Update and return frames stack with given latest single frame. Steps the environment by one step. Args: agent_actions (Dict): Actions for each agent. Returns: Tuple[ Dict[str, List[sensors.Observation]], Dict[str, float], Dict[str, bool], Dict[str, Dict[str, Union[float, sensors.Observation]]] ]: Observation, reward, done, info, for each agent. Resets the environment. Returns: Dict[str, List[sensors.Observation]]: Observation upon reset for each agent.
2.182109
2
microWebSrv.py
youxinweizhi/skill_server_for_esp32
10
6624347
<filename>microWebSrv.py """ The MIT License (MIT) Copyright 漏 2018 <NAME> & HC虏 (www.hc2.fr) """ from json import loads, dumps from os import stat from _thread import start_new_thread import socket import gc import re try : from microWebTemplate import MicroWebTemplate except : pass try : from microWebSocket import MicroWebSocket except : pass class MicroWebSrvRoute : def __init__(self, route, method, func, routeArgNames, routeRegex) : self.route = route self.method = method self.func = func self.routeArgNames = routeArgNames self.routeRegex = routeRegex class MicroWebSrv : # ============================================================================ # ===( Constants )============================================================ # ============================================================================ _indexPages = [ "index.pyhtml", "index.html", "index.htm", "default.pyhtml", "default.html", "default.htm" ] _mimeTypes = { ".txt" : "text/plain", ".htm" : "text/html", ".html" : "text/html", ".css" : "text/css", ".csv" : "text/csv", ".js" : "application/javascript", ".xml" : "application/xml", ".xhtml" : "application/xhtml+xml", ".json" : "application/json", ".zip" : "application/zip", ".pdf" : "application/pdf", ".jpg" : "image/jpeg", ".jpeg" : "image/jpeg", ".png" : "image/png", ".gif" : "image/gif", ".svg" : "image/svg+xml", ".ico" : "image/x-icon" } _html_escape_chars = { "&" : "&amp;", '"' : "&quot;", "'" : "&apos;", ">" : "&gt;", "<" : "&lt;" } _pyhtmlPagesExt = '.pyhtml' # ============================================================================ # ===( Class globals )======================================================= # ============================================================================ _docoratedRouteHandlers = [] # ============================================================================ # ===( Utils )=============================================================== # ============================================================================ @classmethod def route(cls, url, method='GET'): """ Adds a route handler function to the routing list """ def route_decorator(func): item = (url, method, func) cls._docoratedRouteHandlers.append(item) return func return route_decorator # ---------------------------------------------------------------------------- @staticmethod def HTMLEscape(s) : return ''.join(MicroWebSrv._html_escape_chars.get(c, c) for c in s) # ---------------------------------------------------------------------------- @staticmethod def _startThread(func, args=()) : try : start_new_thread(func, args) except : global _mwsrv_thread_id try : _mwsrv_thread_id += 1 except : _mwsrv_thread_id = 0 try : start_new_thread('MWSRV_THREAD_%s' % _mwsrv_thread_id, func, args) except : return False return True # ---------------------------------------------------------------------------- @staticmethod def _unquote(s) : r = s.split('%') for i in range(1, len(r)) : s = r[i] try : r[i] = chr(int(s[:2], 16)) + s[2:] except : r[i] = '%' + s return ''.join(r) # ------------------------------------------------------------------------------ @staticmethod def _unquote_plus(s) : return MicroWebSrv._unquote(s.replace('+', ' ')) # ------------------------------------------------------------------------------ @staticmethod def _fileExists(path) : try : stat(path) return True except : return False # ---------------------------------------------------------------------------- @staticmethod def _isPyHTMLFile(filename) : return filename.lower().endswith(MicroWebSrv._pyhtmlPagesExt) # ============================================================================ # ===( Constructor )========================================================== # ============================================================================ def __init__( self, routeHandlers = [], port = 80, bindIP = '0.0.0.0', webPath = "/flash/www" ) : self._srvAddr = (bindIP, port) self._webPath = webPath self._notFoundUrl = None self._started = False self.MaxWebSocketRecvLen = 1024 self.WebSocketThreaded = True self.AcceptWebSocketCallback = None self.LetCacheStaticContentLevel = 2 self._routeHandlers = [] routeHandlers += self._docoratedRouteHandlers for route, method, func in routeHandlers : routeParts = route.split('/') # -> ['', 'users', '<uID>', 'addresses', '<addrID>', 'test', '<anotherID>'] routeArgNames = [] routeRegex = '' for s in routeParts : if s.startswith('<') and s.endswith('>') : routeArgNames.append(s[1:-1]) routeRegex += '/(\\w*)' elif s : routeRegex += '/' + s routeRegex += '$' # -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$' routeRegex = re.compile(routeRegex) self._routeHandlers.append(MicroWebSrvRoute(route, method, func, routeArgNames, routeRegex)) # ============================================================================ # ===( Server Process )======================================================= # ============================================================================ def _serverProcess(self) : self._started = True while True : try : client, cliAddr = self._server.accept() except Exception as ex : if ex.args and ex.args[0] == 113 : break continue self._client(self, client, cliAddr) self._started = False # ============================================================================ # ===( Functions )============================================================ # ============================================================================ def Start(self, threaded=False) : if not self._started : self._server = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP ) self._server.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) self._server.bind(self._srvAddr) self._server.listen(1) if threaded : MicroWebSrv._startThread(self._serverProcess) else : self._serverProcess() # ---------------------------------------------------------------------------- def Stop(self) : if self._started : self._server.close() # ---------------------------------------------------------------------------- def IsStarted(self) : return self._started # ---------------------------------------------------------------------------- def SetNotFoundPageUrl(self, url=None) : self._notFoundUrl = url # ---------------------------------------------------------------------------- def GetMimeTypeFromFilename(self, filename) : filename = filename.lower() for ext in self._mimeTypes : if filename.endswith(ext) : return self._mimeTypes[ext] return None # ---------------------------------------------------------------------------- def GetRouteHandler(self, resUrl, method) : if self._routeHandlers : #resUrl = resUrl.upper() if resUrl.endswith('/') : resUrl = resUrl[:-1] method = method.upper() for rh in self._routeHandlers : if rh.method == method : m = rh.routeRegex.match(resUrl) if m : # found matching route? if rh.routeArgNames : routeArgs = {} for i, name in enumerate(rh.routeArgNames) : value = m.group(i+1) try : value = int(value) except : pass routeArgs[name] = value return (rh.func, routeArgs) else : return (rh.func, None) return (None, None) # ---------------------------------------------------------------------------- def _physPathFromURLPath(self, urlPath) : if urlPath == '/' : for idxPage in self._indexPages : physPath = self._webPath + '/' + idxPage if MicroWebSrv._fileExists(physPath) : return physPath else : physPath = self._webPath + urlPath if MicroWebSrv._fileExists(physPath) : return physPath return None # ============================================================================ # ===( Class Client )======================================================== # ============================================================================ class _client : # ------------------------------------------------------------------------ def __init__(self, microWebSrv, socket, addr) : socket.settimeout(2) self._microWebSrv = microWebSrv self._socket = socket self._addr = addr self._method = None self._path = None self._httpVer = None self._resPath = "/" self._queryString = "" self._queryParams = { } self._headers = { } self._contentType = None self._contentLength = 0 if hasattr(socket, 'readline'): # MicroPython self._socketfile = self._socket else: # CPython self._socketfile = self._socket.makefile('rwb') self._processRequest() # ------------------------------------------------------------------------ def _processRequest(self) : try : response = MicroWebSrv._response(self) if self._parseFirstLine(response) : if self._parseHeader(response) : upg = self._getConnUpgrade() if not upg : routeHandler, routeArgs = self._microWebSrv.GetRouteHandler(self._resPath, self._method) if routeHandler : if routeArgs is not None: routeHandler(self, response, routeArgs) else: routeHandler(self, response) elif self._method.upper() == "GET" : filepath = self._microWebSrv._physPathFromURLPath(self._resPath) if filepath : if MicroWebSrv._isPyHTMLFile(filepath) : response.WriteResponsePyHTMLFile(filepath) else : contentType = self._microWebSrv.GetMimeTypeFromFilename(filepath) if contentType : if self._microWebSrv.LetCacheStaticContentLevel > 0 : if self._microWebSrv.LetCacheStaticContentLevel > 1 and \ 'if-modified-since' in self._headers : response.WriteResponseNotModified() else: headers = { 'Last-Modified' : 'Fri, 1 Jan 2018 23:42:00 GMT', \ 'Cache-Control' : 'max-age=315360000' } response.WriteResponseFile(filepath, contentType, headers) else : response.WriteResponseFile(filepath, contentType) else : response.WriteResponseForbidden() else : response.WriteResponseNotFound() else : response.WriteResponseMethodNotAllowed() elif upg == 'websocket' and 'MicroWebSocket' in globals() \ and self._microWebSrv.AcceptWebSocketCallback : MicroWebSocket( socket = self._socket, httpClient = self, httpResponse = response, maxRecvLen = self._microWebSrv.MaxWebSocketRecvLen, threaded = self._microWebSrv.WebSocketThreaded, acceptCallback = self._microWebSrv.AcceptWebSocketCallback ) return else : response.WriteResponseNotImplemented() else : response.WriteResponseBadRequest() except : response.WriteResponseInternalServerError() try : if self._socketfile is not self._socket: self._socketfile.close() self._socket.close() except : pass # ------------------------------------------------------------------------ def _parseFirstLine(self, response) : try : elements = self._socketfile.readline().decode().strip().split() if len(elements) == 3 : self._method = elements[0].upper() self._path = elements[1] self._httpVer = elements[2].upper() elements = self._path.split('?', 1) if len(elements) > 0 : self._resPath = MicroWebSrv._unquote_plus(elements[0]) if len(elements) > 1 : self._queryString = elements[1] elements = self._queryString.split('&') for s in elements : param = s.split('=', 1) if len(param) > 0 : value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else '' self._queryParams[MicroWebSrv._unquote(param[0])] = value return True except : pass return False # ------------------------------------------------------------------------ def _parseHeader(self, response) : while True : elements = self._socketfile.readline().decode().strip().split(':', 1) if len(elements) == 2 : self._headers[elements[0].strip().lower()] = elements[1].strip() elif len(elements) == 1 and len(elements[0]) == 0 : if self._method == 'POST' or self._method == 'PUT' : self._contentType = self._headers.get("content-type", None) self._contentLength = int(self._headers.get("content-length", 0)) return True else : return False # ------------------------------------------------------------------------ def _getConnUpgrade(self) : if 'upgrade' in self._headers.get('connection', '').lower() : return self._headers.get('upgrade', '').lower() return None # ------------------------------------------------------------------------ def GetServer(self) : return self._microWebSrv # ------------------------------------------------------------------------ def GetAddr(self) : return self._addr # ------------------------------------------------------------------------ def GetIPAddr(self) : return self._addr[0] # ------------------------------------------------------------------------ def GetPort(self) : return self._addr[1] # ------------------------------------------------------------------------ def GetRequestMethod(self) : return self._method # ------------------------------------------------------------------------ def GetRequestTotalPath(self) : return self._path # ------------------------------------------------------------------------ def GetRequestPath(self) : return self._resPath # ------------------------------------------------------------------------ def GetRequestQueryString(self) : return self._queryString # ------------------------------------------------------------------------ def GetRequestQueryParams(self) : return self._queryParams # ------------------------------------------------------------------------ def GetRequestHeaders(self) : return self._headers # ------------------------------------------------------------------------ def GetRequestContentType(self) : return self._contentType # ------------------------------------------------------------------------ def GetRequestContentLength(self) : return self._contentLength # ------------------------------------------------------------------------ def ReadRequestContent(self, size=None) : self._socket.setblocking(False) b = None try : if not size : b = self._socketfile.read(self._contentLength) elif size > 0 : b = self._socketfile.read(size) except : pass self._socket.setblocking(True) return b if b else b'' # ------------------------------------------------------------------------ def ReadRequestPostedFormData(self) : res = { } data = self.ReadRequestContent() if len(data) > 0 : elements = data.decode().split('&') for s in elements : param = s.split('=', 1) if len(param) > 0 : value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else '' res[MicroWebSrv._unquote(param[0])] = value return res # ------------------------------------------------------------------------ def ReadRequestContentAsJSON(self) : try : return loads(self.ReadRequestContent()) except : return None # ============================================================================ # ===( Class Response )====================================================== # ============================================================================ class _response : # ------------------------------------------------------------------------ def __init__(self, client) : self._client = client # ------------------------------------------------------------------------ def _write(self, data) : if data : if type(data) == str : data = data.encode() return self._client._socketfile.write(data) return 0 # ------------------------------------------------------------------------ def _writeFirstLine(self, code) : reason = self._responseCodes.get(code, ('Unknown reason', ))[0] self._write("HTTP/1.1 %s %s\r\n" % (code, reason)) # ------------------------------------------------------------------------ def _writeHeader(self, name, value) : self._write("%s: %s\r\n" % (name, value)) # ------------------------------------------------------------------------ def _writeContentTypeHeader(self, contentType, charset=None) : if contentType : ct = contentType \ + (("; charset=%s" % charset) if charset else "") else : ct = "application/octet-stream" self._writeHeader("Content-Type", ct) # ------------------------------------------------------------------------ def _writeServerHeader(self) : self._writeHeader("Server", "MicroWebSrv by JC`zic") # ------------------------------------------------------------------------ def _writeEndHeader(self) : self._write("\r\n") # ------------------------------------------------------------------------ def _writeBeforeContent(self, code, headers, contentType, contentCharset, contentLength) : self._writeFirstLine(code) if isinstance(headers, dict) : for header in headers : self._writeHeader(header, headers[header]) if contentLength > 0 : self._writeContentTypeHeader(contentType, contentCharset) self._writeHeader("Content-Length", contentLength) self._writeServerHeader() self._writeHeader("Connection", "close") self._writeEndHeader() # ------------------------------------------------------------------------ def WriteSwitchProto(self, upgrade, headers=None) : self._writeFirstLine(101) self._writeHeader("Connection", "Upgrade") self._writeHeader("Upgrade", upgrade) if isinstance(headers, dict) : for header in headers : self._writeHeader(header, headers[header]) self._writeServerHeader() self._writeEndHeader() if self._client._socketfile is not self._client._socket : self._client._socketfile.flush() # CPython needs flush to continue protocol # ------------------------------------------------------------------------ def WriteResponse(self, code, headers, contentType, contentCharset, content) : try : if content : if type(content) == str : content = content.encode() contentLength = len(content) else : contentLength = 0 self._writeBeforeContent(code, headers, contentType, contentCharset, contentLength) if content : self._write(content) return True except : return False # ------------------------------------------------------------------------ def WriteResponsePyHTMLFile(self, filepath, headers=None, vars=None) : if 'MicroWebTemplate' in globals() : with open(filepath, 'r') as file : code = file.read() mWebTmpl = MicroWebTemplate(code, escapeStrFunc=MicroWebSrv.HTMLEscape, filepath=filepath) try : tmplResult = mWebTmpl.Execute(None, vars) return self.WriteResponse(200, headers, "text/html", "UTF-8", tmplResult) except Exception as ex : return self.WriteResponse( 500, None, "text/html", "UTF-8", self._execErrCtnTmpl % { 'module' : 'PyHTML', 'message' : str(ex) } ) return self.WriteResponseNotImplemented() # ------------------------------------------------------------------------ def WriteResponseFile(self, filepath, contentType=None, headers=None) : try : size = stat(filepath)[6] if size > 0 : with open(filepath, 'rb') as file : self._writeBeforeContent(200, headers, contentType, None, size) try : buf = bytearray(1024) while size > 0 : x = file.readinto(buf) if x < len(buf) : buf = memoryview(buf)[:x] self._write(buf) size -= x return True except : self.WriteResponseInternalServerError() return False except : pass self.WriteResponseNotFound() return False # ------------------------------------------------------------------------ def WriteResponseFileAttachment(self, filepath, attachmentName, headers=None) : if not isinstance(headers, dict) : headers = { } headers["Content-Disposition"] = "attachment; filename=\"%s\"" % attachmentName return self.WriteResponseFile(filepath, None, headers) # ------------------------------------------------------------------------ def WriteResponseOk(self, headers=None, contentType=None, contentCharset=None, content=None) : return self.WriteResponse(200, headers, contentType, contentCharset, content) # ------------------------------------------------------------------------ def WriteResponseJSONOk(self, obj=None, headers=None) : return self.WriteResponse(200, headers, "application/json", "UTF-8", dumps(obj)) # ------------------------------------------------------------------------ def WriteResponseRedirect(self, location) : headers = { "Location" : location } return self.WriteResponse(302, headers, None, None, None) # ------------------------------------------------------------------------ def WriteResponseError(self, code) : responseCode = self._responseCodes.get(code, ('Unknown reason', '')) return self.WriteResponse( code, None, "text/html", "UTF-8", self._errCtnTmpl % { 'code' : code, 'reason' : responseCode[0], 'message' : responseCode[1] } ) # ------------------------------------------------------------------------ def WriteResponseJSONError(self, code, obj=None) : return self.WriteResponse( code, None, "application/json", "UTF-8", dumps(obj if obj else { }) ) # ------------------------------------------------------------------------ def WriteResponseNotModified(self) : return self.WriteResponseError(304) # ------------------------------------------------------------------------ def WriteResponseBadRequest(self) : return self.WriteResponseError(400) # ------------------------------------------------------------------------ def WriteResponseForbidden(self) : return self.WriteResponseError(403) # ------------------------------------------------------------------------ def WriteResponseNotFound(self) : if self._client._microWebSrv._notFoundUrl : self.WriteResponseRedirect(self._client._microWebSrv._notFoundUrl) else : return self.WriteResponseError(404) # ------------------------------------------------------------------------ def WriteResponseMethodNotAllowed(self) : return self.WriteResponseError(405) # ------------------------------------------------------------------------ def WriteResponseInternalServerError(self) : return self.WriteResponseError(500) # ------------------------------------------------------------------------ def WriteResponseNotImplemented(self) : return self.WriteResponseError(501) # ------------------------------------------------------------------------ def FlashMessage(self, messageText, messageStyle='') : if 'MicroWebTemplate' in globals() : MicroWebTemplate.MESSAGE_TEXT = messageText MicroWebTemplate.MESSAGE_STYLE = messageStyle # ------------------------------------------------------------------------ _errCtnTmpl = """\ <html> <head> <title>Error</title> </head> <body> <h1>%(code)d %(reason)s</h1> %(message)s </body> </html> """ # ------------------------------------------------------------------------ _execErrCtnTmpl = """\ <html> <head> <title>Page execution error</title> </head> <body> <h1>%(module)s page execution error</h1> %(message)s </body> </html> """ # ------------------------------------------------------------------------ _responseCodes = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this resource.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), } # ============================================================================ # ============================================================================ # ============================================================================
<filename>microWebSrv.py """ The MIT License (MIT) Copyright 漏 2018 <NAME> & HC虏 (www.hc2.fr) """ from json import loads, dumps from os import stat from _thread import start_new_thread import socket import gc import re try : from microWebTemplate import MicroWebTemplate except : pass try : from microWebSocket import MicroWebSocket except : pass class MicroWebSrvRoute : def __init__(self, route, method, func, routeArgNames, routeRegex) : self.route = route self.method = method self.func = func self.routeArgNames = routeArgNames self.routeRegex = routeRegex class MicroWebSrv : # ============================================================================ # ===( Constants )============================================================ # ============================================================================ _indexPages = [ "index.pyhtml", "index.html", "index.htm", "default.pyhtml", "default.html", "default.htm" ] _mimeTypes = { ".txt" : "text/plain", ".htm" : "text/html", ".html" : "text/html", ".css" : "text/css", ".csv" : "text/csv", ".js" : "application/javascript", ".xml" : "application/xml", ".xhtml" : "application/xhtml+xml", ".json" : "application/json", ".zip" : "application/zip", ".pdf" : "application/pdf", ".jpg" : "image/jpeg", ".jpeg" : "image/jpeg", ".png" : "image/png", ".gif" : "image/gif", ".svg" : "image/svg+xml", ".ico" : "image/x-icon" } _html_escape_chars = { "&" : "&amp;", '"' : "&quot;", "'" : "&apos;", ">" : "&gt;", "<" : "&lt;" } _pyhtmlPagesExt = '.pyhtml' # ============================================================================ # ===( Class globals )======================================================= # ============================================================================ _docoratedRouteHandlers = [] # ============================================================================ # ===( Utils )=============================================================== # ============================================================================ @classmethod def route(cls, url, method='GET'): """ Adds a route handler function to the routing list """ def route_decorator(func): item = (url, method, func) cls._docoratedRouteHandlers.append(item) return func return route_decorator # ---------------------------------------------------------------------------- @staticmethod def HTMLEscape(s) : return ''.join(MicroWebSrv._html_escape_chars.get(c, c) for c in s) # ---------------------------------------------------------------------------- @staticmethod def _startThread(func, args=()) : try : start_new_thread(func, args) except : global _mwsrv_thread_id try : _mwsrv_thread_id += 1 except : _mwsrv_thread_id = 0 try : start_new_thread('MWSRV_THREAD_%s' % _mwsrv_thread_id, func, args) except : return False return True # ---------------------------------------------------------------------------- @staticmethod def _unquote(s) : r = s.split('%') for i in range(1, len(r)) : s = r[i] try : r[i] = chr(int(s[:2], 16)) + s[2:] except : r[i] = '%' + s return ''.join(r) # ------------------------------------------------------------------------------ @staticmethod def _unquote_plus(s) : return MicroWebSrv._unquote(s.replace('+', ' ')) # ------------------------------------------------------------------------------ @staticmethod def _fileExists(path) : try : stat(path) return True except : return False # ---------------------------------------------------------------------------- @staticmethod def _isPyHTMLFile(filename) : return filename.lower().endswith(MicroWebSrv._pyhtmlPagesExt) # ============================================================================ # ===( Constructor )========================================================== # ============================================================================ def __init__( self, routeHandlers = [], port = 80, bindIP = '0.0.0.0', webPath = "/flash/www" ) : self._srvAddr = (bindIP, port) self._webPath = webPath self._notFoundUrl = None self._started = False self.MaxWebSocketRecvLen = 1024 self.WebSocketThreaded = True self.AcceptWebSocketCallback = None self.LetCacheStaticContentLevel = 2 self._routeHandlers = [] routeHandlers += self._docoratedRouteHandlers for route, method, func in routeHandlers : routeParts = route.split('/') # -> ['', 'users', '<uID>', 'addresses', '<addrID>', 'test', '<anotherID>'] routeArgNames = [] routeRegex = '' for s in routeParts : if s.startswith('<') and s.endswith('>') : routeArgNames.append(s[1:-1]) routeRegex += '/(\\w*)' elif s : routeRegex += '/' + s routeRegex += '$' # -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$' routeRegex = re.compile(routeRegex) self._routeHandlers.append(MicroWebSrvRoute(route, method, func, routeArgNames, routeRegex)) # ============================================================================ # ===( Server Process )======================================================= # ============================================================================ def _serverProcess(self) : self._started = True while True : try : client, cliAddr = self._server.accept() except Exception as ex : if ex.args and ex.args[0] == 113 : break continue self._client(self, client, cliAddr) self._started = False # ============================================================================ # ===( Functions )============================================================ # ============================================================================ def Start(self, threaded=False) : if not self._started : self._server = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP ) self._server.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) self._server.bind(self._srvAddr) self._server.listen(1) if threaded : MicroWebSrv._startThread(self._serverProcess) else : self._serverProcess() # ---------------------------------------------------------------------------- def Stop(self) : if self._started : self._server.close() # ---------------------------------------------------------------------------- def IsStarted(self) : return self._started # ---------------------------------------------------------------------------- def SetNotFoundPageUrl(self, url=None) : self._notFoundUrl = url # ---------------------------------------------------------------------------- def GetMimeTypeFromFilename(self, filename) : filename = filename.lower() for ext in self._mimeTypes : if filename.endswith(ext) : return self._mimeTypes[ext] return None # ---------------------------------------------------------------------------- def GetRouteHandler(self, resUrl, method) : if self._routeHandlers : #resUrl = resUrl.upper() if resUrl.endswith('/') : resUrl = resUrl[:-1] method = method.upper() for rh in self._routeHandlers : if rh.method == method : m = rh.routeRegex.match(resUrl) if m : # found matching route? if rh.routeArgNames : routeArgs = {} for i, name in enumerate(rh.routeArgNames) : value = m.group(i+1) try : value = int(value) except : pass routeArgs[name] = value return (rh.func, routeArgs) else : return (rh.func, None) return (None, None) # ---------------------------------------------------------------------------- def _physPathFromURLPath(self, urlPath) : if urlPath == '/' : for idxPage in self._indexPages : physPath = self._webPath + '/' + idxPage if MicroWebSrv._fileExists(physPath) : return physPath else : physPath = self._webPath + urlPath if MicroWebSrv._fileExists(physPath) : return physPath return None # ============================================================================ # ===( Class Client )======================================================== # ============================================================================ class _client : # ------------------------------------------------------------------------ def __init__(self, microWebSrv, socket, addr) : socket.settimeout(2) self._microWebSrv = microWebSrv self._socket = socket self._addr = addr self._method = None self._path = None self._httpVer = None self._resPath = "/" self._queryString = "" self._queryParams = { } self._headers = { } self._contentType = None self._contentLength = 0 if hasattr(socket, 'readline'): # MicroPython self._socketfile = self._socket else: # CPython self._socketfile = self._socket.makefile('rwb') self._processRequest() # ------------------------------------------------------------------------ def _processRequest(self) : try : response = MicroWebSrv._response(self) if self._parseFirstLine(response) : if self._parseHeader(response) : upg = self._getConnUpgrade() if not upg : routeHandler, routeArgs = self._microWebSrv.GetRouteHandler(self._resPath, self._method) if routeHandler : if routeArgs is not None: routeHandler(self, response, routeArgs) else: routeHandler(self, response) elif self._method.upper() == "GET" : filepath = self._microWebSrv._physPathFromURLPath(self._resPath) if filepath : if MicroWebSrv._isPyHTMLFile(filepath) : response.WriteResponsePyHTMLFile(filepath) else : contentType = self._microWebSrv.GetMimeTypeFromFilename(filepath) if contentType : if self._microWebSrv.LetCacheStaticContentLevel > 0 : if self._microWebSrv.LetCacheStaticContentLevel > 1 and \ 'if-modified-since' in self._headers : response.WriteResponseNotModified() else: headers = { 'Last-Modified' : 'Fri, 1 Jan 2018 23:42:00 GMT', \ 'Cache-Control' : 'max-age=315360000' } response.WriteResponseFile(filepath, contentType, headers) else : response.WriteResponseFile(filepath, contentType) else : response.WriteResponseForbidden() else : response.WriteResponseNotFound() else : response.WriteResponseMethodNotAllowed() elif upg == 'websocket' and 'MicroWebSocket' in globals() \ and self._microWebSrv.AcceptWebSocketCallback : MicroWebSocket( socket = self._socket, httpClient = self, httpResponse = response, maxRecvLen = self._microWebSrv.MaxWebSocketRecvLen, threaded = self._microWebSrv.WebSocketThreaded, acceptCallback = self._microWebSrv.AcceptWebSocketCallback ) return else : response.WriteResponseNotImplemented() else : response.WriteResponseBadRequest() except : response.WriteResponseInternalServerError() try : if self._socketfile is not self._socket: self._socketfile.close() self._socket.close() except : pass # ------------------------------------------------------------------------ def _parseFirstLine(self, response) : try : elements = self._socketfile.readline().decode().strip().split() if len(elements) == 3 : self._method = elements[0].upper() self._path = elements[1] self._httpVer = elements[2].upper() elements = self._path.split('?', 1) if len(elements) > 0 : self._resPath = MicroWebSrv._unquote_plus(elements[0]) if len(elements) > 1 : self._queryString = elements[1] elements = self._queryString.split('&') for s in elements : param = s.split('=', 1) if len(param) > 0 : value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else '' self._queryParams[MicroWebSrv._unquote(param[0])] = value return True except : pass return False # ------------------------------------------------------------------------ def _parseHeader(self, response) : while True : elements = self._socketfile.readline().decode().strip().split(':', 1) if len(elements) == 2 : self._headers[elements[0].strip().lower()] = elements[1].strip() elif len(elements) == 1 and len(elements[0]) == 0 : if self._method == 'POST' or self._method == 'PUT' : self._contentType = self._headers.get("content-type", None) self._contentLength = int(self._headers.get("content-length", 0)) return True else : return False # ------------------------------------------------------------------------ def _getConnUpgrade(self) : if 'upgrade' in self._headers.get('connection', '').lower() : return self._headers.get('upgrade', '').lower() return None # ------------------------------------------------------------------------ def GetServer(self) : return self._microWebSrv # ------------------------------------------------------------------------ def GetAddr(self) : return self._addr # ------------------------------------------------------------------------ def GetIPAddr(self) : return self._addr[0] # ------------------------------------------------------------------------ def GetPort(self) : return self._addr[1] # ------------------------------------------------------------------------ def GetRequestMethod(self) : return self._method # ------------------------------------------------------------------------ def GetRequestTotalPath(self) : return self._path # ------------------------------------------------------------------------ def GetRequestPath(self) : return self._resPath # ------------------------------------------------------------------------ def GetRequestQueryString(self) : return self._queryString # ------------------------------------------------------------------------ def GetRequestQueryParams(self) : return self._queryParams # ------------------------------------------------------------------------ def GetRequestHeaders(self) : return self._headers # ------------------------------------------------------------------------ def GetRequestContentType(self) : return self._contentType # ------------------------------------------------------------------------ def GetRequestContentLength(self) : return self._contentLength # ------------------------------------------------------------------------ def ReadRequestContent(self, size=None) : self._socket.setblocking(False) b = None try : if not size : b = self._socketfile.read(self._contentLength) elif size > 0 : b = self._socketfile.read(size) except : pass self._socket.setblocking(True) return b if b else b'' # ------------------------------------------------------------------------ def ReadRequestPostedFormData(self) : res = { } data = self.ReadRequestContent() if len(data) > 0 : elements = data.decode().split('&') for s in elements : param = s.split('=', 1) if len(param) > 0 : value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else '' res[MicroWebSrv._unquote(param[0])] = value return res # ------------------------------------------------------------------------ def ReadRequestContentAsJSON(self) : try : return loads(self.ReadRequestContent()) except : return None # ============================================================================ # ===( Class Response )====================================================== # ============================================================================ class _response : # ------------------------------------------------------------------------ def __init__(self, client) : self._client = client # ------------------------------------------------------------------------ def _write(self, data) : if data : if type(data) == str : data = data.encode() return self._client._socketfile.write(data) return 0 # ------------------------------------------------------------------------ def _writeFirstLine(self, code) : reason = self._responseCodes.get(code, ('Unknown reason', ))[0] self._write("HTTP/1.1 %s %s\r\n" % (code, reason)) # ------------------------------------------------------------------------ def _writeHeader(self, name, value) : self._write("%s: %s\r\n" % (name, value)) # ------------------------------------------------------------------------ def _writeContentTypeHeader(self, contentType, charset=None) : if contentType : ct = contentType \ + (("; charset=%s" % charset) if charset else "") else : ct = "application/octet-stream" self._writeHeader("Content-Type", ct) # ------------------------------------------------------------------------ def _writeServerHeader(self) : self._writeHeader("Server", "MicroWebSrv by JC`zic") # ------------------------------------------------------------------------ def _writeEndHeader(self) : self._write("\r\n") # ------------------------------------------------------------------------ def _writeBeforeContent(self, code, headers, contentType, contentCharset, contentLength) : self._writeFirstLine(code) if isinstance(headers, dict) : for header in headers : self._writeHeader(header, headers[header]) if contentLength > 0 : self._writeContentTypeHeader(contentType, contentCharset) self._writeHeader("Content-Length", contentLength) self._writeServerHeader() self._writeHeader("Connection", "close") self._writeEndHeader() # ------------------------------------------------------------------------ def WriteSwitchProto(self, upgrade, headers=None) : self._writeFirstLine(101) self._writeHeader("Connection", "Upgrade") self._writeHeader("Upgrade", upgrade) if isinstance(headers, dict) : for header in headers : self._writeHeader(header, headers[header]) self._writeServerHeader() self._writeEndHeader() if self._client._socketfile is not self._client._socket : self._client._socketfile.flush() # CPython needs flush to continue protocol # ------------------------------------------------------------------------ def WriteResponse(self, code, headers, contentType, contentCharset, content) : try : if content : if type(content) == str : content = content.encode() contentLength = len(content) else : contentLength = 0 self._writeBeforeContent(code, headers, contentType, contentCharset, contentLength) if content : self._write(content) return True except : return False # ------------------------------------------------------------------------ def WriteResponsePyHTMLFile(self, filepath, headers=None, vars=None) : if 'MicroWebTemplate' in globals() : with open(filepath, 'r') as file : code = file.read() mWebTmpl = MicroWebTemplate(code, escapeStrFunc=MicroWebSrv.HTMLEscape, filepath=filepath) try : tmplResult = mWebTmpl.Execute(None, vars) return self.WriteResponse(200, headers, "text/html", "UTF-8", tmplResult) except Exception as ex : return self.WriteResponse( 500, None, "text/html", "UTF-8", self._execErrCtnTmpl % { 'module' : 'PyHTML', 'message' : str(ex) } ) return self.WriteResponseNotImplemented() # ------------------------------------------------------------------------ def WriteResponseFile(self, filepath, contentType=None, headers=None) : try : size = stat(filepath)[6] if size > 0 : with open(filepath, 'rb') as file : self._writeBeforeContent(200, headers, contentType, None, size) try : buf = bytearray(1024) while size > 0 : x = file.readinto(buf) if x < len(buf) : buf = memoryview(buf)[:x] self._write(buf) size -= x return True except : self.WriteResponseInternalServerError() return False except : pass self.WriteResponseNotFound() return False # ------------------------------------------------------------------------ def WriteResponseFileAttachment(self, filepath, attachmentName, headers=None) : if not isinstance(headers, dict) : headers = { } headers["Content-Disposition"] = "attachment; filename=\"%s\"" % attachmentName return self.WriteResponseFile(filepath, None, headers) # ------------------------------------------------------------------------ def WriteResponseOk(self, headers=None, contentType=None, contentCharset=None, content=None) : return self.WriteResponse(200, headers, contentType, contentCharset, content) # ------------------------------------------------------------------------ def WriteResponseJSONOk(self, obj=None, headers=None) : return self.WriteResponse(200, headers, "application/json", "UTF-8", dumps(obj)) # ------------------------------------------------------------------------ def WriteResponseRedirect(self, location) : headers = { "Location" : location } return self.WriteResponse(302, headers, None, None, None) # ------------------------------------------------------------------------ def WriteResponseError(self, code) : responseCode = self._responseCodes.get(code, ('Unknown reason', '')) return self.WriteResponse( code, None, "text/html", "UTF-8", self._errCtnTmpl % { 'code' : code, 'reason' : responseCode[0], 'message' : responseCode[1] } ) # ------------------------------------------------------------------------ def WriteResponseJSONError(self, code, obj=None) : return self.WriteResponse( code, None, "application/json", "UTF-8", dumps(obj if obj else { }) ) # ------------------------------------------------------------------------ def WriteResponseNotModified(self) : return self.WriteResponseError(304) # ------------------------------------------------------------------------ def WriteResponseBadRequest(self) : return self.WriteResponseError(400) # ------------------------------------------------------------------------ def WriteResponseForbidden(self) : return self.WriteResponseError(403) # ------------------------------------------------------------------------ def WriteResponseNotFound(self) : if self._client._microWebSrv._notFoundUrl : self.WriteResponseRedirect(self._client._microWebSrv._notFoundUrl) else : return self.WriteResponseError(404) # ------------------------------------------------------------------------ def WriteResponseMethodNotAllowed(self) : return self.WriteResponseError(405) # ------------------------------------------------------------------------ def WriteResponseInternalServerError(self) : return self.WriteResponseError(500) # ------------------------------------------------------------------------ def WriteResponseNotImplemented(self) : return self.WriteResponseError(501) # ------------------------------------------------------------------------ def FlashMessage(self, messageText, messageStyle='') : if 'MicroWebTemplate' in globals() : MicroWebTemplate.MESSAGE_TEXT = messageText MicroWebTemplate.MESSAGE_STYLE = messageStyle # ------------------------------------------------------------------------ _errCtnTmpl = """\ <html> <head> <title>Error</title> </head> <body> <h1>%(code)d %(reason)s</h1> %(message)s </body> </html> """ # ------------------------------------------------------------------------ _execErrCtnTmpl = """\ <html> <head> <title>Page execution error</title> </head> <body> <h1>%(module)s page execution error</h1> %(message)s </body> </html> """ # ------------------------------------------------------------------------ _responseCodes = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this resource.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), } # ============================================================================ # ============================================================================ # ============================================================================
en
0.190156
The MIT License (MIT) Copyright 漏 2018 <NAME> & HC虏 (www.hc2.fr) # ============================================================================ # ===( Constants )============================================================ # ============================================================================ # ============================================================================ # ===( Class globals )======================================================= # ============================================================================ # ============================================================================ # ===( Utils )=============================================================== # ============================================================================ Adds a route handler function to the routing list # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ---------------------------------------------------------------------------- # ============================================================================ # ===( Constructor )========================================================== # ============================================================================ # -> ['', 'users', '<uID>', 'addresses', '<addrID>', 'test', '<anotherID>'] # -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$' # ============================================================================ # ===( Server Process )======================================================= # ============================================================================ # ============================================================================ # ===( Functions )============================================================ # ============================================================================ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- #resUrl = resUrl.upper() # found matching route? # ---------------------------------------------------------------------------- # ============================================================================ # ===( Class Client )======================================================== # ============================================================================ # ------------------------------------------------------------------------ # MicroPython # CPython # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ============================================================================ # ===( Class Response )====================================================== # ============================================================================ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # CPython needs flush to continue protocol # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ \ <html> <head> <title>Error</title> </head> <body> <h1>%(code)d %(reason)s</h1> %(message)s </body> </html> # ------------------------------------------------------------------------ \ <html> <head> <title>Page execution error</title> </head> <body> <h1>%(module)s page execution error</h1> %(message)s </body> </html> # ------------------------------------------------------------------------ # ============================================================================ # ============================================================================ # ============================================================================
2.357596
2
lisp/repl.py
fotcorn/lisp
0
6624348
<reponame>fotcorn/lisp import os import sys import readline import atexit from lisp import interpreter_builtins from lisp.interpreter_exceptions import InterpreterException from lisp.lexer import lex, LexerException from lisp.parser import parse, ParseError from lisp.interpreter import run, Interpreter def repl(): print("Write 'exit' to exit repl") history_file = os.path.join(os.path.expanduser("~"), ".fotcorn_lisp_history") try: readline.read_history_file(history_file) readline.set_history_length(1000) except FileNotFoundError: pass atexit.register(readline.write_history_file, history_file) readline.parse_and_bind('') interpreter = Interpreter(interpreter_builtins.builtins) while True: try: line = input('>>> ') except EOFError: sys.exit(0) except KeyboardInterrupt: print() continue if line == 'exit': sys.exit(0) try: tokens = lex(line) ast = parse(tokens) value = interpreter.run(ast) if value: print(value) except (LexerException, ParseError, InterpreterException) as ex: print('Error: ', str(ex))
import os import sys import readline import atexit from lisp import interpreter_builtins from lisp.interpreter_exceptions import InterpreterException from lisp.lexer import lex, LexerException from lisp.parser import parse, ParseError from lisp.interpreter import run, Interpreter def repl(): print("Write 'exit' to exit repl") history_file = os.path.join(os.path.expanduser("~"), ".fotcorn_lisp_history") try: readline.read_history_file(history_file) readline.set_history_length(1000) except FileNotFoundError: pass atexit.register(readline.write_history_file, history_file) readline.parse_and_bind('') interpreter = Interpreter(interpreter_builtins.builtins) while True: try: line = input('>>> ') except EOFError: sys.exit(0) except KeyboardInterrupt: print() continue if line == 'exit': sys.exit(0) try: tokens = lex(line) ast = parse(tokens) value = interpreter.run(ast) if value: print(value) except (LexerException, ParseError, InterpreterException) as ex: print('Error: ', str(ex))
none
1
2.769726
3
reinvent_models/model_factory/generative_model.py
GT4SD/-reinvent_models
0
6624349
<filename>reinvent_models/model_factory/generative_model.py from reinvent_models.model_factory.configurations.model_configuration import ModelConfiguration from reinvent_models.model_factory.enums.model_type_enum import ModelTypeEnum from reinvent_models.model_factory.generative_model_base import GenerativeModelBase from reinvent_models.model_factory.lib_invent_adapter import LibInventAdapter from reinvent_models.model_factory.link_invent_adapter import LinkInventAdapter from reinvent_models.model_factory.reinvent_core_adapter import ReinventCoreAdapter class GenerativeModel: def __new__(cls, configuration: ModelConfiguration) -> GenerativeModelBase: cls._configuration = configuration model_type_enum = ModelTypeEnum() if cls._configuration.model_type == model_type_enum.DEFAULT: model = ReinventCoreAdapter(cls._configuration.model_file_path, mode=cls._configuration.model_mode) elif cls._configuration.model_type == model_type_enum.LIB_INVENT: model = LibInventAdapter(cls._configuration.model_file_path, mode=cls._configuration.model_mode) elif cls._configuration.model_type == model_type_enum.LINK_INVENT: model = LinkInventAdapter(cls._configuration.model_file_path, mode=cls._configuration.model_mode) else: raise ValueError(f"Invalid model_type provided: '{cls._configuration.model_type}") return model
<filename>reinvent_models/model_factory/generative_model.py from reinvent_models.model_factory.configurations.model_configuration import ModelConfiguration from reinvent_models.model_factory.enums.model_type_enum import ModelTypeEnum from reinvent_models.model_factory.generative_model_base import GenerativeModelBase from reinvent_models.model_factory.lib_invent_adapter import LibInventAdapter from reinvent_models.model_factory.link_invent_adapter import LinkInventAdapter from reinvent_models.model_factory.reinvent_core_adapter import ReinventCoreAdapter class GenerativeModel: def __new__(cls, configuration: ModelConfiguration) -> GenerativeModelBase: cls._configuration = configuration model_type_enum = ModelTypeEnum() if cls._configuration.model_type == model_type_enum.DEFAULT: model = ReinventCoreAdapter(cls._configuration.model_file_path, mode=cls._configuration.model_mode) elif cls._configuration.model_type == model_type_enum.LIB_INVENT: model = LibInventAdapter(cls._configuration.model_file_path, mode=cls._configuration.model_mode) elif cls._configuration.model_type == model_type_enum.LINK_INVENT: model = LinkInventAdapter(cls._configuration.model_file_path, mode=cls._configuration.model_mode) else: raise ValueError(f"Invalid model_type provided: '{cls._configuration.model_type}") return model
none
1
1.891927
2
for_loops_protists.py
julencosme/python-crash-course
0
6624350
protists_chlorophyta = ['volvox', 'actinastrum', 'hydrodictyon'] for protist in protists_chlorophyta: print(protist) for protist in protists_chlorophyta: print(protist.title() + ", is a protist in the green algae genus.") print("All of these protists are in the division Chlorophyta, and they are photosynthetic organisms.")
protists_chlorophyta = ['volvox', 'actinastrum', 'hydrodictyon'] for protist in protists_chlorophyta: print(protist) for protist in protists_chlorophyta: print(protist.title() + ", is a protist in the green algae genus.") print("All of these protists are in the division Chlorophyta, and they are photosynthetic organisms.")
none
1
3.128229
3