sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def init_layout(self):
""" Initialize the layout of the toolkit widget.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called.
"""
widget = self.widget
for child_widget in self.child_widgets():
widget.addSubview(child_widget) | Initialize the layout of the toolkit widget.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called. | entailment |
def update_frame(self):
""" Define the view frame for this widgets"""
d = self.declaration
if d.x or d.y or d.width or d.height:
self.frame = (d.x, d.y, d.width, d.height) | Define the view frame for this widgets | entailment |
def child_added(self, child):
""" Handle the child added event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method.
"""
super(UiKitView, self).child_added(child)
widget = self.widget
#: TODO: Should index be cached?
for i, child_widget in enumerate(self.child_widgets()):
if child_widget == child.widget:
widget.insertSubview(child_widget, atIndex=i) | Handle the child added event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method. | entailment |
def child_moved(self, child):
""" Handle the child moved event from the declaration.
"""
super(UiKitView, self).child_moved(child)
#: Remove and re-add in correct spot
#: TODO: Should use exchangeSubviewAtIndex
self.child_removed(child)
self.child_added(child) | Handle the child moved event from the declaration. | entailment |
def child_removed(self, child):
""" Handle the child removed event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method.
"""
super(UiKitView, self).child_removed(child)
if child.widget is not None:
child.widget.removeFromSuperview() | Handle the child removed event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method. | entailment |
def destroy(self):
""" A reimplemented destructor.
This destructor will remove itself from the superview.
"""
widget = self.widget
if widget is not None:
widget.removeFromSuperview()
super(UiKitView, self).destroy() | A reimplemented destructor.
This destructor will remove itself from the superview. | entailment |
def init_layout(self):
""" Add all child widgets to the view
"""
super(AndroidSurfaceView, self).init_layout()
# Force layout using the default params
if not self.layout_params:
self.set_layout({}) | Add all child widgets to the view | entailment |
def main():
""" Called by PyBridge.start()
"""
#: If we set the TMP env variable the dev reloader will save file
#: and load changes in this directory instead of overwriting the
#: ones installed with the app.
os.environ['TMP'] = os.path.join(sys.path[0], '../tmp')
from enamlnative.android.app import AndroidApplication
app = AndroidApplication(
debug=True, #: Makes a lot of lag!
dev='server',
load_view=load_view,
)
app.start() | Called by PyBridge.start() | entailment |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidViewAnimator, self).init_widget()
d = self.declaration
if d.animate_first_view:
self.set_animate_first_view(d.animate_first_view)
if d.displayed_child:
self.set_displayed_child(d.displayed_child) | Initialize the underlying widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
self.widget = ViewPager(self.get_context())
self.adapter = BridgedFragmentStatePagerAdapter() | Create the underlying widget. | entailment |
def child_added(self, child):
""" When a child is added, schedule a data changed notification """
super(AndroidViewPager, self).child_added(child)
self._notify_count += 1
self.get_context().timed_call(
self._notify_delay, self._notify_change) | When a child is added, schedule a data changed notification | entailment |
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) | After all changes have settled, tell Java it changed | entailment |
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) | 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. | entailment |
def create_layout_params(self, child, layout):
""" Override as there is no (width, height) constructor.
"""
from .android_fragment import AndroidFragment
if isinstance(child, AndroidFragment):
return super(AndroidViewPager, self).create_layout_params(child,
layout)
# Only apply to decor views
dp = self.dp
w, h = (coerce_size(layout.get('width', 'match_parent')),
coerce_size(layout.get('height', 'wrap_content')))
w = w if w < 0 else int(w * dp)
h = h if h < 0 else int(h * dp)
# No (w,h) constructor
params = ViewPagerLayoutParams()
params.width = w
params.height = h
params.isDecor = True
return params | Override as there is no (width, height) constructor. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = CardView(self.get_context(), None, d.style) | Create the underlying widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = TextClock(self.get_context(), None, d.style) | Create the underlying widget. | entailment |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidTextClock, self).init_widget()
d = self.declaration
if d.format_12_hour:
self.set_format_12_hour(d.format_12_hour)
if d.format_24_hour:
self.set_format_24_hour(d.format_24_hour)
if d.time_zone:
self.set_time_zone(d.time_zone) | Initialize the underlying widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
if self.indeterminate:
#: Note: Style will only exist on activity indicators!
style = ProgressBar.STYLES[d.size]
else:
style = ProgressBar.STYLE_HORIZONTAL
self.widget = ProgressBar(self.get_context(), None, style) | Create the underlying widget. | entailment |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidProgressBar, self).init_widget()
d = self.declaration
self.set_indeterminate(self.indeterminate)
if not self.indeterminate:
if d.max:
self.set_max(d.max)
if d.min:
self.set_min(d.min)
self.set_progress(d.progress)
if d.secondary_progress:
self.set_secondary_progress(d.secondary_progress) | Initialize the underlying widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = Flexbox(self.get_context(), None, d.style) | Create the underlying widget. | entailment |
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 | Apply the flexbox specific layout. | entailment |
def toggle_keyboard(cls, flag=HIDE_IMPLICIT_ONLY):
""" Toggle the keyboard on and off
Parameters
----------
flag: int
Flag to send to toggleSoftInput
Returns
--------
result: future
Resolves when the toggle is complete
"""
app = AndroidApplication.instance()
f = app.create_future()
def on_ready(ims):
ims.toggleSoftInput(flag, 0)
f.set_result(True)
cls.get().then(on_ready)
return f | Toggle the keyboard on and off
Parameters
----------
flag: int
Flag to send to toggleSoftInput
Returns
--------
result: future
Resolves when the toggle is complete | entailment |
def hide_keyboard(cls):
""" Hide keyboard if it's open
Returns
--------
result: future
Resolves when the hide is complete
"""
app = AndroidApplication.instance()
f = app.create_future()
def on_ready(ims):
view = app.view.proxy.widget
def on_token(__id__):
ims.hideSoftInputFromWindow(
JavaBridgeObject(__id__=__id__), 0).then(f.set_result)
view.getWindowToken().then(on_token)
cls.get().then(on_ready)
return f | Hide keyboard if it's open
Returns
--------
result: future
Resolves when the hide is complete | entailment |
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 | Acquires the NotificationManager service async. | entailment |
def create_channel(cls, channel_id, name, importance=IMPORTANCE_DEFAULT,
description=""):
""" Before you can deliver the notification on Android 8.0 and higher,
you must register your app's notification channel with the system by
passing an instance of NotificationChannel
to createNotificationChannel().
Parameters
----------
channel_id: String-
Channel ID
name: String
Channel name
importance: Int
One of the IMPORTANCE levels
description: String
Channel description
Returns
-------
channel: NotificationChannel or None
The channel that was created.
"""
app = AndroidApplication.instance()
if app.api_level >= 26:
channel = NotificationChannel(channel_id, name, importance)
channel.setDescription(description)
NotificationChannelManager.get().then(
lambda mgr: mgr.createNotificationChannel(channel))
return channel | Before you can deliver the notification on Android 8.0 and higher,
you must register your app's notification channel with the system by
passing an instance of NotificationChannel
to createNotificationChannel().
Parameters
----------
channel_id: String-
Channel ID
name: String
Channel name
importance: Int
One of the IMPORTANCE levels
description: String
Channel description
Returns
-------
channel: NotificationChannel or None
The channel that was created. | entailment |
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() | Create and show a Notification. See `Notification.Builder.update`
for a list of accepted parameters. | entailment |
def cancel_notification(cls, notification_or_id, tag=None):
""" Cancel the notification.
Parameters
----------
notification_or_id: Notification.Builder or int
The notification or id of a notification to clear
tag: String
The tag of the notification to clear
"""
def on_ready(mgr):
if isinstance(notification_or_id, JavaBridgeObject):
nid = notification_or_id.__id__
else:
nid = notification_or_id
if tag is None:
mgr.cancel_(nid)
else:
mgr.cancel(tag, nid)
cls.get().then(on_ready) | Cancel the notification.
Parameters
----------
notification_or_id: Notification.Builder or int
The notification or id of a notification to clear
tag: String
The tag of the notification to clear | entailment |
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) | Create the notification in the top down pass if show = True | entailment |
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() | A reimplemented destructor that cancels
the notification before destroying. | entailment |
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 | Instead of the typical create_widget we use `create_notification`
because after it's closed it needs created again. | entailment |
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) | Create the toolkit widget for the proxy object. | entailment |
def initialize(self):
""" A reimplemented initializer.
This method will add the include objects to the parent of the
include and ensure that they are initialized.
"""
super(Block, self).initialize()
block = self.block
if block: #: This block is setting the content of another block
#: Remove the existing blocks children
if self.mode == 'replace':
#: Clear the blocks children
for c in block.children:
c.destroy()
#: Add this blocks children to the other block
block.insert_children(None, self.children)
else: #: This block is inserting it's children into it's parent
self.parent.insert_children(self, self.children) | A reimplemented initializer.
This method will add the include objects to the parent of the
include and ensure that they are initialized. | entailment |
def _observe_block(self, change):
""" A change handler for the 'objects' list of the Include.
If the object is initialized objects which are removed will be
unparented and objects which are added will be reparented. Old
objects will be destroyed if the 'destroy_old' flag is True.
"""
if self.is_initialized:
if change['type'] == 'update':
old_block = change['oldvalue']
old_parent = old_block.parent
for c in self.children:
old_parent.child_removed(c)
new_block = change['value']
new_block.parent.insert_children(new_block, self.children) | A change handler for the 'objects' list of the Include.
If the object is initialized objects which are removed will be
unparented and objects which are added will be reparented. Old
objects will be destroyed if the 'destroy_old' flag is True. | entailment |
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) | Init text properties for this widget | entailment |
def init_layout(self):
""" Add all child widgets to the view
"""
super(AndroidViewGroup, self).init_layout()
widget = self.widget
i = 0
for child in self.children():
child_widget = child.widget
if child_widget:
if child.layout_params:
widget.addView_(child_widget, i,
child.layout_params)
else:
widget.addView(child_widget, i)
i += 1
# Force layout using the default params
if not self.layout_params:
self.set_layout({}) | Add all child widgets to the view | entailment |
def child_added(self, child):
""" Handle the child added event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method.
"""
super(AndroidViewGroup, self).child_added(child)
widget = self.widget
#: TODO: Should index be cached?
for i, child_widget in enumerate(self.child_widgets()):
if child_widget == child.widget:
if child.layout_params:
widget.addView_(child_widget, i,
child.layout_params)
else:
widget.addView(child_widget, i) | Handle the child added event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method. | entailment |
def child_moved(self, child):
""" Handle the child moved event from the declaration.
"""
super(AndroidViewGroup, self).child_moved(child)
#: Remove and re-add in correct spot
self.child_removed(child)
self.child_added(child) | Handle the child moved event from the declaration. | entailment |
def child_removed(self, child):
""" Handle the child removed event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method.
"""
super(AndroidViewGroup, self).child_removed(child)
if child.widget is not None:
self.widget.removeView(child.widget) | Handle the child removed event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = TimePicker(self.get_context(), None,
d.style or '@attr/timePickerStyle') | Create the underlying widget. | entailment |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidTimePicker, self).init_widget()
d = self.declaration
w = self.widget
self.set_hour(d.hour)
self.set_minute(d.minute)
self.set_hour_mode(d.hour_mode)
w.setOnTimeChangedListener(w.getId())
w.onTimeChanged.connect(self.on_time_changed) | Initialize the underlying widget. | entailment |
def destroy(self):
""" A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None.
"""
widget = self.widget
if widget is not None:
parent = self.parent_widget()
if parent is not None:
parent.removeView(widget)
del self.widget
super(AndroidToolkitObject, self).destroy() | A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = ToggleButton(self.get_context(), None,
d.style or "@attr/buttonStyleToggle") | Create the underlying widget. | entailment |
def init_widget(self):
""" Bind the on property to the checked state """
super(UiKitSwitch, self).init_widget()
d = self.declaration
if d.checked:
self.set_checked(d.checked)
#: Watch the on property for change
#: So apparently UISwitch is not KVO compliant...
# self.widget.addObserver(
# self.get_app().view_controller,
# forKeyPath="on",
# options=UISwitch.NSKeyValueObservingOptionNew|UISwitch.NSKeyValueObservingOptionOld,
# context=self.widget
#)
#: A really ugly way to add the target
#: would be nice if we could just pass the block pointer here :)
self.get_app().bridge.addTarget(
self.widget,
forControlEvents=UISwitch.UIControlEventValueChanged,
andCallback=self.widget.getId(),
usingMethod="onValueChanged",
withValues=["on"]#,"selected"]
)
self.widget.onValueChanged.connect(self.on_checked_changed) | Bind the on property to the checked state | entailment |
def on_checked_changed(self, on):
""" See https://stackoverflow.com/questions/19628310/ """
#: Since iOS decides to call this like 100 times for each defer it
d = self.declaration
with self.widget.setOn.suppressed():
d.checked = on | See https://stackoverflow.com/questions/19628310/ | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = Chronometer(self.get_context(), None, d.style) | Create the underlying widget. | entailment |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidChronometer, self).init_widget()
w = self.widget
w.setOnChronometerTickListener(w.getId())
w.onChronometerTick.connect(self.on_chronometer_tick) | Initialize the underlying widget. | entailment |
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 | Upgrade the code object of a function | entailment |
def update_property(old, new):
"""Replace get/set/del functions of a property"""
update_generic(old.fdel, new.fdel)
update_generic(old.fget, new.fget)
update_generic(old.fset, new.fset) | Replace get/set/del functions of a property | entailment |
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 | 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 | entailment |
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 | Skip reloading the named module in the future | entailment |
def mark_module_reloadable(self, module_name):
"""Reload the named module in the future (if it is imported)"""
try:
del self.skip_modules[module_name]
except KeyError:
pass
self.modules[module_name] = True | Reload the named module in the future (if it is imported) | entailment |
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 | 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 | entailment |
def check(self, check_all=False, do_reload=True):
"""Check whether some modules need to be reloaded."""
if not self.enabled and not check_all:
return
if check_all or self.check_all:
modules = list(sys.modules.keys())
else:
modules = list(self.modules.keys())
for modname in modules:
m = sys.modules.get(modname, None)
if modname in self.skip_modules:
continue
py_filename, pymtime = self.filename_and_mtime(m)
if py_filename is None:
continue
try:
if pymtime <= self.modules_mtimes[modname]:
continue
except KeyError:
self.modules_mtimes[modname] = pymtime
continue
else:
if self.failed.get(py_filename, None) == pymtime:
continue
self.modules_mtimes[modname] = pymtime
# If we've reached this point, we should try to reload the module
if do_reload:
try:
if self.debug:
print("Reloading {}".format(m))
superreload(m, reload, self.old_objects)
if py_filename in self.failed:
del self.failed[py_filename]
except:
print("[autoreload of %s failed: %s]" % (
modname, traceback.format_exc(10)))
self.failed[py_filename] = pymtime | Check whether some modules need to be reloaded. | entailment |
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 | 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. | entailment |
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}) | %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 | entailment |
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) | Cache the modification times of any modules imported in this execution | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = EditText(self.get_context(), None,
d.style or "@attr/editTextStyle") | Create the underlying widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
style = d.style if d.style else (
'@attr/borderlessButtonStyle' if d.flat else '@attr/buttonStyle')
self.widget = Button(self.get_context(), None, style) | Create the underlying widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = FloatingActionButton(self.get_context(), None, d.style) | Create the underlying widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = Picker(self.get_context(), None,
d.style or '@attr/numberPickerStyle') | Create the underlying widget. | entailment |
def init_widget(self):
""" Set the checked state after all children have
been populated.
"""
super(AndroidPicker, self).init_widget()
d = self.declaration
w = self.widget
if d.items:
self.set_items(d.items)
else:
if d.max_value:
self.set_max_value(d.max_value)
if d.min_value:
self.set_min_value(d.min_value)
self.set_value(d.value)
if d.wraps:
self.set_wraps(d.wraps)
if d.long_press_update_interval:
self.set_long_press_update_interval(d.long_press_update_interval)
w.setOnValueChangedListener(w.getId())
w.onValueChange.connect(self.on_value_change) | Set the checked state after all children have
been populated. | entailment |
def on_value_change(self, picker, old, new):
""" Set the checked property based on the checked state
of all the children
"""
d = self.declaration
with self.widget.setValue.suppressed():
d.value = new | Set the checked property based on the checked state
of all the children | entailment |
def create_widget(self):
""" Create the underlying label widget.
"""
d = self.declaration
mode = 1 if d.mode == 'dropdown' else 0
self.widget = Spinner(self.get_context(), mode)
# Create the adapter simple_spinner_item = 0x01090008
self.adapter = ArrayAdapter(self.get_context(),
'@layout/simple_spinner_dropdown_item') | Create the underlying label widget. | entailment |
def init_widget(self):
""" Initialize the underlying widget.
"""
w = self.widget
# Selection listener
w.setAdapter(self.adapter)
w.setOnItemSelectedListener(w.getId())
w.onItemSelected.connect(self.on_item_selected)
w.onNothingSelected.connect(self.on_nothing_selected)
super(AndroidSpinner, self).init_widget() | Initialize the underlying widget. | entailment |
def set_items(self, items):
""" Generate the view cache
"""
self.adapter.clear()
self.adapter.addAll(items) | Generate the view cache | entailment |
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 | Load the objc library using ctypes. | entailment |
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')) | Get an instance of the ENBridge object using ctypes. | entailment |
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)) | Sends msgpack data to the ENBridge instance
by calling the processEvents method via ctypes. | entailment |
def _update_proxy(self, change):
""" An observer which sends the state change to the proxy.
"""
if change['type'] == 'event' and self.proxy_is_active:
self.proxy.set_opened(change['name'] == 'show')
else:
super(ActionMenuView, self)._update_proxy(change) | An observer which sends the state change to the proxy. | entailment |
def current(instance=True):
"""Returns the current thread's `IOLoop`.
If an `IOLoop` is currently running or has been marked as
current by `make_current`, returns that instance. If there is
no current `IOLoop` and ``instance`` is true, creates one.
.. versionchanged:: 4.1
Added ``instance`` argument to control the fallback to
`IOLoop.instance()`.
.. versionchanged:: 5.0
The ``instance`` argument now controls whether an `IOLoop`
is created automatically when there is none, instead of
whether we fall back to `IOLoop.instance()` (which is now
an alias for this method)
"""
current = getattr(IOLoop._current, "instance", None)
if current is None and instance:
current = None
#if asyncio is not None:
# from tornado.platform.asyncio import AsyncIOLoop, AsyncIOMainLoop
# if IOLoop.configured_class() is AsyncIOLoop:
# current = AsyncIOMainLoop()
if current is None:
if sys.platform == 'darwin':
from .platforms import KQueueIOLoop
current = KQueueIOLoop()
else:
from .platforms import EPollIOLoop
current = EPollIOLoop()
current.initialize()
#current = IOLoop()
if IOLoop._current.instance is not current:
raise RuntimeError("new IOLoop did not become current")
return current | Returns the current thread's `IOLoop`.
If an `IOLoop` is currently running or has been marked as
current by `make_current`, returns that instance. If there is
no current `IOLoop` and ``instance`` is true, creates one.
.. versionchanged:: 4.1
Added ``instance`` argument to control the fallback to
`IOLoop.instance()`.
.. versionchanged:: 5.0
The ``instance`` argument now controls whether an `IOLoop`
is created automatically when there is none, instead of
whether we fall back to `IOLoop.instance()` (which is now
an alias for this method) | entailment |
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))) | Signal handler to log the stack trace of the current thread.
For use with `set_blocking_signal_threshold`. | entailment |
def run_sync(self, func, timeout=None):
"""Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either a yieldable object or
``None``. If the function returns a yieldable object, the
`IOLoop` will run until the yieldable is resolved (and
`run_sync()` will return the yieldable's result). If it raises
an exception, the `IOLoop` will stop and the exception will be
re-raised to the caller.
The keyword-only argument ``timeout`` may be used to set
a maximum duration for the function. If the timeout expires,
a `tornado.util.TimeoutError` is raised.
This method is useful in conjunction with `tornado.gen.coroutine`
to allow asynchronous calls in a ``main()`` function::
@gen.coroutine
def main():
# do stuff...
if __name__ == '__main__':
IOLoop.current().run_sync(main)
.. versionchanged:: 4.3
Returning a non-``None``, non-yieldable value is now an error.
"""
future_cell = [None]
def run():
try:
result = func()
if result is not None:
from .gen import convert_yielded
result = convert_yielded(result)
except Exception:
future_cell[0] = TracebackFuture()
future_cell[0].set_exc_info(sys.exc_info())
else:
if is_future(result):
future_cell[0] = result
else:
future_cell[0] = TracebackFuture()
future_cell[0].set_result(result)
self.add_future(future_cell[0], lambda future: self.stop())
self.add_callback(run)
if timeout is not None:
timeout_handle = self.add_timeout(self.time() + timeout, self.stop)
self.start()
if timeout is not None:
self.remove_timeout(timeout_handle)
if not future_cell[0].done():
raise TimeoutError('Operation timed out after %s seconds' % timeout)
return future_cell[0].result() | Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either a yieldable object or
``None``. If the function returns a yieldable object, the
`IOLoop` will run until the yieldable is resolved (and
`run_sync()` will return the yieldable's result). If it raises
an exception, the `IOLoop` will stop and the exception will be
re-raised to the caller.
The keyword-only argument ``timeout`` may be used to set
a maximum duration for the function. If the timeout expires,
a `tornado.util.TimeoutError` is raised.
This method is useful in conjunction with `tornado.gen.coroutine`
to allow asynchronous calls in a ``main()`` function::
@gen.coroutine
def main():
# do stuff...
if __name__ == '__main__':
IOLoop.current().run_sync(main)
.. versionchanged:: 4.3
Returning a non-``None``, non-yieldable value is now an error. | entailment |
def add_timeout(self, deadline, callback, *args, **kwargs):
"""Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object for a deadline relative to the
current time. Since Tornado 4.0, `call_later` is a more
convenient alternative for the relative case since it does not
require a timedelta object.
Note that it is not safe to call `add_timeout` from other threads.
Instead, you must use `add_callback` to transfer control to the
`IOLoop`'s thread, and then call `add_timeout` from there.
Subclasses of IOLoop must implement either `add_timeout` or
`call_at`; the default implementations of each will call
the other. `call_at` is usually easier to implement, but
subclasses that wish to maintain compatibility with Tornado
versions prior to 4.0 must use `add_timeout` instead.
.. versionchanged:: 4.0
Now passes through ``*args`` and ``**kwargs`` to the callback.
"""
if isinstance(deadline, numbers.Real):
return self.call_at(deadline, callback, *args, **kwargs)
elif isinstance(deadline, datetime.timedelta):
return self.call_at(self.time() + timedelta_to_seconds(deadline),
callback, *args, **kwargs)
else:
raise TypeError("Unsupported deadline %r" % deadline) | Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object for a deadline relative to the
current time. Since Tornado 4.0, `call_later` is a more
convenient alternative for the relative case since it does not
require a timedelta object.
Note that it is not safe to call `add_timeout` from other threads.
Instead, you must use `add_callback` to transfer control to the
`IOLoop`'s thread, and then call `add_timeout` from there.
Subclasses of IOLoop must implement either `add_timeout` or
`call_at`; the default implementations of each will call
the other. `call_at` is usually easier to implement, but
subclasses that wish to maintain compatibility with Tornado
versions prior to 4.0 must use `add_timeout` instead.
.. versionchanged:: 4.0
Now passes through ``*args`` and ``**kwargs`` to the callback. | entailment |
def call_later(self, delay, callback, *args, **kwargs):
"""Runs the ``callback`` after ``delay`` seconds have passed.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel()`` method.
See `add_timeout` for comments on thread-safety and subclassing.
.. versionadded:: 4.0
"""
return self.call_at(self.time() + delay, callback, *args, **kwargs) | Runs the ``callback`` after ``delay`` seconds have passed.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel()`` method.
See `add_timeout` for comments on thread-safety and subclassing.
.. versionadded:: 4.0 | entailment |
def call_at(self, when, callback, *args, **kwargs):
"""Runs the ``callback`` at the absolute time designated by ``when``.
``when`` must be a number using the same reference point as
`IOLoop.time`.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel()`` method.
See `add_timeout` for comments on thread-safety and subclassing.
.. versionadded:: 4.0
"""
return self.add_timeout(when, callback, *args, **kwargs) | Runs the ``callback`` at the absolute time designated by ``when``.
``when`` must be a number using the same reference point as
`IOLoop.time`.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel()`` method.
See `add_timeout` for comments on thread-safety and subclassing.
.. versionadded:: 4.0 | entailment |
def spawn_callback(self, callback, *args, **kwargs):
"""Calls the given callback on the next IOLoop iteration.
Unlike all other callback-related methods on IOLoop,
``spawn_callback`` does not associate the callback with its caller's
``stack_context``, so it is suitable for fire-and-forget callbacks
that should not interfere with the caller.
.. versionadded:: 4.0
"""
with stack_context.NullContext():
self.add_callback(callback, *args, **kwargs) | Calls the given callback on the next IOLoop iteration.
Unlike all other callback-related methods on IOLoop,
``spawn_callback`` does not associate the callback with its caller's
``stack_context``, so it is suitable for fire-and-forget callbacks
that should not interfere with the caller.
.. versionadded:: 4.0 | entailment |
def add_future(self, future, callback):
"""Schedules a callback on the ``IOLoop`` when the given
`.Future` is finished.
The callback is invoked with one argument, the
`.Future`.
"""
assert is_future(future)
callback = stack_context.wrap(callback)
future.add_done_callback(
lambda future: self.add_callback(callback, future)) | Schedules a callback on the ``IOLoop`` when the given
`.Future` is finished.
The callback is invoked with one argument, the
`.Future`. | entailment |
def _run_callback(self, callback):
"""Runs a callback with error handling.
For use in subclasses.
"""
try:
ret = callback()
if ret is not None:
from . import gen
# Functions that return Futures typically swallow all
# exceptions and store them in the Future. If a Future
# makes it out to the IOLoop, ensure its exception (if any)
# gets logged too.
try:
ret = gen.convert_yielded(ret)
except gen.BadYieldError:
# It's not unusual for add_callback to be used with
# methods returning a non-None and non-yieldable
# result, which should just be ignored.
pass
else:
self.add_future(ret, self._discard_future_result)
except Exception:
self.handle_callback_exception(callback) | Runs a callback with error handling.
For use in subclasses. | entailment |
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) | 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`. | entailment |
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 | 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 | entailment |
def init_widget(self):
""" Initialize the state of the toolkit widget.
This method is called during the top-down pass, just after the
'create_widget()' method is called. This method should init the
state of the widget. The child widgets will not yet be created.
Note: This does NOT initialize text properties by default!
"""
super(UiKitControl, self).init_widget()
d = self.declaration
if d.clickable:
#: A really ugly way to add the target
#: would be nice if we could just pass the block pointer here :)
self.get_app().bridge.addTarget(
self.widget,
forControlEvents=UIControl.UIControlEventTouchUpInside,
andCallback=self.widget.getId(),
usingMethod="onClicked",
withValues=[]
)
self.widget.onClicked.connect(self.on_clicked) | Initialize the state of the toolkit widget.
This method is called during the top-down pass, just after the
'create_widget()' method is called. This method should init the
state of the widget. The child widgets will not yet be created.
Note: This does NOT initialize text properties by default! | entailment |
def create_widget(self):
""" Create the underlying widget.
A toast is not a subclass of view, hence we don't set name as widget
or children will try to use it as their parent (which crashes).
"""
d = self.declaration
Snackbar.make(self.parent_widget(), d.text,
0 if d.duration else -2).then(self.on_widget_created) | Create the underlying widget.
A toast is not a subclass of view, hence we don't set name as widget
or children will try to use it as their parent (which crashes). | entailment |
def init_widget(self):
""" Our widget may not exist yet so we have to diverge from the normal
way of doing initialization. See `update_widget`
"""
if not self.widget:
return
super(AndroidSnackbar, self).init_widget()
d = self.declaration
#: Bind events
self.widget.onClick.connect(self.on_click)
#: Use the custom callback to listen to events
callback = BridgedSnackbarCallback()
callback.setListener(self.widget.getId())
self.widget.onDismissed.connect(self.on_dismissed)
self.widget.onShown.connect(self.on_shown)
self.widget.addCallback(callback)
#: if d.text: #: Set during creation
#: self.set_duration(d.duration) #: Set during creation
if d.action_text:
self.set_action_text(d.action_text)
if d.action_text_color:
self.set_action_text_color(d.action_text_color)
if d.show:
self.set_show(d.show) | Our widget may not exist yet so we have to diverge from the normal
way of doing initialization. See `update_widget` | entailment |
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() | Using Snackbar.make returns async so we have to
initialize it later. | entailment |
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) | 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`. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = SeekBar(self.get_context(), None,
d.style or '@attr/seekBarStyle') | Create the underlying widget. | entailment |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidSeekBar, self).init_widget()
w = self.widget
#: Setup listener
w.setOnSeekBarChangeListener(w.getId())
w.onProgressChanged.connect(self.on_progress_changed) | Initialize the underlying widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = TextView(self.get_context(), None,
d.style or '@attr/textViewStyle') | Create the underlying widget. | entailment |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidTextView, self).init_widget()
d = self.declaration
w = self.widget
if d.input_type:
self.set_input_type(d.input_type)
w.addTextChangedListener(w.getId())
w.onTextChanged.connect(self.on_text_changed) | Initialize the underlying widget. | entailment |
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) | Set the text in the widget. | entailment |
def create_widget(self):
""" Create the underlying widget.
A dialog is not a subclass of view, hence we don't set name as widget
or children will try to use it as their parent.
"""
d = self.declaration
self.dialog = BottomSheetDialog(self.get_context(), d.style) | Create the underlying widget.
A dialog is not a subclass of view, hence we don't set name as widget
or children will try to use it as their parent. | entailment |
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 | Encode an object for proper decoding by Java or ObjC | entailment |
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) | Dereference the pointer and return the handler method. | entailment |
def suppressed(self, obj):
""" Suppress calls within this context to avoid feedback loops"""
obj.__suppressed__[self.name] = True
yield
obj.__suppressed__[self.name] = False | Suppress calls within this context to avoid feedback loops | entailment |
def init_widget(self):
""" Initialize the state of the toolkit widget.
This method is called during the top-down pass, just after the
'create_widget()' method is called. This method should init the
state of the widget. The child widgets will not yet be created.
"""
super(UiKitActivityIndicator, self).init_widget()
d = self.declaration
if d.size != 'normal':
self.set_size(d.size)
if d.color:
self.set_color(d.color)
#: Why would you want to stop an activity indicator?
self.widget.startAnimating() | Initialize the state of the toolkit widget.
This method is called during the top-down pass, just after the
'create_widget()' method is called. This method should init the
state of the widget. The child widgets will not yet be created. | entailment |
def is_wifi_enabled(cls):
""" Check if wifi is currently enabled.
Returns
--------
result: future
A future that resolves with the value.
"""
app = AndroidApplication.instance()
f = app.create_future()
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(m):
m.isWifiEnabled().then(f.set_result)
WifiManager.get().then(on_ready)
#: Check permission
WifiManager.request_permission([
WifiManager.PERMISSION_ACCESS_WIFI_STATE
]).then(on_permission_result)
return f | Check if wifi is currently enabled.
Returns
--------
result: future
A future that resolves with the value. | entailment |
def set_wifi_enabled(cls, state=True):
""" Set the wifi enabled state.
Returns
--------
result: future
A future that resolves with whether the operation succeeded.
"""
app = AndroidApplication.instance()
f = app.create_future()
def on_permission_result(result):
if not result:
#: Permission denied
f.set_result(None)
return
def on_ready(m):
m.setWifiEnabled(state).then(f.set_result)
WifiManager.get().then(on_ready)
#: Check permission
WifiManager.request_permission([
WifiManager.PERMISSION_CHANGE_WIFI_STATE
]).then(on_permission_result)
return f | Set the wifi enabled state.
Returns
--------
result: future
A future that resolves with whether the operation succeeded. | entailment |
def get_networks(cls):
""" Get the wifi networks currently available.
Returns
--------
result: future
A future that resolves with the list of networks available
or None if wifi could not be enabled (permission denied,
etc...)
"""
app = AndroidApplication.instance()
activity = app.widget
f = app.create_future()
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(mgr):
#: Register a receiver so we know when the scan
#: is complete
receiver = BroadcastReceiver()
receiver.setReceiver(receiver.getId())
def on_scan_complete(context, intent):
#: Finally, pull the scan results
mgr.getScanResults().then(f.set_result)
#: Cleanup receiver
mgr._receivers.remove(receiver)
activity.unregisterReceiver(receiver)
def on_wifi_enabled(enabled):
if not enabled:
#: Access denied or failed to enable
f.set_result(None)
#: Cleanup receiver
mgr._receivers.remove(receiver)
activity.unregisterReceiver(receiver)
return
#: Hook up a callback that's fired when the scan
#: results are ready
receiver.onReceive.connect(on_scan_complete)
#: Save a reference as this must stay alive
mgr._receivers.append(receiver)
#: Register the receiver
intent_filter = IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
activity.registerReceiver(receiver,
intent_filter)
#: Trigger a scan (which "should" eventually
#: call the on on_scan_complete)
mgr.startScan()
#: Enable if needed
mgr.setWifiEnabled(True).then(on_wifi_enabled)
#: Get the service
WifiManager.get().then(on_ready)
#: Request permissions
WifiManager.request_permission(
WifiManager.PERMISSIONS_REQUIRED).then(on_permission_result)
return f | Get the wifi networks currently available.
Returns
--------
result: future
A future that resolves with the list of networks available
or None if wifi could not be enabled (permission denied,
etc...) | entailment |
def disconnect(cls):
""" Disconnect from the current network (if connected).
Returns
--------
result: future
A future that resolves to true if the disconnect was
successful. Will be set to None if the change network
permission is denied.
"""
app = AndroidApplication.instance()
f = app.create_future()
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(mgr):
mgr.disconnect().then(f.set_result)
#: Get the service
WifiManager.get().then(on_ready)
#: Request permissions
WifiManager.request_permission([
WifiManager.PERMISSION_CHANGE_WIFI_STATE
]).then(on_permission_result)
return f | Disconnect from the current network (if connected).
Returns
--------
result: future
A future that resolves to true if the disconnect was
successful. Will be set to None if the change network
permission is denied. | entailment |
def connect(cls, ssid, key=None, **kwargs):
""" Connect to the given ssid using the key (if given).
Returns
--------
result: future
A future that resolves with the result of the connect
"""
app = AndroidApplication.instance()
f = app.create_future()
config = WifiConfiguration()
config.SSID = '"{}"'.format(ssid)
if key is not None:
config.preSharedKey = '"{}"'.format(key)
#: Set any other parameters
for k, v in kwargs.items():
setattr(config, k, v)
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(mgr):
def on_disconnect(result):
if not result:
f.set_result(None)
return #: Done
mgr.setWifiEnabled(True).then(on_wifi_enabled)
def on_wifi_enabled(enabled):
if not enabled:
#: Access denied or failed to enable
f.set_result(None)
return
mgr.addNetwork(config).then(on_network_added)
def on_network_added(net_id):
if net_id == -1:
f.set_result(False)
print("Warning: Invalid network "
"configuration id {}".format(net_id))
return
mgr.enableNetwork(net_id, True).then(on_network_enabled)
def on_network_enabled(result):
if not result:
#: TODO: Should probably say
#: which state it failed at...
f.set_result(None)
return
mgr.reconnect().then(f.set_result)
#: Enable if needed
mgr.disconnect_().then(on_disconnect)
#: Get the service
WifiManager.get().then(on_ready)
#: Request permissions
WifiManager.request_permission(
WifiManager.PERMISSIONS_REQUIRED).then(on_permission_result)
return f | Connect to the given ssid using the key (if given).
Returns
--------
result: future
A future that resolves with the result of the connect | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.