sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def IOR(type, nr, size): """ An ioctl with read parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_READ, type, nr, IOC_TYPECHECK(size))
An ioctl with read parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument.
entailment
def IOW(type, nr, size): """ An ioctl with write parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_WRITE, type, nr, IOC_TYPECHECK(size))
An ioctl with write parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument.
entailment
def IOWR(type, nr, size): """ An ioctl with both read an writes parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument. """ return IOC(IOC_READ | IOC_WRITE, type, nr, IOC_TYPECHECK(size))
An ioctl with both read an writes parameters. size (ctype type or instance) Type/structure of the argument passed to ioctl's "arg" argument.
entailment
def _get_last_dirs(path, num=1): """Get a path including only the trailing `num` directories. Returns ------- last_path : str """ head, tail = os.path.split(path) last_path = str(tail) for ii in range(num): head, tail = os.path.split(head) last_path = os.path.join(tail,...
Get a path including only the trailing `num` directories. Returns ------- last_path : str
entailment
def analyze(self, args): """Run the analysis routines determined from the given `args`. """ self.log.info("Running catalog analysis") if args.count: self.count() return
Run the analysis routines determined from the given `args`.
entailment
def count(self): """Analyze the counts of ...things. Returns ------- retvals : dict Dictionary of 'property-name: counts' pairs for further processing """ self.log.info("Running 'count'") retvals = {} # Numbers of 'tasks' num_tasks =...
Analyze the counts of ...things. Returns ------- retvals : dict Dictionary of 'property-name: counts' pairs for further processing
entailment
def _count_tasks(self): """Count the number of tasks, both in the json and directory. Returns ------- num_tasks : int The total number of all tasks included in the `tasks.json` file. """ self.log.warning("Tasks:") tasks, task_names = self.catalog._lo...
Count the number of tasks, both in the json and directory. Returns ------- num_tasks : int The total number of all tasks included in the `tasks.json` file.
entailment
def _count_repo_files(self): """Count the number of files in the data repositories. `_COUNT_FILE_TYPES` are used to determine which file types are checked explicitly. `_IGNORE_FILES` determine which files are ignored in (most) counts. Returns ------- repo_files ...
Count the number of files in the data repositories. `_COUNT_FILE_TYPES` are used to determine which file types are checked explicitly. `_IGNORE_FILES` determine which files are ignored in (most) counts. Returns ------- repo_files : int Total number of (non-i...
entailment
def _file_nums_str(self, n_all, n_type, n_ign): """Construct a string showing the number of different file types. Returns ------- f_str : str """ # 'other' is the difference between all and named n_oth = n_all - np.sum(n_type) f_str = "{} Files".format(n...
Construct a string showing the number of different file types. Returns ------- f_str : str
entailment
def _count_files_by_type(self, path, pattern, ignore=True): """Count files in the given path, with the given pattern. If `ignore = True`, skip files in the `_IGNORE_FILES` list. Returns ------- num_files : int """ # Get all files matching the given path and pat...
Count files in the given path, with the given pattern. If `ignore = True`, skip files in the `_IGNORE_FILES` list. Returns ------- num_files : int
entailment
def bibcode_from_url(cls, url): """Given a URL, try to find the ADS bibcode. Currently: only `ads` URLs will work, e.g. Returns ------- code : str or 'None' The Bibcode if found, otherwise 'None' """ try: code = url.split('/abs/') ...
Given a URL, try to find the ADS bibcode. Currently: only `ads` URLs will work, e.g. Returns ------- code : str or 'None' The Bibcode if found, otherwise 'None'
entailment
def _get_save_path(self, bury=False): """Return the path that this Entry should be saved to.""" filename = self.get_filename(self[self._KEYS.NAME]) # Put objects that shouldn't belong in this catalog in the boneyard if bury: outdir = self.catalog.get_repo_boneyard() ...
Return the path that this Entry should be saved to.
entailment
def _ordered(self, odict): """Convert the object into a plain OrderedDict.""" ndict = OrderedDict() if isinstance(odict, CatDict) or isinstance(odict, Entry): key = odict.sort_func else: key = None nkeys = list(sorted(odict.keys(), key=key)) for ...
Convert the object into a plain OrderedDict.
entailment
def get_hash(self, keys=[]): """Return a unique hash associated with the listed keys.""" if not len(keys): keys = list(self.keys()) string_rep = '' oself = self._ordered(deepcopy(self)) for key in keys: string_rep += json.dumps(oself.get(key, ''), sort_ke...
Return a unique hash associated with the listed keys.
entailment
def _clean_quantity(self, quantity): """Clean quantity value before it is added to entry.""" value = quantity.get(QUANTITY.VALUE, '').strip() error = quantity.get(QUANTITY.E_VALUE, '').strip() unit = quantity.get(QUANTITY.U_VALUE, '').strip() kind = quantity.get(QUANTITY.KIND, ''...
Clean quantity value before it is added to entry.
entailment
def _convert_odict_to_classes(self, data, clean=False, merge=True, pop_schema=True, compare_to_existing=True, filter...
Convert `OrderedDict` into `Entry` or its derivative classes.
entailment
def _check_cat_dict_source(self, cat_dict_class, key_in_self, **kwargs): """Check that a source exists and that a quantity isn't erroneous.""" # Make sure that a source is given source = kwargs.get(cat_dict_class._KEYS.SOURCE, None) if source is None: raise CatDictError( ...
Check that a source exists and that a quantity isn't erroneous.
entailment
def _add_cat_dict(self, cat_dict_class, key_in_self, check_for_dupes=True, compare_to_existing=True, **kwargs): """Add a `CatDict` to this `Entry`. CatDict only added if initialization succeeds...
Add a `CatDict` to this `Entry`. CatDict only added if initialization succeeds and it doesn't already exist within the Entry.
entailment
def init_from_file(cls, catalog, name=None, path=None, clean=False, merge=True, pop_schema=True, ignore_keys=[], compare_to_existing=Tru...
Construct a new `Entry` instance from an input file. The input file can be given explicitly by `path`, or a path will be constructed appropriately if possible. Arguments --------- catalog : `astrocats.catalog.catalog.Catalog` instance The parent catalog object of wh...
entailment
def add_alias(self, alias, source, clean=True): """Add an alias, optionally 'cleaning' the alias string. Calls the parent `catalog` method `clean_entry_name` - to apply the same name-cleaning as is applied to entry names themselves. Returns ------- alias : str ...
Add an alias, optionally 'cleaning' the alias string. Calls the parent `catalog` method `clean_entry_name` - to apply the same name-cleaning as is applied to entry names themselves. Returns ------- alias : str The stored version of the alias (cleaned or not).
entailment
def add_error(self, value, **kwargs): """Add an `Error` instance to this entry.""" kwargs.update({ERROR.VALUE: value}) self._add_cat_dict(Error, self._KEYS.ERRORS, **kwargs) return
Add an `Error` instance to this entry.
entailment
def add_photometry(self, compare_to_existing=True, **kwargs): """Add a `Photometry` instance to this entry.""" self._add_cat_dict( Photometry, self._KEYS.PHOTOMETRY, compare_to_existing=compare_to_existing, **kwargs) return
Add a `Photometry` instance to this entry.
entailment
def merge_dupes(self): """Merge two entries that correspond to the same entry.""" for dupe in self.dupe_of: if dupe in self.catalog.entries: if self.catalog.entries[dupe]._stub: # merge = False to avoid infinite recursion self.catalog.l...
Merge two entries that correspond to the same entry.
entailment
def add_quantity(self, quantities, value, source, check_for_dupes=True, compare_to_existing=True, **kwargs): """Add an `Quantity` instance to this entry.""" success = True ...
Add an `Quantity` instance to this entry.
entailment
def add_self_source(self): """Add a source that refers to the catalog itself. For now this points to the Open Supernova Catalog by default. """ return self.add_source( bibcode=self.catalog.OSC_BIBCODE, name=self.catalog.OSC_NAME, url=self.catalog.OSC_...
Add a source that refers to the catalog itself. For now this points to the Open Supernova Catalog by default.
entailment
def add_source(self, allow_alias=False, **kwargs): """Add a `Source` instance to this entry.""" if not allow_alias and SOURCE.ALIAS in kwargs: err_str = "`{}` passed in kwargs, this shouldn't happen!".format( SOURCE.ALIAS) self._log.error(err_str) rais...
Add a `Source` instance to this entry.
entailment
def add_model(self, allow_alias=False, **kwargs): """Add a `Model` instance to this entry.""" if not allow_alias and MODEL.ALIAS in kwargs: err_str = "`{}` passed in kwargs, this shouldn't happen!".format( SOURCE.ALIAS) self._log.error(err_str) raise R...
Add a `Model` instance to this entry.
entailment
def add_spectrum(self, compare_to_existing=True, **kwargs): """Add a `Spectrum` instance to this entry.""" spec_key = self._KEYS.SPECTRA # Make sure that a source is given, and is valid (nor erroneous) source = self._check_cat_dict_source(Spectrum, spec_key, **kwargs) if source i...
Add a `Spectrum` instance to this entry.
entailment
def check(self): """Check that the entry has the required fields.""" # Make sure there is a schema key in dict if self._KEYS.SCHEMA not in self: self[self._KEYS.SCHEMA] = self.catalog.SCHEMA.URL # Make sure there is a name key in dict if (self._KEYS.NAME not in self o...
Check that the entry has the required fields.
entailment
def get_aliases(self, includename=True): """Retrieve the aliases of this object as a list of strings. Arguments --------- includename : bool Include the 'name' parameter in the list of aliases. """ # empty list if doesnt exist alias_quanta = self.get(...
Retrieve the aliases of this object as a list of strings. Arguments --------- includename : bool Include the 'name' parameter in the list of aliases.
entailment
def get_entry_text(self, fname): """Retrieve the raw text from a file.""" if fname.split('.')[-1] == 'gz': with gz.open(fname, 'rt') as f: filetext = f.read() else: with codecs.open(fname, 'r') as f: filetext = f.read() return filet...
Retrieve the raw text from a file.
entailment
def get_source_by_alias(self, alias): """Given an alias, find the corresponding source in this entry. If the given alias doesn't exist (e.g. there are no sources), then a `ValueError` is raised. Arguments --------- alias : str The str-integer (e.g. '8') of t...
Given an alias, find the corresponding source in this entry. If the given alias doesn't exist (e.g. there are no sources), then a `ValueError` is raised. Arguments --------- alias : str The str-integer (e.g. '8') of the target source. Returns ------...
entailment
def get_stub(self): """Get a new `Entry` which contains the 'stub' of this one. The 'stub' is only the name and aliases. Usage: ----- To convert a normal entry into a stub (for example), overwrite the entry in place, i.e. >>> entries[name] = entries[name].get_st...
Get a new `Entry` which contains the 'stub' of this one. The 'stub' is only the name and aliases. Usage: ----- To convert a normal entry into a stub (for example), overwrite the entry in place, i.e. >>> entries[name] = entries[name].get_stub() Returns -...
entailment
def is_erroneous(self, field, sources): """Check if attribute has been marked as being erroneous.""" if self._KEYS.ERRORS in self: my_errors = self[self._KEYS.ERRORS] for alias in sources.split(','): source = self.get_source_by_alias(alias) bib_err...
Check if attribute has been marked as being erroneous.
entailment
def is_private(self, key, sources): """Check if attribute is private.""" # aliases are always public. if key == ENTRY.ALIAS: return False return all([ SOURCE.PRIVATE in self.get_source_by_alias(x) for x in sources.split(',') ])
Check if attribute is private.
entailment
def sanitize(self): """Sanitize the data (sort it, etc.) before writing it to disk. Template method that can be overridden in each catalog's subclassed `Entry` object. """ name = self[self._KEYS.NAME] aliases = self.get_aliases(includename=False) if name not in ...
Sanitize the data (sort it, etc.) before writing it to disk. Template method that can be overridden in each catalog's subclassed `Entry` object.
entailment
def save(self, bury=False, final=False): """Write entry to JSON file in the proper location. Arguments --------- bury : bool final : bool If this is the 'final' save, perform additional sanitization and cleaning operations. """ outdir, f...
Write entry to JSON file in the proper location. Arguments --------- bury : bool final : bool If this is the 'final' save, perform additional sanitization and cleaning operations.
entailment
def sort_func(self, key): """Used to sort keys when writing Entry to JSON format. Should be supplemented/overridden by inheriting classes. """ if key == self._KEYS.SCHEMA: return 'aaa' if key == self._KEYS.NAME: return 'aab' if key == self._KEYS.S...
Used to sort keys when writing Entry to JSON format. Should be supplemented/overridden by inheriting classes.
entailment
def set_pd_mag_from_counts(photodict, c='', ec='', lec='', uec='', zp=DEFAULT_ZP, sig=DEFAULT_UL_SIGMA): """Set photometry dictionary from a counts measur...
Set photometry dictionary from a counts measurement.
entailment
def set_pd_mag_from_flux_density(photodict, fd='', efd='', lefd='', uefd='', sig=DEFAULT_UL_SIGMA): """Set photometry dictionary from a flux density me...
Set photometry dictionary from a flux density measurement. `fd` is assumed to be in microjanskys.
entailment
def _check(self): """Check that entry attributes are legal.""" # Run the super method super(Photometry, self)._check() err_str = None has_flux = self._KEYS.FLUX in self has_flux_dens = self._KEYS.FLUX_DENSITY in self has_u_flux = self._KEYS.U_FLUX in self ...
Check that entry attributes are legal.
entailment
def sort_func(self, key): """Specify order for attributes.""" if key == self._KEYS.TIME: return 'aaa' if key == self._KEYS.MODEL: return 'zzy' if key == self._KEYS.SOURCE: return 'zzz' return key
Specify order for attributes.
entailment
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
entailment
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ engine = create_engine(get_url()) connection = engine.connect() context.configure( connection=connection, target_m...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
entailment
def by_resource_user_and_perm( cls, user_id, perm_name, resource_id, db_session=None ): """ return all instances by user name, perm name and resource id :param user_id: :param perm_name: :param resource_id: :param db_session: :return: """ ...
return all instances by user name, perm name and resource id :param user_id: :param perm_name: :param resource_id: :param db_session: :return:
entailment
def tdSensor(self): """Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes. """ protocol = create_string_buffer(20) model = create_string_buffer(20) sid = c_int() datatypes = c_int() self._lib.tdSensor(proto...
Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes.
entailment
def tdSensorValue(self, protocol, model, sid, datatype): """Get the sensor value for a given sensor. :return: a dict with the keys: value, timestamp. """ value = create_string_buffer(20) timestamp = c_int() self._lib.tdSensorValue(protocol, model, sid, datatype, ...
Get the sensor value for a given sensor. :return: a dict with the keys: value, timestamp.
entailment
def tdController(self): """Get the next controller while iterating. :return: a dict with the keys: id, type, name, available. """ cid = c_int() ctype = c_int() name = create_string_buffer(255) available = c_int() self._lib.tdController(byref(cid), byref(...
Get the next controller while iterating. :return: a dict with the keys: id, type, name, available.
entailment
def make_passwordmanager(schemes=None): """ schemes contains a list of replace this list with the hash(es) you wish to support. this example sets pbkdf2_sha256 as the default, with support for legacy bcrypt hashes. :param schemes: :return: CryptContext() """ from passlib.context imp...
schemes contains a list of replace this list with the hash(es) you wish to support. this example sets pbkdf2_sha256 as the default, with support for legacy bcrypt hashes. :param schemes: :return: CryptContext()
entailment
def ziggurat_model_init( user=None, group=None, user_group=None, group_permission=None, user_permission=None, user_resource_permission=None, group_resource_permission=None, resource=None, external_identity=None, *args, **kwargs ): """ This function handles attaching m...
This function handles attaching model to service if model has one specified as `_ziggurat_service`, Also attached a proxy object holding all model definitions that services might use :param args: :param kwargs: :param passwordmanager, the password manager to override default one :param password...
entailment
def messages(request, year=None, month=None, day=None, template="gnotty/messages.html"): """ Show messages for the given query or day. """ query = request.REQUEST.get("q") prev_url, next_url = None, None messages = IRCMessage.objects.all() if hide_joins_and_leaves(request): ...
Show messages for the given query or day.
entailment
def calendar(request, year=None, month=None, template="gnotty/calendar.html"): """ Show calendar months for the given year/month. """ try: year = int(year) except TypeError: year = datetime.now().year lookup = {"message_time__year": year} if month: lookup["message_ti...
Show calendar months for the given year/month.
entailment
def decorate_client(api_client, func, name): """A helper for decorating :class:`bravado.client.SwaggerClient`. :class:`bravado.client.SwaggerClient` can be extended by creating a class which wraps all calls to it. This helper is used in a :func:`__getattr__` to check if the attr exists on the api_client...
A helper for decorating :class:`bravado.client.SwaggerClient`. :class:`bravado.client.SwaggerClient` can be extended by creating a class which wraps all calls to it. This helper is used in a :func:`__getattr__` to check if the attr exists on the api_client. If the attr does not exist raise :class:`Attri...
entailment
def delete_expired_locks(self): """ Deletes all expired mutex locks if a ttl is provided. """ ttl_seconds = self.get_mutex_ttl_seconds() if ttl_seconds is not None: DBMutex.objects.filter(creation_time__lte=timezone.now() - timedelta(seconds=ttl_seconds)).delete()
Deletes all expired mutex locks if a ttl is provided.
entailment
def start(self): """ Acquires the db mutex lock. Takes the necessary steps to delete any stale locks. Throws a DBMutexError if it can't acquire the lock. """ # Delete any expired locks first self.delete_expired_locks() try: with transaction.atomic(): ...
Acquires the db mutex lock. Takes the necessary steps to delete any stale locks. Throws a DBMutexError if it can't acquire the lock.
entailment
def stop(self): """ Releases the db mutex lock. Throws an error if the lock was released before the function finished. """ if not DBMutex.objects.filter(id=self.lock.id).exists(): raise DBMutexTimeoutError('Lock {0} expired before function completed'.format(self.lock_id)) ...
Releases the db mutex lock. Throws an error if the lock was released before the function finished.
entailment
def decorate_callable(self, func): """ Decorates a function with the db_mutex decorator by using this class as a context manager around it. """ def wrapper(*args, **kwargs): try: with self: result = func(*args, **kwargs) ...
Decorates a function with the db_mutex decorator by using this class as a context manager around it.
entailment
def groupfinder(userid, request): """ Default groupfinder implementaion for pyramid applications :param userid: :param request: :return: """ if userid and hasattr(request, "user") and request.user: groups = ["group:%s" % g.id for g in request.user.groups] return groups r...
Default groupfinder implementaion for pyramid applications :param userid: :param request: :return:
entailment
def force_atlas2_layout(graph, pos_list=None, node_masses=None, iterations=100, outbound_attraction_distribution=False, lin_log_mode=False, prevent_overlapping=False, ...
Position nodes using ForceAtlas2 force-directed algorithm Parameters ---------- graph: NetworkX graph A position will be assigned to every node in G. pos_list : dict or None optional (default=None) Initial positions for nodes as a dictionary with node as keys and values as a c...
entailment
def apply_repulsion(repulsion, nodes, barnes_hut_optimize=False, region=None, barnes_hut_theta=1.2): """ Iterate through the nodes or edges and apply the forces directly to the node objects. """ if not barnes_hut_optimize: for i in range(0, len(nodes)): for j in range(0, i): ...
Iterate through the nodes or edges and apply the forces directly to the node objects.
entailment
def apply_gravity(repulsion, nodes, gravity, scaling_ratio): """ Iterate through the nodes or edges and apply the gravity directly to the node objects. """ for i in range(0, len(nodes)): repulsion.apply_gravitation(nodes[i], gravity / scaling_ratio)
Iterate through the nodes or edges and apply the gravity directly to the node objects.
entailment
def get(cls, external_id, local_user_id, provider_name, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param external_id: :param local_user_id: :param provider_name: :param db_session: :return: ...
Fetch row using primary key - will use existing object in session if already present :param external_id: :param local_user_id: :param provider_name: :param db_session: :return:
entailment
def by_external_id_and_provider(cls, external_id, provider_name, db_session=None): """ Returns ExternalIdentity instance based on search params :param external_id: :param provider_name: :param db_session: :return: ExternalIdentity """ db_session = get_db_...
Returns ExternalIdentity instance based on search params :param external_id: :param provider_name: :param db_session: :return: ExternalIdentity
entailment
def user_by_external_id_and_provider( cls, external_id, provider_name, db_session=None ): """ Returns User instance based on search params :param external_id: :param provider_name: :param db_session: :return: User """ db_session = get_db_sessi...
Returns User instance based on search params :param external_id: :param provider_name: :param db_session: :return: User
entailment
def by_user_and_perm(cls, user_id, perm_name, db_session=None): """ return by user and permission name :param user_id: :param perm_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).fi...
return by user and permission name :param user_id: :param perm_name: :param db_session: :return:
entailment
def node_is_subclass(cls, *subclass_names): """Checks if cls node has parent with subclass_name.""" if not isinstance(cls, (ClassDef, Instance)): return False # if cls.bases == YES: # return False for base_cls in cls.bases: try: for inf in base_cls.inferred(): # pra...
Checks if cls node has parent with subclass_name.
entailment
def is_field_method(node): """Checks if a call to a field instance method is valid. A call is valid if the call is a method of the underlying type. So, in a StringField the methods from str are valid, in a ListField the methods from list are valid and so on...""" name = node.attrname parent = no...
Checks if a call to a field instance method is valid. A call is valid if the call is a method of the underlying type. So, in a StringField the methods from str are valid, in a ListField the methods from list are valid and so on...
entailment
def get_node_parent_class(node): """Supposes that node is a mongoengine field in a class and tries to get its parent class""" while node.parent: # pragma no branch if isinstance(node, ClassDef): return node node = node.parent
Supposes that node is a mongoengine field in a class and tries to get its parent class
entailment
def get_field_definition(node): """"node is a class attribute that is a mongoengine. Returns the definition statement for the attribute """ name = node.attrname cls = get_node_parent_class(node) definition = cls.lookup(name)[1][0].statement() return definition
node is a class attribute that is a mongoengine. Returns the definition statement for the attribute
entailment
def get_field_embedded_doc(node): """Returns de ClassDef for the related embedded document in a embedded document field.""" definition = get_field_definition(node) cls_name = definition.last_child().last_child() cls = next(cls_name.infer()) return cls
Returns de ClassDef for the related embedded document in a embedded document field.
entailment
def node_is_embedded_doc_attr(node): """Checks if a node is a valid field or method in a embedded document. """ embedded_doc = get_field_embedded_doc(node.last_child()) name = node.attrname try: r = bool(embedded_doc.lookup(name)[1][0]) except IndexError: r = False return r
Checks if a node is a valid field or method in a embedded document.
entailment
def _dispatcher(self, connection, event): """ This is the method in ``SimpleIRCClient`` that all IRC events get passed through. Here we map events to our own custom event handlers, and call them. """ super(BaseBot, self)._dispatcher(connection, event) for handler ...
This is the method in ``SimpleIRCClient`` that all IRC events get passed through. Here we map events to our own custom event handlers, and call them.
entailment
def message_channel(self, message): """ We won't receive our own messages, so log them manually. """ self.log(None, message) super(BaseBot, self).message_channel(message)
We won't receive our own messages, so log them manually.
entailment
def on_pubmsg(self, connection, event): """ Log any public messages, and also handle the command event. """ for message in event.arguments(): self.log(event, message) command_args = filter(None, message.split()) command_name = command_args.pop(0) ...
Log any public messages, and also handle the command event.
entailment
def handle_command_event(self, event, command, args): """ Command handler - treats each word in the message that triggered the command as an argument to the command, and does some validation to ensure that the number of arguments match. """ argspec = getargspec(co...
Command handler - treats each word in the message that triggered the command as an argument to the command, and does some validation to ensure that the number of arguments match.
entailment
def handle_timer_event(self, handler): """ Runs each timer handler in a separate greenlet thread. """ while True: handler(self) sleep(handler.event.args["seconds"])
Runs each timer handler in a separate greenlet thread.
entailment
def handle_webhook_event(self, environ, url, params): """ Webhook handler - each handler for the webhook event takes an initial pattern argument for matching the URL requested. Here we match the URL to the pattern for each webhook handler, and bail out if it returns a response. ...
Webhook handler - each handler for the webhook event takes an initial pattern argument for matching the URL requested. Here we match the URL to the pattern for each webhook handler, and bail out if it returns a response.
entailment
def DeviceFactory(id, lib=None): """Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ lib = lib or Library() if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP: return DeviceGroup(id, lib=lib) re...
Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance.
entailment
def process_callback(self, block=True): """Dispatch a single callback in the current thread. :param boolean block: If True, blocks waiting for a callback to come. :return: True if a callback was processed; otherwise False. """ try: (callback, args) = self._queue.get(...
Dispatch a single callback in the current thread. :param boolean block: If True, blocks waiting for a callback to come. :return: True if a callback was processed; otherwise False.
entailment
def devices(self): """Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances. """ devices = [] count = self.lib.tdGetNumberOfDevices() for i in range(count): device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)...
Return all known devices. :return: list of :class:`Device` or :class:`DeviceGroup` instances.
entailment
def sensors(self): """Return all known sensors. :return: list of :class:`Sensor` instances. """ sensors = [] try: while True: sensor = self.lib.tdSensor() sensors.append(Sensor(lib=self.lib, **sensor)) except TelldusError as e:...
Return all known sensors. :return: list of :class:`Sensor` instances.
entailment
def controllers(self): """Return all known controllers. Requires Telldus core library version >= 2.1.2. :return: list of :class:`Controller` instances. """ controllers = [] try: while True: controller = self.lib.tdController() ...
Return all known controllers. Requires Telldus core library version >= 2.1.2. :return: list of :class:`Controller` instances.
entailment
def add_device(self, name, protocol, model=None, **parameters): """Add a new device. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ device = Device(self.lib.tdAddDevice(), lib=self.lib) try: device.name = name device.protocol = protocol ...
Add a new device. :return: a :class:`Device` or :class:`DeviceGroup` instance.
entailment
def add_group(self, name, devices): """Add a new device group. :return: a :class:`DeviceGroup` instance. """ device = self.add_device(name, "group") device.add_to_group(devices) return device
Add a new device group. :return: a :class:`DeviceGroup` instance.
entailment
def connect_controller(self, vid, pid, serial): """Connect a controller.""" self.lib.tdConnectTellStickController(vid, pid, serial)
Connect a controller.
entailment
def disconnect_controller(self, vid, pid, serial): """Disconnect a controller.""" self.lib.tdDisconnectTellStickController(vid, pid, serial)
Disconnect a controller.
entailment
def parameters(self): """Get dict with all set parameters.""" parameters = {} for name in self.PARAMETERS: try: parameters[name] = self.get_parameter(name) except AttributeError: pass return parameters
Get dict with all set parameters.
entailment
def get_parameter(self, name): """Get a parameter.""" default_value = "$%!)(INVALID)(!%$" value = self.lib.tdGetDeviceParameter(self.id, name, default_value) if value == default_value: raise AttributeError(name) return value
Get a parameter.
entailment
def set_parameter(self, name, value): """Set a parameter.""" self.lib.tdSetDeviceParameter(self.id, name, str(value))
Set a parameter.
entailment
def add_to_group(self, devices): """Add device(s) to the group.""" ids = {d.id for d in self.devices_in_group()} ids.update(self._device_ids(devices)) self._set_group(ids)
Add device(s) to the group.
entailment
def remove_from_group(self, devices): """Remove device(s) from the group.""" ids = {d.id for d in self.devices_in_group()} ids.difference_update(self._device_ids(devices)) self._set_group(ids)
Remove device(s) from the group.
entailment
def devices_in_group(self): """Fetch list of devices in group.""" try: devices = self.get_parameter('devices') except AttributeError: return [] ctor = DeviceFactory return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]
Fetch list of devices in group.
entailment
def value(self, datatype): """Return the :class:`SensorValue` for the given data type. sensor.value(TELLSTICK_TEMPERATURE) is identical to calling sensor.temperature(). """ value = self.lib.tdSensorValue( self.protocol, self.model, self.id, datatype) return S...
Return the :class:`SensorValue` for the given data type. sensor.value(TELLSTICK_TEMPERATURE) is identical to calling sensor.temperature().
entailment
def _prepPointsForSegments(points): """ Move any off curves at the end of the contour to the beginning of the contour. This makes segmentation easier. """ while 1: point = points[-1] if point.segmentType: break else: point = points.pop() ...
Move any off curves at the end of the contour to the beginning of the contour. This makes segmentation easier.
entailment
def _reversePoints(points): """ Reverse the points. This differs from the reversal point pen in RoboFab in that it doesn't worry about maintaing the start point position. That has no benefit within the context of this module. """ # copy the points points = _copyPoints(points) # find ...
Reverse the points. This differs from the reversal point pen in RoboFab in that it doesn't worry about maintaing the start point position. That has no benefit within the context of this module.
entailment
def _convertPointsToSegments(points, willBeReversed=False): """ Compile points into InputSegment objects. """ # get the last on curve previousOnCurve = None for point in reversed(points): if point.segmentType is not None: previousOnCurve = point.coordinates break ...
Compile points into InputSegment objects.
entailment
def _tValueForPointOnCubicCurve(point, cubicCurve, isHorizontal=0): """ Finds a t value on a curve from a point. The points must be originaly be a point on the curve. This will only back trace the t value, needed to split the curve in parts """ pt1, pt2, pt3, pt4 = cubicCurve a, b, c, d = be...
Finds a t value on a curve from a point. The points must be originaly be a point on the curve. This will only back trace the t value, needed to split the curve in parts
entailment
def _scalePoints(points, scale=1, convertToInteger=True): """ Scale points and optionally convert them to integers. """ if convertToInteger: points = [ (int(round(x * scale)), int(round(y * scale))) for (x, y) in points ] else: points = [(x * scale, y ...
Scale points and optionally convert them to integers.
entailment
def _scaleSinglePoint(point, scale=1, convertToInteger=True): """ Scale a single point """ x, y = point if convertToInteger: return int(round(x * scale)), int(round(y * scale)) else: return (x * scale, y * scale)
Scale a single point
entailment
def _flattenSegment(segment, approximateSegmentLength=_approximateSegmentLength): """ Flatten the curve segment int a list of points. The first and last points in the segment must be on curves. The returned list of points will not include the first on curve point. false curves (where the off cur...
Flatten the curve segment int a list of points. The first and last points in the segment must be on curves. The returned list of points will not include the first on curve point. false curves (where the off curves are not any different from the on curves) must not be sent here. duplicate points ...
entailment