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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ZwaveLight.on_value_update | (self) | Call when the underlying value(s) is added or updated. | Call when the underlying value(s) is added or updated. | def on_value_update(self):
"""Call when the underlying value(s) is added or updated."""
if self.values.dimming_duration is not None:
self._supported_features |= SUPPORT_TRANSITION
if self.values.color is not None:
self._supported_features |= SUPPORT_COLOR
if sel... | [
"def",
"on_value_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"values",
".",
"dimming_duration",
"is",
"not",
"None",
":",
"self",
".",
"_supported_features",
"|=",
"SUPPORT_TRANSITION",
"if",
"self",
".",
"values",
".",
"color",
"is",
"not",
"None",
... | [
77,
4
] | [
99,
42
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight.brightness | (self) | Return the brightness of this light between 0..255.
Zwave multilevel switches use a range of [0, 99] to control brightness.
| Return the brightness of this light between 0..255. | def brightness(self):
"""Return the brightness of this light between 0..255.
Zwave multilevel switches use a range of [0, 99] to control brightness.
"""
if "target" in self.values:
return round((self.values.target.value / 99) * 255)
return round((self.values.primary.... | [
"def",
"brightness",
"(",
"self",
")",
":",
"if",
"\"target\"",
"in",
"self",
".",
"values",
":",
"return",
"round",
"(",
"(",
"self",
".",
"values",
".",
"target",
".",
"value",
"/",
"99",
")",
"*",
"255",
")",
"return",
"round",
"(",
"(",
"self",... | [
102,
4
] | [
109,
60
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight.is_on | (self) | Return true if device is on (brightness above 0). | Return true if device is on (brightness above 0). | def is_on(self):
"""Return true if device is on (brightness above 0)."""
if "target" in self.values:
return self.values.target.value > 0
return self.values.primary.value > 0 | [
"def",
"is_on",
"(",
"self",
")",
":",
"if",
"\"target\"",
"in",
"self",
".",
"values",
":",
"return",
"self",
".",
"values",
".",
"target",
".",
"value",
">",
"0",
"return",
"self",
".",
"values",
".",
"primary",
".",
"value",
">",
"0"
] | [
112,
4
] | [
116,
44
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight.supported_features | (self) | Flag supported features. | Flag supported features. | def supported_features(self):
"""Flag supported features."""
return self._supported_features | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"self",
".",
"_supported_features"
] | [
119,
4
] | [
121,
39
] | python | en | ['da', 'en', 'en'] | True |
ZwaveLight.hs_color | (self) | Return the hs color. | Return the hs color. | def hs_color(self):
"""Return the hs color."""
return self._hs | [
"def",
"hs_color",
"(",
"self",
")",
":",
"return",
"self",
".",
"_hs"
] | [
124,
4
] | [
126,
23
] | python | en | ['en', 'fr', 'en'] | True |
ZwaveLight.white_value | (self) | Return the white value of this light between 0..255. | Return the white value of this light between 0..255. | def white_value(self):
"""Return the white value of this light between 0..255."""
return self._white | [
"def",
"white_value",
"(",
"self",
")",
":",
"return",
"self",
".",
"_white"
] | [
129,
4
] | [
131,
26
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight.color_temp | (self) | Return the color temperature. | Return the color temperature. | def color_temp(self):
"""Return the color temperature."""
return self._ct | [
"def",
"color_temp",
"(",
"self",
")",
":",
"return",
"self",
".",
"_ct"
] | [
134,
4
] | [
136,
23
] | python | en | ['en', 'la', 'en'] | True |
ZwaveLight.min_mireds | (self) | Return the coldest color_temp that this light supports. | Return the coldest color_temp that this light supports. | def min_mireds(self):
"""Return the coldest color_temp that this light supports."""
return self._min_mireds | [
"def",
"min_mireds",
"(",
"self",
")",
":",
"return",
"self",
".",
"_min_mireds"
] | [
139,
4
] | [
141,
31
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight.max_mireds | (self) | Return the warmest color_temp that this light supports. | Return the warmest color_temp that this light supports. | def max_mireds(self):
"""Return the warmest color_temp that this light supports."""
return self._max_mireds | [
"def",
"max_mireds",
"(",
"self",
")",
":",
"return",
"self",
".",
"_max_mireds"
] | [
144,
4
] | [
146,
31
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight.async_set_duration | (self, **kwargs) | Set the transition time for the brightness value.
Zwave Dimming Duration values now use seconds as an
integer (max: 7620 seconds or 127 mins)
Build 1205 https://github.com/OpenZWave/open-zwave/commit/f81bc04
| Set the transition time for the brightness value. | def async_set_duration(self, **kwargs):
"""Set the transition time for the brightness value.
Zwave Dimming Duration values now use seconds as an
integer (max: 7620 seconds or 127 mins)
Build 1205 https://github.com/OpenZWave/open-zwave/commit/f81bc04
"""
if self.values.d... | [
"def",
"async_set_duration",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"values",
".",
"dimming_duration",
"is",
"None",
":",
"return",
"ozw_version",
"=",
"tuple",
"(",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"va... | [
149,
4
] | [
191,
62
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight.async_turn_on | (self, **kwargs) | Turn the device on. | Turn the device on. | async def async_turn_on(self, **kwargs):
"""Turn the device on."""
self.async_set_duration(**kwargs)
rgbw = None
white = kwargs.get(ATTR_WHITE_VALUE)
hs_color = kwargs.get(ATTR_HS_COLOR)
color_temp = kwargs.get(ATTR_COLOR_TEMP)
if hs_color is not None:
... | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"async_set_duration",
"(",
"*",
"*",
"kwargs",
")",
"rgbw",
"=",
"None",
"white",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_WHITE_VALUE",
")",
"hs_color",
"=",
"k... | [
193,
4
] | [
247,
50
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight.async_turn_off | (self, **kwargs) | Turn the device off. | Turn the device off. | async def async_turn_off(self, **kwargs):
"""Turn the device off."""
self.async_set_duration(**kwargs)
self.values.primary.send_value(0) | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"async_set_duration",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"values",
".",
"primary",
".",
"send_value",
"(",
"0",
")"
] | [
249,
4
] | [
253,
41
] | python | en | ['en', 'en', 'en'] | True |
ZwaveLight._calculate_color_values | (self) | Parse color rgb and color temperature data. | Parse color rgb and color temperature data. | def _calculate_color_values(self):
"""Parse color rgb and color temperature data."""
# Color Data String
data = self.values.color.data[ATTR_VALUE]
# RGB is always present in the OpenZWave color data string.
rgb = [int(data[1:3], 16), int(data[3:5], 16), int(data[5:7], 16)]
... | [
"def",
"_calculate_color_values",
"(",
"self",
")",
":",
"# Color Data String",
"data",
"=",
"self",
".",
"values",
".",
"color",
".",
"data",
"[",
"ATTR_VALUE",
"]",
"# RGB is always present in the OpenZWave color data string.",
"rgb",
"=",
"[",
"int",
"(",
"data",... | [
255,
4
] | [
310,
27
] | python | en | ['en', 'en', 'en'] | True |
test_get_device_detects_switch | (mock_openzwave) | Test get_device returns a Z-Wave switch. | Test get_device returns a Z-Wave switch. | def test_get_device_detects_switch(mock_openzwave):
"""Test get_device returns a Z-Wave switch."""
node = MockNode()
value = MockValue(data=0, node=node)
values = MockEntityValues(primary=value)
device = switch.get_device(node=node, values=values, node_config={})
assert isinstance(device, switc... | [
"def",
"test_get_device_detects_switch",
"(",
"mock_openzwave",
")",
":",
"node",
"=",
"MockNode",
"(",
")",
"value",
"=",
"MockValue",
"(",
"data",
"=",
"0",
",",
"node",
"=",
"node",
")",
"values",
"=",
"MockEntityValues",
"(",
"primary",
"=",
"value",
"... | [
7,
0
] | [
14,
49
] | python | en | ['en', 'pl', 'en'] | True |
test_switch_turn_on_and_off | (mock_openzwave) | Test turning on a Z-Wave switch. | Test turning on a Z-Wave switch. | def test_switch_turn_on_and_off(mock_openzwave):
"""Test turning on a Z-Wave switch."""
node = MockNode()
value = MockValue(data=0, node=node)
values = MockEntityValues(primary=value)
device = switch.get_device(node=node, values=values, node_config={})
device.turn_on()
assert node.set_swit... | [
"def",
"test_switch_turn_on_and_off",
"(",
"mock_openzwave",
")",
":",
"node",
"=",
"MockNode",
"(",
")",
"value",
"=",
"MockValue",
"(",
"data",
"=",
"0",
",",
"node",
"=",
"node",
")",
"values",
"=",
"MockEntityValues",
"(",
"primary",
"=",
"value",
")",... | [
17,
0
] | [
37,
25
] | python | en | ['en', 'en', 'en'] | True |
test_switch_value_changed | (mock_openzwave) | Test value changed for Z-Wave switch. | Test value changed for Z-Wave switch. | def test_switch_value_changed(mock_openzwave):
"""Test value changed for Z-Wave switch."""
node = MockNode()
value = MockValue(data=False, node=node)
values = MockEntityValues(primary=value)
device = switch.get_device(node=node, values=values, node_config={})
assert not device.is_on
value.... | [
"def",
"test_switch_value_changed",
"(",
"mock_openzwave",
")",
":",
"node",
"=",
"MockNode",
"(",
")",
"value",
"=",
"MockValue",
"(",
"data",
"=",
"False",
",",
"node",
"=",
"node",
")",
"values",
"=",
"MockEntityValues",
"(",
"primary",
"=",
"value",
")... | [
40,
0
] | [
52,
23
] | python | en | ['en', 'en', 'en'] | True |
test_switch_refresh_on_update | (mock_counter, mock_openzwave) | Test value changed for refresh on update Z-Wave switch. | Test value changed for refresh on update Z-Wave switch. | def test_switch_refresh_on_update(mock_counter, mock_openzwave):
"""Test value changed for refresh on update Z-Wave switch."""
mock_counter.return_value = 10
node = MockNode(manufacturer_id="013c", product_type="0001", product_id="0005")
value = MockValue(data=False, node=node, instance=1)
values = ... | [
"def",
"test_switch_refresh_on_update",
"(",
"mock_counter",
",",
"mock_openzwave",
")",
":",
"mock_counter",
".",
"return_value",
"=",
"10",
"node",
"=",
"MockNode",
"(",
"manufacturer_id",
"=",
"\"013c\"",
",",
"product_type",
"=",
"\"0001\"",
",",
"product_id",
... | [
56,
0
] | [
78,
36
] | python | en | ['en', 'en', 'en'] | True |
get_model_modules | () | Get the model modules inside the transformers library. | Get the model modules inside the transformers library. | def get_model_modules():
""" Get the model modules inside the transformers library. """
_ignore_modules = [
"modeling_auto",
"modeling_encoder_decoder",
"modeling_marian",
"modeling_mmbt",
"modeling_outputs",
"modeling_retribert",
"modeling_utils",
... | [
"def",
"get_model_modules",
"(",
")",
":",
"_ignore_modules",
"=",
"[",
"\"modeling_auto\"",
",",
"\"modeling_encoder_decoder\"",
",",
"\"modeling_marian\"",
",",
"\"modeling_mmbt\"",
",",
"\"modeling_outputs\"",
",",
"\"modeling_retribert\"",
",",
"\"modeling_utils\"",
","... | [
150,
0
] | [
179,
18
] | python | en | ['en', 'en', 'en'] | True |
get_models | (module) | Get the objects in module that are models. | Get the objects in module that are models. | def get_models(module):
""" Get the objects in module that are models."""
models = []
model_classes = (transformers.PreTrainedModel, transformers.TFPreTrainedModel)
for attr_name in dir(module):
if "Pretrained" in attr_name or "PreTrained" in attr_name:
continue
attr = getatt... | [
"def",
"get_models",
"(",
"module",
")",
":",
"models",
"=",
"[",
"]",
"model_classes",
"=",
"(",
"transformers",
".",
"PreTrainedModel",
",",
"transformers",
".",
"TFPreTrainedModel",
")",
"for",
"attr_name",
"in",
"dir",
"(",
"module",
")",
":",
"if",
"\... | [
182,
0
] | [
192,
17
] | python | en | ['en', 'en', 'en'] | True |
get_model_test_files | () | Get the model test files. | Get the model test files. | def get_model_test_files():
""" Get the model test files."""
_ignore_files = [
"test_modeling_common",
"test_modeling_encoder_decoder",
"test_modeling_marian",
"test_modeling_tf_common",
]
test_files = []
for filename in os.listdir(PATH_TO_TESTS):
if (
... | [
"def",
"get_model_test_files",
"(",
")",
":",
"_ignore_files",
"=",
"[",
"\"test_modeling_common\"",
",",
"\"test_modeling_encoder_decoder\"",
",",
"\"test_modeling_marian\"",
",",
"\"test_modeling_tf_common\"",
",",
"]",
"test_files",
"=",
"[",
"]",
"for",
"filename",
... | [
197,
0
] | [
213,
21
] | python | en | ['en', 'en', 'en'] | True |
find_tested_models | (test_file) | Parse the content of test_file to detect what's in all_model_classes | Parse the content of test_file to detect what's in all_model_classes | def find_tested_models(test_file):
""" Parse the content of test_file to detect what's in all_model_classes"""
# This is a bit hacky but I didn't find a way to import the test_file as a module and read inside the class
with open(os.path.join(PATH_TO_TESTS, test_file), "r", encoding="utf-8", newline="\n") as... | [
"def",
"find_tested_models",
"(",
"test_file",
")",
":",
"# This is a bit hacky but I didn't find a way to import the test_file as a module and read inside the class",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"PATH_TO_TESTS",
",",
"test_file",
")",
",",
"\"... | [
218,
0
] | [
233,
27
] | python | en | ['en', 'en', 'en'] | True |
check_models_are_tested | (module, test_file) | Check models defined in module are tested in test_file. | Check models defined in module are tested in test_file. | def check_models_are_tested(module, test_file):
""" Check models defined in module are tested in test_file."""
defined_models = get_models(module)
tested_models = find_tested_models(test_file)
if tested_models is None:
if test_file in TEST_FILES_WITH_NO_COMMON_TESTS:
return
r... | [
"def",
"check_models_are_tested",
"(",
"module",
",",
"test_file",
")",
":",
"defined_models",
"=",
"get_models",
"(",
"module",
")",
"tested_models",
"=",
"find_tested_models",
"(",
"test_file",
")",
"if",
"tested_models",
"is",
"None",
":",
"if",
"test_file",
... | [
236,
0
] | [
257,
19
] | python | en | ['en', 'en', 'en'] | True |
check_all_models_are_tested | () | Check all models are properly tested. | Check all models are properly tested. | def check_all_models_are_tested():
""" Check all models are properly tested."""
modules = get_model_modules()
test_files = get_model_test_files()
failures = []
for module in modules:
test_file = f"test_{module.__name__.split('.')[-1]}.py"
if test_file not in test_files:
f... | [
"def",
"check_all_models_are_tested",
"(",
")",
":",
"modules",
"=",
"get_model_modules",
"(",
")",
"test_files",
"=",
"get_model_test_files",
"(",
")",
"failures",
"=",
"[",
"]",
"for",
"module",
"in",
"modules",
":",
"test_file",
"=",
"f\"test_{module.__name__.s... | [
260,
0
] | [
273,
88
] | python | en | ['en', 'en', 'en'] | True |
get_all_auto_configured_models | () | Return the list of all models in at least one auto class. | Return the list of all models in at least one auto class. | def get_all_auto_configured_models():
""" Return the list of all models in at least one auto class."""
result = set() # To avoid duplicates we concatenate all model classes in a set.
for attr_name in dir(transformers.models.auto.modeling_auto):
if attr_name.startswith("MODEL_") and attr_name.endswi... | [
"def",
"get_all_auto_configured_models",
"(",
")",
":",
"result",
"=",
"set",
"(",
")",
"# To avoid duplicates we concatenate all model classes in a set.",
"for",
"attr_name",
"in",
"dir",
"(",
"transformers",
".",
"models",
".",
"auto",
".",
"modeling_auto",
")",
":"... | [
276,
0
] | [
285,
43
] | python | en | ['en', 'en', 'en'] | True |
check_models_are_auto_configured | (module, all_auto_models) | Check models defined in module are each in an auto class. | Check models defined in module are each in an auto class. | def check_models_are_auto_configured(module, all_auto_models):
""" Check models defined in module are each in an auto class."""
defined_models = get_models(module)
failures = []
for model_name, _ in defined_models:
if model_name not in all_auto_models and model_name not in IGNORE_NON_AUTO_CONFIG... | [
"def",
"check_models_are_auto_configured",
"(",
"module",
",",
"all_auto_models",
")",
":",
"defined_models",
"=",
"get_models",
"(",
"module",
")",
"failures",
"=",
"[",
"]",
"for",
"model_name",
",",
"_",
"in",
"defined_models",
":",
"if",
"model_name",
"not",... | [
288,
0
] | [
299,
19
] | python | en | ['en', 'en', 'en'] | True |
check_all_models_are_auto_configured | () | Check all models are each in an auto class. | Check all models are each in an auto class. | def check_all_models_are_auto_configured():
""" Check all models are each in an auto class."""
modules = get_model_modules()
all_auto_models = get_all_auto_configured_models()
failures = []
for module in modules:
new_failures = check_models_are_auto_configured(module, all_auto_models)
... | [
"def",
"check_all_models_are_auto_configured",
"(",
")",
":",
"modules",
"=",
"get_model_modules",
"(",
")",
"all_auto_models",
"=",
"get_all_auto_configured_models",
"(",
")",
"failures",
"=",
"[",
"]",
"for",
"module",
"in",
"modules",
":",
"new_failures",
"=",
... | [
302,
0
] | [
312,
88
] | python | en | ['en', 'en', 'en'] | True |
check_decorator_order | (filename) | Check that in the test file `filename` the slow decorator is always last. | Check that in the test file `filename` the slow decorator is always last. | def check_decorator_order(filename):
""" Check that in the test file `filename` the slow decorator is always last."""
with open(filename, "r", encoding="utf-8", newline="\n") as f:
lines = f.readlines()
decorator_before = None
errors = []
for i, line in enumerate(lines):
search = _re... | [
"def",
"check_decorator_order",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"newline",
"=",
"\"\\n\"",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"decorator_be... | [
318,
0
] | [
333,
17
] | python | en | ['en', 'en', 'en'] | True |
check_all_decorator_order | () | Check that in all test files, the slow decorator is always last. | Check that in all test files, the slow decorator is always last. | def check_all_decorator_order():
""" Check that in all test files, the slow decorator is always last."""
errors = []
for fname in os.listdir(PATH_TO_TESTS):
if fname.endswith(".py"):
filename = os.path.join(PATH_TO_TESTS, fname)
new_errors = check_decorator_order(filename)
... | [
"def",
"check_all_decorator_order",
"(",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"PATH_TO_TESTS",
")",
":",
"if",
"fname",
".",
"endswith",
"(",
"\".py\"",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
... | [
336,
0
] | [
348,
9
] | python | en | ['en', 'en', 'en'] | True |
find_all_documented_objects | () | Parse the content of all doc files to detect which classes and functions it documents | Parse the content of all doc files to detect which classes and functions it documents | def find_all_documented_objects():
""" Parse the content of all doc files to detect which classes and functions it documents"""
documented_obj = []
for doc_file in Path(PATH_TO_DOC).glob("**/*.rst"):
with open(doc_file, "r", encoding="utf-8", newline="\n") as f:
content = f.read()
... | [
"def",
"find_all_documented_objects",
"(",
")",
":",
"documented_obj",
"=",
"[",
"]",
"for",
"doc_file",
"in",
"Path",
"(",
"PATH_TO_DOC",
")",
".",
"glob",
"(",
"\"**/*.rst\"",
")",
":",
"with",
"open",
"(",
"doc_file",
",",
"\"r\"",
",",
"encoding",
"=",... | [
351,
0
] | [
359,
25
] | python | en | ['en', 'en', 'en'] | True |
ignore_undocumented | (name) | Rules to determine if `name` should be undocumented. | Rules to determine if `name` should be undocumented. | def ignore_undocumented(name):
"""Rules to determine if `name` should be undocumented."""
# NOT DOCUMENTED ON PURPOSE.
# Constants uppercase are not documented.
if name.isupper():
return True
# PreTrainedModels / Encoders / Decoders / Layers / Embeddings / Attention are not documented.
i... | [
"def",
"ignore_undocumented",
"(",
"name",
")",
":",
"# NOT DOCUMENTED ON PURPOSE.",
"# Constants uppercase are not documented.",
"if",
"name",
".",
"isupper",
"(",
")",
":",
"return",
"True",
"# PreTrainedModels / Encoders / Decoders / Layers / Embeddings / Attention are not docum... | [
432,
0
] | [
472,
16
] | python | en | ['en', 'en', 'en'] | True |
check_all_objects_are_documented | () | Check all models are properly documented. | Check all models are properly documented. | def check_all_objects_are_documented():
""" Check all models are properly documented."""
documented_objs = find_all_documented_objects()
modules = transformers._modules
objects = [c for c in dir(transformers) if c not in modules and not c.startswith("_")]
undocumented_objs = [c for c in objects if c... | [
"def",
"check_all_objects_are_documented",
"(",
")",
":",
"documented_objs",
"=",
"find_all_documented_objects",
"(",
")",
"modules",
"=",
"transformers",
".",
"_modules",
"objects",
"=",
"[",
"c",
"for",
"c",
"in",
"dir",
"(",
"transformers",
")",
"if",
"c",
... | [
475,
0
] | [
485,
9
] | python | en | ['en', 'en', 'en'] | True |
check_repo_quality | () | Check all models are properly tested and documented. | Check all models are properly tested and documented. | def check_repo_quality():
""" Check all models are properly tested and documented."""
print("Checking all models are properly tested.")
check_all_decorator_order()
check_all_models_are_tested()
print("Checking all objects are properly documented.")
check_all_objects_are_documented()
print("C... | [
"def",
"check_repo_quality",
"(",
")",
":",
"print",
"(",
"\"Checking all models are properly tested.\"",
")",
"check_all_decorator_order",
"(",
")",
"check_all_models_are_tested",
"(",
")",
"print",
"(",
"\"Checking all objects are properly documented.\"",
")",
"check_all_obje... | [
488,
0
] | [
496,
42
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.async_step_user | (self, user_input=None) | Handle a flow initialized by the user. | Handle a flow initialized by the user. | async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
errors = {}
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
if user_input is not None:
try:
srp_client = S... | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"self",
".",
"_async_current_entries",
"(",
")",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"single_instance_allowe... | [
32,
4
] | [
65,
9
] | python | en | ['en', 'en', 'en'] | True |
ConfigFlow.async_step_import | (self, import_config) | Import from config. | Import from config. | async def async_step_import(self, import_config):
"""Import from config."""
# Validate config values
return await self.async_step_user(user_input=import_config) | [
"async",
"def",
"async_step_import",
"(",
"self",
",",
"import_config",
")",
":",
"# Validate config values",
"return",
"await",
"self",
".",
"async_step_user",
"(",
"user_input",
"=",
"import_config",
")"
] | [
67,
4
] | [
70,
67
] | python | en | ['en', 'en', 'en'] | True |
_whctrs | (anchor) |
Return width, height, x center, and y center for an anchor (window).
|
Return width, height, x center, and y center for an anchor (window).
| def _whctrs(anchor):
"""
Return width, height, x center, and y center for an anchor (window).
"""
w = anchor[2] - anchor[0] + 1
h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (w - 1)
y_ctr = anchor[1] + 0.5 * (h - 1)
return w, h, x_ctr, y_ctr | [
"def",
"_whctrs",
"(",
"anchor",
")",
":",
"w",
"=",
"anchor",
"[",
"2",
"]",
"-",
"anchor",
"[",
"0",
"]",
"+",
"1",
"h",
"=",
"anchor",
"[",
"3",
"]",
"-",
"anchor",
"[",
"1",
"]",
"+",
"1",
"x_ctr",
"=",
"anchor",
"[",
"0",
"]",
"+",
"... | [
16,
0
] | [
25,
29
] | python | en | ['en', 'error', 'th'] | False |
_mkanchors | (ws, hs, x_ctr, y_ctr) |
Given a vector of widths (ws) and heights (hs) around a center
(x_ctr, y_ctr), output a set of anchors (windows).
|
Given a vector of widths (ws) and heights (hs) around a center
(x_ctr, y_ctr), output a set of anchors (windows).
| def _mkanchors(ws, hs, x_ctr, y_ctr):
"""
Given a vector of widths (ws) and heights (hs) around a center
(x_ctr, y_ctr), output a set of anchors (windows).
"""
ws = ws[:, np.newaxis]
hs = hs[:, np.newaxis]
anchors = np.hstack((x_ctr - 0.5 * (ws - 1),
y_ctr - 0.5 * (... | [
"def",
"_mkanchors",
"(",
"ws",
",",
"hs",
",",
"x_ctr",
",",
"y_ctr",
")",
":",
"ws",
"=",
"ws",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"hs",
"=",
"hs",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"anchors",
"=",
"np",
".",
"hstack",
"(",
... | [
28,
0
] | [
40,
18
] | python | en | ['en', 'error', 'th'] | False |
_ratio_enum | (anchor, ratios) |
Enumerate a set of anchors for each aspect ratio wrt an anchor.
|
Enumerate a set of anchors for each aspect ratio wrt an anchor.
| def _ratio_enum(anchor, ratios):
"""
Enumerate a set of anchors for each aspect ratio wrt an anchor.
"""
w, h, x_ctr, y_ctr = _whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hs = np.round(ws * ratios)
anchors = _mkanchors(ws, hs, x_ctr, y... | [
"def",
"_ratio_enum",
"(",
"anchor",
",",
"ratios",
")",
":",
"w",
",",
"h",
",",
"x_ctr",
",",
"y_ctr",
"=",
"_whctrs",
"(",
"anchor",
")",
"size",
"=",
"w",
"*",
"h",
"size_ratios",
"=",
"size",
"/",
"ratios",
"ws",
"=",
"np",
".",
"round",
"("... | [
44,
0
] | [
55,
18
] | python | en | ['en', 'error', 'th'] | False |
_scale_enum | (anchor, scales) |
Enumerate a set of anchors for each scale wrt an anchor.
|
Enumerate a set of anchors for each scale wrt an anchor.
| def _scale_enum(anchor, scales):
"""
Enumerate a set of anchors for each scale wrt an anchor.
"""
w, h, x_ctr, y_ctr = _whctrs(anchor)
ws = w * scales
hs = h * scales
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
return anchors | [
"def",
"_scale_enum",
"(",
"anchor",
",",
"scales",
")",
":",
"w",
",",
"h",
",",
"x_ctr",
",",
"y_ctr",
"=",
"_whctrs",
"(",
"anchor",
")",
"ws",
"=",
"w",
"*",
"scales",
"hs",
"=",
"h",
"*",
"scales",
"anchors",
"=",
"_mkanchors",
"(",
"ws",
",... | [
59,
0
] | [
68,
18
] | python | en | ['en', 'error', 'th'] | False |
anchors_plane | (height, width, stride, base_anchors) |
Parameters
----------
height: height of plane
width: width of plane
stride: stride ot the original image
anchors_base: (A, 4) a base set of anchors
Returns
-------
all_anchors: (height, width, A, 4) ndarray of anchors spreading over the plane
|
Parameters
----------
height: height of plane
width: width of plane
stride: stride ot the original image
anchors_base: (A, 4) a base set of anchors
Returns
-------
all_anchors: (height, width, A, 4) ndarray of anchors spreading over the plane
| def anchors_plane(height, width, stride, base_anchors):
"""
Parameters
----------
height: height of plane
width: width of plane
stride: stride ot the original image
anchors_base: (A, 4) a base set of anchors
Returns
-------
all_anchors: (height, width, A, 4) ndarray of anchors s... | [
"def",
"anchors_plane",
"(",
"height",
",",
"width",
",",
"stride",
",",
"base_anchors",
")",
":",
"A",
"=",
"base_anchors",
".",
"shape",
"[",
"0",
"]",
"all_anchors",
"=",
"np",
".",
"zeros",
"(",
"(",
"height",
",",
"width",
",",
"A",
",",
"4",
... | [
72,
0
] | [
95,
22
] | python | en | ['en', 'error', 'th'] | False |
generate_anchors | (base_size=16, ratios=[0.5, 1, 2],
scales=2 ** np.arange(3, 6), stride=16) |
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
|
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
| def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2 ** np.arange(3, 6), stride=16):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size]) - 1
... | [
"def",
"generate_anchors",
"(",
"base_size",
"=",
"16",
",",
"ratios",
"=",
"[",
"0.5",
",",
"1",
",",
"2",
"]",
",",
"scales",
"=",
"2",
"**",
"np",
".",
"arange",
"(",
"3",
",",
"6",
")",
",",
"stride",
"=",
"16",
")",
":",
"base_anchor",
"="... | [
99,
0
] | [
110,
18
] | python | en | ['en', 'error', 'th'] | False |
generate_anchors_fpn | (cfg) |
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
|
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
| def generate_anchors_fpn(cfg):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
RPN_FEAT_STRIDE = []
for k in cfg:
RPN_FEAT_STRIDE.append(int(k))
RPN_FEAT_STRIDE = sorted(RPN_FEAT_STRIDE, reverse=True)
anchor... | [
"def",
"generate_anchors_fpn",
"(",
"cfg",
")",
":",
"RPN_FEAT_STRIDE",
"=",
"[",
"]",
"for",
"k",
"in",
"cfg",
":",
"RPN_FEAT_STRIDE",
".",
"append",
"(",
"int",
"(",
"k",
")",
")",
"RPN_FEAT_STRIDE",
"=",
"sorted",
"(",
"RPN_FEAT_STRIDE",
",",
"reverse",... | [
114,
0
] | [
135,
18
] | python | en | ['en', 'error', 'th'] | False |
clip_pad | (tensor, pad_shape) |
Clip boxes of the pad area.
:param tensor: [n, c, H, W]
:param pad_shape: [h, w]
:return: [n, c, h, w]
|
Clip boxes of the pad area.
:param tensor: [n, c, H, W]
:param pad_shape: [h, w]
:return: [n, c, h, w]
| def clip_pad(tensor, pad_shape):
"""
Clip boxes of the pad area.
:param tensor: [n, c, H, W]
:param pad_shape: [h, w]
:return: [n, c, h, w]
"""
H, W = tensor.shape[2:]
h, w = pad_shape
if h < H or w < W:
tensor = tensor[:, :, :h, :w].copy()
return tensor | [
"def",
"clip_pad",
"(",
"tensor",
",",
"pad_shape",
")",
":",
"H",
",",
"W",
"=",
"tensor",
".",
"shape",
"[",
"2",
":",
"]",
"h",
",",
"w",
"=",
"pad_shape",
"if",
"h",
"<",
"H",
"or",
"w",
"<",
"W",
":",
"tensor",
"=",
"tensor",
"[",
":",
... | [
138,
0
] | [
151,
17
] | python | en | ['en', 'error', 'th'] | False |
bbox_pred | (boxes, box_deltas) |
Transform the set of class-agnostic boxes into class-specific boxes
by applying the predicted offsets (box_deltas)
:param boxes: !important [N 4]
:param box_deltas: [N, 4 * num_classes]
:return: [N 4 * num_classes]
|
Transform the set of class-agnostic boxes into class-specific boxes
by applying the predicted offsets (box_deltas)
:param boxes: !important [N 4]
:param box_deltas: [N, 4 * num_classes]
:return: [N 4 * num_classes]
| def bbox_pred(boxes, box_deltas):
"""
Transform the set of class-agnostic boxes into class-specific boxes
by applying the predicted offsets (box_deltas)
:param boxes: !important [N 4]
:param box_deltas: [N, 4 * num_classes]
:return: [N 4 * num_classes]
"""
if boxes.shape[0] == 0:
... | [
"def",
"bbox_pred",
"(",
"boxes",
",",
"box_deltas",
")",
":",
"if",
"boxes",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"box_deltas",
".",
"shape",
"[",
"1",
"]",
")",
")",
"boxes",
"=",
"box... | [
154,
0
] | [
194,
21
] | python | en | ['en', 'error', 'th'] | False |
label_smoothed_nll_loss | (lprobs, target, epsilon, ignore_index=-100) | From fairseq | From fairseq | def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=-100):
"""From fairseq"""
if target.dim() == lprobs.dim() - 1:
target = target.unsqueeze(-1)
nll_loss = -lprobs.gather(dim=-1, index=target)
smooth_loss = -lprobs.sum(dim=-1, keepdim=True)
if ignore_index is not None:
... | [
"def",
"label_smoothed_nll_loss",
"(",
"lprobs",
",",
"target",
",",
"epsilon",
",",
"ignore_index",
"=",
"-",
"100",
")",
":",
"if",
"target",
".",
"dim",
"(",
")",
"==",
"lprobs",
".",
"dim",
"(",
")",
"-",
"1",
":",
"target",
"=",
"target",
".",
... | [
34,
0
] | [
52,
25
] | python | en | ['en', 'ja', 'en'] | False |
lmap | (f: Callable, x: Iterable) | list(map(f, x)) | list(map(f, x)) | def lmap(f: Callable, x: Iterable) -> List:
"""list(map(f, x))"""
return list(map(f, x)) | [
"def",
"lmap",
"(",
"f",
":",
"Callable",
",",
"x",
":",
"Iterable",
")",
"->",
"List",
":",
"return",
"list",
"(",
"map",
"(",
"f",
",",
"x",
")",
")"
] | [
55,
0
] | [
57,
26
] | python | en | ['en', 'mt', 'en'] | False |
calculate_bleu | (output_lns, refs_lns, **kwargs) | Uses sacrebleu's corpus_bleu implementation. | Uses sacrebleu's corpus_bleu implementation. | def calculate_bleu(output_lns, refs_lns, **kwargs) -> dict:
"""Uses sacrebleu's corpus_bleu implementation."""
return {"bleu": round(corpus_bleu(output_lns, [refs_lns], **kwargs).score, 4)} | [
"def",
"calculate_bleu",
"(",
"output_lns",
",",
"refs_lns",
",",
"*",
"*",
"kwargs",
")",
"->",
"dict",
":",
"return",
"{",
"\"bleu\"",
":",
"round",
"(",
"corpus_bleu",
"(",
"output_lns",
",",
"[",
"refs_lns",
"]",
",",
"*",
"*",
"kwargs",
")",
".",
... | [
60,
0
] | [
62,
82
] | python | en | ['fr', 'su', 'en'] | False |
trim_batch | (
input_ids,
pad_token_id,
attention_mask=None,
) | Remove columns that are populated exclusively by pad_token_id | Remove columns that are populated exclusively by pad_token_id | def trim_batch(
input_ids,
pad_token_id,
attention_mask=None,
):
"""Remove columns that are populated exclusively by pad_token_id"""
keep_column_mask = input_ids.ne(pad_token_id).any(dim=0)
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_i... | [
"def",
"trim_batch",
"(",
"input_ids",
",",
"pad_token_id",
",",
"attention_mask",
"=",
"None",
",",
")",
":",
"keep_column_mask",
"=",
"input_ids",
".",
"ne",
"(",
"pad_token_id",
")",
".",
"any",
"(",
"dim",
"=",
"0",
")",
"if",
"attention_mask",
"is",
... | [
94,
0
] | [
104,
84
] | python | en | ['en', 'en', 'en'] | True |
sortish_sampler_indices | (data: List, bs: int, shuffle=True) | Go through the text data by order of src length with a bit of randomness. From fastai repo. | Go through the text data by order of src length with a bit of randomness. From fastai repo. | def sortish_sampler_indices(data: List, bs: int, shuffle=True) -> np.array:
"Go through the text data by order of src length with a bit of randomness. From fastai repo."
if not shuffle:
return np.argsort(np.array(data) * -1)
def key_fn(i):
return data[i]
idxs = np.random.permutation(le... | [
"def",
"sortish_sampler_indices",
"(",
"data",
":",
"List",
",",
"bs",
":",
"int",
",",
"shuffle",
"=",
"True",
")",
"->",
"np",
".",
"array",
":",
"if",
"not",
"shuffle",
":",
"return",
"np",
".",
"argsort",
"(",
"np",
".",
"array",
"(",
"data",
"... | [
339,
0
] | [
357,
19
] | python | en | ['en', 'en', 'en'] | True |
use_task_specific_params | (model, task) | Update config with summarization specific params. | Update config with summarization specific params. | def use_task_specific_params(model, task):
"""Update config with summarization specific params."""
task_specific_params = model.config.task_specific_params
if task_specific_params is not None:
pars = task_specific_params.get(task, {})
logger.info(f"using task specific params for {task}: {pa... | [
"def",
"use_task_specific_params",
"(",
"model",
",",
"task",
")",
":",
"task_specific_params",
"=",
"model",
".",
"config",
".",
"task_specific_params",
"if",
"task_specific_params",
"is",
"not",
"None",
":",
"pars",
"=",
"task_specific_params",
".",
"get",
"(",
... | [
416,
0
] | [
423,
33
] | python | en | ['en', 'en', 'en'] | True |
pickle_load | (path) | pickle.load(path) | pickle.load(path) | def pickle_load(path):
"""pickle.load(path)"""
with open(path, "rb") as f:
return pickle.load(f) | [
"def",
"pickle_load",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"return",
"pickle",
".",
"load",
"(",
"f",
")"
] | [
426,
0
] | [
429,
29
] | python | en | ['en', 'en', 'en'] | False |
pickle_save | (obj, path) | pickle.dump(obj, path) | pickle.dump(obj, path) | def pickle_save(obj, path):
"""pickle.dump(obj, path)"""
with open(path, "wb") as f:
return pickle.dump(obj, f) | [
"def",
"pickle_save",
"(",
"obj",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"wb\"",
")",
"as",
"f",
":",
"return",
"pickle",
".",
"dump",
"(",
"obj",
",",
"f",
")"
] | [
432,
0
] | [
435,
34
] | python | en | ['en', 'gd', 'hi'] | False |
save_git_info | (folder_path: str) | Save git information to output_dir/git_log.json | Save git information to output_dir/git_log.json | def save_git_info(folder_path: str) -> None:
"""Save git information to output_dir/git_log.json"""
repo_infos = get_git_info()
save_json(repo_infos, os.path.join(folder_path, "git_log.json")) | [
"def",
"save_git_info",
"(",
"folder_path",
":",
"str",
")",
"->",
"None",
":",
"repo_infos",
"=",
"get_git_info",
"(",
")",
"save_json",
"(",
"repo_infos",
",",
"os",
".",
"path",
".",
"join",
"(",
"folder_path",
",",
"\"git_log.json\"",
")",
")"
] | [
442,
0
] | [
445,
68
] | python | en | ['en', 'su', 'sw'] | False |
calculate_rouge | (
pred_lns: List[str],
tgt_lns: List[str],
use_stemmer=True,
rouge_keys=ROUGE_KEYS,
return_precision_and_recall=False,
bootstrap_aggregation=True,
newline_sep=True,
) | Calculate rouge using rouge_scorer package.
Args:
pred_lns: list of summaries generated by model
tgt_lns: list of groundtruth summaries (e.g. contents of val.target)
use_stemmer: Bool indicating whether Porter stemmer should be used to
strip word suffixes to improve matching.
... | Calculate rouge using rouge_scorer package. | def calculate_rouge(
pred_lns: List[str],
tgt_lns: List[str],
use_stemmer=True,
rouge_keys=ROUGE_KEYS,
return_precision_and_recall=False,
bootstrap_aggregation=True,
newline_sep=True,
) -> Dict:
"""Calculate rouge using rouge_scorer package.
Args:
pred_lns: list of summaries... | [
"def",
"calculate_rouge",
"(",
"pred_lns",
":",
"List",
"[",
"str",
"]",
",",
"tgt_lns",
":",
"List",
"[",
"str",
"]",
",",
"use_stemmer",
"=",
"True",
",",
"rouge_keys",
"=",
"ROUGE_KEYS",
",",
"return_precision_and_recall",
"=",
"False",
",",
"bootstrap_ag... | [
488,
0
] | [
533,
33
] | python | en | ['da', 'en', 'en'] | True |
freeze_params | (model: nn.Module) | Set requires_grad=False for each of model.parameters() | Set requires_grad=False for each of model.parameters() | def freeze_params(model: nn.Module):
"""Set requires_grad=False for each of model.parameters()"""
for par in model.parameters():
par.requires_grad = False | [
"def",
"freeze_params",
"(",
"model",
":",
"nn",
".",
"Module",
")",
":",
"for",
"par",
"in",
"model",
".",
"parameters",
"(",
")",
":",
"par",
".",
"requires_grad",
"=",
"False"
] | [
539,
0
] | [
542,
33
] | python | en | ['en', 'en', 'en'] | True |
freeze_embeds | (model) | Freeze token embeddings and positional embeddings for bart, just token embeddings for t5. | Freeze token embeddings and positional embeddings for bart, just token embeddings for t5. | def freeze_embeds(model):
"""Freeze token embeddings and positional embeddings for bart, just token embeddings for t5."""
model_type = model.config.model_type
if model_type == "t5":
freeze_params(model.shared)
for d in [model.encoder, model.decoder]:
freeze_params(d.embed_tokens... | [
"def",
"freeze_embeds",
"(",
"model",
")",
":",
"model_type",
"=",
"model",
".",
"config",
".",
"model_type",
"if",
"model_type",
"==",
"\"t5\"",
":",
"freeze_params",
"(",
"model",
".",
"shared",
")",
"for",
"d",
"in",
"[",
"model",
".",
"encoder",
",",... | [
545,
0
] | [
561,
41
] | python | en | ['en', 'xh', 'en'] | True |
parse_numeric_n_bool_cl_kwargs | (unparsed_args: List[str]) |
Parse an argv list of unspecified command line args to a dict.
Assumes all values are either numeric or boolean in the form of true/false.
|
Parse an argv list of unspecified command line args to a dict.
Assumes all values are either numeric or boolean in the form of true/false.
| def parse_numeric_n_bool_cl_kwargs(unparsed_args: List[str]) -> Dict[str, Union[int, float, bool]]:
"""
Parse an argv list of unspecified command line args to a dict.
Assumes all values are either numeric or boolean in the form of true/false.
"""
result = {}
assert len(unparsed_args) % 2 == 0, f... | [
"def",
"parse_numeric_n_bool_cl_kwargs",
"(",
"unparsed_args",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Union",
"[",
"int",
",",
"float",
",",
"bool",
"]",
"]",
":",
"result",
"=",
"{",
"}",
"assert",
"len",
"(",
"unparsed_arg... | [
585,
0
] | [
607,
17
] | python | en | ['en', 'error', 'th'] | False |
chunks | (lst, n) | Yield successive n-sized chunks from lst. | Yield successive n-sized chunks from lst. | def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i : i + n] | [
"def",
"chunks",
"(",
"lst",
",",
"n",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"lst",
")",
",",
"n",
")",
":",
"yield",
"lst",
"[",
"i",
":",
"i",
"+",
"n",
"]"
] | [
617,
0
] | [
620,
28
] | python | en | ['en', 'en', 'en'] | True |
check_output_dir | (args, expected_items=0) |
Checks whether to bail out if output_dir already exists and has more than expected_items in it
`args`: needs to have the following attributes of `args`:
- output_dir
- do_train
- overwrite_output_dir
`expected_items`: normally 0 (default) - i.e. empty dir, but in some cases a few files ... |
Checks whether to bail out if output_dir already exists and has more than expected_items in it | def check_output_dir(args, expected_items=0):
"""
Checks whether to bail out if output_dir already exists and has more than expected_items in it
`args`: needs to have the following attributes of `args`:
- output_dir
- do_train
- overwrite_output_dir
`expected_items`: normally 0 (defa... | [
"def",
"check_output_dir",
"(",
"args",
",",
"expected_items",
"=",
"0",
")",
":",
"if",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"args",
".",
"output_dir",
")",
"and",
"len",
"(",
"os",
".",
"listdir",
"(",
"args",
".",
"output_dir",
")",
")",
... | [
623,
0
] | [
644,
9
] | python | en | ['en', 'error', 'th'] | False |
AbstractSeq2SeqDataset.tgt_lens | (self) | Length in characters of target documents | Length in characters of target documents | def tgt_lens(self):
"""Length in characters of target documents"""
return self.get_char_lens(self.tgt_file) | [
"def",
"tgt_lens",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_char_lens",
"(",
"self",
".",
"tgt_file",
")"
] | [
149,
4
] | [
151,
48
] | python | en | ['en', 'en', 'en'] | True |
LegacySeq2SeqDataset.__getitem__ | (self, index) | Call tokenizer on src and tgt_lines | Call tokenizer on src and tgt_lines | def __getitem__(self, index) -> Dict[str, torch.Tensor]:
"""Call tokenizer on src and tgt_lines"""
index = index + 1 # linecache starts at 1
source_line = self.prefix + linecache.getline(str(self.src_file), index).rstrip("\n")
tgt_line = linecache.getline(str(self.tgt_file), index).rstr... | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
":",
"index",
"=",
"index",
"+",
"1",
"# linecache starts at 1",
"source_line",
"=",
"self",
".",
"prefix",
"+",
"linecache",
".",
"getline"... | [
192,
4
] | [
209,
9
] | python | en | ['en', 'en', 'en'] | True |
LegacySeq2SeqDataset.encode_line | (self, tokenizer, line, max_length, pad_to_max_length=True, return_tensors="pt") | Only used by LegacyDataset | Only used by LegacyDataset | def encode_line(self, tokenizer, line, max_length, pad_to_max_length=True, return_tensors="pt"):
"""Only used by LegacyDataset"""
return tokenizer(
[line],
max_length=max_length,
padding="max_length" if pad_to_max_length else None,
truncation=True,
... | [
"def",
"encode_line",
"(",
"self",
",",
"tokenizer",
",",
"line",
",",
"max_length",
",",
"pad_to_max_length",
"=",
"True",
",",
"return_tensors",
"=",
"\"pt\"",
")",
":",
"return",
"tokenizer",
"(",
"[",
"line",
"]",
",",
"max_length",
"=",
"max_length",
... | [
211,
4
] | [
220,
9
] | python | en | ['en', 'en', 'en'] | True |
Seq2SeqDataset.collate_fn | (self, batch) | Call prepare_seq2seq_batch. | Call prepare_seq2seq_batch. | def collate_fn(self, batch) -> Dict[str, torch.Tensor]:
"""Call prepare_seq2seq_batch."""
batch_encoding: Dict[str, torch.Tensor] = self.tokenizer.prepare_seq2seq_batch(
[x["src_texts"] for x in batch],
tgt_texts=[x["tgt_texts"] for x in batch],
max_length=self.max_so... | [
"def",
"collate_fn",
"(",
"self",
",",
"batch",
")",
"->",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
":",
"batch_encoding",
":",
"Dict",
"[",
"str",
",",
"torch",
".",
"Tensor",
"]",
"=",
"self",
".",
"tokenizer",
".",
"prepare_seq2seq_batc... | [
248,
4
] | [
259,
29
] | python | en | ['en', 'gd', 'en'] | False |
test_cloud_system_health | (hass, aioclient_mock) | Test cloud system health. | Test cloud system health. | async def test_cloud_system_health(hass, aioclient_mock):
"""Test cloud system health."""
aioclient_mock.get("https://cloud.bla.com/status", text="")
aioclient_mock.get("https://cert-server", text="")
aioclient_mock.get(
"https://cognito-idp.us-east-1.amazonaws.com/AAAA/.well-known/jwks.json",
... | [
"async",
"def",
"test_cloud_system_health",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"aioclient_mock",
".",
"get",
"(",
"\"https://cloud.bla.com/status\"",
",",
"text",
"=",
"\"\"",
")",
"aioclient_mock",
".",
"get",
"(",
"\"https://cert-server\"",
",",
"text",... | [
12,
0
] | [
59,
5
] | python | en | ['nl', 'en', 'en'] | True |
async_test_humidity | (hass, cluster, entity_id) | Test humidity sensor. | Test humidity sensor. | async def async_test_humidity(hass, cluster, entity_id):
"""Test humidity sensor."""
await send_attributes_report(hass, cluster, {1: 1, 0: 1000, 2: 100})
assert_state(hass, entity_id, "10.0", PERCENTAGE) | [
"async",
"def",
"async_test_humidity",
"(",
"hass",
",",
"cluster",
",",
"entity_id",
")",
":",
"await",
"send_attributes_report",
"(",
"hass",
",",
"cluster",
",",
"{",
"1",
":",
"1",
",",
"0",
":",
"1000",
",",
"2",
":",
"100",
"}",
")",
"assert_stat... | [
38,
0
] | [
41,
53
] | python | en | ['en', 'et', 'en'] | True |
async_test_temperature | (hass, cluster, entity_id) | Test temperature sensor. | Test temperature sensor. | async def async_test_temperature(hass, cluster, entity_id):
"""Test temperature sensor."""
await send_attributes_report(hass, cluster, {1: 1, 0: 2900, 2: 100})
assert_state(hass, entity_id, "29.0", TEMP_CELSIUS) | [
"async",
"def",
"async_test_temperature",
"(",
"hass",
",",
"cluster",
",",
"entity_id",
")",
":",
"await",
"send_attributes_report",
"(",
"hass",
",",
"cluster",
",",
"{",
"1",
":",
"1",
",",
"0",
":",
"2900",
",",
"2",
":",
"100",
"}",
")",
"assert_s... | [
44,
0
] | [
47,
55
] | python | en | ['en', 'la', 'en'] | True |
async_test_pressure | (hass, cluster, entity_id) | Test pressure sensor. | Test pressure sensor. | async def async_test_pressure(hass, cluster, entity_id):
"""Test pressure sensor."""
await send_attributes_report(hass, cluster, {1: 1, 0: 1000, 2: 10000})
assert_state(hass, entity_id, "1000", PRESSURE_HPA)
await send_attributes_report(hass, cluster, {0: 1000, 20: -1, 16: 10000})
assert_state(hass... | [
"async",
"def",
"async_test_pressure",
"(",
"hass",
",",
"cluster",
",",
"entity_id",
")",
":",
"await",
"send_attributes_report",
"(",
"hass",
",",
"cluster",
",",
"{",
"1",
":",
"1",
",",
"0",
":",
"1000",
",",
"2",
":",
"10000",
"}",
")",
"assert_st... | [
50,
0
] | [
56,
55
] | python | en | ['en', 'bs', 'en'] | True |
async_test_illuminance | (hass, cluster, entity_id) | Test illuminance sensor. | Test illuminance sensor. | async def async_test_illuminance(hass, cluster, entity_id):
"""Test illuminance sensor."""
await send_attributes_report(hass, cluster, {1: 1, 0: 10, 2: 20})
assert_state(hass, entity_id, "1.0", LIGHT_LUX) | [
"async",
"def",
"async_test_illuminance",
"(",
"hass",
",",
"cluster",
",",
"entity_id",
")",
":",
"await",
"send_attributes_report",
"(",
"hass",
",",
"cluster",
",",
"{",
"1",
":",
"1",
",",
"0",
":",
"10",
",",
"2",
":",
"20",
"}",
")",
"assert_stat... | [
59,
0
] | [
62,
51
] | python | fi | ['fr', 'fi', 'it'] | False |
async_test_metering | (hass, cluster, entity_id) | Test metering sensor. | Test metering sensor. | async def async_test_metering(hass, cluster, entity_id):
"""Test metering sensor."""
await send_attributes_report(hass, cluster, {1025: 1, 1024: 12345, 1026: 100})
assert_state(hass, entity_id, "12345.0", "unknown") | [
"async",
"def",
"async_test_metering",
"(",
"hass",
",",
"cluster",
",",
"entity_id",
")",
":",
"await",
"send_attributes_report",
"(",
"hass",
",",
"cluster",
",",
"{",
"1025",
":",
"1",
",",
"1024",
":",
"12345",
",",
"1026",
":",
"100",
"}",
")",
"a... | [
65,
0
] | [
68,
55
] | python | af | ['en', 'af', 'nl'] | False |
async_test_electrical_measurement | (hass, cluster, entity_id) | Test electrical measurement sensor. | Test electrical measurement sensor. | async def async_test_electrical_measurement(hass, cluster, entity_id):
"""Test electrical measurement sensor."""
with mock.patch(
(
"homeassistant.components.zha.core.channels.homeautomation"
".ElectricalMeasurementChannel.divisor"
),
new_callable=mock.PropertyMoc... | [
"async",
"def",
"async_test_electrical_measurement",
"(",
"hass",
",",
"cluster",
",",
"entity_id",
")",
":",
"with",
"mock",
".",
"patch",
"(",
"(",
"\"homeassistant.components.zha.core.channels.homeautomation\"",
"\".ElectricalMeasurementChannel.divisor\"",
")",
",",
"new... | [
71,
0
] | [
92,
56
] | python | en | ['en', 'da', 'en'] | True |
async_test_powerconfiguration | (hass, cluster, entity_id) | Test powerconfiguration/battery sensor. | Test powerconfiguration/battery sensor. | async def async_test_powerconfiguration(hass, cluster, entity_id):
"""Test powerconfiguration/battery sensor."""
await send_attributes_report(hass, cluster, {33: 98})
assert_state(hass, entity_id, "49", "%")
assert hass.states.get(entity_id).attributes["battery_voltage"] == 2.9
assert hass.states.ge... | [
"async",
"def",
"async_test_powerconfiguration",
"(",
"hass",
",",
"cluster",
",",
"entity_id",
")",
":",
"await",
"send_attributes_report",
"(",
"hass",
",",
"cluster",
",",
"{",
"33",
":",
"98",
"}",
")",
"assert_state",
"(",
"hass",
",",
"entity_id",
",",... | [
95,
0
] | [
103,
74
] | python | en | ['en', 'no', 'en'] | True |
test_sensor | (
hass,
zigpy_device_mock,
zha_device_joined_restored,
cluster_id,
test_func,
report_count,
read_plug,
) | Test zha sensor platform. | Test zha sensor platform. | async def test_sensor(
hass,
zigpy_device_mock,
zha_device_joined_restored,
cluster_id,
test_func,
report_count,
read_plug,
):
"""Test zha sensor platform."""
zigpy_device = zigpy_device_mock(
{
1: {
"in_clusters": [cluster_id, general.Basic.clust... | [
"async",
"def",
"test_sensor",
"(",
"hass",
",",
"zigpy_device_mock",
",",
"zha_device_joined_restored",
",",
"cluster_id",
",",
"test_func",
",",
"report_count",
",",
"read_plug",
",",
")",
":",
"zigpy_device",
"=",
"zigpy_device_mock",
"(",
"{",
"1",
":",
"{",... | [
151,
0
] | [
194,
75
] | python | bg-Latn | ['cs', 'bg-Latn', 'pl'] | False |
assert_state | (hass, entity_id, state, unit_of_measurement) | Check that the state is what is expected.
This is used to ensure that the logic in each sensor class handled the
attribute report it received correctly.
| Check that the state is what is expected. | def assert_state(hass, entity_id, state, unit_of_measurement):
"""Check that the state is what is expected.
This is used to ensure that the logic in each sensor class handled the
attribute report it received correctly.
"""
hass_state = hass.states.get(entity_id)
assert hass_state.state == state... | [
"def",
"assert_state",
"(",
"hass",
",",
"entity_id",
",",
"state",
",",
"unit_of_measurement",
")",
":",
"hass_state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"hass_state",
".",
"state",
"==",
"state",
"assert",
"hass_state"... | [
197,
0
] | [
205,
85
] | python | en | ['en', 'en', 'en'] | True |
hass_ms | (hass) | Hass instance with measurement system. | Hass instance with measurement system. | def hass_ms(hass):
"""Hass instance with measurement system."""
async def _hass_ms(meas_sys):
await config_util.async_process_ha_core_config(
hass, {CONF_UNIT_SYSTEM: meas_sys}
)
await hass.async_block_till_done()
return hass
return _hass_ms | [
"def",
"hass_ms",
"(",
"hass",
")",
":",
"async",
"def",
"_hass_ms",
"(",
"meas_sys",
")",
":",
"await",
"config_util",
".",
"async_process_ha_core_config",
"(",
"hass",
",",
"{",
"CONF_UNIT_SYSTEM",
":",
"meas_sys",
"}",
")",
"await",
"hass",
".",
"async_bl... | [
209,
0
] | [
219,
19
] | python | en | ['en', 'en', 'en'] | True |
core_rs | (hass_storage) | Core.restore_state fixture. | Core.restore_state fixture. | def core_rs(hass_storage):
"""Core.restore_state fixture."""
def _storage(entity_id, uom, state):
now = dt_util.utcnow().isoformat()
hass_storage[restore_state.STORAGE_KEY] = {
"version": restore_state.STORAGE_VERSION,
"key": restore_state.STORAGE_KEY,
"data... | [
"def",
"core_rs",
"(",
"hass_storage",
")",
":",
"def",
"_storage",
"(",
"entity_id",
",",
"uom",
",",
"state",
")",
":",
"now",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"hass_storage",
"[",
"restore_state",
".",
"STORAGE_KEY"... | [
223,
0
] | [
251,
19
] | python | en | ['en', 'it', 'en'] | False |
test_temp_uom | (
uom,
raw_temp,
expected,
restore,
hass_ms,
core_rs,
zigpy_device_mock,
zha_device_restored,
) | Test zha temperature sensor unit of measurement. | Test zha temperature sensor unit of measurement. | async def test_temp_uom(
uom,
raw_temp,
expected,
restore,
hass_ms,
core_rs,
zigpy_device_mock,
zha_device_restored,
):
"""Test zha temperature sensor unit of measurement."""
entity_id = "sensor.fake1026_fakemodel1026_004f3202_temperature"
if restore:
core_rs(entity_... | [
"async",
"def",
"test_temp_uom",
"(",
"uom",
",",
"raw_temp",
",",
"expected",
",",
"restore",
",",
"hass_ms",
",",
"core_rs",
",",
"zigpy_device_mock",
",",
"zha_device_restored",
",",
")",
":",
"entity_id",
"=",
"\"sensor.fake1026_fakemodel1026_004f3202_temperature\... | [
263,
0
] | [
315,
60
] | python | en | ['en', 'fr', 'en'] | True |
test_electrical_measurement_init | (
hass,
zigpy_device_mock,
zha_device_joined,
) | Test proper initialization of the electrical measurement cluster. | Test proper initialization of the electrical measurement cluster. | async def test_electrical_measurement_init(
hass,
zigpy_device_mock,
zha_device_joined,
):
"""Test proper initialization of the electrical measurement cluster."""
cluster_id = homeautomation.ElectricalMeasurement.cluster_id
zigpy_device = zigpy_device_mock(
{
1: {
... | [
"async",
"def",
"test_electrical_measurement_init",
"(",
"hass",
",",
"zigpy_device_mock",
",",
"zha_device_joined",
",",
")",
":",
"cluster_id",
"=",
"homeautomation",
".",
"ElectricalMeasurement",
".",
"cluster_id",
"zigpy_device",
"=",
"zigpy_device_mock",
"(",
"{",
... | [
318,
0
] | [
372,
53
] | python | en | ['en', 'en', 'en'] | True |
setup_scanner | (hass, config: ConfigType, see, discovery_info=None) | Set up the Google Maps Location sharing scanner. | Set up the Google Maps Location sharing scanner. | def setup_scanner(hass, config: ConfigType, see, discovery_info=None):
"""Set up the Google Maps Location sharing scanner."""
scanner = GoogleMapsScanner(hass, config, see)
return scanner.success_init | [
"def",
"setup_scanner",
"(",
"hass",
",",
"config",
":",
"ConfigType",
",",
"see",
",",
"discovery_info",
"=",
"None",
")",
":",
"scanner",
"=",
"GoogleMapsScanner",
"(",
"hass",
",",
"config",
",",
"see",
")",
"return",
"scanner",
".",
"success_init"
] | [
40,
0
] | [
43,
31
] | python | en | ['en', 'en', 'en'] | True |
GoogleMapsScanner.__init__ | (self, hass, config: ConfigType, see) | Initialize the scanner. | Initialize the scanner. | def __init__(self, hass, config: ConfigType, see) -> None:
"""Initialize the scanner."""
self.see = see
self.username = config[CONF_USERNAME]
self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY]
self.scan_interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=60)
... | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"config",
":",
"ConfigType",
",",
"see",
")",
"->",
"None",
":",
"self",
".",
"see",
"=",
"see",
"self",
".",
"username",
"=",
"config",
"[",
"CONF_USERNAME",
"]",
"self",
".",
"max_gps_accuracy",
"=",
... | [
49,
4
] | [
70,
37
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the RESTful switch. | Set up the RESTful switch. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the RESTful switch."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
body_off = config.get(CONF_BODY_OFF)
body_on = config.get(CONF_BODY_ON)
is_on_template = config.get(CONF_IS_ON_TEMPLATE)... | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"await",
"async_setup_reload_service",
"(",
"hass",
",",
"DOMAIN",
",",
"PLATFORMS",
")",
"body_off",
"=",
"config",
".",... | [
65,
0
] | [
122,
68
] | python | en | ['en', 'en', 'en'] | True |
RestSwitch.__init__ | (
self,
name,
resource,
state_resource,
method,
headers,
params,
auth,
body_on,
body_off,
is_on_template,
timeout,
verify_ssl,
) | Initialize the REST switch. | Initialize the REST switch. | def __init__(
self,
name,
resource,
state_resource,
method,
headers,
params,
auth,
body_on,
body_off,
is_on_template,
timeout,
verify_ssl,
):
"""Initialize the REST switch."""
self._state = None
... | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"resource",
",",
"state_resource",
",",
"method",
",",
"headers",
",",
"params",
",",
"auth",
",",
"body_on",
",",
"body_off",
",",
"is_on_template",
",",
"timeout",
",",
"verify_ssl",
",",
")",
":",
"sel... | [
128,
4
] | [
156,
37
] | python | en | ['en', 'en', 'en'] | True |
RestSwitch.name | (self) | Return the name of the switch. | Return the name of the switch. | def name(self):
"""Return the name of the switch."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
159,
4
] | [
161,
25
] | python | en | ['en', 'en', 'en'] | True |
RestSwitch.is_on | (self) | Return true if device is on. | Return true if device is on. | def is_on(self):
"""Return true if device is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
164,
4
] | [
166,
26
] | python | en | ['en', 'fy', 'en'] | True |
RestSwitch.async_turn_on | (self, **kwargs) | Turn the device on. | Turn the device on. | async def async_turn_on(self, **kwargs):
"""Turn the device on."""
body_on_t = self._body_on.async_render(parse_result=False)
try:
req = await self.set_device_state(body_on_t)
if req.status == HTTP_OK:
self._state = True
else:
... | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"body_on_t",
"=",
"self",
".",
"_body_on",
".",
"async_render",
"(",
"parse_result",
"=",
"False",
")",
"try",
":",
"req",
"=",
"await",
"self",
".",
"set_device_state",
"("... | [
168,
4
] | [
182,
72
] | python | en | ['en', 'en', 'en'] | True |
RestSwitch.async_turn_off | (self, **kwargs) | Turn the device off. | Turn the device off. | async def async_turn_off(self, **kwargs):
"""Turn the device off."""
body_off_t = self._body_off.async_render(parse_result=False)
try:
req = await self.set_device_state(body_off_t)
if req.status == HTTP_OK:
self._state = False
else:
... | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"body_off_t",
"=",
"self",
".",
"_body_off",
".",
"async_render",
"(",
"parse_result",
"=",
"False",
")",
"try",
":",
"req",
"=",
"await",
"self",
".",
"set_device_state",
... | [
184,
4
] | [
197,
73
] | python | en | ['en', 'en', 'en'] | True |
RestSwitch.set_device_state | (self, body) | Send a state update to the device. | Send a state update to the device. | async def set_device_state(self, body):
"""Send a state update to the device."""
websession = async_get_clientsession(self.hass, self._verify_ssl)
with async_timeout.timeout(self._timeout):
req = await getattr(websession, self._method)(
self._resource,
... | [
"async",
"def",
"set_device_state",
"(",
"self",
",",
"body",
")",
":",
"websession",
"=",
"async_get_clientsession",
"(",
"self",
".",
"hass",
",",
"self",
".",
"_verify_ssl",
")",
"with",
"async_timeout",
".",
"timeout",
"(",
"self",
".",
"_timeout",
")",
... | [
199,
4
] | [
211,
22
] | python | en | ['en', 'en', 'en'] | True |
RestSwitch.async_update | (self) | Get the current state, catching errors. | Get the current state, catching errors. | async def async_update(self):
"""Get the current state, catching errors."""
try:
await self.get_device_state(self.hass)
except asyncio.TimeoutError:
_LOGGER.exception("Timed out while fetching data")
except aiohttp.ClientError as err:
_LOGGER.exception... | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"try",
":",
"await",
"self",
".",
"get_device_state",
"(",
"self",
".",
"hass",
")",
"except",
"asyncio",
".",
"TimeoutError",
":",
"_LOGGER",
".",
"exception",
"(",
"\"Timed out while fetching data\"",
")... | [
213,
4
] | [
220,
67
] | python | en | ['en', 'en', 'en'] | True |
RestSwitch.get_device_state | (self, hass) | Get the latest data from REST API and update the state. | Get the latest data from REST API and update the state. | async def get_device_state(self, hass):
"""Get the latest data from REST API and update the state."""
websession = async_get_clientsession(hass, self._verify_ssl)
with async_timeout.timeout(self._timeout):
req = await websession.get(
self._state_resource,
... | [
"async",
"def",
"get_device_state",
"(",
"self",
",",
"hass",
")",
":",
"websession",
"=",
"async_get_clientsession",
"(",
"hass",
",",
"self",
".",
"_verify_ssl",
")",
"with",
"async_timeout",
".",
"timeout",
"(",
"self",
".",
"_timeout",
")",
":",
"req",
... | [
222,
4
] | [
254,
18
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the NSW Fuel Station sensor. | Set up the NSW Fuel Station sensor. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the NSW Fuel Station sensor."""
station_id = config[CONF_STATION_ID]
fuel_types = config[CONF_FUEL_TYPES]
client = FuelCheckClient()
station_data = StationPriceData(client, station_id)
station_data.update()
if ... | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"station_id",
"=",
"config",
"[",
"CONF_STATION_ID",
"]",
"fuel_types",
"=",
"config",
"[",
"CONF_FUEL_TYPES",
"]",
"client",
"=",
"FuelChec... | [
53,
0
] | [
81,
5
] | python | en | ['en', 'da', 'en'] | True |
StationPriceData.__init__ | (self, client, station_id: int) | Initialize the sensor. | Initialize the sensor. | def __init__(self, client, station_id: int) -> None:
"""Initialize the sensor."""
self.station_id = station_id
self._client = client
self._data = None
self._reference_data = None
self.error = None
self._station_name = None | [
"def",
"__init__",
"(",
"self",
",",
"client",
",",
"station_id",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"station_id",
"=",
"station_id",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"_data",
"=",
"None",
"self",
".",
"_reference_data",
... | [
87,
4
] | [
94,
33
] | python | en | ['en', 'en', 'en'] | True |
StationPriceData.update | (self) | Update the internal data using the API client. | Update the internal data using the API client. | def update(self):
"""Update the internal data using the API client."""
if self._reference_data is None:
try:
self._reference_data = self._client.get_reference_data()
except FuelCheckError as exc:
self.error = str(exc)
_LOGGER.error... | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"_reference_data",
"is",
"None",
":",
"try",
":",
"self",
".",
"_reference_data",
"=",
"self",
".",
"_client",
".",
"get_reference_data",
"(",
")",
"except",
"FuelCheckError",
"as",
"exc",
":",
"... | [
97,
4
] | [
114,
81
] | python | en | ['en', 'en', 'en'] | True |
StationPriceData.for_fuel_type | (self, fuel_type: str) | Return the price of the given fuel type. | Return the price of the given fuel type. | def for_fuel_type(self, fuel_type: str):
"""Return the price of the given fuel type."""
if self._data is None:
return None
return next(
(price for price in self._data if price.fuel_type == fuel_type), None
) | [
"def",
"for_fuel_type",
"(",
"self",
",",
"fuel_type",
":",
"str",
")",
":",
"if",
"self",
".",
"_data",
"is",
"None",
":",
"return",
"None",
"return",
"next",
"(",
"(",
"price",
"for",
"price",
"in",
"self",
".",
"_data",
"if",
"price",
".",
"fuel_t... | [
116,
4
] | [
122,
9
] | python | en | ['en', 'en', 'en'] | True |
StationPriceData.get_available_fuel_types | (self) | Return the available fuel types for the station. | Return the available fuel types for the station. | def get_available_fuel_types(self):
"""Return the available fuel types for the station."""
return [price.fuel_type for price in self._data] | [
"def",
"get_available_fuel_types",
"(",
"self",
")",
":",
"return",
"[",
"price",
".",
"fuel_type",
"for",
"price",
"in",
"self",
".",
"_data",
"]"
] | [
124,
4
] | [
126,
56
] | python | en | ['en', 'en', 'en'] | True |
StationPriceData.get_station_name | (self) | Return the name of the station. | Return the name of the station. | def get_station_name(self) -> str:
"""Return the name of the station."""
if self._station_name is None:
name = None
if self._reference_data is not None:
name = next(
(
station.name
for station in ... | [
"def",
"get_station_name",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_station_name",
"is",
"None",
":",
"name",
"=",
"None",
"if",
"self",
".",
"_reference_data",
"is",
"not",
"None",
":",
"name",
"=",
"next",
"(",
"(",
"station",
".",
... | [
128,
4
] | [
144,
33
] | python | en | ['en', 'en', 'en'] | True |
StationPriceSensor.__init__ | (self, station_data: StationPriceData, fuel_type: str) | Initialize the sensor. | Initialize the sensor. | def __init__(self, station_data: StationPriceData, fuel_type: str):
"""Initialize the sensor."""
self._station_data = station_data
self._fuel_type = fuel_type | [
"def",
"__init__",
"(",
"self",
",",
"station_data",
":",
"StationPriceData",
",",
"fuel_type",
":",
"str",
")",
":",
"self",
".",
"_station_data",
"=",
"station_data",
"self",
".",
"_fuel_type",
"=",
"fuel_type"
] | [
150,
4
] | [
153,
35
] | python | en | ['en', 'en', 'en'] | True |
StationPriceSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self) -> str:
"""Return the name of the sensor."""
return f"{self._station_data.get_station_name()} {self._fuel_type}" | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"{self._station_data.get_station_name()} {self._fuel_type}\""
] | [
156,
4
] | [
158,
75
] | python | en | ['en', 'mi', 'en'] | True |
StationPriceSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self) -> Optional[float]:
"""Return the state of the sensor."""
price_info = self._station_data.for_fuel_type(self._fuel_type)
if price_info:
return price_info.price
return None | [
"def",
"state",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"price_info",
"=",
"self",
".",
"_station_data",
".",
"for_fuel_type",
"(",
"self",
".",
"_fuel_type",
")",
"if",
"price_info",
":",
"return",
"price_info",
".",
"price",
"return",... | [
161,
4
] | [
167,
19
] | python | en | ['en', 'en', 'en'] | True |
StationPriceSensor.device_state_attributes | (self) | Return the state attributes of the device. | Return the state attributes of the device. | def device_state_attributes(self) -> dict:
"""Return the state attributes of the device."""
return {
ATTR_STATION_ID: self._station_data.station_id,
ATTR_STATION_NAME: self._station_data.get_station_name(),
ATTR_ATTRIBUTION: ATTRIBUTION,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"ATTR_STATION_ID",
":",
"self",
".",
"_station_data",
".",
"station_id",
",",
"ATTR_STATION_NAME",
":",
"self",
".",
"_station_data",
".",
"get_station_name",
"(",
")",
",",
... | [
170,
4
] | [
176,
9
] | python | en | ['en', 'en', 'en'] | True |
StationPriceSensor.unit_of_measurement | (self) | Return the units of measurement. | Return the units of measurement. | def unit_of_measurement(self) -> str:
"""Return the units of measurement."""
return f"{CURRENCY_CENT}/{VOLUME_LITERS}" | [
"def",
"unit_of_measurement",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"{CURRENCY_CENT}/{VOLUME_LITERS}\""
] | [
179,
4
] | [
181,
49
] | python | en | ['en', 'bg', 'en'] | True |
StationPriceSensor.update | (self) | Update current conditions. | Update current conditions. | def update(self):
"""Update current conditions."""
self._station_data.update() | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_station_data",
".",
"update",
"(",
")"
] | [
183,
4
] | [
185,
35
] | python | en | ['en', 'en', 'en'] | True |
AugustEntityMixin.__init__ | (self, data, device) | Initialize an August device. | Initialize an August device. | def __init__(self, data, device):
"""Initialize an August device."""
super().__init__()
self._data = data
self._device = device | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"device",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_device",
"=",
"device"
] | [
11,
4
] | [
15,
29
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.