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 pointColors(self, scalars, cmap="jet", alpha=1, bands=None, vmin=None, vmax=None): """ Set individual point colors by providing a list of scalar values and a...
poly = self.polydata(False) if isinstance(scalars, str): # if a name is passed scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) n = len(scalars) useAlpha = False if n != poly.GetNumberOfPoints(): colors.printc('~times pointColors Error: nr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPointScalars(self, scalars, name): """ Add point scalars to the actor's polydata assigning it a name. .. hint:: |mesh_coloring| |mesh_coloring.py|_ """
poly = self.polydata(False) if len(scalars) != poly.GetNumberOfPoints(): colors.printc('~times pointScalars Error: Number of scalars != nr. of points', len(scalars), poly.GetNumberOfPoints(), c=1) exit() arr = numpy_to_vtk(np.ascontiguousarray(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 addCellScalars(self, scalars, name): """ Add cell scalars to the actor's polydata assigning it a name. """
poly = self.polydata(False) if isinstance(scalars, str): scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) if len(scalars) != poly.GetNumberOfCells(): colors.printc("~times Number of scalars != nr. of cells", c=1) exit() arr = numpy_to_vt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPointVectors(self, vectors, name): """ Add a point vector field to the actor's polydata assigning it a name. """
poly = self.polydata(False) if len(vectors) != poly.GetNumberOfPoints(): colors.printc('~times addPointVectors Error: Number of vectors != nr. of points', len(vectors), poly.GetNumberOfPoints(), c=1) exit() arr = vtk.vtkDoubleArray() arr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addIDs(self, asfield=False): """ Generate point and cell ids. :param bool asfield: flag to control whether to generate scalar or field data. """
ids = vtk.vtkIdFilter() ids.SetInputData(self.poly) ids.PointIdsOn() ids.CellIdsOn() if asfield: ids.FieldDataOn() else: ids.FieldDataOff() ids.Update() return self.updateMesh(ids.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addCurvatureScalars(self, method=0, lut=None): """ Build an ``Actor`` that contains the color coded surface curvature calculated in three different ways. :pa...
curve = vtk.vtkCurvatures() curve.SetInputData(self.poly) curve.SetCurvatureType(method) curve.Update() self.poly = curve.GetOutput() scls = self.poly.GetPointData().GetScalars().GetRange() print("curvature(): scalar range is", scls) self.mapper.SetInpu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scalars(self, name_or_idx=None, datatype="point"): """ Retrieve point or cell scalars using array name or index number. If no ``name`` is given return the li...
poly = self.polydata(False) if name_or_idx is None: # get mode behaviour ncd = poly.GetCellData().GetNumberOfArrays() npd = poly.GetPointData().GetNumberOfArrays() nfd = poly.GetFieldData().GetNumberOfArrays() arrs = [] for i in range(npd): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subdivide(self, N=1, method=0): """Increase the number of vertices of a surface mesh. :param int N: number of subdivisions. :param int method: Loop(0), Linea...
triangles = vtk.vtkTriangleFilter() triangles.SetInputData(self.polydata()) triangles.Update() originalMesh = triangles.GetOutput() if method == 0: sdf = vtk.vtkLoopSubdivisionFilter() elif method == 1: sdf = vtk.vtkLinearSubdivisionFilter() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decimate(self, fraction=0.5, N=None, boundaries=False, verbose=True): """ Downsample the number of vertices in a mesh. :param float fraction: the desired tar...
poly = self.polydata(True) if N: # N = desired number of points Np = poly.GetNumberOfPoints() fraction = float(N) / Np if fraction >= 1: return self decimate = vtk.vtkDecimatePro() decimate.SetInputData(poly) decimate.SetTarg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addGaussNoise(self, sigma): """ Add gaussian noise. :param float sigma: sigma is expressed in percent of the diagonal size of actor. :Example: .. code-block:...
sz = self.diagonalSize() pts = self.coordinates() n = len(pts) ns = np.random.randn(n, 3) * sigma * sz / 100 vpts = vtk.vtkPoints() vpts.SetNumberOfPoints(n) vpts.SetData(numpy_to_vtk(pts + ns, deep=True)) self.poly.SetPoints(vpts) self.poly.GetPo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smoothLaplacian(self, niter=15, relaxfact=0.1, edgeAngle=15, featureAngle=60): """ Adjust mesh point positions using `Laplacian` smoothing. :param int niter:...
poly = self.poly cl = vtk.vtkCleanPolyData() cl.SetInputData(poly) cl.Update() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(cl.GetOutput()) smoothFilter.SetNumberOfIterations(niter) smoothFilter.SetRelaxationFactor(relaxfact) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smoothWSinc(self, niter=15, passBand=0.1, edgeAngle=15, featureAngle=60): """ Adjust mesh point positions using the `Windowed Sinc` function interpolation ke...
poly = self.poly cl = vtk.vtkCleanPolyData() cl.SetInputData(poly) cl.Update() smoothFilter = vtk.vtkWindowedSincPolyDataFilter() smoothFilter.SetInputData(cl.GetOutput()) smoothFilter.SetNumberOfIterations(niter) smoothFilter.SetEdgeAngle(edgeAngle) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fillHoles(self, size=None): """Identifies and fills holes in input mesh. Holes are identified by locating boundary edges, linking them together into loops, a...
fh = vtk.vtkFillHolesFilter() if not size: mb = self.maxBoundSize() size = mb / 10 fh.SetHoleSize(size) fh.SetInputData(self.poly) fh.Update() return self.updateMesh(fh.GetOutput())
<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, filename="mesh.vtk", binary=True): """ Write actor's polydata in its current transformation to file. """
import vtkplotter.vtkio as vtkio return vtkio.write(self, filename, binary)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalAt(self, i): """Return the normal vector at vertex point `i`."""
normals = self.polydata(True).GetPointData().GetNormals() return np.array(normals.GetTuple(i))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normals(self, cells=False): """Retrieve vertex normals as a numpy array. :params bool cells: if `True` return cell normals. """
if cells: vtknormals = self.polydata(True).GetCellData().GetNormals() else: vtknormals = self.polydata(True).GetPointData().GetNormals() return vtk_to_numpy(vtknormals)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def polydata(self, transformed=True): """ Returns the ``vtkPolyData`` of an ``Actor``. .. note:: If ``transformed=True`` returns a copy of polydata that correspo...
if not transformed: if not self.poly: self.poly = self.GetMapper().GetInput() # cache it for speed return self.poly M = self.GetMatrix() if utils.isIdentity(M): if not self.poly: self.poly = self.GetMapper().GetInput() # cach...
<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, u_function): """ Move a mesh by using an external function which prescribes the displacement at any point in space. Useful for manipulating ``dolf...
if self.mesh: self.u = u_function delta = [u_function(p) for p in self.mesh.coordinates()] movedpts = self.mesh.coordinates() + delta self.polydata(False).GetPoints().SetData(numpy_to_vtk(movedpts)) self.poly.GetPoints().Modified() self.u_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setTransform(self, T): """ Transform actor position and orientation wrt to its polygonal mesh, which remains unmodified. """
if isinstance(T, vtk.vtkMatrix4x4): self.SetUserMatrix(T) else: try: self.SetUserTransform(T) except TypeError: colors.printc('~time Error in setTransform(): consider transformPolydata() instead.', c=1) 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 isInside(self, point, tol=0.0001): """ Return True if point is inside a polydata closed surface. """
poly = self.polydata(True) points = vtk.vtkPoints() points.InsertNextPoint(point) pointsPolydata = vtk.vtkPolyData() pointsPolydata.SetPoints(points) sep = vtk.vtkSelectEnclosedPoints() sep.SetTolerance(tol) sep.CheckSurfaceOff() sep.SetInputData(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cellCenters(self): """Get the list of cell centers of the mesh surface. .. hint:: |delaunay2d| |delaunay2d.py|_ """
vcen = vtk.vtkCellCenters() vcen.SetInputData(self.polydata(True)) vcen.Update() return vtk_to_numpy(vcen.GetOutput().GetPoints().GetData())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectedVertices(self, index, returnIds=False): """Find all vertices connected to an input vertex specified by its index. :param bool returnIds: return vert...
mesh = self.polydata() cellIdList = vtk.vtkIdList() mesh.GetPointCells(index, cellIdList) idxs = [] for i in range(cellIdList.GetNumberOfIds()): pointIdList = vtk.vtkIdList() mesh.GetCellPoints(cellIdList.GetId(i), pointIdList) for j in rang...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectedCells(self, index, returnIds=False): """Find all cellls connected to an input vertex specified by its index."""
# Find all cells connected to point index dpoly = self.polydata() cellPointIds = vtk.vtkIdList() dpoly.GetPointCells(index, cellPointIds) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) rids = [] for k in range(cellPointIds.GetNumber...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersectWithLine(self, p0, p1): """Return the list of points intersecting the actor along the segment defined by two points `p0` and `p1`. :Example: .. code...
if not self.line_locator: line_locator = vtk.vtkOBBTree() line_locator.SetDataSet(self.polydata(True)) line_locator.BuildLocator() self.line_locator = line_locator intersectPoints = vtk.vtkPoints() intersection = [0, 0, 0] self.line_locat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getActors(self): """Unpack a list of ``vtkActor`` objects from a ``vtkAssembly``."""
cl = vtk.vtkPropCollection() self.GetActors(cl) self.actors = [] cl.InitTraversal() for i in range(self.GetNumberOfPaths()): act = vtk.vtkActor.SafeDownCast(cl.GetNextProp()) if act.GetPickable(): self.actors.append(act) return sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diagonalSize(self): """Return the maximum diagonal size of the ``Actors`` of the ``Assembly``."""
szs = [a.diagonalSize() for a in self.actors] return np.max(szs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threshold(self, vmin=None, vmax=None, replaceWith=None): """ Binary or continuous volume thresholding. """
th = vtk.vtkImageThreshold() th.SetInputData(self.image) if vmin is not None and vmax is not None: th.ThresholdBetween(vmin, vmax) elif vmin is not None: th.ThresholdByUpper(vmin) elif vmax is not None: th.ThresholdByLower(vmax) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadOFF(filename, c="gold", alpha=1, wire=False, bc=None): """Read OFF file format."""
if not os.path.exists(filename): colors.printc("~noentry Error in loadOFF: Cannot find", filename, c=1) return None f = open(filename, "r") lines = f.readlines() f.close() vertices = [] faces = [] NumberOfVertices = None i = -1 for text in lines: if len(tex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadImageData(filename, spacing=()): """Read and return a ``vtkImageData`` object from file."""
if not os.path.isfile(filename): colors.printc("~noentry File not found:", filename, c=1) return None if ".tif" in filename.lower(): reader = vtk.vtkTIFFReader() elif ".slc" in filename.lower(): reader = vtk.vtkSLCReader() if not reader.CanReadFile(filename): ...
<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(objct, fileoutput, binary=True): """ Write 3D object to file. Possile extensions are: - vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, png, bmp. """
obj = objct if isinstance(obj, Actor): obj = objct.polydata(True) elif isinstance(obj, vtk.vtkActor): obj = objct.GetMapper().GetInput() fr = fileoutput.lower() if ".vtk" in fr: w = vtk.vtkPolyDataWriter() elif ".ply" in fr: w = vtk.vtkPLYWriter() elif ".stl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convertNeutral2Xml(infile, outfile=None): """Convert Neutral file format to Dolfin XML."""
f = open(infile, "r") lines = f.readlines() f.close() ncoords = int(lines[0]) fdolf_coords = [] for i in range(1, ncoords + 1): x, y, z = lines[i].split() fdolf_coords.append([float(x), float(y), float(z)]) ntets = int(lines[ncoords + 1]) idolf_tets = [] for i 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 screenshot(filename="screenshot.png"): """ Save a screenshot of the current rendering window. """
if not settings.plotter_instance.window: colors.printc('~bomb screenshot(): Rendering window is not present, skip.', c=1) return w2if = vtk.vtkWindowToImageFilter() w2if.ShouldRerenderOff() w2if.SetInput(settings.plotter_instance.window) w2if.ReadFrontBufferOff() # read from the ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addFrame(self): """Add frame to current video."""
fr = "/tmp/vpvid/" + str(len(self.frames)) + ".png" screenshot(fr) self.frames.append(fr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(self, pause=0): """Insert a `pause`, in seconds."""
fr = self.frames[-1] n = int(self.fps * pause) for i in range(n): fr2 = "/tmp/vpvid/" + str(len(self.frames)) + ".png" self.frames.append(fr2) os.system("cp -f %s %s" % (fr, fr2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Render the video and write to file."""
if self.duration: _fps = len(self.frames) / float(self.duration) colors.printc("Recalculated video FPS to", round(_fps, 3), c="yellow") else: _fps = int(_fps) self.name = self.name.split('.')[0]+'.mp4' out = os.system("ffmpeg -loglevel panic -y -r " +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_fields(u, u_old, v_old, a_old): """Update fields at the end of each time step."""
# Get vectors (references) u_vec, u0_vec = u.vector(), u_old.vector() v0_vec, a0_vec = v_old.vector(), a_old.vector() # use update functions using vector arguments a_vec = update_a(u_vec, u0_vec, v0_vec, a0_vec, ufl=False) v_vec = update_v(a_vec, u0_vec, v0_vec, a0_vec, ufl=False) # Upd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def local_project(v, V, u=None): """Element-wise projection using LocalSolver"""
dv = TrialFunction(V) v_ = TestFunction(V) a_proj = inner(dv, v_)*dx b_proj = inner(v, v_)*dx solver = LocalSolver(a_proj, b_proj) solver.factorize() if u is None: u = Function(V) solver.solve_local_rhs(u) return u else: solver.solve_local_rhs(u) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Point(pos=(0, 0, 0), r=12, c="red", alpha=1): """Create a simple point actor."""
if len(pos) == 2: pos = (pos[0], pos[1], 0) actor = Points([pos], r, c, alpha) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Tube(points, r=1, c="r", alpha=1, res=12): """Build a tube along the line defined by a set of points. :param r: constant radius or list of radii. :type r: fl...
ppoints = vtk.vtkPoints() # Generate the polyline ppoints.SetData(numpy_to_vtk(points, deep=True)) lines = vtk.vtkCellArray() lines.InsertNextCell(len(points)) for i in range(len(points)): lines.InsertCellPoint(i) polyln = vtk.vtkPolyData() polyln.SetPoints(ppoints) polyln.SetL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Ribbon(line1, line2, c="m", alpha=1, res=(200, 5)): """Connect two lines to generate the surface inbetween. .. hint:: |ribbon| |ribbon.py|_ """
if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() ppoints1 = vtk.vtkPoints() # Generate the polyline1 ppoints1.SetData(numpy_to_vtk(line1, deep=True)) lines1 = vtk.vtkCellArray() lines1.InsertNextCell(len(line1)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FlatArrow(line1, line2, c="m", alpha=1, tipSize=1, tipWidth=1): """Build a 2D arrow in 3D space by joining two close lines. .. hint:: |flatarrow| |flatarrow....
if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() sm1, sm2 = np.array(line1[-1]), np.array(line2[-1]) v = (sm1-sm2)/3*tipWidth p1 = sm1+v p2 = sm2-v pm1 = (sm1+sm2)/2 pm2 = (np.array(line1[-2])+np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Polygon(pos=(0, 0, 0), normal=(0, 0, 1), nsides=6, r=1, c="coral", bc="darkgreen", lw=1, alpha=1, followcam=False): """ Build a 2D polygon of `nsides` of rad...
ps = vtk.vtkRegularPolygonSource() ps.SetNumberOfSides(nsides) ps.SetRadius(r) ps.SetNormal(-np.array(normal)) ps.Update() tf = vtk.vtkTriangleFilter() tf.SetInputConnection(ps.GetOutputPort()) tf.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(tf.GetOutput...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Rectangle(p1=(0, 0, 0), p2=(2, 1, 0), c="k", bc="dg", lw=1, alpha=1, texture=None): """Build a rectangle in the xy plane identified by two corner points."""
p1 = np.array(p1) p2 = np.array(p2) pos = (p1 + p2) / 2 length = abs(p2[0] - p1[0]) height = abs(p2[1] - p1[1]) return Plane(pos, [0, 0, -1], length, height, c, bc, alpha, texture)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Disc( pos=(0, 0, 0), normal=(0, 0, 1), r1=0.5, r2=1, c="coral", bc="darkgreen", lw=1, alpha=1, res=12, resphi=None, ): """ Build a 2D disc of internal radius...
ps = vtk.vtkDiskSource() ps.SetInnerRadius(r1) ps.SetOuterRadius(r2) ps.SetRadialResolution(res) if not resphi: resphi = 6 * res ps.SetCircumferentialResolution(resphi) ps.Update() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arct...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Sphere(pos=(0, 0, 0), r=1, c="r", alpha=1, res=24): """Build a sphere at position `pos` of radius `r`. |Sphere| """
ss = vtk.vtkSphereSource() ss.SetRadius(r) ss.SetThetaResolution(2 * res) ss.SetPhiResolution(res) ss.Update() pd = ss.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) settings.collectable_actors.append(actor) retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Earth(pos=(0, 0, 0), r=1, lw=1): """Build a textured actor representing the Earth. .. hint:: |geodesic| |geodesic.py|_ """
import os tss = vtk.vtkTexturedSphereSource() tss.SetRadius(r) tss.SetThetaResolution(72) tss.SetPhiResolution(36) earthMapper = vtk.vtkPolyDataMapper() earthMapper.SetInputConnection(tss.GetOutputPort()) earthActor = Actor(c="w") earthActor.SetMapper(earthMapper) atext = vtk.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 Grid( pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=1, c="g", bc="darkgreen", lw=1, alpha=1, resx=10, resy=10, ): """Return a grid plane. .. hint:: |brownian2D| ...
ps = vtk.vtkPlaneSource() ps.SetResolution(resx, resy) ps.Update() poly0 = ps.GetOutput() t0 = vtk.vtkTransform() t0.Scale(sx, sy, 1) tf0 = vtk.vtkTransformPolyDataFilter() tf0.SetInputData(poly0) tf0.SetTransform(t0) tf0.Update() poly = tf0.GetOutput() axis = np.array(n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Plane(pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=None, c="g", bc="darkgreen", alpha=1, texture=None): """ Draw a plane of size `sx` and `sy` oriented perpendi...
if sy is None: sy = sx ps = vtk.vtkPlaneSource() ps.SetResolution(1, 1) tri = vtk.vtkTriangleFilter() tri.SetInputConnection(ps.GetOutputPort()) tri.Update() poly = tri.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arcta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Box(pos=(0, 0, 0), length=1, width=2, height=3, normal=(0, 0, 1), c="g", alpha=1, texture=None): """ Build a box of dimensions `x=length, y=width and z=heigh...
src = vtk.vtkCubeSource() src.SetXLength(length) src.SetYLength(width) src.SetZLength(height) src.Update() poly = src.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMult...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Cube(pos=(0, 0, 0), side=1, normal=(0, 0, 1), c="g", alpha=1, texture=None): """Build a cube of size `side` oriented along vector `normal`. .. hint:: |colorc...
return Box(pos, side, side, side, normal, c, alpha, texture)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Spring( startPoint=(0, 0, 0), endPoint=(1, 0, 0), coils=20, r=0.1, r2=None, thickness=None, c="grey", alpha=1, ): """ Build a spring of specified nr of `coil...
diff = endPoint - np.array(startPoint) length = np.linalg.norm(diff) if not length: return None if not r: r = length / 20 trange = np.linspace(0, length, num=50 * coils) om = 6.283 * (coils - 0.5) / length if not r2: r2 = r pts = [] for t in trange: 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 Cylinder(pos=(0, 0, 0), r=1, height=1, axis=(0, 0, 1), c="teal", alpha=1, res=24): """ Build a cylinder of specified height and radius `r`, centered at `pos`...
if utils.isSequence(pos[0]): # assume user is passing pos=[base, top] base = np.array(pos[0]) top = np.array(pos[1]) pos = (base + top) / 2 height = np.linalg.norm(top - base) axis = top - base axis = utils.versor(axis) else: axis = utils.versor(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 Cone(pos=(0, 0, 0), r=1, height=3, axis=(0, 0, 1), c="dg", alpha=1, res=48): """ Build a cone of specified radius `r` and `height`, centered at `pos`. |Cone|...
con = vtk.vtkConeSource() con.SetResolution(res) con.SetRadius(r) con.SetHeight(height) con.SetDirection(axis) con.Update() actor = Actor(con.GetOutput(), c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) v = utils.versor(axis) * height / 2 actor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c="dg", alpha=1): """ Build a pyramid of specified base size `s` and `height`, centered at `pos`. """
return Cone(pos, s, height, axis, c, alpha, 4)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Torus(pos=(0, 0, 0), r=1, thickness=0.1, axis=(0, 0, 1), c="khaki", alpha=1, res=30): """ Build a torus of specified outer radius `r` internal radius `thickn...
rs = vtk.vtkParametricTorus() rs.SetRingRadius(r) rs.SetCrossSectionRadius(thickness) pfs = vtk.vtkParametricFunctionSource() pfs.SetParametricFunction(rs) pfs.SetUResolution(res * 3) pfs.SetVResolution(res) pfs.Update() nax = np.linalg.norm(axis) if nax: axis = np.arra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getColorName(c): """Find the name of a color. .. hint:: |colorpalette| |colorpalette.py|_ """
c = np.array(getColor(c)) # reformat to rgb mdist = 99.0 kclosest = "" for key in colors.keys(): ci = np.array(getColor(key)) d = np.linalg.norm(c - ci) if d < mdist: mdist = d kclosest = str(key) return kclosest
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makePalette(color1, color2, N, hsv=True): """ Generate N colors starting from `color1` to `color2` by linear interpolation HSV in or RGB spaces. :param int N...
if hsv: color1 = rgb2hsv(color1) color2 = rgb2hsv(color2) c1 = np.array(getColor(color1)) c2 = np.array(getColor(color2)) cols = [] for f in np.linspace(0, 1, N - 1, endpoint=True): c = c1 * (1 - f) + c2 * f if hsv: c = np.array(hsv2rgb(c)) cols.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kelvin2rgb(temperature): """ Converts from Kelvin temperature to an RGB color. Algorithm credits: |tannerhelland|_ """
# range check if temperature < 1000: temperature = 1000 elif temperature > 40000: temperature = 40000 tmp_internal = temperature / 100.0 # red if tmp_internal <= 66: red = 255 else: tmp_red = 329.698727446 * np.power(tmp_internal - 60, -0.1332047592) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geometry(obj): """ Apply ``vtkGeometryFilter``. """
gf = vtk.vtkGeometryFilter() gf.SetInputData(obj) gf.Update() return gf.GetOutput()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spline(points, smooth=0.5, degree=2, s=2, c="b", alpha=1.0, nodes=False, res=20): """ Return an ``Actor`` for a spline so that it does not necessarly pass ex...
from scipy.interpolate import splprep, splev Nout = len(points) * res # Number of points on the spline points = np.array(points) minx, miny, minz = np.min(points, axis=0) maxx, maxy, maxz = np.max(points, axis=0) maxb = max(maxx - minx, maxy - miny, maxz - minz) smooth *= maxb / 2 # mus...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def histogram(values, bins=10, vrange=None, title="", c="g", corner=1, lines=True): """ Build a 2D histogram from a list of values in n bins. Use *vrange* to res...
fs, edges = np.histogram(values, bins=bins, range=vrange) pts = [] for i in range(len(fs)): pts.append([(edges[i] + edges[i + 1]) / 2, fs[i]]) return xyplot(pts, title, c, corner, lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delaunay2D(plist, mode='xy', tol=None): """ Create a mesh from points in the XY plane. If `mode='fit'` then the filter computes a best fitting plane and proj...
pd = vtk.vtkPolyData() vpts = vtk.vtkPoints() vpts.SetData(numpy_to_vtk(plist, deep=True)) pd.SetPoints(vpts) delny = vtk.vtkDelaunay2D() delny.SetInputData(pd) if tol: delny.SetTolerance(tol) if mode=='fit': delny.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE) 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 delaunay3D(dataset, alpha=0, tol=None, boundary=True): """Create 3D Delaunay triangulation of input points."""
deln = vtk.vtkDelaunay3D() deln.SetInputData(dataset) deln.SetAlpha(alpha) if tol: deln.SetTolerance(tol) deln.SetBoundingTriangulation(boundary) deln.Update() return deln.GetOutput()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8): """ Build an ``vtkActor`` made of the normals at vertices shown as lines. """
maskPts = vtk.vtkMaskPoints() maskPts.SetOnRatio(ratio) maskPts.RandomModeOff() actor = actor.computeNormals() src = actor.polydata() maskPts.SetInputData(src) arrow = vtk.vtkLineSource() arrow.SetPoint1(0, 0, 0) arrow.SetPoint2(0.75, 0, 0) glyph = vtk.vtkGlyph3D() glyph.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 extractLargestRegion(actor): """Keep only the largest connected part of a mesh and discard all the smaller pieces. .. hint:: |largestregion.py|_ """
conn = vtk.vtkConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.ScalarConnectivityOff() poly = actor.GetMapper().GetInput() conn.SetInputData(poly) conn.Update() epoly = conn.GetOutput() eact = Actor(epoly) pr = vtk.vtkProperty() pr.DeepCopy(actor.GetProperty()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignLandmarks(source, target, rigid=False): """ Find best matching of source points towards target in the mean least square sense, in one single step. """
lmt = vtk.vtkLandmarkTransform() ss = source.polydata().GetPoints() st = target.polydata().GetPoints() if source.N() != target.N(): vc.printc('~times Error in alignLandmarks(): Source and Target with != nr of points!', source.N(), target.N(), c=1) exit() lmt.SetSou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignICP(source, target, iters=100, rigid=False): """ Return a copy of source actor which is aligned to target actor through the `Iterative Closest Point` al...
if isinstance(source, Actor): source = source.polydata() if isinstance(target, Actor): target = target.polydata() icp = vtk.vtkIterativeClosestPointTransform() icp.SetSource(source) icp.SetTarget(target) icp.SetMaximumNumberOfIterations(iters) if rigid: icp.GetLandm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignProcrustes(sources, rigid=False): """ Return an ``Assembly`` of aligned source actors with the `Procrustes` algorithm. The output ``Assembly`` is normal...
group = vtk.vtkMultiBlockDataGroupFilter() for source in sources: if sources[0].N() != source.N(): vc.printc("~times Procrustes error in align():", c=1) vc.printc(" sources have different nr of points", c=1) exit(0) group.AddInputData(source.polydata()) 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 fitLine(points, c="orange", lw=1): """ Fits a line through points. Extra info is stored in ``actor.info['slope']``, ``actor.info['center']``, ``actor.info['v...
data = np.array(points) datamean = data.mean(axis=0) uu, dd, vv = np.linalg.svd(data - datamean) vv = vv[0] / np.linalg.norm(vv[0]) # vv contains the first principal component, i.e. the direction # vector of the best fit line in the least squares sense. xyz_min = points.min(axis=0) xyz_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fitPlane(points, c="g", bc="darkgreen"): """ Fits a plane to a set of points. Extra info is stored in ``actor.info['normal']``, ``actor.info['center']``, ``a...
data = np.array(points) datamean = data.mean(axis=0) res = np.linalg.svd(data - datamean) dd, vv = res[1], res[2] xyz_min = points.min(axis=0) xyz_max = points.max(axis=0) s = np.linalg.norm(xyz_max - xyz_min) n = np.cross(vv[0], vv[1]) pla = vs.Plane(datamean, n, s, s, c, bc) 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 fitSphere(coords): """ Fits a sphere to a set of points. Extra info is stored in ``actor.info['radius']``, ``actor.info['center']``, ``actor.info['residue']`...
coords = np.array(coords) n = len(coords) A = np.zeros((n, 4)) A[:, :-1] = coords * 2 A[:, 3] = 1 f = np.zeros((n, 1)) x = coords[:, 0] y = coords[:, 1] z = coords[:, 2] f[:, 0] = x * x + y * y + z * z C, residue, rank, sv = np.linalg.lstsq(A, f) # solve AC=f if rank < ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def booleanOperation(actor1, operation, actor2, c=None, alpha=1, wire=False, bc=None, texture=None): """Volumetric union, intersection and subtraction of surface...
bf = vtk.vtkBooleanOperationPolyDataFilter() poly1 = actor1.computeNormals().polydata() poly2 = actor2.computeNormals().polydata() if operation.lower() == "plus" or operation.lower() == "+": bf.SetOperationToUnion() elif operation.lower() == "intersect": bf.SetOperationToIntersectio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def surfaceIntersection(actor1, actor2, tol=1e-06, lw=3): """Intersect 2 surfaces and return a line actor. .. hint:: |surfIntersect.py|_ """
bf = vtk.vtkIntersectionPolyDataFilter() poly1 = actor1.GetMapper().GetInput() poly2 = actor2.GetMapper().GetInput() bf.SetInputData(0, poly1) bf.SetInputData(1, poly2) bf.Update() actor = Actor(bf.GetOutput(), "k", 1) actor.GetProperty().SetLineWidth(lw) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def probePoints(img, pts): """ Takes a ``vtkImageData`` and probes its scalars at the specified points in space. """
src = vtk.vtkProgrammableSource() def readPoints(): output = src.GetPolyDataOutput() points = vtk.vtkPoints() for p in pts: x, y, z = p points.InsertNextPoint(x, y, z) output.SetPoints(points) cells = vtk.vtkCellArray() cells.InsertNextCe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def probeLine(img, p1, p2, res=100): """ Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`. .. hint:: |probeLine| |p...
line = vtk.vtkLineSource() line.SetResolution(res) line.SetPoint1(p1) line.SetPoint2(p2) probeFilter = vtk.vtkProbeFilter() probeFilter.SetSourceData(img) probeFilter.SetInputConnection(line.GetOutputPort()) probeFilter.Update() lact = Actor(probeFilter.GetOutput(), c=None) # Scal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def probePlane(img, origin=(0, 0, 0), normal=(1, 0, 0)): """ Takes a ``vtkImageData`` and probes its scalars on a plane. .. hint:: |probePlane| |probePlane.py|_ ...
plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) planeCut = vtk.vtkCutter() planeCut.SetInputData(img) planeCut.SetCutFunction(plane) planeCut.Update() cutActor = Actor(planeCut.GetOutput(), c=None) # ScalarVisibilityOn cutActor.mapper.SetScalarRange(img.GetP...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recoSurface(points, bins=256): """ Surface reconstruction from a scattered cloud of points. :param int bins: number of voxels in x, y and z. .. hint:: |recos...
if isinstance(points, vtk.vtkActor): points = points.coordinates() N = len(points) if N < 50: print("recoSurface: Use at least 50 points.") return None points = np.array(points) ptsSource = vtk.vtkPointSource() ptsSource.SetNumberOfPoints(N) ptsSource.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 cluster(points, radius): """ Clustering of points in space. `radius` is the radius of local search. Individual subsets can be accessed through ``actor.cluste...
if isinstance(points, vtk.vtkActor): poly = points.GetMapper().GetInput() else: src = vtk.vtkPointSource() src.SetNumberOfPoints(len(points)) src.Update() vpts = src.GetOutput().GetPoints() for i, p in enumerate(points): vpts.SetPoint(i, p) po...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeOutliers(points, radius): """ Remove outliers from a cloud of points within the specified `radius` search. .. hint:: |clustering| |clustering.py|_ """
isactor = False if isinstance(points, vtk.vtkActor): isactor = True poly = points.GetMapper().GetInput() else: src = vtk.vtkPointSource() src.SetNumberOfPoints(len(points)) src.Update() vpts = src.GetOutput().GetPoints() for i, p in enumerate(points):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thinPlateSpline(actor, sourcePts, targetPts, userFunctions=(None, None)): """ `Thin Plate Spline` transformations describe a nonlinear warp transform defined...
ns = len(sourcePts) ptsou = vtk.vtkPoints() ptsou.SetNumberOfPoints(ns) for i in range(ns): ptsou.SetPoint(i, sourcePts[i]) nt = len(sourcePts) if ns != nt: vc.printc("~times thinPlateSpline Error: #source != #target points", ns, nt, c=1) exit() pttar = vtk.vtkPoin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transformFilter(actor, transformation): """ Transform a ``vtkActor`` and return a new object. """
tf = vtk.vtkTransformPolyDataFilter() tf.SetTransform(transformation) prop = None if isinstance(actor, vtk.vtkPolyData): tf.SetInputData(actor) else: tf.SetInputData(actor.polydata()) prop = vtk.vtkProperty() prop.DeepCopy(actor.GetProperty()) tf.Update() tf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def splitByConnectivity(actor, maxdepth=100): """ Split a mesh by connectivity and order the pieces by increasing area. :param int maxdepth: only consider this n...
actor.addIDs() pd = actor.polydata() cf = vtk.vtkConnectivityFilter() cf.SetInputData(pd) cf.SetExtractionModeToAllRegions() cf.ColorRegionsOn() cf.Update() cpd = cf.GetOutput() a = Actor(cpd) alist = [] for t in range(max(a.scalars("RegionId")) - 1): if t == maxdep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pointSampler(actor, distance=None): """ Algorithm to generate points the specified distance apart. """
poly = actor.polydata(True) pointSampler = vtk.vtkPolyDataPointSampler() if not distance: distance = actor.diagonalSize() / 100.0 pointSampler.SetDistance(distance) # pointSampler.GenerateVertexPointsOff() # pointSampler.GenerateEdgePointsOff() # pointSampler.GenerateVerti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geodesic(actor, start, end): """ Dijkstra algorithm to compute the graph geodesic. Takes as input a polygonal mesh and performs a single source shortest path...
dijkstra = vtk.vtkDijkstraGraphGeodesicPath() if vu.isSequence(start): cc = actor.coordinates() pa = vs.Points(cc) start = pa.closestPoint(start, returnIds=True) end = pa.closestPoint(end, returnIds=True) dijkstra.SetInputData(pa.polydata()) else: dijkstra....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convexHull(actor_or_list, alphaConstant=0): """ Create a 3D Delaunay triangulation of input points. :param actor_or_list: can be either an ``Actor`` or a lis...
if vu.isSequence(actor_or_list): actor = vs.Points(actor_or_list) else: actor = actor_or_list apoly = actor.clean().polydata() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(apoly) triangleFilter.Update() poly = triangleFilter.GetOutput() delaunay...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractSurface(image, radius=0.5): """ ``vtkExtractSurface`` filter. Input is a ``vtkImageData``. Generate zero-crossing isosurface from truncated signed dis...
fe = vtk.vtkExtractSurface() fe.SetInputData(image) fe.SetRadius(radius) fe.Update() return Actor(fe.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def projectSphereFilter(actor): """ Project a spherical-like object onto a plane. .. hint:: |projectsphere| |projectsphere.py|_ """
poly = actor.polydata() psf = vtk.vtkProjectSphereFilter() psf.SetInputData(poly) psf.Update() a = Actor(psf.GetOutput()) return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self, timeout=None): """ Wait for events. """
try: if timeout: gevent.sleep(timeout) else: while True: gevent.sleep(1000) except (KeyboardInterrupt, SystemExit, Exception): pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover(self, seconds=2): """ Discover devices in the environment. @param seconds: Number of seconds to broadcast requests. @type seconds: int """
log.info("Discovering devices") with gevent.Timeout(seconds, StopBroadcasting) as timeout: try: try: while True: self.upnp.broadcast() gevent.sleep(1) except Exception as 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 send(self, sender, **named): """ Send signal from sender to all connected receivers. If any receiver raises an error, the error propagates back through send,...
responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses for receiver in self._live_receivers(sender): response = receiver(signal=self, sender=sender, **named) responses.append((receiver, response)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_robust(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can b...
responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. for receiver in self._live_rece...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _live_receivers(self, sender): """ Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then retu...
receivers = None if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) # We could end up here with NO_RECEIVERS even if we do check this case in # .send() prior to calling _live_receivers() due to concurrent .send() cal...
<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): """ Set the state of this device to on or off. """
self.basicevent.SetBinaryState(BinaryState=int(state)) self._state = int(state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def broadcast(self): """ Send a multicast M-SEARCH request asking for devices to report in. """
log.debug("Broadcasting M-SEARCH to %s:%s", self.mcast_ip, self.mcast_port) request = '\r\n'.join(("M-SEARCH * HTTP/1.1", "HOST:{mcast_ip}:{mcast_port}", "ST:upnp:rootdevice", "MX:2", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry_with_delay(f, delay=60): """ Retry the wrapped requests.request function in case of ConnectionError. Optionally limit the number of retries or set the ...
@wraps(f) def inner(*args, **kwargs): kwargs['timeout'] = 5 remaining = get_retries() + 1 while remaining: remaining -= 1 try: return f(*args, **kwargs) except (requests.ConnectionError, requests.Timeout): if not remain...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def searchType(libtype): """ Returns the integer value of the library string type. Parameters: libtype (str): LibType to lookup (movie, show, season, episode, a...
libtype = compat.ustr(libtype) if libtype in [compat.ustr(v) for v in SEARCHTYPES.values()]: return libtype if SEARCHTYPES.get(libtype) is not None: return SEARCHTYPES[libtype] raise NotFound('Unknown libtype: %s' % libtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toDatetime(value, format=None): """ Returns a datetime object from the specified value. Parameters: value (str): value to return as a datetime format (str):...
if value and value is not None: if format: value = datetime.strptime(value, format) else: # https://bugs.python.org/issue30684 # And platform support for before epoch seems to be flaky. # TODO check for others errors too. if int(value) == ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toList(value, itemcast=None, delim=','): """ Returns a list of strings from the specified value. Parameters: value (str): comma delimited string to convert ...
value = value or '' itemcast = itemcast or str return [itemcast(item) for item in value.split(delim) if item != '']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def downloadSessionImages(server, filename=None, height=150, width=150, opacity=100, saturation=100): # pragma: no cover """ Helper to download a bif image or th...
info = {} for media in server.sessions(): url = None for part in media.iterParts(): if media.thumb: url = media.thumb if part.indexes: # always use bif images if available. url = '/library/parts/%s/indexes/%s/%s' % (part.id, part.indexes....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(url, token, filename=None, savepath=None, session=None, chunksize=4024, unpack=False, mocked=False, showstatus=False): """ Helper to download a thum...
from plexapi import log # fetch the data to be saved session = session or requests.Session() headers = {'X-Plex-Token': token} response = session.get(url, headers=headers, stream=True) # make sure the savepath directory exists savepath = savepath or os.getcwd() compat.makedirs(savepath...