text
stringlengths
81
112k
Called when this camera is changes its view. Also called when its associated with a viewbox. 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 anythi...
Canvas change event handler Parameters ---------- event : instance of Event The event. def on_canvas_change(self, event): """Canvas change event handler Parameters ---------- event : instance of Event The event. """ # Con...
Called by subclasses to configure the viewbox scene transform. 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...
Set the OpenGL configuration def _set_config(c): """Set the OpenGL configuration""" glformat = QGLFormat() glformat.setRedBufferSize(c['red_size']) glformat.setGreenBufferSize(c['green_size']) glformat.setBlueBufferSize(c['blue_size']) glformat.setAlphaBufferSize(c['alpha_size']) if QT5_NEW...
Get the window id of a PySide Widget. Might also work for PyQt4. 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)(w...
Six-hump camelback function def obj(x): """Six-hump camelback function""" x1 = x[0] x2 = x[1] f = (4 - 2.1*(x1*x1) + (x1*x1*x1*x1)/3.0)*(x1*x1) + x1*x2 + (-4 + 4*(x2*x2))*(x2*x2) return f
mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: medium, size: medium output: nice, some flaws, no dash) - "agg+" (speed: slow, size: big, output: perfect, no dash) def PathCollection(mode="agg", *args, **kwargs): """ ...
Map coordinates Parameters ---------- coords : array-like Coordinates to map. Returns ------- coords : ndarray Coordinates. def map(self, coords): """Map coordinates Parameters ---------- coords : array-like ...
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. def move(self, move): """Change the translation of this transform by the amount given. Paramete...
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 poin...
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. def from_mappin...
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...
Translate the matrix The translation is applied *after* the transformations already present in the matrix. Parameters ---------- pos : arrayndarray Position to translate by. def translate(self, pos): """ Translate the matrix The translation...
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 coor...
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 coordin...
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. def set_mapping(self, points1, points2): ...
Set ortho transform Parameters ---------- l : float Left. r : float Right. b : float Bottom. t : float Top. n : float Near. f : float Far. def set_ortho(self, l, r, b, t, n, f): ...
Set the perspective Parameters ---------- fov : float Field of view. aspect : float Aspect ratio. near : float Near location. far : float Far location. def set_perspective(self, fov, aspect, near, far): """Set the ...
Set the frustum Parameters ---------- l : float Left. r : float Right. b : float Bottom. t : float Top. n : float Near. f : float Far. def set_frustum(self, l, r, b, t, n, f): ...
See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for computing the log2 of a 32 bit integer using a look up table Parameters ---------- v : int 32 bit integer Returns ------- def log2_lut(v): """ See `this algo <https://graphics.stanfor...
~30% faster than the method below Parameters ---------- uniq Returns ------- def uniq2orderipix_lut(uniq): """ ~30% faster than the method below Parameters ---------- uniq Returns ------- """ order = log2_lut(uniq >> 2) >> 1 ipix = uniq - (1 << (2 * (order...
convert a HEALPix pixel coded as a NUNIQ number to a (norder, ipix) tuple def uniq2orderipix(uniq): """ convert a HEALPix pixel coded as a NUNIQ number to a (norder, ipix) tuple """ order = ((np.log2(uniq//4)) // 2) order = order.astype(int) ipix = uniq - 4 * (4**order) return orde...
Data can be numpy array or the size of data to allocate. def glBufferData(target, data, usage): """ Data can be numpy array or the size of data to allocate. """ if isinstance(data, int): size = data data = None else: size = data.nbytes GL.glBufferData(target, size, data, usa...
Set the line data Parameters ---------- data : array-like The data. **kwargs : dict Keywoard arguments to pass to MarkerVisual and LineVisal. def set_data(self, data=None, **kwargs): """Set the line data Parameters ---------- dat...
Set the data Parameters ---------- pos : float Position of the line along the axis. color : list, tuple, or array The color to use when drawing the line. If an array is given, it must be of shape (1, 4) and provide one rgba color per vertex. def set_...
Return the (min, max) bounding values of this visual along *axis* in the local coordinate system. def _compute_bounds(self, axis, view): """Return the (min, max) bounding values of this visual along *axis* in the local coordinate system. """ is_vertical = self._is_vertical ...
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 ...
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 ...
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 textur...
Render an EDF to a texture def _render_edf(self, orig_tex): """Render an EDF to a texture""" # Set up the necessary textures sdf_size = orig_tex.shape[:2] comp_texs = [] for _ in range(2): tex = Texture2D(sdf_size + (4,), format='rgba', i...
Interactively add a new intent to the intent schema object def _add_intent_interactive(self, intent_num=0): ''' Interactively add a new intent to the intent schema object ''' print ("Name of intent number : ", intent_num) slot_type_mappings = load_builtin_slots() ...
Build an IntentSchema from a file path creates a new intent schema if the file does not exist, throws an error if the file exists but cannot be loaded as a JSON def from_filename(self, filename): ''' Build an IntentSchema from a file path creates a new intent schema if the fil...
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 def launch_request_handler(request): """ Annotate functions with @VoiceHandler so that they can be automatically mapped to request types. Use th...
Use the 'intent' field in the VoiceHandler to map to the respective intent. 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: us...
This is a generic function to handle any intent that reads out a list of tweets 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 retur...
Return index if focused on tweet False if couldn't 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"]: ...
Takes care of things whenver the user says 'next' 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_to...
Get/create the default Application object It is safe to call this function multiple times, as long as backend_name is None or matches the already selected backend. Parameters ---------- backend_name : str | None The name of the backend application to use. If not specified, Vispy tr...
Data can be numpy array or the size of data to allocate. def glBufferData(target, data, usage): """ Data can be numpy array or the size of data to allocate. """ if isinstance(data, int): size = data data = ctypes.c_voidp(0) else: if not data.flags['C_CONTIGUOUS'] or not data.fla...
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...
Get the bounds of the Visual Parameters ---------- axis : int The axis. view : instance of VisualView The view to use. def bounds(self, axis, view=None): """Get the bounds of the Visual Parameters ---------- axis : int ...
Define the set of GL state parameters to use when drawing Parameters ---------- preset : str Preset to use. **kwargs : dict Keyword arguments to `gloo.set_state`. def set_gl_state(self, preset=None, **kwargs): """Define the set of GL state parameters to ...
Modify the set of GL state parameters to use when drawing Parameters ---------- *args : tuple Arguments. **kwargs : dict Keyword argments. def update_gl_state(self, *args, **kwargs): """Modify the set of GL state parameters to use when drawing P...
Return a FunctionChain that Filters may use to modify the program. *shader* should be "frag" or "vert" *name* should be "pre" or "post" def _get_hook(self, shader, name): """Return a FunctionChain that Filters may use to modify the program. *shader* should be "frag" or "vert" ...
Attach a Filter to this visual Each filter modifies the appearance or behavior of the visual. Parameters ---------- filt : object The filter to attach. view : instance of VisualView | None The view to use. def attach(self, filt, view=None): """A...
Detach a filter. Parameters ---------- filt : object The filter to detach. view : instance of VisualView | None The view to use. def detach(self, filt, view=None): """Detach a filter. Parameters ---------- filt : object ...
Add a subvisual Parameters ---------- visual : instance of Visual The visual to add. def add_subvisual(self, visual): """Add a subvisual Parameters ---------- visual : instance of Visual The visual to add. """ visual.tran...
Remove a subvisual Parameters ---------- visual : instance of Visual The visual to remove. def remove_subvisual(self, visual): """Remove a subvisual Parameters ---------- visual : instance of Visual The visual to remove. """ ...
Draw the visual 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()
Define the set of GL state parameters to use when drawing Parameters ---------- preset : str Preset to use. **kwargs : dict Keyword arguments to `gloo.set_state`. def set_gl_state(self, preset=None, **kwargs): """Define the set of GL state parameters to ...
Modify the set of GL state parameters to use when drawing Parameters ---------- *args : tuple Arguments. **kwargs : dict Keyword argments. def update_gl_state(self, *args, **kwargs): """Modify the set of GL state parameters to use when drawing P...
Attach a Filter to this visual Each filter modifies the appearance or behavior of the visual. Parameters ---------- filt : object The filter to attach. view : instance of VisualView | None The view to use. def attach(self, filt, view=None): """A...
Detach a filter. Parameters ---------- filt : object The filter to detach. view : instance of VisualView | None The view to use. def detach(self, filt, view=None): """Detach a filter. Parameters ---------- filt : object ...
main function for placing movements stop_limit = {'gain': [mode, value], 'loss': [mode, value]} def addMov(self, product, quantity=None, mode="buy", stop_limit=None, auto_margin=None, name_counter=None): """main function for placing movements stop_limit = {'gain': [mode, value], ...
check all positions def checkPos(self): """check all positions""" soup = BeautifulSoup(self.css1(path['movs-table']).html, 'html.parser') poss = [] for label in soup.find_all("tr"): pos_id = label['id'] # init an empty list # check if it already exist...
check stocks in preference def checkStock(self): """check stocks in preference""" if not self.preferences: logger.debug("no preferences") return None soup = BeautifulSoup( self.xpath(path['stock-table'])[0].html, "html.parser") count = 0 # ite...
clear the left panel and preferences 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...
add preference in self.preferences 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() ...
Load glyph from font into dict 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 = _loa...
Assign a clipper that is inherited from a parent node. If *clipper* is None, then remove any clippers for *node*. def _set_clipper(self, node, clipper): """Assign a clipper that is inherited from a parent node. If *clipper* is None, then remove any clippers for *node*. """ if ...
Transform object(s) have changed for this Node; assign these to the visual's TransformSystem. def _update_trsys(self, event): """Transform object(s) have changed for this Node; assign these to the visual's TransformSystem. """ doc = self.document_node scene = self.scene_...
Convert CFNumber to python int or float. def cfnumber_to_number(cfnumber): """Convert CFNumber to python int or float.""" numeric_type = cf.CFNumberGetType(cfnumber) cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16, kCFNumberSInt32Type: c_int32, ...
Convert a CFType into an equivalent python type. The convertible CFTypes are taken from the known_cftypes dictionary, which may be added to if another library implements its own conversion methods. def cftype_to_value(cftype): """Convert a CFType into an equivalent python type. The convertible CFTy...
Convert CFSet to python set. def cfset_to_set(cfset): """Convert CFSet to python set.""" count = cf.CFSetGetCount(cfset) buffer = (c_void_p * count)() cf.CFSetGetValues(cfset, byref(buffer)) return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])
Convert CFArray to python list. def cfarray_to_list(cfarray): """Convert CFArray to python list.""" count = cf.CFArrayGetCount(cfarray) return [cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i))) for i in range(count)]
Return ctypes type for an encoded Objective-C type. def ctype_for_encoding(self, encoding): """Return ctypes type for an encoded Objective-C type.""" if encoding in self.typecodes: return self.typecodes[encoding] elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes: ...
Function decorator for class methods. def classmethod(self, encoding): """Function decorator for class methods.""" # Add encodings for hidden self and cmd arguments. encoding = ensure_bytes(encoding) typecodes = parse_type_encoding(encoding) typecodes.insert(1, b'@:') en...
Append a new set of segments to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- P : np.array Vertices positions of the path(s) to be added itemsize: int or None Size ...
Get the fragment shader code - we use the shader_program object to determine which layers are enabled and therefore what to include in the shader code. def get_frag_shader(volumes, clipped=False, n_volume_max=5): """ Get the fragment shader code - we use the shader_program object to determine which lay...
Connect to the EGL display server. def eglGetDisplay(display=EGL_DEFAULT_DISPLAY): """ Connect to the EGL display server. """ res = _lib.eglGetDisplay(display) if not res or res == EGL_NO_DISPLAY: raise RuntimeError('Could not create display') return res
Initialize EGL and return EGL version tuple. def eglInitialize(display): """ Initialize EGL and return EGL version tuple. """ majorVersion = (_c_int*1)() minorVersion = (_c_int*1)() res = _lib.eglInitialize(display, majorVersion, minorVersion) if res == EGL_FALSE: raise RuntimeError('Co...
Query string from display def eglQueryString(display, name): """ Query string from display """ out = _lib.eglQueryString(display, name) if not out: raise RuntimeError('Could not query %s' % name) return out
Edges of the mesh Parameters ---------- indexed : str | None If indexed is None, return (Nf, 3) array of vertex indices, two per edge in the mesh. If indexed is 'faces', then return (Nf, 3, 2) array of vertex indices with 3 edges per face, and...
Set the faces Parameters ---------- faces : ndarray (Nf, 3) array of faces. Each row in the array contains three indices into the vertex array, specifying the three corners of a triangular face. def set_faces(self, faces): """Set the faces P...
Get the vertices Parameters ---------- indexed : str | None If Note, return an array (N,3) of the positions of vertices in the mesh. By default, each unique vertex appears only once. If indexed is 'faces', then the array will instead contain three ...
Get the mesh bounds Returns ------- bounds : list A list of tuples of mesh bounds. def get_bounds(self): """Get the mesh bounds Returns ------- bounds : list A list of tuples of mesh bounds. """ if self._vertices_indexed_...
Set the mesh vertices Parameters ---------- verts : ndarray | None The array (Nv, 3) of vertex coordinates. indexed : str | None If indexed=='faces', then the data must have shape (Nf, 3, 3) and is assumed to be already indexed as a list of faces. Thi...
Return True if this data set has vertex color information def has_vertex_color(self): """Return True if this data set has vertex color information""" for v in (self._vertex_colors, self._vertex_colors_indexed_by_faces, self._vertex_colors_indexed_by_edges): if v is not Non...
Return True if this data set has face color information def has_face_color(self): """Return True if this data set has face color information""" for v in (self._face_colors, self._face_colors_indexed_by_faces, self._face_colors_indexed_by_edges): if v is not None: ...
Get face normals Parameters ---------- indexed : str | None If None, return an array (Nf, 3) of normal vectors for each face. If 'faces', then instead return an indexed array (Nf, 3, 3) (this is just the same array with each vector copied three times). ...
Get vertex normals Parameters ---------- indexed : str | None If None, return an (N, 3) array of normal vectors with one entry per unique vertex in the mesh. If indexed is 'faces', then the array will contain three normal vectors per face (and some ...
Get vertex colors Parameters ---------- indexed : str | None If None, return an array (Nv, 4) of vertex colors. If indexed=='faces', then instead return an indexed array (Nf, 3, 4). Returns ------- colors : ndarray The ver...
Set the vertex color array Parameters ---------- colors : array Array of colors. Must have shape (Nv, 4) (indexing by vertex) or shape (Nf, 3, 4) (vertices indexed by face). indexed : str | None Should be 'faces' if colors are indexed by faces. def s...
Get the face colors Parameters ---------- indexed : str | None If indexed is None, return (Nf, 4) array of face colors. If indexed=='faces', then instead return an indexed array (Nf, 3, 4) (note this is just the same array with each color repeate...
Set the face color array Parameters ---------- colors : array Array of colors. Must have shape (Nf, 4) (indexed by face), or shape (Nf, 3, 4) (face colors indexed by faces). indexed : str | None Should be 'faces' if colors are indexed by faces. def s...
The number of faces in the mesh def n_faces(self): """The number of faces in the mesh""" if self._faces is not None: return self._faces.shape[0] elif self._vertices_indexed_by_faces is not None: return self._vertices_indexed_by_faces.shape[0]
List mapping each vertex index to a list of face indices that use it. def get_vertex_faces(self): """ List mapping each vertex index to a list of face indices that use it. """ if self._vertex_faces is None: self._vertex_faces = [[] for i in xrange(len(self.get_vertices()))] ...
Serialize this mesh to a string appropriate for disk storage Returns ------- state : dict The state. def save(self): """Serialize this mesh to a string appropriate for disk storage Returns ------- state : dict The state. """ ...
Restore the state of a mesh previously saved using save() Parameters ---------- state : dict The previous state. def restore(self, state): """Restore the state of a mesh previously saved using save() Parameters ---------- state : dict Th...
A full implementation of Dave Green's "cubehelix" for Matplotlib. Based on the FORTRAN 77 code provided in D.A. Green, 2011, BASI, 39, 289. http://adsabs.harvard.edu/abs/2011arXiv1108.5083G User can adjust all parameters of the cubehelix algorithm. This enables much greater flexibility in choosing...
Convert matplotlib color code to hex color code def color_to_hex(color): """Convert matplotlib color code to hex color code""" if color is None or colorConverter.to_rgba(color)[3] == 0: return 'none' else: rgb = colorConverter.to_rgb(color) return '#{0:02X}{1:02X}{2:02X}'.format(*(i...
Convert a many-to-one mapping to a one-to-one mapping def _many_to_one(input_dict): """Convert a many-to-one mapping to a one-to-one mapping""" return dict((key, val) for keys, val in input_dict.items() for key in keys)
Get an SVG dash array for the given matplotlib linestyle Parameters ---------- obj : matplotlib object The matplotlib line or path object, which must have a get_linestyle() method which returns a valid matplotlib line code Returns ------- dasharray : string The HTML/SVG...
Construct the vertices and SVG codes for the path Parameters ---------- path : matplotlib.Path object transform : matplotlib transform (optional) if specified, the path will be transformed before computing the output. Returns ------- vertices : array The shape (M, 2) array...
Get the style dictionary for matplotlib path objects def get_path_style(path, fill=True): """Get the style dictionary for matplotlib path objects""" style = {} style['alpha'] = path.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['edgecolor'] = color_to_hex(path.get_edgecolo...
Get the style dictionary for matplotlib line objects def get_line_style(line): """Get the style dictionary for matplotlib line objects""" style = {} style['alpha'] = line.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['color'] = color_to_hex(line.get_color()) style['lin...
Get the style dictionary for matplotlib marker objects def get_marker_style(line): """Get the style dictionary for matplotlib marker objects""" style = {} style['alpha'] = line.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['facecolor'] = color_to_hex(line.get_markerfaceco...
Return the text style dict for a text instance def get_text_style(text): """Return the text style dict for a text instance""" style = {} style['alpha'] = text.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['fontsize'] = text.get_size() style['color'] = color_to_hex(text...
Return the property dictionary for a matplotlib.Axis instance def get_axis_properties(axis): """Return the property dictionary for a matplotlib.Axis instance""" props = {} label1On = axis._major_tick_kw.get('label1On', True) if isinstance(axis, matplotlib.axis.XAxis): if label1On: ...
Returns an iterator over all childen and nested children using obj's get_children() method if skipContainers is true, only childless objects are returned. def iter_all_children(obj, skipContainers=False): """ Returns an iterator over all childen and nested children using obj's get_children() metho...