repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
codelv/enaml-native
src/enamlnative/android/android_view_pager.py
AndroidViewPager._notify_change
def _notify_change(self): """ After all changes have settled, tell Java it changed """ d = self.declaration self._notify_count -= 1 if self._notify_count == 0: #: Tell the UI we made changes self.adapter.notifyDataSetChanged(now=True) self.get_context().timed_call( 500, self._queue_pending_calls)
python
def _notify_change(self): """ After all changes have settled, tell Java it changed """ d = self.declaration self._notify_count -= 1 if self._notify_count == 0: #: Tell the UI we made changes self.adapter.notifyDataSetChanged(now=True) self.get_context().timed_call( 500, self._queue_pending_calls)
[ "def", "_notify_change", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "_notify_count", "-=", "1", "if", "self", ".", "_notify_count", "==", "0", ":", "#: Tell the UI we made changes", "self", ".", "adapter", ".", "notifyDataSetChan...
After all changes have settled, tell Java it changed
[ "After", "all", "changes", "have", "settled", "tell", "Java", "it", "changed" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_view_pager.py#L177-L185
train
38,300
codelv/enaml-native
src/enamlnative/android/android_view_pager.py
AndroidViewPager.set_current_index
def set_current_index(self, 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. """ # d = self.declaration # #: We have to wait for the current_index to be ready before we can # #: change pages if self._notify_count > 0: self._pending_calls.append( lambda index=index: self.widget.setCurrentItem(index)) else: self.widget.setCurrentItem(index)
python
def set_current_index(self, 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. """ # d = self.declaration # #: We have to wait for the current_index to be ready before we can # #: change pages if self._notify_count > 0: self._pending_calls.append( lambda index=index: self.widget.setCurrentItem(index)) else: self.widget.setCurrentItem(index)
[ "def", "set_current_index", "(", "self", ",", "index", ")", ":", "# d = self.declaration", "# #: We have to wait for the current_index to be ready before we can", "# #: change pages", "if", "self", ".", "_notify_count", ">", "0", ":", "self", ".", "_pending_calls", ".", "...
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.
[ "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", "...
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_view_pager.py#L228-L241
train
38,301
codelv/enaml-native
src/enamlnative/android/android_flexbox.py
AndroidFlexbox.apply_layout
def apply_layout(self, child, layout): """ Apply the flexbox specific layout. """ params = self.create_layout_params(child, layout) w = child.widget if w: # padding 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
python
def apply_layout(self, child, layout): """ Apply the flexbox specific layout. """ params = self.create_layout_params(child, layout) w = child.widget if w: # padding 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
[ "def", "apply_layout", "(", "self", ",", "child", ",", "layout", ")", ":", "params", "=", "self", ".", "create_layout_params", "(", "child", ",", "layout", ")", "w", "=", "child", ".", "widget", "if", "w", ":", "# padding", "if", "layout", ".", "get", ...
Apply the flexbox specific layout.
[ "Apply", "the", "flexbox", "specific", "layout", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_flexbox.py#L174-L187
train
38,302
codelv/enaml-native
src/enamlnative/android/android_notification.py
NotificationManager.get
def get(cls): """ Acquires the NotificationManager service async. """ app = AndroidApplication.instance() f = app.create_future() if cls._instance: f.set_result(cls._instance) return f def on_service(obj_id): #: Create the manager 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
python
def get(cls): """ Acquires the NotificationManager service async. """ app = AndroidApplication.instance() f = app.create_future() if cls._instance: f.set_result(cls._instance) return f def on_service(obj_id): #: Create the manager 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
[ "def", "get", "(", "cls", ")", ":", "app", "=", "AndroidApplication", ".", "instance", "(", ")", "f", "=", "app", ".", "create_future", "(", ")", "if", "cls", ".", "_instance", ":", "f", ".", "set_result", "(", "cls", ".", "_instance", ")", "return",...
Acquires the NotificationManager service async.
[ "Acquires", "the", "NotificationManager", "service", "async", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_notification.py#L85-L104
train
38,303
codelv/enaml-native
src/enamlnative/android/android_notification.py
NotificationManager.show_notification
def show_notification(cls, channel_id, *args, **kwargs): """ Create and show a Notification. See `Notification.Builder.update` for a list of accepted parameters. """ app = AndroidApplication.instance() builder = Notification.Builder(app, channel_id) builder.update(*args, **kwargs) return builder.show()
python
def show_notification(cls, channel_id, *args, **kwargs): """ Create and show a Notification. See `Notification.Builder.update` for a list of accepted parameters. """ app = AndroidApplication.instance() builder = Notification.Builder(app, channel_id) builder.update(*args, **kwargs) return builder.show()
[ "def", "show_notification", "(", "cls", ",", "channel_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "app", "=", "AndroidApplication", ".", "instance", "(", ")", "builder", "=", "Notification", ".", "Builder", "(", "app", ",", "channel_id", ")...
Create and show a Notification. See `Notification.Builder.update` for a list of accepted parameters.
[ "Create", "and", "show", "a", "Notification", ".", "See", "Notification", ".", "Builder", ".", "update", "for", "a", "list", "of", "accepted", "parameters", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_notification.py#L153-L161
train
38,304
codelv/enaml-native
src/enamlnative/android/android_notification.py
AndroidNotification.init_layout
def init_layout(self): """ Create the notification in the top down pass if show = True """ d = self.declaration self.create_notification() if d.show: self.set_show(d.show)
python
def init_layout(self): """ Create the notification in the top down pass if show = True """ d = self.declaration self.create_notification() if d.show: self.set_show(d.show)
[ "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
[ "Create", "the", "notification", "in", "the", "top", "down", "pass", "if", "show", "=", "True" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_notification.py#L548-L554
train
38,305
codelv/enaml-native
src/enamlnative/android/android_notification.py
AndroidNotification.destroy
def destroy(self): """ A reimplemented destructor that cancels the notification before destroying. """ builder = self.builder NotificationManager.cancel_notification(builder) del self.builder super(AndroidNotification, self).destroy()
python
def destroy(self): """ A reimplemented destructor that cancels the notification before destroying. """ builder = self.builder NotificationManager.cancel_notification(builder) del self.builder super(AndroidNotification, self).destroy()
[ "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.
[ "A", "reimplemented", "destructor", "that", "cancels", "the", "notification", "before", "destroying", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_notification.py#L556-L564
train
38,306
codelv/enaml-native
src/enamlnative/android/android_notification.py
AndroidNotification.create_notification
def create_notification(self): """ Instead of the typical create_widget we use `create_notification` because after it's closed it needs created again. """ d = self.declaration builder = self.builder = Notification.Builder(self.get_context(), d.channel_id) d = self.declaration # Apply any custom settings 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') # app = self.get_context() # intent = Intent() # intent.setClass(app, ) # builder.setContentIntent(PendingIntent.getActivity(app, 0, intent, 0)) #: Set custom content if present for view in self.child_widgets(): builder.setCustomContentView(view) break
python
def create_notification(self): """ Instead of the typical create_widget we use `create_notification` because after it's closed it needs created again. """ d = self.declaration builder = self.builder = Notification.Builder(self.get_context(), d.channel_id) d = self.declaration # Apply any custom settings 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') # app = self.get_context() # intent = Intent() # intent.setClass(app, ) # builder.setContentIntent(PendingIntent.getActivity(app, 0, intent, 0)) #: Set custom content if present for view in self.child_widgets(): builder.setCustomContentView(view) break
[ "def", "create_notification", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "builder", "=", "self", ".", "builder", "=", "Notification", ".", "Builder", "(", "self", ".", "get_context", "(", ")", ",", "d", ".", "channel_id", ")", "d", "=...
Instead of the typical create_widget we use `create_notification` because after it's closed it needs created again.
[ "Instead", "of", "the", "typical", "create_widget", "we", "use", "create_notification", "because", "after", "it", "s", "closed", "it", "needs", "created", "again", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_notification.py#L569-L595
train
38,307
codelv/enaml-native
src/enamlnative/ios/uikit_button.py
UiKitButton.create_widget
def create_widget(self): """ Create the toolkit widget for the proxy object. """ d = self.declaration button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect self.widget = UIButton(buttonWithType=button_type)
python
def create_widget(self): """ Create the toolkit widget for the proxy object. """ d = self.declaration button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect self.widget = UIButton(buttonWithType=button_type)
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "button_type", "=", "UIButton", ".", "UIButtonTypeSystem", "if", "d", ".", "flat", "else", "UIButton", ".", "UIButtonTypeRoundedRect", "self", ".", "widget", "=", "UIButton", ...
Create the toolkit widget for the proxy object.
[ "Create", "the", "toolkit", "widget", "for", "the", "proxy", "object", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/uikit_button.py#L56-L61
train
38,308
codelv/enaml-native
src/enamlnative/ios/uikit_text_view.py
UiKitTextView.init_text
def init_text(self): """ Init text properties for this widget """ 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)
python
def init_text(self): """ Init text properties for this widget """ 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)
[ "def", "init_text", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", ".", "text", ":", "self", ".", "set_text", "(", "d", ".", "text", ")", "if", "d", ".", "text_color", ":", "self", ".", "set_text_color", "(", "d", ".", "t...
Init text properties for this widget
[ "Init", "text", "properties", "for", "this", "widget" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/uikit_text_view.py#L74-L86
train
38,309
codelv/enaml-native
src/enamlnative/core/hotswap/autoreload.py
update_function
def update_function(old, new): """Upgrade the code object of a function""" for name in func_attrs: try: setattr(old, name, getattr(new, name)) except (AttributeError, TypeError): pass
python
def update_function(old, new): """Upgrade the code object of a function""" for name in func_attrs: try: setattr(old, name, getattr(new, name)) except (AttributeError, TypeError): pass
[ "def", "update_function", "(", "old", ",", "new", ")", ":", "for", "name", "in", "func_attrs", ":", "try", ":", "setattr", "(", "old", ",", "name", ",", "getattr", "(", "new", ",", "name", ")", ")", "except", "(", "AttributeError", ",", "TypeError", ...
Upgrade the code object of a function
[ "Upgrade", "the", "code", "object", "of", "a", "function" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/autoreload.py#L290-L296
train
38,310
codelv/enaml-native
src/enamlnative/core/hotswap/autoreload.py
superreload
def superreload(module, reload=reload, old_objects={}): """Enhanced version of the builtin reload function. superreload remembers objects previously in the module, and - upgrades the class dictionary of every old class in the module - upgrades the code object of every old function and method - clears the module's namespace before reloading """ # collect old objects in the module 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 # reload module try: # clear namespace first from old cruft 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: # restore module dictionary on failed reload module.__dict__.update(old_dict) raise # iterate over all objects and update functions & classes 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
python
def superreload(module, reload=reload, old_objects={}): """Enhanced version of the builtin reload function. superreload remembers objects previously in the module, and - upgrades the class dictionary of every old class in the module - upgrades the code object of every old function and method - clears the module's namespace before reloading """ # collect old objects in the module 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 # reload module try: # clear namespace first from old cruft 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: # restore module dictionary on failed reload module.__dict__.update(old_dict) raise # iterate over all objects and update functions & classes 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
[ "def", "superreload", "(", "module", ",", "reload", "=", "reload", ",", "old_objects", "=", "{", "}", ")", ":", "# collect old objects in the module", "for", "name", ",", "obj", "in", "list", "(", "module", ".", "__dict__", ".", "items", "(", ")", ")", "...
Enhanced version of the builtin reload function. superreload remembers objects previously in the module, and - upgrades the class dictionary of every old class in the module - upgrades the code object of every old function and method - clears the module's namespace before reloading
[ "Enhanced", "version", "of", "the", "builtin", "reload", "function", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/autoreload.py#L363-L419
train
38,311
codelv/enaml-native
src/enamlnative/core/hotswap/autoreload.py
ModuleReloader.mark_module_skipped
def mark_module_skipped(self, module_name): """Skip reloading the named module in the future""" try: del self.modules[module_name] except KeyError: pass self.skip_modules[module_name] = True
python
def mark_module_skipped(self, module_name): """Skip reloading the named module in the future""" try: del self.modules[module_name] except KeyError: pass self.skip_modules[module_name] = True
[ "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
[ "Skip", "reloading", "the", "named", "module", "in", "the", "future" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/autoreload.py#L175-L181
train
38,312
codelv/enaml-native
src/enamlnative/core/hotswap/autoreload.py
ModuleReloader.aimport_module
def aimport_module(self, module_name): """Import a module, and mark it reloadable Returns ------- top_module : module The imported module if it is top-level, or the top-level top_name : module Name of top_module """ 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
python
def aimport_module(self, module_name): """Import a module, and mark it reloadable Returns ------- top_module : module The imported module if it is top-level, or the top-level top_name : module Name of top_module """ 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
[ "def", "aimport_module", "(", "self", ",", "module_name", ")", ":", "self", ".", "mark_module_reloadable", "(", "module_name", ")", "import_module", "(", "module_name", ")", "top_name", "=", "module_name", ".", "split", "(", "'.'", ")", "[", "0", "]", "top_m...
Import a module, and mark it reloadable Returns ------- top_module : module The imported module if it is top-level, or the top-level top_name : module Name of top_module
[ "Import", "a", "module", "and", "mark", "it", "reloadable" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/autoreload.py#L191-L207
train
38,313
codelv/enaml-native
src/enamlnative/core/hotswap/autoreload.py
Autoreloader.autoreload
def autoreload(self, parameter_s=''): r"""%autoreload => Reload modules automatically %autoreload Reload all modules (except those excluded by %aimport) automatically now. %autoreload 0 Disable automatic reloading. %autoreload 1 Reload all modules imported with %aimport every time before executing the Python code typed. %autoreload 2 Reload all modules (except those excluded by %aimport) every time before executing the Python code typed. Reloading Python modules in a reliable way is in general difficult, and unexpected things may occur. %autoreload tries to work around common pitfalls by replacing function code objects and parts of classes previously in the module with new versions. This makes the following things to work: - Functions and classes imported via 'from xxx import foo' are upgraded to new versions when 'xxx' is reloaded. - Methods and properties of classes are upgraded on reload, so that calling 'c.foo()' on an object 'c' created before the reload causes the new code for 'foo' to be executed. Some of the known remaining caveats are: - Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only). - Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded. - C extension modules cannot be reloaded, and so cannot be autoreloaded. """ 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
python
def autoreload(self, parameter_s=''): r"""%autoreload => Reload modules automatically %autoreload Reload all modules (except those excluded by %aimport) automatically now. %autoreload 0 Disable automatic reloading. %autoreload 1 Reload all modules imported with %aimport every time before executing the Python code typed. %autoreload 2 Reload all modules (except those excluded by %aimport) every time before executing the Python code typed. Reloading Python modules in a reliable way is in general difficult, and unexpected things may occur. %autoreload tries to work around common pitfalls by replacing function code objects and parts of classes previously in the module with new versions. This makes the following things to work: - Functions and classes imported via 'from xxx import foo' are upgraded to new versions when 'xxx' is reloaded. - Methods and properties of classes are upgraded on reload, so that calling 'c.foo()' on an object 'c' created before the reload causes the new code for 'foo' to be executed. Some of the known remaining caveats are: - Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only). - Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded. - C extension modules cannot be reloaded, and so cannot be autoreloaded. """ 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
[ "def", "autoreload", "(", "self", ",", "parameter_s", "=", "''", ")", ":", "if", "parameter_s", "==", "''", ":", "self", ".", "_reloader", ".", "check", "(", "True", ")", "elif", "parameter_s", "==", "'0'", ":", "self", ".", "_reloader", ".", "enabled"...
r"""%autoreload => Reload modules automatically %autoreload Reload all modules (except those excluded by %aimport) automatically now. %autoreload 0 Disable automatic reloading. %autoreload 1 Reload all modules imported with %aimport every time before executing the Python code typed. %autoreload 2 Reload all modules (except those excluded by %aimport) every time before executing the Python code typed. Reloading Python modules in a reliable way is in general difficult, and unexpected things may occur. %autoreload tries to work around common pitfalls by replacing function code objects and parts of classes previously in the module with new versions. This makes the following things to work: - Functions and classes imported via 'from xxx import foo' are upgraded to new versions when 'xxx' is reloaded. - Methods and properties of classes are upgraded on reload, so that calling 'c.foo()' on an object 'c' created before the reload causes the new code for 'foo' to be executed. Some of the known remaining caveats are: - Replacing code objects does not always succeed: changing a @property in a class to an ordinary method or a method to a member variable can cause problems (but in old objects only). - Functions that are removed (eg. via monkey-patching) from a module before it is reloaded are not upgraded. - C extension modules cannot be reloaded, and so cannot be autoreloaded.
[ "r", "%autoreload", "=", ">", "Reload", "modules", "automatically" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/autoreload.py#L439-L492
train
38,314
codelv/enaml-native
src/enamlnative/core/hotswap/autoreload.py
Autoreloader.aimport
def aimport(self, parameter_s='', stream=None): """%aimport => Import modules for automatic reloading. %aimport List modules to automatically import and not to import. %aimport foo Import module 'foo' and mark it to be autoreloaded for %autoreload 1 %aimport foo, bar Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload 1 %aimport -foo Mark module 'foo' to not be autoreloaded for %autoreload 1 """ 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) # Inject module to user namespace self.shell.push({top_name: top_module})
python
def aimport(self, parameter_s='', stream=None): """%aimport => Import modules for automatic reloading. %aimport List modules to automatically import and not to import. %aimport foo Import module 'foo' and mark it to be autoreloaded for %autoreload 1 %aimport foo, bar Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload 1 %aimport -foo Mark module 'foo' to not be autoreloaded for %autoreload 1 """ 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) # Inject module to user namespace self.shell.push({top_name: top_module})
[ "def", "aimport", "(", "self", ",", "parameter_s", "=", "''", ",", "stream", "=", "None", ")", ":", "modname", "=", "parameter_s", "if", "not", "modname", ":", "to_reload", "=", "sorted", "(", "self", ".", "_reloader", ".", "modules", ".", "keys", "(",...
%aimport => Import modules for automatic reloading. %aimport List modules to automatically import and not to import. %aimport foo Import module 'foo' and mark it to be autoreloaded for %autoreload 1 %aimport foo, bar Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload 1 %aimport -foo Mark module 'foo' to not be autoreloaded for %autoreload 1
[ "%aimport", "=", ">", "Import", "modules", "for", "automatic", "reloading", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/autoreload.py#L494-L528
train
38,315
codelv/enaml-native
src/enamlnative/core/hotswap/autoreload.py
Autoreloader.post_execute
def post_execute(self): """Cache the modification times of any modules imported in this execution """ 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)
python
def post_execute(self): """Cache the modification times of any modules imported in this execution """ 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)
[ "def", "post_execute", "(", "self", ")", ":", "newly_loaded_modules", "=", "set", "(", "sys", ".", "modules", ")", "-", "self", ".", "loaded_modules", "for", "modname", "in", "newly_loaded_modules", ":", "_", ",", "pymtime", "=", "self", ".", "_reloader", ...
Cache the modification times of any modules imported in this execution
[ "Cache", "the", "modification", "times", "of", "any", "modules", "imported", "in", "this", "execution" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/hotswap/autoreload.py#L537-L546
train
38,316
codelv/enaml-native
src/enamlnative/android/android_spinner.py
AndroidSpinner.set_items
def set_items(self, items): """ Generate the view cache """ self.adapter.clear() self.adapter.addAll(items)
python
def set_items(self, items): """ Generate the view cache """ self.adapter.clear() self.adapter.addAll(items)
[ "def", "set_items", "(", "self", ",", "items", ")", ":", "self", ".", "adapter", ".", "clear", "(", ")", "self", ".", "adapter", ".", "addAll", "(", "items", ")" ]
Generate the view cache
[ "Generate", "the", "view", "cache" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_spinner.py#L115-L120
train
38,317
codelv/enaml-native
src/enamlnative/ios/app.py
ENBridge._default_objc
def _default_objc(self): """ Load the objc library using ctypes. """ 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
python
def _default_objc(self): """ Load the objc library using ctypes. """ 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
[ "def", "_default_objc", "(", "self", ")", ":", "objc", "=", "ctypes", ".", "cdll", ".", "LoadLibrary", "(", "find_library", "(", "'objc'", ")", ")", "objc", ".", "objc_getClass", ".", "restype", "=", "ctypes", ".", "c_void_p", "objc", ".", "sel_registerNam...
Load the objc library using ctypes.
[ "Load", "the", "objc", "library", "using", "ctypes", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/app.py#L34-L41
train
38,318
codelv/enaml-native
src/enamlnative/ios/app.py
ENBridge._default_bridge
def _default_bridge(self): """ Get an instance of the ENBridge object using ctypes. """ objc = self.objc ENBridge = objc.objc_getClass('ENBridge') return objc.objc_msgSend(ENBridge, objc.sel_registerName('instance'))
python
def _default_bridge(self): """ Get an instance of the ENBridge object using ctypes. """ objc = self.objc ENBridge = objc.objc_getClass('ENBridge') return objc.objc_msgSend(ENBridge, objc.sel_registerName('instance'))
[ "def", "_default_bridge", "(", "self", ")", ":", "objc", "=", "self", ".", "objc", "ENBridge", "=", "objc", ".", "objc_getClass", "(", "'ENBridge'", ")", "return", "objc", ".", "objc_msgSend", "(", "ENBridge", ",", "objc", ".", "sel_registerName", "(", "'i...
Get an instance of the ENBridge object using ctypes.
[ "Get", "an", "instance", "of", "the", "ENBridge", "object", "using", "ctypes", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/app.py#L43-L47
train
38,319
codelv/enaml-native
src/enamlnative/ios/app.py
ENBridge.processEvents
def processEvents(self, data): """ Sends msgpack data to the ENBridge instance by calling the processEvents method via ctypes. """ objc = self.objc bridge = self.bridge #: This must come after the above as it changes the arguments! 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))
python
def processEvents(self, data): """ Sends msgpack data to the ENBridge instance by calling the processEvents method via ctypes. """ objc = self.objc bridge = self.bridge #: This must come after the above as it changes the arguments! 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))
[ "def", "processEvents", "(", "self", ",", "data", ")", ":", "objc", "=", "self", ".", "objc", "bridge", "=", "self", ".", "bridge", "#: This must come after the above as it changes the arguments!", "objc", ".", "objc_msgSend", ".", "argtypes", "=", "[", "ctypes", ...
Sends msgpack data to the ENBridge instance by calling the processEvents method via ctypes.
[ "Sends", "msgpack", "data", "to", "the", "ENBridge", "instance", "by", "calling", "the", "processEvents", "method", "via", "ctypes", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/app.py#L49-L59
train
38,320
codelv/enaml-native
src/enamlnative/core/eventloop/ioloop.py
IOLoop.log_stack
def log_stack(self, signal, frame): """Signal handler to log the stack trace of the current thread. For use with `set_blocking_signal_threshold`. """ gen_log.warning('IOLoop blocked for %f seconds in\n%s', self._blocking_signal_threshold, ''.join(traceback.format_stack(frame)))
python
def log_stack(self, signal, frame): """Signal handler to log the stack trace of the current thread. For use with `set_blocking_signal_threshold`. """ gen_log.warning('IOLoop blocked for %f seconds in\n%s', self._blocking_signal_threshold, ''.join(traceback.format_stack(frame)))
[ "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", "(",...
Signal handler to log the stack trace of the current thread. For use with `set_blocking_signal_threshold`.
[ "Signal", "handler", "to", "log", "the", "stack", "trace", "of", "the", "current", "thread", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/ioloop.py#L394-L401
train
38,321
codelv/enaml-native
src/enamlnative/core/eventloop/ioloop.py
IOLoop.handle_callback_exception
def handle_callback_exception(self, callback): """This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The exception itself is not passed explicitly, but is available in `sys.exc_info`. """ if self._error_handler: self._error_handler(callback) else: app_log.error("Exception in callback %r", callback, exc_info=True)
python
def handle_callback_exception(self, callback): """This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The exception itself is not passed explicitly, but is available in `sys.exc_info`. """ if self._error_handler: self._error_handler(callback) else: app_log.error("Exception in callback %r", callback, exc_info=True)
[ "def", "handle_callback_exception", "(", "self", ",", "callback", ")", ":", "if", "self", ".", "_error_handler", ":", "self", ".", "_error_handler", "(", "callback", ")", "else", ":", "app_log", ".", "error", "(", "\"Exception in callback %r\"", ",", "callback",...
This method is called whenever a callback run by the `IOLoop` throws an exception. By default simply logs the exception as an error. Subclasses may override this method to customize reporting of exceptions. The exception itself is not passed explicitly, but is available in `sys.exc_info`.
[ "This", "method", "is", "called", "whenever", "a", "callback", "run", "by", "the", "IOLoop", "throws", "an", "exception", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/ioloop.py#L679-L692
train
38,322
codelv/enaml-native
src/enamlnative/core/eventloop/ioloop.py
IOLoop.close_fd
def close_fd(self, fd): """Utility method to close an ``fd``. If ``fd`` is a file-like object, we close it directly; otherwise we use `os.close`. This method is provided for use by `IOLoop` subclasses (in implementations of ``IOLoop.close(all_fds=True)`` and should not generally be used by application code. .. versionadded:: 4.0 """ try: try: fd.close() except AttributeError: os.close(fd) except OSError: pass
python
def close_fd(self, fd): """Utility method to close an ``fd``. If ``fd`` is a file-like object, we close it directly; otherwise we use `os.close`. This method is provided for use by `IOLoop` subclasses (in implementations of ``IOLoop.close(all_fds=True)`` and should not generally be used by application code. .. versionadded:: 4.0 """ try: try: fd.close() except AttributeError: os.close(fd) except OSError: pass
[ "def", "close_fd", "(", "self", ",", "fd", ")", ":", "try", ":", "try", ":", "fd", ".", "close", "(", ")", "except", "AttributeError", ":", "os", ".", "close", "(", "fd", ")", "except", "OSError", ":", "pass" ]
Utility method to close an ``fd``. If ``fd`` is a file-like object, we close it directly; otherwise we use `os.close`. This method is provided for use by `IOLoop` subclasses (in implementations of ``IOLoop.close(all_fds=True)`` and should not generally be used by application code. .. versionadded:: 4.0
[ "Utility", "method", "to", "close", "an", "fd", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/ioloop.py#L715-L733
train
38,323
codelv/enaml-native
src/enamlnative/android/android_snackbar.py
AndroidSnackbar.on_widget_created
def on_widget_created(self, ref): """ Using Snackbar.make returns async so we have to initialize it later. """ d = self.declaration self.widget = Snackbar(__id__=ref) self.init_widget()
python
def on_widget_created(self, ref): """ Using Snackbar.make returns async so we have to initialize it later. """ d = self.declaration self.widget = Snackbar(__id__=ref) self.init_widget()
[ "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.
[ "Using", "Snackbar", ".", "make", "returns", "async", "so", "we", "have", "to", "initialize", "it", "later", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_snackbar.py#L117-L124
train
38,324
codelv/enaml-native
src/enamlnative/android/android_snackbar.py
AndroidSnackbar.set_duration
def set_duration(self, duration): """ 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`. """ if duration == 0: self.widget.setDuration(-2) #: Infinite else: self.widget.setDuration(0)
python
def set_duration(self, duration): """ 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`. """ if duration == 0: self.widget.setDuration(-2) #: Infinite else: self.widget.setDuration(0)
[ "def", "set_duration", "(", "self", ",", "duration", ")", ":", "if", "duration", "==", "0", ":", "self", ".", "widget", ".", "setDuration", "(", "-", "2", ")", "#: Infinite", "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`.
[ "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", "duratio...
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_snackbar.py#L181-L191
train
38,325
codelv/enaml-native
src/enamlnative/android/android_text_view.py
AndroidTextView.set_text
def set_text(self, text): """ Set the text in the widget. """ d = self.declaration if d.input_type == 'html': text = Spanned(__id__=Html.fromHtml(text)) self.widget.setTextKeepState(text)
python
def set_text(self, text): """ Set the text in the widget. """ d = self.declaration if d.input_type == 'html': text = Spanned(__id__=Html.fromHtml(text)) self.widget.setTextKeepState(text)
[ "def", "set_text", "(", "self", ",", "text", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", ".", "input_type", "==", "'html'", ":", "text", "=", "Spanned", "(", "__id__", "=", "Html", ".", "fromHtml", "(", "text", ")", ")", "self", ".",...
Set the text in the widget.
[ "Set", "the", "text", "in", "the", "widget", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_text_view.py#L209-L216
train
38,326
codelv/enaml-native
src/enamlnative/core/bridge.py
encode
def encode(obj): """ Encode an object for proper decoding by Java or ObjC """ if hasattr(obj, '__id__'): return msgpack.ExtType(ExtType.REF, msgpack.packb(obj.__id__)) return obj
python
def encode(obj): """ Encode an object for proper decoding by Java or ObjC """ if hasattr(obj, '__id__'): return msgpack.ExtType(ExtType.REF, msgpack.packb(obj.__id__)) return obj
[ "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
[ "Encode", "an", "object", "for", "proper", "decoding", "by", "Java", "or", "ObjC" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/bridge.py#L84-L89
train
38,327
codelv/enaml-native
src/enamlnative/core/bridge.py
get_handler
def get_handler(ptr, method): """ Dereference the pointer and return the handler 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)
python
def get_handler(ptr, method): """ Dereference the pointer and return the handler 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)
[ "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\"", "."...
Dereference the pointer and return the handler method.
[ "Dereference", "the", "pointer", "and", "return", "the", "handler", "method", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/bridge.py#L119-L129
train
38,328
codelv/enaml-native
src/enamlnative/core/bridge.py
BridgeMethod.suppressed
def suppressed(self, obj): """ Suppress calls within this context to avoid feedback loops""" obj.__suppressed__[self.name] = True yield obj.__suppressed__[self.name] = False
python
def suppressed(self, obj): """ Suppress calls within this context to avoid feedback loops""" obj.__suppressed__[self.name] = True yield obj.__suppressed__[self.name] = False
[ "def", "suppressed", "(", "self", ",", "obj", ")", ":", "obj", ".", "__suppressed__", "[", "self", ".", "name", "]", "=", "True", "yield", "obj", ".", "__suppressed__", "[", "self", ".", "name", "]", "=", "False" ]
Suppress calls within this context to avoid feedback loops
[ "Suppress", "calls", "within", "this", "context", "to", "avoid", "feedback", "loops" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/bridge.py#L159-L163
train
38,329
codelv/enaml-native
src/enamlnative/android/android_wifi.py
WifiManager.request_permission
def request_permission(cls, permissions): """ Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied. """ 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
python
def request_permission(cls, permissions): """ Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied. """ 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
[ "def", "request_permission", "(", "cls", ",", "permissions", ")", ":", "app", "=", "AndroidApplication", ".", "instance", "(", ")", "f", "=", "app", ".", "create_future", "(", ")", "def", "on_result", "(", "perms", ")", ":", "allowed", "=", "True", "for"...
Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied.
[ "Requests", "permission", "and", "returns", "an", "future", "result", "that", "returns", "a", "boolean", "indicating", "if", "all", "the", "given", "permission", "were", "granted", "or", "denied", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_wifi.py#L401-L417
train
38,330
codelv/enaml-native
src/enamlnative/core/eventloop/concurrent.py
return_future
def return_future(f): """Decorator to make a function that returns via callback return a `Future`. The wrapped function should take a ``callback`` keyword argument and invoke it with one argument when it has finished. To signal failure, the function can simply raise an exception (which will be captured by the `.StackContext` and passed along to the ``Future``). From the caller's perspective, the callback argument is optional. If one is given, it will be invoked when the function is complete with `Future.result()` as an argument. If the function fails, the callback will not be run and an exception will be raised into the surrounding `.StackContext`. If no callback is given, the caller should use the ``Future`` to wait for the function to complete (perhaps by yielding it in a `.gen.engine` function, or passing it to `.IOLoop.add_future`). Usage: .. testcode:: @return_future def future_func(arg1, arg2, callback): # Do stuff (possibly asynchronous) callback(result) @gen.engine def caller(callback): yield future_func(arg1, arg2) callback() .. Note that ``@return_future`` and ``@gen.engine`` can be applied to the same function, provided ``@return_future`` appears first. However, consider using ``@gen.coroutine`` instead of this combination. """ 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: # If the initial synchronous part of f() raised an exception, # go ahead and raise it to the caller directly without waiting # for them to inspect the Future. future.result() # If the caller passed in a callback, schedule it to be called # when the future resolves. It is important that this happens # just before we return the future, or else we risk confusing # stack contexts with multiple exceptions (one here with the # immediate exception, and again when the future resolves and # the callback triggers its exception by calling 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
python
def return_future(f): """Decorator to make a function that returns via callback return a `Future`. The wrapped function should take a ``callback`` keyword argument and invoke it with one argument when it has finished. To signal failure, the function can simply raise an exception (which will be captured by the `.StackContext` and passed along to the ``Future``). From the caller's perspective, the callback argument is optional. If one is given, it will be invoked when the function is complete with `Future.result()` as an argument. If the function fails, the callback will not be run and an exception will be raised into the surrounding `.StackContext`. If no callback is given, the caller should use the ``Future`` to wait for the function to complete (perhaps by yielding it in a `.gen.engine` function, or passing it to `.IOLoop.add_future`). Usage: .. testcode:: @return_future def future_func(arg1, arg2, callback): # Do stuff (possibly asynchronous) callback(result) @gen.engine def caller(callback): yield future_func(arg1, arg2) callback() .. Note that ``@return_future`` and ``@gen.engine`` can be applied to the same function, provided ``@return_future`` appears first. However, consider using ``@gen.coroutine`` instead of this combination. """ 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: # If the initial synchronous part of f() raised an exception, # go ahead and raise it to the caller directly without waiting # for them to inspect the Future. future.result() # If the caller passed in a callback, schedule it to be called # when the future resolves. It is important that this happens # just before we return the future, or else we risk confusing # stack contexts with multiple exceptions (one here with the # immediate exception, and again when the future resolves and # the callback triggers its exception by calling 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
[ "def", "return_future", "(", "f", ")", ":", "replacer", "=", "ArgReplacer", "(", "f", ",", "'callback'", ")", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "future", "=", "Trac...
Decorator to make a function that returns via callback return a `Future`. The wrapped function should take a ``callback`` keyword argument and invoke it with one argument when it has finished. To signal failure, the function can simply raise an exception (which will be captured by the `.StackContext` and passed along to the ``Future``). From the caller's perspective, the callback argument is optional. If one is given, it will be invoked when the function is complete with `Future.result()` as an argument. If the function fails, the callback will not be run and an exception will be raised into the surrounding `.StackContext`. If no callback is given, the caller should use the ``Future`` to wait for the function to complete (perhaps by yielding it in a `.gen.engine` function, or passing it to `.IOLoop.add_future`). Usage: .. testcode:: @return_future def future_func(arg1, arg2, callback): # Do stuff (possibly asynchronous) callback(result) @gen.engine def caller(callback): yield future_func(arg1, arg2) callback() .. Note that ``@return_future`` and ``@gen.engine`` can be applied to the same function, provided ``@return_future`` appears first. However, consider using ``@gen.coroutine`` instead of this combination.
[ "Decorator", "to", "make", "a", "function", "that", "returns", "via", "callback", "return", "a", "Future", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/concurrent.py#L419-L502
train
38,331
codelv/enaml-native
src/enamlnative/core/eventloop/concurrent.py
Future.result
def result(self, timeout=None): """If the operation succeeded, return its result. If it failed, re-raise its exception. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used. """ 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
python
def result(self, timeout=None): """If the operation succeeded, return its result. If it failed, re-raise its exception. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used. """ 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
[ "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"...
If the operation succeeded, return its result. If it failed, re-raise its exception. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used.
[ "If", "the", "operation", "succeeded", "return", "its", "result", ".", "If", "it", "failed", "re", "-", "raise", "its", "exception", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/concurrent.py#L224-L241
train
38,332
codelv/enaml-native
src/enamlnative/core/eventloop/concurrent.py
Future.exception
def exception(self, timeout=None): """If the operation raised an exception, return the `Exception` object. Otherwise returns None. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used. """ self._clear_tb_log() if self._exc_info is not None: return self._exc_info[1] else: self._check_done() return None
python
def exception(self, timeout=None): """If the operation raised an exception, return the `Exception` object. Otherwise returns None. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used. """ self._clear_tb_log() if self._exc_info is not None: return self._exc_info[1] else: self._check_done() return None
[ "def", "exception", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "_clear_tb_log", "(", ")", "if", "self", ".", "_exc_info", "is", "not", "None", ":", "return", "self", ".", "_exc_info", "[", "1", "]", "else", ":", "self", ".", "...
If the operation raised an exception, return the `Exception` object. Otherwise returns None. This method takes a ``timeout`` argument for compatibility with `concurrent.futures.Future` but it is an error to call it before the `Future` is done, so the ``timeout`` is never used.
[ "If", "the", "operation", "raised", "an", "exception", "return", "the", "Exception", "object", ".", "Otherwise", "returns", "None", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/concurrent.py#L243-L256
train
38,333
codelv/enaml-native
src/enamlnative/core/eventloop/concurrent.py
Future.add_done_callback
def add_done_callback(self, fn): """Attaches the given callback to the `Future`. It will be invoked with the `Future` as its argument when the Future has finished running and its result is available. In Tornado consider using `.IOLoop.add_future` instead of calling `add_done_callback` directly. """ if self._done: fn(self) else: self._callbacks.append(fn)
python
def add_done_callback(self, fn): """Attaches the given callback to the `Future`. It will be invoked with the `Future` as its argument when the Future has finished running and its result is available. In Tornado consider using `.IOLoop.add_future` instead of calling `add_done_callback` directly. """ if self._done: fn(self) else: self._callbacks.append(fn)
[ "def", "add_done_callback", "(", "self", ",", "fn", ")", ":", "if", "self", ".", "_done", ":", "fn", "(", "self", ")", "else", ":", "self", ".", "_callbacks", ".", "append", "(", "fn", ")" ]
Attaches the given callback to the `Future`. It will be invoked with the `Future` as its argument when the Future has finished running and its result is available. In Tornado consider using `.IOLoop.add_future` instead of calling `add_done_callback` directly.
[ "Attaches", "the", "given", "callback", "to", "the", "Future", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/concurrent.py#L258-L269
train
38,334
codelv/enaml-native
src/enamlnative/core/eventloop/concurrent.py
Future.set_exception
def set_exception(self, exception): """Sets the exception of a ``Future.``""" self.set_exc_info( (exception.__class__, exception, getattr(exception, '__traceback__', None)))
python
def set_exception(self, exception): """Sets the exception of a ``Future.``""" self.set_exc_info( (exception.__class__, exception, getattr(exception, '__traceback__', None)))
[ "def", "set_exception", "(", "self", ",", "exception", ")", ":", "self", ".", "set_exc_info", "(", "(", "exception", ".", "__class__", ",", "exception", ",", "getattr", "(", "exception", ",", "'__traceback__'", ",", "None", ")", ")", ")" ]
Sets the exception of a ``Future.``
[ "Sets", "the", "exception", "of", "a", "Future", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/concurrent.py#L280-L285
train
38,335
codelv/enaml-native
src/enamlnative/core/eventloop/concurrent.py
Future.set_exc_info
def set_exc_info(self, exc_info): """Sets the exception information of a ``Future.`` Preserves tracebacks on Python 2. .. versionadded:: 4.0 """ 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: # Activate the logger after all callbacks have had a # chance to call result() or exception(). if self._log_traceback and self._tb_logger is not None: self._tb_logger.activate() self._exc_info = exc_info
python
def set_exc_info(self, exc_info): """Sets the exception information of a ``Future.`` Preserves tracebacks on Python 2. .. versionadded:: 4.0 """ 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: # Activate the logger after all callbacks have had a # chance to call result() or exception(). if self._log_traceback and self._tb_logger is not None: self._tb_logger.activate() self._exc_info = exc_info
[ "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",...
Sets the exception information of a ``Future.`` Preserves tracebacks on Python 2. .. versionadded:: 4.0
[ "Sets", "the", "exception", "information", "of", "a", "Future", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/concurrent.py#L295-L314
train
38,336
codelv/enaml-native
src/enamlnative/ios/uikit_view_group.py
UiKitViewGroup.destroy
def destroy(self): """ A reimplemented destructor that destroys the layout widget. """ layout = self.layout if layout is not None: layout.removeFromSuperview() self.layout = None super(UiKitViewGroup, self).destroy()
python
def destroy(self): """ A reimplemented destructor that destroys the layout widget. """ layout = self.layout if layout is not None: layout.removeFromSuperview() self.layout = None super(UiKitViewGroup, self).destroy()
[ "def", "destroy", "(", "self", ")", ":", "layout", "=", "self", ".", "layout", "if", "layout", "is", "not", "None", ":", "layout", ".", "removeFromSuperview", "(", ")", "self", ".", "layout", "=", "None", "super", "(", "UiKitViewGroup", ",", "self", ")...
A reimplemented destructor that destroys the layout widget.
[ "A", "reimplemented", "destructor", "that", "destroys", "the", "layout", "widget", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/uikit_view_group.py#L108-L116
train
38,337
codelv/enaml-native
src/enamlnative/ios/bridge.py
ObjcMethod.pack_args
def pack_args(self, obj, *args, **kwargs): """ Arguments must be packed according to the kwargs passed and the signature defined. """ signature = self.__signature__ #: No arguments expected if not signature: return (self.name, []) #: Build args, first is a string, subsequent are dictionaries 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 #: Sig is a dict so we must pull out the matching kwarg 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: #: If we get here something is wrong raise ValueError("Unexpected or missing argument at index {}. " "Expected {}".format(i, sig)) return ("".join(method_name), bridge_args)
python
def pack_args(self, obj, *args, **kwargs): """ Arguments must be packed according to the kwargs passed and the signature defined. """ signature = self.__signature__ #: No arguments expected if not signature: return (self.name, []) #: Build args, first is a string, subsequent are dictionaries 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 #: Sig is a dict so we must pull out the matching kwarg 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: #: If we get here something is wrong raise ValueError("Unexpected or missing argument at index {}. " "Expected {}".format(i, sig)) return ("".join(method_name), bridge_args)
[ "def", "pack_args", "(", "self", ",", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "signature", "=", "self", ".", "__signature__", "#: No arguments expected", "if", "not", "signature", ":", "return", "(", "self", ".", "name", ",", "[", "...
Arguments must be packed according to the kwargs passed and the signature defined.
[ "Arguments", "must", "be", "packed", "according", "to", "the", "kwargs", "passed", "and", "the", "signature", "defined", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/bridge.py#L59-L91
train
38,338
codelv/enaml-native
src/enamlnative/core/eventloop/stack_context.py
_remove_deactivated
def _remove_deactivated(contexts): """Remove deactivated handlers from the chain""" # Clean ctx handlers stack_contexts = tuple([h for h in contexts[0] if h.active]) # Find new head head = contexts[1] while head is not None and not head.active: head = head.old_contexts[1] # Process chain 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)
python
def _remove_deactivated(contexts): """Remove deactivated handlers from the chain""" # Clean ctx handlers stack_contexts = tuple([h for h in contexts[0] if h.active]) # Find new head head = contexts[1] while head is not None and not head.active: head = head.old_contexts[1] # Process chain 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)
[ "def", "_remove_deactivated", "(", "contexts", ")", ":", "# Clean ctx handlers", "stack_contexts", "=", "tuple", "(", "[", "h", "for", "h", "in", "contexts", "[", "0", "]", "if", "h", ".", "active", "]", ")", "# Find new head", "head", "=", "contexts", "["...
Remove deactivated handlers from the chain
[ "Remove", "deactivated", "handlers", "from", "the", "chain" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/stack_context.py#L246-L269
train
38,339
codelv/enaml-native
src/enamlnative/core/eventloop/stack_context.py
wrap
def wrap(fn): """Returns a callable object that will restore the current `StackContext` when executed. Use this whenever saving a callback to be executed later in a different execution context (either in a different thread or asynchronously in the same thread). """ # Check if function is already wrapped if fn is None or hasattr(fn, '_wrapped'): return fn # Capture current stack head # TODO: Any other better way to store contexts and update them in wrapped function? cap_contexts = [_state.contexts] if not cap_contexts[0][0] and not cap_contexts[0][1]: # Fast path when there are no active contexts. 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: # Capture old state current_state = _state.contexts # Remove deactivated items cap_contexts[0] = contexts = _remove_deactivated(cap_contexts[0]) # Force new state _state.contexts = contexts # Current exception exc = (None, None, None) top = None # Apply stack contexts last_ctx = 0 stack = contexts[0] # Apply state for n in stack: try: n.enter() last_ctx += 1 except: # Exception happened. Record exception info and store top-most handler exc = sys.exc_info() top = n.old_contexts[1] # Execute callback if no exception happened while restoring state if top is None: try: ret = fn(*args, **kwargs) except: exc = sys.exc_info() top = contexts[1] # If there was exception, try to handle it by going through the exception chain if top is not None: exc = _handle_exception(top, exc) else: # Otherwise take shorter path and run stack contexts in reverse order 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 if exception happened while unrolling, take longer exception handler path if top is not None: exc = _handle_exception(top, exc) # If exception was not handled, raise it if exc != (None, None, None): raise_exc_info(exc) finally: _state.contexts = current_state return ret wrapped._wrapped = True return wrapped
python
def wrap(fn): """Returns a callable object that will restore the current `StackContext` when executed. Use this whenever saving a callback to be executed later in a different execution context (either in a different thread or asynchronously in the same thread). """ # Check if function is already wrapped if fn is None or hasattr(fn, '_wrapped'): return fn # Capture current stack head # TODO: Any other better way to store contexts and update them in wrapped function? cap_contexts = [_state.contexts] if not cap_contexts[0][0] and not cap_contexts[0][1]: # Fast path when there are no active contexts. 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: # Capture old state current_state = _state.contexts # Remove deactivated items cap_contexts[0] = contexts = _remove_deactivated(cap_contexts[0]) # Force new state _state.contexts = contexts # Current exception exc = (None, None, None) top = None # Apply stack contexts last_ctx = 0 stack = contexts[0] # Apply state for n in stack: try: n.enter() last_ctx += 1 except: # Exception happened. Record exception info and store top-most handler exc = sys.exc_info() top = n.old_contexts[1] # Execute callback if no exception happened while restoring state if top is None: try: ret = fn(*args, **kwargs) except: exc = sys.exc_info() top = contexts[1] # If there was exception, try to handle it by going through the exception chain if top is not None: exc = _handle_exception(top, exc) else: # Otherwise take shorter path and run stack contexts in reverse order 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 if exception happened while unrolling, take longer exception handler path if top is not None: exc = _handle_exception(top, exc) # If exception was not handled, raise it if exc != (None, None, None): raise_exc_info(exc) finally: _state.contexts = current_state return ret wrapped._wrapped = True return wrapped
[ "def", "wrap", "(", "fn", ")", ":", "# Check if function is already wrapped", "if", "fn", "is", "None", "or", "hasattr", "(", "fn", ",", "'_wrapped'", ")", ":", "return", "fn", "# Capture current stack head", "# TODO: Any other better way to store contexts and update them...
Returns a callable object that will restore the current `StackContext` when executed. Use this whenever saving a callback to be executed later in a different execution context (either in a different thread or asynchronously in the same thread).
[ "Returns", "a", "callable", "object", "that", "will", "restore", "the", "current", "StackContext", "when", "executed", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/stack_context.py#L272-L368
train
38,340
codelv/enaml-native
src/enamlnative/android/android_list_view.py
AndroidListView.get_declared_items
def get_declared_items(self): """ Override to do it manually """ for k, v in super(AndroidListView, self).get_declared_items(): if k == 'layout': yield k, v break
python
def get_declared_items(self): """ Override to do it manually """ for k, v in super(AndroidListView, self).get_declared_items(): if k == 'layout': yield k, v break
[ "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
[ "Override", "to", "do", "it", "manually" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_list_view.py#L201-L208
train
38,341
codelv/enaml-native
src/enamlnative/android/android_list_view.py
AndroidListView.on_recycle_view
def on_recycle_view(self, index, position): """ Update the item the view at the given index should display """ item = self.list_items[index] self.item_mapping[position] = item item.recycle_view(position)
python
def on_recycle_view(self, index, position): """ Update the item the view at the given index should display """ item = self.list_items[index] self.item_mapping[position] = item item.recycle_view(position)
[ "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
[ "Update", "the", "item", "the", "view", "at", "the", "given", "index", "should", "display" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_list_view.py#L234-L239
train
38,342
codelv/enaml-native
src/enamlnative/android/android_list_view.py
AndroidListView.refresh_views
def refresh_views(self, change=None): """ Set the views that the adapter will cycle through. """ adapter = self.adapter # Set initial ListItem state 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])
python
def refresh_views(self, change=None): """ Set the views that the adapter will cycle through. """ adapter = self.adapter # Set initial ListItem state 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])
[ "def", "refresh_views", "(", "self", ",", "change", "=", "None", ")", ":", "adapter", "=", "self", ".", "adapter", "# Set initial ListItem state", "item_mapping", "=", "self", ".", "item_mapping", "for", "i", ",", "item", "in", "enumerate", "(", "self", ".",...
Set the views that the adapter will cycle through.
[ "Set", "the", "views", "that", "the", "adapter", "will", "cycle", "through", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_list_view.py#L247-L260
train
38,343
codelv/enaml-native
src/enamlnative/android/android_list_view.py
AndroidListView._on_items_changed
def _on_items_changed(self, change): """ Observe container events on the items list and update the adapter appropriately. """ 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'): # Reset everything for these self.adapter.notifyDataSetChanged()
python
def _on_items_changed(self, change): """ Observe container events on the items list and update the adapter appropriately. """ 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'): # Reset everything for these self.adapter.notifyDataSetChanged()
[ "def", "_on_items_changed", "(", "self", ",", "change", ")", ":", "if", "change", "[", "'type'", "]", "!=", "'container'", ":", "return", "op", "=", "change", "[", "'operation'", "]", "if", "op", "==", "'append'", ":", "i", "=", "len", "(", "change", ...
Observe container events on the items list and update the adapter appropriately.
[ "Observe", "container", "events", "on", "the", "items", "list", "and", "update", "the", "adapter", "appropriately", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_list_view.py#L268-L290
train
38,344
codelv/enaml-native
src/enamlnative/android/android_list_view.py
AndroidListItem.recycle_view
def recycle_view(self, position): """ Tell the view to render the item at the given 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
python
def recycle_view(self, position): """ Tell the view to render the item at the given 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
[ "def", "recycle_view", "(", "self", ",", "position", ")", ":", "d", "=", "self", ".", "declaration", "if", "position", "<", "len", "(", "d", ".", "parent", ".", "items", ")", ":", "d", ".", "index", "=", "position", "d", ".", "item", "=", "d", "....
Tell the view to render the item at the given position
[ "Tell", "the", "view", "to", "render", "the", "item", "at", "the", "given", "position" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_list_view.py#L351-L360
train
38,345
codelv/enaml-native
src/enamlnative/core/eventloop/util.py
Configurable.configured_class
def configured_class(cls): # type: () -> type """Returns the currently configured class.""" base = cls.configurable_base() # Manually mangle the private name to see whether this base # has been configured (and not another base higher in the # hierarchy). if base.__dict__.get('_Configurable__impl_class') is None: base.__impl_class = cls.configurable_default() return base.__impl_class
python
def configured_class(cls): # type: () -> type """Returns the currently configured class.""" base = cls.configurable_base() # Manually mangle the private name to see whether this base # has been configured (and not another base higher in the # hierarchy). if base.__dict__.get('_Configurable__impl_class') is None: base.__impl_class = cls.configurable_default() return base.__impl_class
[ "def", "configured_class", "(", "cls", ")", ":", "# type: () -> type", "base", "=", "cls", ".", "configurable_base", "(", ")", "# Manually mangle the private name to see whether this base", "# has been configured (and not another base higher in the", "# hierarchy).", "if", "base"...
Returns the currently configured class.
[ "Returns", "the", "currently", "configured", "class", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/util.py#L359-L368
train
38,346
codelv/enaml-native
src/enamlnative/android/android_toast.py
AndroidToast.child_added
def child_added(self, child): """ Overwrite the view """ view = child.widget if view is not None: self.toast.setView(view)
python
def child_added(self, child): """ Overwrite the view """ view = child.widget if view is not None: self.toast.setView(view)
[ "def", "child_added", "(", "self", ",", "child", ")", ":", "view", "=", "child", ".", "widget", "if", "view", "is", "not", "None", ":", "self", ".", "toast", ".", "setView", "(", "view", ")" ]
Overwrite the view
[ "Overwrite", "the", "view" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_toast.py#L89-L93
train
38,347
codelv/enaml-native
src/enamlnative/android/android_toast.py
AndroidToast.on_make_toast
def on_make_toast(self, ref): """ Using Toast.makeToast returns async so we have to initialize it later. """ d = self.declaration self.toast = Toast(__id__=ref) self.init_widget()
python
def on_make_toast(self, ref): """ Using Toast.makeToast returns async so we have to initialize it later. """ d = self.declaration self.toast = Toast(__id__=ref) self.init_widget()
[ "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.
[ "Using", "Toast", ".", "makeToast", "returns", "async", "so", "we", "have", "to", "initialize", "it", "later", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_toast.py#L95-L102
train
38,348
codelv/enaml-native
src/enamlnative/android/android_location.py
LocationManager.start
def start(cls, callback, provider='gps', min_time=1000, min_distance=0): """ Convenience method that checks and requests permission if necessary and if successful calls the callback with a populated `Location` instance on updates. Note you must have the permissions in your manifest or requests will be denied immediately. """ app = AndroidApplication.instance() f = app.create_future() def on_success(lm): #: When we have finally have permission lm.onLocationChanged.connect(callback) #: Save a reference to our listener #: because we may want to stop updates 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): #: When our permission request is accepted or decliend. if allowed: LocationManager.get().then(on_success) else: #: Access denied 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) #: Check permission LocationManager.check_permission( fine=provider == 'gps').then(on_perm_check) return f
python
def start(cls, callback, provider='gps', min_time=1000, min_distance=0): """ Convenience method that checks and requests permission if necessary and if successful calls the callback with a populated `Location` instance on updates. Note you must have the permissions in your manifest or requests will be denied immediately. """ app = AndroidApplication.instance() f = app.create_future() def on_success(lm): #: When we have finally have permission lm.onLocationChanged.connect(callback) #: Save a reference to our listener #: because we may want to stop updates 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): #: When our permission request is accepted or decliend. if allowed: LocationManager.get().then(on_success) else: #: Access denied 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) #: Check permission LocationManager.check_permission( fine=provider == 'gps').then(on_perm_check) return f
[ "def", "start", "(", "cls", ",", "callback", ",", "provider", "=", "'gps'", ",", "min_time", "=", "1000", ",", "min_distance", "=", "0", ")", ":", "app", "=", "AndroidApplication", ".", "instance", "(", ")", "f", "=", "app", ".", "create_future", "(", ...
Convenience method that checks and requests permission if necessary and if successful calls the callback with a populated `Location` instance on updates. Note you must have the permissions in your manifest or requests will be denied immediately.
[ "Convenience", "method", "that", "checks", "and", "requests", "permission", "if", "necessary", "and", "if", "successful", "calls", "the", "callback", "with", "a", "populated", "Location", "instance", "on", "updates", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_location.py#L61-L105
train
38,349
codelv/enaml-native
src/enamlnative/android/android_location.py
LocationManager.stop
def stop(cls): """ Stops location updates if currently updating. """ manager = LocationManager.instance() if manager: for l in manager.listeners: manager.removeUpdates(l) manager.listeners = []
python
def stop(cls): """ Stops location updates if currently updating. """ manager = LocationManager.instance() if manager: for l in manager.listeners: manager.removeUpdates(l) manager.listeners = []
[ "def", "stop", "(", "cls", ")", ":", "manager", "=", "LocationManager", ".", "instance", "(", ")", "if", "manager", ":", "for", "l", "in", "manager", ".", "listeners", ":", "manager", ".", "removeUpdates", "(", "l", ")", "manager", ".", "listeners", "=...
Stops location updates if currently updating.
[ "Stops", "location", "updates", "if", "currently", "updating", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_location.py#L108-L116
train
38,350
codelv/enaml-native
src/enamlnative/android/android_location.py
LocationManager.request_permission
def request_permission(cls, fine=True): """ Requests permission and returns an async result that returns a boolean indicating if the permission was granted or denied. """ 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
python
def request_permission(cls, fine=True): """ Requests permission and returns an async result that returns a boolean indicating if the permission was granted or denied. """ 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
[ "def", "request_permission", "(", "cls", ",", "fine", "=", "True", ")", ":", "app", "=", "AndroidApplication", ".", "instance", "(", ")", "permission", "=", "(", "cls", ".", "ACCESS_FINE_PERMISSION", "if", "fine", "else", "cls", ".", "ACCESS_COARSE_PERMISSION"...
Requests permission and returns an async result that returns a boolean indicating if the permission was granted or denied.
[ "Requests", "permission", "and", "returns", "an", "async", "result", "that", "returns", "a", "boolean", "indicating", "if", "the", "permission", "was", "granted", "or", "denied", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_location.py#L132-L147
train
38,351
codelv/enaml-native
src/enamlnative/android/android_web_view.py
AndroidWebView.destroy
def destroy(self): """ Destroy the client """ if self.client: #: Stop listening self.client.setWebView(self.widget, None) del self.client super(AndroidWebView, self).destroy()
python
def destroy(self): """ Destroy the client """ if self.client: #: Stop listening self.client.setWebView(self.widget, None) del self.client super(AndroidWebView, self).destroy()
[ "def", "destroy", "(", "self", ")", ":", "if", "self", ".", "client", ":", "#: Stop listening", "self", ".", "client", ".", "setWebView", "(", "self", ".", "widget", ",", "None", ")", "del", "self", ".", "client", "super", "(", "AndroidWebView", ",", "...
Destroy the client
[ "Destroy", "the", "client" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_web_view.py#L95-L103
train
38,352
codelv/enaml-native
src/enamlnative/android/android_radio_group.py
AndroidRadioGroup.set_checked
def set_checked(self, checked): """ Properly check the correct radio button. """ if not checked: self.widget.clearCheck() else: #: Checked is a reference to the radio declaration #: so we need to get the ID of it rb = checked.proxy.widget if not rb: return self.widget.check(rb.getId())
python
def set_checked(self, checked): """ Properly check the correct radio button. """ if not checked: self.widget.clearCheck() else: #: Checked is a reference to the radio declaration #: so we need to get the ID of it rb = checked.proxy.widget if not rb: return self.widget.check(rb.getId())
[ "def", "set_checked", "(", "self", ",", "checked", ")", ":", "if", "not", "checked", ":", "self", ".", "widget", ".", "clearCheck", "(", ")", "else", ":", "#: Checked is a reference to the radio declaration", "#: so we need to get the ID of it", "rb", "=", "checked"...
Properly check the correct radio button.
[ "Properly", "check", "the", "correct", "radio", "button", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_radio_group.py#L89-L101
train
38,353
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication.init_widget
def init_widget(self): """ Initialize on the first call """ #: Add a ActivityLifecycleListener to update the application state activity = self.widget activity.addActivityLifecycleListener(activity.getId()) activity.onActivityLifecycleChanged.connect( self.on_activity_lifecycle_changed) #: Add BackPressedListener to trigger the event activity.addBackPressedListener(activity.getId()) activity.onBackPressed.connect(self.on_back_pressed) #: Add ConfigurationChangedListener to trigger the event activity.addConfigurationChangedListener(activity.getId()) activity.onConfigurationChanged.connect(self.on_configuration_changed)
python
def init_widget(self): """ Initialize on the first call """ #: Add a ActivityLifecycleListener to update the application state activity = self.widget activity.addActivityLifecycleListener(activity.getId()) activity.onActivityLifecycleChanged.connect( self.on_activity_lifecycle_changed) #: Add BackPressedListener to trigger the event activity.addBackPressedListener(activity.getId()) activity.onBackPressed.connect(self.on_back_pressed) #: Add ConfigurationChangedListener to trigger the event activity.addConfigurationChangedListener(activity.getId()) activity.onConfigurationChanged.connect(self.on_configuration_changed)
[ "def", "init_widget", "(", "self", ")", ":", "#: Add a ActivityLifecycleListener to update the application state", "activity", "=", "self", ".", "widget", "activity", ".", "addActivityLifecycleListener", "(", "activity", ".", "getId", "(", ")", ")", "activity", ".", "...
Initialize on the first call
[ "Initialize", "on", "the", "first", "call" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L79-L95
train
38,354
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication.has_permission
def has_permission(self, permission): """ Return a future that resolves with the result of the permission """ f = self.create_future() #: Old versions of android did permissions at install time 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
python
def has_permission(self, permission): """ Return a future that resolves with the result of the permission """ f = self.create_future() #: Old versions of android did permissions at install time 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
[ "def", "has_permission", "(", "self", ",", "permission", ")", ":", "f", "=", "self", ".", "create_future", "(", ")", "#: Old versions of android did permissions at install time", "if", "self", ".", "api_level", "<", "23", ":", "f", ".", "set_result", "(", "True"...
Return a future that resolves with the result of the permission
[ "Return", "a", "future", "that", "resolves", "with", "the", "result", "of", "the", "permission" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L100-L117
train
38,355
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication.request_permissions
def request_permissions(self, permissions): """ Return a future that resolves with the results of the permission requests """ f = self.create_future() #: Old versions of android did permissions at install time 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 #: So next call has a unique code #: On first request, setup our listener, and request the permission if request_code == 0: w.setPermissionResultListener(w.getId()) w.onRequestPermissionsResult.connect(self._on_permission_result) def on_results(code, perms, results): #: Check permissions f.set_result({p: r == Activity.PERMISSION_GRANTED for (p, r) in zip(perms, results)}) #: Save a reference self._permission_requests[request_code] = on_results #: Send out the request self.widget.requestPermissions(permissions, request_code) return f
python
def request_permissions(self, permissions): """ Return a future that resolves with the results of the permission requests """ f = self.create_future() #: Old versions of android did permissions at install time 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 #: So next call has a unique code #: On first request, setup our listener, and request the permission if request_code == 0: w.setPermissionResultListener(w.getId()) w.onRequestPermissionsResult.connect(self._on_permission_result) def on_results(code, perms, results): #: Check permissions f.set_result({p: r == Activity.PERMISSION_GRANTED for (p, r) in zip(perms, results)}) #: Save a reference self._permission_requests[request_code] = on_results #: Send out the request self.widget.requestPermissions(permissions, request_code) return f
[ "def", "request_permissions", "(", "self", ",", "permissions", ")", ":", "f", "=", "self", ".", "create_future", "(", ")", "#: Old versions of android did permissions at install time", "if", "self", ".", "api_level", "<", "23", ":", "f", ".", "set_result", "(", ...
Return a future that resolves with the results of the permission requests
[ "Return", "a", "future", "that", "resolves", "with", "the", "results", "of", "the", "permission", "requests" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L119-L151
train
38,356
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication.show_toast
def show_toast(self, msg, long=True): """ Show a toast message for the given duration. This is an android specific api. Parameters ----------- msg: str Text to display in the toast message long: bool Display for a long or short (system defined) duration """ 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)
python
def show_toast(self, msg, long=True): """ Show a toast message for the given duration. This is an android specific api. Parameters ----------- msg: str Text to display in the toast message long: bool Display for a long or short (system defined) duration """ 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)
[ "def", "show_toast", "(", "self", ",", "msg", ",", "long", "=", "True", ")", ":", "from", ".", "android_toast", "import", "Toast", "def", "on_toast", "(", "ref", ")", ":", "t", "=", "Toast", "(", "__id__", "=", "ref", ")", "t", ".", "show", "(", ...
Show a toast message for the given duration. This is an android specific api. Parameters ----------- msg: str Text to display in the toast message long: bool Display for a long or short (system defined) duration
[ "Show", "a", "toast", "message", "for", "the", "given", "duration", ".", "This", "is", "an", "android", "specific", "api", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L153-L171
train
38,357
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication.on_back_pressed
def on_back_pressed(self): """ 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. """ try: event = {'handled': False} self.back_pressed(event) return bool(event.get('handled', False)) except Exception as e: #: Must return a boolean or we will cause android to abort return False
python
def on_back_pressed(self): """ 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. """ try: event = {'handled': False} self.back_pressed(event) return bool(event.get('handled', False)) except Exception as e: #: Must return a boolean or we will cause android to abort return False
[ "def", "on_back_pressed", "(", "self", ")", ":", "try", ":", "event", "=", "{", "'handled'", ":", "False", "}", "self", ".", "back_pressed", "(", "event", ")", "return", "bool", "(", "event", ".", "get", "(", "'handled'", ",", "False", ")", ")", "exc...
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.
[ "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", "d...
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L182-L196
train
38,358
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication.on_configuration_changed
def on_configuration_changed(self, config): """ Handles a screen configuration change. """ self.width = config['width'] self.height = config['height'] self.orientation = ('square', 'portrait', 'landscape')[ config['orientation']]
python
def on_configuration_changed(self, config): """ Handles a screen configuration change. """ self.width = config['width'] self.height = config['height'] self.orientation = ('square', 'portrait', 'landscape')[ config['orientation']]
[ "def", "on_configuration_changed", "(", "self", ",", "config", ")", ":", "self", ".", "width", "=", "config", "[", "'width'", "]", "self", ".", "height", "=", "config", "[", "'height'", "]", "self", ".", "orientation", "=", "(", "'square'", ",", "'portra...
Handles a screen configuration change.
[ "Handles", "a", "screen", "configuration", "change", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L198-L205
train
38,359
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication.show_view
def show_view(self): """ Show the current `app.view`. This will fade out the previous with the new view. """ if not self.build_info: def on_build_info(info): """ Make sure the build info is ready before we display the view """ 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()
python
def show_view(self): """ Show the current `app.view`. This will fade out the previous with the new view. """ if not self.build_info: def on_build_info(info): """ Make sure the build info is ready before we display the view """ 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()
[ "def", "show_view", "(", "self", ")", ":", "if", "not", "self", ".", "build_info", ":", "def", "on_build_info", "(", "info", ")", ":", "\"\"\" Make sure the build info is ready before we \n display the view \n \n \"\"\"", "self", "...
Show the current `app.view`. This will fade out the previous with the new view.
[ "Show", "the", "current", "app", ".", "view", ".", "This", "will", "fade", "out", "the", "previous", "with", "the", "new", "view", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L210-L233
train
38,360
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication._on_permission_result
def _on_permission_result(self, code, perms, results): """ Handles a permission request result by passing it to the handler with the given code. """ #: Get the handler for this request handler = self._permission_requests.get(code, None) if handler is not None: del self._permission_requests[code] #: Invoke that handler with the permission request response handler(code, perms, results)
python
def _on_permission_result(self, code, perms, results): """ Handles a permission request result by passing it to the handler with the given code. """ #: Get the handler for this request handler = self._permission_requests.get(code, None) if handler is not None: del self._permission_requests[code] #: Invoke that handler with the permission request response handler(code, perms, results)
[ "def", "_on_permission_result", "(", "self", ",", "code", ",", "perms", ",", "results", ")", ":", "#: Get the handler for this request", "handler", "=", "self", ".", "_permission_requests", ".", "get", "(", "code", ",", "None", ")", "if", "handler", "is", "not...
Handles a permission request result by passing it to the handler with the given code.
[ "Handles", "a", "permission", "request", "result", "by", "passing", "it", "to", "the", "handler", "with", "the", "given", "code", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L246-L257
train
38,361
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication._observe_keep_screen_on
def _observe_keep_screen_on(self, change): """ Sets or clears the flag to keep the screen on. """ 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)
python
def _observe_keep_screen_on(self, change): """ Sets or clears the flag to keep the screen on. """ 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)
[ "def", "_observe_keep_screen_on", "(", "self", ",", "change", ")", ":", "def", "set_screen_on", "(", "window", ")", ":", "from", ".", "android_window", "import", "Window", "window", "=", "Window", "(", "__id__", "=", "window", ")", "if", "self", ".", "keep...
Sets or clears the flag to keep the screen on.
[ "Sets", "or", "clears", "the", "flag", "to", "keep", "the", "screen", "on", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L259-L271
train
38,362
codelv/enaml-native
src/enamlnative/android/app.py
AndroidApplication.load_plugin_factories
def load_plugin_factories(self): """ Add any plugin toolkit widgets to the ANDROID_FACTORIES """ 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)
python
def load_plugin_factories(self): """ Add any plugin toolkit widgets to the ANDROID_FACTORIES """ 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)
[ "def", "load_plugin_factories", "(", "self", ")", ":", "for", "plugin", "in", "self", ".", "get_plugins", "(", "group", "=", "'enaml_native_android_factories'", ")", ":", "get_factories", "=", "plugin", ".", "load", "(", ")", "PLUGIN_FACTORIES", "=", "get_factor...
Add any plugin toolkit widgets to the ANDROID_FACTORIES
[ "Add", "any", "plugin", "toolkit", "widgets", "to", "the", "ANDROID_FACTORIES" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/app.py#L283-L290
train
38,363
codelv/enaml-native
src/enamlnative/ios/uikit_edit_text.py
UiKitEditText.on_value_changed
def on_value_changed(self, text): """ Update text field """ d = self.declaration with self.widget.get_member('text').suppressed(self.widget): d.text = text
python
def on_value_changed(self, text): """ Update text field """ d = self.declaration with self.widget.get_member('text').suppressed(self.widget): d.text = text
[ "def", "on_value_changed", "(", "self", ",", "text", ")", ":", "d", "=", "self", ".", "declaration", "with", "self", ".", "widget", ".", "get_member", "(", "'text'", ")", ".", "suppressed", "(", "self", ".", "widget", ")", ":", "d", ".", "text", "=",...
Update text field
[ "Update", "text", "field" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/uikit_edit_text.py#L106-L110
train
38,364
codelv/enaml-native
src/enamlnative/__init__.py
imports
def imports(): """ Install the import hook to load python extensions from app's lib folder during the context of this block. This method is preferred as it's faster than using install. """ from .core.import_hooks import ExtensionImporter importer = ExtensionImporter() sys.meta_path.append(importer) yield sys.meta_path.remove(importer)
python
def imports(): """ Install the import hook to load python extensions from app's lib folder during the context of this block. This method is preferred as it's faster than using install. """ from .core.import_hooks import ExtensionImporter importer = ExtensionImporter() sys.meta_path.append(importer) yield sys.meta_path.remove(importer)
[ "def", "imports", "(", ")", ":", "from", ".", "core", ".", "import_hooks", "import", "ExtensionImporter", "importer", "=", "ExtensionImporter", "(", ")", "sys", ".", "meta_path", ".", "append", "(", "importer", ")", "yield", "sys", ".", "meta_path", ".", "...
Install the import hook to load python extensions from app's lib folder during the context of this block. This method is preferred as it's faster than using install.
[ "Install", "the", "import", "hook", "to", "load", "python", "extensions", "from", "app", "s", "lib", "folder", "during", "the", "context", "of", "this", "block", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/__init__.py#L17-L27
train
38,365
codelv/enaml-native
src/enamlnative/__init__.py
install
def install(): """ 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. """ from .core.import_hooks import ExtensionImporter importer = ExtensionImporter() sys.meta_path.append(importer)
python
def install(): """ 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. """ from .core.import_hooks import ExtensionImporter importer = ExtensionImporter() sys.meta_path.append(importer)
[ "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.
[ "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", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/__init__.py#L30-L36
train
38,366
codelv/enaml-native
src/enamlnative/android/http.py
AndroidHttpRequest.init_request
def init_request(self): """ Init the native request using the okhttp3.Request.Builder """ #: Build the request builder = Request.Builder() builder.url(self.url) #: Set any headers for k, v in self.headers.items(): builder.addHeader(k, v) #: Get the body or generate from the data given body = self.body if body: #: Create the request body media_type = MediaType( __id__=MediaType.parse(self.content_type)) request_body = RequestBody( __id__=RequestBody.create(media_type, body)) #: Set the request method builder.method(self.method, request_body) elif self.method in ['get', 'delete', 'head']: #: Set the method getattr(builder, self.method)() else: raise ValueError("Cannot do a '{}' request " "without a body".format(self.method)) #: Save the okhttp request self.request = Request(__id__=builder.build())
python
def init_request(self): """ Init the native request using the okhttp3.Request.Builder """ #: Build the request builder = Request.Builder() builder.url(self.url) #: Set any headers for k, v in self.headers.items(): builder.addHeader(k, v) #: Get the body or generate from the data given body = self.body if body: #: Create the request body media_type = MediaType( __id__=MediaType.parse(self.content_type)) request_body = RequestBody( __id__=RequestBody.create(media_type, body)) #: Set the request method builder.method(self.method, request_body) elif self.method in ['get', 'delete', 'head']: #: Set the method getattr(builder, self.method)() else: raise ValueError("Cannot do a '{}' request " "without a body".format(self.method)) #: Save the okhttp request self.request = Request(__id__=builder.build())
[ "def", "init_request", "(", "self", ")", ":", "#: Build the request", "builder", "=", "Request", ".", "Builder", "(", ")", "builder", ".", "url", "(", "self", ".", "url", ")", "#: Set any headers", "for", "k", ",", "v", "in", "self", ".", "headers", ".",...
Init the native request using the okhttp3.Request.Builder
[ "Init", "the", "native", "request", "using", "the", "okhttp3", ".", "Request", ".", "Builder" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/http.py#L140-L170
train
38,367
codelv/enaml-native
src/enamlnative/android/http.py
AndroidHttpRequest._default_body
def _default_body(self): """ If the body is not passed in by the user try to create one using the given data parameters. """ 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) )
python
def _default_body(self): """ If the body is not passed in by the user try to create one using the given data parameters. """ 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) )
[ "def", "_default_body", "(", "self", ")", ":", "if", "not", "self", ".", "data", ":", "return", "\"\"", "if", "self", ".", "content_type", "==", "'application/json'", ":", "import", "json", "return", "json", ".", "dumps", "(", "self", ".", "data", ")", ...
If the body is not passed in by the user try to create one using the given data parameters.
[ "If", "the", "body", "is", "not", "passed", "in", "by", "the", "user", "try", "to", "create", "one", "using", "the", "given", "data", "parameters", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/http.py#L188-L204
train
38,368
codelv/enaml-native
src/enamlnative/android/http.py
AndroidHttpRequest.on_finish
def on_finish(self): """ Called regardless of success or failure """ r = self.response r.request_time = time.time() - self.start_time if self.callback: self.callback(r)
python
def on_finish(self): """ Called regardless of success or failure """ r = self.response r.request_time = time.time() - self.start_time if self.callback: self.callback(r)
[ "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
[ "Called", "regardless", "of", "success", "or", "failure" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/http.py#L237-L242
train
38,369
codelv/enaml-native
src/enamlnative/android/http.py
AsyncHttpClient._fetch
def _fetch(self, request): """ Fetch using the OkHttpClient """ client = self.client #: Dispatch the async call call = Call(__id__=client.newCall(request.request)) call.enqueue(request.handler) #: Save the call reference request.call = call
python
def _fetch(self, request): """ Fetch using the OkHttpClient """ client = self.client #: Dispatch the async call call = Call(__id__=client.newCall(request.request)) call.enqueue(request.handler) #: Save the call reference request.call = call
[ "def", "_fetch", "(", "self", ",", "request", ")", ":", "client", "=", "self", ".", "client", "#: Dispatch the async call", "call", "=", "Call", "(", "__id__", "=", "client", ".", "newCall", "(", "request", ".", "request", ")", ")", "call", ".", "enqueue...
Fetch using the OkHttpClient
[ "Fetch", "using", "the", "OkHttpClient" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/http.py#L276-L285
train
38,370
codelv/enaml-native
src/enamlnative/core/app.py
Plugin.load
def load(self): """ Load the object defined by the plugin entry point """ 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)
python
def load(self): """ Load the object defined by the plugin entry point """ 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)
[ "def", "load", "(", "self", ")", ":", "print", "(", "\"[DEBUG] Loading plugin {} from {}\"", ".", "format", "(", "self", ".", "name", ",", "self", ".", "source", ")", ")", "import", "pydoc", "path", ",", "attr", "=", "self", ".", "source", ".", "split", ...
Load the object defined by the plugin entry point
[ "Load", "the", "object", "defined", "by", "the", "plugin", "entry", "point" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L34-L41
train
38,371
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication._default_plugins
def _default_plugins(self): """ 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. """ 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
python
def _default_plugins(self): """ 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. """ 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
[ "def", "_default_plugins", "(", "self", ")", ":", "plugins", "=", "{", "}", "try", ":", "with", "open", "(", "'entry_points.json'", ")", "as", "f", ":", "entry_points", "=", "json", ".", "load", "(", "f", ")", "for", "ep", ",", "obj", "in", "entry_po...
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.
[ "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", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L104-L120
train
38,372
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.start
def start(self): """ Start the application's main event loop using either twisted or tornado. """ #: Schedule a load view if given and remote debugging is not active #: the remote debugging init call this after dev connection is ready if self.load_view and self.dev != "remote": self.deferred_call(self.load_view, self) self.loop.start()
python
def start(self): """ Start the application's main event loop using either twisted or tornado. """ #: Schedule a load view if given and remote debugging is not active #: the remote debugging init call this after dev connection is ready if self.load_view and self.dev != "remote": self.deferred_call(self.load_view, self) self.loop.start()
[ "def", "start", "(", "self", ")", ":", "#: Schedule a load view if given and remote debugging is not active", "#: the remote debugging init call this after dev connection is ready", "if", "self", ".", "load_view", "and", "self", ".", "dev", "!=", "\"remote\"", ":", "self", "....
Start the application's main event loop using either twisted or tornado.
[ "Start", "the", "application", "s", "main", "event", "loop", "using", "either", "twisted", "or", "tornado", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L140-L150
train
38,373
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.timed_call
def timed_call(self, ms, callback, *args, **kwargs): """ Invoke a callable on the main event loop thread at a specified time in the future. Parameters ---------- ms : int The time to delay, in milliseconds, before executing the callable. callback : callable The callable object to execute at some point in the future. *args, **kwargs Any additional positional and keyword arguments to pass to the callback. """ return self.loop.timed_call(ms, callback, *args, **kwargs)
python
def timed_call(self, ms, callback, *args, **kwargs): """ Invoke a callable on the main event loop thread at a specified time in the future. Parameters ---------- ms : int The time to delay, in milliseconds, before executing the callable. callback : callable The callable object to execute at some point in the future. *args, **kwargs Any additional positional and keyword arguments to pass to the callback. """ return self.loop.timed_call(ms, callback, *args, **kwargs)
[ "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. Parameters ---------- ms : int The time to delay, in milliseconds, before executing the callable. callback : callable The callable object to execute at some point in the future. *args, **kwargs Any additional positional and keyword arguments to pass to the callback.
[ "Invoke", "a", "callable", "on", "the", "main", "event", "loop", "thread", "at", "a", "specified", "time", "in", "the", "future", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L174-L192
train
38,374
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.add_done_callback
def add_done_callback(self, future, callback): """ Add a callback on a future object put here so it can be implemented with different event loops. Parameters ----------- future: Future or Deferred Future implementation for the current EventLoop callback: callable Callback to invoke when the future is done """ 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)
python
def add_done_callback(self, future, callback): """ Add a callback on a future object put here so it can be implemented with different event loops. Parameters ----------- future: Future or Deferred Future implementation for the current EventLoop callback: callable Callback to invoke when the future is done """ 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)
[ "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 t...
Add a callback on a future object put here so it can be implemented with different event loops. Parameters ----------- future: Future or Deferred Future implementation for the current EventLoop callback: callable Callback to invoke when the future is done
[ "Add", "a", "callback", "on", "a", "future", "object", "put", "here", "so", "it", "can", "be", "implemented", "with", "different", "event", "loops", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L236-L253
train
38,375
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.get_view
def get_view(self): """ Get the root view to display. Make sure it is properly initialized. """ view = self.view if not view.is_initialized: view.initialize() if not view.proxy_is_active: view.activate_proxy() return view.proxy.widget
python
def get_view(self): """ Get the root view to display. Make sure it is properly initialized. """ view = self.view if not view.is_initialized: view.initialize() if not view.proxy_is_active: view.activate_proxy() return view.proxy.widget
[ "def", "get_view", "(", "self", ")", ":", "view", "=", "self", ".", "view", "if", "not", "view", ".", "is_initialized", ":", "view", ".", "initialize", "(", ")", "if", "not", "view", ".", "proxy_is_active", ":", "view", ".", "activate_proxy", "(", ")",...
Get the root view to display. Make sure it is properly initialized.
[ "Get", "the", "root", "view", "to", "display", ".", "Make", "sure", "it", "is", "properly", "initialized", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L278-L288
train
38,376
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.send_event
def send_event(self, name, *args, **kwargs): """ Send an event to the native handler. This call is queued and batched. Parameters ---------- name : str The event name to be processed by MainActivity.processMessages. *args: args The arguments required by the event. **kwargs: kwargs Options for sending. These are: now: boolean Send the event now """ n = len(self._bridge_queue) # Add to queue self._bridge_queue.append((name, args)) if n == 0: # First event, send at next available time self._bridge_last_scheduled = time() self.deferred_call(self._bridge_send) return elif kwargs.get('now'): self._bridge_send(now=True) return # If it's been over 5 ms since we last scheduled, run now dt = time() - self._bridge_last_scheduled if dt > self._bridge_max_delay: self._bridge_send(now=True)
python
def send_event(self, name, *args, **kwargs): """ Send an event to the native handler. This call is queued and batched. Parameters ---------- name : str The event name to be processed by MainActivity.processMessages. *args: args The arguments required by the event. **kwargs: kwargs Options for sending. These are: now: boolean Send the event now """ n = len(self._bridge_queue) # Add to queue self._bridge_queue.append((name, args)) if n == 0: # First event, send at next available time self._bridge_last_scheduled = time() self.deferred_call(self._bridge_send) return elif kwargs.get('now'): self._bridge_send(now=True) return # If it's been over 5 ms since we last scheduled, run now dt = time() - self._bridge_last_scheduled if dt > self._bridge_max_delay: self._bridge_send(now=True)
[ "def", "send_event", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "n", "=", "len", "(", "self", ".", "_bridge_queue", ")", "# Add to queue", "self", ".", "_bridge_queue", ".", "append", "(", "(", "name", ",", "args",...
Send an event to the native handler. This call is queued and batched. Parameters ---------- name : str The event name to be processed by MainActivity.processMessages. *args: args The arguments required by the event. **kwargs: kwargs Options for sending. These are: now: boolean Send the event now
[ "Send", "an", "event", "to", "the", "native", "handler", ".", "This", "call", "is", "queued", "and", "batched", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L296-L330
train
38,377
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication._bridge_send
def _bridge_send(self, now=False): """ Send the events over the bridge to be processed by the native handler. Parameters ---------- now: boolean Send all pending events now instead of waiting for deferred calls to finish. Use this when you want to update the screen """ if len(self._bridge_queue): if self.debug: print("======== Py --> Native ======") for event in self._bridge_queue: print(event) print("===========================") self.dispatch_events(bridge.dumps(self._bridge_queue)) self._bridge_queue = []
python
def _bridge_send(self, now=False): """ Send the events over the bridge to be processed by the native handler. Parameters ---------- now: boolean Send all pending events now instead of waiting for deferred calls to finish. Use this when you want to update the screen """ if len(self._bridge_queue): if self.debug: print("======== Py --> Native ======") for event in self._bridge_queue: print(event) print("===========================") self.dispatch_events(bridge.dumps(self._bridge_queue)) self._bridge_queue = []
[ "def", "_bridge_send", "(", "self", ",", "now", "=", "False", ")", ":", "if", "len", "(", "self", ".", "_bridge_queue", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "\"======== Py --> Native ======\"", ")", "for", "event", "in", "self", ".", ...
Send the events over the bridge to be processed by the native handler. Parameters ---------- now: boolean Send all pending events now instead of waiting for deferred calls to finish. Use this when you want to update the screen
[ "Send", "the", "events", "over", "the", "bridge", "to", "be", "processed", "by", "the", "native", "handler", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L337-L355
train
38,378
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.process_events
def process_events(self, data): """ The native implementation must use this call to """ 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)
python
def process_events(self, data): """ The native implementation must use this call to """ 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)
[ "def", "process_events", "(", "self", ",", "data", ")", ":", "events", "=", "bridge", ".", "loads", "(", "data", ")", "if", "self", ".", "debug", ":", "print", "(", "\"======== Py <-- Native ======\"", ")", "for", "event", "in", "events", ":", "print", "...
The native implementation must use this call to
[ "The", "native", "implementation", "must", "use", "this", "call", "to" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L363-L373
train
38,379
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.handle_event
def handle_event(self, event): """ When we get an 'event' type from the bridge handle it by invoking the handler and if needed sending back the result. """ 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: #: Log the event, don't blow up here msg = "Error processing event: {} - {}".format( event, e).encode("utf-8") print(msg) self.show_error(msg) except: #: Log the event, blow up in user's face 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, #: method result_id, bridge.msgpack_encoder(sig, result) #: args )
python
def handle_event(self, event): """ When we get an 'event' type from the bridge handle it by invoking the handler and if needed sending back the result. """ 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: #: Log the event, don't blow up here msg = "Error processing event: {} - {}".format( event, e).encode("utf-8") print(msg) self.show_error(msg) except: #: Log the event, blow up in user's face 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, #: method result_id, bridge.msgpack_encoder(sig, result) #: args )
[ "def", "handle_event", "(", "self", ",", "event", ")", ":", "result_id", ",", "ptr", ",", "method", ",", "args", "=", "event", "[", "1", "]", "obj", "=", "None", "result", "=", "None", "try", ":", "obj", ",", "handler", "=", "bridge", ".", "get_han...
When we get an 'event' type from the bridge handle it by invoking the handler and if needed sending back the result.
[ "When", "we", "get", "an", "event", "type", "from", "the", "bridge", "handle", "it", "by", "invoking", "the", "handler", "and", "if", "needed", "sending", "back", "the", "result", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L375-L411
train
38,380
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.handle_error
def handle_error(self, callback): """ Called when an error occurs in an event loop callback. By default, sets the error view. """ self.loop.log_error(callback) msg = "\n".join([ "Exception in callback %r"%callback, traceback.format_exc() ]) self.show_error(msg.encode('utf-8'))
python
def handle_error(self, callback): """ Called when an error occurs in an event loop callback. By default, sets the error view. """ self.loop.log_error(callback) msg = "\n".join([ "Exception in callback %r"%callback, traceback.format_exc() ]) self.show_error(msg.encode('utf-8'))
[ "def", "handle_error", "(", "self", ",", "callback", ")", ":", "self", ".", "loop", ".", "log_error", "(", "callback", ")", "msg", "=", "\"\\n\"", ".", "join", "(", "[", "\"Exception in callback %r\"", "%", "callback", ",", "traceback", ".", "format_exc", ...
Called when an error occurs in an event loop callback. By default, sets the error view.
[ "Called", "when", "an", "error", "occurs", "in", "an", "event", "loop", "callback", ".", "By", "default", "sets", "the", "error", "view", "." ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L413-L423
train
38,381
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.start_dev_session
def start_dev_session(self): """ Start a client that attempts to connect to the dev server running on the host `app.dev` """ try: from .dev import DevServerSession session = DevServerSession.initialize(host=self.dev) session.start() #: Save a reference self._dev_session = session except: self.show_error(traceback.format_exc())
python
def start_dev_session(self): """ Start a client that attempts to connect to the dev server running on the host `app.dev` """ try: from .dev import DevServerSession session = DevServerSession.initialize(host=self.dev) session.start() #: Save a reference self._dev_session = session except: self.show_error(traceback.format_exc())
[ "def", "start_dev_session", "(", "self", ")", ":", "try", ":", "from", ".", "dev", "import", "DevServerSession", "session", "=", "DevServerSession", ".", "initialize", "(", "host", "=", "self", ".", "dev", ")", "session", ".", "start", "(", ")", "#: Save a...
Start a client that attempts to connect to the dev server running on the host `app.dev`
[ "Start", "a", "client", "that", "attempts", "to", "connect", "to", "the", "dev", "server", "running", "on", "the", "host", "app", ".", "dev" ]
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L460-L473
train
38,382
codelv/enaml-native
src/enamlnative/core/app.py
BridgedApplication.load_plugin_widgets
def load_plugin_widgets(self): """ 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. def install(): from charts.widgets.chart_view import BarChart, LineChart return { 'BarChart': BarChart, 'LineCart': LineChart, } """ 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()): #: Update the core api with these widgets setattr(api, name, widget)
python
def load_plugin_widgets(self): """ 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. def install(): from charts.widgets.chart_view import BarChart, LineChart return { 'BarChart': BarChart, 'LineCart': LineChart, } """ 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()): #: Update the core api with these widgets setattr(api, name, widget)
[ "def", "load_plugin_widgets", "(", "self", ")", ":", "from", "enamlnative", ".", "widgets", "import", "api", "for", "plugin", "in", "self", ".", "get_plugins", "(", "group", "=", "'enaml_native_widgets'", ")", ":", "get_widgets", "=", "plugin", ".", "load", ...
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. def install(): from charts.widgets.chart_view import BarChart, LineChart return { 'BarChart': BarChart, 'LineCart': LineChart, }
[ "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", "." ...
c33986e9eda468c508806e0a3e73c771401e5718
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/app.py#L485-L503
train
38,383
openxc/openxc-python
openxc/vehicle.py
Vehicle.get
def get(self, measurement_class): """Return the latest measurement for the given class or None if nothing has been received from the vehicle. """ name = Measurement.name_from_class(measurement_class) return self._construct_measurement(name)
python
def get(self, measurement_class): """Return the latest measurement for the given class or None if nothing has been received from the vehicle. """ name = Measurement.name_from_class(measurement_class) return self._construct_measurement(name)
[ "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.
[ "Return", "the", "latest", "measurement", "for", "the", "given", "class", "or", "None", "if", "nothing", "has", "been", "received", "from", "the", "vehicle", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/vehicle.py#L39-L44
train
38,384
openxc/openxc-python
openxc/vehicle.py
Vehicle.add_source
def add_source(self, source): """Add a vehicle data source to the instance. The Vehicle instance will be set as the callback of the source, and the source will be started if it is startable. (i.e. it has a ``start()`` method). """ if source is not None: self.sources.add(source) source.callback = self._receive if hasattr(source, 'start'): source.start()
python
def add_source(self, source): """Add a vehicle data source to the instance. The Vehicle instance will be set as the callback of the source, and the source will be started if it is startable. (i.e. it has a ``start()`` method). """ if source is not None: self.sources.add(source) source.callback = self._receive if hasattr(source, 'start'): source.start()
[ "def", "add_source", "(", "self", ",", "source", ")", ":", "if", "source", "is", "not", "None", ":", "self", ".", "sources", ".", "add", "(", "source", ")", "source", ".", "callback", "=", "self", ".", "_receive", "if", "hasattr", "(", "source", ",",...
Add a vehicle data source to the instance. The Vehicle instance will be set as the callback of the source, and the source will be started if it is startable. (i.e. it has a ``start()`` method).
[ "Add", "a", "vehicle", "data", "source", "to", "the", "instance", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/vehicle.py#L65-L76
train
38,385
openxc/openxc-python
openxc/sinks/notifier.py
MeasurementNotifierSink.register
def register(self, measurement_class, callback): """Call the ``callback`` with any new values of ``measurement_class`` received. """ self.callbacks[Measurement.name_from_class(measurement_class) ].add(callback)
python
def register(self, measurement_class, callback): """Call the ``callback`` with any new values of ``measurement_class`` received. """ self.callbacks[Measurement.name_from_class(measurement_class) ].add(callback)
[ "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.
[ "Call", "the", "callback", "with", "any", "new", "values", "of", "measurement_class", "received", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/sinks/notifier.py#L26-L31
train
38,386
openxc/openxc-python
openxc/sinks/notifier.py
MeasurementNotifierSink.unregister
def unregister(self, measurement_class, callback): """Stop notifying ``callback`` of new values of ``measurement_class``. If the callback wasn't previously registered, this method will have no effect. """ self.callbacks[Measurement.name_from_class(measurement_class) ].remove(callback)
python
def unregister(self, measurement_class, callback): """Stop notifying ``callback`` of new values of ``measurement_class``. If the callback wasn't previously registered, this method will have no effect. """ self.callbacks[Measurement.name_from_class(measurement_class) ].remove(callback)
[ "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``. If the callback wasn't previously registered, this method will have no effect.
[ "Stop", "notifying", "callback", "of", "new", "values", "of", "measurement_class", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/sinks/notifier.py#L33-L40
train
38,387
openxc/openxc-python
openxc/controllers/usb.py
UsbControllerMixin._send_complex_request
def _send_complex_request(self, request): """Send a request via the USB control request endpoint, rather than as a bulk transfer. """ self.device.ctrl_transfer(0x40, self.COMPLEX_CONTROL_COMMAND, 0, 0, self.streamer.serialize_for_stream(request))
python
def _send_complex_request(self, request): """Send a request via the USB control request endpoint, rather than as a bulk transfer. """ self.device.ctrl_transfer(0x40, self.COMPLEX_CONTROL_COMMAND, 0, 0, self.streamer.serialize_for_stream(request))
[ "def", "_send_complex_request", "(", "self", ",", "request", ")", ":", "self", ".", "device", ".", "ctrl_transfer", "(", "0x40", ",", "self", ".", "COMPLEX_CONTROL_COMMAND", ",", "0", ",", "0", ",", "self", ".", "streamer", ".", "serialize_for_stream", "(", ...
Send a request via the USB control request endpoint, rather than as a bulk transfer.
[ "Send", "a", "request", "via", "the", "USB", "control", "request", "endpoint", "rather", "than", "as", "a", "bulk", "transfer", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/usb.py#L32-L37
train
38,388
openxc/openxc-python
openxc/controllers/usb.py
UsbControllerMixin.out_endpoint
def out_endpoint(self): """Open a reference to the USB device's only OUT endpoint. This method assumes that the USB device configuration has already been set. """ 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
python
def out_endpoint(self): """Open a reference to the USB device's only OUT endpoint. This method assumes that the USB device configuration has already been set. """ 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
[ "def", "out_endpoint", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_out_endpoint'", ",", "None", ")", "is", "None", ":", "config", "=", "self", ".", "device", ".", "get_active_configuration", "(", ")", "interface_number", "=", "config", "["...
Open a reference to the USB device's only OUT endpoint. This method assumes that the USB device configuration has already been set.
[ "Open", "a", "reference", "to", "the", "USB", "device", "s", "only", "OUT", "endpoint", ".", "This", "method", "assumes", "that", "the", "USB", "device", "configuration", "has", "already", "been", "set", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/usb.py#L40-L59
train
38,389
openxc/openxc-python
openxc/controllers/base.py
ResponseReceiver.wait_for_responses
def wait_for_responses(self): """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. """ self.thread.join(self.COMMAND_RESPONSE_TIMEOUT_S) self.running = False return self.responses
python
def wait_for_responses(self): """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. """ self.thread.join(self.COMMAND_RESPONSE_TIMEOUT_S) self.running = False return self.responses
[ "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.
[ "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", "anywa...
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L56-L65
train
38,390
openxc/openxc-python
openxc/controllers/base.py
DiagnosticResponseReceiver._response_matches_request
def _response_matches_request(self, response): """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. """ # Accept success/failure command responses 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']
python
def _response_matches_request(self, response): """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. """ # Accept success/failure command responses 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']
[ "def", "_response_matches_request", "(", "self", ",", "response", ")", ":", "# Accept success/failure command responses", "if", "super", "(", "DiagnosticResponseReceiver", ",", "self", ")", ".", "_response_matches_request", "(", "response", ")", ":", "return", "True", ...
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.
[ "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", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L115-L137
train
38,391
openxc/openxc-python
openxc/controllers/base.py
Controller.complex_request
def complex_request(self, request, wait_for_first_response=True): """Send a compound command request to the interface over the normal data channel. request - A dict storing the request to send to the VI. It will be serialized to the currently selected output format. wait_for_first_response - If true, this function will block waiting for a response from the VI and return it to the caller. Otherwise, it will send the command and return immediately and any response will be lost. """ 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
python
def complex_request(self, request, wait_for_first_response=True): """Send a compound command request to the interface over the normal data channel. request - A dict storing the request to send to the VI. It will be serialized to the currently selected output format. wait_for_first_response - If true, this function will block waiting for a response from the VI and return it to the caller. Otherwise, it will send the command and return immediately and any response will be lost. """ 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
[ "def", "complex_request", "(", "self", ",", "request", ",", "wait_for_first_response", "=", "True", ")", ":", "receiver", "=", "self", ".", "_prepare_response_receiver", "(", "request", ",", "receiver_class", "=", "CommandResponseReceiver", ")", "self", ".", "_sen...
Send a compound command request to the interface over the normal data channel. request - A dict storing the request to send to the VI. It will be serialized to the currently selected output format. wait_for_first_response - If true, this function will block waiting for a response from the VI and return it to the caller. Otherwise, it will send the command and return immediately and any response will be lost.
[ "Send", "a", "compound", "command", "request", "to", "the", "interface", "over", "the", "normal", "data", "channel", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L159-L177
train
38,392
openxc/openxc-python
openxc/controllers/base.py
Controller.create_diagnostic_request
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): """Send a new diagnostic message request to the VI Required: message_id - The message ID (arbitration ID) for the request. mode - the diagnostic mode (or service). Optional: bus - The address of the CAN bus controller to send the request, either 1 or 2 for current VI hardware. pid - The parameter ID, or PID, for the request (e.g. for a mode 1 request). frequency - The frequency in hertz to add this as a recurring diagnostic requests. Must be greater than 0, or None if it is a one-time request. payload - A bytearray to send as the request's optional payload. Only single frame diagnostic requests are supported by the VI firmware in the current version, so the payload has a maximum length of 6. wait_for_ack - If True, will wait for an ACK of the command message. wait_for_first_response - If True, this function will block waiting for a diagnostic response to be received for the request. It will return either after timing out or after 1 matching response is received - there may be more responses to functional broadcast requests that arrive after returning. Returns a tuple of ([list of ACK responses to create request], [list of diagnostic responses received]) """ 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
python
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): """Send a new diagnostic message request to the VI Required: message_id - The message ID (arbitration ID) for the request. mode - the diagnostic mode (or service). Optional: bus - The address of the CAN bus controller to send the request, either 1 or 2 for current VI hardware. pid - The parameter ID, or PID, for the request (e.g. for a mode 1 request). frequency - The frequency in hertz to add this as a recurring diagnostic requests. Must be greater than 0, or None if it is a one-time request. payload - A bytearray to send as the request's optional payload. Only single frame diagnostic requests are supported by the VI firmware in the current version, so the payload has a maximum length of 6. wait_for_ack - If True, will wait for an ACK of the command message. wait_for_first_response - If True, this function will block waiting for a diagnostic response to be received for the request. It will return either after timing out or after 1 matching response is received - there may be more responses to functional broadcast requests that arrive after returning. Returns a tuple of ([list of ACK responses to create request], [list of diagnostic responses received]) """ 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
[ "def", "create_diagnostic_request", "(", "self", ",", "message_id", ",", "mode", ",", "bus", "=", "None", ",", "pid", "=", "None", ",", "frequency", "=", "None", ",", "payload", "=", "None", ",", "wait_for_ack", "=", "True", ",", "wait_for_first_response", ...
Send a new diagnostic message request to the VI Required: message_id - The message ID (arbitration ID) for the request. mode - the diagnostic mode (or service). Optional: bus - The address of the CAN bus controller to send the request, either 1 or 2 for current VI hardware. pid - The parameter ID, or PID, for the request (e.g. for a mode 1 request). frequency - The frequency in hertz to add this as a recurring diagnostic requests. Must be greater than 0, or None if it is a one-time request. payload - A bytearray to send as the request's optional payload. Only single frame diagnostic requests are supported by the VI firmware in the current version, so the payload has a maximum length of 6. wait_for_ack - If True, will wait for an ACK of the command message. wait_for_first_response - If True, this function will block waiting for a diagnostic response to be received for the request. It will return either after timing out or after 1 matching response is received - there may be more responses to functional broadcast requests that arrive after returning. Returns a tuple of ([list of ACK responses to create request], [list of diagnostic responses received])
[ "Send", "a", "new", "diagnostic", "message", "request", "to", "the", "VI" ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L213-L263
train
38,393
openxc/openxc-python
openxc/controllers/base.py
Controller.set_passthrough
def set_passthrough(self, bus, enabled): """Control the status of CAN message passthrough for a bus. Returns True if the command was successful. """ request = { "command": "passthrough", "bus": bus, "enabled": enabled } return self._check_command_response_status(request)
python
def set_passthrough(self, bus, enabled): """Control the status of CAN message passthrough for a bus. Returns True if the command was successful. """ request = { "command": "passthrough", "bus": bus, "enabled": enabled } return self._check_command_response_status(request)
[ "def", "set_passthrough", "(", "self", ",", "bus", ",", "enabled", ")", ":", "request", "=", "{", "\"command\"", ":", "\"passthrough\"", ",", "\"bus\"", ":", "bus", ",", "\"enabled\"", ":", "enabled", "}", "return", "self", ".", "_check_command_response_status...
Control the status of CAN message passthrough for a bus. Returns True if the command was successful.
[ "Control", "the", "status", "of", "CAN", "message", "passthrough", "for", "a", "bus", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L269-L279
train
38,394
openxc/openxc-python
openxc/controllers/base.py
Controller.set_payload_format
def set_payload_format(self, payload_format): """Set the payload format for messages sent to and from the VI. Returns True if the command was successful. """ request = { "command": "payload_format", "format": payload_format } status = self._check_command_response_status(request) # Always change the format regardless because if it was already in the # right format, the command will have failed. self.format = payload_format return status
python
def set_payload_format(self, payload_format): """Set the payload format for messages sent to and from the VI. Returns True if the command was successful. """ request = { "command": "payload_format", "format": payload_format } status = self._check_command_response_status(request) # Always change the format regardless because if it was already in the # right format, the command will have failed. self.format = payload_format return status
[ "def", "set_payload_format", "(", "self", ",", "payload_format", ")", ":", "request", "=", "{", "\"command\"", ":", "\"payload_format\"", ",", "\"format\"", ":", "payload_format", "}", "status", "=", "self", ".", "_check_command_response_status", "(", "request", "...
Set the payload format for messages sent to and from the VI. Returns True if the command was successful.
[ "Set", "the", "payload", "format", "for", "messages", "sent", "to", "and", "from", "the", "VI", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L281-L294
train
38,395
openxc/openxc-python
openxc/controllers/base.py
Controller.rtc_configuration
def rtc_configuration(self, unix_time): """Set the Unix time if RTC is supported on the device. Returns True if the command was successful. """ request = { "command": "rtc_configuration", "unix_time": unix_time } status = self._check_command_response_status(request) return status
python
def rtc_configuration(self, unix_time): """Set the Unix time if RTC is supported on the device. Returns True if the command was successful. """ request = { "command": "rtc_configuration", "unix_time": unix_time } status = self._check_command_response_status(request) return status
[ "def", "rtc_configuration", "(", "self", ",", "unix_time", ")", ":", "request", "=", "{", "\"command\"", ":", "\"rtc_configuration\"", ",", "\"unix_time\"", ":", "unix_time", "}", "status", "=", "self", ".", "_check_command_response_status", "(", "request", ")", ...
Set the Unix time if RTC is supported on the device. Returns True if the command was successful.
[ "Set", "the", "Unix", "time", "if", "RTC", "is", "supported", "on", "the", "device", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L297-L307
train
38,396
openxc/openxc-python
openxc/controllers/base.py
Controller.set_acceptance_filter_bypass
def set_acceptance_filter_bypass(self, bus, bypass): """Control the status of CAN acceptance filter for a bus. Returns True if the command was successful. """ request = { "command": "af_bypass", "bus": bus, "bypass": bypass } return self._check_command_response_status(request)
python
def set_acceptance_filter_bypass(self, bus, bypass): """Control the status of CAN acceptance filter for a bus. Returns True if the command was successful. """ request = { "command": "af_bypass", "bus": bus, "bypass": bypass } return self._check_command_response_status(request)
[ "def", "set_acceptance_filter_bypass", "(", "self", ",", "bus", ",", "bypass", ")", ":", "request", "=", "{", "\"command\"", ":", "\"af_bypass\"", ",", "\"bus\"", ":", "bus", ",", "\"bypass\"", ":", "bypass", "}", "return", "self", ".", "_check_command_respons...
Control the status of CAN acceptance filter for a bus. Returns True if the command was successful.
[ "Control", "the", "status", "of", "CAN", "acceptance", "filter", "for", "a", "bus", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L322-L332
train
38,397
openxc/openxc-python
openxc/controllers/base.py
Controller.sd_mount_status
def sd_mount_status(self): """Request for SD Mount status if available. """ request = { "command": "sd_mount_status" } responses = self.complex_request(request) result = None if len(responses) > 0: result = responses[0].get('status') return result
python
def sd_mount_status(self): """Request for SD Mount status if available. """ request = { "command": "sd_mount_status" } responses = self.complex_request(request) result = None if len(responses) > 0: result = responses[0].get('status') return result
[ "def", "sd_mount_status", "(", "self", ")", ":", "request", "=", "{", "\"command\"", ":", "\"sd_mount_status\"", "}", "responses", "=", "self", ".", "complex_request", "(", "request", ")", "result", "=", "None", "if", "len", "(", "responses", ")", ">", "0"...
Request for SD Mount status if available.
[ "Request", "for", "SD", "Mount", "status", "if", "available", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L368-L378
train
38,398
openxc/openxc-python
openxc/controllers/base.py
Controller.write
def write(self, **kwargs): """Serialize a raw or translated write request and send it to the VI, following the OpenXC message format. """ 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
python
def write(self, **kwargs): """Serialize a raw or translated write request and send it to the VI, following the OpenXC message format. """ 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
[ "def", "write", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'id'", "in", "kwargs", "and", "'data'", "in", "kwargs", ":", "result", "=", "self", ".", "write_raw", "(", "kwargs", "[", "'id'", "]", ",", "kwargs", "[", "'data'", "]", ",", ...
Serialize a raw or translated write request and send it to the VI, following the OpenXC message format.
[ "Serialize", "a", "raw", "or", "translated", "write", "request", "and", "send", "it", "to", "the", "VI", "following", "the", "OpenXC", "message", "format", "." ]
4becb4a6310bd658c125195ef6ffea4deaf7d7e7
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/controllers/base.py#L388-L399
train
38,399