sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def disable_gui(self):
"""Disable GUI event loop integration.
If an application was registered, this sets its ``_in_event_loop``
attribute to False. It then calls :meth:`clear_inputhook`.
"""
gui = self._current_gui
if gui in self.apps:
self.apps[gui]... | Disable GUI event loop integration.
If an application was registered, this sets its ``_in_event_loop``
attribute to False. It then calls :meth:`clear_inputhook`. | entailment |
def set_current_canvas(canvas):
""" Make a canvas active. Used primarily by the canvas itself.
"""
# Notify glir
canvas.context._do_CURRENT_command = True
# Try to be quick
if canvasses and canvasses[-1]() is canvas:
return
# Make this the current
cc = [c() for c in canvasses if... | Make a canvas active. Used primarily by the canvas itself. | entailment |
def forget_canvas(canvas):
""" Forget about the given canvas. Used by the canvas when closed.
"""
cc = [c() for c in canvasses if c() is not None]
while canvas in cc:
cc.remove(canvas)
canvasses[:] = [weakref.ref(c) for c in cc] | Forget about the given canvas. Used by the canvas when closed. | entailment |
def create_shared(self, name, ref):
""" For the app backends to create the GLShared object.
Parameters
----------
name : str
The name.
ref : object
The reference.
"""
if self._shared is not None:
raise RuntimeError('Can only se... | For the app backends to create the GLShared object.
Parameters
----------
name : str
The name.
ref : object
The reference. | entailment |
def flush_commands(self, event=None):
""" Flush
Parameters
----------
event : instance of Event
The event.
"""
if self._do_CURRENT_command:
self._do_CURRENT_command = False
canvas = get_current_canvas()
if canvas and hasatt... | Flush
Parameters
----------
event : instance of Event
The event. | entailment |
def add_ref(self, name, ref):
""" Add a reference for the backend object that gives access
to the low level context. Used in vispy.app.canvas.backends.
The given name must match with that of previously added
references.
"""
if self._name is None:
self._name = ... | Add a reference for the backend object that gives access
to the low level context. Used in vispy.app.canvas.backends.
The given name must match with that of previously added
references. | entailment |
def ref(self):
""" A reference (stored internally via a weakref) to an object
that the backend system can use to obtain the low-level
information of the "reference context". In Vispy this will
typically be the CanvasBackend object.
"""
# Clean
self._refs = [r for ... | A reference (stored internally via a weakref) to an object
that the backend system can use to obtain the low-level
information of the "reference context". In Vispy this will
typically be the CanvasBackend object. | entailment |
def get_dpi(raise_error=True):
"""Get screen DPI from the OS
Parameters
----------
raise_error : bool
If True, raise an error if DPI could not be determined.
Returns
-------
dpi : float
Dots per inch of the primary screen.
"""
display = quartz.CGMainDisplayID()
... | Get screen DPI from the OS
Parameters
----------
raise_error : bool
If True, raise an error if DPI could not be determined.
Returns
-------
dpi : float
Dots per inch of the primary screen. | entailment |
def link(self, var):
""" Link this Varying to another object from which it will derive its
dtype. This method is used internally when assigning an attribute to
a varying using syntax ``Function[varying] = attr``.
"""
assert self._dtype is not None or hasattr(var, 'dtype')
... | Link this Varying to another object from which it will derive its
dtype. This method is used internally when assigning an attribute to
a varying using syntax ``Function[varying] = attr``. | entailment |
def obj(x):
"""Two Dimensional Shubert Function"""
j = np.arange(1, 6)
tmp1 = np.dot(j, np.cos((j+1)*x[0] + j))
tmp2 = np.dot(j, np.cos((j+1)*x[1] + j))
return tmp1 * tmp2 | Two Dimensional Shubert Function | entailment |
def besj(self, x, n):
'''
Function BESJ calculates Bessel function of first kind of order n
Arguments:
n - an integer (>=0), the order
x - value at which the Bessel function is required
--------------------
C++ Mathematical Library
Converted from e... | Function BESJ calculates Bessel function of first kind of order n
Arguments:
n - an integer (>=0), the order
x - value at which the Bessel function is required
--------------------
C++ Mathematical Library
Converted from equivalent FORTRAN library
Converte... | entailment |
def copy(self):
""" Create an exact copy of this quaternion.
"""
return Quaternion(self.w, self.x, self.y, self.z, False) | Create an exact copy of this quaternion. | entailment |
def norm(self):
""" Returns the norm of the quaternion
norm = w**2 + x**2 + y**2 + z**2
"""
tmp = self.w**2 + self.x**2 + self.y**2 + self.z**2
return tmp**0.5 | Returns the norm of the quaternion
norm = w**2 + x**2 + y**2 + z**2 | entailment |
def _normalize(self):
""" Make the quaternion unit length.
"""
# Get length
L = self.norm()
if not L:
raise ValueError('Quaternion cannot have 0-length.')
# Correct
self.w /= L
self.x /= L
self.y /= L
self.z /= L | Make the quaternion unit length. | entailment |
def conjugate(self):
""" Obtain the conjugate of the quaternion.
This is simply the same quaternion but with the sign of the
imaginary (vector) parts reversed.
"""
new = self.copy()
new.x *= -1
new.y *= -1
new.z *= -1
return new | Obtain the conjugate of the quaternion.
This is simply the same quaternion but with the sign of the
imaginary (vector) parts reversed. | entailment |
def inverse(self):
""" returns q.conjugate()/q.norm()**2
So if the quaternion is unit length, it is the same
as the conjugate.
"""
new = self.conjugate()
tmp = self.norm()**2
new.w /= tmp
new.x /= tmp
new.y /= tmp
new.z /= tmp
... | returns q.conjugate()/q.norm()**2
So if the quaternion is unit length, it is the same
as the conjugate. | entailment |
def exp(self):
""" Returns the exponent of the quaternion.
(not tested)
"""
# Init
vecNorm = self.x**2 + self.y**2 + self.z**2
wPart = np.exp(self.w)
q = Quaternion()
# Calculate
q.w = wPart * np.cos(vecNorm)
q.x ... | Returns the exponent of the quaternion.
(not tested) | entailment |
def log(self):
""" Returns the natural logarithm of the quaternion.
(not tested)
"""
# Init
norm = self.norm()
vecNorm = self.x**2 + self.y**2 + self.z**2
tmp = self.w / norm
q = Quaternion()
# Calculate
q.w = np.log(norm... | Returns the natural logarithm of the quaternion.
(not tested) | entailment |
def rotate_point(self, p):
""" Rotate a Point instance using this quaternion.
"""
# Prepare
p = Quaternion(0, p[0], p[1], p[2], False) # Do not normalize!
q1 = self.normalize()
q2 = self.inverse()
# Apply rotation
r = (q1*p)*q2
# Make point and r... | Rotate a Point instance using this quaternion. | entailment |
def get_matrix(self):
""" Create a 4x4 homography matrix that represents the rotation
of the quaternion.
"""
# Init matrix (remember, a matrix, not an array)
a = np.zeros((4, 4), dtype=np.float32)
w, x, y, z = self.w, self.x, self.y, self.z
# First row
a[0... | Create a 4x4 homography matrix that represents the rotation
of the quaternion. | entailment |
def get_axis_angle(self):
""" Get the axis-angle representation of the quaternion.
(The angle is in radians)
"""
# Init
angle = 2 * np.arccos(max(min(self.w, 1.), -1.))
scale = (self.x**2 + self.y**2 + self.z**2)**0.5
# Calc axis
if scale:
... | Get the axis-angle representation of the quaternion.
(The angle is in radians) | entailment |
def create_from_axis_angle(cls, angle, ax, ay, az, degrees=False):
""" Classmethod to create a quaternion from an axis-angle representation.
(angle should be in radians).
"""
if degrees:
angle = np.radians(angle)
while angle < 0:
angle += np.pi*2
... | Classmethod to create a quaternion from an axis-angle representation.
(angle should be in radians). | entailment |
def create_from_euler_angles(cls, rx, ry, rz, degrees=False):
""" Classmethod to create a quaternion given the euler angles.
"""
if degrees:
rx, ry, rz = np.radians([rx, ry, rz])
# Obtain quaternions
qx = Quaternion(np.cos(rx/2), 0, 0, np.sin(rx/2))
qy = Quate... | Classmethod to create a quaternion given the euler angles. | entailment |
def as_enum(enum):
""" Turn a possibly string enum into an integer enum.
"""
if isinstance(enum, string_types):
try:
enum = getattr(gl, 'GL_' + enum.upper())
except AttributeError:
try:
enum = _internalformats['GL_' + enum.upper()]
except K... | Turn a possibly string enum into an integer enum. | entailment |
def convert_shaders(convert, shaders):
""" Modify shading code so that we can write code once
and make it run "everywhere".
"""
# New version of the shaders
out = []
if convert == 'es2':
for isfragment, shader in enumerate(shaders):
has_version = False
has_prec... | Modify shading code so that we can write code once
and make it run "everywhere". | entailment |
def as_es2_command(command):
""" Modify a desktop command so it works on es2.
"""
if command[0] == 'FUNC':
return (command[0], re.sub(r'^gl([A-Z])',
lambda m: m.group(1).lower(), command[1])) + command[2:]
if command[0] == 'SHADERS':
return command[:2] + convert_shaders(... | Modify a desktop command so it works on es2. | entailment |
def _check_pyopengl_3D():
"""Helper to ensure users have OpenGL for 3D texture support (for now)"""
global USE_TEX_3D
USE_TEX_3D = True
try:
import OpenGL.GL as _gl
except ImportError:
raise ImportError('PyOpenGL is required for 3D texture support')
return _gl | Helper to ensure users have OpenGL for 3D texture support (for now) | entailment |
def show(self, filter=None):
""" Print the list of commands currently in the queue. If filter is
given, print only commands that match the filter.
"""
for command in self._commands:
if command[0] is None: # or command[1] in self._invalid_objects:
continue # ... | Print the list of commands currently in the queue. If filter is
given, print only commands that match the filter. | entailment |
def flush(self, parser):
""" Flush all current commands to the GLIR interpreter.
"""
if self._verbose:
show = self._verbose if isinstance(self._verbose, str) else None
self.show(show)
parser.parse(self._filter(self.clear(), parser)) | Flush all current commands to the GLIR interpreter. | entailment |
def _filter(self, commands, parser):
""" Filter DATA/SIZE commands that are overridden by a
SIZE command.
"""
resized = set()
commands2 = []
for command in reversed(commands):
if command[0] == 'SHADERS':
convert = parser.convert_shaders()
... | Filter DATA/SIZE commands that are overridden by a
SIZE command. | entailment |
def associate(self, queue):
"""Merge this queue with another.
Both queues will use a shared command list and either one can be used
to fill or flush the shared queue.
"""
assert isinstance(queue, GlirQueue)
if queue._shared is self._shared:
return
# ... | Merge this queue with another.
Both queues will use a shared command list and either one can be used
to fill or flush the shared queue. | entailment |
def _parse(self, command):
""" Parse a single command.
"""
cmd, id_, args = command[0], command[1], command[2:]
if cmd == 'CURRENT':
# This context is made current
self.env.clear()
self._gl_initialize()
self.env['fbo'] = args[0]
... | Parse a single command. | entailment |
def parse(self, commands):
""" Parse a list of commands.
"""
# Get rid of dummy objects that represented deleted objects in
# the last parsing round.
to_delete = []
for id_, val in self._objects.items():
if val == JUST_DELETED:
to_delete.appen... | Parse a list of commands. | entailment |
def _gl_initialize(self):
""" Deal with compatibility; desktop does not have sprites
enabled by default. ES has.
"""
if '.es' in gl.current_backend.__name__:
pass # ES2: no action required
else:
# Desktop, enable sprites
GL_VERTEX_PROGRAM_POIN... | Deal with compatibility; desktop does not have sprites
enabled by default. ES has. | entailment |
def activate(self):
""" Avoid overhead in calling glUseProgram with same arg.
Warning: this will break if glUseProgram is used somewhere else.
Per context we keep track of one current program.
"""
if self._handle != self._parser.env.get('current_program', False):
self... | Avoid overhead in calling glUseProgram with same arg.
Warning: this will break if glUseProgram is used somewhere else.
Per context we keep track of one current program. | entailment |
def deactivate(self):
""" Avoid overhead in calling glUseProgram with same arg.
Warning: this will break if glUseProgram is used somewhere else.
Per context we keep track of one current program.
"""
if self._parser.env.get('current_program', 0) != 0:
self._parser.env[... | Avoid overhead in calling glUseProgram with same arg.
Warning: this will break if glUseProgram is used somewhere else.
Per context we keep track of one current program. | entailment |
def set_shaders(self, vert, frag):
""" This function takes care of setting the shading code and
compiling+linking it into a working program object that is ready
to use.
"""
self._linked = False
# Create temporary shader objects
vert_handle = gl.glCreateShader(gl.G... | This function takes care of setting the shading code and
compiling+linking it into a working program object that is ready
to use. | entailment |
def _get_active_attributes_and_uniforms(self):
""" Retrieve active attributes and uniforms to be able to check that
all uniforms/attributes are set by the user.
Other GLIR implementations may omit this.
"""
# This match a name of the form "name[size]" (= array)
regex = re... | Retrieve active attributes and uniforms to be able to check that
all uniforms/attributes are set by the user.
Other GLIR implementations may omit this. | entailment |
def _parse_error(self, error):
""" Parses a single GLSL error and extracts the linenr and description
Other GLIR implementations may omit this.
"""
error = str(error)
# Nvidia
# 0(7): error C1008: undefined variable "MV"
m = re.match(r'(\d+)\((\d+)\)\s*:\s(.*)', e... | Parses a single GLSL error and extracts the linenr and description
Other GLIR implementations may omit this. | entailment |
def _get_error(self, code, errors, indentation=0):
"""Get error and show the faulty line + some context
Other GLIR implementations may omit this.
"""
# Init
results = []
lines = None
if code is not None:
lines = [line.strip() for line in code.split('\n... | Get error and show the faulty line + some context
Other GLIR implementations may omit this. | entailment |
def set_texture(self, name, value):
""" Set a texture sampler. Value is the id of the texture to link.
"""
if not self._linked:
raise RuntimeError('Cannot set uniform when program has no code')
# Get handle for the uniform, first try cache
handle = self._handles.get(n... | Set a texture sampler. Value is the id of the texture to link. | entailment |
def set_uniform(self, name, type_, value):
""" Set a uniform value. Value is assumed to have been checked.
"""
if not self._linked:
raise RuntimeError('Cannot set uniform when program has no code')
# Get handle for the uniform, first try cache
handle = self._handles.g... | Set a uniform value. Value is assumed to have been checked. | entailment |
def set_attribute(self, name, type_, value):
""" Set an attribute value. Value is assumed to have been checked.
"""
if not self._linked:
raise RuntimeError('Cannot set attribute when program has no code')
# Get handle for the attribute, first try cache
handle = self._... | Set an attribute value. Value is assumed to have been checked. | entailment |
def draw(self, mode, selection):
""" Draw program in given mode, with given selection (IndexBuffer or
first, count).
"""
if not self._linked:
raise RuntimeError('Cannot draw program if code has not been set')
# Init
gl.check_error('Check before draw')
... | Draw program in given mode, with given selection (IndexBuffer or
first, count). | entailment |
def as_matrix_transform(transform):
"""
Simplify a transform to a single matrix transform, which makes it a lot
faster to compute transformations.
Raises a TypeError if the transform cannot be simplified.
"""
if isinstance(transform, ChainTransform):
matrix = np.identity(4)
for ... | Simplify a transform to a single matrix transform, which makes it a lot
faster to compute transformations.
Raises a TypeError if the transform cannot be simplified. | entailment |
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
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 arrow... | Places all nodes on a single circle.
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.
... | entailment |
def append(self, P, closed=False, itemsize=None, **kwargs):
"""
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
----------
P : np.array
Vertices posit... | 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
----------
P : np.array
Vertices positions of the path(s) to be added
closed: bool
Whether path(s... | entailment |
def draw(self, mode="triangles"):
""" Draw collection """
gl.glDepthMask(0)
Collection.draw(self, mode)
gl.glDepthMask(1) | Draw collection | entailment |
def set_data(self, pos=None, symbol='o', size=10., edge_width=1.,
edge_width_rel=None, edge_color='black', face_color='white',
scaling=False):
""" Set the data used to display this visual.
Parameters
----------
pos : array
The array of locat... | Set the data used to display this visual.
Parameters
----------
pos : array
The array of locations to display each symbol.
symbol : str
The style of symbol to draw (see Notes).
size : float or array
The symbol size in px.
edge_width : ... | entailment |
def hook_changed(self, hook_name, widget, new_data):
"""Handle a hook upate."""
if hook_name == 'song':
self.song_changed(widget, new_data)
elif hook_name == 'state':
self.state_changed(widget, new_data)
elif hook_name == 'elapsed_and_total':
elapsed, ... | Handle a hook upate. | entailment |
def update(self, func, **kw):
"Update the signature of func with the data in self"
func.__name__ = self.name
func.__doc__ = getattr(self, 'doc', None)
func.__dict__ = getattr(self, 'dict', {})
func.__defaults__ = getattr(self, 'defaults', ())
func.__kwdefaults__ = getattr... | Update the signature of func with the data in self | entailment |
def make(self, src_templ, evaldict=None, addsource=False, **attrs):
"Make a new function from a given template and update the signature"
src = src_templ % vars(self) # expand name and signature
evaldict = evaldict or {}
mo = DEF.match(src)
if mo is None:
raise SyntaxE... | Make a new function from a given template and update the signature | entailment |
def create(cls, obj, body, evaldict, defaults=None,
doc=None, module=None, addsource=True, **attrs):
"""
Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an attribute
__source__ is added to the result.... | Create a function from the strings name, signature and body.
evaldict is the evaluation dictionary. If addsource is true an attribute
__source__ is added to the result. The attributes attrs are added,
if any. | entailment |
def set_data(self, data=None, vertex_colors=None, face_colors=None,
color=None):
""" Set the scalar array data
Parameters
----------
data : ndarray
A 3D array of scalar values. The isosurface is constructed to show
all locations in the scalar fie... | Set the scalar array data
Parameters
----------
data : ndarray
A 3D array of scalar values. The isosurface is constructed to show
all locations in the scalar field equal to ``self.level``.
vertex_colors : array-like | None
Colors to use for each verte... | entailment |
def get_scene_bounds(self, dim=None):
"""Get the total bounds based on the visuals present in the scene
Parameters
----------
dim : int | None
Dimension to return.
Returns
-------
bounds : list | tuple
If ``dim is None``, Returns a list o... | Get the total bounds based on the visuals present in the scene
Parameters
----------
dim : int | None
Dimension to return.
Returns
-------
bounds : list | tuple
If ``dim is None``, Returns a list of 3 tuples, otherwise
the bounds for ... | entailment |
def _string_to_rgb(color):
"""Convert user string or hex color to color array (length 3 or 4)"""
if not color.startswith('#'):
if color.lower() not in _color_dict:
raise ValueError('Color "%s" unknown' % color)
color = _color_dict[color]
assert color[0] == '#'
# hex color... | Convert user string or hex color to color array (length 3 or 4) | entailment |
def _user_to_rgba(color, expand=True, clip=False):
"""Convert color(s) from any set of fmts (str/hex/arr) to RGB(A) array"""
if color is None:
color = np.zeros(4, np.float32)
if isinstance(color, string_types):
color = _string_to_rgb(color)
elif isinstance(color, ColorArray):
col... | Convert color(s) from any set of fmts (str/hex/arr) to RGB(A) array | entailment |
def _array_clip_val(val):
"""Helper to turn val into array and clip between 0 and 1"""
val = np.array(val)
if val.max() > 1 or val.min() < 0:
logger.warning('value will be clipped between 0 and 1')
val[...] = np.clip(val, 0, 1)
return val | Helper to turn val into array and clip between 0 and 1 | entailment |
def extend(self, colors):
"""Extend a ColorArray with new colors
Parameters
----------
colors : instance of ColorArray
The new colors.
"""
colors = ColorArray(colors)
self._rgba = np.vstack((self._rgba, colors._rgba))
return self | Extend a ColorArray with new colors
Parameters
----------
colors : instance of ColorArray
The new colors. | entailment |
def rgba(self, val):
"""Set the color using an Nx4 array of RGBA floats"""
# Note: all other attribute sets get routed here!
# This method is meant to do the heavy lifting of setting data
rgba = _user_to_rgba(val, expand=False)
if self._rgba is None:
self._rgba = rgba... | Set the color using an Nx4 array of RGBA floats | entailment |
def RGBA(self, val):
"""Set the color using an Nx4 array of RGBA uint8 values"""
# need to convert to normalized float
val = np.atleast_1d(val).astype(np.float32) / 255
self.rgba = val | Set the color using an Nx4 array of RGBA uint8 values | entailment |
def RGB(self, val):
"""Set the color using an Nx3 array of RGB uint8 values"""
# need to convert to normalized float
val = np.atleast_1d(val).astype(np.float32) / 255.
self.rgba = val | Set the color using an Nx3 array of RGB uint8 values | entailment |
def value(self, val):
"""Set the color using length-N array of (from HSV)"""
hsv = self._hsv
hsv[:, 2] = _array_clip_val(val)
self.rgba = _hsv_to_rgb(hsv) | Set the color using length-N array of (from HSV) | entailment |
def lighter(self, dv=0.1, copy=True):
"""Produce a lighter color (if possible)
Parameters
----------
dv : float
Amount to increase the color value by.
copy : bool
If False, operation will be carried out in-place.
Returns
-------
c... | Produce a lighter color (if possible)
Parameters
----------
dv : float
Amount to increase the color value by.
copy : bool
If False, operation will be carried out in-place.
Returns
-------
color : instance of ColorArray
The lig... | entailment |
def darker(self, dv=0.1, copy=True):
"""Produce a darker color (if possible)
Parameters
----------
dv : float
Amount to decrease the color value by.
copy : bool
If False, operation will be carried out in-place.
Returns
-------
col... | Produce a darker color (if possible)
Parameters
----------
dv : float
Amount to decrease the color value by.
copy : bool
If False, operation will be carried out in-place.
Returns
-------
color : instance of ColorArray
The dark... | entailment |
def viewbox_mouse_event(self, event):
""" The ViewBox received a mouse event; update transform
accordingly.
Default implementation adjusts scale factor when scolling.
Parameters
----------
event : instance of Event
The event.
"""
BaseCamera.vi... | The ViewBox received a mouse event; update transform
accordingly.
Default implementation adjusts scale factor when scolling.
Parameters
----------
event : instance of Event
The event. | entailment |
def _set_range(self, init):
""" Reset the camera view using the known limits.
"""
if init and (self._scale_factor is not None):
return # We don't have to set our scale factor
# Get window size (and store factor now to sync with resizing)
w, h = self._viewbox.size
... | Reset the camera view using the known limits. | entailment |
def viewbox_mouse_event(self, event):
"""
The viewbox received a mouse event; update transform
accordingly.
Parameters
----------
event : instance of Event
The event.
"""
if event.handled or not self.interactive:
return
Pe... | The viewbox received a mouse event; update transform
accordingly.
Parameters
----------
event : instance of Event
The event. | entailment |
def _update_camera_pos(self):
""" Set the camera position and orientation"""
# transform will be updated several times; do not update camera
# transform until we are done.
ch_em = self.events.transform_change
with ch_em.blocker(self._update_transform):
tr = self.tran... | Set the camera position and orientation | entailment |
def is_interactive(self):
""" Determine if the user requested interactive mode.
"""
# The Python interpreter sets sys.flags correctly, so use them!
if sys.flags.interactive:
return True
# IPython does not set sys.flags when -i is specified, so first
# check i... | Determine if the user requested interactive mode. | entailment |
def run(self, allow_interactive=True):
""" Enter the native GUI event loop.
Parameters
----------
allow_interactive : bool
Is the application allowed to handle interactive mode for console
terminals? By default, typing ``python -i main.py`` results in
... | Enter the native GUI event loop.
Parameters
----------
allow_interactive : bool
Is the application allowed to handle interactive mode for console
terminals? By default, typing ``python -i main.py`` results in
an interactive shell that also regularly calls th... | entailment |
def _use(self, backend_name=None):
"""Select a backend by name. See class docstring for details.
"""
# See if we're in a specific testing mode, if so DONT check to see
# if it's a valid backend. If it isn't, it's a good thing we
# get an error later because we should have decorat... | Select a backend by name. See class docstring for details. | entailment |
def _set_config(c):
"""Set gl configuration"""
gl_attribs = [glcanvas.WX_GL_RGBA,
glcanvas.WX_GL_DEPTH_SIZE, c['depth_size'],
glcanvas.WX_GL_STENCIL_SIZE, c['stencil_size'],
glcanvas.WX_GL_MIN_RED, c['red_size'],
glcanvas.WX_GL_MIN_GREEN, c... | Set gl configuration | entailment |
def _get_mods(evt):
"""Helper to extract list of mods from event"""
mods = []
mods += [keys.CONTROL] if evt.ControlDown() else []
mods += [keys.ALT] if evt.AltDown() else []
mods += [keys.SHIFT] if evt.ShiftDown() else []
mods += [keys.META] if evt.MetaDown() else []
return mods | Helper to extract list of mods from event | entailment |
def _process_key(evt):
"""Helper to convert from wx keycode to vispy keycode"""
key = evt.GetKeyCode()
if key in KEYMAP:
return KEYMAP[key], ''
if 97 <= key <= 122:
key -= 32
if key >= 32 and key <= 127:
return keys.Key(chr(key)), chr(key)
else:
return None, None | Helper to convert from wx keycode to vispy keycode | entailment |
def is_child(self, node):
"""Check if a node is a child of the current node
Parameters
----------
node : instance of Node
The potential child.
Returns
-------
child : bool
Whether or not the node is a child.
"""
if node in... | Check if a node is a child of the current node
Parameters
----------
node : instance of Node
The potential child.
Returns
-------
child : bool
Whether or not the node is a child. | entailment |
def scene_node(self):
"""The first ancestor of this node that is a SubScene instance, or self
if no such node exists.
"""
if self._scene_node is None:
from .subscene import SubScene
p = self.parent
while True:
if isinstance(p, SubScene)... | The first ancestor of this node that is a SubScene instance, or self
if no such node exists. | entailment |
def update(self):
"""
Emit an event to inform listeners that properties of this Node have
changed. Also request a canvas update.
"""
self.events.update()
c = getattr(self, 'canvas', None)
if c is not None:
c.update(node=self) | Emit an event to inform listeners that properties of this Node have
changed. Also request a canvas update. | entailment |
def set_transform(self, type_, *args, **kwargs):
""" Create a new transform of *type* and assign it to this node.
All extra arguments are used in the construction of the transform.
Parameters
----------
type_ : str
The transform type.
*args : tuple
... | Create a new transform of *type* and assign it to this node.
All extra arguments are used in the construction of the transform.
Parameters
----------
type_ : str
The transform type.
*args : tuple
Arguments.
**kwargs : dict
Keywoard ar... | entailment |
def _update_trsys(self, event):
"""Called when has changed.
This allows the node and its children to react (notably, VisualNode
uses this to update its TransformSystem).
Note that this method is only called when one transform is replaced by
another; it is not c... | Called when has changed.
This allows the node and its children to react (notably, VisualNode
uses this to update its TransformSystem).
Note that this method is only called when one transform is replaced by
another; it is not called if an existing transform internally c... | entailment |
def parent_chain(self):
"""
Return the list of parents starting from this node. The chain ends
at the first node with no parents.
"""
chain = [self]
while True:
try:
parent = chain[-1].parent
except Exception:
break
... | Return the list of parents starting from this node. The chain ends
at the first node with no parents. | entailment |
def _describe_tree(self, prefix, with_transform):
"""Helper function to actuall construct the tree"""
extra = ': "%s"' % self.name if self.name is not None else ''
if with_transform:
extra += (' [%s]' % self.transform.__class__.__name__)
output = ''
if len(prefix) > 0... | Helper function to actuall construct the tree | entailment |
def common_parent(self, node):
"""
Return the common parent of two entities
If the entities have no common parent, return None.
Parameters
----------
node : instance of Node
The other node.
Returns
-------
parent : instance of Node |... | Return the common parent of two entities
If the entities have no common parent, return None.
Parameters
----------
node : instance of Node
The other node.
Returns
-------
parent : instance of Node | None
The parent. | entailment |
def node_path_to_child(self, node):
"""Return a list describing the path from this node to a child node
If *node* is not a (grand)child of this node, then raise RuntimeError.
Parameters
----------
node : instance of Node
The child node.
Returns
----... | Return a list describing the path from this node to a child node
If *node* is not a (grand)child of this node, then raise RuntimeError.
Parameters
----------
node : instance of Node
The child node.
Returns
-------
path : list | None
The ... | entailment |
def node_path(self, node):
"""Return two lists describing the path from this node to another
Parameters
----------
node : instance of Node
The other node.
Returns
-------
p1 : list
First path (see below).
p2 : list
Sec... | Return two lists describing the path from this node to another
Parameters
----------
node : instance of Node
The other node.
Returns
-------
p1 : list
First path (see below).
p2 : list
Second path (see below).
Notes
... | entailment |
def node_path_transforms(self, node):
"""Return the list of transforms along the path to another node.
The transforms are listed in reverse order, such that the last
transform should be applied first when mapping from this node to
the other.
Parameters
-------... | Return the list of transforms along the path to another node.
The transforms are listed in reverse order, such that the last
transform should be applied first when mapping from this node to
the other.
Parameters
----------
node : instance of Node
T... | entailment |
def read(cls, fname):
""" read(fname, fmt)
This classmethod is the entry point for reading OBJ files.
Parameters
----------
fname : str
The name of the file to read.
fmt : str
Can be "obj" or "gz" to specify the file format.
"""
#... | read(fname, fmt)
This classmethod is the entry point for reading OBJ files.
Parameters
----------
fname : str
The name of the file to read.
fmt : str
Can be "obj" or "gz" to specify the file format. | entailment |
def readLine(self):
""" The method that reads a line and processes it.
"""
# Read line
line = self._f.readline().decode('ascii', 'ignore')
if not line:
raise EOFError()
line = line.strip()
if line.startswith('v '):
# self._vertices.append... | The method that reads a line and processes it. | entailment |
def readTuple(self, line, n=3):
""" Reads a tuple of numbers. e.g. vertices, normals or teture coords.
"""
numbers = [num for num in line.split(' ') if num]
return [float(num) for num in numbers[1:n + 1]] | Reads a tuple of numbers. e.g. vertices, normals or teture coords. | entailment |
def readFace(self, line):
""" Each face consists of three or more sets of indices. Each set
consists of 1, 2 or 3 indices to vertices/normals/texcords.
"""
# Get parts (skip first)
indexSets = [num for num in line.split(' ') if num][1:]
final_face = []
for index... | Each face consists of three or more sets of indices. Each set
consists of 1, 2 or 3 indices to vertices/normals/texcords. | entailment |
def finish(self):
""" Converts gathere lists to numpy arrays and creates
BaseMesh instance.
"""
self._vertices = np.array(self._vertices, 'float32')
if self._faces:
self._faces = np.array(self._faces, 'uint32')
else:
# Use vertices only
... | Converts gathere lists to numpy arrays and creates
BaseMesh instance. | entailment |
def write(cls, fname, vertices, faces, normals,
texcoords, name='', reshape_faces=True):
""" This classmethod is the entry point for writing mesh data to OBJ.
Parameters
----------
fname : string
The filename to write to. Must end with ".obj" or ".gz".
... | This classmethod is the entry point for writing mesh data to OBJ.
Parameters
----------
fname : string
The filename to write to. Must end with ".obj" or ".gz".
vertices : numpy array
The vertex data
faces : numpy array
The face data
te... | entailment |
def writeTuple(self, val, what):
""" Writes a tuple of numbers (on one line).
"""
# Limit to three values. so RGBA data drops the alpha channel
# Format can handle up to 3 texcords
val = val[:3]
# Make string
val = ' '.join([str(v) for v in val])
# Write l... | Writes a tuple of numbers (on one line). | entailment |
def writeFace(self, val, what='f'):
""" Write the face info to the net line.
"""
# OBJ counts from 1
val = [v + 1 for v in val]
# Make string
if self._hasValues and self._hasNormals:
val = ' '.join(['%i/%i/%i' % (v, v, v) for v in val])
elif self._hasN... | Write the face info to the net line. | entailment |
def writeMesh(self, vertices, faces, normals, values,
name='', reshape_faces=True):
""" Write the given mesh instance.
"""
# Store properties
self._hasNormals = normals is not None
self._hasValues = values is not None
self._hasFaces = faces is not None
... | Write the given mesh instance. | entailment |
def _fast_cross_3d(x, y):
"""Compute cross product between list of 3D vectors
Much faster than np.cross() when the number of cross products
becomes large (>500). This is because np.cross() methods become
less memory efficient at this stage.
Parameters
----------
x : array
Input arr... | Compute cross product between list of 3D vectors
Much faster than np.cross() when the number of cross products
becomes large (>500). This is because np.cross() methods become
less memory efficient at this stage.
Parameters
----------
x : array
Input array 1.
y : array
Input... | entailment |
def _calculate_normals(rr, tris):
"""Efficiently compute vertex normals for triangulated surface"""
# ensure highest precision for our summation/vectorization "trick"
rr = rr.astype(np.float64)
# first, compute triangle normals
r1 = rr[tris[:, 0], :]
r2 = rr[tris[:, 1], :]
r3 = rr[tris[:, 2]... | Efficiently compute vertex normals for triangulated surface | entailment |
def resize(image, shape, kind='linear'):
"""Resize an image
Parameters
----------
image : ndarray
Array of shape (N, M, ...).
shape : tuple
2-element shape.
kind : str
Interpolation, either "linear" or "nearest".
Returns
-------
scaled_image : ndarray
... | Resize an image
Parameters
----------
image : ndarray
Array of shape (N, M, ...).
shape : tuple
2-element shape.
kind : str
Interpolation, either "linear" or "nearest".
Returns
-------
scaled_image : ndarray
New image, will have dtype np.float64. | entailment |
def append(self, P0, P1, itemsize=None, **kwargs):
"""
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 t... | 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
closed: bool
Whether path(s... | entailment |
def parse(self):
"""Parse the lines, and fill self.line_fields accordingly."""
for line in self.lines:
# Parse the line
field_defs = self.parse_line(line)
fields = []
# Convert field parameters into Field objects
for (kind, options) in field_d... | Parse the lines, and fill self.line_fields accordingly. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.