INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Set the complete data for a single line strip. Parameters ---------- index: int The index of the line strip to be replaced. data: array - like The data to assign to the selected line strip. | def set_data(self, index, data):
"""Set the complete data for a single line strip.
Parameters
----------
index : int
The index of the line strip to be replaced.
data : array-like
The data to assign to the selected line strip.
"""
s... |
Create a program and add it to this MultiProgram. It is the caller s responsibility to keep a reference to the returned program. The * name * must be unique but is otherwise arbitrary and used for debugging purposes. | def add_program(self, name=None):
"""Create a program and add it to this MultiProgram.
It is the caller's responsibility to keep a reference to the returned
program.
The *name* must be unique, but is otherwise arbitrary and used for
debugging purposes.
... |
New program was added to the multiprogram ; update items in the shader. | def _new_program(self, p):
"""New program was added to the multiprogram; update items in the
shader.
"""
for k, v in self._set_items.items():
getattr(p, self._shader)[k] = v |
Attach this tranform to a canvas | def attach(self, canvas):
"""Attach this tranform to a canvas
Parameters
----------
canvas : instance of Canvas
The canvas.
"""
self._canvas = canvas
canvas.events.resize.connect(self.on_resize)
canvas.events.mouse_wheel.connect(self.on_mouse_... |
Resize handler | def on_resize(self, event):
"""Resize handler
Parameters
----------
event : instance of Event
The event.
"""
if self._aspect is None:
return
w, h = self._canvas.size
aspect = self._aspect / (w / h)
self.scale = (self.scale[... |
Mouse move handler | def on_mouse_move(self, event):
"""Mouse move handler
Parameters
----------
event : instance of Event
The event.
"""
if event.is_dragging:
dxy = event.pos - event.last_event.pos
button = event.press_event.button
if button ... |
Mouse wheel handler | def on_mouse_wheel(self, event):
"""Mouse wheel handler
Parameters
----------
event : instance of Event
The event.
"""
self.zoom(np.exp(event.delta * (0.01, -0.01)), event.pos) |
Calculates and returns the tangents normals and binormals for the tube. | def _frenet_frames(points, closed):
'''Calculates and returns the tangents, normals and binormals for
the tube.'''
tangents = np.zeros((len(points), 3))
normals = np.zeros((len(points), 3))
epsilon = 0.0001
# Compute tangent vectors for each segment
tangents = np.roll(points, -1, axis=0) -... |
Depth of the smallest HEALPix cells found in the MOC instance. | def max_order(self):
"""
Depth of the smallest HEALPix cells found in the MOC instance.
"""
# TODO: cache value
combo = int(0)
for iv in self._interval_set._intervals:
combo |= iv[0] | iv[1]
ret = AbstractMOC.HPY_MAX_NORDER - (utils.number_trailing_ze... |
Intersection between the MOC instance and other MOCs. | def intersection(self, another_moc, *args):
"""
Intersection between the MOC instance and other MOCs.
Parameters
----------
another_moc : `~mocpy.moc.MOC`
The MOC used for performing the intersection with self.
args : `~mocpy.moc.MOC`
Other additi... |
Union between the MOC instance and other MOCs. | def union(self, another_moc, *args):
"""
Union between the MOC instance and other MOCs.
Parameters
----------
another_moc : `~mocpy.moc.MOC`
The MOC used for performing the union with self.
args : `~mocpy.moc.MOC`
Other additional MOCs to perform ... |
Difference between the MOC instance and other MOCs. | def difference(self, another_moc, *args):
"""
Difference between the MOC instance and other MOCs.
Parameters
----------
another_moc : `~mocpy.moc.MOC`
The MOC used that will be substracted to self.
args : `~mocpy.moc.MOC`
Other additional MOCs to ... |
Returns all the pixels neighbours of ipix | def _neighbour_pixels(hp, ipix):
"""
Returns all the pixels neighbours of ``ipix``
"""
neigh_ipix = np.unique(hp.neighbours(ipix).ravel())
# Remove negative pixel values returned by `~astropy_healpix.HEALPix.neighbours`
return neigh_ipix[np.where(neigh_ipix >= 0)] |
Creates a MOC from a numpy array representing the HEALPix cells. | def from_cells(cls, cells):
"""
Creates a MOC from a numpy array representing the HEALPix cells.
Parameters
----------
cells : `numpy.ndarray`
Must be a numpy structured array (See https://docs.scipy.org/doc/numpy-1.15.0/user/basics.rec.html).
The structu... |
Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth. | def from_json(cls, json_moc):
"""
Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth.
Parameters
----------
json_moc : dict(str : [int]
A dictionary of HEALPix cell arrays indexed by their depth.
Returns
-------
moc... |
Generator giving the NUNIQ HEALPix pixels of the MOC. | def _uniq_pixels_iterator(self):
"""
Generator giving the NUNIQ HEALPix pixels of the MOC.
Returns
-------
uniq :
the NUNIQ HEALPix pixels iterator
"""
intervals_uniq_l = IntervalSet.to_nuniq_interval_set(self._interval_set)._intervals
for uni... |
Loads a MOC from a FITS file. | def from_fits(cls, filename):
"""
Loads a MOC from a FITS file.
The specified FITS file must store the MOC (i.e. the list of HEALPix cells it contains) in a binary HDU table.
Parameters
----------
filename : str
The path to the FITS file.
Returns
... |
Create a MOC from a str. This grammar is expressed is the MOC IVOA <http:// ivoa. net/ documents/ MOC/ 20190215/ WD - MOC - 1. 1 - 20190215. pdf > __ specification at section 2. 3. 2. | def from_str(cls, value):
"""
Create a MOC from a str.
This grammar is expressed is the `MOC IVOA <http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf>`__
specification at section 2.3.2.
Parameters
----------
value : str
The MOC as... |
Serializes a MOC to the JSON format. | def _to_json(uniq):
"""
Serializes a MOC to the JSON format.
Parameters
----------
uniq : `~numpy.ndarray`
The array of HEALPix cells representing the MOC to serialize.
Returns
-------
result_json : {str : [int]}
A dictionary of H... |
Serializes a MOC to the STRING format. | def _to_str(uniq):
"""
Serializes a MOC to the STRING format.
HEALPix cells are separated by a comma. The HEALPix cell at order 0 and number 10 is encoded
by the string: "0/10", the first digit representing the depth and the second the HEALPix cell number
for this depth. HEALPix... |
Serializes a MOC to the FITS format. | def _to_fits(self, uniq, optional_kw_dict=None):
"""
Serializes a MOC to the FITS format.
Parameters
----------
uniq : `numpy.ndarray`
The array of HEALPix cells representing the MOC to serialize.
optional_kw_dict : dict
Optional keywords argument... |
Serializes the MOC into a specific format. | def serialize(self, format='fits', optional_kw_dict=None):
"""
Serializes the MOC into a specific format.
Possible formats are FITS, JSON and STRING
Parameters
----------
format : str
'fits' by default. The other possible choice is 'json' or 'str'.
o... |
Writes the MOC to a file. | def write(self, path, format='fits', overwrite=False, optional_kw_dict=None):
"""
Writes the MOC to a file.
Format can be 'fits' or 'json', though only the fits format is officially supported by the IVOA.
Parameters
----------
path : str, optional
The path t... |
Degrades the MOC instance to a new less precise MOC. | def degrade_to_order(self, new_order):
"""
Degrades the MOC instance to a new, less precise, MOC.
The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the
degraded MOC is set to ``new_order``.
Parameters
----------
ne... |
Set Screen Name | def set_name(self, name):
""" Set Screen Name """
self.name = name
self.server.request("screen_set %s name %s" % (self.ref, self.name)) |
Set Screen Width | def set_width(self, width):
""" Set Screen Width """
if width > 0 and width <= self.server.server_info.get("screen_width"):
self.width = width
self.server.request("screen_set %s wid %i" % (self.ref, self.width)) |
Set Screen Height | def set_height(self, height):
""" Set Screen Height """
if height > 0 and height <= self.server.server_info.get("screen_height"):
self.height = height
self.server.request("screen_set %s hgt %i" % (self.ref, self.height)) |
Set Screen Cursor X Position | def set_cursor_x(self, x):
""" Set Screen Cursor X Position """
if x >= 0 and x <= self.server.server_info.get("screen_width"):
self.cursor_x = x
self.server.request("screen_set %s cursor_x %i" % (self.ref, self.cursor_x)) |
Set Screen Cursor Y Position | def set_cursor_y(self, y):
""" Set Screen Cursor Y Position """
if y >= 0 and y <= self.server.server_info.get("screen_height"):
self.cursor_y = y
self.server.request("screen_set %s cursor_y %i" % (self.ref, self.cursor_y)) |
Set Screen Change Interval Duration | def set_duration(self, duration):
""" Set Screen Change Interval Duration """
if duration > 0:
self.duration = duration
self.server.request("screen_set %s duration %i" % (self.ref, (self.duration * 8))) |
Set Screen Timeout Duration | def set_timeout(self, timeout):
""" Set Screen Timeout Duration """
if timeout > 0:
self.timeout = timeout
self.server.request("screen_set %s timeout %i" % (self.ref, (self.timeout * 8))) |
Set Screen Priority Class | def set_priority(self, priority):
""" Set Screen Priority Class """
if priority in ["hidden", "background", "info", "foreground", "alert", "input"]:
self.priority = priority
self.server.request("screen_set %s priority %s" % (self.ref, self.priority)) |
Set Screen Backlight Mode | def set_backlight(self, state):
""" Set Screen Backlight Mode """
if state in ["on", "off", "toggle", "open", "blink", "flash"]:
self.backlight = state
self.server.request("screen_set %s backlight %s" % (self.ref, self.backlight)) |
Set Screen Heartbeat Display Mode | def set_heartbeat(self, state):
""" Set Screen Heartbeat Display Mode """
if state in ["on", "off", "open"]:
self.heartbeat = state
self.server.request("screen_set %s heartbeat %s" % (self.ref, self.heartbeat)) |
Set Screen Cursor Mode | def set_cursor(self, cursor):
""" Set Screen Cursor Mode """
if cursor in ["on", "off", "under", "block"]:
self.cursor = cursor
self.server.request("screen_set %s cursor %s" % (self.ref, self.cursor)) |
Clear Screen | def clear(self):
""" Clear Screen """
widgets.StringWidget(self, ref="_w1_", text=" " * 20, x=1, y=1)
widgets.StringWidget(self, ref="_w2_", text=" " * 20, x=1, y=2)
widgets.StringWidget(self, ref="_w3_", text=" " * 20, x=1, y=3)
widgets.StringWidget(self, ref="_w4_", text=" " * ... |
Add String Widget | def add_string_widget(self, ref, text="Text", x=1, y=1):
""" Add String Widget """
if ref not in self.widgets:
widget = widgets.StringWidget(screen=self, ref=ref, text=text, x=x, y=y)
self.widgets[ref] = widget
return self.widgets[ref] |
Add Title Widget | def add_title_widget(self, ref, text="Title"):
""" Add Title Widget """
if ref not in self.widgets:
widget = widgets.TitleWidget(screen=self, ref=ref, text=text)
self.widgets[ref] = widget
return self.widgets[ref] |
Add Horizontal Bar Widget | def add_hbar_widget(self, ref, x=1, y=1, length=10):
""" Add Horizontal Bar Widget """
if ref not in self.widgets:
widget = widgets.HBarWidget(screen=self, ref=ref, x=x, y=y, length=length)
self.widgets[ref] = widget
return self.widgets[ref] |
Add Vertical Bar Widget | def add_vbar_widget(self, ref, x=1, y=1, length=10):
""" Add Vertical Bar Widget """
if ref not in self.widgets:
widget = widgets.VBarWidget(screen=self, ref=ref, x=x, y=y, length=length)
self.widgets[ref] = widget
return self.widgets[ref] |
Add Frame Widget | def add_frame_widget(self, ref, left=1, top=1, right=20, bottom=1, width=20, height=4, direction="h", speed=1):
""" Add Frame Widget """
if ref not in self.widgets:
widget = widgets.FrameWidget(
screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, width=widt... |
Add Number Widget | def add_number_widget(self, ref, x=1, value=1):
""" Add Number Widget """
if ref not in self.widgets:
widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value)
self.widgets[ref] = widget
return self.widgets[ref] |
Delete/ Remove A Widget | def del_widget(self, ref):
""" Delete/Remove A Widget """
self.server.request("widget_del %s %s" % (self.name, ref))
del(self.widgets[ref]) |
Orbits the camera around the center position. | def orbit(self, azim, elev):
""" Orbits the camera around the center position.
Parameters
----------
azim : float
Angle in degrees to rotate horizontally around the center point.
elev : float
Angle in degrees to rotate vertically around the center point.
... |
Update rotation parmeters based on mouse movement | def _update_rotation(self, event):
"""Update rotation parmeters based on mouse movement"""
p1 = event.mouse_event.press_event.pos
p2 = event.mouse_event.pos
if self._event_value is None:
self._event_value = self.azimuth, self.elevation
self.azimuth = self._event_value... |
Rotate the transformation matrix based on camera parameters | def _rotate_tr(self):
"""Rotate the transformation matrix based on camera parameters"""
up, forward, right = self._get_dim_vectors()
self.transform.rotate(self.elevation, -right)
self.transform.rotate(self.azimuth, up) |
Convert mouse x y movement into x y z translations | def _dist_to_trans(self, dist):
"""Convert mouse x, y movement into x, y, z translations"""
rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180
sro, saz, sel = np.sin(rae)
cro, caz, cel = np.cos(rae)
dx = (+ dist[0] * (cro * caz + sro * sel * saz)
... |
Set gl configuration for GLFW | def _set_config(c):
"""Set gl configuration for GLFW """
glfw.glfwWindowHint(glfw.GLFW_RED_BITS, c['red_size'])
glfw.glfwWindowHint(glfw.GLFW_GREEN_BITS, c['green_size'])
glfw.glfwWindowHint(glfw.GLFW_BLUE_BITS, c['blue_size'])
glfw.glfwWindowHint(glfw.GLFW_ALPHA_BITS, c['alpha_size'])
glfw.glf... |
Process ( possible ) keyboard modifiers | def _process_mod(self, key, down):
"""Process (possible) keyboard modifiers
GLFW provides "mod" with many callbacks, but not (critically) the
scroll callback, so we keep track on our own here.
"""
if key in MOD_KEYS:
if down:
if key not in self._mod:
... |
Monkey - patch pyopengl to fix a bug in glBufferSubData. | def _patch():
""" Monkey-patch pyopengl to fix a bug in glBufferSubData. """
import sys
from OpenGL import GL
if sys.version_info > (3,):
buffersubdatafunc = GL.glBufferSubData
if hasattr(buffersubdatafunc, 'wrapperFunction'):
buffersubdatafunc = buffersubdatafunc.wrapperFunc... |
Try getting the given function from PyOpenGL return a dummy function ( that shows a warning when called ) if it could not be found. | def _get_function_from_pyopengl(funcname):
""" Try getting the given function from PyOpenGL, return
a dummy function (that shows a warning when called) if it
could not be found.
"""
func = None
# Get function from GL
try:
func = getattr(_GL, funcname)
except AttributeError:
... |
Copy functions from OpenGL. GL into _pyopengl namespace. | def _inject():
""" Copy functions from OpenGL.GL into _pyopengl namespace.
"""
NS = _pyopengl2.__dict__
for glname, ourname in _pyopengl2._functions_to_import:
func = _get_function_from_pyopengl(glname)
NS[ourname] = func |
Fetch a remote vispy font | def _get_vispy_font_filename(face, bold, italic):
"""Fetch a remote vispy font"""
name = face + '-'
name += 'Regular' if not bold and not italic else ''
name += 'Bold' if bold else ''
name += 'Italic' if italic else ''
name += '.ttf'
return load_data_file('fonts/%s' % name) |
Ensure val is Nx ( n_col ) usually Nx3 | def _check_color_dim(val):
"""Ensure val is Nx(n_col), usually Nx3"""
val = np.atleast_2d(val)
if val.shape[1] not in (3, 4):
raise RuntimeError('Value must have second dimension of size 3 or 4')
return val, val.shape[1] |
Convert hex to rgba permitting alpha values in hex | def _hex_to_rgba(hexs):
"""Convert hex to rgba, permitting alpha values in hex"""
hexs = np.atleast_1d(np.array(hexs, '|U9'))
out = np.ones((len(hexs), 4), np.float32)
for hi, h in enumerate(hexs):
assert isinstance(h, string_types)
off = 1 if h[0] == '#' else 0
assert len(h) in ... |
Convert rgb to hex triplet | def _rgb_to_hex(rgbs):
"""Convert rgb to hex triplet"""
rgbs, n_dim = _check_color_dim(rgbs)
return np.array(['#%02x%02x%02x' % tuple((255*rgb[:3]).astype(np.uint8))
for rgb in rgbs], '|U7') |
Convert Nx3 or Nx4 rgb to hsv | def _rgb_to_hsv(rgbs):
"""Convert Nx3 or Nx4 rgb to hsv"""
rgbs, n_dim = _check_color_dim(rgbs)
hsvs = list()
for rgb in rgbs:
rgb = rgb[:3] # don't use alpha here
idx = np.argmax(rgb)
val = rgb[idx]
c = val - np.min(rgb)
if c == 0:
hue = 0
... |
Convert Nx3 or Nx4 hsv to rgb | def _hsv_to_rgb(hsvs):
"""Convert Nx3 or Nx4 hsv to rgb"""
hsvs, n_dim = _check_color_dim(hsvs)
# In principle, we *might* be able to vectorize this, but might as well
# wait until a compelling use case appears
rgbs = list()
for hsv in hsvs:
c = hsv[1] * hsv[2]
m = hsv[2] - c
... |
Convert Nx3 or Nx4 lab to rgb | def _lab_to_rgb(labs):
"""Convert Nx3 or Nx4 lab to rgb"""
# adapted from BSD-licensed work in MATLAB by Mark Ruzon
# Based on ITU-R Recommendation BT.709 using the D65
labs, n_dim = _check_color_dim(labs)
# Convert Lab->XYZ (silly indexing used to preserve dimensionality)
y = (labs[:, 0] + 16.... |
Find an adequate value for this field from a dict of tags. | def get(self, tags):
"""Find an adequate value for this field from a dict of tags."""
# Try to find our name
value = tags.get(self.name, '')
for name in self.alternate_tags:
# Iterate of alternates until a non-empty value is found
value = value or tags.get(name, ... |
Return the name arguments and return type of the first function definition found in * code *. Arguments are returned as [ ( type name )... ]. | def parse_function_signature(code):
"""
Return the name, arguments, and return type of the first function
definition found in *code*. Arguments are returned as [(type, name), ...].
"""
m = re.search("^\s*" + re_func_decl + "\s*{", code, re.M)
if m is None:
print(code)
raise Excep... |
Return a list of ( name arguments return type ) for all function definition2 found in * code *. Arguments are returned as [ ( type name )... ]. | def find_functions(code):
"""
Return a list of (name, arguments, return type) for all function
definition2 found in *code*. Arguments are returned as [(type, name), ...].
"""
regex = "^\s*" + re_func_decl + "\s*{"
funcs = []
while True:
m = re.search(regex, code, re.M)
... |
Return a list of signatures for each function prototype declared in * code *. Format is [ ( name [ args ] rtype )... ]. | def find_prototypes(code):
"""
Return a list of signatures for each function prototype declared in *code*.
Format is [(name, [args], rtype), ...].
"""
prots = []
lines = code.split('\n')
for line in lines:
m = re.match("\s*" + re_func_prot, line)
if m is not None:
... |
Return a dict describing program variables:: | def find_program_variables(code):
"""
Return a dict describing program variables::
{'var_name': ('uniform|attribute|varying', type), ...}
"""
vars = {}
lines = code.split('\n')
for line in lines:
m = re.match(r"\s*" + re_prog_var_declaration + r"\s*(=|;)", line)
if m is... |
Set gl configuration for SDL2 | def _set_config(c):
"""Set gl configuration for SDL2"""
func = sdl2.SDL_GL_SetAttribute
func(sdl2.SDL_GL_RED_SIZE, c['red_size'])
func(sdl2.SDL_GL_GREEN_SIZE, c['green_size'])
func(sdl2.SDL_GL_BLUE_SIZE, c['blue_size'])
func(sdl2.SDL_GL_ALPHA_SIZE, c['alpha_size'])
func(sdl2.SDL_GL_DEPTH_SIZ... |
message - text message to be spoken out by the Echo end_session - flag to determine whether this interaction should end the session card_obj = JSON card object to substitute the card field in the raw_response | def create_response(self, message=None, end_session=False, card_obj=None,
reprompt_message=None, is_ssml=None):
"""
message - text message to be spoken out by the Echo
end_session - flag to determine whether this interaction should end the session
card_obj = JSON ... |
card_obj = JSON card object to substitute the card field in the raw_response format: { type: Simple #COMPULSORY title: string #OPTIONAL subtitle: string #OPTIONAL content: string #OPTIONAL } | def create_card(self, title=None, subtitle=None, content=None, card_type="Simple"):
"""
card_obj = JSON card object to substitute the 'card' field in the raw_response
format:
{
"type": "Simple", #COMPULSORY
"title": "string", #OPTIONAL
"subtitle": "string", ... |
Decorator to register intent handler | def intent(self, intent):
''' Decorator to register intent handler'''
def _handler(func):
self._handlers['IntentRequest'][intent] = func
return func
return _handler |
Decorator to register generic request handler | def request(self, request_type):
''' Decorator to register generic request handler '''
def _handler(func):
self._handlers[request_type] = func
return func
return _handler |
Route the request object to the right handler function | def route_request(self, request_json, metadata=None):
''' Route the request object to the right handler function '''
request = Request(request_json)
request.metadata = metadata
# add reprompt handler or some such for default?
handler_fn = self._handlers[self._default] # Set defa... |
Friend method of viewbox to register itself. | def _viewbox_set(self, viewbox):
""" Friend method of viewbox to register itself.
"""
self._viewbox = viewbox
# Connect
viewbox.events.mouse_press.connect(self.viewbox_mouse_event)
viewbox.events.mouse_release.connect(self.viewbox_mouse_event)
viewbox.events.mouse... |
Friend method of viewbox to unregister itself. | def _viewbox_unset(self, viewbox):
""" Friend method of viewbox to unregister itself.
"""
self._viewbox = None
# Disconnect
viewbox.events.mouse_press.disconnect(self.viewbox_mouse_event)
viewbox.events.mouse_release.disconnect(self.viewbox_mouse_event)
viewbox.ev... |
Set the range of the view region for the camera | def set_range(self, x=None, y=None, z=None, margin=0.05):
""" Set the range of the view region for the camera
Parameters
----------
x : tuple | None
X range.
y : tuple | None
Y range.
z : tuple | None
Z range.
margin : float
... |
Get the current view state of the camera | def get_state(self):
""" Get the current view state of the camera
Returns a dict of key-value pairs. The exact keys depend on the
camera. Can be passed to set_state() (of this or another camera
of the same type) to reproduce the state.
"""
D = {}
for key in self.... |
Set the view state of the camera | def set_state(self, state=None, **kwargs):
""" Set the view state of the camera
Should be a dict (or kwargs) as returned by get_state. It can
be an incomlete dict, in which case only the specified
properties are set.
Parameters
----------
state : dict
... |
Link this camera with another camera of the same type | def link(self, camera):
""" Link this camera with another camera of the same type
Linked camera's keep each-others' state in sync.
Parameters
----------
camera : instance of Camera
The other camera to link.
"""
cam1, cam2 = self, camera
# Rem... |
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 anything while resetting (are in set_range)
if self._viewbox:
# Set range if necessary
... |
Canvas change event handler | def on_canvas_change(self, event):
"""Canvas change event handler
Parameters
----------
event : instance of Event
The event.
"""
# Connect key events from canvas to camera.
# TODO: canvas should keep track of a single node with keyboard focus.
... |
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
if pre_tr is None:
self._scene_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_API:
# Qt5 >= 5.4.0 -... |
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)(winid, self.width(), self.height())
return ctypes.point... |
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):
"""
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)... |
Map coordinates | def map(self, coords):
"""Map coordinates
Parameters
----------
coords : array-like
Coordinates to map.
Returns
-------
coords : ndarray
Coordinates.
"""
m = np.empty(coords.shape)
m[:, :3] = (coords[:, :3] * self.... |
Change the translation of this transform by the amount given. | def move(self, move):
"""Change the translation of this transform by the amount given.
Parameters
----------
move : array-like
The values to be added to the current translation of the transform.
"""
move = as_vec4(move, default=(0, 0, 0, 0))
self.tran... |
Update the transform such that its scale factor is changed but the specified center point is left unchanged. | def zoom(self, zoom, center=(0, 0, 0), mapped=True):
"""Update the transform such that its scale factor is changed, but
the specified center point is left unchanged.
Parameters
----------
zoom : array-like
Values to multiply the transform's current scale
... |
Create an STTransform from the given mapping | def from_mapping(cls, x0, x1):
""" Create an STTransform from the given mapping
See `set_mapping` for details.
Parameters
----------
x0 : array-like
Start.
x1 : array-like
End.
Returns
-------
t : instance of STTransform
... |
Configure this transform such that it maps points x0 = > x1 | def set_mapping(self, x0, x1, update=True):
"""Configure this transform such that it maps points x0 => x1
Parameters
----------
x0 : array-like, shape (2, 2) or (2, 3)
Start location.
x1 : array-like, shape (2, 2) or (2, 3)
End location.
update : ... |
Translate the matrix | def translate(self, pos):
"""
Translate the matrix
The translation is applied *after* the transformations already present
in the matrix.
Parameters
----------
pos : arrayndarray
Position to translate by.
"""
self.matrix = np.dot(self.... |
Scale the matrix about a given origin. | def scale(self, scale, center=None):
"""
Scale the matrix about a given origin.
The scaling is applied *after* the transformations already present
in the matrix.
Parameters
----------
scale : array-like
Scale factors along x, y and z axes.
ce... |
Rotate the matrix by some angle about a given axis. | def rotate(self, angle, axis):
"""
Rotate the matrix by some angle about a given axis.
The rotation is applied *after* the transformations already present
in the matrix.
Parameters
----------
angle : float
The angle of rotation, in degrees.
a... |
Set to a 3D transformation matrix that maps points1 onto points2. | def set_mapping(self, points1, points2):
""" Set to a 3D transformation matrix that maps points1 onto points2.
Parameters
----------
points1 : array-like, shape (4, 3)
Four starting 3D coordinates.
points2 : array-like, shape (4, 3)
Four ending 3D coordin... |
Set ortho transform | def set_ortho(self, l, r, b, t, n, f):
"""Set ortho transform
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
... |
Set the perspective | def set_perspective(self, fov, aspect, near, far):
"""Set the perspective
Parameters
----------
fov : float
Field of view.
aspect : float
Aspect ratio.
near : float
Near location.
far : float
Far location.
"... |
Set the frustum | def set_frustum(self, l, r, b, t, n, f):
"""Set the frustum
Parameters
----------
l : float
Left.
r : float
Right.
b : float
Bottom.
t : float
Top.
n : float
Near.
f : float
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 | def log2_lut(v):
"""
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
-------
"""
res = np.zeros(v.shape, dtyp... |
~30% faster than the method below Parameters ---------- uniq | def uniq2orderipix_lut(uniq):
"""
~30% faster than the method below
Parameters
----------
uniq
Returns
-------
"""
order = log2_lut(uniq >> 2) >> 1
ipix = uniq - (1 << (2 * (order + 1)))
return order, ipix |
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 order, ipix |
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, usage) |
Set the line data | def set_data(self, data=None, **kwargs):
"""Set the line data
Parameters
----------
data : array-like
The data.
**kwargs : dict
Keywoard arguments to pass to MarkerVisual and LineVisal.
"""
if data is None:
pos = None
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.