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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
233,300
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: return True return False
python
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: 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", ")", "if", "delta_seconds", ">=", "duration_seconds", ":", "return", "True", "return", "False" ]
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
233,301
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): """ Returns the maximum allowable brightness value. """ 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
233,302
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): """ Sets the brightness level. Possible values are from 0 to `max_brightness`. """ 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
233,303
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): """ Returns a list of available triggers. """ 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
233,304
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` and `nand-disk` triggers. Complex triggers whilst available to all LEDs have LED specific parameters and work on a per LED basis. The `timer` trigger is an example. The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` and `off` time can be specified via `delay_{on,off}` attributes in milliseconds. You can change the brightness value of a LED independently of the timer trigger. However, if you set the brightness value to 0 it will also disable the `timer` trigger. """ self._trigger, value = self.get_attr_from_set(self._trigger, 'trigger') return value
python
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` and `nand-disk` triggers. Complex triggers whilst available to all LEDs have LED specific parameters and work on a per LED basis. The `timer` trigger is an example. The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` and `off` time can be specified via `delay_{on,off}` attributes in milliseconds. You can change the brightness value of a LED independently of the timer trigger. However, if you set the brightness value to 0 it will also disable the `timer` trigger. """ 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. Complex triggers whilst available to all LEDs have LED specific parameters and work on a per LED basis. The `timer` trigger is an example. The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` and `off` time can be specified via `delay_{on,off}` attributes in milliseconds. You can change the brightness value of a LED independently of the timer trigger. However, if you set the brightness value to 0 it will also disable the `timer` trigger.
[ "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", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L160-L178
233,305
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 '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
python
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 '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
[ "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.
[ "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
233,306
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' 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
python
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' 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
[ "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.
[ "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
233,307
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('LEFT', 'AMBER') With a custom color:: my_leds = Leds() my_leds.set_color('LEFT', (0.5, 0.3)) """ # 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
python
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('LEFT', 'AMBER') With a custom color:: my_leds = Leds() my_leds.set_color('LEFT', (0.5, 0.3)) """ # 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
[ "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. Example:: my_leds = Leds() my_leds.set_color('LEFT', 'AMBER') With a custom color:: my_leds = Leds() my_leds.set_color('LEFT', (0.5, 0.3))
[ "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
233,308
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: 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])
python
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: 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])
[ "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. 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
233,309
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): """ 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
[ "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
233,310
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): """ 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)
[ "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
233,311
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 ``sleeptime`` seconds. Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_police_lights('RED', 'GREEN', sleeptime=0.75, duration=10) """ 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, ())
python
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 ``sleeptime`` seconds. Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_police_lights('RED', 'GREEN', sleeptime=0.75, duration=10) """ 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, ())
[ "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. Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_police_lights('RED', 'GREEN', sleeptime=0.75, duration=10)
[ "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
233,312
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 forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_cyle(('RED', 'GREEN', 'AMBER')) """ 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, ())
python
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 forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_cyle(('RED', 'GREEN', 'AMBER')) """ 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, ())
[ "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. Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_cyle(('RED', 'GREEN', 'AMBER'))
[ "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
233,313
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 from ev3dev2.led import Leds leds = Leds() leds.animate_rainbow() """ 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, ())
python
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 from ev3dev2.led import Leds leds = Leds() leds.animate_rainbow() """ 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, ())
[ "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 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
233,314
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 white paper will return values in the 250-400 range. If this is an issue, check out the rgb() and calibrate_white() methods. """ self._ensure_mode(self.MODE_RGB_RAW) return self.value(0), self.value(1), self.value(2)
python
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 white paper will return values in the 250-400 range. If this is an issue, check out the rgb() and calibrate_white() methods. """ 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 values in the 250-400 range. If this is an issue, check out the rgb() and calibrate_white() methods.
[ "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", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L226-L238
233,315
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 / 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)
python
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 / 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)
[ "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
[ "Return", "colors", "in", "Lab", "color", "space" ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L273-L317
233,316
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 (default) we will wait until angle has changed by ``delta`` in either direction. """ 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)
python
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 (default) we will wait until angle has changed by ``delta`` in either direction. """ 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)
[ "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. 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
233,317
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._BUTTON_VALUES.get(self.value(channel), [])
python
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._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", ".", "get", "(", "self", ".", "value", "(", "channel", ")", ",", "[", "]", ")" ]
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
233,318
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): """ 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')
[ "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
233,319
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): """ 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')
[ "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
233,320
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): """ A measurement of the reflected light intensity, as a percentage. """ 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
233,321
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): """ A measurement of the ambient light intensity, as a percentage. """ 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
233,322
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(): """ 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)
[ "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.
[ "Returns", "list", "of", "available", "font", "names", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/fonts/__init__.py#L5-L12
233,323
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): """ Returns a list of the available modes of the port. """ (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
233,324
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 implementing this class. """ self._mode, value = self.get_attr_string(self._mode, 'mode') return value
python
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 implementing this class. """ 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", "removed", "new", "ones", "loaded", "however", "this", "this", "will", "depend", "on", "the", "individual", "driver", "implementing", "this", "class", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/port.py#L113-L121
233,325
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. """ self._status, value = self.get_attr_string(self._status, 'status') return value
python
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. """ 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", "error", ".", "See", "individual", "port", "driver", "documentation", "for", "the", "full", "list", "of", "possible", "values", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/port.py#L143-L151
233,326
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: '*'. keyword arguments: used for matching the corresponding device attributes. For example, driver_name='lego-ev3-touch', or address=['in1', 'in3']. When argument value is a list, then a match against any entry of the list is enough. """ 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))
python
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: '*'. keyword arguments: used for matching the corresponding device attributes. For example, driver_name='lego-ev3-touch', or address=['in1', 'in3']. When argument value is a list, then a match against any entry of the list is enough. """ 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", ")", "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. Parameters: name_pattern: pattern that device name should match. For example, 'sensor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, driver_name='lego-ev3-touch', or address=['in1', 'in3']. When argument value is a list, then a match against any entry of the list is enough.
[ "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
233,327
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): """ 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
[ "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.
[ "Returns", "value", "scaling", "coefficient", "for", "the", "given", "mode", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/__init__.py#L112-L122
233,328
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): """ 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
[ "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
233,329
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 value. """ n = int(n) self._value[n], value = self.get_attr_int(self._value[n], 'value'+str(n)) return value
python
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 value. """ 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'", "+", "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.
[ "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", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/__init__.py#L210-L220
233,330
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) return fbfid
python
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) 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
233,331
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): """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
[ "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
233,332
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): """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
[ "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
233,333
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): """Map the framebuffer memory.""" 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", "=", "0", ")" ]
Map the framebuffer memory.
[ "Map", "the", "framebuffer", "memory", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/display.py#L183-L191
233,334
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.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))
python
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.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))
[ "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.
[ "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
233,335
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): """ 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
[ "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
[ "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
233,336
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 seconds :param float delay: Delay after tone, in seconds (can be useful when chaining calls to ``play_tone``) :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``play_tone`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :return: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the PID of the underlying beep command; ``None`` otherwise :raises ValueError: if invalid parameter """ 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)
python
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 seconds :param float delay: Delay after tone, in seconds (can be useful when chaining calls to ``play_tone``) :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``play_tone`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :return: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the PID of the underlying beep command; ``None`` otherwise :raises ValueError: if invalid parameter """ 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)
[ "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. :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``) :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``play_tone`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :return: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the PID of the underlying beep command; ``None`` otherwise :raises ValueError: if invalid parameter
[ "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
233,337
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 play volume, in percent of maximum volume :param play_type: The behavior of ``play_note`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :return: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the PID of the underlying beep command; ``None`` otherwise :raises ValueError: is invalid parameter (note, duration,...) """ 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)
python
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 play volume, in percent of maximum volume :param play_type: The behavior of ``play_note`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :return: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the PID of the underlying beep command; ``None`` otherwise :raises ValueError: is invalid parameter (note, duration,...) """ 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)
[ "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``. :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_note`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :return: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the PID of the underlying beep command; ``None`` otherwise :raises ValueError: is invalid parameter (note, duration,...)
[ "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
233,338
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) :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``speak`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :returns: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the spawn subprocess from ``subprocess.Popen``; ``None`` otherwise """ 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()
python
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) :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``speak`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :returns: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the spawn subprocess from ``subprocess.Popen``; ``None`` otherwise """ 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()
[ "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. 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 ``speak`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLETE``, ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` or ``Sound.PLAY_LOOP`` :returns: When ``Sound.PLAY_NO_WAIT_FOR_COMPLETE`` is specified, returns the spawn subprocess from ``subprocess.Popen``; ``None`` otherwise
[ "Speak", "the", "given", "text", "aloud", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sound.py#L289-L323
233,339
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 durations (e.g. ``q``, ``h``). For an exhaustive list of accepted note symbols and values, have a look at the ``_NOTE_FREQUENCIES`` and ``_NOTE_VALUES`` private dictionaries in the source code. The value can be suffixed by modifiers: - a *divider* introduced by a ``/`` to obtain triplets for instance (e.g. ``q/3`` for a triplet of eight note) - a *multiplier* introduced by ``*`` (e.g. ``*1.5`` is a dotted note). Shortcuts exist for common modifiers: - ``3`` produces a triplet member note. For instance `e3` gives a triplet of eight notes, i.e. 3 eight notes in the duration of a single quarter. You must ensure that 3 triplets notes are defined in sequence to match the count, otherwise the result will not be the expected one. - ``.`` produces a dotted note, i.e. which duration is one and a half the base one. Double dots are not currently supported. Example:: >>> # A long time ago in a galaxy far, >>> # far away... >>> Sound.play_song(( >>> ('D4', 'e3'), # intro anacrouse >>> ('D4', 'e3'), >>> ('D4', 'e3'), >>> ('G4', 'h'), # meas 1 >>> ('D5', 'h'), >>> ('C5', 'e3'), # meas 2 >>> ('B4', 'e3'), >>> ('A4', 'e3'), >>> ('G5', 'h'), >>> ('D5', 'q'), >>> ('C5', 'e3'), # meas 3 >>> ('B4', 'e3'), >>> ('A4', 'e3'), >>> ('G5', 'h'), >>> ('D5', 'q'), >>> ('C5', 'e3'), # meas 4 >>> ('B4', 'e3'), >>> ('C5', 'e3'), >>> ('A4', 'h.'), >>> )) .. important:: Only 4/4 signature songs are supported with respect to note durations. :param iterable[tuple(string, string)] song: the song :param int tempo: the song tempo, given in quarters per minute :param float delay: delay between notes (in seconds) :return: the spawn subprocess from ``subprocess.Popen`` :raises ValueError: if invalid note in song or invalid play parameters """ 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)
python
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 durations (e.g. ``q``, ``h``). For an exhaustive list of accepted note symbols and values, have a look at the ``_NOTE_FREQUENCIES`` and ``_NOTE_VALUES`` private dictionaries in the source code. The value can be suffixed by modifiers: - a *divider* introduced by a ``/`` to obtain triplets for instance (e.g. ``q/3`` for a triplet of eight note) - a *multiplier* introduced by ``*`` (e.g. ``*1.5`` is a dotted note). Shortcuts exist for common modifiers: - ``3`` produces a triplet member note. For instance `e3` gives a triplet of eight notes, i.e. 3 eight notes in the duration of a single quarter. You must ensure that 3 triplets notes are defined in sequence to match the count, otherwise the result will not be the expected one. - ``.`` produces a dotted note, i.e. which duration is one and a half the base one. Double dots are not currently supported. Example:: >>> # A long time ago in a galaxy far, >>> # far away... >>> Sound.play_song(( >>> ('D4', 'e3'), # intro anacrouse >>> ('D4', 'e3'), >>> ('D4', 'e3'), >>> ('G4', 'h'), # meas 1 >>> ('D5', 'h'), >>> ('C5', 'e3'), # meas 2 >>> ('B4', 'e3'), >>> ('A4', 'e3'), >>> ('G5', 'h'), >>> ('D5', 'q'), >>> ('C5', 'e3'), # meas 3 >>> ('B4', 'e3'), >>> ('A4', 'e3'), >>> ('G5', 'h'), >>> ('D5', 'q'), >>> ('C5', 'e3'), # meas 4 >>> ('B4', 'e3'), >>> ('C5', 'e3'), >>> ('A4', 'h.'), >>> )) .. important:: Only 4/4 signature songs are supported with respect to note durations. :param iterable[tuple(string, string)] song: the song :param int tempo: the song tempo, given in quarters per minute :param float delay: delay between notes (in seconds) :return: the spawn subprocess from ``subprocess.Popen`` :raises ValueError: if invalid note in song or invalid play parameters """ 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)
[ "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\n the requested note and value.\n\n Args:\n note (str): the note note and octave\n value (str): the note value expression\n Returns:\n str: the arguments to be passed to the beep command\n \"\"\"", "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. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and durations (e.g. ``q``, ``h``). For an exhaustive list of accepted note symbols and values, have a look at the ``_NOTE_FREQUENCIES`` and ``_NOTE_VALUES`` private dictionaries in the source code. The value can be suffixed by modifiers: - a *divider* introduced by a ``/`` to obtain triplets for instance (e.g. ``q/3`` for a triplet of eight note) - a *multiplier* introduced by ``*`` (e.g. ``*1.5`` is a dotted note). Shortcuts exist for common modifiers: - ``3`` produces a triplet member note. For instance `e3` gives a triplet of eight notes, i.e. 3 eight notes in the duration of a single quarter. You must ensure that 3 triplets notes are defined in sequence to match the count, otherwise the result will not be the expected one. - ``.`` produces a dotted note, i.e. which duration is one and a half the base one. Double dots are not currently supported. Example:: >>> # A long time ago in a galaxy far, >>> # far away... >>> Sound.play_song(( >>> ('D4', 'e3'), # intro anacrouse >>> ('D4', 'e3'), >>> ('D4', 'e3'), >>> ('G4', 'h'), # meas 1 >>> ('D5', 'h'), >>> ('C5', 'e3'), # meas 2 >>> ('B4', 'e3'), >>> ('A4', 'e3'), >>> ('G5', 'h'), >>> ('D5', 'q'), >>> ('C5', 'e3'), # meas 3 >>> ('B4', 'e3'), >>> ('A4', 'e3'), >>> ('G5', 'h'), >>> ('D5', 'q'), >>> ('C5', 'e3'), # meas 4 >>> ('B4', 'e3'), >>> ('C5', 'e3'), >>> ('A4', 'h.'), >>> )) .. important:: Only 4/4 signature songs are supported with respect to note durations. :param iterable[tuple(string, string)] song: the song :param int tempo: the song tempo, given in quarters per minute :param float delay: delay between notes (in seconds) :return: the spawn subprocess from ``subprocess.Popen`` :raises ValueError: if invalid note in song or invalid play parameters
[ "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
233,340
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'. name_pattern: pattern that device name should match. For example, 'sensor*' or 'motor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, address='outA', or driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value is a list, then a match against any entry of the list is enough. """ 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
python
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'. name_pattern: pattern that device name should match. For example, 'sensor*' or 'motor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, address='outA', or driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value is a list, then a match against any entry of the list is enough. """ 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
[ "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. 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 example, 'sensor*' or 'motor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, address='outA', or driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value is a list, then a match against any entry of the list is enough.
[ "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
233,341
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/class. For example, 'tacho-motor'. name_pattern: pattern that device name should match. For example, 'sensor*' or 'motor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, address='outA', or driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value is a list, then a match against any entry of the list is enough. """ 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))
python
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/class. For example, 'tacho-motor'. name_pattern: pattern that device name should match. For example, 'sensor*' or 'motor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, address='outA', or driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value is a list, then a match against any entry of the list is enough. """ 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", ",", "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. Parameters: class_name: class name of the device, a subdirectory of /sys/class. For example, 'tacho-motor'. name_pattern: pattern that device name should match. For example, 'sensor*' or 'motor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, address='outA', or driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value is a list, then a match against any entry of the list is enough.
[ "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
233,342
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 Exception as ex: self._raise_friendly_access_error(ex, name)
python
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 Exception as ex: self._raise_friendly_access_error(ex, name)
[ "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
[ "Device", "attribute", "getter" ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/__init__.py#L240-L249
233,343
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.encode() attribute.write(value) attribute.flush() except Exception as ex: self._raise_friendly_access_error(ex, name) return attribute
python
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.encode() attribute.write(value) attribute.flush() except Exception as ex: self._raise_friendly_access_error(ex, name) return attribute
[ "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
[ "Device", "attribute", "setter" ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/__init__.py#L251-L265
233,344
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_right_file.close() self.dc_left_file.close() self.dc_right_file.close()
python
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_right_file.close() self.dc_left_file.close() self.dc_right_file.close()
[ "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.
[ "Close", "all", "file", "handles", "and", "stop", "all", "motors", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L162-L172
233,345
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): """Function for fast reading from sensor files.""" 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
233,346
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): """Function for fast writing to motor files.""" 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
233,347
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 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)
python
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 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)
[ "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.
[ "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
233,348
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): """Run the _balance method as a thread.""" 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
233,349
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): """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()
[ "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.
[ "Move", "robot", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L475-L481
233,350
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): """Move robot forward.""" 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
233,351
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): """Move robot backward.""" 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
233,352
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): """Rotate robot left.""" 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
233,353
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): """Rotate robot right.""" 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
233,354
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: could not find evdev device '%s'" % (self, self.evdev_device_name))
python
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: 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", "==", "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
[ "Return", "our", "corresponding", "evdev", "device", "object" ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/button.py#L115-L125
233,355
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: timeout_ms -= int((time.time() - start_time) * 1000) return self.wait_for_released(buttons, timeout_ms) return False
python
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: timeout_ms -= int((time.time() - start_time) * 1000) return self.wait_for_released(buttons, timeout_ms) return False
[ "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.
[ "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
233,356
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_cache[v['name']] bit = v['value'] if bool(buf[int(bit / 8)] & 1 << bit % 8): pressed.append(k) return pressed
python
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_cache[v['name']] bit = v['value'] if bool(buf[int(bit / 8)] & 1 << bit % 8): pressed.append(k) return pressed
[ "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.
[ "Returns", "list", "of", "names", "of", "pressed", "buttons", "." ]
afc98d35004b533dc161a01f7c966e78607d7c1e
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/button.py#L255-L270
233,357
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(): """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)
[ "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
[ "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
233,358
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_argument('--NCCL_DEBUG', default="INFO", type=str) return parser.parse_known_args(custom_mpi_options.split())
python
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_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\"", ",", "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.
[ "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
233,359
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 downloads this compressed file and, if provided, transforms it into a module before installing it. This method is the predecessor of :meth:`~sagemaker_containers.beta.framework.files.download_and_extract` and has been kept for backward-compatibility purposes. Args: name (str): name of the script or module. uri (str): the location of the module. cache (bool): defaults to True. It will not download and install the module again if it is already installed. """ 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)
python
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 downloads this compressed file and, if provided, transforms it into a module before installing it. This method is the predecessor of :meth:`~sagemaker_containers.beta.framework.files.download_and_extract` and has been kept for backward-compatibility purposes. Args: name (str): name of the script or module. uri (str): the location of the module. cache (bool): defaults to True. It will not download and install the module again if it is already installed. """ 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)
[ "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. 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 method is the predecessor of :meth:`~sagemaker_containers.beta.framework.files.download_and_extract` and has been kept for backward-compatibility purposes. Args: name (str): name of the script or module. uri (str): the location of the module. cache (bool): defaults to True. It will not download and install the module again if it is already installed.
[ "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
233,360
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 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 this (e.g. it may allow you to use a name that includes a hyphen). Package names (including namespace packages) are also permitted. When a package name is supplied instead of a normal module, the interpreter will execute <pkg>.__main__ as the main module. This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument. Note This option cannot be used with built-in modules and extension modules written in C, since they do not have Python module files. However, it can still be used for precompiled modules, even if the original source file is not available. If this option is given, the first element of sys.argv will be the full path to the module file ( while the module file is being located, the first element will be set to "-m"). As with the -c option, the current directory will be added to the start of sys.path. You can find more information at https://docs.python.org/3/using/cmdline.html#cmdoption-m Example: >>>import sagemaker_containers >>>from sagemaker_containers.beta.framework import mapping, modules >>>env = sagemaker_containers.training_env() {'channel-input-dirs': {'training': '/opt/ml/input/training'}, 'model_dir': '/opt/ml/model', ...} >>>hyperparameters = env.hyperparameters {'batch-size': 128, 'model_dir': '/opt/ml/model'} >>>args = mapping.to_cmd_args(hyperparameters) ['--batch-size', '128', '--model_dir', '/opt/ml/model'] >>>env_vars = mapping.to_env_vars() ['SAGEMAKER_CHANNELS':'training', 'SAGEMAKER_CHANNEL_TRAINING':'/opt/ml/input/training', 'MODEL_DIR':'/opt/ml/model', ...} >>>modules.run('user_script', args, env_vars) SAGEMAKER_CHANNELS=training SAGEMAKER_CHANNEL_TRAINING=/opt/ml/input/training \ SAGEMAKER_MODEL_DIR=/opt/ml/model python -m user_script --batch-size 128 --model_dir /opt/ml/model Args: module_name (str): module name in the same format required by python -m <module-name> cli command. args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written. capture_error (bool): Default false. If True, the running process captures the stderr, and appends it to the returned Exception message in case of errors. """ 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)
python
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 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 this (e.g. it may allow you to use a name that includes a hyphen). Package names (including namespace packages) are also permitted. When a package name is supplied instead of a normal module, the interpreter will execute <pkg>.__main__ as the main module. This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument. Note This option cannot be used with built-in modules and extension modules written in C, since they do not have Python module files. However, it can still be used for precompiled modules, even if the original source file is not available. If this option is given, the first element of sys.argv will be the full path to the module file ( while the module file is being located, the first element will be set to "-m"). As with the -c option, the current directory will be added to the start of sys.path. You can find more information at https://docs.python.org/3/using/cmdline.html#cmdoption-m Example: >>>import sagemaker_containers >>>from sagemaker_containers.beta.framework import mapping, modules >>>env = sagemaker_containers.training_env() {'channel-input-dirs': {'training': '/opt/ml/input/training'}, 'model_dir': '/opt/ml/model', ...} >>>hyperparameters = env.hyperparameters {'batch-size': 128, 'model_dir': '/opt/ml/model'} >>>args = mapping.to_cmd_args(hyperparameters) ['--batch-size', '128', '--model_dir', '/opt/ml/model'] >>>env_vars = mapping.to_env_vars() ['SAGEMAKER_CHANNELS':'training', 'SAGEMAKER_CHANNEL_TRAINING':'/opt/ml/input/training', 'MODEL_DIR':'/opt/ml/model', ...} >>>modules.run('user_script', args, env_vars) SAGEMAKER_CHANNELS=training SAGEMAKER_CHANNEL_TRAINING=/opt/ml/input/training \ SAGEMAKER_MODEL_DIR=/opt/ml/model python -m user_script --batch-size 128 --model_dir /opt/ml/model Args: module_name (str): module name in the same format required by python -m <module-name> cli command. args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written. capture_error (bool): Default false. If True, the running process captures the stderr, and appends it to the returned Exception message in case of errors. """ 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)
[ "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. 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 this (e.g. it may allow you to use a name that includes a hyphen). Package names (including namespace packages) are also permitted. When a package name is supplied instead of a normal module, the interpreter will execute <pkg>.__main__ as the main module. This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument. Note This option cannot be used with built-in modules and extension modules written in C, since they do not have Python module files. However, it can still be used for precompiled modules, even if the original source file is not available. If this option is given, the first element of sys.argv will be the full path to the module file ( while the module file is being located, the first element will be set to "-m"). As with the -c option, the current directory will be added to the start of sys.path. You can find more information at https://docs.python.org/3/using/cmdline.html#cmdoption-m Example: >>>import sagemaker_containers >>>from sagemaker_containers.beta.framework import mapping, modules >>>env = sagemaker_containers.training_env() {'channel-input-dirs': {'training': '/opt/ml/input/training'}, 'model_dir': '/opt/ml/model', ...} >>>hyperparameters = env.hyperparameters {'batch-size': 128, 'model_dir': '/opt/ml/model'} >>>args = mapping.to_cmd_args(hyperparameters) ['--batch-size', '128', '--model_dir', '/opt/ml/model'] >>>env_vars = mapping.to_env_vars() ['SAGEMAKER_CHANNELS':'training', 'SAGEMAKER_CHANNEL_TRAINING':'/opt/ml/input/training', 'MODEL_DIR':'/opt/ml/model', ...} >>>modules.run('user_script', args, env_vars) SAGEMAKER_CHANNELS=training SAGEMAKER_CHANNEL_TRAINING=/opt/ml/input/training \ SAGEMAKER_MODEL_DIR=/opt/ml/model python -m user_script --batch-size 128 --model_dir /opt/ml/model Args: module_name (str): module name in the same format required by python -m <module-name> cli command. args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written. capture_error (bool): Default false. If True, the running process captures the stderr, and appends it to the returned Exception message in case of errors.
[ "Run", "Python", "module", "as", "a", "script", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_modules.py#L162-L225
233,361
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 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 executes it. Args: uri (str): the location of the module. args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written. name (str): name of the script or module. cache (bool): If True it will avoid downloading the module again, if already installed. wait (bool): If True run_module will wait for the user module to exit and check the exit code, otherwise it will launch the user module with subprocess and return the process object. """ _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)
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 """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 executes it. Args: uri (str): the location of the module. args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written. name (str): name of the script or module. cache (bool): If True it will avoid downloading the module again, if already installed. wait (bool): If True run_module will wait for the user module to exit and check the exit code, otherwise it will launch the user module with subprocess and return the process object. """ _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)
[ "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. 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 executes it. Args: uri (str): the location of the module. args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written. name (str): name of the script or module. cache (bool): If True it will avoid downloading the module again, if already installed. wait (bool): If True run_module will wait for the user module to exit and check the exit code, otherwise it will launch the user module with subprocess and return the process object.
[ "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
233,362
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): consider a better default content-type return self.headers.get('ContentType') or self.headers.get( 'Content-Type') or _content_types.JSON
python
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): 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'", ")", "or", "_content_types", ".", "JSON" ]
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
233,363
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') if not accept or accept == _content_types.ANY: return self._default_accept else: return accept
python
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') 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", "else", ":", "return", "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
233,364
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 """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)
[ "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
233,365
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, 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 module_name + args - A Python script: executes the script as >>> env_vars python module_name + args - Any other: executes the command as >>> env_vars /bin/sh -c ./module_name + args Example: >>>import sagemaker_containers >>>from sagemaker_containers.beta.framework import entry_point >>>env = sagemaker_containers.training_env() {'channel-input-dirs': {'training': '/opt/ml/input/training'}, 'model_dir': '/opt/ml/model', ...} >>>hyperparameters = env.hyperparameters {'batch-size': 128, 'model_dir': '/opt/ml/model'} >>>args = mapping.to_cmd_args(hyperparameters) ['--batch-size', '128', '--model_dir', '/opt/ml/model'] >>>env_vars = mapping.to_env_vars() ['SAGEMAKER_CHANNELS':'training', 'SAGEMAKER_CHANNEL_TRAINING':'/opt/ml/input/training', 'MODEL_DIR':'/opt/ml/model', ...} >>>entry_point.run('user_script', args, env_vars) SAGEMAKER_CHANNELS=training SAGEMAKER_CHANNEL_TRAINING=/opt/ml/input/training \ SAGEMAKER_MODEL_DIR=/opt/ml/model python -m user_script --batch-size 128 --model_dir /opt/ml/model Args: uri (str): the location of the module. user_entry_point (str): name of the user provided entry point args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written (default: None). wait (bool): If the user entry point should be run to completion before this method returns (default: True). capture_error (bool): Default false. If True, the running process captures the stderr, and appends it to the returned Exception message in case of errors. runner (sagemaker_containers.beta.framework.runner.RunnerType): the type of runner object to be created (default: sagemaker_containers.beta.framework.runner.ProcessRunnerType). extra_opts (dict): Additional options for running the entry point (default: None). Currently, this only applies for MPI. Returns: sagemaker_containers.beta.framework.process.ProcessRunner: the runner object responsible for executing the entry point. """ 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)
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 """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 module_name + args - A Python script: executes the script as >>> env_vars python module_name + args - Any other: executes the command as >>> env_vars /bin/sh -c ./module_name + args Example: >>>import sagemaker_containers >>>from sagemaker_containers.beta.framework import entry_point >>>env = sagemaker_containers.training_env() {'channel-input-dirs': {'training': '/opt/ml/input/training'}, 'model_dir': '/opt/ml/model', ...} >>>hyperparameters = env.hyperparameters {'batch-size': 128, 'model_dir': '/opt/ml/model'} >>>args = mapping.to_cmd_args(hyperparameters) ['--batch-size', '128', '--model_dir', '/opt/ml/model'] >>>env_vars = mapping.to_env_vars() ['SAGEMAKER_CHANNELS':'training', 'SAGEMAKER_CHANNEL_TRAINING':'/opt/ml/input/training', 'MODEL_DIR':'/opt/ml/model', ...} >>>entry_point.run('user_script', args, env_vars) SAGEMAKER_CHANNELS=training SAGEMAKER_CHANNEL_TRAINING=/opt/ml/input/training \ SAGEMAKER_MODEL_DIR=/opt/ml/model python -m user_script --batch-size 128 --model_dir /opt/ml/model Args: uri (str): the location of the module. user_entry_point (str): name of the user provided entry point args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written (default: None). wait (bool): If the user entry point should be run to completion before this method returns (default: True). capture_error (bool): Default false. If True, the running process captures the stderr, and appends it to the returned Exception message in case of errors. runner (sagemaker_containers.beta.framework.runner.RunnerType): the type of runner object to be created (default: sagemaker_containers.beta.framework.runner.ProcessRunnerType). extra_opts (dict): Additional options for running the entry point (default: None). Currently, this only applies for MPI. Returns: sagemaker_containers.beta.framework.process.ProcessRunner: the runner object responsible for executing the entry point. """ 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)
[ "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. If the entry point is: - A Python package: executes the packages as >>> env_vars python -m module_name + args - A Python script: executes the script as >>> env_vars python module_name + args - Any other: executes the command as >>> env_vars /bin/sh -c ./module_name + args Example: >>>import sagemaker_containers >>>from sagemaker_containers.beta.framework import entry_point >>>env = sagemaker_containers.training_env() {'channel-input-dirs': {'training': '/opt/ml/input/training'}, 'model_dir': '/opt/ml/model', ...} >>>hyperparameters = env.hyperparameters {'batch-size': 128, 'model_dir': '/opt/ml/model'} >>>args = mapping.to_cmd_args(hyperparameters) ['--batch-size', '128', '--model_dir', '/opt/ml/model'] >>>env_vars = mapping.to_env_vars() ['SAGEMAKER_CHANNELS':'training', 'SAGEMAKER_CHANNEL_TRAINING':'/opt/ml/input/training', 'MODEL_DIR':'/opt/ml/model', ...} >>>entry_point.run('user_script', args, env_vars) SAGEMAKER_CHANNELS=training SAGEMAKER_CHANNEL_TRAINING=/opt/ml/input/training \ SAGEMAKER_MODEL_DIR=/opt/ml/model python -m user_script --batch-size 128 --model_dir /opt/ml/model Args: uri (str): the location of the module. user_entry_point (str): name of the user provided entry point args (list): A list of program arguments. env_vars (dict): A map containing the environment variables to be written (default: None). wait (bool): If the user entry point should be run to completion before this method returns (default: True). capture_error (bool): Default false. If True, the running process captures the stderr, and appends it to the returned Exception message in case of errors. runner (sagemaker_containers.beta.framework.runner.RunnerType): the type of runner object to be created (default: sagemaker_containers.beta.framework.runner.ProcessRunnerType). extra_opts (dict): Additional options for running the entry point (default: None). Currently, this only applies for MPI. Returns: sagemaker_containers.beta.framework.process.ProcessRunner: the runner object responsible for executing the entry point.
[ "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", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/entry_point.py#L22-L89
233,366
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.INFO: logging.getLogger('boto3').setLevel(logging.INFO) logging.getLogger('s3transfer').setLevel(logging.INFO) logging.getLogger('botocore').setLevel(logging.WARN)
python
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.INFO: logging.getLogger('boto3').setLevel(logging.INFO) logging.getLogger('s3transfer').setLevel(logging.INFO) logging.getLogger('botocore').setLevel(logging.WARN)
[ "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. 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
233,367
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(): """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))
[ "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.
[ "Return", "a", "timestamp", "with", "microsecond", "precision", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_intermediate_output.py#L36-L40
233,368
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 split criteria prefix (str): A prefix which will be added the split criteria Returns: `SplitResultSpec` : A collections.namedtuple with the following attributes: * Args: included (dict[str, object]: A dictionary with the keys included in the criteria. excluded (dict[str, object]: A dictionary with the keys not included in the criteria. """ 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)
python
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 split criteria prefix (str): A prefix which will be added the split criteria Returns: `SplitResultSpec` : A collections.namedtuple with the following attributes: * Args: included (dict[str, object]: A dictionary with the keys included in the criteria. excluded (dict[str, object]: A dictionary with the keys not included in the criteria. """ 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)
[ "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. 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` : A collections.namedtuple with the following attributes: * Args: included (dict[str, object]: A dictionary with the keys included in the criteria. excluded (dict[str, object]: A dictionary with the keys not included in the criteria.
[ "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
233,369
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 with the following args: * Args: response: the serialized data to return accept: the content-type that the data was transformed to. """ return _worker.Response(response=_encoders.encode(prediction, accept), mimetype=accept)
python
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 with the following args: * Args: response: the serialized data to return accept: the content-type that the data was transformed to. """ 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: response: the serialized data to return accept: the content-type that the data was transformed to.
[ "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
233,370
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: * response: the serialized data to return * accept: the content type that the data was serialized into """ 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
python
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: * response: the serialized data to return * accept: the content type that the data was serialized into """ 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
[ "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. Returns: sagemaker_containers.beta.framework.worker.Response: a Flask response object with the following args: * response: the serialized data to return * accept: the content type that the data was serialized into
[ "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
233,371
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): model loaded by model_fn. content: request content. content_type (str): the request Content-Type. accept (str): accept content-type expected by the client. Returns: sagemaker_containers.beta.framework.worker.Response or tuple: the serialized response data and its content type, either as a Response object or a tuple of the form (response_data, content_type) """ 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, model) try: result = self._output_fn(prediction, accept) except _errors.UnsupportedFormatError as e: return self._error_response(e, http_client.NOT_ACCEPTABLE) return result
python
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): model loaded by model_fn. content: request content. content_type (str): the request Content-Type. accept (str): accept content-type expected by the client. Returns: sagemaker_containers.beta.framework.worker.Response or tuple: the serialized response data and its content type, either as a Response object or a tuple of the form (response_data, content_type) """ 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, model) try: result = self._output_fn(prediction, accept) except _errors.UnsupportedFormatError as e: return self._error_response(e, http_client.NOT_ACCEPTABLE) return result
[ "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", ",", "model", ")", "try", ":", "result", "=", "self", ".", "_output_fn", "(", "prediction", ",", "accept", ")", "except", "_errors", ".", "UnsupportedFormatError", "as", "e", ":", "return", "self", ".", "_error_response", "(", "e", ",", "http_client", ".", "NOT_ACCEPTABLE", ")", "return", "result" ]
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. content_type (str): the request Content-Type. accept (str): accept content-type expected by the client. Returns: sagemaker_containers.beta.framework.worker.Response or tuple: the serialized response data and its content type, either as a Response object or a tuple of the form (response_data, content_type)
[ "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
233,372
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_data_config(), hyperparameters=_env.read_hyperparameters())
python
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_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", "=", "_env", ".", "read_input_data_config", "(", ")", ",", "hyperparameters", "=", "_env", ".", "read_hyperparameters", "(", ")", ")" ]
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
233,373
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 """Writes a serializeable object as a JSON file""" 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
233,374
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({}, hyperparameters_file_dir) _write_json({}, input_data_config_file_dir) host_name = socket.gethostname() resources_dict = { "current_host": host_name, "hosts": [host_name] } _write_json(resources_dict, resource_config_file_dir)
python
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({}, hyperparameters_file_dir) _write_json({}, input_data_config_file_dir) host_name = socket.gethostname() resources_dict = { "current_host": host_name, "hosts": [host_name] } _write_json(resources_dict, resource_config_file_dir)
[ "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", "=", "socket", ".", "gethostname", "(", ")", "resources_dict", "=", "{", "\"current_host\"", ":", "host_name", ",", "\"hosts\"", ":", "[", "host_name", "]", "}", "_write_json", "(", "resources_dict", ",", "resource_config_file_dir", ")" ]
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
233,375
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 sum([1 for x in output.split('\n') if x.startswith('GPU ')]) except (OSError, subprocess.CalledProcessError): logger.info('No GPUs detected (normal if no gpus installed)') return 0
python
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 sum([1 for x in output.split('\n') if x.startswith('GPU ')]) except (OSError, subprocess.CalledProcessError): logger.info('No GPUs detected (normal if no gpus installed)') return 0
[ "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 detected (normal if no gpus installed)'", ")", "return", "0" ]
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
233,376
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(): os.environ[name] = value
python
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(): 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", ",", "value", "in", "env_vars", ".", "items", "(", ")", ":", "os", ".", "environ", "[", "name", "]", "=", "value" ]
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
233,377
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, 'user_entry_point': self.user_entry_point, 'framework_params': self.additional_framework_parameters, 'resource_config': self.resource_config, 'input_data_config': self.input_data_config, 'output_data_dir': self.output_data_dir, 'channels': sorted(self.channel_input_dirs.keys()), 'current_host': self.current_host, 'module_name': self.module_name, 'log_level': self.log_level, 'framework_module': self.framework_module, 'input_dir': self.input_dir, 'input_config_dir': self.input_config_dir, 'output_dir': self.output_dir, 'num_cpus': self.num_cpus, 'num_gpus': self.num_gpus, 'model_dir': self.model_dir, 'module_dir': self.module_dir, 'training_env': dict(self), 'user_args': self.to_cmd_args(), 'output_intermediate_dir': self.output_intermediate_dir } for name, path in self.channel_input_dirs.items(): env['channel_%s' % name] = path for key, value in self.hyperparameters.items(): env['hp_%s' % key] = value return _mapping.to_env_vars(env)
python
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, 'user_entry_point': self.user_entry_point, 'framework_params': self.additional_framework_parameters, 'resource_config': self.resource_config, 'input_data_config': self.input_data_config, 'output_data_dir': self.output_data_dir, 'channels': sorted(self.channel_input_dirs.keys()), 'current_host': self.current_host, 'module_name': self.module_name, 'log_level': self.log_level, 'framework_module': self.framework_module, 'input_dir': self.input_dir, 'input_config_dir': self.input_config_dir, 'output_dir': self.output_dir, 'num_cpus': self.num_cpus, 'num_gpus': self.num_gpus, 'model_dir': self.model_dir, 'module_dir': self.module_dir, 'training_env': dict(self), 'user_args': self.to_cmd_args(), 'output_intermediate_dir': self.output_intermediate_dir } for name, path in self.channel_input_dirs.items(): env['channel_%s' % name] = path for key, value in self.hyperparameters.items(): env['hp_%s' % key] = value return _mapping.to_env_vars(env)
[ "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", ".", "resource_config", ",", "'input_data_config'", ":", "self", ".", "input_data_config", ",", "'output_data_dir'", ":", "self", ".", "output_data_dir", ",", "'channels'", ":", "sorted", "(", "self", ".", "channel_input_dirs", ".", "keys", "(", ")", ")", ",", "'current_host'", ":", "self", ".", "current_host", ",", "'module_name'", ":", "self", ".", "module_name", ",", "'log_level'", ":", "self", ".", "log_level", ",", "'framework_module'", ":", "self", ".", "framework_module", ",", "'input_dir'", ":", "self", ".", "input_dir", ",", "'input_config_dir'", ":", "self", ".", "input_config_dir", ",", "'output_dir'", ":", "self", ".", "output_dir", ",", "'num_cpus'", ":", "self", ".", "num_cpus", ",", "'num_gpus'", ":", "self", ".", "num_gpus", ",", "'model_dir'", ":", "self", ".", "model_dir", ",", "'module_dir'", ":", "self", ".", "module_dir", ",", "'training_env'", ":", "dict", "(", "self", ")", ",", "'user_args'", ":", "self", ".", "to_cmd_args", "(", ")", ",", "'output_intermediate_dir'", ":", "self", ".", "output_intermediate_dir", "}", "for", "name", ",", "path", "in", "self", ".", "channel_input_dirs", ".", "items", "(", ")", ":", "env", "[", "'channel_%s'", "%", "name", "]", "=", "path", "for", "key", ",", "value", "in", "self", ".", "hyperparameters", ".", "items", "(", ")", ":", "env", "[", "'hp_%s'", "%", "key", "]", "=", "value", "return", "_mapping", ".", "to_env_vars", "(", "env", ")" ]
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
233,378
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 Args: array_like (np.array or Iterable or int or float): array like object to be converted to NPY. Returns: (obj): NPY array. """ buffer = BytesIO() np.save(buffer, array_like) return buffer.getvalue()
python
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 Args: array_like (np.array or Iterable or int or float): array like object to be converted to NPY. Returns: (obj): NPY array. """ 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 converted to NPY. Returns: (obj): NPY array.
[ "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
233,379
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 """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)
[ "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
233,380
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: array_like (np.array or Iterable or int or float): array like object to be converted to JSON. Returns: (str): object serialized to JSON """ 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)
python
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: array_like (np.array or Iterable or int or float): array like object to be converted to JSON. Returns: (str): object serialized to JSON """ 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", "(", ")", "return", "json", ".", "JSONEncoder", "(", ")", ".", "default", "(", "_array_like", ")", "return", "json", ".", "dumps", "(", "array_like", ",", "default", "=", "default", ")" ]
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 JSON. Returns: (str): object serialized to JSON
[ "Convert", "an", "array", "like", "object", "to", "JSON", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L53-L71
233,381
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 contents of each column, individually. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy array """ data = json.loads(string_like) return np.array(data, dtype=dtype)
python
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 contents of each column, individually. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy 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 be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy array
[ "Convert", "a", "JSON", "object", "to", "a", "numpy", "array", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L74-L86
233,382
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 contents of each column, individually. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy array """ stream = StringIO(string_like) return np.genfromtxt(stream, dtype=dtype, delimiter=',')
python
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 contents of each column, individually. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy 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 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy array
[ "Convert", "a", "CSV", "object", "to", "a", "numpy", "array", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L89-L101
233,383
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: array_like (np.array or Iterable or int or float): array like object to be converted to CSV. Returns: (str): object serialized to CSV """ stream = StringIO() np.savetxt(stream, array_like, delimiter=',', fmt='%s') return stream.getvalue()
python
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: array_like (np.array or Iterable or int or float): array like object to be converted to CSV. Returns: (str): object serialized to CSV """ 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'", ")", "return", "stream", ".", "getvalue", "(", ")" ]
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 CSV. Returns: (str): object serialized to CSV
[ "Convert", "an", "array", "like", "object", "to", "CSV", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L104-L118
233,384
aws/sagemaker-containers
src/sagemaker_containers/_encoders.py
decode
def decode(obj, content_type): # type: (np.array or Iterable or int or float, str) -> np.array """Decode an object ton a one of the default content types to a numpy array. Args: obj (object): to be decoded. content_type (str): content type to be used. Returns: np.array: decoded object. """ try: decoder = _decoders_map[content_type] return decoder(obj) except KeyError: raise _errors.UnsupportedFormatError(content_type)
python
def decode(obj, content_type): # type: (np.array or Iterable or int or float, str) -> np.array """Decode an object ton a one of the default content types to a numpy array. Args: obj (object): to be decoded. content_type (str): content type to be used. Returns: np.array: decoded object. """ try: decoder = _decoders_map[content_type] return decoder(obj) except KeyError: raise _errors.UnsupportedFormatError(content_type)
[ "def", "decode", "(", "obj", ",", "content_type", ")", ":", "# type: (np.array or Iterable or int or float, str) -> np.array", "try", ":", "decoder", "=", "_decoders_map", "[", "content_type", "]", "return", "decoder", "(", "obj", ")", "except", "KeyError", ":", "raise", "_errors", ".", "UnsupportedFormatError", "(", "content_type", ")" ]
Decode an object ton a one of the default content types to a numpy array. Args: obj (object): to be decoded. content_type (str): content type to be used. Returns: np.array: decoded object.
[ "Decode", "an", "object", "ton", "a", "one", "of", "the", "default", "content", "types", "to", "a", "numpy", "array", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L125-L140
233,385
aws/sagemaker-containers
src/sagemaker_containers/_encoders.py
encode
def encode(array_like, content_type): # type: (np.array or Iterable or int or float, str) -> np.array """Encode an array like object in a specific content_type to a numpy array. 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): to be converted to numpy. content_type (str): content type to be used. Returns: (np.array): object converted as numpy array. """ try: encoder = _encoders_map[content_type] return encoder(array_like) except KeyError: raise _errors.UnsupportedFormatError(content_type)
python
def encode(array_like, content_type): # type: (np.array or Iterable or int or float, str) -> np.array """Encode an array like object in a specific content_type to a numpy array. 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): to be converted to numpy. content_type (str): content type to be used. Returns: (np.array): object converted as numpy array. """ try: encoder = _encoders_map[content_type] return encoder(array_like) except KeyError: raise _errors.UnsupportedFormatError(content_type)
[ "def", "encode", "(", "array_like", ",", "content_type", ")", ":", "# type: (np.array or Iterable or int or float, str) -> np.array", "try", ":", "encoder", "=", "_encoders_map", "[", "content_type", "]", "return", "encoder", "(", "array_like", ")", "except", "KeyError", ":", "raise", "_errors", ".", "UnsupportedFormatError", "(", "content_type", ")" ]
Encode an array like object in a specific content_type to a numpy array. 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): to be converted to numpy. content_type (str): content type to be used. Returns: (np.array): object converted as numpy array.
[ "Encode", "an", "array", "like", "object", "in", "a", "specific", "content_type", "to", "a", "numpy", "array", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_encoders.py#L143-L161
233,386
aws/sagemaker-containers
src/sagemaker_containers/_files.py
tmpdir
def tmpdir(suffix='', prefix='tmp', dir=None): # type: (str, str, str) -> None """Create a temporary directory with a context manager. The file is deleted when the context exits. The prefix, suffix, and dir arguments are the same as for mkstemp(). Args: suffix (str): If suffix is specified, the file name will end with that suffix, otherwise there will be no suffix. prefix (str): If prefix is specified, the file name will begin with that prefix; otherwise, a default prefix is used. dir (str): If dir is specified, the file will be created in that directory; otherwise, a default directory is used. Returns: str: path to the directory """ tmp = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir) yield tmp shutil.rmtree(tmp)
python
def tmpdir(suffix='', prefix='tmp', dir=None): # type: (str, str, str) -> None """Create a temporary directory with a context manager. The file is deleted when the context exits. The prefix, suffix, and dir arguments are the same as for mkstemp(). Args: suffix (str): If suffix is specified, the file name will end with that suffix, otherwise there will be no suffix. prefix (str): If prefix is specified, the file name will begin with that prefix; otherwise, a default prefix is used. dir (str): If dir is specified, the file will be created in that directory; otherwise, a default directory is used. Returns: str: path to the directory """ tmp = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir) yield tmp shutil.rmtree(tmp)
[ "def", "tmpdir", "(", "suffix", "=", "''", ",", "prefix", "=", "'tmp'", ",", "dir", "=", "None", ")", ":", "# type: (str, str, str) -> None", "tmp", "=", "tempfile", ".", "mkdtemp", "(", "suffix", "=", "suffix", ",", "prefix", "=", "prefix", ",", "dir", "=", "dir", ")", "yield", "tmp", "shutil", ".", "rmtree", "(", "tmp", ")" ]
Create a temporary directory with a context manager. The file is deleted when the context exits. The prefix, suffix, and dir arguments are the same as for mkstemp(). Args: suffix (str): If suffix is specified, the file name will end with that suffix, otherwise there will be no suffix. prefix (str): If prefix is specified, the file name will begin with that prefix; otherwise, a default prefix is used. dir (str): If dir is specified, the file will be created in that directory; otherwise, a default directory is used. Returns: str: path to the directory
[ "Create", "a", "temporary", "directory", "with", "a", "context", "manager", ".", "The", "file", "is", "deleted", "when", "the", "context", "exits", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_files.py#L50-L67
233,387
aws/sagemaker-containers
src/sagemaker_containers/_files.py
download_and_extract
def download_and_extract(uri, name, path): # type: (str, str, str) -> None """Download, prepare and install a compressed tar file from S3 or local directory as an entry point. SageMaker Python SDK saves the user provided entry points as compressed tar files in S3 Args: name (str): name of the entry point. uri (str): the location of the entry point. path (bool): The path where the script will be installed. It will not download and install the if the path already has the user entry point. """ if not os.path.exists(path): os.makedirs(path) if not os.listdir(path): with tmpdir() as tmp: if uri.startswith('s3://'): dst = os.path.join(tmp, 'tar_file') s3_download(uri, dst) with tarfile.open(name=dst, mode='r:gz') as t: t.extractall(path=path) elif os.path.isdir(uri): if uri == path: return if os.path.exists(path): shutil.rmtree(path) shutil.move(uri, path) else: shutil.copy2(uri, os.path.join(path, name))
python
def download_and_extract(uri, name, path): # type: (str, str, str) -> None """Download, prepare and install a compressed tar file from S3 or local directory as an entry point. SageMaker Python SDK saves the user provided entry points as compressed tar files in S3 Args: name (str): name of the entry point. uri (str): the location of the entry point. path (bool): The path where the script will be installed. It will not download and install the if the path already has the user entry point. """ if not os.path.exists(path): os.makedirs(path) if not os.listdir(path): with tmpdir() as tmp: if uri.startswith('s3://'): dst = os.path.join(tmp, 'tar_file') s3_download(uri, dst) with tarfile.open(name=dst, mode='r:gz') as t: t.extractall(path=path) elif os.path.isdir(uri): if uri == path: return if os.path.exists(path): shutil.rmtree(path) shutil.move(uri, path) else: shutil.copy2(uri, os.path.join(path, name))
[ "def", "download_and_extract", "(", "uri", ",", "name", ",", "path", ")", ":", "# type: (str, str, str) -> None", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "if", "not", "os", ".", "listdir", "(", "path", ")", ":", "with", "tmpdir", "(", ")", "as", "tmp", ":", "if", "uri", ".", "startswith", "(", "'s3://'", ")", ":", "dst", "=", "os", ".", "path", ".", "join", "(", "tmp", ",", "'tar_file'", ")", "s3_download", "(", "uri", ",", "dst", ")", "with", "tarfile", ".", "open", "(", "name", "=", "dst", ",", "mode", "=", "'r:gz'", ")", "as", "t", ":", "t", ".", "extractall", "(", "path", "=", "path", ")", "elif", "os", ".", "path", ".", "isdir", "(", "uri", ")", ":", "if", "uri", "==", "path", ":", "return", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "shutil", ".", "move", "(", "uri", ",", "path", ")", "else", ":", "shutil", ".", "copy2", "(", "uri", ",", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", ")" ]
Download, prepare and install a compressed tar file from S3 or local directory as an entry point. SageMaker Python SDK saves the user provided entry points as compressed tar files in S3 Args: name (str): name of the entry point. uri (str): the location of the entry point. path (bool): The path where the script will be installed. It will not download and install the if the path already has the user entry point.
[ "Download", "prepare", "and", "install", "a", "compressed", "tar", "file", "from", "S3", "or", "local", "directory", "as", "an", "entry", "point", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_files.py#L108-L137
233,388
aws/sagemaker-containers
src/sagemaker_containers/_files.py
s3_download
def s3_download(url, dst): # type: (str, str) -> None """Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved. """ url = parse.urlparse(url) if url.scheme != 's3': raise ValueError("Expecting 's3' scheme, got: %s in %s" % (url.scheme, url)) bucket, key = url.netloc, url.path.lstrip('/') region = os.environ.get('AWS_REGION', os.environ.get(_params.REGION_NAME_ENV)) s3 = boto3.resource('s3', region_name=region) s3.Bucket(bucket).download_file(key, dst)
python
def s3_download(url, dst): # type: (str, str) -> None """Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved. """ url = parse.urlparse(url) if url.scheme != 's3': raise ValueError("Expecting 's3' scheme, got: %s in %s" % (url.scheme, url)) bucket, key = url.netloc, url.path.lstrip('/') region = os.environ.get('AWS_REGION', os.environ.get(_params.REGION_NAME_ENV)) s3 = boto3.resource('s3', region_name=region) s3.Bucket(bucket).download_file(key, dst)
[ "def", "s3_download", "(", "url", ",", "dst", ")", ":", "# type: (str, str) -> None", "url", "=", "parse", ".", "urlparse", "(", "url", ")", "if", "url", ".", "scheme", "!=", "'s3'", ":", "raise", "ValueError", "(", "\"Expecting 's3' scheme, got: %s in %s\"", "%", "(", "url", ".", "scheme", ",", "url", ")", ")", "bucket", ",", "key", "=", "url", ".", "netloc", ",", "url", ".", "path", ".", "lstrip", "(", "'/'", ")", "region", "=", "os", ".", "environ", ".", "get", "(", "'AWS_REGION'", ",", "os", ".", "environ", ".", "get", "(", "_params", ".", "REGION_NAME_ENV", ")", ")", "s3", "=", "boto3", ".", "resource", "(", "'s3'", ",", "region_name", "=", "region", ")", "s3", ".", "Bucket", "(", "bucket", ")", ".", "download_file", "(", "key", ",", "dst", ")" ]
Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved.
[ "Download", "a", "file", "from", "S3", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_files.py#L140-L157
233,389
aws/sagemaker-containers
src/sagemaker_containers/_functions.py
matching_args
def matching_args(fn, dictionary): # type: (Callable, _mapping.Mapping) -> dict """Given a function fn and a dict dictionary, returns the function arguments that match the dict keys. Example: def train(channel_dirs, model_dir): pass dictionary = {'channel_dirs': {}, 'model_dir': '/opt/ml/model', 'other_args': None} args = functions.matching_args(train, dictionary) # {'channel_dirs': {}, 'model_dir': '/opt/ml/model'} train(**args) Args: fn (function): a function dictionary (dict): the dictionary with the keys Returns: (dict) a dictionary with only matching arguments. """ arg_spec = getargspec(fn) if arg_spec.keywords: return dictionary return _mapping.split_by_criteria(dictionary, arg_spec.args).included
python
def matching_args(fn, dictionary): # type: (Callable, _mapping.Mapping) -> dict """Given a function fn and a dict dictionary, returns the function arguments that match the dict keys. Example: def train(channel_dirs, model_dir): pass dictionary = {'channel_dirs': {}, 'model_dir': '/opt/ml/model', 'other_args': None} args = functions.matching_args(train, dictionary) # {'channel_dirs': {}, 'model_dir': '/opt/ml/model'} train(**args) Args: fn (function): a function dictionary (dict): the dictionary with the keys Returns: (dict) a dictionary with only matching arguments. """ arg_spec = getargspec(fn) if arg_spec.keywords: return dictionary return _mapping.split_by_criteria(dictionary, arg_spec.args).included
[ "def", "matching_args", "(", "fn", ",", "dictionary", ")", ":", "# type: (Callable, _mapping.Mapping) -> dict", "arg_spec", "=", "getargspec", "(", "fn", ")", "if", "arg_spec", ".", "keywords", ":", "return", "dictionary", "return", "_mapping", ".", "split_by_criteria", "(", "dictionary", ",", "arg_spec", ".", "args", ")", ".", "included" ]
Given a function fn and a dict dictionary, returns the function arguments that match the dict keys. Example: def train(channel_dirs, model_dir): pass dictionary = {'channel_dirs': {}, 'model_dir': '/opt/ml/model', 'other_args': None} args = functions.matching_args(train, dictionary) # {'channel_dirs': {}, 'model_dir': '/opt/ml/model'} train(**args) Args: fn (function): a function dictionary (dict): the dictionary with the keys Returns: (dict) a dictionary with only matching arguments.
[ "Given", "a", "function", "fn", "and", "a", "dict", "dictionary", "returns", "the", "function", "arguments", "that", "match", "the", "dict", "keys", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_functions.py#L24-L48
233,390
aws/sagemaker-containers
src/sagemaker_containers/_functions.py
error_wrapper
def error_wrapper(fn, error_class): # type: (Callable or None, Exception) -> ... """Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): function to wrapped error_class (Exception): Error class to be re-raised Returns: (object): fn wrapped in a try catch. """ def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: six.reraise(error_class, error_class(e), sys.exc_info()[2]) return wrapper
python
def error_wrapper(fn, error_class): # type: (Callable or None, Exception) -> ... """Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): function to wrapped error_class (Exception): Error class to be re-raised Returns: (object): fn wrapped in a try catch. """ def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: six.reraise(error_class, error_class(e), sys.exc_info()[2]) return wrapper
[ "def", "error_wrapper", "(", "fn", ",", "error_class", ")", ":", "# type: (Callable or None, Exception) -> ...", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "six", ".", "reraise", "(", "error_class", ",", "error_class", "(", "e", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "return", "wrapper" ]
Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): function to wrapped error_class (Exception): Error class to be re-raised Returns: (object): fn wrapped in a try catch.
[ "Wraps", "function", "fn", "in", "a", "try", "catch", "block", "that", "re", "-", "raises", "error_class", "." ]
0030f07abbaf22a55d986d97274d7a8d1aa1f10c
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_functions.py#L73-L89
233,391
ceph/ceph-deploy
ceph_deploy/util/packages.py
ceph_is_installed
def ceph_is_installed(module): """ A helper callback to be executed after the connection is made to ensure that Ceph is installed. """ ceph_package = Ceph(module.conn) if not ceph_package.installed: host = module.conn.hostname raise RuntimeError( 'ceph needs to be installed in remote host: %s' % host )
python
def ceph_is_installed(module): """ A helper callback to be executed after the connection is made to ensure that Ceph is installed. """ ceph_package = Ceph(module.conn) if not ceph_package.installed: host = module.conn.hostname raise RuntimeError( 'ceph needs to be installed in remote host: %s' % host )
[ "def", "ceph_is_installed", "(", "module", ")", ":", "ceph_package", "=", "Ceph", "(", "module", ".", "conn", ")", "if", "not", "ceph_package", ".", "installed", ":", "host", "=", "module", ".", "conn", ".", "hostname", "raise", "RuntimeError", "(", "'ceph needs to be installed in remote host: %s'", "%", "host", ")" ]
A helper callback to be executed after the connection is made to ensure that Ceph is installed.
[ "A", "helper", "callback", "to", "be", "executed", "after", "the", "connection", "is", "made", "to", "ensure", "that", "Ceph", "is", "installed", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/packages.py#L64-L74
233,392
ceph/ceph-deploy
ceph_deploy/util/log.py
color_format
def color_format(): """ Main entry point to get a colored formatter, it will use the BASE_FORMAT by default and fall back to no colors if the system does not support it """ str_format = BASE_COLOR_FORMAT if supports_color() else BASE_FORMAT color_format = color_message(str_format) return ColoredFormatter(color_format)
python
def color_format(): """ Main entry point to get a colored formatter, it will use the BASE_FORMAT by default and fall back to no colors if the system does not support it """ str_format = BASE_COLOR_FORMAT if supports_color() else BASE_FORMAT color_format = color_message(str_format) return ColoredFormatter(color_format)
[ "def", "color_format", "(", ")", ":", "str_format", "=", "BASE_COLOR_FORMAT", "if", "supports_color", "(", ")", "else", "BASE_FORMAT", "color_format", "=", "color_message", "(", "str_format", ")", "return", "ColoredFormatter", "(", "color_format", ")" ]
Main entry point to get a colored formatter, it will use the BASE_FORMAT by default and fall back to no colors if the system does not support it
[ "Main", "entry", "point", "to", "get", "a", "colored", "formatter", "it", "will", "use", "the", "BASE_FORMAT", "by", "default", "and", "fall", "back", "to", "no", "colors", "if", "the", "system", "does", "not", "support", "it" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/log.py#L59-L67
233,393
ceph/ceph-deploy
ceph_deploy/mon.py
mon_status_check
def mon_status_check(conn, logger, hostname, args): """ A direct check for JSON output on the monitor status. For newer versions of Ceph (dumpling and newer) a new mon_status command was added ( `ceph daemon mon mon_status` ) and should be revisited if the output changes as this check depends on that availability. """ asok_path = paths.mon.asok(args.cluster, hostname) out, err, code = remoto.process.check( conn, [ 'ceph', '--cluster={cluster}'.format(cluster=args.cluster), '--admin-daemon', asok_path, 'mon_status', ], ) for line in err: logger.error(line) try: return json.loads(b''.join(out).decode('utf-8')) except ValueError: return {}
python
def mon_status_check(conn, logger, hostname, args): """ A direct check for JSON output on the monitor status. For newer versions of Ceph (dumpling and newer) a new mon_status command was added ( `ceph daemon mon mon_status` ) and should be revisited if the output changes as this check depends on that availability. """ asok_path = paths.mon.asok(args.cluster, hostname) out, err, code = remoto.process.check( conn, [ 'ceph', '--cluster={cluster}'.format(cluster=args.cluster), '--admin-daemon', asok_path, 'mon_status', ], ) for line in err: logger.error(line) try: return json.loads(b''.join(out).decode('utf-8')) except ValueError: return {}
[ "def", "mon_status_check", "(", "conn", ",", "logger", ",", "hostname", ",", "args", ")", ":", "asok_path", "=", "paths", ".", "mon", ".", "asok", "(", "args", ".", "cluster", ",", "hostname", ")", "out", ",", "err", ",", "code", "=", "remoto", ".", "process", ".", "check", "(", "conn", ",", "[", "'ceph'", ",", "'--cluster={cluster}'", ".", "format", "(", "cluster", "=", "args", ".", "cluster", ")", ",", "'--admin-daemon'", ",", "asok_path", ",", "'mon_status'", ",", "]", ",", ")", "for", "line", "in", "err", ":", "logger", ".", "error", "(", "line", ")", "try", ":", "return", "json", ".", "loads", "(", "b''", ".", "join", "(", "out", ")", ".", "decode", "(", "'utf-8'", ")", ")", "except", "ValueError", ":", "return", "{", "}" ]
A direct check for JSON output on the monitor status. For newer versions of Ceph (dumpling and newer) a new mon_status command was added ( `ceph daemon mon mon_status` ) and should be revisited if the output changes as this check depends on that availability.
[ "A", "direct", "check", "for", "JSON", "output", "on", "the", "monitor", "status", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mon.py#L21-L49
233,394
ceph/ceph-deploy
ceph_deploy/mon.py
catch_mon_errors
def catch_mon_errors(conn, logger, hostname, cfg, args): """ Make sure we are able to catch up common mishaps with monitors and use that state of a monitor to determine what is missing and warn apropriately about it. """ monmap = mon_status_check(conn, logger, hostname, args).get('monmap', {}) mon_initial_members = get_mon_initial_members(args, _cfg=cfg) public_addr = cfg.safe_get('global', 'public_addr') public_network = cfg.safe_get('global', 'public_network') mon_in_monmap = [ mon.get('name') for mon in monmap.get('mons', [{}]) if mon.get('name') == hostname ] if mon_initial_members is None or not hostname in mon_initial_members: logger.warning('%s is not defined in `mon initial members`', hostname) if not mon_in_monmap: logger.warning('monitor %s does not exist in monmap', hostname) if not public_addr and not public_network: logger.warning('neither `public_addr` nor `public_network` keys are defined for monitors') logger.warning('monitors may not be able to form quorum')
python
def catch_mon_errors(conn, logger, hostname, cfg, args): """ Make sure we are able to catch up common mishaps with monitors and use that state of a monitor to determine what is missing and warn apropriately about it. """ monmap = mon_status_check(conn, logger, hostname, args).get('monmap', {}) mon_initial_members = get_mon_initial_members(args, _cfg=cfg) public_addr = cfg.safe_get('global', 'public_addr') public_network = cfg.safe_get('global', 'public_network') mon_in_monmap = [ mon.get('name') for mon in monmap.get('mons', [{}]) if mon.get('name') == hostname ] if mon_initial_members is None or not hostname in mon_initial_members: logger.warning('%s is not defined in `mon initial members`', hostname) if not mon_in_monmap: logger.warning('monitor %s does not exist in monmap', hostname) if not public_addr and not public_network: logger.warning('neither `public_addr` nor `public_network` keys are defined for monitors') logger.warning('monitors may not be able to form quorum')
[ "def", "catch_mon_errors", "(", "conn", ",", "logger", ",", "hostname", ",", "cfg", ",", "args", ")", ":", "monmap", "=", "mon_status_check", "(", "conn", ",", "logger", ",", "hostname", ",", "args", ")", ".", "get", "(", "'monmap'", ",", "{", "}", ")", "mon_initial_members", "=", "get_mon_initial_members", "(", "args", ",", "_cfg", "=", "cfg", ")", "public_addr", "=", "cfg", ".", "safe_get", "(", "'global'", ",", "'public_addr'", ")", "public_network", "=", "cfg", ".", "safe_get", "(", "'global'", ",", "'public_network'", ")", "mon_in_monmap", "=", "[", "mon", ".", "get", "(", "'name'", ")", "for", "mon", "in", "monmap", ".", "get", "(", "'mons'", ",", "[", "{", "}", "]", ")", "if", "mon", ".", "get", "(", "'name'", ")", "==", "hostname", "]", "if", "mon_initial_members", "is", "None", "or", "not", "hostname", "in", "mon_initial_members", ":", "logger", ".", "warning", "(", "'%s is not defined in `mon initial members`'", ",", "hostname", ")", "if", "not", "mon_in_monmap", ":", "logger", ".", "warning", "(", "'monitor %s does not exist in monmap'", ",", "hostname", ")", "if", "not", "public_addr", "and", "not", "public_network", ":", "logger", ".", "warning", "(", "'neither `public_addr` nor `public_network` keys are defined for monitors'", ")", "logger", ".", "warning", "(", "'monitors may not be able to form quorum'", ")" ]
Make sure we are able to catch up common mishaps with monitors and use that state of a monitor to determine what is missing and warn apropriately about it.
[ "Make", "sure", "we", "are", "able", "to", "catch", "up", "common", "mishaps", "with", "monitors", "and", "use", "that", "state", "of", "a", "monitor", "to", "determine", "what", "is", "missing", "and", "warn", "apropriately", "about", "it", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mon.py#L52-L73
233,395
ceph/ceph-deploy
ceph_deploy/mon.py
mon_status
def mon_status(conn, logger, hostname, args, silent=False): """ run ``ceph daemon mon.`hostname` mon_status`` on the remote end and provide not only the output, but be able to return a boolean status of what is going on. ``False`` represents a monitor that is not doing OK even if it is up and running, while ``True`` would mean the monitor is up and running correctly. """ mon = 'mon.%s' % hostname try: out = mon_status_check(conn, logger, hostname, args) if not out: logger.warning('monitor: %s, might not be running yet' % mon) return False if not silent: logger.debug('*'*80) logger.debug('status for monitor: %s' % mon) for line in json.dumps(out, indent=2, sort_keys=True).split('\n'): logger.debug(line) logger.debug('*'*80) if out['rank'] >= 0: logger.info('monitor: %s is running' % mon) return True if out['rank'] == -1 and out['state']: logger.info('monitor: %s is currently at the state of %s' % (mon, out['state'])) return True logger.info('monitor: %s is not running' % mon) return False except RuntimeError: logger.info('monitor: %s is not running' % mon) return False
python
def mon_status(conn, logger, hostname, args, silent=False): """ run ``ceph daemon mon.`hostname` mon_status`` on the remote end and provide not only the output, but be able to return a boolean status of what is going on. ``False`` represents a monitor that is not doing OK even if it is up and running, while ``True`` would mean the monitor is up and running correctly. """ mon = 'mon.%s' % hostname try: out = mon_status_check(conn, logger, hostname, args) if not out: logger.warning('monitor: %s, might not be running yet' % mon) return False if not silent: logger.debug('*'*80) logger.debug('status for monitor: %s' % mon) for line in json.dumps(out, indent=2, sort_keys=True).split('\n'): logger.debug(line) logger.debug('*'*80) if out['rank'] >= 0: logger.info('monitor: %s is running' % mon) return True if out['rank'] == -1 and out['state']: logger.info('monitor: %s is currently at the state of %s' % (mon, out['state'])) return True logger.info('monitor: %s is not running' % mon) return False except RuntimeError: logger.info('monitor: %s is not running' % mon) return False
[ "def", "mon_status", "(", "conn", ",", "logger", ",", "hostname", ",", "args", ",", "silent", "=", "False", ")", ":", "mon", "=", "'mon.%s'", "%", "hostname", "try", ":", "out", "=", "mon_status_check", "(", "conn", ",", "logger", ",", "hostname", ",", "args", ")", "if", "not", "out", ":", "logger", ".", "warning", "(", "'monitor: %s, might not be running yet'", "%", "mon", ")", "return", "False", "if", "not", "silent", ":", "logger", ".", "debug", "(", "'*'", "*", "80", ")", "logger", ".", "debug", "(", "'status for monitor: %s'", "%", "mon", ")", "for", "line", "in", "json", ".", "dumps", "(", "out", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ")", ".", "split", "(", "'\\n'", ")", ":", "logger", ".", "debug", "(", "line", ")", "logger", ".", "debug", "(", "'*'", "*", "80", ")", "if", "out", "[", "'rank'", "]", ">=", "0", ":", "logger", ".", "info", "(", "'monitor: %s is running'", "%", "mon", ")", "return", "True", "if", "out", "[", "'rank'", "]", "==", "-", "1", "and", "out", "[", "'state'", "]", ":", "logger", ".", "info", "(", "'monitor: %s is currently at the state of %s'", "%", "(", "mon", ",", "out", "[", "'state'", "]", ")", ")", "return", "True", "logger", ".", "info", "(", "'monitor: %s is not running'", "%", "mon", ")", "return", "False", "except", "RuntimeError", ":", "logger", ".", "info", "(", "'monitor: %s is not running'", "%", "mon", ")", "return", "False" ]
run ``ceph daemon mon.`hostname` mon_status`` on the remote end and provide not only the output, but be able to return a boolean status of what is going on. ``False`` represents a monitor that is not doing OK even if it is up and running, while ``True`` would mean the monitor is up and running correctly.
[ "run", "ceph", "daemon", "mon", ".", "hostname", "mon_status", "on", "the", "remote", "end", "and", "provide", "not", "only", "the", "output", "but", "be", "able", "to", "return", "a", "boolean", "status", "of", "what", "is", "going", "on", ".", "False", "represents", "a", "monitor", "that", "is", "not", "doing", "OK", "even", "if", "it", "is", "up", "and", "running", "while", "True", "would", "mean", "the", "monitor", "is", "up", "and", "running", "correctly", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mon.py#L76-L108
233,396
ceph/ceph-deploy
ceph_deploy/mon.py
hostname_is_compatible
def hostname_is_compatible(conn, logger, provided_hostname): """ Make sure that the host that we are connecting to has the same value as the `hostname` in the remote host, otherwise mons can fail not reaching quorum. """ logger.debug('determining if provided host has same hostname in remote') remote_hostname = conn.remote_module.shortname() if remote_hostname == provided_hostname: return logger.warning('*'*80) logger.warning('provided hostname must match remote hostname') logger.warning('provided hostname: %s' % provided_hostname) logger.warning('remote hostname: %s' % remote_hostname) logger.warning('monitors may not reach quorum and create-keys will not complete') logger.warning('*'*80)
python
def hostname_is_compatible(conn, logger, provided_hostname): """ Make sure that the host that we are connecting to has the same value as the `hostname` in the remote host, otherwise mons can fail not reaching quorum. """ logger.debug('determining if provided host has same hostname in remote') remote_hostname = conn.remote_module.shortname() if remote_hostname == provided_hostname: return logger.warning('*'*80) logger.warning('provided hostname must match remote hostname') logger.warning('provided hostname: %s' % provided_hostname) logger.warning('remote hostname: %s' % remote_hostname) logger.warning('monitors may not reach quorum and create-keys will not complete') logger.warning('*'*80)
[ "def", "hostname_is_compatible", "(", "conn", ",", "logger", ",", "provided_hostname", ")", ":", "logger", ".", "debug", "(", "'determining if provided host has same hostname in remote'", ")", "remote_hostname", "=", "conn", ".", "remote_module", ".", "shortname", "(", ")", "if", "remote_hostname", "==", "provided_hostname", ":", "return", "logger", ".", "warning", "(", "'*'", "*", "80", ")", "logger", ".", "warning", "(", "'provided hostname must match remote hostname'", ")", "logger", ".", "warning", "(", "'provided hostname: %s'", "%", "provided_hostname", ")", "logger", ".", "warning", "(", "'remote hostname: %s'", "%", "remote_hostname", ")", "logger", ".", "warning", "(", "'monitors may not reach quorum and create-keys will not complete'", ")", "logger", ".", "warning", "(", "'*'", "*", "80", ")" ]
Make sure that the host that we are connecting to has the same value as the `hostname` in the remote host, otherwise mons can fail not reaching quorum.
[ "Make", "sure", "that", "the", "host", "that", "we", "are", "connecting", "to", "has", "the", "same", "value", "as", "the", "hostname", "in", "the", "remote", "host", "otherwise", "mons", "can", "fail", "not", "reaching", "quorum", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mon.py#L290-L304
233,397
ceph/ceph-deploy
ceph_deploy/mon.py
make
def make(parser): """ Ceph MON Daemon management """ parser.formatter_class = ToggleRawTextHelpFormatter mon_parser = parser.add_subparsers(dest='subcommand') mon_parser.required = True mon_add = mon_parser.add_parser( 'add', help=('R|Add a monitor to an existing cluster:\n' '\tceph-deploy mon add node1\n' 'Or:\n' '\tceph-deploy mon add --address 192.168.1.10 node1\n' 'If the section for the monitor exists and defines a `mon addr` that\n' 'will be used, otherwise it will fallback by resolving the hostname to an\n' 'IP. If `--address` is used it will override all other options.') ) mon_add.add_argument( '--address', nargs='?', ) mon_add.add_argument( 'mon', nargs=1, ) mon_create = mon_parser.add_parser( 'create', help=('R|Deploy monitors by specifying them like:\n' '\tceph-deploy mon create node1 node2 node3\n' 'If no hosts are passed it will default to use the\n' '`mon initial members` defined in the configuration.') ) mon_create.add_argument( '--keyrings', nargs='?', help='concatenate multiple keyrings to be seeded on new monitors', ) mon_create.add_argument( 'mon', nargs='*', ) mon_create_initial = mon_parser.add_parser( 'create-initial', help=('Will deploy for monitors defined in `mon initial members`, ' 'wait until they form quorum and then gatherkeys, reporting ' 'the monitor status along the process. If monitors don\'t form ' 'quorum the command will eventually time out.') ) mon_create_initial.add_argument( '--keyrings', nargs='?', help='concatenate multiple keyrings to be seeded on new monitors', ) mon_destroy = mon_parser.add_parser( 'destroy', help='Completely remove Ceph MON from remote host(s)' ) mon_destroy.add_argument( 'mon', nargs='+', ) parser.set_defaults( func=mon, )
python
def make(parser): """ Ceph MON Daemon management """ parser.formatter_class = ToggleRawTextHelpFormatter mon_parser = parser.add_subparsers(dest='subcommand') mon_parser.required = True mon_add = mon_parser.add_parser( 'add', help=('R|Add a monitor to an existing cluster:\n' '\tceph-deploy mon add node1\n' 'Or:\n' '\tceph-deploy mon add --address 192.168.1.10 node1\n' 'If the section for the monitor exists and defines a `mon addr` that\n' 'will be used, otherwise it will fallback by resolving the hostname to an\n' 'IP. If `--address` is used it will override all other options.') ) mon_add.add_argument( '--address', nargs='?', ) mon_add.add_argument( 'mon', nargs=1, ) mon_create = mon_parser.add_parser( 'create', help=('R|Deploy monitors by specifying them like:\n' '\tceph-deploy mon create node1 node2 node3\n' 'If no hosts are passed it will default to use the\n' '`mon initial members` defined in the configuration.') ) mon_create.add_argument( '--keyrings', nargs='?', help='concatenate multiple keyrings to be seeded on new monitors', ) mon_create.add_argument( 'mon', nargs='*', ) mon_create_initial = mon_parser.add_parser( 'create-initial', help=('Will deploy for monitors defined in `mon initial members`, ' 'wait until they form quorum and then gatherkeys, reporting ' 'the monitor status along the process. If monitors don\'t form ' 'quorum the command will eventually time out.') ) mon_create_initial.add_argument( '--keyrings', nargs='?', help='concatenate multiple keyrings to be seeded on new monitors', ) mon_destroy = mon_parser.add_parser( 'destroy', help='Completely remove Ceph MON from remote host(s)' ) mon_destroy.add_argument( 'mon', nargs='+', ) parser.set_defaults( func=mon, )
[ "def", "make", "(", "parser", ")", ":", "parser", ".", "formatter_class", "=", "ToggleRawTextHelpFormatter", "mon_parser", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'subcommand'", ")", "mon_parser", ".", "required", "=", "True", "mon_add", "=", "mon_parser", ".", "add_parser", "(", "'add'", ",", "help", "=", "(", "'R|Add a monitor to an existing cluster:\\n'", "'\\tceph-deploy mon add node1\\n'", "'Or:\\n'", "'\\tceph-deploy mon add --address 192.168.1.10 node1\\n'", "'If the section for the monitor exists and defines a `mon addr` that\\n'", "'will be used, otherwise it will fallback by resolving the hostname to an\\n'", "'IP. If `--address` is used it will override all other options.'", ")", ")", "mon_add", ".", "add_argument", "(", "'--address'", ",", "nargs", "=", "'?'", ",", ")", "mon_add", ".", "add_argument", "(", "'mon'", ",", "nargs", "=", "1", ",", ")", "mon_create", "=", "mon_parser", ".", "add_parser", "(", "'create'", ",", "help", "=", "(", "'R|Deploy monitors by specifying them like:\\n'", "'\\tceph-deploy mon create node1 node2 node3\\n'", "'If no hosts are passed it will default to use the\\n'", "'`mon initial members` defined in the configuration.'", ")", ")", "mon_create", ".", "add_argument", "(", "'--keyrings'", ",", "nargs", "=", "'?'", ",", "help", "=", "'concatenate multiple keyrings to be seeded on new monitors'", ",", ")", "mon_create", ".", "add_argument", "(", "'mon'", ",", "nargs", "=", "'*'", ",", ")", "mon_create_initial", "=", "mon_parser", ".", "add_parser", "(", "'create-initial'", ",", "help", "=", "(", "'Will deploy for monitors defined in `mon initial members`, '", "'wait until they form quorum and then gatherkeys, reporting '", "'the monitor status along the process. If monitors don\\'t form '", "'quorum the command will eventually time out.'", ")", ")", "mon_create_initial", ".", "add_argument", "(", "'--keyrings'", ",", "nargs", "=", "'?'", ",", "help", "=", "'concatenate multiple keyrings to be seeded on new monitors'", ",", ")", "mon_destroy", "=", "mon_parser", ".", "add_parser", "(", "'destroy'", ",", "help", "=", "'Completely remove Ceph MON from remote host(s)'", ")", "mon_destroy", ".", "add_argument", "(", "'mon'", ",", "nargs", "=", "'+'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "mon", ",", ")" ]
Ceph MON Daemon management
[ "Ceph", "MON", "Daemon", "management" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mon.py#L476-L545
233,398
ceph/ceph-deploy
ceph_deploy/mon.py
get_mon_initial_members
def get_mon_initial_members(args, error_on_empty=False, _cfg=None): """ Read the Ceph config file and return the value of mon_initial_members Optionally, a NeedHostError can be raised if the value is None. """ if _cfg: cfg = _cfg else: cfg = conf.ceph.load(args) mon_initial_members = cfg.safe_get('global', 'mon_initial_members') if not mon_initial_members: if error_on_empty: raise exc.NeedHostError( 'could not find `mon initial members` defined in ceph.conf' ) else: mon_initial_members = re.split(r'[,\s]+', mon_initial_members) return mon_initial_members
python
def get_mon_initial_members(args, error_on_empty=False, _cfg=None): """ Read the Ceph config file and return the value of mon_initial_members Optionally, a NeedHostError can be raised if the value is None. """ if _cfg: cfg = _cfg else: cfg = conf.ceph.load(args) mon_initial_members = cfg.safe_get('global', 'mon_initial_members') if not mon_initial_members: if error_on_empty: raise exc.NeedHostError( 'could not find `mon initial members` defined in ceph.conf' ) else: mon_initial_members = re.split(r'[,\s]+', mon_initial_members) return mon_initial_members
[ "def", "get_mon_initial_members", "(", "args", ",", "error_on_empty", "=", "False", ",", "_cfg", "=", "None", ")", ":", "if", "_cfg", ":", "cfg", "=", "_cfg", "else", ":", "cfg", "=", "conf", ".", "ceph", ".", "load", "(", "args", ")", "mon_initial_members", "=", "cfg", ".", "safe_get", "(", "'global'", ",", "'mon_initial_members'", ")", "if", "not", "mon_initial_members", ":", "if", "error_on_empty", ":", "raise", "exc", ".", "NeedHostError", "(", "'could not find `mon initial members` defined in ceph.conf'", ")", "else", ":", "mon_initial_members", "=", "re", ".", "split", "(", "r'[,\\s]+'", ",", "mon_initial_members", ")", "return", "mon_initial_members" ]
Read the Ceph config file and return the value of mon_initial_members Optionally, a NeedHostError can be raised if the value is None.
[ "Read", "the", "Ceph", "config", "file", "and", "return", "the", "value", "of", "mon_initial_members", "Optionally", "a", "NeedHostError", "can", "be", "raised", "if", "the", "value", "is", "None", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mon.py#L552-L569
233,399
ceph/ceph-deploy
ceph_deploy/mon.py
is_running
def is_running(conn, args): """ Run a command to check the status of a mon, return a boolean. We heavily depend on the format of the output, if that ever changes we need to modify this. Check daemon status for 3 times output of the status should be similar to:: mon.mira094: running {"version":"0.61.5"} or when it fails:: mon.mira094: dead {"version":"0.61.5"} mon.mira094: not running {"version":"0.61.5"} """ stdout, stderr, _ = remoto.process.check( conn, args ) result_string = b' '.join(stdout) for run_check in [b': running', b' start/running']: if run_check in result_string: return True return False
python
def is_running(conn, args): """ Run a command to check the status of a mon, return a boolean. We heavily depend on the format of the output, if that ever changes we need to modify this. Check daemon status for 3 times output of the status should be similar to:: mon.mira094: running {"version":"0.61.5"} or when it fails:: mon.mira094: dead {"version":"0.61.5"} mon.mira094: not running {"version":"0.61.5"} """ stdout, stderr, _ = remoto.process.check( conn, args ) result_string = b' '.join(stdout) for run_check in [b': running', b' start/running']: if run_check in result_string: return True return False
[ "def", "is_running", "(", "conn", ",", "args", ")", ":", "stdout", ",", "stderr", ",", "_", "=", "remoto", ".", "process", ".", "check", "(", "conn", ",", "args", ")", "result_string", "=", "b' '", ".", "join", "(", "stdout", ")", "for", "run_check", "in", "[", "b': running'", ",", "b' start/running'", "]", ":", "if", "run_check", "in", "result_string", ":", "return", "True", "return", "False" ]
Run a command to check the status of a mon, return a boolean. We heavily depend on the format of the output, if that ever changes we need to modify this. Check daemon status for 3 times output of the status should be similar to:: mon.mira094: running {"version":"0.61.5"} or when it fails:: mon.mira094: dead {"version":"0.61.5"} mon.mira094: not running {"version":"0.61.5"}
[ "Run", "a", "command", "to", "check", "the", "status", "of", "a", "mon", "return", "a", "boolean", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mon.py#L572-L596