text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
b = __font_6x8__[I]
self._bytes_012[idx, :len(I)] = b[:, :3]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
continue
if var in ('pre', 'post'):
raise ValueError('GLSL uses reserved template variable $%s' %
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 first -- these may contain $placeholders
for key, val in self._replacements.items():
code = code.replace(ke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, function, update=True):
""" Remove a function from the chain. """ |
self._funcs.remove(function)
self._remove_dep(function)
if update:
self._update() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 i... |
if item in self.items:
return
self.items[item] = position
self._add_dep(item)
self.order = None
self.changed(code_changed=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 th... |
if self._faces is None:
if self._vertices is None:
return None
self.triangulate()
return self._convex_hull |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 beginning.
edges = np.empty((npts, 2), dtype=np.uint32)
edges[:, 0] = np.arange(npts)
edges[:, 1] = edges[:, 0] + 1
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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):
return filename
for d in os.listdir(path):
fullpa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
if times == 0:
raise exceptions.BaseExc(e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
logger = logging.getLogger('tradingAPI.utils.num... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ValueError()
if api is not None:
if name is None:
lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def itemsize(self):
""" Individual item sizes """ |
return self._items[:self._count, 1] - self._items[:self._count, 0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 whos... |
self.insert(len(self), data, itemsize) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_if_needed(self):
""" Reset shader source if necesssary. """ |
if self._need_build:
self._build()
self._need_build = False
self.update_variables() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 vie... |
if view is self._linked_view:
return
if self._linked_view is not None:
self._linked_view.scene.transform.changed.disconnect(
self._view_changed)
self._linked_view = view
view.scene.transform.changed.connect(self._view_changed)
self._view_c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
self.axis.domain = (p1[0], p2[0]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 // int(count)
rows = max(1, int(math.ceil(size / float(cols))))
shape = row... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
self._indices_buffer.delete()
self._indices_b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_layout(name, *args, **kwargs):
""" Retrieve a graph layout Some graph layouts accept extra options. Please refer to their documentation for more informat... |
if name not in _layout_map:
raise KeyError("Graph layout '%s' not found. Should be one of %s"
% (name, AVAILABLE_LAYOUTS))
layout = _layout_map[name]
if inspect.isclass(layout):
layout = layout(*args, **kwargs)
return layout |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_viewer_state(rec, context):
""" Given viewer session information, make sure the session information is compatible with the current version of the view... |
if '_protocol' not in rec:
rec.pop('properties')
rec['state'] = {}
rec['state']['values'] = rec.pop('options')
layer_states = []
for layer in rec['layers']:
state_id = str(uuid.uuid4())
state_cls = STATE_CLASS[layer['_type'].split('.')[-1]]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.MULTILINE | re.DOTALL)
def do_replace(match):
# if the 2nd group (capturing ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(filename)
path = glsl.find(filename)
if no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
if row is None:
row = self._next_cell[0]
if col is None:
col = self._next_cell[1]
if widget is None:
widget = Widget(**kwargs)
else:
if kwargs:
raise ValueError("cannot send kwargs if widget is given")
_row = self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()
if val[-1] != widget)
self._need_solver_recreate = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 :... |
row = None
col = None
for (r, c, rspan, cspan, w) in self._grid_widgets.values():
if w == widget:
row = r
col = c
break
if row is None or col is None:
raise ValueError("%s not found in grid" % widget)
s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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[0].f_lineno)
func = record[3]
cls = record[0].f_locals.get('se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
# This method is responsible for setting properties of the handler and
# formatter such that proper messages (possibly with the vispy caller
# prepended) are displayed. Storing log messages is only available
# via the context handler (use_log_level), so that configuration is
# done by the context h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_exception(ignore_callback_errors, print_callback_errors, obj, cb_event=None, node=None):
"""Helper for prining errors in callbacks See EventEmitter._... |
if not hasattr(obj, '_vispy_err_registry'):
obj._vispy_err_registry = {}
registry = obj._vispy_err_registry
if cb_event is not None:
cb, event = cb_event
exp_type = 'callback'
else:
exp_type = 'node'
type_, value, tb = sys.exc_info()
tb = tb.tb_next # Skip *thi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()
elif array_serialization == 'base64':
return {'storage_type': 'base64',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
# Scrolling
BaseCamera.viewbox_mouse_event(self, event)
if event.type == 'mouse_wheel':
center = self._scene_transform.imap(event.pos)
self.zoom((1 + self.zoom_factor) ** (-event.delta[1] * 30), cente... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 th... |
# Check volume
if not isinstance(vol, np.ndarray):
raise ValueError('Volume visual needs a numpy array.')
if not ((vol.ndim == 3) or (vol.ndim == 4 and vol.shape[-1] <= 4)):
raise ValueError('Volume visual needs a 3D image.')
# Handle clim
if cli... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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._changed['color']:
self.color_buf.set_data(self._color)
self._program.vert['color'] = self.color_buf
self._changed['color'] = False
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) << shift) - 1
if stop - start < mask:
ret.append((start, stop))
else:
ofs = start & mask... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def union(self, another_is):
""" Return the union between self and ``another_is``. Parameters another_is : `IntervalSet` an IntervalSet object. Returns ------- i... |
result = IntervalSet()
if another_is.empty():
result._intervals = self._intervals
elif self.empty():
result._intervals = another_is._intervals
else:
# res has no overlapping intervals
result._intervals = IntervalSet.merge(self._intervals,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_nuniq_interval_set(cls, nested_is):
""" Convert an IntervalSet using the NESTED numbering scheme to an IntervalSet containing UNIQ numbers for HEALPix cel... |
r2 = nested_is.copy()
res = []
if r2.empty():
return IntervalSet()
order = 0
while not r2.empty():
shift = int(2 * (IntervalSet.HPY_MAX_ORDER - order))
ofs = (int(1) << shift) - 1
ofs2 = int(1) << (2 * order + 2)
r4 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_nuniq_interval_set(cls, nuniq_is):
""" Convert an IntervalSet containing NUNIQ intervals to an IntervalSet representing HEALPix cells following the NEST... |
nested_is = IntervalSet()
# Appending a list is faster than appending a numpy array
# For these algorithms we append a list and create the interval set from the finished list
rtmp = []
last_order = 0
intervals = nuniq_is._intervals
diff_order = IntervalSet.HPY_MA... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(a_intervals, b_intervals, op):
""" Merge two lists of intervals according to the boolean function op ``a_intervals`` and ``b_intervals`` need to be sor... |
a_endpoints = a_intervals.flatten().tolist()
b_endpoints = b_intervals.flatten().tolist()
sentinel = max(a_endpoints[-1], b_endpoints[-1]) + 1
a_endpoints += [sentinel]
b_endpoints += [sentinel]
a_index = 0
b_index = 0
res = []
scan = min(a_e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Delete the object from GPU memory. Note that the GPU object will also be deleted when this gloo object is about to be deleted. However, som... |
# We only allow the object from being deleted once, otherwise
# we might be deleting another GPU object that got our gl-id
# after our GPU object was deleted. Also note that e.g.
# DataBufferView does not have the _glir attribute.
if hasattr(self, '_glir'):
# Send ou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_interpolation(self):
"""Rebuild the _data_lookup_fn using different interpolations within the shader """ |
interpolation = self._interpolation
self._data_lookup_fn = self._interpolation_fun[interpolation]
self.shared_program.frag['get_data'] = self._data_lookup_fn
# only 'bilinear' uses 'linear' texture interpolation
if interpolation == 'bilinear':
texture_interpolation ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_vertex_data(self):
"""Rebuild the vertex buffers used for rendering the image when using the subdivide method. """ |
grid = self._grid
w = 1.0 / grid[1]
h = 1.0 / grid[0]
quad = np.array([[0, 0, 0], [w, 0, 0], [w, h, 0],
[0, 0, 0], [w, h, 0], [0, h, 0]],
dtype=np.float32)
quads = np.empty((grid[1], grid[0], 6, 3), dtype=np.float32)
quad... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bake(self, P, key='curr', closed=False, itemsize=None):
""" Given a path P, return the baked vertices as they should be copied in the collection if the path ... |
itemsize = itemsize or len(P)
itemcount = len(P) / itemsize # noqa
n = itemsize
if closed:
I = np.arange(n + 3)
if key == 'prev':
I -= 2
I[0], I[1], I[-1] = n - 1, n - 1, n - 1
elif key == 'next':
I[0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stop_timers(canvas):
"""Stop all timers in a canvas.""" |
for attr in dir(canvas):
try:
attr_obj = getattr(canvas, attr)
except NotImplementedError:
# This try/except is needed because canvas.position raises
# an error (it is not implemented in this backend).
attr_obj = None
if isinstance(attr_obj, T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _last_stack_str():
"""Print stack trace from call that didn't originate from here""" |
stack = extract_stack()
for s in stack[::-1]:
if op.join('vispy', 'gloo', 'buffer.py') not in __file__:
break
return format_list([s])[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def glsl_type(self):
""" GLSL declaration strings required for a variable to hold this data. """ |
if self.dtype is None:
return None
dtshape = self.dtype[0].shape
n = dtshape[0] if dtshape else 1
if n > 1:
dtype = 'vec%d' % n
else:
dtype = 'float' if 'f' in self.dtype[0].base.kind else 'int'
return 'attribute', dtype |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rename_objects_pretty(self):
""" Rename all objects like "name_1" to avoid conflicts. Objects are only renamed if necessary. This method produces more reada... |
#
# 1. For each object, add its static names to the global namespace
# and make a list of the shaders used by the object.
#
# {name: obj} mapping for finding unique names
# initialize with reserved keywords.
self._global_ns = dict([(kwd, None) for kwd in gloo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_positions(self):
""" updates the positions of the colorbars and labels """ |
self._colorbar.pos = self._pos
self._border.pos = self._pos
if self._orientation == "right" or self._orientation == "left":
self._label.rotation = -90
x, y = self._pos
halfw, halfh = self._halfdim
label_anchors = \
ColorBarVisual._get_label_anc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calc_positions(center, halfdim, border_width, orientation, transforms):
""" Calculate the text centeritions given the ColorBar parameters. Note ---- This is... |
(x, y) = center
(halfw, halfh) = halfdim
visual_to_doc = transforms.get_transform('visual', 'document')
doc_to_visual = transforms.get_transform('document', 'visual')
# doc_widths = visual_to_doc.map(np.array([halfw, halfh, 0, 0],
# ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def size(self):
""" The size of the ColorBar Returns ------- size: (major_axis_length, minor_axis_length) major and minor axis are defined by the orientation of ... |
(halfw, halfh) = self._halfdim
if self.orientation in ["top", "bottom"]:
return (halfw * 2., halfh * 2.)
else:
return (halfh * 2., halfw * 2.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalized(self):
"""Return a Rect covering the same area, but with height and width guaranteed to be positive.""" |
return Rect(pos=(min(self.left, self.right),
min(self.top, self.bottom)),
size=(abs(self.width), abs(self.height))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flipped(self, x=False, y=True):
"""Return a Rect with the same bounds but with axes inverted Parameters x : bool Flip the X axis. y : bool Flip the Y axis. R... |
pos = list(self.pos)
size = list(self.size)
for i, flip in enumerate((x, y)):
if flip:
pos[i] += size[i]
size[i] *= -1
return Rect(pos, size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _transform_in(self):
"""Return array of coordinates that can be mapped by Transform classes.""" |
return np.array([
[self.left, self.bottom, 0, 1],
[self.right, self.top, 0, 1]]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calculate_delta_pos(adjacency_arr, pos, t, optimal):
"""Helper to calculate the delta position""" |
# XXX eventually this should be refactored for the sparse case to only
# do the necessary pairwise distances
delta = pos[:, np.newaxis, :] - pos
# Distance between points
distance2 = (delta*delta).sum(axis=-1)
# Enforce minimum distance of 0.01
distance2 = np.where(distance2 < 0.0001, 0.00... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_recipe_intent_handler(request):
""" You can insert arbitrary business logic code here """ |
# Get variables like userId, slots, intent name etc from the 'Request' object
ingredient = request.slots["Ingredient"] # Gets an Ingredient Slot from the Request object.
if ingredient == None:
return alexa.create_response("Could not find an ingredient!")
# All manipulations to the reque... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use(app=None, gl=None):
""" Set the usage options for vispy Specify what app backend and GL backend to use. Parameters app : str The app backend to use (case... |
if app is None and gl is None:
raise TypeError('Must specify at least one of "app" or "gl".')
# Example for future. This wont work (yet).
if app == 'ipynb_webgl':
app = 'headless'
gl = 'webgl'
if app == 'osmesa':
from ..util.osmesa_gl import fix_osmesa_gl_lib
f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_subprocess(command, return_code=False, **kwargs):
"""Run command using subprocess.Popen Run command and wait for command to complete. If the return code ... |
# code adapted with permission from mne-python
use_kwargs = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE)
use_kwargs.update(kwargs)
p = subprocess.Popen(command, **use_kwargs)
output = p.communicate()
# communicate() may return bytes, str, or None depending on the kwargs
# passed t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, interval=None, iterations=None):
"""Start the timer. A timeout event will be generated every *interval* seconds. If *interval* is None, then self... |
if self.running:
return # don't do anything if already running
self.iter_count = 0
if interval is not None:
self.interval = interval
if iterations is not None:
self.max_iterations = iterations
self._backend._vispy_start(self.interval)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _best_res_pixels(self):
""" Returns a numpy array of all the HEALPix indexes contained in the MOC at its max order. Returns ------- result : `~numpy.ndarray`... |
factor = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order)
pix_l = []
for iv in self._interval_set._intervals:
for val in range(iv[0] >> factor, iv[1] >> factor):
pix_l.append(val)
return np.asarray(pix_l) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_neighbours(self):
""" Extends the MOC instance so that it includes the HEALPix cells touching its border. The depth of the HEALPix cells added at the bor... |
# Get the pixels array of the MOC at the its max order.
ipix = self._best_res_pixels()
hp = HEALPix(nside=(1 << self.max_order), order='nested')
# Get the HEALPix array containing the neighbors of ``ipix``.
# This array "extends" ``ipix`` by one degree of neighbors.
ex... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_neighbours(self):
""" Removes from the MOC instance the HEALPix cells located at its border. The depth of the HEALPix cells removed is equal to the ma... |
# Get the HEALPix cells of the MOC at its max depth
ipix = self._best_res_pixels()
hp = HEALPix(nside=(1 << self.max_order), order='nested')
# Extend it to include the max depth neighbor cells.
extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix)
# Get only the max de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill(self, ax, wcs, **kw_mpl_pathpatch):
""" Draws the MOC on a matplotlib axis. This performs the projection of the cells from the world coordinate system t... |
fill.fill(self, ax, wcs, **kw_mpl_pathpatch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_image(cls, header, max_norder, mask=None):
""" Creates a `~mocpy.moc.MOC` from an image stored as a FITS file. Parameters header : `astropy.io.fits.Head... |
# load the image data
height = header['NAXIS2']
width = header['NAXIS1']
# use wcs from astropy to locate the image in the world coordinates
w = wcs.WCS(header)
if mask is not None:
# We have an array of pixels that are part of of survey
y, x = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_fits_images(cls, path_l, max_norder):
""" Loads a MOC from a set of FITS file images. Parameters path_l : [str] A list of path where the fits image are ... |
moc = MOC()
for path in path_l:
header = fits.getheader(path)
current_moc = MOC.from_image(header=header, max_norder=max_norder)
moc = moc.union(current_moc)
return moc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_vizier_table(cls, table_id, nside=256):
""" Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astr... |
nside_possible_values = (8, 16, 32, 64, 128, 256, 512)
if nside not in nside_possible_values:
raise ValueError('Bad value for nside. Must be in {0}'.format(nside_possible_values))
result = cls.from_ivorn('ivo://CDS/' + table_id, nside)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_ivorn(cls, ivorn, nside=256):
""" Creates a `~mocpy.moc.MOC` object from a given ivorn. Parameters ivorn : str nside : int, optional 256 by default Retu... |
return cls.from_url('%s?%s' % (MOC.MOC_SERVER_ROOT_URL,
urlencode({
'ivorn': ivorn,
'get': 'moc',
'order': int(np.log2(nside))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_url(cls, url):
""" Creates a `~mocpy.moc.MOC` object from a given url. Parameters url : str The url of a FITS file storing a MOC. Returns ------- result... |
path = download_file(url, show_progress=False, timeout=60)
return cls.from_fits(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_skycoords(cls, skycoords, max_norder):
""" Creates a MOC from an `astropy.coordinates.SkyCoord`. Parameters skycoords : `astropy.coordinates.SkyCoord` T... |
hp = HEALPix(nside=(1 << max_norder), order='nested')
ipix = hp.lonlat_to_healpix(skycoords.icrs.ra, skycoords.icrs.dec)
shift = 2 * (AbstractMOC.HPY_MAX_NORDER - max_norder)
intervals = np.vstack((ipix << shift, (ipix + 1) << shift)).T
interval_set = IntervalSet(intervals)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_polygon_skycoord(cls, skycoord, inside=None, max_depth=10):
""" Creates a MOC from a polygon. The polygon is given as an `astropy.coordinates.SkyCoord` ... |
return MOC.from_polygon(lon=skycoord.icrs.ra, lat=skycoord.icrs.dec,
inside=inside, max_depth=max_depth) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_polygon(cls, lon, lat, inside=None, max_depth=10):
""" Creates a MOC from a polygon The polygon is given as lon and lat `astropy.units.Quantity` that de... |
from .polygon import PolygonComputer
polygon_computer = PolygonComputer(lon, lat, inside, max_depth)
# Create the moc from the python dictionary
moc = MOC.from_json(polygon_computer.ipix)
# We degrade it to the user-requested order
if polygon_computer.degrade_to_max_de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sky_fraction(self):
""" Sky fraction covered by the MOC """ |
pix_id = self._best_res_pixels()
nb_pix_filled = pix_id.size
return nb_pix_filled / float(3 << (2*(self.max_order + 1))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _query(self, resource_id, max_rows):
""" Internal method to query Simbad or a VizieR table for sources in the coverage of the MOC instance """ |
from astropy.io.votable import parse_single_table
if max_rows is not None and max_rows >= 0:
max_rows_str = str(max_rows)
else:
max_rows_str = str(9999999999)
tmp_moc = tempfile.NamedTemporaryFile(delete=False)
self.write(tmp_moc.name)
r = requ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inverse(self):
""" The inverse of this transform. """ |
if self._inverse is None:
self._inverse = InverseTransform(self)
return self._inverse |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tile_ticks(self, frac, tickvec):
"""Tiles tick marks along the axis.""" |
origins = np.tile(self.axis._vec, (len(frac), 1))
origins = self.axis.pos[0].T + (origins.T*frac).T
endpoints = tickvec + origins
return origins, endpoints |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_tick_frac_labels(self):
"""Get the major ticks, minor ticks, and major labels""" |
minor_num = 4 # number of minor ticks per major division
if (self.axis.scale_type == 'linear'):
domain = self.axis.domain
if domain[1] < domain[0]:
flip = True
domain = domain[::-1]
else:
flip = False
offse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_packed(self, outfile, rows):
""" Write PNG file to `outfile`. The pixel data comes from `rows` which should be in boxed row packed format. Each row sho... |
if self.rescale:
raise Error("write_packed method not suitable for bit depth %d" %
self.rescale[0])
return self.write_passes(outfile, rows, packed=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile):
""" Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in ... |
pixels = array('B')
pixels.fromfile(ppmfile,
(self.bitdepth/8) * self.color_planes *
self.width * self.height)
apixels = array('B')
apixels.fromfile(pgmfile,
(self.bitdepth/8) *
self.width ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def array_scanlines_interlace(self, pixels):
""" Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel forma... |
# http://www.w3.org/TR/PNG/#8InterlaceMethods
# Array type.
fmt = 'BH'[self.bitdepth > 8]
# Value per row
vpr = self.width * self.planes
for xstart, ystart, xstep, ystep in _adam7:
if xstart >= self.width:
continue
# Pixels per ro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deinterlace(self, raw):
""" Read raw pixel data, undo filters, deinterlace, and flatten. Return in flat row flat pixel format. """ |
# Values per row (of the target image)
vpr = self.width * self.planes
# Make a result array, and make it big enough. Interleaving
# writes to the output array randomly (well, not quite), so the
# entire output array must be in memory.
fmt = 'BH'[self.bitdepth > 8]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterboxed(self, rows):
"""Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row i... |
def asvalues(raw):
"""Convert a row of raw bytes into a flat row. Result will
be a freshly allocated object, not shared with
argument.
"""
if self.bitdepth == 8:
return array('B', raw)
if self.bitdepth == 16:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_data_file(fname, directory=None, force_download=False):
"""Get a standard vispy demo data file Parameters fname : str The filename on the remote ``demo-... |
_url_root = 'http://github.com/vispy/demo-data/raw/master/'
url = _url_root + fname
if directory is None:
directory = config['data_path']
if directory is None:
raise ValueError('config["data_path"] is not defined, '
'so directory must be supplied')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _chunk_write(chunk, local_file, progress):
"""Write a chunk to file and update the progress bar""" |
local_file.write(chunk)
progress.update_with_increment_value(len(chunk)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch_file(url, file_name, print_destination=True):
"""Load requested file, downloading it if needed or requested Parameters url: string The url of file to ... |
# Adapted from NISL:
# https://github.com/nisl/tutorial/blob/master/nisl/datasets.py
temp_file_name = file_name + ".part"
local_file = None
initial_size = 0
# Checking file size and displaying it alongside the download url
n_try = 3
for ii in range(n_try):
try:
data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, cur_value, mesg=None):
"""Update progressbar with current value of process Parameters cur_value : number Current value of process. Should be <= ... |
# Ensure floating-point division so we can get fractions of a percent
# for the progressbar.
self.cur_value = cur_value
progress = float(self.cur_value) / self.max_value
num_chars = int(progress * self.max_chars)
num_left = self.max_chars - num_chars
# Update th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def central_widget(self):
""" Returns the default widget that occupies the entire area of the canvas. """ |
if self._central_widget is None:
self._central_widget = Widget(size=self.size, parent=self.scene)
return self._central_widget |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visual_at(self, pos):
"""Return the visual at a given position Parameters pos : tuple The position in logical coordinates to query. Returns ------- visual : ... |
tr = self.transforms.get_transform('canvas', 'framebuffer')
fbpos = tr.map(pos)[:2]
try:
id_ = self._render_picking(region=(fbpos[0], fbpos[1],
1, 1))
vis = VisualNode._visual_ids.get(id_[0, 0], None)
except Runtime... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _render_picking(self, **kwargs):
"""Render the scene in picking mode, returning a 2D array of visual IDs. """ |
try:
self._scene.picking = True
img = self.render(bgcolor=(0, 0, 0, 0), **kwargs)
finally:
self._scene.picking = False
img = img.astype('int32') * [2**0, 2**8, 2**16, 2**24]
id_ = img.sum(axis=2).astype('int32')
return id_ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_close(self, event):
"""Close event handler Parameters event : instance of Event The event. """ |
self.events.mouse_press.disconnect(self._process_mouse_event)
self.events.mouse_move.disconnect(self._process_mouse_event)
self.events.mouse_release.disconnect(self._process_mouse_event)
self.events.mouse_wheel.disconnect(self._process_mouse_event) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop_viewport(self):
""" Pop a viewport from the stack. """ |
vp = self._vp_stack.pop()
# Activate latest
if len(self._vp_stack) > 0:
self.context.set_viewport(*self._vp_stack[-1])
else:
self.context.set_viewport(0, 0, *self.physical_size)
self._update_transforms()
return vp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push_fbo(self, fbo, offset, csize):
""" Push an FBO on the stack. This activates the framebuffer and causes subsequent rendering to be written to the framebu... |
self._fb_stack.append((fbo, offset, csize))
try:
fbo.activate()
h, w = fbo.color_buffer.shape[:2]
self.push_viewport((0, 0, w, h))
except Exception:
self._fb_stack.pop()
raise
self._update_transforms() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop_fbo(self):
""" Pop an FBO from the stack. """ |
fbo = self._fb_stack.pop()
fbo[0].deactivate()
self.pop_viewport()
if len(self._fb_stack) > 0:
old_fbo = self._fb_stack[-1]
old_fbo[0].activate()
self._update_transforms()
return fbo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_transforms(self):
"""Update the canvas's TransformSystem to correct for the current canvas size, framebuffer, and viewport. """ |
if len(self._fb_stack) == 0:
fb_size = fb_rect = None
else:
fb, origin, fb_size = self._fb_stack[-1]
fb_rect = origin + fb_size
if len(self._vp_stack) == 0:
viewport = None
else:
viewport = self._vp_stack[-1]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrapping(self):
""" Texture wrapping mode """ |
value = self._wrapping
return value[0] if all([v == value[0] for v in value]) else value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.