code
stringlengths
1
18.2k
points=offCurves + [point], previousOnCurve=previousOnCurve, willBeReversed=willBeReversed ) segments.append(segment) offCurves = [] previousOnCurve = point.coordinates assert not offCurves return segments
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 = bezierTools.calcCubicParameter...
point[isHorizontal]) solutions = [t for t in solutions if 0 <= t < 1] if not solutions and not isHorizontal: # can happen that a horizontal line doens intersect, try the vertical return _tValueForPointOnCubicCurve(point, (pt1, pt2, pt3, pt4), isHorizontal=1) if len(solutions) > 1: intersectionLenghts = {} for t in solu...
minDist = min(intersectionLenghts.keys()) solutions = [intersectionLenghts[minDist]] return solutions
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) for (x, y) in points] return points
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)
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 curves are not any differen...
""" onCurve1, offCurve1, offCurve2, onCurve2 = segment if _pointOnLine(onCurve1, onCurve2, offCurve1) and _pointOnLine(onCurve1, onCurve2, offCurve2): return [onCurve2] est = _estimateCubicCurveLength(onCurve1, offCurve1, offCurve2, onCurve2) / approximateSegmentLength flat = [] minStep = 0.1564 step = 1.0 / est if ste...
same direction as the on - off curve line if not _pointOnLine(offCurve2, onCurve2, pt) and not _pointOnLine(onCurve1, offCurve1, pt): flat.append(pt) t += step flat.append(onCurve2) return flat
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: points.append(_getCubicPoint(i * step, pt0, pt1,...
= points[i + 1] length += _distance(pta, ptb) return length
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)
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 return bezierTools.splitCubicAtT(on1, off1, off2, on2, *tValues) elif self.segmentTyp...
t in tValues: np = (x1+dx*t, y1+dy*t) segments.append([pp, np]) pp = np segments.append([pp, (x2, y2)]) return segments elif self.segmentType == "qcurve": raise NotImplementedError else: raise NotImplementedError
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": on1 = self.previousOnCurve off1 = self.points[0].coordinates off2 =...
elif self.segmentType == "line": return _tValueForPointOnLine(point, (self.previousOnCurve, self.points[0].coordinates)) elif self.segmentType == "qcurve": raise NotImplementedError else: raise NotImplementedError
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.segmentType is not None: haveOnCurve = True break # 2. move the off curves to fro...
3. ignore double points on start and end firstPoint = self._points[0] lastPoint = self._points[-1] if firstPoint.segmentType is not None and lastPoint.segmentType is not None: if firstPoint.coordinates == lastPoint.coordinates: if (firstPoint.segmentType in ["line", "move"]): del self._points[0] else: raise AssertionEr...
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.counterClockwiseFlat outputFlat = [] for segment in self.segments: # XX...
True else: inputStart = inputFlat[0] if inputStart in outputFlat: # there should be only one occurance of the point # but handle it just in case if outputFlat.count(inputStart) > 1: startIndexes = [index for index, point in enumerate(outputFlat) if point == inputStart] else: startIndexes = [outputFlat.index(inputStart)...
inputFlat == test: haveMatch = True break if haveMatch: # clear out the flat points self.segments = [] # replace with the appropriate points from the input if self.clockwise: inputSegments = inputContour.clockwiseSegments else: inputSegments = inputContour.counterClockwiseSegments for inputSegment in inputSegments: sel...
the direction of the final contour self.clockwise = inputContour.clockwise return True return False
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_manager': # pragma no branch return True except Attribute...
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)
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(inferred, '_proxied', None) if _is_custom_qs_manager(...
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.query(cls.model).filter(cls.model.group_id == group_id) query = query.filter(...
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) print "%s [Bot: %s] listening on %s:%s...
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
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_file): print "Daemon killed" else: prin...
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) self.spawn(self.client.start)
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(IRCNamespace, self).disconnect(*args, **kwargs)
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(): interval = default_interval else: interval *= 2 sleep(interval)
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 request]) try: if self.bot is None: raise NotImplementedEr...
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.path.dirname(__file__), path.lstrip("/")) try: with open(path, "r") as f: content = f...
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(template_dir, "base.html"), "r") as f: base = f.read() with op...
"{% endblock %}": "", "{% load gnotty_tags %}": "", "{% extends \"gnotty/base.html\" %}": "", "{% url gnotty_chat %}": "/", "{% gnotty_nav %}": "", "{% templatetag openvariable %}": "{{", "{% templatetag closevariable %}": "}}", } for k, v in replace.items(): base = base.replace(k, v) for k, v in settings.items(): base...
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: from django.conf import settings as django_settings from django.cont...
cookie[cookie_name].value session = Session.objects.get(session_key=session_key) user_id = session.get_decoded().get(SESSION_KEY) user = User.objects.get(id=user_id) except (ImportError, KeyError, ObjectDoesNotExist): return False return True
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'].objects.filter(message="leaves").update(join_...
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 one of passed permission names perm_names - list...
objects returned for group permissions, this might cause performance issues for big groups """ db_session = get_db_session(db_session) # fetch groups and their permissions (possibly with users belonging # to group if needed) query = db_session.query( models_proxy.GroupResourcePermission.perm_name, models_proxy.User, mo...
None) # noqa else: query = query.join( models_proxy.UserGroup, models_proxy.UserGroup.group_id == models_proxy.GroupResourcePermission.group_id, ) query = query.outerjoin( models_proxy.User, models_proxy.User.id == models_proxy.UserGroup.user_id ) if resource_ids: query = query.filter( models_proxy.GroupResourcePermiss...
will fetch users with direct resource permissions query2 = db_session.query( models_proxy.UserResourcePermission.perm_name, models_proxy.User, models_proxy.Group, sa.literal("user").label("type"), models_proxy.Resource, ) query2 = query2.join( models_proxy.User, models_proxy.User.id == models_proxy.UserResourcePermissi...
query2.filter( models_proxy.UserResourcePermission.perm_name.in_(perm_names) ) if resource_ids: query2 = query2.filter( models_proxy.UserResourcePermission.resource_id.in_(resource_ids) ) if resource_types: query2 = query2.filter(models_proxy.Resource.resource_type.in_(resource_types)) if user_ids: query2 = query2.filt...
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": acls.append(("group:%s" % perm.group.id, perm.perm_name)) return acl...
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 perm.type == "group": acls.append((Allow, "group:%s" % perm...
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) return _chunk(self, f)
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)
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
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))
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): break yield e
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): if i == n: break yield e
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 return con
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
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])
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 'objects', we check for it here attrname = getattr(las...
return False
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: :return: """ db_session = get_db_session(db_session) ...
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)
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 event names to lists of ...
event occurs. """ def wrapper(func): for i, arg in args: kwargs[i] = arg func.event = Event(event, kwargs) return func return wrapper
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 argument * finally tries to ...
session: :param obj: :return: """ # try to read the session from instance from ziggurat_foundations import models if obj: return sa.orm.session.object_session(obj) # try passed session elif session: return session # try global pylons-like session then elif models.DBSession: return models.DBSession raise ZigguratSession...
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 returned by this function :param include_ke...
d = {} exclude_keys_list = exclude_keys or [] include_keys_list = include_keys or [] for k in self._get_keys(): if k not in exclude_keys_list and ( k in include_keys_list or not include_keys ): d[k] = getattr(self, k) return d
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
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 from model that should not be updated by thi...
exclude_keys_list = exclude_keys or [] include_keys_list = include_keys or [] for k in self._get_keys(): if ( k in appstruct and k not in exclude_keys_list and (k in include_keys_list or not include_keys) ): setattr(self, k, appstruct[k])
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 from model that should not be updated by thi...
= exclude_keys or [] include_keys_list = include_keys or [] for k in self._get_keys(): if ( hasattr(instance, k) and k not in exclude_keys_list and (k in include_keys_list or not include_keys) ): setattr(self, k, getattr(instance, k))
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)
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
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
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() logging.debug("read some raw data") result = self.get_raw_data(6) if result is False: ra...
def _validate_measure_count(self, times): """ check if "times" is within the borders defined in the class :param times: "times" to check :type times: int """ if not self.min_measures <= times <= self.max_measures: raise ParameterValidationError( "{times} is not within the borders defined in the class".format( times=tim...
def _validate_gain_A_value(self, gain_A): """ validate a given value for gain_A :type gain_A: int :raises: ValueError """ if gain_A not in self._valid_gains_for_channel_A: raise ParameterValidationError("{gain_A} is not a valid gain".format(gain_A=gain_A))
def _ready(self): """ check if ther is som data is ready to get read. :return True if there is some date :rtype bool """ # if DOUT pin is low, data is ready for reading _is_ready = GPIO.input(self._dout) == 0 logging.debug("check data ready for reading: {result}".format( result="YES" if _is_ready is True else "NO" )) r...
def _set_channel_gain(self, num): """ Finish data transmission from HX711 by setting next required gain and channel Only called from the _read function. :param num: how often so do the set (1...3) :type num: int :return True on success :rtype bool """ if not 1 <= num <= 3: raise AttributeError( """"num" has to be in th...
in range(num): logging.debug("_set_channel_gain called") start_counter = time.perf_counter() # start timer now. GPIO.output(self._pd_sck, True) # set high GPIO.output(self._pd_sck, False) # set low end_counter = time.perf_counter() # stop timer time_elapsed = float(end_counter - start_counter) # check if HX711 did not ...
gain and channel took more than 60µs. ' 'Time elapsed: {:0.8f}'.format(time_elapsed) ) # hx711 has turned off. First few readings are inaccurate. # Despite this reading was ok and data can be used. result = self.get_raw_data(times=6) # set for the next reading. if result is False: raise GenericHX711Exception("channel w...
def _read(self, max_tries=40): """ - read the bit stream from HX711 and convert to an int value. - validates the acquired data :param max_tries: how often to try to get data :type max_tries: int :return raw data :rtype: int """ # start by setting the pd_sck to false GPIO.output(self._pd_sck, False) # init the counter r...
halt when maximum number of tires is reached while self._ready() is False: time.sleep(0.01) # sleep for 10 ms before next try ready_counter += 1 # increment counter # check loop count # and stop when defined maximum is reached if ready_counter >= max_tries: logging.debug('self._read() not ready after 40 trials\n') retu...
24 bits of data for i in range(24): # start timer start_counter = time.perf_counter() # request next bit from HX711 GPIO.output(self._pd_sck, True) GPIO.output(self._pd_sck, False) # stop timer end_counter = time.perf_counter() time_elapsed = float(end_counter - start_counter) # check if the hx 711 did not turn off: # ...
if time_elapsed >= 0.00006: logging.debug('Reading data took longer than 60µs. Time elapsed: {:0.8f}'.format(time_elapsed)) return False # Shift the bits as they come to data_in variable. # Left shift by one bit then bitwise OR with the new bit. data_in = (data_in << 1) | GPIO.input(self._dout) if self.channel == 'A' a...
== 64: self._set_channel_gain(num=3) # send three bits else: self._set_channel_gain(num=2) # send two bits logging.debug('Binary value as it has come: ' + str(bin(data_in))) # check if data is valid # 0x800000 is the lowest # 0x7fffff is the highest possible value from HX711 if data_in == 0x7fffff or data_in == 0x80000...
signed_data = 0 if (data_in & 0x800000): # 0b1000 0000 0000 0000 0000 0000 check if the sign bit is 1. Negative number. signed_data = -((data_in ^ 0xffffff) + 1) # convert from 2's complement to int else: # else do not do anything the value is positive number signed_data = data_in logging.debug('Converted 2\'s compleme...
def get_raw_data(self, times=5): """ do some readings and aggregate them using the defined statistics function :param times: how many measures to aggregate :type times: int :return: the aggregate of the measured values :rtype float """ self._validate_measure_count(times) data_list = [] while len(data_list) < times: dat...
def from_resource_deeper( self, resource_id=None, limit_depth=1000000, db_session=None, *args, **kwargs ): """ This returns you subtree of ordered objects relative to the start resource_id (currently only implemented in postgresql) :param resource_id: :param limit_depth: :param db_session: :return: """ return self.serv...
def delete_branch(self, resource_id=None, db_session=None, *args, **kwargs): """ This deletes whole branch with children starting from resource_id :param resource_id: :param db_session: :return: """ return self.service.delete_branch( resource_id=resource_id, db_session=db_session, *args, **kwargs )
def from_parent_deeper( self, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs ): """ This returns you subtree of ordered objects relative to the start parent_id (currently only implemented in postgresql) :param resource_id: :param limit_depth: :param db_session: :return: """ return self.service.fr...
def build_subtree_strut(self, result, *args, **kwargs): """ Returns a dictionary in form of {node:Resource, children:{node_id: Resource}} :param result: :return: """ return self.service.build_subtree_strut(result=result, *args, **kwargs)
def path_upper( self, object_id, limit_depth=1000000, db_session=None, *args, **kwargs ): """ This returns you path to root node starting from object_id currently only for postgresql :param object_id: :param limit_depth: :param db_session: :return: """ return self.service.path_upper( object_id=object_id, limit_depth=li...
def move_to_position( self, resource_id, to_position, new_parent_id=noop, db_session=None, *args, **kwargs ): """ Moves node to new location in the tree :param resource_id: resource to move :param to_position: new position :param new_parent_id: new parent id :param db_session: :return: """ return self.service.move_to_p...
def shift_ordering_down( self, parent_id, position, db_session=None, *args, **kwargs ): """ Shifts ordering to "close gaps" after node deletion or being moved to another branch, begins the shift from given position :param parent_id: :param position: :param db_session: :return: """ return self.service.shift_ordering_dow...
def shift_ordering_up(self, parent_id, position, db_session=None, *args, **kwargs): """ Shifts ordering to "open a gap" for node insertion, begins the shift from given position :param parent_id: :param position: :param db_session: :return: """ return self.service.shift_ordering_up( parent_id=parent_id, position=positio...
def set_position(self, resource_id, to_position, db_session=None, *args, **kwargs): """ Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_session=None): """ return self.service.set_position...
def check_node_parent( self, resource_id, new_parent_id, db_session=None, *args, **kwargs ): """ Checks if parent destination is valid for node :param resource_id: :param new_parent_id: :param db_session: :return: """ return self.service.check_node_parent( resource_id=resource_id, new_parent_id=new_parent_id, db_sessio...
def count_children(self, resource_id, db_session=None, *args, **kwargs): """ Counts children of resource node :param resource_id: :param db_session: :return: """ return self.service.count_children( resource_id=resource_id, db_session=db_session, *args, **kwargs )
def check_node_position( self, parent_id, position, on_same_branch, db_session=None, *args, **kwargs ): """ Checks if node position for given parent is valid, raises exception if this is not the case :param parent_id: :param position: :param on_same_branch: indicates that we are checking same branch :param db_session: ...
def flatten_list(l: List[list]) -> list: """ takes a list of lists, l and returns a flat list """ return [v for inner_l in l for v in inner_l]