text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, sequence): """ Update the set with the given iterable sequence, then return the index of the last element inserted. Example: 4 OrderedSet([1, 2, 3, 5, 4]) """
item_index = None try: for item in sequence: item_index = self.add(item) except TypeError: raise ValueError( "Argument needs to be an iterable, got %s" % type(sequence) ) return item_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop(self): """ Remove and return the last element from the set. Raises KeyError if the set is empty. Example: 3 """
if not self.items: raise KeyError("Set is empty") elem = self.items[-1] del self.items[-1] del self.map[elem] return elem
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def union(self, *sets): """ Combines all unique items. Each items order is defined by its first appearance. Example: OrderedSet([3, 1, 4, 5, 2, 0]) OrderedSet([3, 1, 4, 5, 2, 0, 8, 9]) OrderedSet([3, 1, 4, 5, 2, 0, 10]) """
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet containers = map(list, it.chain([self], sets)) items = it.chain.from_iterable(containers) return cls(items)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersection(self, *sets): """ Returns elements in common between all sets. Order is defined only by the first set. Example: OrderedSet([1, 2, 3]) OrderedSet([2]) OrderedSet([1, 2, 3]) """
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet if sets: common = set.intersection(*map(set, sets)) items = (item for item in self if item in common) else: items = self return cls(items)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def difference(self, *sets): """ Returns all elements that are in this set but not the others. Example: OrderedSet([1, 3]) OrderedSet([1]) OrderedSet([1, 3]) OrderedSet([1, 2, 3]) """
cls = self.__class__ if sets: other = set.union(*map(set, sets)) items = (item for item in self if item not in other) else: items = self return cls(items)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def issubset(self, other): """ Report whether another set contains this set. Example: False True False """
if len(self) > len(other): # Fast check for obvious cases return False return all(item in other for item in self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def issuperset(self, other): """ Report whether this set contains another set. Example: False True False """
if len(self) < len(other): # Fast check for obvious cases return False return all(item in self for item in other)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symmetric_difference(self, other): """ Return the symmetric difference of two OrderedSets as a new set. That is, the new set will contain all elements that are in exactly one of the sets. Their order will be preserved, with elements from `self` preceding elements from `other`. Example: OrderedSet([4, 5, 9, 2]) """
cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet diff1 = cls(self).difference(other) diff2 = cls(other).difference(self) return diff1.union(diff2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_items(self, items): """ Replace the 'items' list of this OrderedSet with a new one, updating self.map accordingly. """
self.items = items self.map = {item: idx for (idx, item) in enumerate(items)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def difference_update(self, *sets): """ Update this OrderedSet to remove items from one or more other sets. Example: OrderedSet([1, 3]) OrderedSet([3, 5]) """
items_to_remove = set() for other in sets: items_to_remove |= set(other) self._update_items([item for item in self.items if item not in items_to_remove])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersection_update(self, other): """ Update this OrderedSet to keep only items in another set, preserving their order in this set. Example: OrderedSet([1, 3, 7]) """
other = set(other) self._update_items([item for item in self.items if item in other])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symmetric_difference_update(self, other): """ Update this OrderedSet to remove items from another set, then add items from the other set that were not present in this set. Example: OrderedSet([4, 5, 9, 2]) """
items_to_add = [item for item in other if item not in self] items_to_remove = set(other) self._update_items( [item for item in self.items if item not in items_to_remove] + items_to_add )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_response(self): """Raises an exception if there was an error. Otherwise, do nothing. Clients should handle these errors, since these require custom handling to properly resolve. """
if self.is_success(): return # Handle the error if we have any information if self.details: error = self.details.get('error', None) if error == PushResponse.ERROR_DEVICE_NOT_REGISTERED: raise DeviceNotRegisteredError(self) elif error == PushResponse.ERROR_MESSAGE_TOO_BIG: raise MessageTooBigError(self) elif error == PushResponse.ERROR_MESSAGE_RATE_EXCEEDED: raise MessageRateExceededError(self) # No known error information, so let's raise a generic error. raise PushResponseError(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_exponent_push_token(cls, token): """Returns `True` if the token is an Exponent push token"""
import six return ( isinstance(token, six.string_types) and token.startswith('ExponentPushToken'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _publish_internal(self, push_messages): """Send push notifications The server will validate any type of syntax errors and the client will raise the proper exceptions for the user to handle. Each notification is of the form: { 'to': 'ExponentPushToken[xxx]', 'body': 'This text gets display in the notification', 'badge': 1, 'data': {'any': 'json object'}, } Args: push_messages: An array of PushMessage objects. """
# Delayed import because this file is immediately read on install, and # the requests library may not be installed yet. import requests response = requests.post( self.host + self.api_url + '/push/send', data=json.dumps([pm.get_payload() for pm in push_messages]), headers={ 'accept': 'application/json', 'accept-encoding': 'gzip, deflate', 'content-type': 'application/json', } ) # Let's validate the response format first. try: response_data = response.json() except ValueError: # The response isn't json. First, let's attempt to raise a normal # http error. If it's a 200, then we'll raise our own error. response.raise_for_status() raise PushServerError('Invalid server response', response) # If there are errors with the entire request, raise an error now. if 'errors' in response_data: raise PushServerError( 'Request failed', response, response_data=response_data, errors=response_data['errors']) # We expect the response to have a 'data' field with the responses. if 'data' not in response_data: raise PushServerError( 'Invalid server response', response, response_data=response_data) # Use the requests library's built-in exceptions for any remaining 4xx # and 5xx errors. response.raise_for_status() # Sanity check the response if len(push_messages) != len(response_data['data']): raise PushServerError( ('Mismatched response length. Expected %d %s but only ' 'received %d' % ( len(push_messages), 'receipt' if len(push_messages) == 1 else 'receipts', len(response_data['data']))), response, response_data=response_data) # At this point, we know it's a 200 and the response format is correct. # Now let's parse the responses per push notification. receipts = [] for i, receipt in enumerate(response_data['data']): receipts.append(PushResponse( push_message=push_messages[i], # If there is no status, assume error. status=receipt.get('status', PushResponse.ERROR_STATUS), message=receipt.get('message', ''), details=receipt.get('details', None))) return receipts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dict_from_buffer(buf, keys=['DISTNAME', 'MAJOR', 'MINOR', 'PATCHLEVEL', 'PYTHON', 'MIN_PYTHON_MAJOR', 'MIN_PYTHON_MINOR', 'MIN_NUMPY_MAJOR', 'MIN_NUMPY_MINOR']): """ Parses a string buffer for key-val pairs for the supplied keys. Returns: Python dictionary with all the keys (all keys in buffer if None is passed for keys) with the values being a list corresponding to each key. Note: Return dict will contain all keys supplied (if not None). If any key was not found in the buffer, then the value for that key will be [] such that dict[key] does not produce a KeyError. Slightly modified from: "http://stackoverflow.com/questions/5323703/regex-how-to-"\ "match-sequence-of-key-value-pairs-at-end-of-string """
pairs = dict() if keys is None: keys = "\S+" regex = re.compile(r''' \n # all key-value pairs are on separate lines \s* # there might be some leading spaces ( # start group to return (?:{0}\s*) # placeholder for tags to detect '\S+' == all \s*:*=\s* # optional spaces, optional colon, = , optional spaces .* # the value ) # end group to return '''.format(keys), re.VERBOSE) validate = False else: keys = [k.strip() for k in keys] regex = re.compile(r''' \n # all key-value pairs are on separate lines \s* # there might be some leading spaces ( # start group to return (?:{0}\s*) # placeholder for tags to detect '\S+' == all \s*:*=\s* # optional spaces, optional colon, = , optional spaces .* # the value ) # end group to return '''.format('|'.join(keys)), re.VERBOSE) validate = True for k in keys: pairs[k] = [] matches = regex.findall(buf) for match in matches: key, val = match.split('=', 1) # remove colon and leading/trailing whitespace from key key = (strip_line(key, ':')).strip() # remove newline and leading/trailing whitespace from value val = (strip_line(val)).strip() if validate and key not in keys: msg = "regex produced incorrect match. regex pattern = {0} "\ "claims key = [{1}] while original set of search keys "\ "= {2}".format(regex.pattern, key, '|'.join(keys)) raise AssertionError(msg) pairs.setdefault(key, []).append(val) return pairs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def replace_first_key_in_makefile(buf, key, replacement, outfile=None): ''' Replaces first line in 'buf' matching 'key' with 'replacement'. Optionally, writes out this new buffer into 'outfile'. Returns: Buffer after replacement has been done ''' regexp = re.compile(r''' \n\s* # there might be some leading spaces ( # start group to return (?:{0}\s*) # placeholder for tags to detect '\S+' == all \s*:*=\s* # optional spaces, optional colon, = , optional spaces .* # the value ) # end group to return '''.format(key), re.VERBOSE) matches = regexp.findall(buf) if matches is None: msg = "Could not find key = {0} in the provided buffer. "\ "Pattern used = {1}".format(key, regexp.pattern) raise ValueError(msg) # Only replace the first occurence newbuf = regexp.sub(replacement, buf, count=1) if outfile is not None: write_text_file(outfile, newbuf) return newbuf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def settings_to_cmd_args(settings_dict): """ Copied from django 1.8 MySQL backend DatabaseClient - where the runshell commandline creation has been extracted and made callable like so. """
args = ['mysql'] db = settings_dict['OPTIONS'].get('db', settings_dict['NAME']) user = settings_dict['OPTIONS'].get('user', settings_dict['USER']) passwd = settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD']) host = settings_dict['OPTIONS'].get('host', settings_dict['HOST']) port = settings_dict['OPTIONS'].get('port', settings_dict['PORT']) cert = settings_dict['OPTIONS'].get('ssl', {}).get('ca') defaults_file = settings_dict['OPTIONS'].get('read_default_file') # Seems to be no good way to set sql_mode with CLI. if defaults_file: args += ["--defaults-file=%s" % defaults_file] if user: args += ["--user=%s" % user] if passwd: args += ["--password=%s" % passwd] if host: if '/' in host: args += ["--socket=%s" % host] else: args += ["--host=%s" % host] if port: args += ["--port=%s" % port] if cert: args += ["--ssl-ca=%s" % cert] if db: args += [db] return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_sql(sql, add_comments, add_hints, add_index_hints): """ Parse the start of the SQL, injecting each string in add_comments in individual SQL comments after the first keyword, and adding the named SELECT hints from add_hints, taking the latest in the list in cases of multiple mutually exclusive hints being given """
match = query_start_re.match(sql) if not match: # We don't understand what kind of query this is, don't rewrite it return sql tokens = [match.group('keyword')] comments = match.group('comments').strip() if comments: tokens.append(comments) # Inject comments after all existing comments for comment in add_comments: tokens.append('/*{}*/'.format(comment)) # Don't bother with SELECT rewrite rules on non-SELECT queries if tokens[0] == "SELECT": for group_name, hint_set in SELECT_HINTS.items(): try: # Take the last hint we were told to add from this hint_set to_add = [hint for hint in add_hints if hint in hint_set][-1] tokens.append(to_add) except IndexError: # We weren't told to add any, so just add any hint from this # set that was already there existing = match.group(group_name) if existing is not None: tokens.append(existing.rstrip()) # Maybe rewrite the remainder of the statement for index hints remainder = sql[match.end():] if tokens[0] == "SELECT" and add_index_hints: for index_hint in add_index_hints: remainder = modify_sql_index_hints(remainder, *index_hint) # Join everything tokens.append(remainder) return ' '.join(tokens)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_key(self, key): """ Django normally warns about maximum key length, but we error on it. """
if len(key) > 250: raise ValueError( "Cache key is longer than the maxmimum 250 characters: {}" .format(key), ) return super(MySQLCache, self).validate_key(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, value, value_type): """ Take a value blob and its value_type one-char code and convert it back to a python object """
if value_type == 'i': return int(value) if value_type == 'z': value = zlib.decompress(value) value_type = 'p' if value_type == 'p': return pickle.loads(force_bytes(value)) raise ValueError( "Unknown value_type '{}' read from the cache table." .format(value_type), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_simple_query(cls, query): """ Inspect the internals of the Query and say if we think its WHERE clause can be used in a HANDLER statement """
return ( not query.low_mark and not query.high_mark and not query.select and not query.group_by and not query.distinct and not query.order_by and len(query.alias_map) <= 1 )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def animate(self, seq_name): """ Returns a generator which "executes" an animation sequence for the given ``seq_name``, inasmuch as the next frame for the given animation is yielded when requested. :param seq_name: The name of a previously defined animation sequence. :type seq_name: str :returns: A generator that yields all frames from the animation sequence. :raises AttributeError: If the ``seq_name`` is unknown. """
while True: index = 0 anim = getattr(self.animations, seq_name) speed = anim.speed if hasattr(anim, "speed") else 1 num_frames = len(anim.frames) while index < num_frames: frame = anim.frames[int(index)] index += speed if isinstance(frame, int): yield self[frame] else: for subseq_frame in self.animate(frame): yield subseq_frame if not hasattr(anim, "next"): break seq_name = anim.next
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def effective_FPS(self): """ Calculates the effective frames-per-second - this should largely correlate to the desired FPS supplied in the constructor, but no guarantees are given. :returns: The effective frame rate. :rtype: float """
if self.start_time is None: self.start_time = 0 elapsed = monotonic() - self.start_time return self.called / elapsed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _crop_box(self, size): """ Helper that calculates the crop box for the offset within the image. :param size: The width and height of the image composition. :type size: tuple :returns: The bounding box of the image, given ``size``. :rtype: tuple """
(left, top) = self.offset right = left + min(size[0], self.width) bottom = top + min(size[1], self.height) return (left, top, right, bottom)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self): """ Clears the composition and renders all the images taking into account their position and offset. """
self._clear() for img in self.composed_images: self._background_image.paste(img.image(self._device.size), img.position) self._background_image.crop(box=self._device.bounding_box)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clear(self): """ Helper that clears the composition. """
draw = ImageDraw.Draw(self._background_image) draw.rectangle(self._device.bounding_box, fill="black") del draw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inflate_bbox(self): """ Realign the left and right edges of the bounding box such that they are inflated to align modulo 4. This method is optional, and used mainly to accommodate devices with COM/SEG GDDRAM structures that store pixels in 4-bit nibbles. """
left, top, right, bottom = self.bounding_box self.bounding_box = ( left & 0xFFFC, top, right if right % 4 == 0 else (right & 0xFFFC) + 0x04, bottom) return self.bounding_box
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def println(self, text=""): """ Prints the supplied text to the device, scrolling where necessary. The text is always followed by a newline. :param text: The text to print. :type text: str """
if self.word_wrap: # find directives in complete text directives = ansi_color.find_directives(text, self) # strip ansi from text clean_text = ansi_color.strip_ansi_codes(text) # wrap clean text clean_lines = self.tw.wrap(clean_text) # print wrapped text index = 0 for line in clean_lines: line_length = len(line) y = 0 while y < line_length: method, args = directives[index] if method == self.putch: y += 1 method(*args) index += 1 self.newline() else: self.puts(text) self.newline()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newline(self): """ Advances the cursor position ot the left hand side, and to the next line. If the cursor is on the lowest line, the displayed contents are scrolled, causing the top line to be lost. """
self.carriage_return() if self._cy + (2 * self._ch) >= self._device.height: # Simulate a vertical scroll copy = self._backing_image.crop((0, self._ch, self._device.width, self._device.height)) self._backing_image.paste(copy, (0, 0)) self._canvas.rectangle((0, copy.height, self._device.width, self._device.height), fill=self.default_bgcolor) else: self._cy += self._ch self.flush() if self.animate: time.sleep(0.2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backspace(self): """ Moves the cursor one place to the left, erasing the character at the current position. Cannot move beyond column zero, nor onto the previous line. """
if self._cx + self._cw >= 0: self.erase() self._cx -= self._cw self.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase(self): """ Erase the contents of the cursor's current position without moving the cursor's position. """
bounds = (self._cx, self._cy, self._cx + self._cw, self._cy + self._ch) self._canvas.rectangle(bounds, fill=self._bgcolor)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ Resets the foreground and background color value back to the original when initialised. """
self._fgcolor = self.default_fgcolor self._bgcolor = self.default_bgcolor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reverse_colors(self): """ Flips the foreground and background colors. """
self._bgcolor, self._fgcolor = self._fgcolor, self._bgcolor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def savepoint(self): """ Copies the last displayed image. """
if self._last_image: self._savepoints.append(self._last_image) self._last_image = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(self, drop=0): """ Restores the last savepoint. If ``drop`` is supplied and greater than zero, then that many savepoints are dropped, and the next savepoint is restored. :param drop: :type drop: int """
assert(drop >= 0) while drop > 0: self._savepoints.pop() drop -= 1 img = self._savepoints.pop() self.display(img)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self, value): """ Updates the seven-segment display with the given value. If there is not enough space to show the full text, an ``OverflowException`` is raised. :param value: The value to render onto the device. Any characters which cannot be rendered will be converted into the ``undefined`` character supplied in the constructor. :type value: str """
self._text_buffer = observable(mutable_string(value), observer=self._flush)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_task(self, func, *args, **kargs): """ Add a task to the queue. """
self.tasks.put((func, args, kargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capabilities(self, width, height, rotate, mode="1"): """ Assigns attributes such as ``width``, ``height``, ``size`` and ``bounding_box`` correctly oriented from the supplied parameters. :param width: The device width. :type width: int :param height: The device height. :type height: int :param rotate: An integer value of 0 (default), 1, 2 or 3 only, where 0 is no rotation, 1 is rotate 90° clockwise, 2 is 180° rotation and 3 represents 270° rotation. :type rotate: int :param mode: The supported color model, one of ``"1"``, ``"RGB"`` or ``"RGBA"`` only. :type mode: str """
assert mode in ("1", "RGB", "RGBA") assert rotate in (0, 1, 2, 3) self._w = width self._h = height self.width = width if rotate % 2 == 0 else height self.height = height if rotate % 2 == 0 else width self.size = (self.width, self.height) self.bounding_box = (0, 0, self.width - 1, self.height - 1) self.rotate = rotate self.mode = mode self.persist = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_message(device, msg, y_offset=0, fill=None, font=None, scroll_delay=0.03): """ Scrolls a message right-to-left across the devices display. :param device: The device to scroll across. :param msg: The text message to display (must be ASCII only). :type msg: str :param y_offset: The row to use to display the text. :type y_offset: int :param fill: The fill color to use (standard Pillow color name or RGB tuple). :param font: The font (from :py:mod:`luma.core.legacy.font`) to use. :param scroll_delay: The number of seconds to delay between scrolling. :type scroll_delay: float """
fps = 0 if scroll_delay == 0 else 1.0 / scroll_delay regulator = framerate_regulator(fps) font = font or DEFAULT_FONT with canvas(device) as draw: w, h = textsize(msg, font) x = device.width virtual = viewport(device, width=w + x + x, height=device.height) with canvas(virtual) as draw: text(draw, (x, y_offset), msg, font=font, fill=fill) i = 0 while i <= w + x: with regulator: virtual.set_position((i, 0)) i += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_str(text): """ Given a string of characters, for each normal ASCII character, yields a directive consisting of a 'putch' instruction followed by the character itself. If a valid ANSI escape sequence is detected within the string, the supported codes are translated into directives. For example ``\\033[42m`` would emit a directive of ``["background_color", "green"]``. Note that unrecognised escape sequences are silently ignored: Only reset, reverse colours and 8 foreground and background colours are supported. It is up to the consumer to interpret the directives and update its state accordingly. :param text: An ASCII string which may or may not include valid ANSI Color escape codes. :type text: str """
prog = re.compile(r'^\033\[(\d+(;\d+)*)m', re.UNICODE) while text != "": result = prog.match(text) if result: for code in result.group(1).split(";"): directive = valid_attributes.get(int(code), None) if directive: yield directive n = len(result.group(0)) text = text[n:] else: yield ["putch", text[0]] text = text[1:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_directives(text, klass): """ Find directives on class ``klass`` in string ``text``. Returns list of ``(method, args)`` tuples. .. versionadded:: 0.9.0 :param text: String containing directives. :type text: str :type klass: object :rtype: list """
directives = [] for directive in parse_str(text): method = klass.__getattribute__(directive[0]) args = directive[1:] directives.append((method, args)) return directives
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_display_types(): """ Get ordered dict containing available display types from available luma sub-projects. :rtype: collections.OrderedDict """
display_types = OrderedDict() for namespace in get_supported_libraries(): display_types[namespace] = get_choices('luma.{0}.device'.format( namespace)) return display_types
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config(path): """ Load device configuration from file path and return list with parsed lines. :param path: Location of configuration file. :type path: str :rtype: list """
args = [] with open(path, 'r') as fp: for line in fp.readlines(): if line.strip() and not line.startswith("#"): args.append(line.replace("\n", "")) return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_device(args, display_types=None): """ Create and return device. :type args: object :type display_types: dict """
device = None if display_types is None: display_types = get_display_types() if args.display in display_types.get('oled'): import luma.oled.device Device = getattr(luma.oled.device, args.display) Serial = getattr(make_serial(args), args.interface) device = Device(Serial(), **vars(args)) elif args.display in display_types.get('lcd'): import luma.lcd.device import luma.lcd.aux Device = getattr(luma.lcd.device, args.display) spi = make_serial(args).spi() device = Device(spi, **vars(args)) luma.lcd.aux.backlight(gpio=spi._gpio, gpio_LIGHT=args.gpio_backlight, active_low=args.backlight_active == "low").enable(True) elif args.display in display_types.get('led_matrix'): import luma.led_matrix.device from luma.core.interface.serial import noop Device = getattr(luma.led_matrix.device, args.display) spi = make_serial(args, gpio=noop()).spi() device = Device(serial_interface=spi, **vars(args)) elif args.display in display_types.get('emulator'): import luma.emulator.device Device = getattr(luma.emulator.device, args.display) device = Device(**vars(args)) return device
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. 'ls: non_existent_file: No such file or directory\n' """
if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd, output=output) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simulate(self): """ Runs the particle simulation. Simulates one time step, dt, of the particle motion. Calculates the force between each pair of particles and updates particles' motion accordingly """
# Main simulation loop for i in range(self.iterations): for a in self.particles: if a.fixed: continue ftot = vector(0, 0, 0) # total force acting on particle a for b in self.particles: if a.negligible and b.negligible or a == b: continue ab = a.pos - b.pos ftot += ((K_COULOMB * a.charge * b.charge) / mag2(ab)) * versor(ab) a.vel += ftot / a.mass * self.dt # update velocity and position of a a.pos += a.vel * self.dt a.vtk_actor.pos(a.pos) if vp: vp.show(zoom=1.2) vp.camera.Azimuth(0.1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addCutterTool(actor): """Create handles to cut away parts of a mesh. .. hint:: |cutter| |cutter.py|_ """
if isinstance(actor, vtk.vtkVolume): return _addVolumeCutterTool(actor) elif isinstance(actor, vtk.vtkImageData): from vtkplotter import Volume return _addVolumeCutterTool(Volume(actor)) vp = settings.plotter_instance if not vp.renderer: save_int = vp.interactive vp.show(interactive=0) vp.interactive = save_int vp.clickedActor = actor if hasattr(actor, "polydata"): apd = actor.polydata() else: apd = actor.GetMapper().GetInput() planes = vtk.vtkPlanes() planes.SetBounds(apd.GetBounds()) clipper = vtk.vtkClipPolyData() clipper.GenerateClipScalarsOff() clipper.SetInputData(apd) clipper.SetClipFunction(planes) clipper.InsideOutOn() clipper.GenerateClippedOutputOn() act0Mapper = vtk.vtkPolyDataMapper() # the part which stays act0Mapper.SetInputConnection(clipper.GetOutputPort()) act0 = Actor() act0.SetMapper(act0Mapper) act0.GetProperty().SetColor(actor.GetProperty().GetColor()) act0.GetProperty().SetOpacity(1) act1Mapper = vtk.vtkPolyDataMapper() # the part which is cut away act1Mapper.SetInputConnection(clipper.GetClippedOutputPort()) act1 = vtk.vtkActor() act1.SetMapper(act1Mapper) act1.GetProperty().SetOpacity(0.02) act1.GetProperty().SetRepresentationToWireframe() act1.VisibilityOn() vp.renderer.AddActor(act0) vp.renderer.AddActor(act1) vp.renderer.RemoveActor(actor) def SelectPolygons(vobj, event): vobj.GetPlanes(planes) boxWidget = vtk.vtkBoxWidget() boxWidget.OutlineCursorWiresOn() boxWidget.GetSelectedOutlineProperty().SetColor(1, 0, 1) boxWidget.GetOutlineProperty().SetColor(0.1, 0.1, 0.1) boxWidget.GetOutlineProperty().SetOpacity(0.8) boxWidget.SetPlaceFactor(1.05) boxWidget.SetInteractor(vp.interactor) boxWidget.SetInputData(apd) boxWidget.PlaceWidget() boxWidget.AddObserver("InteractionEvent", SelectPolygons) boxWidget.On() vp.cutterWidget = boxWidget vp.clickedActor = act0 ia = vp.actors.index(actor) vp.actors[ia] = act0 colors.printc("Mesh Cutter Tool:", c="m", invert=1) colors.printc(" Move gray handles to cut away parts of the mesh", c="m") colors.printc(" Press X to save file to: clipped.vtk", c="m") vp.interactor.Start() boxWidget.Off() vp.widgets.append(boxWidget) vp.interactor.Start() # allow extra interaction return act0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isSequence(arg): """Check if input is iterable."""
if hasattr(arg, "strip"): return False if hasattr(arg, "__getslice__"): return True if hasattr(arg, "__iter__"): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten(list_to_flatten): """Flatten out a list."""
def genflatten(lst): for elem in lst: if isinstance(elem, (list, tuple)): for x in flatten(elem): yield x else: yield elem return list(genflatten(list_to_flatten))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def humansort(l): """Sort in place a given list the way humans expect. E.g. ['file11', 'file1'] -> ['file1', 'file11'] """
import re def alphanum_key(s): # Turn a string into a list of string and number chunks. # e.g. "z23a" -> ["z", 23, "a"] def tryint(s): if s.isdigit(): return int(s) return s return [tryint(c) for c in re.split("([0-9]+)", s)] l.sort(key=alphanum_key) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lin_interp(x, rangeX, rangeY): """ Interpolate linearly variable x in rangeX onto rangeY. """
s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0]) y = rangeY[0] * (1 - s) + rangeY[1] * s return y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def versor(v): """Return the unit vector. Input can be a list of vectors."""
if isinstance(v[0], np.ndarray): return np.divide(v, mag(v)[:, None]) else: return v / mag(v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mag(z): """Get the magnitude of a vector."""
if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def precision(x, p): """ Returns a string representation of `x` formatted with precision `p`. Based on the webkit javascript implementation taken `from here <https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp>`_, and implemented by `randlet <https://github.com/randlet/to-precision>`_. """
import math x = float(x) if x == 0.0: return "0." + "0" * (p - 1) out = [] if x < 0: out.append("-") x = -x e = int(math.log10(x)) tens = math.pow(10, e - p + 1) n = math.floor(x / tens) if n < math.pow(10, p - 1): e = e - 1 tens = math.pow(10, e - p + 1) n = math.floor(x / tens) if abs((n + 1.0) * tens - x) <= abs(n * tens - x): n = n + 1 if n >= math.pow(10, p): n = n / 10.0 e = e + 1 m = "%.*g" % (p, n) if e < -2 or e >= p: out.append(m[0]) if p > 1: out.append(".") out.extend(m[1:p]) out.append("e") if e > 0: out.append("+") out.append(str(e)) elif e == (p - 1): out.append(m) elif e >= 0: out.append(m[: e + 1]) if e + 1 < len(m): out.append(".") out.extend(m[e + 1 :]) else: out.append("0.") out.extend(["0"] * -(e + 1)) out.append(m) return "".join(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spher2cart(rho, theta, phi): """Spherical to Cartesian coordinate conversion."""
st = np.sin(theta) sp = np.sin(phi) ct = np.cos(theta) cp = np.cos(phi) rhost = rho * st x = rhost * cp y = rhost * sp z = rho * ct return np.array([x, y, z])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cart2spher(x, y, z): """Cartesian to Spherical coordinate conversion."""
hxy = np.hypot(x, y) r = np.hypot(hxy, z) theta = np.arctan2(z, hxy) phi = np.arctan2(y, x) return r, theta, phi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cart2pol(x, y): """Cartesian to Polar coordinates conversion."""
theta = np.arctan2(y, x) rho = np.hypot(x, y) return theta, rho
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pol2cart(theta, rho): """Polar to Cartesian coordinates conversion."""
x = rho * np.cos(theta) y = rho * np.sin(theta) return x, y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isIdentity(M, tol=1e-06): """Check if vtkMatrix4x4 is Identity."""
for i in [0, 1, 2, 3]: for j in [0, 1, 2, 3]: e = M.GetElement(i, j) if i == j: if np.abs(e - 1) > tol: return False elif np.abs(e) > tol: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grep(filename, tag, firstOccurrence=False): """Greps the line that starts with a specific `tag` string from inside a file."""
import re try: afile = open(filename, "r") except: print("Error in utils.grep(): cannot open file", filename) exit() content = None for line in afile: if re.search(tag, line): content = line.split() if firstOccurrence: break if content: if len(content) == 2: content = content[1] else: content = content[1:] afile.close() return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makeBands(inputlist, numberOfBands): """ Group values of a list into bands of equal value. :param int numberOfBands: number of bands, a positive integer > 2. :return: a binned list of the same length as the input. """
if numberOfBands < 2: return inputlist vmin = np.min(inputlist) vmax = np.max(inputlist) bb = np.linspace(vmin, vmax, numberOfBands, endpoint=0) dr = bb[1] - bb[0] bb += dr / 2 tol = dr / 2 * 1.001 newlist = [] for s in inputlist: for b in bb: if abs(s - b) < tol: newlist.append(b) break return np.array(newlist)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(actor=()): """ Clear specific actor or list of actors from the current rendering window. """
if not settings.plotter_instance: return settings.plotter_instance.clear(actor) return settings.plotter_instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getVolumes(self, obj=None, renderer=None): """ Return the list of the rendered Volumes. """
if renderer is None: renderer = self.renderer elif isinstance(renderer, int): renderer = self.renderers.index(renderer) else: return [] if obj is None or isinstance(obj, int): if obj is None: acs = renderer.GetVolumes() elif obj >= len(self.renderers): colors.printc("~timesError in getVolumes: non existing renderer", obj, c=1) return [] else: acs = self.renderers[obj].GetVolumes() vols = [] acs.InitTraversal() for i in range(acs.GetNumberOfItems()): a = acs.GetNextItem() if a.GetPickable(): r = self.renderers.index(renderer) if a == self.axes_exist[r]: continue vols.append(a) return vols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getActors(self, obj=None, renderer=None): """ Return an actors list. If ``obj`` is: ``None``, return actors of current renderer ``int``, return actors in given renderer number ``vtkAssembly`` return the contained actors ``string``, return actors matching legend name :param int,vtkRenderer renderer: specify which renederer to look into. """
if renderer is None: renderer = self.renderer elif isinstance(renderer, int): renderer = self.renderers.index(renderer) else: return [] if obj is None or isinstance(obj, int): if obj is None: acs = renderer.GetActors() elif obj >= len(self.renderers): colors.printc("~timesError in getActors: non existing renderer", obj, c=1) return [] else: acs = self.renderers[obj].GetActors() actors = [] acs.InitTraversal() for i in range(acs.GetNumberOfItems()): a = acs.GetNextItem() if a.GetPickable(): r = self.renderers.index(renderer) if a == self.axes_exist[r]: continue actors.append(a) return actors elif isinstance(obj, vtk.vtkAssembly): cl = vtk.vtkPropCollection() obj.GetActors(cl) actors = [] cl.InitTraversal() for i in range(obj.GetNumberOfPaths()): act = vtk.vtkActor.SafeDownCast(cl.GetNextProp()) if act.GetPickable(): actors.append(act) return actors elif isinstance(obj, str): # search the actor by the legend name actors = [] for a in self.actors: if hasattr(a, "_legend") and obj in a._legend: actors.append(a) return actors elif isinstance(obj, vtk.vtkActor): return [obj] if self.verbose: colors.printc("~lightning Warning in getActors: unexpected input type", obj, c=1) return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, actors): """Append input object to the internal list of actors to be shown. :return: returns input actor for possible concatenation. """
if utils.isSequence(actors): for a in actors: if a not in self.actors: self.actors.append(a) return None else: self.actors.append(actors) return actors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def light( self, pos=(1, 1, 1), fp=(0, 0, 0), deg=25, diffuse="y", ambient="r", specular="b", showsource=False, ): """ Generate a source of light placed at pos, directed to focal point fp. :param fp: focal Point, if this is a ``vtkActor`` use its position. :type fp: vtkActor, list :param deg: aperture angle of the light source :param showsource: if `True`, will show a vtk representation of the source of light as an extra actor .. hint:: |lights.py|_ """
if isinstance(fp, vtk.vtkActor): fp = fp.GetPosition() light = vtk.vtkLight() light.SetLightTypeToSceneLight() light.SetPosition(pos) light.SetPositional(1) light.SetConeAngle(deg) light.SetFocalPoint(fp) light.SetDiffuseColor(colors.getColor(diffuse)) light.SetAmbientColor(colors.getColor(ambient)) light.SetSpecularColor(colors.getColor(specular)) save_int = self.interactive self.show(interactive=0) self.interactive = save_int if showsource: lightActor = vtk.vtkLightActor() lightActor.SetLight(light) self.renderer.AddViewProp(lightActor) self.renderer.AddLight(light) return light
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeActor(self, a): """Remove ``vtkActor`` or actor index from current renderer."""
if not self.initializedPlotter: save_int = self.interactive self.show(interactive=0) self.interactive = save_int return if self.renderer: self.renderer.RemoveActor(a) if hasattr(a, 'renderedAt'): ir = self.renderers.index(self.renderer) a.renderedAt.discard(ir) if a in self.actors: i = self.actors.index(a) del self.actors[i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self, actors=()): """Delete specified list of actors, by default delete all."""
if not utils.isSequence(actors): actors = [actors] if len(actors): for a in actors: self.removeActor(a) else: for a in settings.collectable_actors: self.removeActor(a) settings.collectable_actors = [] self.actors = [] for a in self.getActors(): self.renderer.RemoveActor(a) for a in self.getVolumes(): self.renderer.RemoveVolume(a) for s in self.sliders: s.EnabledOff() for b in self.buttons: self.renderer.RemoveActor(b) for w in self.widgets: w.EnabledOff() for c in self.scalarbars: self.renderer.RemoveActor(c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def morph(clm1, clm2, t, lmax): """Interpolate linearly the two sets of sph harm. coeeficients."""
clm = (1 - t) * clm1 + t * clm2 grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components agrid_reco = grid_reco.to_array() pts = [] for i, longs in enumerate(agrid_reco): ilat = grid_reco.lats()[i] for j, value in enumerate(longs): ilong = grid_reco.lons()[j] th = (90 - ilat) / 57.3 ph = ilong / 57.3 r = value + rbias p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * r pts.append(p) return pts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mergeActors(actors, tol=0): """ Build a new actor formed by the fusion of the polydatas of input objects. Similar to Assembly, but in this case the input objects become a single mesh. .. hint:: |thinplate_grid| |thinplate_grid.py|_ """
polylns = vtk.vtkAppendPolyData() for a in actors: polylns.AddInputData(a.polydata()) polylns.Update() pd = polylns.GetOutput() return Actor(pd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isosurface(image, smoothing=0, threshold=None, connectivity=False): """Return a ``vtkActor`` isosurface extracted from a ``vtkImageData`` object. :param float smoothing: gaussian filter to smooth vtkImageData, in units of sigmas :param threshold: value or list of values to draw the isosurface(s) :type threshold: float, list :param bool connectivity: if True only keeps the largest portion of the polydata .. hint:: |isosurfaces| |isosurfaces.py|_ """
if smoothing: smImg = vtk.vtkImageGaussianSmooth() smImg.SetDimensionality(3) smImg.SetInputData(image) smImg.SetStandardDeviations(smoothing, smoothing, smoothing) smImg.Update() image = smImg.GetOutput() scrange = image.GetScalarRange() if scrange[1] > 1e10: print("Warning, high scalar range detected:", scrange) cf = vtk.vtkContourFilter() cf.SetInputData(image) cf.UseScalarTreeOn() cf.ComputeScalarsOn() if utils.isSequence(threshold): cf.SetNumberOfContours(len(threshold)) for i, t in enumerate(threshold): cf.SetValue(i, t) cf.Update() else: if not threshold: threshold = (2 * scrange[0] + scrange[1]) / 3.0 cf.SetValue(0, threshold) cf.Update() clp = vtk.vtkCleanPolyData() clp.SetInputConnection(cf.GetOutputPort()) clp.Update() poly = clp.GetOutput() if connectivity: conn = vtk.vtkPolyDataConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.SetInputData(poly) conn.Update() poly = conn.GetOutput() a = Actor(poly, c=None).phong() a.mapper.SetScalarRange(scrange[0], scrange[1]) return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show( self, at=None, shape=(1, 1), N=None, pos=(0, 0), size="auto", screensize="auto", title="", bg="blackboard", bg2=None, axes=4, infinity=False, verbose=True, interactive=None, offscreen=False, resetcam=True, zoom=None, viewup="", azimuth=0, elevation=0, roll=0, interactorStyle=0, newPlotter=False, depthpeeling=False, q=False, ): """ Create on the fly an instance of class ``Plotter`` or use the last existing one to show one single object. Allowed input objects are: ``Actor`` or ``Volume``. This is meant as a shortcut. If more than one object needs to be visualised :param bool newPlotter: if set to `True`, a call to ``show`` will instantiate a new ``Plotter`` object (a new window) instead of reusing the first created. See e.g.: |readVolumeAsIsoSurface.py|_ :return: the current ``Plotter`` class instance. .. note:: E.g.: """
from vtkplotter.plotter import show return show( self, at=at, shape=shape, N=N, pos=pos, size=size, screensize=screensize, title=title, bg=bg, bg2=bg2, axes=axes, infinity=infinity, verbose=verbose, interactive=interactive, offscreen=offscreen, resetcam=resetcam, zoom=zoom, viewup=viewup, azimuth=azimuth, elevation=elevation, roll=roll, interactorStyle=interactorStyle, newPlotter=newPlotter, depthpeeling=depthpeeling, q=q, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPos(self, dp_x=None, dy=None, dz=None): """Add vector to current actor position."""
p = np.array(self.GetPosition()) if dz is None: # assume dp_x is of the form (x,y,z) self.SetPosition(p + dp_x) else: self.SetPosition(p + [dp_x, dy, dz]) if self.trail: self.updateTrail() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotate(self, angle, axis=(1, 0, 0), axis_point=(0, 0, 0), rad=False): """Rotate ``Actor`` around an arbitrary `axis` passing through `axis_point`."""
if rad: anglerad = angle else: anglerad = angle / 57.29578 axis = utils.versor(axis) a = np.cos(anglerad / 2) b, c, d = -axis * np.sin(anglerad / 2) aa, bb, cc, dd = a * a, b * b, c * c, d * d bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d R = np.array( [ [aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)], [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc], ] ) rv = np.dot(R, self.GetPosition() - np.array(axis_point)) + axis_point if rad: angle *= 57.29578 # this vtk method only rotates in the origin of the actor: self.RotateWXYZ(angle, axis[0], axis[1], axis[2]) self.SetPosition(rv) if self.trail: self.updateTrail() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotateX(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around x-axis. If angle is in radians set ``rad=True``."""
if rad: angle *= 57.29578 self.RotateX(angle) if self.trail: self.updateTrail() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotateY(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around y-axis. If angle is in radians set ``rad=True``."""
if rad: angle *= 57.29578 self.RotateY(angle) if self.trail: self.updateTrail() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotateZ(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around z-axis. If angle is in radians set ``rad=True``."""
if rad: angle *= 57.29578 self.RotateZ(angle) if self.trail: self.updateTrail() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addTrail(self, offset=None, maxlength=None, n=25, c=None, alpha=None, lw=1): """Add a trailing line to actor. :param offset: set an offset vector from the object center. :param maxlength: length of trailing line in absolute units :param n: number of segments to control precision :param lw: line width of the trail .. hint:: |trail| |trail.py|_ """
if maxlength is None: maxlength = self.diagonalSize() * 20 if maxlength == 0: maxlength = 1 if self.trail is None: pos = self.GetPosition() self.trailPoints = [None] * n self.trailSegmentSize = maxlength / n self.trailOffset = offset ppoints = vtk.vtkPoints() # Generate the polyline poly = vtk.vtkPolyData() ppoints.SetData(numpy_to_vtk([pos] * n)) poly.SetPoints(ppoints) lines = vtk.vtkCellArray() lines.InsertNextCell(n) for i in range(n): lines.InsertCellPoint(i) poly.SetPoints(ppoints) poly.SetLines(lines) mapper = vtk.vtkPolyDataMapper() if c is None: if hasattr(self, "GetProperty"): col = self.GetProperty().GetColor() else: col = (0.1, 0.1, 0.1) else: col = colors.getColor(c) if alpha is None: alpha = 1 if hasattr(self, "GetProperty"): alpha = self.GetProperty().GetOpacity() mapper.SetInputData(poly) tline = Actor() tline.SetMapper(mapper) tline.GetProperty().SetColor(col) tline.GetProperty().SetOpacity(alpha) tline.GetProperty().SetLineWidth(lw) self.trail = tline # holds the vtkActor return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateMesh(self, polydata): """ Overwrite the polygonal mesh of the actor with a new one. """
self.poly = polydata self.mapper.SetInputData(polydata) self.mapper.Modified() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addScalarBar(self, c=None, title="", horizontal=False, vmin=None, vmax=None): """ Add a 2D scalar bar to actor. .. hint:: |mesh_bands| |mesh_bands.py|_ """
# book it, it will be created by Plotter.show() later self.scalarbar = [c, title, horizontal, vmin, vmax] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addScalarBar3D( self, pos=(0, 0, 0), normal=(0, 0, 1), sx=0.1, sy=2, nlabels=9, ncols=256, cmap=None, c="k", alpha=1, ): """ Draw a 3D scalar bar to actor. .. hint:: |mesh_coloring| |mesh_coloring.py|_ """
# book it, it will be created by Plotter.show() later self.scalarbar = [pos, normal, sx, sy, nlabels, ncols, cmap, c, alpha] return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def texture(self, name, scale=1, falsecolors=False, mapTo=1): """Assign a texture to actor from image file or predefined texture name."""
import os if mapTo == 1: tmapper = vtk.vtkTextureMapToCylinder() elif mapTo == 2: tmapper = vtk.vtkTextureMapToSphere() elif mapTo == 3: tmapper = vtk.vtkTextureMapToPlane() tmapper.SetInputData(self.polydata(False)) if mapTo == 1: tmapper.PreventSeamOn() xform = vtk.vtkTransformTextureCoords() xform.SetInputConnection(tmapper.GetOutputPort()) xform.SetScale(scale, scale, scale) if mapTo == 1: xform.FlipSOn() xform.Update() mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(xform.GetOutputPort()) mapper.ScalarVisibilityOff() fn = settings.textures_path + name + ".jpg" if os.path.exists(name): fn = name elif not os.path.exists(fn): colors.printc("~sad Texture", name, "not found in", settings.textures_path, c="r") colors.printc("~target Available textures:", c="m", end=" ") for ff in os.listdir(settings.textures_path): colors.printc(ff.split(".")[0], end=" ", c="m") print() return jpgReader = vtk.vtkJPEGReader() jpgReader.SetFileName(fn) atext = vtk.vtkTexture() atext.RepeatOn() atext.EdgeClampOff() atext.InterpolateOn() if falsecolors: atext.MapColorScalarsThroughLookupTableOn() atext.SetInputConnection(jpgReader.GetOutputPort()) self.GetProperty().SetColor(1, 1, 1) self.SetMapper(mapper) self.SetTexture(atext) self.Modified() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def computeNormals(self): """Compute cell and vertex normals for the actor's mesh. .. warning:: Mesh gets modified, can have a different nr. of vertices. """
poly = self.polydata(False) pnormals = poly.GetPointData().GetNormals() cnormals = poly.GetCellData().GetNormals() if pnormals and cnormals: return self pdnorm = vtk.vtkPolyDataNormals() pdnorm.SetInputData(poly) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() return self.updateMesh(pdnorm.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(self, tol=None): """ Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large. If ``tol=None`` only removes coincident points. :param tol: defines how far should be the points from each other in terms of fraction of the bounding box length. .. hint:: |moving_least_squares1D| |moving_least_squares1D.py|_ |recosurface| |recosurface.py|_ """
poly = self.polydata(False) cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.PointMergingOn() cleanPolyData.ConvertLinesToPointsOn() cleanPolyData.ConvertPolysToLinesOn() cleanPolyData.SetInputData(poly) if tol: cleanPolyData.SetTolerance(tol) cleanPolyData.Update() return self.updateMesh(cleanPolyData.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def averageSize(self): """Calculate the average size of a mesh. This is the mean of the vertex distances from the center of mass."""
cm = self.centerOfMass() coords = self.coordinates(copy=False) if not len(coords): return 0 s, c = 0.0, 0.0 n = len(coords) step = int(n / 10000.0) + 1 for i in np.arange(0, n, step): s += utils.mag(coords[i] - cm) c += 1 return s / c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diagonalSize(self): """Get the length of the diagonal of actor bounding box."""
b = self.polydata().GetBounds() return np.sqrt((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maxBoundSize(self): """Get the maximum dimension in x, y or z of the actor bounding box."""
b = self.polydata(True).GetBounds() return max(abs(b[1] - b[0]), abs(b[3] - b[2]), abs(b[5] - b[4]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def centerOfMass(self): """Get the center of mass of actor. .. hint:: |fatlimb| |fatlimb.py|_ """
cmf = vtk.vtkCenterOfMass() cmf.SetInputData(self.polydata(True)) cmf.Update() c = cmf.GetCenter() return np.array(c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def closestPoint(self, pt, N=1, radius=None, returnIds=False): """ Find the closest point on a mesh given from the input point `pt`. :param int N: if greater than 1, return a list of N ordered closest points. :param float radius: if given, get all points within that radius. :param bool returnIds: return points IDs instead of point coordinates. .. hint:: |fitplanes.py|_ |align1| |align1.py|_ |quadratic_morphing| |quadratic_morphing.py|_ .. note:: The appropriate kd-tree search locator is built on the fly and cached for speed. """
poly = self.polydata(True) if N > 1 or radius: plocexists = self.point_locator if not plocexists or (plocexists and self.point_locator is None): point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(poly) point_locator.BuildLocator() self.point_locator = point_locator vtklist = vtk.vtkIdList() if N > 1: self.point_locator.FindClosestNPoints(N, pt, vtklist) else: self.point_locator.FindPointsWithinRadius(radius, pt, vtklist) if returnIds: return [int(vtklist.GetId(k)) for k in range(vtklist.GetNumberOfIds())] else: trgp = [] for i in range(vtklist.GetNumberOfIds()): trgp_ = [0, 0, 0] vi = vtklist.GetId(i) poly.GetPoints().GetPoint(vi, trgp_) trgp.append(trgp_) return np.array(trgp) clocexists = self.cell_locator if not clocexists or (clocexists and self.cell_locator is None): cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(poly) cell_locator.BuildLocator() self.cell_locator = cell_locator trgp = [0, 0, 0] cid = vtk.mutable(0) dist2 = vtk.mutable(0) subid = vtk.mutable(0) self.cell_locator.FindClosestPoint(pt, trgp, cid, subid, dist2) if returnIds: return int(cid) else: return np.array(trgp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transformMesh(self, transformation): """ Apply this transformation to the polygonal `mesh`, not to the actor's transformation, which is reset. :param transformation: ``vtkTransform`` or ``vtkMatrix4x4`` object. """
if isinstance(transformation, vtk.vtkMatrix4x4): tr = vtk.vtkTransform() tr.SetMatrix(transformation) transformation = tr tf = vtk.vtkTransformPolyDataFilter() tf.SetTransform(transformation) tf.SetInputData(self.polydata()) tf.Update() self.PokeMatrix(vtk.vtkMatrix4x4()) # identity return self.updateMesh(tf.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize(self): """ Shift actor's center of mass at origin and scale its average size to unit. """
cm = self.centerOfMass() coords = self.coordinates() if not len(coords): return pts = coords - cm xyz2 = np.sum(pts * pts, axis=0) scale = 1 / np.sqrt(np.sum(xyz2) / len(pts)) t = vtk.vtkTransform() t.Scale(scale, scale, scale) t.Translate(-cm) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(self.poly) tf.SetTransform(t) tf.Update() return self.updateMesh(tf.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mirror(self, axis="x"): """ Mirror the actor polydata along one of the cartesian axes. .. note:: ``axis='n'``, will flip only mesh normals. .. hint:: |mirror| |mirror.py|_ """
poly = self.polydata(transformed=True) polyCopy = vtk.vtkPolyData() polyCopy.DeepCopy(poly) sx, sy, sz = 1, 1, 1 dx, dy, dz = self.GetPosition() if axis.lower() == "x": sx = -1 elif axis.lower() == "y": sy = -1 elif axis.lower() == "z": sz = -1 elif axis.lower() == "n": pass else: colors.printc("~times Error in mirror(): mirror must be set to x, y, z or n.", c=1) raise RuntimeError() if axis != "n": for j in range(polyCopy.GetNumberOfPoints()): p = [0, 0, 0] polyCopy.GetPoint(j, p) polyCopy.GetPoints().SetPoint( j, p[0] * sx - dx * (sx - 1), p[1] * sy - dy * (sy - 1), p[2] * sz - dz * (sz - 1), ) rs = vtk.vtkReverseSense() rs.SetInputData(polyCopy) rs.ReverseNormalsOn() rs.Update() polyCopy = rs.GetOutput() pdnorm = vtk.vtkPolyDataNormals() pdnorm.SetInputData(polyCopy) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() return self.updateMesh(pdnorm.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shrink(self, fraction=0.85): """Shrink the triangle polydata in the representation of the input mesh. Example: .. code-block:: python from vtkplotter import * pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75) s = Sphere(r=0.2).pos(0,0,-0.5) show(pot, s) |shrink| |shrink.py|_ """
poly = self.polydata(True) shrink = vtk.vtkShrinkPolyData() shrink.SetInputData(poly) shrink.SetShrinkFactor(fraction) shrink.Update() return self.updateMesh(shrink.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stretch(self, q1, q2): """Stretch actor between points `q1` and `q2`. Mesh is not affected. .. hint:: |aspring| |aspring.py|_ .. note:: for ``Actors`` like helices, Line, cylinders, cones etc., two attributes ``actor.base``, and ``actor.top`` are already defined. """
if self.base is None: colors.printc('~times Error in stretch(): Please define vectors \ actor.base and actor.top at creation. Exit.', c='r') exit(0) p1, p2 = self.base, self.top q1, q2, z = np.array(q1), np.array(q2), np.array([0, 0, 1]) plength = np.linalg.norm(p2 - p1) qlength = np.linalg.norm(q2 - q1) T = vtk.vtkTransform() T.PostMultiply() T.Translate(-p1) cosa = np.dot(p2 - p1, z) / plength n = np.cross(p2 - p1, z) T.RotateWXYZ(np.arccos(cosa) * 57.3, n) T.Scale(1, 1, qlength / plength) cosa = np.dot(q2 - q1, z) / qlength n = np.cross(q2 - q1, z) T.RotateWXYZ(-np.arccos(cosa) * 57.3, n) T.Translate(q1) self.SetUserMatrix(T.GetMatrix()) if self.trail: self.updateTrail() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cutWithPlane(self, origin=(0, 0, 0), normal=(1, 0, 0), showcut=False): """ Takes a ``vtkActor`` and cuts it with the plane defined by a point and a normal. :param origin: the cutting plane goes through this point :param normal: normal of the cutting plane :param showcut: if `True` show the cut off part of the mesh as thin wireframe. :Example: .. code-block:: python from vtkplotter import Cube cube = Cube().cutWithPlane(normal=(1,1,1)) cube.bc('pink').show() |cutcube| .. hint:: |trail| |trail.py|_ """
if normal is "x": normal = (1,0,0) elif normal is "y": normal = (0,1,0) elif normal is "z": normal = (0,0,1) plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) self.computeNormals() poly = self.polydata() clipper = vtk.vtkClipPolyData() clipper.SetInputData(poly) clipper.SetClipFunction(plane) if showcut: clipper.GenerateClippedOutputOn() else: clipper.GenerateClippedOutputOff() clipper.GenerateClipScalarsOff() clipper.SetValue(0) clipper.Update() self.updateMesh(clipper.GetOutput()) if showcut: c = self.GetProperty().GetColor() cpoly = clipper.GetClippedOutput() restActor = Actor(cpoly, c=c, alpha=0.05, wire=1) restActor.SetUserMatrix(self.GetMatrix()) asse = Assembly([self, restActor]) self = asse return asse else: return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cutWithMesh(self, mesh, invert=False): """ Cut an ``Actor`` mesh with another ``vtkPolyData`` or ``Actor``. :param bool invert: if True return cut off part of actor. .. hint:: |cutWithMesh| |cutWithMesh.py|_ |cutAndCap| |cutAndCap.py|_ """
if isinstance(mesh, vtk.vtkPolyData): polymesh = mesh if isinstance(mesh, Actor): polymesh = mesh.polydata() else: polymesh = mesh.GetMapper().GetInput() poly = self.polydata() # Create an array to hold distance information signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName("SignedDistances") # implicit function that will be used to slice the mesh ippd = vtk.vtkImplicitPolyDataDistance() ippd.SetInput(polymesh) # Evaluate the signed distance function at all of the grid points for pointId in range(poly.GetNumberOfPoints()): p = poly.GetPoint(pointId) signedDistance = ippd.EvaluateFunction(p) signedDistances.InsertNextValue(signedDistance) # add the SignedDistances to the grid poly.GetPointData().SetScalars(signedDistances) # use vtkClipDataSet to slice the grid with the polydata clipper = vtk.vtkClipPolyData() clipper.SetInputData(poly) if invert: clipper.InsideOutOff() else: clipper.InsideOutOn() clipper.SetValue(0.0) clipper.Update() return self.updateMesh(clipper.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cap(self, returnCap=False): """ Generate a "cap" on a clipped actor, or caps sharp edges. .. hint:: |cutAndCap| |cutAndCap.py|_ """
poly = self.polydata(True) fe = vtk.vtkFeatureEdges() fe.SetInputData(poly) fe.BoundaryEdgesOn() fe.FeatureEdgesOff() fe.NonManifoldEdgesOff() fe.ManifoldEdgesOff() fe.Update() stripper = vtk.vtkStripper() stripper.SetInputData(fe.GetOutput()) stripper.Update() boundaryPoly = vtk.vtkPolyData() boundaryPoly.SetPoints(stripper.GetOutput().GetPoints()) boundaryPoly.SetPolys(stripper.GetOutput().GetLines()) tf = vtk.vtkTriangleFilter() tf.SetInputData(boundaryPoly) tf.Update() if returnCap: return Actor(tf.GetOutput()) else: polyapp = vtk.vtkAppendPolyData() polyapp.AddInputData(poly) polyapp.AddInputData(tf.GetOutput()) polyapp.Update() return self.updateMesh(polyapp.GetOutput()).clean()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threshold(self, scalars, vmin=None, vmax=None, useCells=False): """ Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of the scalar :param bool useCells: if `True`, assume array scalars refers to cells. .. hint:: |mesh_threshold| |mesh_threshold.py|_ """
if utils.isSequence(scalars): self.addPointScalars(scalars, "threshold") scalars = "threshold" elif self.scalars(scalars) is None: colors.printc("~times No scalars found with name", scalars, c=1) exit() thres = vtk.vtkThreshold() thres.SetInputData(self.poly) if useCells: asso = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS else: asso = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS thres.SetInputArrayToProcess(0, 0, 0, asso, scalars) if vmin is None and vmax is not None: thres.ThresholdByLower(vmax) elif vmax is None and vmin is not None: thres.ThresholdByUpper(vmin) else: thres.ThresholdBetween(vmin, vmax) thres.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(thres.GetOutput()) gf.Update() return self.updateMesh(gf.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triangle(self, verts=True, lines=True): """ Converts actor polygons and strips to triangles. """
tf = vtk.vtkTriangleFilter() tf.SetPassLines(lines) tf.SetPassVerts(verts) tf.SetInputData(self.poly) tf.Update() return self.updateMesh(tf.GetOutput())