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 get_gl_configuration():
"""Read the current gl configuration This function uses constants that are not in the OpenGL ES 2.1 namespace, so only use this on de... |
# XXX eventually maybe we can ask `gl` whether or not we can access these
gl.check_error('pre-config check')
config = dict()
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
fb_param = gl.glGetFramebufferAttachmentParameter
# copied since they aren't in ES:
GL_FRONT_LEFT = 1024
GL_DEPTH = 614... |
<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_clear_color(self, color='black', alpha=None):
"""Set the screen clear color This is a wrapper for gl.glClearColor. Parameters color : str | tuple | insta... |
self.glir.command('FUNC', 'glClearColor', *Color(color, alpha).rgba) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def glir(self):
""" The GLIR queue corresponding to the current canvas """ |
canvas = get_current_canvas()
if canvas is None:
msg = ("If you want to use gloo without vispy.app, " +
"use a gloo.context.FakeCanvas.")
raise RuntimeError('Gloo requires a Canvas to run.\n' + msg)
return canvas.context.glir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clear_namespace():
""" Clear names that are not part of the strict ES API """ |
ok_names = set(default_backend.__dict__)
ok_names.update(['gl2', 'glplus']) # don't remove the module
NS = globals()
for name in list(NS.keys()):
if name.lower().startswith('gl'):
if name not in ok_names:
del NS[name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _copy_gl_functions(source, dest, constants=False):
""" Inject all objects that start with 'gl' from the source into the dest. source and dest can be dicts, m... |
# Get dicts
if isinstance(source, BaseGLProxy):
s = {}
for key in dir(source):
s[key] = getattr(source, key)
source = s
elif not isinstance(source, dict):
source = source.__dict__
if not isinstance(dest, dict):
dest = dest.__dict__
# Copy names
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_error(when='periodic check'):
""" Check this from time to time to detect GL errors. Parameters when : str Shown in the exception to help the developer ... |
errors = []
while True:
err = glGetError()
if err == GL_NO_ERROR or (errors and err == errors[-1]):
break
errors.append(err)
if errors:
msg = ', '.join([repr(ENUM_MAP.get(e, e)) for e in errors])
err = RuntimeError('OpenGL got errors (%s): %s' % (when, m... |
<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_verts_and_connect(self, paths):
""" retrieve vertices and connects from given paths-list """ |
verts = np.vstack(paths)
gaps = np.add.accumulate(np.array([len(x) for x in paths])) - 1
connect = np.ones(gaps[-1], dtype=bool)
connect[gaps[:-1]] = False
return verts, connect |
<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_iso_line(self):
""" compute LineVisual vertices, connects and color-index """ |
level_index = []
connects = []
verts = []
# calculate which level are within data range
# this works for now and the existing examples, but should be tested
# thoroughly also with the data-sanity check in set_data-function
choice = np.nonzero((self.levels > 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 connect(self, callback, ref=False, position='first', before=None, after=None):
"""Connect this emitter to a new callback. Parameters callback : function | tu... |
callbacks = self.callbacks
callback_refs = self.callback_refs
callback = self._normalize_cb(callback)
if callback in callbacks:
return
# deal with the ref
if isinstance(ref, bool):
if ref:
if isinstance(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 disconnect(self, callback=None):
"""Disconnect a callback from this emitter. If no callback is specified, then *all* callbacks are removed. If the callback w... |
if callback is None:
self._callbacks = []
self._callback_refs = []
else:
callback = self._normalize_cb(callback)
if callback in self._callbacks:
idx = self._callbacks.index(callback)
self._callbacks.pop(idx)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block_all(self):
""" Block all emitters in this group. """ |
self.block()
for em in self._emitters.values():
em.block() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unblock_all(self):
""" Unblock all emitters in this group. """ |
self.unblock()
for em in self._emitters.values():
em.unblock() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_glir_message(commands, array_serialization=None):
"""Create a JSON-serializable message of GLIR commands. NumPy arrays are serialized according to the... |
# Default serialization method for NumPy arrays.
if array_serialization is None:
array_serialization = 'binary'
# Extract the buffers.
commands_modified, buffers = _extract_buffers(commands)
# Serialize the modified commands (with buffer pointers) and the buffers.
commands_serialized = ... |
<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_key(self, ref, mode="shared"):
""" Add a key. (ref) Return key name or None on error """ |
if ref not in self.keys:
response = self.request("client_add_key %s -%s" % (ref, mode))
if "success" not in response:
return None
self.keys.append(ref)
return ref |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def launch(self):
"""launch browser and virtual display, first of all to be launched""" |
try:
# init virtual Display
self.vbro = Display()
self.vbro.start()
logger.debug("virtual display launched")
except Exception:
raise exceptions.VBroException()
try:
self.browser = Browser(self.brow_name)
logger.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def css(self, css_path, dom=None):
"""css find function abbreviation""" |
if dom is None:
dom = self.browser
return expect(dom.find_by_css, args=[css_path]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def css1(self, css_path, dom=None):
"""return the first value of self.css""" |
if dom is None:
dom = self.browser
def _css1(path, domm):
"""virtual local func"""
return self.css(path, domm)[0]
return expect(_css1, args=[css_path, dom]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_name(self, name, dom=None):
"""name find function abbreviation""" |
if dom is None:
dom = self.browser
return expect(dom.find_by_name, args=[name]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xpath(self, xpath, dom=None):
"""xpath find function abbreviation""" |
if dom is None:
dom = self.browser
return expect(dom.find_by_xpath, args=[xpath]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_pos(self, html_div):
"""factory method pattern""" |
pos = self.Position(self, html_div)
pos.bind_mov()
self.positions.append(pos)
return pos |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_lcdproc( lcd_host, lcd_port, retry_config, charset=DEFAULT_LCDPROC_CHARSET, lcdd_debug=False):
"""Create and connect to the LCDd server. Args: lcd_host... |
class ServerSpawner(utils.AutoRetryCandidate):
"""Spawn the server, using auto-retry."""
@utils.auto_retry
def connect(self):
return lcdrunner.LcdProcServer(
lcd_host, lcd_port, charset=charset, debug=lcdd_debug)
spawner = ServerSpawner(retry_config=retry_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_patterns(patterns):
"""Create a ScreenPatternList from a given pattern text. Args: pattern_txt (str list):
the patterns Returns: mpdlcd.display_patter... |
field_registry = display_fields.FieldRegistry()
pattern_list = display_pattern.ScreenPatternList(
field_registry=field_registry,
)
for pattern in patterns:
pattern_list.add(pattern.split('\n'))
return pattern_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_config(filename):
"""Read configuration from the given file. Parsing is performed through the configparser library. Returns: dict: a flattened dict of ... |
parser = configparser.RawConfigParser()
if filename and not parser.read(filename):
sys.stderr.write("Unable to open configuration file %s. Use --config='' to disable this warning.\n" % filename)
config = {}
for section, defaults in BASE_CONFIG.items():
# Patterns are handled separatel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_options(config, options, *args):
"""Extract options values from a configparser, optparse pair. Options given on command line take precedence over op... |
extract = {}
for key in args:
if key not in args:
continue
extract[key] = config[key]
option = getattr(options, key, None)
if option is not None:
extract[key] = option
return extract |
<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(self, shape, format=None):
""" Set the render-buffer size and format Parameters shape : tuple of integers New shape in yx order. A render buffer is al... |
if not self._resizeable:
raise RuntimeError("RenderBuffer is not resizeable")
# Check shape
if not (isinstance(shape, tuple) and len(shape) in (2, 3)):
raise ValueError('RenderBuffer shape must be a 2/3 element tuple')
# Check format
if format is... |
<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(self, shape):
""" Resize all attached buffers with the given shape Parameters shape : tuple of two integers New buffer shape (h, w), to be applied to ... |
# Check
if not (isinstance(shape, tuple) and len(shape) == 2):
raise ValueError('RenderBuffer shape must be a 2-element tuple')
# Resize our buffers
for buf in (self.color_buffer, self.depth_buffer, self.stencil_buffer):
if buf is None:
continue
... |
<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, pos=None, color=None, width=None, connect=None):
""" Set the data used to draw this visual. Parameters pos : array color : Color, tuple, or ar... |
if pos is not None:
self._bounds = None
self._pos = pos
self._changed['pos'] = True
if color is not None:
self._color = color
self._changed['color'] = True
if width is not None:
self._width = width
self._chang... |
<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_bounds(self, axis, view):
"""Get the bounds Parameters mode : str Describes the type of boundary requested. Can be "visual", "data", or "mouse". axi... |
# Can and should we calculate bounds?
if (self._bounds is None) and self._pos is not None:
pos = self._pos
self._bounds = [(pos[:, d].min(), pos[:, d].max())
for d in range(pos.shape[1])]
# Return what we can
if self._bounds is None:
... |
<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_k_p_a(font, left, right):
"""This actually calculates the kerning + advance""" |
# http://lists.apple.com/archives/coretext-dev/2010/Dec/msg00020.html
# 1) set up a CTTypesetter
chars = left + right
args = [None, 1, cf.kCFTypeDictionaryKeyCallBacks,
cf.kCFTypeDictionaryValueCallBacks]
attributes = cf.CFDictionaryCreateMutable(*args)
cf.CFDictionaryAddValue(attri... |
<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, xs=None, ys=None, zs=None, colors=None):
'''Update the mesh data.
Parameters
----------
xs : ndarray | None
A 2d array of x coordinates for the vertices of the mesh.
ys : ndarray | None
A 2d array of y coordinates for the vertices of 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 _make_png(data, level=6):
"""Convert numpy array to PNG byte array. Parameters data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint... |
# Eventually we might want to use ext/png.py for this, but this
# routine *should* be faster b/c it's speacialized for our use case
def mkchunk(data, name):
if isinstance(data, np.ndarray):
size = data.nbytes
else:
size = len(data)
chunk = np.empty(size + 12... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_png(filename):
"""Read a PNG file to RGB8 or RGBA8 Unlike imread, this requires no external dependencies. Parameters filename : str File to read. Return... |
x = Reader(filename)
try:
alpha = x.asDirect()[3]['alpha']
if alpha:
y = x.asRGBA8()[2]
n = 4
else:
y = x.asRGB8()[2]
n = 3
y = np.array([yy for yy in y], np.uint8)
finally:
x.file.close()
y.shape = (y.shape[0], y.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 write_png(filename, data):
"""Write a PNG file Unlike imsave, this requires no external dependencies. Parameters filename : str File to save to. data : array... |
data = np.asarray(data)
if not data.ndim == 3 and data.shape[-1] in (3, 4):
raise ValueError('data must be a 3D array with last dimension 3 or 4')
with open(filename, 'wb') as f:
f.write(_make_png(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 imread(filename, format=None):
"""Read image data from disk Requires imageio or PIL. Parameters filename : str Filename to read. format : str | None Format o... |
imageio, PIL = _check_img_lib()
if imageio is not None:
return imageio.imread(filename, format)
elif PIL is not None:
im = PIL.Image.open(filename)
if im.mode == 'P':
im = im.convert()
# Make numpy array
a = np.asarray(im)
if len(a.shape) == 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 imsave(filename, im, format=None):
"""Save image data to disk Requires imageio or PIL. Parameters filename : str Filename to write. im : array Image data. fo... |
# Import imageio or PIL
imageio, PIL = _check_img_lib()
if imageio is not None:
return imageio.imsave(filename, im, format)
elif PIL is not None:
pim = PIL.Image.fromarray(im)
pim.save(filename, format)
else:
raise RuntimeError("imsave requires the imageio or PIL pac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_img_lib():
"""Utility to search for imageio or PIL""" |
# Import imageio or PIL
imageio = PIL = None
try:
import imageio
except ImportError:
try:
import PIL.Image
except ImportError:
pass
return imageio, PIL |
<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_builtin_slots():
'''
Helper function to load builtin slots from the data location
'''
builtin_slots = {}
for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)):
o = line.strip().split('\t')
builtin_slots[index] = {'name' : o[0],
'descript... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timer(logger=None, level=logging.INFO, fmt="function %(function_name)s execution time: %(execution_time).3f", *func_or_func_args, **timer_kwargs):
""" Functi... |
# store Timer kwargs in local variable so the namespace isn't polluted
# by different level args and kwargs
def wrapped_f(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
with Timer(**timer_kwargs) as t:
out = f(*args, **kwargs)
context = {
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mpl_to_vispy(fig):
"""Convert a given matplotlib figure to vispy This function is experimental and subject to change! Requires matplotlib and mplexporter. P... |
renderer = VispyRenderer()
exporter = Exporter(renderer)
with warnings.catch_warnings(record=True): # py3k mpl warning
exporter.run(fig)
renderer._vispy_done()
return renderer.canvas |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show(block=False):
"""Show current figures using vispy Parameters block : bool If True, blocking mode will be used. If False, then non-blocking / interactive... |
if not has_matplotlib():
raise ImportError('Requires matplotlib version >= 1.2')
cs = [_mpl_to_vispy(plt.figure(ii)) for ii in plt.get_fignums()]
if block and len(cs) > 0:
cs[0].app.run()
return cs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mpl_ax_to(self, mplobj, output='vb'):
"""Helper to get the parent axes of a given mplobj""" |
for ax in self._axs.values():
if ax['ax'] is mplobj.axes:
return ax[output]
raise RuntimeError('Parent axes could not be found!') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random(adjacency_mat, directed=False, random_state=None):
""" Place the graph nodes at random places. Parameters adjacency_mat : matrix or sparse The graph a... |
if random_state is None:
random_state = np.random
elif not isinstance(random_state, np.random.RandomState):
random_state = np.random.RandomState(random_state)
if issparse(adjacency_mat):
adjacency_mat = adjacency_mat.tocoo()
# Randomly place nodes, visual coordinate system is ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pos(self):
""" The position of this event in the local coordinate system of the visual. """ |
if self._pos is None:
tr = self.visual.get_transform('canvas', 'visual')
self._pos = tr.map(self.mouse_event.pos)
return self._pos |
<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_event(self):
""" The mouse event immediately prior to this one. This property is None when no mouse buttons are pressed. """ |
if self.mouse_event.last_event is None:
return None
ev = self.copy()
ev.mouse_event = self.mouse_event.last_event
return ev |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def press_event(self):
""" The mouse press event that initiated a mouse drag, if any. """ |
if self.mouse_event.press_event is None:
return None
ev = self.copy()
ev.mouse_event = self.mouse_event.press_event
return ev |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_enum(enum, name=None, valid=None):
""" Get lowercase string representation of enum. """ |
name = name or 'enum'
# Try to convert
res = None
if isinstance(enum, int):
if hasattr(enum, 'name') and enum.name.startswith('GL_'):
res = enum.name[3:].lower()
elif isinstance(enum, string_types):
res = enum.lower()
# Check
if res is None:
raise ValueEr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_texture(tex):
"""Draw a 2D texture to the current viewport Parameters tex : instance of Texture2D The texture to draw. """ |
from .program import Program
program = Program(vert_draw, frag_draw)
program['u_texture'] = tex
program['a_position'] = [[-1., -1.], [-1., 1.], [1., -1.], [1., 1.]]
program['a_texcoord'] = [[0., 1.], [0., 0.], [1., 1.], [1., 0.]]
program.draw('triangle_strip') |
<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_dpi_from(cmd, pattern, func):
"""Match pattern against the output of func, passing the results as floats to func. If anything fails, return None. """ |
try:
out, _ = run_subprocess([cmd])
except (OSError, CalledProcessError):
pass
else:
match = re.search(pattern, out)
if match:
return func(*map(float, match.groups())) |
<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_size(rect, orientation):
"""Calculate a size Parameters rect : rectangle The rectangle. orientation : str Either "bottom" or "top". """ |
(total_halfx, total_halfy) = rect.center
if orientation in ["bottom", "top"]:
(total_major_axis, total_minor_axis) = (total_halfx, total_halfy)
else:
(total_major_axis, total_minor_axis) = (total_halfy, total_halfx)
major_axis = total_major_axis * (1.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 dtype_reduce(dtype, level=0, depth=0):
""" Try to reduce dtype up to a given level when it is possible dtype = [ ('vertex', [('x', 'f4'), ('y', 'f4'), ('z', ... |
dtype = np.dtype(dtype)
fields = dtype.fields
# No fields
if fields is None:
if len(dtype.shape):
count = reduce(mul, dtype.shape)
else:
count = 1
# size = dtype.itemsize / count
if dtype.subdtype:
name = str(dtype.subdtype[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 create_sphere(rows=10, cols=10, depth=10, radius=1.0, offset=True, subdivisions=3, method='latitude'):
"""Create a sphere Parameters rows : int Number of row... |
if method == 'latitude':
return _latitude(rows, cols, radius, offset)
elif method == 'ico':
return _ico(radius, subdivisions)
elif method == 'cube':
return _cube(rows, cols, depth, radius)
else:
raise Exception("Invalid method. Accepts: 'latitude', 'ico', 'cube'") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False):
"""Create a cylinder Parameters rows : int Number of rows. cols : int Number of col... |
verts = np.empty((rows+1, cols, 3), dtype=np.float32)
if isinstance(radius, int):
radius = [radius, radius] # convert to list
# compute vertices
th = np.linspace(2 * np.pi, 0, cols).reshape(1, cols)
# radius as a function of z
r = np.linspace(radius[0], radius[1], num=rows+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 create_arrow(rows, cols, radius=0.1, length=1.0, cone_radius=None, cone_length=None):
"""Create a 3D arrow using a cylinder plus cone Parameters rows : int N... |
# create the cylinder
md_cyl = None
if cone_radius is None:
cone_radius = radius*2.0
if cone_length is None:
con_L = length/3.0
cyl_L = length*2.0/3.0
else:
cyl_L = max(0, length - cone_length)
con_L = min(cone_length, length)
if cyl_L != 0:
md_cy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_grid_mesh(xs, ys, zs):
'''Generate vertices and indices for an implicitly connected mesh.
The intention is that this makes it simple to generate a mesh
from meshgrid data.
Parameters
----------
xs : ndarray
A 2d array of x coordinates for the vertices of the mesh. Must
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _straight_line_vertices(adjacency_mat, node_coords, directed=False):
""" Generate the vertices for straight lines between nodes. If it is a directed graph, i... |
if not issparse(adjacency_mat):
adjacency_mat = np.asarray(adjacency_mat, float)
if (adjacency_mat.ndim != 2 or adjacency_mat.shape[0] !=
adjacency_mat.shape[1]):
raise ValueError("Adjacency matrix should be square.")
arrow_vertices = np.array([])
edges = _get_edges(adja... |
<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_handle():
'''
Get unique FT_Library handle
'''
global __handle__
if not __handle__:
__handle__ = FT_Library()
error = FT_Init_FreeType(byref(__handle__))
if error:
raise RuntimeError(hex(error))
return __handle__ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_camera(cam_type, *args, **kwargs):
""" Factory function for creating new cameras using a string name. Parameters cam_type : str May be one of: * 'panzoo... |
cam_types = {None: BaseCamera}
for camType in (BaseCamera, PanZoomCamera, PerspectiveCamera,
TurntableCamera, FlyCamera, ArcballCamera):
cam_types[camType.__name__[:-6].lower()] = camType
try:
return cam_types[cam_type](*args, **kwargs)
except KeyError:
rais... |
<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_values(self, label, x, y, z):
""" Set the position of the datapoints """ |
# TODO: avoid re-allocating an array every time
self.layers[label]['data'] = np.array([x, y, z]).transpose()
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 surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0, vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0):
""" Computes the parameterization of a paramet... |
vtype = [('position', np.float32, 3),
('texcoord', np.float32, 2),
('normal', np.float32, 3)]
itype = np.uint32
# umin, umax, ucount = 0, 2*np.pi, 64
# vmin, vmax, vcount = 0, 2*np.pi, 64
vcount += 1
ucount += 1
n = vcount * ucount
Un = np.repeat(np.linsp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_wheel)
canvas.events.mouse_move.connect(self.on_mouse_move) |
<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_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 == 1:
dxy = self.canvas_tr.map(dxy)
o = self.canvas_tr.map([0, 0])
t = dxy - o
self.move(t)
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 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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) -... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_zeros(combo) // 2)
if ret < 0:
ret = 0
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intersection(self, another_moc, *args):
""" Intersection between the MOC instance and other MOCs. Parameters another_moc : `~mocpy.moc.MOC` The MOC used for ... |
interval_set = self._interval_set.intersection(another_moc._interval_set)
for moc in args:
interval_set = interval_set.intersection(moc._interval_set)
return self.__class__(interval_set) |
<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_moc, *args):
""" Union between the MOC instance and other MOCs. Parameters another_moc : `~mocpy.moc.MOC` The MOC used for performing the... |
interval_set = self._interval_set.union(another_moc._interval_set)
for moc in args:
interval_set = interval_set.union(moc._interval_set)
return self.__class__(interval_set) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def difference(self, another_moc, *args):
""" Difference between the MOC instance and other MOCs. Parameters another_moc : `~mocpy.moc.MOC` The MOC used that wil... |
interval_set = self._interval_set.difference(another_moc._interval_set)
for moc in args:
interval_set = interval_set.difference(moc._interval_set)
return self.__class__(interval_set) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)] |
<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_cells(cls, cells):
""" Creates a MOC from a numpy array representing the HEALPix cells. Parameters cells : `numpy.ndarray` Must be a numpy structured ar... |
shift = (AbstractMOC.HPY_MAX_NORDER - cells["depth"]) << 1
p1 = cells["ipix"]
p2 = cells["ipix"] + 1
intervals = np.vstack((p1 << shift, p2 << shift)).T
return cls(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_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 diction... |
intervals = np.array([])
for order, pix_l in json_moc.items():
if len(pix_l) == 0:
continue
pix = np.array(pix_l)
p1 = pix
p2 = pix + 1
shift = 2 * (AbstractMOC.HPY_MAX_NORDER - int(order))
itv = np.vstack((p1 << 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 _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 uniq_iv in intervals_uniq_l:
for uniq in range(uniq_iv[0], uniq_iv[1]):
yield uniq |
<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(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 bina... |
table = Table.read(filename)
intervals = np.vstack((table['UNIQ'], table['UNIQ']+1)).T
nuniq_interval_set = IntervalSet(intervals)
interval_set = IntervalSet.from_nuniq_interval_set(nuniq_interval_set)
return cls(interval_set) |
<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_json(uniq):
""" Serializes a MOC to the JSON format. Parameters uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Ret... |
result_json = {}
depth, ipix = utils.uniq2orderipix(uniq)
min_depth = np.min(depth[0])
max_depth = np.max(depth[-1])
for d in range(min_depth, max_depth+1):
pix_index = np.where(depth == d)[0]
if pix_index.size:
# there are pixels belong... |
<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_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... |
def write_cells(serial, a, b, sep=''):
if a == b:
serial += '{0}{1}'.format(a, sep)
else:
serial += '{0}-{1}{2}'.format(a, b, sep)
return serial
res = ''
if uniq.size == 0:
return res
depth, ipixels = ut... |
<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_fits(self, uniq, optional_kw_dict=None):
""" Serializes a MOC to the FITS format. Parameters uniq : `numpy.ndarray` The array of HEALPix cells representi... |
depth = self.max_order
if depth <= 13:
fits_format = '1J'
else:
fits_format = '1K'
tbhdu = fits.BinTableHDU.from_columns(
fits.ColDefs([
fits.Column(name='UNIQ', format=fits_format, array=uniq)
]))
tbhdu.header['PI... |
<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(self, format='fits', optional_kw_dict=None):
""" Serializes the MOC into a specific format. Possible formats are FITS, JSON and STRING Parameters f... |
formats = ('fits', 'json', 'str')
if format not in formats:
raise ValueError('format should be one of %s' % (str(formats)))
uniq_l = []
for uniq in self._uniq_pixels_iterator():
uniq_l.append(uniq)
uniq = np.array(uniq_l)
if format == 'fits':
... |
<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(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 ... |
serialization = self.serialize(format=format, optional_kw_dict=optional_kw_dict)
if format == 'fits':
serialization.writeto(path, overwrite=overwrite)
else:
import json
with open(path, 'w') as h:
h.write(json.dumps(serialization, sort_keys=Tru... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
shift = 2 * (AbstractMOC.HPY_MAX_NORDER - new_order)
ofs = (int(1) << shift) - 1
mask = ~ofs
adda = int(0)
addb = ofs
iv_set = []
for iv in self._interval_set._intervals:
a = (iv[0] + adda) & mask
b = (iv[1] + addb) & mask
if... |
<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_name(self, name):
""" Set Screen Name """ |
self.name = name
self.server.request("screen_set %s name %s" % (self.ref, self.name)) |
<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_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)) |
<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_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)) |
<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_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)) |
<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_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)) |
<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_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))) |
<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_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))) |
<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_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)) |
<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_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)) |
<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_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)) |
<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_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)) |
<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_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] |
<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_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] |
<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_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] |
<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_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] |
<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_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=width, height=height,
direction=direction, speed=speed,
)
self.widgets[ref] = widget
return 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 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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def orbit(self, azim, elev):
""" Orbits the camera around the center position. Parameters azim : float Angle in degrees to rotate horizontally around the center ... |
self.azimuth += azim
self.elevation = np.clip(self.elevation + elev, -90, 90)
self.view_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 _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.glfwWindowHint(glfw.GLFW_ACCUM_RED_BITS, 0)
glfw.glfwWindow... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.wrapperFunction
_m = sys.modules[buffersubdatafunc.__module__]
_m.long = in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.