prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): <|fim_middle|> def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
"""Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values)
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): <|fim_middle|> def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
return [my_attribute_label(self.distance_to_arterial)]
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): <|fim_middle|> def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant'))
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): <|fim_middle|> def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
self.do_check("x == False or x == True", values)
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): <|fim_middle|> from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"])
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): <|fim_middle|> if __name__=='__main__': opus_unittest.main()<|fim▁end|>
def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be)
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. <|fim_middle|> if __name__=='__main__': opus_unittest.main()<|fim▁end|>
tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be)
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': <|fim_middle|> <|fim▁end|>
opus_unittest.main()
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def <|fim_middle|>(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
dependencies
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def <|fim_middle|>(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
compute
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def <|fim_middle|>(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
post_check
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def <|fim_middle|>(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
get_is_near_arterial
<|file_name|>is_near_arterial.py<|end_file_name|><|fim▁begin|> # Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def <|fim_middle|>( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()<|fim▁end|>
test_my_inputs
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read()<|fim▁hole|> return n<|fim▁end|>
if label: n = {'{}'.format(label):s} else: n = {'source code':s}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): <|fim_middle|> def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
return "test helper text"
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): <|fim_middle|> def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
""" Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): <|fim_middle|> def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
""" Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): <|fim_middle|> def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
""" Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): <|fim_middle|> def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
""" Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): <|fim_middle|> def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
""" Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): <|fim_middle|> <|fim▁end|>
""" Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: <|fim_middle|> version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
return {}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: <|fim_middle|> else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
k = '{}'.format(label)
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: <|fim_middle|> return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
k = '{} version'.format(module)
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): <|fim_middle|> else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
print('ERROR: {} NOT FOUND.'.format(filename)) return {}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: <|fim_middle|> def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: <|fim_middle|> else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
d = {'{}'.format(label): contents}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: <|fim_middle|> return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
d = {filename: contents}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: <|fim_middle|> if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: <|fim_middle|> else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
repo = svn.local.LocalClient(svndir)
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: <|fim_middle|> try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
repo = svn.local.LocalClient(os.getcwd())
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: <|fim_middle|> else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
k = '{}'.format(label)
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: <|fim_middle|> return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
k = 'SVN INFO'
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: <|fim_middle|> try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
thisdir = os.getcwd() os.chdir(gitpath)
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: <|fim_middle|> else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
l = '{}'.format(label)
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: <|fim_middle|> return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
l = 'GIT HASH'
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: <|fim_middle|> if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
os.chdir(sourcepath)
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): <|fim_middle|> else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
print('ERROR: {} NOT FOUND.'.format(scode)) return {}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: <|fim_middle|> return n <|fim▁end|>
with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: <|fim_middle|> else: n = {'source code':s} return n <|fim▁end|>
n = {'{}'.format(label):s}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: <|fim_middle|> return n <|fim▁end|>
n = {'source code':s}
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def <|fim_middle|>(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
test_helper
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def <|fim_middle|>(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
dict_to_str
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def <|fim_middle|>(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
module_version
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def <|fim_middle|>(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
file_contents
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def <|fim_middle|>(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
svn_information
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def <|fim_middle|>(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
get_git_hash
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def <|fim_middle|>(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n <|fim▁end|>
get_source_code
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations <|fim▁hole|> from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], }<|fim▁end|>
import logging from typing import Any
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: <|fim_middle|> async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
"""Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) )
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: <|fim_middle|> class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
"""Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] )
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): <|fim_middle|> <|fim▁end|>
"""Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], }
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: <|fim_middle|> async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
"""Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: <|fim_middle|> async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
"""Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"]
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: <|fim_middle|> async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
"""Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) )
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: <|fim_middle|> @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
"""Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) )
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: <|fim_middle|> @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
"""Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: <|fim_middle|> @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
"""Return true if device is on.""" return self.data["data"]["isOn"]
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: <|fim_middle|> <|fim▁end|>
"""Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], }
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): <|fim_middle|> hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
return
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: <|fim_middle|> self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
return
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: <|fim_middle|> return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
return True
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def <|fim_middle|>( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
async_setup_platform
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def <|fim_middle|>( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
async_setup_entry
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def <|fim_middle|>( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
__init__
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def <|fim_middle|>(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
async_added_to_hass
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def <|fim_middle|>(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
async_turn_on
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def <|fim_middle|>(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
async_turn_off
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def <|fim_middle|>(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
assumed_state
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def <|fim_middle|>(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def extra_state_attributes(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
is_on
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Switchbot bot.""" from __future__ import annotations import logging from typing import Any from switchbot import Switchbot # pylint: disable=import-error import voluptuous as vol from homeassistant.components.switch import ( DEVICE_CLASS_SWITCH, PLATFORM_SCHEMA, SwitchEntity, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ( CONF_MAC, CONF_NAME, CONF_PASSWORD, CONF_SENSOR_TYPE, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .const import ATTR_BOT, CONF_RETRY_COUNT, DATA_COORDINATOR, DEFAULT_NAME, DOMAIN from .coordinator import SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity # Initialize the logger _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: entity_platform.AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Import yaml config and initiates config flow for Switchbot devices.""" # Check if entry config exists and skips import if it does. if hass.config_entries.async_entries(DOMAIN): return hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_NAME: config[CONF_NAME], CONF_PASSWORD: config.get(CONF_PASSWORD, None), CONF_MAC: config[CONF_MAC].replace("-", ":").lower(), CONF_SENSOR_TYPE: ATTR_BOT, }, ) ) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: entity_platform.AddEntitiesCallback, ) -> None: """Set up Switchbot based on a config entry.""" coordinator: SwitchbotDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][ DATA_COORDINATOR ] async_add_entities( [ SwitchBotBotEntity( coordinator, entry.unique_id, entry.data[CONF_MAC], entry.data[CONF_NAME], coordinator.switchbot_api.Switchbot( mac=entry.data[CONF_MAC], password=entry.data.get(CONF_PASSWORD), retry_count=entry.options[CONF_RETRY_COUNT], ), ) ] ) class SwitchBotBotEntity(SwitchbotEntity, SwitchEntity, RestoreEntity): """Representation of a Switchbot.""" coordinator: SwitchbotDataUpdateCoordinator _attr_device_class = DEVICE_CLASS_SWITCH def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, idx: str | None, mac: str, name: str, device: Switchbot, ) -> None: """Initialize the Switchbot.""" super().__init__(coordinator, idx, mac, name) self._attr_unique_id = idx self._device = device async def async_added_to_hass(self) -> None: """Run when entity about to be added.""" await super().async_added_to_hass() last_state = await self.async_get_last_state() if not last_state: return self._attr_is_on = last_state.state == STATE_ON self._last_run_success = last_state.attributes["last_run_success"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" _LOGGER.info("Turn Switchbot bot on %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_on) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" _LOGGER.info("Turn Switchbot bot off %s", self._mac) async with self.coordinator.api_lock: self._last_run_success = bool( await self.hass.async_add_executor_job(self._device.turn_off) ) @property def assumed_state(self) -> bool: """Return true if unable to access real state of entity.""" if not self.data["data"]["switchMode"]: return True return False @property def is_on(self) -> bool: """Return true if device is on.""" return self.data["data"]["isOn"] @property def <|fim_middle|>(self) -> dict: """Return the state attributes.""" return { **super().extra_state_attributes, "switch_mode": self.data["data"]["switchMode"], } <|fim▁end|>
extra_state_attributes
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } }<|fim▁hole|> def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address<|fim▁end|>
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): <|fim_middle|> def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address)
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): <|fim_middle|> <|fim▁end|>
resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): <|fim_middle|> address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
scheme = 'https'
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): <|fim_middle|> return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
address = "[{}]".format(address)
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): <|fim_middle|> else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly <|fim_middle|> else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
resolved_address = config('vip')
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: <|fim_middle|> else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): <|fim_middle|> else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
resolved_address = vip
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: <|fim_middle|> if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr)
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): <|fim_middle|> else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
fallback_addr = get_ipv6_addr()
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: <|fim_middle|> resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
fallback_addr = unit_get(_address_map[endpoint_type]['fallback'])
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: <|fim_middle|> else: return resolved_address <|fim▁end|>
raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration')
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: <|fim_middle|> <|fim▁end|>
return resolved_address
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def <|fim_middle|>(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def resolve_address(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
canonical_url
<|file_name|>ip.py<|end_file_name|><|fim▁begin|>from charmhelpers.core.hookenv import ( config, unit_get, ) from charmhelpers.contrib.network.ip import ( get_address_in_network, is_address_in_network, is_ipv6, get_ipv6_addr, ) from charmhelpers.contrib.hahelpers.cluster import is_clustered PUBLIC = 'public' INTERNAL = 'int' ADMIN = 'admin' _address_map = { PUBLIC: { 'config': 'os-public-network', 'fallback': 'public-address' }, INTERNAL: { 'config': 'os-internal-network', 'fallback': 'private-address' }, ADMIN: { 'config': 'os-admin-network', 'fallback': 'private-address' } } def canonical_url(configs, endpoint_type=PUBLIC): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :configs OSTemplateRenderer: A config tempating object to inspect for a complete https context. :endpoint_type str: The endpoint type to resolve. :returns str: Base URL for services on the current service unit. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' address = resolve_address(endpoint_type) if is_ipv6(address): address = "[{}]".format(address) return '%s://%s' % (scheme, address) def <|fim_middle|>(endpoint_type=PUBLIC): resolved_address = None if is_clustered(): if config(_address_map[endpoint_type]['config']) is None: # Assume vip is simple and pass back directly resolved_address = config('vip') else: for vip in config('vip').split(): if is_address_in_network( config(_address_map[endpoint_type]['config']), vip): resolved_address = vip else: if config('prefer-ipv6'): fallback_addr = get_ipv6_addr() else: fallback_addr = unit_get(_address_map[endpoint_type]['fallback']) resolved_address = get_address_in_network( config(_address_map[endpoint_type]['config']), fallback_addr) if resolved_address is None: raise ValueError('Unable to resolve a suitable IP address' ' based on charm state and configuration') else: return resolved_address <|fim▁end|>
resolve_address
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """<|fim▁hole|><|fim▁end|>
return self.tau / (4.0 * np.pi)
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): <|fim_middle|> <|fim▁end|>
""" Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): <|fim_middle|> @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)<|fim▁end|>
""" Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): <|fim_middle|> @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)<|fim▁end|>
""" Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): <|fim_middle|> @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)<|fim▁end|>
""" Transmission coefficient. """ return np.zeros(self.frequency.amount)
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): <|fim_middle|> <|fim▁end|>
""" Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def <|fim_middle|>(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)<|fim▁end|>
impedance_from
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def <|fim_middle|>(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)<|fim▁end|>
impedance_to
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def <|fim_middle|>(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)<|fim▁end|>
tau
<|file_name|>Coupling2DCavities2D.py<|end_file_name|><|fim▁begin|>import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def <|fim_middle|>(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)<|fim▁end|>
clf
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url from . import views from django.views.decorators.cache import cache_page <|fim▁hole|>urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^logout/$', views.logout_view, name='logout'), ]<|fim▁end|>
app_name = 'webinter'
<|file_name|>feed_parse_extractLittlebambooHomeBlog.py<|end_file_name|><|fim▁begin|>def extractLittlebambooHomeBlog(item):<|fim▁hole|> ''' Parser for 'littlebamboo.home.blog' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('FW', 'Fortunate Wife', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False<|fim▁end|>
<|file_name|>feed_parse_extractLittlebambooHomeBlog.py<|end_file_name|><|fim▁begin|>def extractLittlebambooHomeBlog(item): <|fim_middle|> <|fim▁end|>
''' Parser for 'littlebamboo.home.blog' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('FW', 'Fortunate Wife', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False