prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. """ Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\ fc_rules_cf_fc.build_auxilliary_coordinate`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # import iris tests first so that some things can be initialised before # importing anything else import iris.tests as tests import numpy as np import mock from iris.coords import AuxCoord from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \ build_auxiliary_coordinate class TestBoundsVertexDim(tests.IrisTest): def setUp(self): # Create coordinate cf variables and pyke engine. points = np.arange(6).reshape(2, 3) self.cf_coord_var = mock.Mock( dimensions=('foo', 'bar'), cf_name='wibble', standard_name=None, long_name='wibble', units='m', shape=points.shape, dtype=points.dtype, __getitem__=lambda self, key: points[key]) self.engine = mock.Mock( cube=mock.Mock(), cf_var=mock.Mock(dimensions=('foo', 'bar')), filename='DUMMY', provides=dict(coordinates=[])) # Create patch for deferred loading that prevents attempted # file access. This assumes that self.cf_bounds_var is # defined in the test case. def patched__getitem__(proxy_self, keys): variable = None for var in (self.cf_coord_var, self.cf_bounds_var): if proxy_self.variable_name == var.cf_name: <|fim_middle|> raise RuntimeError() self.deferred_load_patch = mock.patch( 'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__', new=patched__getitem__) def test_slowest_varying_vertex_dim(self): # Create the bounds cf variable. bounds = np.arange(24).reshape(4, 2, 3) self.cf_bounds_var = mock.Mock( dimensions=('nv', 'foo', 'bar'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) # Expected bounds on the resulting coordinate should be rolled so that # the vertex dimension is at the end. expected_bounds = np.rollaxis(bounds, 0, bounds.ndim) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=expected_bounds) # Patch the helper function that retrieves the bounds cf variable. # This avoids the need for setting up further mocking of cf objects. get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_varying_vertex_dim(self): bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('foo', 'bar', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_with_different_dim_names(self): # Despite the dimension names ('x', and 'y') differing from the coord's # which are 'foo' and 'bar' (as permitted by the cf spec), # this should still work because the vertex dim is the fastest varying. bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('x', 'y', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) if __name__ == '__main__': tests.main() <|fim▁end|>
return var[keys]
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. """ Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\ fc_rules_cf_fc.build_auxilliary_coordinate`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # import iris tests first so that some things can be initialised before # importing anything else import iris.tests as tests import numpy as np import mock from iris.coords import AuxCoord from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \ build_auxiliary_coordinate class TestBoundsVertexDim(tests.IrisTest): def setUp(self): # Create coordinate cf variables and pyke engine. points = np.arange(6).reshape(2, 3) self.cf_coord_var = mock.Mock( dimensions=('foo', 'bar'), cf_name='wibble', standard_name=None, long_name='wibble', units='m', shape=points.shape, dtype=points.dtype, __getitem__=lambda self, key: points[key]) self.engine = mock.Mock( cube=mock.Mock(), cf_var=mock.Mock(dimensions=('foo', 'bar')), filename='DUMMY', provides=dict(coordinates=[])) # Create patch for deferred loading that prevents attempted # file access. This assumes that self.cf_bounds_var is # defined in the test case. def patched__getitem__(proxy_self, keys): variable = None for var in (self.cf_coord_var, self.cf_bounds_var): if proxy_self.variable_name == var.cf_name: return var[keys] raise RuntimeError() self.deferred_load_patch = mock.patch( 'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__', new=patched__getitem__) def test_slowest_varying_vertex_dim(self): # Create the bounds cf variable. bounds = np.arange(24).reshape(4, 2, 3) self.cf_bounds_var = mock.Mock( dimensions=('nv', 'foo', 'bar'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) # Expected bounds on the resulting coordinate should be rolled so that # the vertex dimension is at the end. expected_bounds = np.rollaxis(bounds, 0, bounds.ndim) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=expected_bounds) # Patch the helper function that retrieves the bounds cf variable. # This avoids the need for setting up further mocking of cf objects. get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_varying_vertex_dim(self): bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('foo', 'bar', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_with_different_dim_names(self): # Despite the dimension names ('x', and 'y') differing from the coord's # which are 'foo' and 'bar' (as permitted by the cf spec), # this should still work because the vertex dim is the fastest varying. bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('x', 'y', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
tests.main()
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. """ Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\ fc_rules_cf_fc.build_auxilliary_coordinate`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # import iris tests first so that some things can be initialised before # importing anything else import iris.tests as tests import numpy as np import mock from iris.coords import AuxCoord from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \ build_auxiliary_coordinate class TestBoundsVertexDim(tests.IrisTest): def <|fim_middle|>(self): # Create coordinate cf variables and pyke engine. points = np.arange(6).reshape(2, 3) self.cf_coord_var = mock.Mock( dimensions=('foo', 'bar'), cf_name='wibble', standard_name=None, long_name='wibble', units='m', shape=points.shape, dtype=points.dtype, __getitem__=lambda self, key: points[key]) self.engine = mock.Mock( cube=mock.Mock(), cf_var=mock.Mock(dimensions=('foo', 'bar')), filename='DUMMY', provides=dict(coordinates=[])) # Create patch for deferred loading that prevents attempted # file access. This assumes that self.cf_bounds_var is # defined in the test case. def patched__getitem__(proxy_self, keys): variable = None for var in (self.cf_coord_var, self.cf_bounds_var): if proxy_self.variable_name == var.cf_name: return var[keys] raise RuntimeError() self.deferred_load_patch = mock.patch( 'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__', new=patched__getitem__) def test_slowest_varying_vertex_dim(self): # Create the bounds cf variable. bounds = np.arange(24).reshape(4, 2, 3) self.cf_bounds_var = mock.Mock( dimensions=('nv', 'foo', 'bar'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) # Expected bounds on the resulting coordinate should be rolled so that # the vertex dimension is at the end. expected_bounds = np.rollaxis(bounds, 0, bounds.ndim) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=expected_bounds) # Patch the helper function that retrieves the bounds cf variable. # This avoids the need for setting up further mocking of cf objects. get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_varying_vertex_dim(self): bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('foo', 'bar', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_with_different_dim_names(self): # Despite the dimension names ('x', and 'y') differing from the coord's # which are 'foo' and 'bar' (as permitted by the cf spec), # this should still work because the vertex dim is the fastest varying. bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('x', 'y', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) if __name__ == '__main__': tests.main() <|fim▁end|>
setUp
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. """ Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\ fc_rules_cf_fc.build_auxilliary_coordinate`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # import iris tests first so that some things can be initialised before # importing anything else import iris.tests as tests import numpy as np import mock from iris.coords import AuxCoord from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \ build_auxiliary_coordinate class TestBoundsVertexDim(tests.IrisTest): def setUp(self): # Create coordinate cf variables and pyke engine. points = np.arange(6).reshape(2, 3) self.cf_coord_var = mock.Mock( dimensions=('foo', 'bar'), cf_name='wibble', standard_name=None, long_name='wibble', units='m', shape=points.shape, dtype=points.dtype, __getitem__=lambda self, key: points[key]) self.engine = mock.Mock( cube=mock.Mock(), cf_var=mock.Mock(dimensions=('foo', 'bar')), filename='DUMMY', provides=dict(coordinates=[])) # Create patch for deferred loading that prevents attempted # file access. This assumes that self.cf_bounds_var is # defined in the test case. def <|fim_middle|>(proxy_self, keys): variable = None for var in (self.cf_coord_var, self.cf_bounds_var): if proxy_self.variable_name == var.cf_name: return var[keys] raise RuntimeError() self.deferred_load_patch = mock.patch( 'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__', new=patched__getitem__) def test_slowest_varying_vertex_dim(self): # Create the bounds cf variable. bounds = np.arange(24).reshape(4, 2, 3) self.cf_bounds_var = mock.Mock( dimensions=('nv', 'foo', 'bar'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) # Expected bounds on the resulting coordinate should be rolled so that # the vertex dimension is at the end. expected_bounds = np.rollaxis(bounds, 0, bounds.ndim) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=expected_bounds) # Patch the helper function that retrieves the bounds cf variable. # This avoids the need for setting up further mocking of cf objects. get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_varying_vertex_dim(self): bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('foo', 'bar', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_with_different_dim_names(self): # Despite the dimension names ('x', and 'y') differing from the coord's # which are 'foo' and 'bar' (as permitted by the cf spec), # this should still work because the vertex dim is the fastest varying. bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('x', 'y', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) if __name__ == '__main__': tests.main() <|fim▁end|>
patched__getitem__
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. """ Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\ fc_rules_cf_fc.build_auxilliary_coordinate`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # import iris tests first so that some things can be initialised before # importing anything else import iris.tests as tests import numpy as np import mock from iris.coords import AuxCoord from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \ build_auxiliary_coordinate class TestBoundsVertexDim(tests.IrisTest): def setUp(self): # Create coordinate cf variables and pyke engine. points = np.arange(6).reshape(2, 3) self.cf_coord_var = mock.Mock( dimensions=('foo', 'bar'), cf_name='wibble', standard_name=None, long_name='wibble', units='m', shape=points.shape, dtype=points.dtype, __getitem__=lambda self, key: points[key]) self.engine = mock.Mock( cube=mock.Mock(), cf_var=mock.Mock(dimensions=('foo', 'bar')), filename='DUMMY', provides=dict(coordinates=[])) # Create patch for deferred loading that prevents attempted # file access. This assumes that self.cf_bounds_var is # defined in the test case. def patched__getitem__(proxy_self, keys): variable = None for var in (self.cf_coord_var, self.cf_bounds_var): if proxy_self.variable_name == var.cf_name: return var[keys] raise RuntimeError() self.deferred_load_patch = mock.patch( 'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__', new=patched__getitem__) def <|fim_middle|>(self): # Create the bounds cf variable. bounds = np.arange(24).reshape(4, 2, 3) self.cf_bounds_var = mock.Mock( dimensions=('nv', 'foo', 'bar'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) # Expected bounds on the resulting coordinate should be rolled so that # the vertex dimension is at the end. expected_bounds = np.rollaxis(bounds, 0, bounds.ndim) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=expected_bounds) # Patch the helper function that retrieves the bounds cf variable. # This avoids the need for setting up further mocking of cf objects. get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_varying_vertex_dim(self): bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('foo', 'bar', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_with_different_dim_names(self): # Despite the dimension names ('x', and 'y') differing from the coord's # which are 'foo' and 'bar' (as permitted by the cf spec), # this should still work because the vertex dim is the fastest varying. bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('x', 'y', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) if __name__ == '__main__': tests.main() <|fim▁end|>
test_slowest_varying_vertex_dim
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. """ Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\ fc_rules_cf_fc.build_auxilliary_coordinate`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # import iris tests first so that some things can be initialised before # importing anything else import iris.tests as tests import numpy as np import mock from iris.coords import AuxCoord from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \ build_auxiliary_coordinate class TestBoundsVertexDim(tests.IrisTest): def setUp(self): # Create coordinate cf variables and pyke engine. points = np.arange(6).reshape(2, 3) self.cf_coord_var = mock.Mock( dimensions=('foo', 'bar'), cf_name='wibble', standard_name=None, long_name='wibble', units='m', shape=points.shape, dtype=points.dtype, __getitem__=lambda self, key: points[key]) self.engine = mock.Mock( cube=mock.Mock(), cf_var=mock.Mock(dimensions=('foo', 'bar')), filename='DUMMY', provides=dict(coordinates=[])) # Create patch for deferred loading that prevents attempted # file access. This assumes that self.cf_bounds_var is # defined in the test case. def patched__getitem__(proxy_self, keys): variable = None for var in (self.cf_coord_var, self.cf_bounds_var): if proxy_self.variable_name == var.cf_name: return var[keys] raise RuntimeError() self.deferred_load_patch = mock.patch( 'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__', new=patched__getitem__) def test_slowest_varying_vertex_dim(self): # Create the bounds cf variable. bounds = np.arange(24).reshape(4, 2, 3) self.cf_bounds_var = mock.Mock( dimensions=('nv', 'foo', 'bar'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) # Expected bounds on the resulting coordinate should be rolled so that # the vertex dimension is at the end. expected_bounds = np.rollaxis(bounds, 0, bounds.ndim) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=expected_bounds) # Patch the helper function that retrieves the bounds cf variable. # This avoids the need for setting up further mocking of cf objects. get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def <|fim_middle|>(self): bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('foo', 'bar', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_with_different_dim_names(self): # Despite the dimension names ('x', and 'y') differing from the coord's # which are 'foo' and 'bar' (as permitted by the cf spec), # this should still work because the vertex dim is the fastest varying. bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('x', 'y', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) if __name__ == '__main__': tests.main() <|fim▁end|>
test_fastest_varying_vertex_dim
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. """ Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\ fc_rules_cf_fc.build_auxilliary_coordinate`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # import iris tests first so that some things can be initialised before # importing anything else import iris.tests as tests import numpy as np import mock from iris.coords import AuxCoord from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \ build_auxiliary_coordinate class TestBoundsVertexDim(tests.IrisTest): def setUp(self): # Create coordinate cf variables and pyke engine. points = np.arange(6).reshape(2, 3) self.cf_coord_var = mock.Mock( dimensions=('foo', 'bar'), cf_name='wibble', standard_name=None, long_name='wibble', units='m', shape=points.shape, dtype=points.dtype, __getitem__=lambda self, key: points[key]) self.engine = mock.Mock( cube=mock.Mock(), cf_var=mock.Mock(dimensions=('foo', 'bar')), filename='DUMMY', provides=dict(coordinates=[])) # Create patch for deferred loading that prevents attempted # file access. This assumes that self.cf_bounds_var is # defined in the test case. def patched__getitem__(proxy_self, keys): variable = None for var in (self.cf_coord_var, self.cf_bounds_var): if proxy_self.variable_name == var.cf_name: return var[keys] raise RuntimeError() self.deferred_load_patch = mock.patch( 'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__', new=patched__getitem__) def test_slowest_varying_vertex_dim(self): # Create the bounds cf variable. bounds = np.arange(24).reshape(4, 2, 3) self.cf_bounds_var = mock.Mock( dimensions=('nv', 'foo', 'bar'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) # Expected bounds on the resulting coordinate should be rolled so that # the vertex dimension is at the end. expected_bounds = np.rollaxis(bounds, 0, bounds.ndim) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=expected_bounds) # Patch the helper function that retrieves the bounds cf variable. # This avoids the need for setting up further mocking of cf objects. get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def test_fastest_varying_vertex_dim(self): bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('foo', 'bar', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) def <|fim_middle|>(self): # Despite the dimension names ('x', and 'y') differing from the coord's # which are 'foo' and 'bar' (as permitted by the cf spec), # this should still work because the vertex dim is the fastest varying. bounds = np.arange(24).reshape(2, 3, 4) self.cf_bounds_var = mock.Mock( dimensions=('x', 'y', 'nv'), cf_name='wibble_bnds', shape=bounds.shape, dtype=bounds.dtype, __getitem__=lambda self, key: bounds[key]) expected_coord = AuxCoord( self.cf_coord_var[:], long_name=self.cf_coord_var.long_name, var_name=self.cf_coord_var.cf_name, units=self.cf_coord_var.units, bounds=bounds) get_cf_bounds_var_patch = mock.patch( 'iris.fileformats._pyke_rules.compiled_krb.' 'fc_rules_cf_fc.get_cf_bounds_var', return_value=self.cf_bounds_var) # Asserts must lie within context manager because of deferred loading. with self.deferred_load_patch, get_cf_bounds_var_patch: build_auxiliary_coordinate(self.engine, self.cf_coord_var) # Test that expected coord is built and added to cube. self.engine.cube.add_aux_coord.assert_called_with( expected_coord, [0, 1]) # Test that engine.provides container is correctly populated. expected_list = [(expected_coord, self.cf_coord_var.cf_name)] self.assertEqual(self.engine.provides['coordinates'], expected_list) if __name__ == '__main__': tests.main() <|fim▁end|>
test_fastest_with_different_dim_names
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>"""django_todo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')<|fim▁hole|>Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^todo/', include('todo.urls')), url(r'^accounts/', include('accounts.urls')), ]<|fim▁end|>
Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- #!/usr/bin/env python from setuptools import setup, find_packages setup( name = 'wechat-python-sdk', version = '0.5.7', keywords = ('wechat', 'sdk', 'wechat sdk'), description = u'微信公众平台Python开发包',<|fim▁hole|> license = 'BSD License', url = 'https://github.com/doraemonext/wechat-python-sdk', author = 'doraemonext', author_email = '[email protected]', packages = find_packages(), include_package_data = True, platforms = 'any', install_requires=open("requirements.txt").readlines(), )<|fim▁end|>
long_description = open("README.rst").read(),
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context<|fim▁hole|> if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context)<|fim▁end|>
def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view'
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): <|fim_middle|> def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): <|fim_middle|> def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): <|fim_middle|> def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
return redirect('index')
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): <|fim_middle|> def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
return redirect('repo_list', user_name)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): <|fim_middle|> def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): <|fim_middle|> def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): <|fim_middle|> <|fim▁end|>
user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': <|fim_middle|> else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
base = '%s/%s/%s' %(url, user_name, repo_name)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: <|fim_middle|> if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
base = '%s/%s/%s/%s' %(url, user_name, repo_name, method)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: <|fim_middle|> if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
base = '%s/%s' %(base, path)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: <|fim_middle|> print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
base = "%s?%s" % (base, query)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: <|fim_middle|> c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
return path
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: <|fim_middle|> query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
return HttpResponse('Not authorized', status=401)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: <|fim_middle|> query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
return HttpResponse('Not authorized', status=401)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: <|fim_middle|> commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
return HttpResponse('Not authorized', status=401)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': <|fim_middle|> else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: <|fim_middle|> query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
file_path = None
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def <|fim_middle|>(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
cgit_url
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def <|fim_middle|>(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
cumulative_path
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def <|fim_middle|>(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
view_index
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def <|fim_middle|>(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
user_index
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def <|fim_middle|>(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
repo_plain
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def <|fim_middle|>(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def repo_browse(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
repo_snapshot
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import HttpResponse from django.core.servers.basehttp import FileWrapper from django.contrib.auth.models import User from django.shortcuts import render_to_response, redirect, get_object_or_404 from requests import get from urllib import urlretrieve from common.models import Repository from common.util import get_context def cgit_url(user_name, repo_name, method, path, query=None): url = 'http://localhost:8080/view' if method == 'summary': base = '%s/%s/%s' %(url, user_name, repo_name) else: base = '%s/%s/%s/%s' %(url, user_name, repo_name, method) if path is not None: base = '%s/%s' %(base, path) if query is not None and len(query)>1: base = "%s?%s" % (base, query) print base return base def cumulative_path(path): if path is None or len(path) == 0: return path c = [path[0]] for part in path[1:]: c.append('%s/%s'%(c[-1], part)) return c def view_index(request): return redirect('index') def user_index(request, user_name): return redirect('repo_list', user_name) def repo_plain(request, user_name, repo_name, path, prefix='plain'): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() print query url = cgit_url(user_name, repo_name, prefix, path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='text/plain') return response def repo_snapshot(request, user_name, repo_name, path): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) query = request.GET.urlencode() filename = path.split('/')[-1] url = cgit_url(user_name, repo_name, 'snapshot', path, query) (fname, info) = urlretrieve(url) response = HttpResponse(FileWrapper(open(fname)), content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response def <|fim_middle|>(request, user_name, repo_name, method='summary', path=None): user = request.user owner = get_object_or_404(User, username=user_name) repo = get_object_or_404(Repository, owner=owner, name=repo_name) collaborators = repo.collaborators.all() access = repo.user_access(user) if access is None: return HttpResponse('Not authorized', status=401) commit_id = request.GET.get('id') q = request.GET.get('q', '') qtype = request.GET.get('qt', 'grep') messages = { 'grep' : 'Log Message', 'author': 'Author', 'committer' : 'Committer', 'range' : 'Range' } search_text = messages.get(qtype, messages['grep']) if method == 'tree': file_path = path.split('/') path_parts = cumulative_path(file_path) file_path = zip(file_path, path_parts) else: file_path = None query = request.GET.urlencode() url = cgit_url(user_name, repo_name, method, path, query) text = get(url) context = get_context(request, {'owner': owner, 'repo_html':text.text, 'repo':repo, 'access':access, 'id':commit_id, 'method':method, 'q':q, 'qtype':qtype, 'search_text':search_text, 'file_path':file_path}) return render_to_response('viewer/repo_view.html', context) <|fim▁end|>
repo_browse
<|file_name|>test_connection.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): """ Create a queryset with a host given as a string """ # When create a queryset t = QuerySet("localhost", index="bar") # And I have records response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) @httpretty.activate def test_create_queryset_with_host_dict(): """ Create a queryset with a host given as a dict """ # When create a queryset connection_info = {"host": "localhost", "port": 8080} t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") @httpretty.activate def test_create_queryset_with_host_list(): """ Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search",<|fim▁hole|> results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar")<|fim▁end|>
body=json.dumps(good_response), content_type="application/json") # When I run a query
<|file_name|>test_connection.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): <|fim_middle|> @httpretty.activate def test_create_queryset_with_host_dict(): """ Create a queryset with a host given as a dict """ # When create a queryset connection_info = {"host": "localhost", "port": 8080} t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") @httpretty.activate def test_create_queryset_with_host_list(): """ Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") <|fim▁end|>
""" Create a queryset with a host given as a string """ # When create a queryset t = QuerySet("localhost", index="bar") # And I have records response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1)
<|file_name|>test_connection.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): """ Create a queryset with a host given as a string """ # When create a queryset t = QuerySet("localhost", index="bar") # And I have records response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) @httpretty.activate def test_create_queryset_with_host_dict(): <|fim_middle|> @httpretty.activate def test_create_queryset_with_host_list(): """ Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") <|fim▁end|>
""" Create a queryset with a host given as a dict """ # When create a queryset connection_info = {"host": "localhost", "port": 8080} t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar")
<|file_name|>test_connection.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): """ Create a queryset with a host given as a string """ # When create a queryset t = QuerySet("localhost", index="bar") # And I have records response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) @httpretty.activate def test_create_queryset_with_host_dict(): """ Create a queryset with a host given as a dict """ # When create a queryset connection_info = {"host": "localhost", "port": 8080} t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") @httpretty.activate def test_create_queryset_with_host_list(): <|fim_middle|> <|fim▁end|>
""" Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar")
<|file_name|>test_connection.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def <|fim_middle|>(): """ Create a queryset with a host given as a string """ # When create a queryset t = QuerySet("localhost", index="bar") # And I have records response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) @httpretty.activate def test_create_queryset_with_host_dict(): """ Create a queryset with a host given as a dict """ # When create a queryset connection_info = {"host": "localhost", "port": 8080} t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") @httpretty.activate def test_create_queryset_with_host_list(): """ Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") <|fim▁end|>
test_create_queryset_with_host_string
<|file_name|>test_connection.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): """ Create a queryset with a host given as a string """ # When create a queryset t = QuerySet("localhost", index="bar") # And I have records response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) @httpretty.activate def <|fim_middle|>(): """ Create a queryset with a host given as a dict """ # When create a queryset connection_info = {"host": "localhost", "port": 8080} t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") @httpretty.activate def test_create_queryset_with_host_list(): """ Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") <|fim▁end|>
test_create_queryset_with_host_dict
<|file_name|>test_connection.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals import httpretty import json import sure from pyeqs import QuerySet, Filter from pyeqs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): """ Create a queryset with a host given as a string """ # When create a queryset t = QuerySet("localhost", index="bar") # And I have records response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) @httpretty.activate def test_create_queryset_with_host_dict(): """ Create a queryset with a host given as a dict """ # When create a queryset connection_info = {"host": "localhost", "port": 8080} t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") @httpretty.activate def <|fim_middle|>(): """ Create a queryset with a host given as a list """ # When create a queryset connection_info = [{"host": "localhost", "port": 8080}] t = QuerySet(connection_info, index="bar") # And I have records good_response = { "took": 1, "hits": { "total": 1, "max_score": 1, "hits": [ { "_index": "bar", "_type": "baz", "_id": "1", "_score": 10, "_source": { "foo": "bar" }, "sort": [ 1395687078000 ] } ] } } bad_response = { "took": 1, "hits": { "total": 0, "max_score": None, "hits": [] } } httpretty.register_uri(httpretty.GET, "http://localhost:9200/bar/_search", body=json.dumps(bad_response), content_type="application/json") httpretty.register_uri(httpretty.GET, "http://localhost:8080/bar/_search", body=json.dumps(good_response), content_type="application/json") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0]["_source"]["foo"].should.equal("bar") <|fim▁end|>
test_create_queryset_with_host_list
<|file_name|>nmcollector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from noisemapper.mapper import * #from collectors.lib import utils <|fim▁hole|> def main(): # utils.drop_privileges() mapper = NoiseMapper() mapper.run() if __name__ == "__main__": main()<|fim▁end|>
### Define the object mapper and start mapping
<|file_name|>nmcollector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from noisemapper.mapper import * #from collectors.lib import utils ### Define the object mapper and start mapping def main(): # utils.drop_privileges() <|fim_middle|> if __name__ == "__main__": main() <|fim▁end|>
mapper = NoiseMapper() mapper.run()
<|file_name|>nmcollector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from noisemapper.mapper import * #from collectors.lib import utils ### Define the object mapper and start mapping def main(): # utils.drop_privileges() mapper = NoiseMapper() mapper.run() if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
main()
<|file_name|>nmcollector.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from noisemapper.mapper import * #from collectors.lib import utils ### Define the object mapper and start mapping def <|fim_middle|>(): # utils.drop_privileges() mapper = NoiseMapper() mapper.run() if __name__ == "__main__": main() <|fim▁end|>
main
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr)<|fim▁hole|> i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2)<|fim▁end|>
if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4)))
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: <|fim_middle|> <|fim▁end|>
def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2)
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): <|fim_middle|> def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width()
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): <|fim_middle|> def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): <|fim_middle|> def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): <|fim_middle|> def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.x = x self.y = y
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): <|fim_middle|> def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.font = font
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): <|fim_middle|> def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.hcolor = color
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): <|fim_middle|> def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.color = color
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): <|fim_middle|> <|fim▁end|>
self.x = x-(self.width/2) self.y = y-(self.height/2)
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: <|fim_middle|> def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.width = ren.get_width()
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: <|fim_middle|> else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
clr = self.hcolor
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: <|fim_middle|> text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
clr = self.color
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: <|fim_middle|> surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.width = ren.get_width()
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: <|fim_middle|> if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]()
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: <|fim_middle|> if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.option += 1
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: <|fim_middle|> if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.option -= 1
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: <|fim_middle|> if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.options[self.option][1]()
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: <|fim_middle|> if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.option = 0
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: <|fim_middle|> def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
self.option = len(self.options)-1
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def <|fim_middle|>(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
__init__
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def <|fim_middle|>(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
draw
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def <|fim_middle|>(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
update
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def <|fim_middle|>(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
set_pos
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def <|fim_middle|>(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
set_font
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def <|fim_middle|>(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
set_highlight_color
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def <|fim_middle|>(self, color): self.color = color def center_at(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
set_normal_color
<|file_name|>ezmenu.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # I found this file inside Super Mario Bros python # written by HJ https://sourceforge.net/projects/supermariobrosp/ # the complete work is licensed under GPL3 although I can not determine# license of this file # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html import pygame class EzMenu: def __init__(self, *options): self.options = options self.x = 0 self.y = 0 self.font = pygame.font.Font(None, 32) self.option = 0 self.width = 1 self.color = [0, 0, 0] self.hcolor = [255, 0, 0] self.height = len(self.options)*self.font.get_height() for o in self.options: text = o[0] ren = self.font.render(text, 2, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() def draw(self, surface): i=0 for o in self.options: if i==self.option: clr = self.hcolor else: clr = self.color text = o[0] ren = self.font.render(text, 2, clr) if ren.get_width() > self.width: self.width = ren.get_width() surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4))) i+=1 def update(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN: self.options[self.option][1]() if self.option > len(self.options)-1: self.option = 0 if self.option < 0: self.option = len(self.options)-1 def set_pos(self, x, y): self.x = x self.y = y def set_font(self, font): self.font = font def set_highlight_color(self, color): self.hcolor = color def set_normal_color(self, color): self.color = color def <|fim_middle|>(self, x, y): self.x = x-(self.width/2) self.y = y-(self.height/2) <|fim▁end|>
center_at
<|file_name|>test_models.py<|end_file_name|><|fim▁begin|># from test_plus.test import TestCase<|fim▁hole|># class TestUser(TestCase): # # def setUp(self): # self.user = self.make_user() # # def test__str__(self): # self.assertEqual( # self.user.__str__(), # 'testuser' # This is the default username for self.make_user() # ) # # def test_get_absolute_url(self): # self.assertEqual( # self.user.get_absolute_url(), # '/users/testuser/' # )<|fim▁end|>
# #
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * import versioneer __author__ = 'Chia-Jung, Yang'<|fim▁hole|>__version__ = versioneer.get_version() from ._version import get_versions __version__ = get_versions()['version'] del get_versions<|fim▁end|>
__email__ = '[email protected]'
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. currentmodule:: __init__.py .. moduleauthor:: Pat Daburu <[email protected]> <|fim▁hole|><|fim▁end|>
Provide a brief description of the module. """
<|file_name|>model_control_one_enabled_RelativeDifference_ConstantTrend_NoCycle_LSTM.py<|end_file_name|><|fim▁begin|>import tests.model_control.test_ozone_custom_models_enabled as testmod <|fim▁hole|>testmod.build_model( ['RelativeDifference'] , ['ConstantTrend'] , ['NoCycle'] , ['LSTM'] );<|fim▁end|>
<|file_name|>ex32.py<|end_file_name|><|fim▁begin|>the_count = [1, 2, 3, 4, 5] fruits = ['apple', 'oranges', 'pears', 'apricots',] change = [1, 'pennies', 2, 'dimes', 3, 'quarters',] #this first kind of for-loop goes through a list for number in the_count: print("This is count %d" % number) # same as above for fruit in fruits: print("A fruit of type: %s" % fruit) # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print("I got %r " % i)<|fim▁hole|>elements = [] # then use the range function to do 0 to 5 counts for i in range(0,6): print("Adding %d to the list." % i) # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print("Element was: %d" % i)<|fim▁end|>
# we can alse build lists, first start with an empty one
<|file_name|>std_pf_readonly.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals<|fim▁hole|>def execute(): """Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, }, { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'Administrator', 'permlevel': 1, 'read': 1, 'write': 1 }, ] for perms in new_perms: doc = webnotes.model.doc.Document('DocPerm') doc.fields.update(perms) doc.save() webnotes.conn.commit() webnotes.conn.begin() webnotes.reload_doc('core', 'doctype', 'print_format')<|fim▁end|>
<|file_name|>std_pf_readonly.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals def execute(): <|fim_middle|> <|fim▁end|>
"""Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, }, { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'Administrator', 'permlevel': 1, 'read': 1, 'write': 1 }, ] for perms in new_perms: doc = webnotes.model.doc.Document('DocPerm') doc.fields.update(perms) doc.save() webnotes.conn.commit() webnotes.conn.begin() webnotes.reload_doc('core', 'doctype', 'print_format')
<|file_name|>std_pf_readonly.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals def <|fim_middle|>(): """Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, }, { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'Administrator', 'permlevel': 1, 'read': 1, 'write': 1 }, ] for perms in new_perms: doc = webnotes.model.doc.Document('DocPerm') doc.fields.update(perms) doc.save() webnotes.conn.commit() webnotes.conn.begin() webnotes.reload_doc('core', 'doctype', 'print_format')<|fim▁end|>
execute
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else:<|fim▁hole|> coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id)<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: <|fim_middle|> async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
"""Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: <|fim_middle|> async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
"""Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: <|fim_middle|> <|fim▁end|>
"""Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: <|fim_middle|> # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: <|fim_middle|> else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: <|fim_middle|> if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
hass.data[DOMAIN][BTLE_LOCK] = Lock()
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: <|fim_middle|> switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options}
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: <|fim_middle|> await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
coordinator = hass.data[DOMAIN][DATA_COORDINATOR]
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: <|fim_middle|> entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
raise ConfigEntryNotReady
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: <|fim_middle|> return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: <|fim_middle|> return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
hass.data.pop(DOMAIN)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: <|fim_middle|> await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def <|fim_middle|>(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
async_setup_entry
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def <|fim_middle|>(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
async_unload_entry
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot devices.""" from asyncio import Lock import switchbot # pylint: disable=import-error from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SENSOR_TYPE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import ( ATTR_BOT, ATTR_CURTAIN, BTLE_LOCK, COMMON_OPTIONS, CONF_RETRY_COUNT, CONF_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT, CONF_TIME_BETWEEN_UPDATE_COMMAND, DATA_COORDINATOR, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT, DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, DOMAIN, ) from .coordinator import SwitchbotDataUpdateCoordinator PLATFORMS_BY_TYPE = { ATTR_BOT: [Platform.SWITCH, Platform.SENSOR], ATTR_CURTAIN: [Platform.COVER, Platform.BINARY_SENSOR, Platform.SENSOR], } async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Switchbot from a config entry.""" hass.data.setdefault(DOMAIN, {}) if not entry.options: options = { CONF_TIME_BETWEEN_UPDATE_COMMAND: DEFAULT_TIME_BETWEEN_UPDATE_COMMAND, CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT, CONF_RETRY_TIMEOUT: DEFAULT_RETRY_TIMEOUT, CONF_SCAN_TIMEOUT: DEFAULT_SCAN_TIMEOUT, } hass.config_entries.async_update_entry(entry, options=options) # Use same coordinator instance for all entities. # Uses BTLE advertisement data, all Switchbot devices in range is stored here. if DATA_COORDINATOR not in hass.data[DOMAIN]: # Check if asyncio.lock is stored in hass data. # BTLE has issues with multiple connections, # so we use a lock to ensure that only one API request is reaching it at a time: if BTLE_LOCK not in hass.data[DOMAIN]: hass.data[DOMAIN][BTLE_LOCK] = Lock() if COMMON_OPTIONS not in hass.data[DOMAIN]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} switchbot.DEFAULT_RETRY_TIMEOUT = hass.data[DOMAIN][COMMON_OPTIONS][ CONF_RETRY_TIMEOUT ] # Store api in coordinator. coordinator = SwitchbotDataUpdateCoordinator( hass, update_interval=hass.data[DOMAIN][COMMON_OPTIONS][ CONF_TIME_BETWEEN_UPDATE_COMMAND ], api=switchbot, retry_count=hass.data[DOMAIN][COMMON_OPTIONS][CONF_RETRY_COUNT], scan_timeout=hass.data[DOMAIN][COMMON_OPTIONS][CONF_SCAN_TIMEOUT], api_lock=hass.data[DOMAIN][BTLE_LOCK], ) hass.data[DOMAIN][DATA_COORDINATOR] = coordinator else: coordinator = hass.data[DOMAIN][DATA_COORDINATOR] await coordinator.async_config_entry_first_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady entry.async_on_unload(entry.add_update_listener(_async_update_listener)) hass.data[DOMAIN][entry.entry_id] = {DATA_COORDINATOR: coordinator} sensor_type = entry.data[CONF_SENSOR_TYPE] hass.config_entries.async_setup_platforms(entry, PLATFORMS_BY_TYPE[sensor_type]) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" sensor_type = entry.data[CONF_SENSOR_TYPE] unload_ok = await hass.config_entries.async_unload_platforms( entry, PLATFORMS_BY_TYPE[sensor_type] ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) if len(hass.config_entries.async_entries(DOMAIN)) == 0: hass.data.pop(DOMAIN) return unload_ok async def <|fim_middle|>(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle options update.""" # Update entity options stored in hass. if {**entry.options} != hass.data[DOMAIN][COMMON_OPTIONS]: hass.data[DOMAIN][COMMON_OPTIONS] = {**entry.options} hass.data[DOMAIN].pop(DATA_COORDINATOR) await hass.config_entries.async_reload(entry.entry_id) <|fim▁end|>
_async_update_listener
<|file_name|>fasta.py<|end_file_name|><|fim▁begin|>from Bio import SeqIO def get_proteins_for_db(fastafn, fastadelim, genefield): """Runs through fasta file and returns proteins accession nrs, sequences and evidence levels for storage in lookup DB. Duplicate accessions in fasta are accepted and removed by keeping only the last one. """ records = {acc: (rec, get_record_type(rec)) for acc, rec in SeqIO.index(fastafn, 'fasta').items()} proteins = ((x,) for x in records.keys()) sequences = ((acc, str(rec.seq)) for acc, (rec, rtype) in records.items()) desc = ((acc, get_description(rec, rtype)) for acc, (rec, rtype) in records.items() if rtype) evid = ((acc, get_uniprot_evidence_level(rec, rtype)) for acc, (rec, rtype) in records.items()) ensgs = [(get_ensg(rec), acc) for acc, (rec, rtype) in records.items() if rtype == 'ensembl'] def sym_out(): symbols = ((get_symbol(rec, rtype, fastadelim, genefield), acc) for acc, (rec, rtype) in records.items() if rtype) othergene = ((get_other_gene(rec, fastadelim, genefield), acc) for acc, (rec, rtype) in records.items() if not rtype and fastadelim and fastadelim in rec.description) yield from symbols yield from othergene return proteins, sequences, desc, evid, ensgs, [x for x in sym_out()] def parse_fasta(fn): with open(fn) as fp: for record in SeqIO.parse(fp, 'fasta'): yield record def get_record_type(record): dmod = get_decoy_mod_string(record.id) test_name = record.id if dmod is not None: test_name = record.id.replace(dmod, '') if test_name.split('|')[0] in ['sp', 'tr']: return 'swiss' elif test_name[:3] == 'ENS': return 'ensembl' else: return False def get_decoy_mod_string(protein): mods = ['tryp_reverse', 'reverse', 'decoy', 'random', 'shuffle'] for mod in mods: if mod in protein: if protein.endswith('_{}'.format(mod)):<|fim▁hole|> elif protein.endswith('{}'.format(mod)): return mod elif protein.startswith('{}_'.format(mod)): return '{}_'.format(mod) elif protein.startswith('{}'.format(mod)): return mod def get_description(record, rectype): if rectype == 'ensembl': desc_spl = [x.split(':') for x in record.description.split()] try: descix = [ix for ix, x in enumerate(desc_spl) if x[0] == 'description'][0] except IndexError: return 'NA' desc = ' '.join([':'.join(x) for x in desc_spl[descix:]])[12:] return desc elif rectype == 'swiss': desc = [] for part in record.description.split()[1:]: if len(part.split('=')) > 1: break desc.append(part) return ' '.join(desc) def get_other_gene(record, fastadelim, genefield): return record.description.split(fastadelim)[genefield] def get_genes_pickfdr(fastafn, outputtype, fastadelim, genefield): """Called by protein FDR module for both ENSG and e.g. Uniprot""" for rec in parse_fasta(fastafn): rtype = get_record_type(rec) if rtype == 'ensembl' and outputtype == 'ensg': yield get_ensg(rec) elif outputtype == 'genename': yield get_symbol(rec, rtype, fastadelim, genefield) def get_ensg(record): fields = [x.split(':') for x in record.description.split()] try: return [x[1] for x in fields if x[0] == 'gene' and len(x) == 2][0] except IndexError: raise RuntimeError('ENSEMBL detected but cannot find gene ENSG in fasta') def get_symbol(record, rectype, fastadelim, genefield): if rectype == 'ensembl': fields = [x.split(':') for x in record.description.split()] sym = [x[1] for x in fields if x[0] == 'gene_symbol' and len(x) == 2] elif rectype == 'swiss': fields = [x.split('=') for x in record.description.split()] sym = [x[1] for x in fields if x[0] == 'GN' and len(x) == 2] elif fastadelim and fastadelim in record.description and genefield: return record.description.split(fastadelim)[genefield] else: return 'NA' try: return sym[0] except IndexError: return 'NA' def get_uniprot_evidence_level(record, rtype): """Returns uniprot protein existence evidence level for a fasta header. Evidence levels are 1-5, but we return 5 - x since sorting still demands that higher is better.""" if rtype != 'swiss': return -1 for item in record.description.split(): item = item.split('=') try: if item[0] == 'PE' and len(item) == 2: return 5 - int(item[1]) except IndexError: continue return -1<|fim▁end|>
return '_{}'.format(mod)
<|file_name|>fasta.py<|end_file_name|><|fim▁begin|>from Bio import SeqIO def get_proteins_for_db(fastafn, fastadelim, genefield): <|fim_middle|> def parse_fasta(fn): with open(fn) as fp: for record in SeqIO.parse(fp, 'fasta'): yield record def get_record_type(record): dmod = get_decoy_mod_string(record.id) test_name = record.id if dmod is not None: test_name = record.id.replace(dmod, '') if test_name.split('|')[0] in ['sp', 'tr']: return 'swiss' elif test_name[:3] == 'ENS': return 'ensembl' else: return False def get_decoy_mod_string(protein): mods = ['tryp_reverse', 'reverse', 'decoy', 'random', 'shuffle'] for mod in mods: if mod in protein: if protein.endswith('_{}'.format(mod)): return '_{}'.format(mod) elif protein.endswith('{}'.format(mod)): return mod elif protein.startswith('{}_'.format(mod)): return '{}_'.format(mod) elif protein.startswith('{}'.format(mod)): return mod def get_description(record, rectype): if rectype == 'ensembl': desc_spl = [x.split(':') for x in record.description.split()] try: descix = [ix for ix, x in enumerate(desc_spl) if x[0] == 'description'][0] except IndexError: return 'NA' desc = ' '.join([':'.join(x) for x in desc_spl[descix:]])[12:] return desc elif rectype == 'swiss': desc = [] for part in record.description.split()[1:]: if len(part.split('=')) > 1: break desc.append(part) return ' '.join(desc) def get_other_gene(record, fastadelim, genefield): return record.description.split(fastadelim)[genefield] def get_genes_pickfdr(fastafn, outputtype, fastadelim, genefield): """Called by protein FDR module for both ENSG and e.g. Uniprot""" for rec in parse_fasta(fastafn): rtype = get_record_type(rec) if rtype == 'ensembl' and outputtype == 'ensg': yield get_ensg(rec) elif outputtype == 'genename': yield get_symbol(rec, rtype, fastadelim, genefield) def get_ensg(record): fields = [x.split(':') for x in record.description.split()] try: return [x[1] for x in fields if x[0] == 'gene' and len(x) == 2][0] except IndexError: raise RuntimeError('ENSEMBL detected but cannot find gene ENSG in fasta') def get_symbol(record, rectype, fastadelim, genefield): if rectype == 'ensembl': fields = [x.split(':') for x in record.description.split()] sym = [x[1] for x in fields if x[0] == 'gene_symbol' and len(x) == 2] elif rectype == 'swiss': fields = [x.split('=') for x in record.description.split()] sym = [x[1] for x in fields if x[0] == 'GN' and len(x) == 2] elif fastadelim and fastadelim in record.description and genefield: return record.description.split(fastadelim)[genefield] else: return 'NA' try: return sym[0] except IndexError: return 'NA' def get_uniprot_evidence_level(record, rtype): """Returns uniprot protein existence evidence level for a fasta header. Evidence levels are 1-5, but we return 5 - x since sorting still demands that higher is better.""" if rtype != 'swiss': return -1 for item in record.description.split(): item = item.split('=') try: if item[0] == 'PE' and len(item) == 2: return 5 - int(item[1]) except IndexError: continue return -1 <|fim▁end|>
"""Runs through fasta file and returns proteins accession nrs, sequences and evidence levels for storage in lookup DB. Duplicate accessions in fasta are accepted and removed by keeping only the last one. """ records = {acc: (rec, get_record_type(rec)) for acc, rec in SeqIO.index(fastafn, 'fasta').items()} proteins = ((x,) for x in records.keys()) sequences = ((acc, str(rec.seq)) for acc, (rec, rtype) in records.items()) desc = ((acc, get_description(rec, rtype)) for acc, (rec, rtype) in records.items() if rtype) evid = ((acc, get_uniprot_evidence_level(rec, rtype)) for acc, (rec, rtype) in records.items()) ensgs = [(get_ensg(rec), acc) for acc, (rec, rtype) in records.items() if rtype == 'ensembl'] def sym_out(): symbols = ((get_symbol(rec, rtype, fastadelim, genefield), acc) for acc, (rec, rtype) in records.items() if rtype) othergene = ((get_other_gene(rec, fastadelim, genefield), acc) for acc, (rec, rtype) in records.items() if not rtype and fastadelim and fastadelim in rec.description) yield from symbols yield from othergene return proteins, sequences, desc, evid, ensgs, [x for x in sym_out()]
<|file_name|>fasta.py<|end_file_name|><|fim▁begin|>from Bio import SeqIO def get_proteins_for_db(fastafn, fastadelim, genefield): """Runs through fasta file and returns proteins accession nrs, sequences and evidence levels for storage in lookup DB. Duplicate accessions in fasta are accepted and removed by keeping only the last one. """ records = {acc: (rec, get_record_type(rec)) for acc, rec in SeqIO.index(fastafn, 'fasta').items()} proteins = ((x,) for x in records.keys()) sequences = ((acc, str(rec.seq)) for acc, (rec, rtype) in records.items()) desc = ((acc, get_description(rec, rtype)) for acc, (rec, rtype) in records.items() if rtype) evid = ((acc, get_uniprot_evidence_level(rec, rtype)) for acc, (rec, rtype) in records.items()) ensgs = [(get_ensg(rec), acc) for acc, (rec, rtype) in records.items() if rtype == 'ensembl'] def sym_out(): <|fim_middle|> return proteins, sequences, desc, evid, ensgs, [x for x in sym_out()] def parse_fasta(fn): with open(fn) as fp: for record in SeqIO.parse(fp, 'fasta'): yield record def get_record_type(record): dmod = get_decoy_mod_string(record.id) test_name = record.id if dmod is not None: test_name = record.id.replace(dmod, '') if test_name.split('|')[0] in ['sp', 'tr']: return 'swiss' elif test_name[:3] == 'ENS': return 'ensembl' else: return False def get_decoy_mod_string(protein): mods = ['tryp_reverse', 'reverse', 'decoy', 'random', 'shuffle'] for mod in mods: if mod in protein: if protein.endswith('_{}'.format(mod)): return '_{}'.format(mod) elif protein.endswith('{}'.format(mod)): return mod elif protein.startswith('{}_'.format(mod)): return '{}_'.format(mod) elif protein.startswith('{}'.format(mod)): return mod def get_description(record, rectype): if rectype == 'ensembl': desc_spl = [x.split(':') for x in record.description.split()] try: descix = [ix for ix, x in enumerate(desc_spl) if x[0] == 'description'][0] except IndexError: return 'NA' desc = ' '.join([':'.join(x) for x in desc_spl[descix:]])[12:] return desc elif rectype == 'swiss': desc = [] for part in record.description.split()[1:]: if len(part.split('=')) > 1: break desc.append(part) return ' '.join(desc) def get_other_gene(record, fastadelim, genefield): return record.description.split(fastadelim)[genefield] def get_genes_pickfdr(fastafn, outputtype, fastadelim, genefield): """Called by protein FDR module for both ENSG and e.g. Uniprot""" for rec in parse_fasta(fastafn): rtype = get_record_type(rec) if rtype == 'ensembl' and outputtype == 'ensg': yield get_ensg(rec) elif outputtype == 'genename': yield get_symbol(rec, rtype, fastadelim, genefield) def get_ensg(record): fields = [x.split(':') for x in record.description.split()] try: return [x[1] for x in fields if x[0] == 'gene' and len(x) == 2][0] except IndexError: raise RuntimeError('ENSEMBL detected but cannot find gene ENSG in fasta') def get_symbol(record, rectype, fastadelim, genefield): if rectype == 'ensembl': fields = [x.split(':') for x in record.description.split()] sym = [x[1] for x in fields if x[0] == 'gene_symbol' and len(x) == 2] elif rectype == 'swiss': fields = [x.split('=') for x in record.description.split()] sym = [x[1] for x in fields if x[0] == 'GN' and len(x) == 2] elif fastadelim and fastadelim in record.description and genefield: return record.description.split(fastadelim)[genefield] else: return 'NA' try: return sym[0] except IndexError: return 'NA' def get_uniprot_evidence_level(record, rtype): """Returns uniprot protein existence evidence level for a fasta header. Evidence levels are 1-5, but we return 5 - x since sorting still demands that higher is better.""" if rtype != 'swiss': return -1 for item in record.description.split(): item = item.split('=') try: if item[0] == 'PE' and len(item) == 2: return 5 - int(item[1]) except IndexError: continue return -1 <|fim▁end|>
symbols = ((get_symbol(rec, rtype, fastadelim, genefield), acc) for acc, (rec, rtype) in records.items() if rtype) othergene = ((get_other_gene(rec, fastadelim, genefield), acc) for acc, (rec, rtype) in records.items() if not rtype and fastadelim and fastadelim in rec.description) yield from symbols yield from othergene