sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def compute_positions(cls, screen_width, line): """Compute the relative position of the fields on a given line. Args: screen_width (int): the width of the screen line (mpdlcd.display_fields.Field list): the list of fields on the line Returns: ...
Compute the relative position of the fields on a given line. Args: screen_width (int): the width of the screen line (mpdlcd.display_fields.Field list): the list of fields on the line Returns: ((int, mpdlcd.display_fields.Field) list): the positions o...
entailment
def add_to_screen(self, screen_width, screen): """Add the pattern to a screen. Also fills self.widgets. Args: screen_width (int): the width of the screen screen (lcdprod.Screen): the screen to fill. """ for lineno, fields in enumerate(self.line_fields): ...
Add the pattern to a screen. Also fills self.widgets. Args: screen_width (int): the width of the screen screen (lcdprod.Screen): the screen to fill.
entailment
def register_hooks(self, field): """Register a field on its target hooks.""" for hook, subhooks in field.register_hooks(): self.hooks[hook].append(field) self.subhooks[hook] |= set(subhooks)
Register a field on its target hooks.
entailment
def hook_changed(self, hook, new_data): """Called whenever the data for a hook changed.""" for field in self.hooks[hook]: widget = self.widgets[field] field.hook_changed(hook, widget, new_data)
Called whenever the data for a hook changed.
entailment
def parse_line(self, line): """Parse a line of text. A format contains fields, within curly brackets, and free text. Maximum one 'variable width' field is allowed per line. You cannot use the '{' or '}' characters in the various text/... fields. Format: '''{<field_k...
Parse a line of text. A format contains fields, within curly brackets, and free text. Maximum one 'variable width' field is allowed per line. You cannot use the '{' or '}' characters in the various text/... fields. Format: '''{<field_kind>[ <field_option>,<field_option]} te...
entailment
def add(self, pattern_txt): """Add a pattern to the list. Args: pattern_txt (str list): the pattern, as a list of lines. """ self.patterns[len(pattern_txt)] = pattern_txt low = 0 high = len(pattern_txt) - 1 while not pattern_txt[low]: lo...
Add a pattern to the list. Args: pattern_txt (str list): the pattern, as a list of lines.
entailment
def _arcball(xy, wh): """Convert x,y coordinates to w,x,y,z Quaternion parameters Adapted from: linalg library Copyright (c) 2010-2015, Renaud Blanch <rndblnch at gmail dot com> Licence at your convenience: GPLv3 or higher <http://www.gnu.org/licenses/gpl.html> BSD new <http://opensource....
Convert x,y coordinates to w,x,y,z Quaternion parameters Adapted from: linalg library Copyright (c) 2010-2015, Renaud Blanch <rndblnch at gmail dot com> Licence at your convenience: GPLv3 or higher <http://www.gnu.org/licenses/gpl.html> BSD new <http://opensource.org/licenses/BSD-3-Clause>
entailment
def _update_rotation(self, event): """Update rotation parmeters based on mouse movement""" p2 = event.mouse_event.pos if self._event_value is None: self._event_value = p2 wh = self._viewbox.size self._quaternion = (Quaternion(*_arcball(p2, wh)) * ...
Update rotation parmeters based on mouse movement
entailment
def _rotate_tr(self): """Rotate the transformation matrix based on camera parameters""" rot, x, y, z = self._quaternion.get_axis_angle() up, forward, right = self._get_dim_vectors() self.transform.rotate(180 * rot / np.pi, (x, z, y))
Rotate the transformation matrix based on camera parameters
entailment
def _dist_to_trans(self, dist): """Convert mouse x, y movement into x, y, z translations""" rot, x, y, z = self._quaternion.get_axis_angle() tr = MatrixTransform() tr.rotate(180 * rot / np.pi, (x, y, z)) dx, dz, dy = np.dot(tr.matrix[:3, :3], (dist[0], dist[1], 0.)) retur...
Convert mouse x, y movement into x, y, z translations
entailment
def arg_to_array(func): """ Decorator to convert argument to array. Parameters ---------- func : function The function to decorate. Returns ------- func : function The decorated function. """ def fn(self, arg, *args, **kwargs): """Function Param...
Decorator to convert argument to array. Parameters ---------- func : function The function to decorate. Returns ------- func : function The decorated function.
entailment
def as_vec4(obj, default=(0, 0, 0, 1)): """ Convert `obj` to 4-element vector (numpy array with shape[-1] == 4) Parameters ---------- obj : array-like Original object. default : array-like The defaults to use if the object does not have 4 entries. Returns ------- ob...
Convert `obj` to 4-element vector (numpy array with shape[-1] == 4) Parameters ---------- obj : array-like Original object. default : array-like The defaults to use if the object does not have 4 entries. Returns ------- obj : array-like The object promoted to have 4...
entailment
def arg_to_vec4(func, self_, arg, *args, **kwargs): """ Decorator for converting argument to vec4 format suitable for 4x4 matrix multiplication. [x, y] => [[x, y, 0, 1]] [x, y, z] => [[x, y, z, 1]] [[x1, y1], [[x1, y1, 0, 1], [x2, y2], => [x2, y2, 0, 1], [x3, y3]] ...
Decorator for converting argument to vec4 format suitable for 4x4 matrix multiplication. [x, y] => [[x, y, 0, 1]] [x, y, z] => [[x, y, z, 1]] [[x1, y1], [[x1, y1, 0, 1], [x2, y2], => [x2, y2, 0, 1], [x3, y3]] [x3, y3, 0, 1]] If 1D input is provided, then the retu...
entailment
def get(self, path): """ Get a transform from the cache that maps along *path*, which must be a list of Transforms to apply in reverse order (last transform is applied first). Accessed items have their age reset to 0. """ key = tuple(map(id, path)) item = self._c...
Get a transform from the cache that maps along *path*, which must be a list of Transforms to apply in reverse order (last transform is applied first). Accessed items have their age reset to 0.
entailment
def roll(self): """ Increase the age of all items in the cache by 1. Items whose age is greater than self.max_age will be removed from the cache. """ rem = [] for key, item in self._cache.items(): if item[0] > self.max_age: rem.append(key) ...
Increase the age of all items in the cache by 1. Items whose age is greater than self.max_age will be removed from the cache.
entailment
def histogram(self, data, bins=10, color='w', orientation='h'): """Calculate and show a histogram of data Parameters ---------- data : array-like Data to histogram. Currently only 1D data is supported. bins : int | array-like Number of bins, or bin edges....
Calculate and show a histogram of data Parameters ---------- data : array-like Data to histogram. Currently only 1D data is supported. bins : int | array-like Number of bins, or bin edges. color : instance of Color Color of the histogram. ...
entailment
def image(self, data, cmap='cubehelix', clim='auto', fg_color=None): """Show an image Parameters ---------- data : ndarray Should have shape (N, M), (N, M, 3) or (N, M, 4). cmap : str Colormap name. clim : str | tuple Colormap limits. ...
Show an image Parameters ---------- data : ndarray Should have shape (N, M), (N, M, 3) or (N, M, 4). cmap : str Colormap name. clim : str | tuple Colormap limits. Should be ``'auto'`` or a two-element tuple of min and max values. ...
entailment
def mesh(self, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1.), fname=None, meshdata=None): """Show a 3D mesh Parameters ---------- vertices : array Vertices. faces : array | None Face defini...
Show a 3D mesh Parameters ---------- vertices : array Vertices. faces : array | None Face definitions. vertex_colors : array | None Vertex colors. face_colors : array | None Face colors. color : instance of Color ...
entailment
def plot(self, data, color='k', symbol=None, line_kind='-', width=1., marker_size=10., edge_color='k', face_color='b', edge_width=1., title=None, xlabel=None, ylabel=None): """Plot a series of data using lines and markers Parameters ---------- data : array | tw...
Plot a series of data using lines and markers Parameters ---------- data : array | two arrays Arguments can be passed as ``(Y,)``, ``(X, Y)`` or ``np.array((X, Y))``. color : instance of Color Color of the line. symbol : str Marker...
entailment
def spectrogram(self, x, n_fft=256, step=None, fs=1., window='hann', color_scale='log', cmap='cubehelix', clim='auto'): """Calculate and show a spectrogram Parameters ---------- x : array-like 1D signal to operate on. ``If len(x) < n_fft``, x will be ...
Calculate and show a spectrogram Parameters ---------- x : array-like 1D signal to operate on. ``If len(x) < n_fft``, x will be zero-padded to length ``n_fft``. n_fft : int Number of FFT points. Much faster for powers of two. step : int | None...
entailment
def volume(self, vol, clim=None, method='mip', threshold=None, cmap='grays'): """Show a 3D volume Parameters ---------- vol : ndarray Volume to render. clim : tuple of two floats | None The contrast limits. The values in the volume are mapp...
Show a 3D volume Parameters ---------- vol : ndarray Volume to render. clim : tuple of two floats | None The contrast limits. The values in the volume are mapped to black and white corresponding to these values. Default maps between min an...
entailment
def surface(self, zdata, **kwargs): """Show a 3D surface plot. Extra keyword arguments are passed to `SurfacePlot()`. Parameters ---------- zdata : array-like A 2D array of the surface Z values. """ self._configure_3d() surf = scene.SurfaceP...
Show a 3D surface plot. Extra keyword arguments are passed to `SurfacePlot()`. Parameters ---------- zdata : array-like A 2D array of the surface Z values.
entailment
def colorbar(self, cmap, position="right", label="", clim=("", ""), border_width=0.0, border_color="black", **kwargs): """Show a ColorBar Parameters ---------- cmap : str | vispy.color.ColorMap Either the name of the ColorMa...
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...
entailment
def redraw(self): """ Redraw the Vispy canvas """ if self._multiscat is not None: self._multiscat._update() self.vispy_widget.canvas.update()
Redraw the Vispy canvas
entailment
def remove(self): """ Remove the layer artist from the visualization """ if self._multiscat is None: return self._multiscat.deallocate(self.id) self._multiscat = None self._viewer_state.remove_global_callback(self._update_scatter) self.state...
Remove the layer artist from the visualization
entailment
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))
Helper to check valid options
entailment
def _to_args(x): """Convert to args representation""" if not isinstance(x, (list, tuple, np.ndarray)): x = [x] return x
Convert to args representation
entailment
def _check_conversion(key, valid_dict): """Check for existence of key in dict, return value or raise error""" if key not in valid_dict and key not in valid_dict.values(): # Only show users the nice string values keys = [v for v in valid_dict.keys() if isinstance(v, string_types)] raise V...
Check for existence of key in dict, return value or raise error
entailment
def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'): """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...
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,...
entailment
def get_gl_configuration(): """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. """ # XXX eventually maybe we...
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.
entailment
def set_viewport(self, *args): """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 fo...
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.
entailment
def set_depth_range(self, near=0., far=1.): """Set depth values Parameters ---------- near : float Near clipping plane. far : float Far clipping plane. """ self.glir.command('FUNC', 'glDepthRange', float(near), float(far))
Set depth values Parameters ---------- near : float Near clipping plane. far : float Far clipping plane.
entailment
def set_line_width(self, width=1.): """Set line width Parameters ---------- width : float The line width. """ width = float(width) if width < 0: raise RuntimeError('Cannot have width < 0') self.glir.command('FUNC', 'glLineWidth...
Set line width Parameters ---------- width : float The line width.
entailment
def set_polygon_offset(self, factor=0., units=0.): """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 Multiplie...
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 ...
entailment
def clear(self, color=True, depth=True, stencil=True): """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 ...
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 |...
entailment
def set_clear_color(self, color='black', alpha=None): """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 ...
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.
entailment
def set_blend_func(self, srgb='one', drgb='zero', salpha=None, dalpha=None): """Specify pixel arithmetic for RGB and alpha Parameters ---------- srgb : str Source RGB factor. drgb : str Destination RGB factor. salpha : s...
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...
entailment
def set_blend_equation(self, mode_rgb, mode_alpha=None): """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 ...
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.
entailment
def set_scissor(self, x, y, w, h): """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. ...
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.
entailment
def set_stencil_func(self, func='always', ref=0, mask=8, face='front_and_back'): """Set front or back function and reference value Parameters ---------- func : str See set_stencil_func. ref : int Reference value for the stenc...
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 ...
entailment
def set_stencil_mask(self, mask=8, face='front_and_back'): """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',...
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'.
entailment
def set_stencil_op(self, sfail='keep', dpfail='keep', dppass='keep', face='front_and_back'): """Set front or back stencil test actions Parameters ---------- sfail : str Action to take when the stencil fails. Must be one of 'keep', 'zero...
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...
entailment
def set_color_mask(self, red, green, blue, alpha): """Toggle writing of frame buffer color components Parameters ---------- red : bool Red toggle. green : bool Green toggle. blue : bool Blue toggle. alpha : bool ...
Toggle writing of frame buffer color components Parameters ---------- red : bool Red toggle. green : bool Green toggle. blue : bool Blue toggle. alpha : bool Alpha toggle.
entailment
def set_sample_coverage(self, value=1.0, invert=False): """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 inv...
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.
entailment
def set_state(self, preset=None, **kwargs): """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. ...
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...
entailment
def finish(self): """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. """ if ...
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.
entailment
def flush(self): """Flush GL commands This is a wrapper for glFlush(). This also flushes the GLIR command queue. """ if hasattr(self, 'flush_commands'): context = self else: context = get_current_canvas().context context.glir.command('...
Flush GL commands This is a wrapper for glFlush(). This also flushes the GLIR command queue.
entailment
def set_hint(self, target, mode): """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'). ...
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').
entailment
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.FakeCanvas.") raise RuntimeError('Gloo requir...
The GLIR queue corresponding to the current canvas
entailment
def use_gl(target='gl2'): """ 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 ...
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...
entailment
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 name.lower().startswith('gl'): if name not ...
Clear names that are not part of the strict ES API
entailment
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 BaseGLProxy's. """ # Get dicts if isinstance(source, BaseGLProxy): s = {} for key in dir(source): s[k...
Inject all objects that start with 'gl' from the source into the dest. source and dest can be dicts, modules or BaseGLProxy's.
entailment
def check_error(when='periodic check'): """ 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. """ errors = [] while True: err = glGetError() if ...
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.
entailment
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([repr(s) for s in arg.shape]) else: r...
Get a useful (and not too large) represetation of an argument.
entailment
def set_data(self, data): """ 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``. """ self._data = data ...
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``.
entailment
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=bool) connect[gaps[:-1]] = False return...
retrieve vertices and connects from given paths-list
entailment
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 existing examples, but should be tested # thoro...
compute LineVisual vertices, connects and color-index
entailment
def connect(self, callback, ref=False, position='first', before=None, after=None): """Connect this emitter to a new callback. Parameters ---------- callback : function | tuple *callback* may be either a callable object or a tuple (object, attr_nam...
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...
entailment
def disconnect(self, callback=None): """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. """ if callback is None: self._callbacks = [] ...
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.
entailment
def block(self, callback=None): """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 ...
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.
entailment
def unblock(self, callback=None): """ 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)``. """ ...
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)``.
entailment
def add(self, auto_connect=None, **kwargs): """ 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:: # Thi...
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...
entailment
def block_all(self): """ Block all emitters in this group. """ self.block() for em in self._emitters.values(): em.block()
Block all emitters in this group.
entailment
def unblock_all(self): """ Unblock all emitters in this group. """ self.unblock() for em in self._emitters.values(): em.unblock()
Unblock all emitters in this group.
entailment
def connect(self, callback, ref=False, position='first', before=None, after=None): """ 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>` ...
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.
entailment
def disconnect(self, callback=None): """ Disconnect the callback from this group. See :func:`connect() <vispy.event.EmitterGroup.connect>` and :func:`EventEmitter.connect() <vispy.event.EventEmitter.connect>` for more information. """ ret = EventEmitter.disconnect(self, c...
Disconnect the callback from this group. See :func:`connect() <vispy.event.EmitterGroup.connect>` and :func:`EventEmitter.connect() <vispy.event.EventEmitter.connect>` for more information.
entailment
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: if (banned & set(token)): ...
TODO add handling for bad input
entailment
def isosurface(data, level): """ 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 isosurf...
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...
entailment
def _extract_buffers(commands): """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.""" # First, filter all DATA commands. data_commands = [command for co...
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.
entailment
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): return dict([(key, _serialize_item(value)) ...
Internal function: serialize native types.
entailment
def create_glir_message(commands, array_serialization=None): """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 Se...
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: ...
entailment
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]), "screen_height": int...
Start Session
entailment
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 response: # N...
Request
entailment
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 Screen
entailment
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 ...
Add a key. (ref) Return key name or None on error
entailment
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)) self.keys.remove(ref) if "success" in response: ret...
Delete a key. (ref) Return None or LCDd response on error
entailment
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.VBro...
launch browser and virtual display, first of all to be launched
entailment
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])
css find function abbreviation
entailment
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, args=[css_path, dom])
return the first value of self.css
entailment
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])
name find function abbreviation
entailment
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])
xpath find function abbreviation
entailment
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
entailment
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])
check if element is present by css
entailment
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.exceptions.WebD...
login function
entailment
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") return True
logout func (quit browser)
entailment
def new_pos(self, html_div): """factory method pattern""" pos = self.Position(self, html_div) pos.bind_mov() self.positions.append(pos) return pos
factory method pattern
entailment
def _make_hostport(conn, default_host, default_port, default_user='', default_password=None): """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 t...
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...
entailment
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 wh...
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...
entailment
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.FieldRegis...
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.
entailment
def run_forever( lcdproc='', mpd='', lcdproc_screen=DEFAULT_LCD_SCREEN_NAME, lcdproc_charset=DEFAULT_LCDPROC_CHARSET, lcdd_debug=False, pattern='', patterns=[], refresh=DEFAULT_REFRESH, backlight_on=DEFAULT_BACKLIGHT_ON, priority_playing=DEFAULT_PRIORITY, ...
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...
entailment
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): ...
Read configuration from the given file. Parsing is performed through the configparser library. Returns: dict: a flattened dict of (option_name, value), using defaults.
entailment
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 ...
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...
entailment
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 giv...
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. ...
entailment
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.glir.associate(self.glir)
Activate/use this frame buffer.
entailment
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 is not None: return self.depth_buffer.shape[:2] i...
The shape of the Texture/RenderBuffer attached to this FrameBuffer
entailment
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 c...
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.
entailment
def read(self, mode='color', alpha=True): """ 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, ...
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 ------- ...
entailment
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...
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...
entailment
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 ...
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.
entailment
def _agg_bake(cls, vertices, color, closed=False): """ 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). """ n = len(vertices) ...
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).
entailment