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
BlinkSensor.update
(self)
Retrieve sensor data from the camera.
Retrieve sensor data from the camera.
def update(self): """Retrieve sensor data from the camera.""" self.data.refresh() try: self._state = self._camera.attributes[self._sensor_key] except KeyError: self._state = None _LOGGER.error( "%s not a valid camera attribute. Did the API change?", self._sensor_key )
[ "def", "update", "(", "self", ")", ":", "self", ".", "data", ".", "refresh", "(", ")", "try", ":", "self", ".", "_state", "=", "self", ".", "_camera", ".", "attributes", "[", "self", ".", "_sensor_key", "]", "except", "KeyError", ":", "self", ".", "_state", "=", "None", "_LOGGER", ".", "error", "(", "\"%s not a valid camera attribute. Did the API change?\"", ",", "self", ".", "_sensor_key", ")" ]
[ 80, 4 ]
[ 89, 13 ]
python
en
['en', 'pt', 'en']
True
validate_station
(station)
Check that the station ID is well-formed.
Check that the station ID is well-formed.
def validate_station(station): """Check that the station ID is well-formed.""" if station is None: return if not re.fullmatch(r"[A-Z]{2}/s0000\d{3}", station): raise vol.error.Invalid('Station ID must be of the form "XX/s0000###"') return station
[ "def", "validate_station", "(", "station", ")", ":", "if", "station", "is", "None", ":", "return", "if", "not", "re", ".", "fullmatch", "(", "r\"[A-Z]{2}/s0000\\d{3}\"", ",", "station", ")", ":", "raise", "vol", ".", "error", ".", "Invalid", "(", "'Station ID must be of the form \"XX/s0000###\"'", ")", "return", "station" ]
[ 25, 0 ]
[ 31, 18 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_devices, discovery_info=None)
Set up the Environment Canada weather.
Set up the Environment Canada weather.
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Environment Canada weather.""" if config.get(CONF_STATION): ec_data = ECData(station_id=config[CONF_STATION]) else: lat = config.get(CONF_LATITUDE, hass.config.latitude) lon = config.get(CONF_LONGITUDE, hass.config.longitude) ec_data = ECData(coordinates=(lat, lon)) add_devices([ECWeather(ec_data, config)])
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_devices", ",", "discovery_info", "=", "None", ")", ":", "if", "config", ".", "get", "(", "CONF_STATION", ")", ":", "ec_data", "=", "ECData", "(", "station_id", "=", "config", "[", "CONF_STATION", "]", ")", "else", ":", "lat", "=", "config", ".", "get", "(", "CONF_LATITUDE", ",", "hass", ".", "config", ".", "latitude", ")", "lon", "=", "config", ".", "get", "(", "CONF_LONGITUDE", ",", "hass", ".", "config", ".", "longitude", ")", "ec_data", "=", "ECData", "(", "coordinates", "=", "(", "lat", ",", "lon", ")", ")", "add_devices", "(", "[", "ECWeather", "(", "ec_data", ",", "config", ")", "]", ")" ]
[ 62, 0 ]
[ 71, 45 ]
python
en
['en', 'en', 'en']
True
get_forecast
(ec_data, forecast_type)
Build the forecast array.
Build the forecast array.
def get_forecast(ec_data, forecast_type): """Build the forecast array.""" forecast_array = [] if forecast_type == "daily": half_days = ec_data.daily_forecasts if half_days[0]["temperature_class"] == "high": forecast_array.append( { ATTR_FORECAST_TIME: dt.now().isoformat(), ATTR_FORECAST_TEMP: int(half_days[0]["temperature"]), ATTR_FORECAST_TEMP_LOW: int(half_days[1]["temperature"]), ATTR_FORECAST_CONDITION: icon_code_to_condition( int(half_days[0]["icon_code"]) ), ATTR_FORECAST_PRECIPITATION_PROBABILITY: int( half_days[0]["precip_probability"] ), } ) half_days = half_days[2:] else: half_days = half_days[1:] for day, high, low in zip(range(1, 6), range(0, 9, 2), range(1, 10, 2)): forecast_array.append( { ATTR_FORECAST_TIME: ( dt.now() + datetime.timedelta(days=day) ).isoformat(), ATTR_FORECAST_TEMP: int(half_days[high]["temperature"]), ATTR_FORECAST_TEMP_LOW: int(half_days[low]["temperature"]), ATTR_FORECAST_CONDITION: icon_code_to_condition( int(half_days[high]["icon_code"]) ), ATTR_FORECAST_PRECIPITATION_PROBABILITY: int( half_days[high]["precip_probability"] ), } ) elif forecast_type == "hourly": hours = ec_data.hourly_forecasts for hour in range(0, 24): forecast_array.append( { ATTR_FORECAST_TIME: dt.as_local( datetime.datetime.strptime(hours[hour]["period"], "%Y%m%d%H%M") ).isoformat(), ATTR_FORECAST_TEMP: int(hours[hour]["temperature"]), ATTR_FORECAST_CONDITION: icon_code_to_condition( int(hours[hour]["icon_code"]) ), ATTR_FORECAST_PRECIPITATION_PROBABILITY: int( hours[hour]["precip_probability"] ), } ) return forecast_array
[ "def", "get_forecast", "(", "ec_data", ",", "forecast_type", ")", ":", "forecast_array", "=", "[", "]", "if", "forecast_type", "==", "\"daily\"", ":", "half_days", "=", "ec_data", ".", "daily_forecasts", "if", "half_days", "[", "0", "]", "[", "\"temperature_class\"", "]", "==", "\"high\"", ":", "forecast_array", ".", "append", "(", "{", "ATTR_FORECAST_TIME", ":", "dt", ".", "now", "(", ")", ".", "isoformat", "(", ")", ",", "ATTR_FORECAST_TEMP", ":", "int", "(", "half_days", "[", "0", "]", "[", "\"temperature\"", "]", ")", ",", "ATTR_FORECAST_TEMP_LOW", ":", "int", "(", "half_days", "[", "1", "]", "[", "\"temperature\"", "]", ")", ",", "ATTR_FORECAST_CONDITION", ":", "icon_code_to_condition", "(", "int", "(", "half_days", "[", "0", "]", "[", "\"icon_code\"", "]", ")", ")", ",", "ATTR_FORECAST_PRECIPITATION_PROBABILITY", ":", "int", "(", "half_days", "[", "0", "]", "[", "\"precip_probability\"", "]", ")", ",", "}", ")", "half_days", "=", "half_days", "[", "2", ":", "]", "else", ":", "half_days", "=", "half_days", "[", "1", ":", "]", "for", "day", ",", "high", ",", "low", "in", "zip", "(", "range", "(", "1", ",", "6", ")", ",", "range", "(", "0", ",", "9", ",", "2", ")", ",", "range", "(", "1", ",", "10", ",", "2", ")", ")", ":", "forecast_array", ".", "append", "(", "{", "ATTR_FORECAST_TIME", ":", "(", "dt", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "days", "=", "day", ")", ")", ".", "isoformat", "(", ")", ",", "ATTR_FORECAST_TEMP", ":", "int", "(", "half_days", "[", "high", "]", "[", "\"temperature\"", "]", ")", ",", "ATTR_FORECAST_TEMP_LOW", ":", "int", "(", "half_days", "[", "low", "]", "[", "\"temperature\"", "]", ")", ",", "ATTR_FORECAST_CONDITION", ":", "icon_code_to_condition", "(", "int", "(", "half_days", "[", "high", "]", "[", "\"icon_code\"", "]", ")", ")", ",", "ATTR_FORECAST_PRECIPITATION_PROBABILITY", ":", "int", "(", "half_days", "[", "high", "]", "[", "\"precip_probability\"", "]", ")", ",", "}", ")", "elif", "forecast_type", "==", "\"hourly\"", ":", "hours", "=", "ec_data", ".", "hourly_forecasts", "for", "hour", "in", "range", "(", "0", ",", "24", ")", ":", "forecast_array", ".", "append", "(", "{", "ATTR_FORECAST_TIME", ":", "dt", ".", "as_local", "(", "datetime", ".", "datetime", ".", "strptime", "(", "hours", "[", "hour", "]", "[", "\"period\"", "]", ",", "\"%Y%m%d%H%M\"", ")", ")", ".", "isoformat", "(", ")", ",", "ATTR_FORECAST_TEMP", ":", "int", "(", "hours", "[", "hour", "]", "[", "\"temperature\"", "]", ")", ",", "ATTR_FORECAST_CONDITION", ":", "icon_code_to_condition", "(", "int", "(", "hours", "[", "hour", "]", "[", "\"icon_code\"", "]", ")", ")", ",", "ATTR_FORECAST_PRECIPITATION_PROBABILITY", ":", "int", "(", "hours", "[", "hour", "]", "[", "\"precip_probability\"", "]", ")", ",", "}", ")", "return", "forecast_array" ]
[ 168, 0 ]
[ 227, 25 ]
python
en
['en', 'ga', 'en']
True
icon_code_to_condition
(icon_code)
Return the condition corresponding to an icon code.
Return the condition corresponding to an icon code.
def icon_code_to_condition(icon_code): """Return the condition corresponding to an icon code.""" for condition, codes in ICON_CONDITION_MAP.items(): if icon_code in codes: return condition return None
[ "def", "icon_code_to_condition", "(", "icon_code", ")", ":", "for", "condition", ",", "codes", "in", "ICON_CONDITION_MAP", ".", "items", "(", ")", ":", "if", "icon_code", "in", "codes", ":", "return", "condition", "return", "None" ]
[ 230, 0 ]
[ 235, 15 ]
python
en
['en', 'en', 'en']
True
ECWeather.__init__
(self, ec_data, config)
Initialize Environment Canada weather.
Initialize Environment Canada weather.
def __init__(self, ec_data, config): """Initialize Environment Canada weather.""" self.ec_data = ec_data self.platform_name = config.get(CONF_NAME) self.forecast_type = config[CONF_FORECAST]
[ "def", "__init__", "(", "self", ",", "ec_data", ",", "config", ")", ":", "self", ".", "ec_data", "=", "ec_data", "self", ".", "platform_name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "self", ".", "forecast_type", "=", "config", "[", "CONF_FORECAST", "]" ]
[ 77, 4 ]
[ 81, 50 ]
python
en
['en', 'en', 'en']
True
ECWeather.attribution
(self)
Return the attribution.
Return the attribution.
def attribution(self): """Return the attribution.""" return CONF_ATTRIBUTION
[ "def", "attribution", "(", "self", ")", ":", "return", "CONF_ATTRIBUTION" ]
[ 84, 4 ]
[ 86, 31 ]
python
en
['en', 'ja', 'en']
True
ECWeather.name
(self)
Return the name of the weather entity.
Return the name of the weather entity.
def name(self): """Return the name of the weather entity.""" if self.platform_name: return self.platform_name return self.ec_data.metadata.get("location")
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "platform_name", ":", "return", "self", ".", "platform_name", "return", "self", ".", "ec_data", ".", "metadata", ".", "get", "(", "\"location\"", ")" ]
[ 89, 4 ]
[ 93, 52 ]
python
en
['en', 'en', 'en']
True
ECWeather.temperature
(self)
Return the temperature.
Return the temperature.
def temperature(self): """Return the temperature.""" if self.ec_data.conditions.get("temperature", {}).get("value"): return float(self.ec_data.conditions["temperature"]["value"]) if self.ec_data.hourly_forecasts[0].get("temperature"): return float(self.ec_data.hourly_forecasts[0]["temperature"]) return None
[ "def", "temperature", "(", "self", ")", ":", "if", "self", ".", "ec_data", ".", "conditions", ".", "get", "(", "\"temperature\"", ",", "{", "}", ")", ".", "get", "(", "\"value\"", ")", ":", "return", "float", "(", "self", ".", "ec_data", ".", "conditions", "[", "\"temperature\"", "]", "[", "\"value\"", "]", ")", "if", "self", ".", "ec_data", ".", "hourly_forecasts", "[", "0", "]", ".", "get", "(", "\"temperature\"", ")", ":", "return", "float", "(", "self", ".", "ec_data", ".", "hourly_forecasts", "[", "0", "]", "[", "\"temperature\"", "]", ")", "return", "None" ]
[ 96, 4 ]
[ 102, 19 ]
python
en
['en', 'la', 'en']
True
ECWeather.temperature_unit
(self)
Return the unit of measurement.
Return the unit of measurement.
def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", ":", "return", "TEMP_CELSIUS" ]
[ 105, 4 ]
[ 107, 27 ]
python
en
['en', 'la', 'en']
True
ECWeather.humidity
(self)
Return the humidity.
Return the humidity.
def humidity(self): """Return the humidity.""" if self.ec_data.conditions.get("humidity", {}).get("value"): return float(self.ec_data.conditions["humidity"]["value"]) return None
[ "def", "humidity", "(", "self", ")", ":", "if", "self", ".", "ec_data", ".", "conditions", ".", "get", "(", "\"humidity\"", ",", "{", "}", ")", ".", "get", "(", "\"value\"", ")", ":", "return", "float", "(", "self", ".", "ec_data", ".", "conditions", "[", "\"humidity\"", "]", "[", "\"value\"", "]", ")", "return", "None" ]
[ 110, 4 ]
[ 114, 19 ]
python
en
['en', 'sw', 'en']
True
ECWeather.wind_speed
(self)
Return the wind speed.
Return the wind speed.
def wind_speed(self): """Return the wind speed.""" if self.ec_data.conditions.get("wind_speed", {}).get("value"): return float(self.ec_data.conditions["wind_speed"]["value"]) return None
[ "def", "wind_speed", "(", "self", ")", ":", "if", "self", ".", "ec_data", ".", "conditions", ".", "get", "(", "\"wind_speed\"", ",", "{", "}", ")", ".", "get", "(", "\"value\"", ")", ":", "return", "float", "(", "self", ".", "ec_data", ".", "conditions", "[", "\"wind_speed\"", "]", "[", "\"value\"", "]", ")", "return", "None" ]
[ 117, 4 ]
[ 121, 19 ]
python
en
['en', 'zh', 'en']
True
ECWeather.wind_bearing
(self)
Return the wind bearing.
Return the wind bearing.
def wind_bearing(self): """Return the wind bearing.""" if self.ec_data.conditions.get("wind_bearing", {}).get("value"): return float(self.ec_data.conditions["wind_bearing"]["value"]) return None
[ "def", "wind_bearing", "(", "self", ")", ":", "if", "self", ".", "ec_data", ".", "conditions", ".", "get", "(", "\"wind_bearing\"", ",", "{", "}", ")", ".", "get", "(", "\"value\"", ")", ":", "return", "float", "(", "self", ".", "ec_data", ".", "conditions", "[", "\"wind_bearing\"", "]", "[", "\"value\"", "]", ")", "return", "None" ]
[ 124, 4 ]
[ 128, 19 ]
python
en
['en', 'ig', 'en']
True
ECWeather.pressure
(self)
Return the pressure.
Return the pressure.
def pressure(self): """Return the pressure.""" if self.ec_data.conditions.get("pressure", {}).get("value"): return 10 * float(self.ec_data.conditions["pressure"]["value"]) return None
[ "def", "pressure", "(", "self", ")", ":", "if", "self", ".", "ec_data", ".", "conditions", ".", "get", "(", "\"pressure\"", ",", "{", "}", ")", ".", "get", "(", "\"value\"", ")", ":", "return", "10", "*", "float", "(", "self", ".", "ec_data", ".", "conditions", "[", "\"pressure\"", "]", "[", "\"value\"", "]", ")", "return", "None" ]
[ 131, 4 ]
[ 135, 19 ]
python
en
['en', 'ig', 'en']
True
ECWeather.visibility
(self)
Return the visibility.
Return the visibility.
def visibility(self): """Return the visibility.""" if self.ec_data.conditions.get("visibility", {}).get("value"): return float(self.ec_data.conditions["visibility"]["value"]) return None
[ "def", "visibility", "(", "self", ")", ":", "if", "self", ".", "ec_data", ".", "conditions", ".", "get", "(", "\"visibility\"", ",", "{", "}", ")", ".", "get", "(", "\"value\"", ")", ":", "return", "float", "(", "self", ".", "ec_data", ".", "conditions", "[", "\"visibility\"", "]", "[", "\"value\"", "]", ")", "return", "None" ]
[ 138, 4 ]
[ 142, 19 ]
python
en
['en', 'en', 'en']
True
ECWeather.condition
(self)
Return the weather condition.
Return the weather condition.
def condition(self): """Return the weather condition.""" icon_code = None if self.ec_data.conditions.get("icon_code", {}).get("value"): icon_code = self.ec_data.conditions["icon_code"]["value"] elif self.ec_data.hourly_forecasts[0].get("icon_code"): icon_code = self.ec_data.hourly_forecasts[0]["icon_code"] if icon_code: return icon_code_to_condition(int(icon_code)) return ""
[ "def", "condition", "(", "self", ")", ":", "icon_code", "=", "None", "if", "self", ".", "ec_data", ".", "conditions", ".", "get", "(", "\"icon_code\"", ",", "{", "}", ")", ".", "get", "(", "\"value\"", ")", ":", "icon_code", "=", "self", ".", "ec_data", ".", "conditions", "[", "\"icon_code\"", "]", "[", "\"value\"", "]", "elif", "self", ".", "ec_data", ".", "hourly_forecasts", "[", "0", "]", ".", "get", "(", "\"icon_code\"", ")", ":", "icon_code", "=", "self", ".", "ec_data", ".", "hourly_forecasts", "[", "0", "]", "[", "\"icon_code\"", "]", "if", "icon_code", ":", "return", "icon_code_to_condition", "(", "int", "(", "icon_code", ")", ")", "return", "\"\"" ]
[ 145, 4 ]
[ 156, 17 ]
python
en
['en', 'en', 'en']
True
ECWeather.forecast
(self)
Return the forecast array.
Return the forecast array.
def forecast(self): """Return the forecast array.""" return get_forecast(self.ec_data, self.forecast_type)
[ "def", "forecast", "(", "self", ")", ":", "return", "get_forecast", "(", "self", ".", "ec_data", ",", "self", ".", "forecast_type", ")" ]
[ 159, 4 ]
[ 161, 61 ]
python
en
['en', 'ga', 'en']
True
ECWeather.update
(self)
Get the latest data from Environment Canada.
Get the latest data from Environment Canada.
def update(self): """Get the latest data from Environment Canada.""" self.ec_data.update()
[ "def", "update", "(", "self", ")", ":", "self", ".", "ec_data", ".", "update", "(", ")" ]
[ 163, 4 ]
[ 165, 29 ]
python
en
['en', 'en', 'en']
True
auth_ok_message
()
Return an auth_ok message.
Return an auth_ok message.
def auth_ok_message(): """Return an auth_ok message.""" return {"type": TYPE_AUTH_OK, "ha_version": __version__}
[ "def", "auth_ok_message", "(", ")", ":", "return", "{", "\"type\"", ":", "TYPE_AUTH_OK", ",", "\"ha_version\"", ":", "__version__", "}" ]
[ 27, 0 ]
[ 29, 60 ]
python
en
['ms', 'ga', 'en']
False
auth_required_message
()
Return an auth_required message.
Return an auth_required message.
def auth_required_message(): """Return an auth_required message.""" return {"type": TYPE_AUTH_REQUIRED, "ha_version": __version__}
[ "def", "auth_required_message", "(", ")", ":", "return", "{", "\"type\"", ":", "TYPE_AUTH_REQUIRED", ",", "\"ha_version\"", ":", "__version__", "}" ]
[ 32, 0 ]
[ 34, 66 ]
python
en
['en', 'en', 'en']
True
auth_invalid_message
(message)
Return an auth_invalid message.
Return an auth_invalid message.
def auth_invalid_message(message): """Return an auth_invalid message.""" return {"type": TYPE_AUTH_INVALID, "message": message}
[ "def", "auth_invalid_message", "(", "message", ")", ":", "return", "{", "\"type\"", ":", "TYPE_AUTH_INVALID", ",", "\"message\"", ":", "message", "}" ]
[ 37, 0 ]
[ 39, 58 ]
python
en
['en', 'en', 'en']
True
AuthPhase.__init__
(self, logger, hass, send_message, request)
Initialize the authentiated connection.
Initialize the authentiated connection.
def __init__(self, logger, hass, send_message, request): """Initialize the authentiated connection.""" self._hass = hass self._send_message = send_message self._logger = logger self._request = request self._authenticated = False self._connection = None
[ "def", "__init__", "(", "self", ",", "logger", ",", "hass", ",", "send_message", ",", "request", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_send_message", "=", "send_message", "self", ".", "_logger", "=", "logger", "self", ".", "_request", "=", "request", "self", ".", "_authenticated", "=", "False", "self", ".", "_connection", "=", "None" ]
[ 45, 4 ]
[ 52, 31 ]
python
en
['en', 'en', 'en']
True
AuthPhase.async_handle
(self, msg)
Handle authentication.
Handle authentication.
async def async_handle(self, msg): """Handle authentication.""" try: msg = AUTH_MESSAGE_SCHEMA(msg) except vol.Invalid as err: error_msg = ( f"Auth message incorrectly formatted: {humanize_error(msg, err)}" ) self._logger.warning(error_msg) self._send_message(auth_invalid_message(error_msg)) raise Disconnect from err if "access_token" in msg: self._logger.debug("Received access_token") refresh_token = await self._hass.auth.async_validate_access_token( msg["access_token"] ) if refresh_token is not None: return await self._async_finish_auth(refresh_token.user, refresh_token) self._send_message(auth_invalid_message("Invalid access token or password")) await process_wrong_login(self._request) raise Disconnect
[ "async", "def", "async_handle", "(", "self", ",", "msg", ")", ":", "try", ":", "msg", "=", "AUTH_MESSAGE_SCHEMA", "(", "msg", ")", "except", "vol", ".", "Invalid", "as", "err", ":", "error_msg", "=", "(", "f\"Auth message incorrectly formatted: {humanize_error(msg, err)}\"", ")", "self", ".", "_logger", ".", "warning", "(", "error_msg", ")", "self", ".", "_send_message", "(", "auth_invalid_message", "(", "error_msg", ")", ")", "raise", "Disconnect", "from", "err", "if", "\"access_token\"", "in", "msg", ":", "self", ".", "_logger", ".", "debug", "(", "\"Received access_token\"", ")", "refresh_token", "=", "await", "self", ".", "_hass", ".", "auth", ".", "async_validate_access_token", "(", "msg", "[", "\"access_token\"", "]", ")", "if", "refresh_token", "is", "not", "None", ":", "return", "await", "self", ".", "_async_finish_auth", "(", "refresh_token", ".", "user", ",", "refresh_token", ")", "self", ".", "_send_message", "(", "auth_invalid_message", "(", "\"Invalid access token or password\"", ")", ")", "await", "process_wrong_login", "(", "self", ".", "_request", ")", "raise", "Disconnect" ]
[ 54, 4 ]
[ 76, 24 ]
python
de
['de', 'fr', 'en']
False
AuthPhase._async_finish_auth
( self, user: User, refresh_token: RefreshToken )
Create an active connection.
Create an active connection.
async def _async_finish_auth( self, user: User, refresh_token: RefreshToken ) -> ActiveConnection: """Create an active connection.""" self._logger.debug("Auth OK") await process_success_login(self._request) self._send_message(auth_ok_message()) return ActiveConnection( self._logger, self._hass, self._send_message, user, refresh_token )
[ "async", "def", "_async_finish_auth", "(", "self", ",", "user", ":", "User", ",", "refresh_token", ":", "RefreshToken", ")", "->", "ActiveConnection", ":", "self", ".", "_logger", ".", "debug", "(", "\"Auth OK\"", ")", "await", "process_success_login", "(", "self", ".", "_request", ")", "self", ".", "_send_message", "(", "auth_ok_message", "(", ")", ")", "return", "ActiveConnection", "(", "self", ".", "_logger", ",", "self", ".", "_hass", ",", "self", ".", "_send_message", ",", "user", ",", "refresh_token", ")" ]
[ 78, 4 ]
[ 87, 9 ]
python
en
['en', 'en', 'en']
True
device_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def device_reg(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass)
[ "def", "device_reg", "(", "hass", ")", ":", "return", "mock_device_registry", "(", "hass", ")" ]
[ 19, 0 ]
[ 21, 37 ]
python
en
['en', 'fy', 'en']
True
entity_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def entity_reg(hass): """Return an empty, loaded, registry.""" return mock_registry(hass)
[ "def", "entity_reg", "(", "hass", ")", ":", "return", "mock_registry", "(", "hass", ")" ]
[ 25, 0 ]
[ 27, 30 ]
python
en
['en', 'fy', 'en']
True
test_get_actions
(hass, device_reg, entity_reg)
Test we get the expected actions from a NEW_DOMAIN.
Test we get the expected actions from a NEW_DOMAIN.
async def test_get_actions(hass, device_reg, entity_reg): """Test we get the expected actions from a NEW_DOMAIN.""" config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id) expected_actions = [ { "domain": DOMAIN, "type": "turn_on", "device_id": device_entry.id, "entity_id": "NEW_DOMAIN.test_5678", }, { "domain": DOMAIN, "type": "turn_off", "device_id": device_entry.id, "entity_id": "NEW_DOMAIN.test_5678", }, ] actions = await async_get_device_automations(hass, "action", device_entry.id) assert_lists_same(actions, expected_actions)
[ "async", "def", "test_get_actions", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "\"5678\"", ",", "device_id", "=", "device_entry", ".", "id", ")", "expected_actions", "=", "[", "{", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"turn_on\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "\"NEW_DOMAIN.test_5678\"", ",", "}", ",", "{", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"turn_off\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "\"NEW_DOMAIN.test_5678\"", ",", "}", ",", "]", "actions", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"action\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "actions", ",", "expected_actions", ")" ]
[ 30, 0 ]
[ 54, 48 ]
python
en
['en', 'en', 'en']
True
test_action
(hass)
Test for turn_on and turn_off actions.
Test for turn_on and turn_off actions.
async def test_action(hass): """Test for turn_on and turn_off actions.""" assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "event", "event_type": "test_event_turn_off", }, "action": { "domain": DOMAIN, "device_id": "abcdefgh", "entity_id": "NEW_DOMAIN.entity", "type": "turn_off", }, }, { "trigger": { "platform": "event", "event_type": "test_event_turn_on", }, "action": { "domain": DOMAIN, "device_id": "abcdefgh", "entity_id": "NEW_DOMAIN.entity", "type": "turn_on", }, }, ] }, ) turn_off_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_off") turn_on_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_on") hass.bus.async_fire("test_event_turn_off") await hass.async_block_till_done() assert len(turn_off_calls) == 1 assert len(turn_on_calls) == 0 hass.bus.async_fire("test_event_turn_on") await hass.async_block_till_done() assert len(turn_off_calls) == 1 assert len(turn_on_calls) == 1
[ "async", "def", "test_action", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event_turn_off\"", ",", "}", ",", "\"action\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"abcdefgh\"", ",", "\"entity_id\"", ":", "\"NEW_DOMAIN.entity\"", ",", "\"type\"", ":", "\"turn_off\"", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event_turn_on\"", ",", "}", ",", "\"action\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"abcdefgh\"", ",", "\"entity_id\"", ":", "\"NEW_DOMAIN.entity\"", ",", "\"type\"", ":", "\"turn_on\"", ",", "}", ",", "}", ",", "]", "}", ",", ")", "turn_off_calls", "=", "async_mock_service", "(", "hass", ",", "\"NEW_DOMAIN\"", ",", "\"turn_off\"", ")", "turn_on_calls", "=", "async_mock_service", "(", "hass", ",", "\"NEW_DOMAIN\"", ",", "\"turn_on\"", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event_turn_off\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "turn_off_calls", ")", "==", "1", "assert", "len", "(", "turn_on_calls", ")", "==", "0", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event_turn_on\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "turn_off_calls", ")", "==", "1", "assert", "len", "(", "turn_on_calls", ")", "==", "1" ]
[ 57, 0 ]
[ 103, 34 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Demo config entry.
Set up the Demo config entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Demo config entry.""" setup_platform(hass, {}, async_add_entities)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "setup_platform", "(", "hass", ",", "{", "}", ",", "async_add_entities", ")" ]
[ 33, 0 ]
[ 35, 48 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Demo weather.
Set up the Demo weather.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Demo weather.""" add_entities( [ DemoWeather( "South", "Sunshine", 21.6414, 92, 1099, 0.5, TEMP_CELSIUS, [ ["rainy", 1, 22, 15, 60], ["rainy", 5, 19, 8, 30], ["cloudy", 0, 15, 9, 10], ["sunny", 0, 12, 6, 0], ["partlycloudy", 2, 14, 7, 20], ["rainy", 15, 18, 7, 0], ["fog", 0.2, 21, 12, 100], ], ), DemoWeather( "North", "Shower rain", -12, 54, 987, 4.8, TEMP_FAHRENHEIT, [ ["snowy", 2, -10, -15, 60], ["partlycloudy", 1, -13, -14, 25], ["sunny", 0, -18, -22, 70], ["sunny", 0.1, -23, -23, 90], ["snowy", 4, -19, -20, 40], ["sunny", 0.3, -14, -19, 0], ["sunny", 0, -9, -12, 0], ], ), ] )
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "add_entities", "(", "[", "DemoWeather", "(", "\"South\"", ",", "\"Sunshine\"", ",", "21.6414", ",", "92", ",", "1099", ",", "0.5", ",", "TEMP_CELSIUS", ",", "[", "[", "\"rainy\"", ",", "1", ",", "22", ",", "15", ",", "60", "]", ",", "[", "\"rainy\"", ",", "5", ",", "19", ",", "8", ",", "30", "]", ",", "[", "\"cloudy\"", ",", "0", ",", "15", ",", "9", ",", "10", "]", ",", "[", "\"sunny\"", ",", "0", ",", "12", ",", "6", ",", "0", "]", ",", "[", "\"partlycloudy\"", ",", "2", ",", "14", ",", "7", ",", "20", "]", ",", "[", "\"rainy\"", ",", "15", ",", "18", ",", "7", ",", "0", "]", ",", "[", "\"fog\"", ",", "0.2", ",", "21", ",", "12", ",", "100", "]", ",", "]", ",", ")", ",", "DemoWeather", "(", "\"North\"", ",", "\"Shower rain\"", ",", "-", "12", ",", "54", ",", "987", ",", "4.8", ",", "TEMP_FAHRENHEIT", ",", "[", "[", "\"snowy\"", ",", "2", ",", "-", "10", ",", "-", "15", ",", "60", "]", ",", "[", "\"partlycloudy\"", ",", "1", ",", "-", "13", ",", "-", "14", ",", "25", "]", ",", "[", "\"sunny\"", ",", "0", ",", "-", "18", ",", "-", "22", ",", "70", "]", ",", "[", "\"sunny\"", ",", "0.1", ",", "-", "23", ",", "-", "23", ",", "90", "]", ",", "[", "\"snowy\"", ",", "4", ",", "-", "19", ",", "-", "20", ",", "40", "]", ",", "[", "\"sunny\"", ",", "0.3", ",", "-", "14", ",", "-", "19", ",", "0", "]", ",", "[", "\"sunny\"", ",", "0", ",", "-", "9", ",", "-", "12", ",", "0", "]", ",", "]", ",", ")", ",", "]", ")" ]
[ 38, 0 ]
[ 79, 5 ]
python
en
['en', 'en', 'en']
True
DemoWeather.__init__
( self, name, condition, temperature, humidity, pressure, wind_speed, temperature_unit, forecast, )
Initialize the Demo weather.
Initialize the Demo weather.
def __init__( self, name, condition, temperature, humidity, pressure, wind_speed, temperature_unit, forecast, ): """Initialize the Demo weather.""" self._name = name self._condition = condition self._temperature = temperature self._temperature_unit = temperature_unit self._humidity = humidity self._pressure = pressure self._wind_speed = wind_speed self._forecast = forecast
[ "def", "__init__", "(", "self", ",", "name", ",", "condition", ",", "temperature", ",", "humidity", ",", "pressure", ",", "wind_speed", ",", "temperature_unit", ",", "forecast", ",", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_condition", "=", "condition", "self", ".", "_temperature", "=", "temperature", "self", ".", "_temperature_unit", "=", "temperature_unit", "self", ".", "_humidity", "=", "humidity", "self", ".", "_pressure", "=", "pressure", "self", ".", "_wind_speed", "=", "wind_speed", "self", ".", "_forecast", "=", "forecast" ]
[ 85, 4 ]
[ 104, 33 ]
python
en
['en', 'en', 'en']
True
DemoWeather.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return f"Demo Weather {self._name}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"Demo Weather {self._name}\"" ]
[ 107, 4 ]
[ 109, 43 ]
python
en
['en', 'mi', 'en']
True
DemoWeather.should_poll
(self)
No polling needed for a demo weather condition.
No polling needed for a demo weather condition.
def should_poll(self): """No polling needed for a demo weather condition.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 112, 4 ]
[ 114, 20 ]
python
en
['en', 'en', 'en']
True
DemoWeather.temperature
(self)
Return the temperature.
Return the temperature.
def temperature(self): """Return the temperature.""" return self._temperature
[ "def", "temperature", "(", "self", ")", ":", "return", "self", ".", "_temperature" ]
[ 117, 4 ]
[ 119, 32 ]
python
en
['en', 'la', 'en']
True
DemoWeather.temperature_unit
(self)
Return the unit of measurement.
Return the unit of measurement.
def temperature_unit(self): """Return the unit of measurement.""" return self._temperature_unit
[ "def", "temperature_unit", "(", "self", ")", ":", "return", "self", ".", "_temperature_unit" ]
[ 122, 4 ]
[ 124, 37 ]
python
en
['en', 'la', 'en']
True
DemoWeather.humidity
(self)
Return the humidity.
Return the humidity.
def humidity(self): """Return the humidity.""" return self._humidity
[ "def", "humidity", "(", "self", ")", ":", "return", "self", ".", "_humidity" ]
[ 127, 4 ]
[ 129, 29 ]
python
en
['en', 'sw', 'en']
True
DemoWeather.wind_speed
(self)
Return the wind speed.
Return the wind speed.
def wind_speed(self): """Return the wind speed.""" return self._wind_speed
[ "def", "wind_speed", "(", "self", ")", ":", "return", "self", ".", "_wind_speed" ]
[ 132, 4 ]
[ 134, 31 ]
python
en
['en', 'zh', 'en']
True
DemoWeather.pressure
(self)
Return the pressure.
Return the pressure.
def pressure(self): """Return the pressure.""" return self._pressure
[ "def", "pressure", "(", "self", ")", ":", "return", "self", ".", "_pressure" ]
[ 137, 4 ]
[ 139, 29 ]
python
en
['en', 'ig', 'en']
True
DemoWeather.condition
(self)
Return the weather condition.
Return the weather condition.
def condition(self): """Return the weather condition.""" return [ k for k, v in CONDITION_CLASSES.items() if self._condition.lower() in v ][0]
[ "def", "condition", "(", "self", ")", ":", "return", "[", "k", "for", "k", ",", "v", "in", "CONDITION_CLASSES", ".", "items", "(", ")", "if", "self", ".", "_condition", ".", "lower", "(", ")", "in", "v", "]", "[", "0", "]" ]
[ 142, 4 ]
[ 146, 12 ]
python
en
['en', 'en', 'en']
True
DemoWeather.attribution
(self)
Return the attribution.
Return the attribution.
def attribution(self): """Return the attribution.""" return "Powered by Home Assistant"
[ "def", "attribution", "(", "self", ")", ":", "return", "\"Powered by Home Assistant\"" ]
[ 149, 4 ]
[ 151, 42 ]
python
en
['en', 'ja', 'en']
True
DemoWeather.forecast
(self)
Return the forecast.
Return the forecast.
def forecast(self): """Return the forecast.""" reftime = dt_util.now().replace(hour=16, minute=00) forecast_data = [] for entry in self._forecast: data_dict = { ATTR_FORECAST_TIME: reftime.isoformat(), ATTR_FORECAST_CONDITION: entry[0], ATTR_FORECAST_PRECIPITATION: entry[1], ATTR_FORECAST_TEMP: entry[2], ATTR_FORECAST_TEMP_LOW: entry[3], ATTR_FORECAST_PRECIPITATION_PROBABILITY: entry[4], } reftime = reftime + timedelta(hours=4) forecast_data.append(data_dict) return forecast_data
[ "def", "forecast", "(", "self", ")", ":", "reftime", "=", "dt_util", ".", "now", "(", ")", ".", "replace", "(", "hour", "=", "16", ",", "minute", "=", "00", ")", "forecast_data", "=", "[", "]", "for", "entry", "in", "self", ".", "_forecast", ":", "data_dict", "=", "{", "ATTR_FORECAST_TIME", ":", "reftime", ".", "isoformat", "(", ")", ",", "ATTR_FORECAST_CONDITION", ":", "entry", "[", "0", "]", ",", "ATTR_FORECAST_PRECIPITATION", ":", "entry", "[", "1", "]", ",", "ATTR_FORECAST_TEMP", ":", "entry", "[", "2", "]", ",", "ATTR_FORECAST_TEMP_LOW", ":", "entry", "[", "3", "]", ",", "ATTR_FORECAST_PRECIPITATION_PROBABILITY", ":", "entry", "[", "4", "]", ",", "}", "reftime", "=", "reftime", "+", "timedelta", "(", "hours", "=", "4", ")", "forecast_data", ".", "append", "(", "data_dict", ")", "return", "forecast_data" ]
[ 154, 4 ]
[ 171, 28 ]
python
en
['en', 'no', 'en']
True
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities )
Set up the Meteo-France sensor platform.
Set up the Meteo-France sensor platform.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the Meteo-France sensor platform.""" coordinator_forecast = hass.data[DOMAIN][entry.entry_id][COORDINATOR_FORECAST] coordinator_rain = hass.data[DOMAIN][entry.entry_id][COORDINATOR_RAIN] coordinator_alert = hass.data[DOMAIN][entry.entry_id][COORDINATOR_ALERT] entities = [] for sensor_type in SENSOR_TYPES: if sensor_type == "next_rain": if coordinator_rain: entities.append(MeteoFranceRainSensor(sensor_type, coordinator_rain)) elif sensor_type == "weather_alert": if coordinator_alert: entities.append(MeteoFranceAlertSensor(sensor_type, coordinator_alert)) elif sensor_type in ["rain_chance", "freeze_chance", "snow_chance"]: if coordinator_forecast.data.probability_forecast: entities.append(MeteoFranceSensor(sensor_type, coordinator_forecast)) else: _LOGGER.warning( "Sensor %s skipped for %s as data is missing in the API", sensor_type, coordinator_forecast.data.position["name"], ) else: entities.append(MeteoFranceSensor(sensor_type, coordinator_forecast)) async_add_entities( entities, False, )
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "coordinator_forecast", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "COORDINATOR_FORECAST", "]", "coordinator_rain", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "COORDINATOR_RAIN", "]", "coordinator_alert", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "COORDINATOR_ALERT", "]", "entities", "=", "[", "]", "for", "sensor_type", "in", "SENSOR_TYPES", ":", "if", "sensor_type", "==", "\"next_rain\"", ":", "if", "coordinator_rain", ":", "entities", ".", "append", "(", "MeteoFranceRainSensor", "(", "sensor_type", ",", "coordinator_rain", ")", ")", "elif", "sensor_type", "==", "\"weather_alert\"", ":", "if", "coordinator_alert", ":", "entities", ".", "append", "(", "MeteoFranceAlertSensor", "(", "sensor_type", ",", "coordinator_alert", ")", ")", "elif", "sensor_type", "in", "[", "\"rain_chance\"", ",", "\"freeze_chance\"", ",", "\"snow_chance\"", "]", ":", "if", "coordinator_forecast", ".", "data", ".", "probability_forecast", ":", "entities", ".", "append", "(", "MeteoFranceSensor", "(", "sensor_type", ",", "coordinator_forecast", ")", ")", "else", ":", "_LOGGER", ".", "warning", "(", "\"Sensor %s skipped for %s as data is missing in the API\"", ",", "sensor_type", ",", "coordinator_forecast", ".", "data", ".", "position", "[", "\"name\"", "]", ",", ")", "else", ":", "entities", ".", "append", "(", "MeteoFranceSensor", "(", "sensor_type", ",", "coordinator_forecast", ")", ")", "async_add_entities", "(", "entities", ",", "False", ",", ")" ]
[ 37, 0 ]
[ 71, 5 ]
python
en
['en', 'da', 'en']
True
_find_first_probability_forecast_not_null
( probability_forecast: list, path: list )
Search the first not None value in the first forecast elements.
Search the first not None value in the first forecast elements.
def _find_first_probability_forecast_not_null( probability_forecast: list, path: list ) -> int: """Search the first not None value in the first forecast elements.""" for forecast in probability_forecast[0:3]: if forecast[path[1]][path[2]] is not None: return forecast[path[1]][path[2]] # Default return value if no value founded return None
[ "def", "_find_first_probability_forecast_not_null", "(", "probability_forecast", ":", "list", ",", "path", ":", "list", ")", "->", "int", ":", "for", "forecast", "in", "probability_forecast", "[", "0", ":", "3", "]", ":", "if", "forecast", "[", "path", "[", "1", "]", "]", "[", "path", "[", "2", "]", "]", "is", "not", "None", ":", "return", "forecast", "[", "path", "[", "1", "]", "]", "[", "path", "[", "2", "]", "]", "# Default return value if no value founded", "return", "None" ]
[ 206, 0 ]
[ 215, 15 ]
python
en
['en', 'en', 'en']
True
MeteoFranceSensor.__init__
(self, sensor_type: str, coordinator: DataUpdateCoordinator)
Initialize the Meteo-France sensor.
Initialize the Meteo-France sensor.
def __init__(self, sensor_type: str, coordinator: DataUpdateCoordinator): """Initialize the Meteo-France sensor.""" super().__init__(coordinator) self._type = sensor_type if hasattr(self.coordinator.data, "position"): city_name = self.coordinator.data.position["name"] self._name = f"{city_name} {SENSOR_TYPES[self._type][ENTITY_NAME]}" self._unique_id = f"{self.coordinator.data.position['lat']},{self.coordinator.data.position['lon']}_{self._type}"
[ "def", "__init__", "(", "self", ",", "sensor_type", ":", "str", ",", "coordinator", ":", "DataUpdateCoordinator", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "_type", "=", "sensor_type", "if", "hasattr", "(", "self", ".", "coordinator", ".", "data", ",", "\"position\"", ")", ":", "city_name", "=", "self", ".", "coordinator", ".", "data", ".", "position", "[", "\"name\"", "]", "self", ".", "_name", "=", "f\"{city_name} {SENSOR_TYPES[self._type][ENTITY_NAME]}\"", "self", ".", "_unique_id", "=", "f\"{self.coordinator.data.position['lat']},{self.coordinator.data.position['lon']}_{self._type}\"" ]
[ 77, 4 ]
[ 84, 125 ]
python
en
['en', 'en', 'en']
True
MeteoFranceSensor.unique_id
(self)
Return the unique id.
Return the unique id.
def unique_id(self): """Return the unique id.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_unique_id" ]
[ 87, 4 ]
[ 89, 30 ]
python
en
['en', 'la', 'en']
True
MeteoFranceSensor.name
(self)
Return the name.
Return the name.
def name(self): """Return the name.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 92, 4 ]
[ 94, 25 ]
python
en
['en', 'ig', 'en']
True
MeteoFranceSensor.state
(self)
Return the state.
Return the state.
def state(self): """Return the state.""" path = SENSOR_TYPES[self._type][ENTITY_API_DATA_PATH].split(":") data = getattr(self.coordinator.data, path[0]) # Specific case for probability forecast if path[0] == "probability_forecast": if len(path) == 3: # This is a fix compared to other entitty as first index is always null in API result for unknown reason value = _find_first_probability_forecast_not_null(data, path) else: value = data[0][path[1]] # General case else: if len(path) == 3: value = data[path[1]][path[2]] else: value = data[path[1]] if self._type == "wind_speed": # convert API wind speed from m/s to km/h value = round(value * 3.6) return value
[ "def", "state", "(", "self", ")", ":", "path", "=", "SENSOR_TYPES", "[", "self", ".", "_type", "]", "[", "ENTITY_API_DATA_PATH", "]", ".", "split", "(", "\":\"", ")", "data", "=", "getattr", "(", "self", ".", "coordinator", ".", "data", ",", "path", "[", "0", "]", ")", "# Specific case for probability forecast", "if", "path", "[", "0", "]", "==", "\"probability_forecast\"", ":", "if", "len", "(", "path", ")", "==", "3", ":", "# This is a fix compared to other entitty as first index is always null in API result for unknown reason", "value", "=", "_find_first_probability_forecast_not_null", "(", "data", ",", "path", ")", "else", ":", "value", "=", "data", "[", "0", "]", "[", "path", "[", "1", "]", "]", "# General case", "else", ":", "if", "len", "(", "path", ")", "==", "3", ":", "value", "=", "data", "[", "path", "[", "1", "]", "]", "[", "path", "[", "2", "]", "]", "else", ":", "value", "=", "data", "[", "path", "[", "1", "]", "]", "if", "self", ".", "_type", "==", "\"wind_speed\"", ":", "# convert API wind speed from m/s to km/h", "value", "=", "round", "(", "value", "*", "3.6", ")", "return", "value" ]
[ 97, 4 ]
[ 120, 20 ]
python
en
['en', 'en', 'en']
True
MeteoFranceSensor.unit_of_measurement
(self)
Return the unit of measurement.
Return the unit of measurement.
def unit_of_measurement(self): """Return the unit of measurement.""" return SENSOR_TYPES[self._type][ENTITY_UNIT]
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "SENSOR_TYPES", "[", "self", ".", "_type", "]", "[", "ENTITY_UNIT", "]" ]
[ 123, 4 ]
[ 125, 52 ]
python
en
['en', 'la', 'en']
True
MeteoFranceSensor.icon
(self)
Return the icon.
Return the icon.
def icon(self): """Return the icon.""" return SENSOR_TYPES[self._type][ENTITY_ICON]
[ "def", "icon", "(", "self", ")", ":", "return", "SENSOR_TYPES", "[", "self", ".", "_type", "]", "[", "ENTITY_ICON", "]" ]
[ 128, 4 ]
[ 130, 52 ]
python
en
['en', 'sr', 'en']
True
MeteoFranceSensor.device_class
(self)
Return the device class.
Return the device class.
def device_class(self): """Return the device class.""" return SENSOR_TYPES[self._type][ENTITY_DEVICE_CLASS]
[ "def", "device_class", "(", "self", ")", ":", "return", "SENSOR_TYPES", "[", "self", ".", "_type", "]", "[", "ENTITY_DEVICE_CLASS", "]" ]
[ 133, 4 ]
[ 135, 60 ]
python
en
['en', 'en', 'en']
True
MeteoFranceSensor.entity_registry_enabled_default
(self)
Return if the entity should be enabled when first added to the entity registry.
Return if the entity should be enabled when first added to the entity registry.
def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" return SENSOR_TYPES[self._type][ENTITY_ENABLE]
[ "def", "entity_registry_enabled_default", "(", "self", ")", "->", "bool", ":", "return", "SENSOR_TYPES", "[", "self", ".", "_type", "]", "[", "ENTITY_ENABLE", "]" ]
[ 138, 4 ]
[ 140, 54 ]
python
en
['en', 'en', 'en']
True
MeteoFranceSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION}
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", "}" ]
[ 143, 4 ]
[ 145, 46 ]
python
en
['en', 'en', 'en']
True
MeteoFranceRainSensor.state
(self)
Return the state.
Return the state.
def state(self): """Return the state.""" # search first cadran with rain next_rain = next( (cadran for cadran in self.coordinator.data.forecast if cadran["rain"] > 1), None, ) return ( dt_util.utc_from_timestamp(next_rain["dt"]).isoformat() if next_rain else None )
[ "def", "state", "(", "self", ")", ":", "# search first cadran with rain", "next_rain", "=", "next", "(", "(", "cadran", "for", "cadran", "in", "self", ".", "coordinator", ".", "data", ".", "forecast", "if", "cadran", "[", "\"rain\"", "]", ">", "1", ")", ",", "None", ",", ")", "return", "(", "dt_util", ".", "utc_from_timestamp", "(", "next_rain", "[", "\"dt\"", "]", ")", ".", "isoformat", "(", ")", "if", "next_rain", "else", "None", ")" ]
[ 152, 4 ]
[ 163, 9 ]
python
en
['en', 'en', 'en']
True
MeteoFranceRainSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" reference_dt = self.coordinator.data.forecast[0]["dt"] return { ATTR_NEXT_RAIN_DT_REF: dt_util.utc_from_timestamp(reference_dt).isoformat(), ATTR_NEXT_RAIN_1_HOUR_FORECAST: { f"{int((item['dt'] - reference_dt) / 60)} min": item["desc"] for item in self.coordinator.data.forecast }, ATTR_ATTRIBUTION: ATTRIBUTION, }
[ "def", "device_state_attributes", "(", "self", ")", ":", "reference_dt", "=", "self", ".", "coordinator", ".", "data", ".", "forecast", "[", "0", "]", "[", "\"dt\"", "]", "return", "{", "ATTR_NEXT_RAIN_DT_REF", ":", "dt_util", ".", "utc_from_timestamp", "(", "reference_dt", ")", ".", "isoformat", "(", ")", ",", "ATTR_NEXT_RAIN_1_HOUR_FORECAST", ":", "{", "f\"{int((item['dt'] - reference_dt) / 60)} min\"", ":", "item", "[", "\"desc\"", "]", "for", "item", "in", "self", ".", "coordinator", ".", "data", ".", "forecast", "}", ",", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "}" ]
[ 166, 4 ]
[ 176, 9 ]
python
en
['en', 'en', 'en']
True
MeteoFranceAlertSensor.__init__
(self, sensor_type: str, coordinator: DataUpdateCoordinator)
Initialize the Meteo-France sensor.
Initialize the Meteo-France sensor.
def __init__(self, sensor_type: str, coordinator: DataUpdateCoordinator): """Initialize the Meteo-France sensor.""" super().__init__(sensor_type, coordinator) dept_code = self.coordinator.data.domain_id self._name = f"{dept_code} {SENSOR_TYPES[self._type][ENTITY_NAME]}" self._unique_id = self._name
[ "def", "__init__", "(", "self", ",", "sensor_type", ":", "str", ",", "coordinator", ":", "DataUpdateCoordinator", ")", ":", "super", "(", ")", ".", "__init__", "(", "sensor_type", ",", "coordinator", ")", "dept_code", "=", "self", ".", "coordinator", ".", "data", ".", "domain_id", "self", ".", "_name", "=", "f\"{dept_code} {SENSOR_TYPES[self._type][ENTITY_NAME]}\"", "self", ".", "_unique_id", "=", "self", ".", "_name" ]
[ 183, 4 ]
[ 188, 36 ]
python
en
['en', 'en', 'en']
True
MeteoFranceAlertSensor.state
(self)
Return the state.
Return the state.
def state(self): """Return the state.""" return get_warning_text_status_from_indice_color( self.coordinator.data.get_domain_max_color() )
[ "def", "state", "(", "self", ")", ":", "return", "get_warning_text_status_from_indice_color", "(", "self", ".", "coordinator", ".", "data", ".", "get_domain_max_color", "(", ")", ")" ]
[ 191, 4 ]
[ 195, 9 ]
python
en
['en', 'en', 'en']
True
MeteoFranceAlertSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return { **readeable_phenomenoms_dict(self.coordinator.data.phenomenons_max_colors), ATTR_ATTRIBUTION: ATTRIBUTION, }
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "*", "*", "readeable_phenomenoms_dict", "(", "self", ".", "coordinator", ".", "data", ".", "phenomenons_max_colors", ")", ",", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "}" ]
[ 198, 4 ]
[ 203, 9 ]
python
en
['en', 'en', 'en']
True
async_describe_events
(hass, async_describe_event)
Describe logbook events.
Describe logbook events.
def async_describe_events(hass, async_describe_event): # type: ignore """Describe logbook events.""" @callback def async_describe_logbook_event(event): # type: ignore """Describe a logbook event.""" data = event.data message = "has been triggered" if ATTR_SOURCE in data: message = f"{message} by {data[ATTR_SOURCE]}" return { "name": data.get(ATTR_NAME), "message": message, "source": data.get(ATTR_SOURCE), "entity_id": data.get(ATTR_ENTITY_ID), } async_describe_event( DOMAIN, EVENT_AUTOMATION_TRIGGERED, async_describe_logbook_event )
[ "def", "async_describe_events", "(", "hass", ",", "async_describe_event", ")", ":", "# type: ignore", "@", "callback", "def", "async_describe_logbook_event", "(", "event", ")", ":", "# type: ignore", "\"\"\"Describe a logbook event.\"\"\"", "data", "=", "event", ".", "data", "message", "=", "\"has been triggered\"", "if", "ATTR_SOURCE", "in", "data", ":", "message", "=", "f\"{message} by {data[ATTR_SOURCE]}\"", "return", "{", "\"name\"", ":", "data", ".", "get", "(", "ATTR_NAME", ")", ",", "\"message\"", ":", "message", ",", "\"source\"", ":", "data", ".", "get", "(", "ATTR_SOURCE", ")", ",", "\"entity_id\"", ":", "data", ".", "get", "(", "ATTR_ENTITY_ID", ")", ",", "}", "async_describe_event", "(", "DOMAIN", ",", "EVENT_AUTOMATION_TRIGGERED", ",", "async_describe_logbook_event", ")" ]
[ 8, 0 ]
[ 27, 5 ]
python
en
['en', 'es', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the aREST binary sensor.
Set up the aREST binary sensor.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the aREST binary sensor.""" resource = config[CONF_RESOURCE] pin = config[CONF_PIN] device_class = config.get(CONF_DEVICE_CLASS) try: response = requests.get(resource, timeout=10).json() except requests.exceptions.MissingSchema: _LOGGER.error( "Missing resource or schema in configuration. Add http:// to your URL" ) return False except requests.exceptions.ConnectionError: _LOGGER.error("No route to device at %s", resource) return False arest = ArestData(resource, pin) add_entities( [ ArestBinarySensor( arest, resource, config.get(CONF_NAME, response[CONF_NAME]), device_class, pin, ) ], True, )
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "resource", "=", "config", "[", "CONF_RESOURCE", "]", "pin", "=", "config", "[", "CONF_PIN", "]", "device_class", "=", "config", ".", "get", "(", "CONF_DEVICE_CLASS", ")", "try", ":", "response", "=", "requests", ".", "get", "(", "resource", ",", "timeout", "=", "10", ")", ".", "json", "(", ")", "except", "requests", ".", "exceptions", ".", "MissingSchema", ":", "_LOGGER", ".", "error", "(", "\"Missing resource or schema in configuration. Add http:// to your URL\"", ")", "return", "False", "except", "requests", ".", "exceptions", ".", "ConnectionError", ":", "_LOGGER", ".", "error", "(", "\"No route to device at %s\"", ",", "resource", ")", "return", "False", "arest", "=", "ArestData", "(", "resource", ",", "pin", ")", "add_entities", "(", "[", "ArestBinarySensor", "(", "arest", ",", "resource", ",", "config", ".", "get", "(", "CONF_NAME", ",", "response", "[", "CONF_NAME", "]", ")", ",", "device_class", ",", "pin", ",", ")", "]", ",", "True", ",", ")" ]
[ 36, 0 ]
[ 66, 5 ]
python
en
['en', 'cs', 'en']
True
ArestBinarySensor.__init__
(self, arest, resource, name, device_class, pin)
Initialize the aREST device.
Initialize the aREST device.
def __init__(self, arest, resource, name, device_class, pin): """Initialize the aREST device.""" self.arest = arest self._resource = resource self._name = name self._device_class = device_class self._pin = pin if self._pin is not None: request = requests.get(f"{self._resource}/mode/{self._pin}/i", timeout=10) if request.status_code != HTTP_OK: _LOGGER.error("Can't set mode of %s", self._resource)
[ "def", "__init__", "(", "self", ",", "arest", ",", "resource", ",", "name", ",", "device_class", ",", "pin", ")", ":", "self", ".", "arest", "=", "arest", "self", ".", "_resource", "=", "resource", "self", ".", "_name", "=", "name", "self", ".", "_device_class", "=", "device_class", "self", ".", "_pin", "=", "pin", "if", "self", ".", "_pin", "is", "not", "None", ":", "request", "=", "requests", ".", "get", "(", "f\"{self._resource}/mode/{self._pin}/i\"", ",", "timeout", "=", "10", ")", "if", "request", ".", "status_code", "!=", "HTTP_OK", ":", "_LOGGER", ".", "error", "(", "\"Can't set mode of %s\"", ",", "self", ".", "_resource", ")" ]
[ 72, 4 ]
[ 83, 69 ]
python
en
['en', 'en', 'en']
True
ArestBinarySensor.name
(self)
Return the name of the binary sensor.
Return the name of the binary sensor.
def name(self): """Return the name of the binary sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 86, 4 ]
[ 88, 25 ]
python
en
['en', 'mi', 'en']
True
ArestBinarySensor.is_on
(self)
Return true if the binary sensor is on.
Return true if the binary sensor is on.
def is_on(self): """Return true if the binary sensor is on.""" return bool(self.arest.data.get("state"))
[ "def", "is_on", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "arest", ".", "data", ".", "get", "(", "\"state\"", ")", ")" ]
[ 91, 4 ]
[ 93, 49 ]
python
en
['en', 'fy', 'en']
True
ArestBinarySensor.device_class
(self)
Return the class of this sensor.
Return the class of this sensor.
def device_class(self): """Return the class of this sensor.""" return self._device_class
[ "def", "device_class", "(", "self", ")", ":", "return", "self", ".", "_device_class" ]
[ 96, 4 ]
[ 98, 33 ]
python
en
['en', 'en', 'en']
True
ArestBinarySensor.update
(self)
Get the latest data from aREST API.
Get the latest data from aREST API.
def update(self): """Get the latest data from aREST API.""" self.arest.update()
[ "def", "update", "(", "self", ")", ":", "self", ".", "arest", ".", "update", "(", ")" ]
[ 100, 4 ]
[ 102, 27 ]
python
en
['en', 'en', 'en']
True
ArestData.__init__
(self, resource, pin)
Initialize the aREST data object.
Initialize the aREST data object.
def __init__(self, resource, pin): """Initialize the aREST data object.""" self._resource = resource self._pin = pin self.data = {}
[ "def", "__init__", "(", "self", ",", "resource", ",", "pin", ")", ":", "self", ".", "_resource", "=", "resource", "self", ".", "_pin", "=", "pin", "self", ".", "data", "=", "{", "}" ]
[ 108, 4 ]
[ 112, 22 ]
python
en
['en', 'en', 'en']
True
ArestData.update
(self)
Get the latest data from aREST device.
Get the latest data from aREST device.
def update(self): """Get the latest data from aREST device.""" try: response = requests.get(f"{self._resource}/digital/{self._pin}", timeout=10) self.data = {"state": response.json()["return_value"]} except requests.exceptions.ConnectionError: _LOGGER.error("No route to device '%s'", self._resource)
[ "def", "update", "(", "self", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "f\"{self._resource}/digital/{self._pin}\"", ",", "timeout", "=", "10", ")", "self", ".", "data", "=", "{", "\"state\"", ":", "response", ".", "json", "(", ")", "[", "\"return_value\"", "]", "}", "except", "requests", ".", "exceptions", ".", "ConnectionError", ":", "_LOGGER", ".", "error", "(", "\"No route to device '%s'\"", ",", "self", ".", "_resource", ")" ]
[ 115, 4 ]
[ 121, 68 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the departure sensor.
Set up the departure sensor.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the departure sensor.""" nsapi = ns_api.NSAPI(config[CONF_API_KEY]) try: stations = nsapi.get_stations() except ( requests.exceptions.ConnectionError, requests.exceptions.HTTPError, ) as error: _LOGGER.error("Could not connect to the internet: %s", error) raise PlatformNotReady() from error except RequestParametersError as error: _LOGGER.error("Could not fetch stations, please check configuration: %s", error) return sensors = [] for departure in config.get(CONF_ROUTES): if not valid_stations( stations, [departure.get(CONF_FROM), departure.get(CONF_VIA), departure.get(CONF_TO)], ): continue sensors.append( NSDepartureSensor( nsapi, departure.get(CONF_NAME), departure.get(CONF_FROM), departure.get(CONF_TO), departure.get(CONF_VIA), departure.get(CONF_TIME), ) ) if sensors: add_entities(sensors, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "nsapi", "=", "ns_api", ".", "NSAPI", "(", "config", "[", "CONF_API_KEY", "]", ")", "try", ":", "stations", "=", "nsapi", ".", "get_stations", "(", ")", "except", "(", "requests", ".", "exceptions", ".", "ConnectionError", ",", "requests", ".", "exceptions", ".", "HTTPError", ",", ")", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Could not connect to the internet: %s\"", ",", "error", ")", "raise", "PlatformNotReady", "(", ")", "from", "error", "except", "RequestParametersError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Could not fetch stations, please check configuration: %s\"", ",", "error", ")", "return", "sensors", "=", "[", "]", "for", "departure", "in", "config", ".", "get", "(", "CONF_ROUTES", ")", ":", "if", "not", "valid_stations", "(", "stations", ",", "[", "departure", ".", "get", "(", "CONF_FROM", ")", ",", "departure", ".", "get", "(", "CONF_VIA", ")", ",", "departure", ".", "get", "(", "CONF_TO", ")", "]", ",", ")", ":", "continue", "sensors", ".", "append", "(", "NSDepartureSensor", "(", "nsapi", ",", "departure", ".", "get", "(", "CONF_NAME", ")", ",", "departure", ".", "get", "(", "CONF_FROM", ")", ",", "departure", ".", "get", "(", "CONF_TO", ")", ",", "departure", ".", "get", "(", "CONF_VIA", ")", ",", "departure", ".", "get", "(", "CONF_TIME", ")", ",", ")", ")", "if", "sensors", ":", "add_entities", "(", "sensors", ",", "True", ")" ]
[ 47, 0 ]
[ 82, 35 ]
python
en
['en', 'da', 'en']
True
valid_stations
(stations, given_stations)
Verify the existence of the given station codes.
Verify the existence of the given station codes.
def valid_stations(stations, given_stations): """Verify the existence of the given station codes.""" for station in given_stations: if station is None: continue if not any(s.code == station.upper() for s in stations): _LOGGER.warning("Station '%s' is not a valid station", station) return False return True
[ "def", "valid_stations", "(", "stations", ",", "given_stations", ")", ":", "for", "station", "in", "given_stations", ":", "if", "station", "is", "None", ":", "continue", "if", "not", "any", "(", "s", ".", "code", "==", "station", ".", "upper", "(", ")", "for", "s", "in", "stations", ")", ":", "_LOGGER", ".", "warning", "(", "\"Station '%s' is not a valid station\"", ",", "station", ")", "return", "False", "return", "True" ]
[ 85, 0 ]
[ 93, 15 ]
python
en
['en', 'en', 'en']
True
NSDepartureSensor.__init__
(self, nsapi, name, departure, heading, via, time)
Initialize the sensor.
Initialize the sensor.
def __init__(self, nsapi, name, departure, heading, via, time): """Initialize the sensor.""" self._nsapi = nsapi self._name = name self._departure = departure self._via = via self._heading = heading self._time = time self._state = None self._trips = None
[ "def", "__init__", "(", "self", ",", "nsapi", ",", "name", ",", "departure", ",", "heading", ",", "via", ",", "time", ")", ":", "self", ".", "_nsapi", "=", "nsapi", "self", ".", "_name", "=", "name", "self", ".", "_departure", "=", "departure", "self", ".", "_via", "=", "via", "self", ".", "_heading", "=", "heading", "self", ".", "_time", "=", "time", "self", ".", "_state", "=", "None", "self", ".", "_trips", "=", "None" ]
[ 99, 4 ]
[ 108, 26 ]
python
en
['en', 'en', 'en']
True
NSDepartureSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 111, 4 ]
[ 113, 25 ]
python
en
['en', 'mi', 'en']
True
NSDepartureSensor.icon
(self)
Return the icon for the frontend.
Return the icon for the frontend.
def icon(self): """Return the icon for the frontend.""" return ICON
[ "def", "icon", "(", "self", ")", ":", "return", "ICON" ]
[ 116, 4 ]
[ 118, 19 ]
python
en
['en', 'en', 'en']
True
NSDepartureSensor.state
(self)
Return the next departure time.
Return the next departure time.
def state(self): """Return the next departure time.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 121, 4 ]
[ 123, 26 ]
python
en
['en', 'en', 'en']
True
NSDepartureSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" if not self._trips: return if self._trips[0].trip_parts: route = [self._trips[0].departure] for k in self._trips[0].trip_parts: route.append(k.destination) # Static attributes attributes = { "going": self._trips[0].going, "departure_time_planned": None, "departure_time_actual": None, "departure_delay": False, "departure_platform_planned": self._trips[0].departure_platform_planned, "departure_platform_actual": self._trips[0].departure_platform_actual, "arrival_time_planned": None, "arrival_time_actual": None, "arrival_delay": False, "arrival_platform_planned": self._trips[0].arrival_platform_planned, "arrival_platform_actual": self._trips[0].arrival_platform_actual, "next": None, "status": self._trips[0].status.lower(), "transfers": self._trips[0].nr_transfers, "route": route, "remarks": None, ATTR_ATTRIBUTION: ATTRIBUTION, } # Planned departure attributes if self._trips[0].departure_time_planned is not None: attributes["departure_time_planned"] = self._trips[ 0 ].departure_time_planned.strftime("%H:%M") # Actual departure attributes if self._trips[0].departure_time_actual is not None: attributes["departure_time_actual"] = self._trips[ 0 ].departure_time_actual.strftime("%H:%M") # Delay departure attributes if ( attributes["departure_time_planned"] and attributes["departure_time_actual"] and attributes["departure_time_planned"] != attributes["departure_time_actual"] ): attributes["departure_delay"] = True # Planned arrival attributes if self._trips[0].arrival_time_planned is not None: attributes["arrival_time_planned"] = self._trips[ 0 ].arrival_time_planned.strftime("%H:%M") # Actual arrival attributes if self._trips[0].arrival_time_actual is not None: attributes["arrival_time_actual"] = self._trips[ 0 ].arrival_time_actual.strftime("%H:%M") # Delay arrival attributes if ( attributes["arrival_time_planned"] and attributes["arrival_time_actual"] and attributes["arrival_time_planned"] != attributes["arrival_time_actual"] ): attributes["arrival_delay"] = True # Next attributes if len(self._trips) > 1: if self._trips[1].departure_time_actual is not None: attributes["next"] = self._trips[1].departure_time_actual.strftime( "%H:%M" ) elif self._trips[1].departure_time_planned is not None: attributes["next"] = self._trips[1].departure_time_planned.strftime( "%H:%M" ) return attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "if", "not", "self", ".", "_trips", ":", "return", "if", "self", ".", "_trips", "[", "0", "]", ".", "trip_parts", ":", "route", "=", "[", "self", ".", "_trips", "[", "0", "]", ".", "departure", "]", "for", "k", "in", "self", ".", "_trips", "[", "0", "]", ".", "trip_parts", ":", "route", ".", "append", "(", "k", ".", "destination", ")", "# Static attributes", "attributes", "=", "{", "\"going\"", ":", "self", ".", "_trips", "[", "0", "]", ".", "going", ",", "\"departure_time_planned\"", ":", "None", ",", "\"departure_time_actual\"", ":", "None", ",", "\"departure_delay\"", ":", "False", ",", "\"departure_platform_planned\"", ":", "self", ".", "_trips", "[", "0", "]", ".", "departure_platform_planned", ",", "\"departure_platform_actual\"", ":", "self", ".", "_trips", "[", "0", "]", ".", "departure_platform_actual", ",", "\"arrival_time_planned\"", ":", "None", ",", "\"arrival_time_actual\"", ":", "None", ",", "\"arrival_delay\"", ":", "False", ",", "\"arrival_platform_planned\"", ":", "self", ".", "_trips", "[", "0", "]", ".", "arrival_platform_planned", ",", "\"arrival_platform_actual\"", ":", "self", ".", "_trips", "[", "0", "]", ".", "arrival_platform_actual", ",", "\"next\"", ":", "None", ",", "\"status\"", ":", "self", ".", "_trips", "[", "0", "]", ".", "status", ".", "lower", "(", ")", ",", "\"transfers\"", ":", "self", ".", "_trips", "[", "0", "]", ".", "nr_transfers", ",", "\"route\"", ":", "route", ",", "\"remarks\"", ":", "None", ",", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "}", "# Planned departure attributes", "if", "self", ".", "_trips", "[", "0", "]", ".", "departure_time_planned", "is", "not", "None", ":", "attributes", "[", "\"departure_time_planned\"", "]", "=", "self", ".", "_trips", "[", "0", "]", ".", "departure_time_planned", ".", "strftime", "(", "\"%H:%M\"", ")", "# Actual departure attributes", "if", "self", ".", "_trips", "[", "0", "]", ".", "departure_time_actual", "is", "not", "None", ":", "attributes", "[", "\"departure_time_actual\"", "]", "=", "self", ".", "_trips", "[", "0", "]", ".", "departure_time_actual", ".", "strftime", "(", "\"%H:%M\"", ")", "# Delay departure attributes", "if", "(", "attributes", "[", "\"departure_time_planned\"", "]", "and", "attributes", "[", "\"departure_time_actual\"", "]", "and", "attributes", "[", "\"departure_time_planned\"", "]", "!=", "attributes", "[", "\"departure_time_actual\"", "]", ")", ":", "attributes", "[", "\"departure_delay\"", "]", "=", "True", "# Planned arrival attributes", "if", "self", ".", "_trips", "[", "0", "]", ".", "arrival_time_planned", "is", "not", "None", ":", "attributes", "[", "\"arrival_time_planned\"", "]", "=", "self", ".", "_trips", "[", "0", "]", ".", "arrival_time_planned", ".", "strftime", "(", "\"%H:%M\"", ")", "# Actual arrival attributes", "if", "self", ".", "_trips", "[", "0", "]", ".", "arrival_time_actual", "is", "not", "None", ":", "attributes", "[", "\"arrival_time_actual\"", "]", "=", "self", ".", "_trips", "[", "0", "]", ".", "arrival_time_actual", ".", "strftime", "(", "\"%H:%M\"", ")", "# Delay arrival attributes", "if", "(", "attributes", "[", "\"arrival_time_planned\"", "]", "and", "attributes", "[", "\"arrival_time_actual\"", "]", "and", "attributes", "[", "\"arrival_time_planned\"", "]", "!=", "attributes", "[", "\"arrival_time_actual\"", "]", ")", ":", "attributes", "[", "\"arrival_delay\"", "]", "=", "True", "# Next attributes", "if", "len", "(", "self", ".", "_trips", ")", ">", "1", ":", "if", "self", ".", "_trips", "[", "1", "]", ".", "departure_time_actual", "is", "not", "None", ":", "attributes", "[", "\"next\"", "]", "=", "self", ".", "_trips", "[", "1", "]", ".", "departure_time_actual", ".", "strftime", "(", "\"%H:%M\"", ")", "elif", "self", ".", "_trips", "[", "1", "]", ".", "departure_time_planned", "is", "not", "None", ":", "attributes", "[", "\"next\"", "]", "=", "self", ".", "_trips", "[", "1", "]", ".", "departure_time_planned", ".", "strftime", "(", "\"%H:%M\"", ")", "return", "attributes" ]
[ 126, 4 ]
[ 209, 25 ]
python
en
['en', 'en', 'en']
True
NSDepartureSensor.update
(self)
Get the trip information.
Get the trip information.
def update(self): """Get the trip information.""" # If looking for a specific trip time, update around that trip time only. if self._time and ( (datetime.now() + timedelta(minutes=30)).time() < self._time or (datetime.now() - timedelta(minutes=30)).time() > self._time ): self._state = None self._trips = None return # Set the search parameter to search from a specific trip time or to just search for next trip. if self._time: trip_time = ( datetime.today() .replace(hour=self._time.hour, minute=self._time.minute) .strftime("%d-%m-%Y %H:%M") ) else: trip_time = datetime.now().strftime("%d-%m-%Y %H:%M") try: self._trips = self._nsapi.get_trips( trip_time, self._departure, self._via, self._heading, True, 0, 2 ) if self._trips: if self._trips[0].departure_time_actual is None: planned_time = self._trips[0].departure_time_planned self._state = planned_time.strftime("%H:%M") else: actual_time = self._trips[0].departure_time_actual self._state = actual_time.strftime("%H:%M") except ( requests.exceptions.ConnectionError, requests.exceptions.HTTPError, ) as error: _LOGGER.error("Couldn't fetch trip info: %s", error)
[ "def", "update", "(", "self", ")", ":", "# If looking for a specific trip time, update around that trip time only.", "if", "self", ".", "_time", "and", "(", "(", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "minutes", "=", "30", ")", ")", ".", "time", "(", ")", "<", "self", ".", "_time", "or", "(", "datetime", ".", "now", "(", ")", "-", "timedelta", "(", "minutes", "=", "30", ")", ")", ".", "time", "(", ")", ">", "self", ".", "_time", ")", ":", "self", ".", "_state", "=", "None", "self", ".", "_trips", "=", "None", "return", "# Set the search parameter to search from a specific trip time or to just search for next trip.", "if", "self", ".", "_time", ":", "trip_time", "=", "(", "datetime", ".", "today", "(", ")", ".", "replace", "(", "hour", "=", "self", ".", "_time", ".", "hour", ",", "minute", "=", "self", ".", "_time", ".", "minute", ")", ".", "strftime", "(", "\"%d-%m-%Y %H:%M\"", ")", ")", "else", ":", "trip_time", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%d-%m-%Y %H:%M\"", ")", "try", ":", "self", ".", "_trips", "=", "self", ".", "_nsapi", ".", "get_trips", "(", "trip_time", ",", "self", ".", "_departure", ",", "self", ".", "_via", ",", "self", ".", "_heading", ",", "True", ",", "0", ",", "2", ")", "if", "self", ".", "_trips", ":", "if", "self", ".", "_trips", "[", "0", "]", ".", "departure_time_actual", "is", "None", ":", "planned_time", "=", "self", ".", "_trips", "[", "0", "]", ".", "departure_time_planned", "self", ".", "_state", "=", "planned_time", ".", "strftime", "(", "\"%H:%M\"", ")", "else", ":", "actual_time", "=", "self", ".", "_trips", "[", "0", "]", ".", "departure_time_actual", "self", ".", "_state", "=", "actual_time", ".", "strftime", "(", "\"%H:%M\"", ")", "except", "(", "requests", ".", "exceptions", ".", "ConnectionError", ",", "requests", ".", "exceptions", ".", "HTTPError", ",", ")", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"Couldn't fetch trip info: %s\"", ",", "error", ")" ]
[ 212, 4 ]
[ 249, 64 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up of a Nissan Leaf binary sensor.
Set up of a Nissan Leaf binary sensor.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up of a Nissan Leaf binary sensor.""" if discovery_info is None: return devices = [] for vin, datastore in hass.data[DATA_LEAF].items(): _LOGGER.debug("Adding binary_sensors for vin=%s", vin) devices.append(LeafPluggedInSensor(datastore)) devices.append(LeafChargingSensor(datastore)) add_entities(devices, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "if", "discovery_info", "is", "None", ":", "return", "devices", "=", "[", "]", "for", "vin", ",", "datastore", "in", "hass", ".", "data", "[", "DATA_LEAF", "]", ".", "items", "(", ")", ":", "_LOGGER", ".", "debug", "(", "\"Adding binary_sensors for vin=%s\"", ",", "vin", ")", "devices", ".", "append", "(", "LeafPluggedInSensor", "(", "datastore", ")", ")", "devices", ".", "append", "(", "LeafChargingSensor", "(", "datastore", ")", ")", "add_entities", "(", "devices", ",", "True", ")" ]
[ 10, 0 ]
[ 21, 31 ]
python
en
['en', 'haw', 'en']
True
LeafPluggedInSensor.name
(self)
Sensor name.
Sensor name.
def name(self): """Sensor name.""" return f"{self.car.leaf.nickname} Plug Status"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self.car.leaf.nickname} Plug Status\"" ]
[ 28, 4 ]
[ 30, 54 ]
python
en
['en', 'ceb', 'en']
False
LeafPluggedInSensor.is_on
(self)
Return true if plugged in.
Return true if plugged in.
def is_on(self): """Return true if plugged in.""" return self.car.data[DATA_PLUGGED_IN]
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "car", ".", "data", "[", "DATA_PLUGGED_IN", "]" ]
[ 33, 4 ]
[ 35, 45 ]
python
en
['en', 'co', 'en']
True
LeafPluggedInSensor.icon
(self)
Icon handling.
Icon handling.
def icon(self): """Icon handling.""" if self.car.data[DATA_PLUGGED_IN]: return "mdi:power-plug" return "mdi:power-plug-off"
[ "def", "icon", "(", "self", ")", ":", "if", "self", ".", "car", ".", "data", "[", "DATA_PLUGGED_IN", "]", ":", "return", "\"mdi:power-plug\"", "return", "\"mdi:power-plug-off\"" ]
[ 38, 4 ]
[ 42, 35 ]
python
en
['en', 'ja', 'en']
False
LeafChargingSensor.name
(self)
Sensor name.
Sensor name.
def name(self): """Sensor name.""" return f"{self.car.leaf.nickname} Charging Status"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self.car.leaf.nickname} Charging Status\"" ]
[ 49, 4 ]
[ 51, 58 ]
python
en
['en', 'ceb', 'en']
False
LeafChargingSensor.is_on
(self)
Return true if charging.
Return true if charging.
def is_on(self): """Return true if charging.""" return self.car.data[DATA_CHARGING]
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "car", ".", "data", "[", "DATA_CHARGING", "]" ]
[ 54, 4 ]
[ 56, 43 ]
python
en
['en', 'bg', 'en']
True
LeafChargingSensor.icon
(self)
Icon handling.
Icon handling.
def icon(self): """Icon handling.""" if self.car.data[DATA_CHARGING]: return "mdi:flash" return "mdi:flash-off"
[ "def", "icon", "(", "self", ")", ":", "if", "self", ".", "car", ".", "data", "[", "DATA_CHARGING", "]", ":", "return", "\"mdi:flash\"", "return", "\"mdi:flash-off\"" ]
[ 59, 4 ]
[ 63, 30 ]
python
en
['en', 'ja', 'en']
False
build_relative_position
(query_size, key_size, device)
Build relative position according to the query and key We assume the absolute position of query :math:`P_q` is range from (0, query_size) and the absolute position of key :math:`P_k` is range from (0, key_size), The relative positions from query to key is :math:`R_{q \\rightarrow k} = P_q - P_k` Args: query_size (int): the length of query key_size (int): the length of key Return: :obj:`torch.LongTensor`: A tensor with shape [1, query_size, key_size]
Build relative position according to the query and key
def build_relative_position(query_size, key_size, device): """ Build relative position according to the query and key We assume the absolute position of query :math:`P_q` is range from (0, query_size) and the absolute position of key :math:`P_k` is range from (0, key_size), The relative positions from query to key is :math:`R_{q \\rightarrow k} = P_q - P_k` Args: query_size (int): the length of query key_size (int): the length of key Return: :obj:`torch.LongTensor`: A tensor with shape [1, query_size, key_size] """ q_ids = torch.arange(query_size, dtype=torch.long, device=device) k_ids = torch.arange(key_size, dtype=torch.long, device=device) rel_pos_ids = q_ids[:, None] - k_ids.view(1, -1).repeat(query_size, 1) rel_pos_ids = rel_pos_ids[:query_size, :] rel_pos_ids = rel_pos_ids.unsqueeze(0) return rel_pos_ids
[ "def", "build_relative_position", "(", "query_size", ",", "key_size", ",", "device", ")", ":", "q_ids", "=", "torch", ".", "arange", "(", "query_size", ",", "dtype", "=", "torch", ".", "long", ",", "device", "=", "device", ")", "k_ids", "=", "torch", ".", "arange", "(", "key_size", ",", "dtype", "=", "torch", ".", "long", ",", "device", "=", "device", ")", "rel_pos_ids", "=", "q_ids", "[", ":", ",", "None", "]", "-", "k_ids", ".", "view", "(", "1", ",", "-", "1", ")", ".", "repeat", "(", "query_size", ",", "1", ")", "rel_pos_ids", "=", "rel_pos_ids", "[", ":", "query_size", ",", ":", "]", "rel_pos_ids", "=", "rel_pos_ids", ".", "unsqueeze", "(", "0", ")", "return", "rel_pos_ids" ]
[ 439, 0 ]
[ 461, 22 ]
python
en
['en', 'error', 'th']
False
StableDropout.forward
(self, x)
Call the module Args: x (:obj:`torch.tensor`): The input tensor to apply dropout
Call the module
def forward(self, x): """ Call the module Args: x (:obj:`torch.tensor`): The input tensor to apply dropout """ if self.training and self.drop_prob > 0: return XDropout.apply(x, self.get_context()) return x
[ "def", "forward", "(", "self", ",", "x", ")", ":", "if", "self", ".", "training", "and", "self", ".", "drop_prob", ">", "0", ":", "return", "XDropout", ".", "apply", "(", "x", ",", "self", ".", "get_context", "(", ")", ")", "return", "x" ]
[ 179, 4 ]
[ 188, 16 ]
python
en
['en', 'error', 'th']
False
DisentangledSelfAttention.forward
( self, hidden_states, attention_mask, return_att=False, query_states=None, relative_pos=None, rel_embeddings=None, )
Call the module Args: hidden_states (:obj:`torch.FloatTensor`): Input states to the module usually the output from previous layer, it will be the Q,K and V in `Attention(Q,K,V)` attention_mask (:obj:`torch.ByteTensor`): An attention mask matrix of shape [`B`, `N`, `N`] where `B` is the batch size, `N` is the maximum sequence length in which element [i,j] = `1` means the `i` th token in the input can attend to the `j` th token. return_att (:obj:`bool`, optional): Whether return the attention matrix. query_states (:obj:`torch.FloatTensor`, optional): The `Q` state in `Attention(Q,K,V)`. relative_pos (:obj:`torch.LongTensor`): The relative position encoding between the tokens in the sequence. It's of shape [`B`, `N`, `N`] with values ranging in [`-max_relative_positions`, `max_relative_positions`]. rel_embeddings (:obj:`torch.FloatTensor`): The embedding of relative distances. It's a tensor of shape [:math:`2 \\times \\text{max_relative_positions}`, `hidden_size`].
Call the module
def forward( self, hidden_states, attention_mask, return_att=False, query_states=None, relative_pos=None, rel_embeddings=None, ): """ Call the module Args: hidden_states (:obj:`torch.FloatTensor`): Input states to the module usually the output from previous layer, it will be the Q,K and V in `Attention(Q,K,V)` attention_mask (:obj:`torch.ByteTensor`): An attention mask matrix of shape [`B`, `N`, `N`] where `B` is the batch size, `N` is the maximum sequence length in which element [i,j] = `1` means the `i` th token in the input can attend to the `j` th token. return_att (:obj:`bool`, optional): Whether return the attention matrix. query_states (:obj:`torch.FloatTensor`, optional): The `Q` state in `Attention(Q,K,V)`. relative_pos (:obj:`torch.LongTensor`): The relative position encoding between the tokens in the sequence. It's of shape [`B`, `N`, `N`] with values ranging in [`-max_relative_positions`, `max_relative_positions`]. rel_embeddings (:obj:`torch.FloatTensor`): The embedding of relative distances. It's a tensor of shape [:math:`2 \\times \\text{max_relative_positions}`, `hidden_size`]. """ if query_states is None: qp = self.in_proj(hidden_states) # .split(self.all_head_size, dim=-1) query_layer, key_layer, value_layer = self.transpose_for_scores(qp).chunk(3, dim=-1) else: def linear(w, b, x): if b is not None: return torch.matmul(x, w.t()) + b.t() else: return torch.matmul(x, w.t()) # + b.t() ws = self.in_proj.weight.chunk(self.num_attention_heads * 3, dim=0) qkvw = [torch.cat([ws[i * 3 + k] for i in range(self.num_attention_heads)], dim=0) for k in range(3)] qkvb = [None] * 3 q = linear(qkvw[0], qkvb[0], query_states) k, v = [linear(qkvw[i], qkvb[i], hidden_states) for i in range(1, 3)] query_layer, key_layer, value_layer = [self.transpose_for_scores(x) for x in [q, k, v]] query_layer = query_layer + self.transpose_for_scores(self.q_bias[None, None, :]) value_layer = value_layer + self.transpose_for_scores(self.v_bias[None, None, :]) rel_att = None # Take the dot product between "query" and "key" to get the raw attention scores. scale_factor = 1 + len(self.pos_att_type) scale = math.sqrt(query_layer.size(-1) * scale_factor) query_layer = query_layer / scale attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.relative_attention: rel_embeddings = self.pos_dropout(rel_embeddings) rel_att = self.disentangled_att_bias(query_layer, key_layer, relative_pos, rel_embeddings, scale_factor) if rel_att is not None: attention_scores = attention_scores + rel_att # bxhxlxd if self.talking_head: attention_scores = self.head_logits_proj(attention_scores.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) attention_probs = XSoftmax.apply(attention_scores, attention_mask, -1) attention_probs = self.dropout(attention_probs) if self.talking_head: attention_probs = self.head_weights_proj(attention_probs.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (-1,) context_layer = context_layer.view(*new_context_layer_shape) if return_att: return (context_layer, attention_probs) else: return context_layer
[ "def", "forward", "(", "self", ",", "hidden_states", ",", "attention_mask", ",", "return_att", "=", "False", ",", "query_states", "=", "None", ",", "relative_pos", "=", "None", ",", "rel_embeddings", "=", "None", ",", ")", ":", "if", "query_states", "is", "None", ":", "qp", "=", "self", ".", "in_proj", "(", "hidden_states", ")", "# .split(self.all_head_size, dim=-1)", "query_layer", ",", "key_layer", ",", "value_layer", "=", "self", ".", "transpose_for_scores", "(", "qp", ")", ".", "chunk", "(", "3", ",", "dim", "=", "-", "1", ")", "else", ":", "def", "linear", "(", "w", ",", "b", ",", "x", ")", ":", "if", "b", "is", "not", "None", ":", "return", "torch", ".", "matmul", "(", "x", ",", "w", ".", "t", "(", ")", ")", "+", "b", ".", "t", "(", ")", "else", ":", "return", "torch", ".", "matmul", "(", "x", ",", "w", ".", "t", "(", ")", ")", "# + b.t()", "ws", "=", "self", ".", "in_proj", ".", "weight", ".", "chunk", "(", "self", ".", "num_attention_heads", "*", "3", ",", "dim", "=", "0", ")", "qkvw", "=", "[", "torch", ".", "cat", "(", "[", "ws", "[", "i", "*", "3", "+", "k", "]", "for", "i", "in", "range", "(", "self", ".", "num_attention_heads", ")", "]", ",", "dim", "=", "0", ")", "for", "k", "in", "range", "(", "3", ")", "]", "qkvb", "=", "[", "None", "]", "*", "3", "q", "=", "linear", "(", "qkvw", "[", "0", "]", ",", "qkvb", "[", "0", "]", ",", "query_states", ")", "k", ",", "v", "=", "[", "linear", "(", "qkvw", "[", "i", "]", ",", "qkvb", "[", "i", "]", ",", "hidden_states", ")", "for", "i", "in", "range", "(", "1", ",", "3", ")", "]", "query_layer", ",", "key_layer", ",", "value_layer", "=", "[", "self", ".", "transpose_for_scores", "(", "x", ")", "for", "x", "in", "[", "q", ",", "k", ",", "v", "]", "]", "query_layer", "=", "query_layer", "+", "self", ".", "transpose_for_scores", "(", "self", ".", "q_bias", "[", "None", ",", "None", ",", ":", "]", ")", "value_layer", "=", "value_layer", "+", "self", ".", "transpose_for_scores", "(", "self", ".", "v_bias", "[", "None", ",", "None", ",", ":", "]", ")", "rel_att", "=", "None", "# Take the dot product between \"query\" and \"key\" to get the raw attention scores.", "scale_factor", "=", "1", "+", "len", "(", "self", ".", "pos_att_type", ")", "scale", "=", "math", ".", "sqrt", "(", "query_layer", ".", "size", "(", "-", "1", ")", "*", "scale_factor", ")", "query_layer", "=", "query_layer", "/", "scale", "attention_scores", "=", "torch", ".", "matmul", "(", "query_layer", ",", "key_layer", ".", "transpose", "(", "-", "1", ",", "-", "2", ")", ")", "if", "self", ".", "relative_attention", ":", "rel_embeddings", "=", "self", ".", "pos_dropout", "(", "rel_embeddings", ")", "rel_att", "=", "self", ".", "disentangled_att_bias", "(", "query_layer", ",", "key_layer", ",", "relative_pos", ",", "rel_embeddings", ",", "scale_factor", ")", "if", "rel_att", "is", "not", "None", ":", "attention_scores", "=", "attention_scores", "+", "rel_att", "# bxhxlxd", "if", "self", ".", "talking_head", ":", "attention_scores", "=", "self", ".", "head_logits_proj", "(", "attention_scores", ".", "permute", "(", "0", ",", "2", ",", "3", ",", "1", ")", ")", ".", "permute", "(", "0", ",", "3", ",", "1", ",", "2", ")", "attention_probs", "=", "XSoftmax", ".", "apply", "(", "attention_scores", ",", "attention_mask", ",", "-", "1", ")", "attention_probs", "=", "self", ".", "dropout", "(", "attention_probs", ")", "if", "self", ".", "talking_head", ":", "attention_probs", "=", "self", ".", "head_weights_proj", "(", "attention_probs", ".", "permute", "(", "0", ",", "2", ",", "3", ",", "1", ")", ")", ".", "permute", "(", "0", ",", "3", ",", "1", ",", "2", ")", "context_layer", "=", "torch", ".", "matmul", "(", "attention_probs", ",", "value_layer", ")", "context_layer", "=", "context_layer", ".", "permute", "(", "0", ",", "2", ",", "1", ",", "3", ")", ".", "contiguous", "(", ")", "new_context_layer_shape", "=", "context_layer", ".", "size", "(", ")", "[", ":", "-", "2", "]", "+", "(", "-", "1", ",", ")", "context_layer", "=", "context_layer", ".", "view", "(", "*", "new_context_layer_shape", ")", "if", "return_att", ":", "return", "(", "context_layer", ",", "attention_probs", ")", "else", ":", "return", "context_layer" ]
[ 532, 4 ]
[ 621, 32 ]
python
en
['en', 'error', 'th']
False
DebertaPreTrainedModel._init_weights
(self, module)
Initialize the weights.
Initialize the weights.
def _init_weights(self, module): """Initialize the weights.""" if isinstance(module, nn.Linear): # 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_()
[ "def", "_init_weights", "(", "self", ",", "module", ")", ":", "if", "isinstance", "(", "module", ",", "nn", ".", "Linear", ")", ":", "# 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_", "(", ")" ]
[ 768, 4 ]
[ 779, 62 ]
python
en
['en', 'en', 'en']
True
DebertaPreTrainedModel._pre_load_hook
(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Removes the classifier if it doesn't have the correct number of labels.
Removes the classifier if it doesn't have the correct number of labels.
def _pre_load_hook(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): """ Removes the classifier if it doesn't have the correct number of labels. """ self_state = self.state_dict() if ( ("classifier.weight" in self_state) and ("classifier.weight" in state_dict) and self_state["classifier.weight"].size() != state_dict["classifier.weight"].size() ): logger.warning( f"The checkpoint classifier head has a shape {state_dict['classifier.weight'].size()} and this model " f"classifier head has a shape {self_state['classifier.weight'].size()}. Ignoring the checkpoint " f"weights. You should train your model on new data." ) del state_dict["classifier.weight"] if "classifier.bias" in state_dict: del state_dict["classifier.bias"]
[ "def", "_pre_load_hook", "(", "self", ",", "state_dict", ",", "prefix", ",", "local_metadata", ",", "strict", ",", "missing_keys", ",", "unexpected_keys", ",", "error_msgs", ")", ":", "self_state", "=", "self", ".", "state_dict", "(", ")", "if", "(", "(", "\"classifier.weight\"", "in", "self_state", ")", "and", "(", "\"classifier.weight\"", "in", "state_dict", ")", "and", "self_state", "[", "\"classifier.weight\"", "]", ".", "size", "(", ")", "!=", "state_dict", "[", "\"classifier.weight\"", "]", ".", "size", "(", ")", ")", ":", "logger", ".", "warning", "(", "f\"The checkpoint classifier head has a shape {state_dict['classifier.weight'].size()} and this model \"", "f\"classifier head has a shape {self_state['classifier.weight'].size()}. Ignoring the checkpoint \"", "f\"weights. You should train your model on new data.\"", ")", "del", "state_dict", "[", "\"classifier.weight\"", "]", "if", "\"classifier.bias\"", "in", "state_dict", ":", "del", "state_dict", "[", "\"classifier.bias\"", "]" ]
[ 781, 4 ]
[ 798, 49 ]
python
en
['en', 'error', 'th']
False
main
(config: dict = None)
Main function. Run when file is invoked. :param config: dict configuration containing keys: ['tts', 'Audio', 'language']
Main function. Run when file is invoked. :param config: dict configuration containing keys: ['tts', 'Audio', 'language']
def main(config: dict = None): """ Main function. Run when file is invoked. :param config: dict configuration containing keys: ['tts', 'Audio', 'language'] """ reset_sigint_handler() check_for_signal("isSpeaking") bus = MessageBusClient() # Connect to the Mycroft Messagebus speech.init(bus, config) LOG.info("Starting Audio Services") bus.on('message', create_echo_function('AUDIO', ['mycroft.audio.service'])) from neon_utils.configuration_utils import get_neon_device_type if get_neon_device_type() == 'server': audio = None else: audio = AudioService(bus, config) # Connect audio service instance to message bus create_daemon(bus.run_forever) wait_for_exit_signal() speech.shutdown() if audio: audio.shutdown()
[ "def", "main", "(", "config", ":", "dict", "=", "None", ")", ":", "reset_sigint_handler", "(", ")", "check_for_signal", "(", "\"isSpeaking\"", ")", "bus", "=", "MessageBusClient", "(", ")", "# Connect to the Mycroft Messagebus", "speech", ".", "init", "(", "bus", ",", "config", ")", "LOG", ".", "info", "(", "\"Starting Audio Services\"", ")", "bus", ".", "on", "(", "'message'", ",", "create_echo_function", "(", "'AUDIO'", ",", "[", "'mycroft.audio.service'", "]", ")", ")", "from", "neon_utils", ".", "configuration_utils", "import", "get_neon_device_type", "if", "get_neon_device_type", "(", ")", "==", "'server'", ":", "audio", "=", "None", "else", ":", "audio", "=", "AudioService", "(", "bus", ",", "config", ")", "# Connect audio service instance to message bus", "create_daemon", "(", "bus", ".", "run_forever", ")", "wait_for_exit_signal", "(", ")", "speech", ".", "shutdown", "(", ")", "if", "audio", ":", "audio", ".", "shutdown", "(", ")" ]
[ 31, 0 ]
[ 56, 24 ]
python
en
['en', 'error', 'th']
False
async_setup
(hass: HomeAssistant, config: dict)
Set up the BleBox devices component.
Set up the BleBox devices component.
async def async_setup(hass: HomeAssistant, config: dict): """Set up the BleBox devices component.""" return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ")", ":", "return", "True" ]
[ 24, 0 ]
[ 26, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass: HomeAssistant, entry: ConfigEntry)
Set up BleBox devices from a config entry.
Set up BleBox devices from a config entry.
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up BleBox devices from a config entry.""" websession = async_get_clientsession(hass) host = entry.data[CONF_HOST] port = entry.data[CONF_PORT] timeout = DEFAULT_SETUP_TIMEOUT api_host = ApiHost(host, port, timeout, websession, hass.loop) try: product = await Products.async_from_host(api_host) except Error as ex: _LOGGER.error("Identify failed at %s:%d (%s)", api_host.host, api_host.port, ex) raise ConfigEntryNotReady from ex domain = hass.data.setdefault(DOMAIN, {}) domain_entry = domain.setdefault(entry.entry_id, {}) product = domain_entry.setdefault(PRODUCT, product) for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "websession", "=", "async_get_clientsession", "(", "hass", ")", "host", "=", "entry", ".", "data", "[", "CONF_HOST", "]", "port", "=", "entry", ".", "data", "[", "CONF_PORT", "]", "timeout", "=", "DEFAULT_SETUP_TIMEOUT", "api_host", "=", "ApiHost", "(", "host", ",", "port", ",", "timeout", ",", "websession", ",", "hass", ".", "loop", ")", "try", ":", "product", "=", "await", "Products", ".", "async_from_host", "(", "api_host", ")", "except", "Error", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Identify failed at %s:%d (%s)\"", ",", "api_host", ".", "host", ",", "api_host", ".", "port", ",", "ex", ")", "raise", "ConfigEntryNotReady", "from", "ex", "domain", "=", "hass", ".", "data", ".", "setdefault", "(", "DOMAIN", ",", "{", "}", ")", "domain_entry", "=", "domain", ".", "setdefault", "(", "entry", ".", "entry_id", ",", "{", "}", ")", "product", "=", "domain_entry", ".", "setdefault", "(", "PRODUCT", ",", "product", ")", "for", "component", "in", "PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "component", ")", ")", "return", "True" ]
[ 29, 0 ]
[ 55, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass: HomeAssistant, entry: ConfigEntry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, platform) for platform in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
[ "async", "def", "async_unload_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "unload_ok", "=", "all", "(", "await", "asyncio", ".", "gather", "(", "*", "[", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "platform", ")", "for", "platform", "in", "PLATFORMS", "]", ")", ")", "if", "unload_ok", ":", "hass", ".", "data", "[", "DOMAIN", "]", ".", "pop", "(", "entry", ".", "entry_id", ")", "return", "unload_ok" ]
[ 58, 0 ]
[ 72, 20 ]
python
en
['en', 'es', 'en']
True
create_blebox_entities
( hass, config_entry, async_add_entities, entity_klass, entity_type )
Create entities from a BleBox product's features.
Create entities from a BleBox product's features.
def create_blebox_entities( hass, config_entry, async_add_entities, entity_klass, entity_type ): """Create entities from a BleBox product's features.""" product = hass.data[DOMAIN][config_entry.entry_id][PRODUCT] entities = [] if entity_type in product.features: for feature in product.features[entity_type]: entities.append(entity_klass(feature)) async_add_entities(entities, True)
[ "def", "create_blebox_entities", "(", "hass", ",", "config_entry", ",", "async_add_entities", ",", "entity_klass", ",", "entity_type", ")", ":", "product", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "PRODUCT", "]", "entities", "=", "[", "]", "if", "entity_type", "in", "product", ".", "features", ":", "for", "feature", "in", "product", ".", "features", "[", "entity_type", "]", ":", "entities", ".", "append", "(", "entity_klass", "(", "feature", ")", ")", "async_add_entities", "(", "entities", ",", "True", ")" ]
[ 76, 0 ]
[ 88, 38 ]
python
en
['en', 'en', 'en']
True
BleBoxEntity.__init__
(self, feature)
Initialize a BleBox entity.
Initialize a BleBox entity.
def __init__(self, feature): """Initialize a BleBox entity.""" self._feature = feature
[ "def", "__init__", "(", "self", ",", "feature", ")", ":", "self", ".", "_feature", "=", "feature" ]
[ 94, 4 ]
[ 96, 31 ]
python
ca
['ca', 'en', 'it']
False
BleBoxEntity.name
(self)
Return the internal entity name.
Return the internal entity name.
def name(self): """Return the internal entity name.""" return self._feature.full_name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_feature", ".", "full_name" ]
[ 99, 4 ]
[ 101, 38 ]
python
en
['en', 'ig', 'en']
True
BleBoxEntity.unique_id
(self)
Return a unique id.
Return a unique id.
def unique_id(self): """Return a unique id.""" return self._feature.unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_feature", ".", "unique_id" ]
[ 104, 4 ]
[ 106, 38 ]
python
ca
['fr', 'ca', 'en']
False
BleBoxEntity.async_update
(self)
Update the entity state.
Update the entity state.
async def async_update(self): """Update the entity state.""" try: await self._feature.async_update() except Error as ex: _LOGGER.error("Updating '%s' failed: %s", self.name, ex)
[ "async", "def", "async_update", "(", "self", ")", ":", "try", ":", "await", "self", ".", "_feature", ".", "async_update", "(", ")", "except", "Error", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Updating '%s' failed: %s\"", ",", "self", ".", "name", ",", "ex", ")" ]
[ 108, 4 ]
[ 113, 68 ]
python
en
['en', 'en', 'en']
True
BleBoxEntity.device_info
(self)
Return device information for this entity.
Return device information for this entity.
def device_info(self): """Return device information for this entity.""" product = self._feature.product return { "identifiers": {(DOMAIN, product.unique_id)}, "name": product.name, "manufacturer": product.brand, "model": product.model, "sw_version": product.firmware_version, }
[ "def", "device_info", "(", "self", ")", ":", "product", "=", "self", ".", "_feature", ".", "product", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "product", ".", "unique_id", ")", "}", ",", "\"name\"", ":", "product", ".", "name", ",", "\"manufacturer\"", ":", "product", ".", "brand", ",", "\"model\"", ":", "product", ".", "model", ",", "\"sw_version\"", ":", "product", ".", "firmware_version", ",", "}" ]
[ 116, 4 ]
[ 125, 9 ]
python
en
['en', 'en', 'en']
True
device_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def device_reg(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass)
[ "def", "device_reg", "(", "hass", ")", ":", "return", "mock_device_registry", "(", "hass", ")" ]
[ 19, 0 ]
[ 21, 37 ]
python
en
['en', 'fy', 'en']
True
entity_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def entity_reg(hass): """Return an empty, loaded, registry.""" return mock_registry(hass)
[ "def", "entity_reg", "(", "hass", ")", ":", "return", "mock_registry", "(", "hass", ")" ]
[ 25, 0 ]
[ 27, 30 ]
python
en
['en', 'fy', 'en']
True
test_get_actions
(hass, device_reg, entity_reg)
Test we get the expected actions from a water_heater.
Test we get the expected actions from a water_heater.
async def test_get_actions(hass, device_reg, entity_reg): """Test we get the expected actions from a water_heater.""" config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id) expected_actions = [ { "domain": DOMAIN, "type": "turn_on", "device_id": device_entry.id, "entity_id": "water_heater.test_5678", }, { "domain": DOMAIN, "type": "turn_off", "device_id": device_entry.id, "entity_id": "water_heater.test_5678", }, ] actions = await async_get_device_automations(hass, "action", device_entry.id) assert_lists_same(actions, expected_actions)
[ "async", "def", "test_get_actions", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "\"5678\"", ",", "device_id", "=", "device_entry", ".", "id", ")", "expected_actions", "=", "[", "{", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"turn_on\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "\"water_heater.test_5678\"", ",", "}", ",", "{", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"turn_off\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "\"water_heater.test_5678\"", ",", "}", ",", "]", "actions", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"action\"", ",", "device_entry", ".", "id", ")", "assert_lists_same", "(", "actions", ",", "expected_actions", ")" ]
[ 30, 0 ]
[ 54, 48 ]
python
en
['en', 'en', 'en']
True
test_action
(hass)
Test for turn_on and turn_off actions.
Test for turn_on and turn_off actions.
async def test_action(hass): """Test for turn_on and turn_off actions.""" assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "event", "event_type": "test_event_turn_off", }, "action": { "domain": DOMAIN, "device_id": "abcdefgh", "entity_id": "water_heater.entity", "type": "turn_off", }, }, { "trigger": { "platform": "event", "event_type": "test_event_turn_on", }, "action": { "domain": DOMAIN, "device_id": "abcdefgh", "entity_id": "water_heater.entity", "type": "turn_on", }, }, ] }, ) turn_off_calls = async_mock_service(hass, "water_heater", "turn_off") turn_on_calls = async_mock_service(hass, "water_heater", "turn_on") hass.bus.async_fire("test_event_turn_off") await hass.async_block_till_done() assert len(turn_off_calls) == 1 assert len(turn_on_calls) == 0 hass.bus.async_fire("test_event_turn_on") await hass.async_block_till_done() assert len(turn_off_calls) == 1 assert len(turn_on_calls) == 1
[ "async", "def", "test_action", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event_turn_off\"", ",", "}", ",", "\"action\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"abcdefgh\"", ",", "\"entity_id\"", ":", "\"water_heater.entity\"", ",", "\"type\"", ":", "\"turn_off\"", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event_turn_on\"", ",", "}", ",", "\"action\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"abcdefgh\"", ",", "\"entity_id\"", ":", "\"water_heater.entity\"", ",", "\"type\"", ":", "\"turn_on\"", ",", "}", ",", "}", ",", "]", "}", ",", ")", "turn_off_calls", "=", "async_mock_service", "(", "hass", ",", "\"water_heater\"", ",", "\"turn_off\"", ")", "turn_on_calls", "=", "async_mock_service", "(", "hass", ",", "\"water_heater\"", ",", "\"turn_on\"", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event_turn_off\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "turn_off_calls", ")", "==", "1", "assert", "len", "(", "turn_on_calls", ")", "==", "0", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event_turn_on\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "turn_off_calls", ")", "==", "1", "assert", "len", "(", "turn_on_calls", ")", "==", "1" ]
[ 57, 0 ]
[ 103, 34 ]
python
en
['en', 'en', 'en']
True