Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
SyncMediaPlayer.supported_features
(self)
Flag media player features that are supported.
Flag media player features that are supported.
def supported_features(self): """Flag media player features that are supported.""" return ( mp.const.SUPPORT_VOLUME_SET | mp.const.SUPPORT_VOLUME_STEP | mp.const.SUPPORT_PLAY | mp.const.SUPPORT_PAUSE | mp.const.SUPPORT_TURN_OFF | mp.const.SUPPORT_TURN_ON )
[ "def", "supported_features", "(", "self", ")", ":", "return", "(", "mp", ".", "const", ".", "SUPPORT_VOLUME_SET", "|", "mp", ".", "const", ".", "SUPPORT_VOLUME_STEP", "|", "mp", ".", "const", ".", "SUPPORT_PLAY", "|", "mp", ".", "const", ".", "SUPPORT_PAUSE", "|", "mp", ".", "const", ".", "SUPPORT_TURN_OFF", "|", "mp", ".", "const", ".", "SUPPORT_TURN_ON", ")" ]
[ 87, 4 ]
[ 96, 9 ]
python
en
['en', 'en', 'en']
True
SyncMediaPlayer.set_volume_level
(self, volume)
Set volume level, range 0..1.
Set volume level, range 0..1.
def set_volume_level(self, volume): """Set volume level, range 0..1.""" self._volume = volume
[ "def", "set_volume_level", "(", "self", ",", "volume", ")", ":", "self", ".", "_volume", "=", "volume" ]
[ 98, 4 ]
[ 100, 29 ]
python
en
['fr', 'zu', 'en']
False
SyncMediaPlayer.volume_up
(self)
Turn volume up for media player.
Turn volume up for media player.
def volume_up(self): """Turn volume up for media player.""" if self.volume_level < 1: self.set_volume_level(min(1, self.volume_level + 0.2))
[ "def", "volume_up", "(", "self", ")", ":", "if", "self", ".", "volume_level", "<", "1", ":", "self", ".", "set_volume_level", "(", "min", "(", "1", ",", "self", ".", "volume_level", "+", "0.2", ")", ")" ]
[ 102, 4 ]
[ 105, 66 ]
python
en
['en', 'no', 'en']
True
SyncMediaPlayer.volume_down
(self)
Turn volume down for media player.
Turn volume down for media player.
def volume_down(self): """Turn volume down for media player.""" if self.volume_level > 0: self.set_volume_level(max(0, self.volume_level - 0.2))
[ "def", "volume_down", "(", "self", ")", ":", "if", "self", ".", "volume_level", ">", "0", ":", "self", ".", "set_volume_level", "(", "max", "(", "0", ",", "self", ".", "volume_level", "-", "0.2", ")", ")" ]
[ 107, 4 ]
[ 110, 66 ]
python
en
['en', 'en', 'en']
True
SyncMediaPlayer.media_play_pause
(self)
Play or pause the media player.
Play or pause the media player.
def media_play_pause(self): """Play or pause the media player.""" if self._state == STATE_PLAYING: self._state = STATE_PAUSED else: self._state = STATE_PLAYING
[ "def", "media_play_pause", "(", "self", ")", ":", "if", "self", ".", "_state", "==", "STATE_PLAYING", ":", "self", ".", "_state", "=", "STATE_PAUSED", "else", ":", "self", ".", "_state", "=", "STATE_PLAYING" ]
[ 112, 4 ]
[ 117, 39 ]
python
en
['en', 'en', 'en']
True
SyncMediaPlayer.toggle
(self)
Toggle the power on the media player.
Toggle the power on the media player.
def toggle(self): """Toggle the power on the media player.""" if self._state in [STATE_OFF, STATE_IDLE]: self._state = STATE_ON else: self._state = STATE_OFF
[ "def", "toggle", "(", "self", ")", ":", "if", "self", ".", "_state", "in", "[", "STATE_OFF", ",", "STATE_IDLE", "]", ":", "self", ".", "_state", "=", "STATE_ON", "else", ":", "self", ".", "_state", "=", "STATE_OFF" ]
[ 119, 4 ]
[ 124, 35 ]
python
en
['en', 'en', 'en']
True
SyncMediaPlayer.async_media_play_pause
(self)
Create a coroutine to wrap the future returned by ABC. This allows the run_coroutine_threadsafe helper to be used.
Create a coroutine to wrap the future returned by ABC.
async def async_media_play_pause(self): """Create a coroutine to wrap the future returned by ABC. This allows the run_coroutine_threadsafe helper to be used. """ await super().async_media_play_pause()
[ "async", "def", "async_media_play_pause", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_media_play_pause", "(", ")" ]
[ 126, 4 ]
[ 131, 46 ]
python
en
['en', 'en', 'en']
True
SyncMediaPlayer.async_toggle
(self)
Create a coroutine to wrap the future returned by ABC. This allows the run_coroutine_threadsafe helper to be used.
Create a coroutine to wrap the future returned by ABC.
async def async_toggle(self): """Create a coroutine to wrap the future returned by ABC. This allows the run_coroutine_threadsafe helper to be used. """ await super().async_toggle()
[ "async", "def", "async_toggle", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_toggle", "(", ")" ]
[ 133, 4 ]
[ 138, 36 ]
python
en
['en', 'en', 'en']
True
TestAsyncMediaPlayer.setUp
(self)
Set up things to be run when tests are started.
Set up things to be run when tests are started.
def setUp(self): # pylint: disable=invalid-name """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.player = AsyncMediaPlayer(self.hass) self.addCleanup(self.tear_down_cleanup)
[ "def", "setUp", "(", "self", ")", ":", "# pylint: disable=invalid-name", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")", "self", ".", "player", "=", "AsyncMediaPlayer", "(", "self", ".", "hass", ")", "self", ".", "addCleanup", "(", "self", ".", "tear_down_cleanup", ")" ]
[ 144, 4 ]
[ 148, 47 ]
python
en
['en', 'en', 'en']
True
TestAsyncMediaPlayer.tear_down_cleanup
(self)
Shut down test instance.
Shut down test instance.
def tear_down_cleanup(self): """Shut down test instance.""" self.hass.stop()
[ "def", "tear_down_cleanup", "(", "self", ")", ":", "self", ".", "hass", ".", "stop", "(", ")" ]
[ 150, 4 ]
[ 152, 24 ]
python
en
['en', 'de', 'en']
True
TestAsyncMediaPlayer.test_volume_up
(self)
Test the volume_up helper function.
Test the volume_up helper function.
def test_volume_up(self): """Test the volume_up helper function.""" assert self.player.volume_level == 0 asyncio.run_coroutine_threadsafe( self.player.async_set_volume_level(0.5), self.hass.loop ).result() assert self.player.volume_level == 0.5 asyncio.run_coroutine_threadsafe( self.player.async_volume_up(), self.hass.loop ).result() assert self.player.volume_level == 0.6
[ "def", "test_volume_up", "(", "self", ")", ":", "assert", "self", ".", "player", ".", "volume_level", "==", "0", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_set_volume_level", "(", "0.5", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "volume_level", "==", "0.5", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_volume_up", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "volume_level", "==", "0.6" ]
[ 154, 4 ]
[ 164, 46 ]
python
en
['en', 'en', 'en']
True
TestAsyncMediaPlayer.test_volume_down
(self)
Test the volume_down helper function.
Test the volume_down helper function.
def test_volume_down(self): """Test the volume_down helper function.""" assert self.player.volume_level == 0 asyncio.run_coroutine_threadsafe( self.player.async_set_volume_level(0.5), self.hass.loop ).result() assert self.player.volume_level == 0.5 asyncio.run_coroutine_threadsafe( self.player.async_volume_down(), self.hass.loop ).result() assert self.player.volume_level == 0.4
[ "def", "test_volume_down", "(", "self", ")", ":", "assert", "self", ".", "player", ".", "volume_level", "==", "0", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_set_volume_level", "(", "0.5", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "volume_level", "==", "0.5", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_volume_down", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "volume_level", "==", "0.4" ]
[ 166, 4 ]
[ 176, 46 ]
python
en
['en', 'en', 'en']
True
TestAsyncMediaPlayer.test_media_play_pause
(self)
Test the media_play_pause helper function.
Test the media_play_pause helper function.
def test_media_play_pause(self): """Test the media_play_pause helper function.""" assert self.player.state == STATE_OFF asyncio.run_coroutine_threadsafe( self.player.async_media_play_pause(), self.hass.loop ).result() assert self.player.state == STATE_PLAYING asyncio.run_coroutine_threadsafe( self.player.async_media_play_pause(), self.hass.loop ).result() assert self.player.state == STATE_PAUSED
[ "def", "test_media_play_pause", "(", "self", ")", ":", "assert", "self", ".", "player", ".", "state", "==", "STATE_OFF", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_media_play_pause", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "state", "==", "STATE_PLAYING", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_media_play_pause", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "state", "==", "STATE_PAUSED" ]
[ 178, 4 ]
[ 188, 48 ]
python
en
['en', 'en', 'en']
True
TestAsyncMediaPlayer.test_toggle
(self)
Test the toggle helper function.
Test the toggle helper function.
def test_toggle(self): """Test the toggle helper function.""" assert self.player.state == STATE_OFF asyncio.run_coroutine_threadsafe( self.player.async_toggle(), self.hass.loop ).result() assert self.player.state == STATE_ON asyncio.run_coroutine_threadsafe( self.player.async_toggle(), self.hass.loop ).result() assert self.player.state == STATE_OFF
[ "def", "test_toggle", "(", "self", ")", ":", "assert", "self", ".", "player", ".", "state", "==", "STATE_OFF", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_toggle", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "state", "==", "STATE_ON", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_toggle", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "state", "==", "STATE_OFF" ]
[ 190, 4 ]
[ 200, 45 ]
python
en
['en', 'en', 'en']
True
TestSyncMediaPlayer.setUp
(self)
Set up things to be run when tests are started.
Set up things to be run when tests are started.
def setUp(self): # pylint: disable=invalid-name """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.player = SyncMediaPlayer(self.hass) self.addCleanup(self.tear_down_cleanup)
[ "def", "setUp", "(", "self", ")", ":", "# pylint: disable=invalid-name", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")", "self", ".", "player", "=", "SyncMediaPlayer", "(", "self", ".", "hass", ")", "self", ".", "addCleanup", "(", "self", ".", "tear_down_cleanup", ")" ]
[ 206, 4 ]
[ 210, 47 ]
python
en
['en', 'en', 'en']
True
TestSyncMediaPlayer.tear_down_cleanup
(self)
Shut down test instance.
Shut down test instance.
def tear_down_cleanup(self): """Shut down test instance.""" self.hass.stop()
[ "def", "tear_down_cleanup", "(", "self", ")", ":", "self", ".", "hass", ".", "stop", "(", ")" ]
[ 212, 4 ]
[ 214, 24 ]
python
en
['en', 'de', 'en']
True
TestSyncMediaPlayer.test_volume_up
(self)
Test the volume_up helper function.
Test the volume_up helper function.
def test_volume_up(self): """Test the volume_up helper function.""" assert self.player.volume_level == 0 self.player.set_volume_level(0.5) assert self.player.volume_level == 0.5 asyncio.run_coroutine_threadsafe( self.player.async_volume_up(), self.hass.loop ).result() assert self.player.volume_level == 0.7
[ "def", "test_volume_up", "(", "self", ")", ":", "assert", "self", ".", "player", ".", "volume_level", "==", "0", "self", ".", "player", ".", "set_volume_level", "(", "0.5", ")", "assert", "self", ".", "player", ".", "volume_level", "==", "0.5", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_volume_up", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "volume_level", "==", "0.7" ]
[ 216, 4 ]
[ 224, 46 ]
python
en
['en', 'en', 'en']
True
TestSyncMediaPlayer.test_volume_down
(self)
Test the volume_down helper function.
Test the volume_down helper function.
def test_volume_down(self): """Test the volume_down helper function.""" assert self.player.volume_level == 0 self.player.set_volume_level(0.5) assert self.player.volume_level == 0.5 asyncio.run_coroutine_threadsafe( self.player.async_volume_down(), self.hass.loop ).result() assert self.player.volume_level == 0.3
[ "def", "test_volume_down", "(", "self", ")", ":", "assert", "self", ".", "player", ".", "volume_level", "==", "0", "self", ".", "player", ".", "set_volume_level", "(", "0.5", ")", "assert", "self", ".", "player", ".", "volume_level", "==", "0.5", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_volume_down", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "volume_level", "==", "0.3" ]
[ 226, 4 ]
[ 234, 46 ]
python
en
['en', 'en', 'en']
True
TestSyncMediaPlayer.test_media_play_pause
(self)
Test the media_play_pause helper function.
Test the media_play_pause helper function.
def test_media_play_pause(self): """Test the media_play_pause helper function.""" assert self.player.state == STATE_OFF asyncio.run_coroutine_threadsafe( self.player.async_media_play_pause(), self.hass.loop ).result() assert self.player.state == STATE_PLAYING asyncio.run_coroutine_threadsafe( self.player.async_media_play_pause(), self.hass.loop ).result() assert self.player.state == STATE_PAUSED
[ "def", "test_media_play_pause", "(", "self", ")", ":", "assert", "self", ".", "player", ".", "state", "==", "STATE_OFF", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_media_play_pause", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "state", "==", "STATE_PLAYING", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_media_play_pause", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "state", "==", "STATE_PAUSED" ]
[ 236, 4 ]
[ 246, 48 ]
python
en
['en', 'en', 'en']
True
TestSyncMediaPlayer.test_toggle
(self)
Test the toggle helper function.
Test the toggle helper function.
def test_toggle(self): """Test the toggle helper function.""" assert self.player.state == STATE_OFF asyncio.run_coroutine_threadsafe( self.player.async_toggle(), self.hass.loop ).result() assert self.player.state == STATE_ON asyncio.run_coroutine_threadsafe( self.player.async_toggle(), self.hass.loop ).result() assert self.player.state == STATE_OFF
[ "def", "test_toggle", "(", "self", ")", ":", "assert", "self", ".", "player", ".", "state", "==", "STATE_OFF", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_toggle", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "state", "==", "STATE_ON", "asyncio", ".", "run_coroutine_threadsafe", "(", "self", ".", "player", ".", "async_toggle", "(", ")", ",", "self", ".", "hass", ".", "loop", ")", ".", "result", "(", ")", "assert", "self", ".", "player", ".", "state", "==", "STATE_OFF" ]
[ 248, 4 ]
[ 258, 45 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Fritzbox binary sensor from config_entry.
Set up the Fritzbox binary sensor from config_entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Fritzbox binary sensor from config_entry.""" entities = [] devices = hass.data[FRITZBOX_DOMAIN][CONF_DEVICES] fritz = hass.data[FRITZBOX_DOMAIN][CONF_CONNECTIONS][config_entry.entry_id] for device in await hass.async_add_executor_job(fritz.get_devices): if device.has_alarm and device.ain not in devices: entities.append(FritzboxBinarySensor(device, fritz)) devices.add(device.ain) async_add_entities(entities, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "entities", "=", "[", "]", "devices", "=", "hass", ".", "data", "[", "FRITZBOX_DOMAIN", "]", "[", "CONF_DEVICES", "]", "fritz", "=", "hass", ".", "data", "[", "FRITZBOX_DOMAIN", "]", "[", "CONF_CONNECTIONS", "]", "[", "config_entry", ".", "entry_id", "]", "for", "device", "in", "await", "hass", ".", "async_add_executor_job", "(", "fritz", ".", "get_devices", ")", ":", "if", "device", ".", "has_alarm", "and", "device", ".", "ain", "not", "in", "devices", ":", "entities", ".", "append", "(", "FritzboxBinarySensor", "(", "device", ",", "fritz", ")", ")", "devices", ".", "add", "(", "device", ".", "ain", ")", "async_add_entities", "(", "entities", ",", "True", ")" ]
[ 12, 0 ]
[ 23, 38 ]
python
en
['en', 'en', 'en']
True
FritzboxBinarySensor.__init__
(self, device, fritz)
Initialize the Fritzbox binary sensor.
Initialize the Fritzbox binary sensor.
def __init__(self, device, fritz): """Initialize the Fritzbox binary sensor.""" self._device = device self._fritz = fritz
[ "def", "__init__", "(", "self", ",", "device", ",", "fritz", ")", ":", "self", ".", "_device", "=", "device", "self", ".", "_fritz", "=", "fritz" ]
[ 29, 4 ]
[ 32, 27 ]
python
en
['en', 'en', 'en']
True
FritzboxBinarySensor.device_info
(self)
Return device specific attributes.
Return device specific attributes.
def device_info(self): """Return device specific attributes.""" return { "name": self.name, "identifiers": {(FRITZBOX_DOMAIN, self._device.ain)}, "manufacturer": self._device.manufacturer, "model": self._device.productname, "sw_version": self._device.fw_version, }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"name\"", ":", "self", ".", "name", ",", "\"identifiers\"", ":", "{", "(", "FRITZBOX_DOMAIN", ",", "self", ".", "_device", ".", "ain", ")", "}", ",", "\"manufacturer\"", ":", "self", ".", "_device", ".", "manufacturer", ",", "\"model\"", ":", "self", ".", "_device", ".", "productname", ",", "\"sw_version\"", ":", "self", ".", "_device", ".", "fw_version", ",", "}" ]
[ 35, 4 ]
[ 43, 9 ]
python
en
['fr', 'it', 'en']
False
FritzboxBinarySensor.unique_id
(self)
Return the unique ID of the device.
Return the unique ID of the device.
def unique_id(self): """Return the unique ID of the device.""" return self._device.ain
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "ain" ]
[ 46, 4 ]
[ 48, 31 ]
python
en
['en', 'en', 'en']
True
FritzboxBinarySensor.name
(self)
Return the name of the entity.
Return the name of the entity.
def name(self): """Return the name of the entity.""" return self._device.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "name" ]
[ 51, 4 ]
[ 53, 32 ]
python
en
['en', 'en', 'en']
True
FritzboxBinarySensor.device_class
(self)
Return the class of this sensor.
Return the class of this sensor.
def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_WINDOW
[ "def", "device_class", "(", "self", ")", ":", "return", "DEVICE_CLASS_WINDOW" ]
[ 56, 4 ]
[ 58, 34 ]
python
en
['en', 'en', 'en']
True
FritzboxBinarySensor.is_on
(self)
Return true if sensor is on.
Return true if sensor is on.
def is_on(self): """Return true if sensor is on.""" if not self._device.present: return False return self._device.alert_state
[ "def", "is_on", "(", "self", ")", ":", "if", "not", "self", ".", "_device", ".", "present", ":", "return", "False", "return", "self", ".", "_device", ".", "alert_state" ]
[ 61, 4 ]
[ 65, 39 ]
python
en
['en', 'et', 'en']
True
FritzboxBinarySensor.update
(self)
Get latest data from the Fritzbox.
Get latest data from the Fritzbox.
def update(self): """Get latest data from the Fritzbox.""" try: self._device.update() except requests.exceptions.HTTPError as ex: LOGGER.warning("Connection error: %s", ex) self._fritz.login()
[ "def", "update", "(", "self", ")", ":", "try", ":", "self", ".", "_device", ".", "update", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "ex", ":", "LOGGER", ".", "warning", "(", "\"Connection error: %s\"", ",", "ex", ")", "self", ".", "_fritz", ".", "login", "(", ")" ]
[ 67, 4 ]
[ 73, 31 ]
python
en
['en', 'en', 'en']
True
PegasusTokenizerFast.get_special_tokens_mask
( self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False )
Get list where entries are [1] if a token is [eos] or [pad] else 0.
Get list where entries are [1] if a token is [eos] or [pad] else 0.
def get_special_tokens_mask( self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False ) -> List[int]: """Get list where entries are [1] if a token is [eos] or [pad] else 0.""" if already_has_special_tokens: return self._special_token_mask(token_ids_0) elif token_ids_1 is None: return self._special_token_mask(token_ids_0) + [1] else: return self._special_token_mask(token_ids_0 + token_ids_1) + [1]
[ "def", "get_special_tokens_mask", "(", "self", ",", "token_ids_0", ":", "List", ",", "token_ids_1", ":", "Optional", "[", "List", "]", "=", "None", ",", "already_has_special_tokens", ":", "bool", "=", "False", ")", "->", "List", "[", "int", "]", ":", "if", "already_has_special_tokens", ":", "return", "self", ".", "_special_token_mask", "(", "token_ids_0", ")", "elif", "token_ids_1", "is", "None", ":", "return", "self", ".", "_special_token_mask", "(", "token_ids_0", ")", "+", "[", "1", "]", "else", ":", "return", "self", ".", "_special_token_mask", "(", "token_ids_0", "+", "token_ids_1", ")", "+", "[", "1", "]" ]
[ 159, 4 ]
[ 168, 76 ]
python
en
['en', 'en', 'en']
True
PegasusTokenizerFast.build_inputs_with_special_tokens
(self, token_ids_0, token_ids_1=None)
Build model inputs from a sequence by adding eos to the end. no bos token is added to the front. - single sequence: ``X </s>`` - pair of sequences: ``A B </s>`` (not intended use) Args: token_ids_0 (:obj:`List[int]`): List of IDs to which the special tokens will be added token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: list of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
Build model inputs from a sequence by adding eos to the end. no bos token is added to the front.
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> List[int]: """ Build model inputs from a sequence by adding eos to the end. no bos token is added to the front. - single sequence: ``X </s>`` - pair of sequences: ``A B </s>`` (not intended use) Args: token_ids_0 (:obj:`List[int]`): List of IDs to which the special tokens will be added token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: list of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens. """ if token_ids_1 is None: return token_ids_0 + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_0 + token_ids_1 + [self.eos_token_id]
[ "def", "build_inputs_with_special_tokens", "(", "self", ",", "token_ids_0", ",", "token_ids_1", "=", "None", ")", "->", "List", "[", "int", "]", ":", "if", "token_ids_1", "is", "None", ":", "return", "token_ids_0", "+", "[", "self", ".", "eos_token_id", "]", "# We don't expect to process pairs, but leave the pair logic for API consistency", "return", "token_ids_0", "+", "token_ids_1", "+", "[", "self", ".", "eos_token_id", "]" ]
[ 170, 4 ]
[ 189, 62 ]
python
en
['en', 'error', 'th']
False
test_apprise_config_load_fail01
(hass)
Test apprise configuration failures 1.
Test apprise configuration failures 1.
async def test_apprise_config_load_fail01(hass): """Test apprise configuration failures 1.""" config = { BASE_COMPONENT: {"name": "test", "platform": "apprise", "config": "/path/"} } with patch("apprise.AppriseConfig.add", return_value=False): assert await async_setup_component(hass, BASE_COMPONENT, config) await hass.async_block_till_done() # Test that our service failed to load assert not hass.services.has_service(BASE_COMPONENT, "test")
[ "async", "def", "test_apprise_config_load_fail01", "(", "hass", ")", ":", "config", "=", "{", "BASE_COMPONENT", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"platform\"", ":", "\"apprise\"", ",", "\"config\"", ":", "\"/path/\"", "}", "}", "with", "patch", "(", "\"apprise.AppriseConfig.add\"", ",", "return_value", "=", "False", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "BASE_COMPONENT", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Test that our service failed to load", "assert", "not", "hass", ".", "services", ".", "has_service", "(", "BASE_COMPONENT", ",", "\"test\"", ")" ]
[ 8, 0 ]
[ 20, 68 ]
python
fr
['fr', 'fr', 'en']
True
test_apprise_config_load_fail02
(hass)
Test apprise configuration failures 2.
Test apprise configuration failures 2.
async def test_apprise_config_load_fail02(hass): """Test apprise configuration failures 2.""" config = { BASE_COMPONENT: {"name": "test", "platform": "apprise", "config": "/path/"} } with patch("apprise.Apprise.add", return_value=False): with patch("apprise.AppriseConfig.add", return_value=True): assert await async_setup_component(hass, BASE_COMPONENT, config) await hass.async_block_till_done() # Test that our service failed to load assert not hass.services.has_service(BASE_COMPONENT, "test")
[ "async", "def", "test_apprise_config_load_fail02", "(", "hass", ")", ":", "config", "=", "{", "BASE_COMPONENT", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"platform\"", ":", "\"apprise\"", ",", "\"config\"", ":", "\"/path/\"", "}", "}", "with", "patch", "(", "\"apprise.Apprise.add\"", ",", "return_value", "=", "False", ")", ":", "with", "patch", "(", "\"apprise.AppriseConfig.add\"", ",", "return_value", "=", "True", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "BASE_COMPONENT", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Test that our service failed to load", "assert", "not", "hass", ".", "services", ".", "has_service", "(", "BASE_COMPONENT", ",", "\"test\"", ")" ]
[ 23, 0 ]
[ 36, 72 ]
python
fr
['fr', 'fr', 'en']
True
test_apprise_config_load_okay
(hass, tmp_path)
Test apprise configuration failures.
Test apprise configuration failures.
async def test_apprise_config_load_okay(hass, tmp_path): """Test apprise configuration failures.""" # Test cases where our URL is invalid d = tmp_path / "apprise-config" d.mkdir() f = d / "apprise" f.write_text("mailto://user:[email protected]/") config = {BASE_COMPONENT: {"name": "test", "platform": "apprise", "config": str(f)}} assert await async_setup_component(hass, BASE_COMPONENT, config) await hass.async_block_till_done() # Valid configuration was loaded; our service is good assert hass.services.has_service(BASE_COMPONENT, "test")
[ "async", "def", "test_apprise_config_load_okay", "(", "hass", ",", "tmp_path", ")", ":", "# Test cases where our URL is invalid", "d", "=", "tmp_path", "/", "\"apprise-config\"", "d", ".", "mkdir", "(", ")", "f", "=", "d", "/", "\"apprise\"", "f", ".", "write_text", "(", "\"mailto://user:[email protected]/\"", ")", "config", "=", "{", "BASE_COMPONENT", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"platform\"", ":", "\"apprise\"", ",", "\"config\"", ":", "str", "(", "f", ")", "}", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "BASE_COMPONENT", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Valid configuration was loaded; our service is good", "assert", "hass", ".", "services", ".", "has_service", "(", "BASE_COMPONENT", ",", "\"test\"", ")" ]
[ 39, 0 ]
[ 54, 60 ]
python
fr
['fr', 'fr', 'en']
True
test_apprise_url_load_fail
(hass)
Test apprise url failure.
Test apprise url failure.
async def test_apprise_url_load_fail(hass): """Test apprise url failure.""" config = { BASE_COMPONENT: { "name": "test", "platform": "apprise", "url": "mailto://user:[email protected]", } } with patch("apprise.Apprise.add", return_value=False): assert await async_setup_component(hass, BASE_COMPONENT, config) await hass.async_block_till_done() # Test that our service failed to load assert not hass.services.has_service(BASE_COMPONENT, "test")
[ "async", "def", "test_apprise_url_load_fail", "(", "hass", ")", ":", "config", "=", "{", "BASE_COMPONENT", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"platform\"", ":", "\"apprise\"", ",", "\"url\"", ":", "\"mailto://user:[email protected]\"", ",", "}", "}", "with", "patch", "(", "\"apprise.Apprise.add\"", ",", "return_value", "=", "False", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "BASE_COMPONENT", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Test that our service failed to load", "assert", "not", "hass", ".", "services", ".", "has_service", "(", "BASE_COMPONENT", ",", "\"test\"", ")" ]
[ 57, 0 ]
[ 72, 68 ]
python
fr
['fr', 'fr', 'en']
True
test_apprise_notification
(hass)
Test apprise notification.
Test apprise notification.
async def test_apprise_notification(hass): """Test apprise notification.""" config = { BASE_COMPONENT: { "name": "test", "platform": "apprise", "url": "mailto://user:[email protected]", } } # Our Message data = {"title": "Test Title", "message": "Test Message"} with patch("apprise.Apprise") as mock_apprise: obj = MagicMock() obj.add.return_value = True obj.notify.return_value = True mock_apprise.return_value = obj assert await async_setup_component(hass, BASE_COMPONENT, config) await hass.async_block_till_done() # Test the existence of our service assert hass.services.has_service(BASE_COMPONENT, "test") # Test the call to our underlining notify() call await hass.services.async_call(BASE_COMPONENT, "test", data) await hass.async_block_till_done() # Validate calls were made under the hood correctly obj.add.assert_called_once_with([config[BASE_COMPONENT]["url"]]) obj.notify.assert_called_once_with( **{"body": data["message"], "title": data["title"], "tag": None} )
[ "async", "def", "test_apprise_notification", "(", "hass", ")", ":", "config", "=", "{", "BASE_COMPONENT", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"platform\"", ":", "\"apprise\"", ",", "\"url\"", ":", "\"mailto://user:[email protected]\"", ",", "}", "}", "# Our Message", "data", "=", "{", "\"title\"", ":", "\"Test Title\"", ",", "\"message\"", ":", "\"Test Message\"", "}", "with", "patch", "(", "\"apprise.Apprise\"", ")", "as", "mock_apprise", ":", "obj", "=", "MagicMock", "(", ")", "obj", ".", "add", ".", "return_value", "=", "True", "obj", ".", "notify", ".", "return_value", "=", "True", "mock_apprise", ".", "return_value", "=", "obj", "assert", "await", "async_setup_component", "(", "hass", ",", "BASE_COMPONENT", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Test the existence of our service", "assert", "hass", ".", "services", ".", "has_service", "(", "BASE_COMPONENT", ",", "\"test\"", ")", "# Test the call to our underlining notify() call", "await", "hass", ".", "services", ".", "async_call", "(", "BASE_COMPONENT", ",", "\"test\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Validate calls were made under the hood correctly", "obj", ".", "add", ".", "assert_called_once_with", "(", "[", "config", "[", "BASE_COMPONENT", "]", "[", "\"url\"", "]", "]", ")", "obj", ".", "notify", ".", "assert_called_once_with", "(", "*", "*", "{", "\"body\"", ":", "data", "[", "\"message\"", "]", ",", "\"title\"", ":", "data", "[", "\"title\"", "]", ",", "\"tag\"", ":", "None", "}", ")" ]
[ 75, 0 ]
[ 108, 9 ]
python
en
['et', 'en', 'fr']
False
test_apprise_notification_with_target
(hass, tmp_path)
Test apprise notification with a target.
Test apprise notification with a target.
async def test_apprise_notification_with_target(hass, tmp_path): """Test apprise notification with a target.""" # Test cases where our URL is invalid d = tmp_path / "apprise-config" d.mkdir() f = d / "apprise" # Write 2 config entries each assigned to different tags f.write_text("devops=mailto://user:[email protected]/\r\n") f.write_text("system,alert=syslog://\r\n") config = {BASE_COMPONENT: {"name": "test", "platform": "apprise", "config": str(f)}} # Our Message, only notify the services tagged with "devops" data = {"title": "Test Title", "message": "Test Message", "target": ["devops"]} with patch("apprise.Apprise") as mock_apprise: apprise_obj = MagicMock() apprise_obj.add.return_value = True apprise_obj.notify.return_value = True mock_apprise.return_value = apprise_obj assert await async_setup_component(hass, BASE_COMPONENT, config) await hass.async_block_till_done() # Test the existence of our service assert hass.services.has_service(BASE_COMPONENT, "test") # Test the call to our underlining notify() call await hass.services.async_call(BASE_COMPONENT, "test", data) await hass.async_block_till_done() # Validate calls were made under the hood correctly apprise_obj.notify.assert_called_once_with( **{"body": data["message"], "title": data["title"], "tag": data["target"]} )
[ "async", "def", "test_apprise_notification_with_target", "(", "hass", ",", "tmp_path", ")", ":", "# Test cases where our URL is invalid", "d", "=", "tmp_path", "/", "\"apprise-config\"", "d", ".", "mkdir", "(", ")", "f", "=", "d", "/", "\"apprise\"", "# Write 2 config entries each assigned to different tags", "f", ".", "write_text", "(", "\"devops=mailto://user:[email protected]/\\r\\n\"", ")", "f", ".", "write_text", "(", "\"system,alert=syslog://\\r\\n\"", ")", "config", "=", "{", "BASE_COMPONENT", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"platform\"", ":", "\"apprise\"", ",", "\"config\"", ":", "str", "(", "f", ")", "}", "}", "# Our Message, only notify the services tagged with \"devops\"", "data", "=", "{", "\"title\"", ":", "\"Test Title\"", ",", "\"message\"", ":", "\"Test Message\"", ",", "\"target\"", ":", "[", "\"devops\"", "]", "}", "with", "patch", "(", "\"apprise.Apprise\"", ")", "as", "mock_apprise", ":", "apprise_obj", "=", "MagicMock", "(", ")", "apprise_obj", ".", "add", ".", "return_value", "=", "True", "apprise_obj", ".", "notify", ".", "return_value", "=", "True", "mock_apprise", ".", "return_value", "=", "apprise_obj", "assert", "await", "async_setup_component", "(", "hass", ",", "BASE_COMPONENT", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Test the existence of our service", "assert", "hass", ".", "services", ".", "has_service", "(", "BASE_COMPONENT", ",", "\"test\"", ")", "# Test the call to our underlining notify() call", "await", "hass", ".", "services", ".", "async_call", "(", "BASE_COMPONENT", ",", "\"test\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Validate calls were made under the hood correctly", "apprise_obj", ".", "notify", ".", "assert_called_once_with", "(", "*", "*", "{", "\"body\"", ":", "data", "[", "\"message\"", "]", ",", "\"title\"", ":", "data", "[", "\"title\"", "]", ",", "\"tag\"", ":", "data", "[", "\"target\"", "]", "}", ")" ]
[ 111, 0 ]
[ 146, 9 ]
python
en
['en', 'en', 'en']
True
setup_deconz_integration
( hass, config=ENTRY_CONFIG, options=ENTRY_OPTIONS, get_state_response=DECONZ_WEB_REQUEST, entry_id="1", source="user", )
Create the deCONZ gateway.
Create the deCONZ gateway.
async def setup_deconz_integration( hass, config=ENTRY_CONFIG, options=ENTRY_OPTIONS, get_state_response=DECONZ_WEB_REQUEST, entry_id="1", source="user", ): """Create the deCONZ gateway.""" config_entry = MockConfigEntry( domain=DECONZ_DOMAIN, source=source, data=deepcopy(config), connection_class=CONN_CLASS_LOCAL_PUSH, options=deepcopy(options), entry_id=entry_id, ) config_entry.add_to_hass(hass) with patch( "pydeconz.DeconzSession.request", return_value=deepcopy(get_state_response) ), patch("pydeconz.DeconzSession.start", return_value=True): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry
[ "async", "def", "setup_deconz_integration", "(", "hass", ",", "config", "=", "ENTRY_CONFIG", ",", "options", "=", "ENTRY_OPTIONS", ",", "get_state_response", "=", "DECONZ_WEB_REQUEST", ",", "entry_id", "=", "\"1\"", ",", "source", "=", "\"user\"", ",", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "DECONZ_DOMAIN", ",", "source", "=", "source", ",", "data", "=", "deepcopy", "(", "config", ")", ",", "connection_class", "=", "CONN_CLASS_LOCAL_PUSH", ",", "options", "=", "deepcopy", "(", "options", ")", ",", "entry_id", "=", "entry_id", ",", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "with", "patch", "(", "\"pydeconz.DeconzSession.request\"", ",", "return_value", "=", "deepcopy", "(", "get_state_response", ")", ")", ",", "patch", "(", "\"pydeconz.DeconzSession.start\"", ",", "return_value", "=", "True", ")", ":", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "config_entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "return", "config_entry" ]
[ 62, 0 ]
[ 87, 23 ]
python
en
['en', 'de', 'en']
True
test_gateway_setup
(hass)
Successful setup.
Successful setup.
async def test_gateway_setup(hass): """Successful setup.""" with patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup", return_value=True, ) as forward_entry_setup: config_entry = await setup_deconz_integration(hass) gateway = get_gateway_from_config_entry(hass, config_entry) assert gateway.bridgeid == BRIDGEID assert gateway.master is True assert gateway.option_allow_clip_sensor is False assert gateway.option_allow_deconz_groups is True assert gateway.option_allow_new_devices is True assert len(gateway.deconz_ids) == 0 assert len(hass.states.async_all()) == 0 assert forward_entry_setup.mock_calls[0][1] == ( config_entry, BINARY_SENSOR_DOMAIN, ) assert forward_entry_setup.mock_calls[1][1] == (config_entry, CLIMATE_DOMAIN) assert forward_entry_setup.mock_calls[2][1] == (config_entry, COVER_DOMAIN) assert forward_entry_setup.mock_calls[3][1] == (config_entry, FAN_DOMAIN) assert forward_entry_setup.mock_calls[4][1] == (config_entry, LIGHT_DOMAIN) assert forward_entry_setup.mock_calls[5][1] == (config_entry, LOCK_DOMAIN) assert forward_entry_setup.mock_calls[6][1] == (config_entry, SCENE_DOMAIN) assert forward_entry_setup.mock_calls[7][1] == (config_entry, SENSOR_DOMAIN) assert forward_entry_setup.mock_calls[8][1] == (config_entry, SWITCH_DOMAIN)
[ "async", "def", "test_gateway_setup", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.config_entries.ConfigEntries.async_forward_entry_setup\"", ",", "return_value", "=", "True", ",", ")", "as", "forward_entry_setup", ":", "config_entry", "=", "await", "setup_deconz_integration", "(", "hass", ")", "gateway", "=", "get_gateway_from_config_entry", "(", "hass", ",", "config_entry", ")", "assert", "gateway", ".", "bridgeid", "==", "BRIDGEID", "assert", "gateway", ".", "master", "is", "True", "assert", "gateway", ".", "option_allow_clip_sensor", "is", "False", "assert", "gateway", ".", "option_allow_deconz_groups", "is", "True", "assert", "gateway", ".", "option_allow_new_devices", "is", "True", "assert", "len", "(", "gateway", ".", "deconz_ids", ")", "==", "0", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0", "assert", "forward_entry_setup", ".", "mock_calls", "[", "0", "]", "[", "1", "]", "==", "(", "config_entry", ",", "BINARY_SENSOR_DOMAIN", ",", ")", "assert", "forward_entry_setup", ".", "mock_calls", "[", "1", "]", "[", "1", "]", "==", "(", "config_entry", ",", "CLIMATE_DOMAIN", ")", "assert", "forward_entry_setup", ".", "mock_calls", "[", "2", "]", "[", "1", "]", "==", "(", "config_entry", ",", "COVER_DOMAIN", ")", "assert", "forward_entry_setup", ".", "mock_calls", "[", "3", "]", "[", "1", "]", "==", "(", "config_entry", ",", "FAN_DOMAIN", ")", "assert", "forward_entry_setup", ".", "mock_calls", "[", "4", "]", "[", "1", "]", "==", "(", "config_entry", ",", "LIGHT_DOMAIN", ")", "assert", "forward_entry_setup", ".", "mock_calls", "[", "5", "]", "[", "1", "]", "==", "(", "config_entry", ",", "LOCK_DOMAIN", ")", "assert", "forward_entry_setup", ".", "mock_calls", "[", "6", "]", "[", "1", "]", "==", "(", "config_entry", ",", "SCENE_DOMAIN", ")", "assert", "forward_entry_setup", ".", "mock_calls", "[", "7", "]", "[", "1", "]", "==", "(", "config_entry", ",", "SENSOR_DOMAIN", ")", "assert", "forward_entry_setup", ".", "mock_calls", "[", "8", "]", "[", "1", "]", "==", "(", "config_entry", ",", "SWITCH_DOMAIN", ")" ]
[ 90, 0 ]
[ 118, 84 ]
python
en
['en', 'ro', 'en']
False
test_gateway_retry
(hass)
Retry setup.
Retry setup.
async def test_gateway_retry(hass): """Retry setup.""" with patch( "homeassistant.components.deconz.gateway.get_gateway", side_effect=CannotConnect, ): await setup_deconz_integration(hass) assert not hass.data[DECONZ_DOMAIN]
[ "async", "def", "test_gateway_retry", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.deconz.gateway.get_gateway\"", ",", "side_effect", "=", "CannotConnect", ",", ")", ":", "await", "setup_deconz_integration", "(", "hass", ")", "assert", "not", "hass", ".", "data", "[", "DECONZ_DOMAIN", "]" ]
[ 121, 0 ]
[ 128, 39 ]
python
en
['en', 'pt', 'en']
False
test_gateway_setup_fails
(hass)
Retry setup.
Retry setup.
async def test_gateway_setup_fails(hass): """Retry setup.""" with patch( "homeassistant.components.deconz.gateway.get_gateway", side_effect=Exception ): await setup_deconz_integration(hass) assert not hass.data[DECONZ_DOMAIN]
[ "async", "def", "test_gateway_setup_fails", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.deconz.gateway.get_gateway\"", ",", "side_effect", "=", "Exception", ")", ":", "await", "setup_deconz_integration", "(", "hass", ")", "assert", "not", "hass", ".", "data", "[", "DECONZ_DOMAIN", "]" ]
[ 131, 0 ]
[ 137, 39 ]
python
en
['en', 'pt', 'en']
False
test_connection_status_signalling
(hass)
Make sure that connection status triggers a dispatcher send.
Make sure that connection status triggers a dispatcher send.
async def test_connection_status_signalling(hass): """Make sure that connection status triggers a dispatcher send.""" config_entry = await setup_deconz_integration(hass) gateway = get_gateway_from_config_entry(hass, config_entry) event_call = Mock() unsub = async_dispatcher_connect(hass, gateway.signal_reachable, event_call) gateway.async_connection_status_callback(False) await hass.async_block_till_done() assert gateway.available is False assert len(event_call.mock_calls) == 1 unsub()
[ "async", "def", "test_connection_status_signalling", "(", "hass", ")", ":", "config_entry", "=", "await", "setup_deconz_integration", "(", "hass", ")", "gateway", "=", "get_gateway_from_config_entry", "(", "hass", ",", "config_entry", ")", "event_call", "=", "Mock", "(", ")", "unsub", "=", "async_dispatcher_connect", "(", "hass", ",", "gateway", ".", "signal_reachable", ",", "event_call", ")", "gateway", ".", "async_connection_status_callback", "(", "False", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "gateway", ".", "available", "is", "False", "assert", "len", "(", "event_call", ".", "mock_calls", ")", "==", "1", "unsub", "(", ")" ]
[ 140, 0 ]
[ 154, 11 ]
python
en
['en', 'fr', 'en']
True
test_update_address
(hass)
Make sure that connection status triggers a dispatcher send.
Make sure that connection status triggers a dispatcher send.
async def test_update_address(hass): """Make sure that connection status triggers a dispatcher send.""" config_entry = await setup_deconz_integration(hass) gateway = get_gateway_from_config_entry(hass, config_entry) assert gateway.api.host == "1.2.3.4" with patch( "homeassistant.components.deconz.async_setup_entry", return_value=True, ) as mock_setup_entry: await hass.config_entries.flow.async_init( DECONZ_DOMAIN, data={ ATTR_SSDP_LOCATION: "http://2.3.4.5:80/", ATTR_UPNP_MANUFACTURER_URL: DECONZ_MANUFACTURERURL, ATTR_UPNP_SERIAL: BRIDGEID, ATTR_UPNP_UDN: "uuid:456DEF", }, context={"source": SOURCE_SSDP}, ) await hass.async_block_till_done() assert gateway.api.host == "2.3.4.5" assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_update_address", "(", "hass", ")", ":", "config_entry", "=", "await", "setup_deconz_integration", "(", "hass", ")", "gateway", "=", "get_gateway_from_config_entry", "(", "hass", ",", "config_entry", ")", "assert", "gateway", ".", "api", ".", "host", "==", "\"1.2.3.4\"", "with", "patch", "(", "\"homeassistant.components.deconz.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DECONZ_DOMAIN", ",", "data", "=", "{", "ATTR_SSDP_LOCATION", ":", "\"http://2.3.4.5:80/\"", ",", "ATTR_UPNP_MANUFACTURER_URL", ":", "DECONZ_MANUFACTURERURL", ",", "ATTR_UPNP_SERIAL", ":", "BRIDGEID", ",", "ATTR_UPNP_UDN", ":", "\"uuid:456DEF\"", ",", "}", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_SSDP", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "gateway", ".", "api", ".", "host", "==", "\"2.3.4.5\"", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 157, 0 ]
[ 180, 48 ]
python
en
['en', 'fr', 'en']
True
test_reset_after_successful_setup
(hass)
Make sure that connection status triggers a dispatcher send.
Make sure that connection status triggers a dispatcher send.
async def test_reset_after_successful_setup(hass): """Make sure that connection status triggers a dispatcher send.""" config_entry = await setup_deconz_integration(hass) gateway = get_gateway_from_config_entry(hass, config_entry) result = await gateway.async_reset() await hass.async_block_till_done() assert result is True
[ "async", "def", "test_reset_after_successful_setup", "(", "hass", ")", ":", "config_entry", "=", "await", "setup_deconz_integration", "(", "hass", ")", "gateway", "=", "get_gateway_from_config_entry", "(", "hass", ",", "config_entry", ")", "result", "=", "await", "gateway", ".", "async_reset", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result", "is", "True" ]
[ 183, 0 ]
[ 191, 25 ]
python
en
['en', 'fr', 'en']
True
test_get_gateway
(hass)
Successful call.
Successful call.
async def test_get_gateway(hass): """Successful call.""" with patch("pydeconz.DeconzSession.initialize", return_value=True): assert await get_gateway(hass, ENTRY_CONFIG, Mock(), Mock())
[ "async", "def", "test_get_gateway", "(", "hass", ")", ":", "with", "patch", "(", "\"pydeconz.DeconzSession.initialize\"", ",", "return_value", "=", "True", ")", ":", "assert", "await", "get_gateway", "(", "hass", ",", "ENTRY_CONFIG", ",", "Mock", "(", ")", ",", "Mock", "(", ")", ")" ]
[ 194, 0 ]
[ 197, 68 ]
python
co
['es', 'co', 'en']
False
test_get_gateway_fails_unauthorized
(hass)
Failed call.
Failed call.
async def test_get_gateway_fails_unauthorized(hass): """Failed call.""" with patch( "pydeconz.DeconzSession.initialize", side_effect=pydeconz.errors.Unauthorized, ), pytest.raises(AuthenticationRequired): assert await get_gateway(hass, ENTRY_CONFIG, Mock(), Mock()) is False
[ "async", "def", "test_get_gateway_fails_unauthorized", "(", "hass", ")", ":", "with", "patch", "(", "\"pydeconz.DeconzSession.initialize\"", ",", "side_effect", "=", "pydeconz", ".", "errors", ".", "Unauthorized", ",", ")", ",", "pytest", ".", "raises", "(", "AuthenticationRequired", ")", ":", "assert", "await", "get_gateway", "(", "hass", ",", "ENTRY_CONFIG", ",", "Mock", "(", ")", ",", "Mock", "(", ")", ")", "is", "False" ]
[ 200, 0 ]
[ 206, 77 ]
python
en
['en', 'ga', 'en']
False
test_get_gateway_fails_cannot_connect
(hass)
Failed call.
Failed call.
async def test_get_gateway_fails_cannot_connect(hass): """Failed call.""" with patch( "pydeconz.DeconzSession.initialize", side_effect=pydeconz.errors.RequestError, ), pytest.raises(CannotConnect): assert await get_gateway(hass, ENTRY_CONFIG, Mock(), Mock()) is False
[ "async", "def", "test_get_gateway_fails_cannot_connect", "(", "hass", ")", ":", "with", "patch", "(", "\"pydeconz.DeconzSession.initialize\"", ",", "side_effect", "=", "pydeconz", ".", "errors", ".", "RequestError", ",", ")", ",", "pytest", ".", "raises", "(", "CannotConnect", ")", ":", "assert", "await", "get_gateway", "(", "hass", ",", "ENTRY_CONFIG", ",", "Mock", "(", ")", ",", "Mock", "(", ")", ")", "is", "False" ]
[ 209, 0 ]
[ 215, 77 ]
python
en
['en', 'ga', 'en']
False
get_service
(hass, config, discovery_info=None)
Get the Pushsafer.com notification service.
Get the Pushsafer.com notification service.
def get_service(hass, config, discovery_info=None): """Get the Pushsafer.com notification service.""" return PushsaferNotificationService( config.get(CONF_DEVICE_KEY), hass.config.is_allowed_path )
[ "def", "get_service", "(", "hass", ",", "config", ",", "discovery_info", "=", "None", ")", ":", "return", "PushsaferNotificationService", "(", "config", ".", "get", "(", "CONF_DEVICE_KEY", ")", ",", "hass", ".", "config", ".", "is_allowed_path", ")" ]
[ 51, 0 ]
[ 55, 5 ]
python
en
['en', 'en', 'en']
True
PushsaferNotificationService.__init__
(self, private_key, is_allowed_path)
Initialize the service.
Initialize the service.
def __init__(self, private_key, is_allowed_path): """Initialize the service.""" self._private_key = private_key self.is_allowed_path = is_allowed_path
[ "def", "__init__", "(", "self", ",", "private_key", ",", "is_allowed_path", ")", ":", "self", ".", "_private_key", "=", "private_key", "self", ".", "is_allowed_path", "=", "is_allowed_path" ]
[ 61, 4 ]
[ 64, 46 ]
python
en
['en', 'en', 'en']
True
PushsaferNotificationService.send_message
(self, message="", **kwargs)
Send a message to specified target.
Send a message to specified target.
def send_message(self, message="", **kwargs): """Send a message to specified target.""" if kwargs.get(ATTR_TARGET) is None: targets = ["a"] _LOGGER.debug("No target specified. Sending push to all") else: targets = kwargs.get(ATTR_TARGET) _LOGGER.debug("%s target(s) specified", len(targets)) title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT) data = kwargs.get(ATTR_DATA, {}) # Converting the specified image to base64 picture1 = data.get(ATTR_PICTURE1) picture1_encoded = "" if picture1 is not None: _LOGGER.debug("picture1 is available") url = picture1.get(ATTR_PICTURE1_URL, None) local_path = picture1.get(ATTR_PICTURE1_PATH, None) username = picture1.get(ATTR_PICTURE1_USERNAME) password = picture1.get(ATTR_PICTURE1_PASSWORD) auth = picture1.get(ATTR_PICTURE1_AUTH) if url is not None: _LOGGER.debug("Loading image from url %s", url) picture1_encoded = self.load_from_url(url, username, password, auth) elif local_path is not None: _LOGGER.debug("Loading image from file %s", local_path) picture1_encoded = self.load_from_file(local_path) else: _LOGGER.warning("missing url or local_path for picture1") else: _LOGGER.debug("picture1 is not specified") payload = { "k": self._private_key, "t": title, "m": message, "s": data.get(ATTR_SOUND, ""), "v": data.get(ATTR_VIBRATION, ""), "i": data.get(ATTR_ICON, ""), "c": data.get(ATTR_ICONCOLOR, ""), "u": data.get(ATTR_URL, ""), "ut": data.get(ATTR_URLTITLE, ""), "l": data.get(ATTR_TIME2LIVE, ""), "pr": data.get(ATTR_PRIORITY, ""), "re": data.get(ATTR_RETRY, ""), "ex": data.get(ATTR_EXPIRE, ""), "a": data.get(ATTR_ANSWER, ""), "p": picture1_encoded, } for target in targets: payload["d"] = target response = requests.post(_RESOURCE, data=payload, timeout=CONF_TIMEOUT) if response.status_code != HTTP_OK: _LOGGER.error("Pushsafer failed with: %s", response.text) else: _LOGGER.debug("Push send: %s", response.json())
[ "def", "send_message", "(", "self", ",", "message", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "ATTR_TARGET", ")", "is", "None", ":", "targets", "=", "[", "\"a\"", "]", "_LOGGER", ".", "debug", "(", "\"No target specified. Sending push to all\"", ")", "else", ":", "targets", "=", "kwargs", ".", "get", "(", "ATTR_TARGET", ")", "_LOGGER", ".", "debug", "(", "\"%s target(s) specified\"", ",", "len", "(", "targets", ")", ")", "title", "=", "kwargs", ".", "get", "(", "ATTR_TITLE", ",", "ATTR_TITLE_DEFAULT", ")", "data", "=", "kwargs", ".", "get", "(", "ATTR_DATA", ",", "{", "}", ")", "# Converting the specified image to base64", "picture1", "=", "data", ".", "get", "(", "ATTR_PICTURE1", ")", "picture1_encoded", "=", "\"\"", "if", "picture1", "is", "not", "None", ":", "_LOGGER", ".", "debug", "(", "\"picture1 is available\"", ")", "url", "=", "picture1", ".", "get", "(", "ATTR_PICTURE1_URL", ",", "None", ")", "local_path", "=", "picture1", ".", "get", "(", "ATTR_PICTURE1_PATH", ",", "None", ")", "username", "=", "picture1", ".", "get", "(", "ATTR_PICTURE1_USERNAME", ")", "password", "=", "picture1", ".", "get", "(", "ATTR_PICTURE1_PASSWORD", ")", "auth", "=", "picture1", ".", "get", "(", "ATTR_PICTURE1_AUTH", ")", "if", "url", "is", "not", "None", ":", "_LOGGER", ".", "debug", "(", "\"Loading image from url %s\"", ",", "url", ")", "picture1_encoded", "=", "self", ".", "load_from_url", "(", "url", ",", "username", ",", "password", ",", "auth", ")", "elif", "local_path", "is", "not", "None", ":", "_LOGGER", ".", "debug", "(", "\"Loading image from file %s\"", ",", "local_path", ")", "picture1_encoded", "=", "self", ".", "load_from_file", "(", "local_path", ")", "else", ":", "_LOGGER", ".", "warning", "(", "\"missing url or local_path for picture1\"", ")", "else", ":", "_LOGGER", ".", "debug", "(", "\"picture1 is not specified\"", ")", "payload", "=", "{", "\"k\"", ":", "self", ".", "_private_key", ",", "\"t\"", ":", "title", ",", "\"m\"", ":", "message", ",", "\"s\"", ":", "data", ".", "get", "(", "ATTR_SOUND", ",", "\"\"", ")", ",", "\"v\"", ":", "data", ".", "get", "(", "ATTR_VIBRATION", ",", "\"\"", ")", ",", "\"i\"", ":", "data", ".", "get", "(", "ATTR_ICON", ",", "\"\"", ")", ",", "\"c\"", ":", "data", ".", "get", "(", "ATTR_ICONCOLOR", ",", "\"\"", ")", ",", "\"u\"", ":", "data", ".", "get", "(", "ATTR_URL", ",", "\"\"", ")", ",", "\"ut\"", ":", "data", ".", "get", "(", "ATTR_URLTITLE", ",", "\"\"", ")", ",", "\"l\"", ":", "data", ".", "get", "(", "ATTR_TIME2LIVE", ",", "\"\"", ")", ",", "\"pr\"", ":", "data", ".", "get", "(", "ATTR_PRIORITY", ",", "\"\"", ")", ",", "\"re\"", ":", "data", ".", "get", "(", "ATTR_RETRY", ",", "\"\"", ")", ",", "\"ex\"", ":", "data", ".", "get", "(", "ATTR_EXPIRE", ",", "\"\"", ")", ",", "\"a\"", ":", "data", ".", "get", "(", "ATTR_ANSWER", ",", "\"\"", ")", ",", "\"p\"", ":", "picture1_encoded", ",", "}", "for", "target", "in", "targets", ":", "payload", "[", "\"d\"", "]", "=", "target", "response", "=", "requests", ".", "post", "(", "_RESOURCE", ",", "data", "=", "payload", ",", "timeout", "=", "CONF_TIMEOUT", ")", "if", "response", ".", "status_code", "!=", "HTTP_OK", ":", "_LOGGER", ".", "error", "(", "\"Pushsafer failed with: %s\"", ",", "response", ".", "text", ")", "else", ":", "_LOGGER", ".", "debug", "(", "\"Push send: %s\"", ",", "response", ".", "json", "(", ")", ")" ]
[ 66, 4 ]
[ 124, 63 ]
python
en
['en', 'en', 'en']
True
PushsaferNotificationService.get_base64
(cls, filebyte, mimetype)
Convert the image to the expected base64 string of pushsafer.
Convert the image to the expected base64 string of pushsafer.
def get_base64(cls, filebyte, mimetype): """Convert the image to the expected base64 string of pushsafer.""" if mimetype not in _ALLOWED_IMAGES: _LOGGER.warning("%s is a not supported mimetype for images", mimetype) return None base64_image = base64.b64encode(filebyte).decode("utf8") return f"data:{mimetype};base64,{base64_image}"
[ "def", "get_base64", "(", "cls", ",", "filebyte", ",", "mimetype", ")", ":", "if", "mimetype", "not", "in", "_ALLOWED_IMAGES", ":", "_LOGGER", ".", "warning", "(", "\"%s is a not supported mimetype for images\"", ",", "mimetype", ")", "return", "None", "base64_image", "=", "base64", ".", "b64encode", "(", "filebyte", ")", ".", "decode", "(", "\"utf8\"", ")", "return", "f\"data:{mimetype};base64,{base64_image}\"" ]
[ 127, 4 ]
[ 134, 55 ]
python
en
['en', 'en', 'en']
True
PushsaferNotificationService.load_from_url
(self, url=None, username=None, password=None, auth=None)
Load image/document/etc from URL.
Load image/document/etc from URL.
def load_from_url(self, url=None, username=None, password=None, auth=None): """Load image/document/etc from URL.""" if url is not None: _LOGGER.debug("Downloading image from %s", url) if username is not None and password is not None: auth_ = HTTPBasicAuth(username, password) response = requests.get(url, auth=auth_, timeout=CONF_TIMEOUT) else: response = requests.get(url, timeout=CONF_TIMEOUT) return self.get_base64(response.content, response.headers["content-type"]) _LOGGER.warning("url not found in param") return None
[ "def", "load_from_url", "(", "self", ",", "url", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "auth", "=", "None", ")", ":", "if", "url", "is", "not", "None", ":", "_LOGGER", ".", "debug", "(", "\"Downloading image from %s\"", ",", "url", ")", "if", "username", "is", "not", "None", "and", "password", "is", "not", "None", ":", "auth_", "=", "HTTPBasicAuth", "(", "username", ",", "password", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "auth", "=", "auth_", ",", "timeout", "=", "CONF_TIMEOUT", ")", "else", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "timeout", "=", "CONF_TIMEOUT", ")", "return", "self", ".", "get_base64", "(", "response", ".", "content", ",", "response", ".", "headers", "[", "\"content-type\"", "]", ")", "_LOGGER", ".", "warning", "(", "\"url not found in param\"", ")", "return", "None" ]
[ 136, 4 ]
[ 148, 19 ]
python
en
['en', 'en', 'en']
True
PushsaferNotificationService.load_from_file
(self, local_path=None)
Load image/document/etc from a local path.
Load image/document/etc from a local path.
def load_from_file(self, local_path=None): """Load image/document/etc from a local path.""" try: if local_path is not None: _LOGGER.debug("Loading image from local path") if self.is_allowed_path(local_path): file_mimetype = mimetypes.guess_type(local_path) _LOGGER.debug("Detected mimetype %s", file_mimetype) with open(local_path, "rb") as binary_file: data = binary_file.read() return self.get_base64(data, file_mimetype[0]) else: _LOGGER.warning("Local path not found in params!") except OSError as error: _LOGGER.error("Can't load from local path: %s", error) return None
[ "def", "load_from_file", "(", "self", ",", "local_path", "=", "None", ")", ":", "try", ":", "if", "local_path", "is", "not", "None", ":", "_LOGGER", ".", "debug", "(", "\"Loading image from local path\"", ")", "if", "self", ".", "is_allowed_path", "(", "local_path", ")", ":", "file_mimetype", "=", "mimetypes", ".", "guess_type", "(", "local_path", ")", "_LOGGER", ".", "debug", "(", "\"Detected mimetype %s\"", ",", "file_mimetype", ")", "with", "open", "(", "local_path", ",", "\"rb\"", ")", "as", "binary_file", ":", "data", "=", "binary_file", ".", "read", "(", ")", "return", "self", ".", "get_base64", "(", "data", ",", "file_mimetype", "[", "0", "]", ")", "else", ":", "_LOGGER", ".", "warning", "(", "\"Local path not found in params!\"", ")", "except", "OSError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Can't load from local path: %s\"", ",", "error", ")", "return", "None" ]
[ 150, 4 ]
[ 166, 19 ]
python
en
['en', 'en', 'en']
True
Conversation.add_user_input
(self, text: str, overwrite: bool = False)
Add a user input to the conversation for the next round. This populates the internal :obj:`new_user_input` field. Args: text (:obj:`str`): The user input for the next conversation round. overwrite (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not existing and unprocessed user input should be overwritten when this function is called.
Add a user input to the conversation for the next round. This populates the internal :obj:`new_user_input` field.
def add_user_input(self, text: str, overwrite: bool = False): """ Add a user input to the conversation for the next round. This populates the internal :obj:`new_user_input` field. Args: text (:obj:`str`): The user input for the next conversation round. overwrite (:obj:`bool`, `optional`, defaults to :obj:`False`): Whether or not existing and unprocessed user input should be overwritten when this function is called. """ if self.new_user_input: if overwrite: logger.warning( 'User input added while unprocessed input was existing: "{}" was overwritten with: "{}".'.format( self.new_user_input, text ) ) self.new_user_input = text else: logger.warning( 'User input added while unprocessed input was existing: "{}" new input ignored: "{}". ' "Set `overwrite` to True to overwrite unprocessed user input".format(self.new_user_input, text) ) else: self.new_user_input = text
[ "def", "add_user_input", "(", "self", ",", "text", ":", "str", ",", "overwrite", ":", "bool", "=", "False", ")", ":", "if", "self", ".", "new_user_input", ":", "if", "overwrite", ":", "logger", ".", "warning", "(", "'User input added while unprocessed input was existing: \"{}\" was overwritten with: \"{}\".'", ".", "format", "(", "self", ".", "new_user_input", ",", "text", ")", ")", "self", ".", "new_user_input", "=", "text", "else", ":", "logger", ".", "warning", "(", "'User input added while unprocessed input was existing: \"{}\" new input ignored: \"{}\". '", "\"Set `overwrite` to True to overwrite unprocessed user input\"", ".", "format", "(", "self", ".", "new_user_input", ",", "text", ")", ")", "else", ":", "self", ".", "new_user_input", "=", "text" ]
[ 83, 4 ]
[ 107, 38 ]
python
en
['en', 'error', 'th']
False
Conversation.mark_processed
(self)
Mark the conversation as processed (moves the content of :obj:`new_user_input` to :obj:`past_user_inputs`) and empties the :obj:`new_user_input` field.
Mark the conversation as processed (moves the content of :obj:`new_user_input` to :obj:`past_user_inputs`) and empties the :obj:`new_user_input` field.
def mark_processed(self): """ Mark the conversation as processed (moves the content of :obj:`new_user_input` to :obj:`past_user_inputs`) and empties the :obj:`new_user_input` field. """ if self.new_user_input: self.past_user_inputs.append(self.new_user_input) self.new_user_input = None
[ "def", "mark_processed", "(", "self", ")", ":", "if", "self", ".", "new_user_input", ":", "self", ".", "past_user_inputs", ".", "append", "(", "self", ".", "new_user_input", ")", "self", ".", "new_user_input", "=", "None" ]
[ 109, 4 ]
[ 116, 34 ]
python
en
['en', 'error', 'th']
False
Conversation.append_response
(self, response: str)
Append a response to the list of generated responses. Args: response (:obj:`str`): The model generated response.
Append a response to the list of generated responses.
def append_response(self, response: str): """ Append a response to the list of generated responses. Args: response (:obj:`str`): The model generated response. """ self.generated_responses.append(response)
[ "def", "append_response", "(", "self", ",", "response", ":", "str", ")", ":", "self", ".", "generated_responses", ".", "append", "(", "response", ")" ]
[ 118, 4 ]
[ 125, 49 ]
python
en
['en', 'error', 'th']
False
Conversation.iter_texts
(self)
Iterates over all blobs of the conversation. Retuns: Iterator of (is_user, text_chunk) in chronological order of the conversation. ``is_user`` is a :obj:`bool`, ``text_chunks`` is a :obj:`str`.
Iterates over all blobs of the conversation.
def iter_texts(self): """ Iterates over all blobs of the conversation. Retuns: Iterator of (is_user, text_chunk) in chronological order of the conversation. ``is_user`` is a :obj:`bool`, ``text_chunks`` is a :obj:`str`. """ for user_input, generated_response in zip(self.past_user_inputs, self.generated_responses): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input
[ "def", "iter_texts", "(", "self", ")", ":", "for", "user_input", ",", "generated_response", "in", "zip", "(", "self", ".", "past_user_inputs", ",", "self", ".", "generated_responses", ")", ":", "yield", "True", ",", "user_input", "yield", "False", ",", "generated_response", "if", "self", ".", "new_user_input", ":", "yield", "True", ",", "self", ".", "new_user_input" ]
[ 127, 4 ]
[ 138, 43 ]
python
en
['en', 'error', 'th']
False
Conversation.__repr__
(self)
Generates a string representation of the conversation. Return: :obj:`str`: Example: Conversation id: 7d15686b-dc94-49f2-9c4b-c9eac6a1f114 user >> Going to the movies tonight - any suggestions? bot >> The Big Lebowski
Generates a string representation of the conversation.
def __repr__(self): """ Generates a string representation of the conversation. Return: :obj:`str`: Example: Conversation id: 7d15686b-dc94-49f2-9c4b-c9eac6a1f114 user >> Going to the movies tonight - any suggestions? bot >> The Big Lebowski """ output = "Conversation id: {} \n".format(self.uuid) for is_user, text in self.iter_texts(): name = "user" if is_user else "bot" output += "{} >> {} \n".format(name, text) return output
[ "def", "__repr__", "(", "self", ")", ":", "output", "=", "\"Conversation id: {} \\n\"", ".", "format", "(", "self", ".", "uuid", ")", "for", "is_user", ",", "text", "in", "self", ".", "iter_texts", "(", ")", ":", "name", "=", "\"user\"", "if", "is_user", "else", "\"bot\"", "output", "+=", "\"{} >> {} \\n\"", ".", "format", "(", "name", ",", "text", ")", "return", "output" ]
[ 140, 4 ]
[ 154, 21 ]
python
en
['en', 'error', 'th']
False
LutronCasetaFlowHandler.__init__
(self)
Initialize a Lutron Caseta flow.
Initialize a Lutron Caseta flow.
def __init__(self): """Initialize a Lutron Caseta flow.""" self.data = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "data", "=", "{", "}" ]
[ 30, 4 ]
[ 32, 22 ]
python
en
['en', 'fr', 'en']
True
LutronCasetaFlowHandler.async_step_import
(self, import_info)
Import a new Caseta bridge as a config entry. This flow is triggered by `async_setup`.
Import a new Caseta bridge as a config entry.
async def async_step_import(self, import_info): """Import a new Caseta bridge as a config entry. This flow is triggered by `async_setup`. """ # Abort if existing entry with matching host exists. host = import_info[CONF_HOST] if any( host == entry.data[CONF_HOST] for entry in self._async_current_entries() ): return self.async_abort(reason=ABORT_REASON_ALREADY_CONFIGURED) # Store the imported config for other steps in this flow to access. self.data[CONF_HOST] = host self.data[CONF_KEYFILE] = import_info[CONF_KEYFILE] self.data[CONF_CERTFILE] = import_info[CONF_CERTFILE] self.data[CONF_CA_CERTS] = import_info[CONF_CA_CERTS] if not await self.async_validate_connectable_bridge_config(): # Ultimately we won't have a dedicated step for import failure, but # in order to keep configuration.yaml-based configs transparently # working without requiring further actions from the user, we don't # display a form at all before creating a config entry in the # default case, so we're only going to show a form in case the # import fails. # This will change in an upcoming release where UI-based config flow # will become the default for the Lutron Caseta integration (which # will require users to go through a confirmation flow for imports). return await self.async_step_import_failed() return self.async_create_entry(title=ENTRY_DEFAULT_TITLE, data=self.data)
[ "async", "def", "async_step_import", "(", "self", ",", "import_info", ")", ":", "# Abort if existing entry with matching host exists.", "host", "=", "import_info", "[", "CONF_HOST", "]", "if", "any", "(", "host", "==", "entry", ".", "data", "[", "CONF_HOST", "]", "for", "entry", "in", "self", ".", "_async_current_entries", "(", ")", ")", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "ABORT_REASON_ALREADY_CONFIGURED", ")", "# Store the imported config for other steps in this flow to access.", "self", ".", "data", "[", "CONF_HOST", "]", "=", "host", "self", ".", "data", "[", "CONF_KEYFILE", "]", "=", "import_info", "[", "CONF_KEYFILE", "]", "self", ".", "data", "[", "CONF_CERTFILE", "]", "=", "import_info", "[", "CONF_CERTFILE", "]", "self", ".", "data", "[", "CONF_CA_CERTS", "]", "=", "import_info", "[", "CONF_CA_CERTS", "]", "if", "not", "await", "self", ".", "async_validate_connectable_bridge_config", "(", ")", ":", "# Ultimately we won't have a dedicated step for import failure, but", "# in order to keep configuration.yaml-based configs transparently", "# working without requiring further actions from the user, we don't", "# display a form at all before creating a config entry in the", "# default case, so we're only going to show a form in case the", "# import fails.", "# This will change in an upcoming release where UI-based config flow", "# will become the default for the Lutron Caseta integration (which", "# will require users to go through a confirmation flow for imports).", "return", "await", "self", ".", "async_step_import_failed", "(", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "ENTRY_DEFAULT_TITLE", ",", "data", "=", "self", ".", "data", ")" ]
[ 34, 4 ]
[ 65, 81 ]
python
en
['en', 'gl', 'en']
True
LutronCasetaFlowHandler.async_step_import_failed
(self, user_input=None)
Make failed import surfaced to user.
Make failed import surfaced to user.
async def async_step_import_failed(self, user_input=None): """Make failed import surfaced to user.""" if user_input is None: return self.async_show_form( step_id=STEP_IMPORT_FAILED, description_placeholders={"host": self.data[CONF_HOST]}, errors={"base": ERROR_CANNOT_CONNECT}, ) return self.async_abort(reason=ABORT_REASON_CANNOT_CONNECT)
[ "async", "def", "async_step_import_failed", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "user_input", "is", "None", ":", "return", "self", ".", "async_show_form", "(", "step_id", "=", "STEP_IMPORT_FAILED", ",", "description_placeholders", "=", "{", "\"host\"", ":", "self", ".", "data", "[", "CONF_HOST", "]", "}", ",", "errors", "=", "{", "\"base\"", ":", "ERROR_CANNOT_CONNECT", "}", ",", ")", "return", "self", ".", "async_abort", "(", "reason", "=", "ABORT_REASON_CANNOT_CONNECT", ")" ]
[ 67, 4 ]
[ 77, 67 ]
python
en
['en', 'en', 'en']
True
LutronCasetaFlowHandler.async_validate_connectable_bridge_config
(self)
Check if we can connect to the bridge with the current config.
Check if we can connect to the bridge with the current config.
async def async_validate_connectable_bridge_config(self): """Check if we can connect to the bridge with the current config.""" try: bridge = Smartbridge.create_tls( hostname=self.data[CONF_HOST], keyfile=self.hass.config.path(self.data[CONF_KEYFILE]), certfile=self.hass.config.path(self.data[CONF_CERTFILE]), ca_certs=self.hass.config.path(self.data[CONF_CA_CERTS]), ) await bridge.connect() if not bridge.is_connected(): return False await bridge.close() return True except Exception: # pylint: disable=broad-except _LOGGER.exception( "Unknown exception while checking connectivity to bridge %s", self.data[CONF_HOST], ) return False
[ "async", "def", "async_validate_connectable_bridge_config", "(", "self", ")", ":", "try", ":", "bridge", "=", "Smartbridge", ".", "create_tls", "(", "hostname", "=", "self", ".", "data", "[", "CONF_HOST", "]", ",", "keyfile", "=", "self", ".", "hass", ".", "config", ".", "path", "(", "self", ".", "data", "[", "CONF_KEYFILE", "]", ")", ",", "certfile", "=", "self", ".", "hass", ".", "config", ".", "path", "(", "self", ".", "data", "[", "CONF_CERTFILE", "]", ")", ",", "ca_certs", "=", "self", ".", "hass", ".", "config", ".", "path", "(", "self", ".", "data", "[", "CONF_CA_CERTS", "]", ")", ",", ")", "await", "bridge", ".", "connect", "(", ")", "if", "not", "bridge", ".", "is_connected", "(", ")", ":", "return", "False", "await", "bridge", ".", "close", "(", ")", "return", "True", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "exception", "(", "\"Unknown exception while checking connectivity to bridge %s\"", ",", "self", ".", "data", "[", "CONF_HOST", "]", ",", ")", "return", "False" ]
[ 79, 4 ]
[ 101, 24 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the blueprint integration.
Set up the blueprint integration.
async def async_setup(hass, config): """Set up the blueprint integration.""" websocket_api.async_setup(hass) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "websocket_api", ".", "async_setup", "(", "hass", ")", "return", "True" ]
[ 15, 0 ]
[ 18, 15 ]
python
en
['en', 'lb', 'en']
True
validate_input
(hass: core.HomeAssistant, data)
Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.
Validate the user input allows us to connect.
async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ latitude = data[CONF_LATITUDE] longitude = data[CONF_LONGITUDE] api_key = data[CONF_API_KEY] station = data.get(CONF_STATION) client_session = async_get_clientsession(hass) ha_api_key = f"{api_key} homeassistant" nws = SimpleNWS(latitude, longitude, ha_api_key, client_session) try: await nws.set_station(station) except aiohttp.ClientError as err: _LOGGER.error("Could not connect: %s", err) raise CannotConnect from err return {"title": nws.station}
[ "async", "def", "validate_input", "(", "hass", ":", "core", ".", "HomeAssistant", ",", "data", ")", ":", "latitude", "=", "data", "[", "CONF_LATITUDE", "]", "longitude", "=", "data", "[", "CONF_LONGITUDE", "]", "api_key", "=", "data", "[", "CONF_API_KEY", "]", "station", "=", "data", ".", "get", "(", "CONF_STATION", ")", "client_session", "=", "async_get_clientsession", "(", "hass", ")", "ha_api_key", "=", "f\"{api_key} homeassistant\"", "nws", "=", "SimpleNWS", "(", "latitude", ",", "longitude", ",", "ha_api_key", ",", "client_session", ")", "try", ":", "await", "nws", ".", "set_station", "(", "station", ")", "except", "aiohttp", ".", "ClientError", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Could not connect: %s\"", ",", "err", ")", "raise", "CannotConnect", "from", "err", "return", "{", "\"title\"", ":", "nws", ".", "station", "}" ]
[ 18, 0 ]
[ 38, 33 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_step_user
(self, user_input=None)
Handle the initial step.
Handle the initial step.
async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: await self.async_set_unique_id( base_unique_id(user_input[CONF_LATITUDE], user_input[CONF_LONGITUDE]) ) self._abort_if_unique_id_configured() try: info = await validate_input(self.hass, user_input) user_input[CONF_STATION] = info["title"] return self.async_create_entry(title=info["title"], data=user_input) except CannotConnect: errors["base"] = "cannot_connect" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" data_schema = vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Required( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Required( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, vol.Optional(CONF_STATION): str, } ) return self.async_show_form( step_id="user", data_schema=data_schema, errors=errors )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "await", "self", ".", "async_set_unique_id", "(", "base_unique_id", "(", "user_input", "[", "CONF_LATITUDE", "]", ",", "user_input", "[", "CONF_LONGITUDE", "]", ")", ")", "self", ".", "_abort_if_unique_id_configured", "(", ")", "try", ":", "info", "=", "await", "validate_input", "(", "self", ".", "hass", ",", "user_input", ")", "user_input", "[", "CONF_STATION", "]", "=", "info", "[", "\"title\"", "]", "return", "self", ".", "async_create_entry", "(", "title", "=", "info", "[", "\"title\"", "]", ",", "data", "=", "user_input", ")", "except", "CannotConnect", ":", "errors", "[", "\"base\"", "]", "=", "\"cannot_connect\"", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "exception", "(", "\"Unexpected exception\"", ")", "errors", "[", "\"base\"", "]", "=", "\"unknown\"", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_API_KEY", ")", ":", "str", ",", "vol", ".", "Required", "(", "CONF_LATITUDE", ",", "default", "=", "self", ".", "hass", ".", "config", ".", "latitude", ")", ":", "cv", ".", "latitude", ",", "vol", ".", "Required", "(", "CONF_LONGITUDE", ",", "default", "=", "self", ".", "hass", ".", "config", ".", "longitude", ")", ":", "cv", ".", "longitude", ",", "vol", ".", "Optional", "(", "CONF_STATION", ")", ":", "str", ",", "}", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "data_schema", ",", "errors", "=", "errors", ")" ]
[ 47, 4 ]
[ 80, 9 ]
python
en
['en', 'en', 'en']
True
Index.get_doc_dicts
(self, doc_ids: np.ndarray)
Returns a list of dictionaries, containing titles and text of the retrieved documents. Args: doc_ids (:obj:`np.ndarray` of shape :obj:`(batch_size, n_docs)`): A tensor of document indices.
Returns a list of dictionaries, containing titles and text of the retrieved documents.
def get_doc_dicts(self, doc_ids: np.ndarray) -> List[dict]: """ Returns a list of dictionaries, containing titles and text of the retrieved documents. Args: doc_ids (:obj:`np.ndarray` of shape :obj:`(batch_size, n_docs)`): A tensor of document indices. """ raise NotImplementedError
[ "def", "get_doc_dicts", "(", "self", ",", "doc_ids", ":", "np", ".", "ndarray", ")", "->", "List", "[", "dict", "]", ":", "raise", "NotImplementedError" ]
[ 55, 4 ]
[ 63, 33 ]
python
en
['en', 'error', 'th']
False
Index.get_top_docs
(self, question_hidden_states: np.ndarray, n_docs=5)
For each query in the batch, retrieves ``n_docs`` documents. Args: question_hidden_states (:obj:`np.ndarray` of shape :obj:`(batch_size, vector_size): An array of query vectors. n_docs (:obj:`int`): The number of docs retrieved per query. Returns: :obj:`np.ndarray` of shape :obj:`(batch_size, n_docs)`: A tensor of indices of retrieved documents. :obj:`np.ndarray` of shape :obj:`(batch_size, vector_size)`: A tensor of vector representations of retrieved documents.
For each query in the batch, retrieves ``n_docs`` documents.
def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> Tuple[np.ndarray, np.ndarray]: """ For each query in the batch, retrieves ``n_docs`` documents. Args: question_hidden_states (:obj:`np.ndarray` of shape :obj:`(batch_size, vector_size): An array of query vectors. n_docs (:obj:`int`): The number of docs retrieved per query. Returns: :obj:`np.ndarray` of shape :obj:`(batch_size, n_docs)`: A tensor of indices of retrieved documents. :obj:`np.ndarray` of shape :obj:`(batch_size, vector_size)`: A tensor of vector representations of retrieved documents. """ raise NotImplementedError
[ "def", "get_top_docs", "(", "self", ",", "question_hidden_states", ":", "np", ".", "ndarray", ",", "n_docs", "=", "5", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "raise", "NotImplementedError" ]
[ 65, 4 ]
[ 80, 33 ]
python
en
['en', 'error', 'th']
False
Index.is_initialized
(self)
Returns :obj:`True` if index is already initialized.
Returns :obj:`True` if index is already initialized.
def is_initialized(self): """ Returns :obj:`True` if index is already initialized. """ raise NotImplementedError
[ "def", "is_initialized", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 82, 4 ]
[ 86, 33 ]
python
en
['en', 'error', 'th']
False
Index.init_index
(self)
A function responsible for loading the index into memory. Should be called only once per training run of a RAG model. E.g. if the model is trained on multiple GPUs in a distributed setup, only one of the workers will load the index.
A function responsible for loading the index into memory. Should be called only once per training run of a RAG model. E.g. if the model is trained on multiple GPUs in a distributed setup, only one of the workers will load the index.
def init_index(self): """ A function responsible for loading the index into memory. Should be called only once per training run of a RAG model. E.g. if the model is trained on multiple GPUs in a distributed setup, only one of the workers will load the index. """ raise NotImplementedError
[ "def", "init_index", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 88, 4 ]
[ 94, 33 ]
python
en
['en', 'error', 'th']
False
RagRetriever.init_retrieval
(self)
Retriever initalization function. It loads the index into memory.
Retriever initalization function. It loads the index into memory.
def init_retrieval(self): """ Retriever initalization function. It loads the index into memory. """ logger.info("initializing retrieval") self.index.init_index()
[ "def", "init_retrieval", "(", "self", ")", ":", "logger", ".", "info", "(", "\"initializing retrieval\"", ")", "self", ".", "index", ".", "init_index", "(", ")" ]
[ 451, 4 ]
[ 457, 31 ]
python
en
['en', 'error', 'th']
False
RagRetriever.postprocess_docs
(self, docs, input_strings, prefix, n_docs, return_tensors=None)
r""" Postprocessing retrieved ``docs`` and combining them with ``input_strings``. Args: docs (:obj:`dict`): Retrieved documents. input_strings (:obj:`str`): Input strings decoded by ``preprocess_query``. prefix (:obj:`str`): Prefix added at the beginning of each input, typically used with T5-based models. Return: :obj:`tuple(tensors)`: a tuple consisting of two elements: contextualized ``input_ids`` and a compatible ``attention_mask``.
r""" Postprocessing retrieved ``docs`` and combining them with ``input_strings``.
def postprocess_docs(self, docs, input_strings, prefix, n_docs, return_tensors=None): r""" Postprocessing retrieved ``docs`` and combining them with ``input_strings``. Args: docs (:obj:`dict`): Retrieved documents. input_strings (:obj:`str`): Input strings decoded by ``preprocess_query``. prefix (:obj:`str`): Prefix added at the beginning of each input, typically used with T5-based models. Return: :obj:`tuple(tensors)`: a tuple consisting of two elements: contextualized ``input_ids`` and a compatible ``attention_mask``. """ def cat_input_and_doc(doc_title, doc_text, input_string, prefix): # TODO(Patrick): if we train more RAG models, I want to put the input first to take advantage of effortless truncation # TODO(piktus): better handling of truncation if doc_title.startswith('"'): doc_title = doc_title[1:] if doc_title.endswith('"'): doc_title = doc_title[:-1] if prefix is None: prefix = "" out = (prefix + doc_title + self.config.title_sep + doc_text + self.config.doc_sep + input_string).replace( " ", " " ) return out rag_input_strings = [ cat_input_and_doc( docs[i]["title"][j], docs[i]["text"][j], input_strings[i], prefix, ) for i in range(len(docs)) for j in range(n_docs) ] contextualized_inputs = self.generator_tokenizer.batch_encode_plus( rag_input_strings, max_length=self.config.max_combined_length, return_tensors=return_tensors, padding="max_length", truncation=True, ) return contextualized_inputs["input_ids"], contextualized_inputs["attention_mask"]
[ "def", "postprocess_docs", "(", "self", ",", "docs", ",", "input_strings", ",", "prefix", ",", "n_docs", ",", "return_tensors", "=", "None", ")", ":", "def", "cat_input_and_doc", "(", "doc_title", ",", "doc_text", ",", "input_string", ",", "prefix", ")", ":", "# TODO(Patrick): if we train more RAG models, I want to put the input first to take advantage of effortless truncation", "# TODO(piktus): better handling of truncation", "if", "doc_title", ".", "startswith", "(", "'\"'", ")", ":", "doc_title", "=", "doc_title", "[", "1", ":", "]", "if", "doc_title", ".", "endswith", "(", "'\"'", ")", ":", "doc_title", "=", "doc_title", "[", ":", "-", "1", "]", "if", "prefix", "is", "None", ":", "prefix", "=", "\"\"", "out", "=", "(", "prefix", "+", "doc_title", "+", "self", ".", "config", ".", "title_sep", "+", "doc_text", "+", "self", ".", "config", ".", "doc_sep", "+", "input_string", ")", ".", "replace", "(", "\" \"", ",", "\" \"", ")", "return", "out", "rag_input_strings", "=", "[", "cat_input_and_doc", "(", "docs", "[", "i", "]", "[", "\"title\"", "]", "[", "j", "]", ",", "docs", "[", "i", "]", "[", "\"text\"", "]", "[", "j", "]", ",", "input_strings", "[", "i", "]", ",", "prefix", ",", ")", "for", "i", "in", "range", "(", "len", "(", "docs", ")", ")", "for", "j", "in", "range", "(", "n_docs", ")", "]", "contextualized_inputs", "=", "self", ".", "generator_tokenizer", ".", "batch_encode_plus", "(", "rag_input_strings", ",", "max_length", "=", "self", ".", "config", ".", "max_combined_length", ",", "return_tensors", "=", "return_tensors", ",", "padding", "=", "\"max_length\"", ",", "truncation", "=", "True", ",", ")", "return", "contextualized_inputs", "[", "\"input_ids\"", "]", ",", "contextualized_inputs", "[", "\"attention_mask\"", "]" ]
[ 459, 4 ]
[ 509, 90 ]
python
cy
['en', 'cy', 'hi']
False
RagRetriever.retrieve
(self, question_hidden_states: np.ndarray, n_docs: int)
Retrieves documents for specified ``question_hidden_states``. Args: question_hidden_states (:obj:`np.ndarray` of shape :obj:`(batch_size, vector_size)`): A batch of query vectors to retrieve with. n_docs (:obj:`int`): The number of docs retrieved per query. Return: :obj:`Tuple[np.ndarray, np.ndarray, List[dict]]`: A tuple with the following objects: - **retrieved_doc_embeds** (:obj:`np.ndarray` of shape :obj:`(batch_size, n_docs, dim)`) -- The retrieval embeddings of the retrieved docs per query. - **doc_ids** (:obj:`np.ndarray` of shape :obj:`(batch_size, n_docs)`) -- The ids of the documents in the index - **doc_dicts** (:obj:`List[dict]`): The :obj:`retrieved_doc_embeds` examples per query.
Retrieves documents for specified ``question_hidden_states``.
def retrieve(self, question_hidden_states: np.ndarray, n_docs: int) -> Tuple[np.ndarray, List[dict]]: """ Retrieves documents for specified ``question_hidden_states``. Args: question_hidden_states (:obj:`np.ndarray` of shape :obj:`(batch_size, vector_size)`): A batch of query vectors to retrieve with. n_docs (:obj:`int`): The number of docs retrieved per query. Return: :obj:`Tuple[np.ndarray, np.ndarray, List[dict]]`: A tuple with the following objects: - **retrieved_doc_embeds** (:obj:`np.ndarray` of shape :obj:`(batch_size, n_docs, dim)`) -- The retrieval embeddings of the retrieved docs per query. - **doc_ids** (:obj:`np.ndarray` of shape :obj:`(batch_size, n_docs)`) -- The ids of the documents in the index - **doc_dicts** (:obj:`List[dict]`): The :obj:`retrieved_doc_embeds` examples per query. """ doc_ids, retrieved_doc_embeds = self._main_retrieve(question_hidden_states, n_docs) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(doc_ids)
[ "def", "retrieve", "(", "self", ",", "question_hidden_states", ":", "np", ".", "ndarray", ",", "n_docs", ":", "int", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "List", "[", "dict", "]", "]", ":", "doc_ids", ",", "retrieved_doc_embeds", "=", "self", ".", "_main_retrieve", "(", "question_hidden_states", ",", "n_docs", ")", "return", "retrieved_doc_embeds", ",", "doc_ids", ",", "self", ".", "index", ".", "get_doc_dicts", "(", "doc_ids", ")" ]
[ 533, 4 ]
[ 554, 79 ]
python
en
['en', 'error', 'th']
False
RagRetriever.__call__
( self, question_input_ids: List[List[int]], question_hidden_states: np.ndarray, prefix=None, n_docs=None, return_tensors=None, )
Retrieves documents for specified :obj:`question_hidden_states`. Args: question_input_ids: (:obj:`List[List[int]]`) batch of input ids question_hidden_states (:obj:`np.ndarray` of shape :obj:`(batch_size, vector_size)`: A batch of query vectors to retrieve with. prefix: (:obj:`str`, `optional`): The prefix used by the generator's tokenizer. n_docs (:obj:`int`, `optional`): The number of docs retrieved per query. return_tensors (:obj:`str` or :class:`~transformers.file_utils.TensorType`, `optional`, defaults to "pt"): If set, will return tensors instead of list of python integers. Acceptable values are: * :obj:`'tf'`: Return TensorFlow :obj:`tf.constant` objects. * :obj:`'pt'`: Return PyTorch :obj:`torch.Tensor` objects. * :obj:`'np'`: Return Numpy :obj:`np.ndarray` objects. Returns: :class:`~transformers.BatchEncoding`: A :class:`~transformers.BatchEncoding` with the following fields: - **context_input_ids** -- List of token ids to be fed to a model. `What are input IDs? <../glossary.html#input-ids>`__ - **context_attention_mask** -- List of indices specifying which tokens should be attended to by the model (when :obj:`return_attention_mask=True` or if `"attention_mask"` is in :obj:`self.model_input_names`). `What are attention masks? <../glossary.html#attention-mask>`__ - **retrieved_doc_embeds** -- List of embeddings of the retrieved documents - **doc_ids** -- List of ids of the retrieved documents
Retrieves documents for specified :obj:`question_hidden_states`.
def __call__( self, question_input_ids: List[List[int]], question_hidden_states: np.ndarray, prefix=None, n_docs=None, return_tensors=None, ) -> BatchEncoding: """ Retrieves documents for specified :obj:`question_hidden_states`. Args: question_input_ids: (:obj:`List[List[int]]`) batch of input ids question_hidden_states (:obj:`np.ndarray` of shape :obj:`(batch_size, vector_size)`: A batch of query vectors to retrieve with. prefix: (:obj:`str`, `optional`): The prefix used by the generator's tokenizer. n_docs (:obj:`int`, `optional`): The number of docs retrieved per query. return_tensors (:obj:`str` or :class:`~transformers.file_utils.TensorType`, `optional`, defaults to "pt"): If set, will return tensors instead of list of python integers. Acceptable values are: * :obj:`'tf'`: Return TensorFlow :obj:`tf.constant` objects. * :obj:`'pt'`: Return PyTorch :obj:`torch.Tensor` objects. * :obj:`'np'`: Return Numpy :obj:`np.ndarray` objects. Returns: :class:`~transformers.BatchEncoding`: A :class:`~transformers.BatchEncoding` with the following fields: - **context_input_ids** -- List of token ids to be fed to a model. `What are input IDs? <../glossary.html#input-ids>`__ - **context_attention_mask** -- List of indices specifying which tokens should be attended to by the model (when :obj:`return_attention_mask=True` or if `"attention_mask"` is in :obj:`self.model_input_names`). `What are attention masks? <../glossary.html#attention-mask>`__ - **retrieved_doc_embeds** -- List of embeddings of the retrieved documents - **doc_ids** -- List of ids of the retrieved documents """ n_docs = n_docs if n_docs is not None else self.n_docs prefix = prefix if prefix is not None else self.config.generator.prefix retrieved_doc_embeds, doc_ids, docs = self.retrieve(question_hidden_states, n_docs) input_strings = self.question_encoder_tokenizer.batch_decode(question_input_ids, skip_special_tokens=True) context_input_ids, context_attention_mask = self.postprocess_docs( docs, input_strings, prefix, n_docs, return_tensors=return_tensors ) return BatchEncoding( { "context_input_ids": context_input_ids, "context_attention_mask": context_attention_mask, "retrieved_doc_embeds": retrieved_doc_embeds, "doc_ids": doc_ids, }, tensor_type=return_tensors, )
[ "def", "__call__", "(", "self", ",", "question_input_ids", ":", "List", "[", "List", "[", "int", "]", "]", ",", "question_hidden_states", ":", "np", ".", "ndarray", ",", "prefix", "=", "None", ",", "n_docs", "=", "None", ",", "return_tensors", "=", "None", ",", ")", "->", "BatchEncoding", ":", "n_docs", "=", "n_docs", "if", "n_docs", "is", "not", "None", "else", "self", ".", "n_docs", "prefix", "=", "prefix", "if", "prefix", "is", "not", "None", "else", "self", ".", "config", ".", "generator", ".", "prefix", "retrieved_doc_embeds", ",", "doc_ids", ",", "docs", "=", "self", ".", "retrieve", "(", "question_hidden_states", ",", "n_docs", ")", "input_strings", "=", "self", ".", "question_encoder_tokenizer", ".", "batch_decode", "(", "question_input_ids", ",", "skip_special_tokens", "=", "True", ")", "context_input_ids", ",", "context_attention_mask", "=", "self", ".", "postprocess_docs", "(", "docs", ",", "input_strings", ",", "prefix", ",", "n_docs", ",", "return_tensors", "=", "return_tensors", ")", "return", "BatchEncoding", "(", "{", "\"context_input_ids\"", ":", "context_input_ids", ",", "\"context_attention_mask\"", ":", "context_attention_mask", ",", "\"retrieved_doc_embeds\"", ":", "retrieved_doc_embeds", ",", "\"doc_ids\"", ":", "doc_ids", ",", "}", ",", "tensor_type", "=", "return_tensors", ",", ")" ]
[ 556, 4 ]
[ 615, 9 ]
python
en
['en', 'error', 'th']
False
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the PCA switch platform.
Set up the PCA switch platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the PCA switch platform.""" if discovery_info is None: return serial_device = discovery_info["device"] try: pca = pypca.PCA(serial_device) pca.open() entities = [SmartPlugSwitch(pca, device) for device in pca.get_devices()] add_entities(entities, True) except SerialException as exc: _LOGGER.warning("Unable to open serial port: %s", exc) return hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, pca.close) pca.start_scan()
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "if", "discovery_info", "is", "None", ":", "return", "serial_device", "=", "discovery_info", "[", "\"device\"", "]", "try", ":", "pca", "=", "pypca", ".", "PCA", "(", "serial_device", ")", "pca", ".", "open", "(", ")", "entities", "=", "[", "SmartPlugSwitch", "(", "pca", ",", "device", ")", "for", "device", "in", "pca", ".", "get_devices", "(", ")", "]", "add_entities", "(", "entities", ",", "True", ")", "except", "SerialException", "as", "exc", ":", "_LOGGER", ".", "warning", "(", "\"Unable to open serial port: %s\"", ",", "exc", ")", "return", "hass", ".", "bus", ".", "listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "pca", ".", "close", ")", "pca", ".", "start_scan", "(", ")" ]
[ 16, 0 ]
[ 37, 20 ]
python
en
['en', 'zh', 'en']
True
SmartPlugSwitch.__init__
(self, pca, device_id)
Initialize the switch.
Initialize the switch.
def __init__(self, pca, device_id): """Initialize the switch.""" self._device_id = device_id self._name = "PCA 301" self._state = None self._available = True self._emeter_params = {} self._pca = pca
[ "def", "__init__", "(", "self", ",", "pca", ",", "device_id", ")", ":", "self", ".", "_device_id", "=", "device_id", "self", ".", "_name", "=", "\"PCA 301\"", "self", ".", "_state", "=", "None", "self", ".", "_available", "=", "True", "self", ".", "_emeter_params", "=", "{", "}", "self", ".", "_pca", "=", "pca" ]
[ 43, 4 ]
[ 50, 23 ]
python
en
['en', 'en', 'en']
True
SmartPlugSwitch.name
(self)
Return the name of the Smart Plug, if any.
Return the name of the Smart Plug, if any.
def name(self): """Return the name of the Smart Plug, if any.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 53, 4 ]
[ 55, 25 ]
python
en
['en', 'en', 'en']
True
SmartPlugSwitch.available
(self)
Return if switch is available.
Return if switch is available.
def available(self) -> bool: """Return if switch is available.""" return self._available
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_available" ]
[ 58, 4 ]
[ 60, 30 ]
python
en
['en', 'en', 'en']
True
SmartPlugSwitch.is_on
(self)
Return true if switch is on.
Return true if switch is on.
def is_on(self): """Return true if switch is on.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 63, 4 ]
[ 65, 26 ]
python
en
['en', 'fy', 'en']
True
SmartPlugSwitch.turn_on
(self, **kwargs)
Turn the switch on.
Turn the switch on.
def turn_on(self, **kwargs): """Turn the switch on.""" self._pca.turn_on(self._device_id)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_pca", ".", "turn_on", "(", "self", ".", "_device_id", ")" ]
[ 67, 4 ]
[ 69, 42 ]
python
en
['en', 'en', 'en']
True
SmartPlugSwitch.turn_off
(self, **kwargs)
Turn the switch off.
Turn the switch off.
def turn_off(self, **kwargs): """Turn the switch off.""" self._pca.turn_off(self._device_id)
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_pca", ".", "turn_off", "(", "self", ".", "_device_id", ")" ]
[ 71, 4 ]
[ 73, 43 ]
python
en
['en', 'en', 'en']
True
SmartPlugSwitch.device_state_attributes
(self)
Return the state attributes of the device.
Return the state attributes of the device.
def device_state_attributes(self): """Return the state attributes of the device.""" return self._emeter_params
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_emeter_params" ]
[ 76, 4 ]
[ 78, 34 ]
python
en
['en', 'en', 'en']
True
SmartPlugSwitch.update
(self)
Update the PCA switch's state.
Update the PCA switch's state.
def update(self): """Update the PCA switch's state.""" try: self._emeter_params[ ATTR_CURRENT_POWER_W ] = f"{self._pca.get_current_power(self._device_id):.1f}" self._emeter_params[ ATTR_TOTAL_ENERGY_KWH ] = f"{self._pca.get_total_consumption(self._device_id):.2f}" self._available = True self._state = self._pca.get_state(self._device_id) except (OSError) as ex: if self._available: _LOGGER.warning("Could not read state for %s: %s", self.name, ex) self._available = False
[ "def", "update", "(", "self", ")", ":", "try", ":", "self", ".", "_emeter_params", "[", "ATTR_CURRENT_POWER_W", "]", "=", "f\"{self._pca.get_current_power(self._device_id):.1f}\"", "self", ".", "_emeter_params", "[", "ATTR_TOTAL_ENERGY_KWH", "]", "=", "f\"{self._pca.get_total_consumption(self._device_id):.2f}\"", "self", ".", "_available", "=", "True", "self", ".", "_state", "=", "self", ".", "_pca", ".", "get_state", "(", "self", ".", "_device_id", ")", "except", "(", "OSError", ")", "as", "ex", ":", "if", "self", ".", "_available", ":", "_LOGGER", ".", "warning", "(", "\"Could not read state for %s: %s\"", ",", "self", ".", "name", ",", "ex", ")", "self", ".", "_available", "=", "False" ]
[ 80, 4 ]
[ 96, 39 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities )
Set up the HomematicIP Cloud binary sensor from a config entry.
Set up the HomematicIP Cloud binary sensor from a config entry.
async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the HomematicIP Cloud binary sensor from a config entry.""" hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] entities = [HomematicipCloudConnectionSensor(hap)] for device in hap.home.devices: if isinstance(device, AsyncAccelerationSensor): entities.append(HomematicipAccelerationSensor(hap, device)) if isinstance(device, AsyncTiltVibrationSensor): entities.append(HomematicipTiltVibrationSensor(hap, device)) if isinstance(device, AsyncWiredInput32): for channel in range(1, 33): entities.append( HomematicipMultiContactInterface(hap, device, channel=channel) ) elif isinstance( device, (AsyncContactInterface, AsyncFullFlushContactInterface) ): entities.append(HomematicipContactInterface(hap, device)) if isinstance( device, (AsyncShutterContact, AsyncShutterContactMagnetic), ): entities.append(HomematicipShutterContact(hap, device)) if isinstance(device, AsyncRotaryHandleSensor): entities.append(HomematicipShutterContact(hap, device, True)) if isinstance( device, ( AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, ), ): entities.append(HomematicipMotionDetector(hap, device)) if isinstance(device, AsyncPluggableMainsFailureSurveillance): entities.append( HomematicipPluggableMainsFailureSurveillanceSensor(hap, device) ) if isinstance(device, AsyncPresenceDetectorIndoor): entities.append(HomematicipPresenceDetector(hap, device)) if isinstance(device, AsyncSmokeDetector): entities.append(HomematicipSmokeDetector(hap, device)) if isinstance(device, AsyncWaterSensor): entities.append(HomematicipWaterDetector(hap, device)) if isinstance(device, (AsyncWeatherSensorPlus, AsyncWeatherSensorPro)): entities.append(HomematicipRainSensor(hap, device)) if isinstance( device, (AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro) ): entities.append(HomematicipStormSensor(hap, device)) entities.append(HomematicipSunshineSensor(hap, device)) if isinstance(device, AsyncDevice) and device.lowBat is not None: entities.append(HomematicipBatterySensor(hap, device)) for group in hap.home.groups: if isinstance(group, AsyncSecurityGroup): entities.append(HomematicipSecuritySensorGroup(hap, device=group)) elif isinstance(group, AsyncSecurityZoneGroup): entities.append(HomematicipSecurityZoneSensorGroup(hap, device=group)) if entities: async_add_entities(entities)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "config_entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "hap", "=", "hass", ".", "data", "[", "HMIPC_DOMAIN", "]", "[", "config_entry", ".", "unique_id", "]", "entities", "=", "[", "HomematicipCloudConnectionSensor", "(", "hap", ")", "]", "for", "device", "in", "hap", ".", "home", ".", "devices", ":", "if", "isinstance", "(", "device", ",", "AsyncAccelerationSensor", ")", ":", "entities", ".", "append", "(", "HomematicipAccelerationSensor", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "AsyncTiltVibrationSensor", ")", ":", "entities", ".", "append", "(", "HomematicipTiltVibrationSensor", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "AsyncWiredInput32", ")", ":", "for", "channel", "in", "range", "(", "1", ",", "33", ")", ":", "entities", ".", "append", "(", "HomematicipMultiContactInterface", "(", "hap", ",", "device", ",", "channel", "=", "channel", ")", ")", "elif", "isinstance", "(", "device", ",", "(", "AsyncContactInterface", ",", "AsyncFullFlushContactInterface", ")", ")", ":", "entities", ".", "append", "(", "HomematicipContactInterface", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "(", "AsyncShutterContact", ",", "AsyncShutterContactMagnetic", ")", ",", ")", ":", "entities", ".", "append", "(", "HomematicipShutterContact", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "AsyncRotaryHandleSensor", ")", ":", "entities", ".", "append", "(", "HomematicipShutterContact", "(", "hap", ",", "device", ",", "True", ")", ")", "if", "isinstance", "(", "device", ",", "(", "AsyncMotionDetectorIndoor", ",", "AsyncMotionDetectorOutdoor", ",", "AsyncMotionDetectorPushButton", ",", ")", ",", ")", ":", "entities", ".", "append", "(", "HomematicipMotionDetector", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "AsyncPluggableMainsFailureSurveillance", ")", ":", "entities", ".", "append", "(", "HomematicipPluggableMainsFailureSurveillanceSensor", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "AsyncPresenceDetectorIndoor", ")", ":", "entities", ".", "append", "(", "HomematicipPresenceDetector", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "AsyncSmokeDetector", ")", ":", "entities", ".", "append", "(", "HomematicipSmokeDetector", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "AsyncWaterSensor", ")", ":", "entities", ".", "append", "(", "HomematicipWaterDetector", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "(", "AsyncWeatherSensorPlus", ",", "AsyncWeatherSensorPro", ")", ")", ":", "entities", ".", "append", "(", "HomematicipRainSensor", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "(", "AsyncWeatherSensor", ",", "AsyncWeatherSensorPlus", ",", "AsyncWeatherSensorPro", ")", ")", ":", "entities", ".", "append", "(", "HomematicipStormSensor", "(", "hap", ",", "device", ")", ")", "entities", ".", "append", "(", "HomematicipSunshineSensor", "(", "hap", ",", "device", ")", ")", "if", "isinstance", "(", "device", ",", "AsyncDevice", ")", "and", "device", ".", "lowBat", "is", "not", "None", ":", "entities", ".", "append", "(", "HomematicipBatterySensor", "(", "hap", ",", "device", ")", ")", "for", "group", "in", "hap", ".", "home", ".", "groups", ":", "if", "isinstance", "(", "group", ",", "AsyncSecurityGroup", ")", ":", "entities", ".", "append", "(", "HomematicipSecuritySensorGroup", "(", "hap", ",", "device", "=", "group", ")", ")", "elif", "isinstance", "(", "group", ",", "AsyncSecurityZoneGroup", ")", ":", "entities", ".", "append", "(", "HomematicipSecurityZoneSensorGroup", "(", "hap", ",", "device", "=", "group", ")", ")", "if", "entities", ":", "async_add_entities", "(", "entities", ")" ]
[ 77, 0 ]
[ 140, 36 ]
python
en
['en', 'en', 'en']
True
HomematicipCloudConnectionSensor.__init__
(self, hap: HomematicipHAP)
Initialize the cloud connection sensor.
Initialize the cloud connection sensor.
def __init__(self, hap: HomematicipHAP) -> None: """Initialize the cloud connection sensor.""" super().__init__(hap, hap.home)
[ "def", "__init__", "(", "self", ",", "hap", ":", "HomematicipHAP", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "hap", ",", "hap", ".", "home", ")" ]
[ 146, 4 ]
[ 148, 39 ]
python
en
['en', 'fr', 'en']
True
HomematicipCloudConnectionSensor.name
(self)
Return the name cloud connection entity.
Return the name cloud connection entity.
def name(self) -> str: """Return the name cloud connection entity.""" name = "Cloud Connection" # Add a prefix to the name if the homematic ip home has a name. return name if not self._home.name else f"{self._home.name} {name}"
[ "def", "name", "(", "self", ")", "->", "str", ":", "name", "=", "\"Cloud Connection\"", "# Add a prefix to the name if the homematic ip home has a name.", "return", "name", "if", "not", "self", ".", "_home", ".", "name", "else", "f\"{self._home.name} {name}\"" ]
[ 151, 4 ]
[ 156, 75 ]
python
en
['en', 'en', 'en']
True
HomematicipCloudConnectionSensor.device_info
(self)
Return device specific attributes.
Return device specific attributes.
def device_info(self) -> Dict[str, Any]: """Return device specific attributes.""" # Adds a sensor to the existing HAP device return { "identifiers": { # Serial numbers of Homematic IP device (HMIPC_DOMAIN, self._home.id) } }
[ "def", "device_info", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# Adds a sensor to the existing HAP device", "return", "{", "\"identifiers\"", ":", "{", "# Serial numbers of Homematic IP device", "(", "HMIPC_DOMAIN", ",", "self", ".", "_home", ".", "id", ")", "}", "}" ]
[ 159, 4 ]
[ 167, 9 ]
python
en
['fr', 'it', 'en']
False
HomematicipCloudConnectionSensor.icon
(self)
Return the icon of the access point entity.
Return the icon of the access point entity.
def icon(self) -> str: """Return the icon of the access point entity.""" return ( "mdi:access-point-network" if self._home.connected else "mdi:access-point-network-off" )
[ "def", "icon", "(", "self", ")", "->", "str", ":", "return", "(", "\"mdi:access-point-network\"", "if", "self", ".", "_home", ".", "connected", "else", "\"mdi:access-point-network-off\"", ")" ]
[ 170, 4 ]
[ 176, 9 ]
python
en
['en', 'en', 'en']
True
HomematicipCloudConnectionSensor.is_on
(self)
Return true if hap is connected to cloud.
Return true if hap is connected to cloud.
def is_on(self) -> bool: """Return true if hap is connected to cloud.""" return self._home.connected
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_home", ".", "connected" ]
[ 179, 4 ]
[ 181, 35 ]
python
en
['en', 'en', 'en']
True
HomematicipCloudConnectionSensor.available
(self)
Sensor is always available.
Sensor is always available.
def available(self) -> bool: """Sensor is always available.""" return True
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "True" ]
[ 184, 4 ]
[ 186, 19 ]
python
en
['en', 'en', 'en']
True
HomematicipBaseActionSensor.device_class
(self)
Return the class of this sensor.
Return the class of this sensor.
def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOVING
[ "def", "device_class", "(", "self", ")", "->", "str", ":", "return", "DEVICE_CLASS_MOVING" ]
[ 193, 4 ]
[ 195, 34 ]
python
en
['en', 'en', 'en']
True
HomematicipBaseActionSensor.is_on
(self)
Return true if acceleration is detected.
Return true if acceleration is detected.
def is_on(self) -> bool: """Return true if acceleration is detected.""" return self._device.accelerationSensorTriggered
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_device", ".", "accelerationSensorTriggered" ]
[ 198, 4 ]
[ 200, 55 ]
python
en
['en', 'en', 'en']
True
HomematicipBaseActionSensor.device_state_attributes
(self)
Return the state attributes of the acceleration sensor.
Return the state attributes of the acceleration sensor.
def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the acceleration sensor.""" state_attr = super().device_state_attributes for attr, attr_key in SAM_DEVICE_ATTRIBUTES.items(): attr_value = getattr(self._device, attr, None) if attr_value: state_attr[attr_key] = attr_value return state_attr
[ "def", "device_state_attributes", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "state_attr", "=", "super", "(", ")", ".", "device_state_attributes", "for", "attr", ",", "attr_key", "in", "SAM_DEVICE_ATTRIBUTES", ".", "items", "(", ")", ":", "attr_value", "=", "getattr", "(", "self", ".", "_device", ",", "attr", ",", "None", ")", "if", "attr_value", ":", "state_attr", "[", "attr_key", "]", "=", "attr_value", "return", "state_attr" ]
[ 203, 4 ]
[ 212, 25 ]
python
en
['en', 'en', 'en']
True
HomematicipMultiContactInterface.__init__
(self, hap: HomematicipHAP, device, channel: int)
Initialize the multi contact entity.
Initialize the multi contact entity.
def __init__(self, hap: HomematicipHAP, device, channel: int) -> None: """Initialize the multi contact entity.""" super().__init__(hap, device, channel=channel)
[ "def", "__init__", "(", "self", ",", "hap", ":", "HomematicipHAP", ",", "device", ",", "channel", ":", "int", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "hap", ",", "device", ",", "channel", "=", "channel", ")" ]
[ 226, 4 ]
[ 228, 54 ]
python
en
['en', 'en', 'en']
True
HomematicipMultiContactInterface.device_class
(self)
Return the class of this sensor.
Return the class of this sensor.
def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_OPENING
[ "def", "device_class", "(", "self", ")", "->", "str", ":", "return", "DEVICE_CLASS_OPENING" ]
[ 231, 4 ]
[ 233, 35 ]
python
en
['en', 'en', 'en']
True
HomematicipMultiContactInterface.is_on
(self)
Return true if the contact interface is on/open.
Return true if the contact interface is on/open.
def is_on(self) -> bool: """Return true if the contact interface is on/open.""" if self._device.functionalChannels[self._channel].windowState is None: return None return ( self._device.functionalChannels[self._channel].windowState != WindowState.CLOSED )
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_device", ".", "functionalChannels", "[", "self", ".", "_channel", "]", ".", "windowState", "is", "None", ":", "return", "None", "return", "(", "self", ".", "_device", ".", "functionalChannels", "[", "self", ".", "_channel", "]", ".", "windowState", "!=", "WindowState", ".", "CLOSED", ")" ]
[ 236, 4 ]
[ 243, 9 ]
python
en
['en', 'en', 'en']
True
HomematicipContactInterface.device_class
(self)
Return the class of this sensor.
Return the class of this sensor.
def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_OPENING
[ "def", "device_class", "(", "self", ")", "->", "str", ":", "return", "DEVICE_CLASS_OPENING" ]
[ 250, 4 ]
[ 252, 35 ]
python
en
['en', 'en', 'en']
True
HomematicipContactInterface.is_on
(self)
Return true if the contact interface is on/open.
Return true if the contact interface is on/open.
def is_on(self) -> bool: """Return true if the contact interface is on/open.""" if self._device.windowState is None: return None return self._device.windowState != WindowState.CLOSED
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_device", ".", "windowState", "is", "None", ":", "return", "None", "return", "self", ".", "_device", ".", "windowState", "!=", "WindowState", ".", "CLOSED" ]
[ 255, 4 ]
[ 259, 61 ]
python
en
['en', 'en', 'en']
True
HomematicipShutterContact.__init__
( self, hap: HomematicipHAP, device, has_additional_state: bool = False )
Initialize the shutter contact.
Initialize the shutter contact.
def __init__( self, hap: HomematicipHAP, device, has_additional_state: bool = False ) -> None: """Initialize the shutter contact.""" super().__init__(hap, device) self.has_additional_state = has_additional_state
[ "def", "__init__", "(", "self", ",", "hap", ":", "HomematicipHAP", ",", "device", ",", "has_additional_state", ":", "bool", "=", "False", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "hap", ",", "device", ")", "self", ".", "has_additional_state", "=", "has_additional_state" ]
[ 265, 4 ]
[ 270, 56 ]
python
en
['en', 'en', 'en']
True
HomematicipShutterContact.device_class
(self)
Return the class of this sensor.
Return the class of this sensor.
def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_DOOR
[ "def", "device_class", "(", "self", ")", "->", "str", ":", "return", "DEVICE_CLASS_DOOR" ]
[ 273, 4 ]
[ 275, 32 ]
python
en
['en', 'en', 'en']
True
HomematicipShutterContact.is_on
(self)
Return true if the shutter contact is on/open.
Return true if the shutter contact is on/open.
def is_on(self) -> bool: """Return true if the shutter contact is on/open.""" if self._device.windowState is None: return None return self._device.windowState != WindowState.CLOSED
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_device", ".", "windowState", "is", "None", ":", "return", "None", "return", "self", ".", "_device", ".", "windowState", "!=", "WindowState", ".", "CLOSED" ]
[ 278, 4 ]
[ 282, 61 ]
python
en
['en', 'en', 'en']
True
HomematicipShutterContact.device_state_attributes
(self)
Return the state attributes of the Shutter Contact.
Return the state attributes of the Shutter Contact.
def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the Shutter Contact.""" state_attr = super().device_state_attributes if self.has_additional_state: window_state = getattr(self._device, "windowState", None) if window_state and window_state != WindowState.CLOSED: state_attr[ATTR_WINDOW_STATE] = window_state return state_attr
[ "def", "device_state_attributes", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "state_attr", "=", "super", "(", ")", ".", "device_state_attributes", "if", "self", ".", "has_additional_state", ":", "window_state", "=", "getattr", "(", "self", ".", "_device", ",", "\"windowState\"", ",", "None", ")", "if", "window_state", "and", "window_state", "!=", "WindowState", ".", "CLOSED", ":", "state_attr", "[", "ATTR_WINDOW_STATE", "]", "=", "window_state", "return", "state_attr" ]
[ 285, 4 ]
[ 294, 25 ]
python
en
['en', 'en', 'en']
True