text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Add a key. <END_TASK> <USER_TASK:> Description: def add_key(self, ref, mode="shared"): """ Add a key. (ref) Return key name or None on error """
if ref not in self.keys: response = self.request("client_add_key %s -%s" % (ref, mode)) if "success" not in response: return None self.keys.append(ref) return ref
<SYSTEM_TASK:> launch browser and virtual display, first of all to be launched <END_TASK> <USER_TASK:> Description: def launch(self): """launch browser and virtual display, first of all to be launched"""
try: # init virtual Display self.vbro = Display() self.vbro.start() logger.debug("virtual display launched") except Exception: raise exceptions.VBroException() try: self.browser = Browser(self.brow_name) logger.debug(f"browser {self.brow_name} launched") except Exception: raise exceptions.BrowserException( self.brow_name, "failed to launch") return True
<SYSTEM_TASK:> Create and connect to the LCDd server. <END_TASK> <USER_TASK:> Description: def _make_lcdproc( lcd_host, lcd_port, retry_config, charset=DEFAULT_LCDPROC_CHARSET, lcdd_debug=False): """Create and connect to the LCDd server. Args: lcd_host (str): the hostname to connect to lcd_prot (int): the port to connect to charset (str): the charset to use when sending messages to lcdproc lcdd_debug (bool): whether to enable full LCDd debug retry_attempts (int): the number of connection attempts retry_wait (int): the time to wait between connection attempts retry_backoff (int): the backoff for increasing inter-attempt delay Returns: lcdproc.server.Server """
class ServerSpawner(utils.AutoRetryCandidate): """Spawn the server, using auto-retry.""" @utils.auto_retry def connect(self): return lcdrunner.LcdProcServer( lcd_host, lcd_port, charset=charset, debug=lcdd_debug) spawner = ServerSpawner(retry_config=retry_config, logger=logger) try: return spawner.connect() except socket.error as e: logger.error('Unable to connect to lcdproc %s:%s : %r', lcd_host, lcd_port, e) raise SystemExit(1)
<SYSTEM_TASK:> Create a ScreenPatternList from a given pattern text. <END_TASK> <USER_TASK:> Description: def _make_patterns(patterns): """Create a ScreenPatternList from a given pattern text. Args: pattern_txt (str list): the patterns Returns: mpdlcd.display_pattern.ScreenPatternList: a list of patterns from the given entries. """
field_registry = display_fields.FieldRegistry() pattern_list = display_pattern.ScreenPatternList( field_registry=field_registry, ) for pattern in patterns: pattern_list.add(pattern.split('\n')) return pattern_list
<SYSTEM_TASK:> Read configuration from the given file. <END_TASK> <USER_TASK:> Description: def _read_config(filename): """Read configuration from the given file. Parsing is performed through the configparser library. Returns: dict: a flattened dict of (option_name, value), using defaults. """
parser = configparser.RawConfigParser() if filename and not parser.read(filename): sys.stderr.write("Unable to open configuration file %s. Use --config='' to disable this warning.\n" % filename) config = {} for section, defaults in BASE_CONFIG.items(): # Patterns are handled separately if section == 'patterns': continue for name, descr in defaults.items(): kind, default = descr if section in parser.sections() and name in parser.options(section): if kind == 'int': value = parser.getint(section, name) elif kind == 'float': value = parser.getfloat(section, name) elif kind == 'bool': value = parser.getboolean(section, name) else: value = parser.get(section, name) else: value = default config[name] = value if 'patterns' in parser.sections(): patterns = [parser.get('patterns', opt) for opt in parser.options('patterns')] else: patterns = DEFAULT_PATTERNS config['patterns'] = patterns return config
<SYSTEM_TASK:> Extract options values from a configparser, optparse pair. <END_TASK> <USER_TASK:> Description: def _extract_options(config, options, *args): """Extract options values from a configparser, optparse pair. Options given on command line take precedence over options read in the configuration file. Args: config (dict): option values read from a config file through configparser options (optparse.Options): optparse 'options' object containing options values from the command line *args (str tuple): name of the options to extract """
extract = {} for key in args: if key not in args: continue extract[key] = config[key] option = getattr(options, key, None) if option is not None: extract[key] = option return extract
<SYSTEM_TASK:> Set the render-buffer size and format <END_TASK> <USER_TASK:> Description: def resize(self, shape, format=None): """ Set the render-buffer size and format Parameters ---------- shape : tuple of integers New shape in yx order. A render buffer is always 2D. For symmetry with the texture class, a 3-element tuple can also be given, in which case the last dimension is ignored. format : {None, 'color', 'depth', 'stencil'} The buffer format. If None, the current format is maintained. If that is also None, the format will be set upon attaching it to a framebuffer. One can also specify the explicit enum: GL_RGB565, GL_RGBA4, GL_RGB5_A1, GL_DEPTH_COMPONENT16, or GL_STENCIL_INDEX8 """
if not self._resizeable: raise RuntimeError("RenderBuffer is not resizeable") # Check shape if not (isinstance(shape, tuple) and len(shape) in (2, 3)): raise ValueError('RenderBuffer shape must be a 2/3 element tuple') # Check format if format is None: format = self._format # Use current format (may be None) elif isinstance(format, int): pass # Do not check, maybe user needs desktop GL formats elif isinstance(format, string_types): if format not in ('color', 'depth', 'stencil'): raise ValueError('RenderBuffer format must be "color", "depth"' ' or "stencil", not %r' % format) else: raise ValueError('Invalid RenderBuffer format: %r' % format) # Store and send GLIR command self._shape = tuple(shape[:2]) self._format = format if self._format is not None: self._glir.command('SIZE', self._id, self._shape, self._format)
<SYSTEM_TASK:> Resize all attached buffers with the given shape <END_TASK> <USER_TASK:> Description: def resize(self, shape): """ Resize all attached buffers with the given shape Parameters ---------- shape : tuple of two integers New buffer shape (h, w), to be applied to all currently attached buffers. For buffers that are a texture, the number of color channels is preserved. """
# Check if not (isinstance(shape, tuple) and len(shape) == 2): raise ValueError('RenderBuffer shape must be a 2-element tuple') # Resize our buffers for buf in (self.color_buffer, self.depth_buffer, self.stencil_buffer): if buf is None: continue shape_ = shape if isinstance(buf, Texture2D): shape_ = shape + (self.color_buffer.shape[-1], ) buf.resize(shape_, buf.format)
<SYSTEM_TASK:> Set the data used to draw this visual. <END_TASK> <USER_TASK:> Description: def set_data(self, pos=None, color=None, width=None, connect=None): """ Set the data used to draw this visual. Parameters ---------- pos : array Array of shape (..., 2) or (..., 3) specifying vertex coordinates. color : Color, tuple, or array The color to use when drawing the line. If an array is given, it must be of shape (..., 4) and provide one rgba color per vertex. width: The width of the line in px. Line widths < 1 px will be rounded up to 1 px when using the 'gl' method. connect : str or array Determines which vertices are connected by lines. * "strip" causes the line to be drawn with each vertex connected to the next. * "segments" causes each pair of vertices to draw an independent line segment * int numpy arrays specify the exact set of segment pairs to connect. * bool numpy arrays specify which _adjacent_ pairs to connect. """
if pos is not None: self._bounds = None self._pos = pos self._changed['pos'] = True if color is not None: self._color = color self._changed['color'] = True if width is not None: self._width = width self._changed['width'] = True if connect is not None: self._connect = connect self._changed['connect'] = True self.update()
<SYSTEM_TASK:> Get the bounds <END_TASK> <USER_TASK:> Description: def _compute_bounds(self, axis, view): """Get the bounds Parameters ---------- mode : str Describes the type of boundary requested. Can be "visual", "data", or "mouse". axis : 0, 1, 2 The axis along which to measure the bounding values, in x-y-z order. """
# Can and should we calculate bounds? if (self._bounds is None) and self._pos is not None: pos = self._pos self._bounds = [(pos[:, d].min(), pos[:, d].max()) for d in range(pos.shape[1])] # Return what we can if self._bounds is None: return else: if axis < len(self._bounds): return self._bounds[axis] else: return (0, 0)
<SYSTEM_TASK:> This actually calculates the kerning + advance <END_TASK> <USER_TASK:> Description: def _get_k_p_a(font, left, right): """This actually calculates the kerning + advance"""
# http://lists.apple.com/archives/coretext-dev/2010/Dec/msg00020.html # 1) set up a CTTypesetter chars = left + right args = [None, 1, cf.kCFTypeDictionaryKeyCallBacks, cf.kCFTypeDictionaryValueCallBacks] attributes = cf.CFDictionaryCreateMutable(*args) cf.CFDictionaryAddValue(attributes, kCTFontAttributeName, font) string = cf.CFAttributedStringCreate(None, CFSTR(chars), attributes) typesetter = ct.CTTypesetterCreateWithAttributedString(string) cf.CFRelease(string) cf.CFRelease(attributes) # 2) extract a CTLine from it range = CFRange(0, 1) line = ct.CTTypesetterCreateLine(typesetter, range) # 3) use CTLineGetOffsetForStringIndex to get the character positions offset = ct.CTLineGetOffsetForStringIndex(line, 1, None) cf.CFRelease(line) cf.CFRelease(typesetter) return offset
<SYSTEM_TASK:> Convert numpy array to PNG byte array. <END_TASK> <USER_TASK:> Description: def _make_png(data, level=6): """Convert numpy array to PNG byte array. Parameters ---------- data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint8) level : int https://docs.python.org/2/library/zlib.html#zlib.compress An integer from 0 to 9 controlling the level of compression: * 1 is fastest and produces the least compression, * 9 is slowest and produces the most. * 0 is no compression. The default value is 6. Returns ------- png : array PNG formatted array """
# Eventually we might want to use ext/png.py for this, but this # routine *should* be faster b/c it's speacialized for our use case def mkchunk(data, name): if isinstance(data, np.ndarray): size = data.nbytes else: size = len(data) chunk = np.empty(size + 12, dtype=np.ubyte) chunk.data[0:4] = np.array(size, '>u4').tostring() chunk.data[4:8] = name.encode('ASCII') chunk.data[8:8 + size] = data # and-ing may not be necessary, but is done for safety: # https://docs.python.org/3/library/zlib.html#zlib.crc32 chunk.data[-4:] = np.array(zlib.crc32(chunk[4:-4]) & 0xffffffff, '>u4').tostring() return chunk if data.dtype != np.ubyte: raise TypeError('data.dtype must be np.ubyte (np.uint8)') dim = data.shape[2] # Dimension if dim not in (3, 4): raise TypeError('data.shape[2] must be in (3, 4)') # www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.IHDR if dim == 4: ctyp = 0b0110 # RGBA else: ctyp = 0b0010 # RGB # www.libpng.org/pub/png/spec/1.2/PNG-Structure.html header = b'\x89PNG\x0d\x0a\x1a\x0a' # header h, w = data.shape[:2] depth = data.itemsize * 8 ihdr = struct.pack('!IIBBBBB', w, h, depth, ctyp, 0, 0, 0) c1 = mkchunk(ihdr, 'IHDR') # www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.IDAT # insert filter byte at each scanline idat = np.empty((h, w * dim + 1), dtype=np.ubyte) idat[:, 1:] = data.reshape(h, w * dim) idat[:, 0] = 0 comp_data = zlib.compress(idat, level) c2 = mkchunk(comp_data, 'IDAT') c3 = mkchunk(np.empty((0,), dtype=np.ubyte), 'IEND') # concatenate lh = len(header) png = np.empty(lh + c1.nbytes + c2.nbytes + c3.nbytes, dtype=np.ubyte) png.data[:lh] = header p = lh for chunk in (c1, c2, c3): png[p:p + len(chunk)] = chunk p += chunk.nbytes return png
<SYSTEM_TASK:> Read a PNG file to RGB8 or RGBA8 <END_TASK> <USER_TASK:> Description: def read_png(filename): """Read a PNG file to RGB8 or RGBA8 Unlike imread, this requires no external dependencies. Parameters ---------- filename : str File to read. Returns ------- data : array Image data. See also -------- write_png, imread, imsave """
x = Reader(filename) try: alpha = x.asDirect()[3]['alpha'] if alpha: y = x.asRGBA8()[2] n = 4 else: y = x.asRGB8()[2] n = 3 y = np.array([yy for yy in y], np.uint8) finally: x.file.close() y.shape = (y.shape[0], y.shape[1] // n, n) return y
<SYSTEM_TASK:> Write a PNG file <END_TASK> <USER_TASK:> Description: def write_png(filename, data): """Write a PNG file Unlike imsave, this requires no external dependencies. Parameters ---------- filename : str File to save to. data : array Image data. See also -------- read_png, imread, imsave """
data = np.asarray(data) if not data.ndim == 3 and data.shape[-1] in (3, 4): raise ValueError('data must be a 3D array with last dimension 3 or 4') with open(filename, 'wb') as f: f.write(_make_png(data))
<SYSTEM_TASK:> Read image data from disk <END_TASK> <USER_TASK:> Description: def imread(filename, format=None): """Read image data from disk Requires imageio or PIL. Parameters ---------- filename : str Filename to read. format : str | None Format of the file. If None, it will be inferred from the filename. Returns ------- data : array Image data. See also -------- imsave, read_png, write_png """
imageio, PIL = _check_img_lib() if imageio is not None: return imageio.imread(filename, format) elif PIL is not None: im = PIL.Image.open(filename) if im.mode == 'P': im = im.convert() # Make numpy array a = np.asarray(im) if len(a.shape) == 0: raise MemoryError("Too little memory to convert PIL image to " "array") return a else: raise RuntimeError("imread requires the imageio or PIL package.")
<SYSTEM_TASK:> Save image data to disk <END_TASK> <USER_TASK:> Description: def imsave(filename, im, format=None): """Save image data to disk Requires imageio or PIL. Parameters ---------- filename : str Filename to write. im : array Image data. format : str | None Format of the file. If None, it will be inferred from the filename. See also -------- imread, read_png, write_png """
# Import imageio or PIL imageio, PIL = _check_img_lib() if imageio is not None: return imageio.imsave(filename, im, format) elif PIL is not None: pim = PIL.Image.fromarray(im) pim.save(filename, format) else: raise RuntimeError("imsave requires the imageio or PIL package.")
<SYSTEM_TASK:> Utility to search for imageio or PIL <END_TASK> <USER_TASK:> Description: def _check_img_lib(): """Utility to search for imageio or PIL"""
# Import imageio or PIL imageio = PIL = None try: import imageio except ImportError: try: import PIL.Image except ImportError: pass return imageio, PIL
<SYSTEM_TASK:> Function decorator displaying the function execution time <END_TASK> <USER_TASK:> Description: def timer(logger=None, level=logging.INFO, fmt="function %(function_name)s execution time: %(execution_time).3f", *func_or_func_args, **timer_kwargs): """ Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor. """
# store Timer kwargs in local variable so the namespace isn't polluted # by different level args and kwargs def wrapped_f(f): @functools.wraps(f) def wrapped(*args, **kwargs): with Timer(**timer_kwargs) as t: out = f(*args, **kwargs) context = { 'function_name': f.__name__, 'execution_time': t.elapsed, } if logger: logger.log( level, fmt % context, extra=context) else: print(fmt % context) return out return wrapped if (len(func_or_func_args) == 1 and isinstance(func_or_func_args[0], collections.Callable)): return wrapped_f(func_or_func_args[0]) else: return wrapped_f
<SYSTEM_TASK:> Convert a given matplotlib figure to vispy <END_TASK> <USER_TASK:> Description: def _mpl_to_vispy(fig): """Convert a given matplotlib figure to vispy This function is experimental and subject to change! Requires matplotlib and mplexporter. Parameters ---------- fig : instance of matplotlib Figure The populated figure to display. Returns ------- canvas : instance of Canvas The resulting vispy Canvas. """
renderer = VispyRenderer() exporter = Exporter(renderer) with warnings.catch_warnings(record=True): # py3k mpl warning exporter.run(fig) renderer._vispy_done() return renderer.canvas
<SYSTEM_TASK:> Show current figures using vispy <END_TASK> <USER_TASK:> Description: def show(block=False): """Show current figures using vispy Parameters ---------- block : bool If True, blocking mode will be used. If False, then non-blocking / interactive mode will be used. Returns ------- canvases : list List of the vispy canvases that were created. """
if not has_matplotlib(): raise ImportError('Requires matplotlib version >= 1.2') cs = [_mpl_to_vispy(plt.figure(ii)) for ii in plt.get_fignums()] if block and len(cs) > 0: cs[0].app.run() return cs
<SYSTEM_TASK:> Helper to get the parent axes of a given mplobj <END_TASK> <USER_TASK:> Description: def _mpl_ax_to(self, mplobj, output='vb'): """Helper to get the parent axes of a given mplobj"""
for ax in self._axs.values(): if ax['ax'] is mplobj.axes: return ax[output] raise RuntimeError('Parent axes could not be found!')
<SYSTEM_TASK:> Place the graph nodes at random places. <END_TASK> <USER_TASK:> Description: def random(adjacency_mat, directed=False, random_state=None): """ Place the graph nodes at random places. Parameters ---------- adjacency_mat : matrix or sparse The graph adjacency matrix directed : bool Whether the graph is directed. If this is True, is will also generate the vertices for arrows, which can be passed to an ArrowVisual. random_state : instance of RandomState | int | None Random state to use. Can be None to use ``np.random``. Yields ------ (node_vertices, line_vertices, arrow_vertices) : tuple Yields the node and line vertices in a tuple. This layout only yields a single time, and has no builtin animation """
if random_state is None: random_state = np.random elif not isinstance(random_state, np.random.RandomState): random_state = np.random.RandomState(random_state) if issparse(adjacency_mat): adjacency_mat = adjacency_mat.tocoo() # Randomly place nodes, visual coordinate system is between 0 and 1 num_nodes = adjacency_mat.shape[0] node_coords = random_state.rand(num_nodes, 2) line_vertices, arrows = _straight_line_vertices(adjacency_mat, node_coords, directed) yield node_coords, line_vertices, arrows
<SYSTEM_TASK:> The position of this event in the local coordinate system of the <END_TASK> <USER_TASK:> Description: def pos(self): """ The position of this event in the local coordinate system of the visual. """
if self._pos is None: tr = self.visual.get_transform('canvas', 'visual') self._pos = tr.map(self.mouse_event.pos) return self._pos
<SYSTEM_TASK:> The mouse event immediately prior to this one. This <END_TASK> <USER_TASK:> Description: def last_event(self): """ The mouse event immediately prior to this one. This property is None when no mouse buttons are pressed. """
if self.mouse_event.last_event is None: return None ev = self.copy() ev.mouse_event = self.mouse_event.last_event return ev
<SYSTEM_TASK:> The mouse press event that initiated a mouse drag, if any. <END_TASK> <USER_TASK:> Description: def press_event(self): """ The mouse press event that initiated a mouse drag, if any. """
if self.mouse_event.press_event is None: return None ev = self.copy() ev.mouse_event = self.mouse_event.press_event return ev
<SYSTEM_TASK:> Get lowercase string representation of enum. <END_TASK> <USER_TASK:> Description: def check_enum(enum, name=None, valid=None): """ Get lowercase string representation of enum. """
name = name or 'enum' # Try to convert res = None if isinstance(enum, int): if hasattr(enum, 'name') and enum.name.startswith('GL_'): res = enum.name[3:].lower() elif isinstance(enum, string_types): res = enum.lower() # Check if res is None: raise ValueError('Could not determine string represenatation for' 'enum %r' % enum) elif valid and res not in valid: raise ValueError('Value of %s must be one of %r, not %r' % (name, valid, enum)) return res
<SYSTEM_TASK:> Draw a 2D texture to the current viewport <END_TASK> <USER_TASK:> Description: def draw_texture(tex): """Draw a 2D texture to the current viewport Parameters ---------- tex : instance of Texture2D The texture to draw. """
from .program import Program program = Program(vert_draw, frag_draw) program['u_texture'] = tex program['a_position'] = [[-1., -1.], [-1., 1.], [1., -1.], [1., 1.]] program['a_texcoord'] = [[0., 1.], [0., 0.], [1., 1.], [1., 0.]] program.draw('triangle_strip')
<SYSTEM_TASK:> Match pattern against the output of func, passing the results as <END_TASK> <USER_TASK:> Description: def _get_dpi_from(cmd, pattern, func): """Match pattern against the output of func, passing the results as floats to func. If anything fails, return None. """
try: out, _ = run_subprocess([cmd]) except (OSError, CalledProcessError): pass else: match = re.search(pattern, out) if match: return func(*map(float, match.groups()))
<SYSTEM_TASK:> Calculate a size <END_TASK> <USER_TASK:> Description: def calc_size(rect, orientation): """Calculate a size Parameters ---------- rect : rectangle The rectangle. orientation : str Either "bottom" or "top". """
(total_halfx, total_halfy) = rect.center if orientation in ["bottom", "top"]: (total_major_axis, total_minor_axis) = (total_halfx, total_halfy) else: (total_major_axis, total_minor_axis) = (total_halfy, total_halfx) major_axis = total_major_axis * (1.0 - ColorBarWidget.major_axis_padding) minor_axis = major_axis * ColorBarWidget.minor_axis_ratio # if the minor axis is "leaking" from the padding, then clamp minor_axis = np.minimum(minor_axis, total_minor_axis * (1.0 - ColorBarWidget.minor_axis_padding)) return (major_axis, minor_axis)
<SYSTEM_TASK:> Try to reduce dtype up to a given level when it is possible <END_TASK> <USER_TASK:> Description: def dtype_reduce(dtype, level=0, depth=0): """ Try to reduce dtype up to a given level when it is possible dtype = [ ('vertex', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('normal', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('color', [('r', 'f4'), ('g', 'f4'), ('b', 'f4'), ('a', 'f4')])] level 0: ['color,vertex,normal,', 10, 'float32'] level 1: [['color', 4, 'float32'] ['normal', 3, 'float32'] ['vertex', 3, 'float32']] """
dtype = np.dtype(dtype) fields = dtype.fields # No fields if fields is None: if len(dtype.shape): count = reduce(mul, dtype.shape) else: count = 1 # size = dtype.itemsize / count if dtype.subdtype: name = str(dtype.subdtype[0]) else: name = str(dtype) return ['', count, name] else: items = [] name = '' # Get reduced fields for key, value in fields.items(): l = dtype_reduce(value[0], level, depth + 1) if type(l[0]) is str: items.append([key, l[1], l[2]]) else: items.append(l) name += key + ',' # Check if we can reduce item list ctype = None count = 0 for i, item in enumerate(items): # One item is a list, we cannot reduce if type(item[0]) is not str: return items else: if i == 0: ctype = item[2] count += item[1] else: if item[2] != ctype: return items count += item[1] if depth >= level: return [name, count, ctype] else: return items
<SYSTEM_TASK:> Create a sphere <END_TASK> <USER_TASK:> Description: def create_sphere(rows=10, cols=10, depth=10, radius=1.0, offset=True, subdivisions=3, method='latitude'): """Create a sphere Parameters ---------- rows : int Number of rows (for method='latitude' and 'cube'). cols : int Number of columns (for method='latitude' and 'cube'). depth : int Number of depth segments (for method='cube'). radius : float Sphere radius. offset : bool Rotate each row by half a column (for method='latitude'). subdivisions : int Number of subdivisions to perform (for method='ico') method : str Method for generating sphere. Accepts 'latitude' for latitude- longitude, 'ico' for icosahedron, and 'cube' for cube based tessellation. Returns ------- sphere : MeshData Vertices and faces computed for a spherical surface. """
if method == 'latitude': return _latitude(rows, cols, radius, offset) elif method == 'ico': return _ico(radius, subdivisions) elif method == 'cube': return _cube(rows, cols, depth, radius) else: raise Exception("Invalid method. Accepts: 'latitude', 'ico', 'cube'")
<SYSTEM_TASK:> Create a cylinder <END_TASK> <USER_TASK:> Description: def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False): """Create a cylinder Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : tuple of float Cylinder radii. length : float Length of the cylinder. offset : bool Rotate each row by half a column. Returns ------- cylinder : MeshData Vertices and faces computed for a cylindrical surface. """
verts = np.empty((rows+1, cols, 3), dtype=np.float32) if isinstance(radius, int): radius = [radius, radius] # convert to list # compute vertices th = np.linspace(2 * np.pi, 0, cols).reshape(1, cols) # radius as a function of z r = np.linspace(radius[0], radius[1], num=rows+1, endpoint=True).reshape(rows+1, 1) verts[..., 2] = np.linspace(0, length, num=rows+1, endpoint=True).reshape(rows+1, 1) # z if offset: # rotate each row by 1/2 column th = th + ((np.pi / cols) * np.arange(rows+1).reshape(rows+1, 1)) verts[..., 0] = r * np.cos(th) # x = r cos(th) verts[..., 1] = r * np.sin(th) # y = r sin(th) # just reshape: no redundant vertices... verts = verts.reshape((rows+1)*cols, 3) # compute faces faces = np.empty((rows*cols*2, 3), dtype=np.uint32) rowtemplate1 = (((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]])) rowtemplate2 = (((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]])) for row in range(rows): start = row * cols * 2 faces[start:start+cols] = rowtemplate1 + row * cols faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols return MeshData(vertices=verts, faces=faces)
<SYSTEM_TASK:> Create a 3D arrow using a cylinder plus cone <END_TASK> <USER_TASK:> Description: def create_arrow(rows, cols, radius=0.1, length=1.0, cone_radius=None, cone_length=None): """Create a 3D arrow using a cylinder plus cone Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : float Base cylinder radius. length : float Length of the arrow. cone_radius : float Radius of the cone base. If None, then this defaults to 2x the cylinder radius. cone_length : float Length of the cone. If None, then this defaults to 1/3 of the arrow length. Returns ------- arrow : MeshData Vertices and faces computed for a cone surface. """
# create the cylinder md_cyl = None if cone_radius is None: cone_radius = radius*2.0 if cone_length is None: con_L = length/3.0 cyl_L = length*2.0/3.0 else: cyl_L = max(0, length - cone_length) con_L = min(cone_length, length) if cyl_L != 0: md_cyl = create_cylinder(rows, cols, radius=[radius, radius], length=cyl_L) # create the cone md_con = create_cone(cols, radius=cone_radius, length=con_L) verts = md_con.get_vertices() nbr_verts_con = verts.size//3 faces = md_con.get_faces() if md_cyl is not None: trans = np.array([[0.0, 0.0, cyl_L]]) verts = np.vstack((verts+trans, md_cyl.get_vertices())) faces = np.vstack((faces, md_cyl.get_faces()+nbr_verts_con)) return MeshData(vertices=verts, faces=faces)
<SYSTEM_TASK:> Generate the vertices for straight lines between nodes. <END_TASK> <USER_TASK:> Description: def _straight_line_vertices(adjacency_mat, node_coords, directed=False): """ Generate the vertices for straight lines between nodes. If it is a directed graph, it also generates the vertices which can be passed to an :class:`ArrowVisual`. Parameters ---------- adjacency_mat : array The adjacency matrix of the graph node_coords : array The current coordinates of all nodes in the graph directed : bool Wether the graph is directed. If this is true it will also generate the vertices for arrows which can be passed to :class:`ArrowVisual`. Returns ------- vertices : tuple Returns a tuple containing containing (`line_vertices`, `arrow_vertices`) """
if not issparse(adjacency_mat): adjacency_mat = np.asarray(adjacency_mat, float) if (adjacency_mat.ndim != 2 or adjacency_mat.shape[0] != adjacency_mat.shape[1]): raise ValueError("Adjacency matrix should be square.") arrow_vertices = np.array([]) edges = _get_edges(adjacency_mat) line_vertices = node_coords[edges.ravel()] if directed: arrows = np.array(list(_get_directed_edges(adjacency_mat))) arrow_vertices = node_coords[arrows.ravel()] arrow_vertices = arrow_vertices.reshape((len(arrow_vertices)/2, 4)) return line_vertices, arrow_vertices
<SYSTEM_TASK:> Factory function for creating new cameras using a string name. <END_TASK> <USER_TASK:> Description: def make_camera(cam_type, *args, **kwargs): """ Factory function for creating new cameras using a string name. Parameters ---------- cam_type : str May be one of: * 'panzoom' : Creates :class:`PanZoomCamera` * 'turntable' : Creates :class:`TurntableCamera` * None : Creates :class:`Camera` Notes ----- All extra arguments are passed to the __init__ method of the selected Camera class. """
cam_types = {None: BaseCamera} for camType in (BaseCamera, PanZoomCamera, PerspectiveCamera, TurntableCamera, FlyCamera, ArcballCamera): cam_types[camType.__name__[:-6].lower()] = camType try: return cam_types[cam_type](*args, **kwargs) except KeyError: raise KeyError('Unknown camera type "%s". Options are: %s' % (cam_type, cam_types.keys()))
<SYSTEM_TASK:> Set the position of the datapoints <END_TASK> <USER_TASK:> Description: def set_data_values(self, label, x, y, z): """ Set the position of the datapoints """
# TODO: avoid re-allocating an array every time self.layers[label]['data'] = np.array([x, y, z]).transpose() self._update()
<SYSTEM_TASK:> Computes the parameterization of a parametric surface <END_TASK> <USER_TASK:> Description: def surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0, vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0): """ Computes the parameterization of a parametric surface func: function(u,v) Parametric function used to build the surface """
vtype = [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3)] itype = np.uint32 # umin, umax, ucount = 0, 2*np.pi, 64 # vmin, vmax, vcount = 0, 2*np.pi, 64 vcount += 1 ucount += 1 n = vcount * ucount Un = np.repeat(np.linspace(0, 1, ucount, endpoint=True), vcount) Vn = np.tile(np.linspace(0, 1, vcount, endpoint=True), ucount) U = umin + Un * (umax - umin) V = vmin + Vn * (vmax - vmin) vertices = np.zeros(n, dtype=vtype) for i, (u, v) in enumerate(zip(U, V)): vertices["position"][i] = func(u, v) vertices["texcoord"][:, 0] = Un * urepeat vertices["texcoord"][:, 1] = Vn * vrepeat indices = [] for i in range(ucount - 1): for j in range(vcount - 1): indices.append(i * (vcount) + j) indices.append(i * (vcount) + j + 1) indices.append(i * (vcount) + j + vcount + 1) indices.append(i * (vcount) + j + vcount) indices.append(i * (vcount) + j + vcount + 1) indices.append(i * (vcount) + j) indices = np.array(indices, dtype=itype) vertices["normal"] = normals(vertices["position"], indices.reshape(len(indices) / 3, 3)) return vertices, indices
<SYSTEM_TASK:> New program was added to the multiprogram; update items in the <END_TASK> <USER_TASK:> Description: def _new_program(self, p): """New program was added to the multiprogram; update items in the shader. """
for k, v in self._set_items.items(): getattr(p, self._shader)[k] = v
<SYSTEM_TASK:> Attach this tranform to a canvas <END_TASK> <USER_TASK:> Description: def attach(self, canvas): """Attach this tranform to a canvas Parameters ---------- canvas : instance of Canvas The canvas. """
self._canvas = canvas canvas.events.resize.connect(self.on_resize) canvas.events.mouse_wheel.connect(self.on_mouse_wheel) canvas.events.mouse_move.connect(self.on_mouse_move)
<SYSTEM_TASK:> Depth of the smallest HEALPix cells found in the MOC instance. <END_TASK> <USER_TASK:> Description: def max_order(self): """ Depth of the smallest HEALPix cells found in the MOC instance. """
# TODO: cache value combo = int(0) for iv in self._interval_set._intervals: combo |= iv[0] | iv[1] ret = AbstractMOC.HPY_MAX_NORDER - (utils.number_trailing_zeros(combo) // 2) if ret < 0: ret = 0 return ret
<SYSTEM_TASK:> Intersection between the MOC instance and other MOCs. <END_TASK> <USER_TASK:> Description: def intersection(self, another_moc, *args): """ Intersection between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the intersection with self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the intersection with. Returns ------- result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC` The resulting MOC. """
interval_set = self._interval_set.intersection(another_moc._interval_set) for moc in args: interval_set = interval_set.intersection(moc._interval_set) return self.__class__(interval_set)
<SYSTEM_TASK:> Union between the MOC instance and other MOCs. <END_TASK> <USER_TASK:> Description: def union(self, another_moc, *args): """ Union between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the union with self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the union with. Returns ------- result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC` The resulting MOC. """
interval_set = self._interval_set.union(another_moc._interval_set) for moc in args: interval_set = interval_set.union(moc._interval_set) return self.__class__(interval_set)
<SYSTEM_TASK:> Difference between the MOC instance and other MOCs. <END_TASK> <USER_TASK:> Description: def difference(self, another_moc, *args): """ Difference between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used that will be substracted to self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the difference with. Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC. """
interval_set = self._interval_set.difference(another_moc._interval_set) for moc in args: interval_set = interval_set.difference(moc._interval_set) return self.__class__(interval_set)
<SYSTEM_TASK:> Returns all the pixels neighbours of ``ipix`` <END_TASK> <USER_TASK:> Description: def _neighbour_pixels(hp, ipix): """ Returns all the pixels neighbours of ``ipix`` """
neigh_ipix = np.unique(hp.neighbours(ipix).ravel()) # Remove negative pixel values returned by `~astropy_healpix.HEALPix.neighbours` return neigh_ipix[np.where(neigh_ipix >= 0)]
<SYSTEM_TASK:> Creates a MOC from a numpy array representing the HEALPix cells. <END_TASK> <USER_TASK:> Description: def from_cells(cls, cells): """ Creates a MOC from a numpy array representing the HEALPix cells. Parameters ---------- cells : `numpy.ndarray` Must be a numpy structured array (See https://docs.scipy.org/doc/numpy-1.15.0/user/basics.rec.html). The structure of a cell contains 3 attributes: - A `ipix` value being a np.uint64 - A `depth` value being a np.uint32 - A `fully_covered` flag bit stored in a np.uint8 Returns ------- moc : `~mocpy.moc.MOC` The MOC. """
shift = (AbstractMOC.HPY_MAX_NORDER - cells["depth"]) << 1 p1 = cells["ipix"] p2 = cells["ipix"] + 1 intervals = np.vstack((p1 << shift, p2 << shift)).T return cls(IntervalSet(intervals))
<SYSTEM_TASK:> Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth. <END_TASK> <USER_TASK:> Description: def from_json(cls, json_moc): """ Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth. Parameters ---------- json_moc : dict(str : [int] A dictionary of HEALPix cell arrays indexed by their depth. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` the MOC. """
intervals = np.array([]) for order, pix_l in json_moc.items(): if len(pix_l) == 0: continue pix = np.array(pix_l) p1 = pix p2 = pix + 1 shift = 2 * (AbstractMOC.HPY_MAX_NORDER - int(order)) itv = np.vstack((p1 << shift, p2 << shift)).T if intervals.size == 0: intervals = itv else: intervals = np.vstack((intervals, itv)) return cls(IntervalSet(intervals))
<SYSTEM_TASK:> Loads a MOC from a FITS file. <END_TASK> <USER_TASK:> Description: def from_fits(cls, filename): """ Loads a MOC from a FITS file. The specified FITS file must store the MOC (i.e. the list of HEALPix cells it contains) in a binary HDU table. Parameters ---------- filename : str The path to the FITS file. Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC. """
table = Table.read(filename) intervals = np.vstack((table['UNIQ'], table['UNIQ']+1)).T nuniq_interval_set = IntervalSet(intervals) interval_set = IntervalSet.from_nuniq_interval_set(nuniq_interval_set) return cls(interval_set)
<SYSTEM_TASK:> Serializes a MOC to the JSON format. <END_TASK> <USER_TASK:> Description: def _to_json(uniq): """ Serializes a MOC to the JSON format. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result_json : {str : [int]} A dictionary of HEALPix cell lists indexed by their depth. """
result_json = {} depth, ipix = utils.uniq2orderipix(uniq) min_depth = np.min(depth[0]) max_depth = np.max(depth[-1]) for d in range(min_depth, max_depth+1): pix_index = np.where(depth == d)[0] if pix_index.size: # there are pixels belonging to the current order ipix_depth = ipix[pix_index] result_json[str(d)] = ipix_depth.tolist() return result_json
<SYSTEM_TASK:> Serializes a MOC to the STRING format. <END_TASK> <USER_TASK:> Description: def _to_str(uniq): """ Serializes a MOC to the STRING format. HEALPix cells are separated by a comma. The HEALPix cell at order 0 and number 10 is encoded by the string: "0/10", the first digit representing the depth and the second the HEALPix cell number for this depth. HEALPix cells next to each other within a specific depth can be expressed as a range and therefore written like that: "12/10-150". This encodes the list of HEALPix cells from 10 to 150 at the depth 12. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result : str The serialized MOC. """
def write_cells(serial, a, b, sep=''): if a == b: serial += '{0}{1}'.format(a, sep) else: serial += '{0}-{1}{2}'.format(a, b, sep) return serial res = '' if uniq.size == 0: return res depth, ipixels = utils.uniq2orderipix(uniq) min_depth = np.min(depth[0]) max_depth = np.max(depth[-1]) for d in range(min_depth, max_depth+1): pix_index = np.where(depth == d)[0] if pix_index.size > 0: # Serialize the depth followed by a slash res += '{0}/'.format(d) # Retrieve the pixel(s) for this depth ipix_depth = ipixels[pix_index] if ipix_depth.size == 1: # If there is only one pixel we serialize it and # go to the next depth res = write_cells(res, ipix_depth[0], ipix_depth[0]) else: # Sort them in case there are several ipix_depth = np.sort(ipix_depth) beg_range = ipix_depth[0] last_range = beg_range # Loop over the sorted pixels by tracking the lower bound of # the current range and the last pixel. for ipix in ipix_depth[1:]: # If the current pixel does not follow the previous one # then we can end a range and serializes it if ipix > last_range + 1: res = write_cells(res, beg_range, last_range, sep=',') # The current pixel is the beginning of a new range beg_range = ipix last_range = ipix # Write the last range res = write_cells(res, beg_range, last_range) # Add a ' ' separator before writing serializing the pixels of the next depth res += ' ' # Remove the last ' ' character res = res[:-1] return res
<SYSTEM_TASK:> Serializes a MOC to the FITS format. <END_TASK> <USER_TASK:> Description: def _to_fits(self, uniq, optional_kw_dict=None): """ Serializes a MOC to the FITS format. Parameters ---------- uniq : `numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. optional_kw_dict : dict Optional keywords arguments added to the FITS header. Returns ------- thdulist : `astropy.io.fits.HDUList` The list of HDU tables. """
depth = self.max_order if depth <= 13: fits_format = '1J' else: fits_format = '1K' tbhdu = fits.BinTableHDU.from_columns( fits.ColDefs([ fits.Column(name='UNIQ', format=fits_format, array=uniq) ])) tbhdu.header['PIXTYPE'] = 'HEALPIX' tbhdu.header['ORDERING'] = 'NUNIQ' tbhdu.header.update(self._fits_header_keywords) tbhdu.header['MOCORDER'] = depth tbhdu.header['MOCTOOL'] = 'MOCPy' if optional_kw_dict: for key in optional_kw_dict: tbhdu.header[key] = optional_kw_dict[key] thdulist = fits.HDUList([fits.PrimaryHDU(), tbhdu]) return thdulist
<SYSTEM_TASK:> Serializes the MOC into a specific format. <END_TASK> <USER_TASK:> Description: def serialize(self, format='fits', optional_kw_dict=None): """ Serializes the MOC into a specific format. Possible formats are FITS, JSON and STRING Parameters ---------- format : str 'fits' by default. The other possible choice is 'json' or 'str'. optional_kw_dict : dict Optional keywords arguments added to the FITS header. Only used if ``format`` equals to 'fits'. Returns ------- result : `astropy.io.fits.HDUList` or JSON dictionary The result of the serialization. """
formats = ('fits', 'json', 'str') if format not in formats: raise ValueError('format should be one of %s' % (str(formats))) uniq_l = [] for uniq in self._uniq_pixels_iterator(): uniq_l.append(uniq) uniq = np.array(uniq_l) if format == 'fits': result = self._to_fits(uniq=uniq, optional_kw_dict=optional_kw_dict) elif format == 'str': result = self.__class__._to_str(uniq=uniq) else: # json format serialization result = self.__class__._to_json(uniq=uniq) return result
<SYSTEM_TASK:> Writes the MOC to a file. <END_TASK> <USER_TASK:> Description: def write(self, path, format='fits', overwrite=False, optional_kw_dict=None): """ Writes the MOC to a file. Format can be 'fits' or 'json', though only the fits format is officially supported by the IVOA. Parameters ---------- path : str, optional The path to the file to save the MOC in. format : str, optional The format in which the MOC will be serialized before being saved. Possible formats are "fits" or "json". By default, ``format`` is set to "fits". overwrite : bool, optional If the file already exists and you want to overwrite it, then set the ``overwrite`` keyword. Default to False. optional_kw_dict : optional Optional keywords arguments added to the FITS header. Only used if ``format`` equals to 'fits'. """
serialization = self.serialize(format=format, optional_kw_dict=optional_kw_dict) if format == 'fits': serialization.writeto(path, overwrite=overwrite) else: import json with open(path, 'w') as h: h.write(json.dumps(serialization, sort_keys=True, indent=2))
<SYSTEM_TASK:> Degrades the MOC instance to a new, less precise, MOC. <END_TASK> <USER_TASK:> Description: def degrade_to_order(self, new_order): """ Degrades the MOC instance to a new, less precise, MOC. The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the degraded MOC is set to ``new_order``. Parameters ---------- new_order : int Maximum depth of the output degraded MOC. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The degraded MOC. """
shift = 2 * (AbstractMOC.HPY_MAX_NORDER - new_order) ofs = (int(1) << shift) - 1 mask = ~ofs adda = int(0) addb = ofs iv_set = [] for iv in self._interval_set._intervals: a = (iv[0] + adda) & mask b = (iv[1] + addb) & mask if b > a: iv_set.append((a, b)) return self.__class__(IntervalSet(np.asarray(iv_set)))
<SYSTEM_TASK:> Set Screen Height <END_TASK> <USER_TASK:> Description: def set_height(self, height): """ Set Screen Height """
if height > 0 and height <= self.server.server_info.get("screen_height"): self.height = height self.server.request("screen_set %s hgt %i" % (self.ref, self.height))
<SYSTEM_TASK:> Add Title Widget <END_TASK> <USER_TASK:> Description: def add_title_widget(self, ref, text="Title"): """ Add Title Widget """
if ref not in self.widgets: widget = widgets.TitleWidget(screen=self, ref=ref, text=text) self.widgets[ref] = widget return self.widgets[ref]
<SYSTEM_TASK:> Add Frame Widget <END_TASK> <USER_TASK:> Description: def add_frame_widget(self, ref, left=1, top=1, right=20, bottom=1, width=20, height=4, direction="h", speed=1): """ Add Frame Widget """
if ref not in self.widgets: widget = widgets.FrameWidget( screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, width=width, height=height, direction=direction, speed=speed, ) self.widgets[ref] = widget return self.widgets[ref]
<SYSTEM_TASK:> Orbits the camera around the center position. <END_TASK> <USER_TASK:> Description: def orbit(self, azim, elev): """ Orbits the camera around the center position. Parameters ---------- azim : float Angle in degrees to rotate horizontally around the center point. elev : float Angle in degrees to rotate vertically around the center point. """
self.azimuth += azim self.elevation = np.clip(self.elevation + elev, -90, 90) self.view_changed()
<SYSTEM_TASK:> Copy functions from OpenGL.GL into _pyopengl namespace. <END_TASK> <USER_TASK:> Description: def _inject(): """ Copy functions from OpenGL.GL into _pyopengl namespace. """
NS = _pyopengl2.__dict__ for glname, ourname in _pyopengl2._functions_to_import: func = _get_function_from_pyopengl(glname) NS[ourname] = func
<SYSTEM_TASK:> Convert Nx3 or Nx4 lab to rgb <END_TASK> <USER_TASK:> Description: def _lab_to_rgb(labs): """Convert Nx3 or Nx4 lab to rgb"""
# adapted from BSD-licensed work in MATLAB by Mark Ruzon # Based on ITU-R Recommendation BT.709 using the D65 labs, n_dim = _check_color_dim(labs) # Convert Lab->XYZ (silly indexing used to preserve dimensionality) y = (labs[:, 0] + 16.) / 116. x = (labs[:, 1] / 500.) + y z = y - (labs[:, 2] / 200.) xyz = np.concatenate(([x], [y], [z])) # 3xN over = xyz > 0.2068966 xyz[over] = xyz[over] ** 3. xyz[~over] = (xyz[~over] - 0.13793103448275862) / 7.787 # Convert XYZ->LAB rgbs = np.dot(_xyz2rgb_norm, xyz).T over = rgbs > 0.0031308 rgbs[over] = 1.055 * (rgbs[over] ** (1. / 2.4)) - 0.055 rgbs[~over] *= 12.92 if n_dim == 4: rgbs = np.concatenate((rgbs, labs[:, 3]), axis=1) rgbs = np.clip(rgbs, 0., 1.) return rgbs
<SYSTEM_TASK:> Find an adequate value for this field from a dict of tags. <END_TASK> <USER_TASK:> Description: def get(self, tags): """Find an adequate value for this field from a dict of tags."""
# Try to find our name value = tags.get(self.name, '') for name in self.alternate_tags: # Iterate of alternates until a non-empty value is found value = value or tags.get(name, '') # If we still have nothing, return our default value = value or self.default return value
<SYSTEM_TASK:> message - text message to be spoken out by the Echo <END_TASK> <USER_TASK:> Description: def create_response(self, message=None, end_session=False, card_obj=None, reprompt_message=None, is_ssml=None): """ message - text message to be spoken out by the Echo end_session - flag to determine whether this interaction should end the session card_obj = JSON card object to substitute the 'card' field in the raw_response """
response = dict(self.base_response) if message: response['response'] = self.create_speech(message, is_ssml) response['response']['shouldEndSession'] = end_session if card_obj: response['response']['card'] = card_obj if reprompt_message: response['response']['reprompt'] = self.create_speech(reprompt_message, is_ssml) return Response(response)
<SYSTEM_TASK:> Friend method of viewbox to register itself. <END_TASK> <USER_TASK:> Description: def _viewbox_set(self, viewbox): """ Friend method of viewbox to register itself. """
self._viewbox = viewbox # Connect viewbox.events.mouse_press.connect(self.viewbox_mouse_event) viewbox.events.mouse_release.connect(self.viewbox_mouse_event) viewbox.events.mouse_move.connect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.connect(self.viewbox_mouse_event) viewbox.events.resize.connect(self.viewbox_resize_event)
<SYSTEM_TASK:> Friend method of viewbox to unregister itself. <END_TASK> <USER_TASK:> Description: def _viewbox_unset(self, viewbox): """ Friend method of viewbox to unregister itself. """
self._viewbox = None # Disconnect viewbox.events.mouse_press.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_release.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_move.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.disconnect(self.viewbox_mouse_event) viewbox.events.resize.disconnect(self.viewbox_resize_event)
<SYSTEM_TASK:> Set the range of the view region for the camera <END_TASK> <USER_TASK:> Description: def set_range(self, x=None, y=None, z=None, margin=0.05): """ Set the range of the view region for the camera Parameters ---------- x : tuple | None X range. y : tuple | None Y range. z : tuple | None Z range. margin : float Margin to use. Notes ----- The view is set to the given range or to the scene boundaries if ranges are not specified. The ranges should be 2-element tuples specifying the min and max for each dimension. For the PanZoomCamera the view is fully defined by the range. For e.g. the TurntableCamera the elevation and azimuth are not set. One should use reset() for that. """
# Flag to indicate that this is an initializing (not user-invoked) init = self._xlim is None # Collect given bounds bounds = [None, None, None] if x is not None: bounds[0] = float(x[0]), float(x[1]) if y is not None: bounds[1] = float(y[0]), float(y[1]) if z is not None: bounds[2] = float(z[0]), float(z[1]) # If there is no viewbox, store given bounds in lim variables, and stop if self._viewbox is None: self._set_range_args = bounds[0], bounds[1], bounds[2], margin return # There is a viewbox, we're going to set the range for real self._resetting = True # Get bounds from viewbox if not given if all([(b is None) for b in bounds]): bounds = self._viewbox.get_scene_bounds() else: for i in range(3): if bounds[i] is None: bounds[i] = self._viewbox.get_scene_bounds(i) # Calculate ranges and margins ranges = [b[1] - b[0] for b in bounds] margins = [(r*margin or 0.1) for r in ranges] # Assign limits for this camera bounds_margins = [(b[0]-m, b[1]+m) for b, m in zip(bounds, margins)] self._xlim, self._ylim, self._zlim = bounds_margins # Store center location if (not init) or (self._center is None): self._center = [(b[0] + r / 2) for b, r in zip(bounds, ranges)] # Let specific camera handle it self._set_range(init) # Finish self._resetting = False self.view_changed()
<SYSTEM_TASK:> Get the current view state of the camera <END_TASK> <USER_TASK:> Description: def get_state(self): """ Get the current view state of the camera Returns a dict of key-value pairs. The exact keys depend on the camera. Can be passed to set_state() (of this or another camera of the same type) to reproduce the state. """
D = {} for key in self._state_props: D[key] = getattr(self, key) return D
<SYSTEM_TASK:> Set the view state of the camera <END_TASK> <USER_TASK:> Description: def set_state(self, state=None, **kwargs): """ Set the view state of the camera Should be a dict (or kwargs) as returned by get_state. It can be an incomlete dict, in which case only the specified properties are set. Parameters ---------- state : dict The camera state. **kwargs : dict Unused keyword arguments. """
D = state or {} D.update(kwargs) for key, val in D.items(): if key not in self._state_props: raise KeyError('Not a valid camera state property %r' % key) setattr(self, key, val)
<SYSTEM_TASK:> Link this camera with another camera of the same type <END_TASK> <USER_TASK:> Description: def link(self, camera): """ Link this camera with another camera of the same type Linked camera's keep each-others' state in sync. Parameters ---------- camera : instance of Camera The other camera to link. """
cam1, cam2 = self, camera # Remove if already linked while cam1 in cam2._linked_cameras: cam2._linked_cameras.remove(cam1) while cam2 in cam1._linked_cameras: cam1._linked_cameras.remove(cam2) # Link both ways cam1._linked_cameras.append(cam2) cam2._linked_cameras.append(cam1)
<SYSTEM_TASK:> Called when this camera is changes its view. Also called <END_TASK> <USER_TASK:> Description: def view_changed(self): """ Called when this camera is changes its view. Also called when its associated with a viewbox. """
if self._resetting: return # don't update anything while resetting (are in set_range) if self._viewbox: # Set range if necessary if self._xlim is None: args = self._set_range_args or () self.set_range(*args) # Store default state if we have not set it yet if self._default_state is None: self.set_default_state() # Do the actual update self._update_transform()
<SYSTEM_TASK:> Canvas change event handler <END_TASK> <USER_TASK:> Description: def on_canvas_change(self, event): """Canvas change event handler Parameters ---------- event : instance of Event The event. """
# Connect key events from canvas to camera. # TODO: canvas should keep track of a single node with keyboard focus. if event.old is not None: event.old.events.key_press.disconnect(self.viewbox_key_event) event.old.events.key_release.disconnect(self.viewbox_key_event) if event.new is not None: event.new.events.key_press.connect(self.viewbox_key_event) event.new.events.key_release.connect(self.viewbox_key_event)
<SYSTEM_TASK:> Called by subclasses to configure the viewbox scene transform. <END_TASK> <USER_TASK:> Description: def _set_scene_transform(self, tr): """ Called by subclasses to configure the viewbox scene transform. """
# todo: check whether transform has changed, connect to # transform.changed event pre_tr = self.pre_transform if pre_tr is None: self._scene_transform = tr else: self._transform_cache.roll() self._scene_transform = self._transform_cache.get([pre_tr, tr]) # Mark the transform dynamic so that it will not be collapsed with # others self._scene_transform.dynamic = True # Update scene self._viewbox.scene.transform = self._scene_transform self._viewbox.update() # Apply same state to linked cameras, but prevent that camera # to return the favor for cam in self._linked_cameras: if cam is self._linked_cameras_no_update: continue try: cam._linked_cameras_no_update = self cam.set_state(self.get_state()) finally: cam._linked_cameras_no_update = None
<SYSTEM_TASK:> Get the window id of a PySide Widget. Might also work for PyQt4. <END_TASK> <USER_TASK:> Description: def get_window_id(self): """ Get the window id of a PySide Widget. Might also work for PyQt4. """
# Get Qt win id winid = self.winId() # On Linux this is it if IS_RPI: nw = (ctypes.c_int * 3)(winid, self.width(), self.height()) return ctypes.pointer(nw) elif IS_LINUX: return int(winid) # Is int on PySide, but sip.voidptr on PyQt # Get window id from stupid capsule thingy # http://translate.google.com/translate?hl=en&sl=zh-CN&u=http://www.cnb #logs.com/Shiren-Y/archive/2011/04/06/2007288.html&prev=/search%3Fq%3Dp # yside%2Bdirectx%26client%3Dfirefox-a%26hs%3DIsJ%26rls%3Dorg.mozilla:n #l:official%26channel%3Dfflb%26biw%3D1366%26bih%3D614 # Prepare ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p ctypes.pythonapi.PyCapsule_GetName.argtypes = [ctypes.py_object] ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p] # Extract handle from capsule thingy name = ctypes.pythonapi.PyCapsule_GetName(winid) handle = ctypes.pythonapi.PyCapsule_GetPointer(winid, name) return handle
<SYSTEM_TASK:> Change the translation of this transform by the amount given. <END_TASK> <USER_TASK:> Description: def move(self, move): """Change the translation of this transform by the amount given. Parameters ---------- move : array-like The values to be added to the current translation of the transform. """
move = as_vec4(move, default=(0, 0, 0, 0)) self.translate = self.translate + move
<SYSTEM_TASK:> Update the transform such that its scale factor is changed, but <END_TASK> <USER_TASK:> Description: def zoom(self, zoom, center=(0, 0, 0), mapped=True): """Update the transform such that its scale factor is changed, but the specified center point is left unchanged. Parameters ---------- zoom : array-like Values to multiply the transform's current scale factors. center : array-like The center point around which the scaling will take place. mapped : bool Whether *center* is expressed in mapped coordinates (True) or unmapped coordinates (False). """
zoom = as_vec4(zoom, default=(1, 1, 1, 1)) center = as_vec4(center, default=(0, 0, 0, 0)) scale = self.scale * zoom if mapped: trans = center - (center - self.translate) * zoom else: trans = self.scale * (1 - zoom) * center + self.translate self._set_st(scale=scale, translate=trans)
<SYSTEM_TASK:> Create an STTransform from the given mapping <END_TASK> <USER_TASK:> Description: def from_mapping(cls, x0, x1): """ Create an STTransform from the given mapping See `set_mapping` for details. Parameters ---------- x0 : array-like Start. x1 : array-like End. Returns ------- t : instance of STTransform The transform. """
t = cls() t.set_mapping(x0, x1) return t
<SYSTEM_TASK:> Configure this transform such that it maps points x0 => x1 <END_TASK> <USER_TASK:> Description: def set_mapping(self, x0, x1, update=True): """Configure this transform such that it maps points x0 => x1 Parameters ---------- x0 : array-like, shape (2, 2) or (2, 3) Start location. x1 : array-like, shape (2, 2) or (2, 3) End location. update : bool If False, then the update event is not emitted. Examples -------- For example, if we wish to map the corners of a rectangle:: >>> p1 = [[0, 0], [200, 300]] onto a unit cube:: >>> p2 = [[-1, -1], [1, 1]] then we can generate the transform as follows:: >>> tr = STTransform() >>> tr.set_mapping(p1, p2) >>> assert tr.map(p1)[:,:2] == p2 # test """
# if args are Rect, convert to array first if isinstance(x0, Rect): x0 = x0._transform_in()[:3] if isinstance(x1, Rect): x1 = x1._transform_in()[:3] x0 = np.asarray(x0) x1 = np.asarray(x1) if (x0.ndim != 2 or x0.shape[0] != 2 or x1.ndim != 2 or x1.shape[0] != 2): raise TypeError("set_mapping requires array inputs of shape " "(2, N).") denom = x0[1] - x0[0] mask = denom == 0 denom[mask] = 1.0 s = (x1[1] - x1[0]) / denom s[mask] = 1.0 s[x0[1] == x0[0]] = 1.0 t = x1[0] - s * x0[0] s = as_vec4(s, default=(1, 1, 1, 1)) t = as_vec4(t, default=(0, 0, 0, 0)) self._set_st(scale=s, translate=t, update=update)
<SYSTEM_TASK:> Translate the matrix <END_TASK> <USER_TASK:> Description: def translate(self, pos): """ Translate the matrix The translation is applied *after* the transformations already present in the matrix. Parameters ---------- pos : arrayndarray Position to translate by. """
self.matrix = np.dot(self.matrix, transforms.translate(pos[0, :3]))
<SYSTEM_TASK:> Scale the matrix about a given origin. <END_TASK> <USER_TASK:> Description: def scale(self, scale, center=None): """ Scale the matrix about a given origin. The scaling is applied *after* the transformations already present in the matrix. Parameters ---------- scale : array-like Scale factors along x, y and z axes. center : array-like or None The x, y and z coordinates to scale around. If None, (0, 0, 0) will be used. """
scale = transforms.scale(as_vec4(scale, default=(1, 1, 1, 1))[0, :3]) if center is not None: center = as_vec4(center)[0, :3] scale = np.dot(np.dot(transforms.translate(-center), scale), transforms.translate(center)) self.matrix = np.dot(self.matrix, scale)
<SYSTEM_TASK:> Rotate the matrix by some angle about a given axis. <END_TASK> <USER_TASK:> Description: def rotate(self, angle, axis): """ Rotate the matrix by some angle about a given axis. The rotation is applied *after* the transformations already present in the matrix. Parameters ---------- angle : float The angle of rotation, in degrees. axis : array-like The x, y and z coordinates of the axis vector to rotate around. """
self.matrix = np.dot(self.matrix, transforms.rotate(angle, axis))
<SYSTEM_TASK:> Set to a 3D transformation matrix that maps points1 onto points2. <END_TASK> <USER_TASK:> Description: def set_mapping(self, points1, points2): """ Set to a 3D transformation matrix that maps points1 onto points2. Parameters ---------- points1 : array-like, shape (4, 3) Four starting 3D coordinates. points2 : array-like, shape (4, 3) Four ending 3D coordinates. """
# note: need to transpose because util.functions uses opposite # of standard linear algebra order. self.matrix = transforms.affine_map(points1, points2).T
<SYSTEM_TASK:> Set ortho transform <END_TASK> <USER_TASK:> Description: def set_ortho(self, l, r, b, t, n, f): """Set ortho transform Parameters ---------- l : float Left. r : float Right. b : float Bottom. t : float Top. n : float Near. f : float Far. """
self.matrix = transforms.ortho(l, r, b, t, n, f)
<SYSTEM_TASK:> Set the perspective <END_TASK> <USER_TASK:> Description: def set_perspective(self, fov, aspect, near, far): """Set the perspective Parameters ---------- fov : float Field of view. aspect : float Aspect ratio. near : float Near location. far : float Far location. """
self.matrix = transforms.perspective(fov, aspect, near, far)
<SYSTEM_TASK:> Set the frustum <END_TASK> <USER_TASK:> Description: def set_frustum(self, l, r, b, t, n, f): """Set the frustum Parameters ---------- l : float Left. r : float Right. b : float Bottom. t : float Top. n : float Near. f : float Far. """
self.matrix = transforms.frustum(l, r, b, t, n, f)
<SYSTEM_TASK:> Set the line data <END_TASK> <USER_TASK:> Description: def set_data(self, data=None, **kwargs): """Set the line data Parameters ---------- data : array-like The data. **kwargs : dict Keywoard arguments to pass to MarkerVisual and LineVisal. """
if data is None: pos = None else: if isinstance(data, tuple): pos = np.array(data).T.astype(np.float32) else: pos = np.atleast_1d(data).astype(np.float32) if pos.ndim == 1: pos = pos[:, np.newaxis] elif pos.ndim > 2: raise ValueError('data must have at most two dimensions') if pos.size == 0: pos = self._line.pos # if both args and keywords are zero, then there is no # point in calling this function. if len(kwargs) == 0: raise TypeError("neither line points nor line properties" "are provided") elif pos.shape[1] == 1: x = np.arange(pos.shape[0], dtype=np.float32)[:, np.newaxis] pos = np.concatenate((x, pos), axis=1) # if args are empty, don't modify position elif pos.shape[1] > 3: raise TypeError("Too many coordinates given (%s; max is 3)." % pos.shape[1]) # todo: have both sub-visuals share the same buffers. line_kwargs = {} for k in self._line_kwargs: if k in kwargs: k_ = self._kw_trans[k] if k in self._kw_trans else k line_kwargs[k] = kwargs.pop(k_) if pos is not None or len(line_kwargs) > 0: self._line.set_data(pos=pos, **line_kwargs) marker_kwargs = {} for k in self._marker_kwargs: if k in kwargs: k_ = self._kw_trans[k] if k in self._kw_trans else k marker_kwargs[k_] = kwargs.pop(k) if pos is not None or len(marker_kwargs) > 0: self._markers.set_data(pos=pos, **marker_kwargs) if len(kwargs) > 0: raise TypeError("Invalid keyword arguments: %s" % kwargs.keys())
<SYSTEM_TASK:> Generate the vertices for a quadratic Bezier curve. <END_TASK> <USER_TASK:> Description: def curve3_bezier(p1, p2, p3): """ Generate the vertices for a quadratic Bezier curve. The vertices returned by this function can be passed to a LineVisual or ArrowVisual. Parameters ---------- p1 : array 2D coordinates of the start point p2 : array 2D coordinates of the first curve point p3 : array 2D coordinates of the end point Returns ------- coords : list Vertices for the Bezier curve. See Also -------- curve4_bezier Notes ----- For more information about Bezier curves please refer to the `Wikipedia`_ page. .. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve """
x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 points = [] _curve3_recursive_bezier(points, x1, y1, x2, y2, x3, y3) dx, dy = points[0][0] - x1, points[0][1] - y1 if (dx * dx + dy * dy) > 1e-10: points.insert(0, (x1, y1)) dx, dy = points[-1][0] - x3, points[-1][1] - y3 if (dx * dx + dy * dy) > 1e-10: points.append((x3, y3)) return np.array(points).reshape(len(points), 2)
<SYSTEM_TASK:> Generate the vertices for a third order Bezier curve. <END_TASK> <USER_TASK:> Description: def curve4_bezier(p1, p2, p3, p4): """ Generate the vertices for a third order Bezier curve. The vertices returned by this function can be passed to a LineVisual or ArrowVisual. Parameters ---------- p1 : array 2D coordinates of the start point p2 : array 2D coordinates of the first curve point p3 : array 2D coordinates of the second curve point p4 : array 2D coordinates of the end point Returns ------- coords : list Vertices for the Bezier curve. See Also -------- curve3_bezier Notes ----- For more information about Bezier curves please refer to the `Wikipedia`_ page. .. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve """
x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 x4, y4 = p4 points = [] _curve4_recursive_bezier(points, x1, y1, x2, y2, x3, y3, x4, y4) dx, dy = points[0][0] - x1, points[0][1] - y1 if (dx * dx + dy * dy) > 1e-10: points.insert(0, (x1, y1)) dx, dy = points[-1][0] - x4, points[-1][1] - y4 if (dx * dx + dy * dy) > 1e-10: points.append((x4, y4)) return np.array(points).reshape(len(points), 2)
<SYSTEM_TASK:> Render a SDF to a texture at a given offset and size <END_TASK> <USER_TASK:> Description: def render_to_texture(self, data, texture, offset, size): """Render a SDF to a texture at a given offset and size Parameters ---------- data : array Must be 2D with type np.ubyte. texture : instance of Texture2D The texture to render to. offset : tuple of int Offset (x, y) to render to inside the texture. size : tuple of int Size (w, h) to render inside the texture. """
assert isinstance(texture, Texture2D) set_state(blend=False, depth_test=False) # calculate the negative half (within object) orig_tex = Texture2D(255 - data, format='luminance', wrapping='clamp_to_edge', interpolation='nearest') edf_neg_tex = self._render_edf(orig_tex) # calculate positive half (outside object) orig_tex[:, :, 0] = data edf_pos_tex = self._render_edf(orig_tex) # render final product to output texture self.program_insert['u_texture'] = orig_tex self.program_insert['u_pos_texture'] = edf_pos_tex self.program_insert['u_neg_texture'] = edf_neg_tex self.fbo_to[-1].color_buffer = texture with self.fbo_to[-1]: set_viewport(tuple(offset) + tuple(size)) self.program_insert.draw('triangle_strip')
<SYSTEM_TASK:> Annotate functions with @VoiceHandler so that they can be automatically mapped <END_TASK> <USER_TASK:> Description: def launch_request_handler(request): """ Annotate functions with @VoiceHandler so that they can be automatically mapped to request types. Use the 'request_type' field to map them to non-intent requests """
user_id = request.access_token() if user_id in twitter_cache.users(): user_cache = twitter_cache.get_user_state(user_id) user_cache["amzn_id"]= request.user_id() base_message = "Welcome to Twitter, {} . How may I help you today ?".format(user_cache["screen_name"]) print (user_cache) if 'pending_action' in user_cache: base_message += " You have one pending action . " print ("Found pending action") if 'description' in user_cache['pending_action']: print ("Found description") base_message += user_cache['pending_action']['description'] return r.create_response(base_message) card = r.create_card(title="Please log into twitter", card_type="LinkAccount") return r.create_response(message="Welcome to twitter, looks like you haven't logged in!" " Log in via the alexa app.", card_obj=card, end_session=True)
<SYSTEM_TASK:> Use the 'intent' field in the VoiceHandler to map to the respective intent. <END_TASK> <USER_TASK:> Description: def post_tweet_intent_handler(request): """ Use the 'intent' field in the VoiceHandler to map to the respective intent. """
tweet = request.get_slot_value("Tweet") tweet = tweet if tweet else "" if tweet: user_state = twitter_cache.get_user_state(request.access_token()) def action(): return post_tweet(request.access_token(), tweet) message = "I am ready to post the tweet, {} ,\n Please say yes to confirm or stop to cancel .".format(tweet) user_state['pending_action'] = {"action" : action, "description" : message} return r.create_response(message=message, end_session=False) else: # No tweet could be disambiguated message = " ".join( [ "I'm sorry, I couldn't understand what you wanted to tweet .", "Please prepend the message with either post or tweet ." ] ) return alexa.create_response(message=message, end_session=False)
<SYSTEM_TASK:> This is a generic function to handle any intent that reads out a list of tweets <END_TASK> <USER_TASK:> Description: def tweet_list_handler(request, tweet_list_builder, msg_prefix=""): """ This is a generic function to handle any intent that reads out a list of tweets"""
# tweet_list_builder is a function that takes a unique identifier and returns a list of things to say tweets = tweet_list_builder(request.access_token()) print (len(tweets), 'tweets found') if tweets: twitter_cache.initialize_user_queue(user_id=request.access_token(), queue=tweets) text_to_read_out = twitter_cache.user_queue(request.access_token()).read_out_next(MAX_RESPONSE_TWEETS) message = msg_prefix + text_to_read_out + ", say 'next' to hear more, or reply to a tweet by number." return alexa.create_response(message=message, end_session=False) else: return alexa.create_response(message="Sorry, no tweets found, please try something else", end_session=False)
<SYSTEM_TASK:> Return index if focused on tweet False if couldn't <END_TASK> <USER_TASK:> Description: def focused_on_tweet(request): """ Return index if focused on tweet False if couldn't """
slots = request.get_slot_map() if "Index" in slots and slots["Index"]: index = int(slots['Index']) elif "Ordinal" in slots and slots["Index"]: parse_ordinal = lambda inp : int("".join([l for l in inp if l in string.digits])) index = parse_ordinal(slots['Ordinal']) else: return False index = index - 1 # Going from regular notation to CS notation user_state = twitter_cache.get_user_state(request.access_token()) queue = user_state['user_queue'].queue() if index < len(queue): # Analyze tweet in queue tweet_to_analyze = queue[index] user_state['focus_tweet'] = tweet_to_analyze return index + 1 # Returning to regular notation twitter_cache.serialize() return False
<SYSTEM_TASK:> Takes care of things whenver the user says 'next' <END_TASK> <USER_TASK:> Description: def next_intent_handler(request): """ Takes care of things whenver the user says 'next' """
message = "Sorry, couldn't find anything in your next queue" end_session = True if True: user_queue = twitter_cache.user_queue(request.access_token()) if not user_queue.is_finished(): message = user_queue.read_out_next(MAX_RESPONSE_TWEETS) if not user_queue.is_finished(): end_session = False message = message + ". Please, say 'next' if you want me to read out more. " return alexa.create_response(message=message, end_session=end_session)
<SYSTEM_TASK:> Set the mesh data <END_TASK> <USER_TASK:> Description: def set_data(self, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=None, meshdata=None): """Set the mesh data Parameters ---------- vertices : array-like | None The vertices. faces : array-like | None The faces. vertex_colors : array-like | None Colors to use for each vertex. face_colors : array-like | None Colors to use for each face. color : instance of Color The color to use. meshdata : instance of MeshData | None The meshdata. """
if meshdata is not None: self._meshdata = meshdata else: self._meshdata = MeshData(vertices=vertices, faces=faces, vertex_colors=vertex_colors, face_colors=face_colors) self._bounds = self._meshdata.get_bounds() if color is not None: self._color = Color(color) self.mesh_data_changed()
<SYSTEM_TASK:> Get the bounds of the Visual <END_TASK> <USER_TASK:> Description: def bounds(self, axis, view=None): """Get the bounds of the Visual Parameters ---------- axis : int The axis. view : instance of VisualView The view to use. """
if view is None: view = self if axis not in self._vshare.bounds: self._vshare.bounds[axis] = self._compute_bounds(axis, view) return self._vshare.bounds[axis]
<SYSTEM_TASK:> Return a FunctionChain that Filters may use to modify the program. <END_TASK> <USER_TASK:> Description: def _get_hook(self, shader, name): """Return a FunctionChain that Filters may use to modify the program. *shader* should be "frag" or "vert" *name* should be "pre" or "post" """
assert name in ('pre', 'post') key = (shader, name) if key in self._hooks: return self._hooks[key] hook = StatementList() if shader == 'vert': self.view_program.vert[name] = hook elif shader == 'frag': self.view_program.frag[name] = hook self._hooks[key] = hook return hook
<SYSTEM_TASK:> Add a subvisual <END_TASK> <USER_TASK:> Description: def add_subvisual(self, visual): """Add a subvisual Parameters ---------- visual : instance of Visual The visual to add. """
visual.transforms = self.transforms visual._prepare_transforms(visual) self._subvisuals.append(visual) visual.events.update.connect(self._subv_update) self.update()
<SYSTEM_TASK:> Remove a subvisual <END_TASK> <USER_TASK:> Description: def remove_subvisual(self, visual): """Remove a subvisual Parameters ---------- visual : instance of Visual The visual to remove. """
visual.events.update.disconnect(self._subv_update) self._subvisuals.remove(visual) self.update()
<SYSTEM_TASK:> Draw the visual <END_TASK> <USER_TASK:> Description: def draw(self): """Draw the visual """
if not self.visible: return if self._prepare_draw(view=self) is False: return for v in self._subvisuals: if v.visible: v.draw()
<SYSTEM_TASK:> clear the left panel and preferences <END_TASK> <USER_TASK:> Description: def clearPrefs(self): """clear the left panel and preferences"""
self.preferences.clear() tradebox_num = len(self.css('div.tradebox')) for i in range(tradebox_num): self.xpath(path['trade-box'])[0].right_click() self.css1('div.item-trade-contextmenu-list-remove').click() logger.info("cleared preferences")
<SYSTEM_TASK:> add preference in self.preferences <END_TASK> <USER_TASK:> Description: def addPrefs(self, prefs=[]): """add preference in self.preferences"""
if len(prefs) == len(self.preferences) == 0: logger.debug("no preferences") return None self.preferences.extend(prefs) self.css1(path['search-btn']).click() count = 0 for pref in self.preferences: self.css1(path['search-pref']).fill(pref) self.css1(path['pref-icon']).click() btn = self.css1('div.add-to-watchlist-popup-item .icon-wrapper') if not self.css1('svg', btn)['class'] is None: btn.click() count += 1 # remove window self.css1(path['pref-icon']).click() # close finally self.css1(path['back-btn']).click() self.css1(path['back-btn']).click() logger.debug("updated %d preferences" % count) return self.preferences
<SYSTEM_TASK:> Load glyph from font into dict <END_TASK> <USER_TASK:> Description: def _load_glyph(f, char, glyphs_dict): """Load glyph from font into dict"""
from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING, FT_LOAD_NO_AUTOHINT) flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT face = _load_font(f['face'], f['bold'], f['italic']) face.set_char_size(f['size'] * 64) # get the character of interest face.load_char(char, flags) bitmap = face.glyph.bitmap width = face.glyph.bitmap.width height = face.glyph.bitmap.rows bitmap = np.array(bitmap.buffer) w0 = bitmap.size // height if bitmap.size > 0 else 0 bitmap.shape = (height, w0) bitmap = bitmap[:, :width].astype(np.ubyte) left = face.glyph.bitmap_left top = face.glyph.bitmap_top advance = face.glyph.advance.x / 64. glyph = dict(char=char, offset=(left, top), bitmap=bitmap, advance=advance, kerning={}) glyphs_dict[char] = glyph # Generate kerning for other_char, other_glyph in glyphs_dict.items(): kerning = face.get_kerning(other_char, char) glyph['kerning'][other_char] = kerning.x / 64. kerning = face.get_kerning(char, other_char) other_glyph['kerning'][char] = kerning.x / 64.