idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
2,900
def _check_conversion ( key , valid_dict ) : if key not in valid_dict and key not in valid_dict . values ( ) : keys = [ v for v in valid_dict . keys ( ) if isinstance ( v , string_types ) ] raise ValueError ( 'value must be one of %s, not %s' % ( keys , key ) ) return valid_dict [ key ] if key in valid_dict else key
Check for existence of key in dict return value or raise error
2,901
def read_pixels ( viewport = None , alpha = True , out_type = 'unsigned_byte' ) : context = get_current_canvas ( ) . context if context . shared . parser . is_remote ( ) : raise RuntimeError ( 'Cannot use read_pixels() with remote GLIR parser' ) finish ( ) type_dict = { 'unsigned_byte' : gl . GL_UNSIGNED_BYTE , np . uint8 : gl . GL_UNSIGNED_BYTE , 'float' : gl . GL_FLOAT , np . float32 : gl . GL_FLOAT } type_ = _check_conversion ( out_type , type_dict ) if viewport is None : viewport = gl . glGetParameter ( gl . GL_VIEWPORT ) viewport = np . array ( viewport , int ) if viewport . ndim != 1 or viewport . size != 4 : raise ValueError ( 'viewport should be 1D 4-element array-like, not %s' % ( viewport , ) ) x , y , w , h = viewport gl . glPixelStorei ( gl . GL_PACK_ALIGNMENT , 1 ) fmt = gl . GL_RGBA if alpha else gl . GL_RGB im = gl . glReadPixels ( x , y , w , h , fmt , type_ ) gl . glPixelStorei ( gl . GL_PACK_ALIGNMENT , 4 ) if not isinstance ( im , np . ndarray ) : np_dtype = np . uint8 if type_ == gl . GL_UNSIGNED_BYTE else np . float32 im = np . frombuffer ( im , np_dtype ) im . shape = h , w , ( 4 if alpha else 3 ) im = im [ : : - 1 , : , : ] return im
Read pixels from the currently selected buffer . Under most circumstances this function reads from the front buffer . Unlike all other functions in vispy . gloo this function directly executes an OpenGL command .
2,902
def get_gl_configuration ( ) : gl . check_error ( 'pre-config check' ) config = dict ( ) gl . glBindFramebuffer ( gl . GL_FRAMEBUFFER , 0 ) fb_param = gl . glGetFramebufferAttachmentParameter GL_FRONT_LEFT = 1024 GL_DEPTH = 6145 GL_STENCIL = 6146 GL_SRGB = 35904 GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 33296 GL_STEREO = 3123 GL_DOUBLEBUFFER = 3122 sizes = dict ( red = ( GL_FRONT_LEFT , 33298 ) , green = ( GL_FRONT_LEFT , 33299 ) , blue = ( GL_FRONT_LEFT , 33300 ) , alpha = ( GL_FRONT_LEFT , 33301 ) , depth = ( GL_DEPTH , 33302 ) , stencil = ( GL_STENCIL , 33303 ) ) for key , val in sizes . items ( ) : config [ key + '_size' ] = fb_param ( gl . GL_FRAMEBUFFER , val [ 0 ] , val [ 1 ] ) val = fb_param ( gl . GL_FRAMEBUFFER , GL_FRONT_LEFT , GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING ) if val not in ( gl . GL_LINEAR , GL_SRGB ) : raise RuntimeError ( 'unknown value for SRGB: %s' % val ) config [ 'srgb' ] = True if val == GL_SRGB else False config [ 'stereo' ] = True if gl . glGetParameter ( GL_STEREO ) else False config [ 'double_buffer' ] = ( True if gl . glGetParameter ( GL_DOUBLEBUFFER ) else False ) config [ 'samples' ] = gl . glGetParameter ( gl . GL_SAMPLES ) gl . check_error ( 'post-config check' ) return config
Read the current gl configuration
2,903
def set_clear_color ( self , color = 'black' , alpha = None ) : self . glir . command ( 'FUNC' , 'glClearColor' , * Color ( color , alpha ) . rgba )
Set the screen clear color
2,904
def glir ( self ) : canvas = get_current_canvas ( ) if canvas is None : msg = ( "If you want to use gloo without vispy.app, " + "use a gloo.context.FakeCanvas." ) raise RuntimeError ( 'Gloo requires a Canvas to run.\n' + msg ) return canvas . context . glir
The GLIR queue corresponding to the current canvas
2,905
def _clear_namespace ( ) : ok_names = set ( default_backend . __dict__ ) ok_names . update ( [ 'gl2' , 'glplus' ] ) NS = globals ( ) for name in list ( NS . keys ( ) ) : if name . lower ( ) . startswith ( 'gl' ) : if name not in ok_names : del NS [ name ]
Clear names that are not part of the strict ES API
2,906
def _copy_gl_functions ( source , dest , constants = False ) : if isinstance ( source , BaseGLProxy ) : s = { } for key in dir ( source ) : s [ key ] = getattr ( source , key ) source = s elif not isinstance ( source , dict ) : source = source . __dict__ if not isinstance ( dest , dict ) : dest = dest . __dict__ funcnames = [ name for name in source . keys ( ) if name . startswith ( 'gl' ) ] for name in funcnames : dest [ name ] = source [ name ] if constants : constnames = [ name for name in source . keys ( ) if name . startswith ( 'GL_' ) ] for name in constnames : dest [ name ] = source [ name ]
Inject all objects that start with gl from the source into the dest . source and dest can be dicts modules or BaseGLProxy s .
2,907
def check_error ( when = 'periodic check' ) : errors = [ ] while True : err = glGetError ( ) if err == GL_NO_ERROR or ( errors and err == errors [ - 1 ] ) : break errors . append ( err ) if errors : msg = ', ' . join ( [ repr ( ENUM_MAP . get ( e , e ) ) for e in errors ] ) err = RuntimeError ( 'OpenGL got errors (%s): %s' % ( when , msg ) ) err . errors = errors err . err = errors [ - 1 ] raise err
Check this from time to time to detect GL errors .
2,908
def _get_verts_and_connect ( self , paths ) : verts = np . vstack ( paths ) gaps = np . add . accumulate ( np . array ( [ len ( x ) for x in paths ] ) ) - 1 connect = np . ones ( gaps [ - 1 ] , dtype = bool ) connect [ gaps [ : - 1 ] ] = False return verts , connect
retrieve vertices and connects from given paths - list
2,909
def _compute_iso_line ( self ) : level_index = [ ] connects = [ ] verts = [ ] choice = np . nonzero ( ( self . levels > self . _data . min ( ) ) & ( self . _levels < self . _data . max ( ) ) ) levels_to_calc = np . array ( self . levels ) [ choice ] self . _level_min = choice [ 0 ] [ 0 ] for level in levels_to_calc : if _HAS_MPL : nlist = self . _iso . trace ( level , level , 0 ) paths = nlist [ : len ( nlist ) // 2 ] v , c = self . _get_verts_and_connect ( paths ) v += np . array ( [ 0.5 , 0.5 ] ) else : paths = isocurve ( self . _data . astype ( float ) . T , level , extend_to_edge = True , connected = True ) v , c = self . _get_verts_and_connect ( paths ) level_index . append ( v . shape [ 0 ] ) connects . append ( np . hstack ( ( c , [ False ] ) ) ) verts . append ( v ) self . _li = np . hstack ( level_index ) self . _connect = np . hstack ( connects ) self . _verts = np . vstack ( verts )
compute LineVisual vertices connects and color - index
2,910
def connect ( self , callback , ref = False , position = 'first' , before = None , after = None ) : callbacks = self . callbacks callback_refs = self . callback_refs callback = self . _normalize_cb ( callback ) if callback in callbacks : return if isinstance ( ref , bool ) : if ref : if isinstance ( callback , tuple ) : ref = callback [ 1 ] elif hasattr ( callback , '__name__' ) : ref = callback . __name__ else : ref = callback . __class__ . __name__ else : ref = None elif not isinstance ( ref , string_types ) : raise TypeError ( 'ref must be a bool or string' ) if ref is not None and ref in self . _callback_refs : raise ValueError ( 'ref "%s" is not unique' % ref ) if position not in ( 'first' , 'last' ) : raise ValueError ( 'position must be "first" or "last", not %s' % position ) bounds = list ( ) for ri , criteria in enumerate ( ( before , after ) ) : if criteria is None or criteria == [ ] : bounds . append ( len ( callback_refs ) if ri == 0 else 0 ) else : if not isinstance ( criteria , list ) : criteria = [ criteria ] for c in criteria : count = sum ( [ ( c == cn or c == cc ) for cn , cc in zip ( callback_refs , callbacks ) ] ) if count != 1 : raise ValueError ( 'criteria "%s" is in the current ' 'callback list %s times:\n%s\n%s' % ( criteria , count , callback_refs , callbacks ) ) matches = [ ci for ci , ( cn , cc ) in enumerate ( zip ( callback_refs , callbacks ) ) if ( cc in criteria or cn in criteria ) ] bounds . append ( matches [ 0 ] if ri == 0 else ( matches [ - 1 ] + 1 ) ) if bounds [ 0 ] < bounds [ 1 ] : raise RuntimeError ( 'cannot place callback before "%s" ' 'and after "%s" for callbacks: %s' % ( before , after , callback_refs ) ) idx = bounds [ 1 ] if position == 'first' else bounds [ 0 ] self . _callbacks . insert ( idx , callback ) self . _callback_refs . insert ( idx , ref ) return callback
Connect this emitter to a new callback .
2,911
def disconnect ( self , callback = None ) : if callback is None : self . _callbacks = [ ] self . _callback_refs = [ ] else : callback = self . _normalize_cb ( callback ) if callback in self . _callbacks : idx = self . _callbacks . index ( callback ) self . _callbacks . pop ( idx ) self . _callback_refs . pop ( idx )
Disconnect a callback from this emitter .
2,912
def block_all ( self ) : self . block ( ) for em in self . _emitters . values ( ) : em . block ( )
Block all emitters in this group .
2,913
def unblock_all ( self ) : self . unblock ( ) for em in self . _emitters . values ( ) : em . unblock ( )
Unblock all emitters in this group .
2,914
def create_glir_message ( commands , array_serialization = None ) : if array_serialization is None : array_serialization = 'binary' commands_modified , buffers = _extract_buffers ( commands ) commands_serialized = [ _serialize_command ( command_modified ) for command_modified in commands_modified ] buffers_serialized = [ _serialize_buffer ( buffer , array_serialization ) for buffer in buffers ] msg = { 'msg_type' : 'glir_commands' , 'commands' : commands_serialized , 'buffers' : buffers_serialized , } return msg
Create a JSON - serializable message of GLIR commands . NumPy arrays are serialized according to the specified method .
2,915
def add_key ( self , ref , mode = "shared" ) : if ref not in self . keys : response = self . request ( "client_add_key %s -%s" % ( ref , mode ) ) if "success" not in response : return None self . keys . append ( ref ) return ref
Add a key .
2,916
def launch ( self ) : try : self . vbro = Display ( ) self . vbro . start ( ) logger . debug ( "virtual display launched" ) except Exception : raise exceptions . VBroException ( ) try : self . browser = Browser ( self . brow_name ) logger . debug ( f"browser {self.brow_name} launched" ) except Exception : raise exceptions . BrowserException ( self . brow_name , "failed to launch" ) return True
launch browser and virtual display first of all to be launched
2,917
def css ( self , css_path , dom = None ) : if dom is None : dom = self . browser return expect ( dom . find_by_css , args = [ css_path ] )
css find function abbreviation
2,918
def css1 ( self , css_path , dom = None ) : if dom is None : dom = self . browser def _css1 ( path , domm ) : return self . css ( path , domm ) [ 0 ] return expect ( _css1 , args = [ css_path , dom ] )
return the first value of self . css
2,919
def search_name ( self , name , dom = None ) : if dom is None : dom = self . browser return expect ( dom . find_by_name , args = [ name ] )
name find function abbreviation
2,920
def xpath ( self , xpath , dom = None ) : if dom is None : dom = self . browser return expect ( dom . find_by_xpath , args = [ xpath ] )
xpath find function abbreviation
2,921
def new_pos ( self , html_div ) : pos = self . Position ( self , html_div ) pos . bind_mov ( ) self . positions . append ( pos ) return pos
factory method pattern
2,922
def _make_lcdproc ( lcd_host , lcd_port , retry_config , charset = DEFAULT_LCDPROC_CHARSET , lcdd_debug = False ) : class ServerSpawner ( utils . AutoRetryCandidate ) : @ utils . auto_retry def connect ( self ) : return lcdrunner . LcdProcServer ( lcd_host , lcd_port , charset = charset , debug = lcdd_debug ) spawner = ServerSpawner ( retry_config = retry_config , logger = logger ) try : return spawner . connect ( ) except socket . error as e : logger . error ( 'Unable to connect to lcdproc %s:%s : %r' , lcd_host , lcd_port , e ) raise SystemExit ( 1 )
Create and connect to the LCDd server .
2,923
def _make_patterns ( patterns ) : field_registry = display_fields . FieldRegistry ( ) pattern_list = display_pattern . ScreenPatternList ( field_registry = field_registry , ) for pattern in patterns : pattern_list . add ( pattern . split ( '\n' ) ) return pattern_list
Create a ScreenPatternList from a given pattern text .
2,924
def _read_config ( filename ) : parser = configparser . RawConfigParser ( ) if filename and not parser . read ( filename ) : sys . stderr . write ( "Unable to open configuration file %s. Use --config='' to disable this warning.\n" % filename ) config = { } for section , defaults in BASE_CONFIG . items ( ) : if section == 'patterns' : continue for name , descr in defaults . items ( ) : kind , default = descr if section in parser . sections ( ) and name in parser . options ( section ) : if kind == 'int' : value = parser . getint ( section , name ) elif kind == 'float' : value = parser . getfloat ( section , name ) elif kind == 'bool' : value = parser . getboolean ( section , name ) else : value = parser . get ( section , name ) else : value = default config [ name ] = value if 'patterns' in parser . sections ( ) : patterns = [ parser . get ( 'patterns' , opt ) for opt in parser . options ( 'patterns' ) ] else : patterns = DEFAULT_PATTERNS config [ 'patterns' ] = patterns return config
Read configuration from the given file .
2,925
def _extract_options ( config , options , * args ) : extract = { } for key in args : if key not in args : continue extract [ key ] = config [ key ] option = getattr ( options , key , None ) if option is not None : extract [ key ] = option return extract
Extract options values from a configparser optparse pair .
2,926
def resize ( self , shape , format = None ) : if not self . _resizeable : raise RuntimeError ( "RenderBuffer is not resizeable" ) if not ( isinstance ( shape , tuple ) and len ( shape ) in ( 2 , 3 ) ) : raise ValueError ( 'RenderBuffer shape must be a 2/3 element tuple' ) if format is None : format = self . _format elif isinstance ( format , int ) : pass elif isinstance ( format , string_types ) : if format not in ( 'color' , 'depth' , 'stencil' ) : raise ValueError ( 'RenderBuffer format must be "color", "depth"' ' or "stencil", not %r' % format ) else : raise ValueError ( 'Invalid RenderBuffer format: %r' % format ) self . _shape = tuple ( shape [ : 2 ] ) self . _format = format if self . _format is not None : self . _glir . command ( 'SIZE' , self . _id , self . _shape , self . _format )
Set the render - buffer size and format
2,927
def resize ( self , shape ) : if not ( isinstance ( shape , tuple ) and len ( shape ) == 2 ) : raise ValueError ( 'RenderBuffer shape must be a 2-element tuple' ) for buf in ( self . color_buffer , self . depth_buffer , self . stencil_buffer ) : if buf is None : continue shape_ = shape if isinstance ( buf , Texture2D ) : shape_ = shape + ( self . color_buffer . shape [ - 1 ] , ) buf . resize ( shape_ , buf . format )
Resize all attached buffers with the given shape
2,928
def set_data ( self , pos = None , color = None , width = None , connect = None ) : if pos is not None : self . _bounds = None self . _pos = pos self . _changed [ 'pos' ] = True if color is not None : self . _color = color self . _changed [ 'color' ] = True if width is not None : self . _width = width self . _changed [ 'width' ] = True if connect is not None : self . _connect = connect self . _changed [ 'connect' ] = True self . update ( )
Set the data used to draw this visual .
2,929
def _compute_bounds ( self , axis , view ) : if ( self . _bounds is None ) and self . _pos is not None : pos = self . _pos self . _bounds = [ ( pos [ : , d ] . min ( ) , pos [ : , d ] . max ( ) ) for d in range ( pos . shape [ 1 ] ) ] if self . _bounds is None : return else : if axis < len ( self . _bounds ) : return self . _bounds [ axis ] else : return ( 0 , 0 )
Get the bounds
2,930
def _get_k_p_a ( font , left , right ) : chars = left + right args = [ None , 1 , cf . kCFTypeDictionaryKeyCallBacks , cf . kCFTypeDictionaryValueCallBacks ] attributes = cf . CFDictionaryCreateMutable ( * args ) cf . CFDictionaryAddValue ( attributes , kCTFontAttributeName , font ) string = cf . CFAttributedStringCreate ( None , CFSTR ( chars ) , attributes ) typesetter = ct . CTTypesetterCreateWithAttributedString ( string ) cf . CFRelease ( string ) cf . CFRelease ( attributes ) range = CFRange ( 0 , 1 ) line = ct . CTTypesetterCreateLine ( typesetter , range ) offset = ct . CTLineGetOffsetForStringIndex ( line , 1 , None ) cf . CFRelease ( line ) cf . CFRelease ( typesetter ) return offset
This actually calculates the kerning + advance
2,931
def set_data ( self , xs = None , ys = None , zs = None , colors = None ) : if xs is None : xs = self . _xs self . __vertices = None if ys is None : ys = self . _ys self . __vertices = None if zs is None : zs = self . _zs self . __vertices = None if self . __vertices is None : vertices , indices = create_grid_mesh ( xs , ys , zs ) self . _xs = xs self . _ys = ys self . _zs = zs if self . __vertices is None : vertices , indices = create_grid_mesh ( self . _xs , self . _ys , self . _zs ) self . __meshdata . set_vertices ( vertices ) self . __meshdata . set_faces ( indices ) if colors is not None : self . __meshdata . set_vertex_colors ( colors . reshape ( colors . shape [ 0 ] * colors . shape [ 1 ] , colors . shape [ 2 ] ) ) MeshVisual . set_data ( self , meshdata = self . __meshdata )
Update the mesh data .
2,932
def _make_png ( data , level = 6 ) : def mkchunk ( data , name ) : if isinstance ( data , np . ndarray ) : size = data . nbytes else : size = len ( data ) chunk = np . empty ( size + 12 , dtype = np . ubyte ) chunk . data [ 0 : 4 ] = np . array ( size , '>u4' ) . tostring ( ) chunk . data [ 4 : 8 ] = name . encode ( 'ASCII' ) chunk . data [ 8 : 8 + size ] = data chunk . data [ - 4 : ] = np . array ( zlib . crc32 ( chunk [ 4 : - 4 ] ) & 0xffffffff , '>u4' ) . tostring ( ) return chunk if data . dtype != np . ubyte : raise TypeError ( 'data.dtype must be np.ubyte (np.uint8)' ) dim = data . shape [ 2 ] if dim not in ( 3 , 4 ) : raise TypeError ( 'data.shape[2] must be in (3, 4)' ) if dim == 4 : ctyp = 0b0110 else : ctyp = 0b0010 header = b'\x89PNG\x0d\x0a\x1a\x0a' h , w = data . shape [ : 2 ] depth = data . itemsize * 8 ihdr = struct . pack ( '!IIBBBBB' , w , h , depth , ctyp , 0 , 0 , 0 ) c1 = mkchunk ( ihdr , 'IHDR' ) idat = np . empty ( ( h , w * dim + 1 ) , dtype = np . ubyte ) idat [ : , 1 : ] = data . reshape ( h , w * dim ) idat [ : , 0 ] = 0 comp_data = zlib . compress ( idat , level ) c2 = mkchunk ( comp_data , 'IDAT' ) c3 = mkchunk ( np . empty ( ( 0 , ) , dtype = np . ubyte ) , 'IEND' ) lh = len ( header ) png = np . empty ( lh + c1 . nbytes + c2 . nbytes + c3 . nbytes , dtype = np . ubyte ) png . data [ : lh ] = header p = lh for chunk in ( c1 , c2 , c3 ) : png [ p : p + len ( chunk ) ] = chunk p += chunk . nbytes return png
Convert numpy array to PNG byte array .
2,933
def read_png ( filename ) : x = Reader ( filename ) try : alpha = x . asDirect ( ) [ 3 ] [ 'alpha' ] if alpha : y = x . asRGBA8 ( ) [ 2 ] n = 4 else : y = x . asRGB8 ( ) [ 2 ] n = 3 y = np . array ( [ yy for yy in y ] , np . uint8 ) finally : x . file . close ( ) y . shape = ( y . shape [ 0 ] , y . shape [ 1 ] // n , n ) return y
Read a PNG file to RGB8 or RGBA8
2,934
def write_png ( filename , data ) : data = np . asarray ( data ) if not data . ndim == 3 and data . shape [ - 1 ] in ( 3 , 4 ) : raise ValueError ( 'data must be a 3D array with last dimension 3 or 4' ) with open ( filename , 'wb' ) as f : f . write ( _make_png ( data ) )
Write a PNG file
2,935
def imread ( filename , format = None ) : imageio , PIL = _check_img_lib ( ) if imageio is not None : return imageio . imread ( filename , format ) elif PIL is not None : im = PIL . Image . open ( filename ) if im . mode == 'P' : im = im . convert ( ) a = np . asarray ( im ) if len ( a . shape ) == 0 : raise MemoryError ( "Too little memory to convert PIL image to " "array" ) return a else : raise RuntimeError ( "imread requires the imageio or PIL package." )
Read image data from disk
2,936
def imsave ( filename , im , format = None ) : imageio , PIL = _check_img_lib ( ) if imageio is not None : return imageio . imsave ( filename , im , format ) elif PIL is not None : pim = PIL . Image . fromarray ( im ) pim . save ( filename , format ) else : raise RuntimeError ( "imsave requires the imageio or PIL package." )
Save image data to disk
2,937
def _check_img_lib ( ) : imageio = PIL = None try : import imageio except ImportError : try : import PIL . Image except ImportError : pass return imageio , PIL
Utility to search for imageio or PIL
2,938
def load_builtin_slots ( ) : builtin_slots = { } for index , line in enumerate ( open ( BUILTIN_SLOTS_LOCATION ) ) : o = line . strip ( ) . split ( '\t' ) builtin_slots [ index ] = { 'name' : o [ 0 ] , 'description' : o [ 1 ] } return builtin_slots
Helper function to load builtin slots from the data location
2,939
def timer ( logger = None , level = logging . INFO , fmt = "function %(function_name)s execution time: %(execution_time).3f" , * func_or_func_args , ** timer_kwargs ) : def wrapped_f ( f ) : @ functools . wraps ( f ) def wrapped ( * args , ** kwargs ) : with Timer ( ** timer_kwargs ) as t : out = f ( * args , ** kwargs ) context = { 'function_name' : f . __name__ , 'execution_time' : t . elapsed , } if logger : logger . log ( level , fmt % context , extra = context ) else : print ( fmt % context ) return out return wrapped if ( len ( func_or_func_args ) == 1 and isinstance ( func_or_func_args [ 0 ] , collections . Callable ) ) : return wrapped_f ( func_or_func_args [ 0 ] ) else : return wrapped_f
Function decorator displaying the function execution time
2,940
def _mpl_to_vispy ( fig ) : renderer = VispyRenderer ( ) exporter = Exporter ( renderer ) with warnings . catch_warnings ( record = True ) : exporter . run ( fig ) renderer . _vispy_done ( ) return renderer . canvas
Convert a given matplotlib figure to vispy
2,941
def show ( block = False ) : if not has_matplotlib ( ) : raise ImportError ( 'Requires matplotlib version >= 1.2' ) cs = [ _mpl_to_vispy ( plt . figure ( ii ) ) for ii in plt . get_fignums ( ) ] if block and len ( cs ) > 0 : cs [ 0 ] . app . run ( ) return cs
Show current figures using vispy
2,942
def _mpl_ax_to ( self , mplobj , output = 'vb' ) : for ax in self . _axs . values ( ) : if ax [ 'ax' ] is mplobj . axes : return ax [ output ] raise RuntimeError ( 'Parent axes could not be found!' )
Helper to get the parent axes of a given mplobj
2,943
def random ( adjacency_mat , directed = False , random_state = None ) : if random_state is None : random_state = np . random elif not isinstance ( random_state , np . random . RandomState ) : random_state = np . random . RandomState ( random_state ) if issparse ( adjacency_mat ) : adjacency_mat = adjacency_mat . tocoo ( ) num_nodes = adjacency_mat . shape [ 0 ] node_coords = random_state . rand ( num_nodes , 2 ) line_vertices , arrows = _straight_line_vertices ( adjacency_mat , node_coords , directed ) yield node_coords , line_vertices , arrows
Place the graph nodes at random places .
2,944
def pos ( self ) : if self . _pos is None : tr = self . visual . get_transform ( 'canvas' , 'visual' ) self . _pos = tr . map ( self . mouse_event . pos ) return self . _pos
The position of this event in the local coordinate system of the visual .
2,945
def last_event ( self ) : if self . mouse_event . last_event is None : return None ev = self . copy ( ) ev . mouse_event = self . mouse_event . last_event return ev
The mouse event immediately prior to this one . This property is None when no mouse buttons are pressed .
2,946
def press_event ( self ) : if self . mouse_event . press_event is None : return None ev = self . copy ( ) ev . mouse_event = self . mouse_event . press_event return ev
The mouse press event that initiated a mouse drag if any .
2,947
def check_enum ( enum , name = None , valid = None ) : name = name or 'enum' res = None if isinstance ( enum , int ) : if hasattr ( enum , 'name' ) and enum . name . startswith ( 'GL_' ) : res = enum . name [ 3 : ] . lower ( ) elif isinstance ( enum , string_types ) : res = enum . lower ( ) if res is None : raise ValueError ( 'Could not determine string represenatation for' 'enum %r' % enum ) elif valid and res not in valid : raise ValueError ( 'Value of %s must be one of %r, not %r' % ( name , valid , enum ) ) return res
Get lowercase string representation of enum .
2,948
def draw_texture ( tex ) : from . program import Program program = Program ( vert_draw , frag_draw ) program [ 'u_texture' ] = tex program [ 'a_position' ] = [ [ - 1. , - 1. ] , [ - 1. , 1. ] , [ 1. , - 1. ] , [ 1. , 1. ] ] program [ 'a_texcoord' ] = [ [ 0. , 1. ] , [ 0. , 0. ] , [ 1. , 1. ] , [ 1. , 0. ] ] program . draw ( 'triangle_strip' )
Draw a 2D texture to the current viewport
2,949
def _get_dpi_from ( cmd , pattern , func ) : try : out , _ = run_subprocess ( [ cmd ] ) except ( OSError , CalledProcessError ) : pass else : match = re . search ( pattern , out ) if match : return func ( * map ( float , match . groups ( ) ) )
Match pattern against the output of func passing the results as floats to func . If anything fails return None .
2,950
def calc_size ( rect , orientation ) : ( total_halfx , total_halfy ) = rect . center if orientation in [ "bottom" , "top" ] : ( total_major_axis , total_minor_axis ) = ( total_halfx , total_halfy ) else : ( total_major_axis , total_minor_axis ) = ( total_halfy , total_halfx ) major_axis = total_major_axis * ( 1.0 - ColorBarWidget . major_axis_padding ) minor_axis = major_axis * ColorBarWidget . minor_axis_ratio minor_axis = np . minimum ( minor_axis , total_minor_axis * ( 1.0 - ColorBarWidget . minor_axis_padding ) ) return ( major_axis , minor_axis )
Calculate a size
2,951
def dtype_reduce ( dtype , level = 0 , depth = 0 ) : dtype = np . dtype ( dtype ) fields = dtype . fields if fields is None : if len ( dtype . shape ) : count = reduce ( mul , dtype . shape ) else : count = 1 if dtype . subdtype : name = str ( dtype . subdtype [ 0 ] ) else : name = str ( dtype ) return [ '' , count , name ] else : items = [ ] name = '' for key , value in fields . items ( ) : l = dtype_reduce ( value [ 0 ] , level , depth + 1 ) if type ( l [ 0 ] ) is str : items . append ( [ key , l [ 1 ] , l [ 2 ] ] ) else : items . append ( l ) name += key + ',' ctype = None count = 0 for i , item in enumerate ( items ) : if type ( item [ 0 ] ) is not str : return items else : if i == 0 : ctype = item [ 2 ] count += item [ 1 ] else : if item [ 2 ] != ctype : return items count += item [ 1 ] if depth >= level : return [ name , count , ctype ] else : return items
Try to reduce dtype up to a given level when it is possible
2,952
def create_sphere ( rows = 10 , cols = 10 , depth = 10 , radius = 1.0 , offset = True , subdivisions = 3 , method = 'latitude' ) : if method == 'latitude' : return _latitude ( rows , cols , radius , offset ) elif method == 'ico' : return _ico ( radius , subdivisions ) elif method == 'cube' : return _cube ( rows , cols , depth , radius ) else : raise Exception ( "Invalid method. Accepts: 'latitude', 'ico', 'cube'" )
Create a sphere
2,953
def create_cylinder ( rows , cols , radius = [ 1.0 , 1.0 ] , length = 1.0 , offset = False ) : verts = np . empty ( ( rows + 1 , cols , 3 ) , dtype = np . float32 ) if isinstance ( radius , int ) : radius = [ radius , radius ] th = np . linspace ( 2 * np . pi , 0 , cols ) . reshape ( 1 , cols ) r = np . linspace ( radius [ 0 ] , radius [ 1 ] , num = rows + 1 , endpoint = True ) . reshape ( rows + 1 , 1 ) verts [ ... , 2 ] = np . linspace ( 0 , length , num = rows + 1 , endpoint = True ) . reshape ( rows + 1 , 1 ) if offset : th = th + ( ( np . pi / cols ) * np . arange ( rows + 1 ) . reshape ( rows + 1 , 1 ) ) verts [ ... , 0 ] = r * np . cos ( th ) verts [ ... , 1 ] = r * np . sin ( th ) verts = verts . reshape ( ( rows + 1 ) * cols , 3 ) faces = np . empty ( ( rows * cols * 2 , 3 ) , dtype = np . uint32 ) rowtemplate1 = ( ( ( np . arange ( cols ) . reshape ( cols , 1 ) + np . array ( [ [ 0 , 1 , 0 ] ] ) ) % cols ) + np . array ( [ [ 0 , 0 , cols ] ] ) ) rowtemplate2 = ( ( ( np . arange ( cols ) . reshape ( cols , 1 ) + np . array ( [ [ 0 , 1 , 1 ] ] ) ) % cols ) + np . array ( [ [ cols , 0 , cols ] ] ) ) for row in range ( rows ) : start = row * cols * 2 faces [ start : start + cols ] = rowtemplate1 + row * cols faces [ start + cols : start + ( cols * 2 ) ] = rowtemplate2 + row * cols return MeshData ( vertices = verts , faces = faces )
Create a cylinder
2,954
def create_arrow ( rows , cols , radius = 0.1 , length = 1.0 , cone_radius = None , cone_length = None ) : md_cyl = None if cone_radius is None : cone_radius = radius * 2.0 if cone_length is None : con_L = length / 3.0 cyl_L = length * 2.0 / 3.0 else : cyl_L = max ( 0 , length - cone_length ) con_L = min ( cone_length , length ) if cyl_L != 0 : md_cyl = create_cylinder ( rows , cols , radius = [ radius , radius ] , length = cyl_L ) md_con = create_cone ( cols , radius = cone_radius , length = con_L ) verts = md_con . get_vertices ( ) nbr_verts_con = verts . size // 3 faces = md_con . get_faces ( ) if md_cyl is not None : trans = np . array ( [ [ 0.0 , 0.0 , cyl_L ] ] ) verts = np . vstack ( ( verts + trans , md_cyl . get_vertices ( ) ) ) faces = np . vstack ( ( faces , md_cyl . get_faces ( ) + nbr_verts_con ) ) return MeshData ( vertices = verts , faces = faces )
Create a 3D arrow using a cylinder plus cone
2,955
def create_grid_mesh ( xs , ys , zs ) : shape = xs . shape length = shape [ 0 ] * shape [ 1 ] vertices = np . zeros ( ( length , 3 ) ) vertices [ : , 0 ] = xs . reshape ( length ) vertices [ : , 1 ] = ys . reshape ( length ) vertices [ : , 2 ] = zs . reshape ( length ) basic_indices = np . array ( [ 0 , 1 , 1 + shape [ 1 ] , 0 , 0 + shape [ 1 ] , 1 + shape [ 1 ] ] , dtype = np . uint32 ) inner_grid_length = ( shape [ 0 ] - 1 ) * ( shape [ 1 ] - 1 ) offsets = np . arange ( inner_grid_length ) offsets += np . repeat ( np . arange ( shape [ 0 ] - 1 ) , shape [ 1 ] - 1 ) offsets = np . repeat ( offsets , 6 ) indices = np . resize ( basic_indices , len ( offsets ) ) + offsets indices = indices . reshape ( ( len ( indices ) // 3 , 3 ) ) return vertices , indices
Generate vertices and indices for an implicitly connected mesh .
2,956
def _straight_line_vertices ( adjacency_mat , node_coords , directed = False ) : if not issparse ( adjacency_mat ) : adjacency_mat = np . asarray ( adjacency_mat , float ) if ( adjacency_mat . ndim != 2 or adjacency_mat . shape [ 0 ] != adjacency_mat . shape [ 1 ] ) : raise ValueError ( "Adjacency matrix should be square." ) arrow_vertices = np . array ( [ ] ) edges = _get_edges ( adjacency_mat ) line_vertices = node_coords [ edges . ravel ( ) ] if directed : arrows = np . array ( list ( _get_directed_edges ( adjacency_mat ) ) ) arrow_vertices = node_coords [ arrows . ravel ( ) ] arrow_vertices = arrow_vertices . reshape ( ( len ( arrow_vertices ) / 2 , 4 ) ) return line_vertices , arrow_vertices
Generate the vertices for straight lines between nodes .
2,957
def get_handle ( ) : global __handle__ if not __handle__ : __handle__ = FT_Library ( ) error = FT_Init_FreeType ( byref ( __handle__ ) ) if error : raise RuntimeError ( hex ( error ) ) return __handle__
Get unique FT_Library handle
2,958
def make_camera ( cam_type , * args , ** kwargs ) : cam_types = { None : BaseCamera } for camType in ( BaseCamera , PanZoomCamera , PerspectiveCamera , TurntableCamera , FlyCamera , ArcballCamera ) : cam_types [ camType . __name__ [ : - 6 ] . lower ( ) ] = camType try : return cam_types [ cam_type ] ( * args , ** kwargs ) except KeyError : raise KeyError ( 'Unknown camera type "%s". Options are: %s' % ( cam_type , cam_types . keys ( ) ) )
Factory function for creating new cameras using a string name .
2,959
def set_data_values ( self , label , x , y , z ) : self . layers [ label ] [ 'data' ] = np . array ( [ x , y , z ] ) . transpose ( ) self . _update ( )
Set the position of the datapoints
2,960
def surface ( func , umin = 0 , umax = 2 * np . pi , ucount = 64 , urepeat = 1.0 , vmin = 0 , vmax = 2 * np . pi , vcount = 64 , vrepeat = 1.0 ) : vtype = [ ( 'position' , np . float32 , 3 ) , ( 'texcoord' , np . float32 , 2 ) , ( 'normal' , np . float32 , 3 ) ] itype = np . uint32 vcount += 1 ucount += 1 n = vcount * ucount Un = np . repeat ( np . linspace ( 0 , 1 , ucount , endpoint = True ) , vcount ) Vn = np . tile ( np . linspace ( 0 , 1 , vcount , endpoint = True ) , ucount ) U = umin + Un * ( umax - umin ) V = vmin + Vn * ( vmax - vmin ) vertices = np . zeros ( n , dtype = vtype ) for i , ( u , v ) in enumerate ( zip ( U , V ) ) : vertices [ "position" ] [ i ] = func ( u , v ) vertices [ "texcoord" ] [ : , 0 ] = Un * urepeat vertices [ "texcoord" ] [ : , 1 ] = Vn * vrepeat indices = [ ] for i in range ( ucount - 1 ) : for j in range ( vcount - 1 ) : indices . append ( i * ( vcount ) + j ) indices . append ( i * ( vcount ) + j + 1 ) indices . append ( i * ( vcount ) + j + vcount + 1 ) indices . append ( i * ( vcount ) + j + vcount ) indices . append ( i * ( vcount ) + j + vcount + 1 ) indices . append ( i * ( vcount ) + j ) indices = np . array ( indices , dtype = itype ) vertices [ "normal" ] = normals ( vertices [ "position" ] , indices . reshape ( len ( indices ) / 3 , 3 ) ) return vertices , indices
Computes the parameterization of a parametric surface
2,961
def _new_program ( self , p ) : for k , v in self . _set_items . items ( ) : getattr ( p , self . _shader ) [ k ] = v
New program was added to the multiprogram ; update items in the shader .
2,962
def attach ( self , canvas ) : self . _canvas = canvas canvas . events . resize . connect ( self . on_resize ) canvas . events . mouse_wheel . connect ( self . on_mouse_wheel ) canvas . events . mouse_move . connect ( self . on_mouse_move )
Attach this tranform to a canvas
2,963
def on_mouse_move ( self , event ) : if event . is_dragging : dxy = event . pos - event . last_event . pos button = event . press_event . button if button == 1 : dxy = self . canvas_tr . map ( dxy ) o = self . canvas_tr . map ( [ 0 , 0 ] ) t = dxy - o self . move ( t ) elif button == 2 : center = self . canvas_tr . map ( event . press_event . pos ) if self . _aspect is None : self . zoom ( np . exp ( dxy * ( 0.01 , - 0.01 ) ) , center ) else : s = dxy [ 1 ] * - 0.01 self . zoom ( np . exp ( np . array ( [ s , s ] ) ) , center ) self . shader_map ( )
Mouse move handler
2,964
def on_mouse_wheel ( self , event ) : self . zoom ( np . exp ( event . delta * ( 0.01 , - 0.01 ) ) , event . pos )
Mouse wheel handler
2,965
def _frenet_frames ( points , closed ) : tangents = np . zeros ( ( len ( points ) , 3 ) ) normals = np . zeros ( ( len ( points ) , 3 ) ) epsilon = 0.0001 tangents = np . roll ( points , - 1 , axis = 0 ) - np . roll ( points , 1 , axis = 0 ) if not closed : tangents [ 0 ] = points [ 1 ] - points [ 0 ] tangents [ - 1 ] = points [ - 1 ] - points [ - 2 ] mags = np . sqrt ( np . sum ( tangents * tangents , axis = 1 ) ) tangents /= mags [ : , np . newaxis ] t = np . abs ( tangents [ 0 ] ) smallest = np . argmin ( t ) normal = np . zeros ( 3 ) normal [ smallest ] = 1. vec = np . cross ( tangents [ 0 ] , normal ) normals [ 0 ] = np . cross ( tangents [ 0 ] , vec ) for i in range ( 1 , len ( points ) ) : normals [ i ] = normals [ i - 1 ] vec = np . cross ( tangents [ i - 1 ] , tangents [ i ] ) if norm ( vec ) > epsilon : vec /= norm ( vec ) theta = np . arccos ( np . clip ( tangents [ i - 1 ] . dot ( tangents [ i ] ) , - 1 , 1 ) ) normals [ i ] = rotate ( - np . degrees ( theta ) , vec ) [ : 3 , : 3 ] . dot ( normals [ i ] ) if closed : theta = np . arccos ( np . clip ( normals [ 0 ] . dot ( normals [ - 1 ] ) , - 1 , 1 ) ) theta /= len ( points ) - 1 if tangents [ 0 ] . dot ( np . cross ( normals [ 0 ] , normals [ - 1 ] ) ) > 0 : theta *= - 1. for i in range ( 1 , len ( points ) ) : normals [ i ] = rotate ( - np . degrees ( theta * i ) , tangents [ i ] ) [ : 3 , : 3 ] . dot ( normals [ i ] ) binormals = np . cross ( tangents , normals ) return tangents , normals , binormals
Calculates and returns the tangents normals and binormals for the tube .
2,966
def max_order ( self ) : combo = int ( 0 ) for iv in self . _interval_set . _intervals : combo |= iv [ 0 ] | iv [ 1 ] ret = AbstractMOC . HPY_MAX_NORDER - ( utils . number_trailing_zeros ( combo ) // 2 ) if ret < 0 : ret = 0 return ret
Depth of the smallest HEALPix cells found in the MOC instance .
2,967
def intersection ( self , another_moc , * args ) : interval_set = self . _interval_set . intersection ( another_moc . _interval_set ) for moc in args : interval_set = interval_set . intersection ( moc . _interval_set ) return self . __class__ ( interval_set )
Intersection between the MOC instance and other MOCs .
2,968
def union ( self , another_moc , * args ) : interval_set = self . _interval_set . union ( another_moc . _interval_set ) for moc in args : interval_set = interval_set . union ( moc . _interval_set ) return self . __class__ ( interval_set )
Union between the MOC instance and other MOCs .
2,969
def difference ( self , another_moc , * args ) : interval_set = self . _interval_set . difference ( another_moc . _interval_set ) for moc in args : interval_set = interval_set . difference ( moc . _interval_set ) return self . __class__ ( interval_set )
Difference between the MOC instance and other MOCs .
2,970
def _neighbour_pixels ( hp , ipix ) : neigh_ipix = np . unique ( hp . neighbours ( ipix ) . ravel ( ) ) return neigh_ipix [ np . where ( neigh_ipix >= 0 ) ]
Returns all the pixels neighbours of ipix
2,971
def from_cells ( cls , cells ) : shift = ( AbstractMOC . HPY_MAX_NORDER - cells [ "depth" ] ) << 1 p1 = cells [ "ipix" ] p2 = cells [ "ipix" ] + 1 intervals = np . vstack ( ( p1 << shift , p2 << shift ) ) . T return cls ( IntervalSet ( intervals ) )
Creates a MOC from a numpy array representing the HEALPix cells .
2,972
def from_json ( cls , json_moc ) : intervals = np . array ( [ ] ) for order , pix_l in json_moc . items ( ) : if len ( pix_l ) == 0 : continue pix = np . array ( pix_l ) p1 = pix p2 = pix + 1 shift = 2 * ( AbstractMOC . HPY_MAX_NORDER - int ( order ) ) itv = np . vstack ( ( p1 << shift , p2 << shift ) ) . T if intervals . size == 0 : intervals = itv else : intervals = np . vstack ( ( intervals , itv ) ) return cls ( IntervalSet ( intervals ) )
Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth .
2,973
def _uniq_pixels_iterator ( self ) : intervals_uniq_l = IntervalSet . to_nuniq_interval_set ( self . _interval_set ) . _intervals for uniq_iv in intervals_uniq_l : for uniq in range ( uniq_iv [ 0 ] , uniq_iv [ 1 ] ) : yield uniq
Generator giving the NUNIQ HEALPix pixels of the MOC .
2,974
def from_fits ( cls , filename ) : table = Table . read ( filename ) intervals = np . vstack ( ( table [ 'UNIQ' ] , table [ 'UNIQ' ] + 1 ) ) . T nuniq_interval_set = IntervalSet ( intervals ) interval_set = IntervalSet . from_nuniq_interval_set ( nuniq_interval_set ) return cls ( interval_set )
Loads a MOC from a FITS file .
2,975
def _to_json ( uniq ) : result_json = { } depth , ipix = utils . uniq2orderipix ( uniq ) min_depth = np . min ( depth [ 0 ] ) max_depth = np . max ( depth [ - 1 ] ) for d in range ( min_depth , max_depth + 1 ) : pix_index = np . where ( depth == d ) [ 0 ] if pix_index . size : ipix_depth = ipix [ pix_index ] result_json [ str ( d ) ] = ipix_depth . tolist ( ) return result_json
Serializes a MOC to the JSON format .
2,976
def _to_str ( uniq ) : def write_cells ( serial , a , b , sep = '' ) : if a == b : serial += '{0}{1}' . format ( a , sep ) else : serial += '{0}-{1}{2}' . format ( a , b , sep ) return serial res = '' if uniq . size == 0 : return res depth , ipixels = utils . uniq2orderipix ( uniq ) min_depth = np . min ( depth [ 0 ] ) max_depth = np . max ( depth [ - 1 ] ) for d in range ( min_depth , max_depth + 1 ) : pix_index = np . where ( depth == d ) [ 0 ] if pix_index . size > 0 : res += '{0}/' . format ( d ) ipix_depth = ipixels [ pix_index ] if ipix_depth . size == 1 : res = write_cells ( res , ipix_depth [ 0 ] , ipix_depth [ 0 ] ) else : ipix_depth = np . sort ( ipix_depth ) beg_range = ipix_depth [ 0 ] last_range = beg_range for ipix in ipix_depth [ 1 : ] : if ipix > last_range + 1 : res = write_cells ( res , beg_range , last_range , sep = ',' ) beg_range = ipix last_range = ipix res = write_cells ( res , beg_range , last_range ) res += ' ' res = res [ : - 1 ] return res
Serializes a MOC to the STRING format .
2,977
def _to_fits ( self , uniq , optional_kw_dict = None ) : depth = self . max_order if depth <= 13 : fits_format = '1J' else : fits_format = '1K' tbhdu = fits . BinTableHDU . from_columns ( fits . ColDefs ( [ fits . Column ( name = 'UNIQ' , format = fits_format , array = uniq ) ] ) ) tbhdu . header [ 'PIXTYPE' ] = 'HEALPIX' tbhdu . header [ 'ORDERING' ] = 'NUNIQ' tbhdu . header . update ( self . _fits_header_keywords ) tbhdu . header [ 'MOCORDER' ] = depth tbhdu . header [ 'MOCTOOL' ] = 'MOCPy' if optional_kw_dict : for key in optional_kw_dict : tbhdu . header [ key ] = optional_kw_dict [ key ] thdulist = fits . HDUList ( [ fits . PrimaryHDU ( ) , tbhdu ] ) return thdulist
Serializes a MOC to the FITS format .
2,978
def serialize ( self , format = 'fits' , optional_kw_dict = None ) : formats = ( 'fits' , 'json' , 'str' ) if format not in formats : raise ValueError ( 'format should be one of %s' % ( str ( formats ) ) ) uniq_l = [ ] for uniq in self . _uniq_pixels_iterator ( ) : uniq_l . append ( uniq ) uniq = np . array ( uniq_l ) if format == 'fits' : result = self . _to_fits ( uniq = uniq , optional_kw_dict = optional_kw_dict ) elif format == 'str' : result = self . __class__ . _to_str ( uniq = uniq ) else : result = self . __class__ . _to_json ( uniq = uniq ) return result
Serializes the MOC into a specific format .
2,979
def write ( self , path , format = 'fits' , overwrite = False , optional_kw_dict = None ) : serialization = self . serialize ( format = format , optional_kw_dict = optional_kw_dict ) if format == 'fits' : serialization . writeto ( path , overwrite = overwrite ) else : import json with open ( path , 'w' ) as h : h . write ( json . dumps ( serialization , sort_keys = True , indent = 2 ) )
Writes the MOC to a file .
2,980
def degrade_to_order ( self , new_order ) : shift = 2 * ( AbstractMOC . HPY_MAX_NORDER - new_order ) ofs = ( int ( 1 ) << shift ) - 1 mask = ~ ofs adda = int ( 0 ) addb = ofs iv_set = [ ] for iv in self . _interval_set . _intervals : a = ( iv [ 0 ] + adda ) & mask b = ( iv [ 1 ] + addb ) & mask if b > a : iv_set . append ( ( a , b ) ) return self . __class__ ( IntervalSet ( np . asarray ( iv_set ) ) )
Degrades the MOC instance to a new less precise MOC .
2,981
def set_name ( self , name ) : self . name = name self . server . request ( "screen_set %s name %s" % ( self . ref , self . name ) )
Set Screen Name
2,982
def set_width ( self , width ) : if width > 0 and width <= self . server . server_info . get ( "screen_width" ) : self . width = width self . server . request ( "screen_set %s wid %i" % ( self . ref , self . width ) )
Set Screen Width
2,983
def set_height ( self , height ) : if height > 0 and height <= self . server . server_info . get ( "screen_height" ) : self . height = height self . server . request ( "screen_set %s hgt %i" % ( self . ref , self . height ) )
Set Screen Height
2,984
def set_cursor_x ( self , x ) : if x >= 0 and x <= self . server . server_info . get ( "screen_width" ) : self . cursor_x = x self . server . request ( "screen_set %s cursor_x %i" % ( self . ref , self . cursor_x ) )
Set Screen Cursor X Position
2,985
def set_cursor_y ( self , y ) : if y >= 0 and y <= self . server . server_info . get ( "screen_height" ) : self . cursor_y = y self . server . request ( "screen_set %s cursor_y %i" % ( self . ref , self . cursor_y ) )
Set Screen Cursor Y Position
2,986
def set_duration ( self , duration ) : if duration > 0 : self . duration = duration self . server . request ( "screen_set %s duration %i" % ( self . ref , ( self . duration * 8 ) ) )
Set Screen Change Interval Duration
2,987
def set_timeout ( self , timeout ) : if timeout > 0 : self . timeout = timeout self . server . request ( "screen_set %s timeout %i" % ( self . ref , ( self . timeout * 8 ) ) )
Set Screen Timeout Duration
2,988
def set_priority ( self , priority ) : if priority in [ "hidden" , "background" , "info" , "foreground" , "alert" , "input" ] : self . priority = priority self . server . request ( "screen_set %s priority %s" % ( self . ref , self . priority ) )
Set Screen Priority Class
2,989
def set_backlight ( self , state ) : if state in [ "on" , "off" , "toggle" , "open" , "blink" , "flash" ] : self . backlight = state self . server . request ( "screen_set %s backlight %s" % ( self . ref , self . backlight ) )
Set Screen Backlight Mode
2,990
def set_heartbeat ( self , state ) : if state in [ "on" , "off" , "open" ] : self . heartbeat = state self . server . request ( "screen_set %s heartbeat %s" % ( self . ref , self . heartbeat ) )
Set Screen Heartbeat Display Mode
2,991
def set_cursor ( self , cursor ) : if cursor in [ "on" , "off" , "under" , "block" ] : self . cursor = cursor self . server . request ( "screen_set %s cursor %s" % ( self . ref , self . cursor ) )
Set Screen Cursor Mode
2,992
def add_string_widget ( self , ref , text = "Text" , x = 1 , y = 1 ) : if ref not in self . widgets : widget = widgets . StringWidget ( screen = self , ref = ref , text = text , x = x , y = y ) self . widgets [ ref ] = widget return self . widgets [ ref ]
Add String Widget
2,993
def add_title_widget ( self , ref , text = "Title" ) : if ref not in self . widgets : widget = widgets . TitleWidget ( screen = self , ref = ref , text = text ) self . widgets [ ref ] = widget return self . widgets [ ref ]
Add Title Widget
2,994
def add_hbar_widget ( self , ref , x = 1 , y = 1 , length = 10 ) : if ref not in self . widgets : widget = widgets . HBarWidget ( screen = self , ref = ref , x = x , y = y , length = length ) self . widgets [ ref ] = widget return self . widgets [ ref ]
Add Horizontal Bar Widget
2,995
def add_vbar_widget ( self , ref , x = 1 , y = 1 , length = 10 ) : if ref not in self . widgets : widget = widgets . VBarWidget ( screen = self , ref = ref , x = x , y = y , length = length ) self . widgets [ ref ] = widget return self . widgets [ ref ]
Add Vertical Bar Widget
2,996
def add_frame_widget ( self , ref , left = 1 , top = 1 , right = 20 , bottom = 1 , width = 20 , height = 4 , direction = "h" , speed = 1 ) : if ref not in self . widgets : widget = widgets . FrameWidget ( screen = self , ref = ref , left = left , top = top , right = right , bottom = bottom , width = width , height = height , direction = direction , speed = speed , ) self . widgets [ ref ] = widget return self . widgets [ ref ]
Add Frame Widget
2,997
def add_number_widget ( self , ref , x = 1 , value = 1 ) : if ref not in self . widgets : widget = widgets . NumberWidget ( screen = self , ref = ref , x = x , value = value ) self . widgets [ ref ] = widget return self . widgets [ ref ]
Add Number Widget
2,998
def orbit ( self , azim , elev ) : self . azimuth += azim self . elevation = np . clip ( self . elevation + elev , - 90 , 90 ) self . view_changed ( )
Orbits the camera around the center position .
2,999
def _set_config ( c ) : glfw . glfwWindowHint ( glfw . GLFW_RED_BITS , c [ 'red_size' ] ) glfw . glfwWindowHint ( glfw . GLFW_GREEN_BITS , c [ 'green_size' ] ) glfw . glfwWindowHint ( glfw . GLFW_BLUE_BITS , c [ 'blue_size' ] ) glfw . glfwWindowHint ( glfw . GLFW_ALPHA_BITS , c [ 'alpha_size' ] ) glfw . glfwWindowHint ( glfw . GLFW_ACCUM_RED_BITS , 0 ) glfw . glfwWindowHint ( glfw . GLFW_ACCUM_GREEN_BITS , 0 ) glfw . glfwWindowHint ( glfw . GLFW_ACCUM_BLUE_BITS , 0 ) glfw . glfwWindowHint ( glfw . GLFW_ACCUM_ALPHA_BITS , 0 ) glfw . glfwWindowHint ( glfw . GLFW_DEPTH_BITS , c [ 'depth_size' ] ) glfw . glfwWindowHint ( glfw . GLFW_STENCIL_BITS , c [ 'stencil_size' ] ) glfw . glfwWindowHint ( glfw . GLFW_SAMPLES , c [ 'samples' ] ) glfw . glfwWindowHint ( glfw . GLFW_STEREO , c [ 'stereo' ] ) if not c [ 'double_buffer' ] : raise RuntimeError ( 'GLFW must double buffer, consider using a ' 'different backend, or using double buffering' )
Set gl configuration for GLFW