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_vispy_font_filename(face, bold, italic): """Fetch a remote vispy font"""
name = face + '-' name += 'Regular' if not bold and not italic else '' name += 'Bold' if bold else '' name += 'Italic' if italic else '' name += '.ttf' return load_data_file('fonts/%s' % name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hex_to_rgba(hexs): """Convert hex to rgba, permitting alpha values in hex"""
hexs = np.atleast_1d(np.array(hexs, '|U9')) out = np.ones((len(hexs), 4), np.float32) for hi, h in enumerate(hexs): assert isinstance(h, string_types) off = 1 if h[0] == '#' else 0 assert len(h) in (6+off, 8+off) e = (len(h)-off) // 2 out[hi, :e] = [int(h[i:i+2], 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 _rgb_to_hex(rgbs): """Convert rgb to hex triplet"""
rgbs, n_dim = _check_color_dim(rgbs) return np.array(['#%02x%02x%02x' % tuple((255*rgb[:3]).astype(np.uint8)) for rgb in rgbs], '|U7')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rgb_to_hsv(rgbs): """Convert Nx3 or Nx4 rgb to hsv"""
rgbs, n_dim = _check_color_dim(rgbs) hsvs = list() for rgb in rgbs: rgb = rgb[:3] # don't use alpha here idx = np.argmax(rgb) val = rgb[idx] c = val - np.min(rgb) if c == 0: hue = 0 sat = 0 else: if idx == 0: # R == max ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hsv_to_rgb(hsvs): """Convert Nx3 or Nx4 hsv to rgb"""
hsvs, n_dim = _check_color_dim(hsvs) # In principle, we *might* be able to vectorize this, but might as well # wait until a compelling use case appears rgbs = list() for hsv in hsvs: c = hsv[1] * hsv[2] m = hsv[2] - c hp = hsv[0] / 60 x = c * (1 - abs(hp % 2 - 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 _lab_to_rgb(labs): """Convert Nx3 or Nx4 lab to rgb"""
# adapted from BSD-licensed work in MATLAB by Mark Ruzon # Based on ITU-R Recommendation BT.709 using the D65 labs, n_dim = _check_color_dim(labs) # Convert Lab->XYZ (silly indexing used to preserve dimensionality) y = (labs[:, 0] + 16.) / 116. x = (labs[:, 1] / 500.) + y z = y - (labs[:, ...
<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(self, tags): """Find an adequate value for this field from a dict of tags."""
# Try to find our name value = tags.get(self.name, '') for name in self.alternate_tags: # Iterate of alternates until a non-empty value is found value = value or tags.get(name, '') # If we still have nothing, return our default value = value or self.def...
<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 SDL2"""
func = sdl2.SDL_GL_SetAttribute func(sdl2.SDL_GL_RED_SIZE, c['red_size']) func(sdl2.SDL_GL_GREEN_SIZE, c['green_size']) func(sdl2.SDL_GL_BLUE_SIZE, c['blue_size']) func(sdl2.SDL_GL_ALPHA_SIZE, c['alpha_size']) func(sdl2.SDL_GL_DEPTH_SIZE, c['depth_size']) func(sdl2.SDL_GL_STENCIL_SIZE, c['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 create_response(self, message=None, end_session=False, card_obj=None, reprompt_message=None, is_ssml=None): """ message - text message to be spoken out by th...
response = dict(self.base_response) if message: response['response'] = self.create_speech(message, is_ssml) response['response']['shouldEndSession'] = end_session if card_obj: response['response']['card'] = card_obj if reprompt_message: respon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def intent(self, intent): ''' Decorator to register intent handler''' def _handler(func): self._handlers['IntentRequest'][intent] = func return func return _handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def request(self, request_type): ''' Decorator to register generic request handler ''' def _handler(func): self._handlers[request_type] = func return func return _handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def route_request(self, request_json, metadata=None): ''' Route the request object to the right handler function ''' request = Request(request_json) request.metadata = metadata # add reprompt handler or some such for default? handler_fn = self._handlers[self._default] # Set defa...
<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_set(self, viewbox): """ Friend method of viewbox to register itself. """
self._viewbox = viewbox # Connect viewbox.events.mouse_press.connect(self.viewbox_mouse_event) viewbox.events.mouse_release.connect(self.viewbox_mouse_event) viewbox.events.mouse_move.connect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.connect(self.viewbox_mouse...
<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_unset(self, viewbox): """ Friend method of viewbox to unregister itself. """
self._viewbox = None # Disconnect viewbox.events.mouse_press.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_release.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_move.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.disconnect(self.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 set_range(self, x=None, y=None, z=None, margin=0.05): """ Set the range of the view region for the camera Parameters x : tuple | None X range. y : tuple | No...
# Flag to indicate that this is an initializing (not user-invoked) init = self._xlim is None # Collect given bounds bounds = [None, None, None] if x is not None: bounds[0] = float(x[0]), float(x[1]) if y is not None: bounds[1] = float(y[0]), floa...
<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_state(self): """ Get the current view state of the camera Returns a dict of key-value pairs. The exact keys depend on the camera. Can be passed to set_st...
D = {} for key in self._state_props: D[key] = getattr(self, key) return D
<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_state(self, state=None, **kwargs): """ Set the view state of the camera Should be a dict (or kwargs) as returned by get_state. It can be an incomlete dic...
D = state or {} D.update(kwargs) for key, val in D.items(): if key not in self._state_props: raise KeyError('Not a valid camera state property %r' % key) setattr(self, key, val)
<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(self, camera): """ Link this camera with another camera of the same type Linked camera's keep each-others' state in sync. Parameters camera : instance o...
cam1, cam2 = self, camera # Remove if already linked while cam1 in cam2._linked_cameras: cam2._linked_cameras.remove(cam1) while cam2 in cam1._linked_cameras: cam1._linked_cameras.remove(cam2) # Link both ways cam1._linked_cameras.append(cam2) ...
<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): """ Called when this camera is changes its view. Also called when its associated with a viewbox. """
if self._resetting: return # don't update anything while resetting (are in set_range) if self._viewbox: # Set range if necessary if self._xlim is None: args = self._set_range_args or () self.set_range(*args) # Store defaul...
<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_canvas_change(self, event): """Canvas change event handler Parameters event : instance of Event The event. """
# Connect key events from canvas to camera. # TODO: canvas should keep track of a single node with keyboard focus. if event.old is not None: event.old.events.key_press.disconnect(self.viewbox_key_event) event.old.events.key_release.disconnect(self.viewbox_key_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 _set_scene_transform(self, tr): """ Called by subclasses to configure the viewbox scene transform. """
# todo: check whether transform has changed, connect to # transform.changed event pre_tr = self.pre_transform if pre_tr is None: self._scene_transform = tr else: self._transform_cache.roll() self._scene_transform = self._transform_cache.get([p...
<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 the OpenGL configuration"""
glformat = QGLFormat() glformat.setRedBufferSize(c['red_size']) glformat.setGreenBufferSize(c['green_size']) glformat.setBlueBufferSize(c['blue_size']) glformat.setAlphaBufferSize(c['alpha_size']) if QT5_NEW_API: # Qt5 >= 5.4.0 - below options automatically enabled if nonzero. g...
<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_window_id(self): """ Get the window id of a PySide Widget. Might also work for PyQt4. """
# Get Qt win id winid = self.winId() # On Linux this is it if IS_RPI: nw = (ctypes.c_int * 3)(winid, self.width(), self.height()) return ctypes.pointer(nw) elif IS_LINUX: return int(winid) # Is int on PySide, but sip.voidptr on PyQt ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obj(x): """Six-hump camelback function"""
x1 = x[0] x2 = x[1] f = (4 - 2.1*(x1*x1) + (x1*x1*x1*x1)/3.0)*(x1*x1) + x1*x2 + (-4 + 4*(x2*x2))*(x2*x2) return f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, move): """Change the translation of this transform by the amount given. Parameters move : array-like The values to be added to the current transla...
move = as_vec4(move, default=(0, 0, 0, 0)) self.translate = self.translate + 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 zoom(self, zoom, center=(0, 0, 0), mapped=True): """Update the transform such that its scale factor is changed, but the specified center point is left unchan...
zoom = as_vec4(zoom, default=(1, 1, 1, 1)) center = as_vec4(center, default=(0, 0, 0, 0)) scale = self.scale * zoom if mapped: trans = center - (center - self.translate) * zoom else: trans = self.scale * (1 - zoom) * center + self.translate 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 from_mapping(cls, x0, x1): """ Create an STTransform from the given mapping See `set_mapping` for details. Parameters x0 : array-like Start. x1 : array-like ...
t = cls() t.set_mapping(x0, x1) return 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 set_mapping(self, x0, x1, update=True): """Configure this transform such that it maps points x0 => x1 Parameters x0 : array-like, shape (2, 2) or (2, 3) Star...
# if args are Rect, convert to array first if isinstance(x0, Rect): x0 = x0._transform_in()[:3] if isinstance(x1, Rect): x1 = x1._transform_in()[:3] x0 = np.asarray(x0) x1 = np.asarray(x1) if (x0.ndim != 2 or x0.shape[0] != 2 or x1.ndim !...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(self, pos): """ Translate the matrix The translation is applied *after* the transformations already present in the matrix. Parameters pos : arraynd...
self.matrix = np.dot(self.matrix, transforms.translate(pos[0, :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 scale(self, scale, center=None): """ Scale the matrix about a given origin. The scaling is applied *after* the transformations already present in the matrix....
scale = transforms.scale(as_vec4(scale, default=(1, 1, 1, 1))[0, :3]) if center is not None: center = as_vec4(center)[0, :3] scale = np.dot(np.dot(transforms.translate(-center), scale), transforms.translate(center)) self.matrix = np.dot(self.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 rotate(self, angle, axis): """ Rotate the matrix by some angle about a given axis. The rotation is applied *after* the transformations already present in the...
self.matrix = np.dot(self.matrix, transforms.rotate(angle, axis))
<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_mapping(self, points1, points2): """ Set to a 3D transformation matrix that maps points1 onto points2. Parameters points1 : array-like, shape (4, 3) Four...
# note: need to transpose because util.functions uses opposite # of standard linear algebra order. self.matrix = transforms.affine_map(points1, points2).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 set_ortho(self, l, r, b, t, n, f): """Set ortho transform Parameters l : float Left. r : float Right. b : float Bottom. t : float Top. n : float Near. f : fl...
self.matrix = transforms.ortho(l, r, b, t, n, 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 set_perspective(self, fov, aspect, near, far): """Set the perspective Parameters fov : float Field of view. aspect : float Aspect ratio. near : float Near lo...
self.matrix = transforms.perspective(fov, aspect, near, far)
<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_frustum(self, l, r, b, t, n, f): """Set the frustum Parameters l : float Left. r : float Right. b : float Bottom. t : float Top. n : float Near. f : floa...
self.matrix = transforms.frustum(l, r, b, t, n, 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 set_data(self, data=None, **kwargs): """Set the line data Parameters data : array-like The data. **kwargs : dict Keywoard arguments to pass to MarkerVisual a...
if data is None: pos = None else: if isinstance(data, tuple): pos = np.array(data).T.astype(np.float32) else: pos = np.atleast_1d(data).astype(np.float32) if pos.ndim == 1: pos = pos[:, np.newaxis] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def curve3_bezier(p1, p2, p3): """ Generate the vertices for a quadratic Bezier curve. The vertices returned by this function can be passed to a LineVisual or Ar...
x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 points = [] _curve3_recursive_bezier(points, x1, y1, x2, y2, x3, y3) dx, dy = points[0][0] - x1, points[0][1] - y1 if (dx * dx + dy * dy) > 1e-10: points.insert(0, (x1, y1)) dx, dy = points[-1][0] - x3, points[-1][1] - y3 if (dx * dx + d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def curve4_bezier(p1, p2, p3, p4): """ Generate the vertices for a third order Bezier curve. The vertices returned by this function can be passed to a LineVisual...
x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 x4, y4 = p4 points = [] _curve4_recursive_bezier(points, x1, y1, x2, y2, x3, y3, x4, y4) dx, dy = points[0][0] - x1, points[0][1] - y1 if (dx * dx + dy * dy) > 1e-10: points.insert(0, (x1, y1)) dx, dy = points[-1][0] - x4, points[-1][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 render_to_texture(self, data, texture, offset, size): """Render a SDF to a texture at a given offset and size Parameters data : array Must be 2D with type np...
assert isinstance(texture, Texture2D) set_state(blend=False, depth_test=False) # calculate the negative half (within object) orig_tex = Texture2D(255 - data, format='luminance', wrapping='clamp_to_edge', interpolation='nearest') edf_neg_tex = 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 _render_edf(self, orig_tex): """Render an EDF to a texture"""
# Set up the necessary textures sdf_size = orig_tex.shape[:2] comp_texs = [] for _ in range(2): tex = Texture2D(sdf_size + (4,), format='rgba', interpolation='nearest', wrapping='clamp_to_edge') comp_texs.append(tex) self.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 _add_intent_interactive(self, intent_num=0): ''' Interactively add a new intent to the intent schema object ''' print ("Name of intent number : ", intent_num) slot_type_mappings = load_builtin_slots() intent_name = read_from_user(str) print ("How many...
<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_filename(self, filename): ''' Build an IntentSchema from a file path creates a new intent schema if the file does not exist, throws an error if the file exists but cannot be loaded as a JSON ''' if os.path.exists(filename): with open(filename) as fp:...
<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_request_handler(request): """ Annotate functions with @VoiceHandler so that they can be automatically mapped to request types. Use the 'request_type' ...
user_id = request.access_token() if user_id in twitter_cache.users(): user_cache = twitter_cache.get_user_state(user_id) user_cache["amzn_id"]= request.user_id() base_message = "Welcome to Twitter, {} . How may I help you today ?".format(user_cache["screen_name"]) prin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_tweet_intent_handler(request): """ Use the 'intent' field in the VoiceHandler to map to the respective intent. """
tweet = request.get_slot_value("Tweet") tweet = tweet if tweet else "" if tweet: user_state = twitter_cache.get_user_state(request.access_token()) def action(): return post_tweet(request.access_token(), tweet) message = "I am ready to post the tweet, {} ,\n Please 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 tweet_list_handler(request, tweet_list_builder, msg_prefix=""): """ This is a generic function to handle any intent that reads out a list of tweets"""
# tweet_list_builder is a function that takes a unique identifier and returns a list of things to say tweets = tweet_list_builder(request.access_token()) print (len(tweets), 'tweets found') if tweets: twitter_cache.initialize_user_queue(user_id=request.access_token(), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def focused_on_tweet(request): """ Return index if focused on tweet False if couldn't """
slots = request.get_slot_map() if "Index" in slots and slots["Index"]: index = int(slots['Index']) elif "Ordinal" in slots and slots["Index"]: parse_ordinal = lambda inp : int("".join([l for l in inp if l in string.digits])) index = parse_ordinal(slots['Ordinal']) else: ...
<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_intent_handler(request): """ Takes care of things whenver the user says 'next' """
message = "Sorry, couldn't find anything in your next queue" end_session = True if True: user_queue = twitter_cache.user_queue(request.access_token()) if not user_queue.is_finished(): message = user_queue.read_out_next(MAX_RESPONSE_TWEETS) if not user_queue.is_finis...
<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, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=None, meshdata=None): """Set the mesh data Parameters vertices : array-...
if meshdata is not None: self._meshdata = meshdata else: self._meshdata = MeshData(vertices=vertices, faces=faces, vertex_colors=vertex_colors, face_colors=face_colors) self._bounds = self._meshd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bounds(self, axis, view=None): """Get the bounds of the Visual Parameters axis : int The axis. view : instance of VisualView The view to use. """
if view is None: view = self if axis not in self._vshare.bounds: self._vshare.bounds[axis] = self._compute_bounds(axis, view) return self._vshare.bounds[axis]
<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_hook(self, shader, name): """Return a FunctionChain that Filters may use to modify the program. *shader* should be "frag" or "vert" *name* should be "pr...
assert name in ('pre', 'post') key = (shader, name) if key in self._hooks: return self._hooks[key] hook = StatementList() if shader == 'vert': self.view_program.vert[name] = hook elif shader == 'frag': self.view_program.frag[name] = ho...
<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_subvisual(self, visual): """Add a subvisual Parameters visual : instance of Visual The visual to add. """
visual.transforms = self.transforms visual._prepare_transforms(visual) self._subvisuals.append(visual) visual.events.update.connect(self._subv_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_subvisual(self, visual): """Remove a subvisual Parameters visual : instance of Visual The visual to remove. """
visual.events.update.disconnect(self._subv_update) self._subvisuals.remove(visual) 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 draw(self): """Draw the visual """
if not self.visible: return if self._prepare_draw(view=self) is False: return for v in self._subvisuals: if v.visible: v.draw()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkPos(self): """check all positions"""
soup = BeautifulSoup(self.css1(path['movs-table']).html, 'html.parser') poss = [] for label in soup.find_all("tr"): pos_id = label['id'] # init an empty list # check if it already exist pos_list = [x for x in self.positions if x.id == pos_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 checkStock(self): """check stocks in preference"""
if not self.preferences: logger.debug("no preferences") return None soup = BeautifulSoup( self.xpath(path['stock-table'])[0].html, "html.parser") count = 0 # iterate through product in left panel for product in soup.select("div.tradebox"): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clearPrefs(self): """clear the left panel and preferences"""
self.preferences.clear() tradebox_num = len(self.css('div.tradebox')) for i in range(tradebox_num): self.xpath(path['trade-box'])[0].right_click() self.css1('div.item-trade-contextmenu-list-remove').click() logger.info("cleared preferences")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPrefs(self, prefs=[]): """add preference in self.preferences"""
if len(prefs) == len(self.preferences) == 0: logger.debug("no preferences") return None self.preferences.extend(prefs) self.css1(path['search-btn']).click() count = 0 for pref in self.preferences: self.css1(path['search-pref']).fill(pref) ...
<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_glyph(f, char, glyphs_dict): """Load glyph from font into dict"""
from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING, FT_LOAD_NO_AUTOHINT) flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT face = _load_font(f['face'], f['bold'], f['italic']) face.set_char_size(f['size'] * 64) # get the character of int...
<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_clipper(self, node, clipper): """Assign a clipper that is inherited from a parent node. If *clipper* is None, then remove any clippers for *node*. """
if node in self._clippers: self.detach(self._clippers.pop(node)) if clipper is not None: self.attach(clipper) self._clippers[node] = clipper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cfnumber_to_number(cfnumber): """Convert CFNumber to python int or float."""
numeric_type = cf.CFNumberGetType(cfnumber) cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16, kCFNumberSInt32Type: c_int32, kCFNumberSInt64Type: c_int64, kCFNumberFloat32Type: c_float, kCFNumberFlo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cftype_to_value(cftype): """Convert a CFType into an equivalent python type. The convertible CFTypes are taken from the known_cftypes dictionary, which may b...
if not cftype: return None typeID = cf.CFGetTypeID(cftype) if typeID in known_cftypes: convert_function = known_cftypes[typeID] return convert_function(cftype) else: return cftype
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cfset_to_set(cfset): """Convert CFSet to python set."""
count = cf.CFSetGetCount(cfset) buffer = (c_void_p * count)() cf.CFSetGetValues(cfset, byref(buffer)) return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cfarray_to_list(cfarray): """Convert CFArray to python list."""
count = cf.CFArrayGetCount(cfarray) return [cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i))) for i in range(count)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ctype_for_encoding(self, encoding): """Return ctypes type for an encoded Objective-C type."""
if encoding in self.typecodes: return self.typecodes[encoding] elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes: return POINTER(self.typecodes[encoding[1:]]) elif encoding[0:1] == b'^' and encoding[1:] in [CGImageEncoding, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classmethod(self, encoding): """Function decorator for class methods."""
# Add encodings for hidden self and cmd arguments. encoding = ensure_bytes(encoding) typecodes = parse_type_encoding(encoding) typecodes.insert(1, b'@:') encoding = b''.join(typecodes) def decorator(f): def objc_class_method(objc_cls, objc_cmd, *args): ...
<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_frag_shader(volumes, clipped=False, n_volume_max=5): """ Get the fragment shader code - we use the shader_program object to determine which layers are en...
declarations = "" before_loop = "" in_loop = "" after_loop = "" for index in range(n_volume_max): declarations += "uniform $sampler_type u_volumetex_{0:d};\n".format(index) before_loop += "dummy = $sample(u_volumetex_{0:d}, loc).g;\n".format(index) declarations += "uniform $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 eglGetDisplay(display=EGL_DEFAULT_DISPLAY): """ Connect to the EGL display server. """
res = _lib.eglGetDisplay(display) if not res or res == EGL_NO_DISPLAY: raise RuntimeError('Could not create display') return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eglInitialize(display): """ Initialize EGL and return EGL version tuple. """
majorVersion = (_c_int*1)() minorVersion = (_c_int*1)() res = _lib.eglInitialize(display, majorVersion, minorVersion) if res == EGL_FALSE: raise RuntimeError('Could not initialize') return majorVersion[0], minorVersion[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 eglQueryString(display, name): """ Query string from display """
out = _lib.eglQueryString(display, name) if not out: raise RuntimeError('Could not query %s' % name) return out
<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_faces(self, faces): """Set the faces Parameters faces : ndarray (Nf, 3) array of faces. Each row in the array contains three indices into the vertex arra...
self._faces = faces self._edges = None self._edges_indexed_by_faces = None self._vertex_faces = None self._vertices_indexed_by_faces = None self.reset_normals() self._vertex_colors_indexed_by_faces = None self._face_colors_indexed_by_faces = 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_vertices(self, indexed=None): """Get the vertices Parameters indexed : str | None If Note, return an array (N,3) of the positions of vertices in the mesh...
if indexed is None: if (self._vertices is None and self._vertices_indexed_by_faces is not None): self._compute_unindexed_vertices() return self._vertices elif indexed == 'faces': if (self._vertices_indexed_by_faces is None and ...
<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_bounds(self): """Get the mesh bounds Returns ------- bounds : list A list of tuples of mesh bounds. """
if self._vertices_indexed_by_faces is not None: v = self._vertices_indexed_by_faces elif self._vertices is not None: v = self._vertices else: return None bounds = [(v[:, ax].min(), v[:, ax].max()) for ax in range(v.shape[1])] return bounds
<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_vertices(self, verts=None, indexed=None, reset_normals=True): """Set the mesh vertices Parameters verts : ndarray | None The array (Nv, 3) of vertex coor...
if indexed is None: if verts is not None: self._vertices = verts self._vertices_indexed_by_faces = None elif indexed == 'faces': self._vertices = None if verts is not None: self._vertices_indexed_by_faces = verts el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_vertex_color(self): """Return True if this data set has vertex color information"""
for v in (self._vertex_colors, self._vertex_colors_indexed_by_faces, self._vertex_colors_indexed_by_edges): if v is not None: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_face_color(self): """Return True if this data set has face color information"""
for v in (self._face_colors, self._face_colors_indexed_by_faces, self._face_colors_indexed_by_edges): if v is not None: return True return False
<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_face_normals(self, indexed=None): """Get face normals Parameters indexed : str | None If None, return an array (Nf, 3) of normal vectors for each face. I...
if self._face_normals is None: v = self.get_vertices(indexed='faces') self._face_normals = np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0]) if indexed is None: return self._face_normals elif indexed == 'faces': ...
<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_vertex_normals(self, indexed=None): """Get vertex normals Parameters indexed : str | None If None, return an (N, 3) array of normal vectors with one entr...
if self._vertex_normals is None: faceNorms = self.get_face_normals() vertFaces = self.get_vertex_faces() self._vertex_normals = np.empty(self._vertices.shape, dtype=np.float32) for vindex in xrange(self._vertices.shape[...
<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_vertex_colors(self, indexed=None): """Get vertex colors Parameters indexed : str | None If None, return an array (Nv, 4) of vertex colors. If indexed=='f...
if indexed is None: return self._vertex_colors elif indexed == 'faces': if self._vertex_colors_indexed_by_faces is None: self._vertex_colors_indexed_by_faces = \ self._vertex_colors[self.get_faces()] return self._vertex_colors_inde...
<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_vertex_colors(self, colors, indexed=None): """Set the vertex color array Parameters colors : array Array of colors. Must have shape (Nv, 4) (indexing by ...
colors = _fix_colors(np.asarray(colors)) if indexed is None: if colors.ndim != 2: raise ValueError('colors must be 2D if indexed is None') if colors.shape[0] != self.n_vertices: raise ValueError('incorrect number of colors %s, expected %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_face_colors(self, indexed=None): """Get the face colors Parameters indexed : str | None If indexed is None, return (Nf, 4) array of face colors. If index...
if indexed is None: return self._face_colors elif indexed == 'faces': if (self._face_colors_indexed_by_faces is None and self._face_colors is not None): Nf = self._face_colors.shape[0] self._face_colors_indexed_by_faces = \ ...
<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_face_colors(self, colors, indexed=None): """Set the face color array Parameters colors : array Array of colors. Must have shape (Nf, 4) (indexed by face)...
colors = _fix_colors(colors) if colors.shape[0] != self.n_faces: raise ValueError('incorrect number of colors %s, expected %s' % (colors.shape[0], self.n_faces)) if indexed is None: if colors.ndim != 2: raise ValueError('color...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def n_faces(self): """The number of faces in the mesh"""
if self._faces is not None: return self._faces.shape[0] elif self._vertices_indexed_by_faces is not None: return self._vertices_indexed_by_faces.shape[0]
<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_vertex_faces(self): """ List mapping each vertex index to a list of face indices that use it. """
if self._vertex_faces is None: self._vertex_faces = [[] for i in xrange(len(self.get_vertices()))] for i in xrange(self._faces.shape[0]): face = self._faces[i] for ind in face: self._vertex_faces[ind].append(i) return self._ver...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """Serialize this mesh to a string appropriate for disk storage Returns ------- state : dict The state. """
import pickle if self._faces is not None: names = ['_vertices', '_faces'] else: names = ['_vertices_indexed_by_faces'] if self._vertex_colors is not None: names.append('_vertex_colors') elif self._vertex_colors_indexed_by_faces is not 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 cubehelix(start=0.5, rot=1, gamma=1.0, reverse=True, nlev=256., minSat=1.2, maxSat=1.2, minLight=0., maxLight=1., **kwargs): """ A full implementation of Dav...
# override start and rot if startHue and endHue are set if kwargs is not None: if 'startHue' in kwargs: start = (kwargs.get('startHue') / 360. - 1.) * 3. if 'endHue' in kwargs: rot = kwargs.get('endHue') / 360. - start / 3. - 1. if 'sat' in kwargs: minSa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color_to_hex(color): """Convert matplotlib color code to hex color code"""
if color is None or colorConverter.to_rgba(color)[3] == 0: return 'none' else: rgb = colorConverter.to_rgb(color) return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _many_to_one(input_dict): """Convert a many-to-one mapping to a one-to-one mapping"""
return dict((key, val) for keys, val in input_dict.items() for key in keys)
<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_dasharray(obj): """Get an SVG dash array for the given matplotlib linestyle Parameters obj : matplotlib object The matplotlib line or path object, which ...
if obj.__dict__.get('_dashSeq', None) is not None: return ','.join(map(str, obj._dashSeq)) else: ls = obj.get_linestyle() dasharray = LINESTYLES.get(ls, 'not found') if dasharray == 'not found': warnings.warn("line style '{0}' not understood: " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def SVG_path(path, transform=None, simplify=False): """Construct the vertices and SVG codes for the path Parameters path : matplotlib.Path object transform : mat...
if transform is not None: path = path.transformed(transform) vc_tuples = [(vertices if path_code != Path.CLOSEPOLY else [], PATH_DICT[path_code]) for (vertices, path_code) in path.iter_segments(simplify=simplify)] if not vc_tuples: # emp...
<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_path_style(path, fill=True): """Get the style dictionary for matplotlib path objects"""
style = {} style['alpha'] = path.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['edgecolor'] = color_to_hex(path.get_edgecolor()) if fill: style['facecolor'] = color_to_hex(path.get_facecolor()) else: style['facecolor'] = 'none' style['edgewidth'] = ...
<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_line_style(line): """Get the style dictionary for matplotlib line objects"""
style = {} style['alpha'] = line.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['color'] = color_to_hex(line.get_color()) style['linewidth'] = line.get_linewidth() style['dasharray'] = get_dasharray(line) style['zorder'] = line.get_zorder() return style
<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_marker_style(line): """Get the style dictionary for matplotlib marker objects"""
style = {} style['alpha'] = line.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['facecolor'] = color_to_hex(line.get_markerfacecolor()) style['edgecolor'] = color_to_hex(line.get_markeredgecolor()) style['edgewidth'] = line.get_markeredgewidth() style['marker'] = ...
<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_text_style(text): """Return the text style dict for a text instance"""
style = {} style['alpha'] = text.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['fontsize'] = text.get_size() style['color'] = color_to_hex(text.get_color()) style['halign'] = text.get_horizontalalignment() # left, center, right style['valign'] = text.get_verticala...
<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_axis_properties(axis): """Return the property dictionary for a matplotlib.Axis instance"""
props = {} label1On = axis._major_tick_kw.get('label1On', True) if isinstance(axis, matplotlib.axis.XAxis): if label1On: props['position'] = "bottom" else: props['position'] = "top" elif isinstance(axis, matplotlib.axis.YAxis): if label1On: p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_to_base64(image): """ Convert a matplotlib image to a base64 png representation Parameters image : matplotlib image object The image to be converted. R...
ax = image.axes binary_buffer = io.BytesIO() # image is saved in axes coordinates: we need to temporarily # set the correct limits to get the correct image lim = ax.axis() ax.axis(image.get_extent()) image.write_png(binary_buffer) ax.axis(lim) binary_buffer.seek(0) return base...
<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_interactive(enabled=True, app=None): """Activate the IPython hook for VisPy. If the app is not specified, the default is used. """
if enabled: inputhook_manager.enable_gui('vispy', app) else: inputhook_manager.disable_gui()
<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_buffers(self, font_scale): """Resize buffers only if necessary"""
new_sizes = (font_scale,) + self.size if new_sizes == self._current_sizes: # don't need resize return self._n_rows = int(max(self.size[1] / (self._char_height * font_scale), 1)) self._n_cols = int(max(self.size[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 clear(self): """Clear the console"""
if hasattr(self, '_bytes_012'): self._bytes_012.fill(0) self._bytes_345.fill(0) self._text_lines = [] * self._n_rows self._pending_writes = []
<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, text='', wrap=True): """Write text and scroll Parameters text : str Text to write. ``''`` can be used for a blank line, as a newline is automatic...
# Clear line if not isinstance(text, string_types): raise TypeError('text must be a string') # ensure we only have ASCII chars text = text.encode('utf-8').decode('ascii', errors='replace') self._pending_writes.append((text, wrap)) 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 _do_pending_writes(self): """Do any pending text writes"""
for text, wrap in self._pending_writes: # truncate in case of *really* long messages text = text[-self._n_cols*self._n_rows:] text = text.split('\n') text = [t if len(t) > 0 else '' for t in text] nr, nc = self._n_rows, self._n_cols for pa...