diff options
Diffstat (limited to 'cobbler/Cheetah/Tools')
-rw-r--r-- | cobbler/Cheetah/Tools/CGITemplate.py | 78 | ||||
-rw-r--r-- | cobbler/Cheetah/Tools/MondoReport.py | 464 | ||||
-rw-r--r-- | cobbler/Cheetah/Tools/MondoReportDoc.txt | 391 | ||||
-rw-r--r-- | cobbler/Cheetah/Tools/RecursiveNull.py | 23 | ||||
-rw-r--r-- | cobbler/Cheetah/Tools/SiteHierarchy.py | 183 | ||||
-rw-r--r-- | cobbler/Cheetah/Tools/__init__.py | 8 |
6 files changed, 0 insertions, 1147 deletions
diff --git a/cobbler/Cheetah/Tools/CGITemplate.py b/cobbler/Cheetah/Tools/CGITemplate.py deleted file mode 100644 index b72e62b..0000000 --- a/cobbler/Cheetah/Tools/CGITemplate.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# $Id: CGITemplate.py,v 1.6 2006/01/29 02:09:59 tavis_rudd Exp $ -"""A subclass of Cheetah.Template for use in CGI scripts. - -Usage in a template: - #extends Cheetah.Tools.CGITemplate - #implements respond - $cgiHeaders#slurp - -Usage in a template inheriting a Python class: -1. The template - #extends MyPythonClass - #implements respond - $cgiHeaders#slurp - -2. The Python class - from Cheetah.Tools import CGITemplate - class MyPythonClass(CGITemplate): - def cgiHeadersHook(self): - return "Content-Type: text/html; charset=koi8-r\n\n" - -To read GET/POST variables, use the .webInput method defined in -Cheetah.Utils.WebInputMixin (available in all templates without importing -anything), use Python's 'cgi' module, or make your own arrangements. - -This class inherits from Cheetah.Template to make it usable in Cheetah's -single-inheritance model. - - -Meta-Data -================================================================================ -Author: Mike Orr <iron@mso.oz.net> -License: This software is released for unlimited distribution under the - terms of the MIT license. See the LICENSE file. -Version: $Revision: 1.6 $ -Start Date: 2001/10/03 -Last Revision Date: $Date: 2006/01/29 02:09:59 $ -""" -__author__ = "Mike Orr <iron@mso.oz.net>" -__revision__ = "$Revision: 1.6 $"[11:-2] - -import os -from Cheetah.Template import Template - -class CGITemplate(Template): - """Methods useful in CGI scripts. - - Any class that inherits this mixin must also inherit Cheetah.Servlet. - """ - - - def cgiHeaders(self): - """Outputs the CGI headers if this is a CGI script. - - Usage: $cgiHeaders#slurp - Override .cgiHeadersHook() if you want to customize the headers. - """ - if self.isCgi(): - return self.cgiHeadersHook() - - - - def cgiHeadersHook(self): - """Override if you want to customize the CGI headers. - """ - return "Content-type: text/html\n\n" - - - def isCgi(self): - """Is this a CGI script? - """ - env = os.environ.has_key('REQUEST_METHOD') - wk = self._CHEETAH__isControlledByWebKit - return env and not wk - - - -# vim: shiftwidth=4 tabstop=4 expandtab diff --git a/cobbler/Cheetah/Tools/MondoReport.py b/cobbler/Cheetah/Tools/MondoReport.py deleted file mode 100644 index f73e7fc..0000000 --- a/cobbler/Cheetah/Tools/MondoReport.py +++ /dev/null @@ -1,464 +0,0 @@ -#!/usr/bin/env python -""" -@@TR: This code is pretty much unsupported. - -MondoReport.py -- Batching module for Python and Cheetah. - -Version 2001-Nov-18. Doesn't do much practical yet, but the companion -testMondoReport.py passes all its tests. --Mike Orr (Iron) - -TODO: BatchRecord.prev/next/prev_batches/next_batches/query, prev.query, -next.query. - -How about Report: .page(), .all(), .summary()? Or PageBreaker. -""" -import operator, types -try: - from Cheetah.NameMapper import valueForKey as lookup_func -except ImportError: - def lookup_func(obj, name): - if hasattr(obj, name): - return getattr(obj, name) - else: - return obj[name] # Raises KeyError. - -########## CONSTANTS ############################## - -True, False = (1==1), (1==0) -numericTypes = types.IntType, types.LongType, types.FloatType - -########## PUBLIC GENERIC FUNCTIONS ############################## - -class NegativeError(ValueError): - pass - -def isNumeric(v): - return type(v) in numericTypes - -def isNonNegative(v): - ret = isNumeric(v) - if ret and v < 0: - raise NegativeError(v) - -def isNotNone(v): - return v is not None - -def Roman(n): - n = int(n) # Raises TypeError. - if n < 1: - raise ValueError("roman numeral for zero or negative undefined: " + n) - roman = '' - while n >= 1000: - n = n - 1000 - roman = roman + 'M' - while n >= 500: - n = n - 500 - roman = roman + 'D' - while n >= 100: - n = n - 100 - roman = roman + 'C' - while n >= 50: - n = n - 50 - roman = roman + 'L' - while n >= 10: - n = n - 10 - roman = roman + 'X' - while n >= 5: - n = n - 5 - roman = roman + 'V' - while n < 5 and n >= 1: - n = n - 1 - roman = roman + 'I' - roman = roman.replace('DCCCC', 'CM') - roman = roman.replace('CCCC', 'CD') - roman = roman.replace('LXXXX', 'XC') - roman = roman.replace('XXXX', 'XL') - roman = roman.replace('VIIII', 'IX') - roman = roman.replace('IIII', 'IV') - return roman - - -def sum(lis): - return reduce(operator.add, lis, 0) - -def mean(lis): - """Always returns a floating-point number. - """ - lis_len = len(lis) - if lis_len == 0: - return 0.00 # Avoid ZeroDivisionError (not raised for floats anyway) - total = float( sum(lis) ) - return total / lis_len - -def median(lis): - lis = lis[:] - lis.sort() - return lis[int(len(lis)/2)] - - -def variance(lis): - raise NotImplementedError() - -def variance_n(lis): - raise NotImplementedError() - -def standardDeviation(lis): - raise NotImplementedError() - -def standardDeviation_n(lis): - raise NotImplementedError() - - - -class IndexFormats: - """Eight ways to display a subscript index. - ("Fifty ways to leave your lover....") - """ - def __init__(self, index, item=None): - self._index = index - self._number = index + 1 - self._item = item - - def index(self): - return self._index - - __call__ = index - - def number(self): - return self._number - - def even(self): - return self._number % 2 == 0 - - def odd(self): - return not self.even() - - def even_i(self): - return self._index % 2 == 0 - - def odd_i(self): - return not self.even_i() - - def letter(self): - return self.Letter().lower() - - def Letter(self): - n = ord('A') + self._index - return chr(n) - - def roman(self): - return self.Roman().lower() - - def Roman(self): - return Roman(self._number) - - def item(self): - return self._item - - - -########## PRIVATE CLASSES ############################## - -class ValuesGetterMixin: - def __init__(self, origList): - self._origList = origList - - def _getValues(self, field=None, criteria=None): - if field: - ret = [lookup_func(elm, field) for elm in self._origList] - else: - ret = self._origList - if criteria: - ret = filter(criteria, ret) - return ret - - -class RecordStats(IndexFormats, ValuesGetterMixin): - """The statistics that depend on the current record. - """ - def __init__(self, origList, index): - record = origList[index] # Raises IndexError. - IndexFormats.__init__(self, index, record) - ValuesGetterMixin.__init__(self, origList) - - def length(self): - return len(self._origList) - - def first(self): - return self._index == 0 - - def last(self): - return self._index >= len(self._origList) - 1 - - def _firstOrLastValue(self, field, currentIndex, otherIndex): - currentValue = self._origList[currentIndex] # Raises IndexError. - try: - otherValue = self._origList[otherIndex] - except IndexError: - return True - if field: - currentValue = lookup_func(currentValue, field) - otherValue = lookup_func(otherValue, field) - return currentValue != otherValue - - def firstValue(self, field=None): - return self._firstOrLastValue(field, self._index, self._index - 1) - - def lastValue(self, field=None): - return self._firstOrLastValue(field, self._index, self._index + 1) - - # firstPage and lastPage not implemented. Needed? - - def percentOfTotal(self, field=None, suffix='%', default='N/A', decimals=2): - rec = self._origList[self._index] - if field: - val = lookup_func(rec, field) - else: - val = rec - try: - lis = self._getValues(field, isNumeric) - except NegativeError: - return default - total = sum(lis) - if total == 0.00: # Avoid ZeroDivisionError. - return default - val = float(val) - try: - percent = (val / total) * 100 - except ZeroDivisionError: - return default - if decimals == 0: - percent = int(percent) - else: - percent = round(percent, decimals) - if suffix: - return str(percent) + suffix # String. - else: - return percent # Numeric. - - def __call__(self): # Overrides IndexFormats.__call__ - """This instance is not callable, so we override the super method. - """ - raise NotImplementedError() - - def prev(self): - if self._index == 0: - return None - else: - length = self.length() - start = self._index - length - return PrevNextPage(self._origList, length, start) - - def next(self): - if self._index + self.length() == self.length(): - return None - else: - length = self.length() - start = self._index + length - return PrevNextPage(self._origList, length, start) - - def prevPages(self): - raise NotImplementedError() - - def nextPages(self): - raise NotImplementedError() - - prev_batches = prevPages - next_batches = nextPages - - def summary(self): - raise NotImplementedError() - - - - def _prevNextHelper(self, start,end,size,orphan,sequence): - """Copied from Zope's DT_InSV.py's "opt" function. - """ - if size < 1: - if start > 0 and end > 0 and end >= start: - size=end+1-start - else: size=7 - - if start > 0: - - try: sequence[start-1] - except: start=len(sequence) - # if start > l: start=l - - if end > 0: - if end < start: end=start - else: - end=start+size-1 - try: sequence[end+orphan-1] - except: end=len(sequence) - # if l - end < orphan: end=l - elif end > 0: - try: sequence[end-1] - except: end=len(sequence) - # if end > l: end=l - start=end+1-size - if start - 1 < orphan: start=1 - else: - start=1 - end=start+size-1 - try: sequence[end+orphan-1] - except: end=len(sequence) - # if l - end < orphan: end=l - return start,end,size - - - -class Summary(ValuesGetterMixin): - """The summary statistics, that don't depend on the current record. - """ - def __init__(self, origList): - ValuesGetterMixin.__init__(self, origList) - - def sum(self, field=None): - lis = self._getValues(field, isNumeric) - return sum(lis) - - total = sum - - def count(self, field=None): - lis = self._getValues(field, isNotNone) - return len(lis) - - def min(self, field=None): - lis = self._getValues(field, isNotNone) - return min(lis) # Python builtin function min. - - def max(self, field=None): - lis = self._getValues(field, isNotNone) - return max(lis) # Python builtin function max. - - def mean(self, field=None): - """Always returns a floating point number. - """ - lis = self._getValues(field, isNumeric) - return mean(lis) - - average = mean - - def median(self, field=None): - lis = self._getValues(field, isNumeric) - return median(lis) - - def variance(self, field=None): - raiseNotImplementedError() - - def variance_n(self, field=None): - raiseNotImplementedError() - - def standardDeviation(self, field=None): - raiseNotImplementedError() - - def standardDeviation_n(self, field=None): - raiseNotImplementedError() - - -class PrevNextPage: - def __init__(self, origList, size, start): - end = start + size - self.start = IndexFormats(start, origList[start]) - self.end = IndexFormats(end, origList[end]) - self.length = size - - -########## MAIN PUBLIC CLASS ############################## -class MondoReport: - _RecordStatsClass = RecordStats - _SummaryClass = Summary - - def __init__(self, origlist): - self._origList = origlist - - def page(self, size, start, overlap=0, orphan=0): - """Returns list of ($r, $a, $b) - """ - if overlap != 0: - raise NotImplementedError("non-zero overlap") - if orphan != 0: - raise NotImplementedError("non-zero orphan") - origList = self._origList - origList_len = len(origList) - start = max(0, start) - end = min( start + size, len(self._origList) ) - mySlice = origList[start:end] - ret = [] - for rel in range(size): - abs_ = start + rel - r = mySlice[rel] - a = self._RecordStatsClass(origList, abs_) - b = self._RecordStatsClass(mySlice, rel) - tup = r, a, b - ret.append(tup) - return ret - - - batch = page - - def all(self): - origList_len = len(self._origList) - return self.page(origList_len, 0, 0, 0) - - - def summary(self): - return self._SummaryClass(self._origList) - -""" -********************************** - Return a pageful of records from a sequence, with statistics. - - in : origlist, list or tuple. The entire set of records. This is - usually a list of objects or a list of dictionaries. - page, int >= 0. Which page to display. - size, int >= 1. How many records per page. - widow, int >=0. Not implemented. - orphan, int >=0. Not implemented. - base, int >=0. Number of first page (usually 0 or 1). - - out: list of (o, b) pairs. The records for the current page. 'o' is - the original element from 'origlist' unchanged. 'b' is a Batch - object containing meta-info about 'o'. - exc: IndexError if 'page' or 'size' is < 1. If 'origlist' is empty or - 'page' is too high, it returns an empty list rather than raising - an error. - - origlist_len = len(origlist) - start = (page + base) * size - end = min(start + size, origlist_len) - ret = [] - # widow, orphan calculation: adjust 'start' and 'end' up and down, - # Set 'widow', 'orphan', 'first_nonwidow', 'first_nonorphan' attributes. - for i in range(start, end): - o = origlist[i] - b = Batch(origlist, size, i) - tup = o, b - ret.append(tup) - return ret - - def prev(self): - # return a PrevNextPage or None - - def next(self): - # return a PrevNextPage or None - - def prev_batches(self): - # return a list of SimpleBatch for the previous batches - - def next_batches(self): - # return a list of SimpleBatch for the next batches - -########## PUBLIC MIXIN CLASS FOR CHEETAH TEMPLATES ############## -class MondoReportMixin: - def batch(self, origList, size=None, start=0, overlap=0, orphan=0): - bat = MondoReport(origList) - return bat.batch(size, start, overlap, orphan) - def batchstats(self, origList): - bat = MondoReport(origList) - return bat.stats() -""" - -# vim: shiftwidth=4 tabstop=4 expandtab textwidth=79 diff --git a/cobbler/Cheetah/Tools/MondoReportDoc.txt b/cobbler/Cheetah/Tools/MondoReportDoc.txt deleted file mode 100644 index 29a026d..0000000 --- a/cobbler/Cheetah/Tools/MondoReportDoc.txt +++ /dev/null @@ -1,391 +0,0 @@ -MondoReport Documentation -Version 0.01 alpha 24-Nov-2001. iron@mso.oz.net or mso@oz.net. -Copyright (c) 2001 Mike Orr. License: same as Python or Cheetah. - -* * * * * -STATUS: previous/next batches and query string are not implemented yet. -Sorting not designed yet. Considering "click on this column header to sort by -this field" and multiple ascending/descending sort fields for a future version. - -Tested with Python 2.2b1. May work with Python 2.1 or 2.0. - -* * * * * -OVERVIEW - -MondoReport -- provide information about a list that is useful in generating -any kind of report. The module consists of one main public class, and some -generic functions you may find useful in other programs. This file contains an -overview, syntax reference and examples. The module is designed both for -standalone use and for integration with the Cheetah template system -(http://www.cheetahtemplate.org/), so the examples are in both Python and -Cheetah. The main uses of MondoReport are: - -(A) to iterate through a list. In this sense MR is a for-loop enhancer, -providing information that would be verbose to calculate otherwise. - -(B) to separate a list into equal-size "pages" (or "batches"--the two terms are -interchangeable) and only display the current page, plus limited information -about the previous and next pages. - -(C) to extract summary statistics about a certain column ("field") in the list. - -* * * * * -MAIN PUBLIC CLASS - -To create a MondoReport instance, supply a list to operate on. - - mr = MondoReport(origList) - -The list may be a list of anything, but if you use the 'field' argument in any -of the methods below, the elements must be instances or dictionaries. - -MondoReport assumes it's operating on an unchanging list. Do not modify the -list or any of its elements until you are completely finished with the -ModoReport object and its sub-objects. Otherwise, you may get an exception or -incorrect results. - -MondoReport instances have three methods: - - .page(size, start, overlap=0, orphan=0 - sort=None, reverse=False) => list of (r, a, b). - -'size' is an integer >= 1. 'start', 'overlap' and 'orphan' are integers >= 0. -The list returned contains one triple for each record in the current page. 'r' -is the original record. 'a' is a BatchRecord instance for the current record -in relation to all records in the origList. 'b' is a BatchRecord instance for -the current record in relation to all the records in that batch/page. (There -is a .batch method that's identical to .page.) - -The other options aren't implemented yet, but 'overlap' duplicates this many -records on adjacent batches. 'orphan' moves this many records or fewer, if -they are on a page alone, onto the neighboring page. 'sort' (string) specifies -a field to sort the records by. It may be suffixed by ":desc" to sort in -descending order. 'reverse' (boolean) reverses the sort order. If both -":desc" and 'reverse' are specified, they will cancel each other out. This -sorting/reversal happens on a copy of the origList, and all objects returned -by this method use the sorted list, except when resorting the next time. -To do more complicated sorting, such as a hierarchy of columns, do it to the -original list before creating the ModoReport object. - - .all(sort=None, reverse=False) => list of (r, a). - -Same, but the current page spans the entire origList. - - .summary() => Summary instance. - -Summary statistics for the entire origList. - -In Python, use .page or .all in a for loop: - - from Cheetah.Tools.MondoReport import MondoReport - mr = MondoReport(myList) - for r, a, b in mr.page(20, 40): - # Do something with r, a and b. The current page is the third page, - # with twenty records corresponding to origList[40:60]. - if not myList: - # Warn the user there are no records in the list. - -It works the same way in Cheetah, just convert to Cheetah syntax. This example -assumes the template doubles as a Webware servlet, so we use the servlet's -'$request' method to look up the CGI parameter 'start'. The default value is 0 -for the first page. - - #from Cheetah.Tools.MondoReport import MondoReport - #set $mr = $MondoReport($bigList) - #set $start = $request.field("start", 0) - #for $o, $a, $b in $mr.page(20, $start) - ... do something with $o, $a and $b ... - #end for - #unless $bigList - This is displayed if the original list has no elements. - It's equivalent to the "else" part Zope DTML's <dtml-in>. - #end unless - -* * * * * -USING 'r' RECORDS - -Use 'r' just as you would the original element. For instance: - - print r.attribute # If r is an instance. - print r['key'] # If r is a dictionary. - print r # If r is numeric or a string. - -In Cheetah, you can take advantage of Universal Dotted Notation and autocalling: - - $r.name ## 'name' may be an attribute or key of 'r'. If 'r' and/or - ## 'name' is a function or method, it will be called without - ## arguments. - $r.attribute - $r['key'] - $r - $r().attribute()['key']() - -If origList is a list of name/value pairs (2-tuples or 2-lists), you may -prefer to do this: - - for (key, value), a, b in mr.page(20, 40): - print key, "=>", value - - #for ($key, $value), $a, $b in $mr.page(20, $start) - $key => $value - #end for - -* * * * * -STATISTICS METHODS AND FIELD VALUES - -Certain methods below have an optional argument 'field'. If specified, -MondoReport will look up that field in each affected record and use its value -in the calculation. MondoReport uses Cheetah's NameMapper if available, -otherwise it uses a minimal NameMapper substitute that looks for an attribute -or dictionary key called "field". You'll get an exception if any record is a -type without attributes or keys, or if one or more records is missing that -attribute/key. - -If 'field' is None, MondoReport will use the entire record in its -calculation. This makes sense mainly if the records are a numeric type. - -All statistics methods filter out None values from their calculations, and -reduce the number of records accordingly. Most filter out non-numeric fields -(or records). Some raise NegativeError if a numeric field (or record) is -negative. - - -* * * * * -BatchRecord METHODS - -The 'a' and 'b' objects of MondoReport.page() and MondoReport.all() provide -these methods. - - .index() - -The current subscript. For 'a', this is the true subscript into origList. -For 'b', this is relative to the current page, so the first record will be 0. -Hint: In Cheetah, use autocalling to skip the parentheses: '$b.index'. - - .number() - -The record's position starting from 1. This is always '.index() + 1'. - - .Letter() - -The letter ("A", "B", "C") corresponding to .number(). Undefined if .number() -> 26. The current implementation just adds the offset to 'a' and returns -whatever character it happens to be. - -To make a less dumb implementation (e.g., "Z, AA, BB" or "Z, A1, B1"): -1) Subclass BatchRecord and override the .Letter method. -2) Subclass MondoReport and set the class variable .BatchRecordClass to your -new improved class. - - .letter() - -Same but lower case. - - .Roman() - -The Roman numeral corresponding to .number(). - - .roman() - -Same but lower case. - - .even() - -True if .number() is even. - - .odd() - -True if .number() is odd. - - .even_i() - -True if .index() is even. - - .odd_i() - -True if .index() is odd. - - .length() - -For 'a', number of records in origList. For 'b', number of records on this -page. - - .item() - -The record itself. You don't need this in the normal case since it's the same -as 'r', but it's useful for previous/next batches. - - .size() - -The 'size' argument used when this BatchRecord was created. -'a.size() == b.size()'. - - .first() - -True if this is the first record. - - .last() - -True if this is the last record. - - .firstValue(field=None) - -True if there is no previous record, or if the previous field/record has a -different value. Used for to print section headers. For instance, if you -are printing addresses by country, this will be true at the first occurrance -of each country. Or for indexes, you can have a non-printing field showing -which letter of the alphablet this entry starts with, and then print a "B" -header before printing the first record starting with "B". - - .lastValue(field=None) - -True if this is the last record containing the current value in the -field/record. - - .percentOfTotal(field=None, suffix="%", default="N/A", decimals=2) - -Returns the percent that the current field/record is of all fields/records. -If 'suffix' is None, returns a number; otherwise it returns a string with -'suffix' suffixed. If the current value is non-numeric, returns 'default' -instead (without 'suffix'). 'decimals' tells the number of decimal places to -return; if 0, there will be no decimal point. - - .prev() - -Returns a PrevNextBatch instance for the previous page. If there is no -previous page, returns None. [Not implemented yet.] - - .next() - -Returns a PrevNextBatch instance for the next page. If there is no next page, -returns None. [Not implemented yet.] - - .prevPages() - -Returns a list of PrevNextPage instances for every previous page, or [] if no -previous pages. [Not implemented yet.] - - .nextPages() - -Returns a list of PrevNextPage instances for every next page, or [] if no next -pages. [Not implemented yet.] - - .query(start=None, label=None, attribName="start", attribs=[]) - -[Not implemented yet.] - -With no arguments, returns the HTML query string with start value removed (so -you can append a new start value in your hyperlink). The query string is taken -from the 'QUERY_STRING' environmental variable, or "" if missing. (This is -Webware compatible.) - -With 'start' (an integer >= 0), returns the query string with an updated start -value, normally for the next or previous batch. - -With 'label' (a string), returns a complete HTML hyperlink: -'<A HREF="?new_query_string">label</A>'. You'll get a TypeError if you specify -'label' but not 'start'. - -With 'attribName' (a string), uses this attribute name rather than "start". -Useful if you have another CGI parameter "start" that's used for something -else. - -With 'attribs' (a dictionary), adds these attributes to the hyperlink. -For instance, 'attribs={"target": "_blank"}'. Ignored unless 'label' is -specified too. - -This method assumes the start parameter is a GET variable, not a POST variable. - - .summary() - -Returns a Summary instance. 'a.summary()' refers to all records in the -origList, so it's the same as MondoReport.summary(). 'b.summary()' refers only -to the records on the current page. [Not implemented yet.] - -* * * * * -PrevNextPage INSTANCES - -[Not implemented yet.] - -PrevNextPage instances have the following methods: - - .start() - -The index (true index of origList) that that page starts at. You may also use -'.start().index()', '.start().number()', etc. Also -'.start().item(field=None)'. (Oh, so *that*'s what .item is for!) - - .end() - -The index (true index of origList) that that page ends at. You may also use -'.end().index()', '.end().number()', etc. Also -'.end().item(field=None)'. - - .length() - -Number of records on that page. - - .query(label=None, attribName="start", attribs={}, before="", after="") - -[Not implemented yet.] - -Similar to 'a.query()' and 'b.query()', but automatically calculates the start -value for the appropriate page. - -For fancy HTML formatting, 'before' is prepended to the returned text and -'after' is appended. (There was an argument 'else_' for if there is no such -batch, but it was removed because you can't even get to this method at all in -that case.) - -* * * * * * -SUMMARY STATISTICS - -These methods are supported by the Summary instances returned by -MondoReport.Summary(): - - .sum(field=None) - -Sum of all numeric values in a field, or sum of all records. - - .total(field=None) - -Same. - - .count(field=None) - -Number of fields/records with non-None values. - - .min(field=None) - -Minimum value in that field/record. Ignores None values. - - .max(field=None) - -Maximum value in that field/record. Ignores None values. - - .mean(field=None) - -The mean (=average) of all numeric values in that field/record. - - .average(field=None) - -Same. - - .median(field=None) - -The median of all numeric values in that field/record. This is done by sorting -the values and taking the middle value. - - .variance(field=None), .variance_n(field=None) - .standardDeviation(field=None), .standardDeviation_n(field=None) - -[Not implemented yet.] - - -* * * * * -To run the regression tests (requires unittest.py, which is standard with -Python 2.2), run MondoReportTest.py from the command line. The regression test -double as usage examples. - - -# vim: shiftwidth=4 tabstop=4 expandtab textwidth=79 diff --git a/cobbler/Cheetah/Tools/RecursiveNull.py b/cobbler/Cheetah/Tools/RecursiveNull.py deleted file mode 100644 index 4897d80..0000000 --- a/cobbler/Cheetah/Tools/RecursiveNull.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python -"""Nothing, but in a friendly way. Good for filling in for objects you want to -hide. If $form.f1 is a RecursiveNull object, then -$form.f1.anything["you"].might("use") will resolve to the empty string. - -This module was contributed by Ian Bicking. -""" - -class RecursiveNull: - __doc__ = __doc__ # Use the module's docstring for the class's docstring. - def __getattr__(self, attr): - return self - def __getitem__(self, item): - return self - def __call__(self, *vars, **kw): - return self - def __str__(self): - return '' - def __repr__(self): - return '' - def __nonzero__(self): - return 0 - diff --git a/cobbler/Cheetah/Tools/SiteHierarchy.py b/cobbler/Cheetah/Tools/SiteHierarchy.py deleted file mode 100644 index d4a92e1..0000000 --- a/cobbler/Cheetah/Tools/SiteHierarchy.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python -# $Id: SiteHierarchy.py,v 1.1 2001/10/11 03:25:54 tavis_rudd Exp $ -"""Create menus and crumbs from a site hierarchy. - -You define the site hierarchy as lists/tuples. Each location in the hierarchy -is a (url, description) tuple. Each list has the base URL/text in the 0 -position, and all the children coming after it. Any child can be a list, -representing further depth to the hierarchy. See the end of the file for an -example hierarchy. - -Use Hierarchy(contents, currentURL), where contents is this hierarchy, and -currentURL is the position you are currently in. The menubar and crumbs methods -give you the HTML output. - -There are methods you can override to customize the HTML output. - -Meta-Data -================================================================================ -Author: Ian Bicking <ianb@colorstudy.com> -Version: $Revision: 1.1 $ -Start Date: 2001/07/23 -Last Revision Date: $Date: 2001/10/11 03:25:54 $ -""" -__author__ = "Ian Bicking <ianb@colorstudy.com>" -__version__ = "$Revision: 1.1 $"[11:-2] - -################################################## -## DEPENDENCIES -import string -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO - - -################################################## -## GLOBALS & CONSTANTS - -True, False = (1==1), (0==1) - -################################################## -## CLASSES - -class Hierarchy: - def __init__(self, hierarchy, currentURL, prefix='', menuCSSClass=None, - crumbCSSClass=None): - """ - hierarchy is described above, currentURL should be somewhere in - the hierarchy. prefix will be added before all of the URLs (to - help mitigate the problems with absolute URLs), and if given, - cssClass will be used for both links *and* nonlinks. - """ - - self._contents = hierarchy - self._currentURL = currentURL - if menuCSSClass: - self._menuCSSClass = ' class="%s"' % menuCSSClass - else: - self._menuCSSClass = '' - if crumbCSSClass: - self._crumbCSSClass = ' class="%s"' % crumbCSSClass - else: - self._crumbCSSClass = '' - self._prefix=prefix - - - ## Main output methods - - def menuList(self, menuCSSClass=None): - """An indented menu list""" - if menuCSSClass: - self._menuCSSClass = ' class="%s"' % menuCSSClass - - stream = StringIO() - for item in self._contents[1:]: - self._menubarRecurse(item, 0, stream) - return stream.getvalue() - - def crumbs(self, crumbCSSClass=None): - """The home>where>you>are crumbs""" - if crumbCSSClass: - self._crumbCSSClass = ' class="%s"' % crumbCSSClass - - path = [] - pos = self._contents - while 1: - ## This is not the fastest algorithm, I'm afraid. - ## But it probably won't be for a huge hierarchy anyway. - foundAny = False - path.append(pos[0]) - for item in pos[1:]: - if self._inContents(item): - if type(item) is type(()): - path.append(item) - break - else: - pos = item - foundAny = True - break - if not foundAny: - break - if len(path) == 1: - return self.emptyCrumb() - return string.join(map(lambda x, self=self: self.crumbLink(x[0], x[1]), - path), self.crumbSeperator()) + \ - self.crumbTerminator() - - ## Methods to control the Aesthetics - # - override these methods for your own look - - def menuLink(self, url, text, indent): - if url == self._currentURL or self._prefix + url == self._currentURL: - return '%s<B%s>%s</B> <BR>\n' % (' '*2*indent, - self._menuCSSClass, text) - else: - return '%s<A HREF="%s%s"%s>%s</A> <BR>\n' % \ - (' '*2*indent, self._prefix, url, - self._menuCSSClass, text) - - def crumbLink(self, url, text): - if url == self._currentURL or self._prefix + url == self._currentURL: - return '<B%s>%s</B>' % (text, self._crumbCSSClass) - else: - return '<A HREF="%s%s"%s>%s</A>' % \ - (self._prefix, url, self._crumbCSSClass, text) - - def crumbSeperator(self): - return ' > ' - - def crumbTerminator(self): - return '' - - def emptyCrumb(self): - """When you are at the homepage""" - return '' - - ## internal methods - - def _menubarRecurse(self, contents, indent, stream): - if type(contents) is type(()): - url, text = contents - rest = [] - else: - url, text = contents[0] - rest = contents[1:] - stream.write(self.menuLink(url, text, indent)) - if self._inContents(contents): - for item in rest: - self._menubarRecurse(item, indent+1, stream) - - def _inContents(self, contents): - if type(contents) is type(()): - return self._currentURL == contents[0] - for item in contents: - if self._inContents(item): - return True - return False - -################################################## -## from the command line - -if __name__ == '__main__': - hierarchy = [('/', 'home'), - ('/about', 'About Us'), - [('/services', 'Services'), - [('/services/products', 'Products'), - ('/services/products/widget', 'The Widget'), - ('/services/products/wedge', 'The Wedge'), - ('/services/products/thimble', 'The Thimble'), - ], - ('/services/prices', 'Prices'), - ], - ('/contact', 'Contact Us'), - ] - - for url in ['/', '/services', '/services/products/widget', '/contact']: - print '<p>', '='*50 - print '<br> %s: <br>\n' % url - n = Hierarchy(hierarchy, url, menuCSSClass='menu', crumbCSSClass='crumb', - prefix='/here') - print n.menuList() - print '<p>', '-'*50 - print n.crumbs() diff --git a/cobbler/Cheetah/Tools/__init__.py b/cobbler/Cheetah/Tools/__init__.py deleted file mode 100644 index 506503b..0000000 --- a/cobbler/Cheetah/Tools/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -"""This package contains classes, functions, objects and packages contributed - by Cheetah users. They are not used by Cheetah itself. There is no - guarantee that this directory will be included in Cheetah releases, that - these objects will remain here forever, or that they will remain - backward-compatible. -""" - -# vim: shiftwidth=5 tabstop=5 expandtab |