class Activity(BehavioralFlowNode, EventHandler): def __init__(self, definition): super(Activity, self).__init__(definition) self.assigned_to = PersistentList() def assigne_to(self, users): if not isinstance(users, (list, tuple)): users = [users] users = [u for u in users if not(u in self.assigned_to)] self.assigned_to.extend(users) def unassigne(self, users): if not isinstance(users, (list, tuple)): users = [users] users = [u for u in users if (u in self.assigned_to)] for user in users: self.assigned_to.remove(user) def set_assignment(self, users=None): self.assigned_to = PersistentList() if users is not None: self.assigne_to(users)
class OrderedContainer(Container): """A Grok container that remembers the order of its items. This straightforward extension of the basic `grok.Container` remembers the order in which items have been inserted, so that `keys()`, `values()`, `items()`, and iteration across the container can all return the items in the order they were inserted. The only way of changing the order is to call the `updateOrder()` method. """ implements(interfaces.IOrderedContainer) def __init__(self): super(OrderedContainer, self).__init__() self._order = PersistentList() def keys(self): # Return a copy of the list to prevent accidental modifications. return self._order[:] def __iter__(self): return iter(self.keys()) def values(self): return (self[key] for key in self._order) def items(self): return ((key, self[key]) for key in self._order) def __setitem__(self, key, object): foo = self.has_key(key) # Then do whatever containers normally do. super(OrderedContainer, self).__setitem__(key, object) if not foo: self._order.append(key) def __delitem__(self, key): # First do whatever containers normally do. super(OrderedContainer, self).__delitem__(key) self._order.remove(key) def updateOrder(self, order): """Impose a new order on the items in this container. Items in this container are, by default, returned in the order in which they were inserted. To change the order, provide an argument to this method that is a sequence containing every key already in the container, but in a new order. """ if set(order) != set(self._order): raise ValueError("Incompatible key set.") self._order = PersistentList() self._order.extend(order) notifyContainerModified(self)
class OrderedBTreeContainer(BTreeContainer): def __init__(self): super(OrderedBTreeContainer, self).__init__() self._order = PersistentList() def keys(self): return self._order[:] def values(self): return (self[key] for key in self._order) def items(self): return ((key, self[key]) for key in self._order) def __setitem__(self, key, object): exists = key in self if not exists: self._order.append(key) try: super(OrderedBTreeContainer, self).__setitem__(key, object) except Exception as e: if not exists: self._order.remove(key) raise e return key def __delitem__(self, key): super(OrderedBTreeContainer, self).__delitem__(key) self._order.remove(key) def updateOrder(self, order): """Impose a new order on the items in this container. Items in this container are, by default, returned in the order in which they were inserted. To change the order, provide an argument to this method that is a sequence containing every key already in the container, but in a new order. """ if set(order) != set(self._order): raise ValueError("Incompatible key set.") self._order = PersistentList() self._order.extend(order) notifyContainerModified(self)
class User(Persistent): def __acl__(self): return [] def __init__(self, username, roles): """ Create a User entry """ super(User, self).__init__() self.username = username self.set_roles(roles) def set_roles(self, roles): self.roles = PersistentList() self.roles.extend(roles) def as_dict(self): return { 'username': self.username, 'roles': [dict(role=role, active=role in self.roles) for role in ROLES] }
class BusinessAction(Wizard, LockableElement, Persistent): node_definition = NotImplemented context = NotImplemented processs_relation_id = NotImplemented actionType = NotImplemented behavior_id = '' #validation relation_validation = NotImplemented roles_validation = NotImplemented processsecurity_validation = NotImplemented state_validation = NotImplemented #style information access_controled = False def __init__(self, workitem, **kwargs): super(BusinessAction, self).__init__(**kwargs) self.workitem = workitem self.isexecuted = False self.behavior_id = self.behavior_id or self.node_id self.sub_process = None self.local_assigned_to = PersistentList() if self.title == '' or self.title is NotImplemented: self.title = self.node.title if self.description == '' or self.description is NotImplemented: self.description = self.node.description @classmethod def get_instance(cls, context, request, **kw): action_uid = request.params.get('action_uid', None) source_action = None if action_uid: source_action = get_obj(int(action_uid)) if source_action and \ source_action._class_ is cls and \ source_action.validate(context, request): return source_action instances = getBusinessAction(context, request, cls.node_definition.process.id, cls.node_definition.__name__, action_type=cls, validate=kw.get('validate', True)) if instances is None: return None isstart = request.params.get('isstart', False) if isstart: for inst in instances: if inst.isstart: return inst return instances[0] @classmethod def get_allinstances(cls, context, request, **kw): instance = getBusinessAction(context, request, cls.node_definition.process.id, cls.node_definition.__name__) return instance @classmethod def get_validator(cls, **kw): return getBusinessActionValidator(cls) @property def potential_contexts_ids(self): try: contexts = self.process.execution_context.involved_entities( self.processs_relation_id) result = [] for context in contexts: try: result.append(str(get_oid(context))) except Exception: pass return result except Exception: return ['any'] @property def actions(self): allactions = getAllBusinessAction(self) return [ActionCall(a, self) for a in allactions] @property def process(self): return self.workitem.process @property def node(self): return self.workitem.node @property def process_id(self): return self.workitem.process_id @property def definition(self): if self.node_definition is not NotImplemented: return self.node_definition return self.node.definition if isinstance(self.node, BPMNElement)\ else self.node @property def node_id(self): return self.definition.__name__ @property def groups(self): return self.definition.groups @property def view_name(self): return self.action_view.name @property def isautomatic(self): return self.actionType is ActionType.automatic @property def issystem(self): return self.actionType is ActionType.system @property def isstart(self): return isinstance(self.workitem, StartWorkItem) @property def informations(self): # pragma: no cover if self.process is not None: return 'Description: ' + \ self.description + \ '\n Process: '+self.process.title else: return 'Description: ' + \ self.description + \ '\n Process: '+self.node.process.id @property def action_view(self): return DEFAULTMAPPING_ACTIONS_VIEWS.get(self.__class__, None) @property def assigned_to(self): if getattr(self, 'local_assigned_to', []): return self.local_assigned_to return getattr(self.node, 'assigned_to', []) def get_potential_context(self, request=None): if request is None: request = get_current_request() entities = [] try: entities = [ self.process.execution_context.involved_entity( self.processs_relation_id) ] except Exception: try: entities = self.process.execution_context.involved_collection( self.processs_relation_id) except Exception: entities = find_entities((self.context, )) for entity in entities: try: if entity: self.validate(entity, request) return entity except ValidationError: continue return None def url(self, obj): query = {} try: actionuid = get_oid(self) query = {'action_uid': actionuid} except AttributeError: query = {'isstart': 'True'} return get_current_request().resource_url(obj, '@@' + self.view_name, query=query) def assigne_to(self, users): if not isinstance(users, (list, tuple)): users = [users] users = [u for u in users if u not in self.local_assigned_to] self.local_assigned_to.extend(users) def unassigne(self, users): if not isinstance(users, (list, tuple)): users = [users] users = [u for u in users if u in self.local_assigned_to] for user in users: self.local_assigned_to.remove(user) def set_assignment(self, users=None): self.local_assigned_to = PersistentList() if users is not None: self.assigne_to(users) def validate(self, context, request, **kw): is_valid, message = self.validate_mini(context, request, **kw) if not is_valid: raise ValidationError(msg=message) return True def validate_mini(self, context, request, **kw): return validate_action(self, context, request, **kw) def before_execution(self, context, request, **kw): self.lock(request) self.workitem.lock(request) def _consume_decision(self): if isinstance(self.workitem, UserDecision): self.workitem.consume() def start(self, context, request, appstruct, **kw): return {} def execute(self, context, request, appstruct, **kw): self._consume_decision() if self.isstart: return if isinstance(self.node, SubProcess) and not self.sub_process: self.sub_process = self.node._start_subprocess(self) if self.sub_process: if ITEM_INDEX in kw: self.sub_process.execution_context.add_involved_entity( ITEM_INDEX, kw[ITEM_INDEX]) self.process.execution_context.add_sub_execution_context( self.sub_process.execution_context) def finish_execution(self, context, request, **kw): self.after_execution(context, request, **kw) def after_execution(self, context, request, **kw): self.unlock(request) self.workitem.unlock(request) # TODO self.workitem is a real workitem? if self.isexecuted: self.workitem.node.finish_behavior(self.workitem) def redirect(self, context, request, **kw): return kw def cancel_execution(self, context, request, **kw): self.unlock(request) self.workitem.unlock(request) def reindex(self): event = ObjectModified(self) registry = get_current_registry() registry.subscribers((event, self), None)
def checkTheWorld(self): # Test constructors u = PersistentList() u0 = PersistentList(l0) u1 = PersistentList(l1) u2 = PersistentList(l2) uu = PersistentList(u) uu0 = PersistentList(u0) uu1 = PersistentList(u1) uu2 = PersistentList(u2) v = PersistentList(tuple(u)) class OtherList: def __init__(self, initlist): self.__data = initlist def __len__(self): return len(self.__data) def __getitem__(self, i): return self.__data[i] v0 = PersistentList(OtherList(u0)) vv = PersistentList("this is also a sequence") # Test __repr__ eq = self.assertEqual eq(str(u0), str(l0), "str(u0) == str(l0)") eq(repr(u1), repr(l1), "repr(u1) == repr(l1)") eq(repr(u2), repr(l2), "repr(u2) == repr(l2)") # Test __cmp__ and __len__ # Py3: No cmp() or __cmp__ anymore. if PY2: def mycmp(a, b): r = cmp(a, b) if r < 0: return -1 if r > 0: return 1 return r all = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2] for a in all: for b in all: eq(mycmp(a, b), mycmp(len(a), len(b)), "mycmp(a, b) == mycmp(len(a), len(b))") # Test __getitem__ for i in range(len(u2)): eq(u2[i], i, "u2[i] == i") # Test __setitem__ uu2[0] = 0 uu2[1] = 100 try: uu2[2] = 200 except IndexError: pass else: self.fail("uu2[2] shouldn't be assignable") # Test __delitem__ del uu2[1] del uu2[0] try: del uu2[0] except IndexError: pass else: self.fail("uu2[0] shouldn't be deletable") # Test __getslice__ for i in range(-3, 4): eq(u2[:i], l2[:i], "u2[:i] == l2[:i]") eq(u2[i:], l2[i:], "u2[i:] == l2[i:]") for j in range(-3, 4): eq(u2[i:j], l2[i:j], "u2[i:j] == l2[i:j]") # Test __setslice__ for i in range(-3, 4): u2[:i] = l2[:i] eq(u2, l2, "u2 == l2") u2[i:] = l2[i:] eq(u2, l2, "u2 == l2") for j in range(-3, 4): u2[i:j] = l2[i:j] eq(u2, l2, "u2 == l2") uu2 = u2[:] uu2[:0] = [-2, -1] eq(uu2, [-2, -1, 0, 1], "uu2 == [-2, -1, 0, 1]") uu2[0:] = [] eq(uu2, [], "uu2 == []") # Test __contains__ for i in u2: self.assertTrue(i in u2, "i in u2") for i in min(u2) - 1, max(u2) + 1: self.assertTrue(i not in u2, "i not in u2") # Test __delslice__ uu2 = u2[:] del uu2[1:2] del uu2[0:1] eq(uu2, [], "uu2 == []") uu2 = u2[:] del uu2[1:] del uu2[:1] eq(uu2, [], "uu2 == []") # Test __add__, __radd__, __mul__ and __rmul__ #self.assertTrue(u1 + [] == [] + u1 == u1, "u1 + [] == [] + u1 == u1") self.assertTrue(u1 + [1] == u2, "u1 + [1] == u2") #self.assertTrue([-1] + u1 == [-1, 0], "[-1] + u1 == [-1, 0]") self.assertTrue(u2 == u2 * 1 == 1 * u2, "u2 == u2*1 == 1*u2") self.assertTrue(u2 + u2 == u2 * 2 == 2 * u2, "u2+u2 == u2*2 == 2*u2") self.assertTrue(u2 + u2 + u2 == u2 * 3 == 3 * u2, "u2+u2+u2 == u2*3 == 3*u2") # Test append u = u1[:] u.append(1) eq(u, u2, "u == u2") # Test insert u = u2[:] u.insert(0, -1) eq(u, [-1, 0, 1], "u == [-1, 0, 1]") # Test pop u = PersistentList([0, -1, 1]) u.pop() eq(u, [0, -1], "u == [0, -1]") u.pop(0) eq(u, [-1], "u == [-1]") # Test remove u = u2[:] u.remove(1) eq(u, u1, "u == u1") # Test count u = u2 * 3 eq(u.count(0), 3, "u.count(0) == 3") eq(u.count(1), 3, "u.count(1) == 3") eq(u.count(2), 0, "u.count(2) == 0") # Test index eq(u2.index(0), 0, "u2.index(0) == 0") eq(u2.index(1), 1, "u2.index(1) == 1") try: u2.index(2) except ValueError: pass else: self.fail("expected ValueError") # Test reverse u = u2[:] u.reverse() eq(u, [1, 0], "u == [1, 0]") u.reverse() eq(u, u2, "u == u2") # Test sort u = PersistentList([1, 0]) u.sort() eq(u, u2, "u == u2") # Test extend u = u1[:] u.extend(u2) eq(u, u1 + u2, "u == u1 + u2")
class BusinessAction(Wizard, LockableElement, Persistent): node_definition = NotImplemented context = NotImplemented processs_relation_id = NotImplemented actionType = NotImplemented behavior_id = '' #validation relation_validation = NotImplemented roles_validation = NotImplemented processsecurity_validation = NotImplemented state_validation = NotImplemented #style information access_controled = False def __init__(self, workitem, **kwargs): super(BusinessAction, self).__init__(**kwargs) self.workitem = workitem self.isexecuted = False self.behavior_id = self.behavior_id or self.node_id self.sub_process = None self.local_assigned_to = PersistentList() if self.title == '' or self.title is NotImplemented: self.title = self.node.title if self.description == '' or self.description is NotImplemented: self.description = self.node.description @classmethod def get_instance(cls, context, request, **kw): action_uid = request.params.get('action_uid', None) source_action = None if action_uid: source_action = get_obj(int(action_uid)) if source_action and \ source_action._class_ is cls and \ source_action.validate(context, request): return source_action instances = getBusinessAction(context, request, cls.node_definition.process.id, cls.node_definition.__name__, action_type=cls, validate=kw.get('validate', True)) if instances is None: return None isstart = request.params.get('isstart', False) if isstart: for inst in instances: if inst.isstart: return inst return instances[0] @classmethod def get_allinstances(cls, context, request, **kw): instance = getBusinessAction(context, request, cls.node_definition.process.id, cls.node_definition.__name__) return instance @classmethod def get_validator(cls, **kw): return getBusinessActionValidator(cls) @property def potential_contexts_ids(self): try: contexts = self.process.execution_context.involved_entities( self.processs_relation_id) result = [] for context in contexts: try: result.append(str(get_oid(context))) except Exception: pass return result except Exception: return ['any'] @property def actions(self): allactions = getAllBusinessAction(self) return [ActionCall(a, self) for a in allactions] @property def process(self): return self.workitem.process @property def node(self): return self.workitem.node @property def process_id(self): return self.workitem.process_id @property def definition(self): if self.node_definition is not NotImplemented: return self.node_definition return self.node.definition if isinstance(self.node, BPMNElement)\ else self.node @property def node_id(self): return self.definition.__name__ @property def groups(self): return self.definition.groups @property def view_name(self): return self.action_view.name @property def isautomatic(self): return self.actionType is ActionType.automatic @property def issystem(self): return self.actionType is ActionType.system @property def isstart(self): return isinstance(self.workitem, StartWorkItem) @property def informations(self):# pragma: no cover if self.process is not None: return 'Description: ' + \ self.description + \ '\n Process: '+self.process.title else: return 'Description: ' + \ self.description + \ '\n Process: '+self.node.process.id @property def action_view(self): return DEFAULTMAPPING_ACTIONS_VIEWS.get(self.__class__, None) @property def assigned_to(self): if getattr(self, 'local_assigned_to', []): return self.local_assigned_to return getattr(self.node, 'assigned_to', []) def get_potential_context(self, request=None): if request is None: request = get_current_request() entities = [] try: entities = [self.process.execution_context.involved_entity( self.processs_relation_id)] except Exception: try: entities = self.process.execution_context.involved_collection( self.processs_relation_id) except Exception: entities = find_entities((self.context,)) for entity in entities: try: if entity: self.validate(entity, request) return entity except ValidationError: continue return None def url(self, obj): query = {} try: actionuid = get_oid(self) query = {'action_uid': actionuid} except AttributeError: query = {'isstart': 'True'} return get_current_request().resource_url( obj, '@@'+self.view_name, query=query) def assigne_to(self, users): if not isinstance(users, (list, tuple)): users = [users] users = [u for u in users if u not in self.local_assigned_to] self.local_assigned_to.extend(users) def unassigne(self, users): if not isinstance(users, (list, tuple)): users = [users] users = [u for u in users if u in self.local_assigned_to] for user in users: self.local_assigned_to.remove(user) def set_assignment(self, users=None): self.local_assigned_to = PersistentList() if users is not None: self.assigne_to(users) def validate(self, context, request, **kw): is_valid, message = self.validate_mini(context, request, **kw) if not is_valid: raise ValidationError(msg=message) return True def validate_mini(self, context, request, **kw): return validate_action(self, context, request, **kw) def before_execution(self, context, request, **kw): self.lock(request) self.workitem.lock(request) def _consume_decision(self): if isinstance(self.workitem, UserDecision): self.workitem.consume() def start(self, context, request, appstruct, **kw): return {} def execute(self, context, request, appstruct, **kw): self._consume_decision() if self.isstart: return if isinstance(self.node, SubProcess) and not self.sub_process: self.sub_process = self.node._start_subprocess(self) if self.sub_process: if ITEM_INDEX in kw: self.sub_process.execution_context.add_involved_entity( ITEM_INDEX, kw[ITEM_INDEX]) self.process.execution_context.add_sub_execution_context( self.sub_process.execution_context) def finish_execution(self, context, request, **kw): self.after_execution(context, request, **kw) def after_execution(self, context, request, **kw): self.unlock(request) self.workitem.unlock(request) # TODO self.workitem is a real workitem? if self.isexecuted: self.workitem.node.finish_behavior(self.workitem) def redirect(self, context, request, **kw): return kw def cancel_execution(self, context, request, **kw): self.unlock(request) self.workitem.unlock(request) def reindex(self): event = ObjectModified(self) registry = get_current_registry() registry.subscribers((event, self), None)
class Igrac(Persistent): def __init__(self, nadimak, jeLiRacunalo, igra): self.nadimak = nadimak self.karte = PersistentList() self.igra = igra self.jeLiRacunalo = jeLiRacunalo self.zastavice = PersistentDict() self.zastavice.update({ 'uzmiKarte': 0, 'provjeriZvanja': 0, 'hocuLiZvati': 0, 'baciKartu': 0 }) self.igra.onSudjeluj(self) transaction.commit() def uzmiKarte(self): global vidljiveKarteSprites global karteSpritesList self.karte.extend(self.igra.onDajKarte()) self.karte = self.sortirajKarte(self.karte) for i in range(len(self.karte)): kartaSprite = next((x for x in karteSpritesList if x.karta.slika == self.karte[i].slika), None) kartaSprite.pozicioniraj( (1000 - (100 * len(self.karte))) / 2 + 100 * i, 566) kartaSprite.layer = i kartaSprite.prikazi() vidljiveKarteSprites.add(kartaSprite) def sortirajKarte(self, karte): return sorted(karte, key=lambda karta: (karta.boja, karta.poredak), reverse=False) def provjeriZvanja(self): self.igra.onPrijaviZvanje(self, self.karte) def hocuLiZvati(self, moramLiZvati): if self.jeLiRacunalo == True: jacinaAduta = {'Herc': 0, 'Bundeva': 0, 'Zelena': 0, 'Zir': 0} for karta in self.karte: if karta.boja == 'Herc': jacinaAduta['Herc'] += karta.vrijednostAduta elif karta.boja == 'Bundeva': jacinaAduta['Bundeva'] += karta.vrijednostAduta elif karta.boja == 'Zelena': jacinaAduta['Zelena'] += karta.vrijednostAduta elif karta.boja == 'Zir': jacinaAduta['Zir'] += karta.vrijednostAduta najjacaBoja = max(jacinaAduta, key=jacinaAduta.get) if jacinaAduta[najjacaBoja] > 30 or moramLiZvati: print self.nadimak + ": zovem " + najjacaBoja self.igra.onOdaberiAdut(najjacaBoja) else: print self.nadimak + ": dalje!" self.igra.onOdaberiAdut(False) return False def baciKartu(self, odabranaKarta=None): if (self.jeLiRacunalo == True): for karta in self.karte: if self.igra.onJeLiPoPravilima(self.karte, karta) == True: time.sleep(.01) print self.nadimak + ": ", karta self.karte.remove(karta) self.igra.onBaciKartu(karta) else: continue else: if self.igra.onJeLiPoPravilima(self.karte, odabranaKarta) == True: self.zastavice["baciKartu"] = 0 self.igra.onBaciKartu( self.karte.pop(self.karte.index(odabranaKarta))) return True else: return False
def podijeli(self): karteIgraca = PersistentList() karteIgraca.extend(self.karte[:8]) del self.karte[:8] return karteIgraca
def checkTheWorld(self): # Test constructors u = PersistentList() u0 = PersistentList(l0) u1 = PersistentList(l1) u2 = PersistentList(l2) uu = PersistentList(u) uu0 = PersistentList(u0) uu1 = PersistentList(u1) uu2 = PersistentList(u2) v = PersistentList(tuple(u)) class OtherList(object): def __init__(self, initlist): self.__data = initlist def __len__(self): return len(self.__data) def __getitem__(self, i): return self.__data[i] v0 = PersistentList(OtherList(u0)) vv = PersistentList("this is also a sequence") # Test __repr__ eq = self.assertEqual eq(str(u0), str(l0), "str(u0) == str(l0)") eq(repr(u1), repr(l1), "repr(u1) == repr(l1)") eq(repr(u2), repr(l2), "repr(u2) == repr(l2)") # Test __cmp__ and __len__ # Py3: No cmp() or __cmp__ anymore. if PY2: def mycmp(a, b): r = cmp(a, b) if r < 0: return -1 if r > 0: return 1 return r all = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2] for a in all: for b in all: eq(mycmp(a, b), mycmp(len(a), len(b)), "mycmp(a, b) == mycmp(len(a), len(b))") # Test __getitem__ for i in range(len(u2)): eq(u2[i], i, "u2[i] == i") # Test __setitem__ uu2[0] = 0 uu2[1] = 100 try: uu2[2] = 200 except IndexError: pass else: self.fail("uu2[2] shouldn't be assignable") # Test __delitem__ del uu2[1] del uu2[0] try: del uu2[0] except IndexError: pass else: self.fail("uu2[0] shouldn't be deletable") # Test __getslice__ for i in range(-3, 4): eq(u2[:i], l2[:i], "u2[:i] == l2[:i]") eq(u2[i:], l2[i:], "u2[i:] == l2[i:]") for j in range(-3, 4): eq(u2[i:j], l2[i:j], "u2[i:j] == l2[i:j]") # Test __setslice__ for i in range(-3, 4): u2[:i] = l2[:i] eq(u2, l2, "u2 == l2") u2[i:] = l2[i:] eq(u2, l2, "u2 == l2") for j in range(-3, 4): u2[i:j] = l2[i:j] eq(u2, l2, "u2 == l2") uu2 = u2[:] uu2[:0] = [-2, -1] eq(uu2, [-2, -1, 0, 1], "uu2 == [-2, -1, 0, 1]") uu2[0:] = [] eq(uu2, [], "uu2 == []") # Test __contains__ for i in u2: self.assertTrue(i in u2, "i in u2") for i in min(u2)-1, max(u2)+1: self.assertTrue(i not in u2, "i not in u2") # Test __delslice__ uu2 = u2[:] del uu2[1:2] del uu2[0:1] eq(uu2, [], "uu2 == []") uu2 = u2[:] del uu2[1:] del uu2[:1] eq(uu2, [], "uu2 == []") # Test __add__, __radd__, __mul__ and __rmul__ #self.assertTrue(u1 + [] == [] + u1 == u1, "u1 + [] == [] + u1 == u1") self.assertTrue(u1 + [1] == u2, "u1 + [1] == u2") #self.assertTrue([-1] + u1 == [-1, 0], "[-1] + u1 == [-1, 0]") self.assertTrue(u2 == u2*1 == 1*u2, "u2 == u2*1 == 1*u2") self.assertTrue(u2+u2 == u2*2 == 2*u2, "u2+u2 == u2*2 == 2*u2") self.assertTrue(u2+u2+u2 == u2*3 == 3*u2, "u2+u2+u2 == u2*3 == 3*u2") # Test append u = u1[:] u.append(1) eq(u, u2, "u == u2") # Test insert u = u2[:] u.insert(0, -1) eq(u, [-1, 0, 1], "u == [-1, 0, 1]") # Test pop u = PersistentList([0, -1, 1]) u.pop() eq(u, [0, -1], "u == [0, -1]") u.pop(0) eq(u, [-1], "u == [-1]") # Test remove u = u2[:] u.remove(1) eq(u, u1, "u == u1") # Test count u = u2*3 eq(u.count(0), 3, "u.count(0) == 3") eq(u.count(1), 3, "u.count(1) == 3") eq(u.count(2), 0, "u.count(2) == 0") # Test index eq(u2.index(0), 0, "u2.index(0) == 0") eq(u2.index(1), 1, "u2.index(1) == 1") try: u2.index(2) except ValueError: pass else: self.fail("expected ValueError") # Test reverse u = u2[:] u.reverse() eq(u, [1, 0], "u == [1, 0]") u.reverse() eq(u, u2, "u == u2") # Test sort u = PersistentList([1, 0]) u.sort() eq(u, u2, "u == u2") # Test extend u = u1[:] u.extend(u2) eq(u, u1 + u2, "u == u1 + u2")
class PCardList(Persistent): def __init__(self, cards=()): if type(cards) is PCardList: self.cards = PersistentList(cards.cards) elif type(cards) is list: self.cards = PersistentList(cards) else: self.cards = PersistentList() self.name = '' def __getitem__(self, item): return self.cards.__getitem__(item) def __setitem__(self, key, value): self.cards.__setitem__(key, value) def __iter__(self): return iter(self.cards) def __str__(self): return str(self.cards) def __repr__(self): return repr(self.cards) def __add__(self, other): if type(other) is PCardList: return PCardList(self.cards + other.cards) elif type(other) is list: return PCardList(self.cards + other) def __len__(self): return self.cards.__len__() def append(self, card): self.cards.append(card) return self def extend(self, other): if type(other) is PCardList: self.cards.extend(other.cards) elif type(other) is list: self.cards.extend(other) return self def get(self, invert=False, matchExactly=True, **kwargs): qResult = set() for (key, val) in kwargs.items(): if invert: if matchExactly: result = [ card for card in self if not getattr(card, key) == val ] else: result = [ card for card in self if getattr(card, key) and not set(val).issubset(set(getattr(card, key, []))) ] else: if matchExactly: result = [ card for card in self if getattr(card, key) == val ] else: result = [ card for card in self if getattr(card, key) and set(val).issubset(set(getattr(card, key, []))) ] qResult.update(result) return PCardList(list(qResult)) def getRandomSample(self, num, duplicates=False): if duplicates: return PCardList([random.choice(self.cards) for _ in range(num)]) else: try: return random.sample(self.cards, num) except ValueError: return PCardList( [random.choice(self.cards) for _ in range(num)]) def getRandomPack(self, numOfCards, numOfRares=1, numOfUncommons=3): if not numOfRares: numOfRares = int(round(numOfCards / 14.0)) if not numOfUncommons: numOfUncommons = 3 * int(round(numOfCards / 14.0)) numOfCommons = numOfCards - numOfRares - numOfUncommons commons = self.get(rarity='Common').getRandomSample(numOfCommons) uncommons = self.get(rarity='Uncommon').getRandomSample(numOfUncommons) rares = PCardList() if self.get(rarity='Mythic Rare'): for _ in range(numOfRares): if random.randint(0, 7) == 0: rares.extend( self.get(rarity='Mythic Rare').getRandomSample(1)) else: rares.extend(self.get(rarity='Rare').getRandomSample(1)) else: rares.extend(self.get(rarity='Rare').getRandomSample(numOfRares)) return PCardList().extend(commons).extend(uncommons).extend(rares) def getStats(self): totManacosts = '' totC = 0 for c in self.cards: if c.mana_cost: totManacosts += c.mana_cost digits = ''.join(filter(lambda x: x.isdigit(), c.mana_cost)) if digits: totC += int(digits) creatures = sorted(self.get(types=['Creature'], matchExactly=False), key=lambda c: c.cmc or 0) nonCreatures = sorted(self.get(types=['Creature'], matchExactly=False, invert=True).get(types=['Land'], invert=True, matchExactly=False), key=lambda c: c.cmc or 0) lands = self.get(types=['Land'], matchExactly=False) nonLands = creatures + nonCreatures cardsByColors = dict((tuple(k), len(list(v))) for k, v in groupby( sorted(self, key=lambda card: card.colors or ['Colorless']), key=lambda card: card.colors or ['Colorless'])) cmc = dict( (k, len(list(v))) for k, v in groupby(nonLands, key=lambda card: card.cmc or 0)) types = dict((tuple(k), len(list(v))) for k, v in groupby( sorted(self.cards, key=lambda x: x.types or ['None']), key=lambda x: x.types or ['None'])) creatureCmc = dict( (k, len(list(v))) for k, v in groupby(creatures, key=lambda card: card.cmc or 0)) nonCreatureCmc = dict( (k, len(list(v))) for k, v in groupby(nonCreatures, key=lambda card: card.cmc or 0)) manaSymbols = { 'B': totManacosts.count('B'), 'R': totManacosts.count('R'), 'G': totManacosts.count('G'), 'U': totManacosts.count('U'), 'W': totManacosts.count('W'), 'C': totC } simpleTypes = { 'Creature': len(creatures), 'Non-Creature': len(nonCreatures), 'Land': len(lands) } try: avgCmc = round( float(sum([cmc * num for (cmc, num) in cmc.items()])) / float(sum(cmc.values())), 1) except ZeroDivisionError: avgCmc = 0 return { 'colors': cardsByColors, 'cmc': cmc, 'types': types, 'nonCreatureCmc': nonCreatureCmc, 'creatureCmc': creatureCmc, 'manaSymbols': manaSymbols, 'simpleTypes': simpleTypes, 'avgCmc': avgCmc } def filterNonPlayableCards(self): return PCardList([ card for card in self.cards if card.isFrontSide() and card.layout not in [ 'token', 'plane', 'scheme', 'phenomenon', 'leveler', 'vanguard', 'Conspiracy' ] ]) def filterBasicLands(self): return PCardList([ card for card in self.cards if not card.supertypes or 'Basic' not in card.supertypes ]) def filterDuplicateNames(self): temp = set() return PCardList([ card for card in self.cards if card.name not in temp and (temp.add(card.name) or True) ]) def getPool(self): return self.filterBasicLands().filterDuplicateNames( ).filterNonPlayableCards() def toMwsStr(self): creatures = self.get(types=['Creature'], matchExactly=False) nonCreatures = sorted(self.get(types=['Creature'], matchExactly=False, invert=True).get(types=['Land'], invert=True, matchExactly=False), key=lambda c: c.name) lands = sorted(self.get(types=['Land'], matchExactly=False), key=lambda c: c.name) print(creatures) print(creatures.sorted(lambda c: c.id)) mwsStr = '// Deck file for Magic Workstation (http://www.magicworkstation.com)\n\n// Lands\n' for k, v in groupby(lands, key=lambda card: card.id): lst = list(v) card = lst[0] num = len(lst) mwsStr += '{} [{}] {}\n'.format(num, card.set, card.name) mwsStr += '\n// Creatures\n' for k, v in groupby(creatures, key=lambda card: card.id): card = list(v)[0] num = len(lst) mwsStr += '{} [{}] {}\n'.format(num, card.set, card.name) mwsStr += '\n// Non-Creatures\n' for k, v in groupby(nonCreatures, key=lambda card: card.id): lst = list(v) card = lst[0] num = len(lst) mwsStr += '{} [{}] {}\n'.format(num, card.set, card.name) return mwsStr def toJSON(self): return json.dumps({'cards': [card.__dict__ for card in self.cards]}, sort_keys=True, indent=4) def prettyPrint(self): for card in self.cards: print('{:40s} {:30s} {:25s} {:10s}'.format(str(card.name), str(card.types), str(card.mana_cost), str(card.rarity))) def sorted(self, func): return PCardList(sorted(self.cards, key=func))
class WikiPage(QonPersistent, Watchable, qon.karma.HasKarma, IHasBlog): persistenceVersion = 4 def __init__(self, wiki, name=''): Watchable.__init__(self) qon.karma.HasKarma.__init__(self) self.wiki = wiki self.outbound_references = None self.inbound_references = None self.name = clean_page_name(name) self.versions = PersistentList() self.blog = Blog(self) self.locked_by_user = None self.__cached_html = PersistentCache(self._update_html_cache) self.__cached_html2 = PersistentCache(self._update_html2_cache) self.new_revision(force_new=1) def upgradeToVersion4(self): self.inbound_references = None self.version_upgrade_done() def upgradeToVersion3(self): self.__cached_html2 = PersistentCache(self._update_html2_cache) self.version_upgrade_done() def upgradeToVersion2(self): self.__cached_html = PersistentCache(self._update_html_cache) self.version_upgrade_done() def upgradeToVersion1(self): self.blog.ihb = self self.version_upgrade_done() def __repr__(self): return '<%s object at 0x%x: %s>' % (self.__module__ + '.' + self.__class__.__name__, id(self), self.name or "*no name*") def new_revision(self, set_date=True, author=None, title='', raw='', force_new=0): """Create a new revision for this page. Check to make sure that the new text is actually different from the latest revision. If it's not, then don't bother creating a new revision.""" if force_new or (self.versions[-1].get_raw() != raw): w = WikiVersion(page=self, author=author, title=title, raw=raw) if set_date: w.set_date(datetime.utcnow()) self.versions.append(w) self.watchable_changed(w.date) if author: author.karma_activity_credit() # before invalidating referring pages, we want to # update the html cache, which has the side effect # of updating the outbound references. self.invalidate_html_cache() unused_html = self.get_cached_html() # may seem useless for new pages, but we could be creating # a new page that was referred to from another page somewhere self._invalidate_referring_pages() self._p_changed = 1 def _invalidate_referring_pages(self, all_groups=0): """Invalidate HTML cache of pages which refer to this one.""" # we changed default behavior to not scan all groups when invalidating. # this means that cross-group links for new pages after this change # will not be accurate, until the page(s) linking to the new page # is itself modified. refs = self.wiki.references_to(self, all_groups=all_groups) for p in refs: p.invalidate_html_cache() def latest_edit_by(self, user): """Return latest edit by user, or None.""" rvers = self.versions[:] rvers.reverse() for version in rvers: if version.author is user: return version return None def get_comments(self): """Return list of comments (BlogItems).""" blog_item = self.blog.get_item(0) if blog_item: return blog_item.get_comments() else: return [] def get_revision(self, rev_id): """Return revision index rev_id or None.""" rev_id = max(0, rev_id) try: rev = self.versions[rev_id] except IndexError: rev = None return rev def revision_index(self, version): """Return revision index of version, or raise ValueError.""" return self.versions.index(version) def merge_revisions(self, base, old, new): """Merge the newest revision with older revision, off of base. Returns (merged text, exit_code) or None. Base may be -1 to signify empty text. Exit code is 0 for no conflicts, or 1 if conflicts exist. """ if len(self.versions) < 2: return None if base == -1: base_text = '' else: base_text = self.versions[base].get_raw() old_text = self.versions[old].get_raw() new_text = self.versions[new].get_raw() merger = Merger(base_text, old_text, new_text) merged = merger.merge('Revision %d' % base, 'Revision %d' % old, 'Revision %d' % new, ) if not merged: return None exit_code = 0 if merger.has_conflicts(): exit_code = 1 return (merged, exit_code) def watchable_name(self): #return self.wiki.group.name + ' ' + self.versions[-1].title return self.versions[-1].title or self.name def watchable_changed(self, now=None): # wiki changed, too Watchable.watchable_changed(self, now) self.wiki.watchable_changed(now) def watchable_modified_date(self): return self.watchable_last_change() def last_modified(self): sys.stderr.write('WARNING: using deprecated qon.wiki.WikiPage.last_modified.') return self.watchable_last_change() def who_has_lock(self): return self.locked_by_user def can_edit(self, user): """ A page is editable if either it's not locked by anybody, or if the requesting user is the one who holds the lock, or if the user is allowed to edit within the group""" # user must be logged in to edit if not user: return False # check lock if (self.locked_by_user) and (self.locked_by_user is not user) and (not self.can_manage(user)): return False if self.wiki.group.can_edit(user): return True return False def can_show(self): """Return False if this item should be suppressed due to feedback score.""" if self.get_karma_score() < qon.karma.min_karma_to_show: return False return True def can_lock(self, user): """ For now, let only a group owner lock/unlock a page. In the future, we may want to consider allowing the original page author to lock/unlock as well.""" return self.wiki.group.is_owner(user) def lock(self, user): if self.can_lock(user): self.locked_by_user = user def unlock(self, user): if self.can_lock(user): self.locked_by_user = None def can_get_karma_from(self, other): return other is not None # HTML cache methods def add_html_dependency(self, target): """Adds target as something self depends on for its HTML cache.""" self.__cached_html.add_dependency(target) self.__cached_html2.add_dependency(target) def invalidate_html_cache(self): self.__cached_html.flush() self.__cached_html2.flush() def get_cached_html(self): return self.__cached_html.get() def get_cached_html2(self): return self.__cached_html2.get() def _update_html_cache(self): v = self.versions[-1] html = v.raw_to_html(v.get_raw()) # take this opportunity to update the page's outbound references if hasattr(v, '_v_references'): self.set_outbound_references(v._v_references) del v._v_references return html def _update_html2_cache(self): v = self.versions[-1] html = v.raw_to_html(v.get_raw(), suppress_tooltip=1) return html def disable_cache(self): self.__cached_html.disable_cache() self.__cached_html2.disable_cache() def cache_disabled(self): return self.__cached_html.cache_disabled() or self.__cached_html2.cache_disabled() def get_ref(self): """Return a reference (group, page_name) to this page, for use in outbound/inbound references.""" return (self.wiki.group, self.name) def set_outbound_references(self, new_out_refs): """Record new outbound references.""" # filter non-existent cross-group page refs out of new_out_refs # this interacts with the change that no longer scans all groups # for references to new pages. if a cross-group link existed to a new # page, this method (pre-filtering) would have neglected to add the inbound # link from the cross-group reference, even if both pages had been edited. l = [] for r in new_out_refs: group_name, page_name = r if not group_name: l.append(r) else: page = _ref_to_page(r, self.wiki.group) if page: l.append(r) new_out_refs = l # get old outbound refs old_out_refs = self.outbound_references or [] # get two lists: items that used to be outbound references but # are no longer (old_not_new), and new outbound references that # weren't there before (new_not_old) old_not_new, new_not_old = xor_lists(old_out_refs, new_out_refs) # pre-fill reference to me me_ref = self.get_ref() # invalidate inbound references of pages that we no longer refer to for ref in old_not_new: page = _ref_to_page(ref, self.wiki.group) if page: # added by Alex page.remove_inbound_reference(me_ref) # add inbound references for pages we've added outbound links to for ref in new_not_old: page = _ref_to_page(ref, self.wiki.group) if page: # could be ref to new page page.add_inbound_reference(me_ref) # record new outbound references self.outbound_references = PersistentList() self.outbound_references.extend(new_out_refs) def remove_inbound_reference(self, ref): if self.inbound_references is not None: if ref in self.inbound_references: self.inbound_references.remove(ref) def add_inbound_reference(self, ref): if self.inbound_references is not None: if ref not in self.inbound_references: self.inbound_references.append(ref) # IHasBlog methods not implemented by other base classes def can_manage(self, user): """Who can manage this blog? Group owners.""" return self.wiki.group.is_owner(user) def can_read(self, user): return self.wiki.can_read(user) def can_delete_item(self, item): """Can't delete item 0, which holds page comments.""" if self.blog.get_item(0) is item: return False return True def can_create_item(self): """Users aren't allowed to create new topics in wiki pages.""" return False def is_accepted(self): return self.wiki.group.is_accepted() def get_owners(self): return self.wiki.group.get_owners() def is_owner(self, user): return self.wiki.group.is_owner(user) def get_title(self): # this is here and in BlogItem return self.versions[-1].title or self.name def get_blog(self): return self.blog def get_wiki(self): return self.wiki def get_name(self): return self.name def get_all_owners(self): return self.get_owners() def get_all_blogs(self): return [self.blog] def get_member_list(self): return self.wiki.group.get_member_list()
class Motion(Content, ContextACLMixin, LocalRolesMixin): default_view = "view" search_visible = True nav_visible = False type_name = "Motion" type_title = _("Motion") add_permission = ADD_MOTION css_icon = "glyphicon glyphicon-list-alt" body = "" endorsements_text = "" sharing_token = None hashtag = "" _proposals = () _creator = () _endorsements = {} @property def __acl__(self): acl_list = super(Motion, self).__acl__ motion_proc = self.__parent__ if motion_proc: if motion_proc.allow_endorsements == False: acl_list.insert(0, (Deny, ROLE_EVERYONE, (ENDORSE_MOTION,))) if motion_proc.allow_sharing_link == True: acl_list.insert(0, (Allow, ROLE_OWNER, (ENABLE_MOTION_SHARING,))) wf = self.workflow state = "" if wf: state = wf.state in wf.states and wf.state or wf.initial_state if state and state != "draft": if motion_proc.motion_visibility == "authenticated": acl_list.insert(0, (Allow, ROLE_AUTHENTICATED, (PERM_VIEW,))) if motion_proc.motion_visibility == "everyone": acl_list.insert(0, (Allow, ROLE_EVERYONE, (PERM_VIEW,))) return acl_list @property def proposals(self): return tuple(self._proposals) @proposals.setter def proposals(self, value): if not isinstance(self._proposals, PersistentList): self._proposals = PersistentList() if tuple(value) != tuple(self._proposals): self._proposals[:] = [] self._proposals.extend(value) @property def creator(self): return tuple(self._creator) @creator.setter def creator(self, value): if tuple(value) != self._creator: self._creator = tuple(value) @property def endorsements(self): return tuple(self._endorsements) @endorsements.setter def endorsements(self, value): if not isinstance(self._endorsements, OOBTree): self._endorsements = OOBTree() # Add new with timestamp for userid in set(value) - set(self._endorsements): self.local_roles.add(userid, ROLE_VIEWER) self._endorsements[userid] = utcnow() # Remove no longer endorsing userids for userid in set(self._endorsements) - set(value): del self._endorsements[userid] self.local_roles.remove(userid, ROLE_VIEWER) @property def endorsements_info(self): return self._endorsements.items() def enable_sharing_token(self): self.sharing_token = "".join( [choice(string.letters + string.digits) for x in range(15)] ) return self.sharing_token def remove_sharing_token(self): self.sharing_token = None
class Alert(VisualisableElement, Entity): """Alert class""" templates = { InternalAlertKind.content_alert: { 'default': 'lac:views/templates/alerts/content_result.pt', 'small': 'lac:views/templates/alerts/small_content_result.pt' }, InternalAlertKind.moderation_alert: { 'default': 'lac:views/templates/alerts/moderation_result.pt', 'small': 'lac:views/templates/alerts/small_moderation_result.pt' }, InternalAlertKind.service_alert: { 'default': 'lac:views/templates/alerts/service_result.pt', 'small': 'lac:views/templates/alerts/small_service_result.pt' } } icon = 'glyphicon glyphicon-bell' subjects = SharedMultipleProperty('subjects') users_to_alert = SharedMultipleProperty('users_to_alert') def __init__(self, kind, **kwargs): super(Alert, self).__init__(**kwargs) self.set_data(kwargs) self.kind = kind self.users_to_alert = PersistentList() def init_alert(self, users, subjects=[]): self.subscribe(users) for subject in subjects: self.addtoproperty('subjects', subject) def subscribe(self, users): if not isinstance(users, (list, tuple)): users = [users] self.users_to_alert.extend( [str(get_oid(user, user)) for user in users]) def unsubscribe(self, user): key = str(get_oid(user, user)) if key in self.users_to_alert: self.users_to_alert.remove(key) user.addtoproperty('old_alerts', self) self.reindex() def get_subject_state(self, subject, user): return get_states_mapping(user, subject, getattr(subject, 'state_or_none', [None])[0]) def get_templates(self): return self.templates.get(self.kind, {}) def is_kind_of(self, kind): return kind == self.kind def has_args(self, **kwargs): for key in kwargs: if getattr(self, key, None) != kwargs[key]: return False return True
class Alert(VisualisableElement, Entity): """Alert class""" templates = { InternalAlertKind.content_alert: { 'default': 'lac:views/templates/alerts/content_result.pt', 'small': 'lac:views/templates/alerts/small_content_result.pt' }, InternalAlertKind.moderation_alert: { 'default': 'lac:views/templates/alerts/moderation_result.pt', 'small': 'lac:views/templates/alerts/small_moderation_result.pt' }, InternalAlertKind.service_alert: { 'default': 'lac:views/templates/alerts/service_result.pt', 'small': 'lac:views/templates/alerts/small_service_result.pt' } } icon = 'glyphicon glyphicon-bell' subjects = SharedMultipleProperty('subjects') users_to_alert = SharedMultipleProperty('users_to_alert') def __init__(self, kind, **kwargs): super(Alert, self).__init__(**kwargs) self.set_data(kwargs) self.kind = kind self.users_to_alert = PersistentList() def init_alert(self, users, subjects=[]): self.subscribe(users) for subject in subjects: self.addtoproperty('subjects', subject) def subscribe(self, users): if not isinstance(users, (list, tuple)): users = [users] self.users_to_alert.extend( [str(get_oid(user, user)) for user in users]) def unsubscribe(self, user): key = str(get_oid(user, user)) if key in self.users_to_alert: self.users_to_alert.remove(key) user.addtoproperty('old_alerts', self) self.reindex() def get_subject_state(self, subject, user): return get_states_mapping( user, subject, getattr(subject, 'state_or_none', [None])[0]) def get_templates(self): return self.templates.get(self.kind, {}) def is_kind_of(self, kind): return kind == self.kind def has_args(self, **kwargs): for key in kwargs: if getattr(self, key, None) != kwargs[key]: return False return True