idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
21,600 | def convertNeutral2Xml ( infile , outfile = None ) : 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 = i... | Convert Neutral file format to Dolfin XML . |
21,601 | def screenshot ( filename = "screenshot.png" ) : 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 ) w2i... | Save a screenshot of the current rendering window . |
21,602 | def addFrame ( self ) : fr = "/tmp/vpvid/" + str ( len ( self . frames ) ) + ".png" screenshot ( fr ) self . frames . append ( fr ) | Add frame to current video . |
21,603 | def pause ( self , pause = 0 ) : 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 ) ) | Insert a pause in seconds . |
21,604 | def close ( self ) : 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 " +... | Render the video and write to file . |
21,605 | def update_fields ( u , u_old , v_old , a_old ) : u_vec , u0_vec = u . vector ( ) , u_old . vector ( ) v0_vec , a0_vec = v_old . vector ( ) , a_old . vector ( ) 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 ) v_old . vector ( ) [ : ... | Update fields at the end of each time step . |
21,606 | def local_project ( v , V , u = None ) : 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_r... | Element - wise projection using LocalSolver |
21,607 | def Point ( pos = ( 0 , 0 , 0 ) , r = 12 , c = "red" , alpha = 1 ) : if len ( pos ) == 2 : pos = ( pos [ 0 ] , pos [ 1 ] , 0 ) actor = Points ( [ pos ] , r , c , alpha ) return actor | Create a simple point actor . |
21,608 | def Tube ( points , r = 1 , c = "r" , alpha = 1 , res = 12 ) : ppoints = vtk . vtkPoints ( ) 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 (... | Build a tube along the line defined by a set of points . |
21,609 | def Ribbon ( line1 , line2 , c = "m" , alpha = 1 , res = ( 200 , 5 ) ) : if isinstance ( line1 , Actor ) : line1 = line1 . coordinates ( ) if isinstance ( line2 , Actor ) : line2 = line2 . coordinates ( ) ppoints1 = vtk . vtkPoints ( ) ppoints1 . SetData ( numpy_to_vtk ( line1 , deep = True ) ) lines1 = vtk . vtkCellAr... | Connect two lines to generate the surface inbetween . |
21,610 | def FlatArrow ( line1 , line2 , c = "m" , alpha = 1 , tipSize = 1 , tipWidth = 1 ) : 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 * tipWidt... | Build a 2D arrow in 3D space by joining two close lines . |
21,611 | def Polygon ( pos = ( 0 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , nsides = 6 , r = 1 , c = "coral" , bc = "darkgreen" , lw = 1 , alpha = 1 , followcam = False ) : ps = vtk . vtkRegularPolygonSource ( ) ps . SetNumberOfSides ( nsides ) ps . SetRadius ( r ) ps . SetNormal ( - np . array ( normal ) ) ps . Update ( ) tf = vtk .... | Build a 2D polygon of nsides of radius r oriented as normal . |
21,612 | def Rectangle ( p1 = ( 0 , 0 , 0 ) , p2 = ( 2 , 1 , 0 ) , c = "k" , bc = "dg" , lw = 1 , alpha = 1 , texture = None ) : 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... | Build a rectangle in the xy plane identified by two corner points . |
21,613 | 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 , ) : ps = vtk . vtkDiskSource ( ) ps . SetInnerRadius ( r1 ) ps . SetOuterRadius ( r2 ) ps . SetRadialResolution ( res ) if not resphi : resphi = 6 * res ps . Set... | Build a 2D disc of internal radius r1 and outer radius r2 oriented perpendicular to normal . |Disk| |
21,614 | def Sphere ( pos = ( 0 , 0 , 0 ) , r = 1 , c = "r" , alpha = 1 , res = 24 ) : 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 (... | Build a sphere at position pos of radius r . |Sphere| |
21,615 | def Earth ( pos = ( 0 , 0 , 0 ) , r = 1 , lw = 1 ) : 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" )... | Build a textured actor representing the Earth . |
21,616 | 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 , ) : ps = vtk . vtkPlaneSource ( ) ps . SetResolution ( resx , resy ) ps . Update ( ) poly0 = ps . GetOutput ( ) t0 = vtk . vtkTransform ( ) t0 . Scale ( sx , sy , 1 ) tf0... | Return a grid plane . |
21,617 | def Plane ( pos = ( 0 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , sx = 1 , sy = None , c = "g" , bc = "darkgreen" , alpha = 1 , texture = None ) : if sy is None : sy = sx ps = vtk . vtkPlaneSource ( ) ps . SetResolution ( 1 , 1 ) tri = vtk . vtkTriangleFilter ( ) tri . SetInputConnection ( ps . GetOutputPort ( ) ) tri . Updat... | Draw a plane of size sx and sy oriented perpendicular to vector normal and so that it passes through point pos . |
21,618 | def Box ( pos = ( 0 , 0 , 0 ) , length = 1 , width = 2 , height = 3 , normal = ( 0 , 0 , 1 ) , c = "g" , alpha = 1 , texture = None ) : src = vtk . vtkCubeSource ( ) src . SetXLength ( length ) src . SetYLength ( width ) src . SetZLength ( height ) src . Update ( ) poly = src . GetOutput ( ) axis = np . array ( normal ... | Build a box of dimensions x = length y = width and z = height oriented along vector normal . |
21,619 | def Cube ( pos = ( 0 , 0 , 0 ) , side = 1 , normal = ( 0 , 0 , 1 ) , c = "g" , alpha = 1 , texture = None ) : return Box ( pos , side , side , side , normal , c , alpha , texture ) | Build a cube of size side oriented along vector normal . |
21,620 | def Spring ( startPoint = ( 0 , 0 , 0 ) , endPoint = ( 1 , 0 , 0 ) , coils = 20 , r = 0.1 , r2 = None , thickness = None , c = "grey" , alpha = 1 , ) : 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 , len... | Build a spring of specified nr of coils between startPoint and endPoint . |
21,621 | def Cylinder ( pos = ( 0 , 0 , 0 ) , r = 1 , height = 1 , axis = ( 0 , 0 , 1 ) , c = "teal" , alpha = 1 , res = 24 ) : if utils . isSequence ( pos [ 0 ] ) : 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 .... | Build a cylinder of specified height and radius r centered at pos . |
21,622 | def Cone ( pos = ( 0 , 0 , 0 ) , r = 1 , height = 3 , axis = ( 0 , 0 , 1 ) , c = "dg" , alpha = 1 , res = 48 ) : con = vtk . vtkConeSource ( ) con . SetResolution ( res ) con . SetRadius ( r ) con . SetHeight ( height ) con . SetDirection ( axis ) con . Update ( ) actor = Actor ( con . GetOutput ( ) , c , alpha ) actor... | Build a cone of specified radius r and height centered at pos . |Cone| |
21,623 | def Pyramid ( pos = ( 0 , 0 , 0 ) , s = 1 , height = 1 , axis = ( 0 , 0 , 1 ) , c = "dg" , alpha = 1 ) : return Cone ( pos , s , height , axis , c , alpha , 4 ) | Build a pyramid of specified base size s and height centered at pos . |
21,624 | def Torus ( pos = ( 0 , 0 , 0 ) , r = 1 , thickness = 0.1 , axis = ( 0 , 0 , 1 ) , c = "khaki" , alpha = 1 , res = 30 ) : rs = vtk . vtkParametricTorus ( ) rs . SetRingRadius ( r ) rs . SetCrossSectionRadius ( thickness ) pfs = vtk . vtkParametricFunctionSource ( ) pfs . SetParametricFunction ( rs ) pfs . SetUResolutio... | Build a torus of specified outer radius r internal radius thickness centered at pos . |
21,625 | def getColorName ( c ) : c = np . array ( getColor ( c ) ) 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 | Find the name of a color . |
21,626 | def makePalette ( color1 , color2 , N , hsv = True ) : 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 . ar... | Generate N colors starting from color1 to color2 by linear interpolation HSV in or RGB spaces . |
21,627 | def kelvin2rgb ( temperature ) : if temperature < 1000 : temperature = 1000 elif temperature > 40000 : temperature = 40000 tmp_internal = temperature / 100.0 if tmp_internal <= 66 : red = 255 else : tmp_red = 329.698727446 * np . power ( tmp_internal - 60 , - 0.1332047592 ) if tmp_red < 0 : red = 0 elif tmp_red > 255 :... | Converts from Kelvin temperature to an RGB color . |
21,628 | def geometry ( obj ) : gf = vtk . vtkGeometryFilter ( ) gf . SetInputData ( obj ) gf . Update ( ) return gf . GetOutput ( ) | Apply vtkGeometryFilter . |
21,629 | def spline ( points , smooth = 0.5 , degree = 2 , s = 2 , c = "b" , alpha = 1.0 , nodes = False , res = 20 ) : from scipy . interpolate import splprep , splev Nout = len ( points ) * res points = np . array ( points ) minx , miny , minz = np . min ( points , axis = 0 ) maxx , maxy , maxz = np . max ( points , axis = 0 ... | Return an Actor for a spline so that it does not necessarly pass exactly throught all points . |
21,630 | def histogram ( values , bins = 10 , vrange = None , title = "" , c = "g" , corner = 1 , lines = True ) : 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 ... | Build a 2D histogram from a list of values in n bins . |
21,631 | def delaunay2D ( plist , mode = 'xy' , tol = None ) : 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 . SetProj... | Create a mesh from points in the XY plane . If mode = fit then the filter computes a best fitting plane and projects the points onto it . |
21,632 | def delaunay3D ( dataset , alpha = 0 , tol = None , boundary = True ) : deln = vtk . vtkDelaunay3D ( ) deln . SetInputData ( dataset ) deln . SetAlpha ( alpha ) if tol : deln . SetTolerance ( tol ) deln . SetBoundingTriangulation ( boundary ) deln . Update ( ) return deln . GetOutput ( ) | Create 3D Delaunay triangulation of input points . |
21,633 | def normalLines ( actor , ratio = 1 , c = ( 0.6 , 0.6 , 0.6 ) , alpha = 0.8 ) : maskPts = vtk . vtkMaskPoints ( ) maskPts . SetOnRatio ( ratio ) maskPts . RandomModeOff ( ) actor = actor . computeNormals ( ) src = actor . polydata ( ) maskPts . SetInputData ( src ) arrow = vtk . vtkLineSource ( ) arrow . SetPoint1 ( 0 ... | Build an vtkActor made of the normals at vertices shown as lines . |
21,634 | def extractLargestRegion ( actor ) : 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 (... | Keep only the largest connected part of a mesh and discard all the smaller pieces . |
21,635 | def alignLandmarks ( source , target , rigid = False ) : 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... | Find best matching of source points towards target in the mean least square sense in one single step . |
21,636 | def alignICP ( source , target , iters = 100 , rigid = False ) : if isinstance ( source , Actor ) : source = source . polydata ( ) if isinstance ( target , Actor ) : target = target . polydata ( ) icp = vtk . vtkIterativeClosestPointTransform ( ) icp . SetSource ( source ) icp . SetTarget ( target ) icp . SetMaximumNum... | Return a copy of source actor which is aligned to target actor through the Iterative Closest Point algorithm . |
21,637 | def alignProcrustes ( sources , rigid = False ) : 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 . AddInputDa... | Return an Assembly of aligned source actors with the Procrustes algorithm . The output Assembly is normalized in size . |
21,638 | def fitLine ( points , c = "orange" , lw = 1 ) : 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 ] ) xyz_min = points . min ( axis = 0 ) xyz_max = points . max ( axis = 0 ) a = np . linalg . norm ( xyz_min ... | Fits a line through points . |
21,639 | def fitPlane ( points , c = "g" , bc = "darkgreen" ) : 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 ... | Fits a plane to a set of points . |
21,640 | def fitSphere ( coords ) : 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 . l... | Fits a sphere to a set of points . |
21,641 | def booleanOperation ( actor1 , operation , actor2 , c = None , alpha = 1 , wire = False , bc = None , texture = None ) : bf = vtk . vtkBooleanOperationPolyDataFilter ( ) poly1 = actor1 . computeNormals ( ) . polydata ( ) poly2 = actor2 . computeNormals ( ) . polydata ( ) if operation . lower ( ) == "plus" or operation... | Volumetric union intersection and subtraction of surfaces . |
21,642 | def surfaceIntersection ( actor1 , actor2 , tol = 1e-06 , lw = 3 ) : 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 ( )... | Intersect 2 surfaces and return a line actor . |
21,643 | def probePoints ( img , pts ) : 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 . InsertNextCell ( len ( pts... | Takes a vtkImageData and probes its scalars at the specified points in space . |
21,644 | def probeLine ( img , p1 , p2 , res = 100 ) : 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... | Takes a vtkImageData and probes its scalars along a line defined by 2 points p1 and p2 . |
21,645 | def probePlane ( img , origin = ( 0 , 0 , 0 ) , normal = ( 1 , 0 , 0 ) ) : plane = vtk . vtkPlane ( ) plane . SetOrigin ( origin ) plane . SetNormal ( normal ) planeCut = vtk . vtkCutter ( ) planeCut . SetInputData ( img ) planeCut . SetCutFunction ( plane ) planeCut . Update ( ) cutActor = Actor ( planeCut . GetOutput... | Takes a vtkImageData and probes its scalars on a plane . |
21,646 | def recoSurface ( points , bins = 256 ) : 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 ) ptsS... | Surface reconstruction from a scattered cloud of points . |
21,647 | def cluster ( points , radius ) : 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 ... | Clustering of points in space . |
21,648 | def removeOutliers ( points , radius ) : 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 enume... | Remove outliers from a cloud of points within the specified radius search . |
21,649 | def thinPlateSpline ( actor , sourcePts , targetPts , userFunctions = ( None , None ) ) : 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:... | Thin Plate Spline transformations describe a nonlinear warp transform defined by a set of source and target landmarks . Any point on the mesh close to a source landmark will be moved to a place close to the corresponding target landmark . The points in between are interpolated smoothly using Bookstein s Thin Plate Spli... |
21,650 | def transformFilter ( actor , transformation ) : 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 . G... | Transform a vtkActor and return a new object . |
21,651 | def splitByConnectivity ( actor , maxdepth = 100 ) : 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 .... | Split a mesh by connectivity and order the pieces by increasing area . |
21,652 | def pointSampler ( actor , distance = None ) : poly = actor . polydata ( True ) pointSampler = vtk . vtkPolyDataPointSampler ( ) if not distance : distance = actor . diagonalSize ( ) / 100.0 pointSampler . SetDistance ( distance ) pointSampler . SetInputData ( poly ) pointSampler . Update ( ) uactor = Actor ( pointSamp... | Algorithm to generate points the specified distance apart . |
21,653 | def geodesic ( actor , start , end ) : 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 (... | Dijkstra algorithm to compute the graph geodesic . Takes as input a polygonal mesh and performs a single source shortest path calculation . |
21,654 | def convexHull ( actor_or_list , alphaConstant = 0 ) : 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 ... | Create a 3D Delaunay triangulation of input points . |
21,655 | def extractSurface ( image , radius = 0.5 ) : fe = vtk . vtkExtractSurface ( ) fe . SetInputData ( image ) fe . SetRadius ( radius ) fe . Update ( ) return Actor ( fe . GetOutput ( ) ) | vtkExtractSurface filter . Input is a vtkImageData . Generate zero - crossing isosurface from truncated signed distance volume . |
21,656 | def projectSphereFilter ( actor ) : poly = actor . polydata ( ) psf = vtk . vtkProjectSphereFilter ( ) psf . SetInputData ( poly ) psf . Update ( ) a = Actor ( psf . GetOutput ( ) ) return a | Project a spherical - like object onto a plane . |
21,657 | def wait ( self , timeout = None ) : try : if timeout : gevent . sleep ( timeout ) else : while True : gevent . sleep ( 1000 ) except ( KeyboardInterrupt , SystemExit , Exception ) : pass | Wait for events . |
21,658 | def discover ( self , seconds = 2 ) : 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 : raise StopBroadcasting ( e ) except StopBroadcasting : return | Discover devices in the environment . |
21,659 | def send ( self , sender , ** named ) : 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 , re... | Send signal from sender to all connected receivers . |
21,660 | def send_robust ( self , sender , ** named ) : responses = [ ] if not self . receivers or self . sender_receivers_cache . get ( sender ) is NO_RECEIVERS : return responses for receiver in self . _live_receivers ( sender ) : try : response = receiver ( signal = self , sender = sender , ** named ) except Exception as err... | Send signal from sender to all connected receivers catching errors . |
21,661 | def _live_receivers ( self , sender ) : receivers = None if self . use_caching and not self . _dead_receivers : receivers = self . sender_receivers_cache . get ( sender ) if receivers is NO_RECEIVERS : return [ ] if receivers is None : with self . lock : self . _clear_dead_receivers ( ) senderkey = _make_id ( sender ) ... | Filter sequence of receivers to get resolved live receivers . |
21,662 | def set_state ( self , state ) : self . basicevent . SetBinaryState ( BinaryState = int ( state ) ) self . _state = int ( state ) | Set the state of this device to on or off . |
21,663 | def broadcast ( self ) : 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" , 'MAN:"ssdp:discover"' , "" , "" ) ) . format ( ** self . __dict__ ) self . server . sendto ... | Send a multicast M - SEARCH request asking for devices to report in . |
21,664 | def retry_with_delay ( f , delay = 60 ) : @ 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 remaining : raise gevent . sleep ... | Retry the wrapped requests . request function in case of ConnectionError . Optionally limit the number of retries or set the delay between retries . |
21,665 | def searchType ( libtype ) : 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 ) | Returns the integer value of the library string type . |
21,666 | def toDatetime ( value , format = None ) : if value and value is not None : if format : value = datetime . strptime ( value , format ) else : if int ( value ) == 0 : value = 86400 value = datetime . fromtimestamp ( int ( value ) ) return value | Returns a datetime object from the specified value . |
21,667 | def toList ( value , itemcast = None , delim = ',' ) : value = value or '' itemcast = itemcast or str return [ itemcast ( item ) for item in value . split ( delim ) if item != '' ] | Returns a list of strings from the specified value . |
21,668 | def downloadSessionImages ( server , filename = None , height = 150 , width = 150 , opacity = 100 , saturation = 100 ) : info = { } for media in server . sessions ( ) : url = None for part in media . iterParts ( ) : if media . thumb : url = media . thumb if part . indexes : url = '/library/parts/%s/indexes/%s/%s' % ( p... | Helper to download a bif image or thumb . url from plex . server . sessions . |
21,669 | def download ( url , token , filename = None , savepath = None , session = None , chunksize = 4024 , unpack = False , mocked = False , showstatus = False ) : from plexapi import log session = session or requests . Session ( ) headers = { 'X-Plex-Token' : token } response = session . get ( url , headers = headers , stre... | Helper to download a thumb videofile or other media item . Returns the local path to the downloaded file . |
21,670 | def tag_helper ( tag , items , locked = True , remove = False ) : if not isinstance ( items , list ) : items = [ items ] data = { } if not remove : for i , item in enumerate ( items ) : tagname = '%s[%s].tag.tag' % ( tag , i ) data [ tagname ] = item if remove : tagname = '%s[].tag.tag-' % tag data [ tagname ] = ',' . ... | Simple tag helper for editing a object . |
21,671 | def choose ( msg , items , attr ) : if len ( items ) == 1 : return items [ 0 ] print ( ) for index , i in enumerate ( items ) : name = attr ( i ) if callable ( attr ) else getattr ( i , attr ) print ( ' %s: %s' % ( index , name ) ) print ( ) while True : try : inp = input ( '%s: ' % msg ) if any ( s in inp for s in ( ... | Command line helper to display a list of choices asking the user to choose one of the options . |
21,672 | def _find_server ( account , servername = None ) : servers = servers = [ s for s in account . resources ( ) if 'server' in s . provides ] if servername is not None : for server in servers : if server . name == servername : return server . connect ( ) raise SystemExit ( 'Unknown server name: %s' % servername ) return ut... | Find and return a PlexServer object . |
21,673 | def backup_watched ( plex , opts ) : data = defaultdict ( lambda : dict ( ) ) for section in _iter_sections ( plex , opts ) : print ( 'Fetching watched status for %s..' % section . title ) skey = section . title . lower ( ) for item in _iter_items ( section ) : if not opts . watchedonly or item . isWatched : ikey = _it... | Backup watched status to the specified filepath . |
21,674 | def restore_watched ( plex , opts ) : with open ( opts . filepath , 'r' ) as handle : source = json . load ( handle ) differences = defaultdict ( lambda : dict ( ) ) for section in _iter_sections ( plex , opts ) : print ( 'Finding differences in %s..' % section . title ) skey = section . title . lower ( ) for item in _... | Restore watched status from the specified filepath . |
21,675 | def _onMessage ( self , ws , message ) : try : data = json . loads ( message ) [ 'NotificationContainer' ] log . debug ( 'Alert: %s %s %s' , * data ) if self . _callback : self . _callback ( data ) except Exception as err : log . error ( 'AlertListener Msg Error: %s' , err ) | Called when websocket message is recieved . |
21,676 | def _cast ( self , value ) : if self . type != 'text' : value = utils . cast ( self . TYPES . get ( self . type ) [ 'cast' ] , value ) return value | Cast the specifief value to the type of this setting . |
21,677 | def _getEnumValues ( self , data ) : enumstr = data . attrib . get ( 'enumValues' ) if not enumstr : return None if ':' in enumstr : return { self . _cast ( k ) : v for k , v in [ kv . split ( ':' ) for kv in enumstr . split ( '|' ) ] } return enumstr . split ( '|' ) | Returns a list of dictionary of valis value for this setting . |
21,678 | def _headers ( self , ** kwargs ) : headers = BASE_HEADERS . copy ( ) if self . _token : headers [ 'X-Plex-Token' ] = self . _token headers . update ( kwargs ) return headers | Returns dict containing base headers for all requests to the server . |
21,679 | def library ( self ) : if not self . _library : try : data = self . query ( Library . key ) self . _library = Library ( self , data ) except BadRequest : data = self . query ( '/library/sections/' ) return Library ( self , data ) return self . _library | Library to browse or search your media . |
21,680 | def settings ( self ) : if not self . _settings : data = self . query ( Settings . key ) self . _settings = Settings ( self , data ) return self . _settings | Returns a list of all server settings . |
21,681 | def downloadDatabases ( self , savepath = None , unpack = False ) : url = self . url ( '/diagnostics/databases' ) filepath = utils . download ( url , self . _token , None , savepath , self . _session , unpack = unpack ) return filepath | Download databases . |
21,682 | def installUpdate ( self ) : part = '/updater/apply' release = self . check_for_update ( force = True , download = True ) if release and release . version != self . version : return self . query ( part , method = self . _session . put ) | Install the newest version of Plex Media Server . |
21,683 | def startAlertListener ( self , callback = None ) : notifier = AlertListener ( self , callback ) notifier . start ( ) return notifier | Creates a websocket connection to the Plex Server to optionally recieve notifications . These often include messages from Plex about media scans as well as updates to currently running Transcode Sessions . |
21,684 | def url ( self , key , includeToken = None ) : if self . _token and ( includeToken or self . _showSecrets ) : delim = '&' if '?' in key else '?' return '%s%s%sX-Plex-Token=%s' % ( self . _baseurl , key , delim , self . _token ) return '%s%s' % ( self . _baseurl , key ) | Build a URL string with proper token argument . Token will be appended to the URL if either includeToken is True or CONFIG . log . show_secrets is true . |
21,685 | def thumbUrl ( self ) : thumb = self . firstAttr ( 'thumb' , 'parentThumb' , 'granparentThumb' ) return self . _server . url ( thumb , includeToken = True ) if thumb else None | Return the first first thumbnail url starting on the most specific thumbnail for that item . |
21,686 | def artUrl ( self ) : art = self . firstAttr ( 'art' , 'grandparentArt' ) return self . _server . url ( art , includeToken = True ) if art else None | Return the first first art url starting on the most specific for that item . |
21,687 | def url ( self , part ) : return self . _server . url ( part , includeToken = True ) if part else None | Returns the full url for something . Typically used for getting a specific image . |
21,688 | def markWatched ( self ) : key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self . ratingKey self . _server . query ( key ) self . reload ( ) | Mark video as watched . |
21,689 | def markUnwatched ( self ) : key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self . ratingKey self . _server . query ( key ) self . reload ( ) | Mark video unwatched . |
21,690 | def _asDict ( self ) : config = defaultdict ( dict ) for section in self . _sections : for name , value in self . _sections [ section ] . items ( ) : if name != '__name__' : config [ section . lower ( ) ] [ name . lower ( ) ] = value return dict ( config ) | Returns all configuration values as a dictionary . |
21,691 | def parse ( server , data , initpath ) : STREAMCLS = { 1 : VideoStream , 2 : AudioStream , 3 : SubtitleStream } stype = cast ( int , data . attrib . get ( 'streamType' ) ) cls = STREAMCLS . get ( stype , MediaPartStream ) return cls ( server , data , initpath ) | Factory method returns a new MediaPartStream from xml data . |
21,692 | def delete ( self ) : url = SyncList . key . format ( clientId = self . clientIdentifier ) url += '/' + str ( self . id ) self . _server . query ( url , self . _server . _session . delete ) | Removes current SyncItem |
21,693 | def _buildItem ( self , elem , cls = None , initpath = None ) : initpath = initpath or self . _initpath if cls is not None : return cls ( self . _server , elem , initpath ) etype = elem . attrib . get ( 'type' , elem . attrib . get ( 'streamType' ) ) ehash = '%s.%s' % ( elem . tag , etype ) if etype else elem . tag ecl... | Factory function to build objects based on registered PLEXOBJECTS . |
21,694 | def fetchItem ( self , ekey , cls = None , ** kwargs ) : if isinstance ( ekey , int ) : ekey = '/library/metadata/%s' % ekey for elem in self . _server . query ( ekey ) : if self . _checkAttrs ( elem , ** kwargs ) : return self . _buildItem ( elem , cls , ekey ) clsname = cls . __name__ if cls else 'None' raise NotFoun... | Load the specified key to find and build the first item with the specified tag and attrs . If no tag or attrs are specified then the first item in the result set is returned . |
21,695 | def firstAttr ( self , * attrs ) : for attr in attrs : value = self . __dict__ . get ( attr ) if value is not None : return value | Return the first attribute in attrs that is not None . |
21,696 | def reload ( self , key = None ) : key = key or self . _details_key or self . key if not key : raise Unsupported ( 'Cannot reload an object not built from a URL.' ) self . _initpath = key data = self . _server . query ( key ) self . _loadData ( data [ 0 ] ) return self | Reload the data for this object from self . key . |
21,697 | def edit ( self , ** kwargs ) : if 'id' not in kwargs : kwargs [ 'id' ] = self . ratingKey if 'type' not in kwargs : kwargs [ 'type' ] = utils . searchType ( self . type ) part = '/library/sections/%s/all?%s' % ( self . librarySectionID , urlencode ( kwargs ) ) self . _server . query ( part , method = self . _server . ... | Edit an object . |
21,698 | def _edit_tags ( self , tag , items , locked = True , remove = False ) : if not isinstance ( items , list ) : items = [ items ] value = getattr ( self , tag + 's' ) existing_cols = [ t . tag for t in value if t and remove is False ] d = tag_helper ( tag , existing_cols + items , locked , remove ) self . edit ( ** d ) s... | Helper to edit and refresh a tags . |
21,699 | def getStreamURL ( self , ** params ) : if self . TYPE not in ( 'movie' , 'episode' , 'track' ) : raise Unsupported ( 'Fetching stream URL for %s is unsupported.' % self . TYPE ) mvb = params . get ( 'maxVideoBitrate' ) vr = params . get ( 'videoResolution' , '' ) params = { 'path' : self . key , 'offset' : params . ge... | Returns a stream url that may be used by external applications such as VLC . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.