sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def has_face_color(self):
"""Return True if this data set has face color information"""
for v in (self._face_colors, self._face_colors_indexed_by_faces,
self._face_colors_indexed_by_edges):
if v is not None:
return True
return False | Return True if this data set has face color information | entailment |
def get_face_normals(self, indexed=None):
"""Get face normals
Parameters
----------
indexed : str | None
If None, return an array (Nf, 3) of normal vectors for each face.
If 'faces', then instead return an indexed array (Nf, 3, 3)
(this is just the sa... | Get face normals
Parameters
----------
indexed : str | None
If None, return an array (Nf, 3) of normal vectors for each face.
If 'faces', then instead return an indexed array (Nf, 3, 3)
(this is just the same array with each vector copied three times).
... | entailment |
def get_vertex_normals(self, indexed=None):
"""Get vertex normals
Parameters
----------
indexed : str | None
If None, return an (N, 3) array of normal vectors with one entry
per unique vertex in the mesh. If indexed is 'faces', then the
array will con... | Get vertex normals
Parameters
----------
indexed : str | None
If None, return an (N, 3) array of normal vectors with one entry
per unique vertex in the mesh. If indexed is 'faces', then the
array will contain three normal vectors per face (and some
... | entailment |
def get_vertex_colors(self, indexed=None):
"""Get vertex colors
Parameters
----------
indexed : str | None
If None, return an array (Nv, 4) of vertex colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4).
Returns
... | Get vertex colors
Parameters
----------
indexed : str | None
If None, return an array (Nv, 4) of vertex colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4).
Returns
-------
colors : ndarray
The ver... | entailment |
def set_vertex_colors(self, colors, indexed=None):
"""Set the vertex color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nv, 4) (indexing by vertex)
or shape (Nf, 3, 4) (vertices indexed by face).
indexed : str | None
... | Set the vertex color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nv, 4) (indexing by vertex)
or shape (Nf, 3, 4) (vertices indexed by face).
indexed : str | None
Should be 'faces' if colors are indexed by faces. | entailment |
def get_face_colors(self, indexed=None):
"""Get the face colors
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 4) array of face colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4) (note this is jus... | Get the face colors
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 4) array of face colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4) (note this is just the same array with each color
repeate... | entailment |
def set_face_colors(self, colors, indexed=None):
"""Set the face color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nf, 4) (indexed by face),
or shape (Nf, 3, 4) (face colors indexed by faces).
indexed : str | None
... | Set the face color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nf, 4) (indexed by face),
or shape (Nf, 3, 4) (face colors indexed by faces).
indexed : str | None
Should be 'faces' if colors are indexed by faces. | entailment |
def n_faces(self):
"""The number of faces in the mesh"""
if self._faces is not None:
return self._faces.shape[0]
elif self._vertices_indexed_by_faces is not None:
return self._vertices_indexed_by_faces.shape[0] | The number of faces in the mesh | entailment |
def get_vertex_faces(self):
"""
List mapping each vertex index to a list of face indices that use it.
"""
if self._vertex_faces is None:
self._vertex_faces = [[] for i in xrange(len(self.get_vertices()))]
for i in xrange(self._faces.shape[0]):
face... | List mapping each vertex index to a list of face indices that use it. | entailment |
def save(self):
"""Serialize this mesh to a string appropriate for disk storage
Returns
-------
state : dict
The state.
"""
import pickle
if self._faces is not None:
names = ['_vertices', '_faces']
else:
names = ['_vert... | Serialize this mesh to a string appropriate for disk storage
Returns
-------
state : dict
The state. | entailment |
def restore(self, state):
"""Restore the state of a mesh previously saved using save()
Parameters
----------
state : dict
The previous state.
"""
import pickle
state = pickle.loads(state)
for k in state:
if isinstance(state[k], lis... | Restore the state of a mesh previously saved using save()
Parameters
----------
state : dict
The previous state. | entailment |
def cubehelix(start=0.5, rot=1, gamma=1.0, reverse=True, nlev=256.,
minSat=1.2, maxSat=1.2, minLight=0., maxLight=1.,
**kwargs):
"""
A full implementation of Dave Green's "cubehelix" for Matplotlib.
Based on the FORTRAN 77 code provided in
D.A. Green, 2011, BASI, 39, 289.
http://a... | A full implementation of Dave Green's "cubehelix" for Matplotlib.
Based on the FORTRAN 77 code provided in
D.A. Green, 2011, BASI, 39, 289.
http://adsabs.harvard.edu/abs/2011arXiv1108.5083G
User can adjust all parameters of the cubehelix algorithm.
This enables much greater flexibility in choosing... | entailment |
def color_to_hex(color):
"""Convert matplotlib color code to hex color code"""
if color is None or colorConverter.to_rgba(color)[3] == 0:
return 'none'
else:
rgb = colorConverter.to_rgb(color)
return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb)) | Convert matplotlib color code to hex color code | entailment |
def _many_to_one(input_dict):
"""Convert a many-to-one mapping to a one-to-one mapping"""
return dict((key, val)
for keys, val in input_dict.items()
for key in keys) | Convert a many-to-one mapping to a one-to-one mapping | entailment |
def get_dasharray(obj):
"""Get an SVG dash array for the given matplotlib linestyle
Parameters
----------
obj : matplotlib object
The matplotlib line or path object, which must have a get_linestyle()
method which returns a valid matplotlib line code
Returns
-------
dasharra... | Get an SVG dash array for the given matplotlib linestyle
Parameters
----------
obj : matplotlib object
The matplotlib line or path object, which must have a get_linestyle()
method which returns a valid matplotlib line code
Returns
-------
dasharray : string
The HTML/SVG... | entailment |
def SVG_path(path, transform=None, simplify=False):
"""Construct the vertices and SVG codes for the path
Parameters
----------
path : matplotlib.Path object
transform : matplotlib transform (optional)
if specified, the path will be transformed before computing the output.
Returns
... | Construct the vertices and SVG codes for the path
Parameters
----------
path : matplotlib.Path object
transform : matplotlib transform (optional)
if specified, the path will be transformed before computing the output.
Returns
-------
vertices : array
The shape (M, 2) array... | entailment |
def get_path_style(path, fill=True):
"""Get the style dictionary for matplotlib path objects"""
style = {}
style['alpha'] = path.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['edgecolor'] = color_to_hex(path.get_edgecolor())
if fill:
style['facecolor'] = color_t... | Get the style dictionary for matplotlib path objects | entailment |
def get_line_style(line):
"""Get the style dictionary for matplotlib line objects"""
style = {}
style['alpha'] = line.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['color'] = color_to_hex(line.get_color())
style['linewidth'] = line.get_linewidth()
style['dasharray']... | Get the style dictionary for matplotlib line objects | entailment |
def get_marker_style(line):
"""Get the style dictionary for matplotlib marker objects"""
style = {}
style['alpha'] = line.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['facecolor'] = color_to_hex(line.get_markerfacecolor())
style['edgecolor'] = color_to_hex(line.get_ma... | Get the style dictionary for matplotlib marker objects | entailment |
def get_text_style(text):
"""Return the text style dict for a text instance"""
style = {}
style['alpha'] = text.get_alpha()
if style['alpha'] is None:
style['alpha'] = 1
style['fontsize'] = text.get_size()
style['color'] = color_to_hex(text.get_color())
style['halign'] = text.get_hor... | Return the text style dict for a text instance | entailment |
def get_axis_properties(axis):
"""Return the property dictionary for a matplotlib.Axis instance"""
props = {}
label1On = axis._major_tick_kw.get('label1On', True)
if isinstance(axis, matplotlib.axis.XAxis):
if label1On:
props['position'] = "bottom"
else:
props['p... | Return the property dictionary for a matplotlib.Axis instance | entailment |
def iter_all_children(obj, skipContainers=False):
"""
Returns an iterator over all childen and nested children using
obj's get_children() method
if skipContainers is true, only childless objects are returned.
"""
if hasattr(obj, 'get_children') and len(obj.get_children()) > 0:
for child... | Returns an iterator over all childen and nested children using
obj's get_children() method
if skipContainers is true, only childless objects are returned. | entailment |
def image_to_base64(image):
"""
Convert a matplotlib image to a base64 png representation
Parameters
----------
image : matplotlib image object
The image to be converted.
Returns
-------
image_base64 : string
The UTF8-encoded base64 string representation of the png imag... | Convert a matplotlib image to a base64 png representation
Parameters
----------
image : matplotlib image object
The image to be converted.
Returns
-------
image_base64 : string
The UTF8-encoded base64 string representation of the png image. | entailment |
def set_interactive(enabled=True, app=None):
"""Activate the IPython hook for VisPy. If the app is not specified, the
default is used.
"""
if enabled:
inputhook_manager.enable_gui('vispy', app)
else:
inputhook_manager.disable_gui() | Activate the IPython hook for VisPy. If the app is not specified, the
default is used. | entailment |
def _resize_buffers(self, font_scale):
"""Resize buffers only if necessary"""
new_sizes = (font_scale,) + self.size
if new_sizes == self._current_sizes: # don't need resize
return
self._n_rows = int(max(self.size[1] /
(self._char_height * font_... | Resize buffers only if necessary | entailment |
def clear(self):
"""Clear the console"""
if hasattr(self, '_bytes_012'):
self._bytes_012.fill(0)
self._bytes_345.fill(0)
self._text_lines = [] * self._n_rows
self._pending_writes = [] | Clear the console | entailment |
def write(self, text='', wrap=True):
"""Write text and scroll
Parameters
----------
text : str
Text to write. ``''`` can be used for a blank line, as a newline
is automatically added to the end of each line.
wrap : str
If True, long messages w... | Write text and scroll
Parameters
----------
text : str
Text to write. ``''`` can be used for a blank line, as a newline
is automatically added to the end of each line.
wrap : str
If True, long messages will be wrapped to span multiple lines. | entailment |
def _do_pending_writes(self):
"""Do any pending text writes"""
for text, wrap in self._pending_writes:
# truncate in case of *really* long messages
text = text[-self._n_cols*self._n_rows:]
text = text.split('\n')
text = [t if len(t) > 0 else '' for t in te... | Do any pending text writes | entailment |
def _insert_text_buf(self, line, idx):
"""Insert text into bytes buffers"""
self._bytes_012[idx] = 0
self._bytes_345[idx] = 0
# Crop text if necessary
I = np.array([ord(c) - 32 for c in line[:self._n_cols]])
I = np.clip(I, 0, len(__font_6x8__)-1)
if len(I) > 0:
... | Insert text into bytes buffers | entailment |
def replace(self, str1, str2):
""" Set verbatim code replacement
It is strongly recommended to use function['$foo'] = 'bar' where
possible because template variables are less likely to changed
than the code itself in future versions of vispy.
Parameters
... | Set verbatim code replacement
It is strongly recommended to use function['$foo'] = 'bar' where
possible because template variables are less likely to changed
than the code itself in future versions of vispy.
Parameters
----------
str1 : str
S... | entailment |
def _parse_template_vars(self):
""" find all template variables in self._code, excluding the
function name.
"""
template_vars = set()
for var in parsing.find_template_variables(self._code):
var = var.lstrip('$')
if var == self.name:
contin... | find all template variables in self._code, excluding the
function name. | entailment |
def _get_replaced_code(self, names):
""" Return code, with new name, expressions, and replacements applied.
"""
code = self._code
# Modify name
fname = names[self]
code = code.replace(" " + self.name + "(", " " + fname + "(")
# Apply string replacements ... | Return code, with new name, expressions, and replacements applied. | entailment |
def _clean_code(self, code):
""" Return *code* with indentation and leading/trailing blank lines
removed.
"""
lines = code.split("\n")
min_indent = 100
for line in lines:
if line.strip() != "":
indent = len(line) - len(line.lstrip())
... | Return *code* with indentation and leading/trailing blank lines
removed. | entailment |
def add_chain(self, var):
"""
Create a new ChainFunction and attach to $var.
"""
chain = FunctionChain(var, [])
self._chains[var] = chain
self[var] = chain | Create a new ChainFunction and attach to $var. | entailment |
def append(self, function, update=True):
""" Append a new function to the end of this chain.
"""
self._funcs.append(function)
self._add_dep(function)
if update:
self._update() | Append a new function to the end of this chain. | entailment |
def insert(self, index, function, update=True):
""" Insert a new function into the chain at *index*.
"""
self._funcs.insert(index, function)
self._add_dep(function)
if update:
self._update() | Insert a new function into the chain at *index*. | entailment |
def remove(self, function, update=True):
""" Remove a function from the chain.
"""
self._funcs.remove(function)
self._remove_dep(function)
if update:
self._update() | Remove a function from the chain. | entailment |
def add(self, item, position=5):
"""Add an item to the list unless it is already present.
If the item is an expression, then a semicolon will be appended to it
in the final compiled code.
"""
if item in self.items:
return
self.items[item] = position
... | Add an item to the list unless it is already present.
If the item is an expression, then a semicolon will be appended to it
in the final compiled code. | entailment |
def remove(self, item):
"""Remove an item from the list.
"""
self.items.pop(item)
self._remove_dep(item)
self.order = None
self.changed(code_changed=True) | Remove an item from the list. | entailment |
def faces(self):
"""Return an array (Nf, 3) of vertex indexes, three per triangular
face in the mesh.
If faces have not been computed for this mesh, the function
computes them.
If no vertices or faces are specified, the function returns None.
"""
if self._faces ... | Return an array (Nf, 3) of vertex indexes, three per triangular
face in the mesh.
If faces have not been computed for this mesh, the function
computes them.
If no vertices or faces are specified, the function returns None. | entailment |
def vertices(self):
"""Return an array (Nf, 3) of vertices.
If only faces exist, the function computes the vertices and
returns them.
If no vertices or faces are specified, the function returns None.
"""
if self._faces is None:
if self._vertices is None:
... | Return an array (Nf, 3) of vertices.
If only faces exist, the function computes the vertices and
returns them.
If no vertices or faces are specified, the function returns None. | entailment |
def convex_hull(self):
"""Return an array of vertex indexes representing the convex hull.
If faces have not been computed for this mesh, the function
computes them.
If no vertices or faces are specified, the function returns None.
"""
if self._faces is None:
... | Return an array of vertex indexes representing the convex hull.
If faces have not been computed for this mesh, the function
computes them.
If no vertices or faces are specified, the function returns None. | entailment |
def triangulate(self):
"""
Triangulates the set of vertices and stores the triangles in faces and
the convex hull in convex_hull.
"""
npts = self._vertices.shape[0]
if np.any(self._vertices[0] != self._vertices[1]):
# start != end, so edges must wrap around to... | Triangulates the set of vertices and stores the triangles in faces and
the convex hull in convex_hull. | entailment |
def find(name):
"""Locate a filename into the shader library."""
if op.exists(name):
return name
path = op.dirname(__file__) or '.'
paths = [path] + config['include_path']
for path in paths:
filename = op.abspath(op.join(path, name))
if op.exists(filename):
re... | Locate a filename into the shader library. | entailment |
def get(name):
"""Retrieve code from the given filename."""
filename = find(name)
if filename is None:
raise RuntimeError('Could not find %s' % name)
with open(filename) as fid:
return fid.read() | Retrieve code from the given filename. | entailment |
def expect(func, args, times=7, sleep_t=0.5):
"""try many times as in times with sleep time"""
while times > 0:
try:
return func(*args)
except Exception as e:
times -= 1
logger.debug("expect failed - attempts left: %d" % times)
time.sleep(sleep_t)
... | try many times as in times with sleep time | entailment |
def num(string):
"""convert a string to float"""
if not isinstance(string, type('')):
raise ValueError(type(''))
try:
string = re.sub('[^a-zA-Z0-9\.\-]', '', string)
number = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", string)
return float(number[0])
except Exception as e:
... | convert a string to float | entailment |
def get_number_unit(number):
"""get the unit of number"""
n = str(float(number))
mult, submult = n.split('.')
if float(submult) != 0:
unit = '0.' + (len(submult)-1)*'0' + '1'
return float(unit)
else:
return float(1) | get the unit of number | entailment |
def get_pip(mov=None, api=None, name=None):
"""get value of pip"""
# ~ check args
if mov is None and api is None:
logger.error("need at least one of those")
raise ValueError()
elif mov is not None and api is not None:
logger.error("mov and api are exclusive")
raise ValueE... | get value of pip | entailment |
def itemsize(self):
""" Individual item sizes """
return self._items[:self._count, 1] - self._items[:self._count, 0] | Individual item sizes | entailment |
def reserve(self, capacity):
""" Set current capacity of the underlying array"""
if capacity >= self._data.size:
capacity = int(2 ** np.ceil(np.log2(capacity)))
self._data = np.resize(self._data, capacity) | Set current capacity of the underlying array | entailment |
def insert(self, index, data, itemsize=None):
""" Insert data before index
Parameters
----------
index : int
Index before which data will be inserted.
data : array_like
An array, any object exposing the array interface, an object
whose __arr... | Insert data before index
Parameters
----------
index : int
Index before which data will be inserted.
data : array_like
An array, any object exposing the array interface, an object
whose __array__ method returns an array, or any (nested) sequence.
... | entailment |
def append(self, data, itemsize=None):
"""
Append data to the end.
Parameters
----------
data : array_like
An array, any object exposing the array interface, an object
whose __array__ method returns an array, or any (nested) sequence.
itemsize: ... | Append data to the end.
Parameters
----------
data : array_like
An array, any object exposing the array interface, an object
whose __array__ method returns an array, or any (nested) sequence.
itemsize: int or 1-D array
If `itemsize is an integer, N... | entailment |
def minimize(func, bounds=None, nvar=None, args=(), disp=False,
eps=1e-4,
maxf=20000,
maxT=6000,
algmethod=0,
fglobal=-1e100,
fglper=0.01,
volper=-1.0,
sigmaper=-1.0,
**kwargs
):
... | Solve an optimization problem using the DIRECT (Dividing Rectangles) algorithm.
It can be used to solve general nonlinear programming problems of the form:
.. math::
\min_ {x \in R^n} f(x)
subject to
.. math::
x_L \leq x \leq x_U
Where :math:`x` are the... | 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.
"""
try:
user32.SetProcessDPIAware(... | 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 build_if_needed(self):
""" Reset shader source if necesssary.
"""
if self._need_build:
self._build()
self._need_build = False
self.update_variables() | Reset shader source if necesssary. | entailment |
def nmap(a, b, c, d, curvefn=None, normfn=None):
"""
Returns a function that maps a number n from range (a, b) onto a range
(c, d). If no curvefn is given, linear mapping will be used. Optionally a
normalisation function normfn can be provided to transform output.
"""
if not curvefn:
cur... | Returns a function that maps a number n from range (a, b) onto a range
(c, d). If no curvefn is given, linear mapping will be used. Optionally a
normalisation function normfn can be provided to transform output. | entailment |
def link_view(self, view):
"""Link this axis to a ViewBox
This makes it so that the axis's domain always matches the
visible range in the ViewBox.
Parameters
----------
view : instance of ViewBox
The ViewBox to link.
"""
if view is self._link... | Link this axis to a ViewBox
This makes it so that the axis's domain always matches the
visible range in the ViewBox.
Parameters
----------
view : instance of ViewBox
The ViewBox to link. | entailment |
def _view_changed(self, event=None):
"""Linked view transform has changed; update ticks.
"""
tr = self.node_transform(self._linked_view.scene)
p1, p2 = tr.map(self._axis_ends())
if self.orientation in ('left', 'right'):
self.axis.domain = (p1[1], p2[1])
else:
... | Linked view transform has changed; update ticks. | entailment |
def viewbox_mouse_event(self, event):
"""ViewBox mouse event handler
Parameters
----------
event : instance of Event
The mouse event.
"""
# When the attached ViewBox reseives a mouse event, it is sent to the
# camera here.
self.mouse_... | ViewBox mouse event handler
Parameters
----------
event : instance of Event
The mouse event. | entailment |
def on_timer(self, event=None):
"""Timer event handler
Parameters
----------
event : instance of Event
The timer event.
"""
# Smoothly update center and magnification properties of the transform
k = np.clip(100. / self.mag.mag, 10, 100)
s = 10... | Timer event handler
Parameters
----------
event : instance of Event
The timer event. | entailment |
def glBufferData(target, data, usage):
""" Data can be numpy array or the size of data to allocate.
"""
if isinstance(data, int):
size = data
data = ctypes.c_voidp(0)
else:
if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
data = data.copy('C')
d... | Data can be numpy array or the size of data to allocate. | entailment |
def next_power_of_2(n):
""" Return next power of 2 greater than or equal to n """
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n + 1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift *= 2
return max(4, n + 1) | Return next power of 2 greater than or equal to n | entailment |
def append(self, vertices, uniforms=None, indices=None, itemsize=None):
"""
Parameters
----------
vertices : numpy array
An array whose dtype is compatible with self.vdtype
uniforms: numpy array
An array whose dtype is compatible with self.utype
... | Parameters
----------
vertices : numpy array
An array whose dtype is compatible with self.vdtype
uniforms: numpy array
An array whose dtype is compatible with self.utype
indices : numpy array
An array whose dtype is compatible with self.idtype
... | entailment |
def _compute_texture_shape(self, size=1):
""" Compute uniform texture shape """
# We should use this line but we may not have a GL context yet
# linesize = gl.glGetInteger(gl.GL_MAX_TEXTURE_SIZE)
linesize = 1024
count = self._uniforms_float_count
cols = 4 * linesize // i... | Compute uniform texture shape | entailment |
def _update(self):
""" Update vertex buffers & texture """
if self._vertices_buffer is not None:
self._vertices_buffer.delete()
self._vertices_buffer = VertexBuffer(self._vertices_list.data)
if self.itype is not None:
if self._indices_buffer is not None:
... | Update vertex buffers & texture | entailment |
def get_layout(name, *args, **kwargs):
"""
Retrieve a graph layout
Some graph layouts accept extra options. Please refer to their
documentation for more information.
Parameters
----------
name : string
The name of the layout. The variable `AVAILABLE_LAYOUTS`
contains all av... | Retrieve a graph layout
Some graph layouts accept extra options. Please refer to their
documentation for more information.
Parameters
----------
name : string
The name of the layout. The variable `AVAILABLE_LAYOUTS`
contains all available layouts.
*args
Positional argum... | entailment |
def update_viewer_state(rec, context):
"""
Given viewer session information, make sure the session information is
compatible with the current version of the viewers, and if not, update
the session information in-place.
"""
if '_protocol' not in rec:
rec.pop('properties')
rec['... | Given viewer session information, make sure the session information is
compatible with the current version of the viewers, and if not, update
the session information in-place. | entailment |
def remove_comments(code):
"""Remove C-style comment from GLSL code string."""
pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*\n)"
# first group captures quoted strings (double or single)
# second group captures comments (//single-line or /* multi-line */)
regex = re.compile(pattern, re.MULTILI... | Remove C-style comment from GLSL code string. | entailment |
def merge_includes(code):
"""Merge all includes recursively."""
pattern = '\#\s*include\s*"(?P<filename>[a-zA-Z0-9\_\-\.\/]+)"'
regex = re.compile(pattern)
includes = []
def replace(match):
filename = match.group("filename")
if filename not in includes:
includes.append... | Merge all includes recursively. | entailment |
def add_widget(self, widget=None, row=None, col=None, row_span=1,
col_span=1, **kwargs):
"""
Add a new widget to this grid. This will cause other widgets in the
grid to be resized to make room for the new widget. Can be used
to replace a widget as well
Paramet... | Add a new widget to this grid. This will cause other widgets in the
grid to be resized to make room for the new widget. Can be used
to replace a widget as well
Parameters
----------
widget : Widget | None
The Widget to add. New widget is constructed if widget is None... | entailment |
def remove_widget(self, widget):
"""Remove a widget from this grid
Parameters
----------
widget : Widget
The Widget to remove
"""
self._grid_widgets = dict((key, val)
for (key, val) in self._grid_widgets.items()
... | Remove a widget from this grid
Parameters
----------
widget : Widget
The Widget to remove | entailment |
def resize_widget(self, widget, row_span, col_span):
"""Resize a widget in the grid to new dimensions.
Parameters
----------
widget : Widget
The widget to resize
row_span : int
The number of rows to be occupied by this widget.
col_span : int
... | Resize a widget in the grid to new dimensions.
Parameters
----------
widget : Widget
The widget to resize
row_span : int
The number of rows to be occupied by this widget.
col_span : int
The number of columns to be occupied by this widget. | entailment |
def add_grid(self, row=None, col=None, row_span=1, col_span=1,
**kwargs):
"""
Create a new Grid and add it as a child widget.
Parameters
----------
row : int
The row in which to add the widget (0 is the topmost row)
col : int
The ... | Create a new Grid and add it as a child widget.
Parameters
----------
row : int
The row in which to add the widget (0 is the topmost row)
col : int
The column in which to add the widget (0 is the leftmost column)
row_span : int
The number of r... | entailment |
def add_view(self, row=None, col=None, row_span=1, col_span=1,
**kwargs):
"""
Create a new ViewBox and add it as a child widget.
Parameters
----------
row : int
The row in which to add the widget (0 is the topmost row)
col : int
T... | Create a new ViewBox and add it as a child widget.
Parameters
----------
row : int
The row in which to add the widget (0 is the topmost row)
col : int
The column in which to add the widget (0 is the leftmost column)
row_span : int
The number o... | entailment |
def find_font(face, bold, italic):
"""Find font"""
bold = FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR
italic = FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN
face = face.encode('utf8')
fontconfig.FcInit()
pattern = fontconfig.FcPatternCreate()
fontconfig.FcPatternAddInteger(pattern, FC_WEIG... | Find font | entailment |
def _list_fonts():
"""List system fonts"""
stdout_, stderr = run_subprocess(['fc-list', ':scalable=true', 'family'])
vals = [v.split(',')[0] for v in stdout_.strip().splitlines(False)]
return vals | List system fonts | entailment |
def _get_vispy_caller():
"""Helper to get vispy calling function from the stack"""
records = inspect.stack()
# first few records are vispy-based logging calls
for record in records[5:]:
module = record[0].f_globals['__name__']
if module.startswith('vispy'):
line = str(record[... | Helper to get vispy calling function from the stack | entailment |
def set_log_level(verbose, match=None, return_old=False):
"""Convenience function for setting the logging level
Parameters
----------
verbose : bool, str, int, or None
The verbosity of messages to print. If a str, it can be either DEBUG,
INFO, WARNING, ERROR, or CRITICAL. Note that thes... | Convenience function for setting the logging level
Parameters
----------
verbose : bool, str, int, or None
The verbosity of messages to print. If a str, it can be either DEBUG,
INFO, WARNING, ERROR, or CRITICAL. Note that these are for
convenience and are equivalent to passing in lo... | entailment |
def log_exception(level='warning', tb_skip=2):
"""
Send an exception and traceback to the logger.
This function is used in cases where an exception is handled safely but
nevertheless should generate a descriptive error message. An extra line
is inserted into the stack trace indicating where the... | Send an exception and traceback to the logger.
This function is used in cases where an exception is handled safely but
nevertheless should generate a descriptive error message. An extra line
is inserted into the stack trace indicating where the exception was caught.
Parameters
----------
... | entailment |
def _handle_exception(ignore_callback_errors, print_callback_errors, obj,
cb_event=None, node=None):
"""Helper for prining errors in callbacks
See EventEmitter._invoke_callback for a use example.
"""
if not hasattr(obj, '_vispy_err_registry'):
obj._vispy_err_registry = {}
... | Helper for prining errors in callbacks
See EventEmitter._invoke_callback for a use example. | entailment |
def _serialize_buffer(buffer, array_serialization=None):
"""Serialize a NumPy array."""
if array_serialization == 'binary':
# WARNING: in NumPy 1.9, tostring() has been renamed to tobytes()
# but tostring() is still here for now for backward compatibility.
return buffer.ravel().tostring(... | Serialize a NumPy array. | entailment |
def _vispy_emit_match_andor_record(self, record):
"""Log message emitter that optionally matches and/or records"""
test = record.getMessage()
match = self._vispy_match
if (match is None or re.search(match, test) or
re.search(match, _get_vispy_caller())):
if se... | Log message emitter that optionally matches and/or records | entailment |
def create(self, obj, ref=None):
""" Convert *obj* to a new ShaderObject. If the output is a Variable
with no name, then set its name using *ref*.
"""
if isinstance(ref, Variable):
ref = ref.name
elif isinstance(ref, string_types) and ref.startswith('gl_'):
... | Convert *obj* to a new ShaderObject. If the output is a Variable
with no name, then set its name using *ref*. | entailment |
def dependencies(self, sort=False):
""" Return all dependencies required to use this object. The last item
in the list is *self*.
"""
alldeps = []
if sort:
def key(obj):
# sort deps such that we get functions, variables, self.
if not i... | Return all dependencies required to use this object. The last item
in the list is *self*. | entailment |
def _add_dep(self, dep):
""" Increment the reference count for *dep*. If this is a new
dependency, then connect to its *changed* event.
"""
if dep in self._deps:
self._deps[dep] += 1
else:
self._deps[dep] = 1
dep._dependents[self] = None | Increment the reference count for *dep*. If this is a new
dependency, then connect to its *changed* event. | entailment |
def _remove_dep(self, dep):
""" Decrement the reference count for *dep*. If the reference count
reaches 0, then the dependency is removed and its *changed* event is
disconnected.
"""
refcount = self._deps[dep]
if refcount == 1:
self._deps.pop(dep)
... | Decrement the reference count for *dep*. If the reference count
reaches 0, then the dependency is removed and its *changed* event is
disconnected. | entailment |
def _dep_changed(self, dep, code_changed=False, value_changed=False):
""" Called when a dependency's expression has changed.
"""
self.changed(code_changed, value_changed) | Called when a dependency's expression has changed. | entailment |
def changed(self, code_changed=False, value_changed=False):
"""Inform dependents that this shaderobject has changed.
"""
for d in self._dependents:
d._dep_changed(self, code_changed=code_changed,
value_changed=value_changed) | Inform dependents that this shaderobject has changed. | entailment |
def eq(a, b):
""" The great missing equivalence function: Guaranteed evaluation
to a single bool value.
"""
if a is b:
return True
if a is None or b is None:
return True if a is None and b is None else False
try:
e = a == b
except ValueError:
return False
... | The great missing equivalence function: Guaranteed evaluation
to a single bool value. | entailment |
def zoom(self, factor, center=None):
""" Zoom in (or out) at the given center
Parameters
----------
factor : float or tuple
Fraction by which the scene should be zoomed (e.g. a factor of 2
causes the scene to appear twice as large).
center : tuple of 2-4 ... | Zoom in (or out) at the given center
Parameters
----------
factor : float or tuple
Fraction by which the scene should be zoomed (e.g. a factor of 2
causes the scene to appear twice as large).
center : tuple of 2-4 elements
The center of the view. If n... | entailment |
def pan(self, *pan):
"""Pan the view.
Parameters
----------
*pan : length-2 sequence
The distance to pan the view, in the coordinate system of the
scene.
"""
if len(pan) == 1:
pan = pan[0]
self.rect = self.rect + pan | Pan the view.
Parameters
----------
*pan : length-2 sequence
The distance to pan the view, in the coordinate system of the
scene. | entailment |
def viewbox_mouse_event(self, event):
"""
The SubScene received a mouse event; update transform
accordingly.
Parameters
----------
event : instance of Event
The event.
"""
if event.handled or not self.interactive:
return
#... | The SubScene received a mouse event; update transform
accordingly.
Parameters
----------
event : instance of Event
The event. | entailment |
def set_data(self, vol, clim=None):
""" Set the volume data.
Parameters
----------
vol : ndarray
The 3D volume.
clim : tuple | None
Colormap limits to use. None will use the min and max values.
"""
# Check volume
if not isinstance... | Set the volume data.
Parameters
----------
vol : ndarray
The 3D volume.
clim : tuple | None
Colormap limits to use. None will use the min and max values. | entailment |
def _create_vertex_data(self):
""" Create and set positions and texture coords from the given shape
We have six faces with 1 quad (2 triangles) each, resulting in
6*2*3 = 36 vertices in total.
"""
shape = self._vol_shape
# Get corner coordinates. The -0.... | Create and set positions and texture coords from the given shape
We have six faces with 1 quad (2 triangles) each, resulting in
6*2*3 = 36 vertices in total. | entailment |
def set_data(self, pos=None, color=None):
"""Set the data
Parameters
----------
pos : list, tuple or numpy array
Bounds of the region along the axis. len(pos) must be >=2.
color : list, tuple, or array
The color to use when drawing the line. It must have ... | Set the data
Parameters
----------
pos : list, tuple or numpy array
Bounds of the region along the axis. len(pos) must be >=2.
color : list, tuple, or array
The color to use when drawing the line. It must have a shape of
(1, 4) for a single color regi... | entailment |
def _prepare_draw(self, view=None):
"""This method is called immediately before each draw.
The *view* argument indicates which view is about to be drawn.
"""
if self._changed['pos']:
self.pos_buf.set_data(self._pos)
self._changed['pos'] = False
if self.... | This method is called immediately before each draw.
The *view* argument indicates which view is about to be drawn. | entailment |
def refresh_cache(self, cat_id):
'''
Repopulate cache
'''
self.cache[cat_id] = most_recent_25_posts_by_category(cat_id)
self.last_refresh[cat_id] = datetime.now()
print ('Cache refresh at...', str(self.last_refresh[cat_id])) | Repopulate cache | entailment |
def _merge_intervals(self, min_depth):
"""
Merge overlapping intervals.
This method is called only once in the constructor.
"""
def add_interval(ret, start, stop):
if min_depth is not None:
shift = 2 * (29 - min_depth)
mask = (int(1) <... | Merge overlapping intervals.
This method is called only once in the constructor. | entailment |
def union(self, another_is):
"""
Return the union between self and ``another_is``.
Parameters
----------
another_is : `IntervalSet`
an IntervalSet object.
Returns
-------
interval : `IntervalSet`
the union of self with ``another_is... | Return the union between self and ``another_is``.
Parameters
----------
another_is : `IntervalSet`
an IntervalSet object.
Returns
-------
interval : `IntervalSet`
the union of self with ``another_is``. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.