INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Construct a single page PDF from the provided page in memory
def _single_page_pdf(page): """Construct a single page PDF from the provided page in memory""" pdf = Pdf.new() pdf.pages.append(page) bio = BytesIO() pdf.save(bio) bio.seek(0) return bio.read()
Use mupdf draw to rasterize the PDF in the memory buffer
def _mudraw(buffer, fmt): """Use mupdf draw to rasterize the PDF in the memory buffer""" with NamedTemporaryFile(suffix='.pdf') as tmp_in: tmp_in.write(buffer) tmp_in.seek(0) tmp_in.flush() proc = run( ['mudraw', '-F', fmt, '-o', '-', tmp_in.name], stdout=PIPE, stder...
Concatenates a rotation matrix on this matrix
def rotated(self, angle_degrees_ccw): """Concatenates a rotation matrix on this matrix""" angle = angle_degrees_ccw / 180.0 * pi c, s = cos(angle), sin(angle) return self @ PdfMatrix((c, s, -s, c, 0, 0))
Return the 6-tuple (a,b,c,d,e,f) that describes this matrix
def shorthand(self): """Return the 6-tuple (a,b,c,d,e,f) that describes this matrix""" return (self.a, self.b, self.c, self.d, self.e, self.f)
Encode this matrix in binary suitable for including in a PDF
def encode(self): """Encode this matrix in binary suitable for including in a PDF""" return '{:.6f} {:.6f} {:.6f} {:.6f} {:.6f} {:.6f}'.format( self.a, self.b, self.c, self.d, self.e, self.f ).encode()
Parse a PDF content stream into a sequence of instructions. A PDF content stream is list of instructions that describe where to render the text and graphics in a PDF. This is the starting point for analyzing PDFs. If the input is a page and page.Contents is an array, then the content stream is aut...
def parse_content_stream(page_or_stream, operators=''): """ Parse a PDF content stream into a sequence of instructions. A PDF content stream is list of instructions that describe where to render the text and graphics in a PDF. This is the starting point for analyzing PDFs. If the input is a pa...
Groups Tokens that have beginning and end.
def _group_matching(tlist, cls): """Groups Tokens that have beginning and end.""" opens = [] tidx_offset = 0 for idx, token in enumerate(list(tlist)): tidx = idx - tidx_offset if token.is_whitespace: # ~50% of tokens will be whitespace. Will checking early # for ...
Group together Identifier and Asc/Desc token
def group_order(tlist): """Group together Identifier and Asc/Desc token""" tidx, token = tlist.token_next_by(t=T.Keyword.Order) while token: pidx, prev_ = tlist.token_prev(tidx) if imt(prev_, i=sql.Identifier, t=T.Number): tlist.group_tokens(sql.Identifier, pidx, tidx) ...
Groups together tokens that are joined by a middle token. i.e. x < y
def _group(tlist, cls, match, valid_prev=lambda t: True, valid_next=lambda t: True, post=None, extend=True, recurse=True ): """Groups together tokens that are joined by a middle token. i.e. x < y""" tidx_offset = 0 pidx, prev_ = None, None ...
Set the filter attributes to its default values
def _reset(self): """Set the filter attributes to its default values""" self._in_declare = False self._is_create = False self._begin_depth = 0 self.consume_ws = False self.tokens = [] self.level = 0
Get the new split level (increase, decrease or remain equal)
def _change_splitlevel(self, ttype, value): """Get the new split level (increase, decrease or remain equal)""" # parenthesis increase/decrease a level if ttype is T.Punctuation and value == '(': return 1 elif ttype is T.Punctuation and value == ')': return -1 ...
Process the stream
def process(self, stream): """Process the stream""" EOS_TTYPE = T.Whitespace, T.Comment.Single # Run over all stream tokens for ttype, value in stream: # Yield token if we finished a statement and there's no whitespaces # It will count newline token as a non whit...
Validates options.
def validate_options(options): """Validates options.""" kwcase = options.get('keyword_case') if kwcase not in [None, 'upper', 'lower', 'capitalize']: raise SQLParseError('Invalid value for keyword_case: ' '{0!r}'.format(kwcase)) idcase = options.get('identifier_case'...
Setup and return a filter stack. Args: stack: :class:`~sqlparse.filters.FilterStack` instance options: Dictionary with options validated by validate_options.
def build_filter_stack(stack, options): """Setup and return a filter stack. Args: stack: :class:`~sqlparse.filters.FilterStack` instance options: Dictionary with options validated by validate_options. """ # Token filter if options.get('keyword_case'): stack.preprocess.append( ...
Split a string on all unquoted newlines. Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite character is inside of a string.
def split_unquoted_newlines(stmt): """Split a string on all unquoted newlines. Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite character is inside of a string.""" text = text_type(stmt) lines = SPLIT_REGEX.split(text) outputlines = [''] for line in lines: if n...
Function decorator to help with recursion :param cls: Classes to not recurse over :return: function
def recurse(*cls): """Function decorator to help with recursion :param cls: Classes to not recurse over :return: function """ def wrap(f): def wrapped_f(tlist): for sgroup in tlist.get_sublists(): if not isinstance(sgroup, cls): wrapped_f(sgro...
Helper function to simplify comparisons Instance, Match and TokenType :param token: :param i: Class or Tuple/List of Classes :param m: Tuple of TokenType & Value. Can be list of Tuple for multiple :param t: TokenType or Tuple/List of TokenTypes :return: bool
def imt(token, i=None, m=None, t=None): """Helper function to simplify comparisons Instance, Match and TokenType :param token: :param i: Class or Tuple/List of Classes :param m: Tuple of TokenType & Value. Can be list of Tuple for multiple :param t: TokenType or Tuple/List of TokenTypes :return:...
Parses sql statements from file-like object. :param stream: A file-like object. :param encoding: The encoding of the stream contents (optional). :returns: A generator of :class:`~sqlparse.sql.Statement` instances.
def parsestream(stream, encoding=None): """Parses sql statements from file-like object. :param stream: A file-like object. :param encoding: The encoding of the stream contents (optional). :returns: A generator of :class:`~sqlparse.sql.Statement` instances. """ stack = engine.FilterStack() s...
Format *sql* according to *options*. Available options are documented in :ref:`formatting`. In addition to the formatting options this function accepts the keyword "encoding" which determines the encoding of the statement. :returns: The formatted SQL statement as string.
def format(sql, encoding=None, **options): """Format *sql* according to *options*. Available options are documented in :ref:`formatting`. In addition to the formatting options this function accepts the keyword "encoding" which determines the encoding of the statement. :returns: The formatted SQL ...
Split *sql* into single statements. :param sql: A string containing one or more SQL statements. :param encoding: The encoding of the statement (optional). :returns: A list of strings.
def split(sql, encoding=None): """Split *sql* into single statements. :param sql: A string containing one or more SQL statements. :param encoding: The encoding of the statement (optional). :returns: A list of strings. """ stack = engine.FilterStack() return [text_type(stmt).strip() for stmt...
Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined. Also preprocess the text, i.e. expand tabs and strip it if wanted and applies registered filters. Split ``tex...
def get_tokens(text, encoding=None): """ Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined. Also preprocess the text, i.e. expand tabs and strip it if wa...
Yields all tokens up to token but excluding current.
def _flatten_up_to_token(self, token): """Yields all tokens up to token but excluding current.""" if token.is_group: token = next(token.flatten()) for t in self._curr_stmt.flatten(): if t == token: break yield t
Returns the type of a statement. The returned value is a string holding an upper-cased reprint of the first DML or DDL keyword. If the first token in this group isn't a DML or DDL keyword "UNKNOWN" is returned. Whitespaces and comments at the beginning of the statement are igno...
def get_type(self): """Returns the type of a statement. The returned value is a string holding an upper-cased reprint of the first DML or DDL keyword. If the first token in this group isn't a DML or DDL keyword "UNKNOWN" is returned. Whitespaces and comments at the beginning of...
Return ``True`` if this identifier contains a wildcard.
def is_wildcard(self): """Return ``True`` if this identifier contains a wildcard.""" _, token = self.token_next_by(t=T.Wildcard) return token is not None
Returns the typecast or ``None`` of this object as a string.
def get_typecast(self): """Returns the typecast or ``None`` of this object as a string.""" midx, marker = self.token_next_by(m=(T.Punctuation, '::')) nidx, next_ = self.token_next(midx, skip_ws=False) return next_.value if next_ else None
Returns the ordering or ``None`` as uppercase string.
def get_ordering(self): """Returns the ordering or ``None`` as uppercase string.""" _, ordering = self.token_next_by(t=T.Keyword.Order) return ordering.normalized if ordering else None
Returns an iterator of index token lists
def get_array_indices(self): """Returns an iterator of index token lists""" for token in self.tokens: if isinstance(token, SquareBrackets): # Use [1:-1] index to discard the square brackets yield token.tokens[1:-1]
Returns the identifiers. Whitespaces and punctuations are not included in this generator.
def get_identifiers(self): """Returns the identifiers. Whitespaces and punctuations are not included in this generator. """ for token in self.tokens: if not (token.is_whitespace or token.match(T.Punctuation, ',')): yield token
Returns a list of 2-tuples (condition, value). If an ELSE exists condition is None.
def get_cases(self, skip_ws=False): """Returns a list of 2-tuples (condition, value). If an ELSE exists condition is None. """ CONDITION = 1 VALUE = 2 ret = [] mode = CONDITION for token in self.tokens: # Set mode from the current statement ...
Return a list of parameters.
def get_parameters(self): """Return a list of parameters.""" parenthesis = self.tokens[-1] for token in parenthesis.tokens: if isinstance(token, IdentifierList): return token.get_identifiers() elif imt(token, i=(Function, Identifier), t=T.Literal): ...
Turn all the output devices on.
def on(self): """ Turn all the output devices on. """ for device in self: if isinstance(device, (OutputDevice, CompositeOutputDevice)): device.on()
Turn all the output devices off.
def off(self): """ Turn all the output devices off. """ for device in self: if isinstance(device, (OutputDevice, CompositeOutputDevice)): device.off()
Toggle all the output devices. For each device, if it's on, turn it off; if it's off, turn it on.
def toggle(self): """ Toggle all the output devices. For each device, if it's on, turn it off; if it's off, turn it on. """ for device in self: if isinstance(device, (OutputDevice, CompositeOutputDevice)): device.toggle()
If no arguments are specified, turn all the LEDs on. If arguments are specified, they must be the indexes of the LEDs you wish to turn on. For example:: from gpiozero import LEDBoard leds = LEDBoard(2, 3, 4, 5) leds.on(0) # turn on the first LED (pin 2) ...
def on(self, *args): """ If no arguments are specified, turn all the LEDs on. If arguments are specified, they must be the indexes of the LEDs you wish to turn on. For example:: from gpiozero import LEDBoard leds = LEDBoard(2, 3, 4, 5) leds.on(0) ...
If no arguments are specified, turn all the LEDs off. If arguments are specified, they must be the indexes of the LEDs you wish to turn off. For example:: from gpiozero import LEDBoard leds = LEDBoard(2, 3, 4, 5) leds.on() # turn on all LEDs leds.of...
def off(self, *args): """ If no arguments are specified, turn all the LEDs off. If arguments are specified, they must be the indexes of the LEDs you wish to turn off. For example:: from gpiozero import LEDBoard leds = LEDBoard(2, 3, 4, 5) leds.on() ...
If no arguments are specified, toggle the state of all LEDs. If arguments are specified, they must be the indexes of the LEDs you wish to toggle. For example:: from gpiozero import LEDBoard leds = LEDBoard(2, 3, 4, 5) leds.toggle(0) # turn on the first LED (pin 2)...
def toggle(self, *args): """ If no arguments are specified, toggle the state of all LEDs. If arguments are specified, they must be the indexes of the LEDs you wish to toggle. For example:: from gpiozero import LEDBoard leds = LEDBoard(2, 3, 4, 5) led...
Make all LEDs fade in and out repeatedly. Note that this method will only work if the *pwm* parameter was :data:`True` at construction time. :param float fade_in_time: Number of seconds to spend fading in. Defaults to 1. :param float fade_out_time: Number of seconds to ...
def pulse(self, fade_in_time=1, fade_out_time=1, n=None, background=True): """ Make all LEDs fade in and out repeatedly. Note that this method will only work if the *pwm* parameter was :data:`True` at construction time. :param float fade_in_time: Number of seconds to spend f...
The value of the LED bar graph. When no LEDs are lit, the value is 0. When all LEDs are lit, the value is 1. Values between 0 and 1 light LEDs linearly from first to last. Values between 0 and -1 light LEDs linearly from last to first. To light a particular number of LEDs, simply divide...
def value(self): """ The value of the LED bar graph. When no LEDs are lit, the value is 0. When all LEDs are lit, the value is 1. Values between 0 and 1 light LEDs linearly from first to last. Values between 0 and -1 light LEDs linearly from last to first. To light a par...
The number of LEDs on the bar graph actually lit up. Note that just like :attr:`value`, this can be negative if the LEDs are lit from last to first.
def lit_count(self): """ The number of LEDs on the bar graph actually lit up. Note that just like :attr:`value`, this can be negative if the LEDs are lit from last to first. """ lit_value = self.value * len(self) if not isinstance(self[0], PWMLED): lit...
Drive the robot forward by running both motors forward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1. :param float curve_left: The amount to curve left while moving forwards, by driving t...
def forward(self, speed=1, **kwargs): """ Drive the robot forward by running both motors forward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1. :param float curve_left: Th...
Make the robot turn left by running the right motor forward and left motor backward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1.
def left(self, speed=1): """ Make the robot turn left by running the right motor forward and left motor backward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1. """ self...
Make the robot turn right by running the left motor forward and right motor backward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1.
def right(self, speed=1): """ Make the robot turn right by running the left motor forward and right motor backward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1. """ se...
Drive the robot forward by running both motors forward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1.
def forward(self, speed=1): """ Drive the robot forward by running both motors forward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1. """ self.left_motor.forward(speed) ...
Drive the robot backward by running both motors backward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1.
def backward(self, speed=1): """ Drive the robot backward by running both motors backward. :param float speed: Speed at which to drive the motors, as a value between 0 (stopped) and 1 (full speed). The default is 1. """ self.left_motor.backward(speed) ...
Reverse the robot's current motor directions. If the robot is currently running full speed forward, it will run full speed backward. If the robot is turning left at half-speed, it will turn right at half-speed. If the robot is currently stopped it will remain stopped.
def reverse(self): """ Reverse the robot's current motor directions. If the robot is currently running full speed forward, it will run full speed backward. If the robot is turning left at half-speed, it will turn right at half-speed. If the robot is currently stopped it will rema...
Called to indicate that the device reserves the right to use the specified *pins*. This should be done during device construction. If pins are reserved, you must ensure that the reservation is released by eventually called :meth:`release_pins`.
def reserve_pins(self, requester, *pins): """ Called to indicate that the device reserves the right to use the specified *pins*. This should be done during device construction. If pins are reserved, you must ensure that the reservation is released by eventually called :meth:`rel...
Releases the reservation of *reserver* against *pins*. This is typically called during :meth:`~gpiozero.Device.close` to clean up reservations taken during construction. Releasing a reservation that is not currently held will be silently ignored (to permit clean-up after failed / partia...
def release_pins(self, reserver, *pins): """ Releases the reservation of *reserver* against *pins*. This is typically called during :meth:`~gpiozero.Device.close` to clean up reservations taken during construction. Releasing a reservation that is not currently held will be silen...
The pin method for :class:`MockFactory` additionally takes a *pin_class* attribute which can be used to override the class' :attr:`pin_class` attribute. Any additional keyword arguments will be passed along to the pin constructor (useful with things like :class:`MockConnectedPin` which e...
def pin(self, spec, pin_class=None, **kwargs): """ The pin method for :class:`MockFactory` additionally takes a *pin_class* attribute which can be used to override the class' :attr:`pin_class` attribute. Any additional keyword arguments will be passed along to the pin constructor...
Returns a :class:`PiBoardInfo` instance containing information about a *revision* of the Raspberry Pi. :param str revision: The revision of the Pi to return information about. If this is omitted or :data:`None` (the default), then the library will attempt to determine the model of Pi it...
def pi_info(revision=None): """ Returns a :class:`PiBoardInfo` instance containing information about a *revision* of the Raspberry Pi. :param str revision: The revision of the Pi to return information about. If this is omitted or :data:`None` (the default), then the library will attempt...
Return the physical pins supporting the specified *function* as tuples of ``(header, pin_number)`` where *header* is a string specifying the header containing the *pin_number*. Note that the return value is a :class:`set` which is not indexable. Use :func:`physical_pin` if you are expect...
def physical_pins(self, function): """ Return the physical pins supporting the specified *function* as tuples of ``(header, pin_number)`` where *header* is a string specifying the header containing the *pin_number*. Note that the return value is a :class:`set` which is not indexa...
Return the physical pin supporting the specified *function*. If no pins support the desired *function*, this function raises :exc:`PinNoPins`. If multiple pins support the desired *function*, :exc:`PinMultiplePins` will be raised (use :func:`physical_pins` if you expect multiple pins in ...
def physical_pin(self, function): """ Return the physical pin supporting the specified *function*. If no pins support the desired *function*, this function raises :exc:`PinNoPins`. If multiple pins support the desired *function*, :exc:`PinMultiplePins` will be raised (use :func:`...
Returns a bool indicating whether a physical pull-up is attached to the pin supporting the specified *function*. Either :exc:`PinNoPins` or :exc:`PinMultiplePins` may be raised if the function is not associated with a single pin. :param str function: The pin function you wis...
def pulled_up(self, function): """ Returns a bool indicating whether a physical pull-up is attached to the pin supporting the specified *function*. Either :exc:`PinNoPins` or :exc:`PinMultiplePins` may be raised if the function is not associated with a single pin. :param...
Parses a pin *spec*, returning the equivalent Broadcom GPIO port number or raising a :exc:`ValueError` exception if the spec does not represent a GPIO port. The *spec* may be given in any of the following forms: * An integer, which will be accepted as a GPIO number * 'GPIOn' wh...
def to_gpio(self, spec): """ Parses a pin *spec*, returning the equivalent Broadcom GPIO port number or raising a :exc:`ValueError` exception if the spec does not represent a GPIO port. The *spec* may be given in any of the following forms: * An integer, which will be a...
Returns an SPI interface, for the specified SPI *port* and *device*, or for the specified pins (*clock_pin*, *mosi_pin*, *miso_pin*, and *select_pin*). Only one of the schemes can be used; attempting to mix *port* and *device* with pin numbers will raise :exc:`~gpiozero.SPIBadArgs`. ...
def spi(self, **spi_args): """ Returns an SPI interface, for the specified SPI *port* and *device*, or for the specified pins (*clock_pin*, *mosi_pin*, *miso_pin*, and *select_pin*). Only one of the schemes can be used; attempting to mix *port* and *device* with pin numbers will...
Given a set of keyword arguments, splits it into those relevant to SPI implementations and all the rest. SPI arguments are augmented with defaults and converted into the pin format (from the port/device format) if necessary. Returns a tuple of ``(spi_args, other_args)``.
def _extract_spi_args(self, **kwargs): """ Given a set of keyword arguments, splits it into those relevant to SPI implementations and all the rest. SPI arguments are augmented with defaults and converted into the pin format (from the port/device format) if necessary. Ret...
Called to fire the :attr:`when_changed` event handler; override this in descendents if additional (currently redundant) parameters need to be passed.
def _call_when_changed(self, ticks, state): """ Called to fire the :attr:`when_changed` event handler; override this in descendents if additional (currently redundant) parameters need to be passed. """ method = self._when_changed() if method is None: s...
Given a bit-pattern expressed an integer number, return a sequence of the individual words that make up the pattern. The number of bits per word will be obtained from the internal SPI interface.
def _int_to_words(self, pattern): """ Given a bit-pattern expressed an integer number, return a sequence of the individual words that make up the pattern. The number of bits per word will be obtained from the internal SPI interface. """ try: bits_required = in...
Given a sequence of words which each fit in the internal SPI interface's number of bits per word, returns the value obtained by concatenating each word into a single bit-string. If *expected_bits* is specified, it limits the size of the output to the specified number of bits (by masking...
def _words_to_int(self, words, expected_bits=None): """ Given a sequence of words which each fit in the internal SPI interface's number of bits per word, returns the value obtained by concatenating each word into a single bit-string. If *expected_bits* is specified, it limits th...
Writes data (a list of integer words where each word is assumed to have :attr:`bits_per_word` bits or less) to the SPI interface, and reads an equivalent number of words, returning them as a list of integers.
def transfer(self, data, clock_phase=False, lsb_first=False, bits_per_word=8): """ Writes data (a list of integer words where each word is assumed to have :attr:`bits_per_word` bits or less) to the SPI interface, and reads an equivalent number of words, returning them as a list of intege...
Returns :data:`True` if the host returned a single ping, and :data:`False` otherwise.
def value(self): """ Returns :data:`True` if the host returned a single ping, and :data:`False` otherwise. """ # XXX This is doing a DNS lookup every time it's queried; should we # call gethostbyname in the constructor and ping that instead (good # for consistency...
Returns the current CPU temperature in degrees celsius.
def temperature(self): """ Returns the current CPU temperature in degrees celsius. """ with io.open(self.sensor_file, 'r') as f: return float(f.readline().strip()) / 1000
Returns the current CPU temperature as a value between 0.0 (representing the *min_temp* value) and 1.0 (representing the *max_temp* value). These default to 0.0 and 100.0 respectively, hence :attr:`value` is :attr:`temperature` divided by 100 by default.
def value(self): """ Returns the current CPU temperature as a value between 0.0 (representing the *min_temp* value) and 1.0 (representing the *max_temp* value). These default to 0.0 and 100.0 respectively, hence :attr:`value` is :attr:`temperature` divided by 100 by default. ...
Returns the current load average.
def load_average(self): """ Returns the current load average. """ with io.open(self.load_average_file, 'r') as f: file_columns = f.readline().strip().split() return float(file_columns[self._load_average_file_column])
Returns the current load average as a value between 0.0 (representing the *min_load_average* value) and 1.0 (representing the *max_load_average* value). These default to 0.0 and 1.0 respectively.
def value(self): """ Returns the current load average as a value between 0.0 (representing the *min_load_average* value) and 1.0 (representing the *max_load_average* value). These default to 0.0 and 1.0 respectively. """ load_average_range = self.max_load_average - self.m...
Returns :data:`True` when the system clock reads between :attr:`start_time` and :attr:`end_time`, and :data:`False` otherwise. If :attr:`start_time` is greater than :attr:`end_time` (indicating a period that crosses midnight), then this returns :data:`True` when the current time is great...
def value(self): """ Returns :data:`True` when the system clock reads between :attr:`start_time` and :attr:`end_time`, and :data:`False` otherwise. If :attr:`start_time` is greater than :attr:`end_time` (indicating a period that crosses midnight), then this returns :data:`True` w...
Returns the current disk usage as a value between 0.0 and 1.0 by dividing :attr:`usage` by 100.
def value(self): """ Returns the current disk usage as a value between 0.0 and 1.0 by dividing :attr:`usage` by 100. """ # This slightly convoluted calculation is equivalent to df's "Use%"; # it calculates the percentage of FS usage as a proportion of the # space ...
Returns the inversion of the supplied values (*input_min* becomes *input_max*, *input_max* becomes *input_min*, `input_min + 0.1` becomes `input_max - 0.1`, etc.). All items in *values* are assumed to be between *input_min* and *input_max* (which default to 0 and 1 respectively), and the output will be ...
def inverted(values, input_min=0, input_max=1): """ Returns the inversion of the supplied values (*input_min* becomes *input_max*, *input_max* becomes *input_min*, `input_min + 0.1` becomes `input_max - 0.1`, etc.). All items in *values* are assumed to be between *input_min* and *input_max* (which d...
Returns *values* scaled from *output_min* to *output_max*, assuming that all items in *values* lie between *input_min* and *input_max* (which default to 0 and 1 respectively). For example, to control the direction of a motor (which is represented as a value between -1 and 1) using a potentiometer (which...
def scaled(values, output_min, output_max, input_min=0, input_max=1): """ Returns *values* scaled from *output_min* to *output_max*, assuming that all items in *values* lie between *input_min* and *input_max* (which default to 0 and 1 respectively). For example, to control the direction of a motor (...
Returns *values* clamped from *output_min* to *output_max*, i.e. any items less than *output_min* will be returned as *output_min* and any items larger than *output_max* will be returned as *output_max* (these default to 0 and 1 respectively). For example:: from gpiozero import PWMLED, MCP3008 ...
def clamped(values, output_min=0, output_max=1): """ Returns *values* clamped from *output_min* to *output_max*, i.e. any items less than *output_min* will be returned as *output_min* and any items larger than *output_max* will be returned as *output_max* (these default to 0 and 1 respectively). For...
Returns *values* quantized to *steps* increments. All items in *values* are assumed to be between *input_min* and *input_max* (which default to 0 and 1 respectively), and the output will be in the same range. For example, to quantize values between 0 and 1 to 5 "steps" (0.0, 0.25, 0.5, 0.75, 1.0):: ...
def quantized(values, steps, input_min=0, input_max=1): """ Returns *values* quantized to *steps* increments. All items in *values* are assumed to be between *input_min* and *input_max* (which default to 0 and 1 respectively), and the output will be in the same range. For example, to quantize value...
Returns True for each item in *values* between *min_value* and *max_value*, and False otherwise. *hysteresis* can optionally be used to add `hysteresis`_ which prevents the output value rapidly flipping when the input value is fluctuating near the *min_value* or *max_value* thresholds. For example, to l...
def booleanized(values, min_value, max_value, hysteresis=0): """ Returns True for each item in *values* between *min_value* and *max_value*, and False otherwise. *hysteresis* can optionally be used to add `hysteresis`_ which prevents the output value rapidly flipping when the input value is fluctuat...
Returns the `logical conjunction`_ of all supplied values (the result is only :data:`True` if and only if all input values are simultaneously :data:`True`). One or more *values* can be specified. For example, to light an :class:`~gpiozero.LED` only when *both* buttons are pressed:: from gpiozero im...
def all_values(*values): """ Returns the `logical conjunction`_ of all supplied values (the result is only :data:`True` if and only if all input values are simultaneously :data:`True`). One or more *values* can be specified. For example, to light an :class:`~gpiozero.LED` only when *both* buttons ar...
Returns the `logical disjunction`_ of all supplied values (the result is :data:`True` if any of the input values are currently :data:`True`). One or more *values* can be specified. For example, to light an :class:`~gpiozero.LED` when *any* button is pressed:: from gpiozero import LED, Button ...
def any_values(*values): """ Returns the `logical disjunction`_ of all supplied values (the result is :data:`True` if any of the input values are currently :data:`True`). One or more *values* can be specified. For example, to light an :class:`~gpiozero.LED` when *any* button is pressed:: fr...
Returns the mean of all supplied values. One or more *values* can be specified. For example, to light a :class:`~gpiozero.PWMLED` as the average of several potentiometers connected to an :class:`~gpiozero.MCP3008` ADC:: from gpiozero import MCP3008, PWMLED from gpiozero.tools import averaged ...
def averaged(*values): """ Returns the mean of all supplied values. One or more *values* can be specified. For example, to light a :class:`~gpiozero.PWMLED` as the average of several potentiometers connected to an :class:`~gpiozero.MCP3008` ADC:: from gpiozero import MCP3008, PWMLED fro...
Returns the sum of all supplied values. One or more *values* can be specified. For example, to light a :class:`~gpiozero.PWMLED` as the (scaled) sum of several potentiometers connected to an :class:`~gpiozero.MCP3008` ADC:: from gpiozero import MCP3008, PWMLED from gpiozero.tools import sum...
def summed(*values): """ Returns the sum of all supplied values. One or more *values* can be specified. For example, to light a :class:`~gpiozero.PWMLED` as the (scaled) sum of several potentiometers connected to an :class:`~gpiozero.MCP3008` ADC:: from gpiozero import MCP3008, PWMLED ...
Returns the product of all supplied values. One or more *values* can be specified. For example, to light a :class:`~gpiozero.PWMLED` as the product (i.e. multiplication) of several potentiometers connected to an :class:`~gpiozero.MCP3008` ADC:: from gpiozero import MCP3008, PWMLED from ...
def multiplied(*values): """ Returns the product of all supplied values. One or more *values* can be specified. For example, to light a :class:`~gpiozero.PWMLED` as the product (i.e. multiplication) of several potentiometers connected to an :class:`~gpiozero.MCP3008` ADC:: from gpiozero...
Queues up readings from *values* (the number of readings queued is determined by *qsize*) and begins yielding values only when the queue is full. For example, to "cascade" values along a sequence of LEDs:: from gpiozero import LEDBoard, Button from gpiozero.tools import queued from sign...
def queued(values, qsize): """ Queues up readings from *values* (the number of readings queued is determined by *qsize*) and begins yielding values only when the queue is full. For example, to "cascade" values along a sequence of LEDs:: from gpiozero import LEDBoard, Button from gpiozer...
Queues up readings from *values* (the number of readings queued is determined by *qsize*) and begins yielding the *average* of the last *qsize* values when the queue is full. The larger the *qsize*, the more the values are smoothed. For example, to smooth the analog values read from an ADC:: fr...
def smoothed(values, qsize, average=mean): """ Queues up readings from *values* (the number of readings queued is determined by *qsize*) and begins yielding the *average* of the last *qsize* values when the queue is full. The larger the *qsize*, the more the values are smoothed. For example, to smoo...
Waits for *delay* seconds before returning each item from *values*.
def pre_delayed(values, delay): """ Waits for *delay* seconds before returning each item from *values*. """ values = _normalize(values) if delay < 0: raise ValueError("delay must be 0 or larger") for v in values: sleep(delay) yield v
Waits for *delay* seconds after returning each item from *values*.
def post_delayed(values, delay): """ Waits for *delay* seconds after returning each item from *values*. """ values = _normalize(values) if delay < 0: raise ValueError("delay must be 0 or larger") for v in values: yield v sleep(delay)
Blocks the first *block* items from *values*, repeating the block after every *repeat_after* items, if *repeat_after* is non-zero. For example, to discard the first 50 values read from an ADC:: from gpiozero import MCP3008 from gpiozero.tools import pre_periodic_filtered adc = MCP3008(...
def pre_periodic_filtered(values, block, repeat_after): """ Blocks the first *block* items from *values*, repeating the block after every *repeat_after* items, if *repeat_after* is non-zero. For example, to discard the first 50 values read from an ADC:: from gpiozero import MCP3008 from...
Provides an infinite source of values representing a sine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWMLED from gpiozero.tools import sin_values, scaled, inverted ...
def sin_values(period=360): """ Provides an infinite source of values representing a sine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWMLED from gpiozero.tools...
After every *repeat_after* items, blocks the next *block* items from *values*. Note that unlike :func:`pre_periodic_filtered`, *repeat_after* can't be 0. For example, to block every tenth item read from an ADC:: from gpiozero import MCP3008 from gpiozero.tools import post_periodic_filtered ...
def post_periodic_filtered(values, repeat_after, block): """ After every *repeat_after* items, blocks the next *block* items from *values*. Note that unlike :func:`pre_periodic_filtered`, *repeat_after* can't be 0. For example, to block every tenth item read from an ADC:: from gpiozero import M...
Provides an infinite source of values representing a cosine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWMLED from gpiozero.tools import cos_values, scaled, inverted ...
def cos_values(period=360): """ Provides an infinite source of values representing a cosine wave (from -1 to +1) which repeats every *period* values. For example, to produce a "siren" effect with a couple of LEDs that repeats once a second:: from gpiozero import PWMLED from gpiozero.too...
Provides an infinite source of values representing a triangle wave (from 0 to 1 and back again) which repeats every *period* values. For example, to pulse an LED once a second:: from gpiozero import PWMLED from gpiozero.tools import ramping_values from signal import pause red =...
def ramping_values(period=360): """ Provides an infinite source of values representing a triangle wave (from 0 to 1 and back again) which repeats every *period* values. For example, to pulse an LED once a second:: from gpiozero import PWMLED from gpiozero.tools import ramping_values ...
Make the device turn on and off repeatedly. :param float on_time: Number of seconds on. Defaults to 1 second. :param float off_time: Number of seconds off. Defaults to 1 second. :param float fade_in_time: Number of seconds to spend fading in. Defaults to 0....
def blink( self, on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, n=None, background=True): """ Make the device turn on and off repeatedly. :param float on_time: Number of seconds on. Defaults to 1 second. :param float off_time: Nu...
Play the given *tone*. This can either be an instance of :class:`~gpiozero.tones.Tone` or can be anything that could be used to construct an instance of :class:`~gpiozero.tones.Tone`. For example:: >>> from gpiozero import TonalBuzzer >>> from gpiozero.tones import Tone...
def play(self, tone): """ Play the given *tone*. This can either be an instance of :class:`~gpiozero.tones.Tone` or can be anything that could be used to construct an instance of :class:`~gpiozero.tones.Tone`. For example:: >>> from gpiozero import TonalBuzzer ...
Reverse the state of the device. If it's on, turn it off; if it's off, turn it on.
def toggle(self): """ Reverse the state of the device. If it's on, turn it off; if it's off, turn it on. """ with self._lock: if self.is_active: self.off() else: self.on()
Returns the :class:`~gpiozero.tones.Tone` that the buzzer is currently playing, or :data:`None` if the buzzer is silent. This property can also be set to play the specified tone.
def tone(self): """ Returns the :class:`~gpiozero.tones.Tone` that the buzzer is currently playing, or :data:`None` if the buzzer is silent. This property can also be set to play the specified tone. """ if self.pwm_device.pin.frequency is None: return None ...
Represents the state of the buzzer as a value between -1 (representing the minimum tone) and 1 (representing the maximum tone). This can also be the special value :data:`None` indicating that the buzzer is currently silent.
def value(self): """ Represents the state of the buzzer as a value between -1 (representing the minimum tone) and 1 (representing the maximum tone). This can also be the special value :data:`None` indicating that the buzzer is currently silent. """ if self.pwm_dev...
Toggle the state of the device. If the device is currently off (:attr:`value` is ``(0, 0, 0)``), this changes it to "fully" on (:attr:`value` is ``(1, 1, 1)``). If the device has a specific color, this method inverts the color.
def toggle(self): """ Toggle the state of the device. If the device is currently off (:attr:`value` is ``(0, 0, 0)``), this changes it to "fully" on (:attr:`value` is ``(1, 1, 1)``). If the device has a specific color, this method inverts the color. """ r, g, b =...
Make the device turn on and off repeatedly. :param float on_time: Number of seconds on. Defaults to 1 second. :param float off_time: Number of seconds off. Defaults to 1 second. :param float fade_in_time: Number of seconds to spend fading in. Defaults to 0....
def blink( self, on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, on_color=(1, 1, 1), off_color=(0, 0, 0), n=None, background=True): """ Make the device turn on and off repeatedly. :param float on_time: Number of seconds on. Defaults to 1 second. ...
Drive the motor forwards. :param float speed: The speed at which the motor should turn. Can be any value between 0 (stopped) and the default 1 (maximum speed) if *pwm* was :data:`True` when the class was constructed (and only 0 or 1 if not).
def forward(self, speed=1): """ Drive the motor forwards. :param float speed: The speed at which the motor should turn. Can be any value between 0 (stopped) and the default 1 (maximum speed) if *pwm* was :data:`True` when the class was constructed (and only 0...
Represents the speed of the motor as a floating point value between -1 (full speed backward) and 1 (full speed forward).
def value(self): """ Represents the speed of the motor as a floating point value between -1 (full speed backward) and 1 (full speed forward). """ return ( -self.enable_device.value if self.phase_device.is_active else self.enable_device.value ...
Drive the motor forwards. :param float speed: The speed at which the motor should turn. Can be any value between 0 (stopped) and the default 1 (maximum speed).
def forward(self, speed=1): """ Drive the motor forwards. :param float speed: The speed at which the motor should turn. Can be any value between 0 (stopped) and the default 1 (maximum speed). """ if isinstance(self.enable_device, DigitalOutputDevice): ...
Drive the motor backwards. :param float speed: The speed at which the motor should turn. Can be any value between 0 (stopped) and the default 1 (maximum speed).
def backward(self, speed=1): """ Drive the motor backwards. :param float speed: The speed at which the motor should turn. Can be any value between 0 (stopped) and the default 1 (maximum speed). """ if isinstance(self.enable_device, DigitalOutputDevice): ...
Returns the current pulse width controlling the servo.
def pulse_width(self): """ Returns the current pulse width controlling the servo. """ if self.pwm_device.pin.frequency is None: return None else: return self.pwm_device.pin.state * self.frame_width
The position of the servo as an angle measured in degrees. This will only be accurate if :attr:`min_angle` and :attr:`max_angle` have been set appropriately in the constructor. This can also be the special value :data:`None` indicating that the servo is currently "uncontrolled", i.e. th...
def angle(self): """ The position of the servo as an angle measured in degrees. This will only be accurate if :attr:`min_angle` and :attr:`max_angle` have been set appropriately in the constructor. This can also be the special value :data:`None` indicating that the servo...
Construct a :class:`Tone` from a MIDI note, which must be an integer in the range 0 to 127. For reference, A4 (`concert A`_ typically used for tuning) is MIDI note #69. .. _concert A: https://en.wikipedia.org/wiki/Concert_pitch
def from_midi(cls, midi_note): """ Construct a :class:`Tone` from a MIDI note, which must be an integer in the range 0 to 127. For reference, A4 (`concert A`_ typically used for tuning) is MIDI note #69. .. _concert A: https://en.wikipedia.org/wiki/Concert_pitch """ ...
Construct a :class:`Tone` from a musical note which must consist of a capital letter A through G, followed by an optional semi-tone modifier ("b" for flat, "#" for sharp, or their Unicode equivalents), followed by an octave number (0 through 9). For example `concert A`_, the typical tun...
def from_note(cls, note): """ Construct a :class:`Tone` from a musical note which must consist of a capital letter A through G, followed by an optional semi-tone modifier ("b" for flat, "#" for sharp, or their Unicode equivalents), followed by an octave number (0 through 9). ...