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
PhilipsTVMediaPlayer.media_channel
(self)
Get current channel if it's a channel.
Get current channel if it's a channel.
def media_channel(self): """Get current channel if it's a channel.""" if self.media_content_type == MEDIA_TYPE_CHANNEL: return self._channels.get(self._tv.channel_id) return None
[ "def", "media_channel", "(", "self", ")", ":", "if", "self", ".", "media_content_type", "==", "MEDIA_TYPE_CHANNEL", ":", "return", "self", ".", "_channels", ".", "get", "(", "self", ".", "_tv", ".", "channel_id", ")", "return", "None" ]
[ 235, 4 ]
[ 239, 19 ]
python
en
['en', 'en', 'en']
True
PhilipsTVMediaPlayer.media_title
(self)
Title of current playing media.
Title of current playing media.
def media_title(self): """Title of current playing media.""" if self.media_content_type == MEDIA_TYPE_CHANNEL: return self._channels.get(self._tv.channel_id) return self._sources.get(self._tv.source_id)
[ "def", "media_title", "(", "self", ")", ":", "if", "self", ".", "media_content_type", "==", "MEDIA_TYPE_CHANNEL", ":", "return", "self", ".", "_channels", ".", "get", "(", "self", ".", "_tv", ".", "channel_id", ")", "return", "self", ".", "_sources", ".", "get", "(", "self", ".", "_tv", ".", "source_id", ")" ]
[ 242, 4 ]
[ 246, 52 ]
python
en
['en', 'en', 'en']
True
PhilipsTVMediaPlayer.media_content_type
(self)
Return content type of playing media.
Return content type of playing media.
def media_content_type(self): """Return content type of playing media.""" if self._tv.source_id == "tv" or self._tv.source_id == "11": return MEDIA_TYPE_CHANNEL if self._tv.source_id is None and self._tv.channels: return MEDIA_TYPE_CHANNEL return None
[ "def", "media_content_type", "(", "self", ")", ":", "if", "self", ".", "_tv", ".", "source_id", "==", "\"tv\"", "or", "self", ".", "_tv", ".", "source_id", "==", "\"11\"", ":", "return", "MEDIA_TYPE_CHANNEL", "if", "self", ".", "_tv", ".", "source_id", "is", "None", "and", "self", ".", "_tv", ".", "channels", ":", "return", "MEDIA_TYPE_CHANNEL", "return", "None" ]
[ 249, 4 ]
[ 255, 19 ]
python
en
['en', 'en', 'en']
True
PhilipsTVMediaPlayer.media_content_id
(self)
Content type of current playing media.
Content type of current playing media.
def media_content_id(self): """Content type of current playing media.""" if self.media_content_type == MEDIA_TYPE_CHANNEL: return self._channels.get(self._tv.channel_id) return None
[ "def", "media_content_id", "(", "self", ")", ":", "if", "self", ".", "media_content_type", "==", "MEDIA_TYPE_CHANNEL", ":", "return", "self", ".", "_channels", ".", "get", "(", "self", ".", "_tv", ".", "channel_id", ")", "return", "None" ]
[ 258, 4 ]
[ 262, 19 ]
python
en
['en', 'en', 'en']
True
PhilipsTVMediaPlayer.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return {"channel_list": list(self._channels.values())}
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "\"channel_list\"", ":", "list", "(", "self", ".", "_channels", ".", "values", "(", ")", ")", "}" ]
[ 265, 4 ]
[ 267, 62 ]
python
en
['en', 'en', 'en']
True
PhilipsTVMediaPlayer.play_media
(self, media_type, media_id, **kwargs)
Play a piece of media.
Play a piece of media.
def play_media(self, media_type, media_id, **kwargs): """Play a piece of media.""" _LOGGER.debug("Call play media type <%s>, Id <%s>", media_type, media_id) if media_type == MEDIA_TYPE_CHANNEL: channel_id = _inverted(self._channels).get(media_id) if channel_id: self._tv.setChannel(channel_id) self._update_soon(DELAY_ACTION_DEFAULT) else: _LOGGER.error("Unable to find channel <%s>", media_id) else: _LOGGER.error("Unsupported media type <%s>", media_type)
[ "def", "play_media", "(", "self", ",", "media_type", ",", "media_id", ",", "*", "*", "kwargs", ")", ":", "_LOGGER", ".", "debug", "(", "\"Call play media type <%s>, Id <%s>\"", ",", "media_type", ",", "media_id", ")", "if", "media_type", "==", "MEDIA_TYPE_CHANNEL", ":", "channel_id", "=", "_inverted", "(", "self", ".", "_channels", ")", ".", "get", "(", "media_id", ")", "if", "channel_id", ":", "self", ".", "_tv", ".", "setChannel", "(", "channel_id", ")", "self", ".", "_update_soon", "(", "DELAY_ACTION_DEFAULT", ")", "else", ":", "_LOGGER", ".", "error", "(", "\"Unable to find channel <%s>\"", ",", "media_id", ")", "else", ":", "_LOGGER", ".", "error", "(", "\"Unsupported media type <%s>\"", ",", "media_type", ")" ]
[ 269, 4 ]
[ 281, 68 ]
python
en
['en', 'en', 'en']
True
PhilipsTVMediaPlayer.async_browse_media
(self, media_content_type=None, media_content_id=None)
Implement the websocket media browsing helper.
Implement the websocket media browsing helper.
async def async_browse_media(self, media_content_type=None, media_content_id=None): """Implement the websocket media browsing helper.""" if media_content_id not in (None, ""): raise BrowseError( f"Media not found: {media_content_type} / {media_content_id}" ) return BrowseMedia( title="Channels", media_class=MEDIA_CLASS_DIRECTORY, media_content_id="", media_content_type=MEDIA_TYPE_CHANNELS, can_play=False, can_expand=True, children=[ BrowseMedia( title=channel, media_class=MEDIA_CLASS_CHANNEL, media_content_id=channel, media_content_type=MEDIA_TYPE_CHANNEL, can_play=True, can_expand=False, ) for channel in self._channels.values() ], )
[ "async", "def", "async_browse_media", "(", "self", ",", "media_content_type", "=", "None", ",", "media_content_id", "=", "None", ")", ":", "if", "media_content_id", "not", "in", "(", "None", ",", "\"\"", ")", ":", "raise", "BrowseError", "(", "f\"Media not found: {media_content_type} / {media_content_id}\"", ")", "return", "BrowseMedia", "(", "title", "=", "\"Channels\"", ",", "media_class", "=", "MEDIA_CLASS_DIRECTORY", ",", "media_content_id", "=", "\"\"", ",", "media_content_type", "=", "MEDIA_TYPE_CHANNELS", ",", "can_play", "=", "False", ",", "can_expand", "=", "True", ",", "children", "=", "[", "BrowseMedia", "(", "title", "=", "channel", ",", "media_class", "=", "MEDIA_CLASS_CHANNEL", ",", "media_content_id", "=", "channel", ",", "media_content_type", "=", "MEDIA_TYPE_CHANNEL", ",", "can_play", "=", "True", ",", "can_expand", "=", "False", ",", ")", "for", "channel", "in", "self", ".", "_channels", ".", "values", "(", ")", "]", ",", ")" ]
[ 283, 4 ]
[ 308, 9 ]
python
en
['en', 'af', 'en']
True
PhilipsTVMediaPlayer.update
(self)
Get the latest data and update device state.
Get the latest data and update device state.
def update(self): """Get the latest data and update device state.""" self._tv.update() self._sources = { srcid: source["name"] or f"Source {srcid}" for srcid, source in (self._tv.sources or {}).items() } self._channels = { chid: channel["name"] for chid, channel in (self._tv.channels or {}).items() }
[ "def", "update", "(", "self", ")", ":", "self", ".", "_tv", ".", "update", "(", ")", "self", ".", "_sources", "=", "{", "srcid", ":", "source", "[", "\"name\"", "]", "or", "f\"Source {srcid}\"", "for", "srcid", ",", "source", "in", "(", "self", ".", "_tv", ".", "sources", "or", "{", "}", ")", ".", "items", "(", ")", "}", "self", ".", "_channels", "=", "{", "chid", ":", "channel", "[", "\"name\"", "]", "for", "chid", ",", "channel", "in", "(", "self", ".", "_tv", ".", "channels", "or", "{", "}", ")", ".", "items", "(", ")", "}" ]
[ 310, 4 ]
[ 321, 9 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable )
Set up RainMachine sensors based on a config entry.
Set up RainMachine sensors based on a config entry.
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable ) -> None: """Set up RainMachine sensors based on a config entry.""" controller = hass.data[DOMAIN][DATA_CONTROLLER][entry.entry_id] coordinators = hass.data[DOMAIN][DATA_COORDINATOR][entry.entry_id] @callback def async_get_sensor(api_category: str) -> partial: """Generate the appropriate sensor object for an API category.""" if api_category == DATA_PROVISION_SETTINGS: return partial( ProvisionSettingsSensor, coordinators[DATA_PROVISION_SETTINGS], ) return partial( UniversalRestrictionsSensor, coordinators[DATA_RESTRICTIONS_UNIVERSAL], ) async_add_entities( [ async_get_sensor(api_category)( controller, sensor_type, name, icon, unit, device_class, enabled_by_default, ) for ( sensor_type, (name, icon, unit, device_class, enabled_by_default, api_category), ) in SENSORS.items() ] )
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ":", "Callable", ")", "->", "None", ":", "controller", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_CONTROLLER", "]", "[", "entry", ".", "entry_id", "]", "coordinators", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_COORDINATOR", "]", "[", "entry", ".", "entry_id", "]", "@", "callback", "def", "async_get_sensor", "(", "api_category", ":", "str", ")", "->", "partial", ":", "\"\"\"Generate the appropriate sensor object for an API category.\"\"\"", "if", "api_category", "==", "DATA_PROVISION_SETTINGS", ":", "return", "partial", "(", "ProvisionSettingsSensor", ",", "coordinators", "[", "DATA_PROVISION_SETTINGS", "]", ",", ")", "return", "partial", "(", "UniversalRestrictionsSensor", ",", "coordinators", "[", "DATA_RESTRICTIONS_UNIVERSAL", "]", ",", ")", "async_add_entities", "(", "[", "async_get_sensor", "(", "api_category", ")", "(", "controller", ",", "sensor_type", ",", "name", ",", "icon", ",", "unit", ",", "device_class", ",", "enabled_by_default", ",", ")", "for", "(", "sensor_type", ",", "(", "name", ",", "icon", ",", "unit", ",", "device_class", ",", "enabled_by_default", ",", "api_category", ")", ",", ")", "in", "SENSORS", ".", "items", "(", ")", "]", ")" ]
[ 70, 0 ]
[ 107, 5 ]
python
en
['en', 'en', 'en']
True
RainMachineSensor.__init__
( self, coordinator: DataUpdateCoordinator, controller: Controller, sensor_type: str, name: str, icon: str, unit: str, device_class: str, enabled_by_default: bool, )
Initialize.
Initialize.
def __init__( self, coordinator: DataUpdateCoordinator, controller: Controller, sensor_type: str, name: str, icon: str, unit: str, device_class: str, enabled_by_default: bool, ) -> None: """Initialize.""" super().__init__(coordinator, controller) self._device_class = device_class self._enabled_by_default = enabled_by_default self._icon = icon self._name = name self._sensor_type = sensor_type self._state = None self._unit = unit
[ "def", "__init__", "(", "self", ",", "coordinator", ":", "DataUpdateCoordinator", ",", "controller", ":", "Controller", ",", "sensor_type", ":", "str", ",", "name", ":", "str", ",", "icon", ":", "str", ",", "unit", ":", "str", ",", "device_class", ":", "str", ",", "enabled_by_default", ":", "bool", ",", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ",", "controller", ")", "self", ".", "_device_class", "=", "device_class", "self", ".", "_enabled_by_default", "=", "enabled_by_default", "self", ".", "_icon", "=", "icon", "self", ".", "_name", "=", "name", "self", ".", "_sensor_type", "=", "sensor_type", "self", ".", "_state", "=", "None", "self", ".", "_unit", "=", "unit" ]
[ 113, 4 ]
[ 132, 25 ]
python
en
['en', 'en', 'it']
False
RainMachineSensor.entity_registry_enabled_default
(self)
Determine whether an entity is enabled by default.
Determine whether an entity is enabled by default.
def entity_registry_enabled_default(self) -> bool: """Determine whether an entity is enabled by default.""" return self._enabled_by_default
[ "def", "entity_registry_enabled_default", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_enabled_by_default" ]
[ 135, 4 ]
[ 137, 39 ]
python
en
['en', 'en', 'en']
True
RainMachineSensor.icon
(self)
Return the icon.
Return the icon.
def icon(self) -> str: """Return the icon.""" return self._icon
[ "def", "icon", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_icon" ]
[ 140, 4 ]
[ 142, 25 ]
python
en
['en', 'sr', 'en']
True
RainMachineSensor.state
(self)
Return the name of the entity.
Return the name of the entity.
def state(self) -> str: """Return the name of the entity.""" return self._state
[ "def", "state", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_state" ]
[ 145, 4 ]
[ 147, 26 ]
python
en
['en', 'en', 'en']
True
RainMachineSensor.unique_id
(self)
Return a unique, Home Assistant friendly identifier for this entity.
Return a unique, Home Assistant friendly identifier for this entity.
def unique_id(self) -> str: """Return a unique, Home Assistant friendly identifier for this entity.""" return f"{self._unique_id}_{self._sensor_type}"
[ "def", "unique_id", "(", "self", ")", "->", "str", ":", "return", "f\"{self._unique_id}_{self._sensor_type}\"" ]
[ 150, 4 ]
[ 152, 55 ]
python
en
['en', 'en', 'en']
True
RainMachineSensor.unit_of_measurement
(self)
Return the unit the value is expressed in.
Return the unit the value is expressed in.
def unit_of_measurement(self) -> str: """Return the unit the value is expressed in.""" return self._unit
[ "def", "unit_of_measurement", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_unit" ]
[ 155, 4 ]
[ 157, 25 ]
python
en
['en', 'en', 'en']
True
ProvisionSettingsSensor.update_from_latest_data
(self)
Update the state.
Update the state.
def update_from_latest_data(self) -> None: """Update the state.""" if self._sensor_type == TYPE_FLOW_SENSOR_CLICK_M3: self._state = self.coordinator.data["system"].get( "flowSensorClicksPerCubicMeter" ) elif self._sensor_type == TYPE_FLOW_SENSOR_CONSUMED_LITERS: clicks = self.coordinator.data["system"].get("flowSensorWateringClicks") clicks_per_m3 = self.coordinator.data["system"].get( "flowSensorClicksPerCubicMeter" ) if clicks and clicks_per_m3: self._state = (clicks * 1000) / clicks_per_m3 else: self._state = None elif self._sensor_type == TYPE_FLOW_SENSOR_START_INDEX: self._state = self.coordinator.data["system"].get("flowSensorStartIndex") elif self._sensor_type == TYPE_FLOW_SENSOR_WATERING_CLICKS: self._state = self.coordinator.data["system"].get( "flowSensorWateringClicks" )
[ "def", "update_from_latest_data", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_sensor_type", "==", "TYPE_FLOW_SENSOR_CLICK_M3", ":", "self", ".", "_state", "=", "self", ".", "coordinator", ".", "data", "[", "\"system\"", "]", ".", "get", "(", "\"flowSensorClicksPerCubicMeter\"", ")", "elif", "self", ".", "_sensor_type", "==", "TYPE_FLOW_SENSOR_CONSUMED_LITERS", ":", "clicks", "=", "self", ".", "coordinator", ".", "data", "[", "\"system\"", "]", ".", "get", "(", "\"flowSensorWateringClicks\"", ")", "clicks_per_m3", "=", "self", ".", "coordinator", ".", "data", "[", "\"system\"", "]", ".", "get", "(", "\"flowSensorClicksPerCubicMeter\"", ")", "if", "clicks", "and", "clicks_per_m3", ":", "self", ".", "_state", "=", "(", "clicks", "*", "1000", ")", "/", "clicks_per_m3", "else", ":", "self", ".", "_state", "=", "None", "elif", "self", ".", "_sensor_type", "==", "TYPE_FLOW_SENSOR_START_INDEX", ":", "self", ".", "_state", "=", "self", ".", "coordinator", ".", "data", "[", "\"system\"", "]", ".", "get", "(", "\"flowSensorStartIndex\"", ")", "elif", "self", ".", "_sensor_type", "==", "TYPE_FLOW_SENSOR_WATERING_CLICKS", ":", "self", ".", "_state", "=", "self", ".", "coordinator", ".", "data", "[", "\"system\"", "]", ".", "get", "(", "\"flowSensorWateringClicks\"", ")" ]
[ 164, 4 ]
[ 185, 13 ]
python
en
['en', 'en', 'en']
True
UniversalRestrictionsSensor.update_from_latest_data
(self)
Update the state.
Update the state.
def update_from_latest_data(self) -> None: """Update the state.""" if self._sensor_type == TYPE_FREEZE_TEMP: self._state = self.coordinator.data["freezeProtectTemp"]
[ "def", "update_from_latest_data", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_sensor_type", "==", "TYPE_FREEZE_TEMP", ":", "self", ".", "_state", "=", "self", ".", "coordinator", ".", "data", "[", "\"freezeProtectTemp\"", "]" ]
[ 192, 4 ]
[ 195, 68 ]
python
en
['en', 'en', 'en']
True
validate_entity_config
(values)
Validate config entry for CONF_ENTITY.
Validate config entry for CONF_ENTITY.
def validate_entity_config(values): """Validate config entry for CONF_ENTITY.""" if not isinstance(values, dict): raise vol.Invalid("expected a dictionary") entities = {} for entity_id, config in values.items(): entity = cv.entity_id(entity_id) domain, _ = split_entity_id(entity) if not isinstance(config, dict): raise vol.Invalid(f"The configuration for {entity} must be a dictionary.") if domain in ("alarm_control_panel", "lock"): config = CODE_SCHEMA(config) elif domain == media_player.const.DOMAIN: config = FEATURE_SCHEMA(config) feature_list = {} for feature in config[CONF_FEATURE_LIST]: params = MEDIA_PLAYER_SCHEMA(feature) key = params.pop(CONF_FEATURE) if key in feature_list: raise vol.Invalid(f"A feature can be added only once for {entity}") feature_list[key] = params config[CONF_FEATURE_LIST] = feature_list elif domain == "camera": config = CAMERA_SCHEMA(config) elif domain == "switch": config = SWITCH_TYPE_SCHEMA(config) elif domain == "humidifier": config = HUMIDIFIER_SCHEMA(config) elif domain == "cover": config = COVER_SCHEMA(config) else: config = BASIC_INFO_SCHEMA(config) entities[entity] = config return entities
[ "def", "validate_entity_config", "(", "values", ")", ":", "if", "not", "isinstance", "(", "values", ",", "dict", ")", ":", "raise", "vol", ".", "Invalid", "(", "\"expected a dictionary\"", ")", "entities", "=", "{", "}", "for", "entity_id", ",", "config", "in", "values", ".", "items", "(", ")", ":", "entity", "=", "cv", ".", "entity_id", "(", "entity_id", ")", "domain", ",", "_", "=", "split_entity_id", "(", "entity", ")", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "vol", ".", "Invalid", "(", "f\"The configuration for {entity} must be a dictionary.\"", ")", "if", "domain", "in", "(", "\"alarm_control_panel\"", ",", "\"lock\"", ")", ":", "config", "=", "CODE_SCHEMA", "(", "config", ")", "elif", "domain", "==", "media_player", ".", "const", ".", "DOMAIN", ":", "config", "=", "FEATURE_SCHEMA", "(", "config", ")", "feature_list", "=", "{", "}", "for", "feature", "in", "config", "[", "CONF_FEATURE_LIST", "]", ":", "params", "=", "MEDIA_PLAYER_SCHEMA", "(", "feature", ")", "key", "=", "params", ".", "pop", "(", "CONF_FEATURE", ")", "if", "key", "in", "feature_list", ":", "raise", "vol", ".", "Invalid", "(", "f\"A feature can be added only once for {entity}\"", ")", "feature_list", "[", "key", "]", "=", "params", "config", "[", "CONF_FEATURE_LIST", "]", "=", "feature_list", "elif", "domain", "==", "\"camera\"", ":", "config", "=", "CAMERA_SCHEMA", "(", "config", ")", "elif", "domain", "==", "\"switch\"", ":", "config", "=", "SWITCH_TYPE_SCHEMA", "(", "config", ")", "elif", "domain", "==", "\"humidifier\"", ":", "config", "=", "HUMIDIFIER_SCHEMA", "(", "config", ")", "elif", "domain", "==", "\"cover\"", ":", "config", "=", "COVER_SCHEMA", "(", "config", ")", "else", ":", "config", "=", "BASIC_INFO_SCHEMA", "(", "config", ")", "entities", "[", "entity", "]", "=", "config", "return", "entities" ]
[ 223, 0 ]
[ 266, 19 ]
python
en
['en', 'en', 'en']
True
get_media_player_features
(state)
Determine features for media players.
Determine features for media players.
def get_media_player_features(state): """Determine features for media players.""" features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) supported_modes = [] if features & ( media_player.const.SUPPORT_TURN_ON | media_player.const.SUPPORT_TURN_OFF ): supported_modes.append(FEATURE_ON_OFF) if features & (media_player.const.SUPPORT_PLAY | media_player.const.SUPPORT_PAUSE): supported_modes.append(FEATURE_PLAY_PAUSE) if features & (media_player.const.SUPPORT_PLAY | media_player.const.SUPPORT_STOP): supported_modes.append(FEATURE_PLAY_STOP) if features & media_player.const.SUPPORT_VOLUME_MUTE: supported_modes.append(FEATURE_TOGGLE_MUTE) return supported_modes
[ "def", "get_media_player_features", "(", "state", ")", ":", "features", "=", "state", ".", "attributes", ".", "get", "(", "ATTR_SUPPORTED_FEATURES", ",", "0", ")", "supported_modes", "=", "[", "]", "if", "features", "&", "(", "media_player", ".", "const", ".", "SUPPORT_TURN_ON", "|", "media_player", ".", "const", ".", "SUPPORT_TURN_OFF", ")", ":", "supported_modes", ".", "append", "(", "FEATURE_ON_OFF", ")", "if", "features", "&", "(", "media_player", ".", "const", ".", "SUPPORT_PLAY", "|", "media_player", ".", "const", ".", "SUPPORT_PAUSE", ")", ":", "supported_modes", ".", "append", "(", "FEATURE_PLAY_PAUSE", ")", "if", "features", "&", "(", "media_player", ".", "const", ".", "SUPPORT_PLAY", "|", "media_player", ".", "const", ".", "SUPPORT_STOP", ")", ":", "supported_modes", ".", "append", "(", "FEATURE_PLAY_STOP", ")", "if", "features", "&", "media_player", ".", "const", ".", "SUPPORT_VOLUME_MUTE", ":", "supported_modes", ".", "append", "(", "FEATURE_TOGGLE_MUTE", ")", "return", "supported_modes" ]
[ 269, 0 ]
[ 284, 26 ]
python
en
['en', 'en', 'en']
True
validate_media_player_features
(state, feature_list)
Validate features for media players.
Validate features for media players.
def validate_media_player_features(state, feature_list): """Validate features for media players.""" supported_modes = get_media_player_features(state) if not supported_modes: _LOGGER.error("%s does not support any media_player features", state.entity_id) return False if not feature_list: # Auto detected return True error_list = [] for feature in feature_list: if feature not in supported_modes: error_list.append(feature) if error_list: _LOGGER.error( "%s does not support media_player features: %s", state.entity_id, error_list ) return False return True
[ "def", "validate_media_player_features", "(", "state", ",", "feature_list", ")", ":", "supported_modes", "=", "get_media_player_features", "(", "state", ")", "if", "not", "supported_modes", ":", "_LOGGER", ".", "error", "(", "\"%s does not support any media_player features\"", ",", "state", ".", "entity_id", ")", "return", "False", "if", "not", "feature_list", ":", "# Auto detected", "return", "True", "error_list", "=", "[", "]", "for", "feature", "in", "feature_list", ":", "if", "feature", "not", "in", "supported_modes", ":", "error_list", ".", "append", "(", "feature", ")", "if", "error_list", ":", "_LOGGER", ".", "error", "(", "\"%s does not support media_player features: %s\"", ",", "state", ".", "entity_id", ",", "error_list", ")", "return", "False", "return", "True" ]
[ 287, 0 ]
[ 309, 15 ]
python
en
['en', 'en', 'en']
True
show_setup_message
(hass, entry_id, bridge_name, pincode, uri)
Display persistent notification with setup information.
Display persistent notification with setup information.
def show_setup_message(hass, entry_id, bridge_name, pincode, uri): """Display persistent notification with setup information.""" pin = pincode.decode() _LOGGER.info("Pincode: %s", pin) buffer = io.BytesIO() url = pyqrcode.create(uri) url.svg(buffer, scale=5, module_color="#000", background="#FFF") pairing_secret = secrets.token_hex(32) hass.data[DOMAIN][entry_id][HOMEKIT_PAIRING_QR] = buffer.getvalue() hass.data[DOMAIN][entry_id][HOMEKIT_PAIRING_QR_SECRET] = pairing_secret message = ( f"To set up {bridge_name} in the Home App, " f"scan the QR code or enter the following code:\n" f"### {pin}\n" f"![image](/api/homekit/pairingqr?{entry_id}-{pairing_secret})" ) hass.components.persistent_notification.create( message, "HomeKit Bridge Setup", entry_id )
[ "def", "show_setup_message", "(", "hass", ",", "entry_id", ",", "bridge_name", ",", "pincode", ",", "uri", ")", ":", "pin", "=", "pincode", ".", "decode", "(", ")", "_LOGGER", ".", "info", "(", "\"Pincode: %s\"", ",", "pin", ")", "buffer", "=", "io", ".", "BytesIO", "(", ")", "url", "=", "pyqrcode", ".", "create", "(", "uri", ")", "url", ".", "svg", "(", "buffer", ",", "scale", "=", "5", ",", "module_color", "=", "\"#000\"", ",", "background", "=", "\"#FFF\"", ")", "pairing_secret", "=", "secrets", ".", "token_hex", "(", "32", ")", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry_id", "]", "[", "HOMEKIT_PAIRING_QR", "]", "=", "buffer", ".", "getvalue", "(", ")", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry_id", "]", "[", "HOMEKIT_PAIRING_QR_SECRET", "]", "=", "pairing_secret", "message", "=", "(", "f\"To set up {bridge_name} in the Home App, \"", "f\"scan the QR code or enter the following code:\\n\"", "f\"### {pin}\\n\"", "f\"![image](/api/homekit/pairingqr?{entry_id}-{pairing_secret})\"", ")", "hass", ".", "components", ".", "persistent_notification", ".", "create", "(", "message", ",", "\"HomeKit Bridge Setup\"", ",", "entry_id", ")" ]
[ 362, 0 ]
[ 383, 5 ]
python
en
['en', 'en', 'en']
True
dismiss_setup_message
(hass, entry_id)
Dismiss persistent notification and remove QR code.
Dismiss persistent notification and remove QR code.
def dismiss_setup_message(hass, entry_id): """Dismiss persistent notification and remove QR code.""" hass.components.persistent_notification.dismiss(entry_id)
[ "def", "dismiss_setup_message", "(", "hass", ",", "entry_id", ")", ":", "hass", ".", "components", ".", "persistent_notification", ".", "dismiss", "(", "entry_id", ")" ]
[ 386, 0 ]
[ 388, 61 ]
python
en
['en', 'en', 'en']
True
convert_to_float
(state)
Return float of state, catch errors.
Return float of state, catch errors.
def convert_to_float(state): """Return float of state, catch errors.""" try: return float(state) except (ValueError, TypeError): return None
[ "def", "convert_to_float", "(", "state", ")", ":", "try", ":", "return", "float", "(", "state", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "None" ]
[ 391, 0 ]
[ 396, 19 ]
python
en
['en', 'en', 'en']
True
cleanup_name_for_homekit
(name)
Ensure the name of the device will not crash homekit.
Ensure the name of the device will not crash homekit.
def cleanup_name_for_homekit(name): """Ensure the name of the device will not crash homekit.""" # # This is not a security measure. # # UNICODE_EMOJI is also not allowed but that # likely isn't a problem return name.translate(HOMEKIT_CHAR_TRANSLATIONS)
[ "def", "cleanup_name_for_homekit", "(", "name", ")", ":", "#", "# This is not a security measure.", "#", "# UNICODE_EMOJI is also not allowed but that", "# likely isn't a problem", "return", "name", ".", "translate", "(", "HOMEKIT_CHAR_TRANSLATIONS", ")" ]
[ 399, 0 ]
[ 406, 52 ]
python
en
['en', 'en', 'en']
True
temperature_to_homekit
(temperature, unit)
Convert temperature to Celsius for HomeKit.
Convert temperature to Celsius for HomeKit.
def temperature_to_homekit(temperature, unit): """Convert temperature to Celsius for HomeKit.""" return round(temp_util.convert(temperature, unit, TEMP_CELSIUS), 1)
[ "def", "temperature_to_homekit", "(", "temperature", ",", "unit", ")", ":", "return", "round", "(", "temp_util", ".", "convert", "(", "temperature", ",", "unit", ",", "TEMP_CELSIUS", ")", ",", "1", ")" ]
[ 409, 0 ]
[ 411, 71 ]
python
en
['en', 'la', 'en']
True
temperature_to_states
(temperature, unit)
Convert temperature back from Celsius to Home Assistant unit.
Convert temperature back from Celsius to Home Assistant unit.
def temperature_to_states(temperature, unit): """Convert temperature back from Celsius to Home Assistant unit.""" return round(temp_util.convert(temperature, TEMP_CELSIUS, unit) * 2) / 2
[ "def", "temperature_to_states", "(", "temperature", ",", "unit", ")", ":", "return", "round", "(", "temp_util", ".", "convert", "(", "temperature", ",", "TEMP_CELSIUS", ",", "unit", ")", "*", "2", ")", "/", "2" ]
[ 414, 0 ]
[ 416, 76 ]
python
en
['en', 'en', 'en']
True
density_to_air_quality
(density)
Map PM2.5 density to HomeKit AirQuality level.
Map PM2.5 density to HomeKit AirQuality level.
def density_to_air_quality(density): """Map PM2.5 density to HomeKit AirQuality level.""" if density <= 35: return 1 if density <= 75: return 2 if density <= 115: return 3 if density <= 150: return 4 return 5
[ "def", "density_to_air_quality", "(", "density", ")", ":", "if", "density", "<=", "35", ":", "return", "1", "if", "density", "<=", "75", ":", "return", "2", "if", "density", "<=", "115", ":", "return", "3", "if", "density", "<=", "150", ":", "return", "4", "return", "5" ]
[ 419, 0 ]
[ 429, 12 ]
python
en
['en', 'en', 'en']
True
get_persist_filename_for_entry_id
(entry_id: str)
Determine the filename of the homekit state file.
Determine the filename of the homekit state file.
def get_persist_filename_for_entry_id(entry_id: str): """Determine the filename of the homekit state file.""" return f"{DOMAIN}.{entry_id}.state"
[ "def", "get_persist_filename_for_entry_id", "(", "entry_id", ":", "str", ")", ":", "return", "f\"{DOMAIN}.{entry_id}.state\"" ]
[ 432, 0 ]
[ 434, 39 ]
python
en
['en', 'en', 'en']
True
get_aid_storage_filename_for_entry_id
(entry_id: str)
Determine the ilename of homekit aid storage file.
Determine the ilename of homekit aid storage file.
def get_aid_storage_filename_for_entry_id(entry_id: str): """Determine the ilename of homekit aid storage file.""" return f"{DOMAIN}.{entry_id}.aids"
[ "def", "get_aid_storage_filename_for_entry_id", "(", "entry_id", ":", "str", ")", ":", "return", "f\"{DOMAIN}.{entry_id}.aids\"" ]
[ 437, 0 ]
[ 439, 38 ]
python
en
['en', 'et', 'en']
True
get_persist_fullpath_for_entry_id
(hass: HomeAssistant, entry_id: str)
Determine the path to the homekit state file.
Determine the path to the homekit state file.
def get_persist_fullpath_for_entry_id(hass: HomeAssistant, entry_id: str): """Determine the path to the homekit state file.""" return hass.config.path(STORAGE_DIR, get_persist_filename_for_entry_id(entry_id))
[ "def", "get_persist_fullpath_for_entry_id", "(", "hass", ":", "HomeAssistant", ",", "entry_id", ":", "str", ")", ":", "return", "hass", ".", "config", ".", "path", "(", "STORAGE_DIR", ",", "get_persist_filename_for_entry_id", "(", "entry_id", ")", ")" ]
[ 442, 0 ]
[ 444, 85 ]
python
en
['en', 'en', 'en']
True
get_aid_storage_fullpath_for_entry_id
(hass: HomeAssistant, entry_id: str)
Determine the path to the homekit aid storage file.
Determine the path to the homekit aid storage file.
def get_aid_storage_fullpath_for_entry_id(hass: HomeAssistant, entry_id: str): """Determine the path to the homekit aid storage file.""" return hass.config.path( STORAGE_DIR, get_aid_storage_filename_for_entry_id(entry_id) )
[ "def", "get_aid_storage_fullpath_for_entry_id", "(", "hass", ":", "HomeAssistant", ",", "entry_id", ":", "str", ")", ":", "return", "hass", ".", "config", ".", "path", "(", "STORAGE_DIR", ",", "get_aid_storage_filename_for_entry_id", "(", "entry_id", ")", ")" ]
[ 447, 0 ]
[ 451, 5 ]
python
en
['en', 'en', 'en']
True
format_sw_version
(version)
Extract the version string in a format homekit can consume.
Extract the version string in a format homekit can consume.
def format_sw_version(version): """Extract the version string in a format homekit can consume.""" match = re.search(r"([0-9]+)(\.[0-9]+)?(\.[0-9]+)?", str(version).replace("-", ".")) if match: return match.group(0) return None
[ "def", "format_sw_version", "(", "version", ")", ":", "match", "=", "re", ".", "search", "(", "r\"([0-9]+)(\\.[0-9]+)?(\\.[0-9]+)?\"", ",", "str", "(", "version", ")", ".", "replace", "(", "\"-\"", ",", "\".\"", ")", ")", "if", "match", ":", "return", "match", ".", "group", "(", "0", ")", "return", "None" ]
[ 454, 0 ]
[ 459, 15 ]
python
en
['en', 'en', 'en']
True
migrate_filesystem_state_data_for_primary_imported_entry_id
( hass: HomeAssistant, entry_id: str )
Migrate the old paths to the storage directory.
Migrate the old paths to the storage directory.
def migrate_filesystem_state_data_for_primary_imported_entry_id( hass: HomeAssistant, entry_id: str ): """Migrate the old paths to the storage directory.""" legacy_persist_file_path = hass.config.path(HOMEKIT_FILE) if os.path.exists(legacy_persist_file_path): os.rename( legacy_persist_file_path, get_persist_fullpath_for_entry_id(hass, entry_id) ) legacy_aid_storage_path = hass.config.path(STORAGE_DIR, "homekit.aids") if os.path.exists(legacy_aid_storage_path): os.rename( legacy_aid_storage_path, get_aid_storage_fullpath_for_entry_id(hass, entry_id), )
[ "def", "migrate_filesystem_state_data_for_primary_imported_entry_id", "(", "hass", ":", "HomeAssistant", ",", "entry_id", ":", "str", ")", ":", "legacy_persist_file_path", "=", "hass", ".", "config", ".", "path", "(", "HOMEKIT_FILE", ")", "if", "os", ".", "path", ".", "exists", "(", "legacy_persist_file_path", ")", ":", "os", ".", "rename", "(", "legacy_persist_file_path", ",", "get_persist_fullpath_for_entry_id", "(", "hass", ",", "entry_id", ")", ")", "legacy_aid_storage_path", "=", "hass", ".", "config", ".", "path", "(", "STORAGE_DIR", ",", "\"homekit.aids\"", ")", "if", "os", ".", "path", ".", "exists", "(", "legacy_aid_storage_path", ")", ":", "os", ".", "rename", "(", "legacy_aid_storage_path", ",", "get_aid_storage_fullpath_for_entry_id", "(", "hass", ",", "entry_id", ")", ",", ")" ]
[ 462, 0 ]
[ 477, 9 ]
python
en
['en', 'en', 'en']
True
remove_state_files_for_entry_id
(hass: HomeAssistant, entry_id: str)
Remove the state files from disk.
Remove the state files from disk.
def remove_state_files_for_entry_id(hass: HomeAssistant, entry_id: str): """Remove the state files from disk.""" persist_file_path = get_persist_fullpath_for_entry_id(hass, entry_id) aid_storage_path = get_aid_storage_fullpath_for_entry_id(hass, entry_id) os.unlink(persist_file_path) if os.path.exists(aid_storage_path): os.unlink(aid_storage_path) return True
[ "def", "remove_state_files_for_entry_id", "(", "hass", ":", "HomeAssistant", ",", "entry_id", ":", "str", ")", ":", "persist_file_path", "=", "get_persist_fullpath_for_entry_id", "(", "hass", ",", "entry_id", ")", "aid_storage_path", "=", "get_aid_storage_fullpath_for_entry_id", "(", "hass", ",", "entry_id", ")", "os", ".", "unlink", "(", "persist_file_path", ")", "if", "os", ".", "path", ".", "exists", "(", "aid_storage_path", ")", ":", "os", ".", "unlink", "(", "aid_storage_path", ")", "return", "True" ]
[ 480, 0 ]
[ 487, 15 ]
python
en
['en', 'en', 'en']
True
_get_test_socket
()
Create a socket to test binding ports.
Create a socket to test binding ports.
def _get_test_socket(): """Create a socket to test binding ports.""" test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) test_socket.setblocking(False) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return test_socket
[ "def", "_get_test_socket", "(", ")", ":", "test_socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "test_socket", ".", "setblocking", "(", "False", ")", "test_socket", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "return", "test_socket" ]
[ 490, 0 ]
[ 495, 22 ]
python
en
['en', 'en', 'en']
True
port_is_available
(port: int)
Check to see if a port is available.
Check to see if a port is available.
def port_is_available(port: int): """Check to see if a port is available.""" test_socket = _get_test_socket() try: test_socket.bind(("", port)) except OSError: return False return True
[ "def", "port_is_available", "(", "port", ":", "int", ")", ":", "test_socket", "=", "_get_test_socket", "(", ")", "try", ":", "test_socket", ".", "bind", "(", "(", "\"\"", ",", "port", ")", ")", "except", "OSError", ":", "return", "False", "return", "True" ]
[ 498, 0 ]
[ 506, 15 ]
python
en
['en', 'en', 'en']
True
find_next_available_port
(start_port: int)
Find the next available port starting with the given port.
Find the next available port starting with the given port.
def find_next_available_port(start_port: int): """Find the next available port starting with the given port.""" test_socket = _get_test_socket() for port in range(start_port, MAX_PORT): try: test_socket.bind(("", port)) return port except OSError: if port == MAX_PORT: raise continue
[ "def", "find_next_available_port", "(", "start_port", ":", "int", ")", ":", "test_socket", "=", "_get_test_socket", "(", ")", "for", "port", "in", "range", "(", "start_port", ",", "MAX_PORT", ")", ":", "try", ":", "test_socket", ".", "bind", "(", "(", "\"\"", ",", "port", ")", ")", "return", "port", "except", "OSError", ":", "if", "port", "==", "MAX_PORT", ":", "raise", "continue" ]
[ 509, 0 ]
[ 519, 20 ]
python
en
['en', 'en', 'en']
True
pid_is_alive
(pid)
Check to see if a process is alive.
Check to see if a process is alive.
def pid_is_alive(pid): """Check to see if a process is alive.""" try: os.kill(pid, 0) return True except OSError: pass return False
[ "def", "pid_is_alive", "(", "pid", ")", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "0", ")", "return", "True", "except", "OSError", ":", "pass", "return", "False" ]
[ 522, 0 ]
[ 529, 16 ]
python
en
['en', 'en', 'en']
True
HomeKitSpeedMapping.__init__
(self, speed_list)
Initialize a new SpeedMapping object.
Initialize a new SpeedMapping object.
def __init__(self, speed_list): """Initialize a new SpeedMapping object.""" if speed_list[0] != fan.SPEED_OFF: _LOGGER.warning( "%s does not contain the speed setting " "%s as its first element. " "Assuming that %s is equivalent to 'off'", speed_list, fan.SPEED_OFF, speed_list[0], ) self.speed_ranges = OrderedDict() list_size = len(speed_list) for index, speed in enumerate(speed_list): # By dividing by list_size -1 the following # desired attributes hold true: # * index = 0 => 0%, equal to "off" # * index = len(speed_list) - 1 => 100 % # * all other indices are equally distributed target = index * 100 / (list_size - 1) start = index * 100 / list_size self.speed_ranges[speed] = SpeedRange(start, target)
[ "def", "__init__", "(", "self", ",", "speed_list", ")", ":", "if", "speed_list", "[", "0", "]", "!=", "fan", ".", "SPEED_OFF", ":", "_LOGGER", ".", "warning", "(", "\"%s does not contain the speed setting \"", "\"%s as its first element. \"", "\"Assuming that %s is equivalent to 'off'\"", ",", "speed_list", ",", "fan", ".", "SPEED_OFF", ",", "speed_list", "[", "0", "]", ",", ")", "self", ".", "speed_ranges", "=", "OrderedDict", "(", ")", "list_size", "=", "len", "(", "speed_list", ")", "for", "index", ",", "speed", "in", "enumerate", "(", "speed_list", ")", ":", "# By dividing by list_size -1 the following", "# desired attributes hold true:", "# * index = 0 => 0%, equal to \"off\"", "# * index = len(speed_list) - 1 => 100 %", "# * all other indices are equally distributed", "target", "=", "index", "*", "100", "/", "(", "list_size", "-", "1", ")", "start", "=", "index", "*", "100", "/", "list_size", "self", ".", "speed_ranges", "[", "speed", "]", "=", "SpeedRange", "(", "start", ",", "target", ")" ]
[ 324, 4 ]
[ 345, 64 ]
python
en
['en', 'en', 'en']
True
HomeKitSpeedMapping.speed_to_homekit
(self, speed)
Map Home Assistant speed state to HomeKit speed.
Map Home Assistant speed state to HomeKit speed.
def speed_to_homekit(self, speed): """Map Home Assistant speed state to HomeKit speed.""" if speed is None: return None speed_range = self.speed_ranges[speed] return round(speed_range.target)
[ "def", "speed_to_homekit", "(", "self", ",", "speed", ")", ":", "if", "speed", "is", "None", ":", "return", "None", "speed_range", "=", "self", ".", "speed_ranges", "[", "speed", "]", "return", "round", "(", "speed_range", ".", "target", ")" ]
[ 347, 4 ]
[ 352, 40 ]
python
en
['en', 'en', 'en']
True
HomeKitSpeedMapping.speed_to_states
(self, speed)
Map HomeKit speed to Home Assistant speed state.
Map HomeKit speed to Home Assistant speed state.
def speed_to_states(self, speed): """Map HomeKit speed to Home Assistant speed state.""" for state, speed_range in reversed(self.speed_ranges.items()): if speed_range.start <= speed: return state return list(self.speed_ranges)[0]
[ "def", "speed_to_states", "(", "self", ",", "speed", ")", ":", "for", "state", ",", "speed_range", "in", "reversed", "(", "self", ".", "speed_ranges", ".", "items", "(", ")", ")", ":", "if", "speed_range", ".", "start", "<=", "speed", ":", "return", "state", "return", "list", "(", "self", ".", "speed_ranges", ")", "[", "0", "]" ]
[ 354, 4 ]
[ 359, 41 ]
python
en
['en', 'en', 'en']
True
test_climate_thermostat_run
(hass)
Test a thermostat with the schedule running.
Test a thermostat with the schedule running.
async def test_climate_thermostat_run(hass): """Test a thermostat with the schedule running.""" mock_thermostat = _get_mock_thermostat_run() mock_nuheat = _get_mock_nuheat(get_thermostat=mock_thermostat) with patch( "homeassistant.components.nuheat.nuheat.NuHeat", return_value=mock_nuheat, ): assert await async_setup_component(hass, DOMAIN, _mock_get_config()) await hass.async_block_till_done() state = hass.states.get("climate.master_bathroom") assert state.state == "auto" expected_attributes = { "current_temperature": 22.2, "friendly_name": "Master bathroom", "hvac_action": "heating", "hvac_modes": ["auto", "heat"], "max_temp": 69.4, "min_temp": 5.0, "preset_mode": "Run Schedule", "preset_modes": ["Run Schedule", "Temporary Hold", "Permanent Hold"], "supported_features": 17, "temperature": 22.2, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all(item in state.attributes.items() for item in expected_attributes.items())
[ "async", "def", "test_climate_thermostat_run", "(", "hass", ")", ":", "mock_thermostat", "=", "_get_mock_thermostat_run", "(", ")", "mock_nuheat", "=", "_get_mock_nuheat", "(", "get_thermostat", "=", "mock_thermostat", ")", "with", "patch", "(", "\"homeassistant.components.nuheat.nuheat.NuHeat\"", ",", "return_value", "=", "mock_nuheat", ",", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "_mock_get_config", "(", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"climate.master_bathroom\"", ")", "assert", "state", ".", "state", "==", "\"auto\"", "expected_attributes", "=", "{", "\"current_temperature\"", ":", "22.2", ",", "\"friendly_name\"", ":", "\"Master bathroom\"", ",", "\"hvac_action\"", ":", "\"heating\"", ",", "\"hvac_modes\"", ":", "[", "\"auto\"", ",", "\"heat\"", "]", ",", "\"max_temp\"", ":", "69.4", ",", "\"min_temp\"", ":", "5.0", ",", "\"preset_mode\"", ":", "\"Run Schedule\"", ",", "\"preset_modes\"", ":", "[", "\"Run Schedule\"", ",", "\"Temporary Hold\"", ",", "\"Permanent Hold\"", "]", ",", "\"supported_features\"", ":", "17", ",", "\"temperature\"", ":", "22.2", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "item", "in", "state", ".", "attributes", ".", "items", "(", ")", "for", "item", "in", "expected_attributes", ".", "items", "(", ")", ")" ]
[ 21, 0 ]
[ 49, 88 ]
python
en
['en', 'en', 'en']
True
test_climate_thermostat_schedule_hold_unavailable
(hass)
Test a thermostat with the schedule hold that is offline.
Test a thermostat with the schedule hold that is offline.
async def test_climate_thermostat_schedule_hold_unavailable(hass): """Test a thermostat with the schedule hold that is offline.""" mock_thermostat = _get_mock_thermostat_schedule_hold_unavailable() mock_nuheat = _get_mock_nuheat(get_thermostat=mock_thermostat) with patch( "homeassistant.components.nuheat.nuheat.NuHeat", return_value=mock_nuheat, ): assert await async_setup_component(hass, DOMAIN, _mock_get_config()) await hass.async_block_till_done() state = hass.states.get("climate.guest_bathroom") assert state.state == "unavailable" expected_attributes = { "friendly_name": "Guest bathroom", "hvac_modes": ["auto", "heat"], "max_temp": 180.6, "min_temp": -6.1, "preset_modes": ["Run Schedule", "Temporary Hold", "Permanent Hold"], "supported_features": 17, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all(item in state.attributes.items() for item in expected_attributes.items())
[ "async", "def", "test_climate_thermostat_schedule_hold_unavailable", "(", "hass", ")", ":", "mock_thermostat", "=", "_get_mock_thermostat_schedule_hold_unavailable", "(", ")", "mock_nuheat", "=", "_get_mock_nuheat", "(", "get_thermostat", "=", "mock_thermostat", ")", "with", "patch", "(", "\"homeassistant.components.nuheat.nuheat.NuHeat\"", ",", "return_value", "=", "mock_nuheat", ",", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "_mock_get_config", "(", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"climate.guest_bathroom\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "expected_attributes", "=", "{", "\"friendly_name\"", ":", "\"Guest bathroom\"", ",", "\"hvac_modes\"", ":", "[", "\"auto\"", ",", "\"heat\"", "]", ",", "\"max_temp\"", ":", "180.6", ",", "\"min_temp\"", ":", "-", "6.1", ",", "\"preset_modes\"", ":", "[", "\"Run Schedule\"", ",", "\"Temporary Hold\"", ",", "\"Permanent Hold\"", "]", ",", "\"supported_features\"", ":", "17", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "item", "in", "state", ".", "attributes", ".", "items", "(", ")", "for", "item", "in", "expected_attributes", ".", "items", "(", ")", ")" ]
[ 52, 0 ]
[ 77, 88 ]
python
en
['en', 'en', 'en']
True
test_climate_thermostat_schedule_hold_available
(hass)
Test a thermostat with the schedule hold that is online.
Test a thermostat with the schedule hold that is online.
async def test_climate_thermostat_schedule_hold_available(hass): """Test a thermostat with the schedule hold that is online.""" mock_thermostat = _get_mock_thermostat_schedule_hold_available() mock_nuheat = _get_mock_nuheat(get_thermostat=mock_thermostat) with patch( "homeassistant.components.nuheat.nuheat.NuHeat", return_value=mock_nuheat, ): assert await async_setup_component(hass, DOMAIN, _mock_get_config()) await hass.async_block_till_done() state = hass.states.get("climate.available_bathroom") assert state.state == "auto" expected_attributes = { "current_temperature": 38.9, "friendly_name": "Available bathroom", "hvac_action": "idle", "hvac_modes": ["auto", "heat"], "max_temp": 180.6, "min_temp": -6.1, "preset_mode": "Run Schedule", "preset_modes": ["Run Schedule", "Temporary Hold", "Permanent Hold"], "supported_features": 17, "temperature": 26.1, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all(item in state.attributes.items() for item in expected_attributes.items())
[ "async", "def", "test_climate_thermostat_schedule_hold_available", "(", "hass", ")", ":", "mock_thermostat", "=", "_get_mock_thermostat_schedule_hold_available", "(", ")", "mock_nuheat", "=", "_get_mock_nuheat", "(", "get_thermostat", "=", "mock_thermostat", ")", "with", "patch", "(", "\"homeassistant.components.nuheat.nuheat.NuHeat\"", ",", "return_value", "=", "mock_nuheat", ",", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "_mock_get_config", "(", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"climate.available_bathroom\"", ")", "assert", "state", ".", "state", "==", "\"auto\"", "expected_attributes", "=", "{", "\"current_temperature\"", ":", "38.9", ",", "\"friendly_name\"", ":", "\"Available bathroom\"", ",", "\"hvac_action\"", ":", "\"idle\"", ",", "\"hvac_modes\"", ":", "[", "\"auto\"", ",", "\"heat\"", "]", ",", "\"max_temp\"", ":", "180.6", ",", "\"min_temp\"", ":", "-", "6.1", ",", "\"preset_mode\"", ":", "\"Run Schedule\"", ",", "\"preset_modes\"", ":", "[", "\"Run Schedule\"", ",", "\"Temporary Hold\"", ",", "\"Permanent Hold\"", "]", ",", "\"supported_features\"", ":", "17", ",", "\"temperature\"", ":", "26.1", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "item", "in", "state", ".", "attributes", ".", "items", "(", ")", "for", "item", "in", "expected_attributes", ".", "items", "(", ")", ")" ]
[ 80, 0 ]
[ 109, 88 ]
python
en
['en', 'en', 'en']
True
test_climate_thermostat_schedule_temporary_hold
(hass)
Test a thermostat with the temporary schedule hold that is online.
Test a thermostat with the temporary schedule hold that is online.
async def test_climate_thermostat_schedule_temporary_hold(hass): """Test a thermostat with the temporary schedule hold that is online.""" mock_thermostat = _get_mock_thermostat_schedule_temporary_hold() mock_nuheat = _get_mock_nuheat(get_thermostat=mock_thermostat) with patch( "homeassistant.components.nuheat.nuheat.NuHeat", return_value=mock_nuheat, ): assert await async_setup_component(hass, DOMAIN, _mock_get_config()) await hass.async_block_till_done() state = hass.states.get("climate.temp_bathroom") assert state.state == "auto" expected_attributes = { "current_temperature": 94.4, "friendly_name": "Temp bathroom", "hvac_action": "idle", "hvac_modes": ["auto", "heat"], "max_temp": 180.6, "min_temp": -0.6, "preset_mode": "Run Schedule", "preset_modes": ["Run Schedule", "Temporary Hold", "Permanent Hold"], "supported_features": 17, "temperature": 37.2, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all(item in state.attributes.items() for item in expected_attributes.items()) await hass.services.async_call( "climate", "set_temperature", service_data={ATTR_ENTITY_ID: "climate.temp_bathroom", "temperature": 90}, blocking=True, ) await hass.async_block_till_done() # opportunistic set state = hass.states.get("climate.temp_bathroom") assert state.attributes["preset_mode"] == "Temporary Hold" assert state.attributes["temperature"] == 50.0 # and the api poll returns it to the mock async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=3)) await hass.async_block_till_done() state = hass.states.get("climate.temp_bathroom") assert state.attributes["preset_mode"] == "Run Schedule" assert state.attributes["temperature"] == 37.2
[ "async", "def", "test_climate_thermostat_schedule_temporary_hold", "(", "hass", ")", ":", "mock_thermostat", "=", "_get_mock_thermostat_schedule_temporary_hold", "(", ")", "mock_nuheat", "=", "_get_mock_nuheat", "(", "get_thermostat", "=", "mock_thermostat", ")", "with", "patch", "(", "\"homeassistant.components.nuheat.nuheat.NuHeat\"", ",", "return_value", "=", "mock_nuheat", ",", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "_mock_get_config", "(", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"climate.temp_bathroom\"", ")", "assert", "state", ".", "state", "==", "\"auto\"", "expected_attributes", "=", "{", "\"current_temperature\"", ":", "94.4", ",", "\"friendly_name\"", ":", "\"Temp bathroom\"", ",", "\"hvac_action\"", ":", "\"idle\"", ",", "\"hvac_modes\"", ":", "[", "\"auto\"", ",", "\"heat\"", "]", ",", "\"max_temp\"", ":", "180.6", ",", "\"min_temp\"", ":", "-", "0.6", ",", "\"preset_mode\"", ":", "\"Run Schedule\"", ",", "\"preset_modes\"", ":", "[", "\"Run Schedule\"", ",", "\"Temporary Hold\"", ",", "\"Permanent Hold\"", "]", ",", "\"supported_features\"", ":", "17", ",", "\"temperature\"", ":", "37.2", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "item", "in", "state", ".", "attributes", ".", "items", "(", ")", "for", "item", "in", "expected_attributes", ".", "items", "(", ")", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"climate\"", ",", "\"set_temperature\"", ",", "service_data", "=", "{", "ATTR_ENTITY_ID", ":", "\"climate.temp_bathroom\"", ",", "\"temperature\"", ":", "90", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# opportunistic set", "state", "=", "hass", ".", "states", ".", "get", "(", "\"climate.temp_bathroom\"", ")", "assert", "state", ".", "attributes", "[", "\"preset_mode\"", "]", "==", "\"Temporary Hold\"", "assert", "state", ".", "attributes", "[", "\"temperature\"", "]", "==", "50.0", "# and the api poll returns it to the mock", "async_fire_time_changed", "(", "hass", ",", "dt_util", ".", "utcnow", "(", ")", "+", "timedelta", "(", "seconds", "=", "3", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"climate.temp_bathroom\"", ")", "assert", "state", ".", "attributes", "[", "\"preset_mode\"", "]", "==", "\"Run Schedule\"", "assert", "state", ".", "attributes", "[", "\"temperature\"", "]", "==", "37.2" ]
[ 112, 0 ]
[ 161, 50 ]
python
en
['en', 'en', 'en']
True
create_window_covering_service
(accessory)
Define a window-covering characteristics as per page 219 of HAP spec.
Define a window-covering characteristics as per page 219 of HAP spec.
def create_window_covering_service(accessory): """Define a window-covering characteristics as per page 219 of HAP spec.""" service = accessory.add_service(ServicesTypes.WINDOW_COVERING) cur_state = service.add_char(CharacteristicsTypes.POSITION_CURRENT) cur_state.value = 0 targ_state = service.add_char(CharacteristicsTypes.POSITION_TARGET) targ_state.value = 0 position_state = service.add_char(CharacteristicsTypes.POSITION_STATE) position_state.value = 0 position_hold = service.add_char(CharacteristicsTypes.POSITION_HOLD) position_hold.value = 0 obstruction = service.add_char(CharacteristicsTypes.OBSTRUCTION_DETECTED) obstruction.value = False name = service.add_char(CharacteristicsTypes.NAME) name.value = "testdevice" return service
[ "def", "create_window_covering_service", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "WINDOW_COVERING", ")", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "POSITION_CURRENT", ")", "cur_state", ".", "value", "=", "0", "targ_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "POSITION_TARGET", ")", "targ_state", ".", "value", "=", "0", "position_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "POSITION_STATE", ")", "position_state", ".", "value", "=", "0", "position_hold", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "POSITION_HOLD", ")", "position_hold", ".", "value", "=", "0", "obstruction", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "OBSTRUCTION_DETECTED", ")", "obstruction", ".", "value", "=", "False", "name", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "NAME", ")", "name", ".", "value", "=", "\"testdevice\"", "return", "service" ]
[ 24, 0 ]
[ 46, 18 ]
python
en
['en', 'en', 'en']
True
create_window_covering_service_with_h_tilt
(accessory)
Define a window-covering characteristics as per page 219 of HAP spec.
Define a window-covering characteristics as per page 219 of HAP spec.
def create_window_covering_service_with_h_tilt(accessory): """Define a window-covering characteristics as per page 219 of HAP spec.""" service = create_window_covering_service(accessory) tilt_current = service.add_char(CharacteristicsTypes.HORIZONTAL_TILT_CURRENT) tilt_current.value = 0 tilt_target = service.add_char(CharacteristicsTypes.HORIZONTAL_TILT_TARGET) tilt_target.value = 0
[ "def", "create_window_covering_service_with_h_tilt", "(", "accessory", ")", ":", "service", "=", "create_window_covering_service", "(", "accessory", ")", "tilt_current", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "HORIZONTAL_TILT_CURRENT", ")", "tilt_current", ".", "value", "=", "0", "tilt_target", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "HORIZONTAL_TILT_TARGET", ")", "tilt_target", ".", "value", "=", "0" ]
[ 49, 0 ]
[ 57, 25 ]
python
en
['en', 'en', 'en']
True
create_window_covering_service_with_v_tilt
(accessory)
Define a window-covering characteristics as per page 219 of HAP spec.
Define a window-covering characteristics as per page 219 of HAP spec.
def create_window_covering_service_with_v_tilt(accessory): """Define a window-covering characteristics as per page 219 of HAP spec.""" service = create_window_covering_service(accessory) tilt_current = service.add_char(CharacteristicsTypes.VERTICAL_TILT_CURRENT) tilt_current.value = 0 tilt_target = service.add_char(CharacteristicsTypes.VERTICAL_TILT_TARGET) tilt_target.value = 0
[ "def", "create_window_covering_service_with_v_tilt", "(", "accessory", ")", ":", "service", "=", "create_window_covering_service", "(", "accessory", ")", "tilt_current", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "VERTICAL_TILT_CURRENT", ")", "tilt_current", ".", "value", "=", "0", "tilt_target", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "VERTICAL_TILT_TARGET", ")", "tilt_target", ".", "value", "=", "0" ]
[ 60, 0 ]
[ 68, 25 ]
python
en
['en', 'en', 'en']
True
test_change_window_cover_state
(hass, utcnow)
Test that we can turn a HomeKit alarm on and off again.
Test that we can turn a HomeKit alarm on and off again.
async def test_change_window_cover_state(hass, utcnow): """Test that we can turn a HomeKit alarm on and off again.""" helper = await setup_test_component(hass, create_window_covering_service) await hass.services.async_call( "cover", "open_cover", {"entity_id": helper.entity_id}, blocking=True ) assert helper.characteristics[POSITION_TARGET].value == 100 await hass.services.async_call( "cover", "close_cover", {"entity_id": helper.entity_id}, blocking=True ) assert helper.characteristics[POSITION_TARGET].value == 0
[ "async", "def", "test_change_window_cover_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_window_covering_service", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"open_cover\"", ",", "{", "\"entity_id\"", ":", "helper", ".", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "helper", ".", "characteristics", "[", "POSITION_TARGET", "]", ".", "value", "==", "100", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"close_cover\"", ",", "{", "\"entity_id\"", ":", "helper", ".", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "helper", ".", "characteristics", "[", "POSITION_TARGET", "]", ".", "value", "==", "0" ]
[ 71, 0 ]
[ 83, 61 ]
python
en
['en', 'en', 'en']
True
test_read_window_cover_state
(hass, utcnow)
Test that we can read the state of a HomeKit alarm accessory.
Test that we can read the state of a HomeKit alarm accessory.
async def test_read_window_cover_state(hass, utcnow): """Test that we can read the state of a HomeKit alarm accessory.""" helper = await setup_test_component(hass, create_window_covering_service) helper.characteristics[POSITION_STATE].value = 0 state = await helper.poll_and_get_state() assert state.state == "closing" helper.characteristics[POSITION_STATE].value = 1 state = await helper.poll_and_get_state() assert state.state == "opening" helper.characteristics[POSITION_STATE].value = 2 state = await helper.poll_and_get_state() assert state.state == "closed" helper.characteristics[WINDOW_OBSTRUCTION].value = True state = await helper.poll_and_get_state() assert state.attributes["obstruction-detected"] is True
[ "async", "def", "test_read_window_cover_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_window_covering_service", ")", "helper", ".", "characteristics", "[", "POSITION_STATE", "]", ".", "value", "=", "0", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"closing\"", "helper", ".", "characteristics", "[", "POSITION_STATE", "]", ".", "value", "=", "1", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"opening\"", "helper", ".", "characteristics", "[", "POSITION_STATE", "]", ".", "value", "=", "2", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"closed\"", "helper", ".", "characteristics", "[", "WINDOW_OBSTRUCTION", "]", ".", "value", "=", "True", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "attributes", "[", "\"obstruction-detected\"", "]", "is", "True" ]
[ 86, 0 ]
[ 104, 59 ]
python
en
['en', 'en', 'en']
True
test_read_window_cover_tilt_horizontal
(hass, utcnow)
Test that horizontal tilt is handled correctly.
Test that horizontal tilt is handled correctly.
async def test_read_window_cover_tilt_horizontal(hass, utcnow): """Test that horizontal tilt is handled correctly.""" helper = await setup_test_component( hass, create_window_covering_service_with_h_tilt ) helper.characteristics[H_TILT_CURRENT].value = 75 state = await helper.poll_and_get_state() assert state.attributes["current_tilt_position"] == 75
[ "async", "def", "test_read_window_cover_tilt_horizontal", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_window_covering_service_with_h_tilt", ")", "helper", ".", "characteristics", "[", "H_TILT_CURRENT", "]", ".", "value", "=", "75", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "attributes", "[", "\"current_tilt_position\"", "]", "==", "75" ]
[ 107, 0 ]
[ 115, 58 ]
python
en
['en', 'en', 'en']
True
test_read_window_cover_tilt_vertical
(hass, utcnow)
Test that vertical tilt is handled correctly.
Test that vertical tilt is handled correctly.
async def test_read_window_cover_tilt_vertical(hass, utcnow): """Test that vertical tilt is handled correctly.""" helper = await setup_test_component( hass, create_window_covering_service_with_v_tilt ) helper.characteristics[V_TILT_CURRENT].value = 75 state = await helper.poll_and_get_state() assert state.attributes["current_tilt_position"] == 75
[ "async", "def", "test_read_window_cover_tilt_vertical", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_window_covering_service_with_v_tilt", ")", "helper", ".", "characteristics", "[", "V_TILT_CURRENT", "]", ".", "value", "=", "75", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "attributes", "[", "\"current_tilt_position\"", "]", "==", "75" ]
[ 118, 0 ]
[ 126, 58 ]
python
en
['en', 'en', 'en']
True
test_write_window_cover_tilt_horizontal
(hass, utcnow)
Test that horizontal tilt is written correctly.
Test that horizontal tilt is written correctly.
async def test_write_window_cover_tilt_horizontal(hass, utcnow): """Test that horizontal tilt is written correctly.""" helper = await setup_test_component( hass, create_window_covering_service_with_h_tilt ) await hass.services.async_call( "cover", "set_cover_tilt_position", {"entity_id": helper.entity_id, "tilt_position": 90}, blocking=True, ) assert helper.characteristics[H_TILT_TARGET].value == 90
[ "async", "def", "test_write_window_cover_tilt_horizontal", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_window_covering_service_with_h_tilt", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"set_cover_tilt_position\"", ",", "{", "\"entity_id\"", ":", "helper", ".", "entity_id", ",", "\"tilt_position\"", ":", "90", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "H_TILT_TARGET", "]", ".", "value", "==", "90" ]
[ 129, 0 ]
[ 141, 60 ]
python
en
['en', 'hu', 'en']
True
test_write_window_cover_tilt_vertical
(hass, utcnow)
Test that vertical tilt is written correctly.
Test that vertical tilt is written correctly.
async def test_write_window_cover_tilt_vertical(hass, utcnow): """Test that vertical tilt is written correctly.""" helper = await setup_test_component( hass, create_window_covering_service_with_v_tilt ) await hass.services.async_call( "cover", "set_cover_tilt_position", {"entity_id": helper.entity_id, "tilt_position": 90}, blocking=True, ) assert helper.characteristics[V_TILT_TARGET].value == 90
[ "async", "def", "test_write_window_cover_tilt_vertical", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_window_covering_service_with_v_tilt", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"set_cover_tilt_position\"", ",", "{", "\"entity_id\"", ":", "helper", ".", "entity_id", ",", "\"tilt_position\"", ":", "90", "}", ",", "blocking", "=", "True", ",", ")", "assert", "helper", ".", "characteristics", "[", "V_TILT_TARGET", "]", ".", "value", "==", "90" ]
[ 144, 0 ]
[ 156, 60 ]
python
en
['en', 'lb', 'en']
True
test_window_cover_stop
(hass, utcnow)
Test that vertical tilt is written correctly.
Test that vertical tilt is written correctly.
async def test_window_cover_stop(hass, utcnow): """Test that vertical tilt is written correctly.""" helper = await setup_test_component( hass, create_window_covering_service_with_v_tilt ) await hass.services.async_call( "cover", "stop_cover", {"entity_id": helper.entity_id}, blocking=True ) assert helper.characteristics[POSITION_HOLD].value == 1
[ "async", "def", "test_window_cover_stop", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_window_covering_service_with_v_tilt", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"stop_cover\"", ",", "{", "\"entity_id\"", ":", "helper", ".", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "helper", ".", "characteristics", "[", "POSITION_HOLD", "]", ".", "value", "==", "1" ]
[ 159, 0 ]
[ 168, 59 ]
python
en
['en', 'lb', 'en']
True
create_garage_door_opener_service
(accessory)
Define a garage-door-opener chars as per page 217 of HAP spec.
Define a garage-door-opener chars as per page 217 of HAP spec.
def create_garage_door_opener_service(accessory): """Define a garage-door-opener chars as per page 217 of HAP spec.""" service = accessory.add_service(ServicesTypes.GARAGE_DOOR_OPENER) cur_state = service.add_char(CharacteristicsTypes.DOOR_STATE_CURRENT) cur_state.value = 0 cur_state = service.add_char(CharacteristicsTypes.DOOR_STATE_TARGET) cur_state.value = 0 obstruction = service.add_char(CharacteristicsTypes.OBSTRUCTION_DETECTED) obstruction.value = False name = service.add_char(CharacteristicsTypes.NAME) name.value = "testdevice" return service
[ "def", "create_garage_door_opener_service", "(", "accessory", ")", ":", "service", "=", "accessory", ".", "add_service", "(", "ServicesTypes", ".", "GARAGE_DOOR_OPENER", ")", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "DOOR_STATE_CURRENT", ")", "cur_state", ".", "value", "=", "0", "cur_state", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "DOOR_STATE_TARGET", ")", "cur_state", ".", "value", "=", "0", "obstruction", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "OBSTRUCTION_DETECTED", ")", "obstruction", ".", "value", "=", "False", "name", "=", "service", ".", "add_char", "(", "CharacteristicsTypes", ".", "NAME", ")", "name", ".", "value", "=", "\"testdevice\"", "return", "service" ]
[ 171, 0 ]
[ 187, 18 ]
python
en
['en', 'nl', 'en']
True
test_change_door_state
(hass, utcnow)
Test that we can turn open and close a HomeKit garage door.
Test that we can turn open and close a HomeKit garage door.
async def test_change_door_state(hass, utcnow): """Test that we can turn open and close a HomeKit garage door.""" helper = await setup_test_component(hass, create_garage_door_opener_service) await hass.services.async_call( "cover", "open_cover", {"entity_id": helper.entity_id}, blocking=True ) assert helper.characteristics[DOOR_TARGET].value == 0 await hass.services.async_call( "cover", "close_cover", {"entity_id": helper.entity_id}, blocking=True ) assert helper.characteristics[DOOR_TARGET].value == 1
[ "async", "def", "test_change_door_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_garage_door_opener_service", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"open_cover\"", ",", "{", "\"entity_id\"", ":", "helper", ".", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "helper", ".", "characteristics", "[", "DOOR_TARGET", "]", ".", "value", "==", "0", "await", "hass", ".", "services", ".", "async_call", "(", "\"cover\"", ",", "\"close_cover\"", ",", "{", "\"entity_id\"", ":", "helper", ".", "entity_id", "}", ",", "blocking", "=", "True", ")", "assert", "helper", ".", "characteristics", "[", "DOOR_TARGET", "]", ".", "value", "==", "1" ]
[ 190, 0 ]
[ 202, 57 ]
python
en
['en', 'en', 'en']
True
test_read_door_state
(hass, utcnow)
Test that we can read the state of a HomeKit garage door.
Test that we can read the state of a HomeKit garage door.
async def test_read_door_state(hass, utcnow): """Test that we can read the state of a HomeKit garage door.""" helper = await setup_test_component(hass, create_garage_door_opener_service) helper.characteristics[DOOR_CURRENT].value = 0 state = await helper.poll_and_get_state() assert state.state == "open" helper.characteristics[DOOR_CURRENT].value = 1 state = await helper.poll_and_get_state() assert state.state == "closed" helper.characteristics[DOOR_CURRENT].value = 2 state = await helper.poll_and_get_state() assert state.state == "opening" helper.characteristics[DOOR_CURRENT].value = 3 state = await helper.poll_and_get_state() assert state.state == "closing" helper.characteristics[DOOR_OBSTRUCTION].value = True state = await helper.poll_and_get_state() assert state.attributes["obstruction-detected"] is True
[ "async", "def", "test_read_door_state", "(", "hass", ",", "utcnow", ")", ":", "helper", "=", "await", "setup_test_component", "(", "hass", ",", "create_garage_door_opener_service", ")", "helper", ".", "characteristics", "[", "DOOR_CURRENT", "]", ".", "value", "=", "0", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"open\"", "helper", ".", "characteristics", "[", "DOOR_CURRENT", "]", ".", "value", "=", "1", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"closed\"", "helper", ".", "characteristics", "[", "DOOR_CURRENT", "]", ".", "value", "=", "2", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"opening\"", "helper", ".", "characteristics", "[", "DOOR_CURRENT", "]", ".", "value", "=", "3", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "state", "==", "\"closing\"", "helper", ".", "characteristics", "[", "DOOR_OBSTRUCTION", "]", ".", "value", "=", "True", "state", "=", "await", "helper", ".", "poll_and_get_state", "(", ")", "assert", "state", ".", "attributes", "[", "\"obstruction-detected\"", "]", "is", "True" ]
[ 205, 0 ]
[ 227, 59 ]
python
en
['en', 'en', 'en']
True
MatMulWrapper.forward
(self, mat1, mat2)
:param inputs: two torch tensors :return: matmul of these tensors Here are the typical dimensions found in BERT (the B is optional) mat1.shape: [B, <optional extra dims>, M, K] mat2.shape: [B, <optional extra dims>, K, N] output shape: [B, <optional extra dims>, M, N]
def forward(self, mat1, mat2): """ :param inputs: two torch tensors :return: matmul of these tensors Here are the typical dimensions found in BERT (the B is optional) mat1.shape: [B, <optional extra dims>, M, K] mat2.shape: [B, <optional extra dims>, K, N] output shape: [B, <optional extra dims>, M, N] """ return torch.matmul(mat1, mat2)
[ "def", "forward", "(", "self", ",", "mat1", ",", "mat2", ")", ":", "return", "torch", ".", "matmul", "(", "mat1", ",", "mat2", ")" ]
[ 103, 4 ]
[ 111, 39 ]
python
en
['en', 'error', 'th']
False
SqueezeBertSelfAttention.__init__
(self, config, cin, q_groups=1, k_groups=1, v_groups=1)
config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers
config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers
def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1): """ config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers """ super().__init__() if cin % config.num_attention_heads != 0: raise ValueError( "cin (%d) is not a multiple of the number of attention " "heads (%d)" % (cin, config.num_attention_heads) ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(cin / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=q_groups) self.key = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=k_groups) self.value = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=v_groups) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.softmax = nn.Softmax(dim=-1) self.matmul_qk = MatMulWrapper() self.matmul_qkv = MatMulWrapper()
[ "def", "__init__", "(", "self", ",", "config", ",", "cin", ",", "q_groups", "=", "1", ",", "k_groups", "=", "1", ",", "v_groups", "=", "1", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "if", "cin", "%", "config", ".", "num_attention_heads", "!=", "0", ":", "raise", "ValueError", "(", "\"cin (%d) is not a multiple of the number of attention \"", "\"heads (%d)\"", "%", "(", "cin", ",", "config", ".", "num_attention_heads", ")", ")", "self", ".", "num_attention_heads", "=", "config", ".", "num_attention_heads", "self", ".", "attention_head_size", "=", "int", "(", "cin", "/", "config", ".", "num_attention_heads", ")", "self", ".", "all_head_size", "=", "self", ".", "num_attention_heads", "*", "self", ".", "attention_head_size", "self", ".", "query", "=", "nn", ".", "Conv1d", "(", "in_channels", "=", "cin", ",", "out_channels", "=", "cin", ",", "kernel_size", "=", "1", ",", "groups", "=", "q_groups", ")", "self", ".", "key", "=", "nn", ".", "Conv1d", "(", "in_channels", "=", "cin", ",", "out_channels", "=", "cin", ",", "kernel_size", "=", "1", ",", "groups", "=", "k_groups", ")", "self", ".", "value", "=", "nn", ".", "Conv1d", "(", "in_channels", "=", "cin", ",", "out_channels", "=", "cin", ",", "kernel_size", "=", "1", ",", "groups", "=", "v_groups", ")", "self", ".", "dropout", "=", "nn", ".", "Dropout", "(", "config", ".", "attention_probs_dropout_prob", ")", "self", ".", "softmax", "=", "nn", ".", "Softmax", "(", "dim", "=", "-", "1", ")", "self", ".", "matmul_qk", "=", "MatMulWrapper", "(", ")", "self", ".", "matmul_qkv", "=", "MatMulWrapper", "(", ")" ]
[ 166, 4 ]
[ 189, 41 ]
python
en
['en', 'error', 'th']
False
SqueezeBertSelfAttention.transpose_for_scores
(self, x)
- input: [N, C, W] - output: [N, C1, W, C2] where C1 is the head index, and C2 is one head's contents
- input: [N, C, W] - output: [N, C1, W, C2] where C1 is the head index, and C2 is one head's contents
def transpose_for_scores(self, x): """ - input: [N, C, W] - output: [N, C1, W, C2] where C1 is the head index, and C2 is one head's contents """ new_x_shape = (x.size()[0], self.num_attention_heads, self.attention_head_size, x.size()[-1]) # [N, C1, C2, W] x = x.view(*new_x_shape) return x.permute(0, 1, 3, 2)
[ "def", "transpose_for_scores", "(", "self", ",", "x", ")", ":", "new_x_shape", "=", "(", "x", ".", "size", "(", ")", "[", "0", "]", ",", "self", ".", "num_attention_heads", ",", "self", ".", "attention_head_size", ",", "x", ".", "size", "(", ")", "[", "-", "1", "]", ")", "# [N, C1, C2, W]", "x", "=", "x", ".", "view", "(", "*", "new_x_shape", ")", "return", "x", ".", "permute", "(", "0", ",", "1", ",", "3", ",", "2", ")" ]
[ 191, 4 ]
[ 198, 36 ]
python
en
['en', 'error', 'th']
False
SqueezeBertSelfAttention.transpose_key_for_scores
(self, x)
- input: [N, C, W] - output: [N, C1, C2, W] where C1 is the head index, and C2 is one head's contents
- input: [N, C, W] - output: [N, C1, C2, W] where C1 is the head index, and C2 is one head's contents
def transpose_key_for_scores(self, x): """ - input: [N, C, W] - output: [N, C1, C2, W] where C1 is the head index, and C2 is one head's contents """ new_x_shape = (x.size()[0], self.num_attention_heads, self.attention_head_size, x.size()[-1]) # [N, C1, C2, W] x = x.view(*new_x_shape) # no `permute` needed return x
[ "def", "transpose_key_for_scores", "(", "self", ",", "x", ")", ":", "new_x_shape", "=", "(", "x", ".", "size", "(", ")", "[", "0", "]", ",", "self", ".", "num_attention_heads", ",", "self", ".", "attention_head_size", ",", "x", ".", "size", "(", ")", "[", "-", "1", "]", ")", "# [N, C1, C2, W]", "x", "=", "x", ".", "view", "(", "*", "new_x_shape", ")", "# no `permute` needed", "return", "x" ]
[ 200, 4 ]
[ 208, 16 ]
python
en
['en', 'error', 'th']
False
SqueezeBertSelfAttention.transpose_output
(self, x)
- input: [N, C1, W, C2] - output: [N, C, W]
- input: [N, C1, W, C2] - output: [N, C, W]
def transpose_output(self, x): """ - input: [N, C1, W, C2] - output: [N, C, W] """ x = x.permute(0, 1, 3, 2).contiguous() # [N, C1, C2, W] new_x_shape = (x.size()[0], self.all_head_size, x.size()[3]) # [N, C, W] x = x.view(*new_x_shape) return x
[ "def", "transpose_output", "(", "self", ",", "x", ")", ":", "x", "=", "x", ".", "permute", "(", "0", ",", "1", ",", "3", ",", "2", ")", ".", "contiguous", "(", ")", "# [N, C1, C2, W]", "new_x_shape", "=", "(", "x", ".", "size", "(", ")", "[", "0", "]", ",", "self", ".", "all_head_size", ",", "x", ".", "size", "(", ")", "[", "3", "]", ")", "# [N, C, W]", "x", "=", "x", ".", "view", "(", "*", "new_x_shape", ")", "return", "x" ]
[ 210, 4 ]
[ 218, 16 ]
python
en
['en', 'error', 'th']
False
SqueezeBertSelfAttention.forward
(self, hidden_states, attention_mask, output_attentions)
expects hidden_states in [N, C, W] data layout. The attention_mask data layout is [N, W], and it does not need to be transposed.
expects hidden_states in [N, C, W] data layout.
def forward(self, hidden_states, attention_mask, output_attentions): """ expects hidden_states in [N, C, W] data layout. The attention_mask data layout is [N, W], and it does not need to be transposed. """ mixed_query_layer = self.query(hidden_states) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_key_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_score = self.matmul_qk(query_layer, key_layer) attention_score = attention_score / math.sqrt(self.attention_head_size) # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_score = attention_score + attention_mask # Normalize the attention scores to probabilities. attention_probs = self.softmax(attention_score) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) context_layer = self.matmul_qkv(attention_probs, value_layer) context_layer = self.transpose_output(context_layer) result = {"context_layer": context_layer} if output_attentions: result["attention_score"] = attention_score return result
[ "def", "forward", "(", "self", ",", "hidden_states", ",", "attention_mask", ",", "output_attentions", ")", ":", "mixed_query_layer", "=", "self", ".", "query", "(", "hidden_states", ")", "mixed_key_layer", "=", "self", ".", "key", "(", "hidden_states", ")", "mixed_value_layer", "=", "self", ".", "value", "(", "hidden_states", ")", "query_layer", "=", "self", ".", "transpose_for_scores", "(", "mixed_query_layer", ")", "key_layer", "=", "self", ".", "transpose_key_for_scores", "(", "mixed_key_layer", ")", "value_layer", "=", "self", ".", "transpose_for_scores", "(", "mixed_value_layer", ")", "# Take the dot product between \"query\" and \"key\" to get the raw attention scores.", "attention_score", "=", "self", ".", "matmul_qk", "(", "query_layer", ",", "key_layer", ")", "attention_score", "=", "attention_score", "/", "math", ".", "sqrt", "(", "self", ".", "attention_head_size", ")", "# Apply the attention mask is (precomputed for all layers in BertModel forward() function)", "attention_score", "=", "attention_score", "+", "attention_mask", "# Normalize the attention scores to probabilities.", "attention_probs", "=", "self", ".", "softmax", "(", "attention_score", ")", "# This is actually dropping out entire tokens to attend to, which might", "# seem a bit unusual, but is taken from the original Transformer paper.", "attention_probs", "=", "self", ".", "dropout", "(", "attention_probs", ")", "context_layer", "=", "self", ".", "matmul_qkv", "(", "attention_probs", ",", "value_layer", ")", "context_layer", "=", "self", ".", "transpose_output", "(", "context_layer", ")", "result", "=", "{", "\"context_layer\"", ":", "context_layer", "}", "if", "output_attentions", ":", "result", "[", "\"attention_score\"", "]", "=", "attention_score", "return", "result" ]
[ 220, 4 ]
[ 253, 21 ]
python
en
['en', 'error', 'th']
False
SqueezeBertModule.__init__
(self, config)
- hidden_size = input chans = output chans for Q, K, V (they are all the same ... for now) = output chans for the module - intermediate_size = output chans for intermediate layer - groups = number of groups for all layers in the BertModule. (eventually we could change the interface to allow different groups for different layers)
- hidden_size = input chans = output chans for Q, K, V (they are all the same ... for now) = output chans for the module - intermediate_size = output chans for intermediate layer - groups = number of groups for all layers in the BertModule. (eventually we could change the interface to allow different groups for different layers)
def __init__(self, config): """ - hidden_size = input chans = output chans for Q, K, V (they are all the same ... for now) = output chans for the module - intermediate_size = output chans for intermediate layer - groups = number of groups for all layers in the BertModule. (eventually we could change the interface to allow different groups for different layers) """ super().__init__() c0 = config.hidden_size c1 = config.hidden_size c2 = config.intermediate_size c3 = config.hidden_size self.attention = SqueezeBertSelfAttention( config=config, cin=c0, q_groups=config.q_groups, k_groups=config.k_groups, v_groups=config.v_groups ) self.post_attention = ConvDropoutLayerNorm( cin=c0, cout=c1, groups=config.post_attention_groups, dropout_prob=config.hidden_dropout_prob ) self.intermediate = ConvActivation(cin=c1, cout=c2, groups=config.intermediate_groups, act=config.hidden_act) self.output = ConvDropoutLayerNorm( cin=c2, cout=c3, groups=config.output_groups, dropout_prob=config.hidden_dropout_prob )
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "c0", "=", "config", ".", "hidden_size", "c1", "=", "config", ".", "hidden_size", "c2", "=", "config", ".", "intermediate_size", "c3", "=", "config", ".", "hidden_size", "self", ".", "attention", "=", "SqueezeBertSelfAttention", "(", "config", "=", "config", ",", "cin", "=", "c0", ",", "q_groups", "=", "config", ".", "q_groups", ",", "k_groups", "=", "config", ".", "k_groups", ",", "v_groups", "=", "config", ".", "v_groups", ")", "self", ".", "post_attention", "=", "ConvDropoutLayerNorm", "(", "cin", "=", "c0", ",", "cout", "=", "c1", ",", "groups", "=", "config", ".", "post_attention_groups", ",", "dropout_prob", "=", "config", ".", "hidden_dropout_prob", ")", "self", ".", "intermediate", "=", "ConvActivation", "(", "cin", "=", "c1", ",", "cout", "=", "c2", ",", "groups", "=", "config", ".", "intermediate_groups", ",", "act", "=", "config", ".", "hidden_act", ")", "self", ".", "output", "=", "ConvDropoutLayerNorm", "(", "cin", "=", "c2", ",", "cout", "=", "c3", ",", "groups", "=", "config", ".", "output_groups", ",", "dropout_prob", "=", "config", ".", "hidden_dropout_prob", ")" ]
[ 257, 4 ]
[ 281, 9 ]
python
en
['en', 'error', 'th']
False
SqueezeBertPreTrainedModel._init_weights
(self, module)
Initialize the weights
Initialize the weights
def _init_weights(self, module): """ Initialize the weights """ if isinstance(module, (nn.Linear, nn.Conv1d)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, SqueezeBertLayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0)
[ "def", "_init_weights", "(", "self", ",", "module", ")", ":", "if", "isinstance", "(", "module", ",", "(", "nn", ".", "Linear", ",", "nn", ".", "Conv1d", ")", ")", ":", "# Slightly different from the TF version which uses truncated_normal for initialization", "# cf https://github.com/pytorch/pytorch/pull/5617", "module", ".", "weight", ".", "data", ".", "normal_", "(", "mean", "=", "0.0", ",", "std", "=", "self", ".", "config", ".", "initializer_range", ")", "if", "module", ".", "bias", "is", "not", "None", ":", "module", ".", "bias", ".", "data", ".", "zero_", "(", ")", "elif", "isinstance", "(", "module", ",", "nn", ".", "Embedding", ")", ":", "module", ".", "weight", ".", "data", ".", "normal_", "(", "mean", "=", "0.0", ",", "std", "=", "self", ".", "config", ".", "initializer_range", ")", "if", "module", ".", "padding_idx", "is", "not", "None", ":", "module", ".", "weight", ".", "data", "[", "module", ".", "padding_idx", "]", ".", "zero_", "(", ")", "elif", "isinstance", "(", "module", ",", "SqueezeBertLayerNorm", ")", ":", "module", ".", "bias", ".", "data", ".", "zero_", "(", ")", "module", ".", "weight", ".", "data", ".", "fill_", "(", "1.0", ")" ]
[ 433, 4 ]
[ 447, 41 ]
python
en
['en', 'en', 'en']
True
MeteoFranceFlowHandler.__init__
(self)
Init MeteoFranceFlowHandler.
Init MeteoFranceFlowHandler.
def __init__(self): """Init MeteoFranceFlowHandler.""" self.places = []
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "places", "=", "[", "]" ]
[ 23, 4 ]
[ 25, 24 ]
python
en
['en', 'id', 'nl']
False
MeteoFranceFlowHandler.async_get_options_flow
(config_entry)
Get the options flow for this handler.
Get the options flow for this handler.
def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return MeteoFranceOptionsFlowHandler(config_entry)
[ "def", "async_get_options_flow", "(", "config_entry", ")", ":", "return", "MeteoFranceOptionsFlowHandler", "(", "config_entry", ")" ]
[ 29, 4 ]
[ 31, 58 ]
python
en
['en', 'en', 'en']
True
MeteoFranceFlowHandler._show_setup_form
(self, user_input=None, errors=None)
Show the setup form to the user.
Show the setup form to the user.
def _show_setup_form(self, user_input=None, errors=None): """Show the setup form to the user.""" if user_input is None: user_input = {} return self.async_show_form( step_id="user", data_schema=vol.Schema( {vol.Required(CONF_CITY, default=user_input.get(CONF_CITY, "")): str} ), errors=errors or {}, )
[ "def", "_show_setup_form", "(", "self", ",", "user_input", "=", "None", ",", "errors", "=", "None", ")", ":", "if", "user_input", "is", "None", ":", "user_input", "=", "{", "}", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_CITY", ",", "default", "=", "user_input", ".", "get", "(", "CONF_CITY", ",", "\"\"", ")", ")", ":", "str", "}", ")", ",", "errors", "=", "errors", "or", "{", "}", ",", ")" ]
[ 34, 4 ]
[ 46, 9 ]
python
en
['en', 'en', 'en']
True
MeteoFranceFlowHandler.async_step_user
(self, user_input=None)
Handle a flow initiated by the user.
Handle a flow initiated by the user.
async def async_step_user(self, user_input=None): """Handle a flow initiated by the user.""" errors = {} if user_input is None: return self._show_setup_form(user_input, errors) city = user_input[CONF_CITY] # Might be a city name or a postal code latitude = user_input.get(CONF_LATITUDE) longitude = user_input.get(CONF_LONGITUDE) if not latitude: client = MeteoFranceClient() self.places = await self.hass.async_add_executor_job( client.search_places, city ) _LOGGER.debug("Places search result: %s", self.places) if not self.places: errors[CONF_CITY] = "empty" return self._show_setup_form(user_input, errors) return await self.async_step_cities() # Check if already configured await self.async_set_unique_id(f"{latitude}, {longitude}") self._abort_if_unique_id_configured() return self.async_create_entry( title=city, data={CONF_LATITUDE: latitude, CONF_LONGITUDE: longitude}, )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "None", ":", "return", "self", ".", "_show_setup_form", "(", "user_input", ",", "errors", ")", "city", "=", "user_input", "[", "CONF_CITY", "]", "# Might be a city name or a postal code", "latitude", "=", "user_input", ".", "get", "(", "CONF_LATITUDE", ")", "longitude", "=", "user_input", ".", "get", "(", "CONF_LONGITUDE", ")", "if", "not", "latitude", ":", "client", "=", "MeteoFranceClient", "(", ")", "self", ".", "places", "=", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "client", ".", "search_places", ",", "city", ")", "_LOGGER", ".", "debug", "(", "\"Places search result: %s\"", ",", "self", ".", "places", ")", "if", "not", "self", ".", "places", ":", "errors", "[", "CONF_CITY", "]", "=", "\"empty\"", "return", "self", ".", "_show_setup_form", "(", "user_input", ",", "errors", ")", "return", "await", "self", ".", "async_step_cities", "(", ")", "# Check if already configured", "await", "self", ".", "async_set_unique_id", "(", "f\"{latitude}, {longitude}\"", ")", "self", ".", "_abort_if_unique_id_configured", "(", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "city", ",", "data", "=", "{", "CONF_LATITUDE", ":", "latitude", ",", "CONF_LONGITUDE", ":", "longitude", "}", ",", ")" ]
[ 48, 4 ]
[ 78, 9 ]
python
en
['en', 'en', 'en']
True
MeteoFranceFlowHandler.async_step_import
(self, user_input)
Import a config entry.
Import a config entry.
async def async_step_import(self, user_input): """Import a config entry.""" return await self.async_step_user(user_input)
[ "async", "def", "async_step_import", "(", "self", ",", "user_input", ")", ":", "return", "await", "self", ".", "async_step_user", "(", "user_input", ")" ]
[ 80, 4 ]
[ 82, 53 ]
python
en
['en', 'en', 'en']
True
MeteoFranceFlowHandler.async_step_cities
(self, user_input=None)
Step where the user choose the city from the API search results.
Step where the user choose the city from the API search results.
async def async_step_cities(self, user_input=None): """Step where the user choose the city from the API search results.""" if not user_input: if len(self.places) > 1 and self.source != SOURCE_IMPORT: places_for_form = {} for place in self.places: places_for_form[_build_place_key(place)] = f"{place}" return self.async_show_form( step_id="cities", data_schema=vol.Schema( { vol.Required(CONF_CITY): vol.All( vol.Coerce(str), vol.In(places_for_form) ) } ), ) user_input = {CONF_CITY: _build_place_key(self.places[0])} city_infos = user_input[CONF_CITY].split(";") return await self.async_step_user( { CONF_CITY: city_infos[0], CONF_LATITUDE: city_infos[1], CONF_LONGITUDE: city_infos[2], } )
[ "async", "def", "async_step_cities", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "not", "user_input", ":", "if", "len", "(", "self", ".", "places", ")", ">", "1", "and", "self", ".", "source", "!=", "SOURCE_IMPORT", ":", "places_for_form", "=", "{", "}", "for", "place", "in", "self", ".", "places", ":", "places_for_form", "[", "_build_place_key", "(", "place", ")", "]", "=", "f\"{place}\"", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"cities\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_CITY", ")", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "str", ")", ",", "vol", ".", "In", "(", "places_for_form", ")", ")", "}", ")", ",", ")", "user_input", "=", "{", "CONF_CITY", ":", "_build_place_key", "(", "self", ".", "places", "[", "0", "]", ")", "}", "city_infos", "=", "user_input", "[", "CONF_CITY", "]", ".", "split", "(", "\";\"", ")", "return", "await", "self", ".", "async_step_user", "(", "{", "CONF_CITY", ":", "city_infos", "[", "0", "]", ",", "CONF_LATITUDE", ":", "city_infos", "[", "1", "]", ",", "CONF_LONGITUDE", ":", "city_infos", "[", "2", "]", ",", "}", ")" ]
[ 84, 4 ]
[ 111, 9 ]
python
en
['en', 'en', 'en']
True
MeteoFranceOptionsFlowHandler.__init__
(self, config_entry: config_entries.ConfigEntry)
Initialize options flow.
Initialize options flow.
def __init__(self, config_entry: config_entries.ConfigEntry): """Initialize options flow.""" self.config_entry = config_entry
[ "def", "__init__", "(", "self", ",", "config_entry", ":", "config_entries", ".", "ConfigEntry", ")", ":", "self", ".", "config_entry", "=", "config_entry" ]
[ 117, 4 ]
[ 119, 40 ]
python
en
['en', 'en', 'en']
True
MeteoFranceOptionsFlowHandler.async_step_init
(self, user_input=None)
Handle options flow.
Handle options flow.
async def async_step_init(self, user_input=None): """Handle options flow.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) data_schema = vol.Schema( { vol.Optional( CONF_MODE, default=self.config_entry.options.get( CONF_MODE, FORECAST_MODE_DAILY ), ): vol.In(FORECAST_MODE) } ) return self.async_show_form(step_id="init", data_schema=data_schema)
[ "async", "def", "async_step_init", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "user_input", "is", "not", "None", ":", "return", "self", ".", "async_create_entry", "(", "title", "=", "\"\"", ",", "data", "=", "user_input", ")", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "CONF_MODE", ",", "default", "=", "self", ".", "config_entry", ".", "options", ".", "get", "(", "CONF_MODE", ",", "FORECAST_MODE_DAILY", ")", ",", ")", ":", "vol", ".", "In", "(", "FORECAST_MODE", ")", "}", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"init\"", ",", "data_schema", "=", "data_schema", ")" ]
[ 121, 4 ]
[ 136, 76 ]
python
en
['en', 'nl', 'en']
True
_handle_errors
(func)
Handle error with WebSocket calls.
Handle error with WebSocket calls.
def _handle_errors(func): """Handle error with WebSocket calls.""" @wraps(func) async def send_with_error_handling(hass, connection, msg): url_path = msg.get(CONF_URL_PATH) config = hass.data[DOMAIN]["dashboards"].get(url_path) if config is None: connection.send_error( msg["id"], "config_not_found", f"Unknown config specified: {url_path}" ) return error = None try: result = await func(hass, connection, msg, config) except ConfigNotFound: error = "config_not_found", "No config found." except HomeAssistantError as err: error = "error", str(err) if error is not None: connection.send_error(msg["id"], *error) return if msg is not None: await connection.send_big_result(msg["id"], result) else: connection.send_result(msg["id"], result) return send_with_error_handling
[ "def", "_handle_errors", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "async", "def", "send_with_error_handling", "(", "hass", ",", "connection", ",", "msg", ")", ":", "url_path", "=", "msg", ".", "get", "(", "CONF_URL_PATH", ")", "config", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"dashboards\"", "]", ".", "get", "(", "url_path", ")", "if", "config", "is", "None", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"config_not_found\"", ",", "f\"Unknown config specified: {url_path}\"", ")", "return", "error", "=", "None", "try", ":", "result", "=", "await", "func", "(", "hass", ",", "connection", ",", "msg", ",", "config", ")", "except", "ConfigNotFound", ":", "error", "=", "\"config_not_found\"", ",", "\"No config found.\"", "except", "HomeAssistantError", "as", "err", ":", "error", "=", "\"error\"", ",", "str", "(", "err", ")", "if", "error", "is", "not", "None", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "*", "error", ")", "return", "if", "msg", "is", "not", "None", ":", "await", "connection", ".", "send_big_result", "(", "msg", "[", "\"id\"", "]", ",", "result", ")", "else", ":", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "result", ")", "return", "send_with_error_handling" ]
[ 13, 0 ]
[ 44, 35 ]
python
en
['en', 'nl', 'en']
True
websocket_lovelace_resources
(hass, connection, msg)
Send Lovelace UI resources over WebSocket configuration.
Send Lovelace UI resources over WebSocket configuration.
async def websocket_lovelace_resources(hass, connection, msg): """Send Lovelace UI resources over WebSocket configuration.""" resources = hass.data[DOMAIN]["resources"] if not resources.loaded: await resources.async_load() resources.loaded = True connection.send_result(msg["id"], resources.async_items())
[ "async", "def", "websocket_lovelace_resources", "(", "hass", ",", "connection", ",", "msg", ")", ":", "resources", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"resources\"", "]", "if", "not", "resources", ".", "loaded", ":", "await", "resources", ".", "async_load", "(", ")", "resources", ".", "loaded", "=", "True", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "resources", ".", "async_items", "(", ")", ")" ]
[ 49, 0 ]
[ 57, 62 ]
python
en
['en', 'da', 'en']
True
websocket_lovelace_config
(hass, connection, msg, config)
Send Lovelace UI config over WebSocket configuration.
Send Lovelace UI config over WebSocket configuration.
async def websocket_lovelace_config(hass, connection, msg, config): """Send Lovelace UI config over WebSocket configuration.""" return await config.async_load(msg["force"])
[ "async", "def", "websocket_lovelace_config", "(", "hass", ",", "connection", ",", "msg", ",", "config", ")", ":", "return", "await", "config", ".", "async_load", "(", "msg", "[", "\"force\"", "]", ")" ]
[ 69, 0 ]
[ 71, 48 ]
python
en
['en', 'da', 'en']
True
websocket_lovelace_save_config
(hass, connection, msg, config)
Save Lovelace UI configuration.
Save Lovelace UI configuration.
async def websocket_lovelace_save_config(hass, connection, msg, config): """Save Lovelace UI configuration.""" await config.async_save(msg["config"])
[ "async", "def", "websocket_lovelace_save_config", "(", "hass", ",", "connection", ",", "msg", ",", "config", ")", ":", "await", "config", ".", "async_save", "(", "msg", "[", "\"config\"", "]", ")" ]
[ 84, 0 ]
[ 86, 42 ]
python
en
['en', 'ro', 'en']
True
websocket_lovelace_delete_config
(hass, connection, msg, config)
Delete Lovelace UI configuration.
Delete Lovelace UI configuration.
async def websocket_lovelace_delete_config(hass, connection, msg, config): """Delete Lovelace UI configuration.""" await config.async_delete()
[ "async", "def", "websocket_lovelace_delete_config", "(", "hass", ",", "connection", ",", "msg", ",", "config", ")", ":", "await", "config", ".", "async_delete", "(", ")" ]
[ 98, 0 ]
[ 100, 31 ]
python
en
['en', 'fr', 'en']
True
websocket_lovelace_dashboards
(hass, connection, msg)
Delete Lovelace UI configuration.
Delete Lovelace UI configuration.
def websocket_lovelace_dashboards(hass, connection, msg): """Delete Lovelace UI configuration.""" connection.send_result( msg["id"], [ dashboard.config for dashboard in hass.data[DOMAIN]["dashboards"].values() if dashboard.config ], )
[ "def", "websocket_lovelace_dashboards", "(", "hass", ",", "connection", ",", "msg", ")", ":", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "[", "dashboard", ".", "config", "for", "dashboard", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"dashboards\"", "]", ".", "values", "(", ")", "if", "dashboard", ".", "config", "]", ",", ")" ]
[ 105, 0 ]
[ 114, 5 ]
python
en
['en', 'fr', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up tellduslive sensors dynamically.
Set up tellduslive sensors dynamically.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up tellduslive sensors dynamically.""" async def async_discover_binary_sensor(device_id): """Discover and add a discovered sensor.""" client = hass.data[tellduslive.DOMAIN] async_add_entities([TelldusLiveSensor(client, device_id)]) async_dispatcher_connect( hass, tellduslive.TELLDUS_DISCOVERY_NEW.format( binary_sensor.DOMAIN, tellduslive.DOMAIN ), async_discover_binary_sensor, )
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "async", "def", "async_discover_binary_sensor", "(", "device_id", ")", ":", "\"\"\"Discover and add a discovered sensor.\"\"\"", "client", "=", "hass", ".", "data", "[", "tellduslive", ".", "DOMAIN", "]", "async_add_entities", "(", "[", "TelldusLiveSensor", "(", "client", ",", "device_id", ")", "]", ")", "async_dispatcher_connect", "(", "hass", ",", "tellduslive", ".", "TELLDUS_DISCOVERY_NEW", ".", "format", "(", "binary_sensor", ".", "DOMAIN", ",", "tellduslive", ".", "DOMAIN", ")", ",", "async_discover_binary_sensor", ",", ")" ]
[ 8, 0 ]
[ 22, 5 ]
python
en
['en', 'hu', 'en']
True
TelldusLiveSensor.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.device.is_on
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "device", ".", "is_on" ]
[ 29, 4 ]
[ 31, 32 ]
python
en
['en', 'fy', 'en']
True
setup
(hass, config)
Set up the Raspberry PI PFIO component.
Set up the Raspberry PI PFIO component.
def setup(hass, config): """Set up the Raspberry PI PFIO component.""" pifacedigital = PFIO.PiFaceDigital() hass.data[DATA_PFIO_LISTENER] = PFIO.InputEventListener(chip=pifacedigital) def cleanup_pfio(event): """Stuff to do before stopping.""" PFIO.deinit() def prepare_pfio(event): """Stuff to do when Home Assistant starts.""" hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, cleanup_pfio) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, prepare_pfio) PFIO.init() return True
[ "def", "setup", "(", "hass", ",", "config", ")", ":", "pifacedigital", "=", "PFIO", ".", "PiFaceDigital", "(", ")", "hass", ".", "data", "[", "DATA_PFIO_LISTENER", "]", "=", "PFIO", ".", "InputEventListener", "(", "chip", "=", "pifacedigital", ")", "def", "cleanup_pfio", "(", "event", ")", ":", "\"\"\"Stuff to do before stopping.\"\"\"", "PFIO", ".", "deinit", "(", ")", "def", "prepare_pfio", "(", "event", ")", ":", "\"\"\"Stuff to do when Home Assistant starts.\"\"\"", "hass", ".", "bus", ".", "listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "cleanup_pfio", ")", "hass", ".", "bus", ".", "listen_once", "(", "EVENT_HOMEASSISTANT_START", ",", "prepare_pfio", ")", "PFIO", ".", "init", "(", ")", "return", "True" ]
[ 10, 0 ]
[ 26, 15 ]
python
en
['en', 'sr', 'en']
True
write_output
(port, value)
Write a value to a PFIO.
Write a value to a PFIO.
def write_output(port, value): """Write a value to a PFIO.""" PFIO.digital_write(port, value)
[ "def", "write_output", "(", "port", ",", "value", ")", ":", "PFIO", ".", "digital_write", "(", "port", ",", "value", ")" ]
[ 29, 0 ]
[ 31, 35 ]
python
en
['en', 'pt', 'en']
True
read_input
(port)
Read a value from a PFIO.
Read a value from a PFIO.
def read_input(port): """Read a value from a PFIO.""" return PFIO.digital_read(port)
[ "def", "read_input", "(", "port", ")", ":", "return", "PFIO", ".", "digital_read", "(", "port", ")" ]
[ 34, 0 ]
[ 36, 34 ]
python
en
['en', 'en', 'en']
True
edge_detect
(hass, port, event_callback, settle)
Add detection for RISING and FALLING events.
Add detection for RISING and FALLING events.
def edge_detect(hass, port, event_callback, settle): """Add detection for RISING and FALLING events.""" hass.data[DATA_PFIO_LISTENER].register( port, PFIO.IODIR_BOTH, event_callback, settle_time=settle )
[ "def", "edge_detect", "(", "hass", ",", "port", ",", "event_callback", ",", "settle", ")", ":", "hass", ".", "data", "[", "DATA_PFIO_LISTENER", "]", ".", "register", "(", "port", ",", "PFIO", ".", "IODIR_BOTH", ",", "event_callback", ",", "settle_time", "=", "settle", ")" ]
[ 39, 0 ]
[ 43, 5 ]
python
en
['en', 'en', 'en']
True
activate_listener
(hass)
Activate the registered listener events.
Activate the registered listener events.
def activate_listener(hass): """Activate the registered listener events.""" hass.data[DATA_PFIO_LISTENER].activate()
[ "def", "activate_listener", "(", "hass", ")", ":", "hass", ".", "data", "[", "DATA_PFIO_LISTENER", "]", ".", "activate", "(", ")" ]
[ 46, 0 ]
[ 48, 44 ]
python
en
['en', 'en', 'en']
True
test_sensor
(hass)
Test states of the sensor.
Test states of the sensor.
async def test_sensor(hass): """Test states of the sensor.""" await init_integration(hass) registry = await hass.helpers.entity_registry.async_get_registry() state = hass.states.get("sensor.home_humidity") assert state assert state.state == "92.8" assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == PERCENTAGE assert state.attributes.get(ATTR_DEVICE_CLASS) == DEVICE_CLASS_HUMIDITY entry = registry.async_get("sensor.home_humidity") assert entry assert entry.unique_id == "55.55-122.12-humidity" state = hass.states.get("sensor.home_pm1") assert state assert state.state == "9" assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION assert ( state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == CONCENTRATION_MICROGRAMS_PER_CUBIC_METER ) assert state.attributes.get(ATTR_ICON) == "mdi:blur" entry = registry.async_get("sensor.home_pm1") assert entry assert entry.unique_id == "55.55-122.12-pm1" state = hass.states.get("sensor.home_pressure") assert state assert state.state == "1001" assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == PRESSURE_HPA assert state.attributes.get(ATTR_DEVICE_CLASS) == DEVICE_CLASS_PRESSURE entry = registry.async_get("sensor.home_pressure") assert entry assert entry.unique_id == "55.55-122.12-pressure" state = hass.states.get("sensor.home_temperature") assert state assert state.state == "14.2" assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == TEMP_CELSIUS assert state.attributes.get(ATTR_DEVICE_CLASS) == DEVICE_CLASS_TEMPERATURE entry = registry.async_get("sensor.home_temperature") assert entry assert entry.unique_id == "55.55-122.12-temperature"
[ "async", "def", "test_sensor", "(", "hass", ")", ":", "await", "init_integration", "(", "hass", ")", "registry", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.home_humidity\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "\"92.8\"", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "==", "ATTRIBUTION", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_UNIT_OF_MEASUREMENT", ")", "==", "PERCENTAGE", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_DEVICE_CLASS", ")", "==", "DEVICE_CLASS_HUMIDITY", "entry", "=", "registry", ".", "async_get", "(", "\"sensor.home_humidity\"", ")", "assert", "entry", "assert", "entry", ".", "unique_id", "==", "\"55.55-122.12-humidity\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.home_pm1\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "\"9\"", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "==", "ATTRIBUTION", "assert", "(", "state", ".", "attributes", ".", "get", "(", "ATTR_UNIT_OF_MEASUREMENT", ")", "==", "CONCENTRATION_MICROGRAMS_PER_CUBIC_METER", ")", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")", "==", "\"mdi:blur\"", "entry", "=", "registry", ".", "async_get", "(", "\"sensor.home_pm1\"", ")", "assert", "entry", "assert", "entry", ".", "unique_id", "==", "\"55.55-122.12-pm1\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.home_pressure\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "\"1001\"", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "==", "ATTRIBUTION", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_UNIT_OF_MEASUREMENT", ")", "==", "PRESSURE_HPA", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_DEVICE_CLASS", ")", "==", "DEVICE_CLASS_PRESSURE", "entry", "=", "registry", ".", "async_get", "(", "\"sensor.home_pressure\"", ")", "assert", "entry", "assert", "entry", ".", "unique_id", "==", "\"55.55-122.12-pressure\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.home_temperature\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "\"14.2\"", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_ATTRIBUTION", ")", "==", "ATTRIBUTION", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_UNIT_OF_MEASUREMENT", ")", "==", "TEMP_CELSIUS", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_DEVICE_CLASS", ")", "==", "DEVICE_CLASS_TEMPERATURE", "entry", "=", "registry", ".", "async_get", "(", "\"sensor.home_temperature\"", ")", "assert", "entry", "assert", "entry", ".", "unique_id", "==", "\"55.55-122.12-temperature\"" ]
[ 28, 0 ]
[ 78, 56 ]
python
en
['en', 'en', 'en']
True
test_availability
(hass)
Ensure that we mark the entities unavailable correctly when service is offline.
Ensure that we mark the entities unavailable correctly when service is offline.
async def test_availability(hass): """Ensure that we mark the entities unavailable correctly when service is offline.""" await init_integration(hass) state = hass.states.get("sensor.home_humidity") assert state assert state.state != STATE_UNAVAILABLE assert state.state == "92.8" future = utcnow() + timedelta(minutes=60) with patch("airly._private._RequestsHandler.get", side_effect=ConnectionError()): async_fire_time_changed(hass, future) await hass.async_block_till_done() state = hass.states.get("sensor.home_humidity") assert state assert state.state == STATE_UNAVAILABLE future = utcnow() + timedelta(minutes=120) with patch( "airly._private._RequestsHandler.get", return_value=json.loads(load_fixture("airly_valid_station.json")), ): async_fire_time_changed(hass, future) await hass.async_block_till_done() state = hass.states.get("sensor.home_humidity") assert state assert state.state != STATE_UNAVAILABLE assert state.state == "92.8"
[ "async", "def", "test_availability", "(", "hass", ")", ":", "await", "init_integration", "(", "hass", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.home_humidity\"", ")", "assert", "state", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "assert", "state", ".", "state", "==", "\"92.8\"", "future", "=", "utcnow", "(", ")", "+", "timedelta", "(", "minutes", "=", "60", ")", "with", "patch", "(", "\"airly._private._RequestsHandler.get\"", ",", "side_effect", "=", "ConnectionError", "(", ")", ")", ":", "async_fire_time_changed", "(", "hass", ",", "future", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.home_humidity\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "STATE_UNAVAILABLE", "future", "=", "utcnow", "(", ")", "+", "timedelta", "(", "minutes", "=", "120", ")", "with", "patch", "(", "\"airly._private._RequestsHandler.get\"", ",", "return_value", "=", "json", ".", "loads", "(", "load_fixture", "(", "\"airly_valid_station.json\"", ")", ")", ",", ")", ":", "async_fire_time_changed", "(", "hass", ",", "future", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.home_humidity\"", ")", "assert", "state", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "assert", "state", ".", "state", "==", "\"92.8\"" ]
[ 81, 0 ]
[ 110, 36 ]
python
en
['en', 'en', 'en']
True
test_manual_update_entity
(hass)
Test manual update entity via service homeasasistant/update_entity.
Test manual update entity via service homeasasistant/update_entity.
async def test_manual_update_entity(hass): """Test manual update entity via service homeasasistant/update_entity.""" await init_integration(hass) await async_setup_component(hass, "homeassistant", {}) with patch( "homeassistant.components.airly.AirlyDataUpdateCoordinator._async_update_data" ) as mock_update: await hass.services.async_call( "homeassistant", "update_entity", {ATTR_ENTITY_ID: ["sensor.home_humidity"]}, blocking=True, ) assert mock_update.call_count == 1
[ "async", "def", "test_manual_update_entity", "(", "hass", ")", ":", "await", "init_integration", "(", "hass", ")", "await", "async_setup_component", "(", "hass", ",", "\"homeassistant\"", ",", "{", "}", ")", "with", "patch", "(", "\"homeassistant.components.airly.AirlyDataUpdateCoordinator._async_update_data\"", ")", "as", "mock_update", ":", "await", "hass", ".", "services", ".", "async_call", "(", "\"homeassistant\"", ",", "\"update_entity\"", ",", "{", "ATTR_ENTITY_ID", ":", "[", "\"sensor.home_humidity\"", "]", "}", ",", "blocking", "=", "True", ",", ")", "assert", "mock_update", ".", "call_count", "==", "1" ]
[ 113, 0 ]
[ 127, 42 ]
python
en
['en', 'en', 'en']
True
load_corpus
(name, download=True)
Loads and wrangles the passed in text corpus by name. If download is specified, this method will download any missing files. Note: This function is slightly different to the `load_data` function used above to load pandas dataframes into memory.
Loads and wrangles the passed in text corpus by name. If download is specified, this method will download any missing files.
def load_corpus(name, download=True): """ Loads and wrangles the passed in text corpus by name. If download is specified, this method will download any missing files. Note: This function is slightly different to the `load_data` function used above to load pandas dataframes into memory. """ # Get the path from the datasets path = corpora[name] # Check if the data exists, otherwise download or raise if not os.path.exists(path): raise ValueError(( "'{}' dataset has not been downloaded, " "use the download.py module to fetch datasets" ).format(name)) # Read the directories in the directory as the categories. categories = [ cat for cat in os.listdir(path) if os.path.isdir(os.path.join(path, cat)) ] files = [] # holds the file names relative to the root data = [] # holds the text read from the file target = [] # holds the string of the category # Load the data from the files in the corpus for cat in categories: for name in os.listdir(os.path.join(path, cat)): files.append(os.path.join(path, cat, name)) target.append(cat) with open(os.path.join(path, cat, name), 'r') as f: data.append(f.read()) # Return the data bunch for use similar to the newsgroups example return Bunch( categories=categories, files=files, data=data, target=target, )
[ "def", "load_corpus", "(", "name", ",", "download", "=", "True", ")", ":", "# Get the path from the datasets", "path", "=", "corpora", "[", "name", "]", "# Check if the data exists, otherwise download or raise", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "(", "\"'{}' dataset has not been downloaded, \"", "\"use the download.py module to fetch datasets\"", ")", ".", "format", "(", "name", ")", ")", "# Read the directories in the directory as the categories.", "categories", "=", "[", "cat", "for", "cat", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cat", ")", ")", "]", "files", "=", "[", "]", "# holds the file names relative to the root", "data", "=", "[", "]", "# holds the text read from the file", "target", "=", "[", "]", "# holds the string of the category", "# Load the data from the files in the corpus", "for", "cat", "in", "categories", ":", "for", "name", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cat", ")", ")", ":", "files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cat", ",", "name", ")", ")", "target", ".", "append", "(", "cat", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "cat", ",", "name", ")", ",", "'r'", ")", "as", "f", ":", "data", ".", "append", "(", "f", ".", "read", "(", ")", ")", "# Return the data bunch for use similar to the newsgroups example", "return", "Bunch", "(", "categories", "=", "categories", ",", "files", "=", "files", ",", "data", "=", "data", ",", "target", "=", "target", ",", ")" ]
[ 16, 0 ]
[ 60, 5 ]
python
en
['en', 'error', 'th']
False
async_setup
(hass, config)
Set up the forked-daapd component.
Set up the forked-daapd component.
async def async_setup(hass, config): """Set up the forked-daapd component.""" return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "return", "True" ]
[ 6, 0 ]
[ 8, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, entry)
Set up forked-daapd from a config entry by forwarding to platform.
Set up forked-daapd from a config entry by forwarding to platform.
async def async_setup_entry(hass, entry): """Set up forked-daapd from a config entry by forwarding to platform.""" hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, MP_DOMAIN) ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ")", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "MP_DOMAIN", ")", ")", "return", "True" ]
[ 11, 0 ]
[ 16, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass, entry)
Remove forked-daapd component.
Remove forked-daapd component.
async def async_unload_entry(hass, entry): """Remove forked-daapd component.""" status = await hass.config_entries.async_forward_entry_unload(entry, MP_DOMAIN) if status and hass.data.get(DOMAIN) and hass.data[DOMAIN].get(entry.entry_id): hass.data[DOMAIN][entry.entry_id][ HASS_DATA_UPDATER_KEY ].websocket_handler.cancel() for remove_listener in hass.data[DOMAIN][entry.entry_id][ HASS_DATA_REMOVE_LISTENERS_KEY ]: remove_listener() del hass.data[DOMAIN][entry.entry_id] if not hass.data[DOMAIN]: del hass.data[DOMAIN] return status
[ "async", "def", "async_unload_entry", "(", "hass", ",", "entry", ")", ":", "status", "=", "await", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "MP_DOMAIN", ")", "if", "status", "and", "hass", ".", "data", ".", "get", "(", "DOMAIN", ")", "and", "hass", ".", "data", "[", "DOMAIN", "]", ".", "get", "(", "entry", ".", "entry_id", ")", ":", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "HASS_DATA_UPDATER_KEY", "]", ".", "websocket_handler", ".", "cancel", "(", ")", "for", "remove_listener", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "HASS_DATA_REMOVE_LISTENERS_KEY", "]", ":", "remove_listener", "(", ")", "del", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "if", "not", "hass", ".", "data", "[", "DOMAIN", "]", ":", "del", "hass", ".", "data", "[", "DOMAIN", "]", "return", "status" ]
[ 19, 0 ]
[ 33, 17 ]
python
en
['nl', 'en', 'en']
True
test_async_response_request_context
(hass, websocket_client)
Test we can access current request.
Test we can access current request.
async def test_async_response_request_context(hass, websocket_client): """Test we can access current request.""" def handle_request(request, connection, msg): if request is not None: connection.send_result(msg["id"], request.path) else: connection.send_error(msg["id"], "not_found", "") @websocket_api.websocket_command({"type": "test-get-request-executor"}) @websocket_api.async_response async def executor_get_request(hass, connection, msg): handle_request( await hass.async_add_executor_job(http.current_request.get), connection, msg ) @websocket_api.websocket_command({"type": "test-get-request-async"}) @websocket_api.async_response async def async_get_request(hass, connection, msg): handle_request(http.current_request.get(), connection, msg) @websocket_api.websocket_command({"type": "test-get-request"}) def get_request(hass, connection, msg): handle_request(http.current_request.get(), connection, msg) websocket_api.async_register_command(hass, executor_get_request) websocket_api.async_register_command(hass, async_get_request) websocket_api.async_register_command(hass, get_request) await websocket_client.send_json( { "id": 5, "type": "test-get-request", } ) msg = await websocket_client.receive_json() assert msg["id"] == 5 assert msg["success"] assert msg["result"] == "/api/websocket" await websocket_client.send_json( { "id": 6, "type": "test-get-request-async", } ) msg = await websocket_client.receive_json() assert msg["id"] == 6 assert msg["success"] assert msg["result"] == "/api/websocket" await websocket_client.send_json( { "id": 7, "type": "test-get-request-executor", } ) msg = await websocket_client.receive_json() assert msg["id"] == 7 assert not msg["success"] assert msg["error"]["code"] == "not_found"
[ "async", "def", "test_async_response_request_context", "(", "hass", ",", "websocket_client", ")", ":", "def", "handle_request", "(", "request", ",", "connection", ",", "msg", ")", ":", "if", "request", "is", "not", "None", ":", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "request", ".", "path", ")", "else", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"not_found\"", ",", "\"\"", ")", "@", "websocket_api", ".", "websocket_command", "(", "{", "\"type\"", ":", "\"test-get-request-executor\"", "}", ")", "@", "websocket_api", ".", "async_response", "async", "def", "executor_get_request", "(", "hass", ",", "connection", ",", "msg", ")", ":", "handle_request", "(", "await", "hass", ".", "async_add_executor_job", "(", "http", ".", "current_request", ".", "get", ")", ",", "connection", ",", "msg", ")", "@", "websocket_api", ".", "websocket_command", "(", "{", "\"type\"", ":", "\"test-get-request-async\"", "}", ")", "@", "websocket_api", ".", "async_response", "async", "def", "async_get_request", "(", "hass", ",", "connection", ",", "msg", ")", ":", "handle_request", "(", "http", ".", "current_request", ".", "get", "(", ")", ",", "connection", ",", "msg", ")", "@", "websocket_api", ".", "websocket_command", "(", "{", "\"type\"", ":", "\"test-get-request\"", "}", ")", "def", "get_request", "(", "hass", ",", "connection", ",", "msg", ")", ":", "handle_request", "(", "http", ".", "current_request", ".", "get", "(", ")", ",", "connection", ",", "msg", ")", "websocket_api", ".", "async_register_command", "(", "hass", ",", "executor_get_request", ")", "websocket_api", ".", "async_register_command", "(", "hass", ",", "async_get_request", ")", "websocket_api", ".", "async_register_command", "(", "hass", ",", "get_request", ")", "await", "websocket_client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"test-get-request\"", ",", "}", ")", "msg", "=", "await", "websocket_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "5", "assert", "msg", "[", "\"success\"", "]", "assert", "msg", "[", "\"result\"", "]", "==", "\"/api/websocket\"", "await", "websocket_client", ".", "send_json", "(", "{", "\"id\"", ":", "6", ",", "\"type\"", ":", "\"test-get-request-async\"", ",", "}", ")", "msg", "=", "await", "websocket_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "6", "assert", "msg", "[", "\"success\"", "]", "assert", "msg", "[", "\"result\"", "]", "==", "\"/api/websocket\"", "await", "websocket_client", ".", "send_json", "(", "{", "\"id\"", ":", "7", ",", "\"type\"", ":", "\"test-get-request-executor\"", ",", "}", ")", "msg", "=", "await", "websocket_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "7", "assert", "not", "msg", "[", "\"success\"", "]", "assert", "msg", "[", "\"error\"", "]", "[", "\"code\"", "]", "==", "\"not_found\"" ]
[ 4, 0 ]
[ 67, 46 ]
python
en
['en', 'en', 'en']
True
test_eufycam_setup
(hass)
Test that a eufycam can be correctly setup in HA.
Test that a eufycam can be correctly setup in HA.
async def test_eufycam_setup(hass): """Test that a eufycam can be correctly setup in HA.""" accessories = await setup_accessories_from_file(hass, "anker_eufycam.json") config_entry, pairing = await setup_test_accessories(hass, accessories) entity_registry = await hass.helpers.entity_registry.async_get_registry() # Check that the camera is correctly found and set up camera_id = "camera.eufycam2_0000" camera = entity_registry.async_get(camera_id) assert camera.unique_id == "homekit-A0000A000000000D-aid:4" camera_helper = Helper( hass, "camera.eufycam2_0000", pairing, accessories[0], config_entry, ) camera_state = await camera_helper.poll_and_get_state() assert camera_state.attributes["friendly_name"] == "eufyCam2-0000" assert camera_state.state == "idle" assert camera_state.attributes["supported_features"] == 0 device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(camera.device_id) assert device.manufacturer == "Anker" assert device.name == "eufyCam2-0000" assert device.model == "T8113" assert device.sw_version == "1.6.7" # These cameras are via a bridge, so via should be set assert device.via_device_id is not None cameras_count = 0 for state in hass.states.async_all(): if state.entity_id.startswith("camera."): cameras_count += 1 # There are multiple rtsp services, we only want to create 1 # camera entity per accessory, not 1 camera per service. assert cameras_count == 3
[ "async", "def", "test_eufycam_setup", "(", "hass", ")", ":", "accessories", "=", "await", "setup_accessories_from_file", "(", "hass", ",", "\"anker_eufycam.json\"", ")", "config_entry", ",", "pairing", "=", "await", "setup_test_accessories", "(", "hass", ",", "accessories", ")", "entity_registry", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "# Check that the camera is correctly found and set up", "camera_id", "=", "\"camera.eufycam2_0000\"", "camera", "=", "entity_registry", ".", "async_get", "(", "camera_id", ")", "assert", "camera", ".", "unique_id", "==", "\"homekit-A0000A000000000D-aid:4\"", "camera_helper", "=", "Helper", "(", "hass", ",", "\"camera.eufycam2_0000\"", ",", "pairing", ",", "accessories", "[", "0", "]", ",", "config_entry", ",", ")", "camera_state", "=", "await", "camera_helper", ".", "poll_and_get_state", "(", ")", "assert", "camera_state", ".", "attributes", "[", "\"friendly_name\"", "]", "==", "\"eufyCam2-0000\"", "assert", "camera_state", ".", "state", "==", "\"idle\"", "assert", "camera_state", ".", "attributes", "[", "\"supported_features\"", "]", "==", "0", "device_registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "device", "=", "device_registry", ".", "async_get", "(", "camera", ".", "device_id", ")", "assert", "device", ".", "manufacturer", "==", "\"Anker\"", "assert", "device", ".", "name", "==", "\"eufyCam2-0000\"", "assert", "device", ".", "model", "==", "\"T8113\"", "assert", "device", ".", "sw_version", "==", "\"1.6.7\"", "# These cameras are via a bridge, so via should be set", "assert", "device", ".", "via_device_id", "is", "not", "None", "cameras_count", "=", "0", "for", "state", "in", "hass", ".", "states", ".", "async_all", "(", ")", ":", "if", "state", ".", "entity_id", ".", "startswith", "(", "\"camera.\"", ")", ":", "cameras_count", "+=", "1", "# There are multiple rtsp services, we only want to create 1", "# camera entity per accessory, not 1 camera per service.", "assert", "cameras_count", "==", "3" ]
[ 9, 0 ]
[ 52, 29 ]
python
en
['en', 'en', 'en']
True
bytes_to_unicode
()
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on.
def bytes_to_unicode(): """ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. """ bs = ( list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) ) cs = bs[:] n = 0 for b in range(2 ** 8): if b not in bs: bs.append(b) cs.append(2 ** 8 + n) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs))
[ "def", "bytes_to_unicode", "(", ")", ":", "bs", "=", "(", "list", "(", "range", "(", "ord", "(", "\"!\"", ")", ",", "ord", "(", "\"~\"", ")", "+", "1", ")", ")", "+", "list", "(", "range", "(", "ord", "(", "\"¡\")", ",", " ", "rd(", "\"", "¬\") ", "+", "1", ")", " ", "+", "l", "st(r", "a", "nge(o", "r", "d(\"", "®", "\"), ", "o", "r", "(\"ÿ", "\"", ") + ", "1", ")", "", "", "", ")", "cs", "=", "bs", "[", ":", "]", "n", "=", "0", "for", "b", "in", "range", "(", "2", "**", "8", ")", ":", "if", "b", "not", "in", "bs", ":", "bs", ".", "append", "(", "b", ")", "cs", ".", "append", "(", "2", "**", "8", "+", "n", ")", "n", "+=", "1", "cs", "=", "[", "chr", "(", "n", ")", "for", "n", "in", "cs", "]", "return", "dict", "(", "zip", "(", "bs", ",", "cs", ")", ")" ]
[ 65, 0 ]
[ 86, 28 ]
python
en
['en', 'error', 'th']
False
get_pairs
(word)
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
Return set of symbol pairs in a word.
def get_pairs(word): """ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
[ "def", "get_pairs", "(", "word", ")", ":", "pairs", "=", "set", "(", ")", "prev_char", "=", "word", "[", "0", "]", "for", "char", "in", "word", "[", "1", ":", "]", ":", "pairs", ".", "add", "(", "(", "prev_char", ",", "char", ")", ")", "prev_char", "=", "char", "return", "pairs" ]
[ 89, 0 ]
[ 100, 16 ]
python
en
['en', 'error', 'th']
False
GPT2Tokenizer._tokenize
(self, text)
Tokenize a string.
Tokenize a string.
def _tokenize(self, text): """ Tokenize a string. """ bpe_tokens = [] for token in re.findall(self.pat, text): token = "".join( self.byte_encoder[b] for b in token.encode("utf-8") ) # Maps all our bytes to unicode strings, avoiding controle tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" ")) return bpe_tokens
[ "def", "_tokenize", "(", "self", ",", "text", ")", ":", "bpe_tokens", "=", "[", "]", "for", "token", "in", "re", ".", "findall", "(", "self", ".", "pat", ",", "text", ")", ":", "token", "=", "\"\"", ".", "join", "(", "self", ".", "byte_encoder", "[", "b", "]", "for", "b", "in", "token", ".", "encode", "(", "\"utf-8\"", ")", ")", "# Maps all our bytes to unicode strings, avoiding controle tokens of the BPE (spaces in our case)", "bpe_tokens", ".", "extend", "(", "bpe_token", "for", "bpe_token", "in", "self", ".", "bpe", "(", "token", ")", ".", "split", "(", "\" \"", ")", ")", "return", "bpe_tokens" ]
[ 243, 4 ]
[ 251, 25 ]
python
en
['en', 'gl', 'en']
True
GPT2Tokenizer._convert_token_to_id
(self, token)
Converts a token (str) in an id using the vocab.
Converts a token (str) in an id using the vocab.
def _convert_token_to_id(self, token): """ Converts a token (str) in an id using the vocab. """ return self.encoder.get(token, self.encoder.get(self.unk_token))
[ "def", "_convert_token_to_id", "(", "self", ",", "token", ")", ":", "return", "self", ".", "encoder", ".", "get", "(", "token", ",", "self", ".", "encoder", ".", "get", "(", "self", ".", "unk_token", ")", ")" ]
[ 253, 4 ]
[ 255, 72 ]
python
en
['en', 'en', 'en']
True