idx
int64 0
63k
| question
stringlengths 61
4.03k
| target
stringlengths 6
1.23k
|
---|---|---|
3,000 |
def _patch ( ) : import sys from OpenGL import GL if sys . version_info > ( 3 , ) : buffersubdatafunc = GL . glBufferSubData if hasattr ( buffersubdatafunc , 'wrapperFunction' ) : buffersubdatafunc = buffersubdatafunc . wrapperFunction _m = sys . modules [ buffersubdatafunc . __module__ ] _m . long = int try : from OpenGL . GL . VERSION import GL_2_0 GL_2_0 . GL_OBJECT_SHADER_SOURCE_LENGTH = GL_2_0 . GL_SHADER_SOURCE_LENGTH except Exception : pass
|
Monkey - patch pyopengl to fix a bug in glBufferSubData .
|
3,001 |
def _inject ( ) : NS = _pyopengl2 . __dict__ for glname , ourname in _pyopengl2 . _functions_to_import : func = _get_function_from_pyopengl ( glname ) NS [ ourname ] = func
|
Copy functions from OpenGL . GL into _pyopengl namespace .
|
3,002 |
def _get_vispy_font_filename ( face , bold , italic ) : name = face + '-' name += 'Regular' if not bold and not italic else '' name += 'Bold' if bold else '' name += 'Italic' if italic else '' name += '.ttf' return load_data_file ( 'fonts/%s' % name )
|
Fetch a remote vispy font
|
3,003 |
def _hex_to_rgba ( hexs ) : hexs = np . atleast_1d ( np . array ( hexs , '|U9' ) ) out = np . ones ( ( len ( hexs ) , 4 ) , np . float32 ) for hi , h in enumerate ( hexs ) : assert isinstance ( h , string_types ) off = 1 if h [ 0 ] == '#' else 0 assert len ( h ) in ( 6 + off , 8 + off ) e = ( len ( h ) - off ) // 2 out [ hi , : e ] = [ int ( h [ i : i + 2 ] , 16 ) / 255. for i in range ( off , len ( h ) , 2 ) ] return out
|
Convert hex to rgba permitting alpha values in hex
|
3,004 |
def _rgb_to_hex ( rgbs ) : rgbs , n_dim = _check_color_dim ( rgbs ) return np . array ( [ '#%02x%02x%02x' % tuple ( ( 255 * rgb [ : 3 ] ) . astype ( np . uint8 ) ) for rgb in rgbs ] , '|U7' )
|
Convert rgb to hex triplet
|
3,005 |
def _rgb_to_hsv ( rgbs ) : rgbs , n_dim = _check_color_dim ( rgbs ) hsvs = list ( ) for rgb in rgbs : rgb = rgb [ : 3 ] idx = np . argmax ( rgb ) val = rgb [ idx ] c = val - np . min ( rgb ) if c == 0 : hue = 0 sat = 0 else : if idx == 0 : hue = ( ( rgb [ 1 ] - rgb [ 2 ] ) / c ) % 6 elif idx == 1 : hue = ( rgb [ 2 ] - rgb [ 0 ] ) / c + 2 else : hue = ( rgb [ 0 ] - rgb [ 1 ] ) / c + 4 hue *= 60 sat = c / val hsv = [ hue , sat , val ] hsvs . append ( hsv ) hsvs = np . array ( hsvs , dtype = np . float32 ) if n_dim == 4 : hsvs = np . concatenate ( ( hsvs , rgbs [ : , 3 ] ) , axis = 1 ) return hsvs
|
Convert Nx3 or Nx4 rgb to hsv
|
3,006 |
def _hsv_to_rgb ( hsvs ) : hsvs , n_dim = _check_color_dim ( hsvs ) rgbs = list ( ) for hsv in hsvs : c = hsv [ 1 ] * hsv [ 2 ] m = hsv [ 2 ] - c hp = hsv [ 0 ] / 60 x = c * ( 1 - abs ( hp % 2 - 1 ) ) if 0 <= hp < 1 : r , g , b = c , x , 0 elif hp < 2 : r , g , b = x , c , 0 elif hp < 3 : r , g , b = 0 , c , x elif hp < 4 : r , g , b = 0 , x , c elif hp < 5 : r , g , b = x , 0 , c else : r , g , b = c , 0 , x rgb = [ r + m , g + m , b + m ] rgbs . append ( rgb ) rgbs = np . array ( rgbs , dtype = np . float32 ) if n_dim == 4 : rgbs = np . concatenate ( ( rgbs , hsvs [ : , 3 ] ) , axis = 1 ) return rgbs
|
Convert Nx3 or Nx4 hsv to rgb
|
3,007 |
def _lab_to_rgb ( labs ) : labs , n_dim = _check_color_dim ( labs ) y = ( labs [ : , 0 ] + 16. ) / 116. x = ( labs [ : , 1 ] / 500. ) + y z = y - ( labs [ : , 2 ] / 200. ) xyz = np . concatenate ( ( [ x ] , [ y ] , [ z ] ) ) over = xyz > 0.2068966 xyz [ over ] = xyz [ over ] ** 3. xyz [ ~ over ] = ( xyz [ ~ over ] - 0.13793103448275862 ) / 7.787 rgbs = np . dot ( _xyz2rgb_norm , xyz ) . T over = rgbs > 0.0031308 rgbs [ over ] = 1.055 * ( rgbs [ over ] ** ( 1. / 2.4 ) ) - 0.055 rgbs [ ~ over ] *= 12.92 if n_dim == 4 : rgbs = np . concatenate ( ( rgbs , labs [ : , 3 ] ) , axis = 1 ) rgbs = np . clip ( rgbs , 0. , 1. ) return rgbs
|
Convert Nx3 or Nx4 lab to rgb
|
3,008 |
def get ( self , tags ) : value = tags . get ( self . name , '' ) for name in self . alternate_tags : value = value or tags . get ( name , '' ) value = value or self . default return value
|
Find an adequate value for this field from a dict of tags .
|
3,009 |
def _set_config ( c ) : func = sdl2 . SDL_GL_SetAttribute func ( sdl2 . SDL_GL_RED_SIZE , c [ 'red_size' ] ) func ( sdl2 . SDL_GL_GREEN_SIZE , c [ 'green_size' ] ) func ( sdl2 . SDL_GL_BLUE_SIZE , c [ 'blue_size' ] ) func ( sdl2 . SDL_GL_ALPHA_SIZE , c [ 'alpha_size' ] ) func ( sdl2 . SDL_GL_DEPTH_SIZE , c [ 'depth_size' ] ) func ( sdl2 . SDL_GL_STENCIL_SIZE , c [ 'stencil_size' ] ) func ( sdl2 . SDL_GL_DOUBLEBUFFER , 1 if c [ 'double_buffer' ] else 0 ) samps = c [ 'samples' ] func ( sdl2 . SDL_GL_MULTISAMPLEBUFFERS , 1 if samps > 0 else 0 ) func ( sdl2 . SDL_GL_MULTISAMPLESAMPLES , samps if samps > 0 else 0 ) func ( sdl2 . SDL_GL_STEREO , c [ 'stereo' ] )
|
Set gl configuration for SDL2
|
3,010 |
def create_response ( self , message = None , end_session = False , card_obj = None , reprompt_message = None , is_ssml = None ) : response = dict ( self . base_response ) if message : response [ 'response' ] = self . create_speech ( message , is_ssml ) response [ 'response' ] [ 'shouldEndSession' ] = end_session if card_obj : response [ 'response' ] [ 'card' ] = card_obj if reprompt_message : response [ 'response' ] [ 'reprompt' ] = self . create_speech ( reprompt_message , is_ssml ) return Response ( response )
|
message - text message to be spoken out by the Echo end_session - flag to determine whether this interaction should end the session card_obj = JSON card object to substitute the card field in the raw_response
|
3,011 |
def intent ( self , intent ) : def _handler ( func ) : self . _handlers [ 'IntentRequest' ] [ intent ] = func return func return _handler
|
Decorator to register intent handler
|
3,012 |
def request ( self , request_type ) : def _handler ( func ) : self . _handlers [ request_type ] = func return func return _handler
|
Decorator to register generic request handler
|
3,013 |
def route_request ( self , request_json , metadata = None ) : request = Request ( request_json ) request . metadata = metadata handler_fn = self . _handlers [ self . _default ] if not request . is_intent ( ) and ( request . request_type ( ) in self . _handlers ) : handler_fn = self . _handlers [ request . request_type ( ) ] elif request . is_intent ( ) and request . intent_name ( ) in self . _handlers [ 'IntentRequest' ] : handler_fn = self . _handlers [ 'IntentRequest' ] [ request . intent_name ( ) ] response = handler_fn ( request ) response . set_session ( request . session ) return response . to_json ( )
|
Route the request object to the right handler function
|
3,014 |
def _viewbox_set ( self , viewbox ) : self . _viewbox = viewbox viewbox . events . mouse_press . connect ( self . viewbox_mouse_event ) viewbox . events . mouse_release . connect ( self . viewbox_mouse_event ) viewbox . events . mouse_move . connect ( self . viewbox_mouse_event ) viewbox . events . mouse_wheel . connect ( self . viewbox_mouse_event ) viewbox . events . resize . connect ( self . viewbox_resize_event )
|
Friend method of viewbox to register itself .
|
3,015 |
def _viewbox_unset ( self , viewbox ) : self . _viewbox = None viewbox . events . mouse_press . disconnect ( self . viewbox_mouse_event ) viewbox . events . mouse_release . disconnect ( self . viewbox_mouse_event ) viewbox . events . mouse_move . disconnect ( self . viewbox_mouse_event ) viewbox . events . mouse_wheel . disconnect ( self . viewbox_mouse_event ) viewbox . events . resize . disconnect ( self . viewbox_resize_event )
|
Friend method of viewbox to unregister itself .
|
3,016 |
def set_range ( self , x = None , y = None , z = None , margin = 0.05 ) : init = self . _xlim is None bounds = [ None , None , None ] if x is not None : bounds [ 0 ] = float ( x [ 0 ] ) , float ( x [ 1 ] ) if y is not None : bounds [ 1 ] = float ( y [ 0 ] ) , float ( y [ 1 ] ) if z is not None : bounds [ 2 ] = float ( z [ 0 ] ) , float ( z [ 1 ] ) if self . _viewbox is None : self . _set_range_args = bounds [ 0 ] , bounds [ 1 ] , bounds [ 2 ] , margin return self . _resetting = True if all ( [ ( b is None ) for b in bounds ] ) : bounds = self . _viewbox . get_scene_bounds ( ) else : for i in range ( 3 ) : if bounds [ i ] is None : bounds [ i ] = self . _viewbox . get_scene_bounds ( i ) ranges = [ b [ 1 ] - b [ 0 ] for b in bounds ] margins = [ ( r * margin or 0.1 ) for r in ranges ] bounds_margins = [ ( b [ 0 ] - m , b [ 1 ] + m ) for b , m in zip ( bounds , margins ) ] self . _xlim , self . _ylim , self . _zlim = bounds_margins if ( not init ) or ( self . _center is None ) : self . _center = [ ( b [ 0 ] + r / 2 ) for b , r in zip ( bounds , ranges ) ] self . _set_range ( init ) self . _resetting = False self . view_changed ( )
|
Set the range of the view region for the camera
|
3,017 |
def get_state ( self ) : D = { } for key in self . _state_props : D [ key ] = getattr ( self , key ) return D
|
Get the current view state of the camera
|
3,018 |
def set_state ( self , state = None , ** kwargs ) : D = state or { } D . update ( kwargs ) for key , val in D . items ( ) : if key not in self . _state_props : raise KeyError ( 'Not a valid camera state property %r' % key ) setattr ( self , key , val )
|
Set the view state of the camera
|
3,019 |
def link ( self , camera ) : cam1 , cam2 = self , camera while cam1 in cam2 . _linked_cameras : cam2 . _linked_cameras . remove ( cam1 ) while cam2 in cam1 . _linked_cameras : cam1 . _linked_cameras . remove ( cam2 ) cam1 . _linked_cameras . append ( cam2 ) cam2 . _linked_cameras . append ( cam1 )
|
Link this camera with another camera of the same type
|
3,020 |
def view_changed ( self ) : if self . _resetting : return if self . _viewbox : if self . _xlim is None : args = self . _set_range_args or ( ) self . set_range ( * args ) if self . _default_state is None : self . set_default_state ( ) self . _update_transform ( )
|
Called when this camera is changes its view . Also called when its associated with a viewbox .
|
3,021 |
def on_canvas_change ( self , event ) : if event . old is not None : event . old . events . key_press . disconnect ( self . viewbox_key_event ) event . old . events . key_release . disconnect ( self . viewbox_key_event ) if event . new is not None : event . new . events . key_press . connect ( self . viewbox_key_event ) event . new . events . key_release . connect ( self . viewbox_key_event )
|
Canvas change event handler
|
3,022 |
def _set_scene_transform ( self , tr ) : pre_tr = self . pre_transform if pre_tr is None : self . _scene_transform = tr else : self . _transform_cache . roll ( ) self . _scene_transform = self . _transform_cache . get ( [ pre_tr , tr ] ) self . _scene_transform . dynamic = True self . _viewbox . scene . transform = self . _scene_transform self . _viewbox . update ( ) for cam in self . _linked_cameras : if cam is self . _linked_cameras_no_update : continue try : cam . _linked_cameras_no_update = self cam . set_state ( self . get_state ( ) ) finally : cam . _linked_cameras_no_update = None
|
Called by subclasses to configure the viewbox scene transform .
|
3,023 |
def _set_config ( c ) : glformat = QGLFormat ( ) glformat . setRedBufferSize ( c [ 'red_size' ] ) glformat . setGreenBufferSize ( c [ 'green_size' ] ) glformat . setBlueBufferSize ( c [ 'blue_size' ] ) glformat . setAlphaBufferSize ( c [ 'alpha_size' ] ) if QT5_NEW_API : glformat . setSwapBehavior ( glformat . DoubleBuffer if c [ 'double_buffer' ] else glformat . SingleBuffer ) else : glformat . setAccum ( False ) glformat . setRgba ( True ) glformat . setDoubleBuffer ( True if c [ 'double_buffer' ] else False ) glformat . setDepth ( True if c [ 'depth_size' ] else False ) glformat . setStencil ( True if c [ 'stencil_size' ] else False ) glformat . setSampleBuffers ( True if c [ 'samples' ] else False ) glformat . setDepthBufferSize ( c [ 'depth_size' ] if c [ 'depth_size' ] else 0 ) glformat . setStencilBufferSize ( c [ 'stencil_size' ] if c [ 'stencil_size' ] else 0 ) glformat . setSamples ( c [ 'samples' ] if c [ 'samples' ] else 0 ) glformat . setStereo ( c [ 'stereo' ] ) return glformat
|
Set the OpenGL configuration
|
3,024 |
def get_window_id ( self ) : winid = self . winId ( ) if IS_RPI : nw = ( ctypes . c_int * 3 ) ( winid , self . width ( ) , self . height ( ) ) return ctypes . pointer ( nw ) elif IS_LINUX : return int ( winid ) ctypes . pythonapi . PyCapsule_GetName . restype = ctypes . c_char_p ctypes . pythonapi . PyCapsule_GetName . argtypes = [ ctypes . py_object ] ctypes . pythonapi . PyCapsule_GetPointer . restype = ctypes . c_void_p ctypes . pythonapi . PyCapsule_GetPointer . argtypes = [ ctypes . py_object , ctypes . c_char_p ] name = ctypes . pythonapi . PyCapsule_GetName ( winid ) handle = ctypes . pythonapi . PyCapsule_GetPointer ( winid , name ) return handle
|
Get the window id of a PySide Widget . Might also work for PyQt4 .
|
3,025 |
def obj ( x ) : x1 = x [ 0 ] x2 = x [ 1 ] f = ( 4 - 2.1 * ( x1 * x1 ) + ( x1 * x1 * x1 * x1 ) / 3.0 ) * ( x1 * x1 ) + x1 * x2 + ( - 4 + 4 * ( x2 * x2 ) ) * ( x2 * x2 ) return f
|
Six - hump camelback function
|
3,026 |
def move ( self , move ) : move = as_vec4 ( move , default = ( 0 , 0 , 0 , 0 ) ) self . translate = self . translate + move
|
Change the translation of this transform by the amount given .
|
3,027 |
def zoom ( self , zoom , center = ( 0 , 0 , 0 ) , mapped = True ) : zoom = as_vec4 ( zoom , default = ( 1 , 1 , 1 , 1 ) ) center = as_vec4 ( center , default = ( 0 , 0 , 0 , 0 ) ) scale = self . scale * zoom if mapped : trans = center - ( center - self . translate ) * zoom else : trans = self . scale * ( 1 - zoom ) * center + self . translate self . _set_st ( scale = scale , translate = trans )
|
Update the transform such that its scale factor is changed but the specified center point is left unchanged .
|
3,028 |
def from_mapping ( cls , x0 , x1 ) : t = cls ( ) t . set_mapping ( x0 , x1 ) return t
|
Create an STTransform from the given mapping
|
3,029 |
def set_mapping ( self , x0 , x1 , update = True ) : if isinstance ( x0 , Rect ) : x0 = x0 . _transform_in ( ) [ : 3 ] if isinstance ( x1 , Rect ) : x1 = x1 . _transform_in ( ) [ : 3 ] x0 = np . asarray ( x0 ) x1 = np . asarray ( x1 ) if ( x0 . ndim != 2 or x0 . shape [ 0 ] != 2 or x1 . ndim != 2 or x1 . shape [ 0 ] != 2 ) : raise TypeError ( "set_mapping requires array inputs of shape " "(2, N)." ) denom = x0 [ 1 ] - x0 [ 0 ] mask = denom == 0 denom [ mask ] = 1.0 s = ( x1 [ 1 ] - x1 [ 0 ] ) / denom s [ mask ] = 1.0 s [ x0 [ 1 ] == x0 [ 0 ] ] = 1.0 t = x1 [ 0 ] - s * x0 [ 0 ] s = as_vec4 ( s , default = ( 1 , 1 , 1 , 1 ) ) t = as_vec4 ( t , default = ( 0 , 0 , 0 , 0 ) ) self . _set_st ( scale = s , translate = t , update = update )
|
Configure this transform such that it maps points x0 = > x1
|
3,030 |
def translate ( self , pos ) : self . matrix = np . dot ( self . matrix , transforms . translate ( pos [ 0 , : 3 ] ) )
|
Translate the matrix
|
3,031 |
def scale ( self , scale , center = None ) : scale = transforms . scale ( as_vec4 ( scale , default = ( 1 , 1 , 1 , 1 ) ) [ 0 , : 3 ] ) if center is not None : center = as_vec4 ( center ) [ 0 , : 3 ] scale = np . dot ( np . dot ( transforms . translate ( - center ) , scale ) , transforms . translate ( center ) ) self . matrix = np . dot ( self . matrix , scale )
|
Scale the matrix about a given origin .
|
3,032 |
def rotate ( self , angle , axis ) : self . matrix = np . dot ( self . matrix , transforms . rotate ( angle , axis ) )
|
Rotate the matrix by some angle about a given axis .
|
3,033 |
def set_mapping ( self , points1 , points2 ) : self . matrix = transforms . affine_map ( points1 , points2 ) . T
|
Set to a 3D transformation matrix that maps points1 onto points2 .
|
3,034 |
def set_ortho ( self , l , r , b , t , n , f ) : self . matrix = transforms . ortho ( l , r , b , t , n , f )
|
Set ortho transform
|
3,035 |
def set_perspective ( self , fov , aspect , near , far ) : self . matrix = transforms . perspective ( fov , aspect , near , far )
|
Set the perspective
|
3,036 |
def set_frustum ( self , l , r , b , t , n , f ) : self . matrix = transforms . frustum ( l , r , b , t , n , f )
|
Set the frustum
|
3,037 |
def set_data ( self , data = None , ** kwargs ) : if data is None : pos = None else : if isinstance ( data , tuple ) : pos = np . array ( data ) . T . astype ( np . float32 ) else : pos = np . atleast_1d ( data ) . astype ( np . float32 ) if pos . ndim == 1 : pos = pos [ : , np . newaxis ] elif pos . ndim > 2 : raise ValueError ( 'data must have at most two dimensions' ) if pos . size == 0 : pos = self . _line . pos if len ( kwargs ) == 0 : raise TypeError ( "neither line points nor line properties" "are provided" ) elif pos . shape [ 1 ] == 1 : x = np . arange ( pos . shape [ 0 ] , dtype = np . float32 ) [ : , np . newaxis ] pos = np . concatenate ( ( x , pos ) , axis = 1 ) elif pos . shape [ 1 ] > 3 : raise TypeError ( "Too many coordinates given (%s; max is 3)." % pos . shape [ 1 ] ) line_kwargs = { } for k in self . _line_kwargs : if k in kwargs : k_ = self . _kw_trans [ k ] if k in self . _kw_trans else k line_kwargs [ k ] = kwargs . pop ( k_ ) if pos is not None or len ( line_kwargs ) > 0 : self . _line . set_data ( pos = pos , ** line_kwargs ) marker_kwargs = { } for k in self . _marker_kwargs : if k in kwargs : k_ = self . _kw_trans [ k ] if k in self . _kw_trans else k marker_kwargs [ k_ ] = kwargs . pop ( k ) if pos is not None or len ( marker_kwargs ) > 0 : self . _markers . set_data ( pos = pos , ** marker_kwargs ) if len ( kwargs ) > 0 : raise TypeError ( "Invalid keyword arguments: %s" % kwargs . keys ( ) )
|
Set the line data
|
3,038 |
def curve3_bezier ( p1 , p2 , p3 ) : x1 , y1 = p1 x2 , y2 = p2 x3 , y3 = p3 points = [ ] _curve3_recursive_bezier ( points , x1 , y1 , x2 , y2 , x3 , y3 ) dx , dy = points [ 0 ] [ 0 ] - x1 , points [ 0 ] [ 1 ] - y1 if ( dx * dx + dy * dy ) > 1e-10 : points . insert ( 0 , ( x1 , y1 ) ) dx , dy = points [ - 1 ] [ 0 ] - x3 , points [ - 1 ] [ 1 ] - y3 if ( dx * dx + dy * dy ) > 1e-10 : points . append ( ( x3 , y3 ) ) return np . array ( points ) . reshape ( len ( points ) , 2 )
|
Generate the vertices for a quadratic Bezier curve .
|
3,039 |
def curve4_bezier ( p1 , p2 , p3 , p4 ) : x1 , y1 = p1 x2 , y2 = p2 x3 , y3 = p3 x4 , y4 = p4 points = [ ] _curve4_recursive_bezier ( points , x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ) dx , dy = points [ 0 ] [ 0 ] - x1 , points [ 0 ] [ 1 ] - y1 if ( dx * dx + dy * dy ) > 1e-10 : points . insert ( 0 , ( x1 , y1 ) ) dx , dy = points [ - 1 ] [ 0 ] - x4 , points [ - 1 ] [ 1 ] - y4 if ( dx * dx + dy * dy ) > 1e-10 : points . append ( ( x4 , y4 ) ) return np . array ( points ) . reshape ( len ( points ) , 2 )
|
Generate the vertices for a third order Bezier curve .
|
3,040 |
def render_to_texture ( self , data , texture , offset , size ) : assert isinstance ( texture , Texture2D ) set_state ( blend = False , depth_test = False ) orig_tex = Texture2D ( 255 - data , format = 'luminance' , wrapping = 'clamp_to_edge' , interpolation = 'nearest' ) edf_neg_tex = self . _render_edf ( orig_tex ) orig_tex [ : , : , 0 ] = data edf_pos_tex = self . _render_edf ( orig_tex ) self . program_insert [ 'u_texture' ] = orig_tex self . program_insert [ 'u_pos_texture' ] = edf_pos_tex self . program_insert [ 'u_neg_texture' ] = edf_neg_tex self . fbo_to [ - 1 ] . color_buffer = texture with self . fbo_to [ - 1 ] : set_viewport ( tuple ( offset ) + tuple ( size ) ) self . program_insert . draw ( 'triangle_strip' )
|
Render a SDF to a texture at a given offset and size
|
3,041 |
def _render_edf ( self , orig_tex ) : sdf_size = orig_tex . shape [ : 2 ] comp_texs = [ ] for _ in range ( 2 ) : tex = Texture2D ( sdf_size + ( 4 , ) , format = 'rgba' , interpolation = 'nearest' , wrapping = 'clamp_to_edge' ) comp_texs . append ( tex ) self . fbo_to [ 0 ] . color_buffer = comp_texs [ 0 ] self . fbo_to [ 1 ] . color_buffer = comp_texs [ 1 ] for program in self . programs [ 1 : ] : program [ 'u_texh' ] , program [ 'u_texw' ] = sdf_size last_rend = 0 with self . fbo_to [ last_rend ] : set_viewport ( 0 , 0 , sdf_size [ 1 ] , sdf_size [ 0 ] ) self . program_seed [ 'u_texture' ] = orig_tex self . program_seed . draw ( 'triangle_strip' ) stepsize = ( np . array ( sdf_size ) // 2 ) . max ( ) while stepsize > 0 : self . program_flood [ 'u_step' ] = stepsize self . program_flood [ 'u_texture' ] = comp_texs [ last_rend ] last_rend = 1 if last_rend == 0 else 0 with self . fbo_to [ last_rend ] : set_viewport ( 0 , 0 , sdf_size [ 1 ] , sdf_size [ 0 ] ) self . program_flood . draw ( 'triangle_strip' ) stepsize //= 2 return comp_texs [ last_rend ]
|
Render an EDF to a texture
|
3,042 |
def _add_intent_interactive ( self , intent_num = 0 ) : print ( "Name of intent number : " , intent_num ) slot_type_mappings = load_builtin_slots ( ) intent_name = read_from_user ( str ) print ( "How many slots?" ) num_slots = read_from_user ( int ) slot_list = [ ] for i in range ( num_slots ) : print ( "Slot name no." , i + 1 ) slot_name = read_from_user ( str ) . strip ( ) print ( "Slot type? Enter a number for AMAZON supported types below," "else enter a string for a Custom Slot" ) print ( json . dumps ( slot_type_mappings , indent = True ) ) slot_type_str = read_from_user ( str ) try : slot_type = slot_type_mappings [ int ( slot_type_str ) ] [ 'name' ] except : slot_type = slot_type_str slot_list += [ self . build_slot ( slot_name , slot_type ) ] self . add_intent ( intent_name , slot_list )
|
Interactively add a new intent to the intent schema object
|
3,043 |
def from_filename ( self , filename ) : if os . path . exists ( filename ) : with open ( filename ) as fp : return IntentSchema ( json . load ( fp , object_pairs_hook = OrderedDict ) ) else : print ( 'File does not exist' ) return IntentSchema ( )
|
Build an IntentSchema from a file path creates a new intent schema if the file does not exist throws an error if the file exists but cannot be loaded as a JSON
|
3,044 |
def launch_request_handler ( request ) : user_id = request . access_token ( ) if user_id in twitter_cache . users ( ) : user_cache = twitter_cache . get_user_state ( user_id ) user_cache [ "amzn_id" ] = request . user_id ( ) base_message = "Welcome to Twitter, {} . How may I help you today ?" . format ( user_cache [ "screen_name" ] ) print ( user_cache ) if 'pending_action' in user_cache : base_message += " You have one pending action . " print ( "Found pending action" ) if 'description' in user_cache [ 'pending_action' ] : print ( "Found description" ) base_message += user_cache [ 'pending_action' ] [ 'description' ] return r . create_response ( base_message ) card = r . create_card ( title = "Please log into twitter" , card_type = "LinkAccount" ) return r . create_response ( message = "Welcome to twitter, looks like you haven't logged in!" " Log in via the alexa app." , card_obj = card , end_session = True )
|
Annotate functions with
|
3,045 |
def post_tweet_intent_handler ( request ) : tweet = request . get_slot_value ( "Tweet" ) tweet = tweet if tweet else "" if tweet : user_state = twitter_cache . get_user_state ( request . access_token ( ) ) def action ( ) : return post_tweet ( request . access_token ( ) , tweet ) message = "I am ready to post the tweet, {} ,\n Please say yes to confirm or stop to cancel ." . format ( tweet ) user_state [ 'pending_action' ] = { "action" : action , "description" : message } return r . create_response ( message = message , end_session = False ) else : message = " " . join ( [ "I'm sorry, I couldn't understand what you wanted to tweet ." , "Please prepend the message with either post or tweet ." ] ) return alexa . create_response ( message = message , end_session = False )
|
Use the intent field in the VoiceHandler to map to the respective intent .
|
3,046 |
def tweet_list_handler ( request , tweet_list_builder , msg_prefix = "" ) : tweets = tweet_list_builder ( request . access_token ( ) ) print ( len ( tweets ) , 'tweets found' ) if tweets : twitter_cache . initialize_user_queue ( user_id = request . access_token ( ) , queue = tweets ) text_to_read_out = twitter_cache . user_queue ( request . access_token ( ) ) . read_out_next ( MAX_RESPONSE_TWEETS ) message = msg_prefix + text_to_read_out + ", say 'next' to hear more, or reply to a tweet by number." return alexa . create_response ( message = message , end_session = False ) else : return alexa . create_response ( message = "Sorry, no tweets found, please try something else" , end_session = False )
|
This is a generic function to handle any intent that reads out a list of tweets
|
3,047 |
def focused_on_tweet ( request ) : slots = request . get_slot_map ( ) if "Index" in slots and slots [ "Index" ] : index = int ( slots [ 'Index' ] ) elif "Ordinal" in slots and slots [ "Index" ] : parse_ordinal = lambda inp : int ( "" . join ( [ l for l in inp if l in string . digits ] ) ) index = parse_ordinal ( slots [ 'Ordinal' ] ) else : return False index = index - 1 user_state = twitter_cache . get_user_state ( request . access_token ( ) ) queue = user_state [ 'user_queue' ] . queue ( ) if index < len ( queue ) : tweet_to_analyze = queue [ index ] user_state [ 'focus_tweet' ] = tweet_to_analyze return index + 1 twitter_cache . serialize ( ) return False
|
Return index if focused on tweet False if couldn t
|
3,048 |
def next_intent_handler ( request ) : message = "Sorry, couldn't find anything in your next queue" end_session = True if True : user_queue = twitter_cache . user_queue ( request . access_token ( ) ) if not user_queue . is_finished ( ) : message = user_queue . read_out_next ( MAX_RESPONSE_TWEETS ) if not user_queue . is_finished ( ) : end_session = False message = message + ". Please, say 'next' if you want me to read out more. " return alexa . create_response ( message = message , end_session = end_session )
|
Takes care of things whenver the user says next
|
3,049 |
def set_data ( self , vertices = None , faces = None , vertex_colors = None , face_colors = None , color = None , meshdata = None ) : if meshdata is not None : self . _meshdata = meshdata else : self . _meshdata = MeshData ( vertices = vertices , faces = faces , vertex_colors = vertex_colors , face_colors = face_colors ) self . _bounds = self . _meshdata . get_bounds ( ) if color is not None : self . _color = Color ( color ) self . mesh_data_changed ( )
|
Set the mesh data
|
3,050 |
def bounds ( self , axis , view = None ) : if view is None : view = self if axis not in self . _vshare . bounds : self . _vshare . bounds [ axis ] = self . _compute_bounds ( axis , view ) return self . _vshare . bounds [ axis ]
|
Get the bounds of the Visual
|
3,051 |
def _get_hook ( self , shader , name ) : assert name in ( 'pre' , 'post' ) key = ( shader , name ) if key in self . _hooks : return self . _hooks [ key ] hook = StatementList ( ) if shader == 'vert' : self . view_program . vert [ name ] = hook elif shader == 'frag' : self . view_program . frag [ name ] = hook self . _hooks [ key ] = hook return hook
|
Return a FunctionChain that Filters may use to modify the program .
|
3,052 |
def add_subvisual ( self , visual ) : visual . transforms = self . transforms visual . _prepare_transforms ( visual ) self . _subvisuals . append ( visual ) visual . events . update . connect ( self . _subv_update ) self . update ( )
|
Add a subvisual
|
3,053 |
def remove_subvisual ( self , visual ) : visual . events . update . disconnect ( self . _subv_update ) self . _subvisuals . remove ( visual ) self . update ( )
|
Remove a subvisual
|
3,054 |
def draw ( self ) : if not self . visible : return if self . _prepare_draw ( view = self ) is False : return for v in self . _subvisuals : if v . visible : v . draw ( )
|
Draw the visual
|
3,055 |
def checkPos ( self ) : soup = BeautifulSoup ( self . css1 ( path [ 'movs-table' ] ) . html , 'html.parser' ) poss = [ ] for label in soup . find_all ( "tr" ) : pos_id = label [ 'id' ] pos_list = [ x for x in self . positions if x . id == pos_id ] if pos_list : pos = pos_list [ 0 ] pos . update ( label ) else : pos = self . new_pos ( label ) pos . get_gain ( ) poss . append ( pos ) self . positions . clear ( ) self . positions . extend ( poss ) logger . debug ( "%d positions update" % len ( poss ) ) return self . positions
|
check all positions
|
3,056 |
def checkStock ( self ) : if not self . preferences : logger . debug ( "no preferences" ) return None soup = BeautifulSoup ( self . xpath ( path [ 'stock-table' ] ) [ 0 ] . html , "html.parser" ) count = 0 for product in soup . select ( "div.tradebox" ) : prod_name = product . select ( "span.instrument-name" ) [ 0 ] . text stk_name = [ x for x in self . preferences if x . lower ( ) in prod_name . lower ( ) ] if not stk_name : continue name = prod_name if not [ x for x in self . stocks if x . product == name ] : self . stocks . append ( Stock ( name ) ) stock = [ x for x in self . stocks if x . product == name ] [ 0 ] if 'tradebox-market-closed' in product [ 'class' ] : stock . market = False if not stock . market : logger . debug ( "market closed for %s" % stock . product ) continue sell_price = product . select ( "div.tradebox-price-sell" ) [ 0 ] . text buy_price = product . select ( "div.tradebox-price-buy" ) [ 0 ] . text sent = int ( product . select ( path [ 'sent' ] ) [ 0 ] . text . strip ( '%' ) ) / 100 stock . new_rec ( [ sell_price , buy_price , sent ] ) count += 1 logger . debug ( f"added %d stocks" % count ) return self . stocks
|
check stocks in preference
|
3,057 |
def clearPrefs ( self ) : self . preferences . clear ( ) tradebox_num = len ( self . css ( 'div.tradebox' ) ) for i in range ( tradebox_num ) : self . xpath ( path [ 'trade-box' ] ) [ 0 ] . right_click ( ) self . css1 ( 'div.item-trade-contextmenu-list-remove' ) . click ( ) logger . info ( "cleared preferences" )
|
clear the left panel and preferences
|
3,058 |
def addPrefs ( self , prefs = [ ] ) : if len ( prefs ) == len ( self . preferences ) == 0 : logger . debug ( "no preferences" ) return None self . preferences . extend ( prefs ) self . css1 ( path [ 'search-btn' ] ) . click ( ) count = 0 for pref in self . preferences : self . css1 ( path [ 'search-pref' ] ) . fill ( pref ) self . css1 ( path [ 'pref-icon' ] ) . click ( ) btn = self . css1 ( 'div.add-to-watchlist-popup-item .icon-wrapper' ) if not self . css1 ( 'svg' , btn ) [ 'class' ] is None : btn . click ( ) count += 1 self . css1 ( path [ 'pref-icon' ] ) . click ( ) self . css1 ( path [ 'back-btn' ] ) . click ( ) self . css1 ( path [ 'back-btn' ] ) . click ( ) logger . debug ( "updated %d preferences" % count ) return self . preferences
|
add preference in self . preferences
|
3,059 |
def _load_glyph ( f , char , glyphs_dict ) : from . . . ext . freetype import ( FT_LOAD_RENDER , FT_LOAD_NO_HINTING , FT_LOAD_NO_AUTOHINT ) flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT face = _load_font ( f [ 'face' ] , f [ 'bold' ] , f [ 'italic' ] ) face . set_char_size ( f [ 'size' ] * 64 ) face . load_char ( char , flags ) bitmap = face . glyph . bitmap width = face . glyph . bitmap . width height = face . glyph . bitmap . rows bitmap = np . array ( bitmap . buffer ) w0 = bitmap . size // height if bitmap . size > 0 else 0 bitmap . shape = ( height , w0 ) bitmap = bitmap [ : , : width ] . astype ( np . ubyte ) left = face . glyph . bitmap_left top = face . glyph . bitmap_top advance = face . glyph . advance . x / 64. glyph = dict ( char = char , offset = ( left , top ) , bitmap = bitmap , advance = advance , kerning = { } ) glyphs_dict [ char ] = glyph for other_char , other_glyph in glyphs_dict . items ( ) : kerning = face . get_kerning ( other_char , char ) glyph [ 'kerning' ] [ other_char ] = kerning . x / 64. kerning = face . get_kerning ( char , other_char ) other_glyph [ 'kerning' ] [ char ] = kerning . x / 64.
|
Load glyph from font into dict
|
3,060 |
def _set_clipper ( self , node , clipper ) : if node in self . _clippers : self . detach ( self . _clippers . pop ( node ) ) if clipper is not None : self . attach ( clipper ) self . _clippers [ node ] = clipper
|
Assign a clipper that is inherited from a parent node .
|
3,061 |
def cfnumber_to_number ( cfnumber ) : numeric_type = cf . CFNumberGetType ( cfnumber ) cfnum_to_ctype = { kCFNumberSInt8Type : c_int8 , kCFNumberSInt16Type : c_int16 , kCFNumberSInt32Type : c_int32 , kCFNumberSInt64Type : c_int64 , kCFNumberFloat32Type : c_float , kCFNumberFloat64Type : c_double , kCFNumberCharType : c_byte , kCFNumberShortType : c_short , kCFNumberIntType : c_int , kCFNumberLongType : c_long , kCFNumberLongLongType : c_longlong , kCFNumberFloatType : c_float , kCFNumberDoubleType : c_double , kCFNumberCFIndexType : CFIndex , kCFNumberCGFloatType : CGFloat } if numeric_type in cfnum_to_ctype : t = cfnum_to_ctype [ numeric_type ] result = t ( ) if cf . CFNumberGetValue ( cfnumber , numeric_type , byref ( result ) ) : return result . value else : raise Exception ( 'cfnumber_to_number: unhandled CFNumber type %d' % numeric_type )
|
Convert CFNumber to python int or float .
|
3,062 |
def cftype_to_value ( cftype ) : if not cftype : return None typeID = cf . CFGetTypeID ( cftype ) if typeID in known_cftypes : convert_function = known_cftypes [ typeID ] return convert_function ( cftype ) else : return cftype
|
Convert a CFType into an equivalent python type . The convertible CFTypes are taken from the known_cftypes dictionary which may be added to if another library implements its own conversion methods .
|
3,063 |
def cfset_to_set ( cfset ) : count = cf . CFSetGetCount ( cfset ) buffer = ( c_void_p * count ) ( ) cf . CFSetGetValues ( cfset , byref ( buffer ) ) return set ( [ cftype_to_value ( c_void_p ( buffer [ i ] ) ) for i in range ( count ) ] )
|
Convert CFSet to python set .
|
3,064 |
def cfarray_to_list ( cfarray ) : count = cf . CFArrayGetCount ( cfarray ) return [ cftype_to_value ( c_void_p ( cf . CFArrayGetValueAtIndex ( cfarray , i ) ) ) for i in range ( count ) ]
|
Convert CFArray to python list .
|
3,065 |
def ctype_for_encoding ( self , encoding ) : if encoding in self . typecodes : return self . typecodes [ encoding ] elif encoding [ 0 : 1 ] == b'^' and encoding [ 1 : ] in self . typecodes : return POINTER ( self . typecodes [ encoding [ 1 : ] ] ) elif encoding [ 0 : 1 ] == b'^' and encoding [ 1 : ] in [ CGImageEncoding , NSZoneEncoding ] : return c_void_p elif encoding [ 0 : 1 ] == b'r' and encoding [ 1 : ] in self . typecodes : return self . typecodes [ encoding [ 1 : ] ] elif encoding [ 0 : 2 ] == b'r^' and encoding [ 2 : ] in self . typecodes : return POINTER ( self . typecodes [ encoding [ 2 : ] ] ) else : raise Exception ( 'unknown encoding for %s: %s' % ( self . name , encoding ) )
|
Return ctypes type for an encoded Objective - C type .
|
3,066 |
def classmethod ( self , encoding ) : encoding = ensure_bytes ( encoding ) typecodes = parse_type_encoding ( encoding ) typecodes . insert ( 1 , b'@:' ) encoding = b'' . join ( typecodes ) def decorator ( f ) : def objc_class_method ( objc_cls , objc_cmd , * args ) : py_cls = ObjCClass ( objc_cls ) py_cls . objc_cmd = objc_cmd args = convert_method_arguments ( encoding , args ) result = f ( py_cls , * args ) if isinstance ( result , ObjCClass ) : result = result . ptr . value elif isinstance ( result , ObjCInstance ) : result = result . ptr . value return result name = f . __name__ . replace ( '_' , ':' ) self . add_class_method ( objc_class_method , name , encoding ) return objc_class_method return decorator
|
Function decorator for class methods .
|
3,067 |
def get_frag_shader ( volumes , clipped = False , n_volume_max = 5 ) : declarations = "" before_loop = "" in_loop = "" after_loop = "" for index in range ( n_volume_max ) : declarations += "uniform $sampler_type u_volumetex_{0:d};\n" . format ( index ) before_loop += "dummy = $sample(u_volumetex_{0:d}, loc).g;\n" . format ( index ) declarations += "uniform $sampler_type dummy1;\n" declarations += "float dummy;\n" for label in sorted ( volumes ) : index = volumes [ label ] [ 'index' ] declarations += "uniform float u_weight_{0:d};\n" . format ( index ) declarations += "uniform int u_enabled_{0:d};\n" . format ( index ) before_loop += "float max_val_{0:d} = 0;\n" . format ( index ) in_loop += "if(u_enabled_{0:d} == 1) {{\n\n" . format ( index ) if clipped : in_loop += ( "if(loc.r > u_clip_min.r && loc.r < u_clip_max.r &&\n" " loc.g > u_clip_min.g && loc.g < u_clip_max.g &&\n" " loc.b > u_clip_min.b && loc.b < u_clip_max.b) {\n\n" ) in_loop += "// Sample texture for layer {0}\n" . format ( label ) in_loop += "val = $sample(u_volumetex_{0:d}, loc).g;\n" . format ( index ) if volumes [ label ] . get ( 'multiply' ) is not None : index_other = volumes [ volumes [ label ] [ 'multiply' ] ] [ 'index' ] in_loop += ( "if (val != 0) {{ val *= $sample(u_volumetex_{0:d}, loc).g; }}\n" . format ( index_other ) ) in_loop += "max_val_{0:d} = max(val, max_val_{0:d});\n\n" . format ( index ) if clipped : in_loop += "}\n\n" in_loop += "}\n\n" after_loop += "// Compute final color for layer {0}\n" . format ( label ) after_loop += ( "color = $cmap{0:d}(max_val_{0:d});\n" "color.a *= u_weight_{0:d};\n" "total_color += color.a * color;\n" "max_alpha = max(color.a, max_alpha);\n" "count += color.a;\n\n" ) . format ( index ) if not clipped : before_loop += "\nfloat val3 = u_clip_min.g + u_clip_max.g;\n\n" before_loop = indent ( before_loop , " " * 4 ) . strip ( ) in_loop = indent ( in_loop , " " * 16 ) . strip ( ) after_loop = indent ( after_loop , " " * 4 ) . strip ( ) return FRAG_SHADER . format ( declarations = declarations , before_loop = before_loop , in_loop = in_loop , after_loop = after_loop )
|
Get the fragment shader code - we use the shader_program object to determine which layers are enabled and therefore what to include in the shader code .
|
3,068 |
def eglGetDisplay ( display = EGL_DEFAULT_DISPLAY ) : res = _lib . eglGetDisplay ( display ) if not res or res == EGL_NO_DISPLAY : raise RuntimeError ( 'Could not create display' ) return res
|
Connect to the EGL display server .
|
3,069 |
def eglInitialize ( display ) : majorVersion = ( _c_int * 1 ) ( ) minorVersion = ( _c_int * 1 ) ( ) res = _lib . eglInitialize ( display , majorVersion , minorVersion ) if res == EGL_FALSE : raise RuntimeError ( 'Could not initialize' ) return majorVersion [ 0 ] , minorVersion [ 0 ]
|
Initialize EGL and return EGL version tuple .
|
3,070 |
def eglQueryString ( display , name ) : out = _lib . eglQueryString ( display , name ) if not out : raise RuntimeError ( 'Could not query %s' % name ) return out
|
Query string from display
|
3,071 |
def set_faces ( self , faces ) : self . _faces = faces self . _edges = None self . _edges_indexed_by_faces = None self . _vertex_faces = None self . _vertices_indexed_by_faces = None self . reset_normals ( ) self . _vertex_colors_indexed_by_faces = None self . _face_colors_indexed_by_faces = None
|
Set the faces
|
3,072 |
def get_vertices ( self , indexed = None ) : if indexed is None : if ( self . _vertices is None and self . _vertices_indexed_by_faces is not None ) : self . _compute_unindexed_vertices ( ) return self . _vertices elif indexed == 'faces' : if ( self . _vertices_indexed_by_faces is None and self . _vertices is not None ) : self . _vertices_indexed_by_faces = self . _vertices [ self . get_faces ( ) ] return self . _vertices_indexed_by_faces else : raise Exception ( "Invalid indexing mode. Accepts: None, 'faces'" )
|
Get the vertices
|
3,073 |
def get_bounds ( self ) : if self . _vertices_indexed_by_faces is not None : v = self . _vertices_indexed_by_faces elif self . _vertices is not None : v = self . _vertices else : return None bounds = [ ( v [ : , ax ] . min ( ) , v [ : , ax ] . max ( ) ) for ax in range ( v . shape [ 1 ] ) ] return bounds
|
Get the mesh bounds
|
3,074 |
def set_vertices ( self , verts = None , indexed = None , reset_normals = True ) : if indexed is None : if verts is not None : self . _vertices = verts self . _vertices_indexed_by_faces = None elif indexed == 'faces' : self . _vertices = None if verts is not None : self . _vertices_indexed_by_faces = verts else : raise Exception ( "Invalid indexing mode. Accepts: None, 'faces'" ) if reset_normals : self . reset_normals ( )
|
Set the mesh vertices
|
3,075 |
def has_vertex_color ( self ) : for v in ( self . _vertex_colors , self . _vertex_colors_indexed_by_faces , self . _vertex_colors_indexed_by_edges ) : if v is not None : return True return False
|
Return True if this data set has vertex color information
|
3,076 |
def has_face_color ( self ) : for v in ( self . _face_colors , self . _face_colors_indexed_by_faces , self . _face_colors_indexed_by_edges ) : if v is not None : return True return False
|
Return True if this data set has face color information
|
3,077 |
def get_face_normals ( self , indexed = None ) : if self . _face_normals is None : v = self . get_vertices ( indexed = 'faces' ) self . _face_normals = np . cross ( v [ : , 1 ] - v [ : , 0 ] , v [ : , 2 ] - v [ : , 0 ] ) if indexed is None : return self . _face_normals elif indexed == 'faces' : if self . _face_normals_indexed_by_faces is None : norms = np . empty ( ( self . _face_normals . shape [ 0 ] , 3 , 3 ) , dtype = np . float32 ) norms [ : ] = self . _face_normals [ : , np . newaxis , : ] self . _face_normals_indexed_by_faces = norms return self . _face_normals_indexed_by_faces else : raise Exception ( "Invalid indexing mode. Accepts: None, 'faces'" )
|
Get face normals
|
3,078 |
def get_vertex_normals ( self , indexed = None ) : if self . _vertex_normals is None : faceNorms = self . get_face_normals ( ) vertFaces = self . get_vertex_faces ( ) self . _vertex_normals = np . empty ( self . _vertices . shape , dtype = np . float32 ) for vindex in xrange ( self . _vertices . shape [ 0 ] ) : faces = vertFaces [ vindex ] if len ( faces ) == 0 : self . _vertex_normals [ vindex ] = ( 0 , 0 , 0 ) continue norms = faceNorms [ faces ] norm = norms . sum ( axis = 0 ) renorm = ( norm ** 2 ) . sum ( ) ** 0.5 if renorm > 0 : norm /= renorm self . _vertex_normals [ vindex ] = norm if indexed is None : return self . _vertex_normals elif indexed == 'faces' : return self . _vertex_normals [ self . get_faces ( ) ] else : raise Exception ( "Invalid indexing mode. Accepts: None, 'faces'" )
|
Get vertex normals
|
3,079 |
def get_vertex_colors ( self , indexed = None ) : if indexed is None : return self . _vertex_colors elif indexed == 'faces' : if self . _vertex_colors_indexed_by_faces is None : self . _vertex_colors_indexed_by_faces = self . _vertex_colors [ self . get_faces ( ) ] return self . _vertex_colors_indexed_by_faces else : raise Exception ( "Invalid indexing mode. Accepts: None, 'faces'" )
|
Get vertex colors
|
3,080 |
def set_vertex_colors ( self , colors , indexed = None ) : colors = _fix_colors ( np . asarray ( colors ) ) if indexed is None : if colors . ndim != 2 : raise ValueError ( 'colors must be 2D if indexed is None' ) if colors . shape [ 0 ] != self . n_vertices : raise ValueError ( 'incorrect number of colors %s, expected %s' % ( colors . shape [ 0 ] , self . n_vertices ) ) self . _vertex_colors = colors self . _vertex_colors_indexed_by_faces = None elif indexed == 'faces' : if colors . ndim != 3 : raise ValueError ( 'colors must be 3D if indexed is "faces"' ) if colors . shape [ 0 ] != self . n_faces : raise ValueError ( 'incorrect number of faces' ) self . _vertex_colors = None self . _vertex_colors_indexed_by_faces = colors else : raise ValueError ( 'indexed must be None or "faces"' )
|
Set the vertex color array
|
3,081 |
def get_face_colors ( self , indexed = None ) : if indexed is None : return self . _face_colors elif indexed == 'faces' : if ( self . _face_colors_indexed_by_faces is None and self . _face_colors is not None ) : Nf = self . _face_colors . shape [ 0 ] self . _face_colors_indexed_by_faces = np . empty ( ( Nf , 3 , 4 ) , dtype = self . _face_colors . dtype ) self . _face_colors_indexed_by_faces [ : ] = self . _face_colors . reshape ( Nf , 1 , 4 ) return self . _face_colors_indexed_by_faces else : raise Exception ( "Invalid indexing mode. Accepts: None, 'faces'" )
|
Get the face colors
|
3,082 |
def set_face_colors ( self , colors , indexed = None ) : colors = _fix_colors ( colors ) if colors . shape [ 0 ] != self . n_faces : raise ValueError ( 'incorrect number of colors %s, expected %s' % ( colors . shape [ 0 ] , self . n_faces ) ) if indexed is None : if colors . ndim != 2 : raise ValueError ( 'colors must be 2D if indexed is None' ) self . _face_colors = colors self . _face_colors_indexed_by_faces = None elif indexed == 'faces' : if colors . ndim != 3 : raise ValueError ( 'colors must be 3D if indexed is "faces"' ) self . _face_colors = None self . _face_colors_indexed_by_faces = colors else : raise ValueError ( 'indexed must be None or "faces"' )
|
Set the face color array
|
3,083 |
def n_faces ( self ) : if self . _faces is not None : return self . _faces . shape [ 0 ] elif self . _vertices_indexed_by_faces is not None : return self . _vertices_indexed_by_faces . shape [ 0 ]
|
The number of faces in the mesh
|
3,084 |
def get_vertex_faces ( self ) : if self . _vertex_faces is None : self . _vertex_faces = [ [ ] for i in xrange ( len ( self . get_vertices ( ) ) ) ] for i in xrange ( self . _faces . shape [ 0 ] ) : face = self . _faces [ i ] for ind in face : self . _vertex_faces [ ind ] . append ( i ) return self . _vertex_faces
|
List mapping each vertex index to a list of face indices that use it .
|
3,085 |
def save ( self ) : import pickle if self . _faces is not None : names = [ '_vertices' , '_faces' ] else : names = [ '_vertices_indexed_by_faces' ] if self . _vertex_colors is not None : names . append ( '_vertex_colors' ) elif self . _vertex_colors_indexed_by_faces is not None : names . append ( '_vertex_colors_indexed_by_faces' ) if self . _face_colors is not None : names . append ( '_face_colors' ) elif self . _face_colors_indexed_by_faces is not None : names . append ( '_face_colors_indexed_by_faces' ) state = dict ( [ ( n , getattr ( self , n ) ) for n in names ] ) return pickle . dumps ( state )
|
Serialize this mesh to a string appropriate for disk storage
|
3,086 |
def cubehelix ( start = 0.5 , rot = 1 , gamma = 1.0 , reverse = True , nlev = 256. , minSat = 1.2 , maxSat = 1.2 , minLight = 0. , maxLight = 1. , ** kwargs ) : if kwargs is not None : if 'startHue' in kwargs : start = ( kwargs . get ( 'startHue' ) / 360. - 1. ) * 3. if 'endHue' in kwargs : rot = kwargs . get ( 'endHue' ) / 360. - start / 3. - 1. if 'sat' in kwargs : minSat = kwargs . get ( 'sat' ) maxSat = kwargs . get ( 'sat' ) fract = np . linspace ( minLight , maxLight , nlev ) angle = 2.0 * pi * ( start / 3.0 + rot * fract + 1. ) fract = fract ** gamma satar = np . linspace ( minSat , maxSat , nlev ) amp = satar * fract * ( 1. - fract ) / 2. red = fract + amp * ( - 0.14861 * np . cos ( angle ) + 1.78277 * np . sin ( angle ) ) grn = fract + amp * ( - 0.29227 * np . cos ( angle ) - 0.90649 * np . sin ( angle ) ) blu = fract + amp * ( 1.97294 * np . cos ( angle ) ) red [ np . where ( ( red > 1. ) ) ] = 1. grn [ np . where ( ( grn > 1. ) ) ] = 1. blu [ np . where ( ( blu > 1. ) ) ] = 1. red [ np . where ( ( red < 0. ) ) ] = 0. grn [ np . where ( ( grn < 0. ) ) ] = 0. blu [ np . where ( ( blu < 0. ) ) ] = 0. if reverse is True : red = red [ : : - 1 ] blu = blu [ : : - 1 ] grn = grn [ : : - 1 ] return np . array ( ( red , grn , blu ) ) . T
|
A full implementation of Dave Green s cubehelix for Matplotlib . Based on the FORTRAN 77 code provided in D . A . Green 2011 BASI 39 289 .
|
3,087 |
def color_to_hex ( color ) : if color is None or colorConverter . to_rgba ( color ) [ 3 ] == 0 : return 'none' else : rgb = colorConverter . to_rgb ( color ) return '#{0:02X}{1:02X}{2:02X}' . format ( * ( int ( 255 * c ) for c in rgb ) )
|
Convert matplotlib color code to hex color code
|
3,088 |
def _many_to_one ( input_dict ) : return dict ( ( key , val ) for keys , val in input_dict . items ( ) for key in keys )
|
Convert a many - to - one mapping to a one - to - one mapping
|
3,089 |
def get_dasharray ( obj ) : if obj . __dict__ . get ( '_dashSeq' , None ) is not None : return ',' . join ( map ( str , obj . _dashSeq ) ) else : ls = obj . get_linestyle ( ) dasharray = LINESTYLES . get ( ls , 'not found' ) if dasharray == 'not found' : warnings . warn ( "line style '{0}' not understood: " "defaulting to solid line." . format ( ls ) ) dasharray = LINESTYLES [ 'solid' ] return dasharray
|
Get an SVG dash array for the given matplotlib linestyle
|
3,090 |
def SVG_path ( path , transform = None , simplify = False ) : if transform is not None : path = path . transformed ( transform ) vc_tuples = [ ( vertices if path_code != Path . CLOSEPOLY else [ ] , PATH_DICT [ path_code ] ) for ( vertices , path_code ) in path . iter_segments ( simplify = simplify ) ] if not vc_tuples : return np . zeros ( ( 0 , 2 ) ) , [ ] else : vertices , codes = zip ( * vc_tuples ) vertices = np . array ( list ( itertools . chain ( * vertices ) ) ) . reshape ( - 1 , 2 ) return vertices , list ( codes )
|
Construct the vertices and SVG codes for the path
|
3,091 |
def get_path_style ( path , fill = True ) : style = { } style [ 'alpha' ] = path . get_alpha ( ) if style [ 'alpha' ] is None : style [ 'alpha' ] = 1 style [ 'edgecolor' ] = color_to_hex ( path . get_edgecolor ( ) ) if fill : style [ 'facecolor' ] = color_to_hex ( path . get_facecolor ( ) ) else : style [ 'facecolor' ] = 'none' style [ 'edgewidth' ] = path . get_linewidth ( ) style [ 'dasharray' ] = get_dasharray ( path ) style [ 'zorder' ] = path . get_zorder ( ) return style
|
Get the style dictionary for matplotlib path objects
|
3,092 |
def get_line_style ( line ) : style = { } style [ 'alpha' ] = line . get_alpha ( ) if style [ 'alpha' ] is None : style [ 'alpha' ] = 1 style [ 'color' ] = color_to_hex ( line . get_color ( ) ) style [ 'linewidth' ] = line . get_linewidth ( ) style [ 'dasharray' ] = get_dasharray ( line ) style [ 'zorder' ] = line . get_zorder ( ) return style
|
Get the style dictionary for matplotlib line objects
|
3,093 |
def get_marker_style ( line ) : style = { } style [ 'alpha' ] = line . get_alpha ( ) if style [ 'alpha' ] is None : style [ 'alpha' ] = 1 style [ 'facecolor' ] = color_to_hex ( line . get_markerfacecolor ( ) ) style [ 'edgecolor' ] = color_to_hex ( line . get_markeredgecolor ( ) ) style [ 'edgewidth' ] = line . get_markeredgewidth ( ) style [ 'marker' ] = line . get_marker ( ) markerstyle = MarkerStyle ( line . get_marker ( ) ) markersize = line . get_markersize ( ) markertransform = ( markerstyle . get_transform ( ) + Affine2D ( ) . scale ( markersize , - markersize ) ) style [ 'markerpath' ] = SVG_path ( markerstyle . get_path ( ) , markertransform ) style [ 'markersize' ] = markersize style [ 'zorder' ] = line . get_zorder ( ) return style
|
Get the style dictionary for matplotlib marker objects
|
3,094 |
def get_text_style ( text ) : style = { } style [ 'alpha' ] = text . get_alpha ( ) if style [ 'alpha' ] is None : style [ 'alpha' ] = 1 style [ 'fontsize' ] = text . get_size ( ) style [ 'color' ] = color_to_hex ( text . get_color ( ) ) style [ 'halign' ] = text . get_horizontalalignment ( ) style [ 'valign' ] = text . get_verticalalignment ( ) style [ 'malign' ] = text . _multialignment style [ 'rotation' ] = text . get_rotation ( ) style [ 'zorder' ] = text . get_zorder ( ) return style
|
Return the text style dict for a text instance
|
3,095 |
def get_axis_properties ( axis ) : props = { } label1On = axis . _major_tick_kw . get ( 'label1On' , True ) if isinstance ( axis , matplotlib . axis . XAxis ) : if label1On : props [ 'position' ] = "bottom" else : props [ 'position' ] = "top" elif isinstance ( axis , matplotlib . axis . YAxis ) : if label1On : props [ 'position' ] = "left" else : props [ 'position' ] = "right" else : raise ValueError ( "{0} should be an Axis instance" . format ( axis ) ) locator = axis . get_major_locator ( ) props [ 'nticks' ] = len ( locator ( ) ) if isinstance ( locator , ticker . FixedLocator ) : props [ 'tickvalues' ] = list ( locator ( ) ) else : props [ 'tickvalues' ] = None formatter = axis . get_major_formatter ( ) if isinstance ( formatter , ticker . NullFormatter ) : props [ 'tickformat' ] = "" elif isinstance ( formatter , ticker . FixedFormatter ) : props [ 'tickformat' ] = list ( formatter . seq ) elif not any ( label . get_visible ( ) for label in axis . get_ticklabels ( ) ) : props [ 'tickformat' ] = "" else : props [ 'tickformat' ] = None props [ 'scale' ] = axis . get_scale ( ) labels = axis . get_ticklabels ( ) if labels : props [ 'fontsize' ] = labels [ 0 ] . get_fontsize ( ) else : props [ 'fontsize' ] = None props [ 'grid' ] = get_grid_style ( axis ) return props
|
Return the property dictionary for a matplotlib . Axis instance
|
3,096 |
def image_to_base64 ( image ) : ax = image . axes binary_buffer = io . BytesIO ( ) lim = ax . axis ( ) ax . axis ( image . get_extent ( ) ) image . write_png ( binary_buffer ) ax . axis ( lim ) binary_buffer . seek ( 0 ) return base64 . b64encode ( binary_buffer . read ( ) ) . decode ( 'utf-8' )
|
Convert a matplotlib image to a base64 png representation
|
3,097 |
def set_interactive ( enabled = True , app = None ) : if enabled : inputhook_manager . enable_gui ( 'vispy' , app ) else : inputhook_manager . disable_gui ( )
|
Activate the IPython hook for VisPy . If the app is not specified the default is used .
|
3,098 |
def _resize_buffers ( self , font_scale ) : new_sizes = ( font_scale , ) + self . size if new_sizes == self . _current_sizes : return self . _n_rows = int ( max ( self . size [ 1 ] / ( self . _char_height * font_scale ) , 1 ) ) self . _n_cols = int ( max ( self . size [ 0 ] / ( self . _char_width * font_scale ) , 1 ) ) self . _bytes_012 = np . zeros ( ( self . _n_rows , self . _n_cols , 3 ) , np . float32 ) self . _bytes_345 = np . zeros ( ( self . _n_rows , self . _n_cols , 3 ) , np . float32 ) pos = np . empty ( ( self . _n_rows , self . _n_cols , 2 ) , np . float32 ) C , R = np . meshgrid ( np . arange ( self . _n_cols ) , np . arange ( self . _n_rows ) ) x_off = 4. y_off = 4 - self . size [ 1 ] / font_scale pos [ ... , 0 ] = x_off + self . _char_width * C pos [ ... , 1 ] = y_off + self . _char_height * R self . _position = VertexBuffer ( pos ) for ii , line in enumerate ( self . _text_lines [ : self . _n_rows ] ) : self . _insert_text_buf ( line , ii ) self . _current_sizes = new_sizes
|
Resize buffers only if necessary
|
3,099 |
def clear ( self ) : if hasattr ( self , '_bytes_012' ) : self . _bytes_012 . fill ( 0 ) self . _bytes_345 . fill ( 0 ) self . _text_lines = [ ] * self . _n_rows self . _pending_writes = [ ]
|
Clear the console
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.