code
stringlengths
1
18.2k
PHOTOMETRY.MAGNITUDE in x else '')) if (self._KEYS.SPECTRA in self and list( filter(None, [ SPECTRUM.TIME in x for x in self[self._KEYS.SPECTRA] ]))): self[self._KEYS.SPECTRA].sort( key=lambda x: (float(x[SPECTRUM.TIME]) if SPECTRUM.TIME in x else 0.0, x[SPECTRUM.FILENAME] if SPECTRUM.FILENAME in x else '') ) if self._...
retained source_list = [ x[SOURCE.ALIAS] for x in self[self._KEYS.SOURCES] if SOURCE.PRIVATE in x ] for key in self: # if self._KEYS.get_key_by_name(key).no_source: if (key in [ self._KEYS.NAME, self._KEYS.SCHEMA, self._KEYS.SOURCES, self._KEYS.ERRORS ]): continue for item in self[key]: source_list += item[item._KEYS.S...
del self[self._KEYS.SOURCES] self[self._KEYS.SOURCES] = new_sources
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, filename = self._get_save_path(bury=bury) if final: self.sanitize() # FIX: use 'dump...
if not os.path.isdir(outdir): raise RuntimeError("Output directory '{}' for event '{}' does " "not exist.".format(outdir, self[ self._KEYS.NAME])) save_name = os.path.join(outdir, filename + '.json') with codecs.open(save_name, 'w', encoding='utf8') as sf: sf.write(jsonstring) if not os.path.exists(save_name): raise Ru...
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.SOURCES: return 'aac' if key == self._KEYS.ALIAS: return 'aad' if key == s...
def set_pd_mag_from_counts(photodict, c='', ec='', lec='', uec='', zp=DEFAULT_ZP, sig=DEFAULT_UL_SIGMA): """Set photometry dictionary from a counts measurement.""" with localcontext() as ctx: if lec == '' or uec == '': lec = ec uec = ec prec = max( get_sig_digits(str(c), strip_zeroes=False), get_sig_digits(str(lec), st...
= Decimal(str(sig)) photodict[PHOTOMETRY.ZERO_POINT] = str(zp) if c == '' or float(c) < float(sig) * float(uec): photodict[PHOTOMETRY.UPPER_LIMIT] = True photodict[PHOTOMETRY.UPPER_LIMIT_SIGMA] = str(sig) photodict[PHOTOMETRY.MAGNITUDE] = str(dzp - (D25 * (dsig * duec ).log10())) dnec = Decimal('10.0') ** ( (dzp - Deci...
(dc + duec).log10() - dc.log10())) photodict[PHOTOMETRY.E_LOWER_MAGNITUDE] = str(D25 * ( dc.log10() - (dc - dlec).log10()))
def set_pd_mag_from_flux_density(photodict, fd='', efd='', lefd='', uefd='', sig=DEFAULT_UL_SIGMA): """Set photometry dictionary from a flux density measurement. `fd` is assumed to be in microjanskys. """ with localcontext() as ctx: if lefd == '' or uefd == '': lefd = efd uefd = efd prec = max( get_sig_digits(str(fd), ...
'': dfd = Decimal(str(fd)) dsig = Decimal(str(sig)) if fd == '' or float(fd) < DEFAULT_UL_SIGMA * float(uefd): photodict[PHOTOMETRY.UPPER_LIMIT] = True photodict[PHOTOMETRY.UPPER_LIMIT_SIGMA] = str(sig) photodict[PHOTOMETRY.MAGNITUDE] = str(Decimal('23.9') - D25 * ( dsig * duefd).log10()) if fd: photodict[PHOTOMETRY.E_...
= str(D25 * ( dfd.log10() - (dfd - dlefd).log10()))
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 has_u_flux_dens = self._KEYS.U_FLUX_DENSITY in self has_freq = s...
has_flux or has_flux_dens: if not any([has_freq, has_band, has_ener]): err_str = ("Has `{}` or `{}`".format(self._KEYS.FLUX, self._KEYS.FLUX_DENSITY) + " but None of `{}`, `{}`, `{}`".format( self._KEYS.FREQUENCY, self._KEYS.BAND, self._KEYS.ENERGY)) elif has_flux and not has_u_flux: err_str = "`{}` provided without `{...
self._KEYS.U_FREQUENCY) elif has_ener and not has_u_ener: err_str = "`{}` provided without `{}`.".format( self._KEYS.ENERGY, self._KEYS.U_ENERGY) if err_str is not None: raise ValueError(err_str) return
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
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 given string to the script o...
context.run_migrations()
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_metadata=target_metadata, version_table="alembic...
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: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filte...
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(protocol, sizeof(protocol), model, sizeof(model), byref(sid), byref(dat...
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, value, sizeof(value), byref(timestamp)) return {'value': ...
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(ctype), name, sizeof(name), byref(available)) return {'id': cid.va...
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 import CryptContext if not schemes: sche...
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 model to service if model has one specified as `_zigg...
use :return: """ models = ModelProxy() models.User = user models.Group = group models.UserGroup = user_group models.GroupPermission = group_permission models.UserPermission = user_permission models.UserResourcePermission = user_resource_permission models.GroupResourcePermission = group_resource_permission models.Resour...
manager services = model_service_mapping.get(name, []) for service in services: setattr(service, "model", cls) setattr(service, "models_proxy", models)
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): messages = messages.filter(join_or_leave=Fals...
- day_delta next_date = this_date + day_delta prev_url = reverse("gnotty_day", args=prev_date.timetuple()[:3]) next_url = reverse("gnotty_day", args=next_date.timetuple()[:3]) else: return redirect("gnotty_year", year=datetime.now().year) context = dict(settings) context["messages"] = messages context["prev_url"] = pre...
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_time__month"] = month if hide_joins_and_leaves(request)...
max_date = days[0], days[-1] days = set(days) calendar = Calendar(SUNDAY) for m in range(1, 13) if not month else [int(month)]: lt_max = m <= max_date.month or year < max_date.year gt_min = m >= min_date.month or year > min_date.year if lt_max and gt_min: weeks = calendar.monthdatescalendar(year, m) for w, week in enum...
m, "has_messages": day in days, } months.append({"month": date(year, m, 1), "weeks": weeks}) context = dict(settings) context["months"] = months return render(request, template, context)
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. If the attr do...
function calling `func` with `name`. Example usage: .. code-block:: python class SomeClientDecorator(object): def __init__(self, api_client, ...): self.api_client = api_client # First arg should be suffiently unique to not conflict with any of # the kwargs def wrap_call(self, client_call_name, *args, **kwargs): ... def...
accepts `name`, `*args`, `**kwargs` :type func: callable :param name: the attribute being accessed :type name: string :returns: the attribute from the `api_client` or a partial of `func` :raises: :class:`AttributeError` """ client_attr = getattr(api_client, name) if not callable(client_attr): return client_attr return ...
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()
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(): self.lock = DBMutex.objects.create(lock_id=self.lock_id) except Integ...
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)) else: self.lock.delete()
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) return result except DBMutexError as e: if self.suppress_acquisition_exceptions: LOG.error(e) else:...
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 return []
def force_atlas2_layout(graph, pos_list=None, node_masses=None, iterations=100, outbound_attraction_distribution=False, lin_log_mode=False, prevent_overlapping=False, edge_weight_influence=1.0, jitter_tolerance=1.0, barnes_hut_optimize=False, barnes_hut_theta=1.2, scaling_ratio=2.0, strong_gravity_mode=False, multithre...
If None, then use random initial positions. node_masses : dict or None optional (default=None) Predefined masses for nodes with node as keys and masses as values. If None, then use degree of nodes. iterations : int optional (default=50) Number of iterations outbound_attraction_distribution : boolean Distributes attract...
grant authorities (nodes with a high indegree) a more central position than hubs (nodes with a high outdegree). This is useful for social networks and web networks, where authorities are sometimes considered more important than hubs lin_log_mode: boolean Switch ForceAtlas model from lin-lin to lin-log (tribute to Andre...
that the nodes do not overlap. The goal is to produce a more readable and aesthetically pleasing image. edge_weight_influence: float How much influence you give to the edges weight. 0 is “no influence” and 1 is “normal”. jitter_tolerance: float How much swinging you allow. Above 1 discouraged. Lower gives less speed an...
allows larger graphs. barnes_hut_theta: float Theta of the Barnes Hut optimization scaling_ratio: float How much repulsion you want. More makes a more sparse graph. strong_gravity_mode: boolean The “Strong gravity” option sets a force that attracts the nodes that are distant from the center more ( is this distance). Th...
other forces. It may result in a biased placement of the nodes. However, its advantage is to force a very compact layout, which may be useful for certain purposes. multithread: boolean gravity: float Attracts nodes to the center. Prevents islands from drifting away. Returns ------- pos : dict A dictionary of positions ...
isinstance(pos_list, dict) or (pos_list is None), "pos must be specified as a dictionary, as in networkx" assert multithread is False, "Not implemented yet" G = numpy.asarray(networkx.to_numpy_matrix(graph)) pos = None if pos_list is not None: pos = numpy.asarray([pos_list[i] for i in graph.nodes()]) masses = None if n...
2D square" assert numpy.all(G.T == G), "G is not symmetric." # speed and speed efficiency describe a scaling factor of dx and dy # before x and y are adjusted. These are modified as the # algorithm runs to help ensure convergence. speed = 1 speed_efficiency = 1 nodes = [] for i in range(0, G.shape[0]): n = Node() if no...
= 1 + numpy.count_nonzero(G[i]) else: n.mass = masses[i] n.old_dx = 0 n.old_dy = 0 n.dx = 0 n.dy = 0 if pos is None: n.x = random.random() n.y = random.random() else: n.x = pos[i][0] n.y = pos[i][1] nodes.append(n) edges = [] es = numpy.asarray(G.nonzero()).T for e in es: if e[1] <= e[0]: continue # Avoid duplicate edg...
The index of the first node in `nodes` edge.node2 = e[1] # The index of the second node in `nodes` edge.weight = G[tuple(e)] edges.append(edge) repulsion = get_repulsion(prevent_overlapping, scaling_ratio) if strong_gravity_mode: gravity_force = get_strong_gravity(scaling_ratio) else: gravity_force = repulsion if outbo...
in range(0, iterations): for n in nodes: n.old_dx = n.dx n.old_dy = n.dy n.dx = 0 n.dy = 0 # Barnes Hut optimization root_region = None if barnes_hut_optimize: root_region = Quadtree(nodes) root_region.build() apply_repulsion(repulsion, nodes, barnes_hut_optimize=barnes_hut_optimize, barnes_hut_theta=barnes_hut_theta, ...
movement for n in nodes: swinging = math.sqrt((n.old_dx - n.dx) * (n.old_dx - n.dx) + (n.old_dy - n.dy) * (n.old_dy - n.dy)) total_swinging += n.mass * swinging total_effective_traction += .5 * n.mass * math.sqrt( (n.old_dx + n.dx) * (n.old_dx + n.dx) + (n.old_dy + n.dy) * (n.old_dy + n.dy)) # Optimize jitter tolerance...
need more tolerance. Denser networks need less tolerance. # Totally empiric. estimated_optimal_jitter_tolerance = .05 * math.sqrt(len(nodes)) min_jt = math.sqrt(estimated_optimal_jitter_tolerance) max_jt = 10 jt = jitter_tolerance * max(min_jt, min(max_jt, estimated_optimal_jitter_tolerance * total_effective_traction /...
speed_efficiency * total_effective_traction / total_swinging if total_swinging > jt * total_effective_traction: if speed_efficiency > min_speed_efficiency: speed_efficiency *= .7 elif speed < 1000: speed_efficiency *= 1.3 # But the speed shoudn't rise too much too quickly, since it would # make the convergence drop dra...
in nodes: swinging = n.mass * math.sqrt( (n.old_dx - n.dx) * (n.old_dx - n.dx) + (n.old_dy - n.dy) * (n.old_dy - n.dy)) factor = 0.1 * speed / (1 + math.sqrt(speed * swinging)) df = math.sqrt(math.pow(n.dx, 2) + n.dy ** 2) factor = min(factor * df, 10.) / df x = n.dx * factor y = n.dy * factor else: for n in nodes:
swinging = n.mass * math.sqrt( (n.old_dx - n.dx) * (n.old_dx - n.dx) + (n.old_dy - n.dy) * (n.old_dy - n.dy)) factor = speed / (1.0 + math.sqrt(speed * swinging)) n.x = n.x + (n.dx * factor) n.y = n.y + (n.dy * factor) positions = [(n.x, n.y) for n in nodes] return dict(zip(graph.nodes(), positions))
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): repulsion.apply_node_to_node(nodes[i], nodes...
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)
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: """ db_session = get_db_session(db_session) return db_session.que...
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_session(db_session) query = db_session.query(cls.model) query = q...
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_session(db_session) query = db_session.query(cls.models_proxy.User) query = query....
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).filter(cls.model.user_id == user_id) query = query.filter(cls.model.perm_na...
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(): # pragma no branch if inf.qname() in subclass_names: return...
we are a subclass of # a subclass of a subclass ... return True except InferenceError: # pragma no cover continue return False
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 = node.last_child() inferred...
cls_name, inst in FIELD_TYPES.items(): if node_is_instance(inferred, cls_name) and hasattr(inst, name): return True return False
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
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
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
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
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 in self.events[event.eventtype()]: handler(self, connect...
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)
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) for handler in self.events["command"]: if handler.event.args["command"] =...
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(command) num_all_args = len(argspec.args) - 2 # Ignore sel...
= command(self, event, *args) elif num_all_args == num_pos_args: s = "s are" if num_all_args != 1 else " is" response = "%s arg%s required" % (num_all_args, s) else: bits = (num_pos_args, num_all_args) response = "between %s and %s args are required" % bits response = "%s: %s" % (self.get_nickname(event), response) sel...
def handle_timer_event(self, handler): """ Runs each timer handler in a separate greenlet thread. """ while True: handler(self) sleep(handler.event.args["seconds"])
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. """ for handler in self.events["webhook"]...
params) if response: return response
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) return Device(id, lib=lib)
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(block=block) try: callback(*args) finally: self._queu...
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) devices.append(device) return devices
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: if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND: raise return sensors
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() del controller["name"] del controller["available"] controllers.append(Controller(lib=self.lib...
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 if model: device.model = model for key, value in parameters.items...
exc_info[2]) else: exec("raise exc_info[0], exc_info[1], exc_info[2]")
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
def connect_controller(self, vid, pid, serial): """Connect a controller.""" self.lib.tdConnectTellStickController(vid, pid, serial)
def disconnect_controller(self, vid, pid, serial): """Disconnect a controller.""" self.lib.tdDisconnectTellStickController(vid, pid, serial)
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
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
def set_parameter(self, name, value): """Set a parameter.""" self.lib.tdSetDeviceParameter(self.id, name, str(value))
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)
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)
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]
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 SensorValue(datatype, value['value'], value['timestamp'])
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() points.insert(0, point) continue break
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 the first on curve type and recycle ...
for index, point in enumerate(points): if point.segmentType is not None: firstOnCurve = index break lastSegmentType = points[firstOnCurve].segmentType # reverse the points points = reversed(points) # work through the reversed remaining points final = [] for point in points: segmentType = point.segmentType if segmentTyp...
to the start of the points _prepPointsForSegments(final) # done return final
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 assert previousOnCurve is not None # gather the segments...