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 list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
DemoSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
if self._battery:
return {ATTR_BATTERY_LEVEL: self._battery} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_battery",
":",
"return",
"{",
"ATTR_BATTERY_LEVEL",
":",
"self",
".",
"_battery",
"}"
] | [
98,
4
] | [
101,
54
] | python | en | ['en', 'en', 'en'] | True |
test_state | () | Test binary sensor state. | Test binary sensor state. | def test_state():
"""Test binary sensor state."""
sensor = binary_sensor.BinarySensorEntity()
assert STATE_OFF == sensor.state
with mock.patch(
"homeassistant.components.binary_sensor.BinarySensorEntity.is_on",
new=False,
):
assert STATE_OFF == binary_sensor.BinarySensorEntit... | [
"def",
"test_state",
"(",
")",
":",
"sensor",
"=",
"binary_sensor",
".",
"BinarySensorEntity",
"(",
")",
"assert",
"STATE_OFF",
"==",
"sensor",
".",
"state",
"with",
"mock",
".",
"patch",
"(",
"\"homeassistant.components.binary_sensor.BinarySensorEntity.is_on\"",
",",... | [
7,
0
] | [
20,
67
] | python | en | ['en', 'bs', 'en'] | True |
test_deprecated_base_class | (caplog) | Test deprecated base class. | Test deprecated base class. | def test_deprecated_base_class(caplog):
"""Test deprecated base class."""
class CustomBinarySensor(binary_sensor.BinarySensorDevice):
pass
CustomBinarySensor()
assert "BinarySensorDevice is deprecated, modify CustomBinarySensor" in caplog.text | [
"def",
"test_deprecated_base_class",
"(",
"caplog",
")",
":",
"class",
"CustomBinarySensor",
"(",
"binary_sensor",
".",
"BinarySensorDevice",
")",
":",
"pass",
"CustomBinarySensor",
"(",
")",
"assert",
"\"BinarySensorDevice is deprecated, modify CustomBinarySensor\"",
"in",
... | [
23,
0
] | [
30,
87
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Set up the Somfy component. | Set up the Somfy component. | async def async_setup(hass, config):
"""Set up the Somfy component."""
hass.data[DOMAIN] = {}
domain_config = config.get(DOMAIN, {})
hass.data[DOMAIN][CONF_OPTIMISTIC] = domain_config.get(CONF_OPTIMISTIC, False)
if CONF_CLIENT_ID in domain_config:
config_flow.SomfyFlowHandler.async_register... | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"}",
"domain_config",
"=",
"config",
".",
"get",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"... | [
52,
0
] | [
71,
15
] | python | en | ['en', 'da', 'en'] | True |
async_setup_entry | (hass: HomeAssistantType, entry: ConfigEntry) | Set up Somfy from a config entry. | Set up Somfy from a config entry. | async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
"""Set up Somfy from a config entry."""
# Backwards compat
if "auth_implementation" not in entry.data:
hass.config_entries.async_update_entry(
entry, data={**entry.data, "auth_implementation": DOMAIN}
)
... | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"# Backwards compat",
"if",
"\"auth_implementation\"",
"not",
"in",
"entry",
".",
"data",
":",
"hass",
".",
"config_entries",
".",
"async_update... | [
74,
0
] | [
136,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass: HomeAssistantType, entry: ConfigEntry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry):
"""Unload a config entry."""
hass.data[DOMAIN].pop(API, None)
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in SOMFY_COMPONENTS
]
)... | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"pop",
"(",
"API",
",",
"None",
")",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"["... | [
139,
0
] | [
148,
15
] | python | en | ['en', 'es', 'en'] | True |
SomfyEntity.__init__ | (self, coordinator, device_id, somfy_api) | Initialize the Somfy device. | Initialize the Somfy device. | def __init__(self, coordinator, device_id, somfy_api):
"""Initialize the Somfy device."""
super().__init__(coordinator)
self._id = device_id
self.api = somfy_api | [
"def",
"__init__",
"(",
"self",
",",
"coordinator",
",",
"device_id",
",",
"somfy_api",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
")",
"self",
".",
"_id",
"=",
"device_id",
"self",
".",
"api",
"=",
"somfy_api"
] | [
154,
4
] | [
158,
28
] | python | en | ['en', 'en', 'en'] | True |
SomfyEntity.device | (self) | Return data for the device id. | Return data for the device id. | def device(self):
"""Return data for the device id."""
return self.coordinator.data[self._id] | [
"def",
"device",
"(",
"self",
")",
":",
"return",
"self",
".",
"coordinator",
".",
"data",
"[",
"self",
".",
"_id",
"]"
] | [
161,
4
] | [
163,
46
] | python | en | ['en', 'en', 'en'] | True |
SomfyEntity.unique_id | (self) | Return the unique id base on the id returned by Somfy. | Return the unique id base on the id returned by Somfy. | def unique_id(self):
"""Return the unique id base on the id returned by Somfy."""
return self._id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_id"
] | [
166,
4
] | [
168,
23
] | python | en | ['en', 'en', 'en'] | True |
SomfyEntity.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return self.device.name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"device",
".",
"name"
] | [
171,
4
] | [
173,
31
] | python | en | ['en', 'en', 'en'] | True |
SomfyEntity.device_info | (self) | Return device specific attributes.
Implemented by platform classes.
| Return device specific attributes. | def device_info(self):
"""Return device specific attributes.
Implemented by platform classes.
"""
return {
"identifiers": {(DOMAIN, self.unique_id)},
"name": self.name,
"model": self.device.type,
"via_hub": (DOMAIN, self.device.parent_id),... | [
"def",
"device_info",
"(",
"self",
")",
":",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"DOMAIN",
",",
"self",
".",
"unique_id",
")",
"}",
",",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"model\"",
":",
"self",
".",
"device",
".",
"type",
","... | [
176,
4
] | [
188,
9
] | python | en | ['fr', 'it', 'en'] | False |
SomfyEntity.has_capability | (self, capability) | Test if device has a capability. | Test if device has a capability. | def has_capability(self, capability):
"""Test if device has a capability."""
capabilities = self.device.capabilities
return bool([c for c in capabilities if c.name == capability]) | [
"def",
"has_capability",
"(",
"self",
",",
"capability",
")",
":",
"capabilities",
"=",
"self",
".",
"device",
".",
"capabilities",
"return",
"bool",
"(",
"[",
"c",
"for",
"c",
"in",
"capabilities",
"if",
"c",
".",
"name",
"==",
"capability",
"]",
")"
] | [
190,
4
] | [
193,
70
] | python | en | ['en', 'en', 'en'] | True |
SomfyEntity.assumed_state | (self) | Return if the device has an assumed state. | Return if the device has an assumed state. | def assumed_state(self):
"""Return if the device has an assumed state."""
return not bool(self.device.states) | [
"def",
"assumed_state",
"(",
"self",
")",
":",
"return",
"not",
"bool",
"(",
"self",
".",
"device",
".",
"states",
")"
] | [
196,
4
] | [
198,
43
] | python | en | ['en', 'en', 'en'] | True |
SomfyEntity._handle_coordinator_update | (self) | Process an update from the coordinator. | Process an update from the coordinator. | def _handle_coordinator_update(self):
"""Process an update from the coordinator."""
self._create_device()
super()._handle_coordinator_update() | [
"def",
"_handle_coordinator_update",
"(",
"self",
")",
":",
"self",
".",
"_create_device",
"(",
")",
"super",
"(",
")",
".",
"_handle_coordinator_update",
"(",
")"
] | [
201,
4
] | [
204,
44
] | python | en | ['en', 'en', 'en'] | True |
SomfyEntity._create_device | (self) | Update the device with the latest data. | Update the device with the latest data. | def _create_device(self):
"""Update the device with the latest data.""" | [
"def",
"_create_device",
"(",
"self",
")",
":"
] | [
207,
4
] | [
208,
53
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up Abode camera devices. | Set up Abode camera devices. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Abode camera devices."""
data = hass.data[DOMAIN]
entities = []
for device in data.abode.get_devices(generic_type=CONST.TYPE_CAMERA):
entities.append(AbodeCamera(data, device, TIMELINE.CAPTURE_IMAGE))
async_add... | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"entities",
"=",
"[",
"]",
"for",
"device",
"in",
"data",
".",
"abode",
".",
"get_devices",
... | [
17,
0
] | [
26,
32
] | python | en | ['es', 'en', 'en'] | True |
AbodeCamera.__init__ | (self, data, device, event) | Initialize the Abode device. | Initialize the Abode device. | def __init__(self, data, device, event):
"""Initialize the Abode device."""
AbodeDevice.__init__(self, data, device)
Camera.__init__(self)
self._event = event
self._response = None | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"device",
",",
"event",
")",
":",
"AbodeDevice",
".",
"__init__",
"(",
"self",
",",
"data",
",",
"device",
")",
"Camera",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"_event",
"=",
"event",
"self"... | [
32,
4
] | [
37,
29
] | python | en | ['en', 'en', 'en'] | True |
AbodeCamera.async_added_to_hass | (self) | Subscribe Abode events. | Subscribe Abode events. | async def async_added_to_hass(self):
"""Subscribe Abode events."""
await super().async_added_to_hass()
self.hass.async_add_executor_job(
self._data.abode.events.add_timeline_callback,
self._event,
self._capture_callback,
)
signal = f"abode_ca... | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"_data",
".",
"abode",
".",
"events",
".",
"add_timeline_cal... | [
39,
4
] | [
50,
87
] | python | en | ['en', 'en', 'en'] | True |
AbodeCamera.capture | (self) | Request a new image capture. | Request a new image capture. | def capture(self):
"""Request a new image capture."""
return self._device.capture() | [
"def",
"capture",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"capture",
"(",
")"
] | [
52,
4
] | [
54,
37
] | python | en | ['en', 'en', 'en'] | True |
AbodeCamera.refresh_image | (self) | Find a new image on the timeline. | Find a new image on the timeline. | def refresh_image(self):
"""Find a new image on the timeline."""
if self._device.refresh_image():
self.get_image() | [
"def",
"refresh_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_device",
".",
"refresh_image",
"(",
")",
":",
"self",
".",
"get_image",
"(",
")"
] | [
57,
4
] | [
60,
28
] | python | en | ['en', 'en', 'en'] | True |
AbodeCamera.get_image | (self) | Attempt to download the most recent capture. | Attempt to download the most recent capture. | def get_image(self):
"""Attempt to download the most recent capture."""
if self._device.image_url:
try:
self._response = requests.get(self._device.image_url, stream=True)
self._response.raise_for_status()
except requests.HTTPError as err:
... | [
"def",
"get_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_device",
".",
"image_url",
":",
"try",
":",
"self",
".",
"_response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_device",
".",
"image_url",
",",
"stream",
"=",
"True",
")",
"self",... | [
62,
4
] | [
73,
33
] | python | en | ['en', 'en', 'en'] | True |
AbodeCamera.camera_image | (self) | Get a camera image. | Get a camera image. | def camera_image(self):
"""Get a camera image."""
self.refresh_image()
if self._response:
return self._response.content
return None | [
"def",
"camera_image",
"(",
"self",
")",
":",
"self",
".",
"refresh_image",
"(",
")",
"if",
"self",
".",
"_response",
":",
"return",
"self",
".",
"_response",
".",
"content",
"return",
"None"
] | [
75,
4
] | [
82,
19
] | python | en | ['es', 'pt', 'en'] | False |
AbodeCamera.turn_on | (self) | Turn on camera. | Turn on camera. | def turn_on(self):
"""Turn on camera."""
self._device.privacy_mode(False) | [
"def",
"turn_on",
"(",
"self",
")",
":",
"self",
".",
"_device",
".",
"privacy_mode",
"(",
"False",
")"
] | [
84,
4
] | [
86,
40
] | python | en | ['en', 'et', 'en'] | True |
AbodeCamera.turn_off | (self) | Turn off camera. | Turn off camera. | def turn_off(self):
"""Turn off camera."""
self._device.privacy_mode(True) | [
"def",
"turn_off",
"(",
"self",
")",
":",
"self",
".",
"_device",
".",
"privacy_mode",
"(",
"True",
")"
] | [
88,
4
] | [
90,
39
] | python | en | ['en', 'ja', 'en'] | True |
AbodeCamera._capture_callback | (self, capture) | Update the image with the device then refresh device. | Update the image with the device then refresh device. | def _capture_callback(self, capture):
"""Update the image with the device then refresh device."""
self._device.update_image_location(capture)
self.get_image()
self.schedule_update_ha_state() | [
"def",
"_capture_callback",
"(",
"self",
",",
"capture",
")",
":",
"self",
".",
"_device",
".",
"update_image_location",
"(",
"capture",
")",
"self",
".",
"get_image",
"(",
")",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
92,
4
] | [
96,
39
] | python | en | ['en', 'en', 'en'] | True |
AbodeCamera.is_on | (self) | Return true if on. | Return true if on. | def is_on(self):
"""Return true if on."""
return self._device.is_on | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"is_on"
] | [
99,
4
] | [
101,
33
] | python | en | ['en', 'mt', 'en'] | True |
async_setup_entry | (
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], bool], None],
) | Set up Canary sensors based on a config entry. | Set up Canary sensors based on a config entry. | async def async_setup_entry(
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], bool], None],
) -> None:
"""Set up Canary sensors based on a config entry."""
coordinator: CanaryDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id][
DATA_COORDINATOR
... | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
":",
"Callable",
"[",
"[",
"List",
"[",
"Entity",
"]",
",",
"bool",
"]",
",",
"None",
"]",
",",
")",
"->",
"None",
":... | [
53,
0
] | [
74,
37
] | python | en | ['en', 'en', 'en'] | True |
CanarySensor.__init__ | (self, coordinator, sensor_type, location, device) | Initialize the sensor. | Initialize the sensor. | def __init__(self, coordinator, sensor_type, location, device):
"""Initialize the sensor."""
super().__init__(coordinator)
self._sensor_type = sensor_type
self._device_id = device.device_id
self._device_name = device.name
self._device_type_name = device.device_type["name"... | [
"def",
"__init__",
"(",
"self",
",",
"coordinator",
",",
"sensor_type",
",",
"location",
",",
"device",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
")",
"self",
".",
"_sensor_type",
"=",
"sensor_type",
"self",
".",
"_device_id",
"=",
... | [
80,
4
] | [
103,
46
] | python | en | ['en', 'en', 'en'] | True |
CanarySensor.reading | (self) | Return the device sensor reading. | Return the device sensor reading. | def reading(self):
"""Return the device sensor reading."""
readings = self.coordinator.data["readings"][self._device_id]
value = next(
(
reading.value
for reading in readings
if reading.sensor_type == self._canary_type
),
... | [
"def",
"reading",
"(",
"self",
")",
":",
"readings",
"=",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"readings\"",
"]",
"[",
"self",
".",
"_device_id",
"]",
"value",
"=",
"next",
"(",
"(",
"reading",
".",
"value",
"for",
"reading",
"in",
"readings... | [
106,
4
] | [
122,
19
] | python | en | ['en', 'sq', 'en'] | True |
CanarySensor.name | (self) | Return the name of the Canary sensor. | Return the name of the Canary sensor. | def name(self):
"""Return the name of the Canary sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
125,
4
] | [
127,
25
] | python | en | ['en', 'en', 'en'] | True |
CanarySensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self.reading | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"reading"
] | [
130,
4
] | [
132,
27
] | python | en | ['en', 'en', 'en'] | True |
CanarySensor.unique_id | (self) | Return the unique ID of this sensor. | Return the unique ID of this sensor. | def unique_id(self):
"""Return the unique ID of this sensor."""
return f"{self._device_id}_{self._sensor_type[0]}" | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"f\"{self._device_id}_{self._sensor_type[0]}\""
] | [
135,
4
] | [
137,
58
] | python | en | ['en', 'la', 'en'] | True |
CanarySensor.device_info | (self) | Return the device_info of the device. | Return the device_info of the device. | def device_info(self):
"""Return the device_info of the device."""
return {
"identifiers": {(DOMAIN, str(self._device_id))},
"name": self._device_name,
"model": self._device_type_name,
"manufacturer": MANUFACTURER,
} | [
"def",
"device_info",
"(",
"self",
")",
":",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"DOMAIN",
",",
"str",
"(",
"self",
".",
"_device_id",
")",
")",
"}",
",",
"\"name\"",
":",
"self",
".",
"_device_name",
",",
"\"model\"",
":",
"self",
".",
... | [
140,
4
] | [
147,
9
] | python | en | ['en', 'en', 'en'] | True |
CanarySensor.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 self._sensor_type[1] | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor_type",
"[",
"1",
"]"
] | [
150,
4
] | [
152,
35
] | python | en | ['en', 'la', 'en'] | True |
CanarySensor.device_class | (self) | Device class for the sensor. | Device class for the sensor. | def device_class(self):
"""Device class for the sensor."""
return self._sensor_type[3] | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor_type",
"[",
"3",
"]"
] | [
155,
4
] | [
157,
35
] | python | en | ['en', 'en', 'en'] | True |
CanarySensor.icon | (self) | Icon for the sensor. | Icon for the sensor. | def icon(self):
"""Icon for the sensor."""
return self._sensor_type[2] | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sensor_type",
"[",
"2",
"]"
] | [
160,
4
] | [
162,
35
] | python | en | ['en', 'en', 'en'] | True |
CanarySensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
reading = self.reading
if self._sensor_type[0] == "air_quality" and reading is not None:
air_quality = None
if reading <= 0.4:
air_quality = STATE_AIR_QUALITY_VERY_ABNORMAL
... | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"reading",
"=",
"self",
".",
"reading",
"if",
"self",
".",
"_sensor_type",
"[",
"0",
"]",
"==",
"\"air_quality\"",
"and",
"reading",
"is",
"not",
"None",
":",
"air_quality",
"=",
"None",
"if",
"readi... | [
165,
4
] | [
180,
19
] | python | en | ['en', 'en', 'en'] | True |
get_max | (q_values: torch.Tensor, expand_action_dim: bool = True) |
Given Q-values for a batch of states and all actions, return the maximum Q-value and
the corresponding action index for each state.
|
Given Q-values for a batch of states and all actions, return the maximum Q-value and
the corresponding action index for each state.
| def get_max(q_values: torch.Tensor, expand_action_dim: bool = True):
"""
Given Q-values for a batch of states and all actions, return the maximum Q-value and
the corresponding action index for each state.
"""
greedy_q, actions = q_values.max(dim=1)
if expand_action_dim:
actions = actions... | [
"def",
"get_max",
"(",
"q_values",
":",
"torch",
".",
"Tensor",
",",
"expand_action_dim",
":",
"bool",
"=",
"True",
")",
":",
"greedy_q",
",",
"actions",
"=",
"q_values",
".",
"max",
"(",
"dim",
"=",
"1",
")",
"if",
"expand_action_dim",
":",
"actions",
... | [
14,
0
] | [
22,
28
] | python | en | ['en', 'error', 'th'] | False |
async_get_service | (hass, config, discovery_info=None) | Get the MySensors notification service. | Get the MySensors notification service. | async def async_get_service(hass, config, discovery_info=None):
"""Get the MySensors notification service."""
new_devices = mysensors.setup_mysensors_platform(
hass, DOMAIN, discovery_info, MySensorsNotificationDevice
)
if not new_devices:
return None
return MySensorsNotificationServ... | [
"async",
"def",
"async_get_service",
"(",
"hass",
",",
"config",
",",
"discovery_info",
"=",
"None",
")",
":",
"new_devices",
"=",
"mysensors",
".",
"setup_mysensors_platform",
"(",
"hass",
",",
"DOMAIN",
",",
"discovery_info",
",",
"MySensorsNotificationDevice",
... | [
5,
0
] | [
12,
45
] | python | en | ['en', 'en', 'en'] | True |
MySensorsNotificationDevice.send_msg | (self, msg) | Send a message. | Send a message. | def send_msg(self, msg):
"""Send a message."""
for sub_msg in [msg[i : i + 25] for i in range(0, len(msg), 25)]:
# Max mysensors payload is 25 bytes.
self.gateway.set_child_value(
self.node_id, self.child_id, self.value_type, sub_msg
) | [
"def",
"send_msg",
"(",
"self",
",",
"msg",
")",
":",
"for",
"sub_msg",
"in",
"[",
"msg",
"[",
"i",
":",
"i",
"+",
"25",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"msg",
")",
",",
"25",
")",
"]",
":",
"# Max mysensors payload i... | [
18,
4
] | [
24,
13
] | python | en | ['en', 'lb', 'en'] | True |
MySensorsNotificationDevice.__repr__ | (self) | Return the representation. | Return the representation. | def __repr__(self):
"""Return the representation."""
return f"<MySensorsNotificationDevice {self.name}>" | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"f\"<MySensorsNotificationDevice {self.name}>\""
] | [
26,
4
] | [
28,
59
] | python | en | ['en', 'id', 'en'] | True |
MySensorsNotificationService.__init__ | (self, hass) | Initialize the service. | Initialize the service. | def __init__(self, hass):
"""Initialize the service."""
self.devices = mysensors.get_mysensors_devices(hass, DOMAIN) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
")",
":",
"self",
".",
"devices",
"=",
"mysensors",
".",
"get_mysensors_devices",
"(",
"hass",
",",
"DOMAIN",
")"
] | [
34,
4
] | [
36,
68
] | python | en | ['en', 'en', 'en'] | True |
MySensorsNotificationService.async_send_message | (self, message="", **kwargs) | Send a message to a user. | Send a message to a user. | async def async_send_message(self, message="", **kwargs):
"""Send a message to a user."""
target_devices = kwargs.get(ATTR_TARGET)
devices = [
device
for device in self.devices.values()
if target_devices is None or device.name in target_devices
]
... | [
"async",
"def",
"async_send_message",
"(",
"self",
",",
"message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"target_devices",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TARGET",
")",
"devices",
"=",
"[",
"device",
"for",
"device",
"in",
"self",
".",
... | [
38,
4
] | [
48,
36
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Set up the Watson IoT Platform component. | Set up the Watson IoT Platform component. | def setup(hass, config):
"""Set up the Watson IoT Platform component."""
conf = config[DOMAIN]
include = conf[CONF_INCLUDE]
exclude = conf[CONF_EXCLUDE]
include_e = set(include[CONF_ENTITIES])
include_d = set(include[CONF_DOMAINS])
exclude_e = set(exclude[CONF_ENTITIES])
exclude_d = se... | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"conf",
"=",
"config",
"[",
"DOMAIN",
"]",
"include",
"=",
"conf",
"[",
"CONF_INCLUDE",
"]",
"exclude",
"=",
"conf",
"[",
"CONF_EXCLUDE",
"]",
"include_e",
"=",
"set",
"(",
"include",
"[",
"CONF_ENT... | [
70,
0
] | [
151,
15
] | python | en | ['en', 'en', 'en'] | True |
WatsonIOTThread.__init__ | (self, hass, gateway, event_to_json) | Initialize the listener. | Initialize the listener. | def __init__(self, hass, gateway, event_to_json):
"""Initialize the listener."""
threading.Thread.__init__(self, name="WatsonIOT")
self.queue = queue.Queue()
self.gateway = gateway
self.gateway.connect()
self.event_to_json = event_to_json
self.write_errors = 0
... | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"gateway",
",",
"event_to_json",
")",
":",
"threading",
".",
"Thread",
".",
"__init__",
"(",
"self",
",",
"name",
"=",
"\"WatsonIOT\"",
")",
"self",
".",
"queue",
"=",
"queue",
".",
"Queue",
"(",
")",
... | [
157,
4
] | [
166,
66
] | python | en | ['en', 'en', 'en'] | True |
WatsonIOTThread._event_listener | (self, event) | Listen for new messages on the bus and queue them for Watson IoT. | Listen for new messages on the bus and queue them for Watson IoT. | def _event_listener(self, event):
"""Listen for new messages on the bus and queue them for Watson IoT."""
item = (time.monotonic(), event)
self.queue.put(item) | [
"def",
"_event_listener",
"(",
"self",
",",
"event",
")",
":",
"item",
"=",
"(",
"time",
".",
"monotonic",
"(",
")",
",",
"event",
")",
"self",
".",
"queue",
".",
"put",
"(",
"item",
")"
] | [
169,
4
] | [
172,
28
] | python | en | ['en', 'en', 'en'] | True |
WatsonIOTThread.get_events_json | (self) | Return an event formatted for writing. | Return an event formatted for writing. | def get_events_json(self):
"""Return an event formatted for writing."""
events = []
try:
item = self.queue.get()
if item is None:
self.shutdown = True
else:
event_json = self.event_to_json(item[1])
if event_jso... | [
"def",
"get_events_json",
"(",
"self",
")",
":",
"events",
"=",
"[",
"]",
"try",
":",
"item",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"if",
"item",
"is",
"None",
":",
"self",
".",
"shutdown",
"=",
"True",
"else",
":",
"event_json",
"=",
... | [
174,
4
] | [
191,
21
] | python | en | ['en', 'en', 'en'] | True |
WatsonIOTThread.write_to_watson | (self, events) | Write preprocessed events to watson. | Write preprocessed events to watson. | def write_to_watson(self, events):
"""Write preprocessed events to watson."""
for event in events:
for retry in range(MAX_TRIES + 1):
try:
for field in event["fields"]:
value = event["fields"][field]
device_... | [
"def",
"write_to_watson",
"(",
"self",
",",
"events",
")",
":",
"for",
"event",
"in",
"events",
":",
"for",
"retry",
"in",
"range",
"(",
"MAX_TRIES",
"+",
"1",
")",
":",
"try",
":",
"for",
"field",
"in",
"event",
"[",
"\"fields\"",
"]",
":",
"value",... | [
193,
4
] | [
216,
84
] | python | en | ['en', 'en', 'nl'] | True |
WatsonIOTThread.run | (self) | Process incoming events. | Process incoming events. | def run(self):
"""Process incoming events."""
while not self.shutdown:
event = self.get_events_json()
if event:
self.write_to_watson(event)
self.queue.task_done() | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"shutdown",
":",
"event",
"=",
"self",
".",
"get_events_json",
"(",
")",
"if",
"event",
":",
"self",
".",
"write_to_watson",
"(",
"event",
")",
"self",
".",
"queue",
".",
"task_done",
... | [
218,
4
] | [
224,
34
] | python | en | ['en', 'en', 'en'] | True |
WatsonIOTThread.block_till_done | (self) | Block till all events processed. | Block till all events processed. | def block_till_done(self):
"""Block till all events processed."""
self.queue.join() | [
"def",
"block_till_done",
"(",
"self",
")",
":",
"self",
".",
"queue",
".",
"join",
"(",
")"
] | [
226,
4
] | [
228,
25
] | python | en | ['sv', 'en', 'en'] | True |
RobertaTokenizer.build_inputs_with_special_tokens | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) |
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A RoBERTa sequence has the following format:
- single sequence: ``<s> X </s>``
- pair of sequences: ``<s> A </s></s> B </s>``
Args:
... |
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A RoBERTa sequence has the following format: | def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A RoBERTa sequence ha... | [
"def",
"build_inputs_with_special_tokens",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"int",
"]",
":",
"if",
"token_ids_1",
... | [
173,
4
] | [
196,
64
] | python | en | ['en', 'error', 'th'] | False |
RobertaTokenizer.get_special_tokens_mask | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) |
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` method.
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs.
token_ids_1 (:obj:`List[int]`,... |
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer ``prepare_for_model`` method. | def get_special_tokens_mask(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
"""
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens ... | [
"def",
"get_special_tokens_mask",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"already_has_special_tokens",
":",
"bool",
"=",
"False",
")",
"->",
... | [
198,
4
] | [
226,
87
] | python | en | ['en', 'error', 'th'] | False |
RobertaTokenizer.create_token_type_ids_from_sequences | (
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) |
Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (:obj:`List[int]`):
List of IDs.
token_ids_1 (:obj:`List[... |
Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
make use of token type ids, therefore a list of zeros is returned. | def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not
make use of token type ids, therefore a ... | [
"def",
"create_token_type_ids_from_sequences",
"(",
"self",
",",
"token_ids_0",
":",
"List",
"[",
"int",
"]",
",",
"token_ids_1",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"int",
"]",
":",
"sep",
"=",
"[",... | [
228,
4
] | [
249,
75
] | python | en | ['en', 'error', 'th'] | False |
get_files_list | (folder_path, filter_term) | Return the list of files, applying filter. | Return the list of files, applying filter. | def get_files_list(folder_path, filter_term):
"""Return the list of files, applying filter."""
query = folder_path + filter_term
files_list = glob.glob(query)
return files_list | [
"def",
"get_files_list",
"(",
"folder_path",
",",
"filter_term",
")",
":",
"query",
"=",
"folder_path",
"+",
"filter_term",
"files_list",
"=",
"glob",
".",
"glob",
"(",
"query",
")",
"return",
"files_list"
] | [
29,
0
] | [
33,
21
] | python | en | ['en', 'no', 'en'] | True |
get_size | (files_list) | Return the sum of the size in bytes of files in the list. | Return the sum of the size in bytes of files in the list. | def get_size(files_list):
"""Return the sum of the size in bytes of files in the list."""
size_list = [os.stat(f).st_size for f in files_list if os.path.isfile(f)]
return sum(size_list) | [
"def",
"get_size",
"(",
"files_list",
")",
":",
"size_list",
"=",
"[",
"os",
".",
"stat",
"(",
"f",
")",
".",
"st_size",
"for",
"f",
"in",
"files_list",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
"]",
"return",
"sum",
"(",
"size_list",
... | [
36,
0
] | [
39,
25
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the folder sensor. | Set up the folder sensor. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the folder sensor."""
path = config.get(CONF_FOLDER_PATHS)
if not hass.config.is_allowed_path(path):
_LOGGER.error("folder %s is not valid or allowed", path)
else:
folder = Folder(path, config.get(CONF_FILTER... | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"path",
"=",
"config",
".",
"get",
"(",
"CONF_FOLDER_PATHS",
")",
"if",
"not",
"hass",
".",
"config",
".",
"is_allowed_path",
"(",
"path... | [
42,
0
] | [
50,
36
] | python | en | ['en', 'da', 'en'] | True |
Folder.__init__ | (self, folder_path, filter_term) | Initialize the data object. | Initialize the data object. | def __init__(self, folder_path, filter_term):
"""Initialize the data object."""
folder_path = os.path.join(folder_path, "") # If no trailing / add it
self._folder_path = folder_path # Need to check its a valid path
self._filter_term = filter_term
self._number_of_files = None
... | [
"def",
"__init__",
"(",
"self",
",",
"folder_path",
",",
"filter_term",
")",
":",
"folder_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder_path",
",",
"\"\"",
")",
"# If no trailing / add it",
"self",
".",
"_folder_path",
"=",
"folder_path",
"# Need to... | [
58,
4
] | [
67,
30
] | python | en | ['en', 'en', 'en'] | True |
Folder.update | (self) | Update the sensor. | Update the sensor. | def update(self):
"""Update the sensor."""
files_list = get_files_list(self._folder_path, self._filter_term)
self._file_list = files_list
self._number_of_files = len(files_list)
self._size = get_size(files_list) | [
"def",
"update",
"(",
"self",
")",
":",
"files_list",
"=",
"get_files_list",
"(",
"self",
".",
"_folder_path",
",",
"self",
".",
"_filter_term",
")",
"self",
".",
"_file_list",
"=",
"files_list",
"self",
".",
"_number_of_files",
"=",
"len",
"(",
"files_list"... | [
69,
4
] | [
74,
41
] | python | en | ['en', 'nl', 'en'] | True |
Folder.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"
] | [
77,
4
] | [
79,
25
] | python | en | ['en', 'mi', 'en'] | True |
Folder.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
decimals = 2
size_mb = round(self._size / 1e6, decimals)
return size_mb | [
"def",
"state",
"(",
"self",
")",
":",
"decimals",
"=",
"2",
"size_mb",
"=",
"round",
"(",
"self",
".",
"_size",
"/",
"1e6",
",",
"decimals",
")",
"return",
"size_mb"
] | [
82,
4
] | [
86,
22
] | python | en | ['en', 'en', 'en'] | True |
Folder.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
return self.ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"self",
".",
"ICON"
] | [
89,
4
] | [
91,
24
] | python | en | ['en', 'en', 'en'] | True |
Folder.device_state_attributes | (self) | Return other details about the sensor state. | Return other details about the sensor state. | def device_state_attributes(self):
"""Return other details about the sensor state."""
return {
"path": self._folder_path,
"filter": self._filter_term,
"number_of_files": self._number_of_files,
"bytes": self._size,
"file_list": self._file_list,
... | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"path\"",
":",
"self",
".",
"_folder_path",
",",
"\"filter\"",
":",
"self",
".",
"_filter_term",
",",
"\"number_of_files\"",
":",
"self",
".",
"_number_of_files",
",",
"\"bytes\"",
":",
... | [
94,
4
] | [
102,
9
] | python | en | ['en', 'en', 'en'] | True |
Folder.unit_of_measurement | (self) | Return the unit of measurement of this entity, if any. | Return the unit of measurement of this entity, if any. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
105,
4
] | [
107,
40
] | python | en | ['en', 'en', 'en'] | True |
tabulate | (rows: List[List[Union[str, int]]], headers: List[str]) |
Inspired by:
- stackoverflow.com/a/8356620/593036
- stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
|
Inspired by: | def tabulate(rows: List[List[Union[str, int]]], headers: List[str]) -> str:
"""
Inspired by:
- stackoverflow.com/a/8356620/593036
- stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
"""
col_widths = [max(len(str(x)) for x in col) for col in zip(*rows, headers)]
row_format =... | [
"def",
"tabulate",
"(",
"rows",
":",
"List",
"[",
"List",
"[",
"Union",
"[",
"str",
",",
"int",
"]",
"]",
"]",
",",
"headers",
":",
"List",
"[",
"str",
"]",
")",
"->",
"str",
":",
"col_widths",
"=",
"[",
"max",
"(",
"len",
"(",
"str",
"(",
"x... | [
112,
0
] | [
126,
27
] | python | en | ['en', 'error', 'th'] | False |
UploadCommand.walk_dir | (self, rel_path) |
Recursively list all files in a folder.
|
Recursively list all files in a folder.
| def walk_dir(self, rel_path):
"""
Recursively list all files in a folder.
"""
entries: List[os.DirEntry] = list(os.scandir(rel_path))
files = [(os.path.join(os.getcwd(), f.path), f.path) for f in entries if f.is_file()] # (filepath, filename)
for f in entries:
... | [
"def",
"walk_dir",
"(",
"self",
",",
"rel_path",
")",
":",
"entries",
":",
"List",
"[",
"os",
".",
"DirEntry",
"]",
"=",
"list",
"(",
"os",
".",
"scandir",
"(",
"rel_path",
")",
")",
"files",
"=",
"[",
"(",
"os",
".",
"path",
".",
"join",
"(",
... | [
304,
4
] | [
313,
20
] | python | en | ['en', 'error', 'th'] | False |
reshape | (model, n: int = 1, h: int = 480, w: int = 640, mode='auto') |
:param model: Input ONNX model object
:param n: Batch size dimension
:param h: Height dimension
:param w: Width dimension
:param mode: Set `retinaface` to reshape RetinaFace model, otherwise reshape Centerface
:return: ONNX model with reshaped input and outputs
|
:param model: Input ONNX model object
:param n: Batch size dimension
:param h: Height dimension
:param w: Width dimension
:param mode: Set `retinaface` to reshape RetinaFace model, otherwise reshape Centerface
:return: ONNX model with reshaped input and outputs
| def reshape(model, n: int = 1, h: int = 480, w: int = 640, mode='auto'):
'''
:param model: Input ONNX model object
:param n: Batch size dimension
:param h: Height dimension
:param w: Width dimension
:param mode: Set `retinaface` to reshape RetinaFace model, otherwise reshape Centerface
:retu... | [
"def",
"reshape",
"(",
"model",
",",
"n",
":",
"int",
"=",
"1",
",",
"h",
":",
"int",
"=",
"480",
",",
"w",
":",
"int",
"=",
"640",
",",
"mode",
"=",
"'auto'",
")",
":",
"if",
"mode",
"==",
"'auto'",
":",
"# Assert that retinaface models have outputs... | [
6,
0
] | [
56,
16
] | python | en | ['en', 'error', 'th'] | False |
reshape_onnx_input | (onnx_path: str, out_path: str, im_size: List[int] = None, batch_size: int = 1,
mode: str = 'auto') |
Reshape ONNX file input and output for different image sizes. Only applicable for MXNet Retinaface models
and official Centerface models.
:param onnx_path: Path to input ONNX file
:param out_path: Path to output ONNX file
:param im_size: Desired output image size in W, H format. Default: [640, 480... |
Reshape ONNX file input and output for different image sizes. Only applicable for MXNet Retinaface models
and official Centerface models. | def reshape_onnx_input(onnx_path: str, out_path: str, im_size: List[int] = None, batch_size: int = 1,
mode: str = 'auto'):
'''
Reshape ONNX file input and output for different image sizes. Only applicable for MXNet Retinaface models
and official Centerface models.
:param onnx_pat... | [
"def",
"reshape_onnx_input",
"(",
"onnx_path",
":",
"str",
",",
"out_path",
":",
"str",
",",
"im_size",
":",
"List",
"[",
"int",
"]",
"=",
"None",
",",
"batch_size",
":",
"int",
"=",
"1",
",",
"mode",
":",
"str",
"=",
"'auto'",
")",
":",
"if",
"im_... | [
59,
0
] | [
80,
37
] | python | en | ['en', 'error', 'th'] | False |
AzureController.get_connection_string | (storage_account_name: str) | Get the connection string for a storage account.
Args:
storage_account_name: The storage account name.
Returns:
str: Connection string.
| Get the connection string for a storage account. | def get_connection_string(storage_account_name: str) -> str:
"""Get the connection string for a storage account.
Args:
storage_account_name: The storage account name.
Returns:
str: Connection string.
"""
command = f"az storage account show-connection-str... | [
"def",
"get_connection_string",
"(",
"storage_account_name",
":",
"str",
")",
"->",
"str",
":",
"command",
"=",
"f\"az storage account show-connection-string --name {storage_account_name}\"",
"return_str",
"=",
"Subprocess",
".",
"run",
"(",
"command",
"=",
"command",
")"... | [
216,
4
] | [
227,
57
] | python | en | ['en', 'en', 'en'] | True |
_CrossNeuronBlock.forward | (self, x) |
:param x: (bt, c, h, w)
:return:
|
:param x: (bt, c, h, w)
:return:
| def forward(self, x):
'''
:param x: (bt, c, h, w)
:return:
'''
bt, c, h, w = x.shape
residual = x
x_stretch = x.view(bt, c, h * w)
spblock_h = int(np.ceil(h / self.spatial_height))
spblock_w = int(np.ceil(w / self.spatial_width))
stride_h =... | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"bt",
",",
"c",
",",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"residual",
"=",
"x",
"x_stretch",
"=",
"x",
".",
"view",
"(",
"bt",
",",
"c",
",",
"h",
"*",
"w",
")",
"spblock_h",
"=",
"int",
... | [
54,
4
] | [
114,
57
] | python | en | ['en', 'error', 'th'] | False |
test_removing_while_delay_in_progress | (tmpdir) | Test removing while delay in progress. | Test removing while delay in progress. | async def test_removing_while_delay_in_progress(tmpdir):
"""Test removing while delay in progress."""
loop = asyncio.get_event_loop()
hass = await async_test_home_assistant(loop)
test_dir = await hass.async_add_executor_job(tmpdir.mkdir, "storage")
with patch.object(storage, "STORAGE_DIR", test_d... | [
"async",
"def",
"test_removing_while_delay_in_progress",
"(",
"tmpdir",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"hass",
"=",
"await",
"async_test_home_assistant",
"(",
"loop",
")",
"test_dir",
"=",
"await",
"hass",
".",
"async_add_execut... | [
12,
0
] | [
35,
31
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the utility meter sensor. | Set up the utility meter sensor. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the utility meter sensor."""
if discovery_info is None:
_LOGGER.error("This platform is only available through discovery")
return
meters = []
for conf in discovery_info:
meter = conf... | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"This platform is only available through discovery\"... | [
62,
0
] | [
101,
5
] | python | en | ['en', 'da', 'en'] | True |
UtilityMeterSensor.__init__ | (
self,
source_entity,
name,
meter_type,
meter_offset,
net_consumption,
tariff=None,
tariff_entity=None,
) | Initialize the Utility Meter sensor. | Initialize the Utility Meter sensor. | def __init__(
self,
source_entity,
name,
meter_type,
meter_offset,
net_consumption,
tariff=None,
tariff_entity=None,
):
"""Initialize the Utility Meter sensor."""
self._sensor_source_id = source_entity
self._state = 0
se... | [
"def",
"__init__",
"(",
"self",
",",
"source_entity",
",",
"name",
",",
"meter_type",
",",
"meter_offset",
",",
"net_consumption",
",",
"tariff",
"=",
"None",
",",
"tariff_entity",
"=",
"None",
",",
")",
":",
"self",
".",
"_sensor_source_id",
"=",
"source_en... | [
107,
4
] | [
132,
43
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.async_reading | (self, event) | Handle the sensor state changes. | Handle the sensor state changes. | def async_reading(self, event):
"""Handle the sensor state changes."""
old_state = event.data.get("old_state")
new_state = event.data.get("new_state")
if (
old_state is None
or new_state is None
or old_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
... | [
"def",
"async_reading",
"(",
"self",
",",
"event",
")",
":",
"old_state",
"=",
"event",
".",
"data",
".",
"get",
"(",
"\"old_state\"",
")",
"new_state",
"=",
"event",
".",
"data",
".",
"get",
"(",
"\"new_state\"",
")",
"if",
"(",
"old_state",
"is",
"No... | [
135,
4
] | [
169,
35
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.async_tariff_change | (self, event) | Handle tariff changes. | Handle tariff changes. | def async_tariff_change(self, event):
"""Handle tariff changes."""
new_state = event.data.get("new_state")
if new_state is None:
return
if self._tariff == new_state.state:
self._collecting = async_track_state_change_event(
self.hass, [self._sensor_... | [
"def",
"async_tariff_change",
"(",
"self",
",",
"event",
")",
":",
"new_state",
"=",
"event",
".",
"data",
".",
"get",
"(",
"\"new_state\"",
")",
"if",
"new_state",
"is",
"None",
":",
"return",
"if",
"self",
".",
"_tariff",
"==",
"new_state",
".",
"state... | [
172,
4
] | [
193,
35
] | python | en | ['en', 'xh', 'en'] | True |
UtilityMeterSensor._async_reset_meter | (self, event) | Determine cycle - Helper function for larger than daily cycles. | Determine cycle - Helper function for larger than daily cycles. | async def _async_reset_meter(self, event):
"""Determine cycle - Helper function for larger than daily cycles."""
now = dt_util.now().date()
if (
self._period == WEEKLY
and now != now - timedelta(days=now.weekday()) + self._period_offset
):
return
... | [
"async",
"def",
"_async_reset_meter",
"(",
"self",
",",
"event",
")",
":",
"now",
"=",
"dt_util",
".",
"now",
"(",
")",
".",
"date",
"(",
")",
"if",
"(",
"self",
".",
"_period",
"==",
"WEEKLY",
"and",
"now",
"!=",
"now",
"-",
"timedelta",
"(",
"day... | [
195,
4
] | [
222,
57
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.async_reset_meter | (self, entity_id) | Reset meter. | Reset meter. | async def async_reset_meter(self, entity_id):
"""Reset meter."""
if self._tariff_entity != entity_id:
return
_LOGGER.debug("Reset utility meter <%s>", self.entity_id)
self._last_reset = dt_util.now()
self._last_period = str(self._state)
self._state = 0
... | [
"async",
"def",
"async_reset_meter",
"(",
"self",
",",
"entity_id",
")",
":",
"if",
"self",
".",
"_tariff_entity",
"!=",
"entity_id",
":",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Reset utility meter <%s>\"",
",",
"self",
".",
"entity_id",
")",
"self",
".",
... | [
224,
4
] | [
232,
35
] | python | de | ['de', 'nl', 'en'] | False |
UtilityMeterSensor.async_calibrate | (self, value) | Calibrate the Utility Meter with a given value. | Calibrate the Utility Meter with a given value. | async def async_calibrate(self, value):
"""Calibrate the Utility Meter with a given value."""
_LOGGER.debug("Calibrate %s = %s", self._name, value)
self._state = value
self.async_write_ha_state() | [
"async",
"def",
"async_calibrate",
"(",
"self",
",",
"value",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Calibrate %s = %s\"",
",",
"self",
".",
"_name",
",",
"value",
")",
"self",
".",
"_state",
"=",
"value",
"self",
".",
"async_write_ha_state",
"(",
")"
... | [
234,
4
] | [
238,
35
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.async_added_to_hass | (self) | Handle entity which will be added. | Handle entity which will be added. | async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
if self._period == QUARTER_HOURLY:
for quarter in range(4):
async_track_time_change(
self.hass,
self._async_reset... | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")",
"if",
"self",
".",
"_period",
"==",
"QUARTER_HOURLY",
":",
"for",
"quarter",
"in",
"range",
"(",
"4",
")",
":",
"async_track_tim... | [
240,
4
] | [
304,
9
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.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"
] | [
307,
4
] | [
309,
25
] | python | en | ['en', 'mi', 'en'] | True |
UtilityMeterSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
312,
4
] | [
314,
26
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.unit_of_measurement | (self) | Return the unit the value is expressed in. | Return the unit the value is expressed in. | def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
317,
4
] | [
319,
40
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.should_poll | (self) | No polling needed. | No polling needed. | def should_poll(self):
"""No polling needed."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
322,
4
] | [
324,
20
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.device_state_attributes | (self) | Return the state attributes of the sensor. | Return the state attributes of the sensor. | def device_state_attributes(self):
"""Return the state attributes of the sensor."""
state_attr = {
ATTR_SOURCE_ID: self._sensor_source_id,
ATTR_STATUS: PAUSED if self._collecting is None else COLLECTING,
ATTR_LAST_PERIOD: self._last_period,
ATTR_LAST_RESET... | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"state_attr",
"=",
"{",
"ATTR_SOURCE_ID",
":",
"self",
".",
"_sensor_source_id",
",",
"ATTR_STATUS",
":",
"PAUSED",
"if",
"self",
".",
"_collecting",
"is",
"None",
"else",
"COLLECTING",
",",
"ATTR_LAST_PER... | [
327,
4
] | [
339,
25
] | python | en | ['en', 'en', 'en'] | True |
UtilityMeterSensor.icon | (self) | Return the icon to use in the frontend, if any. | Return the icon to use in the frontend, if any. | def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"ICON"
] | [
342,
4
] | [
344,
19
] | python | en | ['en', 'en', 'en'] | True |
find_pruneable_heads_and_indices | (
heads: List[int], n_heads: int, head_size: int, already_pruned_heads: Set[int]
) |
Finds the heads and their indices taking :obj:`already_pruned_heads` into account.
Args:
heads (:obj:`List[int]`): List of the indices of heads to prune.
n_heads (:obj:`int`): The number of heads in the model.
head_size (:obj:`int`): The size of each head.
already_pruned_heads ... |
Finds the heads and their indices taking :obj:`already_pruned_heads` into account. | def find_pruneable_heads_and_indices(
heads: List[int], n_heads: int, head_size: int, already_pruned_heads: Set[int]
) -> Tuple[Set[int], torch.LongTensor]:
"""
Finds the heads and their indices taking :obj:`already_pruned_heads` into account.
Args:
heads (:obj:`List[int]`): List of the indices... | [
"def",
"find_pruneable_heads_and_indices",
"(",
"heads",
":",
"List",
"[",
"int",
"]",
",",
"n_heads",
":",
"int",
",",
"head_size",
":",
"int",
",",
"already_pruned_heads",
":",
"Set",
"[",
"int",
"]",
")",
"->",
"Tuple",
"[",
"Set",
"[",
"int",
"]",
... | [
62,
0
] | [
85,
23
] | python | en | ['en', 'error', 'th'] | False |
unwrap_model | (model: torch.nn.Module) |
Recursively unwraps a model from potential containers (as used in distributed training).
Args:
model (:obj:`torch.nn.Module`): The model to unwrap.
|
Recursively unwraps a model from potential containers (as used in distributed training). | def unwrap_model(model: torch.nn.Module) -> torch.nn.Module:
"""
Recursively unwraps a model from potential containers (as used in distributed training).
Args:
model (:obj:`torch.nn.Module`): The model to unwrap.
"""
# since there could be multiple levels of wrapping, unwrap recursively
... | [
"def",
"unwrap_model",
"(",
"model",
":",
"torch",
".",
"nn",
".",
"Module",
")",
"->",
"torch",
".",
"nn",
".",
"Module",
":",
"# since there could be multiple levels of wrapping, unwrap recursively",
"if",
"hasattr",
"(",
"model",
",",
"\"module\"",
")",
":",
... | [
1646,
0
] | [
1657,
20
] | python | en | ['en', 'error', 'th'] | False |
prune_linear_layer | (layer: torch.nn.Linear, index: torch.LongTensor, dim: int = 0) |
Prune a linear layer to keep only entries in index.
Used to remove heads.
Args:
layer (:obj:`torch.nn.Linear`): The layer to prune.
index (:obj:`torch.LongTensor`): The indices to keep in the layer.
dim (:obj:`int`, `optional`, defaults to 0): The dimension on which to keep the in... |
Prune a linear layer to keep only entries in index. | def prune_linear_layer(layer: torch.nn.Linear, index: torch.LongTensor, dim: int = 0) -> torch.nn.Linear:
"""
Prune a linear layer to keep only entries in index.
Used to remove heads.
Args:
layer (:obj:`torch.nn.Linear`): The layer to prune.
index (:obj:`torch.LongTensor`): The indices... | [
"def",
"prune_linear_layer",
"(",
"layer",
":",
"torch",
".",
"nn",
".",
"Linear",
",",
"index",
":",
"torch",
".",
"LongTensor",
",",
"dim",
":",
"int",
"=",
"0",
")",
"->",
"torch",
".",
"nn",
".",
"Linear",
":",
"index",
"=",
"index",
".",
"to",... | [
1660,
0
] | [
1691,
20
] | python | en | ['en', 'error', 'th'] | False |
prune_conv1d_layer | (layer: Conv1D, index: torch.LongTensor, dim: int = 1) |
Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights
are transposed.
Used to remove heads.
Args:
layer (:class:`~transformers.modeling_utils.Conv1D`): The layer to prune.
index (:obj:`torch.LongTensor`): The indices to kee... |
Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights
are transposed. | def prune_conv1d_layer(layer: Conv1D, index: torch.LongTensor, dim: int = 1) -> Conv1D:
"""
Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights
are transposed.
Used to remove heads.
Args:
layer (:class:`~transformers.modeling_... | [
"def",
"prune_conv1d_layer",
"(",
"layer",
":",
"Conv1D",
",",
"index",
":",
"torch",
".",
"LongTensor",
",",
"dim",
":",
"int",
"=",
"1",
")",
"->",
"Conv1D",
":",
"index",
"=",
"index",
".",
"to",
"(",
"layer",
".",
"weight",
".",
"device",
")",
... | [
1694,
0
] | [
1724,
20
] | python | en | ['en', 'error', 'th'] | False |
prune_layer | (
layer: Union[torch.nn.Linear, Conv1D], index: torch.LongTensor, dim: Optional[int] = None
) |
Prune a Conv1D or linear layer to keep only entries in index.
Used to remove heads.
Args:
layer (:obj:`Union[torch.nn.Linear, Conv1D]`): The layer to prune.
index (:obj:`torch.LongTensor`): The indices to keep in the layer.
dim (:obj:`int`, `optional`): The dimension on which to k... |
Prune a Conv1D or linear layer to keep only entries in index. | def prune_layer(
layer: Union[torch.nn.Linear, Conv1D], index: torch.LongTensor, dim: Optional[int] = None
) -> Union[torch.nn.Linear, Conv1D]:
"""
Prune a Conv1D or linear layer to keep only entries in index.
Used to remove heads.
Args:
layer (:obj:`Union[torch.nn.Linear, Conv1D]`): The l... | [
"def",
"prune_layer",
"(",
"layer",
":",
"Union",
"[",
"torch",
".",
"nn",
".",
"Linear",
",",
"Conv1D",
"]",
",",
"index",
":",
"torch",
".",
"LongTensor",
",",
"dim",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"Union",
"[",
"torch"... | [
1727,
0
] | [
1749,
81
] | python | en | ['en', 'error', 'th'] | False |
apply_chunking_to_forward | (
forward_fn: Callable[..., torch.Tensor], chunk_size: int, chunk_dim: int, *input_tensors
) |
This function chunks the :obj:`input_tensors` into smaller input tensor parts of size :obj:`chunk_size` over the
dimension :obj:`chunk_dim`. It then applies a layer :obj:`forward_fn` to each chunk independently to save memory.
If the :obj:`forward_fn` is independent across the :obj:`chunk_dim` this functi... |
This function chunks the :obj:`input_tensors` into smaller input tensor parts of size :obj:`chunk_size` over the
dimension :obj:`chunk_dim`. It then applies a layer :obj:`forward_fn` to each chunk independently to save memory. | def apply_chunking_to_forward(
forward_fn: Callable[..., torch.Tensor], chunk_size: int, chunk_dim: int, *input_tensors
) -> torch.Tensor:
"""
This function chunks the :obj:`input_tensors` into smaller input tensor parts of size :obj:`chunk_size` over the
dimension :obj:`chunk_dim`. It then applies a la... | [
"def",
"apply_chunking_to_forward",
"(",
"forward_fn",
":",
"Callable",
"[",
"...",
",",
"torch",
".",
"Tensor",
"]",
",",
"chunk_size",
":",
"int",
",",
"chunk_dim",
":",
"int",
",",
"*",
"input_tensors",
")",
"->",
"torch",
".",
"Tensor",
":",
"assert",
... | [
1752,
0
] | [
1818,
37
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin.add_memory_hooks | (self) |
Add a memory hook before and after each sub-module forward pass to record increase in memory consumption.
Increase in memory consumption is stored in a :obj:`mem_rss_diff` attribute for each module and can be reset to
zero with :obj:`model.reset_memory_hooks_state()`.
|
Add a memory hook before and after each sub-module forward pass to record increase in memory consumption. | def add_memory_hooks(self):
"""
Add a memory hook before and after each sub-module forward pass to record increase in memory consumption.
Increase in memory consumption is stored in a :obj:`mem_rss_diff` attribute for each module and can be reset to
zero with :obj:`model.reset_memory_ho... | [
"def",
"add_memory_hooks",
"(",
"self",
")",
":",
"for",
"module",
"in",
"self",
".",
"modules",
"(",
")",
":",
"module",
".",
"register_forward_pre_hook",
"(",
"self",
".",
"_hook_rss_memory_pre_forward",
")",
"module",
".",
"register_forward_hook",
"(",
"self"... | [
149,
4
] | [
159,
39
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin.reset_memory_hooks_state | (self) |
Reset the :obj:`mem_rss_diff` attribute of each module (see
:func:`~transformers.modeling_utils.ModuleUtilsMixin.add_memory_hooks`).
|
Reset the :obj:`mem_rss_diff` attribute of each module (see
:func:`~transformers.modeling_utils.ModuleUtilsMixin.add_memory_hooks`).
| def reset_memory_hooks_state(self):
"""
Reset the :obj:`mem_rss_diff` attribute of each module (see
:func:`~transformers.modeling_utils.ModuleUtilsMixin.add_memory_hooks`).
"""
for module in self.modules():
module.mem_rss_diff = 0
module.mem_rss_post_forwa... | [
"def",
"reset_memory_hooks_state",
"(",
"self",
")",
":",
"for",
"module",
"in",
"self",
".",
"modules",
"(",
")",
":",
"module",
".",
"mem_rss_diff",
"=",
"0",
"module",
".",
"mem_rss_post_forward",
"=",
"0",
"module",
".",
"mem_rss_pre_forward",
"=",
"0"
] | [
161,
4
] | [
169,
42
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin.device | (self) |
:obj:`torch.device`: The device on which the module is (assuming that all the module parameters are on the same
device).
|
:obj:`torch.device`: The device on which the module is (assuming that all the module parameters are on the same
device).
| def device(self) -> device:
"""
:obj:`torch.device`: The device on which the module is (assuming that all the module parameters are on the same
device).
"""
return get_parameter_device(self) | [
"def",
"device",
"(",
"self",
")",
"->",
"device",
":",
"return",
"get_parameter_device",
"(",
"self",
")"
] | [
172,
4
] | [
177,
41
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin.dtype | (self) |
:obj:`torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
|
:obj:`torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
| def dtype(self) -> dtype:
"""
:obj:`torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
"""
return get_parameter_dtype(self) | [
"def",
"dtype",
"(",
"self",
")",
"->",
"dtype",
":",
"return",
"get_parameter_dtype",
"(",
"self",
")"
] | [
180,
4
] | [
184,
40
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin.invert_attention_mask | (self, encoder_attention_mask: Tensor) |
Invert an attention mask (e.g., switches 0. and 1.).
Args:
encoder_attention_mask (:obj:`torch.Tensor`): An attention mask.
Returns:
:obj:`torch.Tensor`: The inverted attention mask.
|
Invert an attention mask (e.g., switches 0. and 1.). | def invert_attention_mask(self, encoder_attention_mask: Tensor) -> Tensor:
"""
Invert an attention mask (e.g., switches 0. and 1.).
Args:
encoder_attention_mask (:obj:`torch.Tensor`): An attention mask.
Returns:
:obj:`torch.Tensor`: The inverted attention mask.
... | [
"def",
"invert_attention_mask",
"(",
"self",
",",
"encoder_attention_mask",
":",
"Tensor",
")",
"->",
"Tensor",
":",
"if",
"encoder_attention_mask",
".",
"dim",
"(",
")",
"==",
"3",
":",
"encoder_extended_attention_mask",
"=",
"encoder_attention_mask",
"[",
":",
"... | [
186,
4
] | [
218,
46
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin.get_extended_attention_mask | (self, attention_mask: Tensor, input_shape: Tuple[int], device: device) |
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
Arguments:
attention_mask (:obj:`torch.Tensor`):
Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
input_shape (:obj:`Tuple[int]`):
... |
Makes broadcastable attention and causal masks so that future and masked tokens are ignored. | def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device) -> Tensor:
"""
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
Arguments:
attention_mask (:obj:`torch.Tensor`):
Mask wi... | [
"def",
"get_extended_attention_mask",
"(",
"self",
",",
"attention_mask",
":",
"Tensor",
",",
"input_shape",
":",
"Tuple",
"[",
"int",
"]",
",",
"device",
":",
"device",
")",
"->",
"Tensor",
":",
"# We can provide a self-attention mask of dimensions [batch_size, from_se... | [
220,
4
] | [
280,
38
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin.get_head_mask | (
self, head_mask: Optional[Tensor], num_hidden_layers: int, is_attention_chunked: bool = False
) |
Prepare the head mask if needed.
Args:
head_mask (:obj:`torch.Tensor` with shape :obj:`[num_heads]` or :obj:`[num_hidden_layers x num_heads]`, `optional`):
The mask indicating if we should keep the heads or not (1.0 for keep, 0.0 for discard).
num_hidden_layers ... |
Prepare the head mask if needed. | def get_head_mask(
self, head_mask: Optional[Tensor], num_hidden_layers: int, is_attention_chunked: bool = False
) -> Tensor:
"""
Prepare the head mask if needed.
Args:
head_mask (:obj:`torch.Tensor` with shape :obj:`[num_heads]` or :obj:`[num_hidden_layers x num_heads]`... | [
"def",
"get_head_mask",
"(",
"self",
",",
"head_mask",
":",
"Optional",
"[",
"Tensor",
"]",
",",
"num_hidden_layers",
":",
"int",
",",
"is_attention_chunked",
":",
"bool",
"=",
"False",
")",
"->",
"Tensor",
":",
"if",
"head_mask",
"is",
"not",
"None",
":",... | [
282,
4
] | [
307,
24
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin._convert_head_mask_to_5d | (self, head_mask, num_hidden_layers) | -> [num_hidden_layers x batch x num_heads x seq_length x seq_length] | -> [num_hidden_layers x batch x num_heads x seq_length x seq_length] | def _convert_head_mask_to_5d(self, head_mask, num_hidden_layers):
"""-> [num_hidden_layers x batch x num_heads x seq_length x seq_length]"""
if head_mask.dim() == 1:
head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
head_mask = head_mask.expand(num_hidde... | [
"def",
"_convert_head_mask_to_5d",
"(",
"self",
",",
"head_mask",
",",
"num_hidden_layers",
")",
":",
"if",
"head_mask",
".",
"dim",
"(",
")",
"==",
"1",
":",
"head_mask",
"=",
"head_mask",
".",
"unsqueeze",
"(",
"0",
")",
".",
"unsqueeze",
"(",
"0",
")"... | [
309,
4
] | [
318,
24
] | python | en | ['en', 'lb', 'sw'] | False |
ModuleUtilsMixin.num_parameters | (self, only_trainable: bool = False, exclude_embeddings: bool = False) |
Get number of (optionally, trainable or non-embeddings) parameters in the module.
Args:
only_trainable (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or not to return only the number of trainable parameters
exclude_embeddings (:obj:`bool`, `option... |
Get number of (optionally, trainable or non-embeddings) parameters in the module. | def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int:
"""
Get number of (optionally, trainable or non-embeddings) parameters in the module.
Args:
only_trainable (:obj:`bool`, `optional`, defaults to :obj:`False`):
Whether or... | [
"def",
"num_parameters",
"(",
"self",
",",
"only_trainable",
":",
"bool",
"=",
"False",
",",
"exclude_embeddings",
":",
"bool",
"=",
"False",
")",
"->",
"int",
":",
"def",
"parameter_filter",
"(",
"x",
")",
":",
"return",
"(",
"x",
".",
"requires_grad",
... | [
320,
4
] | [
341,
45
] | python | en | ['en', 'error', 'th'] | False |
ModuleUtilsMixin.estimate_tokens | (self, input_dict: Dict[str, Union[torch.Tensor, Any]]) |
Helper function to estimate the total number of tokens from the model inputs.
Args:
inputs (:obj:`dict`): The model inputs.
Returns:
:obj:`int`: The total number of tokens.
|
Helper function to estimate the total number of tokens from the model inputs. | def estimate_tokens(self, input_dict: Dict[str, Union[torch.Tensor, Any]]) -> int:
"""
Helper function to estimate the total number of tokens from the model inputs.
Args:
inputs (:obj:`dict`): The model inputs.
Returns:
:obj:`int`: The total number of tokens.
... | [
"def",
"estimate_tokens",
"(",
"self",
",",
"input_dict",
":",
"Dict",
"[",
"str",
",",
"Union",
"[",
"torch",
".",
"Tensor",
",",
"Any",
"]",
"]",
")",
"->",
"int",
":",
"token_inputs",
"=",
"[",
"tensor",
"for",
"key",
",",
"tensor",
"in",
"input_d... | [
343,
4
] | [
360,
20
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.