sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def get_connection_info(cls): """ Get info about current wifi connection (if any). Returns info such as the IP address, BSSID, link speed, signal, etc.. Returns -------- result: future A future that resolves with a dict of the connection info or None if an error occurred (ie permission denied).s """ 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.getConnectionInfo().then(f.set_result) #: Get the service WifiManager.get().then(on_ready) #: Request permissions WifiManager.request_permission([ WifiManager.PERMISSION_ACCESS_WIFI_STATE ]).then(on_permission_result) return f
Get info about current wifi connection (if any). Returns info such as the IP address, BSSID, link speed, signal, etc.. Returns -------- result: future A future that resolves with a dict of the connection info or None if an error occurred (ie permission denied).s
entailment
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
Requests permission and returns an future result that returns a boolean indicating if all the given permission were granted or denied.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidActionMenuView, self).init_widget() d = self.declaration w = self.widget #: Kinda hackish, but when we get the menu back, load it w.getMenu().then(self.on_menu) w.setOnMenuItemClickListener(w.getId()) w.onMenuItemClick.connect(self.on_menu_item_click)
Initialize the underlying widget.
entailment
def _update_proxy(self, change): """ An observer which sends the state change to the proxy. """ if change['type'] == 'event': self.proxy.set_refreshed(True) else: super(SwipeRefreshLayout, self)._update_proxy(change)
An observer which sends the state change to the proxy.
entailment
def _update_proxy(self, change): """ An observer which sends the state change to the proxy. """ if change['type'] in ['event', 'update'] and self.proxy_is_active: handler = getattr(self.proxy, 'set_' + change['name'], None) if handler is not None: handler(change['value'])
An observer which sends the state change to the proxy.
entailment
def run_on_executor(*args, **kwargs): """Decorator to run a synchronous method asynchronously on an executor. The decorated method may be called with a ``callback`` keyword argument and returns a future. The executor to be used is determined by the ``executor`` attributes of ``self``. To use a different attribute name, pass a keyword argument to the decorator:: @run_on_executor(executor='_thread_pool') def foo(self): pass .. versionchanged:: 4.2 Added keyword arguments to use alternative attributes. .. versionchanged:: 5.0 Always uses the current IOLoop instead of ``self.io_loop``. """ def run_on_executor_decorator(fn): executor = kwargs.get("executor", "executor") @functools.wraps(fn) def wrapper(self, *args, **kwargs): callback = kwargs.pop("callback", None) future = getattr(self, executor).submit(fn, self, *args, **kwargs) if callback: from .ioloop import IOLoop IOLoop.current().add_future( future, lambda future: callback(future.result())) return future return wrapper if args and kwargs: raise ValueError("cannot combine positional and keyword args") if len(args) == 1: return run_on_executor_decorator(args[0]) elif len(args) != 0: raise ValueError("expected 1 argument, got %d", len(args)) return run_on_executor_decorator
Decorator to run a synchronous method asynchronously on an executor. The decorated method may be called with a ``callback`` keyword argument and returns a future. The executor to be used is determined by the ``executor`` attributes of ``self``. To use a different attribute name, pass a keyword argument to the decorator:: @run_on_executor(executor='_thread_pool') def foo(self): pass .. versionchanged:: 4.2 Added keyword arguments to use alternative attributes. .. versionchanged:: 5.0 Always uses the current IOLoop instead of ``self.io_loop``.
entailment
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
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.
entailment
def chain_future(a, b): """Chain two futures together so that when one completes, so does the other. The result (success or failure) of ``a`` will be copied to ``b``, unless ``b`` has already been completed or cancelled by the time ``a`` finishes. """ def copy(future): assert future is a if b.done(): return if (isinstance(a, TracebackFuture) and isinstance(b, TracebackFuture) and a.exc_info() is not None): b.set_exc_info(a.exc_info()) elif a.exception() is not None: b.set_exception(a.exception()) else: b.set_result(a.result()) a.add_done_callback(copy)
Chain two futures together so that when one completes, so does the other. The result (success or failure) of ``a`` will be copied to ``b``, unless ``b`` has already been completed or cancelled by the time ``a`` finishes.
entailment
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
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.
entailment
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
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.
entailment
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)
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.
entailment
def set_exception(self, exception): """Sets the exception of a ``Future.``""" self.set_exc_info( (exception.__class__, exception, getattr(exception, '__traceback__', None)))
Sets the exception of a ``Future.``
entailment
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
Sets the exception information of a ``Future.`` Preserves tracebacks on Python 2. .. versionadded:: 4.0
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = CoordinatorLayout(self.get_context(), None, d.style)
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidCompoundButton, self).init_widget() w = self.widget w.setOnCheckedChangeListener(w.getId()) w.onCheckedChanged.connect(self.on_checked)
Initialize the underlying widget.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = RelativeLayout(self.get_context(), None, d.style)
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidRelativeLayout, self).init_widget() d = self.declaration if d.gravity: self.set_gravity(d.gravity) if d.horizontal_gravity: self.set_horizontal_gravity(d.horizontal_gravity) if d.vertical_gravity: self.set_vertical_gravity(d.vertical_gravity)
Initialize the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidTextureView, self).__init__(self) w = self.widget w.setSurfaceTextureListener(w.getId()) w.onSurfaceTextureAvailable.connect(self.on_surface_texture_available) w.onSurfaceTextureDestroyed.connect(self.on_surface_texture_destroyed) w.onSurfaceTextureChanged.connect(self.on_surface_texture_changed) w.onSurfaceTextureUpdated.connect(self.on_surface_texture_updated)
Initialize the underlying widget.
entailment
def init_layout(self): """ Add all child widgets to the view """ super(AndroidTextureView, 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 create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = DrawerLayout(self.get_context(), None, d.style)
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidDrawerLayout, self).init_widget() d = self.declaration if d.title: self.set_title(d.title) if d.drawer_elevation: self.set_drawer_elevation(d.drawer_elevation) if d.lock_mode: self.set_lock_mode(d.lock_mode) if d.scrim_color: self.set_scrim_color(d.scrim_color) if d.status_bar_background_color: self.set_status_bar_background_color(d.status_bar_background_color)
Initialize the underlying widget.
entailment
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. This """ layout = self.layout #: Add the layout as a subview self.widget.addSubview(layout) #: Add all child widgets to the layout for child_widget in self.child_widgets(): layout.addArrangedSubview(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. This
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) layout = self.layout for i, child_widget in enumerate(self.child_widgets()): if child_widget == child.widget: layout.insertArrangedSubview(child_widget, atIndex=i) layout.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_removed(self, child): """ Handle the child removed event from the declaration. The child must be both removed from the arrangement and removed normally. """ layout = self.layout if child.widget is not None: layout.removeArrangedSubview(child.widget) layout.removeSubview(child.widget)
Handle the child removed event from the declaration. The child must be both removed from the arrangement and removed normally.
entailment
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()
A reimplemented destructor that destroys the layout widget.
entailment
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)
Arguments must be packed according to the kwargs passed and the signature defined.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = RatingBar(self.get_context(), None, d.style or '@attr/ratingBarStyle')
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidRatingBar, self).init_widget() d = self.declaration self.set_rating(d.rating) w = self.widget w.setOnRatingBarChangeListener(w.getId()) w.onRatingChanged.connect(self.on_rating_changed)
Initialize the underlying widget.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = LinearLayout(self.get_context(), None, d.style)
Create the underlying widget.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = FrameLayout(self.get_context(), None, d.style)
Create the underlying widget.
entailment
def create_widget(self): """ Create the underlying widget. """ context = self.get_context() d = self.declaration style = d.style or '@attr/autoCompleteTextViewStyle' self.widget = AutoCompleteTextView(context, None, style) self.adapter = ArrayAdapter(context, '@layout/simple_list_item_1')
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidAutoCompleteTextView, self).init_widget() self.widget.setAdapter(self.adapter)
Initialize the underlying widget.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = Icon(self.get_context(), None, d.style)
Create the underlying widget.
entailment
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)
Remove deactivated handlers from the chain
entailment
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
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).
entailment
def get(cls, sensor_type): """ Shortcut that acquires the default Sensor of a given type. Parameters ---------- sensor_type: int Type of sensor to get. Returns ------- result: Future A future that resolves to an instance of the Sensor or None if the sensor is not present or access is not allowed. """ app = AndroidApplication.instance() f = app.create_future() def on_sensor(sid, mgr): if sid is None: f.set_result(None) else: f.set_result(Sensor(__id__=sid, manager=mgr, type=sensor_type)) SensorManager.get().then( lambda sm: sm.getDefaultSensor(sensor_type).then( lambda sid, sm=sm:on_sensor(sid, sm))) return f
Shortcut that acquires the default Sensor of a given type. Parameters ---------- sensor_type: int Type of sensor to get. Returns ------- result: Future A future that resolves to an instance of the Sensor or None if the sensor is not present or access is not allowed.
entailment
def start(self, callback, rate=SENSOR_DELAY_NORMAL): """ Start listening to sensor events. Sensor event data depends on the type of sensor that was given to Parameters ---------- callback: Callable A callback that takes one argument that will be passed the sensor data. Sensor data is a dict with data based on the type of sensor. rate: Integer How fast to update. One of the Sensor.SENSOR_DELAY values Returns ------- result: Future A future that resolves to whether the register call completed. """ if not self.manager: raise RuntimeError( "Cannot start a sensor without a SensorManager!") self.onSensorChanged.connect(callback) return self.manager.registerListener(self.getId(), self, rate)
Start listening to sensor events. Sensor event data depends on the type of sensor that was given to Parameters ---------- callback: Callable A callback that takes one argument that will be passed the sensor data. Sensor data is a dict with data based on the type of sensor. rate: Integer How fast to update. One of the Sensor.SENSOR_DELAY values Returns ------- result: Future A future that resolves to whether the register call completed.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidListView, self).init_widget() d = self.declaration self.set_arrangement(d.arrangement)
Initialize the underlying widget.
entailment
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
Override to do it manually
entailment
def init_layout(self): """ Initialize the underlying widget. """ super(AndroidListView, self).init_layout() d = self.declaration w = self.widget # Prepare adapter adapter = self.adapter = BridgedRecyclerAdapter(w) # I'm sure this will make someone upset haha adapter.setRecyleListener(adapter.getId()) adapter.onRecycleView.connect(self.on_recycle_view) #adapter.onVisibleCountChanged.connect(self.on_visible_count_changed) #adapter.onScrollStateChanged.connect(self.on_scroll_state_changed) self.set_items(d.items) w.setAdapter(adapter) #self.set_selected(d.selected) self.refresh_views()
Initialize the underlying widget.
entailment
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)
Update the item the view at the given index should display
entailment
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])
Set the views that the adapter will cycle through.
entailment
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()
Observe container events on the items list and update the adapter appropriately.
entailment
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
Tell the view to render the item at the given position
entailment
def errno_from_exception(e): # type: (BaseException) -> Optional[int] """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the errno. """ if hasattr(e, 'errno'): return e.errno # type: ignore elif e.args: return e.args[0] else: return None
Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the errno.
entailment
def _websocket_mask_python(mask, data): # type: (bytes, bytes) -> bytes """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available. """ mask_arr = array.array("B", mask) unmasked_arr = array.array("B", data) for i in xrange(len(data)): unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4] if PY3: # tostring was deprecated in py32. It hasn't been removed, # but since we turn on deprecation warnings in our tests # we need to use the right one. return unmasked_arr.tobytes() else: return unmasked_arr.tostring()
Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available.
entailment
def configure(cls, impl, **kwargs): # type: (Any, **Any) -> None """Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters. """ base = cls.configurable_base() if isinstance(impl, (str, unicode_type)): impl = import_object(impl) if impl is not None and not issubclass(impl, cls): raise ValueError("Invalid subclass of %s" % cls) base.__impl_class = impl base.__impl_kwargs = kwargs
Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters.
entailment
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
Returns the currently configured class.
entailment
def get_old_value(self, args, kwargs, default=None): # type: (List[Any], Dict[str, Any], Any) -> Any """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self.arg_pos is not None and len(args) > self.arg_pos: return args[self.arg_pos] else: return kwargs.get(self.name, default)
Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present.
entailment
def replace(self, new_value, args, kwargs): # type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]] """Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may not be the same as the input objects, or the input objects may be mutated. If the named argument was not found, ``new_value`` will be added to ``kwargs`` and None will be returned as ``old_value``. """ if self.arg_pos is not None and len(args) > self.arg_pos: # The arg to replace is passed positionally old_value = args[self.arg_pos] args = list(args) # *args is normally a tuple args[self.arg_pos] = new_value else: # The arg to replace is either omitted or passed by keyword. old_value = kwargs.get(self.name) kwargs[self.name] = new_value return old_value, args, kwargs
Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may not be the same as the input objects, or the input objects may be mutated. If the named argument was not found, ``new_value`` will be added to ``kwargs`` and None will be returned as ``old_value``.
entailment
def popup(self): """ Show the notification from code. This will initialize and activate if needed. Notes ------ This does NOT block. Callbacks should be used to handle click events or the `show` state should be observed to know when it is closed. """ if not self.is_initialized: self.initialize() if not self.proxy_is_active: self.activate_proxy() self.show = True
Show the notification from code. This will initialize and activate if needed. Notes ------ This does NOT block. Callbacks should be used to handle click events or the `show` state should be observed to know when it is closed.
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 if d.text: Toast.makeText(self.get_context(), d.text, 1).then(self.on_make_toast) self.made_toast = True else: self.toast = Toast(self.get_context())
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.toast: return super(AndroidToast, self).init_widget() d = self.declaration if not self.made_toast: #: Set it to LONG self.toast.setDuration(1) if d.gravity: self.set_gravity(d.gravity) 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 init_layout(self): """ If a view is given show it """ super(AndroidToast, self).init_layout() if not self.made_toast: for view in self.child_widgets(): self.toast.setView(view) break
If a view is given show it
entailment
def child_added(self, child): """ Overwrite the view """ view = child.widget if view is not None: self.toast.setView(view)
Overwrite the view
entailment
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()
Using Toast.makeToast returns async so we have to initialize it later.
entailment
def _refresh_show(self, dt): """ While the toast.show is true, keep calling .show() until the duration `dt` expires. Parameters ------------ dt: int Time left to keep showing """ d = self.declaration if dt <= 0: #: Done, hide d.show = False elif d.show: #: If user didn't cancel it, keep it alive self.toast.show() t = min(1000, dt) app = self.get_context() app.timed_call(t, self._refresh_show, dt-t)
While the toast.show is true, keep calling .show() until the duration `dt` expires. Parameters ------------ dt: int Time left to keep showing
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 = Dialog(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 init_widget(self): """ Set the listeners """ w = self.dialog # Listen for events w.setOnDismissListener(w.getId()) w.onDismiss.connect(self.on_dismiss) w.setOnCancelListener(w.getId()) w.onCancel.connect(self.on_cancel) super(AndroidDialog, self).init_widget()
Set the listeners
entailment
def init_layout(self): """ If a view is given show it """ super(AndroidDialog, self).init_layout() #: Set the content for view in self.child_widgets(): self.dialog.setContentView(view) break #: Show it if needed d = self.declaration if d.show: self.set_show(d.show)
If a view is given show it
entailment
def child_added(self, child): """ Overwrite the content view """ view = child.widget if view is not None: self.dialog.setContentView(view)
Overwrite the content view
entailment
def destroy(self): """ A reimplemented destructor that cancels the dialog before destroying. """ dialog = self.dialog if dialog: #: Clear the dismiss listener #: (or we get an error during the callback) dialog.setOnDismissListener(None) dialog.dismiss() del self.dialog super(AndroidDialog, self).destroy()
A reimplemented destructor that cancels the dialog before destroying.
entailment
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
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.
entailment
def stop(cls): """ Stops location updates if currently updating. """ manager = LocationManager.instance() if manager: for l in manager.listeners: manager.removeUpdates(l) manager.listeners = []
Stops location updates if currently updating.
entailment
def check_permission(cls, fine=True): """ Returns a future that returns a boolean indicating if permission is currently granted or denied. If permission is denied, you can request using `LocationManager.request_permission()` below. """ app = AndroidApplication.instance() permission = (cls.ACCESS_FINE_PERMISSION if fine else cls.ACCESS_COARSE_PERMISSION) return app.has_permission(permission)
Returns a future that returns a boolean indicating if permission is currently granted or denied. If permission is denied, you can request using `LocationManager.request_permission()` below.
entailment
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
Requests permission and returns an async result that returns a boolean indicating if the permission was granted or denied.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = WebView(self.get_context(), None, d.style)
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ # Create and init the client c = self.client = BridgedWebViewClient() c.setWebView(self.widget, c.getId()) c.onLoadResource.connect(self.on_load_resource) c.onPageFinished.connect(self.on_page_finished) c.onPageStarted.connect(self.on_page_started) c.onReceivedError.connect(self.on_received_error) c.onScaleChanged.connect(self.on_scale_changed) c.onProgressChanged.connect(self.on_progress_changed) c.onReceivedTitle.connect(self.on_page_title_changed) super(AndroidWebView, self).init_widget()
Initialize the underlying widget.
entailment
def destroy(self): """ Destroy the client """ if self.client: #: Stop listening self.client.setWebView(self.widget, None) del self.client super(AndroidWebView, self).destroy()
Destroy the client
entailment
def init_widget(self): """ Bind the on property to the checked state """ super(UiKitSlider, self).init_widget() d = self.declaration if d.min: self.set_min(d.min) if d.max: self.set_max(d.max) if d.progress: self.set_progress(d.progress) #: 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=UISlider.UIControlEventValueChanged, andCallback=self.widget.getId(), usingMethod="onValueChanged", withValues=["value"]#,"selected"] ) self.widget.onValueChanged.connect(self.on_checked_changed)
Bind the on property to the checked state
entailment
def on_checked_changed(self, value): """ 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.setValue.suppressed(): d.progress = int(value)
See https://stackoverflow.com/questions/19628310/
entailment
def init_layout(self): """ Set the checked state after all children have been populated. """ super(AndroidRadioGroup, self).init_layout() d = self.declaration w = self.widget if d.checked: self.set_checked(d.checked) else: #: Check if any of the children have "checked = True" for c in d.children: if c.checked: d.checked = c w.setOnCheckedChangeListener(w.getId()) w.onCheckedChanged.connect(self.on_checked_changed)
Set the checked state after all children have been populated.
entailment
def on_checked_changed(self, group, checked_id): """ Set the checked property based on the checked state of all the children """ d = self.declaration if checked_id < 0: with self.widget.clearCheck.suppressed(): d.checked = None return else: for c in self.children(): if c.widget.getId() == checked_id: with self.widget.check.suppressed(): d.checked = c.declaration return
Set the checked property based on the checked state of all the children
entailment
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())
Properly check the correct radio button.
entailment
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)
Initialize on the first call
entailment
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
Return a future that resolves with the result of the permission
entailment
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
Return a future that resolves with the results of the permission requests
entailment
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)
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
entailment
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
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.
entailment
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']]
Handles a screen configuration change.
entailment
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()
Show the current `app.view`. This will fade out the previous with the new view.
entailment
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)
Handles a permission request result by passing it to the handler with the given code.
entailment
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)
Sets or clears the flag to keep the screen on.
entailment
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)
Add any plugin toolkit widgets to the ANDROID_FACTORIES
entailment
def init_widget(self): """ Bind the on property to the checked state """ super(UiKitEditText, self).init_widget() #: Init font properties etc... self.init_text() d = self.declaration if d.placeholder: self.set_placeholder(d.placeholder) if d.input_type != 'text': self.set_input_type(d.input_type) if d.style: self.set_style(d.style) #: 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=UITextField.UIControlEventEditingChanged, andCallback=self.widget.getId(), usingMethod="onValueChanged", withValues=["text"]#,"selected"] ) self.widget.onValueChanged.connect(self.on_value_changed)
Bind the on property to the checked state
entailment
def on_value_changed(self, text): """ Update text field """ d = self.declaration with self.widget.get_member('text').suppressed(self.widget): d.text = text
Update text field
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = DatePicker(self.get_context(), None, d.style or "@attr/datePickerStyle")
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ d = self.declaration w = self.widget date = d.date w.init(date.year, date.month-1, date.day, w.getId()) super(AndroidDatePicker, self).init_widget() w.onDateChanged.connect(self.on_date_changed)
Initialize the underlying widget.
entailment
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)
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.
entailment
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)
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.
entailment
def source_from_cache(path): """Given the path to a .pyc. file, return the path to its .py file. The .pyc file does not need to exist; this simply returns the path to the .py file calculated to correspond to the .pyc file. If path does not conform to PEP 3147/488 format, ValueError will be raised. If sys.implementation.cache_tag is None then NotImplementedError is raised. """ #if sys.implementation.cache_tag is None: # raise NotImplementedError('sys.implementation.cache_tag is None') #path = os.fspath(path) head, pycache_filename = os.path.split(path) head, pycache = os.path.split(head) if pycache != _PYCACHE: raise ValueError('{} not bottom-level directory in ' '{!r}'.format(_PYCACHE, path)) dot_count = pycache_filename.count('.') if dot_count not in {2, 3}: raise ValueError('expected only 2 or 3 dots in ' '{!r}'.format(pycache_filename)) elif dot_count == 3: optimization = pycache_filename.rsplit('.', 2)[-2] if not optimization.startswith(_OPT): raise ValueError("optimization portion of filename does not start " "with {!r}".format(_OPT)) opt_level = optimization[len(_OPT):] if not opt_level.isalnum(): raise ValueError("optimization level {!r} is not an alphanumeric " "value".format(optimization)) base_filename = pycache_filename.partition('.')[0] return os.path.join(head, base_filename + SOURCE_SUFFIXES[0])
Given the path to a .pyc. file, return the path to its .py file. The .pyc file does not need to exist; this simply returns the path to the .py file calculated to correspond to the .pyc file. If path does not conform to PEP 3147/488 format, ValueError will be raised. If sys.implementation.cache_tag is None then NotImplementedError is raised.
entailment
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())
Init the native request using the okhttp3.Request.Builder
entailment
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) )
If the body is not passed in by the user try to create one using the given data parameters.
entailment
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)
Called regardless of success or failure
entailment
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
Fetch using the OkHttpClient
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = CheckBox(self.get_context(), None, d.style or "@attr/checkboxStyle")
Create the underlying widget.
entailment
def fetch(self, url, callback=None, raise_error=True, **kwargs): """ Fetch the given url and fire the callback when ready. Optionally pass a `streaming_callback` to handle data from large requests. Parameters ---------- url: string The url to access. callback: callable The callback to invoke when the request completes. You can also use the return value. kwargs: The arguments to pass to the `HttpRequest` object. See it for which values are valid. Returns -------- result: Future A future that resolves with the `HttpResponse` object when the request is complete. """ app = BridgedApplication.instance() f = app.create_future() #: Set callback for when response is in if callback is not None: f.then(callback) def handle_response(response): """ Callback when the request is complete. """ self.requests.remove(response.request) f.set_result(response) #: Create and dispatch the request object request = self.request_factory(url=url, callback=handle_response, **kwargs) #: Save a reference #: This gets removed in the handle response self.requests.append(request) #: Run the request self._fetch(request) #: Save it on the future so it can be accessed and observed #: from a view if needed f.request = request return f
Fetch the given url and fire the callback when ready. Optionally pass a `streaming_callback` to handle data from large requests. Parameters ---------- url: string The url to access. callback: callable The callback to invoke when the request completes. You can also use the return value. kwargs: The arguments to pass to the `HttpRequest` object. See it for which values are valid. Returns -------- result: Future A future that resolves with the `HttpResponse` object when the request is complete.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = GridLayout(self.get_context(), None, d.style)
Create the underlying widget.
entailment
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = Switch(self.get_context(), None, d.style or '@attr/switchStyle')
Create the underlying widget.
entailment
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidSwitch, self).init_widget() d = self.declaration self.set_show_text(d.show_text) if d.split_track: self.set_split_track(d.split_track) if d.text_off: self.set_text_off(d.text_off) if d.text_on: self.set_text_on(d.text_on)
Initialize the underlying widget.
entailment