id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
247,100 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | ServoMotor.run | def run(self, **kwargs):
"""
Drive servo to the position set in the `position_sp` attribute.
"""
for key in kwargs:
setattr(self, key, kwargs[key])
self.command = self.COMMAND_RUN | python | def run(self, **kwargs):
for key in kwargs:
setattr(self, key, kwargs[key])
self.command = self.COMMAND_RUN | [
"def",
"run",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"kwargs",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"kwargs",
"[",
"key",
"]",
")",
"self",
".",
"command",
"=",
"self",
".",
"COMMAND_RUN"
] | Drive servo to the position set in the `position_sp` attribute. | [
"Drive",
"servo",
"to",
"the",
"position",
"set",
"in",
"the",
"position_sp",
"attribute",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1596-L1602 |
247,101 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | ServoMotor.float | def float(self, **kwargs):
"""
Remove power from the motor.
"""
for key in kwargs:
setattr(self, key, kwargs[key])
self.command = self.COMMAND_FLOAT | python | def float(self, **kwargs):
for key in kwargs:
setattr(self, key, kwargs[key])
self.command = self.COMMAND_FLOAT | [
"def",
"float",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"kwargs",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"kwargs",
"[",
"key",
"]",
")",
"self",
".",
"command",
"=",
"self",
".",
"COMMAND_FLOAT"
] | Remove power from the motor. | [
"Remove",
"power",
"from",
"the",
"motor",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1604-L1610 |
247,102 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MotorSet.off | def off(self, motors=None, brake=True):
"""
Stop motors immediately. Configure motors to brake if ``brake`` is set.
"""
motors = motors if motors is not None else self.motors.values()
for motor in motors:
motor._set_brake(brake)
for motor in motors:
... | python | def off(self, motors=None, brake=True):
motors = motors if motors is not None else self.motors.values()
for motor in motors:
motor._set_brake(brake)
for motor in motors:
motor.stop() | [
"def",
"off",
"(",
"self",
",",
"motors",
"=",
"None",
",",
"brake",
"=",
"True",
")",
":",
"motors",
"=",
"motors",
"if",
"motors",
"is",
"not",
"None",
"else",
"self",
".",
"motors",
".",
"values",
"(",
")",
"for",
"motor",
"in",
"motors",
":",
... | Stop motors immediately. Configure motors to brake if ``brake`` is set. | [
"Stop",
"motors",
"immediately",
".",
"Configure",
"motors",
"to",
"brake",
"if",
"brake",
"is",
"set",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1699-L1709 |
247,103 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveTank.on_for_degrees | def on_for_degrees(self, left_speed, right_speed, degrees, brake=True, block=True):
"""
Rotate the motors at 'left_speed & right_speed' for 'degrees'. Speeds
can be percentages or any SpeedValue implementation.
If the left speed is not equal to the right speed (i.e., the robot will
... | python | def on_for_degrees(self, left_speed, right_speed, degrees, brake=True, block=True):
(left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(left_speed, right_speed)
# proof of the following distance calculation: consider the circle formed by each wheel's path
#... | [
"def",
"on_for_degrees",
"(",
"self",
",",
"left_speed",
",",
"right_speed",
",",
"degrees",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"(",
"left_speed_native_units",
",",
"right_speed_native_units",
")",
"=",
"self",
".",
"_unpack_speeds... | Rotate the motors at 'left_speed & right_speed' for 'degrees'. Speeds
can be percentages or any SpeedValue implementation.
If the left speed is not equal to the right speed (i.e., the robot will
turn), the motor on the outside of the turn will rotate for the full
``degrees`` while the m... | [
"Rotate",
"the",
"motors",
"at",
"left_speed",
"&",
"right_speed",
"for",
"degrees",
".",
"Speeds",
"can",
"be",
"percentages",
"or",
"any",
"SpeedValue",
"implementation",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1810-L1861 |
247,104 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveTank.on_for_rotations | def on_for_rotations(self, left_speed, right_speed, rotations, brake=True, block=True):
"""
Rotate the motors at 'left_speed & right_speed' for 'rotations'. Speeds
can be percentages or any SpeedValue implementation.
If the left speed is not equal to the right speed (i.e., the robot wil... | python | def on_for_rotations(self, left_speed, right_speed, rotations, brake=True, block=True):
MoveTank.on_for_degrees(self, left_speed, right_speed, rotations * 360, brake, block) | [
"def",
"on_for_rotations",
"(",
"self",
",",
"left_speed",
",",
"right_speed",
",",
"rotations",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"MoveTank",
".",
"on_for_degrees",
"(",
"self",
",",
"left_speed",
",",
"right_speed",
",",
"ro... | Rotate the motors at 'left_speed & right_speed' for 'rotations'. Speeds
can be percentages or any SpeedValue implementation.
If the left speed is not equal to the right speed (i.e., the robot will
turn), the motor on the outside of the turn will rotate for the full
``rotations`` while t... | [
"Rotate",
"the",
"motors",
"at",
"left_speed",
"&",
"right_speed",
"for",
"rotations",
".",
"Speeds",
"can",
"be",
"percentages",
"or",
"any",
"SpeedValue",
"implementation",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1863-L1873 |
247,105 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveTank.on_for_seconds | def on_for_seconds(self, left_speed, right_speed, seconds, brake=True, block=True):
"""
Rotate the motors at 'left_speed & right_speed' for 'seconds'. Speeds
can be percentages or any SpeedValue implementation.
"""
if seconds < 0:
raise ValueError("seconds is negativ... | python | def on_for_seconds(self, left_speed, right_speed, seconds, brake=True, block=True):
if seconds < 0:
raise ValueError("seconds is negative ({})".format(seconds))
(left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(left_speed, right_speed)
# Set ... | [
"def",
"on_for_seconds",
"(",
"self",
",",
"left_speed",
",",
"right_speed",
",",
"seconds",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"if",
"seconds",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"seconds is negative ({})\"",
".",
"f... | Rotate the motors at 'left_speed & right_speed' for 'seconds'. Speeds
can be percentages or any SpeedValue implementation. | [
"Rotate",
"the",
"motors",
"at",
"left_speed",
"&",
"right_speed",
"for",
"seconds",
".",
"Speeds",
"can",
"be",
"percentages",
"or",
"any",
"SpeedValue",
"implementation",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1875-L1902 |
247,106 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveTank.on | def on(self, left_speed, right_speed):
"""
Start rotating the motors according to ``left_speed`` and ``right_speed`` forever.
Speeds can be percentages or any SpeedValue implementation.
"""
(left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(... | python | def on(self, left_speed, right_speed):
(left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(left_speed, right_speed)
# Set all parameters
self.left_motor.speed_sp = int(round(left_speed_native_units))
self.right_motor.speed_sp = int(round(right_speed... | [
"def",
"on",
"(",
"self",
",",
"left_speed",
",",
"right_speed",
")",
":",
"(",
"left_speed_native_units",
",",
"right_speed_native_units",
")",
"=",
"self",
".",
"_unpack_speeds_to_native_units",
"(",
"left_speed",
",",
"right_speed",
")",
"# Set all parameters",
"... | Start rotating the motors according to ``left_speed`` and ``right_speed`` forever.
Speeds can be percentages or any SpeedValue implementation. | [
"Start",
"rotating",
"the",
"motors",
"according",
"to",
"left_speed",
"and",
"right_speed",
"forever",
".",
"Speeds",
"can",
"be",
"percentages",
"or",
"any",
"SpeedValue",
"implementation",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1904-L1922 |
247,107 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveSteering.on_for_seconds | def on_for_seconds(self, steering, speed, seconds, brake=True, block=True):
"""
Rotate the motors according to the provided ``steering`` for ``seconds``.
"""
(left_speed, right_speed) = self.get_speed_steering(steering, speed)
MoveTank.on_for_seconds(self, SpeedNativeUnits(left_s... | python | def on_for_seconds(self, steering, speed, seconds, brake=True, block=True):
(left_speed, right_speed) = self.get_speed_steering(steering, speed)
MoveTank.on_for_seconds(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), seconds, brake, block) | [
"def",
"on_for_seconds",
"(",
"self",
",",
"steering",
",",
"speed",
",",
"seconds",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"(",
"left_speed",
",",
"right_speed",
")",
"=",
"self",
".",
"get_speed_steering",
"(",
"steering",
",",... | Rotate the motors according to the provided ``steering`` for ``seconds``. | [
"Rotate",
"the",
"motors",
"according",
"to",
"the",
"provided",
"steering",
"for",
"seconds",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1962-L1967 |
247,108 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveSteering.on | def on(self, steering, speed):
"""
Start rotating the motors according to the provided ``steering`` and
``speed`` forever.
"""
(left_speed, right_speed) = self.get_speed_steering(steering, speed)
MoveTank.on(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed... | python | def on(self, steering, speed):
(left_speed, right_speed) = self.get_speed_steering(steering, speed)
MoveTank.on(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed)) | [
"def",
"on",
"(",
"self",
",",
"steering",
",",
"speed",
")",
":",
"(",
"left_speed",
",",
"right_speed",
")",
"=",
"self",
".",
"get_speed_steering",
"(",
"steering",
",",
"speed",
")",
"MoveTank",
".",
"on",
"(",
"self",
",",
"SpeedNativeUnits",
"(",
... | Start rotating the motors according to the provided ``steering`` and
``speed`` forever. | [
"Start",
"rotating",
"the",
"motors",
"according",
"to",
"the",
"provided",
"steering",
"and",
"speed",
"forever",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1969-L1975 |
247,109 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveDifferential._on_arc | def _on_arc(self, speed, radius_mm, distance_mm, brake, block, arc_right):
"""
Drive in a circle with 'radius' for 'distance'
"""
if radius_mm < self.min_circle_radius_mm:
raise ValueError("{}: radius_mm {} is less than min_circle_radius_mm {}" .format(
s... | python | def _on_arc(self, speed, radius_mm, distance_mm, brake, block, arc_right):
if radius_mm < self.min_circle_radius_mm:
raise ValueError("{}: radius_mm {} is less than min_circle_radius_mm {}" .format(
self, radius_mm, self.min_circle_radius_mm))
# The circle formed at the ... | [
"def",
"_on_arc",
"(",
"self",
",",
"speed",
",",
"radius_mm",
",",
"distance_mm",
",",
"brake",
",",
"block",
",",
"arc_right",
")",
":",
"if",
"radius_mm",
"<",
"self",
".",
"min_circle_radius_mm",
":",
"raise",
"ValueError",
"(",
"\"{}: radius_mm {} is less... | Drive in a circle with 'radius' for 'distance' | [
"Drive",
"in",
"a",
"circle",
"with",
"radius",
"for",
"distance"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L2118-L2171 |
247,110 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveDifferential.on_arc_right | def on_arc_right(self, speed, radius_mm, distance_mm, brake=True, block=True):
"""
Drive clockwise in a circle with 'radius_mm' for 'distance_mm'
"""
self._on_arc(speed, radius_mm, distance_mm, brake, block, True) | python | def on_arc_right(self, speed, radius_mm, distance_mm, brake=True, block=True):
self._on_arc(speed, radius_mm, distance_mm, brake, block, True) | [
"def",
"on_arc_right",
"(",
"self",
",",
"speed",
",",
"radius_mm",
",",
"distance_mm",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"self",
".",
"_on_arc",
"(",
"speed",
",",
"radius_mm",
",",
"distance_mm",
",",
"brake",
",",
"bloc... | Drive clockwise in a circle with 'radius_mm' for 'distance_mm' | [
"Drive",
"clockwise",
"in",
"a",
"circle",
"with",
"radius_mm",
"for",
"distance_mm"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L2173-L2177 |
247,111 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveDifferential.on_arc_left | def on_arc_left(self, speed, radius_mm, distance_mm, brake=True, block=True):
"""
Drive counter-clockwise in a circle with 'radius_mm' for 'distance_mm'
"""
self._on_arc(speed, radius_mm, distance_mm, brake, block, False) | python | def on_arc_left(self, speed, radius_mm, distance_mm, brake=True, block=True):
self._on_arc(speed, radius_mm, distance_mm, brake, block, False) | [
"def",
"on_arc_left",
"(",
"self",
",",
"speed",
",",
"radius_mm",
",",
"distance_mm",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"self",
".",
"_on_arc",
"(",
"speed",
",",
"radius_mm",
",",
"distance_mm",
",",
"brake",
",",
"block... | Drive counter-clockwise in a circle with 'radius_mm' for 'distance_mm' | [
"Drive",
"counter",
"-",
"clockwise",
"in",
"a",
"circle",
"with",
"radius_mm",
"for",
"distance_mm"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L2179-L2183 |
247,112 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveDifferential._turn | def _turn(self, speed, degrees, brake=True, block=True):
"""
Rotate in place 'degrees'. Both wheels must turn at the same speed for us
to rotate in place.
"""
# The distance each wheel needs to travel
distance_mm = (abs(degrees) / 360) * self.circumference_mm
# ... | python | def _turn(self, speed, degrees, brake=True, block=True):
# The distance each wheel needs to travel
distance_mm = (abs(degrees) / 360) * self.circumference_mm
# The number of rotations to move distance_mm
rotations = distance_mm/self.wheel.circumference_mm
log.debug("%s: turn() ... | [
"def",
"_turn",
"(",
"self",
",",
"speed",
",",
"degrees",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"# The distance each wheel needs to travel",
"distance_mm",
"=",
"(",
"abs",
"(",
"degrees",
")",
"/",
"360",
")",
"*",
"self",
"."... | Rotate in place 'degrees'. Both wheels must turn at the same speed for us
to rotate in place. | [
"Rotate",
"in",
"place",
"degrees",
".",
"Both",
"wheels",
"must",
"turn",
"at",
"the",
"same",
"speed",
"for",
"us",
"to",
"rotate",
"in",
"place",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L2185-L2207 |
247,113 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveDifferential.turn_right | def turn_right(self, speed, degrees, brake=True, block=True):
"""
Rotate clockwise 'degrees' in place
"""
self._turn(speed, abs(degrees), brake, block) | python | def turn_right(self, speed, degrees, brake=True, block=True):
self._turn(speed, abs(degrees), brake, block) | [
"def",
"turn_right",
"(",
"self",
",",
"speed",
",",
"degrees",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"self",
".",
"_turn",
"(",
"speed",
",",
"abs",
"(",
"degrees",
")",
",",
"brake",
",",
"block",
")"
] | Rotate clockwise 'degrees' in place | [
"Rotate",
"clockwise",
"degrees",
"in",
"place"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L2209-L2213 |
247,114 | ev3dev/ev3dev-lang-python | ev3dev2/motor.py | MoveDifferential.turn_to_angle | def turn_to_angle(self, speed, angle_target_degrees, brake=True, block=True):
"""
Rotate in place to `angle_target_degrees` at `speed`
"""
assert self.odometry_thread_id, "odometry_start() must be called to track robot coordinates"
# Make both target and current angles positive ... | python | def turn_to_angle(self, speed, angle_target_degrees, brake=True, block=True):
assert self.odometry_thread_id, "odometry_start() must be called to track robot coordinates"
# Make both target and current angles positive numbers between 0 and 360
if angle_target_degrees < 0:
angle_targ... | [
"def",
"turn_to_angle",
"(",
"self",
",",
"speed",
",",
"angle_target_degrees",
",",
"brake",
"=",
"True",
",",
"block",
"=",
"True",
")",
":",
"assert",
"self",
".",
"odometry_thread_id",
",",
"\"odometry_start() must be called to track robot coordinates\"",
"# Make ... | Rotate in place to `angle_target_degrees` at `speed` | [
"Rotate",
"in",
"place",
"to",
"angle_target_degrees",
"at",
"speed"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L2310-L2347 |
247,115 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | datetime_delta_to_ms | def datetime_delta_to_ms(delta):
"""
Given a datetime.timedelta object, return the delta in milliseconds
"""
delta_ms = delta.days * 24 * 60 * 60 * 1000
delta_ms += delta.seconds * 1000
delta_ms += delta.microseconds / 1000
delta_ms = int(delta_ms)
return delta_ms | python | def datetime_delta_to_ms(delta):
delta_ms = delta.days * 24 * 60 * 60 * 1000
delta_ms += delta.seconds * 1000
delta_ms += delta.microseconds / 1000
delta_ms = int(delta_ms)
return delta_ms | [
"def",
"datetime_delta_to_ms",
"(",
"delta",
")",
":",
"delta_ms",
"=",
"delta",
".",
"days",
"*",
"24",
"*",
"60",
"*",
"60",
"*",
"1000",
"delta_ms",
"+=",
"delta",
".",
"seconds",
"*",
"1000",
"delta_ms",
"+=",
"delta",
".",
"microseconds",
"/",
"10... | Given a datetime.timedelta object, return the delta in milliseconds | [
"Given",
"a",
"datetime",
".",
"timedelta",
"object",
"return",
"the",
"delta",
"in",
"milliseconds"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L65-L73 |
247,116 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | duration_expired | def duration_expired(start_time, duration_seconds):
"""
Return True if ``duration_seconds`` have expired since ``start_time``
"""
if duration_seconds is not None:
delta_seconds = datetime_delta_to_seconds(dt.datetime.now() - start_time)
if delta_seconds >= duration_seconds:
... | python | def duration_expired(start_time, duration_seconds):
if duration_seconds is not None:
delta_seconds = datetime_delta_to_seconds(dt.datetime.now() - start_time)
if delta_seconds >= duration_seconds:
return True
return False | [
"def",
"duration_expired",
"(",
"start_time",
",",
"duration_seconds",
")",
":",
"if",
"duration_seconds",
"is",
"not",
"None",
":",
"delta_seconds",
"=",
"datetime_delta_to_seconds",
"(",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"start_time",
")",
"i... | Return True if ``duration_seconds`` have expired since ``start_time`` | [
"Return",
"True",
"if",
"duration_seconds",
"have",
"expired",
"since",
"start_time"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L80-L91 |
247,117 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Led.max_brightness | def max_brightness(self):
"""
Returns the maximum allowable brightness value.
"""
self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, 'max_brightness')
return value | python | def max_brightness(self):
self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, 'max_brightness')
return value | [
"def",
"max_brightness",
"(",
"self",
")",
":",
"self",
".",
"_max_brightness",
",",
"value",
"=",
"self",
".",
"get_cached_attr_int",
"(",
"self",
".",
"_max_brightness",
",",
"'max_brightness'",
")",
"return",
"value"
] | Returns the maximum allowable brightness value. | [
"Returns",
"the",
"maximum",
"allowable",
"brightness",
"value",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L132-L137 |
247,118 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Led.brightness | def brightness(self):
"""
Sets the brightness level. Possible values are from 0 to `max_brightness`.
"""
self._brightness, value = self.get_attr_int(self._brightness, 'brightness')
return value | python | def brightness(self):
self._brightness, value = self.get_attr_int(self._brightness, 'brightness')
return value | [
"def",
"brightness",
"(",
"self",
")",
":",
"self",
".",
"_brightness",
",",
"value",
"=",
"self",
".",
"get_attr_int",
"(",
"self",
".",
"_brightness",
",",
"'brightness'",
")",
"return",
"value"
] | Sets the brightness level. Possible values are from 0 to `max_brightness`. | [
"Sets",
"the",
"brightness",
"level",
".",
"Possible",
"values",
"are",
"from",
"0",
"to",
"max_brightness",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L140-L145 |
247,119 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Led.triggers | def triggers(self):
"""
Returns a list of available triggers.
"""
self._triggers, value = self.get_attr_set(self._triggers, 'trigger')
return value | python | def triggers(self):
self._triggers, value = self.get_attr_set(self._triggers, 'trigger')
return value | [
"def",
"triggers",
"(",
"self",
")",
":",
"self",
".",
"_triggers",
",",
"value",
"=",
"self",
".",
"get_attr_set",
"(",
"self",
".",
"_triggers",
",",
"'trigger'",
")",
"return",
"value"
] | Returns a list of available triggers. | [
"Returns",
"a",
"list",
"of",
"available",
"triggers",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L152-L157 |
247,120 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Led.trigger | def trigger(self):
"""
Sets the LED trigger. A trigger is a kernel based source of LED events.
Triggers can either be simple or complex. A simple trigger isn't
configurable and is designed to slot into existing subsystems with
minimal additional code. Examples are the `ide-disk` ... | python | def trigger(self):
self._trigger, value = self.get_attr_from_set(self._trigger, 'trigger')
return value | [
"def",
"trigger",
"(",
"self",
")",
":",
"self",
".",
"_trigger",
",",
"value",
"=",
"self",
".",
"get_attr_from_set",
"(",
"self",
".",
"_trigger",
",",
"'trigger'",
")",
"return",
"value"
] | Sets the LED trigger. A trigger is a kernel based source of LED events.
Triggers can either be simple or complex. A simple trigger isn't
configurable and is designed to slot into existing subsystems with
minimal additional code. Examples are the `ide-disk` and `nand-disk`
triggers.
... | [
"Sets",
"the",
"LED",
"trigger",
".",
"A",
"trigger",
"is",
"a",
"kernel",
"based",
"source",
"of",
"LED",
"events",
".",
"Triggers",
"can",
"either",
"be",
"simple",
"or",
"complex",
".",
"A",
"simple",
"trigger",
"isn",
"t",
"configurable",
"and",
"is"... | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L160-L178 |
247,121 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Led.delay_on | def delay_on(self):
"""
The `timer` trigger will periodically change the LED brightness between
0 and the current brightness setting. The `on` time can
be specified via `delay_on` attribute in milliseconds.
"""
# Workaround for ev3dev/ev3dev#225.
# 'delay_on' and... | python | def delay_on(self):
# Workaround for ev3dev/ev3dev#225.
# 'delay_on' and 'delay_off' attributes are created when trigger is set
# to 'timer', and destroyed when it is set to anything else.
# This means the file cache may become outdated, and we may have to
# reopen the file.
... | [
"def",
"delay_on",
"(",
"self",
")",
":",
"# Workaround for ev3dev/ev3dev#225.",
"# 'delay_on' and 'delay_off' attributes are created when trigger is set",
"# to 'timer', and destroyed when it is set to anything else.",
"# This means the file cache may become outdated, and we may have to",
"# re... | The `timer` trigger will periodically change the LED brightness between
0 and the current brightness setting. The `on` time can
be specified via `delay_on` attribute in milliseconds. | [
"The",
"timer",
"trigger",
"will",
"periodically",
"change",
"the",
"LED",
"brightness",
"between",
"0",
"and",
"the",
"current",
"brightness",
"setting",
".",
"The",
"on",
"time",
"can",
"be",
"specified",
"via",
"delay_on",
"attribute",
"in",
"milliseconds",
... | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L209-L229 |
247,122 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Led.delay_off | def delay_off(self):
"""
The `timer` trigger will periodically change the LED brightness between
0 and the current brightness setting. The `off` time can
be specified via `delay_off` attribute in milliseconds.
"""
# Workaround for ev3dev/ev3dev#225.
# 'delay_on' ... | python | def delay_off(self):
# Workaround for ev3dev/ev3dev#225.
# 'delay_on' and 'delay_off' attributes are created when trigger is set
# to 'timer', and destroyed when it is set to anything else.
# This means the file cache may become outdated, and we may have to
# reopen the file.
... | [
"def",
"delay_off",
"(",
"self",
")",
":",
"# Workaround for ev3dev/ev3dev#225.",
"# 'delay_on' and 'delay_off' attributes are created when trigger is set",
"# to 'timer', and destroyed when it is set to anything else.",
"# This means the file cache may become outdated, and we may have to",
"# r... | The `timer` trigger will periodically change the LED brightness between
0 and the current brightness setting. The `off` time can
be specified via `delay_off` attribute in milliseconds. | [
"The",
"timer",
"trigger",
"will",
"periodically",
"change",
"the",
"LED",
"brightness",
"between",
"0",
"and",
"the",
"current",
"brightness",
"setting",
".",
"The",
"off",
"time",
"can",
"be",
"specified",
"via",
"delay_off",
"attribute",
"in",
"milliseconds",... | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L249-L269 |
247,123 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Leds.set_color | def set_color(self, group, color, pct=1):
"""
Sets brightness of LEDs in the given group to the values specified in
color tuple. When percentage is specified, brightness of each LED is
reduced proportionally.
Example::
my_leds = Leds()
my_leds.set_color(... | python | def set_color(self, group, color, pct=1):
# If this is a platform without LEDs there is nothing to do
if not self.leds:
return
color_tuple = color
if isinstance(color, str):
assert color in self.led_colors, \
"%s is an invalid LED color, valid cho... | [
"def",
"set_color",
"(",
"self",
",",
"group",
",",
"color",
",",
"pct",
"=",
"1",
")",
":",
"# If this is a platform without LEDs there is nothing to do",
"if",
"not",
"self",
".",
"leds",
":",
"return",
"color_tuple",
"=",
"color",
"if",
"isinstance",
"(",
"... | Sets brightness of LEDs in the given group to the values specified in
color tuple. When percentage is specified, brightness of each LED is
reduced proportionally.
Example::
my_leds = Leds()
my_leds.set_color('LEFT', 'AMBER')
With a custom color::
m... | [
"Sets",
"brightness",
"of",
"LEDs",
"in",
"the",
"given",
"group",
"to",
"the",
"values",
"specified",
"in",
"color",
"tuple",
".",
"When",
"percentage",
"is",
"specified",
"brightness",
"of",
"each",
"LED",
"is",
"reduced",
"proportionally",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L321-L353 |
247,124 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Leds.set | def set(self, group, **kwargs):
"""
Set attributes for each LED in group.
Example::
my_leds = Leds()
my_leds.set_color('LEFT', brightness_pct=0.5, trigger='timer')
"""
# If this is a platform without LEDs there is nothing to do
if not self.leds:... | python | def set(self, group, **kwargs):
# If this is a platform without LEDs there is nothing to do
if not self.leds:
return
assert group in self.led_groups, \
"%s is an invalid LED group, valid choices are %s" % \
(group, ', '.join(self.led_groups.keys()))
... | [
"def",
"set",
"(",
"self",
",",
"group",
",",
"*",
"*",
"kwargs",
")",
":",
"# If this is a platform without LEDs there is nothing to do",
"if",
"not",
"self",
".",
"leds",
":",
"return",
"assert",
"group",
"in",
"self",
".",
"led_groups",
",",
"\"%s is an inval... | Set attributes for each LED in group.
Example::
my_leds = Leds()
my_leds.set_color('LEFT', brightness_pct=0.5, trigger='timer') | [
"Set",
"attributes",
"for",
"each",
"LED",
"in",
"group",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L355-L375 |
247,125 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Leds.all_off | def all_off(self):
"""
Turn all LEDs off
"""
# If this is a platform without LEDs there is nothing to do
if not self.leds:
return
for led in self.leds.values():
led.brightness = 0 | python | def all_off(self):
# If this is a platform without LEDs there is nothing to do
if not self.leds:
return
for led in self.leds.values():
led.brightness = 0 | [
"def",
"all_off",
"(",
"self",
")",
":",
"# If this is a platform without LEDs there is nothing to do",
"if",
"not",
"self",
".",
"leds",
":",
"return",
"for",
"led",
"in",
"self",
".",
"leds",
".",
"values",
"(",
")",
":",
"led",
".",
"brightness",
"=",
"0"... | Turn all LEDs off | [
"Turn",
"all",
"LEDs",
"off"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L377-L387 |
247,126 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Leds.reset | def reset(self):
"""
Put all LEDs back to their default color
"""
if not self.leds:
return
self.animate_stop()
for group in self.led_groups:
self.set_color(group, LED_DEFAULT_COLOR) | python | def reset(self):
if not self.leds:
return
self.animate_stop()
for group in self.led_groups:
self.set_color(group, LED_DEFAULT_COLOR) | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"leds",
":",
"return",
"self",
".",
"animate_stop",
"(",
")",
"for",
"group",
"in",
"self",
".",
"led_groups",
":",
"self",
".",
"set_color",
"(",
"group",
",",
"LED_DEFAULT_COLOR",
")"
] | Put all LEDs back to their default color | [
"Put",
"all",
"LEDs",
"back",
"to",
"their",
"default",
"color"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L389-L400 |
247,127 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Leds.animate_police_lights | def animate_police_lights(self, color1, color2, group1='LEFT', group2='RIGHT', sleeptime=0.5, duration=5, block=True):
"""
Cycle the ``group1`` and ``group2`` LEDs between ``color1`` and ``color2``
to give the effect of police lights. Alternate the ``group1`` and ``group2``
LEDs every `... | python | def animate_police_lights(self, color1, color2, group1='LEFT', group2='RIGHT', sleeptime=0.5, duration=5, block=True):
def _animate_police_lights():
self.all_off()
even = True
start_time = dt.datetime.now()
while True:
if even:
... | [
"def",
"animate_police_lights",
"(",
"self",
",",
"color1",
",",
"color2",
",",
"group1",
"=",
"'LEFT'",
",",
"group2",
"=",
"'RIGHT'",
",",
"sleeptime",
"=",
"0.5",
",",
"duration",
"=",
"5",
",",
"block",
"=",
"True",
")",
":",
"def",
"_animate_police_... | Cycle the ``group1`` and ``group2`` LEDs between ``color1`` and ``color2``
to give the effect of police lights. Alternate the ``group1`` and ``group2``
LEDs every ``sleeptime`` seconds.
Animate for ``duration`` seconds. If ``duration`` is None animate for forever.
Example:
.... | [
"Cycle",
"the",
"group1",
"and",
"group2",
"LEDs",
"between",
"color1",
"and",
"color2",
"to",
"give",
"the",
"effect",
"of",
"police",
"lights",
".",
"Alternate",
"the",
"group1",
"and",
"group2",
"LEDs",
"every",
"sleeptime",
"seconds",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L413-L457 |
247,128 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Leds.animate_cycle | def animate_cycle(self, colors, groups=('LEFT', 'RIGHT'), sleeptime=0.5, duration=5, block=True):
"""
Cycle ``groups`` LEDs through ``colors``. Do this in a loop where
we display each color for ``sleeptime`` seconds.
Animate for ``duration`` seconds. If ``duration`` is None animate for... | python | def animate_cycle(self, colors, groups=('LEFT', 'RIGHT'), sleeptime=0.5, duration=5, block=True):
def _animate_cycle():
index = 0
max_index = len(colors)
start_time = dt.datetime.now()
while True:
for group in groups:
self.set_... | [
"def",
"animate_cycle",
"(",
"self",
",",
"colors",
",",
"groups",
"=",
"(",
"'LEFT'",
",",
"'RIGHT'",
")",
",",
"sleeptime",
"=",
"0.5",
",",
"duration",
"=",
"5",
",",
"block",
"=",
"True",
")",
":",
"def",
"_animate_cycle",
"(",
")",
":",
"index",... | Cycle ``groups`` LEDs through ``colors``. Do this in a loop where
we display each color for ``sleeptime`` seconds.
Animate for ``duration`` seconds. If ``duration`` is None animate for forever.
Example:
.. code-block:: python
from ev3dev2.led import Leds
leds... | [
"Cycle",
"groups",
"LEDs",
"through",
"colors",
".",
"Do",
"this",
"in",
"a",
"loop",
"where",
"we",
"display",
"each",
"color",
"for",
"sleeptime",
"seconds",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L501-L543 |
247,129 | ev3dev/ev3dev-lang-python | ev3dev2/led.py | Leds.animate_rainbow | def animate_rainbow(self, group1='LEFT', group2='RIGHT', increment_by=0.1, sleeptime=0.1, duration=5, block=True):
"""
Gradually fade from one color to the next
Animate for ``duration`` seconds. If ``duration`` is None animate for forever.
Example:
.. code-block:: python
... | python | def animate_rainbow(self, group1='LEFT', group2='RIGHT', increment_by=0.1, sleeptime=0.1, duration=5, block=True):
def _animate_rainbow():
# state 0: (LEFT,RIGHT) from (0,0) to (1,0)...RED
# state 1: (LEFT,RIGHT) from (1,0) to (1,1)...AMBER
# state 2: (LEFT,RIGHT) from (1,1) ... | [
"def",
"animate_rainbow",
"(",
"self",
",",
"group1",
"=",
"'LEFT'",
",",
"group2",
"=",
"'RIGHT'",
",",
"increment_by",
"=",
"0.1",
",",
"sleeptime",
"=",
"0.1",
",",
"duration",
"=",
"5",
",",
"block",
"=",
"True",
")",
":",
"def",
"_animate_rainbow",
... | Gradually fade from one color to the next
Animate for ``duration`` seconds. If ``duration`` is None animate for forever.
Example:
.. code-block:: python
from ev3dev2.led import Leds
leds = Leds()
leds.animate_rainbow() | [
"Gradually",
"fade",
"from",
"one",
"color",
"to",
"the",
"next"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L545-L617 |
247,130 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | ColorSensor.raw | def raw(self):
"""
Red, green, and blue components of the detected color, as a tuple.
Officially in the range 0-1020 but the values returned will never be
that high. We do not yet know why the values returned are low, but
pointing the color sensor at a well lit sheet of ... | python | def raw(self):
self._ensure_mode(self.MODE_RGB_RAW)
return self.value(0), self.value(1), self.value(2) | [
"def",
"raw",
"(",
"self",
")",
":",
"self",
".",
"_ensure_mode",
"(",
"self",
".",
"MODE_RGB_RAW",
")",
"return",
"self",
".",
"value",
"(",
"0",
")",
",",
"self",
".",
"value",
"(",
"1",
")",
",",
"self",
".",
"value",
"(",
"2",
")"
] | Red, green, and blue components of the detected color, as a tuple.
Officially in the range 0-1020 but the values returned will never be
that high. We do not yet know why the values returned are low, but
pointing the color sensor at a well lit sheet of white paper will return
val... | [
"Red",
"green",
"and",
"blue",
"components",
"of",
"the",
"detected",
"color",
"as",
"a",
"tuple",
".",
"Officially",
"in",
"the",
"range",
"0",
"-",
"1020",
"but",
"the",
"values",
"returned",
"will",
"never",
"be",
"that",
"high",
".",
"We",
"do",
"n... | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L226-L238 |
247,131 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | ColorSensor.lab | def lab(self):
"""
Return colors in Lab color space
"""
RGB = [0, 0, 0]
XYZ = [0, 0, 0]
for (num, value) in enumerate(self.rgb):
if value > 0.04045:
value = pow(((value + 0.055) / 1.055), 2.4)
else:
value = value / ... | python | def lab(self):
RGB = [0, 0, 0]
XYZ = [0, 0, 0]
for (num, value) in enumerate(self.rgb):
if value > 0.04045:
value = pow(((value + 0.055) / 1.055), 2.4)
else:
value = value / 12.92
RGB[num] = value * 100.0
# http://www... | [
"def",
"lab",
"(",
"self",
")",
":",
"RGB",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"XYZ",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"for",
"(",
"num",
",",
"value",
")",
"in",
"enumerate",
"(",
"self",
".",
"rgb",
")",
":",
"if",
"value",
... | Return colors in Lab color space | [
"Return",
"colors",
"in",
"Lab",
"color",
"space"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L273-L317 |
247,132 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | GyroSensor.wait_until_angle_changed_by | def wait_until_angle_changed_by(self, delta, direction_sensitive=False):
"""
Wait until angle has changed by specified amount.
If ``direction_sensitive`` is True we will wait until angle has changed
by ``delta`` and with the correct sign.
If ``direction_sensitive`` is False (de... | python | def wait_until_angle_changed_by(self, delta, direction_sensitive=False):
assert self.mode in (self.MODE_GYRO_G_A, self.MODE_GYRO_ANG,
self.MODE_TILT_ANG),\
'Gyro mode should be MODE_GYRO_ANG, MODE_GYRO_G_A or MODE_TILT_ANG'
start_angle = self.value(0)
if... | [
"def",
"wait_until_angle_changed_by",
"(",
"self",
",",
"delta",
",",
"direction_sensitive",
"=",
"False",
")",
":",
"assert",
"self",
".",
"mode",
"in",
"(",
"self",
".",
"MODE_GYRO_G_A",
",",
"self",
".",
"MODE_GYRO_ANG",
",",
"self",
".",
"MODE_TILT_ANG",
... | Wait until angle has changed by specified amount.
If ``direction_sensitive`` is True we will wait until angle has changed
by ``delta`` and with the correct sign.
If ``direction_sensitive`` is False (default) we will wait until angle has changed
by ``delta`` in either direction. | [
"Wait",
"until",
"angle",
"has",
"changed",
"by",
"specified",
"amount",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L636-L661 |
247,133 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | InfraredSensor.buttons_pressed | def buttons_pressed(self, channel=1):
"""
Returns list of currently pressed buttons.
Note that the sensor can only identify up to two buttons pressed at once.
"""
self._ensure_mode(self.MODE_IR_REMOTE)
channel = self._normalize_channel(channel)
return self._BUTTO... | python | def buttons_pressed(self, channel=1):
self._ensure_mode(self.MODE_IR_REMOTE)
channel = self._normalize_channel(channel)
return self._BUTTON_VALUES.get(self.value(channel), []) | [
"def",
"buttons_pressed",
"(",
"self",
",",
"channel",
"=",
"1",
")",
":",
"self",
".",
"_ensure_mode",
"(",
"self",
".",
"MODE_IR_REMOTE",
")",
"channel",
"=",
"self",
".",
"_normalize_channel",
"(",
"channel",
")",
"return",
"self",
".",
"_BUTTON_VALUES",
... | Returns list of currently pressed buttons.
Note that the sensor can only identify up to two buttons pressed at once. | [
"Returns",
"list",
"of",
"currently",
"pressed",
"buttons",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L848-L856 |
247,134 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | SoundSensor.sound_pressure | def sound_pressure(self):
"""
A measurement of the measured sound pressure level, as a
percent. Uses a flat weighting.
"""
self._ensure_mode(self.MODE_DB)
return self.value(0) * self._scale('DB') | python | def sound_pressure(self):
self._ensure_mode(self.MODE_DB)
return self.value(0) * self._scale('DB') | [
"def",
"sound_pressure",
"(",
"self",
")",
":",
"self",
".",
"_ensure_mode",
"(",
"self",
".",
"MODE_DB",
")",
"return",
"self",
".",
"value",
"(",
"0",
")",
"*",
"self",
".",
"_scale",
"(",
"'DB'",
")"
] | A measurement of the measured sound pressure level, as a
percent. Uses a flat weighting. | [
"A",
"measurement",
"of",
"the",
"measured",
"sound",
"pressure",
"level",
"as",
"a",
"percent",
".",
"Uses",
"a",
"flat",
"weighting",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L935-L941 |
247,135 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | SoundSensor.sound_pressure_low | def sound_pressure_low(self):
"""
A measurement of the measured sound pressure level, as a
percent. Uses A-weighting, which focuses on levels up to 55 dB.
"""
self._ensure_mode(self.MODE_DBA)
return self.value(0) * self._scale('DBA') | python | def sound_pressure_low(self):
self._ensure_mode(self.MODE_DBA)
return self.value(0) * self._scale('DBA') | [
"def",
"sound_pressure_low",
"(",
"self",
")",
":",
"self",
".",
"_ensure_mode",
"(",
"self",
".",
"MODE_DBA",
")",
"return",
"self",
".",
"value",
"(",
"0",
")",
"*",
"self",
".",
"_scale",
"(",
"'DBA'",
")"
] | A measurement of the measured sound pressure level, as a
percent. Uses A-weighting, which focuses on levels up to 55 dB. | [
"A",
"measurement",
"of",
"the",
"measured",
"sound",
"pressure",
"level",
"as",
"a",
"percent",
".",
"Uses",
"A",
"-",
"weighting",
"which",
"focuses",
"on",
"levels",
"up",
"to",
"55",
"dB",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L944-L950 |
247,136 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | LightSensor.reflected_light_intensity | def reflected_light_intensity(self):
"""
A measurement of the reflected light intensity, as a percentage.
"""
self._ensure_mode(self.MODE_REFLECT)
return self.value(0) * self._scale('REFLECT') | python | def reflected_light_intensity(self):
self._ensure_mode(self.MODE_REFLECT)
return self.value(0) * self._scale('REFLECT') | [
"def",
"reflected_light_intensity",
"(",
"self",
")",
":",
"self",
".",
"_ensure_mode",
"(",
"self",
".",
"MODE_REFLECT",
")",
"return",
"self",
".",
"value",
"(",
"0",
")",
"*",
"self",
".",
"_scale",
"(",
"'REFLECT'",
")"
] | A measurement of the reflected light intensity, as a percentage. | [
"A",
"measurement",
"of",
"the",
"reflected",
"light",
"intensity",
"as",
"a",
"percentage",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L976-L981 |
247,137 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/lego.py | LightSensor.ambient_light_intensity | def ambient_light_intensity(self):
"""
A measurement of the ambient light intensity, as a percentage.
"""
self._ensure_mode(self.MODE_AMBIENT)
return self.value(0) * self._scale('AMBIENT') | python | def ambient_light_intensity(self):
self._ensure_mode(self.MODE_AMBIENT)
return self.value(0) * self._scale('AMBIENT') | [
"def",
"ambient_light_intensity",
"(",
"self",
")",
":",
"self",
".",
"_ensure_mode",
"(",
"self",
".",
"MODE_AMBIENT",
")",
"return",
"self",
".",
"value",
"(",
"0",
")",
"*",
"self",
".",
"_scale",
"(",
"'AMBIENT'",
")"
] | A measurement of the ambient light intensity, as a percentage. | [
"A",
"measurement",
"of",
"the",
"ambient",
"light",
"intensity",
"as",
"a",
"percentage",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L984-L989 |
247,138 | ev3dev/ev3dev-lang-python | ev3dev2/fonts/__init__.py | available | def available():
"""
Returns list of available font names.
"""
font_dir = os.path.dirname(__file__)
names = [os.path.basename(os.path.splitext(f)[0])
for f in glob(os.path.join(font_dir, '*.pil'))]
return sorted(names) | python | def available():
font_dir = os.path.dirname(__file__)
names = [os.path.basename(os.path.splitext(f)[0])
for f in glob(os.path.join(font_dir, '*.pil'))]
return sorted(names) | [
"def",
"available",
"(",
")",
":",
"font_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"names",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"f",
")",
"[",
"0",
"]",
")",
"for... | Returns list of available font names. | [
"Returns",
"list",
"of",
"available",
"font",
"names",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/fonts/__init__.py#L5-L12 |
247,139 | ev3dev/ev3dev-lang-python | ev3dev2/port.py | LegoPort.modes | def modes(self):
"""
Returns a list of the available modes of the port.
"""
(self._modes, value) = self.get_cached_attr_set(self._modes, 'modes')
return value | python | def modes(self):
(self._modes, value) = self.get_cached_attr_set(self._modes, 'modes')
return value | [
"def",
"modes",
"(",
"self",
")",
":",
"(",
"self",
".",
"_modes",
",",
"value",
")",
"=",
"self",
".",
"get_cached_attr_set",
"(",
"self",
".",
"_modes",
",",
"'modes'",
")",
"return",
"value"
] | Returns a list of the available modes of the port. | [
"Returns",
"a",
"list",
"of",
"the",
"available",
"modes",
"of",
"the",
"port",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/port.py#L105-L110 |
247,140 | ev3dev/ev3dev-lang-python | ev3dev2/port.py | LegoPort.mode | def mode(self):
"""
Reading returns the currently selected mode. Writing sets the mode.
Generally speaking when the mode changes any sensor or motor devices
associated with the port will be removed new ones loaded, however this
this will depend on the individual driver implementi... | python | def mode(self):
self._mode, value = self.get_attr_string(self._mode, 'mode')
return value | [
"def",
"mode",
"(",
"self",
")",
":",
"self",
".",
"_mode",
",",
"value",
"=",
"self",
".",
"get_attr_string",
"(",
"self",
".",
"_mode",
",",
"'mode'",
")",
"return",
"value"
] | Reading returns the currently selected mode. Writing sets the mode.
Generally speaking when the mode changes any sensor or motor devices
associated with the port will be removed new ones loaded, however this
this will depend on the individual driver implementing this class. | [
"Reading",
"returns",
"the",
"currently",
"selected",
"mode",
".",
"Writing",
"sets",
"the",
"mode",
".",
"Generally",
"speaking",
"when",
"the",
"mode",
"changes",
"any",
"sensor",
"or",
"motor",
"devices",
"associated",
"with",
"the",
"port",
"will",
"be",
... | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/port.py#L113-L121 |
247,141 | ev3dev/ev3dev-lang-python | ev3dev2/port.py | LegoPort.status | def status(self):
"""
In most cases, reading status will return the same value as `mode`. In
cases where there is an `auto` mode additional values may be returned,
such as `no-device` or `error`. See individual port driver documentation
for the full list of possible values.
... | python | def status(self):
self._status, value = self.get_attr_string(self._status, 'status')
return value | [
"def",
"status",
"(",
"self",
")",
":",
"self",
".",
"_status",
",",
"value",
"=",
"self",
".",
"get_attr_string",
"(",
"self",
".",
"_status",
",",
"'status'",
")",
"return",
"value"
] | In most cases, reading status will return the same value as `mode`. In
cases where there is an `auto` mode additional values may be returned,
such as `no-device` or `error`. See individual port driver documentation
for the full list of possible values. | [
"In",
"most",
"cases",
"reading",
"status",
"will",
"return",
"the",
"same",
"value",
"as",
"mode",
".",
"In",
"cases",
"where",
"there",
"is",
"an",
"auto",
"mode",
"additional",
"values",
"may",
"be",
"returned",
"such",
"as",
"no",
"-",
"device",
"or"... | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/port.py#L143-L151 |
247,142 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/__init__.py | list_sensors | def list_sensors(name_pattern=Sensor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all sensors that match the
provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'sensor*'. Default value: '*'.... | python | def list_sensors(name_pattern=Sensor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
class_path = abspath(Device.DEVICE_ROOT_PATH + '/' + Sensor.SYSTEM_CLASS_NAME)
return (Sensor(name_pattern=name, name_exact=True)
for name in list_device_names(class_path, name_pattern, **kwargs)) | [
"def",
"list_sensors",
"(",
"name_pattern",
"=",
"Sensor",
".",
"SYSTEM_DEVICE_NAME_CONVENTION",
",",
"*",
"*",
"kwargs",
")",
":",
"class_path",
"=",
"abspath",
"(",
"Device",
".",
"DEVICE_ROOT_PATH",
"+",
"'/'",
"+",
"Sensor",
".",
"SYSTEM_CLASS_NAME",
")",
... | This is a generator function that enumerates all sensors that match the
provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'sensor*'. Default value: '*'.
keyword arguments: used for matching the corresponding device
attribut... | [
"This",
"is",
"a",
"generator",
"function",
"that",
"enumerates",
"all",
"sensors",
"that",
"match",
"the",
"provided",
"arguments",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/__init__.py#L282-L297 |
247,143 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/__init__.py | Sensor._scale | def _scale(self, mode):
"""
Returns value scaling coefficient for the given mode.
"""
if mode in self._mode_scale:
scale = self._mode_scale[mode]
else:
scale = 10**(-self.decimals)
self._mode_scale[mode] = scale
return scale | python | def _scale(self, mode):
if mode in self._mode_scale:
scale = self._mode_scale[mode]
else:
scale = 10**(-self.decimals)
self._mode_scale[mode] = scale
return scale | [
"def",
"_scale",
"(",
"self",
",",
"mode",
")",
":",
"if",
"mode",
"in",
"self",
".",
"_mode_scale",
":",
"scale",
"=",
"self",
".",
"_mode_scale",
"[",
"mode",
"]",
"else",
":",
"scale",
"=",
"10",
"**",
"(",
"-",
"self",
".",
"decimals",
")",
"... | Returns value scaling coefficient for the given mode. | [
"Returns",
"value",
"scaling",
"coefficient",
"for",
"the",
"given",
"mode",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/__init__.py#L112-L122 |
247,144 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/__init__.py | Sensor.units | def units(self):
"""
Returns the units of the measured value for the current mode. May return
empty string
"""
self._units, value = self.get_attr_string(self._units, 'units')
return value | python | def units(self):
self._units, value = self.get_attr_string(self._units, 'units')
return value | [
"def",
"units",
"(",
"self",
")",
":",
"self",
".",
"_units",
",",
"value",
"=",
"self",
".",
"get_attr_string",
"(",
"self",
".",
"_units",
",",
"'units'",
")",
"return",
"value"
] | Returns the units of the measured value for the current mode. May return
empty string | [
"Returns",
"the",
"units",
"of",
"the",
"measured",
"value",
"for",
"the",
"current",
"mode",
".",
"May",
"return",
"empty",
"string"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/__init__.py#L202-L208 |
247,145 | ev3dev/ev3dev-lang-python | ev3dev2/sensor/__init__.py | Sensor.value | def value(self, n=0):
"""
Returns the value or values measured by the sensor. Check num_values to
see how many values there are. Values with N >= num_values will return
an error. The values are fixed point numbers, so check decimals to see
if you need to divide to get the actual ... | python | def value(self, n=0):
n = int(n)
self._value[n], value = self.get_attr_int(self._value[n], 'value'+str(n))
return value | [
"def",
"value",
"(",
"self",
",",
"n",
"=",
"0",
")",
":",
"n",
"=",
"int",
"(",
"n",
")",
"self",
".",
"_value",
"[",
"n",
"]",
",",
"value",
"=",
"self",
".",
"get_attr_int",
"(",
"self",
".",
"_value",
"[",
"n",
"]",
",",
"'value'",
"+",
... | Returns the value or values measured by the sensor. Check num_values to
see how many values there are. Values with N >= num_values will return
an error. The values are fixed point numbers, so check decimals to see
if you need to divide to get the actual value. | [
"Returns",
"the",
"value",
"or",
"values",
"measured",
"by",
"the",
"sensor",
".",
"Check",
"num_values",
"to",
"see",
"how",
"many",
"values",
"there",
"are",
".",
"Values",
"with",
"N",
">",
"=",
"num_values",
"will",
"return",
"an",
"error",
".",
"The... | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/__init__.py#L210-L220 |
247,146 | ev3dev/ev3dev-lang-python | ev3dev2/display.py | FbMem._open_fbdev | def _open_fbdev(fbdev=None):
"""Return the framebuffer file descriptor.
Try to use the FRAMEBUFFER
environment variable if fbdev is not given. Use '/dev/fb0' by
default.
"""
dev = fbdev or os.getenv('FRAMEBUFFER', '/dev/fb0')
fbfid = os.open(dev, os.O_RDWR)
... | python | def _open_fbdev(fbdev=None):
dev = fbdev or os.getenv('FRAMEBUFFER', '/dev/fb0')
fbfid = os.open(dev, os.O_RDWR)
return fbfid | [
"def",
"_open_fbdev",
"(",
"fbdev",
"=",
"None",
")",
":",
"dev",
"=",
"fbdev",
"or",
"os",
".",
"getenv",
"(",
"'FRAMEBUFFER'",
",",
"'/dev/fb0'",
")",
"fbfid",
"=",
"os",
".",
"open",
"(",
"dev",
",",
"os",
".",
"O_RDWR",
")",
"return",
"fbfid"
] | Return the framebuffer file descriptor.
Try to use the FRAMEBUFFER
environment variable if fbdev is not given. Use '/dev/fb0' by
default. | [
"Return",
"the",
"framebuffer",
"file",
"descriptor",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/display.py#L157-L166 |
247,147 | ev3dev/ev3dev-lang-python | ev3dev2/display.py | FbMem._get_fix_info | def _get_fix_info(fbfid):
"""Return the fix screen info from the framebuffer file descriptor."""
fix_info = FbMem.FixScreenInfo()
fcntl.ioctl(fbfid, FbMem.FBIOGET_FSCREENINFO, fix_info)
return fix_info | python | def _get_fix_info(fbfid):
fix_info = FbMem.FixScreenInfo()
fcntl.ioctl(fbfid, FbMem.FBIOGET_FSCREENINFO, fix_info)
return fix_info | [
"def",
"_get_fix_info",
"(",
"fbfid",
")",
":",
"fix_info",
"=",
"FbMem",
".",
"FixScreenInfo",
"(",
")",
"fcntl",
".",
"ioctl",
"(",
"fbfid",
",",
"FbMem",
".",
"FBIOGET_FSCREENINFO",
",",
"fix_info",
")",
"return",
"fix_info"
] | Return the fix screen info from the framebuffer file descriptor. | [
"Return",
"the",
"fix",
"screen",
"info",
"from",
"the",
"framebuffer",
"file",
"descriptor",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/display.py#L169-L173 |
247,148 | ev3dev/ev3dev-lang-python | ev3dev2/display.py | FbMem._get_var_info | def _get_var_info(fbfid):
"""Return the var screen info from the framebuffer file descriptor."""
var_info = FbMem.VarScreenInfo()
fcntl.ioctl(fbfid, FbMem.FBIOGET_VSCREENINFO, var_info)
return var_info | python | def _get_var_info(fbfid):
var_info = FbMem.VarScreenInfo()
fcntl.ioctl(fbfid, FbMem.FBIOGET_VSCREENINFO, var_info)
return var_info | [
"def",
"_get_var_info",
"(",
"fbfid",
")",
":",
"var_info",
"=",
"FbMem",
".",
"VarScreenInfo",
"(",
")",
"fcntl",
".",
"ioctl",
"(",
"fbfid",
",",
"FbMem",
".",
"FBIOGET_VSCREENINFO",
",",
"var_info",
")",
"return",
"var_info"
] | Return the var screen info from the framebuffer file descriptor. | [
"Return",
"the",
"var",
"screen",
"info",
"from",
"the",
"framebuffer",
"file",
"descriptor",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/display.py#L176-L180 |
247,149 | ev3dev/ev3dev-lang-python | ev3dev2/display.py | FbMem._map_fb_memory | def _map_fb_memory(fbfid, fix_info):
"""Map the framebuffer memory."""
return mmap.mmap(
fbfid,
fix_info.smem_len,
mmap.MAP_SHARED,
mmap.PROT_READ | mmap.PROT_WRITE,
offset=0
) | python | def _map_fb_memory(fbfid, fix_info):
return mmap.mmap(
fbfid,
fix_info.smem_len,
mmap.MAP_SHARED,
mmap.PROT_READ | mmap.PROT_WRITE,
offset=0
) | [
"def",
"_map_fb_memory",
"(",
"fbfid",
",",
"fix_info",
")",
":",
"return",
"mmap",
".",
"mmap",
"(",
"fbfid",
",",
"fix_info",
".",
"smem_len",
",",
"mmap",
".",
"MAP_SHARED",
",",
"mmap",
".",
"PROT_READ",
"|",
"mmap",
".",
"PROT_WRITE",
",",
"offset",... | Map the framebuffer memory. | [
"Map",
"the",
"framebuffer",
"memory",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/display.py#L183-L191 |
247,150 | ev3dev/ev3dev-lang-python | ev3dev2/display.py | Display.update | def update(self):
"""
Applies pending changes to the screen.
Nothing will be drawn on the screen until this function is called.
"""
if self.var_info.bits_per_pixel == 1:
b = self._img.tobytes("raw", "1;R")
self.mmap[:len(b)] = b
elif self.var_info... | python | def update(self):
if self.var_info.bits_per_pixel == 1:
b = self._img.tobytes("raw", "1;R")
self.mmap[:len(b)] = b
elif self.var_info.bits_per_pixel == 16:
self.mmap[:] = self._img_to_rgb565_bytes()
elif self.var_info.bits_per_pixel == 32:
self.m... | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"var_info",
".",
"bits_per_pixel",
"==",
"1",
":",
"b",
"=",
"self",
".",
"_img",
".",
"tobytes",
"(",
"\"raw\"",
",",
"\"1;R\"",
")",
"self",
".",
"mmap",
"[",
":",
"len",
"(",
"b",
")",... | Applies pending changes to the screen.
Nothing will be drawn on the screen until this function is called. | [
"Applies",
"pending",
"changes",
"to",
"the",
"screen",
".",
"Nothing",
"will",
"be",
"drawn",
"on",
"the",
"screen",
"until",
"this",
"function",
"is",
"called",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/display.py#L294-L311 |
247,151 | ev3dev/ev3dev-lang-python | ev3dev2/sound.py | _make_scales | def _make_scales(notes):
""" Utility function used by Sound class for building the note frequencies table """
res = dict()
for note, freq in notes:
freq = round(freq)
for n in note.split('/'):
res[n] = freq
return res | python | def _make_scales(notes):
res = dict()
for note, freq in notes:
freq = round(freq)
for n in note.split('/'):
res[n] = freq
return res | [
"def",
"_make_scales",
"(",
"notes",
")",
":",
"res",
"=",
"dict",
"(",
")",
"for",
"note",
",",
"freq",
"in",
"notes",
":",
"freq",
"=",
"round",
"(",
"freq",
")",
"for",
"n",
"in",
"note",
".",
"split",
"(",
"'/'",
")",
":",
"res",
"[",
"n",
... | Utility function used by Sound class for building the note frequencies table | [
"Utility",
"function",
"used",
"by",
"Sound",
"class",
"for",
"building",
"the",
"note",
"frequencies",
"table"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sound.py#L37-L44 |
247,152 | ev3dev/ev3dev-lang-python | ev3dev2/sound.py | Sound.play_tone | def play_tone(self, frequency, duration, delay=0.0, volume=100,
play_type=PLAY_WAIT_FOR_COMPLETE):
""" Play a single tone, specified by its frequency, duration, volume and final delay.
:param int frequency: the tone frequency, in Hertz
:param float duration: Tone duration, in ... | python | def play_tone(self, frequency, duration, delay=0.0, volume=100,
play_type=PLAY_WAIT_FOR_COMPLETE):
self._validate_play_type(play_type)
if duration <= 0:
raise ValueError('invalid duration (%s)' % duration)
if delay < 0:
raise ValueError('invalid delay (... | [
"def",
"play_tone",
"(",
"self",
",",
"frequency",
",",
"duration",
",",
"delay",
"=",
"0.0",
",",
"volume",
"=",
"100",
",",
"play_type",
"=",
"PLAY_WAIT_FOR_COMPLETE",
")",
":",
"self",
".",
"_validate_play_type",
"(",
"play_type",
")",
"if",
"duration",
... | Play a single tone, specified by its frequency, duration, volume and final delay.
:param int frequency: the tone frequency, in Hertz
:param float duration: Tone duration, in seconds
:param float delay: Delay after tone, in seconds (can be useful when chaining calls to ``play_tone``)
:pa... | [
"Play",
"a",
"single",
"tone",
"specified",
"by",
"its",
"frequency",
"duration",
"volume",
"and",
"final",
"delay",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sound.py#L192-L222 |
247,153 | ev3dev/ev3dev-lang-python | ev3dev2/sound.py | Sound.play_note | def play_note(self, note, duration, volume=100, play_type=PLAY_WAIT_FOR_COMPLETE):
""" Plays a note, given by its name as defined in ``_NOTE_FREQUENCIES``.
:param string note: The note symbol with its octave number
:param float duration: Tone duration, in seconds
:param int volume: The ... | python | def play_note(self, note, duration, volume=100, play_type=PLAY_WAIT_FOR_COMPLETE):
self._validate_play_type(play_type)
try:
freq = self._NOTE_FREQUENCIES.get(note.upper(), self._NOTE_FREQUENCIES[note])
except KeyError:
raise ValueError('invalid note (%s)' % note)
... | [
"def",
"play_note",
"(",
"self",
",",
"note",
",",
"duration",
",",
"volume",
"=",
"100",
",",
"play_type",
"=",
"PLAY_WAIT_FOR_COMPLETE",
")",
":",
"self",
".",
"_validate_play_type",
"(",
"play_type",
")",
"try",
":",
"freq",
"=",
"self",
".",
"_NOTE_FRE... | Plays a note, given by its name as defined in ``_NOTE_FREQUENCIES``.
:param string note: The note symbol with its octave number
:param float duration: Tone duration, in seconds
:param int volume: The play volume, in percent of maximum volume
:param play_type: The behavior of ``play_not... | [
"Plays",
"a",
"note",
"given",
"by",
"its",
"name",
"as",
"defined",
"in",
"_NOTE_FREQUENCIES",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sound.py#L224-L249 |
247,154 | ev3dev/ev3dev-lang-python | ev3dev2/sound.py | Sound.speak | def speak(self, text, espeak_opts='-a 200 -s 130', volume=100, play_type=PLAY_WAIT_FOR_COMPLETE):
""" Speak the given text aloud.
Uses the ``espeak`` external command.
:param string text: The text to speak
:param string espeak_opts: ``espeak`` command options (advanced usage)
:... | python | def speak(self, text, espeak_opts='-a 200 -s 130', volume=100, play_type=PLAY_WAIT_FOR_COMPLETE):
self._validate_play_type(play_type)
self.set_volume(volume)
with open(os.devnull, 'w') as n:
cmd_line = ['/usr/bin/espeak', '--stdout'] + shlex.split(espeak_opts) + [shlex.quote(text)]
... | [
"def",
"speak",
"(",
"self",
",",
"text",
",",
"espeak_opts",
"=",
"'-a 200 -s 130'",
",",
"volume",
"=",
"100",
",",
"play_type",
"=",
"PLAY_WAIT_FOR_COMPLETE",
")",
":",
"self",
".",
"_validate_play_type",
"(",
"play_type",
")",
"self",
".",
"set_volume",
... | Speak the given text aloud.
Uses the ``espeak`` external command.
:param string text: The text to speak
:param string espeak_opts: ``espeak`` command options (advanced usage)
:param int volume: The play volume, in percent of maximum volume
:param play_type: The behavior of ``s... | [
"Speak",
"the",
"given",
"text",
"aloud",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sound.py#L289-L323 |
247,155 | ev3dev/ev3dev-lang-python | ev3dev2/sound.py | Sound.play_song | def play_song(self, song, tempo=120, delay=0.05):
""" Plays a song provided as a list of tuples containing the note name and its
value using music conventional notation instead of numerical values for frequency
and duration.
It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and... | python | def play_song(self, song, tempo=120, delay=0.05):
if tempo <= 0:
raise ValueError('invalid tempo (%s)' % tempo)
if delay < 0:
raise ValueError('invalid delay (%s)' % delay)
delay_ms = int(delay * 1000)
meas_duration_ms = 60000 / tempo * 4 # we only support ... | [
"def",
"play_song",
"(",
"self",
",",
"song",
",",
"tempo",
"=",
"120",
",",
"delay",
"=",
"0.05",
")",
":",
"if",
"tempo",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'invalid tempo (%s)'",
"%",
"tempo",
")",
"if",
"delay",
"<",
"0",
":",
"raise",
... | Plays a song provided as a list of tuples containing the note name and its
value using music conventional notation instead of numerical values for frequency
and duration.
It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and durations (e.g. ``q``, ``h``).
For an exhaustive lis... | [
"Plays",
"a",
"song",
"provided",
"as",
"a",
"list",
"of",
"tuples",
"containing",
"the",
"note",
"name",
"and",
"its",
"value",
"using",
"music",
"conventional",
"notation",
"instead",
"of",
"numerical",
"values",
"for",
"frequency",
"and",
"duration",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sound.py#L380-L485 |
247,156 | ev3dev/ev3dev-lang-python | ev3dev2/__init__.py | list_device_names | def list_device_names(class_path, name_pattern, **kwargs):
"""
This is a generator function that lists names of all devices matching the
provided parameters.
Parameters:
class_path: class path of the device, a subdirectory of /sys/class.
For example, '/sys/class/tacho-motor'.
... | python | def list_device_names(class_path, name_pattern, **kwargs):
if not os.path.isdir(class_path):
return
def matches(attribute, pattern):
try:
with io.FileIO(attribute) as f:
value = f.read().strip().decode()
except:
return False
if isinstance... | [
"def",
"list_device_names",
"(",
"class_path",
",",
"name_pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"class_path",
")",
":",
"return",
"def",
"matches",
"(",
"attribute",
",",
"pattern",
")",
":",
"t... | This is a generator function that lists names of all devices matching the
provided parameters.
Parameters:
class_path: class path of the device, a subdirectory of /sys/class.
For example, '/sys/class/tacho-motor'.
name_pattern: pattern that device name should match.
For ... | [
"This",
"is",
"a",
"generator",
"function",
"that",
"lists",
"names",
"of",
"all",
"devices",
"matching",
"the",
"provided",
"parameters",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/__init__.py#L100-L136 |
247,157 | ev3dev/ev3dev-lang-python | ev3dev2/__init__.py | list_devices | def list_devices(class_name, name_pattern, **kwargs):
"""
This is a generator function that takes same arguments as `Device` class
and enumerates all devices present in the system that match the provided
arguments.
Parameters:
class_name: class name of the device, a subdirectory of /sys/cla... | python | def list_devices(class_name, name_pattern, **kwargs):
classpath = abspath(Device.DEVICE_ROOT_PATH + '/' + class_name)
return (Device(class_name, name, name_exact=True)
for name in list_device_names(classpath, name_pattern, **kwargs)) | [
"def",
"list_devices",
"(",
"class_name",
",",
"name_pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"classpath",
"=",
"abspath",
"(",
"Device",
".",
"DEVICE_ROOT_PATH",
"+",
"'/'",
"+",
"class_name",
")",
"return",
"(",
"Device",
"(",
"class_name",
",",
"nam... | This is a generator function that takes same arguments as `Device` class
and enumerates all devices present in the system that match the provided
arguments.
Parameters:
class_name: class name of the device, a subdirectory of /sys/class.
For example, 'tacho-motor'.
name_pattern: ... | [
"This",
"is",
"a",
"generator",
"function",
"that",
"takes",
"same",
"arguments",
"as",
"Device",
"class",
"and",
"enumerates",
"all",
"devices",
"present",
"in",
"the",
"system",
"that",
"match",
"the",
"provided",
"arguments",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/__init__.py#L352-L372 |
247,158 | ev3dev/ev3dev-lang-python | ev3dev2/__init__.py | Device._get_attribute | def _get_attribute(self, attribute, name):
"""Device attribute getter"""
try:
if attribute is None:
attribute = self._attribute_file_open( name )
else:
attribute.seek(0)
return attribute, attribute.read().strip().decode()
except... | python | def _get_attribute(self, attribute, name):
try:
if attribute is None:
attribute = self._attribute_file_open( name )
else:
attribute.seek(0)
return attribute, attribute.read().strip().decode()
except Exception as ex:
self._ra... | [
"def",
"_get_attribute",
"(",
"self",
",",
"attribute",
",",
"name",
")",
":",
"try",
":",
"if",
"attribute",
"is",
"None",
":",
"attribute",
"=",
"self",
".",
"_attribute_file_open",
"(",
"name",
")",
"else",
":",
"attribute",
".",
"seek",
"(",
"0",
"... | Device attribute getter | [
"Device",
"attribute",
"getter"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/__init__.py#L240-L249 |
247,159 | ev3dev/ev3dev-lang-python | ev3dev2/__init__.py | Device._set_attribute | def _set_attribute(self, attribute, name, value):
"""Device attribute setter"""
try:
if attribute is None:
attribute = self._attribute_file_open( name )
else:
attribute.seek(0)
if isinstance(value, str):
value = value.e... | python | def _set_attribute(self, attribute, name, value):
try:
if attribute is None:
attribute = self._attribute_file_open( name )
else:
attribute.seek(0)
if isinstance(value, str):
value = value.encode()
attribute.write(va... | [
"def",
"_set_attribute",
"(",
"self",
",",
"attribute",
",",
"name",
",",
"value",
")",
":",
"try",
":",
"if",
"attribute",
"is",
"None",
":",
"attribute",
"=",
"self",
".",
"_attribute_file_open",
"(",
"name",
")",
"else",
":",
"attribute",
".",
"seek",... | Device attribute setter | [
"Device",
"attribute",
"setter"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/__init__.py#L251-L265 |
247,160 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer.shutdown | def shutdown(self):
"""Close all file handles and stop all motors."""
self.stop_balance.set() # Stop balance thread
self.motor_left.stop()
self.motor_right.stop()
self.gyro_file.close()
self.touch_file.close()
self.encoder_left_file.close()
self.encoder_r... | python | def shutdown(self):
self.stop_balance.set() # Stop balance thread
self.motor_left.stop()
self.motor_right.stop()
self.gyro_file.close()
self.touch_file.close()
self.encoder_left_file.close()
self.encoder_right_file.close()
self.dc_left_file.close()
... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"stop_balance",
".",
"set",
"(",
")",
"# Stop balance thread",
"self",
".",
"motor_left",
".",
"stop",
"(",
")",
"self",
".",
"motor_right",
".",
"stop",
"(",
")",
"self",
".",
"gyro_file",
".",
"c... | Close all file handles and stop all motors. | [
"Close",
"all",
"file",
"handles",
"and",
"stop",
"all",
"motors",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L162-L172 |
247,161 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer._fast_read | def _fast_read(self, infile):
"""Function for fast reading from sensor files."""
infile.seek(0)
return(int(infile.read().decode().strip())) | python | def _fast_read(self, infile):
infile.seek(0)
return(int(infile.read().decode().strip())) | [
"def",
"_fast_read",
"(",
"self",
",",
"infile",
")",
":",
"infile",
".",
"seek",
"(",
"0",
")",
"return",
"(",
"int",
"(",
"infile",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
".",
"strip",
"(",
")",
")",
")"
] | Function for fast reading from sensor files. | [
"Function",
"for",
"fast",
"reading",
"from",
"sensor",
"files",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L174-L177 |
247,162 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer._fast_write | def _fast_write(self, outfile, value):
"""Function for fast writing to motor files."""
outfile.truncate(0)
outfile.write(str(int(value)))
outfile.flush() | python | def _fast_write(self, outfile, value):
outfile.truncate(0)
outfile.write(str(int(value)))
outfile.flush() | [
"def",
"_fast_write",
"(",
"self",
",",
"outfile",
",",
"value",
")",
":",
"outfile",
".",
"truncate",
"(",
"0",
")",
"outfile",
".",
"write",
"(",
"str",
"(",
"int",
"(",
"value",
")",
")",
")",
"outfile",
".",
"flush",
"(",
")"
] | Function for fast writing to motor files. | [
"Function",
"for",
"fast",
"writing",
"to",
"motor",
"files",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L179-L183 |
247,163 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer._set_duty | def _set_duty(self, motor_duty_file, duty, friction_offset,
voltage_comp):
"""Function to set the duty cycle of the motors."""
# Compensate for nominal voltage and round the input
duty_int = int(round(duty*voltage_comp))
# Add or subtract offset and clamp the value bet... | python | def _set_duty(self, motor_duty_file, duty, friction_offset,
voltage_comp):
# Compensate for nominal voltage and round the input
duty_int = int(round(duty*voltage_comp))
# Add or subtract offset and clamp the value between -100 and 100
if duty_int > 0:
duty_... | [
"def",
"_set_duty",
"(",
"self",
",",
"motor_duty_file",
",",
"duty",
",",
"friction_offset",
",",
"voltage_comp",
")",
":",
"# Compensate for nominal voltage and round the input",
"duty_int",
"=",
"int",
"(",
"round",
"(",
"duty",
"*",
"voltage_comp",
")",
")",
"... | Function to set the duty cycle of the motors. | [
"Function",
"to",
"set",
"the",
"duty",
"cycle",
"of",
"the",
"motors",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L185-L198 |
247,164 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer.balance | def balance(self):
"""Run the _balance method as a thread."""
balance_thread = threading.Thread(target=self._balance)
balance_thread.start() | python | def balance(self):
balance_thread = threading.Thread(target=self._balance)
balance_thread.start() | [
"def",
"balance",
"(",
"self",
")",
":",
"balance_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_balance",
")",
"balance_thread",
".",
"start",
"(",
")"
] | Run the _balance method as a thread. | [
"Run",
"the",
"_balance",
"method",
"as",
"a",
"thread",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L212-L215 |
247,165 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer._move | def _move(self, speed=0, steering=0, seconds=None):
"""Move robot."""
self.drive_queue.put((speed, steering))
if seconds is not None:
time.sleep(seconds)
self.drive_queue.put((0, 0))
self.drive_queue.join() | python | def _move(self, speed=0, steering=0, seconds=None):
self.drive_queue.put((speed, steering))
if seconds is not None:
time.sleep(seconds)
self.drive_queue.put((0, 0))
self.drive_queue.join() | [
"def",
"_move",
"(",
"self",
",",
"speed",
"=",
"0",
",",
"steering",
"=",
"0",
",",
"seconds",
"=",
"None",
")",
":",
"self",
".",
"drive_queue",
".",
"put",
"(",
"(",
"speed",
",",
"steering",
")",
")",
"if",
"seconds",
"is",
"not",
"None",
":"... | Move robot. | [
"Move",
"robot",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L475-L481 |
247,166 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer.move_forward | def move_forward(self, seconds=None):
"""Move robot forward."""
self._move(speed=SPEED_MAX, steering=0, seconds=seconds) | python | def move_forward(self, seconds=None):
self._move(speed=SPEED_MAX, steering=0, seconds=seconds) | [
"def",
"move_forward",
"(",
"self",
",",
"seconds",
"=",
"None",
")",
":",
"self",
".",
"_move",
"(",
"speed",
"=",
"SPEED_MAX",
",",
"steering",
"=",
"0",
",",
"seconds",
"=",
"seconds",
")"
] | Move robot forward. | [
"Move",
"robot",
"forward",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L483-L485 |
247,167 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer.move_backward | def move_backward(self, seconds=None):
"""Move robot backward."""
self._move(speed=-SPEED_MAX, steering=0, seconds=seconds) | python | def move_backward(self, seconds=None):
self._move(speed=-SPEED_MAX, steering=0, seconds=seconds) | [
"def",
"move_backward",
"(",
"self",
",",
"seconds",
"=",
"None",
")",
":",
"self",
".",
"_move",
"(",
"speed",
"=",
"-",
"SPEED_MAX",
",",
"steering",
"=",
"0",
",",
"seconds",
"=",
"seconds",
")"
] | Move robot backward. | [
"Move",
"robot",
"backward",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L487-L489 |
247,168 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer.rotate_left | def rotate_left(self, seconds=None):
"""Rotate robot left."""
self._move(speed=0, steering=STEER_MAX, seconds=seconds) | python | def rotate_left(self, seconds=None):
self._move(speed=0, steering=STEER_MAX, seconds=seconds) | [
"def",
"rotate_left",
"(",
"self",
",",
"seconds",
"=",
"None",
")",
":",
"self",
".",
"_move",
"(",
"speed",
"=",
"0",
",",
"steering",
"=",
"STEER_MAX",
",",
"seconds",
"=",
"seconds",
")"
] | Rotate robot left. | [
"Rotate",
"robot",
"left",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L491-L493 |
247,169 | ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | GyroBalancer.rotate_right | def rotate_right(self, seconds=None):
"""Rotate robot right."""
self._move(speed=0, steering=-STEER_MAX, seconds=seconds) | python | def rotate_right(self, seconds=None):
self._move(speed=0, steering=-STEER_MAX, seconds=seconds) | [
"def",
"rotate_right",
"(",
"self",
",",
"seconds",
"=",
"None",
")",
":",
"self",
".",
"_move",
"(",
"speed",
"=",
"0",
",",
"steering",
"=",
"-",
"STEER_MAX",
",",
"seconds",
"=",
"seconds",
")"
] | Rotate robot right. | [
"Rotate",
"robot",
"right",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L495-L497 |
247,170 | ev3dev/ev3dev-lang-python | ev3dev2/button.py | ButtonBase.evdev_device | def evdev_device(self):
"""
Return our corresponding evdev device object
"""
devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
for device in devices:
if device.name == self.evdev_device_name:
return device
raise Exception("%s: ... | python | def evdev_device(self):
devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
for device in devices:
if device.name == self.evdev_device_name:
return device
raise Exception("%s: could not find evdev device '%s'" % (self, self.evdev_device_name)) | [
"def",
"evdev_device",
"(",
"self",
")",
":",
"devices",
"=",
"[",
"evdev",
".",
"InputDevice",
"(",
"fn",
")",
"for",
"fn",
"in",
"evdev",
".",
"list_devices",
"(",
")",
"]",
"for",
"device",
"in",
"devices",
":",
"if",
"device",
".",
"name",
"==",
... | Return our corresponding evdev device object | [
"Return",
"our",
"corresponding",
"evdev",
"device",
"object"
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/button.py#L115-L125 |
247,171 | ev3dev/ev3dev-lang-python | ev3dev2/button.py | ButtonBase.wait_for_bump | def wait_for_bump(self, buttons, timeout_ms=None):
"""
Wait for the button to be pressed down and then released.
Both actions must happen within timeout_ms.
"""
start_time = time.time()
if self.wait_for_pressed(buttons, timeout_ms):
if timeout_ms is not None:... | python | def wait_for_bump(self, buttons, timeout_ms=None):
start_time = time.time()
if self.wait_for_pressed(buttons, timeout_ms):
if timeout_ms is not None:
timeout_ms -= int((time.time() - start_time) * 1000)
return self.wait_for_released(buttons, timeout_ms)
... | [
"def",
"wait_for_bump",
"(",
"self",
",",
"buttons",
",",
"timeout_ms",
"=",
"None",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"wait_for_pressed",
"(",
"buttons",
",",
"timeout_ms",
")",
":",
"if",
"timeout_ms",
"is",... | Wait for the button to be pressed down and then released.
Both actions must happen within timeout_ms. | [
"Wait",
"for",
"the",
"button",
"to",
"be",
"pressed",
"down",
"and",
"then",
"released",
".",
"Both",
"actions",
"must",
"happen",
"within",
"timeout_ms",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/button.py#L202-L214 |
247,172 | ev3dev/ev3dev-lang-python | ev3dev2/button.py | ButtonEVIO.buttons_pressed | def buttons_pressed(self):
"""
Returns list of names of pressed buttons.
"""
for b in self._buffer_cache:
fcntl.ioctl(self._button_file(b), self.EVIOCGKEY, self._buffer_cache[b])
pressed = []
for k, v in self._buttons.items():
buf = self._buffer_c... | python | def buttons_pressed(self):
for b in self._buffer_cache:
fcntl.ioctl(self._button_file(b), self.EVIOCGKEY, self._buffer_cache[b])
pressed = []
for k, v in self._buttons.items():
buf = self._buffer_cache[v['name']]
bit = v['value']
if bool(buf[int(... | [
"def",
"buttons_pressed",
"(",
"self",
")",
":",
"for",
"b",
"in",
"self",
".",
"_buffer_cache",
":",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"_button_file",
"(",
"b",
")",
",",
"self",
".",
"EVIOCGKEY",
",",
"self",
".",
"_buffer_cache",
"[",
"b",
... | Returns list of names of pressed buttons. | [
"Returns",
"list",
"of",
"names",
"of",
"pressed",
"buttons",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/button.py#L255-L270 |
247,173 | aws/sagemaker-containers | src/sagemaker_containers/_mpi.py | _orted_process | def _orted_process():
"""Waits maximum of 5 minutes for orted process to start"""
for i in range(5 * 60):
procs = [p for p in psutil.process_iter(attrs=['name']) if p.info['name'] == 'orted']
if procs:
return procs
time.sleep(1) | python | def _orted_process():
for i in range(5 * 60):
procs = [p for p in psutil.process_iter(attrs=['name']) if p.info['name'] == 'orted']
if procs:
return procs
time.sleep(1) | [
"def",
"_orted_process",
"(",
")",
":",
"for",
"i",
"in",
"range",
"(",
"5",
"*",
"60",
")",
":",
"procs",
"=",
"[",
"p",
"for",
"p",
"in",
"psutil",
".",
"process_iter",
"(",
"attrs",
"=",
"[",
"'name'",
"]",
")",
"if",
"p",
".",
"info",
"[",
... | Waits maximum of 5 minutes for orted process to start | [
"Waits",
"maximum",
"of",
"5",
"minutes",
"for",
"orted",
"process",
"to",
"start"
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_mpi.py#L75-L82 |
247,174 | aws/sagemaker-containers | src/sagemaker_containers/_mpi.py | _parse_custom_mpi_options | def _parse_custom_mpi_options(custom_mpi_options):
# type: (str) -> Tuple[argparse.Namespace, List[str]]
"""Parse custom MPI options provided by user. Known options default value will be overridden
and unknown options would be identified separately."""
parser = argparse.ArgumentParser()
parser.add_... | python | def _parse_custom_mpi_options(custom_mpi_options):
# type: (str) -> Tuple[argparse.Namespace, List[str]]
parser = argparse.ArgumentParser()
parser.add_argument('--NCCL_DEBUG', default="INFO", type=str)
return parser.parse_known_args(custom_mpi_options.split()) | [
"def",
"_parse_custom_mpi_options",
"(",
"custom_mpi_options",
")",
":",
"# type: (str) -> Tuple[argparse.Namespace, List[str]]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--NCCL_DEBUG'",
",",
"default",
"=",
"\"INFO... | Parse custom MPI options provided by user. Known options default value will be overridden
and unknown options would be identified separately. | [
"Parse",
"custom",
"MPI",
"options",
"provided",
"by",
"user",
".",
"Known",
"options",
"default",
"value",
"will",
"be",
"overridden",
"and",
"unknown",
"options",
"would",
"be",
"identified",
"separately",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_mpi.py#L230-L238 |
247,175 | aws/sagemaker-containers | src/sagemaker_containers/_modules.py | download_and_install | def download_and_install(uri, name=DEFAULT_MODULE_NAME, cache=True):
# type: (str, str, bool) -> None
"""Download, prepare and install a compressed tar file from S3 or local directory as a module.
The SageMaker Python SDK saves the user provided scripts as compressed tar files in S3.
This function down... | python | def download_and_install(uri, name=DEFAULT_MODULE_NAME, cache=True):
# type: (str, str, bool) -> None
should_use_cache = cache and exists(name)
if not should_use_cache:
with _files.tmpdir() as tmpdir:
if uri.startswith('s3://'):
dst = os.path.join(tmpdir, 'tar_file')
... | [
"def",
"download_and_install",
"(",
"uri",
",",
"name",
"=",
"DEFAULT_MODULE_NAME",
",",
"cache",
"=",
"True",
")",
":",
"# type: (str, str, bool) -> None",
"should_use_cache",
"=",
"cache",
"and",
"exists",
"(",
"name",
")",
"if",
"not",
"should_use_cache",
":",
... | Download, prepare and install a compressed tar file from S3 or local directory as a module.
The SageMaker Python SDK saves the user provided scripts as compressed tar files in S3.
This function downloads this compressed file and, if provided, transforms it
into a module before installing it.
This meth... | [
"Download",
"prepare",
"and",
"install",
"a",
"compressed",
"tar",
"file",
"from",
"S3",
"or",
"local",
"directory",
"as",
"a",
"module",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_modules.py#L126-L159 |
247,176 | aws/sagemaker-containers | src/sagemaker_containers/_modules.py | run | def run(module_name, args=None, env_vars=None, wait=True, capture_error=False):
# type: (str, list, dict, bool, bool) -> subprocess.Popen
"""Run Python module as a script.
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you mus... | python | def run(module_name, args=None, env_vars=None, wait=True, capture_error=False):
# type: (str, list, dict, bool, bool) -> subprocess.Popen
args = args or []
env_vars = env_vars or {}
cmd = [_process.python_executable(), '-m', module_name] + args
_logging.log_script_invocation(cmd, env_vars)
if... | [
"def",
"run",
"(",
"module_name",
",",
"args",
"=",
"None",
",",
"env_vars",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"capture_error",
"=",
"False",
")",
":",
"# type: (str, list, dict, bool, bool) -> subprocess.Popen",
"args",
"=",
"args",
"or",
"[",
"]",
... | Run Python module as a script.
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you must not give a file extension (.py). The module name should be a valid
absolute Python module name, but the implementation may not always enforce t... | [
"Run",
"Python",
"module",
"as",
"a",
"script",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_modules.py#L162-L225 |
247,177 | aws/sagemaker-containers | src/sagemaker_containers/_modules.py | run_module | def run_module(uri, args, env_vars=None, name=DEFAULT_MODULE_NAME, cache=None, wait=True, capture_error=False):
# type: (str, list, dict, str, bool, bool, bool) -> subprocess.Popen
"""Download, prepare and executes a compressed tar file from S3 or provided directory as a module.
SageMaker Python SDK saves ... | python | def run_module(uri, args, env_vars=None, name=DEFAULT_MODULE_NAME, cache=None, wait=True, capture_error=False):
# type: (str, list, dict, str, bool, bool, bool) -> subprocess.Popen
_warning_cache_deprecation(cache)
env_vars = env_vars or {}
env_vars = env_vars.copy()
_files.download_and_extract(uri... | [
"def",
"run_module",
"(",
"uri",
",",
"args",
",",
"env_vars",
"=",
"None",
",",
"name",
"=",
"DEFAULT_MODULE_NAME",
",",
"cache",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"capture_error",
"=",
"False",
")",
":",
"# type: (str, list, dict, str, bool, bool, ... | Download, prepare and executes a compressed tar file from S3 or provided directory as a module.
SageMaker Python SDK saves the user provided scripts as compressed tar files in S3
https://github.com/aws/sagemaker-python-sdk.
This function downloads this compressed file, transforms it as a module, and execut... | [
"Download",
"prepare",
"and",
"executes",
"a",
"compressed",
"tar",
"file",
"from",
"S3",
"or",
"provided",
"directory",
"as",
"a",
"module",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_modules.py#L254-L281 |
247,178 | aws/sagemaker-containers | src/sagemaker_containers/_worker.py | Request.content_type | def content_type(self): # type: () -> str
"""The request's content-type.
Returns:
(str): The value, if any, of the header 'ContentType' (used by some AWS services) and 'Content-Type'.
Otherwise, returns 'application/json' as default.
"""
# todo(mvsusp): ... | python | def content_type(self): # type: () -> str
# todo(mvsusp): consider a better default content-type
return self.headers.get('ContentType') or self.headers.get(
'Content-Type') or _content_types.JSON | [
"def",
"content_type",
"(",
"self",
")",
":",
"# type: () -> str",
"# todo(mvsusp): consider a better default content-type",
"return",
"self",
".",
"headers",
".",
"get",
"(",
"'ContentType'",
")",
"or",
"self",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")"... | The request's content-type.
Returns:
(str): The value, if any, of the header 'ContentType' (used by some AWS services) and 'Content-Type'.
Otherwise, returns 'application/json' as default. | [
"The",
"request",
"s",
"content",
"-",
"type",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_worker.py#L135-L144 |
247,179 | aws/sagemaker-containers | src/sagemaker_containers/_worker.py | Request.accept | def accept(self): # type: () -> str
"""The content-type for the response to the client.
Returns:
(str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT
environment variable.
"""
accept = self.headers.get('Accept... | python | def accept(self): # type: () -> str
accept = self.headers.get('Accept')
if not accept or accept == _content_types.ANY:
return self._default_accept
else:
return accept | [
"def",
"accept",
"(",
"self",
")",
":",
"# type: () -> str",
"accept",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'Accept'",
")",
"if",
"not",
"accept",
"or",
"accept",
"==",
"_content_types",
".",
"ANY",
":",
"return",
"self",
".",
"_default_accept",
... | The content-type for the response to the client.
Returns:
(str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT
environment variable. | [
"The",
"content",
"-",
"type",
"for",
"the",
"response",
"to",
"the",
"client",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_worker.py#L147-L159 |
247,180 | aws/sagemaker-containers | src/sagemaker_containers/_worker.py | Request.content | def content(self): # type: () -> object
"""The request incoming data.
It automatic decodes from utf-8
Returns:
(obj): incoming data
"""
as_text = self.content_type in _content_types.UTF8_TYPES
return self.get_data(as_text=as_text) | python | def content(self): # type: () -> object
as_text = self.content_type in _content_types.UTF8_TYPES
return self.get_data(as_text=as_text) | [
"def",
"content",
"(",
"self",
")",
":",
"# type: () -> object",
"as_text",
"=",
"self",
".",
"content_type",
"in",
"_content_types",
".",
"UTF8_TYPES",
"return",
"self",
".",
"get_data",
"(",
"as_text",
"=",
"as_text",
")"
] | The request incoming data.
It automatic decodes from utf-8
Returns:
(obj): incoming data | [
"The",
"request",
"incoming",
"data",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_worker.py#L162-L172 |
247,181 | aws/sagemaker-containers | src/sagemaker_containers/entry_point.py | run | def run(uri,
user_entry_point,
args,
env_vars=None,
wait=True,
capture_error=False,
runner=_runner.ProcessRunnerType,
extra_opts=None):
# type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None
"""Download, prepa... | python | def run(uri,
user_entry_point,
args,
env_vars=None,
wait=True,
capture_error=False,
runner=_runner.ProcessRunnerType,
extra_opts=None):
# type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None
env_vars = env_var... | [
"def",
"run",
"(",
"uri",
",",
"user_entry_point",
",",
"args",
",",
"env_vars",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"capture_error",
"=",
"False",
",",
"runner",
"=",
"_runner",
".",
"ProcessRunnerType",
",",
"extra_opts",
"=",
"None",
")",
":",... | Download, prepare and executes a compressed tar file from S3 or provided directory as an user
entrypoint. Runs the user entry point, passing env_vars as environment variables and args as command
arguments.
If the entry point is:
- A Python package: executes the packages as >>> env_vars python -m mo... | [
"Download",
"prepare",
"and",
"executes",
"a",
"compressed",
"tar",
"file",
"from",
"S3",
"or",
"provided",
"directory",
"as",
"an",
"user",
"entrypoint",
".",
"Runs",
"the",
"user",
"entry",
"point",
"passing",
"env_vars",
"as",
"environment",
"variables",
"a... | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/entry_point.py#L22-L89 |
247,182 | aws/sagemaker-containers | src/sagemaker_containers/_logging.py | configure_logger | def configure_logger(level, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s'):
# type: (int, str) -> None
"""Set logger configuration.
Args:
level (int): Logger level
format (str): Logger format
"""
logging.basicConfig(format=format, level=level)
if level >= logging... | python | def configure_logger(level, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s'):
# type: (int, str) -> None
logging.basicConfig(format=format, level=level)
if level >= logging.INFO:
logging.getLogger('boto3').setLevel(logging.INFO)
logging.getLogger('s3transfer').setLevel(logging.... | [
"def",
"configure_logger",
"(",
"level",
",",
"format",
"=",
"'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'",
")",
":",
"# type: (int, str) -> None",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"format",
",",
"level",
"=",
"level",
")",
"if",
"level",
... | Set logger configuration.
Args:
level (int): Logger level
format (str): Logger format | [
"Set",
"logger",
"configuration",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_logging.py#L25-L38 |
247,183 | aws/sagemaker-containers | src/sagemaker_containers/_intermediate_output.py | _timestamp | def _timestamp():
"""Return a timestamp with microsecond precision."""
moment = time.time()
moment_us = repr(moment).split('.')[1]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_us), time.gmtime(moment)) | python | def _timestamp():
moment = time.time()
moment_us = repr(moment).split('.')[1]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_us), time.gmtime(moment)) | [
"def",
"_timestamp",
"(",
")",
":",
"moment",
"=",
"time",
".",
"time",
"(",
")",
"moment_us",
"=",
"repr",
"(",
"moment",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"return",
"time",
".",
"strftime",
"(",
"\"%Y-%m-%d-%H-%M-%S-{}\"",
".",
"fo... | Return a timestamp with microsecond precision. | [
"Return",
"a",
"timestamp",
"with",
"microsecond",
"precision",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_intermediate_output.py#L36-L40 |
247,184 | aws/sagemaker-containers | src/sagemaker_containers/_mapping.py | split_by_criteria | def split_by_criteria(dictionary, keys=None, prefix=None): # type: (dict, set or list or tuple) -> SplitResultSpec
"""Split a dictionary in two by the provided keys.
Args:
dictionary (dict[str, object]): A Python dictionary
keys (sequence [str]): A sequence of keys which will be added the spli... | python | def split_by_criteria(dictionary, keys=None, prefix=None): # type: (dict, set or list or tuple) -> SplitResultSpec
keys = keys or []
keys = set(keys)
included_items = {k: dictionary[k] for k in dictionary.keys() if k in keys or (prefix and k.startswith(prefix))}
excluded_items = {k: dictionary[k] for ... | [
"def",
"split_by_criteria",
"(",
"dictionary",
",",
"keys",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"# type: (dict, set or list or tuple) -> SplitResultSpec",
"keys",
"=",
"keys",
"or",
"[",
"]",
"keys",
"=",
"set",
"(",
"keys",
")",
"included_items",... | Split a dictionary in two by the provided keys.
Args:
dictionary (dict[str, object]): A Python dictionary
keys (sequence [str]): A sequence of keys which will be added the split criteria
prefix (str): A prefix which will be added the split criteria
Returns:
`SplitResultSpec` : ... | [
"Split",
"a",
"dictionary",
"in",
"two",
"by",
"the",
"provided",
"keys",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_mapping.py#L119-L140 |
247,185 | aws/sagemaker-containers | src/sagemaker_containers/_transformer.py | default_output_fn | def default_output_fn(prediction, accept):
"""Function responsible to serialize the prediction for the response.
Args:
prediction (obj): prediction returned by predict_fn .
accept (str): accept content-type expected by the client.
Returns:
(worker.Response): a Flask response object... | python | def default_output_fn(prediction, accept):
return _worker.Response(response=_encoders.encode(prediction, accept), mimetype=accept) | [
"def",
"default_output_fn",
"(",
"prediction",
",",
"accept",
")",
":",
"return",
"_worker",
".",
"Response",
"(",
"response",
"=",
"_encoders",
".",
"encode",
"(",
"prediction",
",",
"accept",
")",
",",
"mimetype",
"=",
"accept",
")"
] | Function responsible to serialize the prediction for the response.
Args:
prediction (obj): prediction returned by predict_fn .
accept (str): accept content-type expected by the client.
Returns:
(worker.Response): a Flask response object with the following args:
* Args:
... | [
"Function",
"responsible",
"to",
"serialize",
"the",
"prediction",
"for",
"the",
"response",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_transformer.py#L77-L91 |
247,186 | aws/sagemaker-containers | src/sagemaker_containers/_transformer.py | Transformer.transform | def transform(self): # type: () -> _worker.Response
"""Take a request with input data, deserialize it, make a prediction, and return a
serialized response.
Returns:
sagemaker_containers.beta.framework.worker.Response: a Flask response object with
the following args:... | python | def transform(self): # type: () -> _worker.Response
request = _worker.Request()
result = self._transform_fn(self._model, request.content, request.content_type, request.accept)
if isinstance(result, tuple):
# transforms tuple in Response for backwards compatibility
retur... | [
"def",
"transform",
"(",
"self",
")",
":",
"# type: () -> _worker.Response",
"request",
"=",
"_worker",
".",
"Request",
"(",
")",
"result",
"=",
"self",
".",
"_transform_fn",
"(",
"self",
".",
"_model",
",",
"request",
".",
"content",
",",
"request",
".",
... | Take a request with input data, deserialize it, make a prediction, and return a
serialized response.
Returns:
sagemaker_containers.beta.framework.worker.Response: a Flask response object with
the following args:
* response: the serialized data to return
... | [
"Take",
"a",
"request",
"with",
"input",
"data",
"deserialize",
"it",
"make",
"a",
"prediction",
"and",
"return",
"a",
"serialized",
"response",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_transformer.py#L159-L177 |
247,187 | aws/sagemaker-containers | src/sagemaker_containers/_transformer.py | Transformer._default_transform_fn | def _default_transform_fn(self, model, content, content_type, accept):
"""Make predictions against the model and return a serialized response.
This serves as the default implementation of transform_fn, used when the user has not
implemented one themselves.
Args:
model (obj)... | python | def _default_transform_fn(self, model, content, content_type, accept):
try:
data = self._input_fn(content, content_type)
except _errors.UnsupportedFormatError as e:
return self._error_response(e, http_client.UNSUPPORTED_MEDIA_TYPE)
prediction = self._predict_fn(data, mod... | [
"def",
"_default_transform_fn",
"(",
"self",
",",
"model",
",",
"content",
",",
"content_type",
",",
"accept",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"_input_fn",
"(",
"content",
",",
"content_type",
")",
"except",
"_errors",
".",
"UnsupportedFormat... | Make predictions against the model and return a serialized response.
This serves as the default implementation of transform_fn, used when the user has not
implemented one themselves.
Args:
model (obj): model loaded by model_fn.
content: request content.
cont... | [
"Make",
"predictions",
"against",
"the",
"model",
"and",
"return",
"a",
"serialized",
"response",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_transformer.py#L179-L208 |
247,188 | aws/sagemaker-containers | src/sagemaker_containers/__init__.py | training_env | def training_env(): # type: () -> _env.TrainingEnv
"""Create a TrainingEnv.
Returns:
TrainingEnv: an instance of TrainingEnv
"""
from sagemaker_containers import _env
return _env.TrainingEnv(
resource_config=_env.read_resource_config(),
input_data_config=_env.read_input_d... | python | def training_env(): # type: () -> _env.TrainingEnv
from sagemaker_containers import _env
return _env.TrainingEnv(
resource_config=_env.read_resource_config(),
input_data_config=_env.read_input_data_config(),
hyperparameters=_env.read_hyperparameters()) | [
"def",
"training_env",
"(",
")",
":",
"# type: () -> _env.TrainingEnv",
"from",
"sagemaker_containers",
"import",
"_env",
"return",
"_env",
".",
"TrainingEnv",
"(",
"resource_config",
"=",
"_env",
".",
"read_resource_config",
"(",
")",
",",
"input_data_config",
"=",
... | Create a TrainingEnv.
Returns:
TrainingEnv: an instance of TrainingEnv | [
"Create",
"a",
"TrainingEnv",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/__init__.py#L16-L28 |
247,189 | aws/sagemaker-containers | src/sagemaker_containers/_env.py | _write_json | def _write_json(obj, path): # type: (object, str) -> None
"""Writes a serializeable object as a JSON file"""
with open(path, 'w') as f:
json.dump(obj, f) | python | def _write_json(obj, path): # type: (object, str) -> None
with open(path, 'w') as f:
json.dump(obj, f) | [
"def",
"_write_json",
"(",
"obj",
",",
"path",
")",
":",
"# type: (object, str) -> None",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"obj",
",",
"f",
")"
] | Writes a serializeable object as a JSON file | [
"Writes",
"a",
"serializeable",
"object",
"as",
"a",
"JSON",
"file"
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_env.py#L36-L39 |
247,190 | aws/sagemaker-containers | src/sagemaker_containers/_env.py | _create_training_directories | def _create_training_directories():
"""Creates the directory structure and files necessary for training under the base path
"""
logger.info('Creating a new training folder under %s .' % base_dir)
os.makedirs(model_dir)
os.makedirs(input_config_dir)
os.makedirs(output_data_dir)
_write_json(... | python | def _create_training_directories():
logger.info('Creating a new training folder under %s .' % base_dir)
os.makedirs(model_dir)
os.makedirs(input_config_dir)
os.makedirs(output_data_dir)
_write_json({}, hyperparameters_file_dir)
_write_json({}, input_data_config_file_dir)
host_name = socke... | [
"def",
"_create_training_directories",
"(",
")",
":",
"logger",
".",
"info",
"(",
"'Creating a new training folder under %s .'",
"%",
"base_dir",
")",
"os",
".",
"makedirs",
"(",
"model_dir",
")",
"os",
".",
"makedirs",
"(",
"input_config_dir",
")",
"os",
".",
"... | Creates the directory structure and files necessary for training under the base path | [
"Creates",
"the",
"directory",
"structure",
"and",
"files",
"necessary",
"for",
"training",
"under",
"the",
"base",
"path"
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_env.py#L150-L168 |
247,191 | aws/sagemaker-containers | src/sagemaker_containers/_env.py | num_gpus | def num_gpus(): # type: () -> int
"""The number of gpus available in the current container.
Returns:
int: number of gpus available in the current container.
"""
try:
cmd = shlex.split('nvidia-smi --list-gpus')
output = subprocess.check_output(cmd).decode('utf-8')
return... | python | def num_gpus(): # type: () -> int
try:
cmd = shlex.split('nvidia-smi --list-gpus')
output = subprocess.check_output(cmd).decode('utf-8')
return sum([1 for x in output.split('\n') if x.startswith('GPU ')])
except (OSError, subprocess.CalledProcessError):
logger.info('No GPUs dete... | [
"def",
"num_gpus",
"(",
")",
":",
"# type: () -> int",
"try",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"'nvidia-smi --list-gpus'",
")",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"su... | The number of gpus available in the current container.
Returns:
int: number of gpus available in the current container. | [
"The",
"number",
"of",
"gpus",
"available",
"in",
"the",
"current",
"container",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_env.py#L285-L297 |
247,192 | aws/sagemaker-containers | src/sagemaker_containers/_env.py | write_env_vars | def write_env_vars(env_vars=None): # type: (dict) -> None
"""Write the dictionary env_vars in the system, as environment variables.
Args:
env_vars ():
Returns:
"""
env_vars = env_vars or {}
env_vars['PYTHONPATH'] = ':'.join(sys.path)
for name, value in env_vars.items():
... | python | def write_env_vars(env_vars=None): # type: (dict) -> None
env_vars = env_vars or {}
env_vars['PYTHONPATH'] = ':'.join(sys.path)
for name, value in env_vars.items():
os.environ[name] = value | [
"def",
"write_env_vars",
"(",
"env_vars",
"=",
"None",
")",
":",
"# type: (dict) -> None",
"env_vars",
"=",
"env_vars",
"or",
"{",
"}",
"env_vars",
"[",
"'PYTHONPATH'",
"]",
"=",
"':'",
".",
"join",
"(",
"sys",
".",
"path",
")",
"for",
"name",
",",
"valu... | Write the dictionary env_vars in the system, as environment variables.
Args:
env_vars ():
Returns: | [
"Write",
"the",
"dictionary",
"env_vars",
"in",
"the",
"system",
"as",
"environment",
"variables",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_env.py#L925-L938 |
247,193 | aws/sagemaker-containers | src/sagemaker_containers/_env.py | TrainingEnv.to_env_vars | def to_env_vars(self):
"""Environment variable representation of the training environment
Returns:
dict: an instance of dictionary
"""
env = {
'hosts': self.hosts, 'network_interface_name': self.network_interface_name,
'hps': self.hyperparameters, 'u... | python | def to_env_vars(self):
env = {
'hosts': self.hosts, 'network_interface_name': self.network_interface_name,
'hps': self.hyperparameters, 'user_entry_point': self.user_entry_point,
'framework_params': self.additional_framework_parameters,
'resource_config': self.res... | [
"def",
"to_env_vars",
"(",
"self",
")",
":",
"env",
"=",
"{",
"'hosts'",
":",
"self",
".",
"hosts",
",",
"'network_interface_name'",
":",
"self",
".",
"network_interface_name",
",",
"'hps'",
":",
"self",
".",
"hyperparameters",
",",
"'user_entry_point'",
":",
... | Environment variable representation of the training environment
Returns:
dict: an instance of dictionary | [
"Environment",
"variable",
"representation",
"of",
"the",
"training",
"environment"
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_env.py#L641-L671 |
247,194 | aws/sagemaker-containers | src/sagemaker_containers/_encoders.py | array_to_npy | def array_to_npy(array_like): # type: (np.array or Iterable or int or float) -> object
"""Convert an array like object to the NPY format.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
... | python | def array_to_npy(array_like): # type: (np.array or Iterable or int or float) -> object
buffer = BytesIO()
np.save(buffer, array_like)
return buffer.getvalue() | [
"def",
"array_to_npy",
"(",
"array_like",
")",
":",
"# type: (np.array or Iterable or int or float) -> object",
"buffer",
"=",
"BytesIO",
"(",
")",
"np",
".",
"save",
"(",
"buffer",
",",
"array_like",
")",
"return",
"buffer",
".",
"getvalue",
"(",
")"
] | Convert an array like object to the NPY format.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
array_like (np.array or Iterable or int or float): array like object to be co... | [
"Convert",
"an",
"array",
"like",
"object",
"to",
"the",
"NPY",
"format",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L24-L38 |
247,195 | aws/sagemaker-containers | src/sagemaker_containers/_encoders.py | npy_to_numpy | def npy_to_numpy(npy_array): # type: (object) -> np.array
"""Convert an NPY array into numpy.
Args:
npy_array (npy array): to be converted to numpy array
Returns:
(np.array): converted numpy array.
"""
stream = BytesIO(npy_array)
return np.load(stream, allow_pickle=True) | python | def npy_to_numpy(npy_array): # type: (object) -> np.array
stream = BytesIO(npy_array)
return np.load(stream, allow_pickle=True) | [
"def",
"npy_to_numpy",
"(",
"npy_array",
")",
":",
"# type: (object) -> np.array",
"stream",
"=",
"BytesIO",
"(",
"npy_array",
")",
"return",
"np",
".",
"load",
"(",
"stream",
",",
"allow_pickle",
"=",
"True",
")"
] | Convert an NPY array into numpy.
Args:
npy_array (npy array): to be converted to numpy array
Returns:
(np.array): converted numpy array. | [
"Convert",
"an",
"NPY",
"array",
"into",
"numpy",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L41-L50 |
247,196 | aws/sagemaker-containers | src/sagemaker_containers/_encoders.py | array_to_json | def array_to_json(array_like): # type: (np.array or Iterable or int or float) -> str
"""Convert an array like object to JSON.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
... | python | def array_to_json(array_like): # type: (np.array or Iterable or int or float) -> str
def default(_array_like):
if hasattr(_array_like, 'tolist'):
return _array_like.tolist()
return json.JSONEncoder().default(_array_like)
return json.dumps(array_like, default=default) | [
"def",
"array_to_json",
"(",
"array_like",
")",
":",
"# type: (np.array or Iterable or int or float) -> str",
"def",
"default",
"(",
"_array_like",
")",
":",
"if",
"hasattr",
"(",
"_array_like",
",",
"'tolist'",
")",
":",
"return",
"_array_like",
".",
"tolist",
"(",... | Convert an array like object to JSON.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
array_like (np.array or Iterable or int or float): array like object to be converted to... | [
"Convert",
"an",
"array",
"like",
"object",
"to",
"JSON",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L53-L71 |
247,197 | aws/sagemaker-containers | src/sagemaker_containers/_encoders.py | json_to_numpy | def json_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a JSON object to a numpy array.
Args:
string_like (str): JSON string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
... | python | def json_to_numpy(string_like, dtype=None): # type: (str) -> np.array
data = json.loads(string_like)
return np.array(data, dtype=dtype) | [
"def",
"json_to_numpy",
"(",
"string_like",
",",
"dtype",
"=",
"None",
")",
":",
"# type: (str) -> np.array",
"data",
"=",
"json",
".",
"loads",
"(",
"string_like",
")",
"return",
"np",
".",
"array",
"(",
"data",
",",
"dtype",
"=",
"dtype",
")"
] | Convert a JSON object to a numpy array.
Args:
string_like (str): JSON string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
contents of each column, individually. This argument can only b... | [
"Convert",
"a",
"JSON",
"object",
"to",
"a",
"numpy",
"array",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L74-L86 |
247,198 | aws/sagemaker-containers | src/sagemaker_containers/_encoders.py | csv_to_numpy | def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
... | python | def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array
stream = StringIO(string_like)
return np.genfromtxt(stream, dtype=dtype, delimiter=',') | [
"def",
"csv_to_numpy",
"(",
"string_like",
",",
"dtype",
"=",
"None",
")",
":",
"# type: (str) -> np.array",
"stream",
"=",
"StringIO",
"(",
"string_like",
")",
"return",
"np",
".",
"genfromtxt",
"(",
"stream",
",",
"dtype",
"=",
"dtype",
",",
"delimiter",
"... | Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
contents of each column, individually. This argument can only be used to
... | [
"Convert",
"a",
"CSV",
"object",
"to",
"a",
"numpy",
"array",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L89-L101 |
247,199 | aws/sagemaker-containers | src/sagemaker_containers/_encoders.py | array_to_csv | def array_to_csv(array_like): # type: (np.array or Iterable or int or float) -> str
"""Convert an array like object to CSV.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
... | python | def array_to_csv(array_like): # type: (np.array or Iterable or int or float) -> str
stream = StringIO()
np.savetxt(stream, array_like, delimiter=',', fmt='%s')
return stream.getvalue() | [
"def",
"array_to_csv",
"(",
"array_like",
")",
":",
"# type: (np.array or Iterable or int or float) -> str",
"stream",
"=",
"StringIO",
"(",
")",
"np",
".",
"savetxt",
"(",
"stream",
",",
"array_like",
",",
"delimiter",
"=",
"','",
",",
"fmt",
"=",
"'%s'",
")",
... | Convert an array like object to CSV.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
array_like (np.array or Iterable or int or float): array like object to be converted to ... | [
"Convert",
"an",
"array",
"like",
"object",
"to",
"CSV",
"."
] | 0030f07abbaf22a55d986d97274d7a8d1aa1f10c | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L104-L118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.