idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
38,300
def _notify_change ( self ) : d = self . declaration self . _notify_count -= 1 if self . _notify_count == 0 : self . adapter . notifyDataSetChanged ( now = True ) self . get_context ( ) . timed_call ( 500 , self . _queue_pending_calls )
After all changes have settled tell Java it changed
38,301
def set_current_index ( self , index ) : if self . _notify_count > 0 : self . _pending_calls . append ( lambda index = index : self . widget . setCurrentItem ( index ) ) else : self . widget . setCurrentItem ( index )
We can only set the index once the page has been created . otherwise we get FragmentManager is already executing transactions errors in Java . To avoid this we only call this once has been loaded .
38,302
def apply_layout ( self , child , layout ) : params = self . create_layout_params ( child , layout ) w = child . widget if w : if layout . get ( 'padding' ) : dp = self . dp l , t , r , b = layout [ 'padding' ] w . setPadding ( int ( l * dp ) , int ( t * dp ) , int ( r * dp ) , int ( b * dp ) ) child . layout_params = params
Apply the flexbox specific layout .
38,303
def get ( cls ) : app = AndroidApplication . instance ( ) f = app . create_future ( ) if cls . _instance : f . set_result ( cls . _instance ) return f def on_service ( obj_id ) : if not cls . instance ( ) : m = cls ( __id__ = obj_id ) else : m = cls . instance ( ) f . set_result ( m ) cls . from_ ( app ) . then ( on_service ) return f
Acquires the NotificationManager service async .
38,304
def show_notification ( cls , channel_id , * args , ** kwargs ) : app = AndroidApplication . instance ( ) builder = Notification . Builder ( app , channel_id ) builder . update ( * args , ** kwargs ) return builder . show ( )
Create and show a Notification . See Notification . Builder . update for a list of accepted parameters .
38,305
def init_layout ( self ) : d = self . declaration self . create_notification ( ) if d . show : self . set_show ( d . show )
Create the notification in the top down pass if show = True
38,306
def destroy ( self ) : builder = self . builder NotificationManager . cancel_notification ( builder ) del self . builder super ( AndroidNotification , self ) . destroy ( )
A reimplemented destructor that cancels the notification before destroying .
38,307
def create_notification ( self ) : d = self . declaration builder = self . builder = Notification . Builder ( self . get_context ( ) , d . channel_id ) d = self . declaration if d . settings : builder . update ( ** d . settings ) for k , v in self . get_declared_items ( ) : handler = getattr ( self , 'set_{}' . format ( k ) ) handler ( v ) builder . setSmallIcon ( d . icon or '@mipmap/ic_launcher' ) for view in self . child_widgets ( ) : builder . setCustomContentView ( view ) break
Instead of the typical create_widget we use create_notification because after it s closed it needs created again .
38,308
def create_widget ( self ) : d = self . declaration button_type = UIButton . UIButtonTypeSystem if d . flat else UIButton . UIButtonTypeRoundedRect self . widget = UIButton ( buttonWithType = button_type )
Create the toolkit widget for the proxy object .
38,309
def init_text ( self ) : d = self . declaration if d . text : self . set_text ( d . text ) if d . text_color : self . set_text_color ( d . text_color ) if d . text_alignment : self . set_text_alignment ( d . text_alignment ) if d . font_family or d . text_size : self . refresh_font ( ) if hasattr ( d , 'max_lines' ) and d . max_lines : self . set_max_lines ( d . max_lines )
Init text properties for this widget
38,310
def update_function ( old , new ) : for name in func_attrs : try : setattr ( old , name , getattr ( new , name ) ) except ( AttributeError , TypeError ) : pass
Upgrade the code object of a function
38,311
def superreload ( module , reload = reload , old_objects = { } ) : for name , obj in list ( module . __dict__ . items ( ) ) : if not hasattr ( obj , '__module__' ) or obj . __module__ != module . __name__ : continue key = ( module . __name__ , name ) try : old_objects . setdefault ( key , [ ] ) . append ( weakref . ref ( obj ) ) except TypeError : pass try : old_dict = module . __dict__ . copy ( ) old_name = module . __name__ module . __dict__ . clear ( ) module . __dict__ [ '__name__' ] = old_name module . __dict__ [ '__loader__' ] = old_dict [ '__loader__' ] except ( TypeError , AttributeError , KeyError ) : pass try : module = reload ( module ) except : module . __dict__ . update ( old_dict ) raise for name , new_obj in list ( module . __dict__ . items ( ) ) : key = ( module . __name__ , name ) if key not in old_objects : continue new_refs = [ ] for old_ref in old_objects [ key ] : old_obj = old_ref ( ) if old_obj is None : continue new_refs . append ( old_ref ) update_generic ( old_obj , new_obj ) if new_refs : old_objects [ key ] = new_refs else : del old_objects [ key ] return module
Enhanced version of the builtin reload function .
38,312
def mark_module_skipped ( self , module_name ) : try : del self . modules [ module_name ] except KeyError : pass self . skip_modules [ module_name ] = True
Skip reloading the named module in the future
38,313
def aimport_module ( self , module_name ) : self . mark_module_reloadable ( module_name ) import_module ( module_name ) top_name = module_name . split ( '.' ) [ 0 ] top_module = sys . modules [ top_name ] return top_module , top_name
Import a module and mark it reloadable
38,314
def autoreload ( self , parameter_s = '' ) : r if parameter_s == '' : self . _reloader . check ( True ) elif parameter_s == '0' : self . _reloader . enabled = False elif parameter_s == '1' : self . _reloader . check_all = False self . _reloader . enabled = True elif parameter_s == '2' : self . _reloader . check_all = True self . _reloader . enabled = True
r %autoreload = > Reload modules automatically
38,315
def aimport ( self , parameter_s = '' , stream = None ) : modname = parameter_s if not modname : to_reload = sorted ( self . _reloader . modules . keys ( ) ) to_skip = sorted ( self . _reloader . skip_modules . keys ( ) ) if stream is None : stream = sys . stdout if self . _reloader . check_all : stream . write ( "Modules to reload:\nall-except-skipped\n" ) else : stream . write ( "Modules to reload:\n%s\n" % ' ' . join ( to_reload ) ) stream . write ( "\nModules to skip:\n%s\n" % ' ' . join ( to_skip ) ) elif modname . startswith ( '-' ) : modname = modname [ 1 : ] self . _reloader . mark_module_skipped ( modname ) else : for _module in ( [ _ . strip ( ) for _ in modname . split ( ',' ) ] ) : top_module , top_name = self . _reloader . aimport_module ( _module ) self . shell . push ( { top_name : top_module } )
%aimport = > Import modules for automatic reloading .
38,316
def post_execute ( self ) : newly_loaded_modules = set ( sys . modules ) - self . loaded_modules for modname in newly_loaded_modules : _ , pymtime = self . _reloader . filename_and_mtime ( sys . modules [ modname ] ) if pymtime is not None : self . _reloader . modules_mtimes [ modname ] = pymtime self . loaded_modules . update ( newly_loaded_modules )
Cache the modification times of any modules imported in this execution
38,317
def set_items ( self , items ) : self . adapter . clear ( ) self . adapter . addAll ( items )
Generate the view cache
38,318
def _default_objc ( self ) : objc = ctypes . cdll . LoadLibrary ( find_library ( 'objc' ) ) objc . objc_getClass . restype = ctypes . c_void_p objc . sel_registerName . restype = ctypes . c_void_p objc . objc_msgSend . restype = ctypes . c_void_p objc . objc_msgSend . argtypes = [ ctypes . c_void_p , ctypes . c_void_p ] return objc
Load the objc library using ctypes .
38,319
def _default_bridge ( self ) : objc = self . objc ENBridge = objc . objc_getClass ( 'ENBridge' ) return objc . objc_msgSend ( ENBridge , objc . sel_registerName ( 'instance' ) )
Get an instance of the ENBridge object using ctypes .
38,320
def processEvents ( self , data ) : objc = self . objc bridge = self . bridge objc . objc_msgSend . argtypes = [ ctypes . c_void_p , ctypes . c_void_p , ctypes . c_char_p , ctypes . c_int ] objc . objc_msgSend ( bridge , objc . sel_registerName ( 'processEvents:length:' ) , data , len ( data ) )
Sends msgpack data to the ENBridge instance by calling the processEvents method via ctypes .
38,321
def log_stack ( self , signal , frame ) : gen_log . warning ( 'IOLoop blocked for %f seconds in\n%s' , self . _blocking_signal_threshold , '' . join ( traceback . format_stack ( frame ) ) )
Signal handler to log the stack trace of the current thread .
38,322
def handle_callback_exception ( self , callback ) : if self . _error_handler : self . _error_handler ( callback ) else : app_log . error ( "Exception in callback %r" , callback , exc_info = True )
This method is called whenever a callback run by the IOLoop throws an exception .
38,323
def close_fd ( self , fd ) : try : try : fd . close ( ) except AttributeError : os . close ( fd ) except OSError : pass
Utility method to close an fd .
38,324
def on_widget_created ( self , ref ) : d = self . declaration self . widget = Snackbar ( __id__ = ref ) self . init_widget ( )
Using Snackbar . make returns async so we have to initialize it later .
38,325
def set_duration ( self , duration ) : if duration == 0 : self . widget . setDuration ( - 2 ) else : self . widget . setDuration ( 0 )
Android for whatever stupid reason doesn t let you set the time it only allows 1 - long or 0 - short . So we have to repeatedly call show until the duration expires hence this method does nothing see set_show .
38,326
def set_text ( self , text ) : d = self . declaration if d . input_type == 'html' : text = Spanned ( __id__ = Html . fromHtml ( text ) ) self . widget . setTextKeepState ( text )
Set the text in the widget .
38,327
def encode ( obj ) : if hasattr ( obj , '__id__' ) : return msgpack . ExtType ( ExtType . REF , msgpack . packb ( obj . __id__ ) ) return obj
Encode an object for proper decoding by Java or ObjC
38,328
def get_handler ( ptr , method ) : obj = CACHE . get ( ptr , None ) if obj is None : raise BridgeReferenceError ( "Reference id={} never existed or has already been destroyed" . format ( ptr ) ) elif not hasattr ( obj , method ) : raise NotImplementedError ( "{}.{} is not implemented." . format ( obj , method ) ) return obj , getattr ( obj , method )
Dereference the pointer and return the handler method .
38,329
def suppressed ( self , obj ) : obj . __suppressed__ [ self . name ] = True yield obj . __suppressed__ [ self . name ] = False
Suppress calls within this context to avoid feedback loops
38,330
def request_permission ( cls , permissions ) : app = AndroidApplication . instance ( ) f = app . create_future ( ) def on_result ( perms ) : allowed = True for p in permissions : allowed = allowed and perms . get ( p , False ) f . set_result ( allowed ) app . request_permissions ( permissions ) . then ( on_result ) return f
Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied .
38,331
def return_future ( f ) : replacer = ArgReplacer ( f , 'callback' ) @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : future = TracebackFuture ( ) callback , args , kwargs = replacer . replace ( lambda value = _NO_RESULT : future . set_result ( value ) , args , kwargs ) def handle_error ( typ , value , tb ) : future . set_exc_info ( ( typ , value , tb ) ) return True exc_info = None with ExceptionStackContext ( handle_error ) : try : result = f ( * args , ** kwargs ) if result is not None : raise ReturnValueIgnoredError ( "@return_future should not be used with functions " "that return values" ) except : exc_info = sys . exc_info ( ) raise if exc_info is not None : future . result ( ) if callback is not None : def run_callback ( future ) : result = future . result ( ) if result is _NO_RESULT : callback ( ) else : callback ( future . result ( ) ) future . add_done_callback ( wrap ( run_callback ) ) return future return wrapper
Decorator to make a function that returns via callback return a Future .
38,332
def result ( self , timeout = None ) : self . _clear_tb_log ( ) if self . _result is not None : return self . _result if self . _exc_info is not None : try : raise_exc_info ( self . _exc_info ) finally : self = None self . _check_done ( ) return self . _result
If the operation succeeded return its result . If it failed re - raise its exception .
38,333
def exception ( self , timeout = None ) : self . _clear_tb_log ( ) if self . _exc_info is not None : return self . _exc_info [ 1 ] else : self . _check_done ( ) return None
If the operation raised an exception return the Exception object . Otherwise returns None .
38,334
def add_done_callback ( self , fn ) : if self . _done : fn ( self ) else : self . _callbacks . append ( fn )
Attaches the given callback to the Future .
38,335
def set_exception ( self , exception ) : self . set_exc_info ( ( exception . __class__ , exception , getattr ( exception , '__traceback__' , None ) ) )
Sets the exception of a Future .
38,336
def set_exc_info ( self , exc_info ) : self . _exc_info = exc_info self . _log_traceback = True if not _GC_CYCLE_FINALIZERS : self . _tb_logger = _TracebackLogger ( exc_info ) try : self . _set_done ( ) finally : if self . _log_traceback and self . _tb_logger is not None : self . _tb_logger . activate ( ) self . _exc_info = exc_info
Sets the exception information of a Future .
38,337
def destroy ( self ) : layout = self . layout if layout is not None : layout . removeFromSuperview ( ) self . layout = None super ( UiKitViewGroup , self ) . destroy ( )
A reimplemented destructor that destroys the layout widget .
38,338
def pack_args ( self , obj , * args , ** kwargs ) : signature = self . __signature__ if not signature : return ( self . name , [ ] ) method_name = [ self . name ] bridge_args = [ ] for i , sig in enumerate ( signature ) : if i == 0 : method_name . append ( ":" ) bridge_args . append ( msgpack_encoder ( sig , args [ 0 ] ) ) continue found = False for k in sig : if k in kwargs : method_name . append ( "{}:" . format ( k ) ) bridge_args . append ( msgpack_encoder ( sig [ k ] , kwargs [ k ] ) ) found = True break if not found : raise ValueError ( "Unexpected or missing argument at index {}. " "Expected {}" . format ( i , sig ) ) return ( "" . join ( method_name ) , bridge_args )
Arguments must be packed according to the kwargs passed and the signature defined .
38,339
def _remove_deactivated ( contexts ) : stack_contexts = tuple ( [ h for h in contexts [ 0 ] if h . active ] ) head = contexts [ 1 ] while head is not None and not head . active : head = head . old_contexts [ 1 ] ctx = head while ctx is not None : parent = ctx . old_contexts [ 1 ] while parent is not None : if parent . active : break ctx . old_contexts = parent . old_contexts parent = parent . old_contexts [ 1 ] ctx = parent return ( stack_contexts , head )
Remove deactivated handlers from the chain
38,340
def wrap ( fn ) : if fn is None or hasattr ( fn , '_wrapped' ) : return fn cap_contexts = [ _state . contexts ] if not cap_contexts [ 0 ] [ 0 ] and not cap_contexts [ 0 ] [ 1 ] : def null_wrapper ( * args , ** kwargs ) : try : current_state = _state . contexts _state . contexts = cap_contexts [ 0 ] return fn ( * args , ** kwargs ) finally : _state . contexts = current_state null_wrapper . _wrapped = True return null_wrapper def wrapped ( * args , ** kwargs ) : ret = None try : current_state = _state . contexts cap_contexts [ 0 ] = contexts = _remove_deactivated ( cap_contexts [ 0 ] ) _state . contexts = contexts exc = ( None , None , None ) top = None last_ctx = 0 stack = contexts [ 0 ] for n in stack : try : n . enter ( ) last_ctx += 1 except : exc = sys . exc_info ( ) top = n . old_contexts [ 1 ] if top is None : try : ret = fn ( * args , ** kwargs ) except : exc = sys . exc_info ( ) top = contexts [ 1 ] if top is not None : exc = _handle_exception ( top , exc ) else : while last_ctx > 0 : last_ctx -= 1 c = stack [ last_ctx ] try : c . exit ( * exc ) except : exc = sys . exc_info ( ) top = c . old_contexts [ 1 ] break else : top = None if top is not None : exc = _handle_exception ( top , exc ) if exc != ( None , None , None ) : raise_exc_info ( exc ) finally : _state . contexts = current_state return ret wrapped . _wrapped = True return wrapped
Returns a callable object that will restore the current StackContext when executed .
38,341
def get_declared_items ( self ) : for k , v in super ( AndroidListView , self ) . get_declared_items ( ) : if k == 'layout' : yield k , v break
Override to do it manually
38,342
def on_recycle_view ( self , index , position ) : item = self . list_items [ index ] self . item_mapping [ position ] = item item . recycle_view ( position )
Update the item the view at the given index should display
38,343
def refresh_views ( self , change = None ) : adapter = self . adapter item_mapping = self . item_mapping for i , item in enumerate ( self . list_items ) : item_mapping [ i ] = item item . recycle_view ( i ) if adapter : adapter . clearRecycleViews ( ) adapter . setRecycleViews ( [ encode ( li . get_view ( ) ) for li in self . list_items ] )
Set the views that the adapter will cycle through .
38,344
def _on_items_changed ( self , change ) : if change [ 'type' ] != 'container' : return op = change [ 'operation' ] if op == 'append' : i = len ( change [ 'value' ] ) - 1 self . adapter . notifyItemInserted ( i ) elif op == 'insert' : self . adapter . notifyItemInserted ( change [ 'index' ] ) elif op in ( 'pop' , '__delitem__' ) : self . adapter . notifyItemRemoved ( change [ 'index' ] ) elif op == '__setitem__' : self . adapter . notifyItemChanged ( change [ 'index' ] ) elif op == 'extend' : n = len ( change [ 'items' ] ) i = len ( change [ 'value' ] ) - n self . adapter . notifyItemRangeInserted ( i , n ) elif op in ( 'remove' , 'reverse' , 'sort' ) : self . adapter . notifyDataSetChanged ( )
Observe container events on the items list and update the adapter appropriately .
38,345
def recycle_view ( self , position ) : d = self . declaration if position < len ( d . parent . items ) : d . index = position d . item = d . parent . items [ position ] else : d . index = - 1 d . item = None
Tell the view to render the item at the given position
38,346
def configured_class ( cls ) : base = cls . configurable_base ( ) if base . __dict__ . get ( '_Configurable__impl_class' ) is None : base . __impl_class = cls . configurable_default ( ) return base . __impl_class
Returns the currently configured class .
38,347
def child_added ( self , child ) : view = child . widget if view is not None : self . toast . setView ( view )
Overwrite the view
38,348
def on_make_toast ( self , ref ) : d = self . declaration self . toast = Toast ( __id__ = ref ) self . init_widget ( )
Using Toast . makeToast returns async so we have to initialize it later .
38,349
def start ( cls , callback , provider = 'gps' , min_time = 1000 , min_distance = 0 ) : app = AndroidApplication . instance ( ) f = app . create_future ( ) def on_success ( lm ) : lm . onLocationChanged . connect ( callback ) listener = LocationManager . LocationListener ( lm ) lm . listeners . append ( listener ) lm . requestLocationUpdates ( provider , min_time , min_distance , listener ) app . set_future_result ( f , True ) def on_perm_request_result ( allowed ) : if allowed : LocationManager . get ( ) . then ( on_success ) else : app . set_future_result ( f , False ) def on_perm_check ( allowed ) : if allowed : LocationManager . get ( ) . then ( on_success ) else : LocationManager . request_permission ( fine = provider == 'gps' ) . then ( on_perm_request_result ) LocationManager . check_permission ( fine = provider == 'gps' ) . then ( on_perm_check ) return f
Convenience method that checks and requests permission if necessary and if successful calls the callback with a populated Location instance on updates .
38,350
def stop ( cls ) : manager = LocationManager . instance ( ) if manager : for l in manager . listeners : manager . removeUpdates ( l ) manager . listeners = [ ]
Stops location updates if currently updating .
38,351
def request_permission ( cls , fine = True ) : app = AndroidApplication . instance ( ) permission = ( cls . ACCESS_FINE_PERMISSION if fine else cls . ACCESS_COARSE_PERMISSION ) f = app . create_future ( ) def on_result ( perms ) : app . set_future_result ( f , perms [ permission ] ) app . request_permissions ( [ permission ] ) . then ( on_result ) return f
Requests permission and returns an async result that returns a boolean indicating if the permission was granted or denied .
38,352
def destroy ( self ) : if self . client : self . client . setWebView ( self . widget , None ) del self . client super ( AndroidWebView , self ) . destroy ( )
Destroy the client
38,353
def set_checked ( self , checked ) : if not checked : self . widget . clearCheck ( ) else : rb = checked . proxy . widget if not rb : return self . widget . check ( rb . getId ( ) )
Properly check the correct radio button .
38,354
def init_widget ( self ) : activity = self . widget activity . addActivityLifecycleListener ( activity . getId ( ) ) activity . onActivityLifecycleChanged . connect ( self . on_activity_lifecycle_changed ) activity . addBackPressedListener ( activity . getId ( ) ) activity . onBackPressed . connect ( self . on_back_pressed ) activity . addConfigurationChangedListener ( activity . getId ( ) ) activity . onConfigurationChanged . connect ( self . on_configuration_changed )
Initialize on the first call
38,355
def has_permission ( self , permission ) : f = self . create_future ( ) if self . api_level < 23 : f . set_result ( True ) return f def on_result ( allowed ) : result = allowed == Activity . PERMISSION_GRANTED self . set_future_result ( f , result ) self . widget . checkSelfPermission ( permission ) . then ( on_result ) return f
Return a future that resolves with the result of the permission
38,356
def request_permissions ( self , permissions ) : f = self . create_future ( ) if self . api_level < 23 : f . set_result ( { p : True for p in permissions } ) return f w = self . widget request_code = self . _permission_code self . _permission_code += 1 if request_code == 0 : w . setPermissionResultListener ( w . getId ( ) ) w . onRequestPermissionsResult . connect ( self . _on_permission_result ) def on_results ( code , perms , results ) : f . set_result ( { p : r == Activity . PERMISSION_GRANTED for ( p , r ) in zip ( perms , results ) } ) self . _permission_requests [ request_code ] = on_results self . widget . requestPermissions ( permissions , request_code ) return f
Return a future that resolves with the results of the permission requests
38,357
def show_toast ( self , msg , long = True ) : from . android_toast import Toast def on_toast ( ref ) : t = Toast ( __id__ = ref ) t . show ( ) Toast . makeText ( self , msg , 1 if long else 0 ) . then ( on_toast )
Show a toast message for the given duration . This is an android specific api .
38,358
def on_back_pressed ( self ) : try : event = { 'handled' : False } self . back_pressed ( event ) return bool ( event . get ( 'handled' , False ) ) except Exception as e : return False
Fire the back_pressed event with a dictionary with a handled key when the back hardware button is pressed If handled is set to any value that evaluates to True the default event implementation will be ignored .
38,359
def on_configuration_changed ( self , config ) : self . width = config [ 'width' ] self . height = config [ 'height' ] self . orientation = ( 'square' , 'portrait' , 'landscape' ) [ config [ 'orientation' ] ]
Handles a screen configuration change .
38,360
def show_view ( self ) : if not self . build_info : def on_build_info ( info ) : self . dp = info [ 'DISPLAY_DENSITY' ] self . width = info [ 'DISPLAY_WIDTH' ] self . height = info [ 'DISPLAY_HEIGHT' ] self . orientation = ( 'square' , 'portrait' , 'landscape' ) [ info [ 'DISPLAY_ORIENTATION' ] ] self . api_level = info [ 'SDK_INT' ] self . build_info = info self . _show_view ( ) self . init_widget ( ) self . widget . getBuildInfo ( ) . then ( on_build_info ) else : self . _show_view ( )
Show the current app . view . This will fade out the previous with the new view .
38,361
def _on_permission_result ( self , code , perms , results ) : handler = self . _permission_requests . get ( code , None ) if handler is not None : del self . _permission_requests [ code ] handler ( code , perms , results )
Handles a permission request result by passing it to the handler with the given code .
38,362
def _observe_keep_screen_on ( self , change ) : def set_screen_on ( window ) : from . android_window import Window window = Window ( __id__ = window ) if self . keep_screen_on : window . addFlags ( Window . FLAG_KEEP_SCREEN_ON ) else : window . clearFlags ( Window . FLAG_KEEP_SCREEN_ON ) self . widget . getWindow ( ) . then ( set_screen_on )
Sets or clears the flag to keep the screen on .
38,363
def load_plugin_factories ( self ) : for plugin in self . get_plugins ( group = 'enaml_native_android_factories' ) : get_factories = plugin . load ( ) PLUGIN_FACTORIES = get_factories ( ) factories . ANDROID_FACTORIES . update ( PLUGIN_FACTORIES )
Add any plugin toolkit widgets to the ANDROID_FACTORIES
38,364
def on_value_changed ( self , text ) : d = self . declaration with self . widget . get_member ( 'text' ) . suppressed ( self . widget ) : d . text = text
Update text field
38,365
def imports ( ) : from . core . import_hooks import ExtensionImporter importer = ExtensionImporter ( ) sys . meta_path . append ( importer ) yield sys . meta_path . remove ( importer )
Install the import hook to load python extensions from app s lib folder during the context of this block .
38,366
def install ( ) : from . core . import_hooks import ExtensionImporter importer = ExtensionImporter ( ) sys . meta_path . append ( importer )
Install the import hook to load extensions from the app Lib folder . Like imports but leaves it in the meta_path thus it is slower .
38,367
def init_request ( self ) : builder = Request . Builder ( ) builder . url ( self . url ) for k , v in self . headers . items ( ) : builder . addHeader ( k , v ) body = self . body if body : media_type = MediaType ( __id__ = MediaType . parse ( self . content_type ) ) request_body = RequestBody ( __id__ = RequestBody . create ( media_type , body ) ) builder . method ( self . method , request_body ) elif self . method in [ 'get' , 'delete' , 'head' ] : getattr ( builder , self . method ) ( ) else : raise ValueError ( "Cannot do a '{}' request " "without a body" . format ( self . method ) ) self . request = Request ( __id__ = builder . build ( ) )
Init the native request using the okhttp3 . Request . Builder
38,368
def _default_body ( self ) : if not self . data : return "" if self . content_type == 'application/json' : import json return json . dumps ( self . data ) elif self . content_type == 'application/x-www-form-urlencoded' : import urllib return urllib . urlencode ( self . data ) else : raise NotImplementedError ( "You must manually encode the request " "body for '{}'" . format ( self . content_type ) )
If the body is not passed in by the user try to create one using the given data parameters .
38,369
def on_finish ( self ) : r = self . response r . request_time = time . time ( ) - self . start_time if self . callback : self . callback ( r )
Called regardless of success or failure
38,370
def _fetch ( self , request ) : client = self . client call = Call ( __id__ = client . newCall ( request . request ) ) call . enqueue ( request . handler ) request . call = call
Fetch using the OkHttpClient
38,371
def load ( self ) : print ( "[DEBUG] Loading plugin {} from {}" . format ( self . name , self . source ) ) import pydoc path , attr = self . source . split ( ":" ) module = pydoc . locate ( path ) return getattr ( module , attr )
Load the object defined by the plugin entry point
38,372
def _default_plugins ( self ) : plugins = { } try : with open ( 'entry_points.json' ) as f : entry_points = json . load ( f ) for ep , obj in entry_points . items ( ) : plugins [ ep ] = [ ] for name , src in obj . items ( ) : plugins [ ep ] . append ( Plugin ( name = name , source = src ) ) except Exception as e : print ( "Failed to load entry points {}" . format ( e ) ) return plugins
Get entry points to load any plugins installed . The build process should create an entry_points . json file with all of the data from the installed entry points .
38,373
def start ( self ) : if self . load_view and self . dev != "remote" : self . deferred_call ( self . load_view , self ) self . loop . start ( )
Start the application s main event loop using either twisted or tornado .
38,374
def timed_call ( self , ms , callback , * args , ** kwargs ) : return self . loop . timed_call ( ms , callback , * args , ** kwargs )
Invoke a callable on the main event loop thread at a specified time in the future .
38,375
def add_done_callback ( self , future , callback ) : if future is None : raise bridge . BridgeReferenceError ( "Tried to add a callback to a nonexistent Future. " "Make sure you pass the `returns` argument to your JavaMethod" ) return self . loop . add_done_callback ( future , callback )
Add a callback on a future object put here so it can be implemented with different event loops .
38,376
def get_view ( self ) : view = self . view if not view . is_initialized : view . initialize ( ) if not view . proxy_is_active : view . activate_proxy ( ) return view . proxy . widget
Get the root view to display . Make sure it is properly initialized .
38,377
def send_event ( self , name , * args , ** kwargs ) : n = len ( self . _bridge_queue ) self . _bridge_queue . append ( ( name , args ) ) if n == 0 : self . _bridge_last_scheduled = time ( ) self . deferred_call ( self . _bridge_send ) return elif kwargs . get ( 'now' ) : self . _bridge_send ( now = True ) return dt = time ( ) - self . _bridge_last_scheduled if dt > self . _bridge_max_delay : self . _bridge_send ( now = True )
Send an event to the native handler . This call is queued and batched .
38,378
def _bridge_send ( self , now = False ) : if len ( self . _bridge_queue ) : if self . debug : print ( "======== Py ) for event in self . _bridge_queue : print ( event ) print ( "===========================" ) self . dispatch_events ( bridge . dumps ( self . _bridge_queue ) ) self . _bridge_queue = [ ]
Send the events over the bridge to be processed by the native handler .
38,379
def process_events ( self , data ) : events = bridge . loads ( data ) if self . debug : print ( "======== Py <-- Native ======" ) for event in events : print ( event ) print ( "===========================" ) for event in events : if event [ 0 ] == 'event' : self . handle_event ( event )
The native implementation must use this call to
38,380
def handle_event ( self , event ) : result_id , ptr , method , args = event [ 1 ] obj = None result = None try : obj , handler = bridge . get_handler ( ptr , method ) result = handler ( * [ v for t , v in args ] ) except bridge . BridgeReferenceError as e : msg = "Error processing event: {} - {}" . format ( event , e ) . encode ( "utf-8" ) print ( msg ) self . show_error ( msg ) except : msg = "Error processing event: {} - {}" . format ( event , traceback . format_exc ( ) ) . encode ( "utf-8" ) print ( msg ) self . show_error ( msg ) raise finally : if result_id : if hasattr ( obj , '__nativeclass__' ) : sig = getattr ( type ( obj ) , method ) . __returns__ else : sig = type ( result ) . __name__ self . send_event ( bridge . Command . RESULT , result_id , bridge . msgpack_encoder ( sig , result ) )
When we get an event type from the bridge handle it by invoking the handler and if needed sending back the result .
38,381
def handle_error ( self , callback ) : self . loop . log_error ( callback ) msg = "\n" . join ( [ "Exception in callback %r" % callback , traceback . format_exc ( ) ] ) self . show_error ( msg . encode ( 'utf-8' ) )
Called when an error occurs in an event loop callback . By default sets the error view .
38,382
def start_dev_session ( self ) : try : from . dev import DevServerSession session = DevServerSession . initialize ( host = self . dev ) session . start ( ) self . _dev_session = session except : self . show_error ( traceback . format_exc ( ) )
Start a client that attempts to connect to the dev server running on the host app . dev
38,383
def load_plugin_widgets ( self ) : from enamlnative . widgets import api for plugin in self . get_plugins ( group = 'enaml_native_widgets' ) : get_widgets = plugin . load ( ) for name , widget in iter ( get_widgets ( ) ) : setattr ( api , name , widget )
Pull widgets added via plugins using the enaml_native_widgets entry point . The entry point function must return a dictionary of Widget declarations to add to the core api .
38,384
def get ( self , measurement_class ) : name = Measurement . name_from_class ( measurement_class ) return self . _construct_measurement ( name )
Return the latest measurement for the given class or None if nothing has been received from the vehicle .
38,385
def add_source ( self , source ) : if source is not None : self . sources . add ( source ) source . callback = self . _receive if hasattr ( source , 'start' ) : source . start ( )
Add a vehicle data source to the instance .
38,386
def register ( self , measurement_class , callback ) : self . callbacks [ Measurement . name_from_class ( measurement_class ) ] . add ( callback )
Call the callback with any new values of measurement_class received .
38,387
def unregister ( self , measurement_class , callback ) : self . callbacks [ Measurement . name_from_class ( measurement_class ) ] . remove ( callback )
Stop notifying callback of new values of measurement_class .
38,388
def _send_complex_request ( self , request ) : self . device . ctrl_transfer ( 0x40 , self . COMPLEX_CONTROL_COMMAND , 0 , 0 , self . streamer . serialize_for_stream ( request ) )
Send a request via the USB control request endpoint rather than as a bulk transfer .
38,389
def out_endpoint ( self ) : if getattr ( self , '_out_endpoint' , None ) is None : config = self . device . get_active_configuration ( ) interface_number = config [ ( 0 , 0 ) ] . bInterfaceNumber interface = usb . util . find_descriptor ( config , bInterfaceNumber = interface_number ) self . _out_endpoint = usb . util . find_descriptor ( interface , custom_match = lambda e : usb . util . endpoint_direction ( e . bEndpointAddress ) == usb . util . ENDPOINT_OUT ) if not self . _out_endpoint : raise ControllerError ( "Couldn't find OUT endpoint on the USB device" ) return self . _out_endpoint
Open a reference to the USB device s only OUT endpoint . This method assumes that the USB device configuration has already been set .
38,390
def wait_for_responses ( self ) : self . thread . join ( self . COMMAND_RESPONSE_TIMEOUT_S ) self . running = False return self . responses
Block the thread and wait for the response to the given request to arrive from the VI . If no matching response is received in COMMAND_RESPONSE_TIMEOUT_S seconds returns anyway .
38,391
def _response_matches_request ( self , response ) : if super ( DiagnosticResponseReceiver , self ) . _response_matches_request ( response ) : return True if ( 'bus' in self . diagnostic_request and response . get ( 'bus' , None ) != self . diagnostic_request [ 'bus' ] ) : return False if ( self . diagnostic_request [ 'id' ] != 0x7df and response . get ( 'id' , None ) != self . diagnostic_request [ 'id' ] ) : return False if ( response . get ( 'success' , True ) and response . get ( 'pid' , None ) != self . diagnostic_request . get ( 'pid' , None ) ) : return False return response . get ( 'mode' , None ) == self . diagnostic_request [ 'mode' ]
Return true if the response is to a diagnostic request and the bus id mode match . If the request was successful the PID echo is also checked .
38,392
def complex_request ( self , request , wait_for_first_response = True ) : receiver = self . _prepare_response_receiver ( request , receiver_class = CommandResponseReceiver ) self . _send_complex_request ( request ) responses = [ ] if wait_for_first_response : responses = receiver . wait_for_responses ( ) return responses
Send a compound command request to the interface over the normal data channel .
38,393
def create_diagnostic_request ( self , message_id , mode , bus = None , pid = None , frequency = None , payload = None , wait_for_ack = True , wait_for_first_response = False , decoded_type = None ) : request = self . _build_diagnostic_request ( message_id , mode , bus , pid , frequency , payload , decoded_type ) diag_response_receiver = None if wait_for_first_response : diag_response_receiver = self . _prepare_response_receiver ( request , DiagnosticResponseReceiver ) request [ 'action' ] = 'add' ack_responses = self . complex_request ( request , wait_for_ack ) diag_responses = None if diag_response_receiver is not None : diag_responses = diag_response_receiver . wait_for_responses ( ) return ack_responses , diag_responses
Send a new diagnostic message request to the VI
38,394
def set_passthrough ( self , bus , enabled ) : request = { "command" : "passthrough" , "bus" : bus , "enabled" : enabled } return self . _check_command_response_status ( request )
Control the status of CAN message passthrough for a bus .
38,395
def set_payload_format ( self , payload_format ) : request = { "command" : "payload_format" , "format" : payload_format } status = self . _check_command_response_status ( request ) self . format = payload_format return status
Set the payload format for messages sent to and from the VI .
38,396
def rtc_configuration ( self , unix_time ) : request = { "command" : "rtc_configuration" , "unix_time" : unix_time } status = self . _check_command_response_status ( request ) return status
Set the Unix time if RTC is supported on the device .
38,397
def set_acceptance_filter_bypass ( self , bus , bypass ) : request = { "command" : "af_bypass" , "bus" : bus , "bypass" : bypass } return self . _check_command_response_status ( request )
Control the status of CAN acceptance filter for a bus .
38,398
def sd_mount_status ( self ) : request = { "command" : "sd_mount_status" } responses = self . complex_request ( request ) result = None if len ( responses ) > 0 : result = responses [ 0 ] . get ( 'status' ) return result
Request for SD Mount status if available .
38,399
def write ( self , ** kwargs ) : if 'id' in kwargs and 'data' in kwargs : result = self . write_raw ( kwargs [ 'id' ] , kwargs [ 'data' ] , bus = kwargs . get ( 'bus' , None ) , frame_format = kwargs . get ( 'frame_format' , None ) ) else : result = self . write_translated ( kwargs [ 'name' ] , kwargs [ 'value' ] , event = kwargs . get ( 'event' , None ) ) return result
Serialize a raw or translated write request and send it to the VI following the OpenXC message format .