bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
12,200
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
12,201
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
12,202
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
12,203
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
12,204
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
def __getitem__(self, i): if i >= 0 and i < 3: return i raise IndexError
12,205
def __getitem__(self, i): if i >= 0 and i < 3: return i elif i == 3: raise BozoError else: raise IndexError
def __getitem__(self, i): if i >= 0 and i < 3: return i elif i == 3: raise BozoError else: raise IndexError
12,206
def __getitem__(self, i): if i >= 0 and i < 3: return i elif i == 3: raise BozoError else: raise IndexError
def __getitem__(self, i): if i >= 0 and i < 3: return i elif i == 3: raise BozoError else: raise IndexError
12,207
def copy(self): if self.__class__ is UserDict: return UserDict(self.data) import copy return copy.copy(self)
def copy(self): if self.__class__ is UserDict: return UserDict(self.data) import copy return copy.copy(self)
12,208
def test_set_boundary(self): eq = self.assertEqual # This one has no existing boundary parameter, but the Content-Type: # header appears fifth. msg = self._msgobj('msg_01.txt') msg.set_boundary('BOUNDARY') header, value = msg.items()[4] eq(header.lower(), 'content-type') eq(value, 'text/plain; charset=us-ascii; boundary="BOUNDARY"') # This one has a Content-Type: header, with a boundary, stuck in the # middle of its headers. Make sure the order is preserved; it should # be fifth. msg = self._msgobj('msg_04.txt') msg.set_boundary('BOUNDARY') header, value = msg.items()[4] eq(header.lower(), 'content-type') eq(value, 'multipart/mixed; boundary="BOUNDARY"') # And this one has no Content-Type: header at all. msg = self._msgobj('msg_03.txt') self.assertRaises(Errors.HeaderParseError, msg.set_boundary, 'BOUNDARY')
def test_set_boundary(self): eq = self.assertEqual # This one has no existing boundary parameter, but the Content-Type: # header appears fifth. msg = self._msgobj('msg_01.txt') msg.set_boundary('BOUNDARY') header, value = msg.items()[4] eq(header.lower(), 'content-type') eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"') # This one has a Content-Type: header, with a boundary, stuck in the # middle of its headers. Make sure the order is preserved; it should # be fifth. msg = self._msgobj('msg_04.txt') msg.set_boundary('BOUNDARY') header, value = msg.items()[4] eq(header.lower(), 'content-type') eq(value, 'multipart/mixed; boundary="BOUNDARY"') # And this one has no Content-Type: header at all. msg = self._msgobj('msg_03.txt') self.assertRaises(Errors.HeaderParseError, msg.set_boundary, 'BOUNDARY')
12,209
def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle_maintype_subtype(). If there's no handler for the full # MIME type, then dispatch to self._handle_maintype(). If that's # missing too, then dispatch to self._writeBody(). ctype = msg.get_type() if ctype is None: # No Content-Type: header so try the default handler self._writeBody(msg) else: # We do have a Content-Type: header. specific = UNDERSCORE.join(ctype.split('/')).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = msg.get_main_type().replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg)
def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle_maintype_subtype(). If there's no handler for the full # MIME type, then dispatch to self._handle_maintype(). If that's # missing too, then dispatch to self._writeBody(). ctype = msg.get_type() if ctype is None: # No Content-Type: header so try the default handler self._writeBody(msg) else: # We do have a Content-Type: header. specific = UNDERSCORE.join(ctype.split('/')).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = msg.get_main_type().replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg)
12,210
def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle_maintype_subtype(). If there's no handler for the full # MIME type, then dispatch to self._handle_maintype(). If that's # missing too, then dispatch to self._writeBody(). ctype = msg.get_type() if ctype is None: # No Content-Type: header so try the default handler self._writeBody(msg) else: # We do have a Content-Type: header. specific = UNDERSCORE.join(ctype.split('/')).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = msg.get_main_type().replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg)
def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle_maintype_subtype(). If there's no handler for the full # MIME type, then dispatch to self._handle_maintype(). If that's # missing too, then dispatch to self._writeBody(). ctype = msg.get_type() if ctype is None: # No Content-Type: header so try the default handler self._writeBody(msg) else: # We do have a Content-Type: header. specific = UNDERSCORE.join(ctype.split('/')).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = msg.get_main_type().replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg)
12,211
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
12,212
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
12,213
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
12,214
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
12,215
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has every been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
12,216
def _handle_multipart_digest(self, msg): self._handle_multipart(msg, isdigest=1)
def _handle_multipart_digest(self, msg): self._handle_multipart(msg, isdigest=1)
12,217
def _handle_message_delivery_status(self, msg): # We can't just write the headers directly to self's file object # because this will leave an extra newline between the last header # block and the boundary. Sigh. blocks = [] for part in msg.get_payload(): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g.flatten(part, unixfrom=0) text = s.getvalue() lines = text.split('\n') # Strip off the unnecessary trailing empty line if lines and lines[-1] == '': blocks.append(NL.join(lines[:-1])) else: blocks.append(text) # Now join all the blocks with an empty line. This has the lovely # effect of separating each block with an empty line, but not adding # an extra one after the last one. self._fp.write(NL.join(blocks))
def _handle_message_delivery_status(self, msg): # We can't just write the headers directly to self's file object # because this will leave an extra newline between the last header # block and the boundary. Sigh. blocks = [] for part in msg.get_payload(): s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=0) text = s.getvalue() lines = text.split('\n') # Strip off the unnecessary trailing empty line if lines and lines[-1] == '': blocks.append(NL.join(lines[:-1])) else: blocks.append(text) # Now join all the blocks with an empty line. This has the lovely # effect of separating each block with an empty line, but not adding # an extra one after the last one. self._fp.write(NL.join(blocks))
12,218
def _handle_message(self, msg): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) # The payload of a message/rfc822 part should be a multipart sequence # of length 1. The zeroth element of the list should be the Message # object for the subpart.Extract that object, stringify it, and write # that out. g.flatten(msg.get_payload(0), unixfrom=0) self._fp.write(s.getvalue())
def _handle_message(self, msg): s = StringIO() g = self.clone(s) # The payload of a message/rfc822 part should be a multipart sequence # of length 1. The zeroth element of the list should be the Message # object for the subpart.Extract that object, stringify it, and write # that out. g.flatten(msg.get_payload(0), unixfrom=0) self._fp.write(s.getvalue())
12,219
def _handle_message(self, msg): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) # The payload of a message/rfc822 part should be a multipart sequence # of length 1. The zeroth element of the list should be the Message # object for the subpart.Extract that object, stringify it, and write # that out. g.flatten(msg.get_payload(0), unixfrom=0) self._fp.write(s.getvalue())
def _handle_message(self, msg): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) # The payload of a message/rfc822 part should be a multipart sequence # of length 1. The zeroth element of the list should be the Message # object for the subpart.Extract that object, stringify it, and write # that out. g.flatten(msg.get_payload(0), unixfrom=0) self._fp.write(s.getvalue())
12,220
def save_int(self, object, pack=struct.pack): if self.bin: # If the int is small enough to fit in a signed 4-byte 2's-comp # format, we can store it more efficiently than the general # case. # First one- and two-byte unsigned ints: if object >= 0: if object <= 0xff: self.write(BININT1 + chr(object)) return if object <= 0xffff: self.write(BININT2 + chr(object&0xff) + chr(object>>8)) return # Next check for 4-byte signed ints: high_bits = object >> 31 # note that Python shift sign-extends if high_bits == 0 or high_bits == -1: # All high bits are copies of bit 2**31, so the value # fits in a 4-byte signed int. self.write(BININT + pack("<i", object)) return # Text pickle, or int too big to fit in signed 4-byte format. self.write(INT + `object` + '\n')
def save_int(self, object, pack=struct.pack): if self.bin: # If the int is small enough to fit in a signed 4-byte 2's-comp # format, we can store it more efficiently than the general # case. # First one- and two-byte unsigned ints: if object >= 0: if object <= 0xff: self.write(BININT1 + chr(object)) return if object <= 0xffff: self.write(BININT2 + chr(object&0xff) + chr(object>>8)) return # Next check for 4-byte signed ints: high_bits = object >> 31 # note that Python shift sign-extends if high_bits == 0 or high_bits == -1: # All high bits are copies of bit 2**31, so the value # fits in a 4-byte signed int. self.write(BININT + pack("<i", object)) return # Text pickle, or int too big to fit in signed 4-byte format. self.write(INT + `object` + '\n')
12,221
def save(self, object, pers_save = 0): memo = self.memo
def save(self, object, pers_save = 0): memo = self.memo
12,222
def openfile(self, path, activate = 1): if activate: self.activate() self.OpenURL("file:///" + string.join(string.split(path,':'), '/'))
def openfile(self, path, activate = 1): if activate: self.activate() self.OpenURL("file:///" + string.join(string.split(path,':'), '/'))
12,223
def sucktitle(path): f = open(path) text = f.read(1024) # assume the title is in the first 1024 bytes f.close() lowertext = string.lower(text) matcher = _titlepat.search(lowertext) if matcher: return matcher.group(1) return path
def sucktitle(path): f = open(path) text = f.read(1024) # assume the title is in the first 1024 bytes f.close() lowertext = text.lower() matcher = _titlepat.search(lowertext) if matcher: return matcher.group(1) return path
12,224
def __init__(self, hits): global _resultscounter hits = map(lambda (path, hits): (sucktitle(path), path, hits), hits) hits.sort() self.hits = hits nicehits = map( lambda (title, path, hits): title + '\r' + string.join( map(lambda (c, p): "%s (%d)" % (p, c), hits), ', '), hits) nicehits.sort() self.w = W.Window((440, 300), "Search results %d" % _resultscounter, minsize = (200, 100)) self.w.results = TwoLineList((-1, -1, 1, -14), nicehits, self.listhit) self.w.open() self.w.bind('return', self.listhit) self.w.bind('enter', self.listhit) _resultscounter = _resultscounter + 1 self.browser = None
def __init__(self, hits): global _resultscounter hits = map(lambda (path, hits): (sucktitle(path), path, hits), hits) hits.sort() self.hits = hits nicehits = map( lambda (title, path, hits): title + '\r' + string.join( map(lambda (c, p): "%s (%d)" % (p, c), hits), ', '), hits) nicehits.sort() self.w = W.Window((440, 300), "Search results %d" % _resultscounter, minsize = (200, 100)) self.w.results = W.TwoLineList((-1, -1, 1, -14), nicehits, self.listhit) self.w.open() self.w.bind('return', self.listhit) self.w.bind('enter', self.listhit) _resultscounter = _resultscounter + 1 self.browser = None
12,225
def __init__(self, hits): global _resultscounter hits = map(lambda (path, hits): (sucktitle(path), path, hits), hits) hits.sort() self.hits = hits nicehits = map( lambda (title, path, hits): title + '\r' + string.join( map(lambda (c, p): "%s (%d)" % (p, c), hits), ', '), hits) nicehits.sort() self.w = W.Window((440, 300), "Search results %d" % _resultscounter, minsize = (200, 100)) self.w.results = TwoLineList((-1, -1, 1, -14), nicehits, self.listhit) self.w.open() self.w.bind('return', self.listhit) self.w.bind('enter', self.listhit) _resultscounter = _resultscounter + 1 self.browser = None
def __init__(self, hits): global _resultscounter hits = map(lambda (path, hits): (sucktitle(path), path, hits), hits) hits.sort() self.hits = hits nicehits = map( lambda (title, path, hits): title + '\r' + string.join( map(lambda (c, p): "%s (%d)" % (p, c), hits), ', '), hits) nicehits.sort() self.w = W.Window((440, 300), "Search results %d" % _resultscounter, minsize = (200, 100)) self.w.results = TwoLineList((-1, -1, 1, -14), nicehits, self.listhit) self.w.open() self.w.bind('return', self.listhit) self.w.bind('enter', self.listhit) _resultscounter = _resultscounter + 1
12,226
def listhit(self, isdbl = 1): if isdbl: for i in self.w.results.getselection(): if self.browser is None: self.browser = WebBrowser(SIGNATURE, start = 1) self.browser.openfile(self.hits[i][1])
def listhit(self, isdbl = 1): if isdbl: for i in self.w.results.getselection(): if self.browser is None: self.browser = WebBrowser(SIGNATURE, start = 1) self.browser.openfile(self.hits[i][1])
12,227
def __init__(self): self.w = W.Dialog((440, 64), "Searching\xc9") self.w.searching = W.TextBox((4, 4, -4, 16), "DevDev:PyPyDoc 1.5.1:ext:parseTupleAndKeywords.html") self.w.hits = W.TextBox((4, 24, -4, 16), "Hits: 0") self.w.canceltip = W.TextBox((4, 44, -4, 16), "Type cmd-period (.) to cancel.") self.w.open()
def __init__(self): self.w = W.Dialog((440, 64), "Searching\xc9") self.w.searching = W.TextBox((4, 4, -4, 16), "") self.w.hits = W.TextBox((4, 24, -4, 16), "Hits: 0") self.w.canceltip = W.TextBox((4, 44, -4, 16), "Type cmd-period (.) to cancel.") self.w.open()
12,228
def __init__(self): prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) try: (docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine except: (docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine = \ ("", 0, 0, 0, 1, 1, 0, 0, 0) if docpath and not verifydocpath(docpath): docpath = "" self.w = W.Window((400, 200), "Search the Python Documentation") self.w.searchtext = W.EditText((10, 10, -100, 20), callback = self.checkbuttons) self.w.searchbutton = W.Button((-90, 12, 80, 16), "Search", self.search) buttons = [] gutter = 10 width = 130 bookstart = width + 2 * gutter self.w.phraseradio = W.RadioButton((10, 38, width, 16), "As a phrase", buttons) self.w.allwordsradio = W.RadioButton((10, 58, width, 16), "All words", buttons) self.w.anywordsradio = W.RadioButton((10, 78, width, 16), "Any word", buttons) self.w.casesens = W.CheckBox((10, 98, width, 16), "Case sensitive") self.w.wholewords = W.CheckBox((10, 118, width, 16), "Whole words") self.w.tutorial = W.CheckBox((bookstart, 38, -10, 16), "Tutorial") self.w.library = W.CheckBox((bookstart, 58, -10, 16), "Library reference") self.w.langueref = W.CheckBox((bookstart, 78, -10, 16), "Lanuage reference manual") self.w.extending = W.CheckBox((bookstart, 98, -10, 16), "Extending & embedding") self.w.api = W.CheckBox((bookstart, 118, -10, 16), "C/C++ API") self.w.setdocfolderbutton = W.Button((10, -30, 80, 16), "Set doc folder", self.setdocpath) if docpath: self.w.setdefaultbutton(self.w.searchbutton) else: self.w.setdefaultbutton(self.w.setdocfolderbutton) self.docpath = docpath if not docpath: docpath = "(please select the Python html documentation folder)" self.w.docfolder = W.TextBox((100, -28, -10, 16), docpath) [self.w.phraseradio, self.w.allwordsradio, self.w.anywordsradio][kind].set(1) self.w.casesens.set(case) self.w.wholewords.set(word) self.w.tutorial.set(tut) self.w.library.set(lib) self.w.langueref.set(ref) self.w.extending.set(ext) self.w.api.set(api) self.w.open() self.w.wholewords.enable(0) self.w.bind('<close>', self.close) self.w.searchbutton.enable(0)
def __init__(self): prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) try: (docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine except: (docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine = \ ("", 0, 0, 0, 1, 1, 0, 0, 0) if docpath and not verifydocpath(docpath): docpath = "" self.w = W.Window((400, 200), "Search the Python Documentation") self.w.searchtext = W.EditText((10, 10, -100, 20), callback = self.checkbuttons) self.w.searchbutton = W.Button((-90, 12, 80, 16), "Search", self.search) buttons = [] gutter = 10 width = 130 bookstart = width + 2 * gutter self.w.phraseradio = W.RadioButton((10, 38, width, 16), "As a phrase", buttons) self.w.allwordsradio = W.RadioButton((10, 58, width, 16), "All words", buttons) self.w.anywordsradio = W.RadioButton((10, 78, width, 16), "Any word", buttons) self.w.casesens = W.CheckBox((10, 98, width, 16), "Case sensitive") self.w.wholewords = W.CheckBox((10, 118, width, 16), "Whole words") self.w.tutorial = W.CheckBox((bookstart, 38, -10, 16), "Tutorial") self.w.library = W.CheckBox((bookstart, 58, -10, 16), "Library reference") self.w.langueref = W.CheckBox((bookstart, 78, -10, 16), "Lanuage reference manual") self.w.extending = W.CheckBox((bookstart, 98, -10, 16), "Extending & embedding") self.w.api = W.CheckBox((bookstart, 118, -10, 16), "C/C++ API") self.w.setdocfolderbutton = W.Button((10, -30, 100, 16), "Set doc folder", self.setdocpath) if docpath: self.w.setdefaultbutton(self.w.searchbutton) else: self.w.setdefaultbutton(self.w.setdocfolderbutton) self.docpath = docpath if not docpath: docpath = "(please select the Python html documentation folder)" self.w.docfolder = W.TextBox((100, -28, -10, 16), docpath) [self.w.phraseradio, self.w.allwordsradio, self.w.anywordsradio][kind].set(1) self.w.casesens.set(case) self.w.wholewords.set(word) self.w.tutorial.set(tut) self.w.library.set(lib) self.w.langueref.set(ref) self.w.extending.set(ext) self.w.api.set(api) self.w.open() self.w.wholewords.enable(0) self.w.bind('<close>', self.close) self.w.searchbutton.enable(0)
12,229
def __init__(self): prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) try: (docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine except: (docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine = \ ("", 0, 0, 0, 1, 1, 0, 0, 0) if docpath and not verifydocpath(docpath): docpath = "" self.w = W.Window((400, 200), "Search the Python Documentation") self.w.searchtext = W.EditText((10, 10, -100, 20), callback = self.checkbuttons) self.w.searchbutton = W.Button((-90, 12, 80, 16), "Search", self.search) buttons = [] gutter = 10 width = 130 bookstart = width + 2 * gutter self.w.phraseradio = W.RadioButton((10, 38, width, 16), "As a phrase", buttons) self.w.allwordsradio = W.RadioButton((10, 58, width, 16), "All words", buttons) self.w.anywordsradio = W.RadioButton((10, 78, width, 16), "Any word", buttons) self.w.casesens = W.CheckBox((10, 98, width, 16), "Case sensitive") self.w.wholewords = W.CheckBox((10, 118, width, 16), "Whole words") self.w.tutorial = W.CheckBox((bookstart, 38, -10, 16), "Tutorial") self.w.library = W.CheckBox((bookstart, 58, -10, 16), "Library reference") self.w.langueref = W.CheckBox((bookstart, 78, -10, 16), "Lanuage reference manual") self.w.extending = W.CheckBox((bookstart, 98, -10, 16), "Extending & embedding") self.w.api = W.CheckBox((bookstart, 118, -10, 16), "C/C++ API") self.w.setdocfolderbutton = W.Button((10, -30, 80, 16), "Set doc folder", self.setdocpath) if docpath: self.w.setdefaultbutton(self.w.searchbutton) else: self.w.setdefaultbutton(self.w.setdocfolderbutton) self.docpath = docpath if not docpath: docpath = "(please select the Python html documentation folder)" self.w.docfolder = W.TextBox((100, -28, -10, 16), docpath) [self.w.phraseradio, self.w.allwordsradio, self.w.anywordsradio][kind].set(1) self.w.casesens.set(case) self.w.wholewords.set(word) self.w.tutorial.set(tut) self.w.library.set(lib) self.w.langueref.set(ref) self.w.extending.set(ext) self.w.api.set(api) self.w.open() self.w.wholewords.enable(0) self.w.bind('<close>', self.close) self.w.searchbutton.enable(0)
def __init__(self): prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) try: (docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine except: (docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine = \ ("", 0, 0, 0, 1, 1, 0, 0, 0) if docpath and not verifydocpath(docpath): docpath = "" self.w = W.Window((400, 200), "Search the Python Documentation") self.w.searchtext = W.EditText((10, 10, -100, 20), callback = self.checkbuttons) self.w.searchbutton = W.Button((-90, 12, 80, 16), "Search", self.search) buttons = [] gutter = 10 width = 130 bookstart = width + 2 * gutter self.w.phraseradio = W.RadioButton((10, 38, width, 16), "As a phrase", buttons) self.w.allwordsradio = W.RadioButton((10, 58, width, 16), "All words", buttons) self.w.anywordsradio = W.RadioButton((10, 78, width, 16), "Any word", buttons) self.w.casesens = W.CheckBox((10, 98, width, 16), "Case sensitive") self.w.wholewords = W.CheckBox((10, 118, width, 16), "Whole words") self.w.tutorial = W.CheckBox((bookstart, 38, -10, 16), "Tutorial") self.w.library = W.CheckBox((bookstart, 58, -10, 16), "Library reference") self.w.langueref = W.CheckBox((bookstart, 78, -10, 16), "Lanuage reference manual") self.w.extending = W.CheckBox((bookstart, 98, -10, 16), "Extending & embedding") self.w.api = W.CheckBox((bookstart, 118, -10, 16), "C/C++ API") self.w.setdocfolderbutton = W.Button((10, -30, 80, 16), "Set doc folder", self.setdocpath) if docpath: self.w.setdefaultbutton(self.w.searchbutton) else: self.w.setdefaultbutton(self.w.setdocfolderbutton) self.docpath = docpath if not docpath: docpath = "(please select the Python html documentation folder)" self.w.docfolder = W.TextBox((120, -28, -10, 16), docpath) [self.w.phraseradio, self.w.allwordsradio, self.w.anywordsradio][kind].set(1) self.w.casesens.set(case) self.w.wholewords.set(word) self.w.tutorial.set(tut) self.w.library.set(lib) self.w.langueref.set(ref) self.w.extending.set(ext) self.w.api.set(api) self.w.open() self.w.wholewords.enable(0) self.w.bind('<close>', self.close) self.w.searchbutton.enable(0)
12,230
def search(self): hits = dosearch(self.docpath, self.w.searchtext.get(), self.getsettings()) if hits: Results(hits) elif hasattr(MacOS, 'SysBeep'): MacOS.SysBeep(0) #import PyBrowser #PyBrowser.Browser(hits)
def search(self): hits = dosearch(self.docpath, self.w.searchtext.get(), self.getsettings()) if hits: Results(hits) elif hasattr(MacOS, 'SysBeep'): MacOS.SysBeep(0) #import PyBrowser #PyBrowser.Browser(hits)
12,231
def test_closure(func, closure, exc): try: new.function(func.func_code, {}, "", None, closure) except exc: pass else: print "corrupt closure accepted"
def test_closure(func, closure, exc): try: new.function(func.func_code, {}, "", None, closure) except exc: pass else: print "corrupt closure accepted"
12,232
def test_closure(func, closure, exc): try: new.function(func.func_code, {}, "", None, closure) except exc: pass else: print "corrupt closure accepted"
def test_closure(func, closure, exc): try: new.function(func.func_code, {}, "", None, closure) except exc: pass else: print "corrupt closure accepted"
12,233
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
12,234
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
12,235
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
12,236
def process_message(self, peer, mailfrom, rcpttos, data): """Override this abstract method to handle messages from the client.
def process_message(self, peer, mailfrom, rcpttos, data): """Override this abstract method to handle messages from the client.
12,237
def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternative default.""" return environ.get(key, default)
def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.""" return environ.get(key, default)
12,238
def popen2(cmd, mode="t", bufsize=-1): assert mode[:1] in ("b", "t") import popen2 stdout, stdin = popen2.popen2(cmd, bufsize) return stdin, stdout
def popen2(cmd, mode="t", bufsize=-1): import popen2 stdout, stdin = popen2.popen2(cmd, bufsize) return stdin, stdout
12,239
def begin(self): if self.msg is not None: # we've already started reading the response return
def begin(self): if self.msg is not None: # we've already started reading the response return
12,240
def begin(self): if self.msg is not None: # we've already started reading the response return
def begin(self): if self.msg is not None: # we've already started reading the response return
12,241
def suite(): sqlite_type_suite = unittest.makeSuite(SqliteTypeTests, "Check") decltypes_type_suite = unittest.makeSuite(DeclTypesTests, "Check") colnames_type_suite = unittest.makeSuite(ColNamesTests, "Check") adaptation_suite = unittest.makeSuite(ObjectAdaptationTests, "Check") date_suite = unittest.makeSuite(DateTimeTests, "Check") return unittest.TestSuite((sqlite_type_suite, decltypes_type_suite, colnames_type_suite, adaptation_suite, date_suite))
def suite(): sqlite_type_suite = unittest.makeSuite(SqliteTypeTests, "Check") decltypes_type_suite = unittest.makeSuite(DeclTypesTests, "Check") colnames_type_suite = unittest.makeSuite(ColNamesTests, "Check") adaptation_suite = unittest.makeSuite(ObjectAdaptationTests, "Check") date_suite = unittest.makeSuite(DateTimeTests, "Check") return unittest.TestSuite((sqlite_type_suite, decltypes_type_suite, colnames_type_suite, adaptation_suite, bin_suite, date_suite))
12,242
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier.
def loadTestsFromName(self, name, module=None): """Return a suite of all tests cases given a string specifier.
12,243
def _subn(pattern, template, string, count=0): # internal: pattern.subn implementation hook if callable(template): filter = callable else: # FIXME: prepare template def filter(match, template=template): return _expand(match, template) n = i = 0 s = [] append = s.append c = pattern.cursor(string) while not count or n < count: m = c.search() if not m: break j = m.start() if j > i: append(string[i:j]) append(filter(m)) i = m.end() n = n + 1 if i < len(string): append(string[i:]) return string[:0].join(s), n
def _subn(pattern, template, string, count=0): # internal: pattern.subn implementation hook if callable(template): filter = template else: # FIXME: prepare template def filter(match, template=template): return _expand(match, template) n = i = 0 s = [] append = s.append c = pattern.cursor(string) while not count or n < count: m = c.search() if not m: break j = m.start() if j > i: append(string[i:j]) append(filter(m)) i = m.end() n = n + 1 if i < len(string): append(string[i:]) return string[:0].join(s), n
12,244
def __init__(self, root=None, font=None, name=None, **options): if not root: root = Tkinter._default_root if font: # get actual settings corresponding to the given font font = root.tk.splitlist(root.tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(id(self)) self.name = name root.tk.call("font", "create", name, *font) # backlinks! self._root = root self._split = root.tk.splitlist self._call = root.tk.call
def __init__(self, root=None, font=None, name=None, exists=False, **options): if not root: root = Tkinter._default_root if font: # get actual settings corresponding to the given font font = root.tk.splitlist(root.tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(id(self)) self.name = name root.tk.call("font", "create", name, *font) # backlinks! self._root = root self._split = root.tk.splitlist self._call = root.tk.call
12,245
def __init__(self, root=None, font=None, name=None, **options): if not root: root = Tkinter._default_root if font: # get actual settings corresponding to the given font font = root.tk.splitlist(root.tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(id(self)) self.name = name root.tk.call("font", "create", name, *font) # backlinks! self._root = root self._split = root.tk.splitlist self._call = root.tk.call
def __init__(self, root=None, font=None, name=None, **options): if not root: root = Tkinter._default_root if font: # get actual settings corresponding to the given font font = root.tk.splitlist(root.tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(id(self)) self.name = name if exists: self.delete_font = False if self.name not in root.tk.call("font", "names"): raise Tkinter._tkinter.TclError, "named font %s does not already exist" % (self.name,) if font: print "font=%r" % font root.tk.call("font", "configure", self.name, *font) else: root.tk.call("font", "create", self.name, *font) self.delete_font = True # backlinks! self._root = root self._split = root.tk.splitlist self._call = root.tk.call
12,246
def __del__(self): try: self._call("font", "delete", self.name) except (AttributeError, Tkinter.TclError): pass
def __del__(self): try: if self.delete_font: self._call("font", "delete", self.name) except (AttributeError, Tkinter.TclError): pass
12,247
def __del__(self): try: self._call("font", "delete", self.name) except (AttributeError, Tkinter.TclError): pass
def __del__(self): try: self._call("font", "delete", self.name) except (AttributeError, Tkinter.TclError): pass
12,248
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (HKEY_CLASSES_ROOT, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
12,249
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
12,250
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
12,251
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except RegError: break i = i + 1 except RegError: pass L.sort() L.reverse() return L
12,252
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except _RegError: break i = i + 1 except _RegError: pass L.sort() L.reverse() return L
def get_devstudio_versions (): """Get list of devstudio versions from the Windows registry. Return a list of strings containing version numbers; the list will be empty if we were unable to access the registry (eg. couldn't import a registry-access module) or the appropriate registry keys weren't found.""" if not _can_read_reg: return [] K = 'Software\\Microsoft\\Devstudio' L = [] for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: p = _RegEnumKey(k,i) if p[0] in '123456789' and p not in L: L.append(p) except RegError: break i = i + 1 except RegError: pass L.sort() L.reverse() return L
12,253
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (HKEY_CLASSES_ROOT, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
12,254
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
12,255
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
12,256
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except RegError: break except RegError: pass return L
12,257
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except _RegError: break except _RegError: pass return L
def get_msvc_paths (path, version='6.0', platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings; will be empty list if unable to access the registry or appropriate registry keys not found.""" if not _can_read_reg: return [] L = [] if path=='lib': path= 'Library' path = string.upper(path + ' Dirs') K = ('Software\\Microsoft\\Devstudio\\%s\\' + 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \ (version,platform) for base in (_HKEY_CLASSES_ROOT, _HKEY_LOCAL_MACHINE, _HKEY_CURRENT_USER, _HKEY_USERS): try: k = _RegOpenKeyEx(base,K) i = 0 while 1: try: (p,v,t) = _RegEnumValue(k,i) if string.upper(p) == path: V = string.split(v,';') for v in V: if v == '' or v in L: continue L.append(v) break i = i + 1 except RegError: break except RegError: pass return L
12,258
def mysetattr(self, name, value): if name == "spam": raise AttributeError return object.__setattr__(self, name, value)
defverify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) mysetattr(self,verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) name,verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) value):verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) ifverify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) nameverify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) ==verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) "spam":verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) raiseverify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) AttributeErrorverify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) returnverify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) object.__setattr__(self,verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) name,verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) value)
12,259
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k, v in value.items(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
12,260
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: if unicode and type(k) is UnicodeType: k = k.encode(self.encoding) else: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
12,261
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(v, write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
12,262
def install(self, unicode=0): import __builtin__ __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
def install(self, unicode=0): import __builtin__ __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
12,263
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
12,264
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<I', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
12,265
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20]) ii = '<II' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
12,266
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20]) ii = '>II' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
12,267
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints# Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
12,268
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
12,269
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) toff &= MASK tend = toff + (tlen & MASK) if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
def _parse(self, fp): """Override this method to support alternative .mo formats.""" # We need to & all 32 bit unsigned integers with 0xffffffff for # portability to 64 bit machines. MASK = 0xffffffff unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<i', buf[:4])[0] & MASK if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4i', buf[4:20]) ii = '<ii' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4i', buf[4:20]) ii = '>ii' else: raise IOError(0, 'Bad magic number', filename) # more unsigned ints msgcount &= MASK masteridx &= MASK transidx &= MASK # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) moff &= MASK mend = moff + (mlen & MASK) tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < buflen and tend < buflen: tmsg = buf[toff:tend] catalog[buf[moff:mend]] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.split('\n'): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] # advance to next entry in the seek tables masteridx += 8 transidx += 8
12,270
def unpack_double(self): # XXX i = self.pos self.pos = j = i+8 data = self.buf[i:j] if len(data) < 8: raise EOFError return struct.unpack('8', data)[0]
def unpack_double(self): # XXX i = self.pos self.pos = j = i+8 data = self.buf[i:j] if len(data) < 8: raise EOFError return struct.unpack('8', data)[0]
12,271
def js_output(self, attrs=None): # Print javascript return """ <SCRIPT LANGUAGE="JavaScript"> <!-- begin hiding document.cookie = \"%s\" // end hiding --> </script> """ % ( self.OutputString(attrs), )
def js_output(self, attrs=None): # Print javascript return """ <script type="text/javascript"> <!-- begin hiding document.cookie = \"%s\" // end hiding --> </script> """ % ( self.OutputString(attrs), )
12,272
def js_output(self, attrs=None): # Print javascript return """ <SCRIPT LANGUAGE="JavaScript"> <!-- begin hiding document.cookie = \"%s\" // end hiding --> </script> """ % ( self.OutputString(attrs), )
def js_output(self, attrs=None): # Print javascript return """ <SCRIPT LANGUAGE="JavaScript"> <!-- begin hiding document.cookie = \"%s\"; // end hiding --> </script> """ % ( self.OutputString(attrs), )
12,273
def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '200' if all goes well) - server response string corresponding to response code - any RFC822 headers in the response from the server
def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '200' if all goes well) - server response string corresponding to response code - any RFC822 headers in the response from the server
12,274
def decode(self, input, errors='strict'):
def decode(self, input, errors='strict'):
12,275
def __init__(self, errors='strict'): """ Creates a IncrementalEncoder instance.
def __init__(self, errors='strict'): """ Creates a IncrementalEncoder instance.
12,276
def pack_fstring(self, n, s): if n < 0: raise ValueError, 'fstring size must be nonnegative' data = s[:n] n = ((n+3)/4)*4 data = data + (n - len(data)) * '\0' self.__buf.write(data)
def pack_fstring(self, n, s): if n < 0: raise ValueError, 'fstring size must be nonnegative' data = s[:n] n = ((n+3)//4)*4 data = data + (n - len(data)) * '\0' self.__buf.write(data)
12,277
def unpack_fstring(self, n): if n < 0: raise ValueError, 'fstring size must be nonnegative' i = self.__pos j = i + (n+3)/4*4 if j > len(self.__buf): raise EOFError self.__pos = j return self.__buf[i:i+n]
def unpack_fstring(self, n): if n < 0: raise ValueError, 'fstring size must be nonnegative' i = self.__pos j = i + (n+3)//4*4 if j > len(self.__buf): raise EOFError self.__pos = j return self.__buf[i:i+n]
12,278
def __div__(self, other): return "B.__div__"
def __div__(self, other): return "B.__div__"
12,279
def __div__(self, other): return "C.__div__"
def __div__(self, other): return "C.__div__"
12,280
def __div__(self, other): return "D.__div__"
def __div__(self, other): return "D.__div__"
12,281
def __rdiv__(self, other): return "D.__rdiv__"
def __rdiv__(self, other): return "D.__rdiv__"
12,282
def urlunparse((scheme, netloc, url, params, query, fragment)): """Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent).""" if netloc or (scheme in uses_netloc and url[:2] == '//'): if url[:1] != '/': url = '/' + url url = '//' + (netloc or '') + url if scheme: url = scheme + ':' + url if params: url = url + ';' + params if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url
def urlunparse((scheme, netloc, url, params, query, fragment)): """Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent).""" if netloc or (scheme in uses_netloc and url[:2] == '//'): if url and url[:1] != '/': url = '/' + url url = '//' + (netloc or '') + url if scheme: url = scheme + ':' + url if params: url = url + ';' + params if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url
12,283
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return url if scheme in uses_netloc: if netloc: return url netloc = bnetloc if path[:1] == '/': return url if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
12,284
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
12,285
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if (segments[i] == '..' and segments[i-1] not in ('', '..')): del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
12,286
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if len(segments) == 2 and segments[1] == '..' and segments[0] == '': segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
def urljoin(base, url, allow_fragments = 1): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter.""" if not base: return url bscheme, bnetloc, bpath, bparams, bquery, bfragment = \ urlparse(base, '', allow_fragments) scheme, netloc, path, params, query, fragment = \ urlparse(url, bscheme, allow_fragments) if scheme != bscheme or scheme not in uses_relative: return urlunparse((scheme, netloc, path, params, query, fragment)) if scheme in uses_netloc: if netloc: return urlunparse((scheme, netloc, path, params, query, fragment)) netloc = bnetloc if path[:1] == '/': return urlunparse((scheme, netloc, path, params, query, fragment)) if not path: return urlunparse((scheme, netloc, bpath, params, query or bquery, fragment)) segments = bpath.split('/')[:-1] + path.split('/') # XXX The stuff below is bogus in various ways... if segments[-1] == '.': segments[-1] = '' while '.' in segments: segments.remove('.') while 1: i = 1 n = len(segments) - 1 while i < n: if segments[i] == '..' and segments[i-1]: del segments[i-1:i+1] break i = i+1 else: break if segments == ['', '..']: segments[-1] = '' elif len(segments) >= 2 and segments[-1] == '..': segments[-2:] = [''] return urlunparse((scheme, netloc, '/'.join(segments), params, query, fragment))
12,287
def next(self, index=0): while 1: try: what, tdelta, fileno, lineno = self._nextitem() except TypeError: # logreader().next() returns None at the end self._reader.close() raise StopIteration()
def next(self, index=0): while 1: try: what, tdelta, fileno, lineno = self._nextitem() except TypeError: # logreader().next() returns None at the end self._reader.close() raise StopIteration()
12,288
def missing_ok(str): try: getattr(socket, str) except AttributeError: pass
def missing_ok(str): try: getattr(socket, str) except AttributeError: pass
12,289
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line) >= 0: must_quote_header = 1 if mv.match(line) >= 0: is_mime = 1 if cte.match(line) >= 0: has_cte = 1 if qp.match(line) >= 0: is_qp = 1 if mp.match(line) >= 0: multipart = '--' + mp.group(1) if he.match(line) >= 0: header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line) >= 0: has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) if chrset.match(line) >= 0: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset.group(2)) == 'us-ascii': line = chrset.group(1) + \ CHARSET + chrset.group(3) else: # change iso-8859-* into us-ascii line = chrset.group(1) + 'us-ascii' + chrset.group(3) if has_cte and cte.match(line) >= 0: line = 'Content-Transfer-Encoding: ' if must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': return if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line) >= 0: must_quote_header = 1 if mv.match(line) >= 0: is_mime = 1 if cte.match(line) >= 0: has_cte = 1 if qp.match(line) >= 0: is_qp = 1 if mp.match(line) >= 0: multipart = '--' + mp.group(1) if he.match(line) >= 0: header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line) >= 0: has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) if chrset.match(line) >= 0: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset.group(2)) == 'us-ascii': line = chrset.group(1) + \ CHARSET + chrset.group(3) else: # change iso-8859-* into us-ascii line = chrset.group(1) + 'us-ascii' + chrset.group(3) if has_cte and cte.match(line) >= 0: line = 'Content-Transfer-Encoding: ' if must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': return if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
12,290
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line) >= 0: must_quote_header = 1 if mv.match(line) >= 0: is_mime = 1 if cte.match(line) >= 0: has_cte = 1 if qp.match(line) >= 0: is_qp = 1 if mp.match(line) >= 0: multipart = '--' + mp.group(1) if he.match(line) >= 0: header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line) >= 0: has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) if chrset.match(line) >= 0: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset.group(2)) == 'us-ascii': line = chrset.group(1) + \ CHARSET + chrset.group(3) else: # change iso-8859-* into us-ascii line = chrset.group(1) + 'us-ascii' + chrset.group(3) if has_cte and cte.match(line) >= 0: line = 'Content-Transfer-Encoding: ' if must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': return if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line) >= 0: must_quote_header = 1 if mv.match(line) >= 0: is_mime = 1 if cte.match(line) >= 0: has_cte = 1 if qp.match(line) >= 0: is_qp = 1 if mp.match(line) >= 0: multipart = '--' + mp.group(1) if he.match(line) >= 0: header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line) >= 0: has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) if chrset.match(line) >= 0: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset.group(2)) == 'us-ascii': line = chrset.group(1) + \ CHARSET + chrset.group(3) else: # change iso-8859-* into us-ascii line = chrset.group(1) + 'us-ascii' + chrset.group(3) if has_cte and cte.match(line) >= 0: line = 'Content-Transfer-Encoding: ' if is_base64: line = line + 'base64\n' elif must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if is_base64: line = line + 'base64\n' elif must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': return if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
12,291
def run (self):
def run (self):
12,292
def __init__(self, fp): self.fp = fp self.stack = [] # Grows down self.level = 0 self.last = 0 self.start = self.fp.tell() self.posstack = [] # Grows down
seekable = 0 def __init__(self, fp, seekable=1): self.fp = fp self.stack = [] # Grows down self.level = 0 self.last = 0 self.start = self.fp.tell() self.posstack = [] # Grows down
12,293
def __init__(self, fp): self.fp = fp self.stack = [] # Grows down self.level = 0 self.last = 0 self.start = self.fp.tell() self.posstack = [] # Grows down
def __init__(self, fp): self.fp = fp self.stack = [] # Grows down self.level = 0 self.last = 0 if seekable: self.seekable = 1 self.start = self.fp.tell() self.posstack = [] # Grows down
12,294
def readline(self): if self.level > 0: return '' line = self.fp.readline() if not line: self.level = len(self.stack) self.last = (self.level > 0) if self.last: err('*** Sudden EOF in MultiFile.readline()\n') return '' if line[:2] <> '--': return line n = len(line) k = n while k > 0 and line[k-1] in string.whitespace: k = k-1 mark = line[2:k] if mark[-2:] == '--': mark1 = mark[:-2] else: mark1 = None for i in range(len(self.stack)): sep = self.stack[i] if sep == mark: self.last = 0 break elif mark1 <> None and sep == mark1: self.last = 1 break else: return line # Get here after break out of loop self.lastpos = self.tell() - len(line) self.level = i+1 if self.level > 1: err('*** Missing endmarker in MultiFile.readline()\n') return ''
def readline(self): if self.level > 0: return '' line = self.fp.readline() if not line: self.level = len(self.stack) self.last = (self.level > 0) if self.last: err('*** Sudden EOF in MultiFile.readline()\n') return '' if line[:2] <> '--': return line n = len(line) k = n while k > 0 and line[k-1] in string.whitespace: k = k-1 mark = line[2:k] if mark[-2:] == '--': mark1 = mark[:-2] else: mark1 = None for i in range(len(self.stack)): sep = self.stack[i] if sep == mark: self.last = 0 break elif mark1 <> None and sep == mark1: self.last = 1 break else: return line # Get here after break out of loop if self.seekable: self.lastpos = self.tell() - len(line) self.level = i+1 if self.level > 1: err('*** Missing endmarker in MultiFile.readline()\n') return ''
12,295
def next(self): while self.readline(): pass if self.level > 1 or self.last: return 0 self.level = 0 self.last = 0 self.start = self.fp.tell() return 1
def next(self): while self.readline(): pass if self.level > 1 or self.last: return 0 self.level = 0 self.last = 0 if self.seekable: self.start = self.fp.tell() return 1
12,296
def push(self, sep): if self.level > 0: raise Error, 'bad MultiFile.push() call' self.stack.insert(0, sep) self.posstack.insert(0, self.start) self.start = self.fp.tell()
def push(self, sep): if self.level > 0: raise Error, 'bad MultiFile.push() call' self.stack.insert(0, sep) self.posstack.insert(0, self.start) self.start = self.fp.tell()
12,297
def handleLogRecord(self, record): logname = "logrecv.tcp." + record.name #If the end-of-messages sentinel is seen, tell the server to terminate if record.msg == FINISH_UP: self.server.abort = 1 record.msg = record.msg + " (via " + logname + ")" logger = logging.getLogger(logname) logger.handle(record)
def handleLogRecord(self, record): logname = "logrecv.tcp." + record.name #If the end-of-messages sentinel is seen, tell the server to terminate if record.msg == FINISH_UP: self.server.abort = 1 record.msg = record.msg + " (via " + logname + ")" logger = logging.getLogger(logname) logger.handle(record)
12,298
def serve_until_stopped(self): abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() abort = self.abort #notify the main thread that we're about to exit socketDataProcessed.acquire() socketDataProcessed.notify() socketDataProcessed.release()
def serve_until_stopped(self): abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() abort = self.abort #notify the main thread that we're about to exit socketDataProcessed.acquire() socketDataProcessed.notify() socketDataProcessed.release()
12,299