Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Interfaces.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2001, 2002 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE
  12. #
  13. ##############################################################################
  14. from zope.interface import Interface, Attribute
  15. class ICollection(Interface):
  16. def clear():
  17. """Remove all of the items from the collection."""
  18. def __nonzero__():
  19. """Check if the collection is non-empty.
  20. Return a true value if the collection is non-empty and a
  21. false value otherwise.
  22. """
  23. class IReadSequence(Interface):
  24. def __getitem__(index):
  25. """Return the value at the given index.
  26. An IndexError is raised if the index cannot be found.
  27. """
  28. def __getslice__(index1, index2):
  29. """Return a subsequence from the original sequence.
  30. The subsequence includes the items from index1 up to, but not
  31. including, index2.
  32. """
  33. class IKeyed(ICollection):
  34. def has_key(key):
  35. """Check whether the object has an item with the given key.
  36. Return a true value if the key is present, else a false value.
  37. """
  38. def keys(min=None, max=None, excludemin=False, excludemax=False):
  39. """Return an IReadSequence containing the keys in the collection.
  40. The type of the IReadSequence is not specified. It could be a list
  41. or a tuple or some other type.
  42. All arguments are optional, and may be specified as keyword
  43. arguments, or by position.
  44. If a min is specified, then output is constrained to keys greater
  45. than or equal to the given min, and, if excludemin is specified and
  46. true, is further constrained to keys strictly greater than min. A
  47. min value of None is ignored. If min is None or not specified, and
  48. excludemin is true, the smallest key is excluded.
  49. If a max is specified, then output is constrained to keys less than
  50. or equal to the given max, and, if excludemax is specified and
  51. true, is further constrained to keys strictly less than max. A max
  52. value of None is ignored. If max is None or not specified, and
  53. excludemax is true, the largest key is excluded.
  54. """
  55. def maxKey(key=None):
  56. """Return the maximum key.
  57. If a key argument if provided and not None, return the largest key
  58. that is less than or equal to the argument. Raise an exception if
  59. no such key exists.
  60. """
  61. def minKey(key=None):
  62. """Return the minimum key.
  63. If a key argument if provided and not None, return the smallest key
  64. that is greater than or equal to the argument. Raise an exception
  65. if no such key exists.
  66. """
  67. class ISetMutable(IKeyed):
  68. def insert(key):
  69. """Add the key (value) to the set.
  70. If the key was already in the set, return 0, otherwise return 1.
  71. """
  72. def remove(key):
  73. """Remove the key from the set.
  74. Raises KeyError if key is not in the set.
  75. """
  76. def update(seq):
  77. """Add the items from the given sequence to the set."""
  78. class ISized(Interface):
  79. """An object that supports __len__."""
  80. def __len__():
  81. """Return the number of items in the container."""
  82. class IKeySequence(IKeyed, ISized):
  83. def __getitem__(index):
  84. """Return the key in the given index position.
  85. This allows iteration with for loops and use in functions,
  86. like map and list, that read sequences.
  87. """
  88. class ISet(IKeySequence, ISetMutable):
  89. pass
  90. class ITreeSet(IKeyed, ISetMutable):
  91. pass
  92. class IMinimalDictionary(ISized, IKeyed):
  93. def get(key, default):
  94. """Get the value associated with the given key.
  95. Return the default if has_key(key) is false.
  96. """
  97. def __getitem__(key):
  98. """Get the value associated with the given key.
  99. Raise KeyError if has_key(key) is false.
  100. """
  101. def __setitem__(key, value):
  102. """Set the value associated with the given key."""
  103. def __delitem__(key):
  104. """Delete the value associated with the given key.
  105. Raise KeyError if has_key(key) is false.
  106. """
  107. def values(min=None, max=None, excludemin=False, excludemax=False):
  108. """Return an IReadSequence containing the values in the collection.
  109. The type of the IReadSequence is not specified. It could be a list
  110. or a tuple or some other type.
  111. All arguments are optional, and may be specified as keyword
  112. arguments, or by position.
  113. If a min is specified, then output is constrained to values whose
  114. keys are greater than or equal to the given min, and, if excludemin
  115. is specified and true, is further constrained to values whose keys
  116. are strictly greater than min. A min value of None is ignored. If
  117. min is None or not specified, and excludemin is true, the value
  118. corresponding to the smallest key is excluded.
  119. If a max is specified, then output is constrained to values whose
  120. keys are less than or equal to the given max, and, if excludemax is
  121. specified and true, is further constrained to values whose keys are
  122. strictly less than max. A max value of None is ignored. If max is
  123. None or not specified, and excludemax is true, the value
  124. corresponding to the largest key is excluded.
  125. """
  126. def items(min=None, max=None, excludemin=False, excludemax=False):
  127. """Return an IReadSequence containing the items in the collection.
  128. An item is a 2-tuple, a (key, value) pair.
  129. The type of the IReadSequence is not specified. It could be a list
  130. or a tuple or some other type.
  131. All arguments are optional, and may be specified as keyword
  132. arguments, or by position.
  133. If a min is specified, then output is constrained to items whose
  134. keys are greater than or equal to the given min, and, if excludemin
  135. is specified and true, is further constrained to items whose keys
  136. are strictly greater than min. A min value of None is ignored. If
  137. min is None or not specified, and excludemin is true, the item with
  138. the smallest key is excluded.
  139. If a max is specified, then output is constrained to items whose
  140. keys are less than or equal to the given max, and, if excludemax is
  141. specified and true, is further constrained to items whose keys are
  142. strictly less than max. A max value of None is ignored. If max is
  143. None or not specified, and excludemax is true, the item with the
  144. largest key is excluded.
  145. """
  146. class IDictionaryIsh(IMinimalDictionary):
  147. def update(collection):
  148. """Add the items from the given collection object to the collection.
  149. The input collection must be a sequence of (key, value) 2-tuples,
  150. or an object with an 'items' method that returns a sequence of
  151. (key, value) pairs.
  152. """
  153. def byValue(minValue):
  154. """Return a sequence of (value, key) pairs, sorted by value.
  155. Values < minValue are omitted and other values are "normalized" by
  156. the minimum value. This normalization may be a noop, but, for
  157. integer values, the normalization is division.
  158. """
  159. def setdefault(key, d):
  160. """D.setdefault(k, d) -> D.get(k, d), also set D[k]=d if k not in D.
  161. Return the value like get() except that if key is missing, d is both
  162. returned and inserted into the dictionary as the value of k.
  163. Note that, unlike as for Python's dict.setdefault(), d is not
  164. optional. Python defaults d to None, but that doesn't make sense
  165. for mappings that can't have None as a value (for example, an
  166. IIBTree can have only integers as values).
  167. """
  168. def pop(key, d):
  169. """D.pop(k[, d]) -> v, remove key and return the corresponding value.
  170. If key is not found, d is returned if given, otherwise KeyError is
  171. raised.
  172. """
  173. class IBTree(IDictionaryIsh):
  174. def insert(key, value):
  175. """Insert a key and value into the collection.
  176. If the key was already in the collection, then there is no
  177. change and 0 is returned.
  178. If the key was not already in the collection, then the item is
  179. added and 1 is returned.
  180. This method is here to allow one to generate random keys and
  181. to insert and test whether the key was there in one operation.
  182. A standard idiom for generating new keys will be::
  183. key = generate_key()
  184. while not t.insert(key, value):
  185. key=generate_key()
  186. """
  187. class IMerge(Interface):
  188. """Object with methods for merging sets, buckets, and trees.
  189. These methods are supplied in modules that define collection
  190. classes with particular key and value types. The operations apply
  191. only to collections from the same module. For example, the
  192. IIBTree.union can only be used with IIBTree.IIBTree,
  193. IIBTree.IIBucket, IIBTree.IISet, and IIBTree.IITreeSet.
  194. The implementing module has a value type. The IOBTree and OOBTree
  195. modules have object value type. The IIBTree and OIBTree modules
  196. have integer value types. Other modules may be defined in the
  197. future that have other value types.
  198. The individual types are classified into set (Set and TreeSet) and
  199. mapping (Bucket and BTree) types.
  200. """
  201. def difference(c1, c2):
  202. """Return the keys or items in c1 for which there is no key in c2.
  203. If c1 is None, then None is returned. If c2 is None, then c1
  204. is returned.
  205. If neither c1 nor c2 is None, the output is a Set if c1 is a Set or
  206. TreeSet, and is a Bucket if c1 is a Bucket or BTree.
  207. """
  208. def union(c1, c2):
  209. """Compute the Union of c1 and c2.
  210. If c1 is None, then c2 is returned, otherwise, if c2 is None,
  211. then c1 is returned.
  212. The output is a Set containing keys from the input
  213. collections.
  214. """
  215. def intersection(c1, c2):
  216. """Compute the intersection of c1 and c2.
  217. If c1 is None, then c2 is returned, otherwise, if c2 is None,
  218. then c1 is returned.
  219. The output is a Set containing matching keys from the input
  220. collections.
  221. """
  222. class IBTreeModule(Interface):
  223. """These are available in all modules (IOBTree, OIBTree, OOBTree, IIBTree,
  224. IFBTree, LFBTree, LOBTree, OLBTree, and LLBTree).
  225. """
  226. BTree = Attribute(
  227. """The IBTree for this module.
  228. Also available as [prefix]BTree, as in IOBTree.""")
  229. Bucket = Attribute(
  230. """The leaf-node data buckets used by the BTree.
  231. (IBucket is not currently defined in this file, but is essentially
  232. IDictionaryIsh, with the exception of __nonzero__, as of this
  233. writing.)
  234. Also available as [prefix]Bucket, as in IOBucket.""")
  235. TreeSet = Attribute(
  236. """The ITreeSet for this module.
  237. Also available as [prefix]TreeSet, as in IOTreeSet.""")
  238. Set = Attribute(
  239. """The ISet for this module: the leaf-node data buckets used by the
  240. TreeSet.
  241. Also available as [prefix]BTree, as in IOSet.""")
  242. class IIMerge(IMerge):
  243. """Merge collections with integer value type.
  244. A primary intent is to support operations with no or integer
  245. values, which are used as "scores" to rate indiviual keys. That
  246. is, in this context, a BTree or Bucket is viewed as a set with
  247. scored keys, using integer scores.
  248. """
  249. def weightedUnion(c1, c2, weight1=1, weight2=1):
  250. """Compute the weighted union of c1 and c2.
  251. If c1 and c2 are None, the output is (0, None).
  252. If c1 is None and c2 is not None, the output is (weight2, c2).
  253. If c1 is not None and c2 is None, the output is (weight1, c1).
  254. Else, and hereafter, c1 is not None and c2 is not None.
  255. If c1 and c2 are both sets, the output is 1 and the (unweighted)
  256. union of the sets.
  257. Else the output is 1 and a Bucket whose keys are the union of c1 and
  258. c2's keys, and whose values are::
  259. v1*weight1 + v2*weight2
  260. where:
  261. v1 is 0 if the key is not in c1
  262. 1 if the key is in c1 and c1 is a set
  263. c1[key] if the key is in c1 and c1 is a mapping
  264. v2 is 0 if the key is not in c2
  265. 1 if the key is in c2 and c2 is a set
  266. c2[key] if the key is in c2 and c2 is a mapping
  267. Note that c1 and c2 must be collections.
  268. """
  269. def weightedIntersection(c1, c2, weight1=1, weight2=1):
  270. """Compute the weighted intersection of c1 and c2.
  271. If c1 and c2 are None, the output is (0, None).
  272. If c1 is None and c2 is not None, the output is (weight2, c2).
  273. If c1 is not None and c2 is None, the output is (weight1, c1).
  274. Else, and hereafter, c1 is not None and c2 is not None.
  275. If c1 and c2 are both sets, the output is the sum of the weights
  276. and the (unweighted) intersection of the sets.
  277. Else the output is 1 and a Bucket whose keys are the intersection of
  278. c1 and c2's keys, and whose values are::
  279. v1*weight1 + v2*weight2
  280. where:
  281. v1 is 1 if c1 is a set
  282. c1[key] if c1 is a mapping
  283. v2 is 1 if c2 is a set
  284. c2[key] if c2 is a mapping
  285. Note that c1 and c2 must be collections.
  286. """
  287. class IMergeIntegerKey(IMerge):
  288. """IMerge-able objects with integer keys.
  289. Concretely, this means the types in IOBTree and IIBTree.
  290. """
  291. def multiunion(seq):
  292. """Return union of (zero or more) integer sets, as an integer set.
  293. seq is a sequence of objects each convertible to an integer set.
  294. These objects are convertible to an integer set:
  295. + An integer, which is added to the union.
  296. + A Set or TreeSet from the same module (for example, an
  297. IIBTree.TreeSet for IIBTree.multiunion()). The elements of the
  298. set are added to the union.
  299. + A Bucket or BTree from the same module (for example, an
  300. IOBTree.IOBTree for IOBTree.multiunion()). The keys of the
  301. mapping are added to the union.
  302. The union is returned as a Set from the same module (for example,
  303. IIBTree.multiunion() returns an IIBTree.IISet).
  304. The point to this method is that it can run much faster than
  305. doing a sequence of two-input union() calls. Under the covers,
  306. all the integers in all the inputs are sorted via a single
  307. linear-time radix sort, then duplicates are removed in a second
  308. linear-time pass.
  309. """
  310. class IBTreeFamily(Interface):
  311. """the 64-bit or 32-bit family"""
  312. IO = Attribute('The IIntegerObjectBTreeModule for this family')
  313. OI = Attribute('The IObjectIntegerBTreeModule for this family')
  314. II = Attribute('The IIntegerIntegerBTreeModule for this family')
  315. IF = Attribute('The IIntegerFloatBTreeModule for this family')
  316. OO = Attribute('The IObjectObjectBTreeModule for this family')
  317. maxint = Attribute('The maximum integer storable in this family')
  318. minint = Attribute('The minimum integer storable in this family')
  319. class IIntegerObjectBTreeModule(IBTreeModule, IMerge):
  320. """keys, or set values, are integers; values are objects.
  321. describes IOBTree and LOBTree"""
  322. family = Attribute('The IBTreeFamily of this module')
  323. class IObjectIntegerBTreeModule(IBTreeModule, IIMerge):
  324. """keys, or set values, are objects; values are integers.
  325. Object keys (and set values) must sort reliably (for instance, *not* on
  326. object id)! Homogenous key types recommended.
  327. describes OIBTree and LOBTree"""
  328. family = Attribute('The IBTreeFamily of this module')
  329. class IIntegerIntegerBTreeModule(IBTreeModule, IIMerge, IMergeIntegerKey):
  330. """keys, or set values, are integers; values are also integers.
  331. describes IIBTree and LLBTree"""
  332. family = Attribute('The IBTreeFamily of this module')
  333. class IObjectObjectBTreeModule(IBTreeModule, IMerge):
  334. """keys, or set values, are objects; values are also objects.
  335. Object keys (and set values) must sort reliably (for instance, *not* on
  336. object id)! Homogenous key types recommended.
  337. describes OOBTree"""
  338. # Note that there's no ``family`` attribute; all families include
  339. # the OO flavor of BTrees.
  340. class IIntegerFloatBTreeModule(IBTreeModule, IMerge):
  341. """keys, or set values, are integers; values are floats.
  342. describes IFBTree and LFBTree"""
  343. family = Attribute('The IBTreeFamily of this module')
  344. try:
  345. from ZODB.POSException import BTreesConflictError
  346. except ImportError:
  347. class BTreesConflictError(ValueError):
  348. @property
  349. def reason(self):
  350. return self.args[-1]
  351. ###############################################################
  352. # IMPORTANT NOTE
  353. #
  354. # Getting the length of a BTree, TreeSet, or output of keys,
  355. # values, or items of same is expensive. If you need to get the
  356. # length, you need to maintain this separately.
  357. #
  358. # Eventually, I need to express this through the interfaces.
  359. #
  360. ################################################################