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 width_max(self, width_max): """Set the maximum width of the widget. Parameters width_max: None | float the maximum width of the widget. if None, maximum widt...
if width_max is None: self._width_limits[1] = None return width_max = float(width_max) assert(self.width_min <= width_max) self._width_limits[1] = width_max self._update_layout()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def height_max(self, height_max): """Set the maximum height of the widget. Parameters height_max: None | float the maximum height of the widget. if None, maximum...
if height_max is None: self._height_limits[1] = None return height_max = float(height_max) assert(0 <= self.height_min <= height_max) self._height_limits[1] = height_max self._update_layout()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inner_rect(self): """The rectangular area inside the margin, border, and padding. Generally widgets should avoid drawing or placing sub-widgets outside this ...
m = self.margin + self._border_width + self.padding if not self.border_color.is_blank: m += 1 return Rect((m, m), (self.size[0]-2*m, self.size[1]-2*m))
<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_clipper(self): """Called whenever the clipper for this widget may need to be updated. """
if self.clip_children and self._clipper is None: self._clipper = Clipper() elif not self.clip_children: self._clipper = None if self._clipper is None: return self._clipper.rect = self.inner_rect self._clipper.transform = self.get_transform('f...
<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_line(self): """ Update border line to match new shape """
w = self._border_width m = self.margin # border is drawn within the boundaries of the widget: # # size = (8, 7) margin=2 # internal rect = (3, 3, 2, 1) # ........ # ........ # ..BBBB.. # ..B B.. # ..BBBB.. # ........
<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_widget(self, widget): """ Add a Widget as a managed child of this Widget. The child will be automatically positioned and sized to fill the entire space i...
self._widgets.append(widget) widget.parent = self self._update_child_widgets() return widget
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_widget(self, widget): """ Remove a Widget as a managed child of this Widget. Parameters widget : instance of Widget The widget to remove. """
self._widgets.remove(widget) widget.parent = None self._update_child_widgets()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pack_ieee(value): """Packs float ieee binary representation into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """
return np.fromstring(value.tostring(), np.ubyte).reshape((value.shape + (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 load_spatial_filters(packed=True): """Load spatial-filters kernel Parameters packed : bool Whether or not the data should be in "packed" representation for u...
names = ("Bilinear", "Hanning", "Hamming", "Hermite", "Kaiser", "Quadric", "Bicubic", "CatRom", "Mitchell", "Spline16", "Spline36", "Gaussian", "Bessel", "Sinc", "Lanczos", "Blackman", "Nearest") kernel = np.load(op.join(DATA_DIR, 'spatial-filters.npy')) if packed: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timeout(limit, handler): """A decorator ensuring that the decorated function tun time does not exceeds the argument limit. :args limit: the time limit :type ...
def wrapper(f): def wrapped_f(*args, **kwargs): old_handler = signal.getsignal(signal.SIGALRM) signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(limit) try: res = f(*args, **kwargs) except Timeout: handler...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_backend_kwargs(self, kwargs): """ Simple utility to retrieve kwargs in predetermined order. Also checks whether the values of the backend arguments ...
# Verify given argument with capability of the backend app = self._vispy_canvas.app capability = app.backend_module.capability if kwargs['context'].shared.name: # name already assigned: shared if not capability['context']: raise RuntimeError('Cannot share co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def viewbox_key_event(self, event): """ViewBox key event handler Parameters event : instance of Event The event. """
PerspectiveCamera.viewbox_key_event(self, event) if event.handled or not self.interactive: return # Ensure the timer runs if not self._timer.running: self._timer.start() if event.key in self._keymap: val_dims = self._keymap[event.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 set_inputhook(self, callback): """Set PyOS_InputHook to callback and return the previous one."""
# On platforms with 'readline' support, it's all too likely to # have a KeyboardInterrupt signal delivered *even before* an # initial ``try:`` clause in the callback can be executed, so # we need to disable CTRL+C in this situation. ignore_CTRL_C() self._callback = callb...
<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_inputhook(self, app=None): """Set PyOS_InputHook to NULL and return the previous one. Parameters app : optional, ignored This parameter is allowed only...
pyos_inputhook_ptr = self.get_pyos_inputhook() original = self.get_pyos_inputhook_as_func() pyos_inputhook_ptr.value = ctypes.c_void_p(None).value allow_CTRL_C() self._reset() return original
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_current_canvas(canvas): """ Make a canvas active. Used primarily by the canvas itself. """
# Notify glir canvas.context._do_CURRENT_command = True # Try to be quick if canvasses and canvasses[-1]() is canvas: return # Make this the current cc = [c() for c in canvasses if c() is not None] while canvas in cc: cc.remove(canvas) cc.append(canvas) canvasses[:]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forget_canvas(canvas): """ Forget about the given canvas. Used by the canvas when closed. """
cc = [c() for c in canvasses if c() is not None] while canvas in cc: cc.remove(canvas) canvasses[:] = [weakref.ref(c) for c in cc]
<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_shared(self, name, ref): """ For the app backends to create the GLShared object. Parameters name : str The name. ref : object The reference. """
if self._shared is not None: raise RuntimeError('Can only set_shared once.') self._shared = GLShared(name, ref)
<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_ref(self, name, ref): """ Add a reference for the backend object that gives access to the low level context. Used in vispy.app.canvas.backends. The given...
if self._name is None: self._name = name elif name != self._name: raise RuntimeError('Contexts can only share between backends of ' 'the same type') self._refs.append(weakref.ref(ref))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obj(x): """Two Dimensional Shubert Function"""
j = np.arange(1, 6) tmp1 = np.dot(j, np.cos((j+1)*x[0] + j)) tmp2 = np.dot(j, np.cos((j+1)*x[1] + j)) return tmp1 * tmp2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """ Create an exact copy of this quaternion. """
return Quaternion(self.w, self.x, self.y, self.z, 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 _normalize(self): """ Make the quaternion unit length. """
# Get length L = self.norm() if not L: raise ValueError('Quaternion cannot have 0-length.') # Correct self.w /= L self.x /= L self.y /= L self.z /= L
<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_point(self, p): """ Rotate a Point instance using this quaternion. """
# Prepare p = Quaternion(0, p[0], p[1], p[2], False) # Do not normalize! q1 = self.normalize() q2 = self.inverse() # Apply rotation r = (q1*p)*q2 # Make point and return return r.x, r.y, r.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 get_matrix(self): """ Create a 4x4 homography matrix that represents the rotation of the quaternion. """
# Init matrix (remember, a matrix, not an array) a = np.zeros((4, 4), dtype=np.float32) w, x, y, z = self.w, self.x, self.y, self.z # First row a[0, 0] = - 2.0 * (y * y + z * z) + 1.0 a[1, 0] = + 2.0 * (x * y + z * w) a[2, 0] = + 2.0 * (x * z - y * w) a[3...
<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_from_euler_angles(cls, rx, ry, rz, degrees=False): """ Classmethod to create a quaternion given the euler angles. """
if degrees: rx, ry, rz = np.radians([rx, ry, rz]) # Obtain quaternions qx = Quaternion(np.cos(rx/2), 0, 0, np.sin(rx/2)) qy = Quaternion(np.cos(ry/2), 0, np.sin(ry/2), 0) qz = Quaternion(np.cos(rz/2), np.sin(rz/2), 0, 0) # Almost done return qx*qy*qz
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_enum(enum): """ Turn a possibly string enum into an integer enum. """
if isinstance(enum, string_types): try: enum = getattr(gl, 'GL_' + enum.upper()) except AttributeError: try: enum = _internalformats['GL_' + enum.upper()] except KeyError: raise ValueError('Could not find int value for enum %r' % e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_shaders(convert, shaders): """ Modify shading code so that we can write code once and make it run "everywhere". """
# New version of the shaders out = [] if convert == 'es2': for isfragment, shader in enumerate(shaders): has_version = False has_prec_float = False has_prec_int = False lines = [] # Iterate over lines for line in shader.lstr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_es2_command(command): """ Modify a desktop command so it works on es2. """
if command[0] == 'FUNC': return (command[0], re.sub(r'^gl([A-Z])', lambda m: m.group(1).lower(), command[1])) + command[2:] if command[0] == 'SHADERS': return command[:2] + convert_shaders('es2', command[2:]) if command[0] == 'UNIFORM': return command[:-1] + (comman...
<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, filter=None): """ Print the list of commands currently in the queue. If filter is given, print only commands that match the filter. """
for command in self._commands: if command[0] is None: # or command[1] in self._invalid_objects: continue # Skip nill commands if filter and command[0] != filter: continue t = [] for e in command: if isinstance(e, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self, parser): """ Flush all current commands to the GLIR interpreter. """
if self._verbose: show = self._verbose if isinstance(self._verbose, str) else None self.show(show) parser.parse(self._filter(self.clear(), parser))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def associate(self, queue): """Merge this queue with another. Both queues will use a shared command list and either one can be used to fill or flush the shared q...
assert isinstance(queue, GlirQueue) if queue._shared is self._shared: return # merge commands self._shared._commands.extend(queue.clear()) self._shared._verbose |= queue._shared._verbose self._shared._associations[queue] = None # update queue and all...
<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(self, command): """ Parse a single command. """
cmd, id_, args = command[0], command[1], command[2:] if cmd == 'CURRENT': # This context is made current self.env.clear() self._gl_initialize() self.env['fbo'] = args[0] gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, args[0]) elif cmd == 'FU...
<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(self, commands): """ Parse a list of commands. """
# Get rid of dummy objects that represented deleted objects in # the last parsing round. to_delete = [] for id_, val in self._objects.items(): if val == JUST_DELETED: to_delete.append(id_) for id_ in to_delete: self._objects.pop(id_) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gl_initialize(self): """ Deal with compatibility; desktop does not have sprites enabled by default. ES has. """
if '.es' in gl.current_backend.__name__: pass # ES2: no action required else: # Desktop, enable sprites GL_VERTEX_PROGRAM_POINT_SIZE = 34370 GL_POINT_SPRITE = 34913 gl.glEnable(GL_VERTEX_PROGRAM_POINT_SIZE) gl.glEnable(GL_POINT_SP...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_shaders(self, vert, frag): """ This function takes care of setting the shading code and compiling+linking it into a working program object that is ready ...
self._linked = False # Create temporary shader objects vert_handle = gl.glCreateShader(gl.GL_VERTEX_SHADER) frag_handle = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) # For both vertex and fragment shader: set source, compile, check for code, handle, type_ in [(vert, vert_ha...
<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_error(self, error): """ Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this. """
error = str(error) # Nvidia # 0(7): error C1008: undefined variable "MV" m = re.match(r'(\d+)\((\d+)\)\s*:\s(.*)', error) if m: return int(m.group(2)), m.group(3) # ATI / Intel # ERROR: 0:131: '{' : syntax error parse error m = re.match(r'ERRO...
<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_error(self, code, errors, indentation=0): """Get error and show the faulty line + some context Other GLIR implementations may omit this. """
# Init results = [] lines = None if code is not None: lines = [line.strip() for line in code.split('\n')] for error in errors.split('\n'): # Strip; skip empy lines error = error.strip() if not error: continue ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_texture(self, name, value): """ Set a texture sampler. Value is the id of the texture to link. """
if not self._linked: raise RuntimeError('Cannot set uniform when program has no code') # Get handle for the uniform, first try cache handle = self._handles.get(name, -1) if handle < 0: if name in self._known_invalid: return handle = gl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_uniform(self, name, type_, value): """ Set a uniform value. Value is assumed to have been checked. """
if not self._linked: raise RuntimeError('Cannot set uniform when program has no code') # Get handle for the uniform, first try cache handle = self._handles.get(name, -1) count = 1 if handle < 0: if name in self._known_invalid: 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 set_attribute(self, name, type_, value): """ Set an attribute value. Value is assumed to have been checked. """
if not self._linked: raise RuntimeError('Cannot set attribute when program has no code') # Get handle for the attribute, first try cache handle = self._handles.get(name, -1) if handle < 0: if name in self._known_invalid: return handle ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_matrix_transform(transform): """ Simplify a transform to a single matrix transform, which makes it a lot faster to compute transformations. Raises a TypeE...
if isinstance(transform, ChainTransform): matrix = np.identity(4) for tr in transform.transforms: # We need to do the matrix multiplication manually because VisPy # somehow doesn't mutliply matrices if there is a perspective # component. The equation below looks ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def circular(adjacency_mat, directed=False): """Places all nodes on a single circle. Parameters adjacency_mat : matrix or sparse The graph adjacency matrix direc...
if issparse(adjacency_mat): adjacency_mat = adjacency_mat.tocoo() num_nodes = adjacency_mat.shape[0] t = np.linspace(0, 2 * np.pi, num_nodes, endpoint=False, dtype=np.float32) # Visual coordinate system is between 0 and 1, so generate a circle with # radius 0.5 and center it at the poin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_data(self, pos=None, symbol='o', size=10., edge_width=1., edge_width_rel=None, edge_color='black', face_color='white', scaling=False): """ Set the data u...
assert (isinstance(pos, np.ndarray) and pos.ndim == 2 and pos.shape[1] in (2, 3)) if (edge_width is not None) + (edge_width_rel is not None) != 1: raise ValueError('exactly one of edge_width and edge_width_rel ' 'must be non-None') if edg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hook_changed(self, hook_name, widget, new_data): """Handle a hook upate."""
if hook_name == 'song': self.song_changed(widget, new_data) elif hook_name == 'state': self.state_changed(widget, new_data) elif hook_name == 'elapsed_and_total': elapsed, total = new_data self.time_changed(widget, elapsed, total)
<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, func, **kw): "Update the signature of func with the data in self" func.__name__ = self.name func.__doc__ = getattr(self, 'doc', None) func.__dict__ = getattr(self, 'dict', {}) func.__defaults__ = getattr(self, 'defaults', ()) func.__kwdefaults__ = getattr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def make(self, src_templ, evaldict=None, addsource=False, **attrs): "Make a new function from a given template and update the signature" src = src_templ % vars(self) # expand name and signature evaldict = evaldict or {} mo = DEF.match(src) if mo is None: raise SyntaxE...
<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_scene_bounds(self, dim=None): """Get the total bounds based on the visuals present in the scene Parameters dim : int | None Dimension to return. Returns ...
# todo: handle sub-children # todo: handle transformations # Init bounds = [(np.inf, -np.inf), (np.inf, -np.inf), (np.inf, -np.inf)] # Get bounds of all children for ob in self.scene.children: if hasattr(ob, 'bounds'): for axis in (0, 1, 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 _array_clip_val(val): """Helper to turn val into array and clip between 0 and 1"""
val = np.array(val) if val.max() > 1 or val.min() < 0: logger.warning('value will be clipped between 0 and 1') val[...] = np.clip(val, 0, 1) return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend(self, colors): """Extend a ColorArray with new colors Parameters colors : instance of ColorArray The new colors. """
colors = ColorArray(colors) self._rgba = np.vstack((self._rgba, colors._rgba)) 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 rgba(self, val): """Set the color using an Nx4 array of RGBA floats"""
# Note: all other attribute sets get routed here! # This method is meant to do the heavy lifting of setting data rgba = _user_to_rgba(val, expand=False) if self._rgba is None: self._rgba = rgba # only on init else: self._rgba[:, :rgba.shape[1]] = rgba
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RGBA(self, val): """Set the color using an Nx4 array of RGBA uint8 values"""
# need to convert to normalized float val = np.atleast_1d(val).astype(np.float32) / 255 self.rgba = val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RGB(self, val): """Set the color using an Nx3 array of RGB uint8 values"""
# need to convert to normalized float val = np.atleast_1d(val).astype(np.float32) / 255. self.rgba = val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def viewbox_mouse_event(self, event): """ The ViewBox received a mouse event; update transform accordingly. Default implementation adjusts scale factor when scol...
BaseCamera.viewbox_mouse_event(self, event) if event.type == 'mouse_wheel': s = 1.1 ** - event.delta[1] self._scale_factor *= s if self._distance is not None: self._distance *= s self.view_changed()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_range(self, init): """ Reset the camera view using the known limits. """
if init and (self._scale_factor is not None): return # We don't have to set our scale factor # Get window size (and store factor now to sync with resizing) w, h = self._viewbox.size w, h = float(w), float(h) # Get range and translation for x and y x1, y1,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def viewbox_mouse_event(self, event): """ The viewbox received a mouse event; update transform accordingly. Parameters event : instance of Event The event. """
if event.handled or not self.interactive: return PerspectiveCamera.viewbox_mouse_event(self, event) if event.type == 'mouse_release': self._event_value = None # Reset elif event.type == 'mouse_press': event.handled = True elif event.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 _update_camera_pos(self): """ Set the camera position and orientation"""
# transform will be updated several times; do not update camera # transform until we are done. ch_em = self.events.transform_change with ch_em.blocker(self._update_transform): tr = self.transform tr.reset() up, forward, right = self._get_dim_vectors...
<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_interactive(self): """ Determine if the user requested interactive mode. """
# The Python interpreter sets sys.flags correctly, so use them! if sys.flags.interactive: return True # IPython does not set sys.flags when -i is specified, so first # check it if it is already imported. if '__IPYTHON__' not in dir(six.moves.builtins): r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, allow_interactive=True): """ Enter the native GUI event loop. Parameters allow_interactive : bool Is the application allowed to handle interactive ...
if allow_interactive and self.is_interactive(): inputhook.set_interactive(enabled=True, app=self) else: return self._backend._vispy_run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _use(self, backend_name=None): """Select a backend by name. See class docstring for details. """
# See if we're in a specific testing mode, if so DONT check to see # if it's a valid backend. If it isn't, it's a good thing we # get an error later because we should have decorated our test # with requires_application() test_name = os.getenv('_VISPY_TESTING_APP', 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 _get_mods(evt): """Helper to extract list of mods from event"""
mods = [] mods += [keys.CONTROL] if evt.ControlDown() else [] mods += [keys.ALT] if evt.AltDown() else [] mods += [keys.SHIFT] if evt.ShiftDown() else [] mods += [keys.META] if evt.MetaDown() else [] return mods
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_key(evt): """Helper to convert from wx keycode to vispy keycode"""
key = evt.GetKeyCode() if key in KEYMAP: return KEYMAP[key], '' if 97 <= key <= 122: key -= 32 if key >= 32 and key <= 127: return keys.Key(chr(key)), chr(key) else: return None, 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 is_child(self, node): """Check if a node is a child of the current node Parameters node : instance of Node The potential child. Returns ------- child : bool ...
if node in self.children: return True for c in self.children: if c.is_child(node): 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 scene_node(self): """The first ancestor of this node that is a SubScene instance, or self if no such node exists. """
if self._scene_node is None: from .subscene import SubScene p = self.parent while True: if isinstance(p, SubScene) or p is None: self._scene_node = p break p = p.parent if self._scene_node is...
<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): """ Emit an event to inform listeners that properties of this Node have changed. Also request a canvas update. """
self.events.update() c = getattr(self, 'canvas', None) if c is not None: c.update(node=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 parent_chain(self): """ Return the list of parents starting from this node. The chain ends at the first node with no parents. """
chain = [self] while True: try: parent = chain[-1].parent except Exception: break if parent is None: break chain.append(parent) return chain
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _describe_tree(self, prefix, with_transform): """Helper function to actuall construct the tree"""
extra = ': "%s"' % self.name if self.name is not None else '' if with_transform: extra += (' [%s]' % self.transform.__class__.__name__) output = '' if len(prefix) > 0: output += prefix[:-3] output += ' +--' output += '%s%s\n' % (self.__class_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def common_parent(self, node): """ Return the common parent of two entities If the entities have no common parent, return None. Parameters node : instance of Nod...
p1 = self.parent_chain() p2 = node.parent_chain() for p in p1: if p in p2: return p 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 node_path_to_child(self, node): """Return a list describing the path from this node to a child node If *node* is not a (grand)child of this node, then raise ...
if node is self: return [] # Go up from the child node as far as we can path1 = [node] child = node while child.parent is not None: child = child.parent path1.append(child) # Early exit if child is 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 node_path(self, node): """Return two lists describing the path from this node to another Parameters node : instance of Node The other node. Returns ------- p...
p1 = self.parent_chain() p2 = node.parent_chain() cp = None for p in p1: if p in p2: cp = p break if cp is None: raise RuntimeError("No single-path common parent between nodes %s " "and %s." %...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def node_path_transforms(self, node): """Return the list of transforms along the path to another node. The transforms are listed in reverse order, such that the ...
a, b = self.node_path(node) return ([n.transform for n in a[:-1]] + [n.transform.inverse for n in b])[::-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 readLine(self): """ The method that reads a line and processes it. """
# Read line line = self._f.readline().decode('ascii', 'ignore') if not line: raise EOFError() line = line.strip() if line.startswith('v '): # self._vertices.append( *self.readTuple(line) ) self._v.append(self.readTuple(line)) elif li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish(self): """ Converts gathere lists to numpy arrays and creates BaseMesh instance. """
self._vertices = np.array(self._vertices, 'float32') if self._faces: self._faces = np.array(self._faces, 'uint32') else: # Use vertices only self._vertices = np.array(self._v, 'float32') self._faces = None if self._normals: sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(cls, fname, vertices, faces, normals, texcoords, name='', reshape_faces=True): """ This classmethod is the entry point for writing mesh data to OBJ. Pa...
# Open file fmt = op.splitext(fname)[1].lower() if fmt not in ('.obj', '.gz'): raise ValueError('Filename must end with .obj or .gz, not "%s"' % (fmt,)) opener = open if fmt == '.obj' else gzip_open f = opener(fname, 'wb') try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeFace(self, val, what='f'): """ Write the face info to the net line. """
# OBJ counts from 1 val = [v + 1 for v in val] # Make string if self._hasValues and self._hasNormals: val = ' '.join(['%i/%i/%i' % (v, v, v) for v in val]) elif self._hasNormals: val = ' '.join(['%i//%i' % (v, v) for v in val]) elif self._hasValue...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeMesh(self, vertices, faces, normals, values, name='', reshape_faces=True): """ Write the given mesh instance. """
# Store properties self._hasNormals = normals is not None self._hasValues = values is not None self._hasFaces = faces is not None # Get faces and number of vertices if faces is None: faces = np.arange(len(vertices)) reshape_faces = 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 _fast_cross_3d(x, y): """Compute cross product between list of 3D vectors Much faster than np.cross() when the number of cross products becomes large (>500)....
assert x.ndim == 2 assert y.ndim == 2 assert x.shape[1] == 3 assert y.shape[1] == 3 assert (x.shape[0] == 1 or y.shape[0] == 1) or x.shape[0] == y.shape[0] if max([x.shape[0], y.shape[0]]) >= 500: return np.c_[x[:, 1] * y[:, 2] - x[:, 2] * y[:, 1], x[:, 2] * y[:, 0]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_normals(rr, tris): """Efficiently compute vertex normals for triangulated surface"""
# ensure highest precision for our summation/vectorization "trick" rr = rr.astype(np.float64) # first, compute triangle normals r1 = rr[tris[:, 0], :] r2 = rr[tris[:, 1], :] r3 = rr[tris[:, 2], :] tri_nn = _fast_cross_3d((r2 - r1), (r3 - r1)) # Triangle normals and areas size = n...
<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(self): """Parse the lines, and fill self.line_fields accordingly."""
for line in self.lines: # Parse the line field_defs = self.parse_line(line) fields = [] # Convert field parameters into Field objects for (kind, options) in field_defs: logger.debug("Creating field %s(%r)", kind, options) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_positions(cls, screen_width, line): """Compute the relative position of the fields on a given line. Args: screen_width (int): the width of the scree...
# First index left = 1 # Last index right = screen_width + 1 # Current 'flexible' field flexible = None # Compute the space to the left and to the right of the (optional) # flexible field. for field in line: if field.is_flexible(): ...
<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_to_screen(self, screen_width, screen): """Add the pattern to a screen. Also fills self.widgets. Args: screen_width (int): the width of the screen screen...
for lineno, fields in enumerate(self.line_fields): for left, field in self.compute_positions(screen_width, fields): logger.debug( "Adding field %s to screen %s at x=%d->%d, y=%d", field, screen.ref, left, left + field.width - 1, 1 + lineno, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_hooks(self, field): """Register a field on its target hooks."""
for hook, subhooks in field.register_hooks(): self.hooks[hook].append(field) self.subhooks[hook] |= set(subhooks)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hook_changed(self, hook, new_data): """Called whenever the data for a hook changed."""
for field in self.hooks[hook]: widget = self.widgets[field] field.hook_changed(hook, widget, new_data)
<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, pattern_txt): """Add a pattern to the list. Args: pattern_txt (str list): the pattern, as a list of lines. """
self.patterns[len(pattern_txt)] = pattern_txt low = 0 high = len(pattern_txt) - 1 while not pattern_txt[low]: low += 1 while not pattern_txt[high]: high -= 1 min_pattern = pattern_txt[low:high + 1] self.min_patterns[len(min_pattern)] =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _arcball(xy, wh): """Convert x,y coordinates to w,x,y,z Quaternion parameters Adapted from: linalg library Copyright (c) 2010-2015, Renaud Blanch <rndblnch a...
x, y = xy w, h = wh r = (w + h) / 2. x, y = -(2. * x - w) / r, (2. * y - h) / r h = np.sqrt(x*x + y*y) return (0., x/h, y/h, 0.) if h > 1. else (0., x, y, np.sqrt(1. - h*h))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def arg_to_array(func): """ Decorator to convert argument to array. Parameters func : function The function to decorate. Returns ------- func : function The deco...
def fn(self, arg, *args, **kwargs): """Function Parameters ---------- arg : array-like Argument to convert. *args : tuple Arguments. **kwargs : dict Keyword arguments. Returns ------- value : object ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def arg_to_vec4(func, self_, arg, *args, **kwargs): """ Decorator for converting argument to vec4 format suitable for 4x4 matrix multiplication. [x, y] => [[x, y...
if isinstance(arg, (tuple, list, np.ndarray)): arg = np.array(arg) flatten = arg.ndim == 1 arg = as_vec4(arg) ret = func(self_, arg, *args, **kwargs) if flatten and ret is not None: return ret.flatten() return ret elif hasattr(arg, '_transform_in'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roll(self): """ Increase the age of all items in the cache by 1. Items whose age is greater than self.max_age will be removed from the cache. """
rem = [] for key, item in self._cache.items(): if item[0] > self.max_age: rem.append(key) item[0] += 1 for key in rem: logger.debug("TransformCache remove: %s", key) del self._cache[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 histogram(self, data, bins=10, color='w', orientation='h'): """Calculate and show a histogram of data Parameters data : array-like Data to histogram. Current...
self._configure_2d() hist = scene.Histogram(data, bins, color, orientation) self.view.add(hist) self.view.camera.set_range() return hist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image(self, data, cmap='cubehelix', clim='auto', fg_color=None): """Show an image Parameters data : ndarray Should have shape (N, M), (N, M, 3) or (N, M, 4)....
self._configure_2d(fg_color) image = scene.Image(data, cmap=cmap, clim=clim) self.view.add(image) self.view.camera.aspect = 1 self.view.camera.set_range() return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mesh(self, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1.), fname=None, meshdata=None): """Show a 3D mesh Parameters ve...
self._configure_3d() if fname is not None: if not all(x is None for x in (vertices, faces, meshdata)): raise ValueError('vertices, faces, and meshdata must be None ' 'if fname is not None') vertices, faces = read_mesh(fname)[: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 plot(self, data, color='k', symbol=None, line_kind='-', width=1., marker_size=10., edge_color='k', face_color='b', edge_width=1., title=None, xlabel=None, yla...
self._configure_2d() line = scene.LinePlot(data, connect='strip', color=color, symbol=symbol, line_kind=line_kind, width=width, marker_size=marker_size, edge_color=edge_color, face_co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spectrogram(self, x, n_fft=256, step=None, fs=1., window='hann', color_scale='log', cmap='cubehelix', clim='auto'): """Calculate and show a spectrogram Param...
self._configure_2d() # XXX once we have axes, we should use "fft_freqs", too spec = scene.Spectrogram(x, n_fft, step, fs, window, color_scale, cmap, clim) self.view.add(spec) self.view.camera.set_range() return spec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def volume(self, vol, clim=None, method='mip', threshold=None, cmap='grays'): """Show a 3D volume Parameters vol : ndarray Volume to render. clim : tuple of two ...
self._configure_3d() volume = scene.Volume(vol, clim, method, threshold, cmap=cmap) self.view.add(volume) self.view.camera.set_range() return volume
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def surface(self, zdata, **kwargs): """Show a 3D surface plot. Extra keyword arguments are passed to `SurfacePlot()`. Parameters zdata : array-like A 2D array of...
self._configure_3d() surf = scene.SurfacePlot(z=zdata, **kwargs) self.view.add(surf) self.view.camera.set_range() return surf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colorbar(self, cmap, position="right", label="", clim=("", ""), border_width=0.0, border_color="black", **kwargs): """Show a ColorBar Parameters cmap : str |...
self._configure_2d() cbar = scene.ColorBarWidget(orientation=position, label_str=label, cmap=cmap, clim=clim, border_width=border_width, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redraw(self): """ Redraw the Vispy canvas """
if self._multiscat is not None: self._multiscat._update() self.vispy_widget.canvas.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self): """ Remove the layer artist from the visualization """
if self._multiscat is None: return self._multiscat.deallocate(self.id) self._multiscat = None self._viewer_state.remove_global_callback(self._update_scatter) self.state.remove_global_callback(self._update_scatter)
<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_valid(key, val, valid): """Helper to check valid options"""
if val not in valid: raise ValueError('%s must be one of %s, not "%s"' % (key, valid, val))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_args(x): """Convert to args representation"""
if not isinstance(x, (list, tuple, np.ndarray)): x = [x] return x
<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_conversion(key, valid_dict): """Check for existence of key in dict, return value or raise error"""
if key not in valid_dict and key not in valid_dict.values(): # Only show users the nice string values keys = [v for v in valid_dict.keys() if isinstance(v, string_types)] raise ValueError('value must be one of %s, not %s' % (keys, key)) return valid_dict[key] if key in valid_dict else k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'): """Read pixels from the currently selected buffer. Under most circumstances, this function ...
# Check whether the GL context is direct or remote context = get_current_canvas().context if context.shared.parser.is_remote(): raise RuntimeError('Cannot use read_pixels() with remote GLIR parser') finish() # noqa - finish first, also flushes GLIR commands type_dict = {'unsigned_byte...