idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
227,200
def run_to_abs_pos ( self , * * kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN_TO_ABS_POS
Run to an absolute position specified by position_sp and then stop using the action specified in stop_action .
57
22
227,201
def run_to_rel_pos ( self , * * kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN_TO_REL_POS
Run to a position relative to the current position value . The new position will be current position + position_sp . When the new position is reached the motor will stop using the action specified by stop_action .
56
42
227,202
def run_timed ( self , * * kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RUN_TIMED
Run the motor for the amount of time specified in time_sp and then stop the motor using the action specified by stop_action .
51
27
227,203
def stop ( self , * * kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_STOP
Stop any of the run commands before they are complete using the action specified by stop_action .
44
19
227,204
def reset ( self , * * kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_RESET
Reset all of the motor parameter attributes to their default value . This will also have the effect of stopping the motor .
44
24
227,205
def on_for_rotations ( self , speed , rotations , brake = True , block = True ) : speed_sp = self . _speed_native_units ( speed ) self . _set_rel_position_degrees_and_speed_sp ( rotations * 360 , speed_sp ) self . _set_brake ( brake ) self . run_to_rel_pos ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( )
Rotate the motor at speed for rotations
123
9
227,206
def on_for_degrees ( self , speed , degrees , brake = True , block = True ) : speed_sp = self . _speed_native_units ( speed ) self . _set_rel_position_degrees_and_speed_sp ( degrees , speed_sp ) self . _set_brake ( brake ) self . run_to_rel_pos ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( )
Rotate the motor at speed for degrees
119
8
227,207
def on_to_position ( self , speed , position , brake = True , block = True ) : speed = self . _speed_native_units ( speed ) self . speed_sp = int ( round ( speed ) ) self . position_sp = position self . _set_brake ( brake ) self . run_to_abs_pos ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( )
Rotate the motor at speed to position
112
8
227,208
def on_for_seconds ( self , speed , seconds , brake = True , block = True ) : if seconds < 0 : raise ValueError ( "seconds is negative ({})" . format ( seconds ) ) speed = self . _speed_native_units ( speed ) self . speed_sp = int ( round ( speed ) ) self . time_sp = int ( seconds * 1000 ) self . _set_brake ( brake ) self . run_timed ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( )
Rotate the motor at speed for seconds
136
8
227,209
def on ( self , speed , brake = True , block = False ) : speed = self . _speed_native_units ( speed ) self . speed_sp = int ( round ( speed ) ) self . _set_brake ( brake ) self . run_forever ( ) if block : self . wait_until ( 'running' , timeout = WAIT_RUNNING_TIMEOUT ) self . wait_until_not_moving ( )
Rotate the motor at speed for forever
96
8
227,210
def commands ( self ) : self . _commands , value = self . get_attr_set ( self . _commands , 'commands' ) return value
Returns a list of commands supported by the motor controller .
35
11
227,211
def stop_actions ( self ) : self . _stop_actions , value = self . get_attr_set ( self . _stop_actions , 'stop_actions' ) return value
Gets a list of stop actions . Valid values are coast and brake .
40
15
227,212
def mid_pulse_sp ( self ) : self . _mid_pulse_sp , value = self . get_attr_int ( self . _mid_pulse_sp , 'mid_pulse_sp' ) return value
Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the mid position_sp . Default value is 1500 . Valid values are 1300 to 1700 . For example on a 180 degree servo this would be 90 degrees . On continuous rotation servo this is the neutral position_sp where the motor does not turn . You must write to the position_sp attribute for changes to this attribute to take effect .
52
88
227,213
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 .
44
14
227,214
def float ( self , * * kwargs ) : for key in kwargs : setattr ( self , key , kwargs [ key ] ) self . command = self . COMMAND_FLOAT
Remove power from the motor .
45
6
227,215
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 ( )
Stop motors immediately . Configure motors to brake if brake is set .
55
14
227,216
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 # v_l = d_l/t, v_r = d_r/t # therefore, t = d_l/v_l = d_r/v_r if degrees == 0 or ( left_speed_native_units == 0 and right_speed_native_units == 0 ) : left_degrees = degrees right_degrees = degrees # larger speed by magnitude is the "outer" wheel, and rotates the full "degrees" elif abs ( left_speed_native_units ) > abs ( right_speed_native_units ) : left_degrees = degrees right_degrees = abs ( right_speed_native_units / left_speed_native_units ) * degrees else : left_degrees = abs ( left_speed_native_units / right_speed_native_units ) * degrees right_degrees = degrees # Set all parameters self . left_motor . _set_rel_position_degrees_and_speed_sp ( left_degrees , left_speed_native_units ) self . left_motor . _set_brake ( brake ) self . right_motor . _set_rel_position_degrees_and_speed_sp ( right_degrees , right_speed_native_units ) self . right_motor . _set_brake ( brake ) log . debug ( "{}: on_for_degrees {}" . format ( self , degrees ) ) # These debugs involve disk I/O to pull position and position_sp so only uncomment # if you need to troubleshoot in more detail. # log.debug("{}: left_speed {}, left_speed_native_units {}, left_degrees {}, left-position {}->{}".format( # self, left_speed, left_speed_native_units, left_degrees, # self.left_motor.position, self.left_motor.position_sp)) # log.debug("{}: right_speed {}, right_speed_native_units {}, right_degrees {}, right-position {}->{}".format( # self, right_speed, right_speed_native_units, right_degrees, # self.right_motor.position, self.right_motor.position_sp)) # Start the motors self . left_motor . run_to_rel_pos ( ) self . right_motor . run_to_rel_pos ( ) if block : self . _block ( )
Rotate the motors at left_speed & right_speed for degrees . Speeds can be percentages or any SpeedValue implementation .
636
26
227,217
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 )
Rotate the motors at left_speed & right_speed for rotations . Speeds can be percentages or any SpeedValue implementation .
59
27
227,218
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 all parameters self . left_motor . speed_sp = int ( round ( left_speed_native_units ) ) self . left_motor . time_sp = int ( seconds * 1000 ) self . left_motor . _set_brake ( brake ) self . right_motor . speed_sp = int ( round ( right_speed_native_units ) ) self . right_motor . time_sp = int ( seconds * 1000 ) self . right_motor . _set_brake ( brake ) log . debug ( "%s: on_for_seconds %ss at left-speed %s, right-speed %s" % ( self , seconds , left_speed , right_speed ) ) # Start the motors self . left_motor . run_timed ( ) self . right_motor . run_timed ( ) if block : self . _block ( )
Rotate the motors at left_speed & right_speed for seconds . Speeds can be percentages or any SpeedValue implementation .
288
26
227,219
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_native_units ) ) # This debug involves disk I/O to pull speed_sp so only uncomment # if you need to troubleshoot in more detail. # log.debug("%s: on at left-speed %s, right-speed %s" % # (self, self.left_motor.speed_sp, self.right_motor.speed_sp)) # Start the motors self . left_motor . run_forever ( ) self . right_motor . run_forever ( )
Start rotating the motors according to left_speed and right_speed forever . Speeds can be percentages or any SpeedValue implementation .
215
26
227,220
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 )
Rotate the motors according to the provided steering for seconds .
84
12
227,221
def on ( self , steering , speed ) : ( left_speed , right_speed ) = self . get_speed_steering ( steering , speed ) MoveTank . on ( self , SpeedNativeUnits ( left_speed ) , SpeedNativeUnits ( right_speed ) )
Start rotating the motors according to the provided steering and speed forever .
60
13
227,222
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 halfway point between the two wheels is the # circle that must have a radius of radius_mm circle_outer_mm = 2 * math . pi * ( radius_mm + ( self . wheel_distance_mm / 2 ) ) circle_middle_mm = 2 * math . pi * radius_mm circle_inner_mm = 2 * math . pi * ( radius_mm - ( self . wheel_distance_mm / 2 ) ) if arc_right : # The left wheel is making the larger circle and will move at 'speed' # The right wheel is making a smaller circle so its speed will be a fraction of the left motor's speed left_speed = speed right_speed = float ( circle_inner_mm / circle_outer_mm ) * left_speed else : # The right wheel is making the larger circle and will move at 'speed' # The left wheel is making a smaller circle so its speed will be a fraction of the right motor's speed right_speed = speed left_speed = float ( circle_inner_mm / circle_outer_mm ) * right_speed log . debug ( "%s: arc %s, radius %s, distance %s, left-speed %s, right-speed %s, circle_outer_mm %s, circle_middle_mm %s, circle_inner_mm %s" % ( self , "right" if arc_right else "left" , radius_mm , distance_mm , left_speed , right_speed , circle_outer_mm , circle_middle_mm , circle_inner_mm ) ) # We know we want the middle circle to be of length distance_mm so # calculate the percentage of circle_middle_mm we must travel for the # middle of the robot to travel distance_mm. circle_middle_percentage = float ( distance_mm / circle_middle_mm ) # Now multiple that percentage by circle_outer_mm to calculate how # many mm the outer wheel should travel. circle_outer_final_mm = circle_middle_percentage * circle_outer_mm outer_wheel_rotations = float ( circle_outer_final_mm / self . wheel . circumference_mm ) outer_wheel_degrees = outer_wheel_rotations * 360 log . debug ( "%s: arc %s, circle_middle_percentage %s, circle_outer_final_mm %s, outer_wheel_rotations %s, outer_wheel_degrees %s" % ( self , "right" if arc_right else "left" , circle_middle_percentage , circle_outer_final_mm , outer_wheel_rotations , outer_wheel_degrees ) ) MoveTank . on_for_degrees ( self , left_speed , right_speed , outer_wheel_degrees , brake , block )
Drive in a circle with radius for distance
694
8
227,223
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 )
Drive clockwise in a circle with radius_mm for distance_mm
51
14
227,224
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 )
Drive counter - clockwise in a circle with radius_mm for distance_mm
51
16
227,225
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() degrees %s, distance_mm %s, rotations %s, degrees %s" % ( self , degrees , distance_mm , rotations , degrees ) ) # If degrees is positive rotate clockwise if degrees > 0 : MoveTank . on_for_rotations ( self , speed , speed * - 1 , rotations , brake , block ) # If degrees is negative rotate counter-clockwise else : rotations = distance_mm / self . wheel . circumference_mm MoveTank . on_for_rotations ( self , speed * - 1 , speed , rotations , brake , block )
Rotate in place degrees . Both wheels must turn at the same speed for us to rotate in place .
205
21
227,226
def turn_right ( self , speed , degrees , brake = True , block = True ) : self . _turn ( speed , abs ( degrees ) , brake , block )
Rotate clockwise degrees in place
36
7
227,227
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_target_degrees += 360 angle_current_degrees = math . degrees ( self . theta ) if angle_current_degrees < 0 : angle_current_degrees += 360 # Is it shorter to rotate to the right or left # to reach angle_target_degrees? if angle_current_degrees > angle_target_degrees : turn_right = True angle_delta = angle_current_degrees - angle_target_degrees else : turn_right = False angle_delta = angle_target_degrees - angle_current_degrees if angle_delta > 180 : angle_delta = 360 - angle_delta turn_right = not turn_right log . debug ( "%s: turn_to_angle %s, current angle %s, delta %s, turn_right %s" % ( self , angle_target_degrees , angle_current_degrees , angle_delta , turn_right ) ) self . odometry_coordinates_log ( ) if turn_right : self . turn_right ( speed , angle_delta , brake , block ) else : self . turn_left ( speed , angle_delta , brake , block ) self . odometry_coordinates_log ( )
Rotate in place to angle_target_degrees at speed
348
13
227,228
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
Given a datetime . timedelta object return the delta in milliseconds
62
13
227,229
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
Return True if duration_seconds have expired since start_time
64
12
227,230
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 .
47
7
227,231
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 .
35
17
227,232
def triggers ( self ) : self . _triggers , value = self . get_attr_set ( self . _triggers , 'trigger' ) return value
Returns a list of available triggers .
36
7
227,233
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 .
34
61
227,234
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. for retry in ( True , False ) : try : self . _delay_on , value = self . get_attr_int ( self . _delay_on , 'delay_on' ) return value except OSError : if retry : self . _delay_on = None else : raise
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 .
141
31
227,235
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. for retry in ( True , False ) : try : self . _delay_off , value = self . get_attr_int ( self . _delay_off , 'delay_off' ) return value except OSError : if retry : self . _delay_off = None else : raise
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 .
141
31
227,236
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 choices are %s" % ( color , ', ' . join ( self . led_colors . keys ( ) ) ) color_tuple = self . led_colors [ color ] assert group in self . led_groups , "%s is an invalid LED group, valid choices are %s" % ( group , ', ' . join ( self . led_groups . keys ( ) ) ) for led , value in zip ( self . led_groups [ group ] , color_tuple ) : led . brightness_pct = value * pct
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 .
188
30
227,237
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 ( ) ) ) for led in self . led_groups [ group ] : for k in kwargs : setattr ( led , k , kwargs [ k ] )
Set attributes for each LED in group .
111
8
227,238
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
46
4
227,239
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
45
8
227,240
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 : self . set_color ( group1 , color1 ) self . set_color ( group2 , color2 ) else : self . set_color ( group1 , color2 ) self . set_color ( group2 , color1 ) if self . animate_thread_stop or duration_expired ( start_time , duration ) : break even = not even sleep ( sleeptime ) self . animate_thread_stop = False self . animate_thread_id = None self . animate_stop ( ) if block : _animate_police_lights ( ) else : self . animate_thread_id = _thread . start_new_thread ( _animate_police_lights , ( ) )
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 .
234
37
227,241
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_color ( group , colors [ index ] ) index += 1 if index == max_index : index = 0 if self . animate_thread_stop or duration_expired ( start_time , duration ) : break sleep ( sleeptime ) self . animate_thread_stop = False self . animate_thread_id = None self . animate_stop ( ) if block : _animate_cycle ( ) else : self . animate_thread_id = _thread . start_new_thread ( _animate_cycle , ( ) )
Cycle groups LEDs through colors . Do this in a loop where we display each color for sleeptime seconds .
195
23
227,242
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) to (0,1)...GREEN # state 3: (LEFT,RIGHT) from (0,1) to (0,0)...OFF state = 0 left_value = 0 right_value = 0 MIN_VALUE = 0 MAX_VALUE = 1 self . all_off ( ) start_time = dt . datetime . now ( ) while True : if state == 0 : left_value += increment_by elif state == 1 : right_value += increment_by elif state == 2 : left_value -= increment_by elif state == 3 : right_value -= increment_by else : raise Exception ( "Invalid state {}" . format ( state ) ) # Keep left_value and right_value within the MIN/MAX values left_value = min ( left_value , MAX_VALUE ) right_value = min ( right_value , MAX_VALUE ) left_value = max ( left_value , MIN_VALUE ) right_value = max ( right_value , MIN_VALUE ) self . set_color ( group1 , ( left_value , right_value ) ) self . set_color ( group2 , ( left_value , right_value ) ) if state == 0 and left_value == MAX_VALUE : state = 1 elif state == 1 and right_value == MAX_VALUE : state = 2 elif state == 2 and left_value == MIN_VALUE : state = 3 elif state == 3 and right_value == MIN_VALUE : state = 0 if self . animate_thread_stop or duration_expired ( start_time , duration ) : break sleep ( sleeptime ) self . animate_thread_stop = False self . animate_thread_id = None self . animate_stop ( ) if block : _animate_rainbow ( ) else : self . animate_thread_id = _thread . start_new_thread ( _animate_rainbow , ( ) )
Gradually fade from one color to the next
535
9
227,243
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 values in the 250 - 400 range .
44
66
227,244
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.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html # sRGB # 0.4124564 0.3575761 0.1804375 # 0.2126729 0.7151522 0.0721750 # 0.0193339 0.1191920 0.9503041 X = ( RGB [ 0 ] * 0.4124564 ) + ( RGB [ 1 ] * 0.3575761 ) + ( RGB [ 2 ] * 0.1804375 ) Y = ( RGB [ 0 ] * 0.2126729 ) + ( RGB [ 1 ] * 0.7151522 ) + ( RGB [ 2 ] * 0.0721750 ) Z = ( RGB [ 0 ] * 0.0193339 ) + ( RGB [ 1 ] * 0.1191920 ) + ( RGB [ 2 ] * 0.9503041 ) XYZ [ 0 ] = X / 95.047 # ref_X = 95.047 XYZ [ 1 ] = Y / 100.0 # ref_Y = 100.000 XYZ [ 2 ] = Z / 108.883 # ref_Z = 108.883 for ( num , value ) in enumerate ( XYZ ) : if value > 0.008856 : value = pow ( value , ( 1.0 / 3.0 ) ) else : value = ( 7.787 * value ) + ( 16 / 116.0 ) XYZ [ num ] = value L = ( 116.0 * XYZ [ 1 ] ) - 16 a = 500.0 * ( XYZ [ 0 ] - XYZ [ 1 ] ) b = 200.0 * ( XYZ [ 1 ] - XYZ [ 2 ] ) L = round ( L , 4 ) a = round ( a , 4 ) b = round ( b , 4 ) return ( L , a , b )
Return colors in Lab color space
499
6
227,245
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 direction_sensitive : if delta > 0 : while ( self . value ( 0 ) - start_angle ) < delta : time . sleep ( 0.01 ) else : delta *= - 1 while ( start_angle - self . value ( 0 ) ) < delta : time . sleep ( 0.01 ) else : while abs ( start_angle - self . value ( 0 ) ) < delta : time . sleep ( 0.01 )
Wait until angle has changed by specified amount .
197
9
227,246
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 ) , [ ] )
Returns list of currently pressed buttons .
64
7
227,247
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 .
40
18
227,248
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 .
44
26
227,249
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 .
44
11
227,250
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 .
46
11
227,251
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 )
Returns list of available font names .
72
7
227,252
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 .
40
11
227,253
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 .
32
46
227,254
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 .
32
47
227,255
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 ) )
This is a generator function that enumerates all sensors that match the provided arguments .
100
16
227,256
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
Returns value scaling coefficient for the given mode .
57
9
227,257
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
32
16
227,258
def value ( self , n = 0 ) : n = int ( n ) self . _value [ n ] , value = self . get_attr_int ( self . _value [ n ] , 'value' + str ( n ) ) return 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 .
53
59
227,259
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 .
60
7
227,260
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 .
60
12
227,261
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 .
60
12
227,262
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 )
Map the framebuffer memory .
65
6
227,263
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 . mmap [ : ] = self . _img . convert ( "RGB" ) . tobytes ( "raw" , "XRGB" ) else : raise Exception ( "Not supported - platform %s with bits_per_pixel %s" % ( self . platform , self . var_info . bits_per_pixel ) )
Applies pending changes to the screen . Nothing will be drawn on the screen until this function is called .
180
21
227,264
def _make_scales ( notes ) : res = dict ( ) for note , freq in notes : freq = round ( freq ) for n in note . split ( '/' ) : res [ n ] = freq return res
Utility function used by Sound class for building the note frequencies table
51
13
227,265
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 (%s)' % delay ) if not 0 < volume <= 100 : raise ValueError ( 'invalid volume (%s)' % volume ) self . set_volume ( volume ) duration_ms = int ( duration * 1000 ) delay_ms = int ( delay * 1000 ) self . tone ( [ ( frequency , duration_ms , delay_ms ) ] , play_type = play_type )
Play a single tone specified by its frequency duration volume and final delay .
164
14
227,266
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 ) if duration <= 0 : raise ValueError ( 'invalid duration (%s)' % duration ) if not 0 < volume <= 100 : raise ValueError ( 'invalid volume (%s)' % volume ) return self . play_tone ( freq , duration = duration , volume = volume , play_type = play_type )
Plays a note given by its name as defined in _NOTE_FREQUENCIES .
167
20
227,267
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 ) ] aplay_cmd_line = shlex . split ( '/usr/bin/aplay -q' ) if play_type == Sound . PLAY_WAIT_FOR_COMPLETE : espeak = Popen ( cmd_line , stdout = PIPE ) play = Popen ( aplay_cmd_line , stdin = espeak . stdout , stdout = n ) play . wait ( ) elif play_type == Sound . PLAY_NO_WAIT_FOR_COMPLETE : espeak = Popen ( cmd_line , stdout = PIPE ) return Popen ( aplay_cmd_line , stdin = espeak . stdout , stdout = n ) elif play_type == Sound . PLAY_LOOP : while True : espeak = Popen ( cmd_line , stdout = PIPE ) play = Popen ( aplay_cmd_line , stdin = espeak . stdout , stdout = n ) play . wait ( )
Speak the given text aloud .
334
7
227,268
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 4/4 bars, hence "* 4" def beep_args ( note , value ) : """ Builds the arguments string for producing a beep matching the requested note and value. Args: note (str): the note note and octave value (str): the note value expression Returns: str: the arguments to be passed to the beep command """ freq = self . _NOTE_FREQUENCIES . get ( note . upper ( ) , self . _NOTE_FREQUENCIES [ note ] ) if '/' in value : base , factor = value . split ( '/' ) duration_ms = meas_duration_ms * self . _NOTE_VALUES [ base ] / float ( factor ) elif '*' in value : base , factor = value . split ( '*' ) duration_ms = meas_duration_ms * self . _NOTE_VALUES [ base ] * float ( factor ) elif value . endswith ( '.' ) : base = value [ : - 1 ] duration_ms = meas_duration_ms * self . _NOTE_VALUES [ base ] * 1.5 elif value . endswith ( '3' ) : base = value [ : - 1 ] duration_ms = meas_duration_ms * self . _NOTE_VALUES [ base ] * 2 / 3 else : duration_ms = meas_duration_ms * self . _NOTE_VALUES [ value ] return '-f %d -l %d -D %d' % ( freq , duration_ms , delay_ms ) try : return self . beep ( ' -n ' . join ( [ beep_args ( note , value ) for ( note , value ) in song ] ) ) except KeyError as e : raise ValueError ( 'invalid note (%s)' % e )
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 .
477
31
227,269
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 ( pattern , list ) : return any ( [ value . find ( p ) >= 0 for p in pattern ] ) else : return value . find ( pattern ) >= 0 for f in os . listdir ( class_path ) : if fnmatch . fnmatch ( f , name_pattern ) : path = class_path + '/' + f if all ( [ matches ( path + '/' + k , kwargs [ k ] ) for k in kwargs ] ) : yield f
This is a generator function that lists names of all devices matching the provided parameters .
183
16
227,270
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 ) )
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 .
83
27
227,271
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 . _raise_friendly_access_error ( ex , name )
Device attribute getter
77
4
227,272
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 ( value ) attribute . flush ( ) except Exception as ex : self . _raise_friendly_access_error ( ex , name ) return attribute
Device attribute setter
92
4
227,273
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 ( ) self . dc_right_file . close ( )
Close all file handles and stop all motors .
102
9
227,274
def _fast_read ( self , infile ) : infile . seek ( 0 ) return ( int ( infile . read ( ) . decode ( ) . strip ( ) ) )
Function for fast reading from sensor files .
39
8
227,275
def _fast_write ( self , outfile , value ) : outfile . truncate ( 0 ) outfile . write ( str ( int ( value ) ) ) outfile . flush ( )
Function for fast writing to motor files .
41
8
227,276
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_int = min ( 100 , duty_int + friction_offset ) elif duty_int < 0 : duty_int = max ( - 100 , duty_int - friction_offset ) # Apply the signal to the motor self . _fast_write ( motor_duty_file , duty_int )
Function to set the duty cycle of the motors .
137
10
227,277
def balance ( self ) : balance_thread = threading . Thread ( target = self . _balance ) balance_thread . start ( )
Run the _balance method as a thread .
29
9
227,278
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 ( )
Move robot .
68
3
227,279
def move_forward ( self , seconds = None ) : self . _move ( speed = SPEED_MAX , steering = 0 , seconds = seconds )
Move robot forward .
32
4
227,280
def move_backward ( self , seconds = None ) : self . _move ( speed = - SPEED_MAX , steering = 0 , seconds = seconds )
Move robot backward .
34
4
227,281
def rotate_left ( self , seconds = None ) : self . _move ( speed = 0 , steering = STEER_MAX , seconds = seconds )
Rotate robot left .
32
5
227,282
def rotate_right ( self , seconds = None ) : self . _move ( speed = 0 , steering = - STEER_MAX , seconds = seconds )
Rotate robot right .
33
5
227,283
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 ) )
Return our corresponding evdev device object
83
7
227,284
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 ) return False
Wait for the button to be pressed down and then released . Both actions must happen within timeout_ms .
89
21
227,285
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 ( bit / 8 ) ] & 1 << bit % 8 ) : pressed . append ( k ) return pressed
Returns list of names of pressed buttons .
125
8
227,286
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 )
Waits maximum of 5 minutes for orted process to start
69
12
227,287
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 ( ) )
Parse custom MPI options provided by user . Known options default value will be overridden and unknown options would be identified separately .
93
26
227,288
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' ) _files . s3_download ( uri , dst ) module_path = os . path . join ( tmpdir , 'module_dir' ) os . makedirs ( module_path ) with tarfile . open ( name = dst , mode = 'r:gz' ) as t : t . extractall ( path = module_path ) else : module_path = uri prepare ( module_path , name ) install ( module_path )
Download prepare and install a compressed tar file from S3 or local directory as a module .
197
18
227,289
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 wait : return _process . check_error ( cmd , _errors . ExecuteUserScriptError , capture_error = capture_error ) else : return _process . create ( cmd , _errors . ExecuteUserScriptError , capture_error = capture_error )
Run Python module as a script .
166
7
227,290
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 , name , _env . code_dir ) prepare ( _env . code_dir , name ) install ( _env . code_dir ) _env . write_env_vars ( env_vars ) return run ( name , args , env_vars , wait , capture_error )
Download prepare and executes a compressed tar file from S3 or provided directory as a module .
177
18
227,291
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
The request s content - type .
61
7
227,292
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
The content - type for the response to the client .
48
11
227,293
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 .
48
5
227,294
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_vars or { } env_vars = env_vars . copy ( ) _files . download_and_extract ( uri , user_entry_point , _env . code_dir ) install ( user_entry_point , _env . code_dir , capture_error ) _env . write_env_vars ( env_vars ) return _runner . get ( runner , user_entry_point , args , env_vars , extra_opts ) . run ( wait , capture_error )
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 .
206
39
227,295
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 . INFO ) logging . getLogger ( 'botocore' ) . setLevel ( logging . WARN )
Set logger configuration .
129
4
227,296
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 ) )
Return a timestamp with microsecond precision .
74
8
227,297
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 k in dictionary . keys ( ) if k not in included_items } return SplitResultSpec ( included = included_items , excluded = excluded_items )
Split a dictionary in two by the provided keys .
128
10
227,298
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 .
38
11
227,299
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 return _worker . Response ( response = result [ 0 ] , mimetype = result [ 1 ] ) return result
Take a request with input data deserialize it make a prediction and return a serialized response .
92
20