sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def choices(tree): """ Get the 'address' of each leaf node in terms of internal node choices """ n = len(leaves(tree)) addr = np.nan * np.ones((n, n-1)) def _addresses(node, index, choices): # index is the index of the current internal node # choices is a list of (indice, 0/1...
Get the 'address' of each leaf node in terms of internal node choices
entailment
def adjacency(tree): """ Construct the adjacency matrix of the tree :param tree: :return: """ dd = ids(tree) N = len(dd) A = np.zeros((N, N)) def _adj(node): if np.isscalar(node): return elif isinstance(node, tuple) and len(node) == 2: A[dd[no...
Construct the adjacency matrix of the tree :param tree: :return:
entailment
def max_likelihood(self, data, weights=None, stats=None, lmbda=0.1): """ As an alternative to MCMC with Polya-gamma augmentation, we also implement maximum likelihood learning via gradient descent with autograd. This follows the pybasicbayes convention. :param data: list...
As an alternative to MCMC with Polya-gamma augmentation, we also implement maximum likelihood learning via gradient descent with autograd. This follows the pybasicbayes convention. :param data: list of tuples, (x,y), for each dataset. :param weights: Not used in this implementat...
entailment
def resample(self, data, mask=None, omega=None): """ Multinomial regression is somewhat special. We have to compute the kappa functions for the entire dataset, not just for one column of the data at a time. """ if not isinstance(data, list): assert isinstance(...
Multinomial regression is somewhat special. We have to compute the kappa functions for the entire dataset, not just for one column of the data at a time.
entailment
def get_claims_for(self, user_id, requested_claims): # type: (str, Mapping[str, Optional[Mapping[str, Union[str, List[str]]]]) -> Dict[str, Union[str, List[str]]] """ Filter the userinfo based on which claims where requested. :param user_id: user identifier :param requested_claim...
Filter the userinfo based on which claims where requested. :param user_id: user identifier :param requested_claims: see <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter"> "OpenID Connect Core 1.0", Section 5.5</a> for structure :return: All requested clai...
entailment
def create_authorization_code(self, authorization_request, subject_identifier, scope=None): # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> str """ Creates an authorization code bound to the authorization request and the authenticated user identified by the su...
Creates an authorization code bound to the authorization request and the authenticated user identified by the subject identifier.
entailment
def create_access_token(self, authorization_request, subject_identifier, scope=None): # type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> se_leg_op.access_token.AccessToken """ Creates an access token bound to the authentication request and the authenticated user identifi...
Creates an access token bound to the authentication request and the authenticated user identified by the subject identifier.
entailment
def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None): # type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken """ Creates an access token bound to the subject identifier, client id and requested scope...
Creates an access token bound to the subject identifier, client id and requested scope.
entailment
def exchange_code_for_token(self, authorization_code): # type: (str) -> se_leg_op.access_token.AccessToken """ Exchanges an authorization code for an access token. """ if authorization_code not in self.authorization_codes: raise InvalidAuthorizationCode('{} unknown'.f...
Exchanges an authorization code for an access token.
entailment
def introspect_access_token(self, access_token_value): # type: (str) -> Dict[str, Union[str, List[str]]] """ Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>. """ if acces...
Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>.
entailment
def create_refresh_token(self, access_token_value): # type: (str) -> str """ Creates an refresh token bound to the specified access token. """ if access_token_value not in self.access_tokens: raise InvalidAccessToken('{} unknown'.format(access_token_value)) i...
Creates an refresh token bound to the specified access token.
entailment
def use_refresh_token(self, refresh_token, scope=None): # type (str, Optional[List[str]]) -> Tuple[se_leg_op.access_token.AccessToken, Optional[str]] """ Creates a new access token, and refresh token, based on the supplied refresh token. :return: new access token and new refresh token if...
Creates a new access token, and refresh token, based on the supplied refresh token. :return: new access token and new refresh token if the old one had an expiration time
entailment
def get_subject_identifier(self, subject_type, user_id, sector_identifier=None): # type: (str, str, str) -> str """ Returns a subject identifier for the local user identifier. :param subject_type: 'pairwise' or 'public', see <a href="http://openid.net/specs/openid-connect-cor...
Returns a subject identifier for the local user identifier. :param subject_type: 'pairwise' or 'public', see <a href="http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes"> "OpenID Connect Core 1.0", Section 8</a>. :param user_id: local user identifier :par...
entailment
def authorization_request_verify(authentication_request): """ Verifies that all required parameters and correct values are included in the authentication request. :param authentication_request: the authentication request to verify :raise InvalidAuthenticationRequest: if the authentication is incorrect ...
Verifies that all required parameters and correct values are included in the authentication request. :param authentication_request: the authentication request to verify :raise InvalidAuthenticationRequest: if the authentication is incorrect
entailment
def client_id_is_known(provider, authentication_request): """ Verifies the client identifier is known. :param provider: provider instance :param authentication_request: the authentication request to verify :raise InvalidAuthenticationRequest: if the client_id is unknown """ if authentication...
Verifies the client identifier is known. :param provider: provider instance :param authentication_request: the authentication request to verify :raise InvalidAuthenticationRequest: if the client_id is unknown
entailment
def redirect_uri_is_in_registered_redirect_uris(provider, authentication_request): """ Verifies the redirect uri is registered for the client making the request. :param provider: provider instance :param authentication_request: authentication request to verify :raise InvalidAuthenticationRequest: if...
Verifies the redirect uri is registered for the client making the request. :param provider: provider instance :param authentication_request: authentication request to verify :raise InvalidAuthenticationRequest: if the redirect uri is not registered
entailment
def response_type_is_in_registered_response_types(provider, authentication_request): """ Verifies that the requested response type is allowed for the client making the request. :param provider: provider instance :param authentication_request: authentication request to verify :raise InvalidAuthentica...
Verifies that the requested response type is allowed for the client making the request. :param provider: provider instance :param authentication_request: authentication request to verify :raise InvalidAuthenticationRequest: if the response type is not allowed
entailment
def userinfo_claims_only_specified_when_access_token_is_issued(authentication_request): """ According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter"> "OpenID Connect Core 1.0", Section 5.5</a>: "When the userinfo member is used, the request MUST also use a response_typ...
According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter"> "OpenID Connect Core 1.0", Section 5.5</a>: "When the userinfo member is used, the request MUST also use a response_type value that results in an Access Token being issued to the Client for use at the UserInfo Endpo...
entailment
def registration_request_verify(registration_request): """ Verifies that all required parameters and correct values are included in the client registration request. :param registration_request: the authentication request to verify :raise InvalidClientRegistrationRequest: if the registration is incorrect...
Verifies that all required parameters and correct values are included in the client registration request. :param registration_request: the authentication request to verify :raise InvalidClientRegistrationRequest: if the registration is incorrect
entailment
def client_preferences_match_provider_capabilities(provider, registration_request): """ Verifies that all requested preferences in the client metadata can be fulfilled by this provider. :param registration_request: the authentication request to verify :raise InvalidClientRegistrationRequest: if the regi...
Verifies that all requested preferences in the client metadata can be fulfilled by this provider. :param registration_request: the authentication request to verify :raise InvalidClientRegistrationRequest: if the registration is incorrect
entailment
def _psi_n(x, n, b): """ Compute the n-th term in the infinite sum of the Jacobi density. """ return 2**(b-1) / gamma(b) * (-1)**n * \ np.exp(gammaln(n+b) - gammaln(n+1) + np.log(2*n+b) - 0.5 * np.log(2*np.pi*x**3) - (2*n+b)**2 / (8.*x))
Compute the n-th term in the infinite sum of the Jacobi density.
entailment
def _tilt(omega, b, psi): """ Compute the tilt of the PG density for value omega and tilt psi. :param omega: point at which to evaluate the density :param psi: tilt parameter """ return np.cosh(psi/2.0)**b * np.exp(-psi**2/2.0 * omega)
Compute the tilt of the PG density for value omega and tilt psi. :param omega: point at which to evaluate the density :param psi: tilt parameter
entailment
def pgpdf(omega, b, psi, trunc=200): """ Approximate the density log PG(omega | b, psi) using a truncation of the density written as an infinite sum. :param omega: point at which to evaluate density :param b: first parameter of PG :param psi: tilting of PG :param trunc: number of terms in...
Approximate the density log PG(omega | b, psi) using a truncation of the density written as an infinite sum. :param omega: point at which to evaluate density :param b: first parameter of PG :param psi: tilting of PG :param trunc: number of terms in sum
entailment
def psi_to_pi(psi, axis=None): """ Convert psi to a probability vector pi :param psi: Length K-1 vector :return: Length K normalized probability vector """ if axis is None: if psi.ndim == 1: K = psi.size + 1 pi = np.zeros(K) # Set pi[1..K-1...
Convert psi to a probability vector pi :param psi: Length K-1 vector :return: Length K normalized probability vector
entailment
def verify_client_authentication(clients, parsed_request, authz_header=None): # type: (Mapping[str, str], Mapping[str, Mapping[str, Any]], Optional[str]) -> bool """ Verifies client authentication at the token endpoint, see <a href="https://tools.ietf.org/html/rfc6749#section-2.3.1">"The OAuth 2.0 Autho...
Verifies client authentication at the token endpoint, see <a href="https://tools.ietf.org/html/rfc6749#section-2.3.1">"The OAuth 2.0 Authorization Framework", Section 2.3.1</a> :param parsed_request: key-value pairs from parsed urlencoded request :param clients: clients db :param authz_header: the H...
entailment
def add_visualization(self, visualization, size_x=6, size_y=3, col=0, row=0): """ Adds the visualization to the dashboard. Leave col and row = 0 for automatic placement of the visualization. Visualizations are placed on a grid with 12 columns and unlimited rows. :param visualization: pre...
Adds the visualization to the dashboard. Leave col and row = 0 for automatic placement of the visualization. Visualizations are placed on a grid with 12 columns and unlimited rows. :param visualization: previously loaded visualization :param size_x width of the panel :param size_y height...
entailment
def remove_visualization(self, visualization_id): """ Removes all visualizations with the specified id from the dashboard :param visualization_id: :return: """ for i, panel in enumerate(self.panels): if panel['id'] == visualization_id: del self...
Removes all visualizations with the specified id from the dashboard :param visualization_id: :return:
entailment
def get_all(self): """ Returns a list of all visualizations :return: list of the Visualization instances """ res = self.es.search(index=self.index, doc_type=self.doc_type, body={'query': {'match_all': {}}}) if not res['hits']['total']: return [] return...
Returns a list of all visualizations :return: list of the Visualization instances
entailment
def add(self, visualization): """ Creates a new visualization :param visualization: instance of Visualization :return: """ res = self.es.create(index=self.index, id=visualization.id or str(uuid.uuid1()), doc_type=s...
Creates a new visualization :param visualization: instance of Visualization :return:
entailment
def update(self, visualization): """ Updates existing visualization :param visualization: instance of Visualization that was previously loaded :return: """ res = self.es.update(index=self.index, id=visualization.id, doc_type=self.doc_type, bod...
Updates existing visualization :param visualization: instance of Visualization that was previously loaded :return:
entailment
def remove(self, visualization): """ Deletes the visualization :param visualization: instance of Visualization that was previously loaded :return: """ res = self.es.delete(index=self.index, id=visualization.id, doc_type=self.doc_type, refresh=True) return res
Deletes the visualization :param visualization: instance of Visualization that was previously loaded :return:
entailment
def bottoms(panels): """ Finds bottom lines of all panels :param panels: :return: sorted by row list of tuples representing lines (col, row , col + len, row) """ bottom_lines = [(p['col'], p['row'] + p['size_y'], p['col'] + p['size_x'], p['row'] + p['size_y']) for p in panels] return sorted(...
Finds bottom lines of all panels :param panels: :return: sorted by row list of tuples representing lines (col, row , col + len, row)
entailment
def find_shape(bottom_lines, max_len): """ Finds a shape of lowest horizontal lines with step=1 :param bottom_lines: :param max_len: :return: list of levels (row values), list indexes are columns """ shape = [1] * max_len for i in range(max_len): for line in bottom_lines: ...
Finds a shape of lowest horizontal lines with step=1 :param bottom_lines: :param max_len: :return: list of levels (row values), list indexes are columns
entailment
def longest_lines(shape): """ Creates lines from shape :param shape: :return: list of dictionaries with col,row,len fields """ lines = [] for level in set(shape): count = 0 for i in range(len(shape)): if shape[i] <= level: count += 1 el...
Creates lines from shape :param shape: :return: list of dictionaries with col,row,len fields
entailment
def append_panel(panels, size_x, size_y, max_col=12): """ Appends a panel to the list of panels. Finds the highest palce at the left for the new panel. :param panels: :param size_x: :param size_y: :param max_col: :return: a new panel or None if it is not possible to place a panel with such s...
Appends a panel to the list of panels. Finds the highest palce at the left for the new panel. :param panels: :param size_x: :param size_y: :param max_col: :return: a new panel or None if it is not possible to place a panel with such size_x
entailment
def run_from_argv(self, argv): """ Set the default Gherkin test runner for its options to be parsed. """ self.test_runner = test_runner_class super(Command, self).run_from_argv(argv)
Set the default Gherkin test runner for its options to be parsed.
entailment
def handle(self, *test_labels, **options): """ Set the default Gherkin test runner. """ if not options.get('testrunner', None): options['testrunner'] = test_runner_class return super(Command, self).handle(*test_labels, **options)
Set the default Gherkin test runner.
entailment
def django_url(step, url=None): """ The URL for a page from the test server. :param step: A Gherkin step :param url: If specified, the relative URL to append. """ base_url = step.test.live_server_url if url: return urljoin(base_url, url) else: return base_url
The URL for a page from the test server. :param step: A Gherkin step :param url: If specified, the relative URL to append.
entailment
def namespace(self, namespace, to=None): """ Filter by namespace. Try to guess which field to use in lookup. Accept 'to' argument if you need to specify. """ fields = get_apphook_field_names(self.model) if not fields: raise ValueError( ugettext...
Filter by namespace. Try to guess which field to use in lookup. Accept 'to' argument if you need to specify.
entailment
def _app_config_select(self, request, obj): """ Return the select value for apphook configs :param request: request object :param obj: current object :return: False if no preselected value is available (more than one or no apphook config is present), apphook con...
Return the select value for apphook configs :param request: request object :param obj: current object :return: False if no preselected value is available (more than one or no apphook config is present), apphook config instance if exactly one apphook config is d...
entailment
def _set_config_defaults(self, request, form, obj=None): """ Cycle through app_config_values and sets the form value according to the options in the current apphook config. self.app_config_values is a dictionary containing config options as keys, form fields as values:: ...
Cycle through app_config_values and sets the form value according to the options in the current apphook config. self.app_config_values is a dictionary containing config options as keys, form fields as values:: app_config_values = { 'apphook_config': 'form_field', ...
entailment
def get_fieldsets(self, request, obj=None): """ If the apphook config must be selected first, returns a fieldset with just the app config field and help text :param request: :param obj: :return: """ app_config_default = self._app_config_select(request, ob...
If the apphook config must be selected first, returns a fieldset with just the app config field and help text :param request: :param obj: :return:
entailment
def get_config_data(self, request, obj, name): """ Method that retrieves a configuration option for a specific AppHookConfig instance :param request: the request object :param obj: the model instance :param name: name of the config option as defined in the config form :...
Method that retrieves a configuration option for a specific AppHookConfig instance :param request: the request object :param obj: the model instance :param name: name of the config option as defined in the config form :return value: config value or None if no app config is found
entailment
def get_form(self, request, obj=None, **kwargs): """ Provides a flexible way to get the right form according to the context For the add view it checks whether the app_config is set; if not, a special form to select the namespace is shown, which is reloaded after namespace selection. ...
Provides a flexible way to get the right form according to the context For the add view it checks whether the app_config is set; if not, a special form to select the namespace is shown, which is reloaded after namespace selection. If only one namespace exists, the current is selected and the no...
entailment
def _models_generator(): """ Build a hash of model verbose names to models """ for app in apps.get_app_configs(): for model in app.get_models(): yield (str(model._meta.verbose_name).lower(), model) yield (str(model._meta.verbose_name_plural).lower(), model)
Build a hash of model verbose names to models
entailment
def get_model(name): """ Convert a model's verbose name to the model class. This allows us to use the models verbose name in steps. """ model = MODELS.get(name.lower(), None) assert model, "Could not locate model by name '%s'" % name return model
Convert a model's verbose name to the model class. This allows us to use the models verbose name in steps.
entailment
def reset_sequence(model): """ Reset the ID sequence for a model. """ sql = connection.ops.sequence_reset_sql(no_style(), [model]) for cmd in sql: connection.cursor().execute(cmd)
Reset the ID sequence for a model.
entailment
def _dump_model(model, attrs=None): """ Dump the model fields for debugging. """ fields = [] for field in model._meta.fields: fields.append((field.name, str(getattr(model, field.name)))) if attrs is not None: for attr in attrs: fields.append((attr, str(getattr(mode...
Dump the model fields for debugging.
entailment
def _model_exists_step(self, model, should_exist): """ Test for the existence of a model matching the given data. """ model = get_model(model) data = guess_types(self.hashes) queryset = model.objects try: existence_check = _TEST_MODEL[model] except KeyError: existence_...
Test for the existence of a model matching the given data.
entailment
def write_models(model, data, field): """ :param model: a Django model class :param data: a list of hashes to build models from :param field: a field name to match models on, or None :returns: a list of models written Create or update models for each data hash. `field` is the field that is...
:param model: a Django model class :param data: a list of hashes to build models from :param field: a field name to match models on, or None :returns: a list of models written Create or update models for each data hash. `field` is the field that is used to get the existing models out of the da...
entailment
def _write_models_step(self, model, field=None): """ Write or update a model. """ model = get_model(model) data = guess_types(self.hashes) try: func = _WRITE_MODEL[model] except KeyError: func = partial(write_models, model) func(data, field)
Write or update a model.
entailment
def _create_models_for_relation_step(self, rel_model_name, rel_key, rel_value, model): """ Create a new model linked to the given model. Syntax: And `model` with `field` "`value`" has `new model` in the database: Example: .. code-block:: gherkin ...
Create a new model linked to the given model. Syntax: And `model` with `field` "`value`" has `new model` in the database: Example: .. code-block:: gherkin And project with name "Ball Project" has goals in the database: | description | ...
entailment
def _create_m2m_links_step(self, rel_model_name, rel_key, rel_value, relation_name): """ Link many-to-many models together. Syntax: And `model` with `field` "`value`" is linked to `other model` in the database: Example: .. code-block:: gherkin ...
Link many-to-many models together. Syntax: And `model` with `field` "`value`" is linked to `other model` in the database: Example: .. code-block:: gherkin And article with name "Guidelines" is linked to tags in the database: | name | | coding | ...
entailment
def _model_count_step(self, count, model): """ Count the number of models in the database. Example: .. code-block:: gherkin Then there should be 0 goals in the database """ model = get_model(model) expected = int(count) found = model.objects.count() assert found == expec...
Count the number of models in the database. Example: .. code-block:: gherkin Then there should be 0 goals in the database
entailment
def mail_sent_count(self, count): """ Test that `count` mails have been sent. Syntax: I have sent `count` emails Example: .. code-block:: gherkin Then I have sent 2 emails """ expected = int(count) actual = len(mail.outbox) assert expected == actual, \ "E...
Test that `count` mails have been sent. Syntax: I have sent `count` emails Example: .. code-block:: gherkin Then I have sent 2 emails
entailment
def mail_sent_content(self, text, part): """ Test an email contains (assert text in) the given text in the relevant message part (accessible as an attribute on the email object). This step strictly applies whitespace. Syntax: I have sent an email with "`text`" in the `part` Example: ...
Test an email contains (assert text in) the given text in the relevant message part (accessible as an attribute on the email object). This step strictly applies whitespace. Syntax: I have sent an email with "`text`" in the `part` Example: .. code-block:: gherkin Then I have sen...
entailment
def mail_sent_contains_html(self): """ Test that an email contains the HTML (assert HTML in) in the multiline as one of its MIME alternatives. The HTML is normalised by passing through Django's :func:`django.test.html.parse_html`. Example: .. code-block:: gherkin And I have sent ...
Test that an email contains the HTML (assert HTML in) in the multiline as one of its MIME alternatives. The HTML is normalised by passing through Django's :func:`django.test.html.parse_html`. Example: .. code-block:: gherkin And I have sent an email with the following HTML alternative: ...
entailment
def dump_emails(part): """Show the sent emails' tested parts, to aid in debugging.""" print("Sent emails:") for email in mail.outbox: print(getattr(email, part))
Show the sent emails' tested parts, to aid in debugging.
entailment
def namespace_url(context, view_name, *args, **kwargs): """ Returns an absolute URL matching named view with its parameters and the provided application instance namespace. If no namespace is passed as a kwarg (or it is "" or None), this templatetag will look into the request object for the app_con...
Returns an absolute URL matching named view with its parameters and the provided application instance namespace. If no namespace is passed as a kwarg (or it is "" or None), this templatetag will look into the request object for the app_config's namespace. If there is still no namespace found, this tag ...
entailment
def get_app_instance(request): """ Returns a tuple containing the current namespace and the AppHookConfig instance :param request: request object :return: namespace, config """ app = None if getattr(request, 'current_page', None) and request.current_page.application_urls: app = apph...
Returns a tuple containing the current namespace and the AppHookConfig instance :param request: request object :return: namespace, config
entailment
def setup_config(form_class, config_model=None): """ Register the provided form as config form for the provided config model This can be used as a decorator by adding a `model` attribute to the config form:: @setup_config class ExampleConfigForm(AppDataForm): model = ExampleCon...
Register the provided form as config form for the provided config model This can be used as a decorator by adding a `model` attribute to the config form:: @setup_config class ExampleConfigForm(AppDataForm): model = ExampleConfig :param form_class: Form class derived from AppDataFo...
entailment
def _get_apphook_field_names(model): """ Return all foreign key field names for a AppHookConfig based model """ from .models import AppHookConfig # avoid circular dependencies fields = [] for field in model._meta.fields: if isinstance(field, ForeignKey) and issubclass(field.remote_field...
Return all foreign key field names for a AppHookConfig based model
entailment
def get_apphook_field_names(model): """ Cache app-hook field names on model :param model: model class or object :return: list of foreign key field names to AppHookConfigs """ key = APP_CONFIG_FIELDS_KEY.format( app_label=model._meta.app_label, model_name=model._meta.object_name ...
Cache app-hook field names on model :param model: model class or object :return: list of foreign key field names to AppHookConfigs
entailment
def get_apphook_configs(obj): """ Get apphook configs for an object obj :param obj: any model instance :return: list of apphook configs for given obj """ keys = get_apphook_field_names(obj) return [getattr(obj, key) for key in keys] if keys else []
Get apphook configs for an object obj :param obj: any model instance :return: list of apphook configs for given obj
entailment
def data_received(self, data): """Receive data from the protocol. Called when asyncio.Protocol detects received data from network. """ _LOGGER.debug("Starting: data_received") _LOGGER.debug('Received %d bytes from PLM: %s', len(data), binascii.hexlify(data)...
Receive data from the protocol. Called when asyncio.Protocol detects received data from network.
entailment
def connection_lost(self, exc): """Reestablish the connection to the transport. Called when asyncio.Protocol loses the network connection. """ if exc is None: _LOGGER.warning('End of file received from Insteon Modem') else: _LOGGER.warning('Lost connectio...
Reestablish the connection to the transport. Called when asyncio.Protocol loses the network connection.
entailment
def add_all_link_done_callback(self, callback): """Register a callback to be invoked when the ALDB is loaded.""" _LOGGER.debug('Added new callback %s ', callback) self._cb_load_all_link_db_done.append(callback)
Register a callback to be invoked when the ALDB is loaded.
entailment
def add_device_not_active_callback(self, callback): """Register callback to be invoked when a device is not responding.""" _LOGGER.debug('Added new callback %s ', callback) self._cb_device_not_active.append(callback)
Register callback to be invoked when a device is not responding.
entailment
def poll_devices(self): """Request status updates from each device.""" for addr in self.devices: device = self.devices[addr] if not device.address.is_x10: device.async_refresh_state()
Request status updates from each device.
entailment
def send_msg(self, msg, wait_nak=True, wait_timeout=WAIT_TIMEOUT): """Place a message on the send queue for sending. Message are sent in the order they are placed in the queue. """ msg_info = MessageInfo(msg=msg, wait_nak=wait_nak, wait_timeout=wait_timeou...
Place a message on the send queue for sending. Message are sent in the order they are placed in the queue.
entailment
def start_all_linking(self, mode, group): """Put the IM into All-Linking mode. Puts the IM into All-Linking mode for 4 minutes. Parameters: mode: 0 | 1 | 3 | 255 0 - PLM is responder 1 - PLM is controller 3 - Device that initiat...
Put the IM into All-Linking mode. Puts the IM into All-Linking mode for 4 minutes. Parameters: mode: 0 | 1 | 3 | 255 0 - PLM is responder 1 - PLM is controller 3 - Device that initiated All-Linking is Controller 255 = De...
entailment
def add_x10_device(self, housecode, unitcode, feature='OnOff'): """Add an X10 device based on a feature description. Current features are: - OnOff - Dimmable - Sensor - AllUnitsOff - AllLightsOn - AllLightsOff """ device = insteonplm.devic...
Add an X10 device based on a feature description. Current features are: - OnOff - Dimmable - Sensor - AllUnitsOff - AllLightsOn - AllLightsOff
entailment
def device_not_active(self, addr): """Handle inactive devices.""" self.aldb_device_handled(addr) for callback in self._cb_device_not_active: callback(addr)
Handle inactive devices.
entailment
def aldb_device_handled(self, addr): """Remove device from ALDB device list.""" if isinstance(addr, Address): remove_addr = addr.id else: remove_addr = addr try: self._aldb_devices.pop(remove_addr) _LOGGER.debug('Removed ALDB device %s', re...
Remove device from ALDB device list.
entailment
def manage_aldb_record(self, control_code, control_flags, group, address, data1, data2, data3): """Update an IM All-Link record. Control Code values: - 0x00 Find First Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link...
Update an IM All-Link record. Control Code values: - 0x00 Find First Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. You will receive an ACK at the en...
entailment
async def pause_writing(self): """Pause writing.""" self._restart_writer = False if self._writer_task: self._writer_task.remove_done_callback(self.restart_writing) self._writer_task.cancel() await self._writer_task await asyncio.sleep(0, loop=self....
Pause writing.
entailment
def restart_writing(self, task=None): """Resume writing.""" if self._restart_writer: self._writer_task = asyncio.ensure_future( self._get_message_from_send_queue(), loop=self._loop) self._writer_task.add_done_callback(self.restart_writing)
Resume writing.
entailment
def _get_plm_info(self): """Request PLM Info.""" _LOGGER.info('Requesting Insteon Modem Info') msg = GetImInfo() self.send_msg(msg, wait_nak=True, wait_timeout=.5)
Request PLM Info.
entailment
def _load_all_link_database(self): """Load the ALL-Link Database into object.""" _LOGGER.debug("Starting: _load_all_link_database") self.devices.state = 'loading' self._get_first_all_link_record() _LOGGER.debug("Ending: _load_all_link_database")
Load the ALL-Link Database into object.
entailment
def _get_first_all_link_record(self): """Request first ALL-Link record.""" _LOGGER.debug("Starting: _get_first_all_link_record") _LOGGER.info('Requesting ALL-Link Records') if self.aldb.status == ALDBStatus.LOADED: self._next_all_link_rec_nak_retries = 3 self._han...
Request first ALL-Link record.
entailment
def _get_next_all_link_record(self): """Request next ALL-Link record.""" _LOGGER.debug("Starting: _get_next_all_link_record") _LOGGER.debug("Requesting Next All-Link Record") msg = GetNextAllLinkRecord() self.send_msg(msg, wait_nak=True, wait_timeout=.5) _LOGGER.debug("En...
Request next ALL-Link record.
entailment
def x10_all_units_off(self, housecode): """Send the X10 All Units Off command.""" if isinstance(housecode, str): housecode = housecode.upper() else: raise TypeError('Housecode must be a string') msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_UNITS_OFF) ...
Send the X10 All Units Off command.
entailment
def x10_all_lights_off(self, housecode): """Send the X10 All Lights Off command.""" msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_LIGHTS_OFF) self.send_msg(msg) self._x10_command_to_device(housecode, X10_COMMAND_ALL_LIGHTS_OFF, msg)
Send the X10 All Lights Off command.
entailment
def x10_all_lights_on(self, housecode): """Send the X10 All Lights Off command.""" msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_LIGHTS_ON) self.send_msg(msg) self._x10_command_to_device(housecode, X10_COMMAND_ALL_LIGHTS_ON, msg)
Send the X10 All Lights Off command.
entailment
def connection_made(self, transport): """Start the PLM connection process. Called when asyncio.Protocol establishes the network connection. """ _LOGGER.info('Connection established to PLM') self.transport = transport self._restart_writer = True self.restart_writ...
Start the PLM connection process. Called when asyncio.Protocol establishes the network connection.
entailment
def connection_made(self, transport): """Start the Hub connection process. Called when asyncio.Protocol establishes the network connection. """ _LOGGER.info('Connection established to Hub') _LOGGER.debug('Transport: %s', transport) self.transport = transport sel...
Start the Hub connection process. Called when asyncio.Protocol establishes the network connection.
entailment
def create(plm, address, cat, subcat, firmware=None): """Create a device from device info data.""" from insteonplm.devices.ipdb import IPDB ipdb = IPDB() product = ipdb[[cat, subcat]] deviceclass = product.deviceclass device = None if deviceclass is not None: device = deviceclass(plm...
Create a device from device info data.
entailment
def create_x10(plm, housecode, unitcode, feature): """Create an X10 device from a feature definition.""" from insteonplm.devices.ipdb import IPDB ipdb = IPDB() product = ipdb.x10(feature) deviceclass = product.deviceclass device = None if deviceclass: device = deviceclass(plm, housec...
Create an X10 device from a feature definition.
entailment
def id_request(self): """Request a device ID from a device.""" import inspect curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) _LOGGER.debug('caller name: %s', calframe[1][3]) msg = StandardSend(self.address, COMMAND_ID_REQUEST_0X10_0X00) ...
Request a device ID from a device.
entailment
def product_data_request(self): """Request product data from a device. Not supported by all devices. Required after 01-Feb-2007. """ msg = StandardSend(self._address, COMMAND_PRODUCT_DATA_REQUEST_0X03_0X00) self._send_msg(msg)
Request product data from a device. Not supported by all devices. Required after 01-Feb-2007.
entailment
def assign_to_all_link_group(self, group=0x01): """Assign a device to an All-Link Group. The default is group 0x01. """ msg = StandardSend(self._address, COMMAND_ASSIGN_TO_ALL_LINK_GROUP_0X01_NONE, cmd2=group) self._send_msg(...
Assign a device to an All-Link Group. The default is group 0x01.
entailment
def delete_from_all_link_group(self, group): """Delete a device to an All-Link Group.""" msg = StandardSend(self._address, COMMAND_DELETE_FROM_ALL_LINK_GROUP_0X02_NONE, cmd2=group) self._send_msg(msg)
Delete a device to an All-Link Group.
entailment
def fx_username(self): """Get FX Username. Only required for devices that support FX Commands. FX Addressee responds with an ED 0x0301 FX Username Response message """ msg = StandardSend(self._address, COMMAND_FX_USERNAME_0X03_0X01) self._send_msg(msg)
Get FX Username. Only required for devices that support FX Commands. FX Addressee responds with an ED 0x0301 FX Username Response message
entailment
def device_text_string_request(self): """Get FX Username. Only required for devices that support FX Commands. FX Addressee responds with an ED 0x0301 FX Username Response message. """ msg = StandardSend(self._address, COMMAND_FX_USERNAME_0X03_0X01) self._send_msg(msg)
Get FX Username. Only required for devices that support FX Commands. FX Addressee responds with an ED 0x0301 FX Username Response message.
entailment
def enter_linking_mode(self, group=0x01): """Tell a device to enter All-Linking Mode. Same as holding down the Set button for 10 sec. Default group is 0x01. Not supported by i1 devices. """ msg = ExtendedSend(self._address, COMMAND_ENTER_LINKI...
Tell a device to enter All-Linking Mode. Same as holding down the Set button for 10 sec. Default group is 0x01. Not supported by i1 devices.
entailment
def enter_unlinking_mode(self, group): """Unlink a device from an All-Link group. Not supported by i1 devices. """ msg = StandardSend(self._address, COMMAND_ENTER_UNLINKING_MODE_0X0A_NONE, cmd2=group) self._send_msg(msg)
Unlink a device from an All-Link group. Not supported by i1 devices.
entailment
def get_engine_version(self): """Get the device engine version.""" msg = StandardSend(self._address, COMMAND_GET_INSTEON_ENGINE_VERSION_0X0D_0X00) self._send_msg(msg)
Get the device engine version.
entailment
def ping(self): """Ping a device.""" msg = StandardSend(self._address, COMMAND_PING_0X0F_0X00) self._send_msg(msg)
Ping a device.
entailment
def create_default_links(self): """Create the default links between the IM and the device.""" self._plm.manage_aldb_record(0x40, 0xe2, 0x00, self.address, self.cat, self.subcat, self.product_key) self.manage_aldb_record(0x41, 0xa2, 0x00, self._plm.address, ...
Create the default links between the IM and the device.
entailment
def read_aldb(self, mem_addr=0x0000, num_recs=0): """Read the device All-Link Database.""" if self._aldb.version == ALDBVersion.Null: _LOGGER.info('Device %s does not contain an All-Link Database', self._address.human) else: _LOGGER.info('Reading ...
Read the device All-Link Database.
entailment