def __init__(self, imm, addr, heap = 0x0, log = None ): """ Win32 Heap Lookaside list """ UserList.__init__(self) if not log: log = imm.Log self.log = log self.imm = imm self.heap = heap self.Lookaside = [] LookSize = PLook(self.imm, 0x0).getSize() mem = imm.readMemory(addr, LookSize * HEAP_MAX_FREELIST) for ndx in range(0, HEAP_MAX_FREELIST): base_addr = addr + ndx * LookSize l = PLook(self.imm, base_addr, mem[ ndx * LookSize : ndx * LookSize + LookSize ], self.heap ) self.data.append(l) next = l.ListHead while next and next != base_addr: l.append( next ) try: next = self.imm.readLong(next) except: break
def _add_default_row(self): cols = [0] * self.column_size row = UserList(cols) row.context = [] row.committed = False self.rows.append(row) return row
def __init__(self, numYears, quartersNotUsed, coursesTakenFileName, courseList, currentQuarter): """inits the parameters and objects in the schedule object""" UserList.__init__(self) self.numYears = numYears self.quartersNotUsed = quartersNotUsed # A - Autumn/Fall, W - Winter, Sp - Spring S - Summer self.quarters = quarterAbbrev = ['A', 'W', 'Sp', 'S'] # keeps track of courses added to the schedule self.coursesTaken = [] # the list of courses to be assigned to the quarters self.courseList = courseList # file name of courses taken so that they can be loaded into their respective quarters self.coursesTakenFileName = coursesTakenFileName # sets the total difficulty self.totalDifficulty = courseList.returnTotalDifficulty() # inits the difficulty upper bound self.difficultyUpperBound = float(courseList.returnTotalDifficulty()/courseList.returnNum()) # quarter to start planning {quarter : q, year : y} self.start = currentQuarter
def append(self, element): if self.feature_no: assert self.feature_no == element.feature_no() else: self.feature_no = element.feature_no() UserList.append(self, element) self.init_precomputed()
def __setitem__(self, i, item): #print "------- %s::__setitem__ -------" % self._attributes[SELF][NAME] child = self._attributes[SELF][CHILDKEYS][0] self.checkType(child, item) if isinstance(item, GenClass): item._setParent(self) UserList.__setitem__(self, i, item)
def __init__(self, sFilename, sFormat): # The list stores all information contained in the file UserList.__init__(self) self.sFilename = sFilename self.sFormat = sFormat self.stylesheet = None assert self.sFormat in ["fixed", "free"]
def __init__(self,filename='',encoding='utf-8',linesep='\n'): UserList.__init__(self) if filename: self.linesep=linesep self.encoding=encoding self.filename=filename self.load()
def __init__(self, docstring=DEFAULTS['docstring'], options=DEFAULTS['options'], default=[], optional=DEFAULTS['optional'], values=DEFAULTS['values'], category=DEFAULTS['category'], callback=DEFAULTS['callback'], synopsis=DEFAULTS['synopsis'], environ=DEFAULTS['environ'], registry=DEFAULTS['registry'], delim=',', range=[1,'*'], mandatory=None, name=DEFAULTS['name'], source=DEFAULTS['source'], template=StringOption): """ Initialize a multi option This class is initialized with the same options as the Option class with one addition: delim. The 'delim' argument specifies what the delimiter is for each item in the list. If the delimiter is 'None' or whitespace, each item in the list is assumed to be delimited by whitespace. """ self.delim = delim self.range = range assert not issubclass(template, MultiOption), \ 'MultiOptions can not have a MultiOption as a template' assert issubclass(template, GenericOption), \ 'Templates must be a subclass of GenericOption' self.template = template(options=options,name=name,values=values) UserList.__init__(self, []) GenericOption.initialize(self, locals())
def __init__(self, docstring=DEFAULTS['docstring'], options=DEFAULTS['options'], default=[], optional=DEFAULTS['optional'], values=DEFAULTS['values'], category=DEFAULTS['category'], callback=DEFAULTS['callback'], synopsis=DEFAULTS['synopsis'], environ=DEFAULTS['environ'], registry=DEFAULTS['registry'], delim=' ', range=[1,'*'], mandatory=None, name=DEFAULTS['name'], source=DEFAULTS['source'], template=StringOption): """ Initialize a multi argument """ self.delim = delim self.range = range assert not issubclass(template, MultiArgument), \ 'MultiArguments can not have a MultiArguments as a template' assert not issubclass(template, MultiOption), \ 'MultiOptions can not have a MultiOptions as a template' assert issubclass(template, GenericOption), \ 'Templates must be a subclass of GenericOption' self.template = template(options=options,name=name,values=values) UserList.__init__(self, []) GenericOption.initialize(self, locals())
def test_reverse(self): u = UserList((0, 1)) u2 = u[:] u.reverse() self.assertEqual(u, [1, 0]) u.reverse() self.assertEqual(u, u2)
def __init__(self, name="Default deck", initlist=None): ''' Create a deck ''' UserList.__init__(self, initlist) self.name = name logging.info("Creating %s" % name)
def __setslice__(self, i, j, seq): old=list.__getslice__(self, i, j) for f in old: self.__unregister_field(f) for f in seq: self.__register_field(f) list.__setslice__(self, i, j, seq)
def __init__(self, file_name=None): """Creates a ReservationList composed by Reservation objects, from a file with a list of reservations. Requires: If given, file_name is str with the name of a .txt file containing a list of reservations organized as in the examples provided in the general specification (omitted here for the sake of readability). Ensures: if file_name is given: a ReservationList, composed by objects of class Service that correspond to the services listed in file with name file_name. if file_name is none: a empty ServiceList.""" UserList.__init__(self) if file_name is not None: inFile = FileUtil(file_name) for line in inFile.getContent(): reservData = line.rstrip().split(", ") reservClient = reservData[ReservationsList.INDEXClientNameInReservation] reservRequestedStartTime = Time(reservData[ReservationsList.INDEXRequestedStartHour]) reservRequestedEndTime = Time(reservData[ReservationsList.INDEXRequestedEndHour]) reservCircuit = reservData[ReservationsList.INDEXCircuitInReservation] reservCircuitKms = reservData[ReservationsList.INDEXCircuitKmsInReservation] newReserv = Reservation(reservClient, reservRequestedStartTime, reservRequestedEndTime, reservCircuit, reservCircuitKms) self.append(newReserv)
def __delitem__(self, index): try: x=list.__getitem__(self, index) except IndexError: raise IndexError, "index out of range" self.__unregister_field(x) list.__delitem__(self, index)
def testSequenceArrayConversionTypeChecking(self): """Test error handling for sequence conversion to array arguments.""" from Python.Test import ArrayConversionTest from Python.Test import Spam from UserList import UserList # This should work, because null / None is a valid value in an # array of reference types. items = UserList() for i in range(10): items.append(Spam(str(i))) items[1] = None result = ArrayConversionTest.EchoRange(items) self.failUnless(result[0].__class__ == Spam) self.failUnless(result[1] == None) self.failUnless(len(result) == 10) def test(items=items): items[1] = 1 result = ArrayConversionTest.EchoRange(items) self.failUnlessRaises(TypeError, test) def test(items=items): items[1] = "spam" result = ArrayConversionTest.EchoRange(items) self.failUnlessRaises(TypeError, test)
def __setslice__ (self, i, j, collection): """L.__setslice__ (i, j, collection) -> L[i:j] = collection Raises a TypeError, if the passed collection argument does not inherit from the ListItemCollection class. """ if not isinstance (collection, ListItemCollection): raise TypeError ("collection must inherit from ListItemCollection") old = UserList.__getslice__ (self, i, j) UserList.__setslice__ (self, i, j, collection[:]) new = UserList.__getslice__ (self, i, j) # Clean up the old ones. for item in old: item.collection = None self._length -= 1 del item # Set the relations for the new ones. for item in new: item.collection = self self._length += 1 if self.list_changed: self.list_changed (self)
def append(self, light): if self.enforce_limit: _constrain_lights(len(self) + 1) light.light_no = lightno(len(self)) else: light.light_no = vlightno(len(self)) UserList.append(self, light)
def __init__(self, data=None, name=None, kind=None, element=None): self.value = 0 self.free_spaces = 8 self.name = name UserList.__init__(self) if data == None: # The code below creates 4 units of element with a comp # of (4,2,2,0). Each unit is equiped with a unique weapon. if kind == 'mins': if element != None: s = Stone() s[element] = 4 s[OPP[element]] = 0 for o in ORTH[element]: s[o] = 2 for wep in WEP_LIST: scient = Scient(element, s) scient.equip(eval(wep)(element, Stone())) scient.name = "Ms. " + wep self.append(scient) else: raise("Kind requires element from %s." %ELEMENTS) if self.name == None: self.name = element + " " + 'mins' return if isinstance(data, list): for x in data: self.append(x) else: self.append(data)
def __init__(self, seq=None, fieldmapper=_donothing, storelists=1): list.__init__(self, seq or []) self.fieldmapper=fieldmapper self.__d={} self.storelists=storelists if seq: for s in seq: self.__register_field(s)
def sort (self, cmp=None, key=None, reverse=False): """L.sort (...) -> None Stable in place sort for the ListItemCollection. """ UserList.sort (self, cmp, key, reverse) if self.list_changed: self.list_changed (self)
def __init__(self, l = None): if isinstance(l, basestring): UserList.__init__(self) self.add(l) return if l: l = [ PBXType.Convert(v) for v in l ] UserList.__init__(self, l)
def __init__(self, quarter, year, courses = [], currentDifficulty = 0): """inits the quarter object""" UserList.__init__(self) self.quarter = quarter self.year = year # keeps track of the current difficulty of the quarter self.currentDifficulty = currentDifficulty
def __init__(self, f=None, procmail=""): UserList.__init__(self) if procmail: self.procmail = "|%s " % procmail else: self.procmail = "" self.pmlen = len(self.procmail) self.addrs = self.data if f: if hasattr(f, "read"): self.parse(f.read()) else: self.parse(f)
def __init__(self): UserList.__init__(self) self.tables = {} # _table_names entries relate a paramter line name to a table and # its Entry object name. The tables are defined in external text # files. for param, tabledata in self.__class__._table_names.items(): tablename, rowclass = tabledata self.tables[param] = (ParameterTable(tablename), rowclass)
def __init__(self, data=[]): UserList.__init__(self) self.feature_no = None self.name = None self.class_omega = None self.init_precomputed() self.classadmin = pylib_basics.name_number_hash() for i in data: self.append(i)
def test_extend(self): u1 = UserList((0, )) u2 = UserList((0, 1)) u = u1[:] u.extend(u2) self.assertEqual(u, u1 + u2) u = UserList("spam") u.extend("eggs") self.assertEqual(u, list("spameggs"))
def __setitem__(self, index, item): if not isinstance(index, int): raise TypeError, "cannot set items by key, only by index" try: x=list.__getitem__(self, index) except IndexError: raise IndexError, "index out of range" self.__unregister_field(x) self.__register_field(item) list.__setitem__(self, index, item)
def remove (self, item): """L.remove (...) -> None Removes the first occurance of item from the ListItemCollection. """ UserList.remove (self, item) item.collection = None self._length -= 1 if self.list_changed: self.list_changed (self)
def append(self, *others): for other in others: if not other: continue if isinstance(other, Frag) or \ type(other) == type(()) or \ type(other) == type([]): List.extend(self, other) else: List.append(self, other)
def count (self, item): """L.count (...) -> int Returns the number of occurences of the ListItem. Raises a TypeError, if the passed argument does not inherit from the ListItem class. """ if not isinstance (item, ListItem): raise TypeError ("item must inherit from ListItem") UserList.count (self, item)
def __init__(self, perforceClient, rootPath, lowerBound=0): PerforceObject.__init__(self, perforceClient) UserList.__init__(self) self.rootPath = rootPath self.getChanges(rootPath, lowerBound)
def testWritelinesIntegersUserList(self): # verify writelines with integers in UserList l = UserList([1,2,3]) self.assertRaises(TypeError, self.f.writelines, l)
def __init__(self, app): SelectDialogTreeData.__init__(self) self.all_games_gi = map(app.gdb.get, app.gdb.getGamesIdSortedByName()) self.no_games = [ SelectGameLeaf(None, None, _("(no games)"), None), ] # s_by_type = s_oriental = s_special = s_original = s_contrib = s_mahjongg = None g = [] for data in ( GI.SELECT_GAME_BY_TYPE, GI.SELECT_ORIENTAL_GAME_BY_TYPE, GI.SELECT_SPECIAL_GAME_BY_TYPE, GI.SELECT_ORIGINAL_GAME_BY_TYPE, GI.SELECT_CONTRIB_GAME_BY_TYPE, ): gg = [] for name, select_func in data: if name is None or not filter(select_func, self.all_games_gi): continue gg.append(SelectGameNode(None, _(name), select_func)) g.append(gg) select_mahjongg_game = lambda gi: gi.si.game_type == GI.GT_MAHJONGG gg = None if filter(select_mahjongg_game, self.all_games_gi): gg = SelectGameNode(None, _("Mahjongg Games"), select_mahjongg_game) g.append(gg) if g[0]: s_by_type = SelectGameNode(None, _("French games"), tuple(g[0]), expanded=1) if g[1]: s_oriental = SelectGameNode(None, _("Oriental Games"), tuple(g[1])) if g[2]: s_special = SelectGameNode(None, _("Special Games"), tuple(g[2])) if g[3]: s_original = SelectGameNode(None, _("Original Games"), tuple(g[3])) ## if g[4]: ## s_contrib = SelectGameNode(None, "Contributed Games", tuple(g[4])) if g[5]: s_mahjongg = g[5] # s_by_compatibility, gg = None, [] for name, games in GI.GAMES_BY_COMPATIBILITY: select_func = lambda gi, games=games: gi.id in games if name is None or not filter(select_func, self.all_games_gi): continue gg.append(SelectGameNode(None, name, select_func)) if 1 and gg: s_by_compatibility = SelectGameNode(None, _("by Compatibility"), tuple(gg)) # s_by_pysol_version, gg = None, [] for name, games in GI.GAMES_BY_PYSOL_VERSION: select_func = lambda gi, games=games: gi.id in games if name is None or not filter(select_func, self.all_games_gi): continue name = _("New games in v. ") + name gg.append(SelectGameNode(None, name, select_func)) if 1 and gg: s_by_pysol_version = SelectGameNode(None, _("by PySol version"), tuple(gg)) s_by_inventors, gg = None, [] for name, games in GI.GAMES_BY_INVENTORS: select_func = lambda gi, games=games: gi.id in games if name is None or not filter(select_func, self.all_games_gi): continue gg.append(SelectGameNode(None, name, select_func)) if 1 and gg: s_by_inventors = SelectGameNode(None, _("by Inventors"), tuple(gg)) # ul_alternate_names = UserList( list(app.gdb.getGamesTuplesSortedByAlternateName())) # self.rootnodes = filter( None, ( SelectGameNode(None, _("All Games"), None, expanded=0), SelectGameNode(None, _("Alternate Names"), ul_alternate_names), SelectGameNode(None, _("Popular Games"), lambda gi: gi.si.game_flags & GI.GT_POPULAR), s_by_type, s_mahjongg, s_oriental, s_special, SelectGameNode(None, _("Custom Games"), lambda gi: gi.si.game_type == GI.GT_CUSTOM), SelectGameNode(None, _('by Skill Level'), ( SelectGameNode(None, _('Luck only'), lambda gi: gi.skill_level == GI.SL_LUCK), SelectGameNode( None, _('Mostly luck'), lambda gi: gi.skill_level == GI.SL_MOSTLY_LUCK), SelectGameNode( None, _('Balanced'), lambda gi: gi.skill_level == GI.SL_BALANCED), SelectGameNode( None, _('Mostly skill'), lambda gi: gi.skill_level == GI.SL_MOSTLY_SKILL), SelectGameNode(None, _('Skill only'), lambda gi: gi.skill_level == GI.SL_SKILL), )), SelectGameNode( None, _("by Game Feature"), ( SelectGameNode(None, _("by Number of Cards"), ( SelectGameNode(None, _("32 cards"), lambda gi: gi.si.ncards == 32), SelectGameNode(None, _("48 cards"), lambda gi: gi.si.ncards == 48), SelectGameNode(None, _("52 cards"), lambda gi: gi.si.ncards == 52), SelectGameNode(None, _("64 cards"), lambda gi: gi.si.ncards == 64), SelectGameNode(None, _("78 cards"), lambda gi: gi.si.ncards == 78), SelectGameNode(None, _("104 cards"), lambda gi: gi.si.ncards == 104), SelectGameNode(None, _("144 cards"), lambda gi: gi.si.ncards == 144), SelectGameNode( None, _("Other number"), lambda gi: gi.si.ncards not in (32, 48, 52, 64, 78, 104, 144)), )), SelectGameNode(None, _("by Number of Decks"), ( SelectGameNode(None, _("1 deck games"), lambda gi: gi.si.decks == 1), SelectGameNode(None, _("2 deck games"), lambda gi: gi.si.decks == 2), SelectGameNode(None, _("3 deck games"), lambda gi: gi.si.decks == 3), SelectGameNode(None, _("4 deck games"), lambda gi: gi.si.decks == 4), )), SelectGameNode( None, _("by Number of Redeals"), ( SelectGameNode(None, _("No redeal"), lambda gi: gi.si.redeals == 0), SelectGameNode(None, _("1 redeal"), lambda gi: gi.si.redeals == 1), SelectGameNode(None, _("2 redeals"), lambda gi: gi.si.redeals == 2), SelectGameNode(None, _("3 redeals"), lambda gi: gi.si.redeals == 3), SelectGameNode(None, _("Unlimited redeals"), lambda gi: gi.si.redeals == -1), ## SelectGameNode(None, "Variable redeals", ## lambda gi: gi.si.redeals == -2), SelectGameNode( None, _("Other number of redeals"), lambda gi: gi.si.redeals not in (-1, 0, 1, 2, 3)), )), s_by_compatibility, )), s_by_pysol_version, s_by_inventors, SelectGameNode(None, _("Other Categories"), ( SelectGameNode( None, _("Games for Children (very easy)"), lambda gi: gi.si.game_flags & GI.GT_CHILDREN), SelectGameNode(None, _("Games with Scoring"), lambda gi: gi.si.game_flags & GI.GT_SCORE), SelectGameNode( None, _("Games with Separate Decks"), lambda gi: gi.si.game_flags & GI.GT_SEPARATE_DECKS), SelectGameNode(None, _("Open Games (all cards visible)"), lambda gi: gi.si.game_flags & GI.GT_OPEN), SelectGameNode( None, _("Relaxed Variants"), lambda gi: gi.si.game_flags & GI.GT_RELAXED), )), s_original, s_contrib, ))
def cstmString(self, emptyword): if self == []: return emptyword return string.replace(UserList.__str__(self)[1:-1], '\'', '')
def g(x, *y, **z): print x, y, z def h(j=1, a=2, h=3): print j, a, h f() f(1) f(1, 2) f(1, 2, 3) f(1, 2, 3, *(4, 5)) f(1, 2, 3, *[4, 5]) f(1, 2, 3, *UserList([4, 5])) f(1, 2, 3, **{'a': 4, 'b': 5}) f(1, 2, 3, *(4, 5), **{'a': 6, 'b': 7}) f(1, 2, 3, x=4, y=5, *(6, 7), **{'a': 8, 'b': 9}) try: g() except TypeError, err: print "TypeError:", err else: print "should raise TypeError: not enough arguments; expected 1, got 0" try: g(*()) except TypeError, err: print "TypeError:", err
def __init__(self, seq=[]): UserList.__init__(self, seq) self.unique = True
def __init__(self, initlist=None): UserList.__init__(self, initlist)
def __setitem__(self, i, item): validateInformation(item) UserList.__setitem__(self, i, item)
def append(self, item): validateInformation(item) UserList.append(self, item)
def test_precomputed(self): for func, data, elem, expected in self.precomputedCases: self.assertEqual(func(data, elem), expected) self.assertEqual(func(UserList(data), elem), expected)
def __init__(self, list=None): if list: for obj in list: validateInformation(obj) UserList.__init__(self, list)
if chr(32) != ' ': raise TestFailed, 'chr(32)' if chr(65) != 'A': raise TestFailed, 'chr(65)' if chr(97) != 'a': raise TestFailed, 'chr(97)' # cmp print 'cmp' if cmp(-1, 1) != -1: raise TestFailed, 'cmp(-1, 1)' if cmp(1, -1) != 1: raise TestFailed, 'cmp(1, -1)' if cmp(1, 1) != 0: raise TestFailed, 'cmp(1, 1)' # verify that circular objects are handled a = [] a.append(a) b = [] b.append(b) from UserList import UserList c = UserList() c.append(c) if cmp(a, b) != 0: raise TestFailed, "cmp(%s, %s)" % (a, b) if cmp(b, c) != 0: raise TestFailed, "cmp(%s, %s)" % (b, c) if cmp(c, a) != 0: raise TestFailed, "cmp(%s, %s)" % (c, a) if cmp(a, c) != 0: raise TestFailed, "cmp(%s, %s)" % (a, c) # okay, now break the cycles a.pop() b.pop() c.pop() print 'coerce' if fcmp(coerce(1, 1.1), (1.0, 1.1)): raise TestFailed, 'coerce(1, 1.1)' if coerce(1, 1L) != (1L, 1L): raise TestFailed, 'coerce(1, 1L)' if fcmp(coerce(1L, 1.1), (1.0, 1.1)): raise TestFailed, 'coerce(1L, 1.1)'
def run_method_tests(test): """Run all tests that exercise a method of a string object""" test('capitalize', ' hello ', ' hello ') test('capitalize', 'hello ', 'Hello ') test('capitalize', 'aaaa', 'Aaaa') test('capitalize', 'AaAa', 'Aaaa') test('count', 'aaa', 3, 'a') test('count', 'aaa', 0, 'b') test('find', 'abcdefghiabc', 0, 'abc') test('find', 'abcdefghiabc', 9, 'abc', 1) test('find', 'abcdefghiabc', -1, 'def', 4) test('rfind', 'abcdefghiabc', 9, 'abc') test('lower', 'HeLLo', 'hello') test('lower', 'hello', 'hello') test('upper', 'HeLLo', 'HELLO') test('upper', 'HELLO', 'HELLO') test('title', ' hello ', ' Hello ') test('title', 'hello ', 'Hello ') test('title', "fOrMaT thIs aS titLe String", 'Format This As Title String') test('title', "fOrMaT,thIs-aS*titLe;String", 'Format,This-As*Title;String') test('title', "getInt", 'Getint') test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi') test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi', 8) test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi', 4) test('expandtabs', 'abc\r\nab\tdef\ng\thi', 'abc\r\nab def\ng hi', 4) test('islower', 'a', 1) test('islower', 'A', 0) test('islower', '\n', 0) test('islower', 'abc', 1) test('islower', 'aBc', 0) test('islower', 'abc\n', 1) test('isupper', 'a', 0) test('isupper', 'A', 1) test('isupper', '\n', 0) test('isupper', 'ABC', 1) test('isupper', 'AbC', 0) test('isupper', 'ABC\n', 1) test('istitle', 'a', 0) test('istitle', 'A', 1) test('istitle', '\n', 0) test('istitle', 'A Titlecased Line', 1) test('istitle', 'A\nTitlecased Line', 1) test('istitle', 'A Titlecased, Line', 1) test('istitle', 'Not a capitalized String', 0) test('istitle', 'Not\ta Titlecase String', 0) test('istitle', 'Not--a Titlecase String', 0) test('isalpha', 'a', 1) test('isalpha', 'A', 1) test('isalpha', '\n', 0) test('isalpha', 'abc', 1) test('isalpha', 'aBc123', 0) test('isalpha', 'abc\n', 0) test('isalnum', 'a', 1) test('isalnum', 'A', 1) test('isalnum', '\n', 0) test('isalnum', '123abc456', 1) test('isalnum', 'a1b3c', 1) test('isalnum', 'aBc000 ', 0) test('isalnum', 'abc\n', 0) # join now works with any sequence type test('join', ' ', 'a b c d', ['a', 'b', 'c', 'd']) test('join', '', 'abcd', ('a', 'b', 'c', 'd')) test('join', ' ', 'w x y z', Sequence()) test('join', 'a', 'abc', ('abc', )) test('join', 'a', 'z', UserList(['z'])) if have_unicode: test('join', unicode('.'), unicode('a.b.c'), ['a', 'b', 'c']) test('join', '.', unicode('a.b.c'), [unicode('a'), 'b', 'c']) test('join', '.', unicode('a.b.c'), ['a', unicode('b'), 'c']) test('join', '.', unicode('a.b.c'), ['a', 'b', unicode('c')]) test('join', '.', TypeError, ['a', unicode('b'), 3]) for i in [5, 25, 125]: test('join', '-', ((('a' * i) + '-') * i)[:-1], ['a' * i] * i) test('join', ' ', TypeError, BadSeq1()) test('join', ' ', 'a b c', BadSeq2()) test('splitlines', "abc\ndef\n\rghi", ['abc', 'def', '', 'ghi']) test('splitlines', "abc\ndef\n\r\nghi", ['abc', 'def', '', 'ghi']) test('splitlines', "abc\ndef\r\nghi", ['abc', 'def', 'ghi']) test('splitlines', "abc\ndef\r\nghi\n", ['abc', 'def', 'ghi']) test('splitlines', "abc\ndef\r\nghi\n\r", ['abc', 'def', 'ghi', '']) test('splitlines', "\nabc\ndef\r\nghi\n\r", ['', 'abc', 'def', 'ghi', '']) test('splitlines', "\nabc\ndef\r\nghi\n\r", ['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], 1) test('split', 'this is the split function', ['this', 'is', 'the', 'split', 'function']) test('split', 'a|b|c|d', ['a', 'b', 'c', 'd'], '|') test('split', 'a|b|c|d', ['a', 'b', 'c|d'], '|', 2) test('split', 'a b c d', ['a', 'b c d'], None, 1) test('split', 'a b c d', ['a', 'b', 'c d'], None, 2) test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 3) test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 4) test('split', 'a b c d', ['a b c d'], None, 0) test('split', 'a b c d', ['a', 'b', 'c d'], None, 2) test('split', 'a b c d ', ['a', 'b', 'c', 'd']) test('strip', ' hello ', 'hello') test('lstrip', ' hello ', 'hello ') test('rstrip', ' hello ', ' hello') test('strip', 'hello', 'hello') # strip/lstrip/rstrip with None arg test('strip', ' hello ', 'hello', None) test('lstrip', ' hello ', 'hello ', None) test('rstrip', ' hello ', ' hello', None) test('strip', 'hello', 'hello', None) # strip/lstrip/rstrip with str arg test('strip', 'xyzzyhelloxyzzy', 'hello', 'xyz') test('lstrip', 'xyzzyhelloxyzzy', 'helloxyzzy', 'xyz') test('rstrip', 'xyzzyhelloxyzzy', 'xyzzyhello', 'xyz') test('strip', 'hello', 'hello', 'xyz') # strip/lstrip/rstrip with unicode arg test('strip', 'xyzzyhelloxyzzy', u'hello', u'xyz') test('lstrip', 'xyzzyhelloxyzzy', u'helloxyzzy', u'xyz') test('rstrip', 'xyzzyhelloxyzzy', u'xyzzyhello', u'xyz') test('strip', 'hello', u'hello', u'xyz') test('swapcase', 'HeLLo cOmpUteRs', 'hEllO CoMPuTErS') test('translate', 'xyzabcdef', 'xyzxyz', transtable, 'def') table = string.maketrans('a', 'A') test('translate', 'abc', 'Abc', table) test('translate', 'xyz', 'xyz', table) test('replace', 'one!two!three!', 'one@two!three!', '!', '@', 1) test('replace', 'one!two!three!', 'onetwothree', '!', '') test('replace', 'one!two!three!', 'one@two@three!', '!', '@', 2) test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 3) test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 4) test('replace', 'one!two!three!', 'one!two!three!', '!', '@', 0) test('replace', 'one!two!three!', 'one@two@three@', '!', '@') test('replace', 'one!two!three!', 'one!two!three!', 'x', '@') test('replace', 'one!two!three!', 'one!two!three!', 'x', '@', 2) # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with # MemoryError due to empty result (platform malloc issue when requesting # 0 bytes). test('replace', '123', '', '123', '') test('replace', '123123', '', '123', '') test('replace', '123x123', 'x', '123', '') test('startswith', 'hello', 1, 'he') test('startswith', 'hello', 1, 'hello') test('startswith', 'hello', 0, 'hello world') test('startswith', 'hello', 1, '') test('startswith', 'hello', 0, 'ello') test('startswith', 'hello', 1, 'ello', 1) test('startswith', 'hello', 1, 'o', 4) test('startswith', 'hello', 0, 'o', 5) test('startswith', 'hello', 1, '', 5) test('startswith', 'hello', 0, 'lo', 6) test('startswith', 'helloworld', 1, 'lowo', 3) test('startswith', 'helloworld', 1, 'lowo', 3, 7) test('startswith', 'helloworld', 0, 'lowo', 3, 6) test('endswith', 'hello', 1, 'lo') test('endswith', 'hello', 0, 'he') test('endswith', 'hello', 1, '') test('endswith', 'hello', 0, 'hello world') test('endswith', 'helloworld', 0, 'worl') test('endswith', 'helloworld', 1, 'worl', 3, 9) test('endswith', 'helloworld', 1, 'world', 3, 12) test('endswith', 'helloworld', 1, 'lowo', 1, 7) test('endswith', 'helloworld', 1, 'lowo', 2, 7) test('endswith', 'helloworld', 1, 'lowo', 3, 7) test('endswith', 'helloworld', 0, 'lowo', 4, 7) test('endswith', 'helloworld', 0, 'lowo', 3, 8) test('endswith', 'ab', 0, 'ab', 0, 1) test('endswith', 'ab', 0, 'ab', 0, 0) test('zfill', '123', '123', 2) test('zfill', '123', '123', 3) test('zfill', '123', '0123', 4) test('zfill', '+123', '+123', 3) test('zfill', '+123', '+123', 4) test('zfill', '+123', '+0123', 5) test('zfill', '-123', '-123', 3) test('zfill', '-123', '-123', 4) test('zfill', '-123', '-0123', 5) test('zfill', '', '000', 3) test('zfill', '34', '34', 1) test('zfill', '34', '0034', 4) # Encoding/decoding codecs = [('rot13', 'uryyb jbeyq'), ('base64', 'aGVsbG8gd29ybGQ=\n'), ('hex', '68656c6c6f20776f726c64'), ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')] for encoding, data in codecs: test('encode', 'hello world', data, encoding) test('decode', data, 'hello world', encoding) # zlib is optional, so we make the test optional too... try: import zlib except ImportError: pass else: data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]' verify('hello world'.encode('zlib') == data) verify(data.decode('zlib') == 'hello world')
def __contains__(self, item): if item == None: return True else: return UserList.__contains__(self, item)
def __setitem__(self, key, value): UserList.__setitem__(self, PBXType.Convert(key), PBXType.Convert(value))
def __init__(self, list, emptyword=''): UserList.__init__(self, list) self.emptyword = emptyword
def __init__(self, seq=[]): UserList.__init__(self, Split(seq))
"Demonstrate what happens with/without DEEPCOPY --fpm" import gnosis.xml.pickle as xml_pickle from gnosis.xml.pickle.util import setParanoia, setDeepCopy from UserList import UserList import sys import funcs funcs.set_parser() a = (1,2,3) b = [4,5,6] c = {'a':1,'b':2,'c':3,'d':[100,200,300]} dd = c['d'] # make sure subitems get refchecked uu = UserList([10,11,12]) u = UserList([[uu,c,b,a],[a,b,c,uu],[c,a,b,uu],dd]) print u # allow xml_pickle to read our namespace setParanoia(0) # by default, with references x = xml_pickle.dumps(u) print x del u g = xml_pickle.loads(x) print g # next, using DEEPCOPY
def __ne__(self, other): self.__make_unique() return UserList.__ne__(self, other)
def __setslice__(self, i, j, other): for obj in other: validateInformation(obj) UserList.__setslice__(self, i, j, other)
def __init__(self, items=None, eol=None, path=None, encoding='utf-8'): UserList.__init__(self, items or []) self._eol = eol self.path = path self.encoding = encoding
def __radd__(self, other): for obj in other: validateInformation(obj) UserList.__radd__(self, other)
def doit2(): u = UserList([1, 2, [(3, 4, 5), (6, 7, 8)], 3, UserList([0, 1, 2]), 4]) x = xml_pickle.dumps(u) print x g = thing_from_sax2(None, x) print g
def __init__(self): UserList.__init__(self) self.level = 0
def insert(self, i, item): validateInformation(item) UserList.insert(self, i, item)
return obj.__class__ == foo def mutate(self, obj): # a tricky self-ref obj.breakage = obj return XMLP_Mutated(obj) def unmutate(self, mobj): return mobj.obj my = foomu() mutate.add_mutator(my) f = foo() f.a = UserList([4, 5, 6]) f.b = "abc" #print f.a,f.b x = xml_pickle.dumps(f) #print x g = xml_pickle.loads(x) #print g.a,g.b if g.__class__ != foo or g.a != f.a or g.b != f.b: raise "ERROR(7)" mutate.remove_mutator(my) # handcoded selfrefs from dqm that caused problems (even # with xml_pickle-0.51) s = """<?xml version="1.0"?>
def __init__(self, sequence=[]): GObject.__init__(self) UserList.__init__(self, sequence)
def extend(self, other): for obj in other: validateInformation(obj) UserList.extend(self, other)
def __init__(self, filename=None): if isinstance(filename, str): UserList.__init__(self) self.readFilename(filename) else: UserList.__init__(self, filename)
def test_recursion(self): # Check that comparison for recursive objects fails gracefully from UserList import UserList a = UserList() b = UserList() a.append(b) b.append(a) self.assertRaises(RuntimeError, operator.eq, a, b) self.assertRaises(RuntimeError, operator.ne, a, b) self.assertRaises(RuntimeError, operator.lt, a, b) self.assertRaises(RuntimeError, operator.le, a, b) self.assertRaises(RuntimeError, operator.gt, a, b) self.assertRaises(RuntimeError, operator.ge, a, b) b.append(17) # Even recursive lists of different lengths are different, # but they cannot be ordered self.assert_(not (a == b)) self.assert_(a != b) self.assertRaises(RuntimeError, operator.lt, a, b) self.assertRaises(RuntimeError, operator.le, a, b) self.assertRaises(RuntimeError, operator.gt, a, b) self.assertRaises(RuntimeError, operator.ge, a, b) a.append(17) self.assertRaises(RuntimeError, operator.eq, a, b) self.assertRaises(RuntimeError, operator.ne, a, b) a.insert(0, 11) b.insert(0, 12) self.assert_(not (a == b)) self.assert_(a != b) self.assert_(a < b)