Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
ws_delete_blueprint | (hass, connection, msg) | Delete a blueprint. | Delete a blueprint. | async def ws_delete_blueprint(hass, connection, msg):
"""Delete a blueprint."""
path = msg["path"]
domain = msg["domain"]
domain_blueprints: Optional[Dict[str, models.DomainBlueprints]] = hass.data.get(
DOMAIN, {}
)
if domain not in domain_blueprints:
connection.send_error(
msg["id"], websocket_api.ERR_INVALID_FORMAT, "Unsupported domain"
)
try:
await domain_blueprints[domain].async_remove_blueprint(path)
except OSError as err:
connection.send_error(msg["id"], websocket_api.ERR_UNKNOWN_ERROR, str(err))
return
connection.send_result(
msg["id"],
) | [
"async",
"def",
"ws_delete_blueprint",
"(",
"hass",
",",
"connection",
",",
"msg",
")",
":",
"path",
"=",
"msg",
"[",
"\"path\"",
"]",
"domain",
"=",
"msg",
"[",
"\"domain\"",
"]",
"domain_blueprints",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"models",
".",
"DomainBlueprints",
"]",
"]",
"=",
"hass",
".",
"data",
".",
"get",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"if",
"domain",
"not",
"in",
"domain_blueprints",
":",
"connection",
".",
"send_error",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"websocket_api",
".",
"ERR_INVALID_FORMAT",
",",
"\"Unsupported domain\"",
")",
"try",
":",
"await",
"domain_blueprints",
"[",
"domain",
"]",
".",
"async_remove_blueprint",
"(",
"path",
")",
"except",
"OSError",
"as",
"err",
":",
"connection",
".",
"send_error",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
"websocket_api",
".",
"ERR_UNKNOWN_ERROR",
",",
"str",
"(",
"err",
")",
")",
"return",
"connection",
".",
"send_result",
"(",
"msg",
"[",
"\"id\"",
"]",
",",
")"
] | [
149,
0
] | [
172,
5
] | python | en | ['en', 'hu', 'en'] | True |
color_name_to_rgb | (color_name: str) | Convert color name to RGB hex value. | Convert color name to RGB hex value. | def color_name_to_rgb(color_name: str) -> Tuple[int, int, int]:
"""Convert color name to RGB hex value."""
# COLORS map has no spaces in it, so make the color_name have no
# spaces in it as well for matching purposes
hex_value = COLORS.get(color_name.replace(" ", "").lower())
if not hex_value:
raise ValueError("Unknown color")
return hex_value | [
"def",
"color_name_to_rgb",
"(",
"color_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"# COLORS map has no spaces in it, so make the color_name have no",
"# spaces in it as well for matching purposes",
"hex_value",
"=",
"COLORS",
".",
"get",
"(",
"color_name",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
")",
"if",
"not",
"hex_value",
":",
"raise",
"ValueError",
"(",
"\"Unknown color\"",
")",
"return",
"hex_value"
] | [
183,
0
] | [
191,
20
] | python | en | ['en', 'en', 'en'] | True |
color_RGB_to_xy | (
iR: int, iG: int, iB: int, Gamut: Optional[GamutType] = None
) | Convert from RGB color to XY color. | Convert from RGB color to XY color. | def color_RGB_to_xy(
iR: int, iG: int, iB: int, Gamut: Optional[GamutType] = None
) -> Tuple[float, float]:
"""Convert from RGB color to XY color."""
return color_RGB_to_xy_brightness(iR, iG, iB, Gamut)[:2] | [
"def",
"color_RGB_to_xy",
"(",
"iR",
":",
"int",
",",
"iG",
":",
"int",
",",
"iB",
":",
"int",
",",
"Gamut",
":",
"Optional",
"[",
"GamutType",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"return",
"color_RGB_to_xy_brightness",
"(",
"iR",
",",
"iG",
",",
"iB",
",",
"Gamut",
")",
"[",
":",
"2",
"]"
] | [
195,
0
] | [
199,
60
] | python | en | ['en', 'en', 'en'] | True |
color_RGB_to_xy_brightness | (
iR: int, iG: int, iB: int, Gamut: Optional[GamutType] = None
) | Convert from RGB color to XY color. | Convert from RGB color to XY color. | def color_RGB_to_xy_brightness(
iR: int, iG: int, iB: int, Gamut: Optional[GamutType] = None
) -> Tuple[float, float, int]:
"""Convert from RGB color to XY color."""
if iR + iG + iB == 0:
return 0.0, 0.0, 0
R = iR / 255
B = iB / 255
G = iG / 255
# Gamma correction
R = pow((R + 0.055) / (1.0 + 0.055), 2.4) if (R > 0.04045) else (R / 12.92)
G = pow((G + 0.055) / (1.0 + 0.055), 2.4) if (G > 0.04045) else (G / 12.92)
B = pow((B + 0.055) / (1.0 + 0.055), 2.4) if (B > 0.04045) else (B / 12.92)
# Wide RGB D65 conversion formula
X = R * 0.664511 + G * 0.154324 + B * 0.162028
Y = R * 0.283881 + G * 0.668433 + B * 0.047685
Z = R * 0.000088 + G * 0.072310 + B * 0.986039
# Convert XYZ to xy
x = X / (X + Y + Z)
y = Y / (X + Y + Z)
# Brightness
Y = 1 if Y > 1 else Y
brightness = round(Y * 255)
# Check if the given xy value is within the color-reach of the lamp.
if Gamut:
in_reach = check_point_in_lamps_reach((x, y), Gamut)
if not in_reach:
xy_closest = get_closest_point_to_point((x, y), Gamut)
x = xy_closest[0]
y = xy_closest[1]
return round(x, 3), round(y, 3), brightness | [
"def",
"color_RGB_to_xy_brightness",
"(",
"iR",
":",
"int",
",",
"iG",
":",
"int",
",",
"iB",
":",
"int",
",",
"Gamut",
":",
"Optional",
"[",
"GamutType",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"int",
"]",
":",
"if",
"iR",
"+",
"iG",
"+",
"iB",
"==",
"0",
":",
"return",
"0.0",
",",
"0.0",
",",
"0",
"R",
"=",
"iR",
"/",
"255",
"B",
"=",
"iB",
"/",
"255",
"G",
"=",
"iG",
"/",
"255",
"# Gamma correction",
"R",
"=",
"pow",
"(",
"(",
"R",
"+",
"0.055",
")",
"/",
"(",
"1.0",
"+",
"0.055",
")",
",",
"2.4",
")",
"if",
"(",
"R",
">",
"0.04045",
")",
"else",
"(",
"R",
"/",
"12.92",
")",
"G",
"=",
"pow",
"(",
"(",
"G",
"+",
"0.055",
")",
"/",
"(",
"1.0",
"+",
"0.055",
")",
",",
"2.4",
")",
"if",
"(",
"G",
">",
"0.04045",
")",
"else",
"(",
"G",
"/",
"12.92",
")",
"B",
"=",
"pow",
"(",
"(",
"B",
"+",
"0.055",
")",
"/",
"(",
"1.0",
"+",
"0.055",
")",
",",
"2.4",
")",
"if",
"(",
"B",
">",
"0.04045",
")",
"else",
"(",
"B",
"/",
"12.92",
")",
"# Wide RGB D65 conversion formula",
"X",
"=",
"R",
"*",
"0.664511",
"+",
"G",
"*",
"0.154324",
"+",
"B",
"*",
"0.162028",
"Y",
"=",
"R",
"*",
"0.283881",
"+",
"G",
"*",
"0.668433",
"+",
"B",
"*",
"0.047685",
"Z",
"=",
"R",
"*",
"0.000088",
"+",
"G",
"*",
"0.072310",
"+",
"B",
"*",
"0.986039",
"# Convert XYZ to xy",
"x",
"=",
"X",
"/",
"(",
"X",
"+",
"Y",
"+",
"Z",
")",
"y",
"=",
"Y",
"/",
"(",
"X",
"+",
"Y",
"+",
"Z",
")",
"# Brightness",
"Y",
"=",
"1",
"if",
"Y",
">",
"1",
"else",
"Y",
"brightness",
"=",
"round",
"(",
"Y",
"*",
"255",
")",
"# Check if the given xy value is within the color-reach of the lamp.",
"if",
"Gamut",
":",
"in_reach",
"=",
"check_point_in_lamps_reach",
"(",
"(",
"x",
",",
"y",
")",
",",
"Gamut",
")",
"if",
"not",
"in_reach",
":",
"xy_closest",
"=",
"get_closest_point_to_point",
"(",
"(",
"x",
",",
"y",
")",
",",
"Gamut",
")",
"x",
"=",
"xy_closest",
"[",
"0",
"]",
"y",
"=",
"xy_closest",
"[",
"1",
"]",
"return",
"round",
"(",
"x",
",",
"3",
")",
",",
"round",
"(",
"y",
",",
"3",
")",
",",
"brightness"
] | [
206,
0
] | [
243,
47
] | python | en | ['en', 'en', 'en'] | True |
color_xy_to_RGB | (
vX: float, vY: float, Gamut: Optional[GamutType] = None
) | Convert from XY to a normalized RGB. | Convert from XY to a normalized RGB. | def color_xy_to_RGB(
vX: float, vY: float, Gamut: Optional[GamutType] = None
) -> Tuple[int, int, int]:
"""Convert from XY to a normalized RGB."""
return color_xy_brightness_to_RGB(vX, vY, 255, Gamut) | [
"def",
"color_xy_to_RGB",
"(",
"vX",
":",
"float",
",",
"vY",
":",
"float",
",",
"Gamut",
":",
"Optional",
"[",
"GamutType",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"return",
"color_xy_brightness_to_RGB",
"(",
"vX",
",",
"vY",
",",
"255",
",",
"Gamut",
")"
] | [
246,
0
] | [
250,
57
] | python | en | ['en', 'en', 'en'] | True |
color_xy_brightness_to_RGB | (
vX: float, vY: float, ibrightness: int, Gamut: Optional[GamutType] = None
) | Convert from XYZ to RGB. | Convert from XYZ to RGB. | def color_xy_brightness_to_RGB(
vX: float, vY: float, ibrightness: int, Gamut: Optional[GamutType] = None
) -> Tuple[int, int, int]:
"""Convert from XYZ to RGB."""
if Gamut:
if not check_point_in_lamps_reach((vX, vY), Gamut):
xy_closest = get_closest_point_to_point((vX, vY), Gamut)
vX = xy_closest[0]
vY = xy_closest[1]
brightness = ibrightness / 255.0
if brightness == 0.0:
return (0, 0, 0)
Y = brightness
if vY == 0.0:
vY += 0.00000000001
X = (Y / vY) * vX
Z = (Y / vY) * (1 - vX - vY)
# Convert to RGB using Wide RGB D65 conversion.
r = X * 1.656492 - Y * 0.354851 - Z * 0.255038
g = -X * 0.707196 + Y * 1.655397 + Z * 0.036152
b = X * 0.051713 - Y * 0.121364 + Z * 1.011530
# Apply reverse gamma correction.
r, g, b = map(
lambda x: (12.92 * x)
if (x <= 0.0031308)
else ((1.0 + 0.055) * pow(x, (1.0 / 2.4)) - 0.055),
[r, g, b],
)
# Bring all negative components to zero.
r, g, b = map(lambda x: max(0, x), [r, g, b])
# If one component is greater than 1, weight components by that value.
max_component = max(r, g, b)
if max_component > 1:
r, g, b = map(lambda x: x / max_component, [r, g, b])
ir, ig, ib = map(lambda x: int(x * 255), [r, g, b])
return (ir, ig, ib) | [
"def",
"color_xy_brightness_to_RGB",
"(",
"vX",
":",
"float",
",",
"vY",
":",
"float",
",",
"ibrightness",
":",
"int",
",",
"Gamut",
":",
"Optional",
"[",
"GamutType",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"if",
"Gamut",
":",
"if",
"not",
"check_point_in_lamps_reach",
"(",
"(",
"vX",
",",
"vY",
")",
",",
"Gamut",
")",
":",
"xy_closest",
"=",
"get_closest_point_to_point",
"(",
"(",
"vX",
",",
"vY",
")",
",",
"Gamut",
")",
"vX",
"=",
"xy_closest",
"[",
"0",
"]",
"vY",
"=",
"xy_closest",
"[",
"1",
"]",
"brightness",
"=",
"ibrightness",
"/",
"255.0",
"if",
"brightness",
"==",
"0.0",
":",
"return",
"(",
"0",
",",
"0",
",",
"0",
")",
"Y",
"=",
"brightness",
"if",
"vY",
"==",
"0.0",
":",
"vY",
"+=",
"0.00000000001",
"X",
"=",
"(",
"Y",
"/",
"vY",
")",
"*",
"vX",
"Z",
"=",
"(",
"Y",
"/",
"vY",
")",
"*",
"(",
"1",
"-",
"vX",
"-",
"vY",
")",
"# Convert to RGB using Wide RGB D65 conversion.",
"r",
"=",
"X",
"*",
"1.656492",
"-",
"Y",
"*",
"0.354851",
"-",
"Z",
"*",
"0.255038",
"g",
"=",
"-",
"X",
"*",
"0.707196",
"+",
"Y",
"*",
"1.655397",
"+",
"Z",
"*",
"0.036152",
"b",
"=",
"X",
"*",
"0.051713",
"-",
"Y",
"*",
"0.121364",
"+",
"Z",
"*",
"1.011530",
"# Apply reverse gamma correction.",
"r",
",",
"g",
",",
"b",
"=",
"map",
"(",
"lambda",
"x",
":",
"(",
"12.92",
"*",
"x",
")",
"if",
"(",
"x",
"<=",
"0.0031308",
")",
"else",
"(",
"(",
"1.0",
"+",
"0.055",
")",
"*",
"pow",
"(",
"x",
",",
"(",
"1.0",
"/",
"2.4",
")",
")",
"-",
"0.055",
")",
",",
"[",
"r",
",",
"g",
",",
"b",
"]",
",",
")",
"# Bring all negative components to zero.",
"r",
",",
"g",
",",
"b",
"=",
"map",
"(",
"lambda",
"x",
":",
"max",
"(",
"0",
",",
"x",
")",
",",
"[",
"r",
",",
"g",
",",
"b",
"]",
")",
"# If one component is greater than 1, weight components by that value.",
"max_component",
"=",
"max",
"(",
"r",
",",
"g",
",",
"b",
")",
"if",
"max_component",
">",
"1",
":",
"r",
",",
"g",
",",
"b",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
"/",
"max_component",
",",
"[",
"r",
",",
"g",
",",
"b",
"]",
")",
"ir",
",",
"ig",
",",
"ib",
"=",
"map",
"(",
"lambda",
"x",
":",
"int",
"(",
"x",
"*",
"255",
")",
",",
"[",
"r",
",",
"g",
",",
"b",
"]",
")",
"return",
"(",
"ir",
",",
"ig",
",",
"ib",
")"
] | [
255,
0
] | [
300,
23
] | python | en | ['en', 'en', 'en'] | True |
color_hsb_to_RGB | (fH: float, fS: float, fB: float) | Convert a hsb into its rgb representation. | Convert a hsb into its rgb representation. | def color_hsb_to_RGB(fH: float, fS: float, fB: float) -> Tuple[int, int, int]:
"""Convert a hsb into its rgb representation."""
if fS == 0.0:
fV = int(fB * 255)
return fV, fV, fV
r = g = b = 0
h = fH / 60
f = h - float(math.floor(h))
p = fB * (1 - fS)
q = fB * (1 - fS * f)
t = fB * (1 - (fS * (1 - f)))
if int(h) == 0:
r = int(fB * 255)
g = int(t * 255)
b = int(p * 255)
elif int(h) == 1:
r = int(q * 255)
g = int(fB * 255)
b = int(p * 255)
elif int(h) == 2:
r = int(p * 255)
g = int(fB * 255)
b = int(t * 255)
elif int(h) == 3:
r = int(p * 255)
g = int(q * 255)
b = int(fB * 255)
elif int(h) == 4:
r = int(t * 255)
g = int(p * 255)
b = int(fB * 255)
elif int(h) == 5:
r = int(fB * 255)
g = int(p * 255)
b = int(q * 255)
return (r, g, b) | [
"def",
"color_hsb_to_RGB",
"(",
"fH",
":",
"float",
",",
"fS",
":",
"float",
",",
"fB",
":",
"float",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"if",
"fS",
"==",
"0.0",
":",
"fV",
"=",
"int",
"(",
"fB",
"*",
"255",
")",
"return",
"fV",
",",
"fV",
",",
"fV",
"r",
"=",
"g",
"=",
"b",
"=",
"0",
"h",
"=",
"fH",
"/",
"60",
"f",
"=",
"h",
"-",
"float",
"(",
"math",
".",
"floor",
"(",
"h",
")",
")",
"p",
"=",
"fB",
"*",
"(",
"1",
"-",
"fS",
")",
"q",
"=",
"fB",
"*",
"(",
"1",
"-",
"fS",
"*",
"f",
")",
"t",
"=",
"fB",
"*",
"(",
"1",
"-",
"(",
"fS",
"*",
"(",
"1",
"-",
"f",
")",
")",
")",
"if",
"int",
"(",
"h",
")",
"==",
"0",
":",
"r",
"=",
"int",
"(",
"fB",
"*",
"255",
")",
"g",
"=",
"int",
"(",
"t",
"*",
"255",
")",
"b",
"=",
"int",
"(",
"p",
"*",
"255",
")",
"elif",
"int",
"(",
"h",
")",
"==",
"1",
":",
"r",
"=",
"int",
"(",
"q",
"*",
"255",
")",
"g",
"=",
"int",
"(",
"fB",
"*",
"255",
")",
"b",
"=",
"int",
"(",
"p",
"*",
"255",
")",
"elif",
"int",
"(",
"h",
")",
"==",
"2",
":",
"r",
"=",
"int",
"(",
"p",
"*",
"255",
")",
"g",
"=",
"int",
"(",
"fB",
"*",
"255",
")",
"b",
"=",
"int",
"(",
"t",
"*",
"255",
")",
"elif",
"int",
"(",
"h",
")",
"==",
"3",
":",
"r",
"=",
"int",
"(",
"p",
"*",
"255",
")",
"g",
"=",
"int",
"(",
"q",
"*",
"255",
")",
"b",
"=",
"int",
"(",
"fB",
"*",
"255",
")",
"elif",
"int",
"(",
"h",
")",
"==",
"4",
":",
"r",
"=",
"int",
"(",
"t",
"*",
"255",
")",
"g",
"=",
"int",
"(",
"p",
"*",
"255",
")",
"b",
"=",
"int",
"(",
"fB",
"*",
"255",
")",
"elif",
"int",
"(",
"h",
")",
"==",
"5",
":",
"r",
"=",
"int",
"(",
"fB",
"*",
"255",
")",
"g",
"=",
"int",
"(",
"p",
"*",
"255",
")",
"b",
"=",
"int",
"(",
"q",
"*",
"255",
")",
"return",
"(",
"r",
",",
"g",
",",
"b",
")"
] | [
303,
0
] | [
341,
20
] | python | en | ['en', 'ca', 'en'] | True |
color_RGB_to_hsv | (iR: float, iG: float, iB: float) | Convert an rgb color to its hsv representation.
Hue is scaled 0-360
Sat is scaled 0-100
Val is scaled 0-100
| Convert an rgb color to its hsv representation. | def color_RGB_to_hsv(iR: float, iG: float, iB: float) -> Tuple[float, float, float]:
"""Convert an rgb color to its hsv representation.
Hue is scaled 0-360
Sat is scaled 0-100
Val is scaled 0-100
"""
fHSV = colorsys.rgb_to_hsv(iR / 255.0, iG / 255.0, iB / 255.0)
return round(fHSV[0] * 360, 3), round(fHSV[1] * 100, 3), round(fHSV[2] * 100, 3) | [
"def",
"color_RGB_to_hsv",
"(",
"iR",
":",
"float",
",",
"iG",
":",
"float",
",",
"iB",
":",
"float",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"fHSV",
"=",
"colorsys",
".",
"rgb_to_hsv",
"(",
"iR",
"/",
"255.0",
",",
"iG",
"/",
"255.0",
",",
"iB",
"/",
"255.0",
")",
"return",
"round",
"(",
"fHSV",
"[",
"0",
"]",
"*",
"360",
",",
"3",
")",
",",
"round",
"(",
"fHSV",
"[",
"1",
"]",
"*",
"100",
",",
"3",
")",
",",
"round",
"(",
"fHSV",
"[",
"2",
"]",
"*",
"100",
",",
"3",
")"
] | [
344,
0
] | [
352,
84
] | python | en | ['en', 'en', 'en'] | True |
color_RGB_to_hs | (iR: float, iG: float, iB: float) | Convert an rgb color to its hs representation. | Convert an rgb color to its hs representation. | def color_RGB_to_hs(iR: float, iG: float, iB: float) -> Tuple[float, float]:
"""Convert an rgb color to its hs representation."""
return color_RGB_to_hsv(iR, iG, iB)[:2] | [
"def",
"color_RGB_to_hs",
"(",
"iR",
":",
"float",
",",
"iG",
":",
"float",
",",
"iB",
":",
"float",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"return",
"color_RGB_to_hsv",
"(",
"iR",
",",
"iG",
",",
"iB",
")",
"[",
":",
"2",
"]"
] | [
355,
0
] | [
357,
43
] | python | en | ['en', 'en', 'en'] | True |
color_hsv_to_RGB | (iH: float, iS: float, iV: float) | Convert an hsv color into its rgb representation.
Hue is scaled 0-360
Sat is scaled 0-100
Val is scaled 0-100
| Convert an hsv color into its rgb representation. | def color_hsv_to_RGB(iH: float, iS: float, iV: float) -> Tuple[int, int, int]:
"""Convert an hsv color into its rgb representation.
Hue is scaled 0-360
Sat is scaled 0-100
Val is scaled 0-100
"""
fRGB = colorsys.hsv_to_rgb(iH / 360, iS / 100, iV / 100)
return (int(fRGB[0] * 255), int(fRGB[1] * 255), int(fRGB[2] * 255)) | [
"def",
"color_hsv_to_RGB",
"(",
"iH",
":",
"float",
",",
"iS",
":",
"float",
",",
"iV",
":",
"float",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"fRGB",
"=",
"colorsys",
".",
"hsv_to_rgb",
"(",
"iH",
"/",
"360",
",",
"iS",
"/",
"100",
",",
"iV",
"/",
"100",
")",
"return",
"(",
"int",
"(",
"fRGB",
"[",
"0",
"]",
"*",
"255",
")",
",",
"int",
"(",
"fRGB",
"[",
"1",
"]",
"*",
"255",
")",
",",
"int",
"(",
"fRGB",
"[",
"2",
"]",
"*",
"255",
")",
")"
] | [
360,
0
] | [
368,
71
] | python | en | ['en', 'ca', 'en'] | True |
color_hs_to_RGB | (iH: float, iS: float) | Convert an hsv color into its rgb representation. | Convert an hsv color into its rgb representation. | def color_hs_to_RGB(iH: float, iS: float) -> Tuple[int, int, int]:
"""Convert an hsv color into its rgb representation."""
return color_hsv_to_RGB(iH, iS, 100) | [
"def",
"color_hs_to_RGB",
"(",
"iH",
":",
"float",
",",
"iS",
":",
"float",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"return",
"color_hsv_to_RGB",
"(",
"iH",
",",
"iS",
",",
"100",
")"
] | [
371,
0
] | [
373,
40
] | python | en | ['en', 'ca', 'en'] | True |
color_xy_to_hs | (
vX: float, vY: float, Gamut: Optional[GamutType] = None
) | Convert an xy color to its hs representation. | Convert an xy color to its hs representation. | def color_xy_to_hs(
vX: float, vY: float, Gamut: Optional[GamutType] = None
) -> Tuple[float, float]:
"""Convert an xy color to its hs representation."""
h, s, _ = color_RGB_to_hsv(*color_xy_to_RGB(vX, vY, Gamut))
return h, s | [
"def",
"color_xy_to_hs",
"(",
"vX",
":",
"float",
",",
"vY",
":",
"float",
",",
"Gamut",
":",
"Optional",
"[",
"GamutType",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"h",
",",
"s",
",",
"_",
"=",
"color_RGB_to_hsv",
"(",
"*",
"color_xy_to_RGB",
"(",
"vX",
",",
"vY",
",",
"Gamut",
")",
")",
"return",
"h",
",",
"s"
] | [
376,
0
] | [
381,
15
] | python | en | ['en', 'en', 'en'] | True |
color_hs_to_xy | (
iH: float, iS: float, Gamut: Optional[GamutType] = None
) | Convert an hs color to its xy representation. | Convert an hs color to its xy representation. | def color_hs_to_xy(
iH: float, iS: float, Gamut: Optional[GamutType] = None
) -> Tuple[float, float]:
"""Convert an hs color to its xy representation."""
return color_RGB_to_xy(*color_hs_to_RGB(iH, iS), Gamut) | [
"def",
"color_hs_to_xy",
"(",
"iH",
":",
"float",
",",
"iS",
":",
"float",
",",
"Gamut",
":",
"Optional",
"[",
"GamutType",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"return",
"color_RGB_to_xy",
"(",
"*",
"color_hs_to_RGB",
"(",
"iH",
",",
"iS",
")",
",",
"Gamut",
")"
] | [
384,
0
] | [
388,
59
] | python | en | ['en', 'en', 'en'] | True |
_match_max_scale | (input_colors: Tuple, output_colors: Tuple) | Match the maximum value of the output to the input. | Match the maximum value of the output to the input. | def _match_max_scale(input_colors: Tuple, output_colors: Tuple) -> Tuple:
"""Match the maximum value of the output to the input."""
max_in = max(input_colors)
max_out = max(output_colors)
if max_out == 0:
factor = 0.0
else:
factor = max_in / max_out
return tuple(int(round(i * factor)) for i in output_colors) | [
"def",
"_match_max_scale",
"(",
"input_colors",
":",
"Tuple",
",",
"output_colors",
":",
"Tuple",
")",
"->",
"Tuple",
":",
"max_in",
"=",
"max",
"(",
"input_colors",
")",
"max_out",
"=",
"max",
"(",
"output_colors",
")",
"if",
"max_out",
"==",
"0",
":",
"factor",
"=",
"0.0",
"else",
":",
"factor",
"=",
"max_in",
"/",
"max_out",
"return",
"tuple",
"(",
"int",
"(",
"round",
"(",
"i",
"*",
"factor",
")",
")",
"for",
"i",
"in",
"output_colors",
")"
] | [
391,
0
] | [
399,
63
] | python | en | ['en', 'en', 'en'] | True |
color_rgb_to_rgbw | (r: int, g: int, b: int) | Convert an rgb color to an rgbw representation. | Convert an rgb color to an rgbw representation. | def color_rgb_to_rgbw(r: int, g: int, b: int) -> Tuple[int, int, int, int]:
"""Convert an rgb color to an rgbw representation."""
# Calculate the white channel as the minimum of input rgb channels.
# Subtract the white portion from the remaining rgb channels.
w = min(r, g, b)
rgbw = (r - w, g - w, b - w, w)
# Match the output maximum value to the input. This ensures the full
# channel range is used.
return _match_max_scale((r, g, b), rgbw) | [
"def",
"color_rgb_to_rgbw",
"(",
"r",
":",
"int",
",",
"g",
":",
"int",
",",
"b",
":",
"int",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
",",
"int",
"]",
":",
"# Calculate the white channel as the minimum of input rgb channels.",
"# Subtract the white portion from the remaining rgb channels.",
"w",
"=",
"min",
"(",
"r",
",",
"g",
",",
"b",
")",
"rgbw",
"=",
"(",
"r",
"-",
"w",
",",
"g",
"-",
"w",
",",
"b",
"-",
"w",
",",
"w",
")",
"# Match the output maximum value to the input. This ensures the full",
"# channel range is used.",
"return",
"_match_max_scale",
"(",
"(",
"r",
",",
"g",
",",
"b",
")",
",",
"rgbw",
")"
] | [
402,
0
] | [
411,
44
] | python | en | ['en', 'en', 'en'] | True |
color_rgbw_to_rgb | (r: int, g: int, b: int, w: int) | Convert an rgbw color to an rgb representation. | Convert an rgbw color to an rgb representation. | def color_rgbw_to_rgb(r: int, g: int, b: int, w: int) -> Tuple[int, int, int]:
"""Convert an rgbw color to an rgb representation."""
# Add the white channel back into the rgb channels.
rgb = (r + w, g + w, b + w)
# Match the output maximum value to the input. This ensures the
# output doesn't overflow.
return _match_max_scale((r, g, b, w), rgb) | [
"def",
"color_rgbw_to_rgb",
"(",
"r",
":",
"int",
",",
"g",
":",
"int",
",",
"b",
":",
"int",
",",
"w",
":",
"int",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
":",
"# Add the white channel back into the rgb channels.",
"rgb",
"=",
"(",
"r",
"+",
"w",
",",
"g",
"+",
"w",
",",
"b",
"+",
"w",
")",
"# Match the output maximum value to the input. This ensures the",
"# output doesn't overflow.",
"return",
"_match_max_scale",
"(",
"(",
"r",
",",
"g",
",",
"b",
",",
"w",
")",
",",
"rgb",
")"
] | [
414,
0
] | [
421,
46
] | python | en | ['en', 'en', 'en'] | True |
color_rgb_to_hex | (r: int, g: int, b: int) | Return a RGB color from a hex color string. | Return a RGB color from a hex color string. | def color_rgb_to_hex(r: int, g: int, b: int) -> str:
"""Return a RGB color from a hex color string."""
return "{:02x}{:02x}{:02x}".format(round(r), round(g), round(b)) | [
"def",
"color_rgb_to_hex",
"(",
"r",
":",
"int",
",",
"g",
":",
"int",
",",
"b",
":",
"int",
")",
"->",
"str",
":",
"return",
"\"{:02x}{:02x}{:02x}\"",
".",
"format",
"(",
"round",
"(",
"r",
")",
",",
"round",
"(",
"g",
")",
",",
"round",
"(",
"b",
")",
")"
] | [
424,
0
] | [
426,
68
] | python | en | ['en', 'en', 'en'] | True |
rgb_hex_to_rgb_list | (hex_string: str) | Return an RGB color value list from a hex color string. | Return an RGB color value list from a hex color string. | def rgb_hex_to_rgb_list(hex_string: str) -> List[int]:
"""Return an RGB color value list from a hex color string."""
return [
int(hex_string[i : i + len(hex_string) // 3], 16)
for i in range(0, len(hex_string), len(hex_string) // 3)
] | [
"def",
"rgb_hex_to_rgb_list",
"(",
"hex_string",
":",
"str",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"[",
"int",
"(",
"hex_string",
"[",
"i",
":",
"i",
"+",
"len",
"(",
"hex_string",
")",
"//",
"3",
"]",
",",
"16",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"hex_string",
")",
",",
"len",
"(",
"hex_string",
")",
"//",
"3",
")",
"]"
] | [
429,
0
] | [
434,
5
] | python | en | ['en', 'en', 'en'] | True |
color_temperature_to_hs | (color_temperature_kelvin: float) | Return an hs color from a color temperature in Kelvin. | Return an hs color from a color temperature in Kelvin. | def color_temperature_to_hs(color_temperature_kelvin: float) -> Tuple[float, float]:
"""Return an hs color from a color temperature in Kelvin."""
return color_RGB_to_hs(*color_temperature_to_rgb(color_temperature_kelvin)) | [
"def",
"color_temperature_to_hs",
"(",
"color_temperature_kelvin",
":",
"float",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"return",
"color_RGB_to_hs",
"(",
"*",
"color_temperature_to_rgb",
"(",
"color_temperature_kelvin",
")",
")"
] | [
437,
0
] | [
439,
79
] | python | en | ['en', 'en', 'en'] | True |
color_temperature_to_rgb | (
color_temperature_kelvin: float,
) |
Return an RGB color from a color temperature in Kelvin.
This is a rough approximation based on the formula provided by T. Helland
http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
|
Return an RGB color from a color temperature in Kelvin. | def color_temperature_to_rgb(
color_temperature_kelvin: float,
) -> Tuple[float, float, float]:
"""
Return an RGB color from a color temperature in Kelvin.
This is a rough approximation based on the formula provided by T. Helland
http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
"""
# range check
if color_temperature_kelvin < 1000:
color_temperature_kelvin = 1000
elif color_temperature_kelvin > 40000:
color_temperature_kelvin = 40000
tmp_internal = color_temperature_kelvin / 100.0
red = _get_red(tmp_internal)
green = _get_green(tmp_internal)
blue = _get_blue(tmp_internal)
return red, green, blue | [
"def",
"color_temperature_to_rgb",
"(",
"color_temperature_kelvin",
":",
"float",
",",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"# range check",
"if",
"color_temperature_kelvin",
"<",
"1000",
":",
"color_temperature_kelvin",
"=",
"1000",
"elif",
"color_temperature_kelvin",
">",
"40000",
":",
"color_temperature_kelvin",
"=",
"40000",
"tmp_internal",
"=",
"color_temperature_kelvin",
"/",
"100.0",
"red",
"=",
"_get_red",
"(",
"tmp_internal",
")",
"green",
"=",
"_get_green",
"(",
"tmp_internal",
")",
"blue",
"=",
"_get_blue",
"(",
"tmp_internal",
")",
"return",
"red",
",",
"green",
",",
"blue"
] | [
442,
0
] | [
465,
27
] | python | en | ['en', 'error', 'th'] | False |
_bound | (color_component: float, minimum: float = 0, maximum: float = 255) |
Bound the given color component value between the given min and max values.
The minimum and maximum values will be included in the valid output.
i.e. Given a color_component of 0 and a minimum of 10, the returned value
will be 10.
|
Bound the given color component value between the given min and max values. | def _bound(color_component: float, minimum: float = 0, maximum: float = 255) -> float:
"""
Bound the given color component value between the given min and max values.
The minimum and maximum values will be included in the valid output.
i.e. Given a color_component of 0 and a minimum of 10, the returned value
will be 10.
"""
color_component_out = max(color_component, minimum)
return min(color_component_out, maximum) | [
"def",
"_bound",
"(",
"color_component",
":",
"float",
",",
"minimum",
":",
"float",
"=",
"0",
",",
"maximum",
":",
"float",
"=",
"255",
")",
"->",
"float",
":",
"color_component_out",
"=",
"max",
"(",
"color_component",
",",
"minimum",
")",
"return",
"min",
"(",
"color_component_out",
",",
"maximum",
")"
] | [
468,
0
] | [
477,
44
] | python | en | ['en', 'error', 'th'] | False |
_get_red | (temperature: float) | Get the red component of the temperature in RGB space. | Get the red component of the temperature in RGB space. | def _get_red(temperature: float) -> float:
"""Get the red component of the temperature in RGB space."""
if temperature <= 66:
return 255
tmp_red = 329.698727446 * math.pow(temperature - 60, -0.1332047592)
return _bound(tmp_red) | [
"def",
"_get_red",
"(",
"temperature",
":",
"float",
")",
"->",
"float",
":",
"if",
"temperature",
"<=",
"66",
":",
"return",
"255",
"tmp_red",
"=",
"329.698727446",
"*",
"math",
".",
"pow",
"(",
"temperature",
"-",
"60",
",",
"-",
"0.1332047592",
")",
"return",
"_bound",
"(",
"tmp_red",
")"
] | [
480,
0
] | [
485,
26
] | python | en | ['en', 'en', 'en'] | True |
_get_green | (temperature: float) | Get the green component of the given color temp in RGB space. | Get the green component of the given color temp in RGB space. | def _get_green(temperature: float) -> float:
"""Get the green component of the given color temp in RGB space."""
if temperature <= 66:
green = 99.4708025861 * math.log(temperature) - 161.1195681661
else:
green = 288.1221695283 * math.pow(temperature - 60, -0.0755148492)
return _bound(green) | [
"def",
"_get_green",
"(",
"temperature",
":",
"float",
")",
"->",
"float",
":",
"if",
"temperature",
"<=",
"66",
":",
"green",
"=",
"99.4708025861",
"*",
"math",
".",
"log",
"(",
"temperature",
")",
"-",
"161.1195681661",
"else",
":",
"green",
"=",
"288.1221695283",
"*",
"math",
".",
"pow",
"(",
"temperature",
"-",
"60",
",",
"-",
"0.0755148492",
")",
"return",
"_bound",
"(",
"green",
")"
] | [
488,
0
] | [
494,
24
] | python | en | ['en', 'en', 'en'] | True |
_get_blue | (temperature: float) | Get the blue component of the given color temperature in RGB space. | Get the blue component of the given color temperature in RGB space. | def _get_blue(temperature: float) -> float:
"""Get the blue component of the given color temperature in RGB space."""
if temperature >= 66:
return 255
if temperature <= 19:
return 0
blue = 138.5177312231 * math.log(temperature - 10) - 305.0447927307
return _bound(blue) | [
"def",
"_get_blue",
"(",
"temperature",
":",
"float",
")",
"->",
"float",
":",
"if",
"temperature",
">=",
"66",
":",
"return",
"255",
"if",
"temperature",
"<=",
"19",
":",
"return",
"0",
"blue",
"=",
"138.5177312231",
"*",
"math",
".",
"log",
"(",
"temperature",
"-",
"10",
")",
"-",
"305.0447927307",
"return",
"_bound",
"(",
"blue",
")"
] | [
497,
0
] | [
504,
23
] | python | en | ['en', 'en', 'en'] | True |
color_temperature_mired_to_kelvin | (mired_temperature: float) | Convert absolute mired shift to degrees kelvin. | Convert absolute mired shift to degrees kelvin. | def color_temperature_mired_to_kelvin(mired_temperature: float) -> float:
"""Convert absolute mired shift to degrees kelvin."""
return math.floor(1000000 / mired_temperature) | [
"def",
"color_temperature_mired_to_kelvin",
"(",
"mired_temperature",
":",
"float",
")",
"->",
"float",
":",
"return",
"math",
".",
"floor",
"(",
"1000000",
"/",
"mired_temperature",
")"
] | [
507,
0
] | [
509,
50
] | python | en | ['en', 'en', 'en'] | True |
color_temperature_kelvin_to_mired | (kelvin_temperature: float) | Convert degrees kelvin to mired shift. | Convert degrees kelvin to mired shift. | def color_temperature_kelvin_to_mired(kelvin_temperature: float) -> float:
"""Convert degrees kelvin to mired shift."""
return math.floor(1000000 / kelvin_temperature) | [
"def",
"color_temperature_kelvin_to_mired",
"(",
"kelvin_temperature",
":",
"float",
")",
"->",
"float",
":",
"return",
"math",
".",
"floor",
"(",
"1000000",
"/",
"kelvin_temperature",
")"
] | [
512,
0
] | [
514,
51
] | python | en | ['en', 'en', 'en'] | True |
cross_product | (p1: XYPoint, p2: XYPoint) | Calculate the cross product of two XYPoints. | Calculate the cross product of two XYPoints. | def cross_product(p1: XYPoint, p2: XYPoint) -> float:
"""Calculate the cross product of two XYPoints."""
return float(p1.x * p2.y - p1.y * p2.x) | [
"def",
"cross_product",
"(",
"p1",
":",
"XYPoint",
",",
"p2",
":",
"XYPoint",
")",
"->",
"float",
":",
"return",
"float",
"(",
"p1",
".",
"x",
"*",
"p2",
".",
"y",
"-",
"p1",
".",
"y",
"*",
"p2",
".",
"x",
")"
] | [
520,
0
] | [
522,
43
] | python | en | ['en', 'en', 'en'] | True |
get_distance_between_two_points | (one: XYPoint, two: XYPoint) | Calculate the distance between two XYPoints. | Calculate the distance between two XYPoints. | def get_distance_between_two_points(one: XYPoint, two: XYPoint) -> float:
"""Calculate the distance between two XYPoints."""
dx = one.x - two.x
dy = one.y - two.y
return math.sqrt(dx * dx + dy * dy) | [
"def",
"get_distance_between_two_points",
"(",
"one",
":",
"XYPoint",
",",
"two",
":",
"XYPoint",
")",
"->",
"float",
":",
"dx",
"=",
"one",
".",
"x",
"-",
"two",
".",
"x",
"dy",
"=",
"one",
".",
"y",
"-",
"two",
".",
"y",
"return",
"math",
".",
"sqrt",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")"
] | [
525,
0
] | [
529,
39
] | python | en | ['en', 'en', 'en'] | True |
get_closest_point_to_line | (A: XYPoint, B: XYPoint, P: XYPoint) |
Find the closest point from P to a line defined by A and B.
This point will be reproducible by the lamp
as it is on the edge of the gamut.
|
Find the closest point from P to a line defined by A and B. | def get_closest_point_to_line(A: XYPoint, B: XYPoint, P: XYPoint) -> XYPoint:
"""
Find the closest point from P to a line defined by A and B.
This point will be reproducible by the lamp
as it is on the edge of the gamut.
"""
AP = XYPoint(P.x - A.x, P.y - A.y)
AB = XYPoint(B.x - A.x, B.y - A.y)
ab2 = AB.x * AB.x + AB.y * AB.y
ap_ab = AP.x * AB.x + AP.y * AB.y
t = ap_ab / ab2
if t < 0.0:
t = 0.0
elif t > 1.0:
t = 1.0
return XYPoint(A.x + AB.x * t, A.y + AB.y * t) | [
"def",
"get_closest_point_to_line",
"(",
"A",
":",
"XYPoint",
",",
"B",
":",
"XYPoint",
",",
"P",
":",
"XYPoint",
")",
"->",
"XYPoint",
":",
"AP",
"=",
"XYPoint",
"(",
"P",
".",
"x",
"-",
"A",
".",
"x",
",",
"P",
".",
"y",
"-",
"A",
".",
"y",
")",
"AB",
"=",
"XYPoint",
"(",
"B",
".",
"x",
"-",
"A",
".",
"x",
",",
"B",
".",
"y",
"-",
"A",
".",
"y",
")",
"ab2",
"=",
"AB",
".",
"x",
"*",
"AB",
".",
"x",
"+",
"AB",
".",
"y",
"*",
"AB",
".",
"y",
"ap_ab",
"=",
"AP",
".",
"x",
"*",
"AB",
".",
"x",
"+",
"AP",
".",
"y",
"*",
"AB",
".",
"y",
"t",
"=",
"ap_ab",
"/",
"ab2",
"if",
"t",
"<",
"0.0",
":",
"t",
"=",
"0.0",
"elif",
"t",
">",
"1.0",
":",
"t",
"=",
"1.0",
"return",
"XYPoint",
"(",
"A",
".",
"x",
"+",
"AB",
".",
"x",
"*",
"t",
",",
"A",
".",
"y",
"+",
"AB",
".",
"y",
"*",
"t",
")"
] | [
532,
0
] | [
550,
50
] | python | en | ['en', 'error', 'th'] | False |
get_closest_point_to_point | (
xy_tuple: Tuple[float, float], Gamut: GamutType
) |
Get the closest matching color within the gamut of the light.
Should only be used if the supplied color is outside of the color gamut.
|
Get the closest matching color within the gamut of the light. | def get_closest_point_to_point(
xy_tuple: Tuple[float, float], Gamut: GamutType
) -> Tuple[float, float]:
"""
Get the closest matching color within the gamut of the light.
Should only be used if the supplied color is outside of the color gamut.
"""
xy_point = XYPoint(xy_tuple[0], xy_tuple[1])
# find the closest point on each line in the CIE 1931 'triangle'.
pAB = get_closest_point_to_line(Gamut.red, Gamut.green, xy_point)
pAC = get_closest_point_to_line(Gamut.blue, Gamut.red, xy_point)
pBC = get_closest_point_to_line(Gamut.green, Gamut.blue, xy_point)
# Get the distances per point and see which point is closer to our Point.
dAB = get_distance_between_two_points(xy_point, pAB)
dAC = get_distance_between_two_points(xy_point, pAC)
dBC = get_distance_between_two_points(xy_point, pBC)
lowest = dAB
closest_point = pAB
if dAC < lowest:
lowest = dAC
closest_point = pAC
if dBC < lowest:
lowest = dBC
closest_point = pBC
# Change the xy value to a value which is within the reach of the lamp.
cx = closest_point.x
cy = closest_point.y
return (cx, cy) | [
"def",
"get_closest_point_to_point",
"(",
"xy_tuple",
":",
"Tuple",
"[",
"float",
",",
"float",
"]",
",",
"Gamut",
":",
"GamutType",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"xy_point",
"=",
"XYPoint",
"(",
"xy_tuple",
"[",
"0",
"]",
",",
"xy_tuple",
"[",
"1",
"]",
")",
"# find the closest point on each line in the CIE 1931 'triangle'.",
"pAB",
"=",
"get_closest_point_to_line",
"(",
"Gamut",
".",
"red",
",",
"Gamut",
".",
"green",
",",
"xy_point",
")",
"pAC",
"=",
"get_closest_point_to_line",
"(",
"Gamut",
".",
"blue",
",",
"Gamut",
".",
"red",
",",
"xy_point",
")",
"pBC",
"=",
"get_closest_point_to_line",
"(",
"Gamut",
".",
"green",
",",
"Gamut",
".",
"blue",
",",
"xy_point",
")",
"# Get the distances per point and see which point is closer to our Point.",
"dAB",
"=",
"get_distance_between_two_points",
"(",
"xy_point",
",",
"pAB",
")",
"dAC",
"=",
"get_distance_between_two_points",
"(",
"xy_point",
",",
"pAC",
")",
"dBC",
"=",
"get_distance_between_two_points",
"(",
"xy_point",
",",
"pBC",
")",
"lowest",
"=",
"dAB",
"closest_point",
"=",
"pAB",
"if",
"dAC",
"<",
"lowest",
":",
"lowest",
"=",
"dAC",
"closest_point",
"=",
"pAC",
"if",
"dBC",
"<",
"lowest",
":",
"lowest",
"=",
"dBC",
"closest_point",
"=",
"pBC",
"# Change the xy value to a value which is within the reach of the lamp.",
"cx",
"=",
"closest_point",
".",
"x",
"cy",
"=",
"closest_point",
".",
"y",
"return",
"(",
"cx",
",",
"cy",
")"
] | [
553,
0
] | [
588,
19
] | python | en | ['en', 'error', 'th'] | False |
check_point_in_lamps_reach | (p: Tuple[float, float], Gamut: GamutType) | Check if the provided XYPoint can be recreated by a Hue lamp. | Check if the provided XYPoint can be recreated by a Hue lamp. | def check_point_in_lamps_reach(p: Tuple[float, float], Gamut: GamutType) -> bool:
"""Check if the provided XYPoint can be recreated by a Hue lamp."""
v1 = XYPoint(Gamut.green.x - Gamut.red.x, Gamut.green.y - Gamut.red.y)
v2 = XYPoint(Gamut.blue.x - Gamut.red.x, Gamut.blue.y - Gamut.red.y)
q = XYPoint(p[0] - Gamut.red.x, p[1] - Gamut.red.y)
s = cross_product(q, v2) / cross_product(v1, v2)
t = cross_product(v1, q) / cross_product(v1, v2)
return (s >= 0.0) and (t >= 0.0) and (s + t <= 1.0) | [
"def",
"check_point_in_lamps_reach",
"(",
"p",
":",
"Tuple",
"[",
"float",
",",
"float",
"]",
",",
"Gamut",
":",
"GamutType",
")",
"->",
"bool",
":",
"v1",
"=",
"XYPoint",
"(",
"Gamut",
".",
"green",
".",
"x",
"-",
"Gamut",
".",
"red",
".",
"x",
",",
"Gamut",
".",
"green",
".",
"y",
"-",
"Gamut",
".",
"red",
".",
"y",
")",
"v2",
"=",
"XYPoint",
"(",
"Gamut",
".",
"blue",
".",
"x",
"-",
"Gamut",
".",
"red",
".",
"x",
",",
"Gamut",
".",
"blue",
".",
"y",
"-",
"Gamut",
".",
"red",
".",
"y",
")",
"q",
"=",
"XYPoint",
"(",
"p",
"[",
"0",
"]",
"-",
"Gamut",
".",
"red",
".",
"x",
",",
"p",
"[",
"1",
"]",
"-",
"Gamut",
".",
"red",
".",
"y",
")",
"s",
"=",
"cross_product",
"(",
"q",
",",
"v2",
")",
"/",
"cross_product",
"(",
"v1",
",",
"v2",
")",
"t",
"=",
"cross_product",
"(",
"v1",
",",
"q",
")",
"/",
"cross_product",
"(",
"v1",
",",
"v2",
")",
"return",
"(",
"s",
">=",
"0.0",
")",
"and",
"(",
"t",
">=",
"0.0",
")",
"and",
"(",
"s",
"+",
"t",
"<=",
"1.0",
")"
] | [
591,
0
] | [
600,
55
] | python | en | ['en', 'en', 'en'] | True |
check_valid_gamut | (Gamut: GamutType) | Check if the supplied gamut is valid. | Check if the supplied gamut is valid. | def check_valid_gamut(Gamut: GamutType) -> bool:
"""Check if the supplied gamut is valid."""
# Check if the three points of the supplied gamut are not on the same line.
v1 = XYPoint(Gamut.green.x - Gamut.red.x, Gamut.green.y - Gamut.red.y)
v2 = XYPoint(Gamut.blue.x - Gamut.red.x, Gamut.blue.y - Gamut.red.y)
not_on_line = cross_product(v1, v2) > 0.0001
# Check if all six coordinates of the gamut lie between 0 and 1.
red_valid = (
Gamut.red.x >= 0 and Gamut.red.x <= 1 and Gamut.red.y >= 0 and Gamut.red.y <= 1
)
green_valid = (
Gamut.green.x >= 0
and Gamut.green.x <= 1
and Gamut.green.y >= 0
and Gamut.green.y <= 1
)
blue_valid = (
Gamut.blue.x >= 0
and Gamut.blue.x <= 1
and Gamut.blue.y >= 0
and Gamut.blue.y <= 1
)
return not_on_line and red_valid and green_valid and blue_valid | [
"def",
"check_valid_gamut",
"(",
"Gamut",
":",
"GamutType",
")",
"->",
"bool",
":",
"# Check if the three points of the supplied gamut are not on the same line.",
"v1",
"=",
"XYPoint",
"(",
"Gamut",
".",
"green",
".",
"x",
"-",
"Gamut",
".",
"red",
".",
"x",
",",
"Gamut",
".",
"green",
".",
"y",
"-",
"Gamut",
".",
"red",
".",
"y",
")",
"v2",
"=",
"XYPoint",
"(",
"Gamut",
".",
"blue",
".",
"x",
"-",
"Gamut",
".",
"red",
".",
"x",
",",
"Gamut",
".",
"blue",
".",
"y",
"-",
"Gamut",
".",
"red",
".",
"y",
")",
"not_on_line",
"=",
"cross_product",
"(",
"v1",
",",
"v2",
")",
">",
"0.0001",
"# Check if all six coordinates of the gamut lie between 0 and 1.",
"red_valid",
"=",
"(",
"Gamut",
".",
"red",
".",
"x",
">=",
"0",
"and",
"Gamut",
".",
"red",
".",
"x",
"<=",
"1",
"and",
"Gamut",
".",
"red",
".",
"y",
">=",
"0",
"and",
"Gamut",
".",
"red",
".",
"y",
"<=",
"1",
")",
"green_valid",
"=",
"(",
"Gamut",
".",
"green",
".",
"x",
">=",
"0",
"and",
"Gamut",
".",
"green",
".",
"x",
"<=",
"1",
"and",
"Gamut",
".",
"green",
".",
"y",
">=",
"0",
"and",
"Gamut",
".",
"green",
".",
"y",
"<=",
"1",
")",
"blue_valid",
"=",
"(",
"Gamut",
".",
"blue",
".",
"x",
">=",
"0",
"and",
"Gamut",
".",
"blue",
".",
"x",
"<=",
"1",
"and",
"Gamut",
".",
"blue",
".",
"y",
">=",
"0",
"and",
"Gamut",
".",
"blue",
".",
"y",
"<=",
"1",
")",
"return",
"not_on_line",
"and",
"red_valid",
"and",
"green_valid",
"and",
"blue_valid"
] | [
603,
0
] | [
627,
67
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the SAJ sensors. | Set up the SAJ sensors. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the SAJ sensors."""
remove_interval_update = None
wifi = config[CONF_TYPE] == INVERTER_TYPES[1]
# Init all sensors
sensor_def = pysaj.Sensors(wifi)
# Use all sensors by default
hass_sensors = []
kwargs = {}
if wifi:
kwargs["wifi"] = True
if config.get(CONF_USERNAME) and config.get(CONF_PASSWORD):
kwargs["username"] = config[CONF_USERNAME]
kwargs["password"] = config[CONF_PASSWORD]
try:
saj = pysaj.SAJ(config[CONF_HOST], **kwargs)
done = await saj.read(sensor_def)
except pysaj.UnauthorizedException:
_LOGGER.error("Username and/or password is wrong")
return
except pysaj.UnexpectedResponseException as err:
_LOGGER.error(
"Error in SAJ, please check host/ip address. Original error: %s", err
)
return
if not done:
raise PlatformNotReady
for sensor in sensor_def:
if sensor.enabled:
hass_sensors.append(
SAJsensor(saj.serialnumber, sensor, inverter_name=config.get(CONF_NAME))
)
async_add_entities(hass_sensors)
async def async_saj():
"""Update all the SAJ sensors."""
values = await saj.read(sensor_def)
for sensor in hass_sensors:
state_unknown = False
if not values:
# SAJ inverters are powered by DC via solar panels and thus are
# offline after the sun has set. If a sensor resets on a daily
# basis like "today_yield", this reset won't happen automatically.
# Code below checks if today > day when sensor was last updated
# and if so: set state to None.
# Sensors with live values like "temperature" or "current_power"
# will also be reset to None.
if (sensor.per_day_basis and date.today() > sensor.date_updated) or (
not sensor.per_day_basis and not sensor.per_total_basis
):
state_unknown = True
sensor.async_update_values(unknown_state=state_unknown)
return values
def start_update_interval(event):
"""Start the update interval scheduling."""
nonlocal remove_interval_update
remove_interval_update = async_track_time_interval_backoff(hass, async_saj)
def stop_update_interval(event):
"""Properly cancel the scheduled update."""
remove_interval_update() # pylint: disable=not-callable
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_update_interval)
hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, stop_update_interval) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"remove_interval_update",
"=",
"None",
"wifi",
"=",
"config",
"[",
"CONF_TYPE",
"]",
"==",
"INVERTER_TYPES",
"[",
"1",
"]",
"# Init all sensors",
"sensor_def",
"=",
"pysaj",
".",
"Sensors",
"(",
"wifi",
")",
"# Use all sensors by default",
"hass_sensors",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"if",
"wifi",
":",
"kwargs",
"[",
"\"wifi\"",
"]",
"=",
"True",
"if",
"config",
".",
"get",
"(",
"CONF_USERNAME",
")",
"and",
"config",
".",
"get",
"(",
"CONF_PASSWORD",
")",
":",
"kwargs",
"[",
"\"username\"",
"]",
"=",
"config",
"[",
"CONF_USERNAME",
"]",
"kwargs",
"[",
"\"password\"",
"]",
"=",
"config",
"[",
"CONF_PASSWORD",
"]",
"try",
":",
"saj",
"=",
"pysaj",
".",
"SAJ",
"(",
"config",
"[",
"CONF_HOST",
"]",
",",
"*",
"*",
"kwargs",
")",
"done",
"=",
"await",
"saj",
".",
"read",
"(",
"sensor_def",
")",
"except",
"pysaj",
".",
"UnauthorizedException",
":",
"_LOGGER",
".",
"error",
"(",
"\"Username and/or password is wrong\"",
")",
"return",
"except",
"pysaj",
".",
"UnexpectedResponseException",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error in SAJ, please check host/ip address. Original error: %s\"",
",",
"err",
")",
"return",
"if",
"not",
"done",
":",
"raise",
"PlatformNotReady",
"for",
"sensor",
"in",
"sensor_def",
":",
"if",
"sensor",
".",
"enabled",
":",
"hass_sensors",
".",
"append",
"(",
"SAJsensor",
"(",
"saj",
".",
"serialnumber",
",",
"sensor",
",",
"inverter_name",
"=",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
")",
")",
"async_add_entities",
"(",
"hass_sensors",
")",
"async",
"def",
"async_saj",
"(",
")",
":",
"\"\"\"Update all the SAJ sensors.\"\"\"",
"values",
"=",
"await",
"saj",
".",
"read",
"(",
"sensor_def",
")",
"for",
"sensor",
"in",
"hass_sensors",
":",
"state_unknown",
"=",
"False",
"if",
"not",
"values",
":",
"# SAJ inverters are powered by DC via solar panels and thus are",
"# offline after the sun has set. If a sensor resets on a daily",
"# basis like \"today_yield\", this reset won't happen automatically.",
"# Code below checks if today > day when sensor was last updated",
"# and if so: set state to None.",
"# Sensors with live values like \"temperature\" or \"current_power\"",
"# will also be reset to None.",
"if",
"(",
"sensor",
".",
"per_day_basis",
"and",
"date",
".",
"today",
"(",
")",
">",
"sensor",
".",
"date_updated",
")",
"or",
"(",
"not",
"sensor",
".",
"per_day_basis",
"and",
"not",
"sensor",
".",
"per_total_basis",
")",
":",
"state_unknown",
"=",
"True",
"sensor",
".",
"async_update_values",
"(",
"unknown_state",
"=",
"state_unknown",
")",
"return",
"values",
"def",
"start_update_interval",
"(",
"event",
")",
":",
"\"\"\"Start the update interval scheduling.\"\"\"",
"nonlocal",
"remove_interval_update",
"remove_interval_update",
"=",
"async_track_time_interval_backoff",
"(",
"hass",
",",
"async_saj",
")",
"def",
"stop_update_interval",
"(",
"event",
")",
":",
"\"\"\"Properly cancel the scheduled update.\"\"\"",
"remove_interval_update",
"(",
")",
"# pylint: disable=not-callable",
"hass",
".",
"bus",
".",
"async_listen_once",
"(",
"EVENT_HOMEASSISTANT_START",
",",
"start_update_interval",
")",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"stop_update_interval",
")"
] | [
58,
0
] | [
132,
73
] | python | en | ['en', 'sq', 'en'] | True |
async_track_time_interval_backoff | (hass, action) | Add a listener that fires repetitively and increases the interval when failed. | Add a listener that fires repetitively and increases the interval when failed. | def async_track_time_interval_backoff(hass, action) -> CALLBACK_TYPE:
"""Add a listener that fires repetitively and increases the interval when failed."""
remove = None
interval = MIN_INTERVAL
async def interval_listener(now=None):
"""Handle elapsed interval with backoff."""
nonlocal interval, remove
try:
if await action():
interval = MIN_INTERVAL
else:
interval = min(interval * 2, MAX_INTERVAL)
finally:
remove = async_call_later(hass, interval, interval_listener)
hass.async_create_task(interval_listener())
def remove_listener():
"""Remove interval listener."""
if remove:
remove() # pylint: disable=not-callable
return remove_listener | [
"def",
"async_track_time_interval_backoff",
"(",
"hass",
",",
"action",
")",
"->",
"CALLBACK_TYPE",
":",
"remove",
"=",
"None",
"interval",
"=",
"MIN_INTERVAL",
"async",
"def",
"interval_listener",
"(",
"now",
"=",
"None",
")",
":",
"\"\"\"Handle elapsed interval with backoff.\"\"\"",
"nonlocal",
"interval",
",",
"remove",
"try",
":",
"if",
"await",
"action",
"(",
")",
":",
"interval",
"=",
"MIN_INTERVAL",
"else",
":",
"interval",
"=",
"min",
"(",
"interval",
"*",
"2",
",",
"MAX_INTERVAL",
")",
"finally",
":",
"remove",
"=",
"async_call_later",
"(",
"hass",
",",
"interval",
",",
"interval_listener",
")",
"hass",
".",
"async_create_task",
"(",
"interval_listener",
"(",
")",
")",
"def",
"remove_listener",
"(",
")",
":",
"\"\"\"Remove interval listener.\"\"\"",
"if",
"remove",
":",
"remove",
"(",
")",
"# pylint: disable=not-callable",
"return",
"remove_listener"
] | [
136,
0
] | [
159,
26
] | python | en | ['en', 'en', 'en'] | True |
SAJsensor.__init__ | (self, serialnumber, pysaj_sensor, inverter_name=None) | Initialize the SAJ sensor. | Initialize the SAJ sensor. | def __init__(self, serialnumber, pysaj_sensor, inverter_name=None):
"""Initialize the SAJ sensor."""
self._sensor = pysaj_sensor
self._inverter_name = inverter_name
self._serialnumber = serialnumber
self._state = self._sensor.value | [
"def",
"__init__",
"(",
"self",
",",
"serialnumber",
",",
"pysaj_sensor",
",",
"inverter_name",
"=",
"None",
")",
":",
"self",
".",
"_sensor",
"=",
"pysaj_sensor",
"self",
".",
"_inverter_name",
"=",
"inverter_name",
"self",
".",
"_serialnumber",
"=",
"serialnumber",
"self",
".",
"_state",
"=",
"self",
".",
"_sensor",
".",
"value"
] | [
165,
4
] | [
170,
40
] | python | en | ['en', 'sq', 'en'] | True |
SAJsensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
if self._inverter_name:
return f"saj_{self._inverter_name}_{self._sensor.name}"
return f"saj_{self._sensor.name}" | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_inverter_name",
":",
"return",
"f\"saj_{self._inverter_name}_{self._sensor.name}\"",
"return",
"f\"saj_{self._sensor.name}\""
] | [
173,
4
] | [
178,
41
] | python | en | ['en', 'mi', 'en'] | True |
SAJsensor.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"
] | [
181,
4
] | [
183,
26
] | python | en | ['en', 'en', 'en'] | True |
SAJsensor.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 SAJ_UNIT_MAPPINGS[self._sensor.unit] | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"SAJ_UNIT_MAPPINGS",
"[",
"self",
".",
"_sensor",
".",
"unit",
"]"
] | [
186,
4
] | [
188,
51
] | python | en | ['en', 'en', 'en'] | True |
SAJsensor.device_class | (self) | Return the device class the sensor belongs to. | Return the device class the sensor belongs to. | def device_class(self):
"""Return the device class the sensor belongs to."""
if self.unit_of_measurement == POWER_WATT:
return DEVICE_CLASS_POWER
if (
self.unit_of_measurement == TEMP_CELSIUS
or self._sensor.unit == TEMP_FAHRENHEIT
):
return DEVICE_CLASS_TEMPERATURE | [
"def",
"device_class",
"(",
"self",
")",
":",
"if",
"self",
".",
"unit_of_measurement",
"==",
"POWER_WATT",
":",
"return",
"DEVICE_CLASS_POWER",
"if",
"(",
"self",
".",
"unit_of_measurement",
"==",
"TEMP_CELSIUS",
"or",
"self",
".",
"_sensor",
".",
"unit",
"==",
"TEMP_FAHRENHEIT",
")",
":",
"return",
"DEVICE_CLASS_TEMPERATURE"
] | [
191,
4
] | [
199,
43
] | python | en | ['en', 'zh-Latn', 'en'] | True |
SAJsensor.should_poll | (self) | SAJ sensors are updated & don't poll. | SAJ sensors are updated & don't poll. | def should_poll(self) -> bool:
"""SAJ sensors are updated & don't poll."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"False"
] | [
202,
4
] | [
204,
20
] | python | en | ['en', 'en', 'en'] | True |
SAJsensor.per_day_basis | (self) | Return if the sensors value is on daily basis or not. | Return if the sensors value is on daily basis or not. | def per_day_basis(self) -> bool:
"""Return if the sensors value is on daily basis or not."""
return self._sensor.per_day_basis | [
"def",
"per_day_basis",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_sensor",
".",
"per_day_basis"
] | [
207,
4
] | [
209,
41
] | python | en | ['en', 'en', 'en'] | True |
SAJsensor.per_total_basis | (self) | Return if the sensors value is cumulative or not. | Return if the sensors value is cumulative or not. | def per_total_basis(self) -> bool:
"""Return if the sensors value is cumulative or not."""
return self._sensor.per_total_basis | [
"def",
"per_total_basis",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_sensor",
".",
"per_total_basis"
] | [
212,
4
] | [
214,
43
] | python | en | ['en', 'en', 'en'] | True |
SAJsensor.date_updated | (self) | Return the date when the sensor was last updated. | Return the date when the sensor was last updated. | def date_updated(self) -> date:
"""Return the date when the sensor was last updated."""
return self._sensor.date | [
"def",
"date_updated",
"(",
"self",
")",
"->",
"date",
":",
"return",
"self",
".",
"_sensor",
".",
"date"
] | [
217,
4
] | [
219,
32
] | python | en | ['en', 'en', 'en'] | True |
SAJsensor.async_update_values | (self, unknown_state=False) | Update this sensor. | Update this sensor. | def async_update_values(self, unknown_state=False):
"""Update this sensor."""
update = False
if self._sensor.value != self._state:
update = True
self._state = self._sensor.value
if unknown_state and self._state is not None:
update = True
self._state = None
if update:
self.async_write_ha_state() | [
"def",
"async_update_values",
"(",
"self",
",",
"unknown_state",
"=",
"False",
")",
":",
"update",
"=",
"False",
"if",
"self",
".",
"_sensor",
".",
"value",
"!=",
"self",
".",
"_state",
":",
"update",
"=",
"True",
"self",
".",
"_state",
"=",
"self",
".",
"_sensor",
".",
"value",
"if",
"unknown_state",
"and",
"self",
".",
"_state",
"is",
"not",
"None",
":",
"update",
"=",
"True",
"self",
".",
"_state",
"=",
"None",
"if",
"update",
":",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
222,
4
] | [
235,
39
] | python | en | ['en', 'id', 'en'] | True |
SAJsensor.unique_id | (self) | Return a unique identifier for this sensor. | Return a unique identifier for this sensor. | def unique_id(self):
"""Return a unique identifier for this sensor."""
return f"{self._serialnumber}_{self._sensor.name}" | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"f\"{self._serialnumber}_{self._sensor.name}\""
] | [
238,
4
] | [
240,
58
] | python | en | ['en', 'fr', 'en'] | True |
get_config | () |
Get config from argument parser.
|
Get config from argument parser.
| def get_config():
'''
Get config from argument parser.
'''
parser = argparse.ArgumentParser(
description='This program is using genetic algorithm to search architecture for SQuAD.')
parser.add_argument('--input_file', type=str,
default='./train-v1.1.json', help='input file')
parser.add_argument('--dev_file', type=str,
default='./dev-v1.1.json', help='dev file')
parser.add_argument('--embedding_file', type=str,
default='./glove.840B.300d.txt', help='dev file')
parser.add_argument('--root_path', default='./data/',
type=str, help='Root path of models')
parser.add_argument('--batch_size', type=int, default=64, help='batch size')
parser.add_argument('--save_path', type=str,
default='./save', help='save path dir')
parser.add_argument('--learning_rate', type=float, default=0.0001,
help='set half of original learning rate reload data and train.')
parser.add_argument('--max_epoch', type=int, default=30)
parser.add_argument('--dropout_rate', type=float,
default=0.1, help='dropout_rate')
parser.add_argument('--labelsmoothing', type=float,
default=0.1, help='labelsmoothing')
parser.add_argument('--num_heads', type=int, default=1, help='num_heads')
parser.add_argument('--rnn_units', type=int, default=256, help='rnn_units')
args = parser.parse_args()
return args | [
"def",
"get_config",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'This program is using genetic algorithm to search architecture for SQuAD.'",
")",
"parser",
".",
"add_argument",
"(",
"'--input_file'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'./train-v1.1.json'",
",",
"help",
"=",
"'input file'",
")",
"parser",
".",
"add_argument",
"(",
"'--dev_file'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'./dev-v1.1.json'",
",",
"help",
"=",
"'dev file'",
")",
"parser",
".",
"add_argument",
"(",
"'--embedding_file'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'./glove.840B.300d.txt'",
",",
"help",
"=",
"'dev file'",
")",
"parser",
".",
"add_argument",
"(",
"'--root_path'",
",",
"default",
"=",
"'./data/'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'Root path of models'",
")",
"parser",
".",
"add_argument",
"(",
"'--batch_size'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"64",
",",
"help",
"=",
"'batch size'",
")",
"parser",
".",
"add_argument",
"(",
"'--save_path'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'./save'",
",",
"help",
"=",
"'save path dir'",
")",
"parser",
".",
"add_argument",
"(",
"'--learning_rate'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.0001",
",",
"help",
"=",
"'set half of original learning rate reload data and train.'",
")",
"parser",
".",
"add_argument",
"(",
"'--max_epoch'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"30",
")",
"parser",
".",
"add_argument",
"(",
"'--dropout_rate'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.1",
",",
"help",
"=",
"'dropout_rate'",
")",
"parser",
".",
"add_argument",
"(",
"'--labelsmoothing'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"0.1",
",",
"help",
"=",
"'labelsmoothing'",
")",
"parser",
".",
"add_argument",
"(",
"'--num_heads'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1",
",",
"help",
"=",
"'num_heads'",
")",
"parser",
".",
"add_argument",
"(",
"'--rnn_units'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"256",
",",
"help",
"=",
"'rnn_units'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"return",
"args"
] | [
46,
0
] | [
74,
15
] | python | en | ['en', 'error', 'th'] | False |
get_id | (word_dict, word) |
Return word id.
|
Return word id.
| def get_id(word_dict, word):
'''
Return word id.
'''
return word_dict.get(word, word_dict['<unk>']) | [
"def",
"get_id",
"(",
"word_dict",
",",
"word",
")",
":",
"return",
"word_dict",
".",
"get",
"(",
"word",
",",
"word_dict",
"[",
"'<unk>'",
"]",
")"
] | [
77,
0
] | [
81,
50
] | python | en | ['en', 'error', 'th'] | False |
load_embedding | (path) |
return embedding for a specific file by given file path.
|
return embedding for a specific file by given file path.
| def load_embedding(path):
'''
return embedding for a specific file by given file path.
'''
EMBEDDING_DIM = 300
embedding_dict = {}
with open(path, 'r', encoding='utf-8') as file:
pairs = [line.strip('\r\n').split() for line in file.readlines()]
for pair in pairs:
if len(pair) == EMBEDDING_DIM + 1:
embedding_dict[pair[0]] = [float(x) for x in pair[1:]]
logger.debug('embedding_dict size: %d', len(embedding_dict))
return embedding_dict | [
"def",
"load_embedding",
"(",
"path",
")",
":",
"EMBEDDING_DIM",
"=",
"300",
"embedding_dict",
"=",
"{",
"}",
"with",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"file",
":",
"pairs",
"=",
"[",
"line",
".",
"strip",
"(",
"'\\r\\n'",
")",
".",
"split",
"(",
")",
"for",
"line",
"in",
"file",
".",
"readlines",
"(",
")",
"]",
"for",
"pair",
"in",
"pairs",
":",
"if",
"len",
"(",
"pair",
")",
"==",
"EMBEDDING_DIM",
"+",
"1",
":",
"embedding_dict",
"[",
"pair",
"[",
"0",
"]",
"]",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"pair",
"[",
"1",
":",
"]",
"]",
"logger",
".",
"debug",
"(",
"'embedding_dict size: %d'",
",",
"len",
"(",
"embedding_dict",
")",
")",
"return",
"embedding_dict"
] | [
84,
0
] | [
96,
25
] | python | en | ['en', 'error', 'th'] | False |
generate_predict_json | (position1_result, position2_result, ids, passage_tokens) |
Generate json by prediction.
|
Generate json by prediction.
| def generate_predict_json(position1_result, position2_result, ids, passage_tokens):
'''
Generate json by prediction.
'''
predict_len = len(position1_result)
logger.debug('total prediction num is %s', str(predict_len))
answers = {}
for i in range(predict_len):
sample_id = ids[i]
passage, tokens = passage_tokens[i]
kbest = find_best_answer_span(
position1_result[i], position2_result[i], len(tokens), 23)
_, start, end = kbest[0]
answer = passage[tokens[start]['char_begin']:tokens[end]['char_end']]
answers[sample_id] = answer
logger.debug('generate predict done.')
return answers | [
"def",
"generate_predict_json",
"(",
"position1_result",
",",
"position2_result",
",",
"ids",
",",
"passage_tokens",
")",
":",
"predict_len",
"=",
"len",
"(",
"position1_result",
")",
"logger",
".",
"debug",
"(",
"'total prediction num is %s'",
",",
"str",
"(",
"predict_len",
")",
")",
"answers",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"predict_len",
")",
":",
"sample_id",
"=",
"ids",
"[",
"i",
"]",
"passage",
",",
"tokens",
"=",
"passage_tokens",
"[",
"i",
"]",
"kbest",
"=",
"find_best_answer_span",
"(",
"position1_result",
"[",
"i",
"]",
",",
"position2_result",
"[",
"i",
"]",
",",
"len",
"(",
"tokens",
")",
",",
"23",
")",
"_",
",",
"start",
",",
"end",
"=",
"kbest",
"[",
"0",
"]",
"answer",
"=",
"passage",
"[",
"tokens",
"[",
"start",
"]",
"[",
"'char_begin'",
"]",
":",
"tokens",
"[",
"end",
"]",
"[",
"'char_end'",
"]",
"]",
"answers",
"[",
"sample_id",
"]",
"=",
"answer",
"logger",
".",
"debug",
"(",
"'generate predict done.'",
")",
"return",
"answers"
] | [
247,
0
] | [
264,
18
] | python | en | ['en', 'error', 'th'] | False |
generate_data | (path, tokenizer, char_vcb, word_vcb, is_training=False) |
Generate data
|
Generate data
| def generate_data(path, tokenizer, char_vcb, word_vcb, is_training=False):
'''
Generate data
'''
global root_path
qp_pairs = data.load_from_file(path=path, is_training=is_training)
tokenized_sent = 0
# qp_pairs = qp_pairs[:1000]1
for qp_pair in qp_pairs:
tokenized_sent += 1
data.tokenize(qp_pair, tokenizer, is_training)
for word in qp_pair['question_tokens']:
word_vcb.add(word['word'])
for char in word['word']:
char_vcb.add(char)
for word in qp_pair['passage_tokens']:
word_vcb.add(word['word'])
for char in word['word']:
char_vcb.add(char)
max_query_length = max(len(x['question_tokens']) for x in qp_pairs)
max_passage_length = max(len(x['passage_tokens']) for x in qp_pairs)
#min_passage_length = min(len(x['passage_tokens']) for x in qp_pairs)
cfg.max_query_length = max_query_length
cfg.max_passage_length = max_passage_length
return qp_pairs | [
"def",
"generate_data",
"(",
"path",
",",
"tokenizer",
",",
"char_vcb",
",",
"word_vcb",
",",
"is_training",
"=",
"False",
")",
":",
"global",
"root_path",
"qp_pairs",
"=",
"data",
".",
"load_from_file",
"(",
"path",
"=",
"path",
",",
"is_training",
"=",
"is_training",
")",
"tokenized_sent",
"=",
"0",
"# qp_pairs = qp_pairs[:1000]1",
"for",
"qp_pair",
"in",
"qp_pairs",
":",
"tokenized_sent",
"+=",
"1",
"data",
".",
"tokenize",
"(",
"qp_pair",
",",
"tokenizer",
",",
"is_training",
")",
"for",
"word",
"in",
"qp_pair",
"[",
"'question_tokens'",
"]",
":",
"word_vcb",
".",
"add",
"(",
"word",
"[",
"'word'",
"]",
")",
"for",
"char",
"in",
"word",
"[",
"'word'",
"]",
":",
"char_vcb",
".",
"add",
"(",
"char",
")",
"for",
"word",
"in",
"qp_pair",
"[",
"'passage_tokens'",
"]",
":",
"word_vcb",
".",
"add",
"(",
"word",
"[",
"'word'",
"]",
")",
"for",
"char",
"in",
"word",
"[",
"'word'",
"]",
":",
"char_vcb",
".",
"add",
"(",
"char",
")",
"max_query_length",
"=",
"max",
"(",
"len",
"(",
"x",
"[",
"'question_tokens'",
"]",
")",
"for",
"x",
"in",
"qp_pairs",
")",
"max_passage_length",
"=",
"max",
"(",
"len",
"(",
"x",
"[",
"'passage_tokens'",
"]",
")",
"for",
"x",
"in",
"qp_pairs",
")",
"#min_passage_length = min(len(x['passage_tokens']) for x in qp_pairs)",
"cfg",
".",
"max_query_length",
"=",
"max_query_length",
"cfg",
".",
"max_passage_length",
"=",
"max_passage_length",
"return",
"qp_pairs"
] | [
267,
0
] | [
294,
19
] | python | en | ['en', 'error', 'th'] | False |
train_with_graph | (graph, qp_pairs, dev_qp_pairs) |
Train a network from a specific graph.
|
Train a network from a specific graph.
| def train_with_graph(graph, qp_pairs, dev_qp_pairs):
'''
Train a network from a specific graph.
'''
global sess
with tf.Graph().as_default():
train_model = GAG(cfg, embed, graph)
train_model.build_net(is_training=True)
tf.get_variable_scope().reuse_variables()
dev_model = GAG(cfg, embed, graph)
dev_model.build_net(is_training=False)
with tf.Session() as sess:
logger.debug('init variables')
init = tf.global_variables_initializer()
sess.run(init)
# writer = tf.summary.FileWriter('%s/graph/'%execution_path, sess.graph)
logger.debug('assign to graph')
saver = tf.train.Saver()
train_loss = None
bestacc = 0
patience = 5
patience_increase = 2
improvement_threshold = 0.995
for epoch in range(max_epoch):
logger.debug('begin to train')
train_batches = data.get_batches(qp_pairs, cfg.batch_size)
train_loss = run_epoch(train_batches, train_model, True)
logger.debug('epoch ' + str(epoch) +
' loss: ', str(train_loss))
dev_batches = list(data.get_batches(
dev_qp_pairs, cfg.batch_size))
_, position1, position2, ids, contexts = run_epoch(
dev_batches, dev_model, False)
answers = generate_predict_json(
position1, position2, ids, contexts)
if save_path is not None:
with open(os.path.join(save_path, 'epoch%d.prediction' % epoch), 'w') as file:
json.dump(answers, file)
else:
answers = json.dumps(answers)
answers = json.loads(answers)
iter = epoch + 1
acc = evaluate.evaluate_with_predictions(
args.dev_file, answers)
logger.debug('Send intermediate acc: %s', str(acc))
nni.report_intermediate_result(acc)
logger.debug('Send intermediate result done.')
if acc > bestacc:
if acc * improvement_threshold > bestacc:
patience = max(patience, iter * patience_increase)
bestacc = acc
if save_path is not None:
saver.save(os.path.join(sess, save_path + 'epoch%d.model' % epoch))
with open(os.path.join(save_path, 'epoch%d.score' % epoch), 'wb') as file:
pickle.dump(
(position1, position2, ids, contexts), file)
logger.debug('epoch %d acc %g bestacc %g', epoch, acc, bestacc)
if patience <= iter:
break
logger.debug('save done.')
return train_loss, bestacc | [
"def",
"train_with_graph",
"(",
"graph",
",",
"qp_pairs",
",",
"dev_qp_pairs",
")",
":",
"global",
"sess",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"train_model",
"=",
"GAG",
"(",
"cfg",
",",
"embed",
",",
"graph",
")",
"train_model",
".",
"build_net",
"(",
"is_training",
"=",
"True",
")",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"reuse_variables",
"(",
")",
"dev_model",
"=",
"GAG",
"(",
"cfg",
",",
"embed",
",",
"graph",
")",
"dev_model",
".",
"build_net",
"(",
"is_training",
"=",
"False",
")",
"with",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"logger",
".",
"debug",
"(",
"'init variables'",
")",
"init",
"=",
"tf",
".",
"global_variables_initializer",
"(",
")",
"sess",
".",
"run",
"(",
"init",
")",
"# writer = tf.summary.FileWriter('%s/graph/'%execution_path, sess.graph)",
"logger",
".",
"debug",
"(",
"'assign to graph'",
")",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"train_loss",
"=",
"None",
"bestacc",
"=",
"0",
"patience",
"=",
"5",
"patience_increase",
"=",
"2",
"improvement_threshold",
"=",
"0.995",
"for",
"epoch",
"in",
"range",
"(",
"max_epoch",
")",
":",
"logger",
".",
"debug",
"(",
"'begin to train'",
")",
"train_batches",
"=",
"data",
".",
"get_batches",
"(",
"qp_pairs",
",",
"cfg",
".",
"batch_size",
")",
"train_loss",
"=",
"run_epoch",
"(",
"train_batches",
",",
"train_model",
",",
"True",
")",
"logger",
".",
"debug",
"(",
"'epoch '",
"+",
"str",
"(",
"epoch",
")",
"+",
"' loss: '",
",",
"str",
"(",
"train_loss",
")",
")",
"dev_batches",
"=",
"list",
"(",
"data",
".",
"get_batches",
"(",
"dev_qp_pairs",
",",
"cfg",
".",
"batch_size",
")",
")",
"_",
",",
"position1",
",",
"position2",
",",
"ids",
",",
"contexts",
"=",
"run_epoch",
"(",
"dev_batches",
",",
"dev_model",
",",
"False",
")",
"answers",
"=",
"generate_predict_json",
"(",
"position1",
",",
"position2",
",",
"ids",
",",
"contexts",
")",
"if",
"save_path",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"save_path",
",",
"'epoch%d.prediction'",
"%",
"epoch",
")",
",",
"'w'",
")",
"as",
"file",
":",
"json",
".",
"dump",
"(",
"answers",
",",
"file",
")",
"else",
":",
"answers",
"=",
"json",
".",
"dumps",
"(",
"answers",
")",
"answers",
"=",
"json",
".",
"loads",
"(",
"answers",
")",
"iter",
"=",
"epoch",
"+",
"1",
"acc",
"=",
"evaluate",
".",
"evaluate_with_predictions",
"(",
"args",
".",
"dev_file",
",",
"answers",
")",
"logger",
".",
"debug",
"(",
"'Send intermediate acc: %s'",
",",
"str",
"(",
"acc",
")",
")",
"nni",
".",
"report_intermediate_result",
"(",
"acc",
")",
"logger",
".",
"debug",
"(",
"'Send intermediate result done.'",
")",
"if",
"acc",
">",
"bestacc",
":",
"if",
"acc",
"*",
"improvement_threshold",
">",
"bestacc",
":",
"patience",
"=",
"max",
"(",
"patience",
",",
"iter",
"*",
"patience_increase",
")",
"bestacc",
"=",
"acc",
"if",
"save_path",
"is",
"not",
"None",
":",
"saver",
".",
"save",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sess",
",",
"save_path",
"+",
"'epoch%d.model'",
"%",
"epoch",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"save_path",
",",
"'epoch%d.score'",
"%",
"epoch",
")",
",",
"'wb'",
")",
"as",
"file",
":",
"pickle",
".",
"dump",
"(",
"(",
"position1",
",",
"position2",
",",
"ids",
",",
"contexts",
")",
",",
"file",
")",
"logger",
".",
"debug",
"(",
"'epoch %d acc %g bestacc %g'",
",",
"epoch",
",",
"acc",
",",
"bestacc",
")",
"if",
"patience",
"<=",
"iter",
":",
"break",
"logger",
".",
"debug",
"(",
"'save done.'",
")",
"return",
"train_loss",
",",
"bestacc"
] | [
297,
0
] | [
365,
30
] | python | en | ['en', 'error', 'th'] | False |
async_setup_platform | (hass, config, async_add_devices, discovery_info=None) | Set up the TFIAC climate device. | Set up the TFIAC climate device. | async def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up the TFIAC climate device."""
tfiac_client = Tfiac(config[CONF_HOST])
try:
await tfiac_client.update()
except futures.TimeoutError:
_LOGGER.error("Unable to connect to %s", config[CONF_HOST])
return
async_add_devices([TfiacClimate(hass, tfiac_client)]) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_devices",
",",
"discovery_info",
"=",
"None",
")",
":",
"tfiac_client",
"=",
"Tfiac",
"(",
"config",
"[",
"CONF_HOST",
"]",
")",
"try",
":",
"await",
"tfiac_client",
".",
"update",
"(",
")",
"except",
"futures",
".",
"TimeoutError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to connect to %s\"",
",",
"config",
"[",
"CONF_HOST",
"]",
")",
"return",
"async_add_devices",
"(",
"[",
"TfiacClimate",
"(",
"hass",
",",
"tfiac_client",
")",
"]",
")"
] | [
64,
0
] | [
72,
57
] | python | en | ['en', 'haw', 'en'] | True |
TfiacClimate.__init__ | (self, hass, client) | Init class. | Init class. | def __init__(self, hass, client):
"""Init class."""
self._client = client
self._available = True | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"client",
")",
":",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"_available",
"=",
"True"
] | [
78,
4
] | [
81,
30
] | python | en | ['en', 'mt', 'en'] | False |
TfiacClimate.available | (self) | Return if the device is available. | Return if the device is available. | def available(self):
"""Return if the device is available."""
return self._available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_available"
] | [
84,
4
] | [
86,
30
] | python | en | ['en', 'en', 'en'] | True |
TfiacClimate.async_update | (self) | Update status via socket polling. | Update status via socket polling. | async def async_update(self):
"""Update status via socket polling."""
try:
await self._client.update()
self._available = True
except futures.TimeoutError:
self._available = False | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"try",
":",
"await",
"self",
".",
"_client",
".",
"update",
"(",
")",
"self",
".",
"_available",
"=",
"True",
"except",
"futures",
".",
"TimeoutError",
":",
"self",
".",
"_available",
"=",
"False"
] | [
88,
4
] | [
94,
35
] | python | en | ['en', 'af', 'en'] | True |
TfiacClimate.supported_features | (self) | Return the list of supported features. | Return the list of supported features. | def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_FLAGS"
] | [
97,
4
] | [
99,
28
] | python | en | ['en', 'en', 'en'] | True |
TfiacClimate.min_temp | (self) | Return the minimum temperature. | Return the minimum temperature. | def min_temp(self):
"""Return the minimum temperature."""
return MIN_TEMP | [
"def",
"min_temp",
"(",
"self",
")",
":",
"return",
"MIN_TEMP"
] | [
102,
4
] | [
104,
23
] | python | en | ['en', 'la', 'en'] | True |
TfiacClimate.max_temp | (self) | Return the maximum temperature. | Return the maximum temperature. | def max_temp(self):
"""Return the maximum temperature."""
return MAX_TEMP | [
"def",
"max_temp",
"(",
"self",
")",
":",
"return",
"MAX_TEMP"
] | [
107,
4
] | [
109,
23
] | python | en | ['en', 'la', 'en'] | True |
TfiacClimate.name | (self) | Return the name of the climate device. | Return the name of the climate device. | def name(self):
"""Return the name of the climate device."""
return self._client.name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"name"
] | [
112,
4
] | [
114,
32
] | python | en | ['en', 'en', 'en'] | True |
TfiacClimate.target_temperature | (self) | Return the temperature we try to reach. | Return the temperature we try to reach. | def target_temperature(self):
"""Return the temperature we try to reach."""
return self._client.status["target_temp"] | [
"def",
"target_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"status",
"[",
"\"target_temp\"",
"]"
] | [
117,
4
] | [
119,
49
] | python | en | ['en', 'en', 'en'] | True |
TfiacClimate.temperature_unit | (self) | Return the unit of measurement. | Return the unit of measurement. | def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_FAHRENHEIT | [
"def",
"temperature_unit",
"(",
"self",
")",
":",
"return",
"TEMP_FAHRENHEIT"
] | [
122,
4
] | [
124,
30
] | python | en | ['en', 'la', 'en'] | True |
TfiacClimate.current_temperature | (self) | Return the current temperature. | Return the current temperature. | def current_temperature(self):
"""Return the current temperature."""
return self._client.status["current_temp"] | [
"def",
"current_temperature",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"status",
"[",
"\"current_temp\"",
"]"
] | [
127,
4
] | [
129,
50
] | python | en | ['en', 'la', 'en'] | True |
TfiacClimate.hvac_mode | (self) | Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
| Return hvac operation ie. heat, cool mode. | def hvac_mode(self):
"""Return hvac operation ie. heat, cool mode.
Need to be one of HVAC_MODE_*.
"""
if self._client.status[ON_MODE] != "on":
return HVAC_MODE_OFF
state = self._client.status["operation"]
return HVAC_MAP_REV.get(state) | [
"def",
"hvac_mode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_client",
".",
"status",
"[",
"ON_MODE",
"]",
"!=",
"\"on\"",
":",
"return",
"HVAC_MODE_OFF",
"state",
"=",
"self",
".",
"_client",
".",
"status",
"[",
"\"operation\"",
"]",
"return",
"HVAC_MAP_REV",
".",
"get",
"(",
"state",
")"
] | [
132,
4
] | [
141,
38
] | python | bg | ['en', 'bg', 'bg'] | True |
TfiacClimate.hvac_modes | (self) | Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
| Return the list of available hvac operation modes. | def hvac_modes(self):
"""Return the list of available hvac operation modes.
Need to be a subset of HVAC_MODES.
"""
return list(HVAC_MAP) | [
"def",
"hvac_modes",
"(",
"self",
")",
":",
"return",
"list",
"(",
"HVAC_MAP",
")"
] | [
144,
4
] | [
149,
29
] | python | en | ['en', 'en', 'en'] | True |
TfiacClimate.fan_mode | (self) | Return the fan setting. | Return the fan setting. | def fan_mode(self):
"""Return the fan setting."""
return self._client.status["fan_mode"].lower() | [
"def",
"fan_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"status",
"[",
"\"fan_mode\"",
"]",
".",
"lower",
"(",
")"
] | [
152,
4
] | [
154,
54
] | python | en | ['en', 'fy', 'en'] | True |
TfiacClimate.fan_modes | (self) | Return the list of available fan modes. | Return the list of available fan modes. | def fan_modes(self):
"""Return the list of available fan modes."""
return SUPPORT_FAN | [
"def",
"fan_modes",
"(",
"self",
")",
":",
"return",
"SUPPORT_FAN"
] | [
157,
4
] | [
159,
26
] | python | en | ['en', 'en', 'en'] | True |
TfiacClimate.swing_mode | (self) | Return the swing setting. | Return the swing setting. | def swing_mode(self):
"""Return the swing setting."""
return self._client.status["swing_mode"].lower() | [
"def",
"swing_mode",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"status",
"[",
"\"swing_mode\"",
"]",
".",
"lower",
"(",
")"
] | [
162,
4
] | [
164,
56
] | python | en | ['en', 'ig', 'en'] | True |
TfiacClimate.swing_modes | (self) | List of available swing modes. | List of available swing modes. | def swing_modes(self):
"""List of available swing modes."""
return SUPPORT_SWING | [
"def",
"swing_modes",
"(",
"self",
")",
":",
"return",
"SUPPORT_SWING"
] | [
167,
4
] | [
169,
28
] | python | en | ['en', 'en', 'en'] | True |
TfiacClimate.async_set_temperature | (self, **kwargs) | Set new target temperature. | Set new target temperature. | async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
temp = kwargs.get(ATTR_TEMPERATURE)
if temp is not None:
await self._client.set_state(TARGET_TEMP, temp) | [
"async",
"def",
"async_set_temperature",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"temp",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TEMPERATURE",
")",
"if",
"temp",
"is",
"not",
"None",
":",
"await",
"self",
".",
"_client",
".",
"set_state",
"(",
"TARGET_TEMP",
",",
"temp",
")"
] | [
171,
4
] | [
175,
59
] | python | en | ['en', 'ca', 'en'] | True |
TfiacClimate.async_set_hvac_mode | (self, hvac_mode) | Set new target hvac mode. | Set new target hvac mode. | async def async_set_hvac_mode(self, hvac_mode):
"""Set new target hvac mode."""
if hvac_mode == HVAC_MODE_OFF:
await self._client.set_state(ON_MODE, "off")
else:
await self._client.set_state(OPERATION_MODE, HVAC_MAP[hvac_mode]) | [
"async",
"def",
"async_set_hvac_mode",
"(",
"self",
",",
"hvac_mode",
")",
":",
"if",
"hvac_mode",
"==",
"HVAC_MODE_OFF",
":",
"await",
"self",
".",
"_client",
".",
"set_state",
"(",
"ON_MODE",
",",
"\"off\"",
")",
"else",
":",
"await",
"self",
".",
"_client",
".",
"set_state",
"(",
"OPERATION_MODE",
",",
"HVAC_MAP",
"[",
"hvac_mode",
"]",
")"
] | [
177,
4
] | [
182,
77
] | python | da | ['da', 'su', 'en'] | False |
TfiacClimate.async_set_fan_mode | (self, fan_mode) | Set new fan mode. | Set new fan mode. | async def async_set_fan_mode(self, fan_mode):
"""Set new fan mode."""
await self._client.set_state(FAN_MODE, fan_mode.capitalize()) | [
"async",
"def",
"async_set_fan_mode",
"(",
"self",
",",
"fan_mode",
")",
":",
"await",
"self",
".",
"_client",
".",
"set_state",
"(",
"FAN_MODE",
",",
"fan_mode",
".",
"capitalize",
"(",
")",
")"
] | [
184,
4
] | [
186,
69
] | python | en | ['id', 'fy', 'en'] | False |
TfiacClimate.async_set_swing_mode | (self, swing_mode) | Set new swing mode. | Set new swing mode. | async def async_set_swing_mode(self, swing_mode):
"""Set new swing mode."""
await self._client.set_swing(swing_mode.capitalize()) | [
"async",
"def",
"async_set_swing_mode",
"(",
"self",
",",
"swing_mode",
")",
":",
"await",
"self",
".",
"_client",
".",
"set_swing",
"(",
"swing_mode",
".",
"capitalize",
"(",
")",
")"
] | [
188,
4
] | [
190,
61
] | python | en | ['en', 'no', 'en'] | True |
TfiacClimate.async_turn_on | (self) | Turn device on. | Turn device on. | async def async_turn_on(self):
"""Turn device on."""
await self._client.set_state(OPERATION_MODE) | [
"async",
"def",
"async_turn_on",
"(",
"self",
")",
":",
"await",
"self",
".",
"_client",
".",
"set_state",
"(",
"OPERATION_MODE",
")"
] | [
192,
4
] | [
194,
52
] | python | en | ['es', 'en', 'en'] | True |
TfiacClimate.async_turn_off | (self) | Turn device off. | Turn device off. | async def async_turn_off(self):
"""Turn device off."""
await self._client.set_state(ON_MODE, "off") | [
"async",
"def",
"async_turn_off",
"(",
"self",
")",
":",
"await",
"self",
".",
"_client",
".",
"set_state",
"(",
"ON_MODE",
",",
"\"off\"",
")"
] | [
196,
4
] | [
198,
52
] | python | en | ['en', 'en', 'en'] | True |
b58encode_int | (i, default_one=True) | Encode an integer using Base58 | Encode an integer using Base58 | def b58encode_int(i, default_one=True):
'''Encode an integer using Base58'''
if not i and default_one:
return alphabet[0:1]
string = b""
while i:
i, idx = divmod(i, 58)
string = alphabet[idx:idx+1] + string
return string | [
"def",
"b58encode_int",
"(",
"i",
",",
"default_one",
"=",
"True",
")",
":",
"if",
"not",
"i",
"and",
"default_one",
":",
"return",
"alphabet",
"[",
"0",
":",
"1",
"]",
"string",
"=",
"b\"\"",
"while",
"i",
":",
"i",
",",
"idx",
"=",
"divmod",
"(",
"i",
",",
"58",
")",
"string",
"=",
"alphabet",
"[",
"idx",
":",
"idx",
"+",
"1",
"]",
"+",
"string",
"return",
"string"
] | [
50,
0
] | [
58,
17
] | python | de | ['de', 'st', 'en'] | False |
b58encode | (v) | Encode a string using Base58 | Encode a string using Base58 | def b58encode(v):
'''Encode a string using Base58'''
v = scrub_input(v)
nPad = len(v)
v = v.lstrip(b'\0')
nPad -= len(v)
p, acc = 1, 0
for c in iseq(reversed(v)):
acc += p * c
p = p << 8
result = b58encode_int(acc, default_one=False)
return (alphabet[0:1] * nPad + result) | [
"def",
"b58encode",
"(",
"v",
")",
":",
"v",
"=",
"scrub_input",
"(",
"v",
")",
"nPad",
"=",
"len",
"(",
"v",
")",
"v",
"=",
"v",
".",
"lstrip",
"(",
"b'\\0'",
")",
"nPad",
"-=",
"len",
"(",
"v",
")",
"p",
",",
"acc",
"=",
"1",
",",
"0",
"for",
"c",
"in",
"iseq",
"(",
"reversed",
"(",
"v",
")",
")",
":",
"acc",
"+=",
"p",
"*",
"c",
"p",
"=",
"p",
"<<",
"8",
"result",
"=",
"b58encode_int",
"(",
"acc",
",",
"default_one",
"=",
"False",
")",
"return",
"(",
"alphabet",
"[",
"0",
":",
"1",
"]",
"*",
"nPad",
"+",
"result",
")"
] | [
61,
0
] | [
77,
42
] | python | en | ['en', 'zu', 'en'] | True |
b58decode_int | (v) | Decode a Base58 encoded string as an integer | Decode a Base58 encoded string as an integer | def b58decode_int(v):
'''Decode a Base58 encoded string as an integer'''
v = scrub_input(v)
decimal = 0
for char in v:
decimal = decimal * 58 + alphabet.index(char)
return decimal | [
"def",
"b58decode_int",
"(",
"v",
")",
":",
"v",
"=",
"scrub_input",
"(",
"v",
")",
"decimal",
"=",
"0",
"for",
"char",
"in",
"v",
":",
"decimal",
"=",
"decimal",
"*",
"58",
"+",
"alphabet",
".",
"index",
"(",
"char",
")",
"return",
"decimal"
] | [
80,
0
] | [
88,
18
] | python | en | ['en', 'en', 'nl'] | True |
b58decode | (v) | Decode a Base58 encoded string | Decode a Base58 encoded string | def b58decode(v):
'''Decode a Base58 encoded string'''
v = scrub_input(v)
origlen = len(v)
v = v.lstrip(alphabet[0:1])
newlen = len(v)
acc = b58decode_int(v)
result = []
while acc > 0:
acc, mod = divmod(acc, 256)
result.append(mod)
return (b'\0' * (origlen - newlen) + bseq(reversed(result))) | [
"def",
"b58decode",
"(",
"v",
")",
":",
"v",
"=",
"scrub_input",
"(",
"v",
")",
"origlen",
"=",
"len",
"(",
"v",
")",
"v",
"=",
"v",
".",
"lstrip",
"(",
"alphabet",
"[",
"0",
":",
"1",
"]",
")",
"newlen",
"=",
"len",
"(",
"v",
")",
"acc",
"=",
"b58decode_int",
"(",
"v",
")",
"result",
"=",
"[",
"]",
"while",
"acc",
">",
"0",
":",
"acc",
",",
"mod",
"=",
"divmod",
"(",
"acc",
",",
"256",
")",
"result",
".",
"append",
"(",
"mod",
")",
"return",
"(",
"b'\\0'",
"*",
"(",
"origlen",
"-",
"newlen",
")",
"+",
"bseq",
"(",
"reversed",
"(",
"result",
")",
")",
")"
] | [
91,
0
] | [
107,
64
] | python | en | ['en', 'en', 'nl'] | True |
b58encode_check | (v) | Encode a string using Base58 with a 4 character checksum | Encode a string using Base58 with a 4 character checksum | def b58encode_check(v):
'''Encode a string using Base58 with a 4 character checksum'''
digest = sha256(sha256(v).digest()).digest()
return b58encode(v + digest[:4]) | [
"def",
"b58encode_check",
"(",
"v",
")",
":",
"digest",
"=",
"sha256",
"(",
"sha256",
"(",
"v",
")",
".",
"digest",
"(",
")",
")",
".",
"digest",
"(",
")",
"return",
"b58encode",
"(",
"v",
"+",
"digest",
"[",
":",
"4",
"]",
")"
] | [
110,
0
] | [
114,
36
] | python | en | ['en', 'en', 'en'] | True |
b58decode_check | (v) | Decode and verify the checksum of a Base58 encoded string | Decode and verify the checksum of a Base58 encoded string | def b58decode_check(v):
'''Decode and verify the checksum of a Base58 encoded string'''
result = b58decode(v)
result, check = result[:-4], result[-4:]
digest = sha256(sha256(result).digest()).digest()
if check != digest[:4]:
raise ValueError("Invalid checksum")
return result | [
"def",
"b58decode_check",
"(",
"v",
")",
":",
"result",
"=",
"b58decode",
"(",
"v",
")",
"result",
",",
"check",
"=",
"result",
"[",
":",
"-",
"4",
"]",
",",
"result",
"[",
"-",
"4",
":",
"]",
"digest",
"=",
"sha256",
"(",
"sha256",
"(",
"result",
")",
".",
"digest",
"(",
")",
")",
".",
"digest",
"(",
")",
"if",
"check",
"!=",
"digest",
"[",
":",
"4",
"]",
":",
"raise",
"ValueError",
"(",
"\"Invalid checksum\"",
")",
"return",
"result"
] | [
117,
0
] | [
127,
17
] | python | en | ['en', 'en', 'en'] | True |
main | () | Base58 encode or decode FILE, or standard input, to standard output. | Base58 encode or decode FILE, or standard input, to standard output. | def main():
'''Base58 encode or decode FILE, or standard input, to standard output.'''
import sys
import argparse
stdout = buffer(sys.stdout)
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'file',
metavar='FILE',
nargs='?',
type=argparse.FileType('r'),
default='-')
parser.add_argument(
'-d', '--decode',
action='store_true',
help='decode data')
parser.add_argument(
'-c', '--check',
action='store_true',
help='append a checksum before encoding')
args = parser.parse_args()
fun = {
(False, False): b58encode,
(False, True): b58encode_check,
(True, False): b58decode,
(True, True): b58decode_check
}[(args.decode, args.check)]
data = buffer(args.file).read()
try:
result = fun(data)
except Exception as e:
sys.exit(e)
if not isinstance(result, bytes):
result = result.encode('ascii')
stdout.write(result) | [
"def",
"main",
"(",
")",
":",
"import",
"sys",
"import",
"argparse",
"stdout",
"=",
"buffer",
"(",
"sys",
".",
"stdout",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'file'",
",",
"metavar",
"=",
"'FILE'",
",",
"nargs",
"=",
"'?'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'r'",
")",
",",
"default",
"=",
"'-'",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--decode'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'decode data'",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--check'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'append a checksum before encoding'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"fun",
"=",
"{",
"(",
"False",
",",
"False",
")",
":",
"b58encode",
",",
"(",
"False",
",",
"True",
")",
":",
"b58encode_check",
",",
"(",
"True",
",",
"False",
")",
":",
"b58decode",
",",
"(",
"True",
",",
"True",
")",
":",
"b58decode_check",
"}",
"[",
"(",
"args",
".",
"decode",
",",
"args",
".",
"check",
")",
"]",
"data",
"=",
"buffer",
"(",
"args",
".",
"file",
")",
".",
"read",
"(",
")",
"try",
":",
"result",
"=",
"fun",
"(",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"sys",
".",
"exit",
"(",
"e",
")",
"if",
"not",
"isinstance",
"(",
"result",
",",
"bytes",
")",
":",
"result",
"=",
"result",
".",
"encode",
"(",
"'ascii'",
")",
"stdout",
".",
"write",
"(",
"result",
")"
] | [
130,
0
] | [
172,
24
] | python | en | ['en', 'en', 'en'] | True |
setup_google_domains | (hass, aioclient_mock) | Fixture that sets up NamecheapDNS. | Fixture that sets up NamecheapDNS. | def setup_google_domains(hass, aioclient_mock):
"""Fixture that sets up NamecheapDNS."""
aioclient_mock.get(UPDATE_URL, params={"hostname": DOMAIN}, text="ok 0.0.0.0")
hass.loop.run_until_complete(
async_setup_component(
hass,
google_domains.DOMAIN,
{
"google_domains": {
"domain": DOMAIN,
"username": USERNAME,
"password": PASSWORD,
}
},
)
) | [
"def",
"setup_google_domains",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"aioclient_mock",
".",
"get",
"(",
"UPDATE_URL",
",",
"params",
"=",
"{",
"\"hostname\"",
":",
"DOMAIN",
"}",
",",
"text",
"=",
"\"ok 0.0.0.0\"",
")",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"async_setup_component",
"(",
"hass",
",",
"google_domains",
".",
"DOMAIN",
",",
"{",
"\"google_domains\"",
":",
"{",
"\"domain\"",
":",
"DOMAIN",
",",
"\"username\"",
":",
"USERNAME",
",",
"\"password\"",
":",
"PASSWORD",
",",
"}",
"}",
",",
")",
")"
] | [
19,
0
] | [
35,
5
] | python | en | ['en', 'en', 'en'] | True |
test_setup | (hass, aioclient_mock) | Test setup works if update passes. | Test setup works if update passes. | async def test_setup(hass, aioclient_mock):
"""Test setup works if update passes."""
aioclient_mock.get(UPDATE_URL, params={"hostname": DOMAIN}, text="nochg 0.0.0.0")
result = await async_setup_component(
hass,
google_domains.DOMAIN,
{
"google_domains": {
"domain": DOMAIN,
"username": USERNAME,
"password": PASSWORD,
}
},
)
assert result
assert aioclient_mock.call_count == 1
async_fire_time_changed(hass, utcnow() + timedelta(minutes=5))
await hass.async_block_till_done()
assert aioclient_mock.call_count == 2 | [
"async",
"def",
"test_setup",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"aioclient_mock",
".",
"get",
"(",
"UPDATE_URL",
",",
"params",
"=",
"{",
"\"hostname\"",
":",
"DOMAIN",
"}",
",",
"text",
"=",
"\"nochg 0.0.0.0\"",
")",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"google_domains",
".",
"DOMAIN",
",",
"{",
"\"google_domains\"",
":",
"{",
"\"domain\"",
":",
"DOMAIN",
",",
"\"username\"",
":",
"USERNAME",
",",
"\"password\"",
":",
"PASSWORD",
",",
"}",
"}",
",",
")",
"assert",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"1",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"minutes",
"=",
"5",
")",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"2"
] | [
38,
0
] | [
58,
41
] | python | en | ['en', 'en', 'en'] | True |
test_setup_fails_if_update_fails | (hass, aioclient_mock) | Test setup fails if first update fails. | Test setup fails if first update fails. | async def test_setup_fails_if_update_fails(hass, aioclient_mock):
"""Test setup fails if first update fails."""
aioclient_mock.get(UPDATE_URL, params={"hostname": DOMAIN}, text="nohost")
result = await async_setup_component(
hass,
google_domains.DOMAIN,
{
"google_domains": {
"domain": DOMAIN,
"username": USERNAME,
"password": PASSWORD,
}
},
)
assert not result
assert aioclient_mock.call_count == 1 | [
"async",
"def",
"test_setup_fails_if_update_fails",
"(",
"hass",
",",
"aioclient_mock",
")",
":",
"aioclient_mock",
".",
"get",
"(",
"UPDATE_URL",
",",
"params",
"=",
"{",
"\"hostname\"",
":",
"DOMAIN",
"}",
",",
"text",
"=",
"\"nohost\"",
")",
"result",
"=",
"await",
"async_setup_component",
"(",
"hass",
",",
"google_domains",
".",
"DOMAIN",
",",
"{",
"\"google_domains\"",
":",
"{",
"\"domain\"",
":",
"DOMAIN",
",",
"\"username\"",
":",
"USERNAME",
",",
"\"password\"",
":",
"PASSWORD",
",",
"}",
"}",
",",
")",
"assert",
"not",
"result",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"1"
] | [
61,
0
] | [
77,
41
] | python | en | ['ms', 'lb', 'en'] | False |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Lutron shades. | Set up the Lutron shades. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Lutron shades."""
devs = []
for (area_name, device) in hass.data[LUTRON_DEVICES]["cover"]:
dev = LutronCover(area_name, device, hass.data[LUTRON_CONTROLLER])
devs.append(dev)
add_entities(devs, True)
return True | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"devs",
"=",
"[",
"]",
"for",
"(",
"area_name",
",",
"device",
")",
"in",
"hass",
".",
"data",
"[",
"LUTRON_DEVICES",
"]",
"[",
"\"cover\"",
"]",
":",
"dev",
"=",
"LutronCover",
"(",
"area_name",
",",
"device",
",",
"hass",
".",
"data",
"[",
"LUTRON_CONTROLLER",
"]",
")",
"devs",
".",
"append",
"(",
"dev",
")",
"add_entities",
"(",
"devs",
",",
"True",
")",
"return",
"True"
] | [
16,
0
] | [
24,
15
] | python | en | ['en', 'en', 'en'] | True |
LutronCover.supported_features | (self) | Flag supported features. | Flag supported features. | def supported_features(self):
"""Flag supported features."""
return SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_OPEN",
"|",
"SUPPORT_CLOSE",
"|",
"SUPPORT_SET_POSITION"
] | [
31,
4
] | [
33,
66
] | python | en | ['da', 'en', 'en'] | True |
LutronCover.is_closed | (self) | Return if the cover is closed. | Return if the cover is closed. | def is_closed(self):
"""Return if the cover is closed."""
return self._lutron_device.last_level() < 1 | [
"def",
"is_closed",
"(",
"self",
")",
":",
"return",
"self",
".",
"_lutron_device",
".",
"last_level",
"(",
")",
"<",
"1"
] | [
36,
4
] | [
38,
51
] | python | en | ['en', 'en', 'en'] | True |
LutronCover.current_cover_position | (self) | Return the current position of cover. | Return the current position of cover. | def current_cover_position(self):
"""Return the current position of cover."""
return self._lutron_device.last_level() | [
"def",
"current_cover_position",
"(",
"self",
")",
":",
"return",
"self",
".",
"_lutron_device",
".",
"last_level",
"(",
")"
] | [
41,
4
] | [
43,
47
] | python | en | ['en', 'en', 'en'] | True |
LutronCover.close_cover | (self, **kwargs) | Close the cover. | Close the cover. | def close_cover(self, **kwargs):
"""Close the cover."""
self._lutron_device.level = 0 | [
"def",
"close_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_lutron_device",
".",
"level",
"=",
"0"
] | [
45,
4
] | [
47,
37
] | python | en | ['en', 'en', 'en'] | True |
LutronCover.open_cover | (self, **kwargs) | Open the cover. | Open the cover. | def open_cover(self, **kwargs):
"""Open the cover."""
self._lutron_device.level = 100 | [
"def",
"open_cover",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_lutron_device",
".",
"level",
"=",
"100"
] | [
49,
4
] | [
51,
39
] | python | en | ['en', 'en', 'en'] | True |
LutronCover.set_cover_position | (self, **kwargs) | Move the shade to a specific position. | Move the shade to a specific position. | def set_cover_position(self, **kwargs):
"""Move the shade to a specific position."""
if ATTR_POSITION in kwargs:
position = kwargs[ATTR_POSITION]
self._lutron_device.level = position | [
"def",
"set_cover_position",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ATTR_POSITION",
"in",
"kwargs",
":",
"position",
"=",
"kwargs",
"[",
"ATTR_POSITION",
"]",
"self",
".",
"_lutron_device",
".",
"level",
"=",
"position"
] | [
53,
4
] | [
57,
48
] | python | en | ['en', 'en', 'en'] | True |
LutronCover.update | (self) | Call when forcing a refresh of the device. | Call when forcing a refresh of the device. | def update(self):
"""Call when forcing a refresh of the device."""
# Reading the property (rather than last_level()) fetches value
level = self._lutron_device.level
_LOGGER.debug("Lutron ID: %d updated to %f", self._lutron_device.id, level) | [
"def",
"update",
"(",
"self",
")",
":",
"# Reading the property (rather than last_level()) fetches value",
"level",
"=",
"self",
".",
"_lutron_device",
".",
"level",
"_LOGGER",
".",
"debug",
"(",
"\"Lutron ID: %d updated to %f\"",
",",
"self",
".",
"_lutron_device",
".",
"id",
",",
"level",
")"
] | [
59,
4
] | [
63,
83
] | python | en | ['en', 'en', 'en'] | True |
LutronCover.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return {"Lutron Integration ID": self._lutron_device.id} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"Lutron Integration ID\"",
":",
"self",
".",
"_lutron_device",
".",
"id",
"}"
] | [
66,
4
] | [
68,
64
] | python | en | ['en', 'en', 'en'] | True |
get_data_in_format | (original_data) | Convert the json data into dataframe.
Args:
original_data: Json data requested from database directly.
Returns:
pd.Dataframe: Formatted dataframe.
| Convert the json data into dataframe. | def get_data_in_format(original_data) -> pd.DataFrame:
"""Convert the json data into dataframe.
Args:
original_data: Json data requested from database directly.
Returns:
pd.Dataframe: Formatted dataframe.
"""
dataset = original_data["dataset"]
column = original_data["columns"]
dataheader = []
for col_index in range(0, len(column)):
dataheader.append(column[col_index]["name"])
data_in_format = pd.DataFrame(dataset, columns=dataheader)
return data_in_format | [
"def",
"get_data_in_format",
"(",
"original_data",
")",
"->",
"pd",
".",
"DataFrame",
":",
"dataset",
"=",
"original_data",
"[",
"\"dataset\"",
"]",
"column",
"=",
"original_data",
"[",
"\"columns\"",
"]",
"dataheader",
"=",
"[",
"]",
"for",
"col_index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"column",
")",
")",
":",
"dataheader",
".",
"append",
"(",
"column",
"[",
"col_index",
"]",
"[",
"\"name\"",
"]",
")",
"data_in_format",
"=",
"pd",
".",
"DataFrame",
"(",
"dataset",
",",
"columns",
"=",
"dataheader",
")",
"return",
"data_in_format"
] | [
6,
0
] | [
22,
25
] | python | en | ['en', 'lb', 'en'] | True |
get_input_range | (start_tick: str, end_tick: str) | Get the tick input range in string format.
Args:
start_tick(str): Start point of range.
end_tick(str): End point of range.
Returns:
str: Range of tick in string format.
| Get the tick input range in string format. | def get_input_range(start_tick: str, end_tick: str) -> str:
"""Get the tick input range in string format.
Args:
start_tick(str): Start point of range.
end_tick(str): End point of range.
Returns:
str: Range of tick in string format.
"""
i = int(start_tick)
input_range = "("
while i < int(end_tick):
if i == int(end_tick) - 1:
input_range = input_range + "'" + str(i) + "'" + ")"
else:
input_range = input_range + "'" + str(i) + "'" + ","
i = i + 1
return input_range | [
"def",
"get_input_range",
"(",
"start_tick",
":",
"str",
",",
"end_tick",
":",
"str",
")",
"->",
"str",
":",
"i",
"=",
"int",
"(",
"start_tick",
")",
"input_range",
"=",
"\"(\"",
"while",
"i",
"<",
"int",
"(",
"end_tick",
")",
":",
"if",
"i",
"==",
"int",
"(",
"end_tick",
")",
"-",
"1",
":",
"input_range",
"=",
"input_range",
"+",
"\"'\"",
"+",
"str",
"(",
"i",
")",
"+",
"\"'\"",
"+",
"\")\"",
"else",
":",
"input_range",
"=",
"input_range",
"+",
"\"'\"",
"+",
"str",
"(",
"i",
")",
"+",
"\"'\"",
"+",
"\",\"",
"i",
"=",
"i",
"+",
"1",
"return",
"input_range"
] | [
25,
0
] | [
44,
22
] | python | en | ['en', 'en', 'en'] | True |
cfupdate | (hass) | Mock the CloudflareUpdater for easier testing. | Mock the CloudflareUpdater for easier testing. | def cfupdate(hass):
"""Mock the CloudflareUpdater for easier testing."""
mock_cfupdate = _get_mock_cfupdate()
with patch(
"homeassistant.components.cloudflare.CloudflareUpdater",
return_value=mock_cfupdate,
) as mock_api:
yield mock_api | [
"def",
"cfupdate",
"(",
"hass",
")",
":",
"mock_cfupdate",
"=",
"_get_mock_cfupdate",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.components.cloudflare.CloudflareUpdater\"",
",",
"return_value",
"=",
"mock_cfupdate",
",",
")",
"as",
"mock_api",
":",
"yield",
"mock_api"
] | [
9,
0
] | [
16,
22
] | python | en | ['en', 'en', 'en'] | True |
cfupdate_flow | (hass) | Mock the CloudflareUpdater for easier config flow testing. | Mock the CloudflareUpdater for easier config flow testing. | def cfupdate_flow(hass):
"""Mock the CloudflareUpdater for easier config flow testing."""
mock_cfupdate = _get_mock_cfupdate()
with patch(
"homeassistant.components.cloudflare.config_flow.CloudflareUpdater",
return_value=mock_cfupdate,
) as mock_api:
yield mock_api | [
"def",
"cfupdate_flow",
"(",
"hass",
")",
":",
"mock_cfupdate",
"=",
"_get_mock_cfupdate",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.components.cloudflare.config_flow.CloudflareUpdater\"",
",",
"return_value",
"=",
"mock_cfupdate",
",",
")",
"as",
"mock_api",
":",
"yield",
"mock_api"
] | [
20,
0
] | [
27,
22
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the vlc platform. | Set up the vlc platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the vlc platform."""
add_entities(
[
VlcDevice(
config.get(CONF_NAME),
config.get(CONF_HOST),
config.get(CONF_PORT),
config.get(CONF_PASSWORD),
)
],
True,
) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"add_entities",
"(",
"[",
"VlcDevice",
"(",
"config",
".",
"get",
"(",
"CONF_NAME",
")",
",",
"config",
".",
"get",
"(",
"CONF_HOST",
")",
",",
"config",
".",
"get",
"(",
"CONF_PORT",
")",
",",
"config",
".",
"get",
"(",
"CONF_PASSWORD",
")",
",",
")",
"]",
",",
"True",
",",
")"
] | [
63,
0
] | [
75,
5
] | python | en | ['en', 'da', 'en'] | True |
VlcDevice.__init__ | (self, name, host, port, passwd) | Initialize the vlc device. | Initialize the vlc device. | def __init__(self, name, host, port, passwd):
"""Initialize the vlc device."""
self._instance = None
self._name = name
self._volume = None
self._muted = None
self._state = STATE_UNAVAILABLE
self._media_position_updated_at = None
self._media_position = None
self._media_duration = None
self._host = host
self._port = port
self._password = passwd
self._vlc = None
self._available = False
self._volume_bkp = 0
self._media_artist = ""
self._media_title = "" | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"host",
",",
"port",
",",
"passwd",
")",
":",
"self",
".",
"_instance",
"=",
"None",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_volume",
"=",
"None",
"self",
".",
"_muted",
"=",
"None",
"self",
".",
"_state",
"=",
"STATE_UNAVAILABLE",
"self",
".",
"_media_position_updated_at",
"=",
"None",
"self",
".",
"_media_position",
"=",
"None",
"self",
".",
"_media_duration",
"=",
"None",
"self",
".",
"_host",
"=",
"host",
"self",
".",
"_port",
"=",
"port",
"self",
".",
"_password",
"=",
"passwd",
"self",
".",
"_vlc",
"=",
"None",
"self",
".",
"_available",
"=",
"False",
"self",
".",
"_volume_bkp",
"=",
"0",
"self",
".",
"_media_artist",
"=",
"\"\"",
"self",
".",
"_media_title",
"=",
"\"\""
] | [
81,
4
] | [
98,
30
] | python | en | ['en', 'en', 'en'] | True |
VlcDevice.update | (self) | Get the latest details from the device. | Get the latest details from the device. | def update(self):
"""Get the latest details from the device."""
if self._vlc is None:
try:
self._vlc = VLCTelnet(self._host, self._password, self._port)
self._state = STATE_IDLE
self._available = True
except (ConnErr, EOFError):
self._available = False
self._vlc = None
else:
try:
status = self._vlc.status()
if status:
if "volume" in status:
self._volume = int(status["volume"]) / 500.0
else:
self._volume = None
if "state" in status:
state = status["state"]
if state == "playing":
self._state = STATE_PLAYING
elif state == "paused":
self._state = STATE_PAUSED
else:
self._state = STATE_IDLE
else:
self._state = STATE_IDLE
self._media_duration = self._vlc.get_length()
self._media_position = self._vlc.get_time()
info = self._vlc.info()
if info:
self._media_artist = info[0].get("artist")
self._media_title = info[0].get("title")
except (ConnErr, EOFError):
self._available = False
self._vlc = None
return True | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"_vlc",
"is",
"None",
":",
"try",
":",
"self",
".",
"_vlc",
"=",
"VLCTelnet",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_password",
",",
"self",
".",
"_port",
")",
"self",
".",
"_state",
"=",
"STATE_IDLE",
"self",
".",
"_available",
"=",
"True",
"except",
"(",
"ConnErr",
",",
"EOFError",
")",
":",
"self",
".",
"_available",
"=",
"False",
"self",
".",
"_vlc",
"=",
"None",
"else",
":",
"try",
":",
"status",
"=",
"self",
".",
"_vlc",
".",
"status",
"(",
")",
"if",
"status",
":",
"if",
"\"volume\"",
"in",
"status",
":",
"self",
".",
"_volume",
"=",
"int",
"(",
"status",
"[",
"\"volume\"",
"]",
")",
"/",
"500.0",
"else",
":",
"self",
".",
"_volume",
"=",
"None",
"if",
"\"state\"",
"in",
"status",
":",
"state",
"=",
"status",
"[",
"\"state\"",
"]",
"if",
"state",
"==",
"\"playing\"",
":",
"self",
".",
"_state",
"=",
"STATE_PLAYING",
"elif",
"state",
"==",
"\"paused\"",
":",
"self",
".",
"_state",
"=",
"STATE_PAUSED",
"else",
":",
"self",
".",
"_state",
"=",
"STATE_IDLE",
"else",
":",
"self",
".",
"_state",
"=",
"STATE_IDLE",
"self",
".",
"_media_duration",
"=",
"self",
".",
"_vlc",
".",
"get_length",
"(",
")",
"self",
".",
"_media_position",
"=",
"self",
".",
"_vlc",
".",
"get_time",
"(",
")",
"info",
"=",
"self",
".",
"_vlc",
".",
"info",
"(",
")",
"if",
"info",
":",
"self",
".",
"_media_artist",
"=",
"info",
"[",
"0",
"]",
".",
"get",
"(",
"\"artist\"",
")",
"self",
".",
"_media_title",
"=",
"info",
"[",
"0",
"]",
".",
"get",
"(",
"\"title\"",
")",
"except",
"(",
"ConnErr",
",",
"EOFError",
")",
":",
"self",
".",
"_available",
"=",
"False",
"self",
".",
"_vlc",
"=",
"None",
"return",
"True"
] | [
100,
4
] | [
141,
19
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.