text
stringlengths
81
112k
Show a ColorBar Parameters ---------- cmap : str | vispy.color.ColorMap Either the name of the ColorMap to be used from the standard set of names (refer to `vispy.color.get_colormap`), or a custom ColorMap object. The ColorMap is used to apply a g...
Redraw the Vispy canvas def redraw(self): """ Redraw the Vispy canvas """ if self._multiscat is not None: self._multiscat._update() self.vispy_widget.canvas.update()
Remove the layer artist from the visualization 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_c...
Helper to check valid options 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))
Convert to args representation def _to_args(x): """Convert to args representation""" if not isinstance(x, (list, tuple, np.ndarray)): x = [x] return x
Check for existence of key in dict, return value or raise error 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 ...
Read pixels from the currently selected buffer. Under most circumstances, this function reads from the front buffer. Unlike all other functions in vispy.gloo, this function directly executes an OpenGL command. Parameters ---------- viewport : array-like | None 4-element list of x,...
Read the current gl configuration This function uses constants that are not in the OpenGL ES 2.1 namespace, so only use this on desktop systems. Returns ------- config : dict The currently active OpenGL configuration. def get_gl_configuration(): """Read the current gl configuration ...
Set the OpenGL viewport This is a wrapper for gl.glViewport. Parameters ---------- *args : tuple X and Y coordinates, plus width and height. Can be passed in as individual components, or as a single tuple with four values. def set_viewport(self, *args):...
Set depth values Parameters ---------- near : float Near clipping plane. far : float Far clipping plane. def set_depth_range(self, near=0., far=1.): """Set depth values Parameters ---------- near : float Near ...
Set line width Parameters ---------- width : float The line width. def set_line_width(self, width=1.): """Set line width Parameters ---------- width : float The line width. """ width = float(width) if widt...
Set the scale and units used to calculate depth values Parameters ---------- factor : float Scale factor used to create a variable depth offset for each polygon. units : float Multiplied by an implementation-specific value to create a ...
Clear the screen buffers This is a wrapper for gl.glClear. Parameters ---------- color : bool | str | tuple | instance of Color Clear the color buffer bit. If not bool, ``set_clear_color`` will be used to set the color clear value. depth : bool |...
Set the screen clear color This is a wrapper for gl.glClearColor. Parameters ---------- color : str | tuple | instance of Color Color to use. See vispy.color.Color for options. alpha : float | None Alpha to use. def set_clear_color(self, color='black', ...
Specify pixel arithmetic for RGB and alpha Parameters ---------- srgb : str Source RGB factor. drgb : str Destination RGB factor. salpha : str | None Source alpha factor. If None, ``srgb`` is used. dalpha : str Destinat...
Specify the equation for RGB and alpha blending Parameters ---------- mode_rgb : str Mode for RGB. mode_alpha : str | None Mode for Alpha. If None, ``mode_rgb`` is used. Notes ----- See ``set_blend_equation`` for valid modes. def...
Define the scissor box Parameters ---------- x : int Left corner of the box. y : int Lower corner of the box. w : int The width of the box. h : int The height of the box. def set_scissor(self, x, y, w, h): """D...
Set front or back function and reference value Parameters ---------- func : str See set_stencil_func. ref : int Reference value for the stencil test. mask : int Mask that is ANDed with ref and stored stencil value. face : str ...
Control the front or back writing of individual bits in the stencil Parameters ---------- mask : int Mask that is ANDed with ref and stored stencil value. face : str Can be 'front', 'back', or 'front_and_back'. def set_stencil_mask(self, mask=8, face='front_...
Set front or back stencil test actions Parameters ---------- sfail : str Action to take when the stencil fails. Must be one of 'keep', 'zero', 'replace', 'incr', 'incr_wrap', 'decr', 'decr_wrap', or 'invert'. dpfail : str Action to tak...
Toggle writing of frame buffer color components Parameters ---------- red : bool Red toggle. green : bool Green toggle. blue : bool Blue toggle. alpha : bool Alpha toggle. def set_color_mask(self, red, green, blue, alp...
Specify multisample coverage parameters Parameters ---------- value : float Sample coverage value (will be clamped between 0. and 1.). invert : bool Specify if the coverage masks should be inverted. def set_sample_coverage(self, value=1.0, invert=False): ...
Set OpenGL rendering state, optionally using a preset Parameters ---------- preset : str | None Can be one of ('opaque', 'translucent', 'additive') to use use reasonable defaults for these typical use cases. **kwargs : keyword arguments Other supp...
Wait for GL commands to to finish This creates a GLIR command for glFinish and then processes the GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this function will return before GL has finished processing the commands. def finish(self): """Wait for GL commands t...
Flush GL commands This is a wrapper for glFlush(). This also flushes the GLIR command queue. def flush(self): """Flush GL commands This is a wrapper for glFlush(). This also flushes the GLIR command queue. """ if hasattr(self, 'flush_commands'): ...
Set OpenGL drawing hint Parameters ---------- target : str The target, e.g. 'fog_hint', 'line_smooth_hint', 'point_smooth_hint'. mode : str The mode to set (e.g., 'fastest', 'nicest', 'dont_care'). def set_hint(self, target, mode): """Set...
The GLIR queue corresponding to the current canvas def glir(self): """ The GLIR queue corresponding to the current canvas """ canvas = get_current_canvas() if canvas is None: msg = ("If you want to use gloo without vispy.app, " + "use a gloo.context.FakeC...
Let Vispy use the target OpenGL ES 2.0 implementation Also see ``vispy.use()``. Parameters ---------- target : str The target GL backend to use. Available backends: * gl2 - Use ES 2.0 subset of desktop (i.e. normal) OpenGL * gl+ - Use the desktop ES 2.0 subset plus all non...
Clear names that are not part of the strict ES API def _clear_namespace(): """ Clear names that are not part of the strict ES API """ ok_names = set(default_backend.__dict__) ok_names.update(['gl2', 'glplus']) # don't remove the module NS = globals() for name in list(NS.keys()): if nam...
Inject all objects that start with 'gl' from the source into the dest. source and dest can be dicts, modules or BaseGLProxy's. def _copy_gl_functions(source, dest, constants=False): """ Inject all objects that start with 'gl' from the source into the dest. source and dest can be dicts, modules or BaseGLPro...
Check this from time to time to detect GL errors. Parameters ---------- when : str Shown in the exception to help the developer determine when this check was done. def check_error(when='periodic check'): """ Check this from time to time to detect GL errors. Parameters --------...
Get a useful (and not too large) represetation of an argument. def _arg_repr(self, arg): """ Get a useful (and not too large) represetation of an argument. """ r = repr(arg) max = 40 if len(r) > max: if hasattr(arg, 'shape'): r = 'array:' + 'x'.join([...
Set the scalar array data Parameters ---------- data : ndarray A 2D array of scalar values. The isocurve is constructed to show all locations in the scalar field equal to ``self.levels``. def set_data(self, data): """ Set the scalar array data Parameter...
retrieve vertices and connects from given paths-list def _get_verts_and_connect(self, paths): """ retrieve vertices and connects from given paths-list """ verts = np.vstack(paths) gaps = np.add.accumulate(np.array([len(x) for x in paths])) - 1 connect = np.ones(gaps[-1], dtype=b...
compute LineVisual vertices, connects and color-index def _compute_iso_line(self): """ compute LineVisual vertices, connects and color-index """ level_index = [] connects = [] verts = [] # calculate which level are within data range # this works for now and the ...
Connect this emitter to a new callback. Parameters ---------- callback : function | tuple *callback* may be either a callable object or a tuple (object, attr_name) where object.attr_name will point to a callable object. Note that only a weak reference to ``ob...
Disconnect a callback from this emitter. If no callback is specified, then *all* callbacks are removed. If the callback was not already connected, then the call does nothing. def disconnect(self, callback=None): """Disconnect a callback from this emitter. If no callback is specified, ...
Block this emitter. Any attempts to emit an event while blocked will be silently ignored. If *callback* is given, then the emitter is only blocked for that specific callback. Calls to block are cumulative; the emitter must be unblocked the same number of times as it is blocked. def blo...
Unblock this emitter. See :func:`event.EventEmitter.block`. Note: Use of ``unblock(None)`` only reverses the effect of ``block(None)``; it does not unblock callbacks that were explicitly blocked using ``block(callback)``. def unblock(self, callback=None): """ Unblock this emi...
Add one or more EventEmitter instances to this emitter group. Each keyword argument may be specified as either an EventEmitter instance or an Event subclass, in which case an EventEmitter will be generated automatically:: # This statement: group.add(mouse_press=MouseEven...
Block all emitters in this group. def block_all(self): """ Block all emitters in this group. """ self.block() for em in self._emitters.values(): em.block()
Unblock all emitters in this group. def unblock_all(self): """ Unblock all emitters in this group. """ self.unblock() for em in self._emitters.values(): em.unblock()
Connect the callback to the event group. The callback will receive events from *all* of the emitters in the group. See :func:`EventEmitter.connect() <vispy.event.EventEmitter.connect>` for arguments. def connect(self, callback, ref=False, position='first', before=None, after=No...
Disconnect the callback from this group. See :func:`connect() <vispy.event.EmitterGroup.connect>` and :func:`EventEmitter.connect() <vispy.event.EventEmitter.connect>` for more information. def disconnect(self, callback=None): """ Disconnect the callback from this group. See :fu...
TODO add handling for bad input def validate_input_format(utterance, intent): """ TODO add handling for bad input""" slots = {slot["name"] for slot in intent["slots"]} split_utt = re.split("{(.*)}", utterance) banned = set("-/\\()^%$#@~`-_=+><;:") # Banned characters for token in split_utt: ...
Generate isosurface from volumetric data using marching cubes algorithm. See Paul Bourke, "Polygonising a Scalar Field" (http://paulbourke.net/geometry/polygonise/) *data* 3D numpy array of scalar values *level* The level at which to generate an isosurface Returns an array of vertex c...
Extract all data buffers from the list of GLIR commands, and replace them by buffer pointers {buffer: <buffer_index>}. Return the modified list # of GILR commands and the list of buffers as well. def _extract_buffers(commands): """Extract all data buffers from the list of GLIR commands, and replace the...
Internal function: serialize native types. def _serialize_item(item): """Internal function: serialize native types.""" # Recursively serialize lists, tuples, and dicts. if isinstance(item, (list, tuple)): return [_serialize_item(subitem) for subitem in item] elif isinstance(item, dict): ...
Create a JSON-serializable message of GLIR commands. NumPy arrays are serialized according to the specified method. Arguments --------- commands : list List of GLIR commands. array_serialization : string or None Serialization method for NumPy arrays. Possible values are: ...
Start Session def start_session(self): """ Start Session """ response = self.request("hello") bits = response.split(" ") self.server_info.update({ "server_version": bits[2], "protocol_version": bits[4], "screen_width": int(bits[7]), "scre...
Request def request(self, command_string): """ Request """ self.send(command_string) if self.debug: print("Telnet Request: %s" % (command_string)) while True: response = urllib.parse.unquote(self.tn.read_until(b"\n").decode()) if "success" in respon...
Add Screen def add_screen(self, ref): """ Add Screen """ if ref not in self.screens: screen = Screen(self, ref) screen.clear() # TODO Check this is needed, new screens should be clear. self.screens[ref] = screen return self.screens[ref]
Add a key. (ref) Return key name or None on error 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)) ...
Delete a key. (ref) Return None or LCDd response on error def del_key(self, ref): """ Delete a key. (ref) Return None or LCDd response on error """ if ref not in self.keys: response = self.request("client_del_key %s" % (ref)) sel...
launch browser and virtual display, first of all to be launched 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 launc...
css find function abbreviation def css(self, css_path, dom=None): """css find function abbreviation""" if dom is None: dom = self.browser return expect(dom.find_by_css, args=[css_path])
return the first value of self.css def css1(self, css_path, dom=None): """return the first value of self.css""" if dom is None: dom = self.browser def _css1(path, domm): """virtual local func""" return self.css(path, domm)[0] return expect(_css1, ar...
name find function abbreviation def search_name(self, name, dom=None): """name find function abbreviation""" if dom is None: dom = self.browser return expect(dom.find_by_name, args=[name])
xpath find function abbreviation def xpath(self, xpath, dom=None): """xpath find function abbreviation""" if dom is None: dom = self.browser return expect(dom.find_by_xpath, args=[xpath])
check if element is present by css def elCss(self, css_path, dom=None): """check if element is present by css""" if dom is None: dom = self.browser return expect(dom.is_element_present_by_css, args=[css_path])
check if element is present by css def elXpath(self, xpath, dom=None): """check if element is present by css""" if dom is None: dom = self.browser return expect(dom.is_element_present_by_xpath, args=[xpath])
login function def login(self, username, password, mode="demo"): """login function""" url = "https://trading212.com/it/login" try: logger.debug(f"visiting %s" % url) self.browser.visit(url) logger.debug(f"connected to %s" % url) except selenium.common...
logout func (quit browser) def logout(self): """logout func (quit browser)""" try: self.browser.quit() except Exception: raise exceptions.BrowserException(self.brow_name, "not started") return False self.vbro.stop() logger.info("logged out") ...
factory method pattern def new_pos(self, html_div): """factory method pattern""" pos = self.Position(self, html_div) pos.bind_mov() self.positions.append(pos) return pos
Convert a '[user[:pass]@]host:port' string to a Connection tuple. If the given connection is empty, use defaults. If no port is given, use the default. Args: conn (str): the string describing the target hsot/port default_host (str): the host to use if ``conn`` is empty default_port...
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 nu...
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. def _make_patterns(patterns): """Create a ScreenPatternList from a given pattern text....
Run the server. Args: lcdproc (str): the target connection (host:port) for lcdproc mpd (str): the target connection ([pwd@]host:port) for mpd lcdproc_screen (str): the name of the screen to use for lcdproc lcdproc_charset (str): the charset to use with lcdproc lcdd_debug (bo...
Read configuration from the given file. Parsing is performed through the configparser library. Returns: dict: a flattened dict of (option_name, value), using defaults. def _read_config(filename): """Read configuration from the given file. Parsing is performed through the configparser library...
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' o...
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. ...
Activate/use this frame buffer. def activate(self): """ Activate/use this frame buffer. """ # Send command self._glir.command('FRAMEBUFFER', self._id, True) # Associate canvas now canvas = get_current_canvas() if canvas is not None: canvas.context.gli...
The shape of the Texture/RenderBuffer attached to this FrameBuffer def shape(self): """ The shape of the Texture/RenderBuffer attached to this FrameBuffer """ if self.color_buffer is not None: return self.color_buffer.shape[:2] # in case its a texture if self.depth_buffer i...
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. def resi...
Return array of pixel values in an attached buffer Parameters ---------- mode : str The buffer type to read. May be 'color', 'depth', or 'stencil'. alpha : bool If True, returns RGBA array. Otherwise, returns RGB. Returns ------- ...
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 shap...
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. def _compute_bounds(self, a...
Bake a list of 2D vertices for rendering them as thick line. Each line segment must have its own vertices because of antialias (this means no vertex sharing between two adjacent line segments). def _agg_bake(cls, vertices, color, closed=False): """ Bake a list of 2D vertices for renderi...
This actually calculates the kerning + advance 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.kCFTypeDictionaryKeyCallBa...
Update the mesh data. Parameters ---------- xs : ndarray | None A 2d array of x coordinates for the vertices of the mesh. ys : ndarray | None A 2d array of y coordinates for the vertices of the mesh. zs : ndarray | None A 2d array of z coordin...
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: ...
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 def read_png(filename): """Read...
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 def write_png(filename, data): """Write a PNG file Unlike imsave,...
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 --------...
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...
Utility to search for imageio or PIL 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 imagei...
Helper function to prompt user for input of a specific type e.g. float, str, int Designed to work with both python 2 and 3 Yes I know this is ugly. def read_from_user(input_type, *args, **kwargs): ''' Helper function to prompt user for input of a specific type e.g. float, str, int Desi...
Helper function to load builtin slots from the data location def load_builtin_slots(): ''' Helper function to load builtin slots from the data location ''' builtin_slots = {} for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)): o = line.strip().split('\t') builtin_slots[inde...
Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor. def timer(logger=None, level=logging.INFO, fmt="function %(function_name)s execution time: %(execution_time).3f", *func_or_func_args, **timer_kwargs): """ Function d...
Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- points : np.array Vertices composing the triangles indices : np.array Indices describi...
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 T...
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. def show(block=False): ...
Helper to get the parent axes of a given mplobj 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 f...
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....
Generate isocurve from 2D data using marching squares algorithm. Parameters ---------- data : ndarray 2D numpy array of scalar values level : float The level at which to generate an isosurface connected : bool If False, return a single long list of point pairs If Tru...
The position of this event in the local coordinate system of the visual. 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 = t...
The mouse event immediately prior to this one. This property is None when no mouse buttons are pressed. 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: ...
The mouse press event that initiated a mouse drag, if any. 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 ...
Get lowercase string representation of enum. 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_'): ...
Draw a 2D texture to the current viewport Parameters ---------- tex : instance of Texture2D The texture to draw. def draw_texture(tex): """Draw a 2D texture to the current viewport Parameters ---------- tex : instance of Texture2D The texture to draw. """ from .pro...