INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Get the sensor value for a given sensor.
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 next controller while iterating.
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(...
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.
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...
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
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...
Show messages for the given query or day.
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 calendar months for the given year/ month.
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...
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: AttributeError if it...
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...
Deletes all expired mutex locks if a ttl is provided.
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()
Acquires the db mutex lock. Takes the necessary steps to delete any stale locks. Throws a DBMutexError if it can t acquire the lock.
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(): ...
Releases the db mutex lock. Throws an error if the lock was released before the function finished.
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)) ...
Decorates a function with the db_mutex decorator by using this class as a context manager around it.
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) ...
Default groupfinder implementaion for pyramid applications
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...
Position nodes using ForceAtlas2 force - directed algorithm
def force_atlas2_layout(graph, pos_list=None, node_masses=None, iterations=100, outbound_attraction_distribution=False, lin_log_mode=False, prevent_overlapping=False, ...
Iterate through the nodes or edges and apply the forces directly to the node objects.
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 gravity directly to the node objects.
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)
Fetch row using primary key - will use existing object in session if already present
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: ...
Returns ExternalIdentity instance based on search params
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 User instance based on search params
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...
return by user and permission name
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...
Checks if cls node has parent with subclass_name.
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 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...
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...
Supposes that node is a mongoengine field in a class and tries to get its parent class
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
node is a class attribute that is a mongoengine. Returns the definition statement for the attribute
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
Returns de ClassDef for the related embedded document in a embedded document field.
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
Checks if a node is a valid field or method in a embedded document.
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
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.
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 ...
We won t receive our own messages so log them manually.
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)
Log any public messages and also handle the command event.
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) ...
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.
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...
Runs each timer handler in a separate greenlet thread.
def handle_timer_event(self, handler): """ Runs each timer handler in a separate greenlet thread. """ while True: handler(self) sleep(handler.event.args["seconds"])
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.
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. ...
Create the correct device instance based on device type and return it.
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...
Dispatch a single callback in the current thread.
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(...
Return all known devices.
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 sensors.
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 controllers.
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() ...
Add a new device.
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 group.
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
Connect a controller.
def connect_controller(self, vid, pid, serial): """Connect a controller.""" self.lib.tdConnectTellStickController(vid, pid, serial)
Disconnect a controller.
def disconnect_controller(self, vid, pid, serial): """Disconnect a controller.""" self.lib.tdDisconnectTellStickController(vid, pid, serial)
Get dict with all set parameters.
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 a parameter.
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
Set a parameter.
def set_parameter(self, name, value): """Set a parameter.""" self.lib.tdSetDeviceParameter(self.id, name, str(value))
Add device ( s ) to the group.
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)
Remove device ( s ) from the group.
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)
Fetch list of devices in group.
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]
Return the: class: SensorValue for the given data type.
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...
Move any off curves at the end of the contour to the beginning of the contour. This makes segmentation easier.
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() ...
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.
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 ...
Compile points into InputSegment objects.
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 ...
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
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...
Scale points and optionally convert them to integers.
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 a single point
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)
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 must not be sent here.
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...
Estimate the length of this curve by iterating through it and averaging the length of the flat bits.
def _estimateCubicCurveLength(pt0, pt1, pt2, pt3, precision=10): """ Estimate the length of this curve by iterating through it and averaging the length of the flat bits. """ points = [] length = 0 step = 1.0 / precision factors = range(0, precision + 1) for i in factors: poin...
( Point Point ) - > Point Return the point that lies in between the two input points.
def _mid(pt1, pt2): """ (Point, Point) -> Point Return the point that lies in between the two input points. """ (x0, y0), (x1, y1) = pt1, pt2 return 0.5 * (x0 + x1), 0.5 * (y0 + y1)
Split the segment according the t values
def split(self, tValues): """ Split the segment according the t values """ if self.segmentType == "curve": on1 = self.previousOnCurve off1 = self.points[0].coordinates off2 = self.points[1].coordinates on2 = self.points[2].coordinates ...
get a t values for a given point required: the point must be a point on the curve. in an overlap cause the point will be an intersection points wich is alwasy a point on the curve
def tValueForPoint(self, point): """ get a t values for a given point required: the point must be a point on the curve. in an overlap cause the point will be an intersection points wich is alwasy a point on the curve """ if self.segmentType == "curve": ...
Return a list of normalized InputPoint objects for the contour drawn with this pen.
def getData(self): """ Return a list of normalized InputPoint objects for the contour drawn with this pen. """ # organize the points into segments # 1. make sure there is an on curve haveOnCurve = False for point in self._points: if point.segme...
Match if entire input contour matches entire output contour allowing for different start point.
def reCurveFromEntireInputContour(self, inputContour): """ Match if entire input contour matches entire output contour, allowing for different start point. """ if self.clockwise: inputFlat = inputContour.clockwiseFlat else: inputFlat = inputContour...
Checks if a function definition is a queryset manager created with the
def _is_custom_qs_manager(funcdef): """Checks if a function definition is a queryset manager created with the @queryset_manager decorator.""" decors = getattr(funcdef, 'decorators', None) if decors: for dec in decors.get_children(): try: if dec.name == 'queryset_mana...
Checks if the call is being done to a custom queryset manager.
def _is_call2custom_manager(node): """Checks if the call is being done to a custom queryset manager.""" called = safe_infer(node.func) funcdef = getattr(called, '_proxied', None) return _is_custom_qs_manager(funcdef)
Checks if the attribute is a valid attribute for a queryset manager.
def _is_custom_manager_attribute(node): """Checks if the attribute is a valid attribute for a queryset manager. """ attrname = node.attrname if not name_is_from_qs(attrname): return False for attr in node.get_children(): inferred = safe_infer(attr) funcdef = getattr(inferre...
return by by_user_and_perm and permission name
def by_group_and_perm(cls, group_id, perm_name, db_session=None): """ return by by_user_and_perm and permission name :param group_id: :param perm_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.quer...
Starts the gevent - socketio server.
def serve_forever(django=False): """ Starts the gevent-socketio server. """ logger = getLogger("irc.dispatch") logger.setLevel(settings.LOG_LEVEL) logger.addHandler(StreamHandler()) app = IRCApplication(django) server = SocketIOServer((settings.HTTP_HOST, settings.HTTP_PORT), app) pr...
Attempts to shut down a previously started daemon.
def kill(pid_file): """ Attempts to shut down a previously started daemon. """ try: with open(pid_file) as f: os.kill(int(f.read()), 9) os.remove(pid_file) except (IOError, OSError): return False return True
CLI entry point. Parses args and starts the gevent - socketio server.
def run(): """ CLI entry point. Parses args and starts the gevent-socketio server. """ settings.parse_args() pid_name = "gnotty-%s-%s.pid" % (settings.HTTP_HOST, settings.HTTP_PORT) pid_file = settings.PID_FILE or os.path.join(gettempdir(), pid_name) if settings.KILL: if kill(pid_fil...
A WebSocket session has started - create a greenlet to host the IRC client and start it.
def on_start(self, host, port, channel, nickname, password): """ A WebSocket session has started - create a greenlet to host the IRC client, and start it. """ self.client = WebSocketIRCClient(host, port, channel, nickname, password, self) ...
WebSocket was disconnected - leave the IRC channel.
def disconnect(self, *args, **kwargs): """ WebSocket was disconnected - leave the IRC channel. """ quit_message = "%s %s" % (settings.GNOTTY_VERSION_STRING, settings.GNOTTY_PROJECT_URL) self.client.connection.quit(quit_message) super(IRCN...
Thread ( greenlet ) that will try and reconnect the bot if it s not connected.
def bot_watcher(self): """ Thread (greenlet) that will try and reconnect the bot if it's not connected. """ default_interval = 5 interval = default_interval while True: if not self.bot.connection.connected: if self.bot.reconnect(): ...
Passes the request onto a bot with a webhook if the webhook path is requested.
def respond_webhook(self, environ): """ Passes the request onto a bot with a webhook if the webhook path is requested. """ request = FieldStorage(fp=environ["wsgi.input"], environ=environ) url = environ["PATH_INFO"] params = dict([(k, request[k].value) for k in re...
Serves a static file when Django isn t being used.
def respond_static(self, environ): """ Serves a static file when Django isn't being used. """ path = os.path.normpath(environ["PATH_INFO"]) if path == "/": content = self.index() content_type = "text/html" else: path = os.path.join(os.p...
Loads the chat interface template when Django isn t being used manually dealing with the Django template bits.
def index(self): """ Loads the chat interface template when Django isn't being used, manually dealing with the Django template bits. """ root_dir = os.path.dirname(__file__) template_dir = os.path.join(root_dir, "templates", "gnotty") with open(os.path.join(templa...
If we re running Django and GNOTTY_LOGIN_REQUIRED is set to True pull the session cookie from the environment and validate that the user is authenticated.
def authorized(self, environ): """ If we're running Django and ``GNOTTY_LOGIN_REQUIRED`` is set to ``True``, pull the session cookie from the environment and validate that the user is authenticated. """ if self.django and settings.LOGIN_REQUIRED: try: ...
Write your forwards methods here.
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." if not db.dry_run: orm['gnotty.IRCMessage'].objects.filter(message="joins").update(join_or_leave=True) orm['gnotty.IRCMessage...
Returns permission tuples that match one of passed permission names perm_names - list of permissions that can be matched user_ids - restrict to specific users group_ids - restrict to specific groups resource_ids - restrict to specific resources limit_group_permissions - should be used if we do not want to have user obj...
def resource_permissions_for_users( models_proxy, perm_names, resource_ids=None, user_ids=None, group_ids=None, resource_types=None, limit_group_permissions=False, skip_user_perms=False, skip_group_perms=False, db_session=None, ): """ Returns permission tuples that match ...
Legacy acl format kept for bw. compatibility: param permissions:: return:
def permission_to_04_acls(permissions): """ Legacy acl format kept for bw. compatibility :param permissions: :return: """ acls = [] for perm in permissions: if perm.type == "user": acls.append((perm.user.id, perm.perm_name)) elif perm.type == "group": ...
Returns a list of permissions in a format understood by pyramid: param permissions:: return:
def permission_to_pyramid_acls(permissions): """ Returns a list of permissions in a format understood by pyramid :param permissions: :return: """ acls = [] for perm in permissions: if perm.type == "user": acls.append((Allow, perm.user.id, perm.perm_name)) elif per...
[ { self: [ 1 1 3 3 1 1 ] f: lambda x: x%2 assert: lambda ret: ret == [[ 1 1 ] [ 3 3 ] [ 1 1 ]] } ]
def ChunkBy(self, f=None): """ [ { 'self': [1, 1, 3, 3, 1, 1], 'f': lambda x: x%2, 'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]] } ] """ if f is None: return _chunk(self) if is_to_destruct(f): f = destruct_func(f) r...
[ { self: [ 1 2 3 ] f: lambda x: x%2 assert: lambda ret: ret [ 0 ] == [ 2 ] and ret [ 1 ] == [ 1 3 ] } ]
def GroupBy(self: Iterable, f=None): """ [ { 'self': [1, 2, 3], 'f': lambda x: x%2, 'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3] } ] """ if f and is_to_destruct(f): f = destruct_func(f) return _group_by(self, f)
[ { self: [ 1 2 3 ] n: 2 assert: lambda ret: list ( ret ) == [ 1 2 ] } ]
def Take(self: Iterable, n): """ [ { 'self': [1, 2, 3], 'n': 2, 'assert': lambda ret: list(ret) == [1, 2] } ] """ for i, e in enumerate(self): if i == n: break yield e
[ { self: [ 1 2 3 ] f: lambda e: e%2 assert: lambda ret: list ( ret ) == [ 1 3 ] } ]
def TakeIf(self: Iterable, f): """ [ { 'self': [1, 2, 3], 'f': lambda e: e%2, 'assert': lambda ret: list(ret) == [1, 3] } ] """ if is_to_destruct(f): f = destruct_func(f) return (e for e in self if f(e))
[ { self: [ 1 2 3 4 5 ] f: lambda x: x < 4 assert: lambda ret: list ( ret ) == [ 1 2 3 ] } ]
def TakeWhile(self: Iterable, f): """ [ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: list(ret) == [1, 2, 3] } ] """ if is_to_destruct(f): f = destruct_func(f) for e in self: if not f(e): ...
[ { self: [ 1 2 3 4 5 ] n: 3 assert: lambda ret: list ( ret ) == [ 1 2 ] } ]
def Drop(self: Iterable, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ] """ con = tuple(self) n = len(con) - n if n <= 0: yield from con else: for i, e in enumerate(con): ...
[ { self: [ 1 2 3 4 5 ] n: 3 assert: lambda ret: list ( ret ) == [ 4 5 ] } ]
def Skip(self: Iterable, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5] } ] """ con = iter(self) for i, _ in enumerate(con): if i == n: break retur...
[ { self: [ 1 2 3 4 5 ] n: 3 assert: lambda ret: list ( ret ) == [ 4 5 1 2 3 ] } ]
def Shift(self, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5, 1, 2, 3] } ] """ headn = tuple(Take(self, n)) yield from self yield from headn
[ { self: [ 1 2 3 ]: args: [[ 4 5 6 ] [ 7 8 9 ]] assert: lambda ret: list ( ret ) == [ 1 2 3 4 5 6 7 8 9 ] } ]
def Concat(self: Iterable, *others): """ [ { 'self': [1, 2, 3], ':args': [[4, 5, 6], [7, 8, 9]], 'assert': lambda ret: list(ret) == [1, 2, 3, 4, 5, 6, 7, 8, 9] } ] """ return concat_generator(self, *[unbox_if_flow(other) for other in others])
Checks if an attribute is being accessed throught the default queryset manager ie: MyClass. objects. filter ( some = value )
def _called_thru_default_qs(self, node): """Checks if an attribute is being accessed throught the default queryset manager, ie: MyClass.objects.filter(some='value')""" last_child = node.last_child() if not last_child: return False # the default qs manager is called '...
returns all objects of specific type - will work correctly with sqlalchemy inheritance models you should normally use models base_query () instead of this function its for bw. compat purposes
def all(cls, klass, db_session=None): """ returns all objects of specific type - will work correctly with sqlalchemy inheritance models, you should normally use models base_query() instead of this function its for bw. compat purposes :param klass: :param db_session: ...
returns base query for specific service
def base_query(cls, db_session=None): """ returns base query for specific service :param db_session: :return: query """ db_session = get_db_session(db_session) return db_session.query(cls.model)
Event method wrapper for bot mixins. When a bot is constructed its metaclass inspects all members of all base classes and looks for methods marked with an event attribute which is assigned via this wrapper. It then stores all the methods in a dict that maps event names to lists of these methods which are each called wh...
def on(event, *args, **kwargs): """ Event method wrapper for bot mixins. When a bot is constructed, its metaclass inspects all members of all base classes, and looks for methods marked with an event attribute which is assigned via this wrapper. It then stores all the methods in a dict that maps ...
utility function that attempts to return sqlalchemy session that could have been created/ passed in one of few ways:
def get_db_session(session=None, obj=None): """ utility function that attempts to return sqlalchemy session that could have been created/passed in one of few ways: * It first tries to read session attached to instance if object argument was passed * then it tries to return session passed as...
return dictionary of keys and values corresponding to this model s data - if include_keys is null the function will return all keys
def get_dict(self, exclude_keys=None, include_keys=None): """ return dictionary of keys and values corresponding to this model's data - if include_keys is null the function will return all keys :param exclude_keys: (optional) is a list of columns from model that should not be re...
return list of tuples keys and values corresponding to this model s data
def get_appstruct(self): """ return list of tuples keys and values corresponding to this model's data """ result = [] for k in self._get_keys(): result.append((k, getattr(self, k))) return result
updates instance properties * for column names that exist * for this model and are keys present in passed dictionary
def populate_obj(self, appstruct, exclude_keys=None, include_keys=None): """ updates instance properties *for column names that exist* for this model and are keys present in passed dictionary :param appstruct: (dictionary) :param exclude_keys: (optional) is a list of columns fro...
updates instance properties * for column names that exist * for this model and are properties present in passed dictionary
def populate_obj_from_obj(self, instance, exclude_keys=None, include_keys=None): """ updates instance properties *for column names that exist* for this model and are properties present in passed dictionary :param instance: :param exclude_keys: (optional) is a list of columns fro...
Deletes the object via session this will permanently delete the object from storage on commit
def delete(self, db_session=None): """ Deletes the object via session, this will permanently delete the object from storage on commit :param db_session: :return: """ db_session = get_db_session(db_session, self) db_session.delete(self)
turn off the HX711: return: always True: rtype bool
def power_down(self): """ turn off the HX711 :return: always True :rtype bool """ GPIO.output(self._pd_sck, False) GPIO.output(self._pd_sck, True) time.sleep(0.01) return True
power up the HX711
def power_up(self): """ power up the HX711 :return: always True :rtype bool """ GPIO.output(self._pd_sck, False) time.sleep(0.01) return True
reset the HX711 and prepare it for the next reading
def reset(self): """ reset the HX711 and prepare it for the next reading :return: True on success :rtype bool :raises GenericHX711Exception """ logging.debug("power down") self.power_down() logging.debug("power up") self.power_up() ...